molecule-cli/internal/cmd/completion.go
Molecule AI SDK-Dev 1471cad4c1 feat(cli): add molecule completion [bash|zsh|fish|powershell] subcommand
Wires shell completion for all 4 shells via Cobra's built-in generators.
Covers the remaining item from the implementation status checklist.

Adds:
- internal/cmd/completion.go: cobra.GenXxxCompletion wrappers with
  usage examples for each shell
- 5 new integration tests in cmd/molecule/molecule_test.go:
  - TestCLI_Completion_Help (4 shells × help flag)
  - TestCLI_Completion_GeneratesScript (4 shells × script output)
  - TestCLI_Completion_InvalidShell (exit code 2 on bad shell)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 18:06:02 +00:00

61 lines
1.6 KiB
Go

package cmd
import (
"os"
"github.com/spf13/cobra"
)
// completionCmd represents the shell completion subcommand.
// Cobra v1.10+ generates completions for bash, zsh, fish, and PowerShell.
var completionCmd = &cobra.Command{
Use: "completion [bash|zsh|fish|powershell]",
Short: "Generate shell completion scripts",
Long: `Generate shell completion scripts for molecule.
Cobra automatically generates completions for:
Bash — completions for bash (~/.bashrc or ~/.bash_completion)
Zsh — completions for zsh (usually ~/.zshrc)
Fish — completions for fish (~/.config/fish/completions)
PowerShell — completions for PowerShell (profile)
Examples:
# Bash (add to ~/.bashrc or ~/.bash_completion)
source <(molecule completion bash)
# Zsh (add to ~/.zshrc)
autoload -U compinit && compinit
autoload -Uz bashcompinit && bashcompinit
source <(molecule completion zsh)
compdef _molecule molecule
# Fish
molecule completion fish | source
# PowerShell (add to $PROFILE)
molecule completion powershell | Out-String | Invoke-Expression
`,
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.ExactValidArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
switch args[0] {
case "bash":
return rootCmd.GenBashCompletion(os.Stdout)
case "zsh":
return rootCmd.GenZshCompletion(os.Stdout)
case "fish":
return rootCmd.GenFishCompletion(os.Stdout, true)
case "powershell":
return rootCmd.GenPowerShellCompletionWithDesc(os.Stdout)
}
return nil // unreachable
},
}
func init() {
rootCmd.AddCommand(completionCmd)
}