|
| 1 | +from struct_module.commands import Command |
| 2 | +import os |
| 3 | + |
| 4 | +SUPPORTED_SHELLS = ["bash", "zsh", "fish"] |
| 5 | + |
| 6 | +class CompletionCommand(Command): |
| 7 | + def __init__(self, parser): |
| 8 | + super().__init__(parser) |
| 9 | + parser.description = "Manage CLI shell completions for struct (argcomplete)" |
| 10 | + sub = parser.add_subparsers(dest="action") |
| 11 | + |
| 12 | + install = sub.add_parser("install", help="Print the commands to enable completion for your shell") |
| 13 | + install.add_argument("shell", nargs="?", choices=SUPPORTED_SHELLS, help="Shell type (auto-detected if omitted)") |
| 14 | + install.set_defaults(func=self._install) |
| 15 | + |
| 16 | + def _detect_shell(self): |
| 17 | + shell = os.environ.get("SHELL", "") |
| 18 | + if shell: |
| 19 | + basename = os.path.basename(shell) |
| 20 | + if basename in SUPPORTED_SHELLS: |
| 21 | + return basename |
| 22 | + # Fallback to zsh if running zsh, else bash |
| 23 | + if os.environ.get("ZSH_NAME") or os.environ.get("ZDOTDIR"): |
| 24 | + return "zsh" |
| 25 | + return "bash" |
| 26 | + |
| 27 | + def _install(self, args): |
| 28 | + shell = args.shell or self._detect_shell() |
| 29 | + print(f"Detected shell: {shell}") |
| 30 | + |
| 31 | + if shell == "bash": |
| 32 | + print("\n# One-time dependency (if not installed):") |
| 33 | + print("python -m pip install argcomplete") |
| 34 | + print("\n# Enable completion for 'struct' in bash (append to ~/.bashrc):") |
| 35 | + print('echo "eval \"$(register-python-argcomplete struct)\"" >> ~/.bashrc') |
| 36 | + print("\n# Apply now:") |
| 37 | + print("source ~/.bashrc") |
| 38 | + |
| 39 | + elif shell == "zsh": |
| 40 | + print("\n# One-time dependency (if not installed):") |
| 41 | + print("python -m pip install argcomplete") |
| 42 | + print("\n# Enable completion for 'struct' in zsh (append to ~/.zshrc):") |
| 43 | + print('echo "eval \"$(register-python-argcomplete --shell zsh struct)\"" >> ~/.zshrc') |
| 44 | + print("\n# Apply now:") |
| 45 | + print("source ~/.zshrc") |
| 46 | + |
| 47 | + elif shell == "fish": |
| 48 | + print("\n# One-time dependency (if not installed):") |
| 49 | + print("python -m pip install argcomplete") |
| 50 | + print("\n# Install fish completion file for 'struct':") |
| 51 | + print('mkdir -p ~/.config/fish/completions') |
| 52 | + print('register-python-argcomplete --shell fish struct > ~/.config/fish/completions/struct.fish') |
| 53 | + print("\n# Apply now:") |
| 54 | + print("fish -c 'source ~/.config/fish/completions/struct.fish'") |
| 55 | + |
| 56 | + else: |
| 57 | + self.logger.error(f"Unsupported shell: {shell}. Supported: {', '.join(SUPPORTED_SHELLS)}") |
| 58 | + return |
| 59 | + |
| 60 | + print("\nTip: If 'register-python-argcomplete' is not found, try:\n python -m argcomplete.shellintegration <shell>") |
0 commit comments