Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<name>` on your `PATH` becomes `cu <name>`, 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-<name>`. 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/)
Expand Down
180 changes: 180 additions & 0 deletions internal/cmd/extension.go
Original file line number Diff line number Diff line change
@@ -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"
}
11 changes: 11 additions & 0 deletions internal/cmd/extension_other.go
Original file line number Diff line number Diff line change
@@ -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()
}
Loading
Loading