Repository navigation
Parser rewrite 2 - #3924
Parser rewrite 2#3924Rowlando13 wants to merge 17 commits into
Conversation
7dce211 to
51054b8
Compare
|
Oh. Before I even start to look at this PR, what is the goal of this one? Just a rebase on top of |
|
@kdeldycke its ready for review. |
| @@ -0,0 +1 @@ | |||
| from __future__ import annotations | |||
kdeldycke
left a comment
There was a problem hiding this comment.
OK, so this PR is indeed a reboot of David's parser-rewrite-1 and keeps its refactor big points.
I like how this PR splits David's initial inline code into smaller pieces like _build_opt_tables, _scan_tokens and _assign_args, with the additional _OptTables. Even if private, it already helps me clean some fancy stuff I do in Click Extra around introspection. And gives more flexibility to other users, at their own risks off course.
I like the TypeError when two option names collides. There are probably some overlaps with #3827 but I will revise my PR against this one once it is merged.
I left a lot of test in my review to illustrate edge-cases that need to be documented, covered, discussed or fixed. Not sure if these were intentionals.
But all in all I like this PR ! Only a small effort and I guess we can start laying the fondation for 9.0.0. If we decide to merge, should we create a new 9.x branch? Or push to main, declare it 9.x and merge the upcoming 8.6.0 to stable?
|
|
||
| claimed[name] = (param, original, is_secondary) | ||
| prefix, value = _split_opt(name) | ||
| opt_prefixes.add(prefix[0]) |
There was a problem hiding this comment.
You take prefix[0] here without checking it. So an option declared without dashes, like @click.option("fruit-name"), now gives a different error: we get the less-informative IndexError: string index out of range instead of the original ValueError: Invalid start character for option (fruit-name).
| def parse_args(self, ctx: Context, args: list[str]) -> list[str]: | ||
| return self._parse_args(ctx, args) | ||
|
|
||
| def _parse_args(self, ctx: Context, args: list[str]) -> list[str]: |
There was a problem hiding this comment.
This method still parses and processes arguments in one go. I propose to use the oportunity to split the pure parsing part from the processing part, as suggested in #2205 (comment)
| @@ -1,7 +1,24 @@ | |||
| ## Version 8.6.0 | |||
| ## Version 9.0.0 | |||
There was a problem hiding this comment.
Keep the 8.6.0 changelog as we need a 8.6.0 to deprecate stuff explicitly before 9.0.0
| self._exit_stack = ExitStack() | ||
|
|
||
| @property | ||
| def protected_args(self) -> list[str]: |
There was a problem hiding this comment.
Maybe you should delete this property altogether since it is already marked for deletion for 9.0.0 and you already removed self._protected_args?
| context. ``Command.show_default`` overrides this default for the | ||
| specific command. | ||
| .. versionchanged:: 8.2 |
There was a problem hiding this comment.
Maybe add a note here to inform about protected_args deletion.
| `-v` and `-V` with a lower-casing function, raise a `TypeError` when parsing | ||
| instead of one silently making the other unreachable. This includes the on | ||
| and off names of a boolean flag, such as `-s/-S`. | ||
|
|
| elif token[:2] in tables.opt_prefixes: | ||
| # long prefix, no matching long opt | ||
| if not ctx.ignore_unknown_options: | ||
| raise NoSuchOption( |
There was a problem hiding this comment.
An option here with a str.lower normalizer does not suggest an option.
This test fail on this PR:
@pytest.mark.parametrize(
("args", "expect"),
[
pytest.param(["--RIPPE"], "Did you mean '--ripe'?", id="option"),
pytest.param(["PEEEL"], "Did you mean 'peel'?", id="command"),
],
)
def test_normalization_suggestion(runner, args, expect):
@click.group(context_settings=CONTEXT_SETTINGS)
@click.option("--ripe", is_flag=True)
def cli(ripe):
pass
@cli.command()
def peel():
pass
result = runner.invoke(cli, args)
assert expect in result.output|
|
||
| if value is not UNSET and not self.multiple: | ||
| # Use only the last occurrence of the option if multiple isn't enabled. | ||
| value = value[-1] |
There was a problem hiding this comment.
This test does not pass on this PR but works on main and shows that a custom option redefining handle_parse_result does not work when reading or writing a single value:
@pytest.mark.parametrize(
("rewrite", "args", "expect"),
[
pytest.param(lambda value: "kiwi", [], "kiwi", id="write"),
pytest.param(
lambda value: value.upper(),
["--fruit", "kiwi"],
"KIWI",
id="read-and-write",
),
],
)
def test_handle_parse_result_rewrites_opts(runner, rewrite, args, expect):
class RewriteOption(click.Option):
def handle_parse_result(self, ctx, opts, args):
opts = {**opts, self.name: rewrite(opts.get(self.name))}
return super().handle_parse_result(ctx, opts, args)
@click.command()
@click.option("--fruit", cls=RewriteOption)
def cli(fruit):
return fruit
result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)
assert result.return_value == expectI know that both handle_parse_result and consume_value are marked :meta private: so I am OK to change the behavior. Just maybe a good idea to lock it down with these kind of tests.
| `split_opt`. `split_arg_string` is available as | ||
| {func}`click.split_arg_string`. | ||
| Use `optparse` from the standard library if you need the old parser. | ||
| - `Command.make_parser` and `Parameter.add_to_parser` are removed. |
There was a problem hiding this comment.
Maybe we should add a deprecation warning for that in 8.6.0 ?
| # No more tokens, but the current opt still required a value. | ||
| assert looking_opt is not None and looking_opt_name is not None | ||
| message = ngettext( | ||
| "Option {name!r} requires a value.", |
There was a problem hiding this comment.
Ah! That's a better error message! :) Should we add an entry to inform users of that change in the changelog?
Command._parse_args_build_opt_tables,_scan_tokens, and_assign_args.-Sto-sfor lowercase token normalization, when they are just other names for the same thing.-
split_arg_stringis now public. It was basically halfway public already where we import it in the docs but not from the top level to show how to make you own shell completion. Its very small.ToDo: