Debian Codegraph @

test/lib/ansible_test/_internal/cli/argparsing/argcompletion.py

raw
1 """Wrapper around argcomplete providing bug fixes and additional features."""
2
3 from __future__ import annotations
4
5 import argparse
6 import enum
7 import os
8 import typing as t
9
10
11 class Substitute:
12 """Substitute for missing class which accepts all arguments."""
13
14 def __init__(self, *args, **kwargs) -> None:
15 pass
16
17
18 try:
19 import argcomplete
20
21 try:
22 # argcomplete 3+
23 # see: https://github.com/kislyuk/argcomplete/commit/bd781cb08512b94966312377186ebc5550f46ae0
24 from argcomplete.finders import (
25 CompletionFinder,
26 default_validator,
27 )
28 except ImportError:
29 # argcomplete <3
30 from argcomplete import (
31 CompletionFinder,
32 default_validator,
33 )
34
35 warn = argcomplete.warn # pylint: disable=invalid-name
36 except ImportError:
37 argcomplete = None
38
39 CompletionFinder = Substitute
40 default_validator = Substitute # pylint: disable=invalid-name
41 warn = Substitute # pylint: disable=invalid-name
42
43
44 class CompType(enum.Enum):
45 """
46 Bash COMP_TYPE argument completion types.
47 For documentation, see: https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html#index-COMP_005fTYPE
48 """
49
50 COMPLETION = '\t'
51 """
52 Standard completion, typically triggered by a single tab.
53 """
54 MENU_COMPLETION = '%'
55 """
56 Menu completion, which cycles through each completion instead of showing a list.
57 For help using this feature, see: https://stackoverflow.com/questions/12044574/getting-complete-and-menu-complete-to-work-together
58 """
59 LIST = '?'
60 """
61 Standard list, typically triggered by a double tab.
62 """
63 LIST_AMBIGUOUS = '!'
64 """
65 Listing with `show-all-if-ambiguous` set.
66 For documentation, see https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html#index-show_002dall_002dif_002dambiguous
67 For additional details, see: https://unix.stackexchange.com/questions/614123/explanation-of-bash-completion-comp-type
68 """
69 LIST_UNMODIFIED = '@'
70 """
71 Listing with `show-all-if-unmodified` set.
72 For documentation, see https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html#index-show_002dall_002dif_002dunmodified
73 For additional details, see: : https://unix.stackexchange.com/questions/614123/explanation-of-bash-completion-comp-type
74 """
75
76 @property
77 def list_mode(self) -> bool:
78 """True if completion is running in list mode, otherwise False."""
79 return self in (CompType.LIST, CompType.LIST_AMBIGUOUS, CompType.LIST_UNMODIFIED)
80
81
82 def register_safe_action(action_type: t.Type[argparse.Action]) -> None:
83 """Register the given action as a safe action for argcomplete to use during completion if it is not already registered."""
84 if argcomplete and action_type not in argcomplete.safe_actions:
85 if isinstance(argcomplete.safe_actions, set):
86 # argcomplete 3+
87 # see: https://github.com/kislyuk/argcomplete/commit/bd781cb08512b94966312377186ebc5550f46ae0
88 argcomplete.safe_actions.add(action_type)
89 else:
90 # argcomplete <3
91 argcomplete.safe_actions += (action_type,)
92
93
94 def get_comp_type() -> t.Optional[CompType]:
95 """Parse the COMP_TYPE environment variable (if present) and return the associated CompType enum value."""
96 value = os.environ.get('COMP_TYPE')
97 comp_type = CompType(chr(int(value))) if value else None
98 return comp_type
99
100
101 class OptionCompletionFinder(CompletionFinder):
102 """
103 Custom completion finder for argcomplete.
104 It provides support for running completion in list mode, which argcomplete natively handles the same as standard completion.
105 """
106
107 enabled = bool(argcomplete)
108
109 def __init__(self, *args, validator=None, **kwargs) -> None:
110 if validator:
111 raise ValueError()
112
113 self.comp_type = get_comp_type()
114 self.list_mode = self.comp_type.list_mode if self.comp_type else False
115 self.disable_completion_mangling = False
116
117 finder = self
118
119 def custom_validator(completion, prefix):
120 """Completion validator used to optionally bypass validation."""
121 if finder.disable_completion_mangling:
122 return True
123
124 return default_validator(completion, prefix)
125
126 super().__init__(
127 *args,
128 validator=custom_validator,
129 **kwargs,
130 )
131
132 def __call__(self, *args, **kwargs):
133 if self.enabled:
134 super().__call__(*args, **kwargs)
135
136 def quote_completions(self, completions, cword_prequote, last_wordbreak_pos):
137 """Intercept default quoting behavior to optionally block mangling of completion entries."""
138 if self.disable_completion_mangling:
139 # Word breaks have already been handled when generating completions, don't mangle them further.
140 # This is needed in many cases when returning completion lists which lack the existing completion prefix.
141 last_wordbreak_pos = None
142
143 return super().quote_completions(completions, cword_prequote, last_wordbreak_pos)