-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.go
46 lines (39 loc) · 1.12 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
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func lookPath(file, excludedDir string) (string, error) {
return lookPathEnv(file, excludedDir, os.Getenv("PATH"))
}
// lookPathEnv search for an executable named file in the given path that is
// not in the excludedDir.
// Example:
// - file: prog
// - path: /Users/john/bin:/usr/local/bin
// - both /Users/john/bin/prog and /usr/local/bin/prog exists and are
// executable
// - excludedDir: /Users/john/bin/
//
// this function will return /usr/local/bin/prog, not /Users/john/bin/prog.
func lookPathEnv(file, excludedDir, path string) (string, error) {
excludedDir = filepath.Clean(excludedDir)
var paths []string
for _, dir := range filepath.SplitList(path) {
if filepath.Clean(dir) != excludedDir {
paths = append(paths, dir)
}
}
effectivePath := strings.Join(paths, string(os.PathListSeparator))
origPath := os.Getenv("PATH")
if err := os.Setenv("PATH", effectivePath); err != nil {
return "", fmt.Errorf("set effective PATH: %w", err)
}
defer func() {
_ = os.Setenv("PATH", origPath)
}()
return exec.LookPath(file)
}