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
99 changes: 75 additions & 24 deletions internal/cli/generate/zsh/zsh.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package zsh

import (
"cmp"
"fmt"
"io"
"os"
"path/filepath"
"strings"

"github.com/spf13/cobra"
)
Expand All @@ -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
Expand All @@ -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},
}
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -215,23 +217,20 @@ _%[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
%[10]s)
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
# '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:
Expand Down Expand Up @@ -359,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)
` + commandCasePattern(root, "create") + `)
shift
local no_cd=0 herdr=0 no_herdr=0 skip_next=0
local -a forward=()
Expand Down Expand Up @@ -436,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 $?
Expand All @@ -459,9 +458,9 @@ func (x *zshCommandOptions) writeFunctionFile(target string) error {
fi
cd "$target_dir"
;;
repo)
` + 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 "$@"
Expand All @@ -482,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
Expand All @@ -513,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 "$@"
Expand All @@ -534,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=$?
Expand Down Expand Up @@ -589,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")
}
Loading
Loading