Port python's shutil.which()

This commit is contained in:
Kovid Goyal 2023-01-03 12:09:49 +05:30
parent fd71d2035d
commit 4d21be9eb5
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

35
tools/utils/which.go Normal file
View File

@ -0,0 +1,35 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"os"
"path/filepath"
"strings"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func Which(cmd string) string {
if strings.Contains(cmd, string(os.PathSeparator)) {
return ""
}
path := os.Getenv("PATH")
if path == "" {
return ""
}
for _, dir := range strings.Split(path, string(os.PathListSeparator)) {
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 ""
}