From 4d21be9eb59d58b9dd169c12d93017b55ee289c3 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 3 Jan 2023 12:09:49 +0530 Subject: [PATCH] Port python's shutil.which() --- tools/utils/which.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 tools/utils/which.go diff --git a/tools/utils/which.go b/tools/utils/which.go new file mode 100644 index 000000000..184221803 --- /dev/null +++ b/tools/utils/which.go @@ -0,0 +1,35 @@ +// License: GPLv3 Copyright: 2023, Kovid Goyal, + +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 "" +}