File: which.go

package info (click to toggle)
kitty 0.42.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 28,564 kB
  • sloc: ansic: 82,787; python: 55,191; objc: 5,122; sh: 1,295; xml: 364; makefile: 143; javascript: 78
file content (62 lines) | stat: -rw-r--r-- 1,195 bytes parent folder | download | duplicates (2)
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
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>

package utils

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"golang.org/x/sys/unix"
)

var _ = fmt.Print

var DefaultExeSearchPaths = sync.OnceValue(func() []string {
	candidates := [...]string{"/usr/local/bin", "/opt/bin", "/opt/homebrew/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"}
	ans := make([]string, 0, len(candidates))
	for _, x := range candidates {
		if s, err := os.Stat(x); err == nil && s.IsDir() {
			ans = append(ans, x)
		}
	}
	return ans
})

func Which(cmd string, paths ...string) string {
	if strings.Contains(cmd, string(os.PathSeparator)) {
		return ""
	}
	if len(paths) == 0 {
		path := os.Getenv("PATH")
		if path == "" {
			return ""
		}
		paths = strings.Split(path, string(os.PathListSeparator))
	}
	for _, dir := range paths {
		q := filepath.Join(dir, cmd)
		if unix.Access(q, unix.X_OK) == nil {
			s, err := os.Stat(q)
			if err == nil && !s.IsDir() {
				return q
			}
		}

	}
	return ""
}

func FindExe(name string) string {
	ans := Which(name)
	if ans != "" {
		return ans
	}
	ans = Which(name, DefaultExeSearchPaths()...)
	if ans == "" {
		ans = name
	}
	return ans
}