forked from direnv/direnv
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cmd_expand_path.go
54 lines (44 loc) · 947 Bytes
/
cmd_expand_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
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
)
func expandPath(path, relTo string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Clean(filepath.Join(relTo, path))
}
// `direnv expand_path PATH [REL_TO]`
var CmdExpandPath = &Cmd{
Name: "expand_path",
Desc: "Transforms a PATH to an absolute path to REL_TO or $PWD",
Args: []string{"PATH", "[REL_TO]"},
Private: true,
Fn: func(env Env, args []string) (err error) {
var path string
flagset := flag.NewFlagSet(args[0], flag.ExitOnError)
flagset.Parse(args[1:])
path = flagset.Arg(0)
if path == "" {
return fmt.Errorf("PATH missing")
}
if !filepath.IsAbs(path) {
wd, err := os.Getwd()
if err != nil {
return err
}
relTo := flagset.Arg(1)
if relTo == "" {
relTo = wd
} else {
relTo = expandPath(relTo, wd)
}
path = expandPath(path, relTo)
}
_, err = fmt.Println(path)
return
},
}