2024-07-05 02:37:59 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var ErrNotFound = errors.New("which: command not found")
|
|
|
|
|
2024-07-10 00:53:22 +02:00
|
|
|
type BasicOptions struct {
|
2024-07-10 00:44:28 +02:00
|
|
|
Env map[string]string
|
|
|
|
Sources []string
|
|
|
|
Cwd string
|
|
|
|
}
|
|
|
|
|
2024-07-10 00:53:22 +02:00
|
|
|
func Which(cmd string, options BasicOptions) (dir string, err error) {
|
2024-07-10 00:44:28 +02:00
|
|
|
|
|
|
|
var sourceCommand strings.Builder
|
|
|
|
for _, value := range options.Sources {
|
|
|
|
sourceCommand.WriteString(fmt.Sprintf("source %s && ", value))
|
|
|
|
}
|
2024-07-05 02:37:59 +02:00
|
|
|
|
2024-07-11 03:49:07 +02:00
|
|
|
command := exec.Command("which", cmd)
|
2024-07-10 00:44:28 +02:00
|
|
|
|
|
|
|
if options.Cwd != "" {
|
|
|
|
command.Dir = options.Cwd
|
|
|
|
}
|
|
|
|
|
2024-07-11 03:45:07 +02:00
|
|
|
for k, v := range options.Env {
|
|
|
|
command.Env = append(command.Env, fmt.Sprintf("%s=%s", k, v))
|
|
|
|
}
|
2024-07-05 02:37:59 +02:00
|
|
|
|
|
|
|
outputBytes, err := command.Output()
|
|
|
|
if err != nil {
|
|
|
|
var exitErr *exec.ExitError
|
|
|
|
if errors.As(err, &exitErr) {
|
|
|
|
if exitErr.ExitCode() == 1 {
|
|
|
|
return "", ErrNotFound
|
|
|
|
} else {
|
|
|
|
return "", fmt.Errorf("command error: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-11 03:48:37 +02:00
|
|
|
fmt.Println(string(outputBytes))
|
|
|
|
|
2024-07-05 02:37:59 +02:00
|
|
|
return strings.Trim(string(outputBytes), "\n"), nil
|
|
|
|
|
|
|
|
}
|