lp_plan9.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. package exec
  5. import (
  6. "errors"
  7. "os"
  8. "strings"
  9. )
  10. // ErrNotFound is the error resulting if a path search failed to find an executable file.
  11. var ErrNotFound = errors.New("executable file not found in $path")
  12. func findExecutable(file string) error {
  13. d, err := os.Stat(file)
  14. if err != nil {
  15. return err
  16. }
  17. if m := d.Mode(); !m.IsDir() && m&0111 != 0 {
  18. return nil
  19. }
  20. return os.ErrPermission
  21. }
  22. // LookPath searches for an executable binary named file
  23. // in the directories named by the path environment variable.
  24. // If file begins with "/", "#", "./", or "../", it is tried
  25. // directly and the path is not consulted.
  26. // The result may be an absolute path or a path relative to the current directory.
  27. func LookPath(file string) (string, error) {
  28. // skip the path lookup for these prefixes
  29. skip := []string{"/", "#", "./", "../"}
  30. for _, p := range skip {
  31. if strings.HasPrefix(file, p) {
  32. err := findExecutable(file)
  33. if err == nil {
  34. return file, nil
  35. }
  36. return "", &Error{file, err}
  37. }
  38. }
  39. path := os.Getenv("path")
  40. for _, dir := range strings.Split(path, "\000") {
  41. if err := findExecutable(dir + "/" + file); err == nil {
  42. return dir + "/" + file, nil
  43. }
  44. }
  45. return "", &Error{file, ErrNotFound}
  46. }