completion.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import shlex
  2. from argparse import Action
  3. from textwrap import dedent
  4. from borgmatic.commands import arguments
  5. def upgrade_message(language: str, upgrade_command: str, completion_file: str):
  6. return f'''
  7. Your {language} completions script is from a different version of borgmatic than is
  8. currently installed. Please upgrade your script so your completions match the
  9. command-line flags in your installed borgmatic! Try this to upgrade:
  10. {upgrade_command}
  11. source {completion_file}
  12. '''
  13. def parser_flags(parser):
  14. '''
  15. Given an argparse.ArgumentParser instance, return its argument flags in a space-separated
  16. string.
  17. '''
  18. return ' '.join(option for action in parser._actions for option in action.option_strings)
  19. def bash_completion():
  20. '''
  21. Return a bash completion script for the borgmatic command. Produce this by introspecting
  22. borgmatic's command-line argument parsers.
  23. '''
  24. top_level_parser, subparsers = arguments.make_parsers()
  25. global_flags = parser_flags(top_level_parser)
  26. actions = ' '.join(subparsers.choices.keys())
  27. # Avert your eyes.
  28. return '\n'.join(
  29. (
  30. 'check_version() {',
  31. ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"',
  32. ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"',
  33. ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];'
  34. f''' then cat << EOF\n{upgrade_message(
  35. 'bash',
  36. 'sudo sh -c "borgmatic --bash-completion > $BASH_SOURCE"',
  37. '$BASH_SOURCE',
  38. )}\nEOF''',
  39. ' fi',
  40. '}',
  41. 'complete_borgmatic() {',
  42. )
  43. + tuple(
  44. ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then
  45. COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}"))
  46. return 0
  47. fi'''
  48. % (action, parser_flags(subparser), actions, global_flags)
  49. for action, subparser in subparsers.choices.items()
  50. )
  51. + (
  52. ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' # noqa: FS003
  53. % (actions, global_flags),
  54. ' (check_version &)',
  55. '}',
  56. '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic',
  57. )
  58. )
  59. file_metavars = (
  60. 'FILENAME',
  61. 'PATH',
  62. )
  63. file_destinations = 'config_paths'
  64. def has_exact_options(action: Action):
  65. return action.metavar in file_metavars or action.dest in file_destinations or action.choices
  66. def exact_options_completion(action: Action):
  67. '''
  68. Given an argparse.Action instance, return a completion invocation
  69. that forces file completion or options completion, if the action
  70. takes such an argument and was the last action on the command line.
  71. Otherwise, return an empty string.
  72. '''
  73. if not has_exact_options(action):
  74. return ''
  75. args = ' '.join(action.option_strings)
  76. if action.metavar in file_metavars or action.dest in file_destinations:
  77. return f'''\ncomplete -c borgmatic -Fr -n "__borgmatic_last_arg {args}"'''
  78. if action.choices:
  79. return f'''\ncomplete -c borgmatic -f -a '{' '.join(map(str, action.choices))}' -n "__borgmatic_last_arg {args}"'''
  80. raise RuntimeError(
  81. f'Unexpected action: {action} passes has_exact_options but has no choices produced'
  82. )
  83. def dedent_strip_as_tuple(string: str):
  84. return (dedent(string).strip("\n"),)
  85. def fish_completion():
  86. '''
  87. Return a fish completion script for the borgmatic command. Produce this by introspecting
  88. borgmatic's command-line argument parsers.
  89. '''
  90. top_level_parser, subparsers = arguments.make_parsers()
  91. all_subparsers = ' '.join(action for action in subparsers.choices.keys())
  92. exact_option_args = tuple(
  93. ' '.join(action.option_strings)
  94. for subparser in subparsers.choices.values()
  95. for action in subparser._actions
  96. if has_exact_options(action)
  97. ) + tuple(
  98. ' '.join(action.option_strings)
  99. for action in top_level_parser._actions
  100. if len(action.option_strings) > 0
  101. if has_exact_options(action)
  102. )
  103. # Avert your eyes.
  104. return '\n'.join(
  105. dedent_strip_as_tuple(
  106. f'''
  107. function __borgmatic_check_version
  108. set this_filename (status current-filename)
  109. set this_script (cat $this_filename 2> /dev/null)
  110. set installed_script (borgmatic --fish-completion 2> /dev/null)
  111. if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ]
  112. echo "{upgrade_message(
  113. 'fish',
  114. 'borgmatic --fish-completion | sudo tee $this_filename',
  115. '$this_filename',
  116. )}"
  117. end
  118. end
  119. __borgmatic_check_version &
  120. function __borgmatic_last_arg --description 'Check if any of the given arguments are the last on the command line'
  121. set -l all_args (commandline -poc)
  122. # premature optimization to avoid iterating all args if there aren't enough
  123. # to have a last arg beyond borgmatic
  124. if [ (count $all_args) -lt 2 ]
  125. return 1
  126. end
  127. for arg in $argv
  128. if [ "$arg" = "$all_args[-1]" ]
  129. return 0
  130. end
  131. end
  132. return 1
  133. end
  134. set --local subparser_condition "not __fish_seen_subcommand_from {all_subparsers}"
  135. set --local exact_option_condition "not __borgmatic_last_arg {' '.join(exact_option_args)}"
  136. '''
  137. )
  138. + ('\n# subparser completions',)
  139. + tuple(
  140. f'''complete -c borgmatic -f -n "$subparser_condition" -n "$exact_option_condition" -a '{action_name}' -d {shlex.quote(subparser.description)}'''
  141. for action_name, subparser in subparsers.choices.items()
  142. )
  143. + ('\n# global flags',)
  144. + tuple(
  145. f'''complete -c borgmatic -f -n "$exact_option_condition" -a '{' '.join(action.option_strings)}' -d {shlex.quote(action.help)}{exact_options_completion(action)}'''
  146. for action in top_level_parser._actions
  147. if len(action.option_strings) > 0
  148. )
  149. + ('\n# subparser flags',)
  150. + tuple(
  151. f'''complete -c borgmatic -f -n "$exact_option_condition" -a '{' '.join(action.option_strings)}' -d {shlex.quote(action.help)} -n "__fish_seen_subcommand_from {action_name}"{exact_options_completion(action)}'''
  152. for action_name, subparser in subparsers.choices.items()
  153. for action in subparser._actions
  154. )
  155. )