| 1 |
// Copyright 2011 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 |
package exec |
| 6 |
|
| 7 |
import ( |
| 8 |
"errors" |
| 9 |
"io/fs" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// ErrNotFound is the error resulting if a path search failed to find an executable file. |
| 16 |
var ErrNotFound = errors.New("executable file not found in $path") |
| 17 |
|
| 18 |
func findExecutable(file string) error { |
| 19 |
d, err := os.Stat(file) |
| 20 |
if err != nil { |
| 21 |
return err |
| 22 |
} |
| 23 |
if m := d.Mode(); !m.IsDir() && m&0111 != 0 { |
| 24 |
return nil |
| 25 |
} |
| 26 |
return fs.ErrPermission |
| 27 |
} |
| 28 |
|
| 29 |
func lookPath(file string) (string, error) { |
| 30 |
if err := validateLookPath(filepath.Clean(file)); err != nil { |
| 31 |
return "", &Error{file, err} |
| 32 |
} |
| 33 |
|
| 34 |
// skip the path lookup for these prefixes |
| 35 |
skip := []string{"/", "#", "./", "../"} |
| 36 |
|
| 37 |
for _, p := range skip { |
| 38 |
if strings.HasPrefix(file, p) { |
| 39 |
err := findExecutable(file) |
| 40 |
if err == nil { |
| 41 |
return file, nil |
| 42 |
} |
| 43 |
return "", &Error{file, err} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
path := os.Getenv("path") |
| 48 |
for _, dir := range filepath.SplitList(path) { |
| 49 |
path := filepath.Join(dir, file) |
| 50 |
if err := findExecutable(path); err == nil { |
| 51 |
if !filepath.IsAbs(path) { |
| 52 |
if execerrdot.Value() != "0" { |
| 53 |
return path, &Error{file, ErrDot} |
| 54 |
} |
| 55 |
execerrdot.IncNonDefault() |
| 56 |
} |
| 57 |
return path, nil |
| 58 |
} |
| 59 |
} |
| 60 |
return "", &Error{file, ErrNotFound} |
| 61 |
} |
| 62 |
|
| 63 |
// lookExtensions is a no-op on non-Windows platforms, since |
| 64 |
// they do not restrict executables to specific extensions. |
| 65 |
func lookExtensions(path, dir string) (string, error) { |
| 66 |
return path, nil |
| 67 |
} |