completion.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """Shell completion script generation for hermes CLI. Walks the live argparse parser tree, so
  2. completion scripts never go stale; no extra dependencies."""
  3. from __future__ import annotations
  4. import argparse
  5. from typing import Any
  6. def _walk(parser: argparse.ArgumentParser) -> dict[str, Any]:
  7. """Recursively extract subcommands and flags from a parser."""
  8. flags: list[str] = []
  9. subcommands: dict[str, Any] = {}
  10. for action in parser._actions:
  11. if isinstance(action, argparse._SubParsersAction):
  12. # _choices_actions has one entry per canonical name (aliases omitted).
  13. for pseudo in action._choices_actions:
  14. name = pseudo.dest
  15. subparser = action.choices.get(name)
  16. if name in subcommands or subparser is None:
  17. continue
  18. subcommands[name] = {**_walk(subparser), "help": _clean(pseudo.help or "")}
  19. elif action.option_strings:
  20. flags.extend(o for o in action.option_strings if o.startswith("-"))
  21. return {"flags": flags, "subcommands": subcommands}
  22. def _clean(text: str, maxlen: int = 60) -> str:
  23. """Strip shell-unsafe characters and truncate."""
  24. return text.replace("'", "").replace('"', "").replace("\\", "")[:maxlen]
  25. # Profile actions that take a profile name as their next argument.
  26. _PROFILE_NAME_ACTIONS = ("use", "delete", "show", "alias", "rename", "export")
  27. def _sorted_subcommands(parser: argparse.ArgumentParser) -> list[tuple[str, dict[str, Any]]]:
  28. return sorted(_walk(parser)["subcommands"].items())
  29. def generate_bash(parser: argparse.ArgumentParser) -> str:
  30. subcommands = _sorted_subcommands(parser)
  31. top_cmds = " ".join(cmd for cmd, _ in subcommands)
  32. cases: list[str] = []
  33. for cmd, info in subcommands:
  34. if cmd == "profile" and info["subcommands"]:
  35. # Complete actions, then profile names for actions that accept a profile argument.
  36. subcmds = " ".join(sorted(info["subcommands"]))
  37. cases.append(
  38. f" profile)\n"
  39. f" case \"$prev\" in\n"
  40. f" profile)\n"
  41. f" COMPREPLY=($(compgen -W \"{subcmds}\" -- \"$cur\"))\n"
  42. f" return\n"
  43. f" ;;\n"
  44. f" {'|'.join(_PROFILE_NAME_ACTIONS)})\n"
  45. f" COMPREPLY=($(compgen -W \"$(_hermes_profiles)\" -- \"$cur\"))\n"
  46. f" return\n"
  47. f" ;;\n"
  48. f" esac\n"
  49. f" ;;")
  50. elif info["subcommands"] or info["flags"]:
  51. words = " ".join(sorted(info["subcommands"]) if info["subcommands"] else info["flags"])
  52. cases.append(
  53. f" {cmd})\n"
  54. f" COMPREPLY=($(compgen -W \"{words}\" -- \"$cur\"))\n"
  55. f" return\n"
  56. f" ;;")
  57. cases_str = "\n".join(cases)
  58. return f"""# Hermes Agent bash completion
  59. # Add to ~/.bashrc:
  60. # eval "$(hermes completion bash)"
  61. _hermes_profiles() {{
  62. local profiles_dir="$HOME/.hermes/profiles"
  63. local profiles="default"
  64. if [ -d "$profiles_dir" ]; then
  65. for f in "$profiles_dir"/*/; do
  66. [ -d "$f" ] && profiles="$profiles $(basename "$f")"
  67. done
  68. fi
  69. echo "$profiles"
  70. }}
  71. _hermes_completion() {{
  72. local cur prev
  73. COMPREPLY=()
  74. cur="${{COMP_WORDS[COMP_CWORD]}}"
  75. prev="${{COMP_WORDS[COMP_CWORD-1]}}"
  76. # Complete profile names after -p / --profile
  77. if [[ "$prev" == "-p" || "$prev" == "--profile" ]]; then
  78. COMPREPLY=($(compgen -W "$(_hermes_profiles)" -- "$cur"))
  79. return
  80. fi
  81. if [[ $COMP_CWORD -ge 2 ]]; then
  82. case "${{COMP_WORDS[1]}}" in
  83. {cases_str}
  84. esac
  85. fi
  86. if [[ $COMP_CWORD -eq 1 ]]; then
  87. COMPREPLY=($(compgen -W "{top_cmds}" -- "$cur"))
  88. fi
  89. }}
  90. complete -F _hermes_completion hermes
  91. """
  92. def _zsh_describe_lines(subcommands: dict[str, Any], indent: str) -> str:
  93. """One ``'name:help'`` line per subcommand, sorted, at the given indent."""
  94. return "\n".join(
  95. f"{indent}'{sc}:{_clean(subcommands[sc].get('help', ''))}'" for sc in sorted(subcommands))
  96. def generate_zsh(parser: argparse.ArgumentParser) -> str:
  97. subcommands = _sorted_subcommands(parser)
  98. top_cmds_str = _zsh_describe_lines(dict(subcommands), " " * 16)
  99. sub_cases: list[str] = []
  100. for cmd, info in subcommands:
  101. if not info["subcommands"]:
  102. continue
  103. if cmd == "profile":
  104. # Complete actions, then profile names for actions that accept a profile argument.
  105. sub_str = _zsh_describe_lines(info["subcommands"], " " * 24)
  106. sub_cases.append(
  107. f" profile)\n"
  108. f" case ${{line[2]}} in\n"
  109. f" {'|'.join(_PROFILE_NAME_ACTIONS)})\n"
  110. f" _hermes_profiles\n"
  111. f" ;;\n"
  112. f" *)\n"
  113. f" local -a profile_cmds\n"
  114. f" profile_cmds=(\n"
  115. f"{sub_str}\n"
  116. f" )\n"
  117. f" _describe 'profile command' profile_cmds\n"
  118. f" ;;\n"
  119. f" esac\n"
  120. f" ;;")
  121. else:
  122. sub_str = _zsh_describe_lines(info["subcommands"], " " * 20)
  123. safe = cmd.replace("-", "_")
  124. sub_cases.append(
  125. f" {cmd})\n"
  126. f" local -a {safe}_cmds\n"
  127. f" {safe}_cmds=(\n"
  128. f"{sub_str}\n"
  129. f" )\n"
  130. f" _describe '{cmd} command' {safe}_cmds\n"
  131. f" ;;")
  132. sub_cases_str = "\n".join(sub_cases)
  133. return f"""#compdef hermes
  134. # Hermes Agent zsh completion
  135. # Add to ~/.zshrc:
  136. # eval "$(hermes completion zsh)"
  137. _hermes_profiles() {{
  138. local -a profiles
  139. profiles=(default)
  140. if [[ -d "$HOME/.hermes/profiles" ]]; then
  141. profiles+=($HOME/.hermes/profiles/*(N/:t))
  142. fi
  143. _describe 'profile' profiles
  144. }}
  145. _hermes() {{
  146. local context state line
  147. typeset -A opt_args
  148. _arguments -C \\
  149. '(-)'{{-h,--help}}'[Show help and exit]' \\
  150. '(-)'{{-V,--version}}'[Show version and exit]' \\
  151. '(-)'{{-p,--profile}}'[Profile name]:profile:_hermes_profiles' \\
  152. '1:command:->commands' \\
  153. '*::arg:->args'
  154. case $state in
  155. commands)
  156. local -a subcmds
  157. subcmds=(
  158. {top_cmds_str}
  159. )
  160. _describe 'hermes command' subcmds
  161. ;;
  162. args)
  163. case ${{line[1]}} in
  164. {sub_cases_str}
  165. esac
  166. ;;
  167. esac
  168. }}
  169. compdef _hermes hermes
  170. """
  171. def generate_fish(parser: argparse.ArgumentParser) -> str:
  172. subcommands = _sorted_subcommands(parser)
  173. top_cmds_str = " ".join(cmd for cmd, _ in subcommands)
  174. lines: list[str] = [
  175. "# Hermes Agent fish completion",
  176. "# Add to your config:",
  177. "# hermes completion fish | source",
  178. "",
  179. "# Helper: list available profiles",
  180. "function __hermes_profiles",
  181. " echo default",
  182. " if test -d $HOME/.hermes/profiles",
  183. " for d in $HOME/.hermes/profiles/*/",
  184. " basename $d",
  185. " end",
  186. " end",
  187. "end",
  188. "",
  189. "# Disable file completion by default",
  190. "complete -c hermes -f",
  191. "",
  192. "# Complete profile names after -p / --profile",
  193. "complete -c hermes -f -s p -l profile"
  194. " -d 'Profile name' -xa '(__hermes_profiles)'",
  195. "",
  196. "# Top-level subcommands"]
  197. for cmd, info in subcommands:
  198. lines.append(
  199. f"complete -c hermes -f "
  200. f"-n 'not __fish_seen_subcommand_from {top_cmds_str}' "
  201. f"-a {cmd} -d '{_clean(info.get('help', ''))}'")
  202. lines += ["", "# Subcommand completions"]
  203. for cmd, info in subcommands:
  204. if not info["subcommands"]:
  205. continue
  206. lines.append(f"# {cmd}")
  207. for sc, sinfo in sorted(info["subcommands"].items()):
  208. lines.append(
  209. f"complete -c hermes -f "
  210. f"-n '__fish_seen_subcommand_from {cmd}' "
  211. f"-a {sc} -d '{_clean(sinfo.get('help', ''))}'")
  212. if cmd == "profile": # profile names for the actions that take one
  213. for action in sorted(_PROFILE_NAME_ACTIONS):
  214. lines.append(
  215. f"complete -c hermes -f "
  216. f"-n '__fish_seen_subcommand_from {action}; "
  217. f"and __fish_seen_subcommand_from profile' "
  218. f"-a '(__hermes_profiles)' -d 'Profile name'")
  219. lines.append("")
  220. return "\n".join(lines)