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.
|
|
|
|
|
2011-10-27 01:57:58 +02:00
|
|
|
// +build darwin freebsd linux openbsd
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
if d.IsRegular() && d.Permission()&0111 != 0 {
|
|
|
|
return nil
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
return os.EPERM
|
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.
|
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")
|
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 = "."
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
if err := findExecutable(dir + "/" + file); err == nil {
|
2010-12-03 05:34:57 +01:00
|
|
|
return dir + "/" + file, nil
|
|
|
|
}
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
return "", &Error{file, ErrNotFound}
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|