From 53ad0d691c52797922eaa4cec0c0a88ab08470fc Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Thu, 19 Nov 2026 09:11:33 -0600 Subject: [PATCH 1/2] Handle create and repo aliases in generated zsh integration The generated t wrapper only matched canonical names for create and repo, so invocations using their Cobra aliases (t c and t rp) fell through to timber without directory switching, --no-cd handling, or --no-cd flag completion. Match all aliases for create and repo in the generated wrapper and completion script, and cover aliases for every wrapper-handled command in the zsh functional tests. Change-Id: I5db15b0debac67adc7a3f41c0a9d6ca1c87f010d --- internal/cli/generate/zsh/zsh.go | 12 +- internal/cli/generate_test.go | 202 +++++++++++------- .../generate_zsh_create_functional_test.go | 36 ++-- ...enerate_zsh_create_nocd_functional_test.go | 16 +- 4 files changed, 164 insertions(+), 102 deletions(-) diff --git a/internal/cli/generate/zsh/zsh.go b/internal/cli/generate/zsh/zsh.go index 69997ec..35ec137 100644 --- a/internal/cli/generate/zsh/zsh.go +++ b/internal/cli/generate/zsh/zsh.go @@ -215,11 +215,13 @@ _%[1]s() # The shell wrapper adds 'create --no-cd', which timber itself does not # define, so offer it alongside Cobra's completions when completing flags. - if [[ ${words[2]} == create && ${lastParam} == -* ]]; then - if (( ${completions[(I)--no-cd:*]:-0} == 0 )); then + case "${words[2]}" in + create|c) + if [[ ${lastParam} == -* ]] && (( ${completions[(I)--no-cd:*]:-0} == 0 )); then completions+=('--no-cd:Create without changing directories') fi - fi + ;; + esac # The 'switch' subcommand is hidden from 'timber --help' (the wrapper # handles 'switch|sw' itself so it can cd), which also hides it from @@ -370,7 +372,7 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { ` + x.name + `() { case "$1" in - create) + create|c) shift local no_cd=0 herdr=0 no_herdr=0 skip_next=0 local -a forward=() @@ -459,7 +461,7 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { fi cd "$target_dir" ;; - repo) + repo|rp) case "$2" in rename|mv) local path_file diff --git a/internal/cli/generate_test.go b/internal/cli/generate_test.go index 6de52c4..23aaa5c 100644 --- a/internal/cli/generate_test.go +++ b/internal/cli/generate_test.go @@ -664,9 +664,11 @@ sys.stdout.write(log.decode("utf-8", "replace")) sortValue := runComplete("t list --sort rec", "recency") assert.Contains(t, sortValue, "t list --sort recency") - wrapperFlags := runComplete("t create --no-", "--no-cd", "--no-herdr") - assert.Contains(t, wrapperFlags, "--no-cd") - assert.Contains(t, wrapperFlags, "--no-herdr") + for _, command := range []string{"create", "c"} { + wrapperFlags := runComplete("t "+command+" --no-", "--no-cd", "--no-herdr") + assert.Contains(t, wrapperFlags, "--no-cd", "command=%s", command) + assert.Contains(t, wrapperFlags, "--no-herdr", "command=%s", command) + } } func TestGeneratedZshWrapperAutoloadsAfterCompinit(t *testing.T) { @@ -710,29 +712,46 @@ func TestGeneratedZshWrapperChangesToRenamedCurrentWorktree(t *testing.T) { outDir := resolvedTempDir(t) require.NoError(t, runTimberCommand(t, "generate", "zsh", "--out", outDir, "--force").err) - worktreeParent := resolvedTempDir(t) - oldWorktree := filepath.Join(worktreeParent, "old") - oldSubdirectory := filepath.Join(oldWorktree, "nested") - require.NoError(t, os.MkdirAll(oldSubdirectory, 0o755)) - - binDir := resolvedTempDir(t) - fakeTimber := `#!/bin/sh + type testCase struct { + name string + invocation string + } + for _, tc := range []testCase{ + {name: "repo rename", invocation: "repo rename"}, + {name: "repo mv", invocation: "repo mv"}, + {name: "rp rename", invocation: "rp rename"}, + {name: "rp mv", invocation: "rp mv"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + worktreeParent := resolvedTempDir(t) + oldWorktree := filepath.Join(worktreeParent, "old") + oldSubdirectory := filepath.Join(oldWorktree, "nested") + require.NoError(t, os.MkdirAll(oldSubdirectory, 0o755)) + + binDir := resolvedTempDir(t) + fakeTimber := `#!/bin/sh old_worktree=$(dirname "$PWD") new_worktree=$(dirname "$old_worktree")/new mv "$old_worktree" "$new_worktree" || exit $? -printf '%s\n' "$new_worktree/nested" > "$TIMBER_RENAME_PATH_FILE" +if [ -n "${TIMBER_RENAME_PATH_FILE:-}" ]; then + printf '%s\n' "$new_worktree/nested" > "$TIMBER_RENAME_PATH_FILE" +fi ` - require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) - - command := shellTestCommand(t, - "zsh", "-f", "-c", - `source "$1"; cd "$2"; t repo rename old new >/dev/null; pwd -P`, - "--", filepath.Join(outDir, "t"), oldSubdirectory, - ) - command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := command.CombinedOutput() - require.NoError(t, err, string(output)) - assert.Equal(t, shellCanonicalPath(filepath.Join(worktreeParent, "new", "nested")), strings.TrimSpace(string(output))) + require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) + + command := shellTestCommand(t, + "zsh", "-f", "-c", + `source "$1"; cd "$2"; t `+tc.invocation+` old new >/dev/null; printf '%s\n%s\n' "$PWD" "$(pwd -P)"`, + "--", filepath.Join(outDir, "t"), oldSubdirectory, + ) + command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := command.CombinedOutput() + require.NoError(t, err, string(output)) + want := shellCanonicalPath(filepath.Join(worktreeParent, "new", "nested")) + assert.Equal(t, want+"\n"+want, strings.TrimSpace(string(output))) + }) + } } func TestGeneratedZshWrapperChangesToMovedCurrentWorktree(t *testing.T) { @@ -744,29 +763,37 @@ func TestGeneratedZshWrapperChangesToMovedCurrentWorktree(t *testing.T) { outDir := resolvedTempDir(t) require.NoError(t, runTimberCommand(t, "generate", "zsh", "--out", outDir, "--force").err) - worktreeParent := resolvedTempDir(t) - oldWorktree := filepath.Join(worktreeParent, "old") - oldSubdirectory := filepath.Join(oldWorktree, "nested") - require.NoError(t, os.MkdirAll(oldSubdirectory, 0o755)) + for _, subcommand := range []string{"move", "mv"} { + t.Run(subcommand, func(t *testing.T) { + t.Parallel() + worktreeParent := resolvedTempDir(t) + oldWorktree := filepath.Join(worktreeParent, "old") + oldSubdirectory := filepath.Join(oldWorktree, "nested") + require.NoError(t, os.MkdirAll(oldSubdirectory, 0o755)) - binDir := resolvedTempDir(t) - fakeTimber := `#!/bin/sh + binDir := resolvedTempDir(t) + fakeTimber := `#!/bin/sh old_worktree=$(dirname "$PWD") new_worktree=$(dirname "$old_worktree")/new mv "$old_worktree" "$new_worktree" || exit $? -printf '%s\n' "$new_worktree/nested" > "$TIMBER_RENAME_PATH_FILE" +if [ -n "${TIMBER_RENAME_PATH_FILE:-}" ]; then + printf '%s\n' "$new_worktree/nested" > "$TIMBER_RENAME_PATH_FILE" +fi ` - require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) - - command := shellTestCommand(t, - "zsh", "-f", "-c", - `source "$1"; cd "$2"; t move feature@repo "$3" >/dev/null; pwd -P`, - "--", filepath.Join(outDir, "t"), oldSubdirectory, filepath.Join(worktreeParent, "new"), - ) - command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := command.CombinedOutput() - require.NoError(t, err, string(output)) - assert.Equal(t, shellCanonicalPath(filepath.Join(worktreeParent, "new", "nested")), strings.TrimSpace(string(output))) + require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) + + command := shellTestCommand(t, + "zsh", "-f", "-c", + `source "$1"; cd "$2"; t `+subcommand+` feature@repo "$3" >/dev/null; printf '%s\n%s\n' "$PWD" "$(pwd -P)"`, + "--", filepath.Join(outDir, "t"), oldSubdirectory, filepath.Join(worktreeParent, "new"), + ) + command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := command.CombinedOutput() + require.NoError(t, err, string(output)) + want := shellCanonicalPath(filepath.Join(worktreeParent, "new", "nested")) + assert.Equal(t, want+"\n"+want, strings.TrimSpace(string(output))) + }) + } } func TestGeneratedZshWrapperRestoresDirectoryOnFailure(t *testing.T) { @@ -832,37 +859,49 @@ func TestGeneratedZshWrapperLeavesRemovedCurrentDirectoryForHome(t *testing.T) { outDir := resolvedTempDir(t) require.NoError(t, runTimberCommand(t, "generate", "zsh", "--out", outDir, "--force").err) - removedDir := resolvedTempDir(t) - binDir := resolvedTempDir(t) - fakeTimber := `#!/bin/sh + for _, subcommand := range []string{"remove", "rm"} { + t.Run(subcommand, func(t *testing.T) { + t.Parallel() + removedDir := resolvedTempDir(t) + binDir := resolvedTempDir(t) + fakeTimber := `#!/bin/sh cd / && rm -rf "$2" ` - require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) - - command := shellTestCommand(t, - "zsh", "-f", "-c", - `source "$1"; cd "$2"; t remove "$2" >/dev/null; printf '%s' "$PWD"`, - "--", filepath.Join(outDir, "t"), removedDir, - ) - command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := command.CombinedOutput() - require.NoError(t, err, string(output)) - assert.Equal(t, shellCanonicalPath(command.Dir), strings.TrimSpace(string(output))) + require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) + + command := shellTestCommand(t, + "zsh", "-f", "-c", + `source "$1"; cd "$2"; t `+subcommand+` "$2" >/dev/null; printf '%s' "$PWD"`, + "--", filepath.Join(outDir, "t"), removedDir, + ) + command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := command.CombinedOutput() + require.NoError(t, err, string(output)) + assert.Equal(t, shellCanonicalPath(command.Dir), strings.TrimSpace(string(output))) + }) + } } func TestGeneratedZshWrapperChangesDirectoryOnSwitch(t *testing.T) { t.Parallel() - targetDir := resolvedTempDir(t) - fakeTimber := `#!/bin/sh -printf '%s\n' "$TIMBER_SWITCH_PATH_FILE_TARGET" > "$TIMBER_SWITCH_PATH_FILE" + for _, subcommand := range []string{"switch", "sw"} { + t.Run(subcommand, func(t *testing.T) { + t.Parallel() + targetDir := resolvedTempDir(t) + fakeTimber := `#!/bin/sh +if [ -n "${TIMBER_SWITCH_PATH_FILE:-}" ]; then + printf '%s\n' "$TIMBER_SWITCH_PATH_FILE_TARGET" > "$TIMBER_SWITCH_PATH_FILE" +fi ` - command := generatedZshCommand(t, fakeTimber, - `source "$1"; t switch feature@repo >/dev/null; pwd -P`, - ) - command.Env = shellTestEnvironment(command.Env, "TIMBER_SWITCH_PATH_FILE_TARGET="+targetDir) - output, err := command.CombinedOutput() - require.NoError(t, err, string(output)) - assert.Equal(t, shellCanonicalPath(targetDir), strings.TrimSpace(string(output))) + command := generatedZshCommand(t, fakeTimber, + `source "$1"; t `+subcommand+` feature@repo >/dev/null; pwd -P`, + ) + command.Env = shellTestEnvironment(command.Env, "TIMBER_SWITCH_PATH_FILE_TARGET="+targetDir) + output, err := command.CombinedOutput() + require.NoError(t, err, string(output)) + assert.Equal(t, shellCanonicalPath(targetDir), strings.TrimSpace(string(output))) + }) + } } func TestGeneratedZshWrapperLeavesImportedSourceDirectory(t *testing.T) { @@ -874,23 +913,28 @@ func TestGeneratedZshWrapperLeavesImportedSourceDirectory(t *testing.T) { outDir := resolvedTempDir(t) require.NoError(t, runTimberCommand(t, "generate", "zsh", "--out", outDir, "--force").err) - startDir := resolvedTempDir(t) - sourceDir := resolvedTempDir(t) - binDir := resolvedTempDir(t) - fakeTimber := `#!/bin/sh + for _, subcommand := range []string{"repo", "rp"} { + t.Run(subcommand, func(t *testing.T) { + t.Parallel() + startDir := resolvedTempDir(t) + sourceDir := resolvedTempDir(t) + binDir := resolvedTempDir(t) + fakeTimber := `#!/bin/sh rm -rf "$3" ` - require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) - - command := shellTestCommand(t, - "zsh", "-f", "-c", - `source "$1"; cd "$2"; t repo import "$3" >/dev/null; printf '%s' "$PWD"`, - "--", filepath.Join(outDir, "t"), startDir, sourceDir, - ) - command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := command.CombinedOutput() - require.NoError(t, err, string(output)) - assert.Equal(t, shellCanonicalPath(command.Dir), strings.TrimSpace(string(output))) + require.NoError(t, os.WriteFile(filepath.Join(binDir, "timber"), []byte(fakeTimber), 0o755)) + + command := shellTestCommand(t, + "zsh", "-f", "-c", + `source "$1"; cd "$2"; t `+subcommand+` import "$3" >/dev/null; printf '%s' "$PWD"`, + "--", filepath.Join(outDir, "t"), startDir, sourceDir, + ) + command.Env = shellTestEnvironment(command.Env, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := command.CombinedOutput() + require.NoError(t, err, string(output)) + assert.Equal(t, shellCanonicalPath(command.Dir), strings.TrimSpace(string(output))) + }) + } } func TestGeneratedZshWrapperRestoresDirectoryOnFailedImport(t *testing.T) { diff --git a/internal/cli/generate_zsh_create_functional_test.go b/internal/cli/generate_zsh_create_functional_test.go index 30a82ca..a9f4256 100644 --- a/internal/cli/generate_zsh_create_functional_test.go +++ b/internal/cli/generate_zsh_create_functional_test.go @@ -12,30 +12,42 @@ import ( func TestFunctionalZshCreateChangesDirectoryToReportedPath(t *testing.T) { t.Parallel() - for _, custom := range []bool{false, true} { - name := "default" - if custom { - name = "custom" - } - t.Run(name, func(t *testing.T) { + type testCase struct { + name string + subcommand string + custom bool + } + for _, tc := range []testCase{ + {name: "create default", subcommand: "create"}, + {name: "create custom", subcommand: "create", custom: true}, + {name: "alias default", subcommand: "c"}, + {name: "alias custom", subcommand: "c", custom: true}, + } { + t.Run(tc.name, func(t *testing.T) { t.Parallel() target := filepath.Join(resolvedTempDir(t), "worktree with spaces") require.NoError(t, os.Mkdir(target, 0o755)) - invocation := `source "$1"; t create feature@repo >/dev/null || exit $?; pwd -P` - if custom { - invocation = `source "$1"; t create feature@repo "$TARGET_DIR" >/dev/null || exit $?; pwd -P` + invocation := `source "$1"; t ` + tc.subcommand + ` feature@repo >/dev/null || exit $?; pwd -P` + if tc.custom { + invocation = `source "$1"; t ` + tc.subcommand + ` feature@repo "$TARGET_DIR" >/dev/null || exit $?; pwd -P` } command := generatedZshCommand(t, `#!/bin/sh -[ "$1" = create ] && [ "$2" = feature@repo ] || exit 98 +case "$1" in +create|c) ;; +*) exit 98 ;; +esac +[ "$2" = feature@repo ] || exit 98 if [ "$CUSTOM_PATH" = true ]; then [ "$#" = 3 ] && [ "$3" = "$TARGET_DIR" ] || exit 97 else [ "$#" = 2 ] || exit 96 fi -printf '%s\n' "$TARGET_DIR" > "$TIMBER_CREATE_PATH_FILE" +if [ -n "${TIMBER_CREATE_PATH_FILE:-}" ]; then + printf '%s\n' "$TARGET_DIR" > "$TIMBER_CREATE_PATH_FILE" +fi `, invocation) customValue := "false" - if custom { + if tc.custom { customValue = "true" } command.Env = shellTestEnvironment(command.Env, "TARGET_DIR="+target, "CUSTOM_PATH="+customValue) diff --git a/internal/cli/generate_zsh_create_nocd_functional_test.go b/internal/cli/generate_zsh_create_nocd_functional_test.go index dac4fc0..faf36d4 100644 --- a/internal/cli/generate_zsh_create_nocd_functional_test.go +++ b/internal/cli/generate_zsh_create_nocd_functional_test.go @@ -12,22 +12,26 @@ func TestFunctionalZshCreateHonorsDirectoryChangeOverrides(t *testing.T) { t.Parallel() for _, testCase := range []struct { name string + subcommand string flag string herdr string forwarded string wantChange bool }{ - {name: "no-cd", flag: "--no-cd", forwarded: "create\nfeature@repo\n"}, - {name: "explicit herdr", flag: "--herdr", forwarded: "create\n--herdr\nfeature@repo\n"}, - {name: "automatic herdr", herdr: "1", forwarded: "create\nfeature@repo\n"}, - {name: "suppress automatic herdr", flag: "--no-herdr", herdr: "1", forwarded: "create\n--no-herdr\nfeature@repo\n", wantChange: true}, + {name: "no-cd", subcommand: "create", flag: "--no-cd", forwarded: "create\nfeature@repo\n"}, + {name: "alias no-cd", subcommand: "c", flag: "--no-cd", forwarded: "create\nfeature@repo\n"}, + {name: "explicit herdr", subcommand: "create", flag: "--herdr", forwarded: "create\n--herdr\nfeature@repo\n"}, + {name: "automatic herdr", subcommand: "create", herdr: "1", forwarded: "create\nfeature@repo\n"}, + {name: "suppress automatic herdr", subcommand: "create", flag: "--no-herdr", herdr: "1", forwarded: "create\n--no-herdr\nfeature@repo\n", wantChange: true}, } { t.Run(testCase.name, func(t *testing.T) { target := resolvedTempDir(t) command := generatedZshCommand(t, `#!/bin/sh -printf '%s\n' "$TARGET_DIR" > "$TIMBER_CREATE_PATH_FILE" +if [ -n "${TIMBER_CREATE_PATH_FILE:-}" ]; then + printf '%s\n' "$TARGET_DIR" > "$TIMBER_CREATE_PATH_FILE" +fi printf '%s\n' "$@" -`, `source "$1"; shift; t create "$@" feature@repo || exit $?; pwd -P`) +`, `source "$1"; shift; t `+testCase.subcommand+` "$@" feature@repo || exit $?; pwd -P`) if testCase.flag != "" { command.Args = append(command.Args, testCase.flag) } From 06eafb15d5f4f8e6097e6def35e0d2b5e9ea89aa Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Thu, 19 Nov 2026 09:26:33 -0600 Subject: [PATCH 2/2] Refactor: Derive zsh wrapper command aliases from Cobra commands Extract command lookup helpers in the zsh generator so wrapper case patterns and completion rules read command names and aliases directly from the Cobra command tree rather than duplicating hardcoded lists. This prevents future alias additions on wrapper-handled commands from drifting out of sync with the generated shell integration. Change-Id: Iedbfa45b1689daae565bb3de01a5140bf64723cd --- internal/cli/generate/zsh/zsh.go | 93 ++++++++++++++++++++++++-------- 1 file changed, 71 insertions(+), 22 deletions(-) diff --git a/internal/cli/generate/zsh/zsh.go b/internal/cli/generate/zsh/zsh.go index 35ec137..fcaebad 100644 --- a/internal/cli/generate/zsh/zsh.go +++ b/internal/cli/generate/zsh/zsh.go @@ -1,10 +1,12 @@ package zsh import ( + "cmp" "fmt" "io" "os" "path/filepath" + "strings" "github.com/spf13/cobra" ) @@ -20,7 +22,7 @@ func (x *zshCommandOptions) Execute(command *cobra.Command, args []string) error return fmt.Errorf(`create output directory: %w`, err) } - generatedFiles := x.generatedFiles() + generatedFiles := x.generatedFiles(command.Root()) if !x.force { if err := ensureGeneratedFilesDoNotExist(generatedFiles); err != nil { return err @@ -36,10 +38,10 @@ func (x *zshCommandOptions) Execute(command *cobra.Command, args []string) error return x.reportGeneratedFiles(command.ErrOrStderr(), generatedFiles) } -func (x *zshCommandOptions) generatedFiles() []generatedZshFile { +func (x *zshCommandOptions) generatedFiles(root *cobra.Command) []generatedZshFile { return []generatedZshFile{ - {kind: "function", path: filepath.Join(x.out, x.name), write: x.writeFunctionFile}, - {kind: "completion", path: filepath.Join(x.out, `_`+x.name), write: x.writeCompletionFile}, + {kind: "function", path: filepath.Join(x.out, x.name), write: func(target string) error { return x.writeFunctionFile(target, root) }}, + {kind: "completion", path: filepath.Join(x.out, `_`+x.name), write: func(target string) error { return x.writeCompletionFile(target, root) }}, {kind: "autoload helper", path: filepath.Join(x.out, `_`+x.name+`_autoload`), write: x.writeAutoloadFile}, } } @@ -67,7 +69,7 @@ func (x *zshCommandOptions) writeAutoloadFile(target string) error { return os.WriteFile(target, []byte(content), 0o644) } -func (x *zshCommandOptions) writeCompletionFile(target string) error { +func (x *zshCommandOptions) writeCompletionFile(target string, root *cobra.Command) error { // Completion delegates to 'timber __complete', so flags, subcommands, // and argument completions never drift from the Cobra definitions. // Only wrapper-only flags are layered on top. @@ -216,7 +218,7 @@ _%[1]s() # The shell wrapper adds 'create --no-cd', which timber itself does not # define, so offer it alongside Cobra's completions when completing flags. case "${words[2]}" in - create|c) + %[10]s) if [[ ${lastParam} == -* ]] && (( ${completions[(I)--no-cd:*]:-0} == 0 )); then completions+=('--no-cd:Create without changing directories') fi @@ -228,12 +230,7 @@ _%[1]s() # 'timber __complete', so offer it alongside Cobra's completions when # completing the subcommand name. if (( CURRENT == 2 )); then - if [[ switch == "${lastParam}"* ]] && (( ${completions[(I)switch:*]:-0} == 0 )); then - completions+=('switch:Resolve a managed worktree path') - fi - if [[ sw == "${lastParam}"* ]] && (( ${completions[(I)sw:*]:-0} == 0 )); then - completions+=('sw:Resolve a managed worktree path') - fi +%[11]s fi # Add a delimiter after the activeHelp statements, but only if: @@ -361,18 +358,18 @@ fi `, x.name, cobra.ShellCompRequestCmd, cobra.ShellCompDirectiveError, cobra.ShellCompDirectiveNoSpace, cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveFilterFileExt, cobra.ShellCompDirectiveFilterDirs, cobra.ShellCompDirectiveKeepOrder, - "_activeHelp_ ") + "_activeHelp_ ", commandCasePattern(root, "create"), switchCompletionChecks(root)) return os.WriteFile(target, []byte(content), 0o644) } -func (x *zshCommandOptions) writeFunctionFile(target string) error { +func (x *zshCommandOptions) writeFunctionFile(target string, root *cobra.Command) error { content := `# Generated by timber generate zsh # DO NOT EDIT. Regenerate with timber generate zsh ` + x.name + `() { case "$1" in - create|c) + ` + commandCasePattern(root, "create") + `) shift local no_cd=0 herdr=0 no_herdr=0 skip_next=0 local -a forward=() @@ -438,7 +435,7 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { fi cd "$target_dir" ;; - switch|sw) + ` + commandCasePattern(root, "switch") + `) shift local path_file path_file=$(mktemp) || return $? @@ -461,9 +458,9 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { fi cd "$target_dir" ;; - repo|rp) + ` + commandCasePattern(root, "repo") + `) case "$2" in - rename|mv) + ` + commandCasePattern(root, "repo", "rename") + `) local path_file path_file=$(mktemp) || return $? TIMBER_RENAME_PATH_FILE=$path_file command timber "$@" @@ -484,13 +481,13 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { cd "$target_dir" || return $? fi ;; - init) + ` + commandCasePattern(root, "repo", "init") + `) # init creates only a bare repository, so there is no checkout to # enter and the caller's directory stays where it is. command timber "$@" return $? ;; - import) + ` + commandCasePattern(root, "repo", "import") + `) # Snapshot cwd, then leave it before the source tree may disappear; # import moves the source worktrees to the system trash. local previous_dir=$PWD @@ -515,7 +512,7 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { ;; esac ;; - move|mv) + ` + commandCasePattern(root, "move") + `) local path_file path_file=$(mktemp) || return $? TIMBER_RENAME_PATH_FILE=$path_file command timber "$@" @@ -536,7 +533,7 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error { cd "$target_dir" || return $? fi ;; - remove|rm) + ` + commandCasePattern(root, "remove") + `) local command_status command timber "$@" command_status=$? @@ -591,3 +588,55 @@ func ensureGeneratedFilesDoNotExist(generatedFiles []generatedZshFile) error { return nil } + +func findDirectSubcommand(parent *cobra.Command, name string) *cobra.Command { + if parent == nil { + return nil + } + for _, candidate := range parent.Commands() { + if candidate.Name() == name { + return candidate + } + } + return nil +} + +func findSubcommand(root *cobra.Command, name string, subcommands ...string) *cobra.Command { + current := findDirectSubcommand(root, name) + for _, subcommand := range subcommands { + current = findDirectSubcommand(current, subcommand) + } + return current +} + +func commandNames(root *cobra.Command, name string, subcommands ...string) []string { + if subcommand := findSubcommand(root, name, subcommands...); subcommand != nil { + names := make([]string, 0, 1+len(subcommand.Aliases)) + names = append(names, subcommand.Name()) + names = append(names, subcommand.Aliases...) + return names + } + if len(subcommands) > 0 { + return []string{subcommands[len(subcommands)-1]} + } + return []string{name} +} + +func commandCasePattern(root *cobra.Command, name string, subcommands ...string) string { + return strings.Join(commandNames(root, name, subcommands...), "|") +} + +func switchCompletionChecks(root *cobra.Command) string { + var short string + if switchCommand := findSubcommand(root, "switch"); switchCommand != nil { + short = switchCommand.Short + } + description := strings.ReplaceAll(cmp.Or(short, "Resolve a managed worktree path"), "'", "'\\''") + var builder strings.Builder + for _, name := range commandNames(root, "switch") { + fmt.Fprintf(&builder, " if [[ %[1]s == \"${lastParam}\"* ]] && (( ${completions[(I)%[1]s:*]:-0} == 0 )); then\n", name) + fmt.Fprintf(&builder, " completions+=('%s:%s')\n", name, description) + builder.WriteString(" fi\n") + } + return strings.TrimSuffix(builder.String(), "\n") +}