Debian Codegraph @

internal/os/execpath/lp_unix.go

raw
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build aix || darwin || dragonfly || freebsd || linux || nacl || netbsd || openbsd || solaris
6
7 package execpath
8
9 import (
10 "cmp"
11 "os"
12 "path/filepath"
13 "strings"
14 )
15
16 func findExecutable(file string) error {
17 d, err := os.Stat(file)
18 if err != nil {
19 return err
20 }
21 if m := d.Mode(); !m.IsDir() && m&0111 != 0 {
22 return nil
23 }
24 return os.ErrPermission
25 }
26
27 // Look searches for an executable named file, using getenv to look up
28 // environment variables. If getenv is nil, os.Getenv will be used. If file
29 // contains a slash, it is tried directly and getenv will not be called. The
30 // result may be an absolute path or a path relative to the current directory.
31 func Look(file string, getenv func(string) string) (string, error) {
32 if getenv == nil {
33 getenv = os.Getenv
34 }
35
36 // NOTE(rsc): I wish we could use the Plan 9 behavior here
37 // (only bypass the path if file begins with / or ./ or ../)
38 // but that would not match all the Unix shells.
39
40 if strings.Contains(file, "/") {
41 err := findExecutable(file)
42 if err == nil {
43 return file, nil
44 }
45 return "", &Error{file, err}
46 }
47 path := getenv("PATH")
48 for _, dir := range filepath.SplitList(path) {
49 // Unix shell semantics: path element "" means "."
50 dir = cmp.Or(dir, ".")
51 path := filepath.Join(dir, file)
52 if err := findExecutable(path); err == nil {
53 return path, nil
54 }
55 }
56 return "", &Error{file, ErrNotFound}
57 }