2010-12-03 05:34:57 +01: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.
|
|
|
|
|
2013-11-06 20:49:01 +01:00
|
|
|
// +build darwin dragonfly freebsd linux netbsd openbsd
|
2011-10-27 01:57:58 +02:00
|
|
|
|
2010-12-03 05:34:57 +01:00
|
|
|
package exec
|
|
|
|
|
|
|
|
import (
|
2011-12-03 03:17:34 +01:00
|
|
|
"errors"
|
2010-12-03 05:34:57 +01:00
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2011-09-16 17:47:21 +02:00
|
|
|
// ErrNotFound is the error resulting if a path search failed to find an executable file.
|
2011-12-03 03:17:34 +01:00
|
|
|
var ErrNotFound = errors.New("executable file not found in $PATH")
|
2011-09-16 17:47:21 +02:00
|
|
|
|
2011-12-03 03:17:34 +01:00
|
|
|
func findExecutable(file string) error {
|
2010-12-03 05:34:57 +01:00
|
|
|
d, err := os.Stat(file)
|
|
|
|
if err != nil {
|
2011-09-16 17:47:21 +02:00
|
|
|
return err
|
|
|
|
}
|
2011-12-13 20:16:27 +01:00
|
|
|
if m := d.Mode(); !m.IsDir() && m&0111 != 0 {
|
2011-09-16 17:47:21 +02:00
|
|
|
return nil
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|
2012-03-02 21:01:37 +01:00
|
|
|
return os.ErrPermission
|
2010-12-03 05:34:57 +01: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 20:49:01 +01:00
|
|
|
// The result may be an absolute path or a path relative to the current directory.
|
2011-12-03 03:17:34 +01:00
|
|
|
func LookPath(file string) (string, error) {
|
2010-12-03 05:34:57 +01: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 17:47:21 +02:00
|
|
|
err := findExecutable(file)
|
|
|
|
if err == nil {
|
2010-12-03 05:34:57 +01:00
|
|
|
return file, nil
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
return "", &Error{file, err}
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|
|
|
|
pathenv := os.Getenv("PATH")
|
2013-07-16 08:54:42 +02:00
|
|
|
if pathenv == "" {
|
|
|
|
return "", &Error{file, ErrNotFound}
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
for _, dir := range strings.Split(pathenv, ":") {
|
2010-12-03 05:34:57 +01:00
|
|
|
if dir == "" {
|
|
|
|
// Unix shell semantics: path element "" means "."
|
|
|
|
dir = "."
|
|
|
|
}
|
2012-01-25 22:54:22 +01:00
|
|
|
path := dir + "/" + file
|
|
|
|
if err := findExecutable(path); err == nil {
|
|
|
|
return path, nil
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
return "", &Error{file, ErrNotFound}
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|