completion.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. 'set -uo pipefail',
  27. 'check_version() {',
  28. ' local this_script="$(cat "$BASH_SOURCE" 2> /dev/null)"',
  29. ' local installed_script="$(borgmatic --bash-completion 2> /dev/null)"',
  30. ' if [ "$this_script" != "$installed_script" ] && [ "$installed_script" != "" ];'
  31. ' then cat << EOF\n%s\nEOF' % UPGRADE_MESSAGE,
  32. ' fi',
  33. '}',
  34. 'complete_borgmatic() {',
  35. )
  36. + tuple(
  37. ''' if [[ " ${COMP_WORDS[*]} " =~ " %s " ]]; then
  38. COMPREPLY=($(compgen -W "%s %s %s" -- "${COMP_WORDS[COMP_CWORD]}"))
  39. return 0
  40. fi'''
  41. % (action, parser_flags(subparser), actions, global_flags)
  42. for action, subparser in subparsers.choices.items()
  43. )
  44. + (
  45. ' COMPREPLY=($(compgen -W "%s %s" -- "${COMP_WORDS[COMP_CWORD]}"))'
  46. % (actions, global_flags),
  47. ' (check_version &)',
  48. '}',
  49. '\ncomplete -o bashdefault -o default -F complete_borgmatic borgmatic',
  50. )
  51. )