You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
3.7KB

  1. """Allow bash-completion for argparse with argcomplete if installed.
  2. Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
  3. to find the magic string, so _ARGCOMPLETE env. var is never set, and
  4. this does not need special code).
  5. Function try_argcomplete(parser) should be called directly before
  6. the call to ArgumentParser.parse_args().
  7. The filescompleter is what you normally would use on the positional
  8. arguments specification, in order to get "dirname/" after "dirn<TAB>"
  9. instead of the default "dirname ":
  10. optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter
  11. Other, application specific, completers should go in the file
  12. doing the add_argument calls as they need to be specified as .completer
  13. attributes as well. (If argcomplete is not installed, the function the
  14. attribute points to will not be used).
  15. SPEEDUP
  16. =======
  17. The generic argcomplete script for bash-completion
  18. (/etc/bash_completion.d/python-argcomplete.sh)
  19. uses a python program to determine startup script generated by pip.
  20. You can speed up completion somewhat by changing this script to include
  21. # PYTHON_ARGCOMPLETE_OK
  22. so the python-argcomplete-check-easy-install-script does not
  23. need to be called to find the entry point of the code and see if that is
  24. marked with PYTHON_ARGCOMPLETE_OK.
  25. INSTALL/DEBUGGING
  26. =================
  27. To include this support in another application that has setup.py generated
  28. scripts:
  29. - Add the line:
  30. # PYTHON_ARGCOMPLETE_OK
  31. near the top of the main python entry point.
  32. - Include in the file calling parse_args():
  33. from _argcomplete import try_argcomplete, filescompleter
  34. Call try_argcomplete just before parse_args(), and optionally add
  35. filescompleter to the positional arguments' add_argument().
  36. If things do not work right away:
  37. - Switch on argcomplete debugging with (also helpful when doing custom
  38. completers):
  39. export _ARC_DEBUG=1
  40. - Run:
  41. python-argcomplete-check-easy-install-script $(which appname)
  42. echo $?
  43. will echo 0 if the magic line has been found, 1 if not.
  44. - Sometimes it helps to find early on errors using:
  45. _ARGCOMPLETE=1 _ARC_DEBUG=1 appname
  46. which should throw a KeyError: 'COMPLINE' (which is properly set by the
  47. global argcomplete script).
  48. """
  49. import argparse
  50. import os
  51. import sys
  52. from glob import glob
  53. from typing import Any
  54. from typing import List
  55. from typing import Optional
  56. class FastFilesCompleter:
  57. """Fast file completer class."""
  58. def __init__(self, directories: bool = True) -> None:
  59. self.directories = directories
  60. def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
  61. # Only called on non option completions.
  62. if os.path.sep in prefix[1:]:
  63. prefix_dir = len(os.path.dirname(prefix) + os.path.sep)
  64. else:
  65. prefix_dir = 0
  66. completion = []
  67. globbed = []
  68. if "*" not in prefix and "?" not in prefix:
  69. # We are on unix, otherwise no bash.
  70. if not prefix or prefix[-1] == os.path.sep:
  71. globbed.extend(glob(prefix + ".*"))
  72. prefix += "*"
  73. globbed.extend(glob(prefix))
  74. for x in sorted(globbed):
  75. if os.path.isdir(x):
  76. x += "/"
  77. # Append stripping the prefix (like bash, not like compgen).
  78. completion.append(x[prefix_dir:])
  79. return completion
  80. if os.environ.get("_ARGCOMPLETE"):
  81. try:
  82. import argcomplete.completers
  83. except ImportError:
  84. sys.exit(-1)
  85. filescompleter: Optional[FastFilesCompleter] = FastFilesCompleter()
  86. def try_argcomplete(parser: argparse.ArgumentParser) -> None:
  87. argcomplete.autocomplete(parser, always_complete_options=False)
  88. else:
  89. def try_argcomplete(parser: argparse.ArgumentParser) -> None:
  90. pass
  91. filescompleter = None