github.com/hashicorp/nomad/api@v0.0.0-20240306165712-3193ac204f65/internal/testutil/discover/discover.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package discover
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"os/exec"
    10  	"path/filepath"
    11  	"runtime"
    12  	"strings"
    13  )
    14  
    15  // Checks the current executable, then $GOPATH/bin, and finally the CWD, in that
    16  // order. If it can't be found, an error is returned.
    17  func NomadExecutable() (string, error) {
    18  	nomadExe := "nomad"
    19  	if runtime.GOOS == "windows" {
    20  		nomadExe = "nomad.exe"
    21  	}
    22  
    23  	// Check the current executable.
    24  	bin, err := os.Executable()
    25  	if err != nil {
    26  		return "", fmt.Errorf("Failed to determine the nomad executable: %v", err)
    27  	}
    28  
    29  	if _, err := os.Stat(bin); err == nil && isNomad(bin, nomadExe) {
    30  		return bin, nil
    31  	}
    32  
    33  	// Check the $PATH
    34  	if bin, err := exec.LookPath(nomadExe); err == nil {
    35  		return bin, nil
    36  	}
    37  
    38  	// Check the $GOPATH.
    39  	bin = filepath.Join(os.Getenv("GOPATH"), "bin", nomadExe)
    40  	if _, err := os.Stat(bin); err == nil {
    41  		return bin, nil
    42  	}
    43  
    44  	// Check the CWD.
    45  	pwd, err := os.Getwd()
    46  	if err != nil {
    47  		return "", fmt.Errorf("Could not find Nomad executable (%v): %v", nomadExe, err)
    48  	}
    49  
    50  	bin = filepath.Join(pwd, nomadExe)
    51  	if _, err := os.Stat(bin); err == nil {
    52  		return bin, nil
    53  	}
    54  
    55  	// Check CWD/bin
    56  	bin = filepath.Join(pwd, "bin", nomadExe)
    57  	if _, err := os.Stat(bin); err == nil {
    58  		return bin, nil
    59  	}
    60  
    61  	return "", fmt.Errorf("Could not find Nomad executable (%v)", nomadExe)
    62  }
    63  
    64  func isNomad(path, nomadExe string) bool {
    65  	switch {
    66  	case strings.HasSuffix(path, ".test"):
    67  		return false
    68  	case strings.HasSuffix(path, ".test.exe"):
    69  		return false
    70  	// delve debug executable for debugging test
    71  	case strings.HasSuffix(path, "__debug_bin"):
    72  		return false
    73  	case strings.HasSuffix(path, "__debug_bin.exe"):
    74  		return false
    75  	default:
    76  		return true
    77  	}
    78  }