github.com/taylorchu/nomad@v0.5.3-rc1.0.20170407200202-db11e7dd7b55/helper/discover/discover.go (about)

     1  package discover
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"path/filepath"
     8  	"runtime"
     9  )
    10  
    11  // Checks the current executable, then $GOPATH/bin, and finally the CWD, in that
    12  // order. If it can't be found, an error is returned.
    13  func NomadExecutable() (string, error) {
    14  	nomadExe := "nomad"
    15  	if runtime.GOOS == "windows" {
    16  		nomadExe = "nomad.exe"
    17  	}
    18  
    19  	// Check the current executable.
    20  	bin, err := os.Executable()
    21  	if err != nil {
    22  		return "", fmt.Errorf("Failed to determine the nomad executable: %v", err)
    23  	}
    24  
    25  	if _, err := os.Stat(bin); err == nil && isNomad(bin, nomadExe) {
    26  		return bin, nil
    27  	}
    28  
    29  	// Check the $PATH
    30  	if bin, err := exec.LookPath(nomadExe); err == nil {
    31  		return bin, nil
    32  	}
    33  
    34  	// Check the $GOPATH.
    35  	bin = filepath.Join(os.Getenv("GOPATH"), "bin", nomadExe)
    36  	if _, err := os.Stat(bin); err == nil {
    37  		return bin, nil
    38  	}
    39  
    40  	// Check the CWD.
    41  	pwd, err := os.Getwd()
    42  	if err != nil {
    43  		return "", fmt.Errorf("Could not find Nomad executable (%v): %v", nomadExe, err)
    44  	}
    45  
    46  	bin = filepath.Join(pwd, nomadExe)
    47  	if _, err := os.Stat(bin); err == nil {
    48  		return bin, nil
    49  	}
    50  
    51  	// Check CWD/bin
    52  	bin = filepath.Join(pwd, "bin", nomadExe)
    53  	if _, err := os.Stat(bin); err == nil {
    54  		return bin, nil
    55  	}
    56  
    57  	return "", fmt.Errorf("Could not find Nomad executable (%v)", nomadExe)
    58  }