Debian Codegraph @

invoke/parser/parser.py

raw ◀ ▶
1 Debian patch touch this file
1 import copy
2 from typing import TYPE_CHECKING, Any, Iterable, List, Optional
3
4 try:
5 from ..vendor.lexicon import Lexicon
6 except ImportError:
7 from lexicon import Lexicon # type: ignore[no-redef]
•8 try:
9 from ..vendor.fluidity import StateMachine, state, transition
10 except ImportError:
11 from fluidity import ( # type: ignore[no-redef]
12 StateMachine,
13 state,
14 transition,
15 )
16
17 from ..exceptions import ParseError
18 from ..util import debug
19
20 if TYPE_CHECKING:
21 from .context import ParserContext
22
23
24 def is_flag(value: str) -> bool:
25 return value.startswith("-")
26
27
28 def is_long_flag(value: str) -> bool:
29 return value.startswith("--")
30
31
32 class ParseResult(List["ParserContext"]):
33 """
34 List-like object with some extra parse-related attributes.
35
36 Specifically, a ``.remainder`` attribute, which is the string found after a
37 ``--`` in any parsed argv list; and an ``.unparsed`` attribute, a list of
38 tokens that were unable to be parsed.
39
40 .. versionadded:: 1.0
41 """
42
43 def __init__(self, *args: Any, **kwargs: Any) -> None:
44 super().__init__(*args, **kwargs)
45 self.remainder = ""
46 self.unparsed: List[str] = []
47
48
49 class Parser:
50 """
51 Create parser conscious of ``contexts`` and optional ``initial`` context.
52
53 ``contexts`` should be an iterable of ``Context`` instances which will be
54 searched when new context names are encountered during a parse. These
55 Contexts determine what flags may follow them, as well as whether given
56 flags take values.
57
58 ``initial`` is optional and will be used to determine validity of "core"
59 options/flags at the start of the parse run, if any are encountered.
60
61 ``ignore_unknown`` determines what to do when contexts are found which do
62 not map to any members of ``contexts``. By default it is ``False``, meaning
63 any unknown contexts result in a parse error exception. If ``True``,
64 encountering an unknown context halts parsing and populates the return
65 value's ``.unparsed`` attribute with the remaining parse tokens.
66
67 .. versionadded:: 1.0
68 """
69
70 def __init__(
71 self,
72 contexts: Iterable["ParserContext"] = (),
73 initial: Optional["ParserContext"] = None,
74 ignore_unknown: bool = False,
75 ) -> None:
76 self.initial = initial
77 self.contexts = Lexicon()
78 self.ignore_unknown = ignore_unknown
79 for context in contexts:
80 debug("Adding {}".format(context))
81 if not context.name:
82 raise ValueError("Non-initial contexts must have names.")
83 exists = "A context named/aliased {!r} is already in this parser!"
84 if context.name in self.contexts:
85 raise ValueError(exists.format(context.name))
86 self.contexts[context.name] = context
87 for alias in context.aliases:
88 if alias in self.contexts:
89 raise ValueError(exists.format(alias))
90 self.contexts.alias(alias, to=context.name)
91
92 def parse_argv(self, argv: List[str]) -> ParseResult:
93 """
94 Parse an argv-style token list ``argv``.
95
96 Returns a list (actually a subclass, `.ParseResult`) of
97 `.ParserContext` objects matching the order they were found in the
98 ``argv`` and containing `.Argument` objects with updated values based
99 on any flags given.
100
101 Assumes any program name has already been stripped out. Good::
102
103 Parser(...).parse_argv(['--core-opt', 'task', '--task-opt'])
104
105 Bad::
106
107 Parser(...).parse_argv(['invoke', '--core-opt', ...])
108
109 :param argv: List of argument string tokens.
110 :returns:
111 A `.ParseResult` (a ``list`` subclass containing some number of
112 `.ParserContext` objects).
113
114 .. versionadded:: 1.0
115 """
116 machine = ParseMachine(
117 # FIXME: initial should not be none
118 initial=self.initial, # type: ignore[arg-type]
119 contexts=self.contexts,
120 ignore_unknown=self.ignore_unknown,
121 )
122 # FIXME: Why isn't there str.partition for lists? There must be a
123 # better way to do this. Split argv around the double-dash remainder
124 # sentinel.
125 debug("Starting argv: {!r}".format(argv))
126 try:
127 ddash = argv.index("--")
128 except ValueError:
129 ddash = len(argv) # No remainder == body gets all
130 body = argv[:ddash]
131 remainder = argv[ddash:][1:] # [1:] to strip off remainder itself
132 if remainder:
133 debug(
134 "Remainder: argv[{!r}:][1:] => {!r}".format(ddash, remainder)
135 )
136 for index, token in enumerate(body):
137 # Handle non-space-delimited forms, if not currently expecting a
138 # flag value and still in valid parsing territory (i.e. not in
139 # "unknown" state which implies store-only)
140 # NOTE: we do this in a few steps so we can
141 # split-then-check-validity; necessary for things like when the
142 # previously seen flag optionally takes a value.
143 mutations = []
144 orig = token
145 if is_flag(token) and not machine.result.unparsed:
146 # Equals-sign-delimited flags, eg --foo=bar or -f=bar
147 if "=" in token:
148 token, _, value = token.partition("=")
149 msg = "Splitting x=y expr {!r} into tokens {!r} and {!r}"
150 debug(msg.format(orig, token, value))
151 mutations.append((index + 1, value))
152 # Contiguous boolean short flags, e.g. -qv
153 elif not is_long_flag(token) and len(token) > 2:
154 full_token = token[:]
155 rest, token = token[2:], token[:2]
156 err = "Splitting {!r} into token {!r} and rest {!r}"
157 debug(err.format(full_token, token, rest))
158 # Handle boolean flag block vs short-flag + value. Make
159 # sure not to test the token as a context flag if we've
160 # passed into 'storing unknown stuff' territory (e.g. on a
161 # core-args pass, handling what are going to be task args)
162 have_flag = (
163 token in machine.context.flags
164 and machine.current_state != "unknown"
165 )
166 if have_flag and machine.context.flags[token].takes_value:
167 msg = "{!r} is a flag for current context & it takes a value, giving it {!r}" # noqa
168 debug(msg.format(token, rest))
169 mutations.append((index + 1, rest))
170 else:
171 _rest = ["-{}".format(x) for x in rest]
172 msg = "Splitting multi-flag glob {!r} into {!r} and {!r}" # noqa
173 debug(msg.format(orig, token, _rest))
174 for item in reversed(_rest):
175 mutations.append((index + 1, item))
176 # Here, we've got some possible mutations queued up, and 'token'
177 # may have been overwritten as well. Whether we apply those and
178 # continue as-is, or roll it back, depends:
179 # - If the parser wasn't waiting for a flag value, we're already on
180 # the right track, so apply mutations and move along to the
181 # handle() step.
182 # - If we ARE waiting for a value, and the flag expecting it ALWAYS
183 # wants a value (it's not optional), we go back to using the
184 # original token. (TODO: could reorganize this to avoid the
185 # sub-parsing in this case, but optimizing for human-facing
186 # execution isn't critical.)
187 # - Finally, if we are waiting for a value AND it's optional, we
188 # inspect the first sub-token/mutation to see if it would otherwise
189 # have been a valid flag, and let that determine what we do (if
190 # valid, we apply the mutations; if invalid, we reinstate the
191 # original token.)
192 if machine.waiting_for_flag_value:
193 optional = machine.flag and machine.flag.optional
194 subtoken_is_valid_flag = token in machine.context.flags
195 if not (optional and subtoken_is_valid_flag):
196 token = orig
197 mutations = []
198 for index, value in mutations:
199 body.insert(index, value)
200 machine.handle(token)
201 machine.finish()
202 result = machine.result
203 result.remainder = " ".join(remainder)
204 return result
205
206
207 class ParseMachine(StateMachine):
208 initial_state = "context"
209
210 state("context", enter=["complete_flag", "complete_context"])
211 state("unknown", enter=["complete_flag", "complete_context"])
212 state("end", enter=["complete_flag", "complete_context"])
213
214 transition(from_=("context", "unknown"), event="finish", to="end")
215 transition(
216 from_="context",
217 event="see_context",
218 action="switch_to_context",
219 to="context",
220 )
221 transition(
222 from_=("context", "unknown"),
223 event="see_unknown",
224 action="store_only",
225 to="unknown",
226 )
227
228 def changing_state(self, from_: str, to: str) -> None:
229 debug("ParseMachine: {!r} => {!r}".format(from_, to))
230
231 def __init__(
232 self,
233 initial: "ParserContext",
234 contexts: Lexicon,
235 ignore_unknown: bool,
236 ) -> None:
237 # Initialize
238 self.ignore_unknown = ignore_unknown
239 self.initial = self.context = copy.deepcopy(initial)
240 debug("Initialized with context: {!r}".format(self.context))
241 self.flag = None
242 self.flag_got_value = False
243 self.result = ParseResult()
244 self.contexts = copy.deepcopy(contexts)
245 debug("Available contexts: {!r}".format(self.contexts))
246 # In case StateMachine does anything in __init__
247 super().__init__()
248
249 @property
250 def waiting_for_flag_value(self) -> bool:
251 # Do we have a current flag, and does it expect a value (vs being a
252 # bool/toggle)?
253 takes_value = self.flag and self.flag.takes_value
254 if not takes_value:
255 return False
256 # OK, this flag is one that takes values.
257 # Is it a list type (which has only just been switched to)? Then it'll
258 # always accept more values.
259 # TODO: how to handle somebody wanting it to be some other iterable
260 # like tuple or custom class? Or do we just say unsupported?
261 if self.flag.kind is list and not self.flag_got_value:
262 return True
263 # Not a list, okay. Does it already have a value?
264 has_value = self.flag.raw_value is not None
265 # If it doesn't have one, we're waiting for one (which tells the parser
266 # how to proceed and typically to store the next token.)
267 # TODO: in the negative case here, we should do something else instead:
268 # - Except, "hey you screwed up, you already gave that flag!"
269 # - Overwrite, "oh you changed your mind?" - which requires more work
270 # elsewhere too, unfortunately. (Perhaps additional properties on
271 # Argument that can be queried, e.g. "arg.is_iterable"?)
272 return not has_value
273
274 def handle(self, token: str) -> None:
275 debug("Handling token: {!r}".format(token))
276 # Handle unknown state at the top: we don't care about even
277 # possibly-valid input if we've encountered unknown input.
278 if self.current_state == "unknown":
279 debug("Top-of-handle() see_unknown({!r})".format(token))
280 self.see_unknown(token)
281 return
282 # Flag
283 if self.context and token in self.context.flags:
284 debug("Saw flag {!r}".format(token))
285 self.switch_to_flag(token)
286 elif self.context and token in self.context.inverse_flags:
287 debug("Saw inverse flag {!r}".format(token))
288 self.switch_to_flag(token, inverse=True)
289 # Value for current flag
290 elif self.waiting_for_flag_value:
291 debug(
292 "We're waiting for a flag value so {!r} must be it?".format(
293 token
294 )
295 ) # noqa
296 self.see_value(token)
297 # Positional args (must come above context-name check in case we still
298 # need a posarg and the user legitimately wants to give it a value that
299 # just happens to be a valid context name.)
300 elif self.context and self.context.missing_positional_args:
301 msg = "Context {!r} requires positional args, eating {!r}"
302 debug(msg.format(self.context, token))
303 self.see_positional_arg(token)
304 # New context
305 elif token in self.contexts:
306 self.see_context(token)
307 # Initial-context flag being given as per-task flag (e.g. --help)
308 elif self.initial and token in self.initial.flags:
309 debug("Saw (initial-context) flag {!r}".format(token))
310 flag = self.initial.flags[token]
311 # Special-case for core --help flag: context name is used as value.
312 if flag.name == "help":
313 flag.value = self.context.name
314 msg = "Saw --help in a per-task context, setting task name ({!r}) as its value" # noqa
315 debug(msg.format(flag.value))
316 # All others: just enter the 'switch to flag' parser state
317 else:
318 # TODO: handle inverse core flags too? There are none at the
319 # moment (e.g. --no-dedupe is actually 'no_dedupe', not a
320 # default-False 'dedupe') and it's up to us whether we actually
321 # put any in place.
322 self.switch_to_flag(token)
323 # Unknown
324 else:
325 if not self.ignore_unknown:
326 debug("Can't find context named {!r}, erroring".format(token))
327 self.error("No idea what {!r} is!".format(token))
328 else:
329 debug("Bottom-of-handle() see_unknown({!r})".format(token))
330 self.see_unknown(token)
331
332 def store_only(self, token: str) -> None:
333 # Start off the unparsed list
334 debug("Storing unknown token {!r}".format(token))
335 self.result.unparsed.append(token)
336
337 def complete_context(self) -> None:
338 debug(
339 "Wrapping up context {!r}".format(
340 self.context.name if self.context else self.context
341 )
342 )
343 # Ensure all of context's positional args have been given.
344 if self.context and self.context.missing_positional_args:
345 err = "'{}' did not receive required positional arguments: {}"
346 names = ", ".join(
347 "'{}'".format(x.name)
348 for x in self.context.missing_positional_args
349 )
350 self.error(err.format(self.context.name, names))
351 if self.context and self.context not in self.result:
352 self.result.append(self.context)
353
354 def switch_to_context(self, name: str) -> None:
355 self.context = copy.deepcopy(self.contexts[name])
356 debug("Moving to context {!r}".format(name))
357 debug("Context args: {!r}".format(self.context.args))
358 debug("Context flags: {!r}".format(self.context.flags))
359 debug("Context inverse_flags: {!r}".format(self.context.inverse_flags))
360
361 def complete_flag(self) -> None:
362 if self.flag:
363 msg = "Completing current flag {} before moving on"
364 debug(msg.format(self.flag))
365 # Barf if we needed a value and didn't get one
366 if (
367 self.flag
368 and self.flag.takes_value
369 and self.flag.raw_value is None
370 and not self.flag.optional
371 ):
372 err = "Flag {!r} needed value and was not given one!"
373 self.error(err.format(self.flag))
374 # Handle optional-value flags; at this point they were not given an
375 # explicit value, but they were seen, ergo they should get treated like
376 # bools.
377 if self.flag and self.flag.raw_value is None and self.flag.optional:
378 msg = "Saw optional flag {!r} go by w/ no value; setting to True"
379 debug(msg.format(self.flag.name))
380 # Skip casting so the bool gets preserved
381 self.flag.set_value(True, cast=False)
382
383 def check_ambiguity(self, value: Any) -> bool:
384 """
385 Guard against ambiguity when current flag takes an optional value.
386
387 .. versionadded:: 1.0
388 """
389 # No flag is currently being examined, or one is but it doesn't take an
390 # optional value? Ambiguity isn't possible.
391 if not (self.flag and self.flag.optional):
392 return False
393 # We *are* dealing with an optional-value flag, but it's already
394 # received a value? There can't be ambiguity here either.
395 if self.flag.raw_value is not None:
396 return False
397 # Otherwise, there *may* be ambiguity if 1 or more of the below tests
398 # fail.
399 tests = []
400 # Unfilled posargs still exist?
401 tests.append(self.context and self.context.missing_positional_args)
402 # Value matches another valid task/context name?
403 tests.append(value in self.contexts)
404 if any(tests):
405 msg = "{!r} is ambiguous when given after an optional-value flag"
406 raise ParseError(msg.format(value))
407
408 def switch_to_flag(self, flag: str, inverse: bool = False) -> None:
409 # Sanity check for ambiguity w/ prior optional-value flag
410 self.check_ambiguity(flag)
411 # Also tie it off, in case prior had optional value or etc. Seems to be
412 # harmless for other kinds of flags. (TODO: this is a serious indicator
413 # that we need to move some of this flag-by-flag bookkeeping into the
414 # state machine bits, if possible - as-is it was REAL confusing re: why
415 # this was manually required!)
416 self.complete_flag()
417 # Set flag/arg obj
418 flag = self.context.inverse_flags[flag] if inverse else flag
419 # Update state
420 try:
421 self.flag = self.context.flags[flag]
422 except KeyError as e:
423 # Try fallback to initial/core flag
424 try:
425 self.flag = self.initial.flags[flag]
426 except KeyError:
427 # If it wasn't in either, raise the original context's
428 # exception, as that's more useful / correct.
429 raise e
430 debug("Moving to flag {!r}".format(self.flag))
431 # Bookkeeping for iterable-type flags (where the typical 'value
432 # non-empty/nondefault -> clearly it got its value already' test is
433 # insufficient)
434 self.flag_got_value = False
435 # Handle boolean flags (which can immediately be updated)
436 if self.flag and not self.flag.takes_value:
437 val = not inverse
438 debug("Marking seen flag {!r} as {}".format(self.flag, val))
439 self.flag.value = val
440
441 def see_value(self, value: Any) -> None:
442 self.check_ambiguity(value)
443 if self.flag and self.flag.takes_value:
444 debug("Setting flag {!r} to value {!r}".format(self.flag, value))
445 self.flag.value = value
446 self.flag_got_value = True
447 else:
448 self.error("Flag {!r} doesn't take any value!".format(self.flag))
449
450 def see_positional_arg(self, value: Any) -> None:
451 for arg in self.context.positional_args:
452 if arg.value is None:
453 arg.value = value
454 break
455
456 def error(self, msg: str) -> None:
457 raise ParseError(msg, self.context)