completion.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from borgmatic.commands import arguments
  2. UPGRADE_MESSAGE = '''
  3. Your bash completions script is from a different version of borgmatic than is
  4. currently installed. Please upgrade your script so your completions match the
  5. command-line flags in your installed borgmatic! Try this to upgrade:
  6. sudo sh -c "borgmatic --bash-completion > $BASH_SOURCE"
  7. source $BASH_SOURCE
  8. '''
  9. def parser_flags(parser):
  10. '''
  11. Given an argparse.ArgumentParser instance, return its argument flags in a space-separated
  12. string.
  13. '''
  14. return ' '.join(option for action in parser._actions for option in action.option_strings)
  15. def bash_completion():
  16. '''
  17. Return a bash completion script for the borgmatic command. Produce this by introspecting
  18. borgmatic's command-line argument parsers.
  19. '''
  20. top_level_parser, subparsers = arguments.make_parsers()
  21. global_flags = parser_flags(top_level_parser)
  22. actions = ' '.join(subparsers.choices.keys())
  23. # Avert your eyes.
  24. return '\n'.join(
  25. (
  26. 'check_version() {',
  27. ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"',
  28. ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"',
  29. ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];'
  30. f' then cat << EOF\n{UPGRADE_MESSAGE}\nEOF',
  31. ' fi',
  32. '}',
  33. 'complete_borgmatic() {',
  34. )
  35. + tuple(
  36. ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then
  37. COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}"))
  38. return 0
  39. fi'''
  40. % (action, parser_flags(subparser), actions, global_flags)
  41. for action, subparser in subparsers.choices.items()
  42. )
  43. + (
  44. ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))' # noqa: FS003
  45. % (actions, global_flags),
  46. ' (check_version &)',
  47. '}',
  48. '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic',
  49. )
  50. )