-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.go
57 lines (49 loc) · 1.02 KB
/
path.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package human
import (
"encoding"
"flag"
"fmt"
"os"
"os/user"
"path/filepath"
)
// Path represents a path on the file system.
//
// The type interprets the special prefix "~/" as representing the home
// directory of the user that the program is running as.
type Path string
func (p Path) String() string {
return string(p)
}
func (p Path) Get() any {
return string(p)
}
func (p *Path) Set(s string) error {
*p = Path(s)
return nil
}
func (p *Path) UnmarshalText(b []byte) error {
return p.Set(string(b))
}
func (p Path) Resolve() (string, error) {
switch {
case len(p) >= 2 && p[0] == '~' && p[1] == os.PathSeparator:
home, ok := os.LookupEnv("HOME")
if !ok {
u, err := user.Current()
if err != nil {
return "", err
}
home = u.HomeDir
}
return filepath.Join(home, string(p[2:])), nil
default:
return string(p), nil
}
}
var (
_ fmt.Stringer = Path("")
_ encoding.TextUnmarshaler = (*Path)(nil)
_ flag.Getter = (*Path)(nil)
_ flag.Value = (*Path)(nil)
)