add env and source options to commands

This commit is contained in:
Shane C 2024-07-09 18:44:28 -04:00
parent 992dd14272
commit 5d646427bd
Signed by: shane
GPG key ID: E46B5FEA35B22FF9
3 changed files with 26 additions and 8 deletions

View file

@ -9,9 +9,28 @@ import (
var ErrNotFound = errors.New("which: command not found")
func Which(cmd string) (dir string, err error) {
type WhichOptions struct {
Env map[string]string
Sources []string
Cwd string
}
command := exec.Command("which", cmd)
func Which(cmd string, options WhichOptions) (dir string, err error) {
var sourceCommand strings.Builder
for _, value := range options.Sources {
sourceCommand.WriteString(fmt.Sprintf("source %s && ", value))
}
command := exec.Command(sourceCommand.String(), "which", cmd)
if options.Cwd != "" {
command.Dir = options.Cwd
}
for k, v := range options.Env {
command.Env = append(command.Env, fmt.Sprintf("%s=%s", k, v))
}
outputBytes, err := command.Output()
if err != nil {

View file

@ -160,11 +160,6 @@ func (cmd *LinuxCommand) Run() error {
}
}()
// Loop through env to format and add them to the command.
for key, value := range cmd.Options.Env {
command.Env = append(command.Env, fmt.Sprintf("%s=%s", key, value))
}
isCommandExecutable, err := cmd.isCommandExecutable(cmd.Options.Command)
if err != nil {
return err

View file

@ -12,7 +12,11 @@ import (
func (cmd *LinuxCommand) isCommandExecutable(command string) (bool, error) {
whichOut, err := cmd2.Which(command)
whichOut, err := cmd2.Which(command, cmd2.WhichOptions{
Env: cmd.Options.Env,
Sources: cmd.Options.Sources,
Cwd: cmd.Options.Cwd,
})
if err != nil {
if errors.Is(err, cmd2.ErrNotFound) {
if _, err := os.Stat(command); errors.Is(err, fs.ErrNotExist) {