github.com/sandwich-go/boost@v1.3.29/xos/binary.go (about)

     1  package xos
     2  
     3  import (
     4  	"path/filepath"
     5  	"runtime"
     6  	"strings"
     7  
     8  	"github.com/sandwich-go/boost/xstrings"
     9  )
    10  
    11  // SearchBinary 查找二进制文件
    12  func SearchBinary(file string) string {
    13  	// Check if it's absolute path of exists at current working directory.
    14  	if ExistsFile(file) {
    15  		return file
    16  	}
    17  	return SearchBinaryPath(file)
    18  }
    19  
    20  // SearchBinaryPath searches the binary <file> in PATH environment.
    21  func SearchBinaryPath(file string) string {
    22  	array := ([]string)(nil)
    23  	switch runtime.GOOS {
    24  	case "windows":
    25  		envPath := EnvGet("PATH", EnvGet("Path"))
    26  		if strings.Contains(envPath, ";") {
    27  			array = xstrings.SplitAndTrim(envPath, ";")
    28  		} else if strings.Contains(envPath, ":") {
    29  			array = xstrings.SplitAndTrim(envPath, ":")
    30  		}
    31  		if Ext(file) != ".exe" {
    32  			file += ".exe"
    33  		}
    34  	default:
    35  		array = xstrings.SplitAndTrim(EnvGet("PATH"), ":")
    36  	}
    37  	if len(array) > 0 {
    38  		path := ""
    39  		for _, v := range array {
    40  			path = v + string(filepath.Separator) + file
    41  			if ExistsFile(path) {
    42  				return path
    43  			}
    44  		}
    45  	}
    46  	return ""
    47  }