Skip to content

Commit c72ec65

Browse files
fall-through for other binaries (#489)
If you have a binary, nais-foo in your path and you call nais foo the cli will run nais-foo with all the rest of the args provided. This gives a bit of user extension capabilities and allows us to widen the ecosystem of how we do subcommands * fall-throuhg for other binaries * exit cleanly after running bin * E l u c i d a t e
1 parent 495bd34 commit c72ec65

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

cmd/cmd.go

+39
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package cmd
33
import (
44
"log"
55
"os"
6+
"os/exec"
67

78
"github.com/nais/cli/cmd/debugcmd"
89

@@ -48,8 +49,46 @@ func Run() {
4849

4950
m.CollectCommandHistogram(app.Commands)
5051

52+
// first, before running the cli propper we check if the argv[1] contains a
53+
// thing that is named nais-argv[1]. if so, we run that with the rest of the
54+
// argument string and then exit.
55+
// This gives us and our users a nice way of extending the cli by just shipping other
56+
// binaries. this is spiritually what git and others do.
57+
if len(os.Args) > 1 {
58+
if !isCommand(os.Args[1], app.Commands) {
59+
binaryName := "nais-" + os.Args[1]
60+
if err := runOtherBin(binaryName, os.Args[2:]); err == nil {
61+
os.Exit(0)
62+
63+
}
64+
}
65+
}
66+
5167
err := app.Run(os.Args)
5268
if err != nil {
5369
log.Fatal(err)
5470
}
5571
}
72+
73+
func isCommand(command string, commands []*cli.Command) bool {
74+
for _, cmd := range commands {
75+
if cmd.Name == command {
76+
return true
77+
}
78+
}
79+
return false
80+
}
81+
82+
func runOtherBin(binary string, args []string) error {
83+
binaryPath, err := exec.LookPath(binary)
84+
if err != nil {
85+
return err
86+
}
87+
88+
cmd := exec.Command(binaryPath, args...)
89+
cmd.Stdout = os.Stdout
90+
cmd.Stderr = os.Stderr
91+
cmd.Stdin = os.Stdin
92+
93+
return cmd.Run()
94+
}

0 commit comments

Comments
 (0)