2010-12-03 04:34:57 +00:00
|
|
|
// Copyright 2010 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2014-07-19 08:53:52 +00:00
|
|
|
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
|
2011-10-26 23:57:58 +00:00
|
|
|
|
2010-12-03 04:34:57 +00:00
|
|
|
package exec
|
|
|
|
|
|
|
|
import (
|
2011-12-03 02:17:34 +00:00
|
|
|
"errors"
|
2010-12-03 04:34:57 +00:00
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2011-09-16 15:47:21 +00:00
|
|
|
// ErrNotFound is the error resulting if a path search failed to find an executable file.
|
2011-12-03 02:17:34 +00:00
|
|
|
var ErrNotFound = errors.New("executable file not found in $PATH")
|
2011-09-16 15:47:21 +00:00
|
|
|
|
2011-12-03 02:17:34 +00:00
|
|
|
func findExecutable(file string) error {
|
2010-12-03 04:34:57 +00:00
|
|
|
d, err := os.Stat(file)
|
|
|
|
if err != nil {
|
2011-09-16 15:47:21 +00:00
|
|
|
return err
|
|
|
|
}
|
2011-12-13 19:16:27 +00:00
|
|
|
if m := d.Mode(); !m.IsDir() && m&0111 != 0 {
|
2011-09-16 15:47:21 +00:00
|
|
|
return nil
|
2010-12-03 04:34:57 +00:00
|
|
|
}
|
2012-03-02 20:01:37 +00:00
|
|
|
return os.ErrPermission
|
2010-12-03 04:34:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// LookPath searches for an executable binary named file
|
|
|
|
// in the directories named by the PATH environment variable.
|
|
|
|
// If file contains a slash, it is tried directly and the PATH is not consulted.
|
2013-11-06 19:49:01 +00:00
|
|
|
// The result may be an absolute path or a path relative to the current directory.
|
2011-12-03 02:17:34 +00:00
|
|
|
func LookPath(file string) (string, error) {
|
2010-12-03 04:34:57 +00:00
|
|
|
// NOTE(rsc): I wish we could use the Plan 9 behavior here
|
|
|
|
// (only bypass the path if file begins with / or ./ or ../)
|
|
|
|
// but that would not match all the Unix shells.
|
|
|
|
|
|
|
|
if strings.Contains(file, "/") {
|
2011-09-16 15:47:21 +00:00
|
|
|
err := findExecutable(file)
|
|
|
|
if err == nil {
|
2010-12-03 04:34:57 +00:00
|
|
|
return file, nil
|
|
|
|
}
|
2011-09-16 15:47:21 +00:00
|
|
|
return "", &Error{file, err}
|
2010-12-03 04:34:57 +00:00
|
|
|
}
|
|
|
|
pathenv := os.Getenv("PATH")
|
2013-07-16 06:54:42 +00:00
|
|
|
if pathenv == "" {
|
|
|
|
return "", &Error{file, ErrNotFound}
|
|
|
|
}
|
2011-09-16 15:47:21 +00:00
|
|
|
for _, dir := range strings.Split(pathenv, ":") {
|
2010-12-03 04:34:57 +00:00
|
|
|
if dir == "" {
|
|
|
|
// Unix shell semantics: path element "" means "."
|
|
|
|
dir = "."
|
|
|
|
}
|
2012-01-25 21:54:22 +00:00
|
|
|
path := dir + "/" + file
|
|
|
|
if err := findExecutable(path); err == nil {
|
|
|
|
return path, nil
|
2010-12-03 04:34:57 +00:00
|
|
|
}
|
|
|
|
}
|
2011-09-16 15:47:21 +00:00
|
|
|
return "", &Error{file, ErrNotFound}
|
2010-12-03 04:34:57 +00:00
|
|
|
}
|