diff --git a/README.md b/README.md index f4d55f2..540c632 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,21 @@ cu api /list/abc123/task -X POST -d '{"name": "New Task"}' cu api "/list/abc123/task?archived=false" ``` +## Extensions + +Any executable named `cu-` on your `PATH` becomes `cu `, the same +convention `kubectl` and `gh` use: + +```bash +# an executable called cu-worklog on PATH +cu worklog plan --since 1d # runs: cu-worklog plan --since 1d +``` + +Builtins always win, so an extension can never shadow a cu command — a shadowed +extension stays runnable directly as `cu-`. The child inherits +`CU_CONFIG_DIR`, `CU_WORKSPACE` and `CU_PROJECT_CONFIG` so it does not have to +rediscover cu's context, and its exit code is passed through unchanged. + ## Documentation Full documentation is available at [https://timimsms.github.io/cu/](https://timimsms.github.io/cu/) diff --git a/internal/cmd/extension.go b/internal/cmd/extension.go new file mode 100644 index 0000000..38a593d --- /dev/null +++ b/internal/cmd/extension.go @@ -0,0 +1,180 @@ +package cmd + +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + + "github.com/spf13/pflag" + "github.com/timimsms/cu/internal/config" +) + +// extensionPrefix is the naming convention for external subcommands: +// `cu worklog` runs `cu-worklog` from PATH, the same shape kubectl and gh use. +const extensionPrefix = "cu-" + +// extensionName constrains a word to a bare command name. Without this, +// exec.LookPath treats anything containing a separator as a *path* rather than +// a PATH search, so `cu ../../tmp/evil` would resolve and run an executable +// that was never on PATH at all. Extensions are found on PATH, by name, or not +// at all. +var extensionName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]*$`) + +// tryExtension runs an external subcommand when cobra cannot resolve the word, +// and never returns if it does. It is deliberately the *last* resort: builtins +// always win, so an extension can never shadow a cu command. +// +// There is no PATH scan at startup — one exec.LookPath only once a word is +// known to be unresolvable — so this costs nothing on the normal path. +func tryExtension(args []string) { + if len(args) == 0 { + return + } + + // cobra only registers its default help and completion commands inside + // Execute, so register them now: otherwise Find cannot see `help`, and a + // `cu-help` on PATH would replace it. + rootCmd.InitDefaultHelpCmd() + rootCmd.InitDefaultCompletionCmd(args...) + + // Only consider a word cobra itself could not resolve. + if _, _, err := rootCmd.Find(args); err == nil { + return + } + + idx := firstCommandWord(args, rootCmd.PersistentFlags()) + if idx < 0 { + return + } + word := args[idx] + if strings.HasPrefix(word, extensionPrefix) || !extensionName.MatchString(word) { + return + } + + path, err := exec.LookPath(extensionPrefix + word) + if err != nil { + // No such extension: fall through so cobra reports the unknown + // command with its did-you-mean suggestions. + return + } + + runExtension(path, args[:idx], args[idx+1:]) +} + +// runExtension execs the extension and exits with its status. It does not +// return. globals are cu's own arguments that preceded the extension word; +// rest is everything after it. +func runExtension(path string, globals, rest []string) { + // Pass every argument after the extension word through verbatim, including + // flags that look like cu's own — they belong to the extension. + + // #nosec G702 G204 -- the resolved path is not attacker-controlled: the word + // is constrained to ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ so it cannot contain a path + // separator, meaning LookPath can only return an executable already on the + // user's own PATH. The arguments are the user's own command line, forwarded + // verbatim, and cross no privilege boundary — this is the same trust model + // as the shell that invoked cu. + cmd := exec.Command(path, rest...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Env = extensionEnv(globals) + + err := cmd.Run() + if err == nil { + os.Exit(0) + } + + // Propagate the child's exit status; a cu-shaped failure code from an + // extension should reach the caller's shell unchanged. + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + os.Exit(exitStatus(exitErr)) + } + + fmt.Fprintf(os.Stderr, "failed to run %s: %v\n", filepath.Base(path), err) + os.Exit(1) +} + +// extensionEnv hands the child the context it would otherwise have to +// rediscover: which config cu resolved, and which workspace and project file +// are in play. globals must be only the arguments before the extension word: +// a --config after it belongs to the extension, not to cu. +func extensionEnv(globals []string) []string { + // The extension runs before PersistentPreRunE, so load config here. A + // failure is not fatal — the extension simply gets less context. + _ = config.Init(configFileFrom(globals)) + + env := append(os.Environ(), + "CU_CONFIG_DIR="+filepath.Dir(config.GlobalConfigPath()), + "CU_WORKSPACE="+config.GetString("default_workspace"), + "CU_PROJECT_CONFIG="+config.GetProjectConfigPath(), + ) + return env +} + +// configFileFrom extracts a --config value so the child sees the same config +// cu would have used. +func configFileFrom(args []string) string { + for i := 0; i < len(args); i++ { + a := args[i] + if v, ok := strings.CutPrefix(a, "--config="); ok { + return v + } + if a == "--config" && i+1 < len(args) { + return args[i+1] + } + } + return "" +} + +// firstCommandWord returns the index of the first positional argument — the +// candidate command — skipping global flags and the values they consume, or -1 +// if there is none. Getting this wrong would treat a flag's value as a command +// name, so flag arity is read from the flag set rather than guessed. It returns +// an index rather than the word because the word can also appear earlier as a +// flag value (`cu --config hello hello`). +func firstCommandWord(args []string, flags *pflag.FlagSet) int { + for i := 0; i < len(args); i++ { + a := args[i] + + switch { + case a == "--": + return -1 + + case strings.HasPrefix(a, "--"): + if strings.Contains(a, "=") { + continue // --flag=value consumes nothing further + } + name := strings.TrimPrefix(a, "--") + if takesValue(flags.Lookup(name)) { + i++ + } + + case strings.HasPrefix(a, "-") && len(a) > 1: + if strings.Contains(a, "=") { + continue + } + // In a shorthand cluster only the final flag can take a value. + last := a[len(a)-1:] + if takesValue(flags.ShorthandLookup(last)) { + i++ + } + + default: + return i + } + } + return -1 +} + +// takesValue reports whether a flag consumes the following argument. An +// unknown flag is assumed not to, so an unrecognised flag cannot swallow the +// command word. +func takesValue(f *pflag.Flag) bool { + return f != nil && f.Value.Type() != "bool" +} diff --git a/internal/cmd/extension_other.go b/internal/cmd/extension_other.go new file mode 100644 index 0000000..495cddb --- /dev/null +++ b/internal/cmd/extension_other.go @@ -0,0 +1,11 @@ +//go:build !unix + +package cmd + +import "os/exec" + +// exitStatus returns the child's exit code. Outside Unix there are no signal +// exits to translate. +func exitStatus(err *exec.ExitError) int { + return err.ExitCode() +} diff --git a/internal/cmd/extension_test.go b/internal/cmd/extension_test.go new file mode 100644 index 0000000..7637072 --- /dev/null +++ b/internal/cmd/extension_test.go @@ -0,0 +1,215 @@ +package cmd + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/spf13/pflag" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func testFlags() *pflag.FlagSet { + fs := pflag.NewFlagSet("cu", pflag.ContinueOnError) + fs.String("config", "", "") + fs.Bool("debug", false, "") + fs.StringP("output", "o", "table", "") + return fs +} + +func TestFirstCommandWord(t *testing.T) { + cases := []struct { + name string + args []string + want int + }{ + {"bare word", []string{"worklog", "plan"}, 0}, + {"no args", nil, -1}, + {"only flags", []string{"--debug"}, -1}, + + // A value-taking flag must not have its value mistaken for the + // command — that would exec cu-x instead of cu-worklog. + {"long flag with value", []string{"--config", "x", "worklog"}, 2}, + {"long flag with equals", []string{"--config=x", "worklog"}, 1}, + {"shorthand with value", []string{"-o", "json", "worklog"}, 2}, + {"shorthand with equals", []string{"-o=json", "worklog"}, 1}, + + // Boolean flags consume nothing. + {"bool flag", []string{"--debug", "worklog"}, 1}, + {"bool then valued", []string{"--debug", "--config", "x", "worklog"}, 3}, + + // The word itself can appear earlier as a flag value; the index must + // point at the command, not the first string that matches it. + {"word repeated as flag value", []string{"--config", "worklog", "worklog", "plan"}, 2}, + + // An unknown flag is assumed not to take a value, so it cannot + // swallow the command word. + {"unknown flag", []string{"--mystery", "worklog"}, 1}, + + {"double dash ends the search", []string{"--", "worklog"}, -1}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, firstCommandWord(tc.args, testFlags())) + }) + } +} + +func TestConfigFileFrom(t *testing.T) { + assert.Equal(t, "/tmp/c.yaml", configFileFrom([]string{"--config", "/tmp/c.yaml", "worklog"})) + assert.Equal(t, "/tmp/c.yaml", configFileFrom([]string{"--config=/tmp/c.yaml", "worklog"})) + assert.Equal(t, "", configFileFrom([]string{"worklog", "plan"})) + assert.Equal(t, "", configFileFrom([]string{"--config"}), "a dangling --config must not panic") +} + +func TestTryExtensionLeavesBuiltinsAlone(t *testing.T) { + // tryExtension exits the process when it dispatches, so the safe + // assertion is that a resolvable builtin returns normally — proving + // builtins are never routed to an extension. + tryExtension([]string{"version"}) + tryExtension([]string{"task", "list"}) + tryExtension([]string{}) +} + +func TestExtensionNameRejectsPaths(t *testing.T) { + // exec.LookPath treats a word containing a separator as a path rather than + // a PATH search, so without this constraint `cu ../../tmp/evil` would run + // an executable that was never on PATH. Extensions are found on PATH, by + // name, or not at all. + for _, bad := range []string{ + "../evil", "../../tmp/evil", "/abs/evil", "dir/evil", + ".hidden", "-leading-dash", "", "has space", "semi;colon", "dot.dot", + } { + assert.False(t, extensionName.MatchString(bad), "must reject %q", bad) + } + + for _, good := range []string{"worklog", "trailer", "my-ext", "my_ext", "ext2"} { + assert.True(t, extensionName.MatchString(good), "must accept %q", good) + } +} + +// TestExtensionHelperProcess is not a real test: runCu re-executes the test +// binary into it so the full Execute path — including os.Exit — runs in a +// child process the test can observe. +func TestExtensionHelperProcess(t *testing.T) { + if os.Getenv("CU_EXT_HELPER") != "1" { + t.Skip("helper process for exec-based extension tests") + } + args := []string{"cu"} + for i, a := range os.Args { + if a == "--" { + args = append(args, os.Args[i+1:]...) + break + } + } + os.Args = args + if err := Execute(); err != nil { + os.Exit(1) + } + os.Exit(0) +} + +// fakeExtension is a cu-hello that prints each argument it received, then the +// config dir cu handed it, then exits with $FAKE_EXIT (or kills itself with +// SIGTERM when asked). +const fakeExtension = `#!/bin/sh +for a in "$@"; do printf 'arg:%s\n' "$a"; done +printf 'dir:%s\n' "$CU_CONFIG_DIR" +if [ "$FAKE_SIGNAL" = "1" ]; then kill -TERM $$; fi +exit "${FAKE_EXIT:-0}" +` + +// runCu runs `cu args...` in a child process with only binDir on PATH and an +// isolated HOME, returning its stdout and exit status. +func runCu(t *testing.T, binDir string, env []string, args ...string) (string, int) { + t.Helper() + home := t.TempDir() + cmd := exec.Command(os.Args[0], append([]string{"-test.run=^TestExtensionHelperProcess$", "--"}, args...)...) + cmd.Env = append([]string{ + "CU_EXT_HELPER=1", + "PATH=" + binDir, + "HOME=" + home, + "XDG_CONFIG_HOME=" + filepath.Join(home, ".config"), + }, env...) + out, err := cmd.Output() + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return string(out), exitErr.ExitCode() + } + require.NoError(t, err) + return string(out), 0 +} + +func writeScript(t *testing.T, dir, name, body string) { + t.Helper() + // #nosec G306 -- the test fixture must be executable to be found on PATH. + require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(body), 0o700)) +} + +func TestExtensionDispatchExec(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("uses a POSIX shell script as the fake extension") + } + bin := t.TempDir() + writeScript(t, bin, "cu-hello", fakeExtension) + + argsOf := func(out string) []string { + var got []string + for _, line := range strings.Split(out, "\n") { + if v, ok := strings.CutPrefix(line, "arg:"); ok { + got = append(got, v) + } + } + return got + } + + t.Run("forwards everything after the word verbatim", func(t *testing.T) { + out, code := runCu(t, bin, nil, "hello", "plan", "--since", "1d", "-o", "json") + assert.Equal(t, 0, code) + assert.Equal(t, []string{"plan", "--since", "1d", "-o", "json"}, argsOf(out)) + }) + + t.Run("cu's own preceding flags are not forwarded", func(t *testing.T) { + out, code := runCu(t, bin, nil, "--debug", "-o", "json", "hello", "plan") + assert.Equal(t, 0, code) + assert.Equal(t, []string{"plan"}, argsOf(out)) + }) + + t.Run("word repeated as a flag value", func(t *testing.T) { + out, code := runCu(t, bin, nil, "--config", "hello", "hello", "real") + assert.Equal(t, 0, code) + assert.Equal(t, []string{"real"}, argsOf(out)) + }) + + t.Run("a --config after the word belongs to the extension", func(t *testing.T) { + out, code := runCu(t, bin, nil, "hello", "--config", "/elsewhere/c.yaml") + assert.Equal(t, 0, code) + assert.Equal(t, []string{"--config", "/elsewhere/c.yaml"}, argsOf(out)) + assert.NotContains(t, out, "dir:/elsewhere", "cu must not adopt the extension's --config") + }) + + t.Run("exit code passes through", func(t *testing.T) { + _, code := runCu(t, bin, []string{"FAKE_EXIT=7"}, "hello") + assert.Equal(t, 7, code) + }) + + t.Run("signal exit maps to 128+signal", func(t *testing.T) { + _, code := runCu(t, bin, []string{"FAKE_SIGNAL=1"}, "hello") + assert.Equal(t, 128+15, code) + }) + + t.Run("cu-help on PATH does not replace cu help", func(t *testing.T) { + hijack := t.TempDir() + writeScript(t, hijack, "cu-help", "#!/bin/sh\necho HIJACKED\nexit 3\n") + out, code := runCu(t, hijack, nil, "help") + assert.Equal(t, 0, code) + assert.NotContains(t, out, "HIJACKED") + assert.Contains(t, out, "Usage:") + }) +} diff --git a/internal/cmd/extension_unix.go b/internal/cmd/extension_unix.go new file mode 100644 index 0000000..491d66c --- /dev/null +++ b/internal/cmd/extension_unix.go @@ -0,0 +1,18 @@ +//go:build unix + +package cmd + +import ( + "os/exec" + "syscall" +) + +// exitStatus maps a child's exit to the status a shell would report. A child +// killed by a signal has no exit code (ExitCode returns -1, which would surface +// as 255), so follow the shell convention of 128+signal instead. +func exitStatus(err *exec.ExitError) int { + if ws, ok := err.Sys().(syscall.WaitStatus); ok && ws.Signaled() { + return 128 + int(ws.Signal()) + } + return err.ExitCode() +} diff --git a/internal/cmd/root.go b/internal/cmd/root.go index e1738df..49ae424 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -40,6 +40,9 @@ enabling efficient task management and seamless integration with development wor // Execute adds all child commands to the root command and sets flags appropriately. func Execute() error { + // Builtins first: tryExtension only acts on a word cobra cannot resolve, + // and does not return when it finds one. + tryExtension(os.Args[1:]) return rootCmd.Execute() }