|
| 1 | +/** |
| 2 | + * `testsprite completion [bash|zsh|fish]` — emit a shell completion script. |
| 3 | + * |
| 4 | + * The command names, per-group subcommands, and global flags are NOT hardcoded: |
| 5 | + * `index.ts` builds a {@link CompletionSpec} by walking the fully-assembled |
| 6 | + * Commander program and passes it in, so the generated script can never drift |
| 7 | + * from the real command tree. `renderCompletion` is a pure function of the spec, |
| 8 | + * which keeps it unit-testable without a live program. |
| 9 | + * |
| 10 | + * Usage: |
| 11 | + * bash: eval "$(testsprite completion bash)" (add to ~/.bashrc) |
| 12 | + * zsh: testsprite completion zsh > ~/.zsh/_testsprite (on your fpath) |
| 13 | + * fish: testsprite completion fish | source (add to config.fish) |
| 14 | + */ |
| 15 | + |
| 16 | +import { Command } from 'commander'; |
| 17 | +import { localValidationError } from '../lib/errors.js'; |
| 18 | + |
| 19 | +export const SUPPORTED_SHELLS = ['bash', 'zsh', 'fish'] as const; |
| 20 | +export type Shell = (typeof SUPPORTED_SHELLS)[number]; |
| 21 | + |
| 22 | +export interface CompletionSpec { |
| 23 | + /** Binary name, e.g. "testsprite". */ |
| 24 | + program: string; |
| 25 | + /** Top-level command names. */ |
| 26 | + commands: string[]; |
| 27 | + /** command name -> its subcommand names (only groups that have subcommands). */ |
| 28 | + subcommands: Record<string, string[]>; |
| 29 | + /** Global long option flags (e.g. "--output"). */ |
| 30 | + globalFlags: string[]; |
| 31 | +} |
| 32 | + |
| 33 | +export interface CompletionDeps { |
| 34 | + env?: NodeJS.ProcessEnv; |
| 35 | + stdout?: (line: string) => void; |
| 36 | +} |
| 37 | + |
| 38 | +export function isShell(value: string): value is Shell { |
| 39 | + return (SUPPORTED_SHELLS as readonly string[]).includes(value); |
| 40 | +} |
| 41 | + |
| 42 | +/** Best-effort shell detection from `$SHELL` (e.g. "/bin/zsh" -> "zsh"). */ |
| 43 | +export function detectShell(env: NodeJS.ProcessEnv): Shell | undefined { |
| 44 | + const shellPath = env.SHELL ?? ''; |
| 45 | + const base = shellPath.slice(shellPath.lastIndexOf('/') + 1); |
| 46 | + return isShell(base) ? base : undefined; |
| 47 | +} |
| 48 | + |
| 49 | +export function renderCompletion(shell: Shell, spec: CompletionSpec): string { |
| 50 | + switch (shell) { |
| 51 | + case 'bash': |
| 52 | + return renderBash(spec); |
| 53 | + case 'zsh': |
| 54 | + return renderZsh(spec); |
| 55 | + case 'fish': |
| 56 | + return renderFish(spec); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +function renderBash(spec: CompletionSpec): string { |
| 61 | + const fn = `_${spec.program}_completion`; |
| 62 | + const lines = [ |
| 63 | + `# ${spec.program} bash completion. Enable with: eval "$(${spec.program} completion bash)"`, |
| 64 | + `${fn}() {`, |
| 65 | + ' local cur prev', |
| 66 | + ' cur="${COMP_WORDS[COMP_CWORD]}"', |
| 67 | + ' prev="${COMP_WORDS[COMP_CWORD-1]}"', |
| 68 | + ` local commands="${spec.commands.join(' ')}"`, |
| 69 | + ` local global_flags="${spec.globalFlags.join(' ')}"`, |
| 70 | + ' case "$prev" in', |
| 71 | + ...Object.entries(spec.subcommands).map( |
| 72 | + ([group, subs]) => |
| 73 | + ` ${group}) COMPREPLY=( $(compgen -W "${subs.join(' ')}" -- "$cur") ); return;;`, |
| 74 | + ), |
| 75 | + ' esac', |
| 76 | + ' if [[ "$cur" == -* ]]; then', |
| 77 | + ' COMPREPLY=( $(compgen -W "$global_flags" -- "$cur") ); return', |
| 78 | + ' fi', |
| 79 | + ' COMPREPLY=( $(compgen -W "$commands" -- "$cur") )', |
| 80 | + '}', |
| 81 | + `complete -F ${fn} ${spec.program}`, |
| 82 | + ]; |
| 83 | + return lines.join('\n'); |
| 84 | +} |
| 85 | + |
| 86 | +function renderZsh(spec: CompletionSpec): string { |
| 87 | + const fn = `_${spec.program}`; |
| 88 | + const lines = [ |
| 89 | + `#compdef ${spec.program}`, |
| 90 | + `# ${spec.program} zsh completion. Enable with: ${spec.program} completion zsh > "$fpath[1]/_${spec.program}"`, |
| 91 | + `${fn}() {`, |
| 92 | + ' local -a commands', |
| 93 | + ` commands=(${spec.commands.join(' ')})`, |
| 94 | + ' if (( CURRENT == 2 )); then', |
| 95 | + " _describe 'command' commands", |
| 96 | + ' return', |
| 97 | + ' fi', |
| 98 | + ' case "${words[2]}" in', |
| 99 | + ...Object.entries(spec.subcommands).map( |
| 100 | + ([group, subs]) => |
| 101 | + ` ${group}) local -a subs; subs=(${subs.join(' ')}); _describe 'subcommand' subs;;`, |
| 102 | + ), |
| 103 | + ' esac', |
| 104 | + '}', |
| 105 | + `compdef ${fn} ${spec.program}`, |
| 106 | + ]; |
| 107 | + return lines.join('\n'); |
| 108 | +} |
| 109 | + |
| 110 | +function renderFish(spec: CompletionSpec): string { |
| 111 | + const lines = [ |
| 112 | + `# ${spec.program} fish completion. Enable with: ${spec.program} completion fish | source`, |
| 113 | + `complete -c ${spec.program} -f`, |
| 114 | + ...spec.commands.map( |
| 115 | + command => `complete -c ${spec.program} -n '__fish_use_subcommand' -a '${command}'`, |
| 116 | + ), |
| 117 | + ...Object.entries(spec.subcommands).flatMap(([group, subs]) => |
| 118 | + subs.map( |
| 119 | + sub => `complete -c ${spec.program} -n '__fish_seen_subcommand_from ${group}' -a '${sub}'`, |
| 120 | + ), |
| 121 | + ), |
| 122 | + ...spec.globalFlags.map(flag => `complete -c ${spec.program} -l ${flag.replace(/^--/, '')}`), |
| 123 | + ]; |
| 124 | + return lines.join('\n'); |
| 125 | +} |
| 126 | + |
| 127 | +export function createCompletionCommand( |
| 128 | + getSpec: () => CompletionSpec, |
| 129 | + deps: CompletionDeps = {}, |
| 130 | +): Command { |
| 131 | + return new Command('completion') |
| 132 | + .description('Print a shell completion script (bash|zsh|fish)') |
| 133 | + .argument( |
| 134 | + '[shell]', |
| 135 | + 'Shell to generate for (bash|zsh|fish); auto-detected from $SHELL when omitted', |
| 136 | + ) |
| 137 | + .addHelpText( |
| 138 | + 'after', |
| 139 | + '\nExamples:\n' + |
| 140 | + ' eval "$(testsprite completion bash)" # bash, current session\n' + |
| 141 | + ' testsprite completion zsh > ~/.zsh/_testsprite\n' + |
| 142 | + ' testsprite completion fish | source # fish, current session', |
| 143 | + ) |
| 144 | + .action((shellArg: string | undefined, _cmdOpts: unknown) => { |
| 145 | + const env = deps.env ?? process.env; |
| 146 | + const shell = shellArg ?? detectShell(env); |
| 147 | + if (shell === undefined) { |
| 148 | + throw localValidationError( |
| 149 | + 'shell', |
| 150 | + `could not detect the shell from $SHELL; pass one explicitly (${SUPPORTED_SHELLS.join(', ')})`, |
| 151 | + [...SUPPORTED_SHELLS], |
| 152 | + ); |
| 153 | + } |
| 154 | + if (!isShell(shell)) { |
| 155 | + throw localValidationError( |
| 156 | + 'shell', |
| 157 | + `unsupported shell "${shell}"; use one of: ${SUPPORTED_SHELLS.join(', ')}`, |
| 158 | + [...SUPPORTED_SHELLS], |
| 159 | + ); |
| 160 | + } |
| 161 | + const write = deps.stdout ?? ((line: string) => process.stdout.write(`${line}\n`)); |
| 162 | + write(renderCompletion(shell, getSpec())); |
| 163 | + }); |
| 164 | +} |
0 commit comments