Skip to content

Commit

Permalink
Custom error for command not found
Browse files Browse the repository at this point in the history
  • Loading branch information
Dharma-09 committed Sep 20, 2024
1 parent 41ba430 commit f07d67c
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 6 deletions.
7 changes: 5 additions & 2 deletions ee/allowedcmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"path/filepath"
"errors"
)

type AllowedCommand func(ctx context.Context, arg ...string) (*exec.Cmd, error)
Expand All @@ -20,6 +21,8 @@ func newCmd(ctx context.Context, fullPathToCmd string, arg ...string) *exec.Cmd
return exec.CommandContext(ctx, fullPathToCmd, arg...) //nolint:forbidigo // This is our approved usage of exec.CommandContext
}

var ErrCommandNotFound = errors.New("command not found")

func validatedCommand(ctx context.Context, knownPath string, arg ...string) (*exec.Cmd, error) {
knownPath = filepath.Clean(knownPath)

Expand All @@ -31,15 +34,15 @@ func validatedCommand(ctx context.Context, knownPath string, arg ...string) (*ex
// We expect to know the exact location for allowlisted commands on all
// OSes except for a few Linux distros.
if !allowSearchPath() {
return nil, fmt.Errorf("not found: %s", knownPath)
return nil, fmt.Errorf("%w: %s",ErrCommandNotFound, knownPath)
}

cmdName := filepath.Base(knownPath)
if foundPath, err := exec.LookPath(cmdName); err == nil {
return newCmd(ctx, foundPath, arg...), nil
}

return nil, fmt.Errorf("%s not found at %s and could not be located elsewhere", cmdName, knownPath)
return nil, fmt.Errorf("%w: %s and could not be located elsewhere", ErrCommandNotFound, knownPath)
}

func allowSearchPath() bool {
Expand Down
4 changes: 1 addition & 3 deletions ee/allowedcmd/cmd_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@ func Apt(ctx context.Context, arg ...string) (*exec.Cmd, error) {
return validatedCommand(ctx, "/usr/bin/apt", arg...)
}

var ErrHomebrewNotFound = errors.New("homebrew not found")

func Brew(ctx context.Context, arg ...string) (*exec.Cmd, error) {
validatedCmd, err := validatedCommand(ctx, "/home/linuxbrew/.linuxbrew/bin/brew", arg...)
if err != nil {
return nil, ErrHomebrewNotFound
return nil, nil
}

validatedCmd.Env = append(validatedCmd.Environ(), "HOMEBREW_NO_AUTO_UPDATE=1")
Expand Down
2 changes: 1 addition & 1 deletion ee/tables/homebrew/upgradeable.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (t *Table) generate(ctx context.Context, queryContext table.QueryContext) (
cmd, err := allowedcmd.Brew(ctx)

if err != nil {
if errors.Is(err, allowedcmd.ErrHomebrewNotFound) {
if errors.Is(err, allowedcmd.ErrCommandNotFound) {
// No data, no error
return nil, nil
}
Expand Down

0 comments on commit f07d67c

Please sign in to comment.