-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathxexec.go
62 lines (58 loc) · 1.31 KB
/
xexec.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
package xexec
import (
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
)
// findExecutable is from package os/exec
func findExecutable(file string) error {
d, err := os.Stat(file)
if err != nil {
return err
}
m := d.Mode()
if !m.IsDir() && m&0111 != 0 {
return nil
}
return fs.ErrPermission
}
// SearchPath searches for all executables that have prefix in their names in
// the directories named by the PATH environment variable.
func SearchPath(prefix string) ([]string, error) {
var matches []string
envPath := os.Getenv("PATH")
dirSet := make(map[string]struct{})
for _, dir := range filepath.SplitList(envPath) {
if dir == "" {
// From exec package:
// Unix shell semantics: path element "" means "."
dir = "."
}
if _, ok := dirSet[dir]; ok {
continue
}
dirSet[dir] = struct{}{}
files, err := os.ReadDir(dir)
if err != nil {
continue
}
for _, f := range files {
if strings.HasPrefix(f.Name(), prefix) {
match := filepath.Join(dir, f.Name())
// Unideal but I don't want to maintain two separate implementations of this
// function like os/exec.
if runtime.GOOS == "windows" {
matches = append(matches, match)
continue
}
err = findExecutable(match)
if err == nil {
matches = append(matches, match)
}
}
}
}
return matches, nil
}