github.com/neugram/ng@v0.0.0-20180309130942-d472ff93d872/eval/shell/findexec_unix.go (about)

     1  // Copyright 2015 The Neugram 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  // +build !windows
     6  
     7  package shell
     8  
     9  import (
    10  	"fmt"
    11  	"os"
    12  	"path/filepath"
    13  	"strings"
    14  
    15  	"neugram.io/ng/eval/environ"
    16  )
    17  
    18  func findExec(name string) error {
    19  	fi, err := os.Stat(name)
    20  	if err != nil {
    21  		return err
    22  	}
    23  	if fi.IsDir() || fi.Mode()&0111 == 0 {
    24  		return fmt.Errorf("%q is not an executable", name)
    25  	}
    26  	return nil
    27  }
    28  
    29  func findExecInPath(name string, env *environ.Environ) (string, error) {
    30  	if strings.Contains(name, "/") {
    31  		err := findExec(name)
    32  		if err == nil {
    33  			return name, nil
    34  		}
    35  		return "", err
    36  	}
    37  
    38  	path := filepath.SplitList(env.Get("PATH"))
    39  	if len(path) == 0 {
    40  		return "", fmt.Errorf("cannot find %q, no PATH", name)
    41  	}
    42  
    43  	for _, dir := range path {
    44  		if dir == "" {
    45  			dir = "."
    46  		}
    47  		file := dir + "/" + name
    48  		if err := findExec(file); err == nil {
    49  			return file, nil
    50  		}
    51  	}
    52  	return "", fmt.Errorf("cannot find %q in PATH", name)
    53  }