shell/cmd/which.go

50 lines
936 B
Go
Raw Permalink Normal View History

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-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))
}
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)
}
}
}
return strings.Trim(string(outputBytes), "\n"), nil
}