filesystem.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. from __future__ import unicode_literals
  2. from prompt_toolkit.completion import Completer, Completion
  3. import os
  4. __all__ = (
  5. 'PathCompleter',
  6. 'ExecutableCompleter',
  7. )
  8. class PathCompleter(Completer):
  9. """
  10. Complete for Path variables.
  11. :param get_paths: Callable which returns a list of directories to look into
  12. when the user enters a relative path.
  13. :param file_filter: Callable which takes a filename and returns whether
  14. this file should show up in the completion. ``None``
  15. when no filtering has to be done.
  16. :param min_input_len: Don't do autocompletion when the input string is shorter.
  17. """
  18. def __init__(self, only_directories=False, get_paths=None, file_filter=None,
  19. min_input_len=0, expanduser=False):
  20. assert get_paths is None or callable(get_paths)
  21. assert file_filter is None or callable(file_filter)
  22. assert isinstance(min_input_len, int)
  23. assert isinstance(expanduser, bool)
  24. self.only_directories = only_directories
  25. self.get_paths = get_paths or (lambda: ['.'])
  26. self.file_filter = file_filter or (lambda _: True)
  27. self.min_input_len = min_input_len
  28. self.expanduser = expanduser
  29. def get_completions(self, document, complete_event):
  30. text = document.text_before_cursor
  31. # Complete only when we have at least the minimal input length,
  32. # otherwise, we can too many results and autocompletion will become too
  33. # heavy.
  34. if len(text) < self.min_input_len:
  35. return
  36. try:
  37. # Do tilde expansion.
  38. if self.expanduser:
  39. text = os.path.expanduser(text)
  40. # Directories where to look.
  41. dirname = os.path.dirname(text)
  42. if dirname:
  43. directories = [os.path.dirname(os.path.join(p, text))
  44. for p in self.get_paths()]
  45. else:
  46. directories = self.get_paths()
  47. # Start of current file.
  48. prefix = os.path.basename(text)
  49. # Get all filenames.
  50. filenames = []
  51. for directory in directories:
  52. # Look for matches in this directory.
  53. if os.path.isdir(directory):
  54. for filename in os.listdir(directory):
  55. if filename.startswith(prefix):
  56. filenames.append((directory, filename))
  57. # Sort
  58. filenames = sorted(filenames, key=lambda k: k[1])
  59. # Yield them.
  60. for directory, filename in filenames:
  61. completion = filename[len(prefix):]
  62. full_name = os.path.join(directory, filename)
  63. if os.path.isdir(full_name):
  64. # For directories, add a slash to the filename.
  65. # (We don't add them to the `completion`. Users can type it
  66. # to trigger the autocompletion themself.)
  67. filename += '/'
  68. elif self.only_directories:
  69. continue
  70. if not self.file_filter(full_name):
  71. continue
  72. yield Completion(completion, 0, display=filename)
  73. except OSError:
  74. pass
  75. class ExecutableCompleter(PathCompleter):
  76. """
  77. Complete only excutable files in the current path.
  78. """
  79. def __init__(self):
  80. PathCompleter.__init__(
  81. self,
  82. only_directories=False,
  83. min_input_len=1,
  84. get_paths=lambda: os.environ.get('PATH', '').split(os.pathsep),
  85. file_filter=lambda name: os.access(name, os.X_OK),
  86. expanduser=True),