Skip to content

Commit

Permalink
add git like subcommand deferring mechanism
Browse files Browse the repository at this point in the history
This commit implements a simple mechanism of deferring unknown
subcommands to other executables in $PATH.

When users executes `kks foo` kks will try to run `kks-foo` command.
  • Loading branch information
TeddyDD committed Nov 12, 2021
1 parent df89306 commit 08cd1a6
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ ENVIRONMENT VARIABLES
Use "kks <command> -h" for command usage.
```

### Unknown command

When unknown command is run, `kks` will try to find an executable named
`kks-<command>` in `$PATH`. If the executable is found, `kks` will run it
with all arguments that were provided to the unknown command.

## Configuration

`kks` can be configured through environment variables.
Expand Down
27 changes: 27 additions & 0 deletions cmd/external.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cmd

import (
"fmt"
"os"
"os/exec"
"path/filepath"
"syscall"
)

func External(args []string, original error) error {
if len(args) == 0 {
return original
}

thisExecutable := filepath.Base(os.Args[0])
path, err := exec.LookPath(fmt.Sprintf("%s-%s", thisExecutable, args[0]))
if err != nil {
// no such executable - return original error
return original
}
if len(args) < 1 {
args = args[1:]
}

return syscall.Exec(path, args, os.Environ())
}
5 changes: 4 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package cmd

import (
_ "embed"
"errors"
"fmt"
"os"
)

//go:embed embed/help
var helpTxt string

var UnknownSubcommand = errors.New("unknown subcommand")

func Root(args []string) error {
if len(args) < 1 || args[0] == "-h" || args[0] == "--help" {
printHelp()
Expand Down Expand Up @@ -39,7 +42,7 @@ func Root(args []string) error {
}
}

return fmt.Errorf("unknown subcommand: %s", subcommand)
return fmt.Errorf("can't run %s: %w", subcommand, UnknownSubcommand)
}

func containsString(s []string, e string) bool {
Expand Down
8 changes: 7 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"errors"
"fmt"
"log"
"os"
Expand All @@ -18,7 +19,12 @@ func main() {
os.Exit(0)
}

if err := cmd.Root(os.Args[1:]); err != nil {
err := cmd.Root(os.Args[1:])

if err != nil && errors.Is(err, cmd.UnknownSubcommand) {
err = cmd.External(os.Args[1:], err)
}
if err != nil {
log.Fatal(err)
}
}

0 comments on commit 08cd1a6

Please sign in to comment.