forked from laher/someutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
which.go
83 lines (76 loc) · 1.47 KB
/
which.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package someutils
import (
"github.com/laher/uggo"
"os"
"path/filepath"
"runtime"
"strings"
)
type WhichOptions struct {
all bool
}
func init() {
Register(Util{
"which",
Which})
}
func Which(call []string) error {
options := WhichOptions{}
flagSet := uggo.NewFlagSetDefault("which", "[-a] args", VERSION)
flagSet.BoolVar(&options.all, "a", false, "Print all matching executables in PATH, not just the first.")
err := flagSet.Parse(call[1:])
if err != nil {
println("Error parsing flags")
return err
}
if flagSet.ProcessHelpOrVersion() {
return nil
}
args := flagSet.Args()
path := os.Getenv("PATH")
if runtime.GOOS == "windows" {
path = ".;" + path
}
pl := filepath.SplitList(path)
for _, arg := range args {
checkPathParts(arg, pl, options)
/*
if err != nil {
return err
}*/
}
return nil
}
func checkPathParts(arg string, pathParts []string, options WhichOptions) {
for _, pathPart := range pathParts {
fi, err := os.Stat(pathPart)
if err == nil {
if fi.IsDir() {
possibleExe := filepath.Join(pathPart, arg)
if runtime.GOOS == "windows" {
if !strings.HasSuffix(possibleExe, ".exe") {
possibleExe += ".exe"
}
}
_, err := os.Stat(possibleExe)
if err != nil {
//skip
} else {
abs, err := filepath.Abs(possibleExe)
if err == nil {
println(abs)
} else {
//skip
}
if !options.all {
return
}
}
} else {
//skip
}
} else {
//skip
}
}
}