github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/osutils/find.go (about) 1 package osutils 2 3 import ( 4 "os" 5 "path/filepath" 6 "strings" 7 8 "github.com/ActiveState/cli/internal/fileutils" 9 "github.com/thoas/go-funk" 10 ) 11 12 // FindExeOnPATH returns the first path from the PATH env var for which the executable exists 13 func FindExeOnPATH(executable string) string { 14 exes := findExes(executable, os.Getenv("PATH"), exts, fileutils.TargetExists, nil) 15 if len(exes) == 0 { 16 return "" 17 } 18 return exes[0] 19 } 20 21 // FindExeOnPATH returns the first path from the PATH env var for which the executable exists 22 func FilterExesOnPATH(executable string, PATH string, filter func(exe string) bool) []string { 23 return findExes(executable, PATH, exts, fileutils.TargetExists, filter) 24 } 25 26 func FindExeInside(executable string, PATH string) string { 27 exes := findExes(executable, PATH, exts, fileutils.TargetExists, nil) 28 if len(exes) == 0 { 29 return "" 30 } 31 return exes[0] 32 } 33 34 func findExes(executable string, PATH string, exts []string, fileExists func(string) bool, filter func(exe string) bool) []string { 35 // if executable has valid extension for an executable file, we have to check for its existence without appending more extensions 36 if len(exts) == 0 || funk.ContainsString(exts, strings.ToLower(filepath.Ext(executable))) { 37 exts = []string{""} 38 } 39 40 result := []string{} 41 candidates := funk.Uniq(strings.Split(PATH, string(os.PathListSeparator))).([]string) 42 for _, p := range candidates { 43 for _, ext := range exts { 44 fp := filepath.Clean(filepath.Join(p, executable+ext)) 45 if fileExists(fp) && !fileutils.IsDir(fp) && (filter == nil || filter(fp)) { 46 result = append(result, fp) 47 } 48 } 49 } 50 return result 51 } 52 53 func findExe(executable string, PATH string, exts []string, fileExists func(string) bool, filter func(exe string) bool) string { 54 r := findExes(executable, PATH, exts, fileExists, filter) 55 if len(r) > 0 { 56 return r[0] 57 } 58 return "" 59 }