repo
stringclasses
358 values
pull_number
int64
6
67.9k
instance_id
stringlengths
12
49
issue_numbers
sequencelengths
1
7
base_commit
stringlengths
40
40
patch
stringlengths
87
101M
test_patch
stringlengths
72
22.3M
problem_statement
stringlengths
3
256k
hints_text
stringlengths
0
545k
created_at
stringlengths
20
20
PASS_TO_PASS
sequencelengths
0
0
FAIL_TO_PASS
sequencelengths
0
0
pallets/click
1,306
pallets__click-1306
[ "1139" ]
14fa50aefbfe7b8b1b978d7ea8c02f5b14d60032
diff --git a/click/exceptions.py b/click/exceptions.py --- a/click/exceptions.py +++ b/click/exceptions.py @@ -152,6 +152,19 @@ def format_message(self): msg or '', ) + def __str__(self): + if self.message is None: + param_name = self.param.name if self.param else None + return "missing parameter: {}".format(param_name) + else: + return self.message + + if PY2: + __unicode__ = __str__ + + def __str__(self): + return self.__unicode__().encode("utf-8") + class NoSuchOption(UsageError): """Raised if click attempted to handle an option that does not
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -203,6 +203,15 @@ def cmd(arg): assert 'Missing argument "ARG".' in result.output +def test_missing_argument_string_cast(): + ctx = click.Context(click.Command("")) + + with pytest.raises(click.MissingParameter) as excinfo: + click.Argument(["a"], required=True).full_process_value(ctx, None) + + assert str(excinfo.value) == "missing parameter: a" + + def test_implicit_non_required(runner): @click.command() @click.argument('f', default='test') diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -321,6 +321,15 @@ def cmd(whatever): assert result.output == '23\n' +def test_missing_option_string_cast(): + ctx = click.Context(click.Command("")) + + with pytest.raises(click.MissingParameter) as excinfo: + click.Option(['-a'], required=True).full_process_value(ctx, None) + + assert str(excinfo.value) == "missing parameter: a" + + def test_missing_choice(runner): @click.command() @click.option('--foo', type=click.Choice(['foo', 'bar']),
Unprintable MissingParameter exception My code is (correctly) hitting https://github.com/pallets/click/blob/master/click/core.py#L1444 and raising a MissingParameter exception. However, there's no `message` passed there, which means `exc.message` is defaulted to `None` by the base class (`ClickException`) constructor here https://github.com/pallets/click/blob/master/click/exceptions.py#L23. With other `ClickException`s I've seen (e.g. `NoSuchOption` https://github.com/pallets/click/blob/master/click/exceptions.py#L165), if message is set to None then it gets reset as something more sensible e.g. `"No such option 'foo'"`. This means that doing `str(exc)` works nicely. However, `MissingParameter` doesn't have this, which means any attempt to stringify (e.g. print or log) a `MissingParameter` actually causes a `TypeError: __str__ returned non-string (type NoneType)` and then things go badly wrong. Is it expected that `MissingParameter` is an unprintable exception when caused e.g. by missing out a required argument? It seems odd that no one else has come across this before. I'm using click in a slightly unusual context in that I'm using the group/command/arg/option parsing stuff outside of a traditional command line script, which might be why no one has seen this if click does it's own special handling for `MissingParameter` errors. TL;DR It would be nice if `MissingParameter` was printable when raised via `Parameter.full_process_value` (or ideally more generally). It might be enough to have something along the lines of what `NoSuchOption` does?
Hello. Any progress on this? The PR above does not pass the tests. I can't investigate further at the moment. This is still a problem. I just hit this myself in click 7.0.0 I'll take a look at this.
2019-05-06T20:22:08Z
[]
[]
pallets/click
1,309
pallets__click-1309
[ "914" ]
9ea9666f0f5646713be799e764ecc252c9f7ebbd
diff --git a/click/termui.py b/click/termui.py --- a/click/termui.py +++ b/click/termui.py @@ -1,3 +1,4 @@ +import io import os import sys import struct @@ -5,11 +6,12 @@ import itertools from ._compat import raw_input, text_type, string_types, \ - isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN + isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN from .utils import echo from .exceptions import Abort, UsageError from .types import convert_type, Choice, Path from .globals import resolve_color_default +from .utils import LazyFile # The prompt functions to use. The doc tools currently override these @@ -48,10 +50,17 @@ def _build_prompt(text, suffix, show_default=False, default=None, show_choices=T if type is not None and show_choices and isinstance(type, Choice): prompt += ' (' + ", ".join(map(str, type.choices)) + ')' if default is not None and show_default: - prompt = '%s [%s]' % (prompt, default) + prompt = '%s [%s]' % (prompt, _format_default(default)) return prompt + suffix +def _format_default(default): + if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): + return default.name + + return default + + def prompt(text, default=None, hide_input=False, confirmation_prompt=False, type=None, value_proc=None, prompt_suffix=': ', show_default=True, err=False, show_choices=True):
diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -225,6 +225,24 @@ def cli_without_choices(g): assert '(none, day, week, month)' not in result.output [email protected]( + "file_kwargs", + [ + {"mode": "rt"}, + {"mode": "rb"}, + {"lazy": True}, + ] +) +def test_file_prompt_default_format(runner, file_kwargs): + @click.command() + @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs)) + def cli(f): + click.echo(f.name) + + result = runner.invoke(cli) + assert result.output == "file [{0}]: \n{0}\n".format(__file__) + + def test_secho(runner): with runner.isolation() as outstreams: click.secho(None, nl=False)
File option - prompting with pretty default? Hello, I'm developing simple script, but I have found horrible default when using a file option with prompting with default value... I have this code: ```python import click import os.path @click.command() @click.option('-f', default=os.path.realpath("subdir/file.txt"), prompt="Please provide a file", type=click.File('rt')) def func(f): pass func() ``` But when I call it, it produces prompt like this: me@computer:~/directory$ python3 script.py Please provide a file [<_io.TextIOWrapper name='/home/me/directory/subdir/file.txt' mode='rt' encoding='UTF-8'>]: Is this solved anywhere or how difficult would it be to fix it, so it would show `[/home/me/directory/subdir/file.txt]`? `Ubuntu 16.04 LTS 32-bit, Python 3.5.2, click 6.7` Please excuse any imperfections of this issue, I'm quite new to GitHub and haven't written any issues yet...
Can't reproduce on Mac - Python 3.6.2, Click 6.7... ``` (tmp-314aa1dbdcce094) ✔ ~/.venvs/tmp-314aa1dbdcce094 21:17 $ pip install click Collecting click Using cached click-6.7-py2.py3-none-any.whl Installing collected packages: click Successfully installed click-6.7 (tmp-314aa1dbdcce094) ✔ ~/.venvs/tmp-314aa1dbdcce094 21:17 $ python test.py --help Usage: test.py [OPTIONS] Options: -f FILENAME --help Show this message and exit. (tmp-314aa1dbdcce094) ✔ ~/.venvs/tmp-314aa1dbdcce094 21:17 $ cat test.py import click import os.path @click.command() @click.option('-f', default=os.path.realpath("subdir/file.txt"), prompt="Please provide a file", type=click.File('rt')) def func(f): pass func() (tmp-314aa1dbdcce094) ✔ ~/.venvs/tmp-314aa1dbdcce094 21:17 $ python test.py Usage: test.py [OPTIONS] Error: Invalid value for "-f": Could not open file: /Users/tomgoren/.venvs/tmp-314aa1dbdcce094/subdir/file.txt: No such file or directory (tmp-314aa1dbdcce094) ✘-2 ~/.venvs/tmp-314aa1dbdcce094 21:17 $ pip freeze -f file:///Users/tomgoren/.cache/pip/wheelhouse click==6.7 (tmp-314aa1dbdcce094) ✔ ~/.venvs/tmp-314aa1dbdcce094 21:17 $ python --version Python 3.6.2 ``` Oh, @tomgoren, this isn't meant to be reproduced as is. If you want to: ``` mkdir subdir touch subdir/file.txt ``` _Sorry for late reply and writing bad issues..._ Okay - I see it now @mvolfik. The problem seems to be [here](https://github.com/pallets/click/blob/master/click/types.py#L373). There is only one value returned, `f`. If we were to return `f.name` for instance, then what we would get back would only be a string, and not the actual file handler. So, while the output would be as expected, it would produce the wrong result if you were to try something like `f.read()`. Test case using your example (I changed `click/types.py` locally): ``` 22:21 $ python test.py Please provide a file [/home/tomgoren/.venvs/tmp-d5c5119e57bcfc5/subdir/file.txt]: Traceback (most recent call last): File "test.py", line 9, in <module> func() File "/home/tomgoren/.venvs/tmp-d5c5119e57bcfc5/lib/python3.6/site-packages/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/home/tomgoren/.venvs/tmp-d5c5119e57bcfc5/lib/python3.6/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/tomgoren/.venvs/tmp-d5c5119e57bcfc5/lib/python3.6/site-packages/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/tomgoren/.venvs/tmp-d5c5119e57bcfc5/lib/python3.6/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "test.py", line 7, in func print(f.read()) AttributeError: 'str' object has no attribute 'read' ``` After digging a bit deeper, there seems to be a whole song and dance between [`convert`](https://github.com/pallets/click/blob/master/click/types.py#L346), [`convert_type`](https://github.com/pallets/click/blob/master/click/types.py#L518), [`prompt`](https://github.com/pallets/click/blob/master/click/termui.py#L36), and a [few other bits and pieces](https://github.com/pallets/click/blob/master/click/core.py#L1341). The long and the short of it is that I got a bit lost, and I'm sorry I wasn't able to help more, but it seems like an actual bug, and a tricky one at that. I'm very curious to see how this is solved either way. Good luck! Starting to work on it
2019-05-07T15:54:29Z
[]
[]
pallets/click
1,318
pallets__click-1318
[ "1277" ]
68c93287a8195af539c85656927f5c67ba5631d5
diff --git a/click/types.py b/click/types.py --- a/click/types.py +++ b/click/types.py @@ -133,6 +133,10 @@ class Choice(ParamType): You should only pass a list or tuple of choices. Other iterables (like generators) may lead to surprising results. + The resulting value will always be one of the originally passed choices + regardless of ``case_sensitive`` or any ``ctx.token_normalize_func`` + being specified. + See :ref:`choice-opts` for an example. :param case_sensitive: Set to false to make choices case @@ -152,29 +156,34 @@ def get_missing_message(self, param): return 'Choose from:\n\t%s.' % ',\n\t'.join(self.choices) def convert(self, value, param, ctx): - # Exact match - if value in self.choices: - return value - # Match through normalization and case sensitivity # first do token_normalize_func, then lowercase # preserve original `value` to produce an accurate message in # `self.fail` normed_value = value - normed_choices = self.choices + normed_choices = {choice: choice for choice in self.choices} - if ctx is not None and \ - ctx.token_normalize_func is not None: + if ctx is not None and ctx.token_normalize_func is not None: normed_value = ctx.token_normalize_func(value) - normed_choices = [ctx.token_normalize_func(choice) for choice in - self.choices] + normed_choices = { + ctx.token_normalize_func(normed_choice): original + for normed_choice, original in normed_choices.items() + } if not self.case_sensitive: - normed_value = normed_value.lower() - normed_choices = [choice.lower() for choice in normed_choices] + if PY2: + lower = str.lower + else: + lower = str.casefold + + normed_value = lower(normed_value) + normed_choices = { + lower(normed_choice): original + for normed_choice, original in normed_choices.items() + } if normed_value in normed_choices: - return normed_value + return normed_choices[normed_value] self.fail('invalid choice: %s. (choose from %s)' % (value, ', '.join(self.choices)), param, ctx)
diff --git a/tests/test_normalization.py b/tests/test_normalization.py --- a/tests/test_normalization.py +++ b/tests/test_normalization.py @@ -20,7 +20,7 @@ def test_choice_normalization(runner): @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--choice', type=click.Choice(['Foo', 'Bar'])) def cli(choice): - click.echo('Foo') + click.echo(choice) result = runner.invoke(cli, ['--CHOICE', 'FOO']) assert result.output == 'Foo\n' diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -335,12 +335,15 @@ def cmd(foo): result = runner.invoke(cmd, ['--foo', 'apple']) assert result.exit_code == 0 + assert result.output == 'Apple\n' result = runner.invoke(cmd, ['--foo', 'oRANGe']) assert result.exit_code == 0 + assert result.output == 'Orange\n' result = runner.invoke(cmd, ['--foo', 'Apple']) assert result.exit_code == 0 + assert result.output == 'Apple\n' @click.command() @click.option('--foo', type=click.Choice(['Orange', 'Apple'])) @@ -357,6 +360,18 @@ def cmd2(foo): assert result.exit_code == 0 +def test_case_insensitive_choice_returned_exactly(runner): + @click.command() + @click.option('--foo', type=click.Choice( + ['Orange', 'Apple'], case_sensitive=False)) + def cmd(foo): + click.echo(foo) + + result = runner.invoke(cmd, ['--foo', 'apple']) + assert result.exit_code == 0 + assert result.output == 'Apple\n' + + def test_multiline_help(runner): @click.command() @click.option('--foo', help="""
Add coercion/normalization of Choice values I want my CLI to be case insensitive for certain `Choice` options but I don't want to deal with that variability internally as it has no meaning. I think an option like `coerce_case` or `normalize_case` would be a reasonable addition. PR to follow.
It appears #887 already added this. Never mind, this is about what value gets returned, that was about what got matched. > I don't want to deal with that variability internally as it has no meaning. Sounds like you should just be handling things in all-lowercase? #887 set things to return the `normed_value` -- so when `case_sensitive=False`, `click.Choice` should always be returning a lowercase string. (Yes, this should be improved in the documentation for `case_sensitive=False`.) Reading #1278, it seems this is about allowing `--foo [Apple|Orange]` and always returning title-case `Apple` or `Orange` even if `case_sensitive=False`. Unless there's some other rationale, I don't think this is well-justified. It adds another parameter to `click.Choice` which is conditional on `case_sensitive=False` and "undoes" part of that behavior -- I think that will be confusing for most users. I'm not saying there isn't a reason! In #569 I argued that I really have a use-case where case-sensitivity is driven by external constraints. But I'd need to know what the use-case is before agreeing that this should be part of `click`. [I'm reminded of this comment on the initial request for case_sensitive](https://github.com/pallets/click/issues/569#issuecomment-216515603). If there is a clear use-case here, it's worth considering a generic parameter which changes the `token_normalize_func` on a per-option basis. @sirosen, yes, #1278 retains the original (not necessarily title) case specified by the choices. It seems to me this may have been a better approach to begin with as opposed having case insensitivity force the introduction of a third casing (lower as opposed to original choice and user-entered). But, for backwards compatibility I introduced this as an option with default behavior remaining as it is now. My actual use case is in https://github.com/altendky/romp where I have choices for platform and Python interpreter (and more, but specifically those). I stuck a copy of the modified choice in there which I am using for now. https://github.com/altendky/romp/blob/742d4ac5ff0b918e33002af1f374b8ce6938367a/src/romp/_matrix.py#L11-L18 ```python vm_images = collections.OrderedDict(( ('Linux', 'ubuntu-16.04'), ('macOS', 'macOS-10.13'), ('Windows', 'vs2017-win2016'), )) all_platforms = tuple(vm_images.keys()) ``` `all_platforms` is used as a choice list elsewhere. I could `.lower()` in various places for comparison or create another mapping `lower_platforms_to_display = {platform.lower(): platform for platform in all_platforms}` and use that wherever I want to display the proper case. Or I could recover the case from the `.lower()`ed result from the Click choice. Or I could just have one casing that I work with everywhere. As mentioned above it's not clear to me yet that the present functionality of 'returning' the lower case form is actually good over returning original or user entered. Is there a reason it is beyond (the sufficient) backwards compatibility? Thanks for your time and feedback. Thanks for linking the original/relevant source of this issue. I was kind of guessing this might be a matter of having a source of data where case is important, then being fed into the CLI opts. I may have to take a break from click for the moment, but will try to circle back and look again later this week -- but I can answer one question: > As mentioned above it's not clear to me yet that the present functionality of 'returning' the lower case form is actually good over returning original or user entered. Is there a reason it is beyond (the sufficient) backwards compatibility? Maybe those who reviewed it have a different take, but as the author of #887, no, there's no reason. 😅 My use case was that I wanted `--foo [apple|orange]` and not to care about `--foo oRanGE`, but I didn't really at the time consider that the choices offered might have actually had important information encoded in the case. We could argue that changing this behavior would be a backwards incompatible change -- demanding that it be saved for v8.0 -- or we could make the case that, as I noted that "the doc for case_sensitive should be improved", the behavior is unspecified. I would be okay with saying `case_sensitive=False` returns the choice value as specified, not lowercased, and calling it a fix for v7.1. (i.e. `case_sensitive=False` has a bug in v7.0, in that it _incorrectly_ returns a lowercased value instead of the matching choice value) Realistically, most callers using `case_sensitive=True` are probably, like me, passing in a list of lowercase strings and would see no change. Making the new behavior in #1278 the only behavior would almost definitely make `click` better to use long-term. Changing the default behavior strikes me as better than adding another option with conditional/nuanced behavior. I want to just change it in v7.1 and field any complaints. But if we do that and someone _is_ relying on the lowercasing and gets broken, I'm sure I'll catch some grief for taking that stance... @sirosen, I can certainly make another PR to implement the 'fix' rather than the 'feature addition' in #1278. For the people banking on the forced lowercase result I guess they would get whatever misc failures in their code and the fix would be `option_value = option_value.lower()` (or, `.casefold()` perhaps if py3). An option to do that in Click itself would of course be easy but it seems it wouldn't add much value and would probably just be a generic post-proc to allow for choosing lower vs casefold vs... ?? who knows. I suppose the value in having it in Click is in reuse of defined options (I do this a good bit, `x_option = click.Option('--x')` then `@x_option` on multiple commands). Or, perhaps Click already has such a feature? I honestly am not familiar with the possible modifiers. No rush on this on my behalf. I've got my workaround in place for now and can remove it whenever. > Or, perhaps Click already has such a feature? I honestly am not familiar with the possible modifiers. The best path on that sort of thing is to define a specialized decorator which applies your option with desired params. The `callback` parameter lets you do post-processing pretty cleanly: ```python def common_options(cmd): def _lower_callback(ctx, param, value): if value is None: return value else: return value.lower() cmd = click.option('--x', callback=_lower_callback)(cmd) cmd = click.option('--foo', callback=_lower_callback)(cmd) return cmd ``` --- If you're comfortable with letting this wait around a little, I'd like to hear someone else's input (e.g. @davidism if he can spare the time) on whether or not it's okay to simply change the behavior and say it was unspecified in 7.0 and will be specified in 7.1 . Just to be clear, the new proposal is to make `case_sensistive=True` mean "match case insensitive, but return exact value", and `False` would be "match and return exact"? @davidism, I believe so. Where 'exact' refers to 'as passed to `click.Choice()` in code' not 'as written on the command line'. Seems fine for 7.1, along with clarifying the documentation of the option, it would be good to add an example of normalizing to lowercase if there's not one already. @davdism, for the additional example, you are referring to `callback=_lower_callback` which would allow recovery of the existing 7.0 behavior regarding `case_sensitive=False`? Note that 7.0 returns the normed value not the exact value passed to `click.Choice()`. So we have three values: 'exact', 'normed', and 'normed+lowered'. I haven't personally used the normalization system. Do we want to restrict this change to only correcting the result for `case_sensitive=False` and make it return the 'normed' value? Or to universally return the 'exact' value passed to the `click.Choice()` call thus also changing behavior for normalized values? The latter seems more complete and easy to clearly document. To have the list handy, and in case I missed something, here is the documentation for `click.Choice()` that I found. None of them seem to clarify what will be passed to the command. * http://click.palletsprojects.com/en/7.x/api/#click.Choice * https://github.com/pallets/click/blob/baf01249d2bb662390f66a5574a264d723862b8e/click/types.py#L130-L140 * http://click.palletsprojects.com/en/7.x/options/#choice-opts * https://github.com/pallets/click/blob/baf01249d2bb662390f66a5574a264d723862b8e/docs/options.rst#L311-L344 * http://click.palletsprojects.com/en/7.x/advanced/?highlight=choice#token-normalization * https://github.com/pallets/click/blob/baf01249d2bb662390f66a5574a264d723862b8e/docs/advanced.rst#L120-L128 * http://click.palletsprojects.com/en/7.x/bashcomplete/?highlight=choice#what-it-completes * https://github.com/pallets/click/blob/baf01249d2bb662390f66a5574a264d723862b8e/docs/bashcomplete.rst#L18-L24 I think the best thing to do for the examples is to write a command which takes a choice like `Apple|Orange|Banana` and then show how it can be updated to `case_insensitive=False` to also accept `apple`, `APPLE`, and other spellings. Show that `Apple` is the string passed to the command function regardless -- and note that it is specified by the option definition, not what's passed on the command-line. The token normalize function and use of `callback` on `Option`s are both probably out of scope for this -- at least, I wouldn't add them to the examples unless lots of people show up asking questions about how they interact with this specific case. > Do we want to restrict this change to only correcting the result for `case_sensitive=False` and make it return the 'normed' value? Or to universally return the 'exact' value passed to the `click.Choice()` call thus also changing behavior for normalized values? To clarify, you're distinguishing - the value passed to `click.Choice` vs - the value passed to `click.Choice`, passed through `ctx.token_normalize_func`, but without `str.lower()` ? I think the easiest behavior to explain is that it returns the original string passed to `click.Choice`, not the normalized-but-not-lowercased version. --- Also, something we haven't discussed is that `case_sensitive=False` will interact with this new behavior in an interesting way if multiple choices are different spellings of the same value. With `click.Choice(['apple', 'APPLE'], case_sensitive=False)` -- it now will matter which one of these two choices `aPPle` matches. I think it's fine for such behavior to remain undefined, but, if possible, I'd like to take the first or last matching choice in a consistent way. Yes, that is the value I'm referring to. Or maybe raise an exception on creation of a non-unique case-insensitive list? `if len(set(choice.lower() for choice in choices)) < len(choices): raise...` It always looked funny having the optimized direct check against the original choices at the beginning. It allowed things to match without enforcing the normalization. I think these are the two open questions. Questions: - Should the pre-callback value always be the same as was passed to `click.Choice()`? - We already agreed that `case_sensitive=False` should be corrected to not modify the value - Presently `ctx.token_normalize_func` modifies the value, should that behavior be changed? - What should be done with `click.Choice(['apple', 'APPLE'], case_sensitive=False)`? - Undefined? - Raise an exception? - Out of scope for this ticket? > Presently ctx.token_normalize_func modifies the value, should that behavior be changed? I think so. My rationale is based on looking at the diff for #887 . Prior to that, the choice value which was matched, without passing through `ctx.token_normalize_func`, would be returned by `click.Choice`. So *not* applying `ctx.token_normalize_func` is the most similar behavior to click 6.x and below. > What should be done with click.Choice(['apple', 'APPLE'], case_sensitive=False)? I'm fine with any of the options you put forth. They all make sense on the grounds that "If the user isn't sure what he/she is asking for, how could Click possibly know?" :)
2019-05-11T19:41:38Z
[]
[]
pallets/click
1,329
pallets__click-1329
[ "1264" ]
0b1e32b0d6d44590f0dae2e28b99bd7ccb6579f7
diff --git a/click/__init__.py b/click/__init__.py --- a/click/__init__.py +++ b/click/__init__.py @@ -14,7 +14,7 @@ # Core classes from .core import Context, BaseCommand, Command, MultiCommand, Group, \ - CommandCollection, Parameter, Option, Argument + CommandCollection, Parameter, Option, Argument, ParameterSource # Globals from .globals import get_current_context diff --git a/click/core.py b/click/core.py --- a/click/core.py +++ b/click/core.py @@ -129,6 +129,35 @@ def sort_key(item): return sorted(declaration_order, key=sort_key) +class ParameterSource(object): + """This is an enum that indicates the source of a command line parameter. + + The enum has one of the following values: COMMANDLINE, + ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the + default value in the decorator was used. This class should be + converted to an enum when Python 2 support is dropped. + """ + + COMMANDLINE = "COMMANDLINE" + ENVIRONMENT = "ENVIRONMENT" + DEFAULT = "DEFAULT" + DEFAULT_MAP = "DEFAULT_MAP" + + VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP} + + @classmethod + def validate(cls, value): + """Validate that the specified value is a valid enum. + + This method will raise a ValueError if the value is + not a valid enum. + + :param value: the string value to verify + """ + if value not in cls.VALUES: + raise ValueError("Invalid ParameterSource value: '{}'. Valid " + "values are: {}".format(value, ",".join(cls.VALUES))) + class Context(object): """The context is a special internal object that holds state relevant @@ -339,7 +368,8 @@ def __init__(self, command, parent=None, info_name=None, obj=None, self._close_callbacks = [] self._depth = 0 - + self._source_by_paramname = {} + def __enter__(self): self._depth += 1 push_context(self) @@ -572,6 +602,35 @@ def forward(*args, **kwargs): return self.invoke(cmd, **kwargs) + def set_parameter_source(self, name, source): + """Set the source of a parameter. + + This indicates the location from which the value of the + parameter was obtained. + + :param name: the name of the command line parameter + :param source: the source of the command line parameter, which + should be a valid ParameterSource value + """ + ParameterSource.validate(source) + self._source_by_paramname[name] = source + + def get_parameter_source(self, name): + """Get the source of a parameter. + + This indicates the location from which the value of the + parameter was obtained. This can be useful for determining + when a user specified an option on the command line that is + the same as the default. In that case, the source would be + ParameterSource.COMMANDLINE, even though the value of the + parameter was equivalent to the default. + + :param name: the name of the command line parameter + :returns: the source + :rtype: ParameterSource + """ + return self._source_by_paramname[name] + class BaseCommand(object): """The base command implements the minimal API contract of commands. @@ -1394,10 +1453,15 @@ def add_to_parser(self, parser, ctx): def consume_value(self, ctx, opts): value = opts.get(self.name) + source = ParameterSource.COMMANDLINE if value is None: value = self.value_from_envvar(ctx) + source = ParameterSource.ENVIRONMENT if value is None: value = ctx.lookup_default(self.name) + source = ParameterSource.DEFAULT_MAP + if value is not None: + ctx.set_parameter_source(self.name, source) return value def type_cast_value(self, ctx, value): @@ -1444,6 +1508,8 @@ def full_process_value(self, ctx, value): if value is None and not ctx.resilient_parsing: value = self.get_default(ctx) + if value is not None: + ctx.set_parameter_source(self.name, ParameterSource.DEFAULT) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self)
diff --git a/tests/test_context.py b/tests/test_context.py --- a/tests/test_context.py +++ b/tests/test_context.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import click - +import pytest def test_ensure_context_objects(runner): class Foo(object): @@ -256,3 +256,62 @@ def cli(ctx): ctx.exit(0) assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0 + +def test_parameter_source_default(): + @click.command() + @click.pass_context + @click.option("-o", "--option", default=1) + def cli(ctx, option): + assert ctx.get_parameter_source("option") == click.ParameterSource.DEFAULT + ctx.exit(1) + + assert cli.main([], "test_parameter_source_default", standalone_mode=False) == 1 + +def test_parameter_source_default_map(): + @click.command() + @click.pass_context + @click.option("-o", "--option", default=1) + def cli(ctx, option): + assert ctx.get_parameter_source("option") == click.ParameterSource.DEFAULT_MAP + ctx.exit(1) + + assert cli.main([], "test_parameter_source_default", standalone_mode=False, default_map={ "option": 1}) == 1 + + +def test_parameter_source_commandline(): + @click.command() + @click.pass_context + @click.option("-o", "--option", default=1) + def cli(ctx, option): + assert ctx.get_parameter_source("option") == click.ParameterSource.COMMANDLINE + ctx.exit(1) + + assert cli.main(["-o", "1"], "test_parameter_source_commandline", standalone_mode=False) == 1 + assert cli.main(["--option", "1"], "test_parameter_source_default", standalone_mode=False) == 1 + + +def test_parameter_source_environment(runner): + @click.command() + @click.pass_context + @click.option("-o", "--option", default=1) + def cli(ctx, option): + assert ctx.get_parameter_source("option") == click.ParameterSource.ENVIRONMENT + sys.exit(1) + + assert runner.invoke(cli, [], prog_name="test_parameter_source_environment", env={"TEST_OPTION": "1"}, auto_envvar_prefix="TEST").exit_code == 1 + + +def test_parameter_source_environment_variable_specified(runner): + @click.command() + @click.pass_context + @click.option("-o", "--option", default=1, envvar="NAME") + def cli(ctx, option): + assert ctx.get_parameter_source("option") == click.ParameterSource.ENVIRONMENT + sys.exit(1) + + assert runner.invoke(cli, [], prog_name="test_parameter_source_environment", env={"NAME": "1"}).exit_code == 1 + + +def test_validate_parameter_source(): + with pytest.raises(ValueError): + click.ParameterSource.validate("NOT_A_VALID_PARAMETER_SOURCE")
Differentiate defaults from explicitly passed values Unless I've missed something it seems there is currently no way to differentiate between an explicitly passed value and a default value. This is problematic for establishing value precedence when dealing with other sources of parameter values (a config file in our case). We're currently using the default values to detect if a given option was passed on the command line but this is imperfect and leads to the following problem: - `@option('--some-option', default=1)` - Some other way of specifying option values (e.g. a config file) sets `some-option = 2` - User calls cli with `--some-option 1` Under the above workaround this makes it appear as if the config file value (`2`) should have precedence even though the user explicitly requested value `1`.
How would you propose we distinguish these? I'm not sure if click should even do this, although the info is probably somewhere in the context or could be handled with an extension.
2019-05-31T15:31:38Z
[]
[]
pallets/click
1,332
pallets__click-1332
[ "1226" ]
a43832228f19d041050940e513652e4e28461ab9
diff --git a/click/_termui_impl.py b/click/_termui_impl.py --- a/click/_termui_impl.py +++ b/click/_termui_impl.py @@ -260,8 +260,21 @@ def make_step(self, n_steps): self.eta_known = self.length_known - def update(self, n_steps): + def update(self, n_steps, current_item=None): + """Update the progress bar by advancing a specified number of + steps, and optionally set the ``current_item`` for this new + position. + + :param n_steps: Number of steps to advance. + :param current_item: Optional item to set as ``current_item`` + for the updated position. + + .. versionadded:: 8.0 + Added the ``current_item`` optional parameter. + """ self.make_step(n_steps) + if current_item is not None: + self.current_item = current_item self.render_progress() def finish(self): diff --git a/click/termui.py b/click/termui.py --- a/click/termui.py +++ b/click/termui.py @@ -302,6 +302,20 @@ def progressbar(iterable=None, length=None, label=None, show_eta=True, process_chunk(chunk) bar.update(chunks.bytes) + The ``update()`` method also takes an optional value specifying the + ``current_item`` at the new position. This is useful when used + together with ``item_show_func`` to customize the output for each + manual step:: + + with click.progressbar( + length=total_size, + label='Unzipping archive', + item_show_func=lambda a: a.filename + ) as bar: + for archive in zip_file: + archive.extract() + bar.update(archive.size, archive) + .. versionadded:: 2.0 .. versionadded:: 4.0
diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -239,6 +239,50 @@ def cli(): assert '100% ' in lines[3] +def test_progressbar_item_show_func(runner, monkeypatch): + fake_clock = FakeClock() + + @click.command() + def cli(): + with click.progressbar(range(4), item_show_func=lambda x: "Custom {}".format(x)) as progress: + for _ in progress: + fake_clock.advance_time() + print("") + + monkeypatch.setattr(time, 'time', fake_clock.time) + monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True) + output = runner.invoke(cli, []).output + + lines = [line for line in output.split('\n') if '[' in line] + + assert 'Custom 0' in lines[0] + assert 'Custom 1' in lines[1] + assert 'Custom 2' in lines[2] + assert 'Custom None' in lines[3] + + +def test_progressbar_update_with_item_show_func(runner, monkeypatch): + fake_clock = FakeClock() + + @click.command() + def cli(): + with click.progressbar(length=6, item_show_func=lambda x: "Custom {}".format(x)) as progress: + while not progress.finished: + fake_clock.advance_time() + progress.update(2, progress.pos) + print("") + + monkeypatch.setattr(time, 'time', fake_clock.time) + monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True) + output = runner.invoke(cli, []).output + + lines = [line for line in output.split('\n') if '[' in line] + + assert 'Custom 0' in lines[0] + assert 'Custom 2' in lines[1] + assert 'Custom 4' in lines[2] + + @pytest.mark.parametrize( 'key_char', (u'h', u'H', u'é', u'À', u' ', u'字', u'àH', u'àR') )
Add `current_item` parameter to `ProgressBar.update()` When using a ProgressBar in manual update mode, we can call the `ProgressBar.update(n_steps)` method to update the progress bar. In this usage pattern, the `current_item` property doesn't get set, which means the `item_show_func` feature can't work as it should. I propose adding an optional `current_item` parameter to update, so update would look like this: ```python def update(self, n_steps, current_item=None): self.make_step(n_steps) if current_item is not None: self.current_item = current_item self.render_progress() ``` This would allow a usage pattern like this (adapted from click documentation): ```python with click.progressbar(length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive) ``` I can submit a PR for this if you don't see anything wrong with the idea.
2019-05-31T17:31:58Z
[]
[]
pallets/click
1,400
pallets__click-1400
[ "1376" ]
b24c51f34724e7cf531b88e5914f0036aab6b2ec
diff --git a/click/_compat.py b/click/_compat.py --- a/click/_compat.py +++ b/click/_compat.py @@ -504,9 +504,38 @@ def open_stream(filename, mode='r', encoding=None, errors='strict', # as a proxy in the same folder and then using the fdopen # functionality to wrap it in a Python file. Then we wrap it in an # atomic file that moves the file over on close. - import tempfile - fd, tmp_filename = tempfile.mkstemp(dir=os.path.dirname(filename), - prefix='.__atomic-write') + import errno + import random + + try: + perm = os.stat(filename).st_mode + except OSError: + perm = None + + flags = os.O_RDWR | os.O_CREAT | os.O_EXCL + if 'b' in mode: + flags |= getattr(os, 'O_BINARY', 0) + + while True: + tmp_filename = os.path.join( + os.path.dirname(filename), + '.__atomic-write%08x' % (random.randrange(1 << 32),), + ) + try: + fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) + break + except OSError as e: + if e.errno == errno.EEXIST or ( + os.name == "nt" + and e.errno == errno.EACCES + and os.path.isdir(dir) + and os.access(dir, os.W_OK) + ): + continue + raise + + if perm is not None: + os.chmod(tmp_filename, perm) # in case perm includes bits in umask if encoding is not None: f = io.open(fd, mode, encoding=encoding, errors=errors)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,4 +1,5 @@ import os +import stat import sys import pytest @@ -298,6 +299,48 @@ def cli(filename): assert result.output == 'foobar\nmeep\n' [email protected](WIN, reason='os.chmod() is not fully supported on Windows.') [email protected]('permissions', [ + 0o400, + 0o444, + 0o600, + 0o644, + ]) +def test_open_file_atomic_permissions_existing_file(runner, permissions): + with runner.isolated_filesystem(): + with open('existing.txt', 'w') as f: + f.write('content') + os.chmod('existing.txt', permissions) + + @click.command() + @click.argument('filename') + def cli(filename): + click.open_file(filename, 'w', atomic=True).close() + + result = runner.invoke(cli, ['existing.txt']) + assert result.exception is None + assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions + + [email protected](WIN, reason='os.stat() is not fully supported on Windows.') +def test_open_file_atomic_permissions_new_file(runner): + with runner.isolated_filesystem(): + @click.command() + @click.argument('filename') + def cli(filename): + click.open_file(filename, 'w', atomic=True).close() + + # Create a test file to get the expected permissions for new files + # according to the current umask. + with open('test.txt', 'w'): + pass + permissions = stat.S_IMODE(os.stat('test.txt').st_mode) + + result = runner.invoke(cli, ['new.txt']) + assert result.exception is None + assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions + + @pytest.mark.xfail(WIN and not PY2, reason='God knows ...') def test_iter_keepopenfile(tmpdir): expected = list(map(str, range(10)))
open_file(…, 'w', atomic=True) sets or resets permissions to 600, ignoring umask Files are normally created with permission `666 & umask` as expected: ```pycon >>> click.open_file('/tmp/test1', 'w').close() >>> oct(os.stat('/tmp/test1').st_mode) '0o100644' ``` However, opening a new or existing file with `atomic=True` sets or resets its permissions to `600` unconditionally: ```python >>> click.open_file('/tmp/test2', 'w', atomic=True).close() >>> oct(os.stat('/tmp/test2').st_mode) '0o100600' >>> click.open_file('/tmp/test1', 'w', atomic=True).close() >>> oct(os.stat('/tmp/test1').st_mode) '0o100600' ``` I’d expect a new file created with `atomic=True` to be created with the usual permission `666 & umask`, and an existing file opened with `atomic=True` to have the previous permissions preserved. (There’s probably no way to preserve permissions atomically; taking the previous permissions at the time of the initial open is fine.)
Could you please tell me the operating system you working with??
2019-09-19T05:07:46Z
[]
[]
pallets/click
1,402
pallets__click-1402
[ "1381" ]
b41940747860a13e1d12b54d2d55b0cec57f0ce3
diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -172,21 +172,29 @@ def confirm( If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. - .. versionadded:: 4.0 - Added the `err` parameter. - :param text: the question to ask. - :param default: the default for the prompt. + :param default: The default value to use when no input is given. If + ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. + + .. versionchanged:: 8.0 + Repeat until input is given if ``default`` is ``None``. + + .. versionadded:: 4.0 + Added the ``err`` parameter. """ prompt = _build_prompt( - text, prompt_suffix, show_default, "Y/n" if default else "y/N" + text, + prompt_suffix, + show_default, + "y/n" if default is None else ("Y/n" if default else "y/N"), ) + while 1: try: # Write the prompt separately so that we get nice @@ -199,7 +207,7 @@ def confirm( rv = True elif value in ("n", "no"): rv = False - elif value == "": + elif default is not None and value == "": rv = default else: echo("Error: invalid input", err=err)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -131,6 +131,14 @@ def test_no(): assert result.output == "Foo [Y/n]: n\nno :(\n" +def test_confirm_repeat(runner): + cli = click.Command( + "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)] + ) + result = runner.invoke(cli, input="\ny\n") + assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n" + + @pytest.mark.skipif(WIN, reason="Different behavior on windows.") def test_prompts_abort(monkeypatch, capsys): def f(_):
Option to reask on no input in `click.confirm` It would be nice if similarly to `click.prompt`, `click.confirm` would allow to reask the user if no input is given.
2019-09-30T17:23:37Z
[]
[]
pallets/click
1,455
pallets__click-1455
[ "1446" ]
7147f41d0fd6676a8c0410875f43250dc8e54dc8
diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -329,7 +329,9 @@ def _process_args_for_options(self, state): def _match_long_opt(self, opt, explicit_value, state): if opt not in self._long_opt: - possibilities = [word for word in self._long_opt if word.startswith(opt)] + from difflib import get_close_matches + + possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) option = self._long_opt[opt]
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -86,6 +86,22 @@ def cli(): assert f"no such option: {unknown_flag}" in result.output [email protected]( + ("value", "expect"), + [ + ("--cat", "Did you mean --count?"), + ("--bounds", "(Possible options: --bound, --count)"), + ("--bount", "(Possible options: --bound, --count)"), + ], +) +def test_suggest_possible_options(runner, value, expect): + cli = click.Command( + "cli", params=[click.Option(["--bound"]), click.Option(["--count"])] + ) + result = runner.invoke(cli, [value]) + assert expect in result.output + + def test_multiple_required(runner): @click.command() @click.option("-m", "--message", multiple=True, required=True)
Use difflib for potential suggestions in cli error messages Currently click only does startswith match at https://github.com/pallets/click/blob/6c454c88b76f7a0be396dba72513bd316cd141e6/click/parser.py#L328-L329 so a typo like using `--boun` suggests `--bount` but using `--bound` doesn't make any suggestions. Using [difflib.get_close_matches](https://docs.python.org/3/library/difflib.html#difflib.get_close_matches) could get better suggestions and nearest matches. Sample implementation : https://github.com/tirkarthi/click/tree/difflib-suggestions ```python import click @click.option("--count") @click.option("--bount") @click.command() def cli(count, bount): click.echo(f"count = {count}, bount = {bount}") if __name__ == "__main__": cli() ``` ```shell python sample.py --boun 1 Usage: sample.py [OPTIONS] Try "sample.py --help" for help. Error: no such option: --boun Did you mean --bount? ``` ```shell python sample.py --bound 1 Usage: sample.py [OPTIONS] Try "sample.py --help" for help. Error: no such option: --bound ``` Using `--bound` with `difflib.get_close_matches` ```shell python sample.py --bound 1 Usage: sample.py [OPTIONS] Try "sample.py --help" for help. Error: no such option: --bound (Possible options: --bount, --count) ``` Using `--counter` with `difflib.get_close_matches` ```shell python sample.py --counter 1 Usage: sample.py [OPTIONS] Try "sample.py --help" for help. Error: no such option: --counter (Possible options: --count, --bount) ```
2020-01-17T12:33:31Z
[]
[]
pallets/click
1,470
pallets__click-1470
[ "1026" ]
59a4530884570bbe3bd99e2b99ecfb08edb23974
diff --git a/click/_compat.py b/click/_compat.py --- a/click/_compat.py +++ b/click/_compat.py @@ -162,6 +162,8 @@ def seekable(self): iteritems = lambda x: x.iteritems() range_type = xrange + from pipes import quote as shlex_quote + def is_bytes(x): return isinstance(x, (buffer, bytearray)) @@ -268,6 +270,8 @@ def filename_to_ui(value): isidentifier = lambda x: x.isidentifier() iteritems = lambda x: iter(x.items()) + from shlex import quote as shlex_quote + def is_bytes(x): return isinstance(x, (bytes, memoryview, bytearray)) diff --git a/click/_termui_impl.py b/click/_termui_impl.py --- a/click/_termui_impl.py +++ b/click/_termui_impl.py @@ -16,9 +16,9 @@ import time import math import contextlib -from ._compat import _default_text_stdout, range_type, PY2, isatty, \ - open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \ - CYGWIN +from ._compat import _default_text_stdout, range_type, isatty, \ + open_stream, shlex_quote, strip_ansi, term_len, get_best_encoding, WIN, \ + int_types, CYGWIN from .utils import echo from .exceptions import ClickException @@ -328,7 +328,7 @@ def pager(generator, color=None): fd, filename = tempfile.mkstemp() os.close(fd) try: - if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: + if hasattr(os, 'system') and os.system("more %s" % shlex_quote(filename)) == 0: return _pipepager(generator, 'more', color) return _nullpager(stdout, generator, color) finally: @@ -396,7 +396,7 @@ def _tempfilepager(generator, cmd, color): with open_stream(filename, 'wb')[0] as f: f.write(text.encode(encoding)) try: - os.system(cmd + ' "' + filename + '"') + os.system("%s %s" % (shlex_quote(cmd), shlex_quote(filename))) finally: os.unlink(filename) @@ -441,8 +441,11 @@ def edit_file(self, filename): else: environ = None try: - c = subprocess.Popen('%s "%s"' % (editor, filename), - env=environ, shell=True) + c = subprocess.Popen( + "%s %s" % (shlex_quote(editor), shlex_quote(filename)), + env=environ, + shell=True + ) exit_code = c.wait() if exit_code != 0: raise ClickException('%s: Editing failed!' % editor) @@ -513,19 +516,16 @@ def _unquote_file(url): elif WIN: if locate: url = _unquote_file(url) - args = 'explorer /select,"%s"' % _unquote_file( - url.replace('"', '')) + args = "explorer /select,%s" % (shlex_quote(url),) else: - args = 'start %s "" "%s"' % ( - wait and '/WAIT' or '', url.replace('"', '')) + args = 'start %s "" %s' % ("/WAIT" if wait else "", shlex_quote(url)) return os.system(args) elif CYGWIN: if locate: url = _unquote_file(url) - args = 'cygstart "%s"' % (os.path.dirname(url).replace('"', '')) + args = "cygstart %s" % (shlex_quote(os.path.dirname(url)),) else: - args = 'cygstart %s "%s"' % ( - wait and '-w' or '', url.replace('"', '')) + args = "cygstart %s %s" % ("-w" if wait else "", shlex_quote(url)) return os.system(args) try:
diff --git a/tests/test_imports.py b/tests/test_imports.py --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -32,7 +32,7 @@ def tracking_import(module, locals=None, globals=None, fromlist=None, ALLOWED_IMPORTS = set([ 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib', 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io', - 'threading', 'colorama', 'errno', 'fcntl', 'datetime' + 'threading', 'colorama', 'errno', 'fcntl', 'datetime', 'pipes', 'shlex' ]) if WIN:
click.edit() Support Editor Paths Containing Spaces **Environment** * Python 3.6.5 * click 6.7 * Windows 7 When using click.edit(), an editor with a space in the path throws an error. For example : "C:\Program Files\Sublime Text 3\sublime_text.exe" If I put quotes around the path name in the subprocess.Popen call [here](https://github.com/pallets/click/blob/master/click/_termui_impl.py#L425) the problem is fixed. **Before** ```python c = subprocess.Popen('%s "%s"' % (editor, filename), env=environ, shell=True) ``` **After** ```python c = subprocess.Popen('"%s" "%s"' % (editor, filename), env=environ, shell=True) ```
I do not encounter an issue on Mac as I can escape the space and open Sublime Text 3. message = click.edit( text='\n\n' + '', editor='/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl') Releasing Issue, please feel free to take if you work specifically on Windows.
2020-02-15T20:40:43Z
[]
[]
pallets/click
1,478
pallets__click-1478
[ "1406" ]
70c449386b91261f4c5fa43b87f0a84692535525
diff --git a/click/core.py b/click/core.py --- a/click/core.py +++ b/click/core.py @@ -945,8 +945,7 @@ def format_options(self, ctx, formatter): for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: - part_a, part_b = rv - opts.append((part_a, part_b.replace('\n', ' '))) + opts.append(rv) if opts: with formatter.section('Options'): diff --git a/click/formatting.py b/click/formatting.py --- a/click/formatting.py +++ b/click/formatting.py @@ -198,12 +198,14 @@ def write_dl(self, rows, col_max=30, col_spacing=2): self.write(' ' * (first_col + self.current_indent)) text_width = max(self.width - first_col - 2, 10) - lines = iter(wrap_text(second, text_width).splitlines()) + wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) + lines = wrapped_text.splitlines() + if lines: - self.write(next(lines) + '\n') - for line in lines: - self.write('%*s%s\n' % ( - first_col + self.current_indent, '', line)) + self.write(lines[0] + '\n') + + for line in lines[1:]: + self.write('%*s%s\n' % (first_col + self.current_indent, '', line)) else: self.write('\n')
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -408,22 +408,30 @@ def cmd(foo): assert result.output == 'Apple\n' -def test_multiline_help(runner): - @click.command() - @click.option('--foo', help=""" - hello - - i am - - multiline - """) - def cmd(foo): - click.echo(foo) +def test_option_help_preserve_paragraphs(runner): + @click.command() + @click.option( + "-C", + "--config", + type=click.Path(), + help="""Configuration file to use. + + If not given, the environment variable CONFIG_FILE is consulted + and used if set. If neither are given, a default configuration + file is loaded.""", + ) + def cmd(config): + pass - result = runner.invoke(cmd, ['--help']) + result = runner.invoke(cmd, ['--help'], ) assert result.exit_code == 0 - out = result.output.splitlines() - assert ' --foo TEXT hello i am multiline' in out + assert ( + " -C, --config PATH Configuration file to use.\n" + "{i}\n" + "{i}If not given, the environment variable CONFIG_FILE is\n" + "{i}consulted and used if set. If neither are given, a default\n" + "{i}configuration file is loaded.".format(i=" " * 21) + ) in result.output def test_argument_custom_class(runner): class CustomArgument(click.Argument):
Make option format replace newlines with spaces. #834 Remade to point 7.x
Turns out the underlying `wrap_text` function already takes a `preserve_paragraphs` option, but it's not enabled for option help text right now. This enables the behavior in the command help text where `\n\n` is preserved and each paragraph is wrapped separately. I'll submit a new PR that rolls this change back and uses `preserve_paragraphs` instead.
2020-02-23T19:58:05Z
[]
[]
pallets/click
1,481
pallets__click-1481
[ "1267" ]
856f0b72c8d91d1abbdaff97eecb1528810f5eb2
diff --git a/click/core.py b/click/core.py --- a/click/core.py +++ b/click/core.py @@ -622,6 +622,9 @@ def __init__(self, name, context_settings=None): #: an optional dictionary with defaults passed to the context. self.context_settings = context_settings + def __repr__(self): + return "<%s %s>" % (self.__class__.__name__, self.name) + def get_usage(self, ctx): raise NotImplementedError('Base commands cannot get usage') @@ -1393,6 +1396,9 @@ def __init__(self, param_decls=None, type=None, required=False, self.envvar = envvar self.autocompletion = autocompletion + def __repr__(self): + return "<%s %s>" % (self.__class__.__name__, self.name) + @property def human_readable_name(self): """Returns the human readable name of this parameter. This is the
diff --git a/tests/test_basic.py b/tests/test_basic.py --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -23,6 +23,24 @@ def cli(): assert result.exit_code == 0 +def test_repr(): + @click.command() + def command(): + pass + + @click.group() + def group(): + pass + + @group.command() + def subcommand(): + pass + + assert repr(command) == '<Command command>' + assert repr(group) == '<Group group>' + assert repr(subcommand) == '<Command subcommand>' + + def test_return_values(): @click.command() def cli():
Friendly __repr__ for Command ```python (Pdb) pp cmd <click.core.Command object at 0x7ff869ef1550> (Pdb) pp cmd.name 'run-gunicorn' ``` What do you think of showing the command name in the `__repr__` string, for friendlier debugging? Could be a good beginner-friendly issue!
I'm going to take a stab at this
2020-02-24T15:49:09Z
[]
[]
pallets/click
1,535
pallets__click-1535
[ "1530" ]
d15d0cdf4f59ea0a0bf6f8a82449e042bc5f9732
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1,3 +1,4 @@ +import enum import errno import inspect import os @@ -132,36 +133,25 @@ def sort_key(item): return sorted(declaration_order, key=sort_key) -class ParameterSource: - """This is an enum that indicates the source of a command line parameter. +class ParameterSource(enum.Enum): + """This is an :class:`~enum.Enum` that indicates the source of a + parameter's value. - The enum has one of the following values: COMMANDLINE, - ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the - default value in the decorator was used. This class should be - converted to an enum when Python 2 support is dropped. - """ - - COMMANDLINE = "COMMANDLINE" - ENVIRONMENT = "ENVIRONMENT" - DEFAULT = "DEFAULT" - DEFAULT_MAP = "DEFAULT_MAP" + Use :meth:`click.Context.get_parameter_source` to get the + source for a parameter by name. - VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP} - - @classmethod - def validate(cls, value): - """Validate that the specified value is a valid enum. + .. versionchanged:: 8.0 + Use :class:`~enum.Enum` and drop the ``validate`` method. + """ - This method will raise a ValueError if the value is - not a valid enum. - - :param value: the string value to verify - """ - if value not in cls.VALUES: - raise ValueError( - f"Invalid ParameterSource value: {value!r}. Valid" - f" values are: {','.join(cls.VALUES)}" - ) + COMMANDLINE = enum.auto() + """The value was provided by the command line args.""" + ENVIRONMENT = enum.auto() + """The value was provided with an environment variable.""" + DEFAULT = enum.auto() + """Used the default specified by the parameter.""" + DEFAULT_MAP = enum.auto() + """Used a default provided by :attr:`Context.default_map`.""" class Context: @@ -417,7 +407,7 @@ def __init__( self._close_callbacks = [] self._depth = 0 - self._source_by_paramname = {} + self._parameter_source = {} self._exit_stack = ExitStack() def to_info_dict(self): @@ -728,33 +718,27 @@ def forward(*args, **kwargs): # noqa: B902 return self.invoke(cmd, **kwargs) def set_parameter_source(self, name, source): - """Set the source of a parameter. - - This indicates the location from which the value of the - parameter was obtained. + """Set the source of a parameter. This indicates the location + from which the value of the parameter was obtained. - :param name: the name of the command line parameter - :param source: the source of the command line parameter, which - should be a valid ParameterSource value + :param name: The name of the parameter. + :param source: A member of :class:`~click.core.ParameterSource`. """ - ParameterSource.validate(source) - self._source_by_paramname[name] = source + self._parameter_source[name] = source def get_parameter_source(self, name): - """Get the source of a parameter. + """Get the source of a parameter. This indicates the location + from which the value of the parameter was obtained. - This indicates the location from which the value of the - parameter was obtained. This can be useful for determining - when a user specified an option on the command line that is - the same as the default. In that case, the source would be - ParameterSource.COMMANDLINE, even though the value of the - parameter was equivalent to the default. + This can be useful for determining when a user specified a value + on the command line that is the same as the default value. It + will be :attr:`~click.core.ParameterSource.DEFAULT` only if the + value was actually taken from the default. - :param name: the name of the command line parameter - :returns: the source + :param name: The name of the parameter. :rtype: ParameterSource """ - return self._source_by_paramname[name] + return self._parameter_source[name] class BaseCommand: @@ -1933,14 +1917,18 @@ def add_to_parser(self, parser, ctx): def consume_value(self, ctx, opts): value = opts.get(self.name) source = ParameterSource.COMMANDLINE + if value is None: value = self.value_from_envvar(ctx) source = ParameterSource.ENVIRONMENT + if value is None: value = ctx.lookup_default(self.name) source = ParameterSource.DEFAULT_MAP + if value is not None: ctx.set_parameter_source(self.name, source) + return value def type_cast_value(self, ctx, value):
diff --git a/tests/test_context.py b/tests/test_context.py --- a/tests/test_context.py +++ b/tests/test_context.py @@ -297,63 +297,48 @@ def cli(ctx): assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0 -def test_parameter_source_default(runner): [email protected]( + ("option_args", "invoke_args", "expect"), + [ + pytest.param({}, {}, ParameterSource.DEFAULT, id="default"), + pytest.param( + {}, + {"default_map": {"option": 1}}, + ParameterSource.DEFAULT_MAP, + id="default_map", + ), + pytest.param( + {}, + {"args": ["-o", "1"]}, + ParameterSource.COMMANDLINE, + id="commandline short", + ), + pytest.param( + {}, + {"args": ["--option", "1"]}, + ParameterSource.COMMANDLINE, + id="commandline long", + ), + pytest.param( + {}, + {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}}, + ParameterSource.ENVIRONMENT, + id="environment auto", + ), + pytest.param( + {"envvar": "NAME"}, + {"env": {"NAME": "1"}}, + ParameterSource.ENVIRONMENT, + id="environment manual", + ), + ], +) +def test_parameter_source(runner, option_args, invoke_args, expect): @click.command() @click.pass_context - @click.option("-o", "--option", default=1) + @click.option("-o", "--option", default=1, **option_args) def cli(ctx, option): - click.echo(ctx.get_parameter_source("option")) + return ctx.get_parameter_source("option") - rv = runner.invoke(cli) - assert rv.output.rstrip() == ParameterSource.DEFAULT - - -def test_parameter_source_default_map(runner): - @click.command() - @click.pass_context - @click.option("-o", "--option", default=1) - def cli(ctx, option): - click.echo(ctx.get_parameter_source("option")) - - rv = runner.invoke(cli, default_map={"option": 1}) - assert rv.output.rstrip() == ParameterSource.DEFAULT_MAP - - -def test_parameter_source_commandline(runner): - @click.command() - @click.pass_context - @click.option("-o", "--option", default=1) - def cli(ctx, option): - click.echo(ctx.get_parameter_source("option")) - - rv = runner.invoke(cli, ["-o", "1"]) - assert rv.output.rstrip() == ParameterSource.COMMANDLINE - rv = runner.invoke(cli, ["--option", "1"]) - assert rv.output.rstrip() == ParameterSource.COMMANDLINE - - -def test_parameter_source_environment(runner): - @click.command() - @click.pass_context - @click.option("-o", "--option", default=1) - def cli(ctx, option): - click.echo(ctx.get_parameter_source("option")) - - rv = runner.invoke(cli, auto_envvar_prefix="TEST", env={"TEST_OPTION": "1"}) - assert rv.output.rstrip() == ParameterSource.ENVIRONMENT - - -def test_parameter_source_environment_variable_specified(runner): - @click.command() - @click.pass_context - @click.option("-o", "--option", default=1, envvar="NAME") - def cli(ctx, option): - click.echo(ctx.get_parameter_source("option")) - - rv = runner.invoke(cli, env={"NAME": "1"}) - assert rv.output.rstrip() == ParameterSource.ENVIRONMENT - - -def test_validate_parameter_source(): - with pytest.raises(ValueError): - ParameterSource.validate("NOT_A_VALID_PARAMETER_SOURCE") + rv = runner.invoke(cli, standalone_mode=False, **invoke_args) + assert rv.return_value == expect diff --git a/tests/test_imports.py b/tests/test_imports.py --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -45,7 +45,7 @@ def tracking_import(module, locals=None, globals=None, fromlist=None, "errno", "fcntl", "datetime", - "pipes", + "enum", } if WIN:
Make ParameterSource an Enum `core.ParameterSource` was implemented as fake enum for compatibility with Python 2. Replace this with a simple `enum.Enum` now that we support Python >= 3.6. Can remove the `ParameterSource.validate` method too, it was just for ensuring the enum values were used.
I'd like to work on this! Go for it, no need to comment first! :-) I just merged a big PR, so make sure your repo is up to date before you start.
2020-04-20T18:14:15Z
[]
[]
pallets/click
1,543
pallets__click-1543
[ "1514" ]
a6b10db3882fe464898f1ffaa6fbba6fc390f894
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -174,8 +174,6 @@ def seekable(self): iteritems = lambda x: x.iteritems() range_type = xrange - from pipes import quote as shlex_quote - def is_bytes(x): return isinstance(x, (buffer, bytearray)) @@ -284,8 +282,6 @@ def filename_to_ui(value): isidentifier = lambda x: x.isidentifier() iteritems = lambda x: iter(x.items()) - from shlex import quote as shlex_quote - def is_bytes(x): return isinstance(x, (bytes, memoryview, bytearray)) diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -17,7 +17,6 @@ from ._compat import isatty from ._compat import open_stream from ._compat import range_type -from ._compat import shlex_quote from ._compat import strip_ansi from ._compat import term_len from ._compat import WIN @@ -346,10 +345,7 @@ def pager(generator, color=None): fd, filename = tempfile.mkstemp() os.close(fd) try: - if ( - hasattr(os, "system") - and os.system("more {}".format(shlex_quote(filename))) == 0 - ): + if hasattr(os, "system") and os.system('more "{}"'.format(filename)) == 0: return _pipepager(generator, "more", color) return _nullpager(stdout, generator, color) finally: @@ -418,7 +414,7 @@ def _tempfilepager(generator, cmd, color): with open_stream(filename, "wb")[0] as f: f.write(text.encode(encoding)) try: - os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename))) + os.system('{} "{}"'.format(cmd, filename)) finally: os.unlink(filename) @@ -463,9 +459,7 @@ def edit_file(self, filename): environ = None try: c = subprocess.Popen( - "{} {}".format(shlex_quote(editor), shlex_quote(filename)), - env=environ, - shell=True, + '{} "{}"'.format(editor, filename), env=environ, shell=True, ) exit_code = c.wait() if exit_code != 0: @@ -536,16 +530,18 @@ def _unquote_file(url): elif WIN: if locate: url = _unquote_file(url) - args = "explorer /select,{}".format(shlex_quote(url)) + args = 'explorer /select,"{}"'.format(_unquote_file(url.replace('"', ""))) else: - args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url)) + args = 'start {} "" "{}"'.format( + "/WAIT" if wait else "", url.replace('"', "") + ) return os.system(args) elif CYGWIN: if locate: url = _unquote_file(url) - args = "cygstart {}".format(shlex_quote(os.path.dirname(url))) + args = 'cygstart "{}"'.format(os.path.dirname(url).replace('"', "")) else: - args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url)) + args = 'cygstart {} "{}"'.format("-w" if wait else "", url.replace('"', "")) return os.system(args) try:
diff --git a/tests/test_imports.py b/tests/test_imports.py --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -49,7 +49,6 @@ def tracking_import(module, locals=None, globals=None, fromlist=None, "fcntl", "datetime", "pipes", - "shlex", } if WIN:
echo_via_pager broken on Windows in 7.1 Calls to `click.echo_via_pager` are failing on Windows since upgrading to 7.1 ### Expected behavior (7.0) ``` Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import click >>> click.__version__ '7.0' >>> text = [f"hello {i} \n" for i in range(1000)] >>> click.echo_via_pager(text) hello 0 hello 1 hello 2 hello 3 hello 4 -- MORE -- ``` ### Actual behavior (7.1) ``` Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import click >>> click.__version__ '7.1.1' >>> text = [f"hello {i} \n" for i in range(1000)] >>> click.echo_via_pager(text) The system cannot find the file specified. >>> ``` ## Notes - Only seems broken on Windows: tested with Ubuntu WSL and click 7.1, works as expected ### Environment * Python version: 3.7, 3.8 (same results) * Click version: 7.1.1
Same issue as [here](https://github.com/dbcli/pgcli/issues/1167) - and same root cause: ```python >>> os.environ['PAGER'] = 'less -SRXF' >>> import click >>> text = [f"hello {i} \n" for i in range(1000)] >>> click.echo_via_pager(text) The system cannot find the file specified. >>> os.environ['PAGER'] = 'less' >>> click.echo_via_pager(text) hello 0 hello 1 hello 2 hello 3 [...] ``` `click.edit()` exhibits the same problem Due to #1470. I'll see about reverting that or fixing it on Windows.
2020-04-27T19:32:20Z
[]
[]
pallets/click
1,549
pallets__click-1549
[ "1548" ]
c067af761a70a6cbb91fa49083a41511207297da
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1,6 +1,5 @@ import enum import errno -import inspect import os import sys from contextlib import contextmanager @@ -613,15 +612,23 @@ def ensure_object(self, object_type): self.obj = rv = object_type() return rv - def lookup_default(self, name): - """Looks up the default for a parameter name. This by default - looks into the :attr:`default_map` if available. + def lookup_default(self, name, call=True): + """Get the default for a parameter from :attr:`default_map`. + + :param name: Name of the parameter. + :param call: If the default is a callable, call it. Disable to + return the callable instead. + + .. versionchanged:: 8.0 + Added the ``call`` parameter. """ if self.default_map is not None: - rv = self.default_map.get(name) - if callable(rv): - rv = rv() - return rv + value = self.default_map.get(name) + + if call and callable(value): + return value() + + return value def fail(self, message): """Aborts the execution of the program with a specific error @@ -1920,14 +1927,33 @@ def make_metavar(self): metavar += "..." return metavar - def get_default(self, ctx): - """Given a context variable this calculates the default value.""" - # Otherwise go with the regular default. - if callable(self.default): - rv = self.default() - else: - rv = self.default - return self.type_cast_value(ctx, rv) + def get_default(self, ctx, call=True): + """Get the default for the parameter. Tries + :meth:`Context.lookup_value` first, then the local default. + + :param ctx: Current context. + :param call: If the default is a callable, call it. Disable to + return the callable instead. + + .. versionchanged:: 8.0 + Looks at ``ctx.default_map`` first. + + .. versionchanged:: 8.0 + Added the ``call`` parameter. + """ + value = ctx.lookup_default(self.name, call=False) + + if value is None: + value = self.default + + if callable(value): + if not call: + # Don't type cast the callable. + return value + + value = value() + + return self.type_cast_value(ctx, value) def add_to_parser(self, parser, ctx): pass @@ -2355,12 +2381,15 @@ def _write_opts(opts): else envvar ) extra.append(f"env var: {var_str}") - if self.default is not None and (self.show_default or ctx.show_default): + + default_value = self.get_default(ctx, call=False) + + if default_value is not None and (self.show_default or ctx.show_default): if isinstance(self.show_default, str): default_string = f"({self.show_default})" - elif isinstance(self.default, (list, tuple)): - default_string = ", ".join(str(d) for d in self.default) - elif inspect.isfunction(self.default): + elif isinstance(default_value, (list, tuple)): + default_string = ", ".join(str(d) for d in default_value) + elif callable(default_value): default_string = "(dynamic)" elif self.is_bool_flag and self.secondary_opts: # For boolean flags that have distinct True/False opts, @@ -2369,7 +2398,8 @@ def _write_opts(opts): (self.opts if self.default else self.secondary_opts)[0] )[1] else: - default_string = self.default + default_string = default_value + extra.append(f"default: {default_string}") if isinstance(self.type, _NumberRangeBase): @@ -2386,7 +2416,7 @@ def _write_opts(opts): return ("; " if any_prefix_is_slash else " / ").join(rv), help - def get_default(self, ctx): + def get_default(self, ctx, call=True): # If we're a non boolean flag our default is more complex because # we need to look at all flags in the same group to figure out # if we're the the default one in which case we return the flag @@ -2395,9 +2425,10 @@ def get_default(self, ctx): for param in ctx.command.params: if param.name == self.name and param.default: return param.flag_value + return None - return super().get_default(ctx) + return super().get_default(ctx, call=call) def prompt_for_value(self, ctx): """This is an alternative flow that can be activated in the full
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -188,6 +188,18 @@ def cmd(arg, arg2): assert "1, 2" in result.output +def test_show_default_default_map(runner): + @click.command() + @click.option("--arg", default="a", show_default=True) + def cmd(arg): + click.echo(arg) + + result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"}) + + assert not result.exception + assert "[default: b]" in result.output + + def test_multiple_default_type(): opt = click.Option(["-a"], multiple=True, default=(1, 2)) assert opt.nargs == 1
show_default and default_map don't play nice together ```python #!/usr/bin/env python import click @click.command(context_settings={ "show_default": True, "default_map": {"a": "b"} }) @click.option("-a", default="c") def func(a): print(a) if __name__ == "__main__": func() ``` ```console $ # This is expected $ ./cli.py b $ # This is not (default should be b) $ ./cli.py --help Usage: cli.py [OPTIONS] Options: -a TEXT [default: c] --help Show this message and exit. [default: False] ``` ### Expected Behavior I expect the default shown to be identical to the one being used. ### Actual Behavior The default shown was the value provided as `default`, without taking the `default_map` into account ### Environment * Python version: 3.7 * Click version: ``click==7.1.2``
I may be able to make a failing test or a PR if you point me to the right direction. Would calling `lookup_default` instead of `.default` in this line be enough ? https://github.com/pallets/click/blob/bce4ea4ba54e15959cb412d6793634e0c9b24491/src/click/core.py#L1936 Seems plausible, happy to review a PR. Ok, I'll try to remember to communicate here whether it happens or not. If I have neither said nor committed anything by May 17th, assume I have forgotten about it and you're free to go :)
2020-05-09T23:02:11Z
[]
[]
pallets/click
1,566
pallets__click-1566
[ "1565" ]
0ad4e7985a919041ec590a4d672afb44f05dd162
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -173,21 +173,6 @@ class Context: A context can be used as context manager in which case it will call :meth:`close` on teardown. - .. versionadded:: 2.0 - Added the `resilient_parsing`, `help_option_names`, - `token_normalize_func` parameters. - - .. versionadded:: 3.0 - Added the `allow_extra_args` and `allow_interspersed_args` - parameters. - - .. versionadded:: 4.0 - Added the `color`, `ignore_unknown_options`, and - `max_content_width` parameters. - - .. versionadded:: 7.1 - Added the `show_default` parameter. - :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this @@ -242,9 +227,28 @@ class Context: codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. - :param show_default: if True, shows defaults for all options. - Even if an option is later created with show_default=False, - this command-level setting overrides it. + :param show_default: Show defaults for all options. If not set, + defaults to the value from a parent context. Overrides an + option's ``show_default`` argument. + + .. versionchanged:: 8.0 + The ``show_default`` parameter defaults to the value from the + parent context. + + .. versionchanged:: 7.1 + Added the ``show_default`` parameter. + + .. versionchanged:: 4.0 + Added the ``color``, ``ignore_unknown_options``, and + ``max_content_width`` parameters. + + .. versionchanged:: 3.0 + Added the ``allow_extra_args`` and ``allow_interspersed_args`` + parameters. + + .. versionchanged:: 2.0 + Added the ``resilient_parsing``, ``help_option_names``, and + ``token_normalize_func`` parameters. """ #: The formatter class to create with :meth:`make_formatter`. @@ -398,6 +402,10 @@ def __init__( #: Controls if styling output is wanted or not. self.color = color + if show_default is None and parent is not None: + show_default = parent.show_default + + #: Show option default values when formatting help text. self.show_default = show_default self._close_callbacks = []
diff --git a/tests/test_context.py b/tests/test_context.py --- a/tests/test_context.py +++ b/tests/test_context.py @@ -267,6 +267,20 @@ def test2(ctx, foo): assert result.output == "foocmd\n" +def test_propagate_show_default_setting(runner): + """A context's ``show_default`` setting defaults to the value from + the parent context. + """ + group = click.Group( + commands={ + "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]), + }, + context_settings={"show_default": True}, + ) + result = runner.invoke(group, ["sub", "--help"]) + assert "[default: a]" in result.output + + def test_exit_not_standalone(): @click.command() @click.pass_context
show_default in group's context_settings not propagated to subcommands ### Expected Behavior #1018 and #1225 seems to have fixed supporting a global `show_default` option via context settings, but in Click 7.1.2, it doesn't cover my use case yet. I thought the following should work with 7.1+: ```python import click @click.group(context_settings={ 'show_default': True, 'help_option_names': ['-x', '--xhelp'], }) @click.pass_context def main(ctx): print('==== main ====') print(ctx.show_default) print(ctx.help_option_names) @main.command() @click.option('-v', '--value', type=int, default=123, help='some value') @click.pass_context def do(ctx, value): print('==== do ====') print(ctx.show_default) print(ctx.help_option_names) print('----') print(value) main() ``` ```console $ python test-click.py -x Usage: test-click.py [OPTIONS] COMMAND [ARGS]... Options: -x, --xhelp Show this message and exit. [default: False] Commands: do $ python test-click.py do -x ==== main ==== True ['-x', '--xhelp'] Usage: test-click.py do [OPTIONS] Options: -v, --value INTEGER some value [default: 123] -x, --xhelp Show this message and exit. $ python test-click.py do ==== main ==== True ['-x', '--xhelp'] ==== do ==== True ['-x', '--xhelp'] ---- 123 ``` ### Actual Behavior But the current implementation seems to loose the value of `show_default` when "going into" subcommands. ```console $ python test-click.py -x Usage: test-click.py [OPTIONS] COMMAND [ARGS]... Options: -x, --xhelp Show this message and exit. [default: False] Commands: do $ python test-click.py do -x ==== main ==== True ['-x', '--xhelp'] Usage: test-click.py do [OPTIONS] Options: -v, --value INTEGER some value -x, --xhelp Show this message and exit. $ python test-click.py do ==== main ==== True ['-x', '--xhelp'] ==== do ==== None ['-x', '--xhelp'] ---- 123 ``` ### Environment * Python version: 3.8.3 * Click version: 7.1.2
2020-05-29T09:41:51Z
[]
[]
pallets/click
1,591
pallets__click-1591
[ "1590" ]
dfb842d95a7c146d8fe8140c8100065410d95c4d
diff --git a/src/click/_winconsole.py b/src/click/_winconsole.py --- a/src/click/_winconsole.py +++ b/src/click/_winconsole.py @@ -284,7 +284,7 @@ def _is_console(f): try: fileno = f.fileno() - except OSError: + except (OSError, io.UnsupportedOperation): return False handle = msvcrt.get_osfhandle(fileno)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -261,6 +261,12 @@ def emulate_input(text): assert err == "Pause to stderr\n" +def test_echo_with_capsys(capsys): + click.echo("Capture me.") + out, err = capsys.readouterr() + assert out == "Capture me.\n" + + def test_open_file(runner): @click.command() @click.argument("filename")
click.echo() raises UnsupportedOperation on Windows when using pytest capsys ### Actual behavior When using `click.echo()` in a test function that uses the pytest `capsys` fixture, it raises `UnsupportedOperation` on Windows. It runs fine on Linux and macOS. Here is a complete test module `tests/unit/test_error_click.py` that reproduces the issue: ``` import click import pytest def myfunc(): """Function to be tested""" click.echo('bla') def test_myfunc(capsys): myfunc() stdout, stderr = capsys.readouterr() assert stdout == 'bla\n' ``` Here is the failure on Windows (using Python 2.7): ``` $ pytest tests . . . _________________________________ test_myfunc _________________________________ capsys = <_pytest.capture.CaptureFixture object at 0x04865830> def test_myfunc(capsys): > myfunc() tests\unit\test_error_click.py:15: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ tests\unit\test_error_click.py:11: in myfunc click.echo('bla') .tox\win64_py27_32\lib\site-packages\click\utils.py:230: in echo file = _default_text_stdout() .tox\win64_py27_32\lib\site-packages\click\_compat.py:760: in func rv = wrapper_func() .tox\win64_py27_32\lib\site-packages\click\_compat.py:256: in get_text_stdout rv = _get_windows_console_stream(sys.stdout, encoding, errors) .tox\win64_py27_32\lib\site-packages\click\_winconsole.py:356: in _get_windows_console_stream and _is_console(f) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ f = <_pytest.compat.CaptureIO object at 0x049156F0> def _is_console(f): if not hasattr(f, "fileno"): return False try: > fileno = f.fileno() E UnsupportedOperation: fileno .tox\win64_py27_32\lib\site-packages\click\_winconsole.py:343: UnsupportedOperation ``` This is from this Appveyor run on Python 2.7: https://ci.appveyor.com/project/KSchopmeyer/pywbemtools/builds/33566529/job/j22nqi2rq10f7uk2#L1463 It also happens on Python 3.8: https://ci.appveyor.com/project/KSchopmeyer/pywbemtools/builds/33566529/job/0mo646j7ck1yidhs#L1473 ### Expected behavior This should succeed on Windows as it does on Linux and macOS. ### Possible solutions I think `UnsupportedOperation` should be tolerated in the call to `f.fileno()` in `_winconsole._is_console()`. This seems to be done in other people's code calling fileno(), too: https://www.programcreek.com/python/example/17474/io.UnsupportedOperation ### Environment * Python version: 2.7, 3.8 * Click version: 7.1.2
2020-06-17T03:19:15Z
[]
[]
pallets/click
1,594
pallets__click-1594
[ "1465" ]
e8de91d9955ca5a96cf130f24c113ba904b1e9e9
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1840,6 +1840,11 @@ def _parse_decls(self, decls, expose_value): second = second.lstrip() if second: secondary_opts.append(second.lstrip()) + if first == second: + raise ValueError( + f"Boolean option {decl!r} cannot use the" + " same flag for true/false." + ) else: possible_names.append(split_opt(decl)) opts.append(decl)
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -565,3 +565,8 @@ def cmd(**kwargs): if form.startswith("-"): result = runner.invoke(cmd, [form]) assert result.output == "True\n" + + +def test_flag_duplicate_names(runner): + with pytest.raises(ValueError, match="cannot use the same flag for true/false"): + click.Option(["--foo/--foo"], default=False)
Duplicate Boolean flag options "--foo/--foo" are not detected (defaults to False) I ran into an issue where I had the code: @click.option( "--print-verbose-info/--print-verbose-info", help="...", default=False ) ...and running `cli.py --print-verbose-info` was apparently defaulting over to the `False` value. Totally my mistake (it should have been `--no-print-verbose-info`), but it'd be nice to get a warning/error for boolean values which match exactly (ie: cannot be set to true). It was kindof tricky to diagnose b/c I assumed that the `--print-verbose-info` that I was passing on the CLI was triggering the `True` path, not the `False` path, and usually Click option parsing is pretty bulletproof so it took a while to find that copy/paste problem. This would be a `good-first-issue`, I'm submitting it now more as a reminder to maybe follow-up on it and figure out the appropriate P.R.
untested, but probably something like this? ``` diff --git a/click/core.py b/click/core.py index 36004fe..edddd9f 100644 --- a/click/core.py +++ b/click/core.py @@ -1731,6 +1731,8 @@ class Option(Parameter): second = second.lstrip() if second: secondary_opts.append(second.lstrip()) + if first == second: + raise TypeError('Boolean options cannot use the same flag for true and false.') else: possible_names.append(split_opt(decl)) opts.append(decl) ``` I will work on this
2020-06-18T12:46:32Z
[]
[]
pallets/click
1,604
pallets__click-1604
[ "729" ]
6271cee2e8b2cf9a392377271bc9ed8345ce77c8
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1624,12 +1624,26 @@ def full_process_value(self, ctx, value): if value is None and not ctx.resilient_parsing: value = self.get_default(ctx) + if value is not None: ctx.set_parameter_source(self.name, ParameterSource.DEFAULT) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) + # For bounded nargs (!= -1), validate the number of values. + if ( + not ctx.resilient_parsing + and self.nargs > 1 + and self.nargs != len(value) + and isinstance(value, (tuple, list)) + ): + were = "was" if len(value) == 1 else "were" + ctx.fail( + f"Argument {self.name!r} takes {self.nargs} values but" + f" {len(value)} {were} given." + ) + return value def resolve_envvar_value(self, ctx): diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -183,6 +183,10 @@ def process(self, value, state): raise BadArgumentUsage( f"argument {self.dest} takes {self.nargs} values" ) + + if self.nargs == -1 and self.obj.envvar is not None: + value = None + state.opts[self.dest] = value state.order.append(self.obj)
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -18,7 +18,7 @@ def copy(src, dst): assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"] -def test_nargs_default(runner): +def test_argument_unbounded_nargs_cant_have_default(runner): with pytest.raises(TypeError, match="nargs=-1"): @click.command() @@ -163,26 +163,31 @@ def inout(output): assert result.output == "Foo bar baz\n" -def test_nargs_envvar(runner): - @click.command() - @click.option("--arg", nargs=2) - def cmd(arg): - click.echo("|".join(arg)) - - result = runner.invoke( - cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"} - ) - assert not result.exception - assert result.output == "foo|bar\n" [email protected]( + ("nargs", "value", "code", "output"), + [ + (2, "", 2, "Argument 'arg' takes 2 values but 0 were given."), + (2, "a", 2, "Argument 'arg' takes 2 values but 1 was given."), + (2, "a b", 0, "len 2"), + (2, "a b c", 2, "Argument 'arg' takes 2 values but 3 were given."), + (-1, "a b c", 0, "len 3"), + (-1, "", 0, "len 0"), + ], +) +def test_nargs_envvar(runner, nargs, value, code, output): + if nargs == -1: + param = click.argument("arg", envvar="X", nargs=nargs) + else: + param = click.option("--arg", envvar="X", nargs=nargs) @click.command() - @click.option("--arg", envvar="X", nargs=2) + @param def cmd(arg): - click.echo("|".join(arg)) + click.echo(f"len {len(arg)}") - result = runner.invoke(cmd, [], env={"X": "foo bar"}) - assert not result.exception - assert result.output == "foo|bar\n" + result = runner.invoke(cmd, env={"X": value}) + assert result.exit_code == code + assert output in result.output def test_empty_nargs(runner): @@ -303,3 +308,23 @@ def test_multiple_param_decls_not_allowed(runner): @click.argument("x", click.Choice(["a", "b"])) def copy(x): click.echo(x) + + [email protected]( + ("value", "code", "output"), + [ + ((), 2, "Argument 'arg' takes 2 values but 0 were given."), + (("a",), 2, "Argument 'arg' takes 2 values but 1 was given."), + (("a", "b"), 0, "len 2"), + (("a", "b", "c"), 2, "Argument 'arg' takes 2 values but 3 were given."), + ], +) +def test_nargs_default(runner, value, code, output): + @click.command() + @click.argument("arg", nargs=2, default=value) + def cmd(arg): + click.echo(f"len {len(arg)}") + + result = runner.invoke(cmd) + assert result.exit_code == code + assert output in result.output
Can't mix nargs=-1 with envvar `@click.argument(name, nargs=2, envvar=NAME)` Works as expected. If you set `NAME="a b"` and run your command `name` in the called function will be a tuple of `('a', 'b')`. `@click.argument(name, nargs=-1, envvar=NAME)` on the other hand doesn't work as expected. If you call it in the same exact way, `name` will be set to the empty tuple.
Thanks! Looks like there may be a couple bugs around this behavior. my test code to reproduce ```python @click.group() def cli(): pass @cli.command(short_help='test') @click.argument('src', nargs=-1, envvar="TEST") def testing(src): click.echo("src") click.echo(src) click.echo("len %s" % len(src)) click.echo("type %s" % type(src)) for c,v in enumerate(src): click.echo('elemenet %s of src: %s ' % (c,v)) cli() ``` case above nargs=-1 gives an empty tuple ``` TEST="one two three 4" python repo.py testing src () len 0 type <class 'tuple'> ``` if we run with nargs=2 shouldn't become a 4-tuple (the correct behavior here is a bit ambiguous) ``` TEST="one two three 4" python repo.py testing src ('one', 'two', 'three', '4') len 4 type <class 'tuple'> elemenet 0 of src: one elemenet 1 of src: two elemenet 2 of src: three elemenet 3 of src: 4 ```
2020-06-25T17:34:29Z
[]
[]
pallets/click
1,606
pallets__click-1606
[ "1605" ]
a11a5da0a8459f4098ec884b7cc52534336856db
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -497,11 +497,15 @@ class BoolParamType(ParamType): def convert(self, value, param, ctx): if isinstance(value, bool): return bool(value) - value = value.lower() - if value in {"1", "true", "t", "yes", "y", "on"}: + + norm = value.strip().lower() + + if norm in {"1", "true", "t", "yes", "y", "on"}: return True - elif value in {"0", "false", "f", "no", "n", "off"}: + + if norm in {"0", "false", "f", "no", "n", "off"}: return False + self.fail(f"{value!r} is not a valid boolean value.", param, ctx) def __repr__(self):
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -164,6 +164,17 @@ def cmd(arg): assert result.output == "foo|bar\n" +def test_trailing_blanks_boolean_envvar(runner): + @click.command() + @click.option("--shout/--no-shout", envvar="SHOUT") + def cli(shout): + click.echo(f"shout: {shout!r}") + + result = runner.invoke(cli, [], env={"SHOUT": " true "}) + assert result.exit_code == 0 + assert result.output == "shout: True\n" + + def test_multiple_default_help(runner): @click.command() @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)
Trailing blanks in envvars of boolean options cause otherwise valid values to be rejected ### Actual Behavior When defining a boolean option that also can be set via envvar, trailing blanks in the envvar value cause otherwise valid values to be rejected with this error message: ``` Error: Invalid value for '--something': true is not a valid boolean ``` Because the value is shown in the error message unquoted, the trailing blank cannot easily be seen, but it is there. Why is this an issue? Invoking the command on Linux/macOS as follows does not trigger the issue: ``` $ SOMETHING=true command ``` However, invoking it like this on Windows does trigger the issue: ``` > set SOMETHING=true & command ``` Apparently, Windows sets the envvar with a trailing blank in this case. The issue can be circumvented like this: ``` > set SOMETHING=true& command ``` Here is the code that causes this behavior: click/types.py at line 406: ``` class BoolParamType(ParamType): name = "boolean" def convert(self, value, param, ctx): if isinstance(value, bool): return bool(value) value = value.lower() if value in ("true", "t", "1", "yes", "y"): return True elif value in ("false", "f", "0", "no", "n"): return False self.fail("{!r} is not a valid boolean".format(value), param, ctx) def __repr__(self): return "BOOL" ``` ### Expected Behavior I would like to see click strip any leading or trailing blanks from the boolean envvar before it is evaluated. ### Environment * Python version: any * Click version: 7.1.2
2020-06-28T20:14:45Z
[]
[]
pallets/click
1,609
pallets__click-1609
[ "1603" ]
82ca854f587af919789a9baae9a732fe0ce0052c
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -25,6 +25,7 @@ from .types import BOOL from .types import convert_type from .types import IntRange +from .utils import _detect_program_name from .utils import echo from .utils import make_default_short_help from .utils import make_str @@ -795,9 +796,7 @@ def main( args = list(args) if prog_name is None: - prog_name = make_str( - os.path.basename(sys.argv[0] if sys.argv else __file__) - ) + prog_name = _detect_program_name() # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -438,3 +438,52 @@ def flush(self): def __getattr__(self, attr): return getattr(self.wrapped, attr) + + +def _detect_program_name(path=None, _main=sys.modules["__main__"]): + """Determine the command used to run the program, for use in help + text. If a file or entry point was executed, the file name is + returned. If ``python -m`` was used to execute a module or package, + ``python -m name`` is returned. + + This doesn't try to be too precise, the goal is to give a concise + name for help text. Files are only shown as their name without the + path. ``python`` is only shown for modules, and the full path to + ``sys.executable`` is not shown. + + :param path: The Python file being executed. Python puts this in + ``sys.argv[0]``, which is used by default. + :param _main: The ``__main__`` module. This should only be passed + during internal testing. + + .. versionadded:: 8.0 + Based on command args detection in the Werkzeug reloader. + + :meta private: + """ + if not path: + path = sys.argv[0] + + # The value of __package__ indicates how Python was called. It may + # not exist if a setuptools script is installed as an egg. It may be + # set incorrectly for entry points created with pip on Windows. + if getattr(_main, "__package__", None) is None or ( + os.name == "nt" + and _main.__package__ == "" + and not os.path.exists(path) + and os.path.exists(f"{path}.exe") + ): + # Executed a file, like "python app.py". + return os.path.basename(path) + + # Executed a module, like "python -m example". + # Rewritten by Python from "-m script" to "/path/to/script.py". + # Need to look at main module to determine how it was executed. + py_module = _main.__package__ + name = os.path.splitext(os.path.basename(path))[0] + + # A submodule like "example.cli". + if name != "__main__": + py_module = f"{py_module}.{name}" + + return f"python -m {py_module.lstrip('.')}"
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,4 +1,5 @@ import os +import pathlib import stat import sys from io import StringIO @@ -382,3 +383,32 @@ def test_iter_lazyfile(tmpdir): with click.utils.LazyFile(f.name) as lf: for e_line, a_line in zip(expected, lf): assert e_line == a_line.strip() + + +class MockMain: + __slots__ = "__package__" + + def __init__(self, package_name): + self.__package__ = package_name + + [email protected]( + ("path", "main", "expected"), + [ + ("example.py", None, "example.py"), + (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"), + ("example", None, "example"), + ( + str(pathlib.Path("example/__main__.py")), + MockMain(".example"), + "python -m example", + ), + ( + str(pathlib.Path("example/cli.py")), + MockMain(".example"), + "python -m example.cli", + ), + ], +) +def test_detect_program_name(path, main, expected): + assert click.utils._detect_program_name(path, _main=main) == expected
detection of program name when run with `python -m` The program name (referred to as `prog_name` or `info_name`) is the name Click uses in usage help text. If it's not specified, Click tries to detect it by looking at `sys.argv[0]`. https://github.com/pallets/click/blob/dfb842d95a7c146d8fe8140c8100065410d95c4d/src/click/core.py#L797-L800 This works when the CLI is run as a script, either directly, or indirectly as an entry point, or as a module when the program is a single file, but fails when the program is a package and run with `python -m`. In that case, Python converts the `-m name` to the Python file within the package that would be executed. (The use of `__file__` there is also incorrect, as that will always point to `click/core.py`. There should never be a case where `sys.argv` is empty. `make_str` is probably not needed either.) This leads to the following names: * `python example.py`, executing a script directly - `example.py` * `python -m example`, the single file module `example.py` - `example.py` * `python -m example`, a package like `example/__main__.py` - `__main__.py` * `python -m example.cli`, a submodule like `example/cli.py` - `cli.py` * `example`, an entry point, with any of the layouts above - `example` What's usually expected is that executing a script will print the Python file name (`example.py`), executing an entry point will print the entry point name (`example`), and executing a module or package will print the Python command (`python -m example`, `python -m example.cli`) This leads to projects that expect to be run as either an entry point or `-m` writing their own wrapper around the CLI to control what name gets used. For example, Flask uses a wrapper that the entry point will call with no args, while `__main__.py` or `__name__ == "__main__"` will pass `as_module=True`. ```python def main(as_module=False): cli.main(prog_name="python -m flask" if as_module else None) ``` Unfortunately, detecting whether `python -m` was used is really, really complicated. Luckily, I did the work already in Werkzeug's reloader: https://github.com/pallets/werkzeug/blob/102bcda52176db448d383a9ef1ccf7e406a379eb/src/werkzeug/_reloader.py#L59. It won't be quite the same in Click because we're not concerned with the exact path to the `python` command or script file, or with arguments, but that should be a good start. Write a function `detect_program_name()` to detect this and call it in place of the existing code.
I'll look into this! One more note, there is Windows-specific behavior here, so remember to test the fix against the different cases listed above on both Linux/Mac and Windows. Here's a simple project to test out the commands with. [example.tar.gz](https://github.com/pallets/click/files/4832332/example.tar.gz) ``` $ tar xf example.tar.gz $ cd example $ python3 -m venv venv $ . venv/bin/activate $ pip install -e ../click # wherever your click repo is $ pip install -e . ``` Now you can do different commands and changes you make to your click repo will be reflected. The command echos the detected program name. ``` $ python -m example $ python -m example.cli $ example $ python single.py $ python -m single ```
2020-06-29T12:36:41Z
[]
[]
pallets/click
1,614
pallets__click-1614
[ "1475" ]
6c1eabae3bc08fba81f8b18f8a9111a93f2b0107
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -508,7 +508,10 @@ def command_path(self): if self.info_name is not None: rv = self.info_name if self.parent is not None: - rv = f"{self.parent.command_path} {rv}" + parent_command_path = [self.parent.command_path] + for param in self.parent.command.get_params(self): + parent_command_path.extend(param.get_usage_pieces(self)) + rv = f"{' '.join(parent_command_path)} {rv}" return rv.lstrip() def find_root(self):
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -328,3 +328,44 @@ def cmd(arg): result = runner.invoke(cmd) assert result.exit_code == code assert output in result.output + + +def test_subcommand_help(runner): + @click.group() + @click.argument("name") + @click.argument("val") + @click.option("--opt") + @click.pass_context + def cli(ctx, name, val, opt): + ctx.obj = dict(name=name, val=val) + + @cli.command() + @click.pass_obj + def cmd(obj): + click.echo(f"CMD for {obj['name']} with value {obj['val']}") + + result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"]) + assert not result.exception + assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output + + +def test_nested_subcommand_help(runner): + @click.group() + @click.argument("arg1") + @click.option("--opt1") + def cli(arg1, opt1): + pass + + @cli.group() + @click.argument("arg2") + @click.option("--opt2") + def cmd(arg2, opt2): + pass + + @cmd.command() + def subcmd(): + click.echo("subcommand") + + result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"]) + assert not result.exception + assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output
Required arguments are omitted from command help synopsis I have a `@click.group` that requires an argument. The help text of the group itself correctly says `Usage: p.py [OPTIONS] NAME COMMAND [ARGS]...`. However, the help text of the subcommand omits `NAME` which confuses my users. Example code: ```python #!/usr/bin/python3 import click @click.group() @click.argument("name") @click.pass_context def main(ctx, name): ctx.obj = dict(name=name) @main.command() @click.pass_obj def cmd(obj): print("Running CMD for %s" % (obj['name'])) if __name__ == "__main__": main() ``` Output: ``` $ python3 /tmp/p.py test cmd Running CMD for test $ python3 /tmp/p.py --help Usage: p.py [OPTIONS] NAME COMMAND [ARGS]... Options: --help Show this message and exit. Commands: cmd $ python3 /tmp/p.py test cmd --help Usage: p.py cmd [OPTIONS] Options: --help Show this message and exit. $ ``` I would expect the latter output to be ``` Usage: p.py NAME cmd [OPTIONS] ``` ### Environment * Python version: 3.any * Click version: 7.0
Seams to be the same that this issue: https://github.com/pallets/click/issues/1413
2020-06-30T14:41:47Z
[]
[]
pallets/click
1,615
pallets__click-1615
[ "1422" ]
f3e55b6e2351d506470ccb9ed719eedb34b4c5b4
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1346,7 +1346,7 @@ def resolve_command(self, ctx, args): self.parse_args(ctx, ctx.args) ctx.fail(f"No such command '{original_cmd_name}'.") - return cmd_name, cmd, args[1:] + return cmd.name, cmd, args[1:] def get_command(self, ctx, cmd_name): """Given a context and a command name, this returns a
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -258,6 +258,22 @@ def sync(): assert result.output == "no subcommand, use default\nin subcommand\n" +def test_aliased_command_canonical_name(runner): + class AliasedGroup(click.Group): + def get_command(self, ctx, cmd_name): + return push + + cli = AliasedGroup() + + @cli.command() + def push(): + click.echo("push command") + + result = runner.invoke(cli, ["pu", "--help"]) + assert not result.exception + assert result.output.startswith("Usage: root push [OPTIONS]") + + def test_unprocessed_options(runner): @click.command(context_settings=dict(ignore_unknown_options=True)) @click.argument("args", nargs=-1, type=click.UNPROCESSED)
Generated help with aliased group shows abbreviated command in usage The typical AliasGroup class overrides the get_command method and returns a matching sub command; however, when help is displayed, the usage information shows the matched abbreviated subcommand instead of the full subcommand name. After debugging, I found that the context.info_name contains the the abbreviated sub command name. I think when a sub-command context is being created, it should use the full command name for this field rather than what the user typed.
I believe line 1280 in core.py should be: return cmd.name, cmd, args[1:] instead of: return cmd_name, cmd, args[1:]
2020-06-30T15:52:41Z
[]
[]
pallets/click
1,617
pallets__click-1617
[ "1538" ]
4e0dd2bf848bd7fc8ac4311d19e5fb81f5b84f7f
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1948,6 +1948,12 @@ def _write_opts(opts): default_string = ", ".join(str(d) for d in self.default) elif inspect.isfunction(self.default): default_string = "(dynamic)" + elif self.is_bool_flag and self.secondary_opts: + # For boolean flags that have distinct True/False opts, + # use the opt without prefix instead of the value. + default_string = split_opt( + (self.opts if self.default else self.secondary_opts)[0] + )[1] else: default_string = self.default extra.append(f"default: {default_string}")
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -570,3 +570,32 @@ def cmd(**kwargs): def test_flag_duplicate_names(runner): with pytest.raises(ValueError, match="cannot use the same flag for true/false"): click.Option(["--foo/--foo"], default=False) + + [email protected](("default", "expect"), [(False, "no-cache"), (True, "cache")]) +def test_show_default_boolean_flag_name(runner, default, expect): + """When a boolean flag has distinct True/False opts, it should show + the default opt name instead of the default value. It should only + show one name even if multiple are declared. + """ + opt = click.Option( + ("--cache/--no-cache", "--c/--nc"), + default=default, + show_default=True, + help="Enable/Disable the cache.", + ) + ctx = click.Context(click.Command("test")) + message = opt.get_help_record(ctx)[1] + assert f"[default: {expect}]" in message + + +def test_show_default_boolean_flag_value(runner): + """When a boolean flag only has one opt, it will show the default + value, not the opt name. + """ + opt = click.Option( + ("--cache",), is_flag=True, show_default=True, help="Enable the cache.", + ) + ctx = click.Context(click.Command("test")) + message = opt.get_help_record(ctx)[1] + assert "[default: False]" in message
Improvement for show_default showing in case of a flag the name instead of True/False First to say: It's not a bug ... it's (in my opinion) a reasonable improvement. ### Expected Behavior That's how the boolean flag is configured: ```python @click.option('--cache/--no-cache', default=False, show_default=True, help="Enable/Diable the cache.") ``` Using the --help you see following (just the line of interest): ``` --cache / --no-cache Enable/Diable the cache. [default: False] ``` but preferable woud be: ``` --cache / --no-cache Enable/Diable the cache. [default: no-cache] ``` It's clear to me that this works for --cache/--no-cache like flags only. ### Actual Behavior The output is as documented by the API the default **value** (*not the name*) which is for a boolean True or False. ### Environment * Python version: 3.8.1 * Click version: 7.0
2020-07-01T13:42:19Z
[]
[]
pallets/click
1,618
pallets__click-1618
[ "1015" ]
7332f00ed4c27d8da041788ca6a7aa405f062c76
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -18,6 +18,7 @@ from .formatting import join_options from .globals import pop_context from .globals import push_context +from .parser import _flag_needs_value from .parser import OptionParser from .parser import split_opt from .termui import confirm @@ -2148,6 +2149,9 @@ class Option(Parameter): option name capitalized. :param confirmation_prompt: if set then the value will need to be confirmed if it was prompted for. + :param prompt_required: If set to ``False``, the user will be + prompted for input only when the option was specified as a flag + without a value. :param hide_input: if this is `True` then the input on the prompt will be hidden from the user. This is useful for password input. @@ -2177,6 +2181,7 @@ def __init__( show_default=False, prompt=False, confirmation_prompt=False, + prompt_required=True, hide_input=False, is_flag=None, flag_value=None, @@ -2201,21 +2206,38 @@ def __init__( prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt + self.prompt_required = prompt_required self.hide_input = hide_input self.hidden = hidden - # Flags + # If prompt is enabled but not required, then the option can be + # used as a flag to indicate using prompt or flag_value. + self._flag_needs_value = self.prompt is not None and not self.prompt_required + if is_flag is None: if flag_value is not None: + # Implicitly a flag because flag_value was set. is_flag = True + elif self._flag_needs_value: + # Not a flag, but when used as a flag it shows a prompt. + is_flag = False else: + # Implicitly a flag because flag options were given. is_flag = bool(self.secondary_opts) + elif is_flag is False and not self._flag_needs_value: + # Not a flag, and prompt is not enabled, can be used as a + # flag if flag_value is set. + self._flag_needs_value = flag_value is not None + if is_flag and default_is_missing: self.default = False + if flag_value is None: flag_value = not self.default + self.is_flag = is_flag self.flag_value = flag_value + if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]: self.type = BOOL self.is_bool_flag = True @@ -2486,11 +2508,23 @@ def value_from_envvar(self, ctx): def consume_value(self, ctx, opts): value, source = super().consume_value(ctx, opts) + # The parser will emit a sentinel value if the option can be + # given as a flag without a value. This is different from None + # to distinguish from the flag not being given at all. + if value is _flag_needs_value: + if self.prompt is not None and not ctx.resilient_parsing: + value = self.prompt_for_value(ctx) + source = ParameterSource.PROMPT + else: + value = self.flag_value + source = ParameterSource.COMMANDLINE + # The value wasn't set, or used the param's default, prompt if # prompting is enabled. - if ( + elif ( source in {None, ParameterSource.DEFAULT} and self.prompt is not None + and (self.required or self.prompt_required) and not ctx.resilient_parsing ): value = self.prompt_for_value(ctx) diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -29,6 +29,11 @@ from .exceptions import NoSuchOption from .exceptions import UsageError +# Sentinel value that indicates an option was passed as a flag without a +# value but is not a flag option. Option.consume_value uses this to +# prompt or use the flag_value. +_flag_needs_value = object() + def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, @@ -81,12 +86,6 @@ def _fetch(c): return tuple(rv), list(args) -def _error_opt_args(nargs, opt): - if nargs == 1: - raise BadOptionUsage(opt, f"{opt} option requires an argument") - raise BadOptionUsage(opt, f"{opt} option requires {nargs} arguments") - - def split_opt(opt): first = opt[:1] if first.isalnum(): @@ -343,14 +342,7 @@ def _match_long_opt(self, opt, explicit_value, state): if explicit_value is not None: state.rargs.insert(0, explicit_value) - nargs = option.nargs - if len(state.rargs) < nargs: - _error_opt_args(nargs, opt) - elif nargs == 1: - value = state.rargs.pop(0) - else: - value = tuple(state.rargs[:nargs]) - del state.rargs[:nargs] + value = self._get_value_from_state(opt, option, state) elif explicit_value is not None: raise BadOptionUsage(opt, f"{opt} option does not take a value") @@ -383,14 +375,7 @@ def _match_short_opt(self, arg, state): state.rargs.insert(0, arg[i:]) stop = True - nargs = option.nargs - if len(state.rargs) < nargs: - _error_opt_args(nargs, opt) - elif nargs == 1: - value = state.rargs.pop(0) - else: - value = tuple(state.rargs[:nargs]) - del state.rargs[:nargs] + value = self._get_value_from_state(opt, option, state) else: value = None @@ -407,6 +392,38 @@ def _match_short_opt(self, arg, state): if self.ignore_unknown_options and unknown_options: state.largs.append(f"{prefix}{''.join(unknown_options)}") + def _get_value_from_state(self, option_name, option, state): + nargs = option.nargs + + if len(state.rargs) < nargs: + if option.obj._flag_needs_value: + # Option allows omitting the value. + value = _flag_needs_value + else: + n_str = "an argument" if nargs == 1 else f"{nargs} arguments" + raise BadOptionUsage( + option_name, f"{option_name} option requires {n_str}." + ) + elif nargs == 1: + next_rarg = state.rargs[0] + + if ( + option.obj._flag_needs_value + and isinstance(next_rarg, str) + and next_rarg[:1] in self._opt_prefixes + and len(next_rarg) > 1 + ): + # The next arg looks like the start of an option, don't + # use it as the value if omitting the value is allowed. + value = _flag_needs_value + else: + value = state.rargs.pop(0) + else: + value = tuple(state.rargs[:nargs]) + del state.rargs[:nargs] + + return value + def _process_opts(self, arg, state): explicit_value = None # Long option handling happens in two parts. The first part is
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -658,3 +658,34 @@ def test_show_default_boolean_flag_value(runner): ctx = click.Context(click.Command("test")) message = opt.get_help_record(ctx)[1] assert "[default: False]" in message + + [email protected]( + ("args", "expect"), + [ + (None, (None, None, ())), + (["--opt"], ("flag", None, ())), + (["--opt", "-a", 42], ("flag", "42", ())), + (["--opt", "test", "-a", 42], ("test", "42", ())), + (["--opt=test", "-a", 42], ("test", "42", ())), + (["-o"], ("flag", None, ())), + (["-o", "-a", 42], ("flag", "42", ())), + (["-o", "test", "-a", 42], ("test", "42", ())), + (["-otest", "-a", 42], ("test", "42", ())), + (["a", "b", "c"], (None, None, ("a", "b", "c"))), + (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))), + (["--opt", "test"], ("test", None, ())), + (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))), + (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))), + ], +) +def test_option_with_optional_value(runner, args, expect): + @click.command() + @click.option("-o", "--opt", is_flag=False, flag_value="flag") + @click.option("-a") + @click.argument("b", nargs=-1) + def cli(opt, a, b): + return opt, a, b + + result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False) + assert result.return_value == expect diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -385,3 +385,54 @@ def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc): def test_fast_edit(runner): result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'") assert result == "aTest\nbTest\n" + + [email protected]( + ("prompt_required", "required", "args", "expect"), + [ + (True, False, None, "prompt"), + (True, False, ["-v"], "-v option requires an argument"), + (False, True, None, "prompt"), + (False, True, ["-v"], "prompt"), + ], +) +def test_prompt_required_with_required(runner, prompt_required, required, args, expect): + @click.command() + @click.option("-v", prompt=True, prompt_required=prompt_required, required=required) + def cli(v): + click.echo(str(v)) + + result = runner.invoke(cli, args, input="prompt") + assert expect in result.output + + [email protected]( + ("args", "expect"), + [ + # Flag not passed, don't prompt. + pytest.param(None, None, id="no flag"), + # Flag and value passed, don't prompt. + pytest.param(["-v", "value"], "value", id="short sep value"), + pytest.param(["--value", "value"], "value", id="long sep value"), + pytest.param(["-vvalue"], "value", id="short join value"), + pytest.param(["--value=value"], "value", id="long join value"), + # Flag without value passed, prompt. + pytest.param(["-v"], "prompt", id="short no value"), + pytest.param(["--value"], "prompt", id="long no value"), + # Don't use next option flag as value. + pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"), + ], +) +def test_prompt_required_false(runner, args, expect): + @click.command() + @click.option("-v", "--value", prompt=True, prompt_required=False) + @click.option("-o") + def cli(value, o): + if o is not None: + return value, o + + return value + + result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False) + assert result.exception is None + assert result.return_value == expect
Creating an option with prompt always prompts even if the option isn't added to command call Hi, I'm having an issue when I add a prompt or password prompt option to my command. It will prompt even if the command doesn't have that option specified when calling the command in terminal. I used this cookiecutter template to generate the boilerplate code: https://github.com/nvie/cookiecutter-python-cli And the default configs generate a working command that i used to test this: 1. I added an password_prompt decorator in the main command at `my_tool/cli.py`: ```python import click @click.command() @click.option('--as-cowboy', '-c', is_flag=True, help='Greet as a cowboy.') @click.password_option('--password', '-p', help='Input a password') @click.argument('name', default='world', required=False) def main(name, as_cowboy): """My Tool does one thing, and one thing well.""" greet = 'Howdy' if as_cowboy else 'Hello' click.echo('{0}, {1}.'.format(greet, name)) ``` 2. Installed in the project virtualenv with pip ``` pip install --editable . ``` 3. Calling the my-tool command in virtualenv makes click prompt for the password: ``` $ my-tool Password: ``` As it is an option I thought that it wouldn't prompt it it isn't passed when calling the command. There is something that I'm missing?
That is by design I would guess, the documentation example shows this behaviour as well: http://click.pocoo.org/5/options/#password-prompts Just below the section I referenced above comes the section about callbacks, those might be usefull to you: http://click.pocoo.org/5/options/#callbacks-and-eager-options related to #736
2020-07-01T17:55:45Z
[]
[]
pallets/click
1,621
pallets__click-1621
[ "1178" ]
28154558840b43864acc688ed9248db1c4007a12
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1170,7 +1170,7 @@ def format_options(self, ctx, formatter): self.format_commands(ctx, formatter) def resultcallback(self, replace=False): - """Adds a result callback to the chain command. By default if a + """Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand @@ -1189,10 +1189,10 @@ def cli(input): def process_result(result, input): return result + input - .. versionadded:: 3.0 - :param replace: if set to `True` an already existing result callback will be removed. + + .. versionadded:: 3.0 """ def decorator(f): @@ -1258,18 +1258,13 @@ def _process_result(value): return value if not ctx.protected_args: - # If we are invoked without command the chain flag controls - # how this happens. If we are not in chain mode, the return - # value here is the return value of the command. - # If however we are in chain mode, the return value is the - # return value of the result processor invoked with an empty - # list (which means that no subcommand actually was executed). if self.invoke_without_command: - if not self.chain: - return Command.invoke(self, ctx) + # No subcommand was invoked, so the result callback is + # invoked with None for regular groups, or an empty list + # for chained groups. with ctx: Command.invoke(self, ctx) - return _process_result([]) + return _process_result([] if self.chain else None) ctx.fail("Missing command.") # Fetch args back out
diff --git a/tests/test_chain.py b/tests/test_chain.py --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -88,6 +88,25 @@ def bdist(format): assert result.output.splitlines() == ["bdist called 1", "sdist called 2"] [email protected](("chain", "expect"), [(False, "None"), (True, "[]")]) +def test_no_command_result_callback(runner, chain, expect): + """When a group has ``invoke_without_command=True``, the result + callback is always invoked. A regular group invokes it with + ``None``, a chained group with ``[]``. + """ + + @click.group(invoke_without_command=True, chain=chain) + def cli(): + pass + + @cli.resultcallback() + def process_result(result): + click.echo(str(result), nl=False) + + result = runner.invoke(cli, []) + assert result.output == expect + + def test_chaining_with_arguments(runner): @click.group(chain=True) def cli():
resultcallback is not being called when invoke_without_command=True I have a group-command (called `groupcmd`) which I would like the user to be able to invoke without having to specify a subcommand. I also have a resultcallback (via `@groupcmd.resultcallback`) which I would like to call after the group-command finishes for processing errors and logging them to file. If I set `invoke_without_command=True` inside of the `@click.group` definition, then the resultcallback does not get called. I am using click 6.6 on python 2.7.12
Click 6 will only receive security fixes. Please verify that this still happens on Click 7. I've confirmed this happens with click 7.0 on python 3.5.2. Here is some minimal code to reproduce the issue (test.py): ``` import click @click.group(invoke_without_command=True) def main(): print("Invoking main") return "main result" @main.command() def sub(): print("Invoking sub") return "sub result" @main.resultcallback() def process_result(result): print("result was:", result) if __name__ == '__main__': main() ``` If the subcommand is invoked (i.e, `python test.py sub`) then it will print `result was: sub result` but if main is invoked without a subcommand (i.e, `python test.py`) then it will not print the result. I'm not familiar with `resultcallback` off the top of my head, but if you don't find anything in the docs contradicting the behavior you want, I'd be happy to review a PR. I'm looking into this issue at the moment [The documentation](https://click.palletsprojects.com/en/7.x/api/?highlight=resultcallback#click.MultiCommand.resultcallback) states that `resultcallback` *"Adds a result callback to the **chain** command."* [Another example](https://click.palletsprojects.com/en/7.x/commands/#multi-command-pipelines) in the docs shows the result callback being invoked when using subcommands which is what it is meant for. From this I think that `resultcallback` is just used more or less for getting data from subcommands and not singular calls without any subcommands invoked which your script attempts to do. @IamCathal further on in the doc for `resultcallback`, it calls out a difference in behavior for chaining, which seems to imply that a result callback should be called for either type of command. And that is the case, it's called for a group with a subcommand and for a chain. Looking through the code, the picture gets more complicated. If `invoke_without_command` is triggered, the code specifically calls out only invoking the result callback for chained commands (with an empty list of results), while ignoring groups. https://github.com/pallets/click/blob/35f73b8c2c314e56968de8bc483da9a84ac5c53e/src/click/core.py#L1261-L1272 So it seems like this is intentional behavior, but there's no explanation for why it was done. The best explanation I can guess is that in a chain you would get an empty list for no commands, but for a regular group you'd only get `None` and wouldn't be able to distinguish between no subcommand and one that returned `None`. But if you were using `resultcallback` with a regular group, you'd presumably be returning a value from subcommands, or not care if the result was `None`. I'm ok with changing this behavior.
2020-07-06T16:09:17Z
[]
[]
pallets/click
1,622
pallets__click-1622
[ "780" ]
47ecf34af4f4b761eb66a15b1d07e5fc4c319992
diff --git a/docs/conf.py b/docs/conf.py --- a/docs/conf.py +++ b/docs/conf.py @@ -22,6 +22,7 @@ "sphinxcontrib.log_cabinet", "pallets_sphinx_themes", "sphinx_issues", + "sphinx_tabs.tabs", ] intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)} issues_github_path = "pallets/click" diff --git a/examples/bashcompletion/bashcompletion.py b/examples/bashcompletion/bashcompletion.py deleted file mode 100644 --- a/examples/bashcompletion/bashcompletion.py +++ /dev/null @@ -1,45 +0,0 @@ -import os - -import click - - [email protected]() -def cli(): - pass - - -def get_env_vars(ctx, args, incomplete): - # Completions returned as strings do not have a description displayed. - for key in os.environ.keys(): - if incomplete in key: - yield key - - [email protected](help="A command to print environment variables") [email protected]("envvar", type=click.STRING, autocompletion=get_env_vars) -def cmd1(envvar): - click.echo(f"Environment variable: {envvar}") - click.echo(f"Value: {os.environ[envvar]}") - - [email protected](help="A group that holds a subcommand") -def group(): - pass - - -def list_users(ctx, args, incomplete): - # You can generate completions with descriptions by returning - # tuples in the form (completion, description). - users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")] - # Ths will allow completion matches based on matches within the - # description string too! - return [user for user in users if incomplete in user[0] or incomplete in user[1]] - - [email protected](help="Choose a user") [email protected]("user", type=click.STRING, autocompletion=list_users) -def subcmd(user): - click.echo(f"Chosen user is {user}") - - -cli.add_command(group) diff --git a/examples/completion/completion.py b/examples/completion/completion.py new file mode 100644 --- /dev/null +++ b/examples/completion/completion.py @@ -0,0 +1,53 @@ +import os + +import click +from click.shell_completion import CompletionItem + + [email protected]() +def cli(): + pass + + [email protected]() [email protected]("--dir", type=click.Path(file_okay=False)) +def ls(dir): + click.echo("\n".join(os.listdir(dir))) + + +def get_env_vars(ctx, param, incomplete): + # Returning a list of values is a shortcut to returning a list of + # CompletionItem(value). + return [k for k in os.environ if incomplete in k] + + [email protected](help="A command to print environment variables") [email protected]("envvar", shell_complete=get_env_vars) +def show_env(envvar): + click.echo(f"Environment variable: {envvar}") + click.echo(f"Value: {os.environ[envvar]}") + + [email protected](help="A group that holds a subcommand") +def group(): + pass + + +def list_users(ctx, param, incomplete): + # You can generate completions with help strings by returning a list + # of CompletionItem. You can match on whatever you want, including + # the help. + items = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")] + + for value, help in items: + if incomplete in value or incomplete in help: + yield CompletionItem(value, help=help) + + [email protected](help="Choose a user") [email protected]("user", shell_complete=list_users) +def select_user(user): + click.echo(f"Chosen user is {user}") + + +cli.add_command(group) diff --git a/examples/bashcompletion/setup.py b/examples/completion/setup.py similarity index 60% rename from examples/bashcompletion/setup.py rename to examples/completion/setup.py --- a/examples/bashcompletion/setup.py +++ b/examples/completion/setup.py @@ -1,13 +1,13 @@ from setuptools import setup setup( - name="click-example-bashcompletion", + name="click-example-completion", version="1.0", - py_modules=["bashcompletion"], + py_modules=["completion"], include_package_data=True, install_requires=["click"], entry_points=""" [console_scripts] - bashcompletion=bashcompletion:cli + completion=completion:cli """, ) diff --git a/src/click/_bashcomplete.py b/src/click/_bashcomplete.py deleted file mode 100644 --- a/src/click/_bashcomplete.py +++ /dev/null @@ -1,371 +0,0 @@ -import copy -import os -import re -from collections import abc - -from .core import Argument -from .core import MultiCommand -from .core import Option -from .parser import split_arg_string -from .types import Choice -from .utils import echo - -WORDBREAK = "=" - -# Note, only BASH version 4.4 and later have the nosort option. -COMPLETION_SCRIPT_BASH = """ -%(complete_func)s() { - local IFS=$'\n' - COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\ - COMP_CWORD=$COMP_CWORD \\ - %(autocomplete_var)s=complete $1 ) ) - return 0 -} - -%(complete_func)s_setup() { - local COMPLETION_OPTIONS="" - local BASH_VERSION_ARR=(${BASH_VERSION//./ }) - # Only BASH version 4.4 and later have the nosort option. - if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] \ -&& [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then - COMPLETION_OPTIONS="-o nosort" - fi - - complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s -} - -%(complete_func)s_setup -""" - -COMPLETION_SCRIPT_ZSH = """ -#compdef %(script_names)s - -%(complete_func)s() { - local -a completions - local -a completions_with_descriptions - local -a response - (( ! $+commands[%(script_names)s] )) && return 1 - - response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\ - COMP_CWORD=$((CURRENT-1)) \\ - %(autocomplete_var)s=\"complete_zsh\" \\ - %(script_names)s )}") - - for key descr in ${(kv)response}; do - if [[ "$descr" == "_" ]]; then - completions+=("$key") - else - completions_with_descriptions+=("$key":"$descr") - fi - done - - if [ -n "$completions_with_descriptions" ]; then - _describe -V unsorted completions_with_descriptions -U - fi - - if [ -n "$completions" ]; then - compadd -U -V unsorted -a completions - fi - compstate[insert]="automenu" -} - -compdef %(complete_func)s %(script_names)s -""" - -COMPLETION_SCRIPT_FISH = ( - "complete --no-files --command %(script_names)s --arguments" - ' "(env %(autocomplete_var)s=complete_fish' - " COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t)" - ' %(script_names)s)"' -) - -_completion_scripts = { - "bash": COMPLETION_SCRIPT_BASH, - "zsh": COMPLETION_SCRIPT_ZSH, - "fish": COMPLETION_SCRIPT_FISH, -} - -_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]") - - -def get_completion_script(prog_name, complete_var, shell): - cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_")) - script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH) - return ( - script - % { - "complete_func": f"_{cf_name}_completion", - "script_names": prog_name, - "autocomplete_var": complete_var, - } - ).strip() + ";" - - -def resolve_ctx(cli, prog_name, args): - """Parse into a hierarchy of contexts. Contexts are connected - through the parent variable. - - :param cli: command definition - :param prog_name: the program that is running - :param args: full list of args - :return: the final context/command parsed - """ - ctx = cli.make_context(prog_name, args, resilient_parsing=True) - args = ctx.protected_args + ctx.args - while args: - if isinstance(ctx.command, MultiCommand): - if not ctx.command.chain: - cmd_name, cmd, args = ctx.command.resolve_command(ctx, args) - if cmd is None: - return ctx - ctx = cmd.make_context( - cmd_name, args, parent=ctx, resilient_parsing=True - ) - args = ctx.protected_args + ctx.args - else: - # Walk chained subcommand contexts saving the last one. - while args: - cmd_name, cmd, args = ctx.command.resolve_command(ctx, args) - if cmd is None: - return ctx - sub_ctx = cmd.make_context( - cmd_name, - args, - parent=ctx, - allow_extra_args=True, - allow_interspersed_args=False, - resilient_parsing=True, - ) - args = sub_ctx.args - ctx = sub_ctx - args = sub_ctx.protected_args + sub_ctx.args - else: - break - return ctx - - -def start_of_option(param_str): - """ - :param param_str: param_str to check - :return: whether or not this is the start of an option declaration - (i.e. starts "-" or "--") - """ - return param_str and param_str[:1] == "-" - - -def is_incomplete_option(all_args, cmd_param): - """ - :param all_args: the full original list of args supplied - :param cmd_param: the current command parameter - :return: whether or not the last option declaration (i.e. starts - "-" or "--") is incomplete and corresponds to this cmd_param. In - other words whether this cmd_param option can still accept - values - """ - if not isinstance(cmd_param, Option): - return False - if cmd_param.is_flag: - return False - last_option = None - for index, arg_str in enumerate( - reversed([arg for arg in all_args if arg != WORDBREAK]) - ): - if index + 1 > cmd_param.nargs: - break - if start_of_option(arg_str): - last_option = arg_str - - return True if last_option and last_option in cmd_param.opts else False - - -def is_incomplete_argument(current_params, cmd_param): - """ - :param current_params: the current params and values for this - argument as already entered - :param cmd_param: the current command parameter - :return: whether or not the last argument is incomplete and - corresponds to this cmd_param. In other words whether or not the - this cmd_param argument can still accept values - """ - if not isinstance(cmd_param, Argument): - return False - current_param_values = current_params[cmd_param.name] - if current_param_values is None: - return True - if cmd_param.nargs == -1: - return True - if ( - isinstance(current_param_values, abc.Iterable) - and cmd_param.nargs > 1 - and len(current_param_values) < cmd_param.nargs - ): - return True - return False - - -def get_user_autocompletions(ctx, args, incomplete, cmd_param): - """ - :param ctx: context associated with the parsed command - :param args: full list of args - :param incomplete: the incomplete text to autocomplete - :param cmd_param: command definition - :return: all the possible user-specified completions for the param - """ - results = [] - if isinstance(cmd_param.type, Choice): - # Choices don't support descriptions. - results = [ - (c, None) for c in cmd_param.type.choices if str(c).startswith(incomplete) - ] - elif cmd_param.autocompletion is not None: - dynamic_completions = cmd_param.autocompletion( - ctx=ctx, args=args, incomplete=incomplete - ) - results = [ - c if isinstance(c, tuple) else (c, None) for c in dynamic_completions - ] - return results - - -def get_visible_commands_starting_with(ctx, starts_with): - """ - :param ctx: context associated with the parsed command - :starts_with: string that visible commands must start with. - :return: all visible (not hidden) commands that start with starts_with. - """ - for c in ctx.command.list_commands(ctx): - if c.startswith(starts_with): - command = ctx.command.get_command(ctx, c) - if not command.hidden: - yield command - - -def add_subcommand_completions(ctx, incomplete, completions_out): - # Add subcommand completions. - if isinstance(ctx.command, MultiCommand): - completions_out.extend( - [ - (c.name, c.get_short_help_str()) - for c in get_visible_commands_starting_with(ctx, incomplete) - ] - ) - - # Walk up the context list and add any other completion - # possibilities from chained commands - while ctx.parent is not None: - ctx = ctx.parent - if isinstance(ctx.command, MultiCommand) and ctx.command.chain: - remaining_commands = [ - c - for c in get_visible_commands_starting_with(ctx, incomplete) - if c.name not in ctx.protected_args - ] - completions_out.extend( - [(c.name, c.get_short_help_str()) for c in remaining_commands] - ) - - -def get_choices(cli, prog_name, args, incomplete): - """ - :param cli: command definition - :param prog_name: the program that is running - :param args: full list of args - :param incomplete: the incomplete text to autocomplete - :return: all the possible completions for the incomplete - """ - all_args = copy.deepcopy(args) - - ctx = resolve_ctx(cli, prog_name, args) - if ctx is None: - return [] - - has_double_dash = "--" in all_args - - # In newer versions of bash long opts with '='s are partitioned, but - # it's easier to parse without the '=' - if start_of_option(incomplete) and WORDBREAK in incomplete: - partition_incomplete = incomplete.partition(WORDBREAK) - all_args.append(partition_incomplete[0]) - incomplete = partition_incomplete[2] - elif incomplete == WORDBREAK: - incomplete = "" - - completions = [] - if not has_double_dash and start_of_option(incomplete): - # completions for partial options - for param in ctx.command.get_params(ctx): - if isinstance(param, Option) and not param.hidden: - param_opts = [ - param_opt - for param_opt in param.opts + param.secondary_opts - if param_opt not in all_args or param.multiple - ] - completions.extend( - [(o, param.help) for o in param_opts if o.startswith(incomplete)] - ) - return completions - # completion for option values from user supplied values - for param in ctx.command.get_params(ctx): - if is_incomplete_option(all_args, param): - return get_user_autocompletions(ctx, all_args, incomplete, param) - # completion for argument values from user supplied values - for param in ctx.command.get_params(ctx): - if is_incomplete_argument(ctx.params, param): - return get_user_autocompletions(ctx, all_args, incomplete, param) - - add_subcommand_completions(ctx, incomplete, completions) - # Sort before returning so that proper ordering can be enforced in custom types. - return sorted(completions) - - -def do_complete(cli, prog_name, include_descriptions): - cwords = split_arg_string(os.environ["COMP_WORDS"]) - cword = int(os.environ["COMP_CWORD"]) - args = cwords[1:cword] - try: - incomplete = cwords[cword] - except IndexError: - incomplete = "" - - for item in get_choices(cli, prog_name, args, incomplete): - echo(item[0]) - if include_descriptions: - # ZSH has trouble dealing with empty array parameters when - # returned from commands, use '_' to indicate no description - # is present. - echo(item[1] if item[1] else "_") - - return True - - -def do_complete_fish(cli, prog_name): - cwords = split_arg_string(os.environ["COMP_WORDS"]) - incomplete = os.environ["COMP_CWORD"] - args = cwords[1:] - - for item in get_choices(cli, prog_name, args, incomplete): - if item[1]: - echo(f"{item[0]}\t{item[1]}") - else: - echo(item[0]) - - return True - - -def bashcomplete(cli, prog_name, complete_var, complete_instr): - if "_" in complete_instr: - command, shell = complete_instr.split("_", 1) - else: - command = complete_instr - shell = "bash" - - if command == "source": - echo(get_completion_script(prog_name, complete_var, shell)) - return True - elif command == "complete": - if shell == "fish": - return do_complete_fish(cli, prog_name) - elif shell in {"bash", "zsh"}: - return do_complete(cli, prog_name, shell == "zsh") - - return False diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -47,27 +47,30 @@ def _maybe_show_deprecated_notice(cmd): echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True) -def fast_exit(code): - """Exit without garbage collection, this speeds up exit by about 10ms for - things like bash completion. +def _fast_exit(code): + """Low-level exit that skips Python's cleanup but speeds up exit by + about 10ms for things like shell completion. + + :param code: Exit code. """ sys.stdout.flush() sys.stderr.flush() os._exit(code) -def _bashcomplete(cmd, prog_name, complete_var=None): - """Internal handler for the bash completion support.""" - if complete_var is None: - complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() - complete_instr = os.environ.get(complete_var) - if not complete_instr: - return +def _complete_visible_commands(ctx, incomplete): + """List all the subcommands of a group that start with the + incomplete value and aren't hidden. - from ._bashcomplete import bashcomplete + :param ctx: Invocation context for the group. + :param incomplete: Value being completed. May be empty. + """ + for name in ctx.command.list_commands(ctx): + if name.startswith(incomplete): + command = ctx.command.get_command(ctx, name) - if bashcomplete(cmd, prog_name, complete_var, complete_instr): - fast_exit(1) + if not command.hidden: + yield name, command def _check_multicommand(base_command, cmd_name, cmd, register=False): @@ -281,9 +284,13 @@ def __init__( self.command = command #: the descriptive information name self.info_name = info_name - #: the parsed parameters except if the value is hidden in which - #: case it's not remembered. + #: Map of parameter names to their parsed values. Parameters + #: with ``expose_value=False`` are not stored. self.params = {} + # This tracks the actual param objects that were parsed, even if + # they didn't expose a value. Used by completion system to know + # what parameters to exclude. + self._seen_params = set() #: the leftover arguments. self.args = [] #: protected arguments. These are arguments that are prepended @@ -861,6 +868,35 @@ def invoke(self, ctx): """ raise NotImplementedError("Base commands are not invokable by default") + def shell_complete(self, ctx, incomplete): + """Return a list of completions for the incomplete value. Looks + at the names of chained multi-commands. + + Any command could be part of a chained multi-command, so sibling + commands are valid at any point during command completion. Other + command classes will return more completions. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results = [] + + while ctx.parent is not None: + ctx = ctx.parent + + if isinstance(ctx.command, MultiCommand) and ctx.command.chain: + results.extend( + CompletionItem(name, help=command.get_short_help_str()) + for name, command in _complete_visible_commands(ctx, incomplete) + if name not in ctx.protected_args + ) + + return results + def main( self, args=None, @@ -913,10 +949,8 @@ def main( if prog_name is None: prog_name = _detect_program_name() - # Hook for the Bash completion. This only activates if the Bash - # completion is actually enabled, otherwise this is quite a fast - # noop. - _bashcomplete(self, prog_name, complete_var) + # Process shell completion requests and exit early. + self._main_shell_completion(prog_name, complete_var) try: try: @@ -966,6 +1000,29 @@ def main( echo("Aborted!", file=sys.stderr) sys.exit(1) + def _main_shell_completion(self, prog_name, complete_var=None): + """Check if the shell is asking for tab completion, process + that, then exit early. Called from :meth:`main` before the + program is invoked. + + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. Defaults to + ``_{PROG_NAME}_COMPLETE``. + """ + if complete_var is None: + complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() + + instruction = os.environ.get(complete_var) + + if not instruction: + return + + from .shell_completion import shell_complete + + rv = shell_complete(self, prog_name, complete_var, instruction) + _fast_exit(rv) + def __call__(self, *args, **kwargs): """Alias for :meth:`main`.""" return self.main(*args, **kwargs) @@ -1224,6 +1281,37 @@ def invoke(self, ctx): if self.callback is not None: return ctx.invoke(self.callback, **ctx.params) + def shell_complete(self, ctx, incomplete): + """Return a list of completions for the incomplete value. Looks + at the names of options and chained multi-commands. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results = [] + + if incomplete and not incomplete[0].isalnum(): + for param in self.get_params(ctx): + if ( + not isinstance(param, Option) + or param.hidden + or (not param.multiple and param in ctx._seen_params) + ): + continue + + results.extend( + CompletionItem(name, help=param.help) + for name in param.opts + param.secondary_opts + if name.startswith(incomplete) + ) + + results.extend(super().shell_complete(ctx, incomplete)) + return results + class MultiCommand(Command): """A multi command is the basic implementation of a command that @@ -1481,8 +1569,7 @@ def resolve_command(self, ctx, args): if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) ctx.fail(f"No such command '{original_cmd_name}'.") - - return cmd.name, cmd, args[1:] + return cmd.name if cmd else None, cmd, args[1:] def get_command(self, ctx, cmd_name): """Given a context and a command name, this returns a @@ -1496,6 +1583,25 @@ def list_commands(self, ctx): """ return [] + def shell_complete(self, ctx, incomplete): + """Return a list of completions for the incomplete value. Looks + at the names of options, subcommands, and chained + multi-commands. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results = [ + CompletionItem(name, help=command.get_short_help_str()) + for name, command in _complete_visible_commands(ctx, incomplete) + ] + results.extend(super().shell_complete(ctx, incomplete)) + return results + class Group(MultiCommand): """A group allows a command to have subcommands attached. This is @@ -1677,6 +1783,17 @@ class Parameter: order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. + :param shell_complete: A function that returns custom shell + completions. Used instead of the param's type completion if + given. Takes ``ctx, param, incomplete`` and must return a list + of :class:`~click.shell_completion.CompletionItem` or a list of + strings. + + .. versionchanged:: 8.0 + ``autocompletion`` is renamed to ``shell_complete`` and has new + semantics described above. The old name is deprecated and will + be removed in 8.1, until then it will be wrapped to match the + new requirements. .. versionchanged:: 7.1 Empty environment variables are ignored rather than taking the @@ -1688,6 +1805,7 @@ class Parameter: parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier. """ + param_type_name = "parameter" def __init__( @@ -1702,6 +1820,7 @@ def __init__( expose_value=True, is_eager=False, envvar=None, + shell_complete=None, autocompletion=None, ): self.name, self.opts, self.secondary_opts = self._parse_decls( @@ -1727,7 +1846,35 @@ def __init__( self.is_eager = is_eager self.metavar = metavar self.envvar = envvar - self.autocompletion = autocompletion + + if autocompletion is not None: + import warnings + + warnings.warn( + "'autocompletion' is renamed to 'shell_complete'. The old name is" + " deprecated and will be removed in Click 8.1. See the docs about" + " 'Parameter' for information about new behavior.", + DeprecationWarning, + stacklevel=2, + ) + + def shell_complete(ctx, param, incomplete): + from click.shell_completion import CompletionItem + + out = [] + + for c in autocompletion(ctx, [], incomplete): + if isinstance(c, tuple): + c = CompletionItem(c[0], help=c[1]) + elif isinstance(c, str): + c = CompletionItem(c) + + if c.value.startswith(incomplete): + out.append(c) + + return out + + self._custom_shell_complete = shell_complete def to_info_dict(self): """Gather information that could be useful for a tool generating @@ -1902,6 +2049,10 @@ def handle_parse_result(self, ctx, opts, args): if self.expose_value: ctx.params[self.name] = value + + if value is not None: + ctx._seen_params.add(self) + return value, args def get_help_record(self, ctx): @@ -1917,6 +2068,29 @@ def get_error_hint(self, ctx): hint_list = self.opts or [self.human_readable_name] return " / ".join(repr(x) for x in hint_list) + def shell_complete(self, ctx, incomplete): + """Return a list of completions for the incomplete value. If a + ``shell_complete`` function was given during init, it is used. + Otherwise, the :attr:`type` + :meth:`~click.types.ParamType.shell_complete` function is used. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + if self._custom_shell_complete is not None: + results = self._custom_shell_complete(ctx, self, incomplete) + + if results and isinstance(results[0], str): + from click.shell_completion import CompletionItem + + results = [CompletionItem(c) for c in results] + + return results + + return self.type.shell_complete(ctx, self, incomplete) + class Option(Parameter): """Options are usually optional values on the command line and diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py new file mode 100644 --- /dev/null +++ b/src/click/shell_completion.py @@ -0,0 +1,536 @@ +import os +import re + +from .core import Argument +from .core import MultiCommand +from .core import Option +from .parser import split_arg_string +from .utils import echo + + +def shell_complete(cli, prog_name, complete_var, instruction): + """Perform shell completion for the given CLI program. + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. + :param instruction: Value of ``complete_var`` with the completion + instruction and shell, in the form ``instruction_shell``. + :return: Status code to exit with. + """ + instruction, _, shell = instruction.partition("_") + comp_cls = get_completion_class(shell) + + if comp_cls is None: + return 1 + + comp = comp_cls(cli, prog_name, complete_var) + + if instruction == "source": + echo(comp.source()) + return 0 + + if instruction == "complete": + echo(comp.complete()) + return 0 + + return 1 + + +class CompletionItem: + """Represents a completion value and metadata about the value. The + default metadata is ``type`` to indicate special shell handling, + and ``help`` if a shell supports showing a help string next to the + value. + + Arbitrary parameters can be passed when creating the object, and + accessed using ``item.attr``. If an attribute wasn't passed, + accessing it returns ``None``. + + :param value: The completion suggestion. + :param type: Tells the shell script to provide special completion + support for the type. Click uses ``"dir"`` and ``"file"``. + :param help: String shown next to the value if supported. + :param kwargs: Arbitrary metadata. The built-in implementations + don't use this, but custom type completions paired with custom + shell support could use it. + """ + + __slots__ = ("value", "type", "help", "_info") + + def __init__(self, value, type="plain", help=None, **kwargs): + self.value = value + self.type = type + self.help = help + self._info = kwargs + + def __getattr__(self, name): + return self._info.get(name) + + +# Only Bash >= 4.4 has the nosort option. +_SOURCE_BASH = """\ +%(complete_func)s() { + local IFS=$'\\n' + local response + + response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ +%(complete_var)s=complete_bash $1) + + for completion in $response; do + IFS=',' read type value <<< "$completion" + + if [[ $type == 'dir' ]]; then + COMREPLY=() + compopt -o dirnames + elif [[ $type == 'file' ]]; then + COMREPLY=() + compopt -o default + elif [[ $type == 'plain' ]]; then + COMPREPLY+=($value) + fi + done + + return 0 +} + +%(complete_func)s_setup() { + complete -o nosort -F %(complete_func)s %(prog_name)s +} + +%(complete_func)s_setup; +""" + +_SOURCE_ZSH = """\ +#compdef %(prog_name)s + +%(complete_func)s() { + local -a completions + local -a completions_with_descriptions + local -a response + (( ! $+commands[%(prog_name)s] )) && return 1 + + response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \ +%(complete_var)s=complete_zsh %(prog_name)s)}") + + for type key descr in ${response}; do + if [[ "$type" == "plain" ]]; then + if [[ "$descr" == "_" ]]; then + completions+=("$key") + else + completions_with_descriptions+=("$key":"$descr") + fi + elif [[ "$type" == "dir" ]]; then + _path_files -/ + elif [[ "$type" == "file" ]]; then + _path_files -f + fi + done + + if [ -n "$completions_with_descriptions" ]; then + _describe -V unsorted completions_with_descriptions -U + fi + + if [ -n "$completions" ]; then + compadd -U -V unsorted -a completions + fi +} + +compdef %(complete_func)s %(prog_name)s; +""" + +_SOURCE_FISH = """\ +function %(complete_func)s; + set -l response; + + for value in (env %(complete_var)s=complete_fish COMP_WORDS=(commandline -cp) \ +COMP_CWORD=(commandline -t) %(prog_name)s); + set response $response $value; + end; + + for completion in $response; + set -l metadata (string split "," $completion); + + if test $metadata[1] = "dir"; + __fish_complete_directories $metadata[2]; + else if test $metadata[1] = "file"; + __fish_complete_path $metadata[2]; + else if test $metadata[1] = "plain"; + echo $metadata[2]; + end; + end; +end; + +complete --no-files --command %(prog_name)s --arguments \ +"(%(complete_func)s)"; +""" + + +class ShellComplete: + """Base class for providing shell completion support. A subclass for + a given shell will override attributes and methods to implement the + completion instructions (``source`` and ``complete``). + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. + + .. versionadded:: 8.0 + """ + + name = None + """Name to register the shell as with :func:`add_completion_class`. + This is used in completion instructions (``source_{name}`` and + ``complete_{name}``). + """ + source_template = None + """Completion script template formatted by :meth:`source`. This must + be provided by subclasses. + """ + + def __init__(self, cli, prog_name, complete_var): + self.cli = cli + self.prog_name = prog_name + self.complete_var = complete_var + + @property + def func_name(self): + """The name of the shell function defined by the completion + script. + """ + safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), re.ASCII) + return f"_{safe_name}_completion" + + def source_vars(self): + """Vars for formatting :attr:`source_template`. + + By default this provides ``complete_func``, ``complete_var``, + and ``prog_name``. + """ + return { + "complete_func": self.func_name, + "complete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def source(self): + """Produce the shell script that defines the completion + function. By default this ``%``-style formats + :attr:`source_template` with the dict returned by + :meth:`source_vars`. + """ + return self.source_template % self.source_vars() + + def get_completion_args(self): + """Use the env vars defined by the shell script to return a + tuple of ``args, incomplete``. This must be implemented by + subclasses. + """ + raise NotImplementedError + + def get_completions(self, args, incomplete): + """Determine the context and last complete command or parameter + from the complete args. Call that object's ``shell_complete`` + method to get the completions for the incomplete value. + + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ + ctx = _resolve_context(self.cli, self.prog_name, args) + + if ctx is None: + return [] + + obj, incomplete = _resolve_incomplete(ctx, args, incomplete) + return obj.shell_complete(ctx, incomplete) + + def format_completion(self, item): + """Format a completion item into the form recognized by the + shell script. This must be implemented by subclasses. + + :param item: Completion item to format. + """ + raise NotImplementedError + + def complete(self): + """Produce the completion data to send back to the shell. + + By default this calls :meth:`get_completion_args`, gets the + completions, then calls :meth:`format_completion` for each + completion. + """ + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + out = [self.format_completion(item) for item in completions] + return "\n".join(out) + + +class BashComplete(ShellComplete): + """Shell completion for Bash.""" + + name = "bash" + source_template = _SOURCE_BASH + + def _check_version(self): + import subprocess + + output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE) + match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode()) + + if match is not None: + major, minor = match.groups() + + if major < "4" or major == "4" and minor < "4": + raise RuntimeError( + "Shell completion is not supported for Bash" + " versions older than 4.4." + ) + else: + raise RuntimeError( + "Couldn't detect Bash version, shell completion is not supported." + ) + + def source(self): + self._check_version() + return super().source() + + def get_completion_args(self): + cwords = split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: CompletionItem): + return f"{item.type},{item.value}" + + +class ZshComplete(ShellComplete): + """Shell completion for Zsh.""" + + name = "zsh" + source_template = _SOURCE_ZSH + + def get_completion_args(self): + cwords = split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: CompletionItem): + return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}" + + +class FishComplete(ShellComplete): + """Shell completion for Fish.""" + + name = "fish" + source_template = _SOURCE_FISH + + def get_completion_args(self): + cwords = split_arg_string(os.environ["COMP_WORDS"]) + incomplete = os.environ["COMP_CWORD"] + args = cwords[1:] + + # Fish stores the partial word in both COMP_WORDS and + # COMP_CWORD, remove it from complete args. + if incomplete and args and args[-1] == incomplete: + args.pop() + + return args, incomplete + + def format_completion(self, item: CompletionItem): + if item.help: + return f"{item.type},{item.value}\t{item.help}" + + return f"{item.type},{item.value}" + + +_available_shells = { + "bash": BashComplete, + "fish": FishComplete, + "zsh": ZshComplete, +} + + +def add_completion_class(cls, name=None): + """Register a :class:`ShellComplete` subclass under the given name. + The name will be provided by the completion instruction environment + variable during completion. + + :param cls: The completion class that will handle completion for the + shell. + :param name: Name to register the class under. Defaults to the + class's ``name`` attribute. + """ + if name is None: + name = cls.name + + _available_shells[name] = cls + + +def get_completion_class(shell): + """Look up a registered :class:`ShellComplete` subclass by the name + provided by the completion instruction environment variable. If the + name isn't registered, returns ``None``. + + :param shell: Name the class is registered under. + """ + return _available_shells.get(shell) + + +def _is_incomplete_argument(values, param): + """Determine if the given parameter is an argument that can still + accept values. + + :param values: Dict of param names and values parsed from the + command line args. + :param param: Argument object being checked. + """ + if not isinstance(param, Argument): + return False + + value = values[param.name] + + if value is None: + return True + + if param.nargs == -1: + return True + + if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs: + return True + + return False + + +def _start_of_option(value): + """Check if the value looks like the start of an option.""" + return value and not value[0].isalnum() + + +def _is_incomplete_option(args, param): + """Determine if the given parameter is an option that needs a value. + + :param args: List of complete args before the incomplete value. + :param param: Option object being checked. + """ + if not isinstance(param, Option): + return False + + if param.is_flag: + return False + + last_option = None + + for index, arg in enumerate(reversed(args)): + if index + 1 > param.nargs: + break + + if _start_of_option(arg): + last_option = arg + + return last_option is not None and last_option in param.opts + + +def _resolve_context(cli, prog_name, args): + """Produce the context hierarchy starting with the command and + traversing the complete arguments. This only follows the commands, + it doesn't trigger input prompts or callbacks. + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param args: List of complete args before the incomplete value. + """ + ctx = cli.make_context(prog_name, args.copy(), resilient_parsing=True) + args = ctx.protected_args + ctx.args + + while args: + if isinstance(ctx.command, MultiCommand): + if not ctx.command.chain: + name, cmd, args = ctx.command.resolve_command(ctx, args) + + if cmd is None: + return ctx + + ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True) + args = ctx.protected_args + ctx.args + else: + while args: + name, cmd, args = ctx.command.resolve_command(ctx, args) + + if cmd is None: + return ctx + + sub_ctx = cmd.make_context( + name, + args, + parent=ctx, + allow_extra_args=True, + allow_interspersed_args=False, + resilient_parsing=True, + ) + args = sub_ctx.args + + ctx = sub_ctx + args = sub_ctx.protected_args + sub_ctx.args + else: + break + + return ctx + + +def _resolve_incomplete(ctx, args, incomplete): + """Find the Click object that will handle the completion of the + incomplete value. Return the object and the incomplete value. + + :param ctx: Invocation context for the command represented by + the parsed complete args. + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ + # Different shells treat an "=" between a long option name and + # value differently. Might keep the value joined, return the "=" + # as a separate item, or return the split name and value. Always + # split and discard the "=" to make completion easier. + if incomplete == "=": + incomplete = "" + elif "=" in incomplete and _start_of_option(incomplete): + name, _, incomplete = incomplete.partition("=") + args.append(name) + + # The "--" marker tells Click to stop treating values as options + # even if they start with the option character. If it hasn't been + # given and the incomplete arg looks like an option, the current + # command will provide option name completions. + if "--" not in args and _start_of_option(incomplete): + return ctx.command, incomplete + + # If the last complete arg is an option name with an incomplete + # value, the option will provide value completions. + for param in ctx.command.get_params(ctx): + if _is_incomplete_option(args, param): + return param, incomplete + + # It's not an option name or value. The first argument without a + # parsed value will provide value completions. + for param in ctx.command.get_params(ctx): + if _is_incomplete_argument(ctx.params, param): + return param, incomplete + + # There were no unparsed arguments, the command may be a group that + # will provide command name completions. + return ctx.command, incomplete diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -107,6 +107,21 @@ def fail(self, message, param=None, ctx=None): """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param) + def shell_complete(self, ctx, param, incomplete): + """Return a list of + :class:`~click.shell_completion.CompletionItem` objects for the + incomplete value. Most types do not provide completions, but + some do, and this allows custom types to provide custom + completions as well. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + return [] + class CompositeParamType(ParamType): is_composite = True @@ -249,6 +264,20 @@ def convert(self, value, param, ctx): def __repr__(self): return f"Choice({list(self.choices)})" + def shell_complete(self, ctx, param, incomplete): + """Complete choices that start with the incomplete value. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + str_choices = map(str, self.choices) + return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)] + class DateTime(ParamType): """The DateTime type converts date strings into `datetime` objects. @@ -583,6 +612,20 @@ def convert(self, value, param, ctx): ctx, ) + def shell_complete(self, ctx, param, incomplete): + """Return a special completion marker that tells the completion + system to use the shell to provide file path completions. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + return [CompletionItem(incomplete, type="file")] + class Path(ParamType): """The path type is similar to the :class:`File` type but it performs @@ -714,6 +757,22 @@ def convert(self, value, param, ctx): return self.coerce_path_result(rv) + def shell_complete(self, ctx, param, incomplete): + """Return a special completion marker that tells the completion + system to use the shell to provide path completions for only + directories or any paths. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + type = "dir" if self.dir_okay and not self.file_okay else "file" + return [CompletionItem(incomplete, type=type)] + class Tuple(CompositeParamType): """The default behavior of Click is to apply a type on a value directly.
diff --git a/tests/test_bashcomplete.py b/tests/test_bashcomplete.py deleted file mode 100644 --- a/tests/test_bashcomplete.py +++ /dev/null @@ -1,519 +0,0 @@ -import pytest - -import click -from click._bashcomplete import get_choices - - -def choices_without_help(cli, args, incomplete): - completions = get_choices(cli, "dummy", args, incomplete) - return [c[0] for c in completions] - - -def choices_with_help(cli, args, incomplete): - return list(get_choices(cli, "dummy", args, incomplete)) - - -def test_single_command(): - @click.command() - @click.option("--local-opt") - def cli(local_opt): - pass - - assert choices_without_help(cli, [], "-") == ["--local-opt", "--help"] - assert choices_without_help(cli, [], "") == [] - - -def test_boolean_flag(): - @click.command() - @click.option("--shout/--no-shout", default=False) - def cli(local_opt): - pass - - assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout", "--help"] - - -def test_multi_value_option(): - @click.group() - @click.option("--pos", nargs=2, type=float) - def cli(local_opt): - pass - - @cli.command() - @click.option("--local-opt") - def sub(local_opt): - pass - - assert choices_without_help(cli, [], "-") == ["--pos", "--help"] - assert choices_without_help(cli, ["--pos"], "") == [] - assert choices_without_help(cli, ["--pos", "1.0"], "") == [] - assert choices_without_help(cli, ["--pos", "1.0", "1.0"], "") == ["sub"] - - -def test_multi_option(): - @click.command() - @click.option("--message", "-m", multiple=True) - def cli(local_opt): - pass - - assert choices_without_help(cli, [], "-") == ["--message", "-m", "--help"] - assert choices_without_help(cli, ["-m"], "") == [] - - -def test_small_chain(): - @click.group() - @click.option("--global-opt") - def cli(global_opt): - pass - - @cli.command() - @click.option("--local-opt") - def sub(local_opt): - pass - - assert choices_without_help(cli, [], "") == ["sub"] - assert choices_without_help(cli, [], "-") == ["--global-opt", "--help"] - assert choices_without_help(cli, ["sub"], "") == [] - assert choices_without_help(cli, ["sub"], "-") == ["--local-opt", "--help"] - - -def test_long_chain(): - @click.group("cli") - @click.option("--cli-opt") - def cli(cli_opt): - pass - - @cli.group("asub") - @click.option("--asub-opt") - def asub(asub_opt): - pass - - @asub.group("bsub") - @click.option("--bsub-opt") - def bsub(bsub_opt): - pass - - COLORS = ["red", "green", "blue"] - - def get_colors(ctx, args, incomplete): - for c in COLORS: - if c.startswith(incomplete): - yield c - - def search_colors(ctx, args, incomplete): - for c in COLORS: - if incomplete in c: - yield c - - CSUB_OPT_CHOICES = ["foo", "bar"] - CSUB_CHOICES = ["bar", "baz"] - - @bsub.command("csub") - @click.option("--csub-opt", type=click.Choice(CSUB_OPT_CHOICES)) - @click.option("--csub", type=click.Choice(CSUB_CHOICES)) - @click.option("--search-color", autocompletion=search_colors) - @click.argument("color", autocompletion=get_colors) - def csub(csub_opt, color): - pass - - assert choices_without_help(cli, [], "-") == ["--cli-opt", "--help"] - assert choices_without_help(cli, [], "") == ["asub"] - assert choices_without_help(cli, ["asub"], "-") == ["--asub-opt", "--help"] - assert choices_without_help(cli, ["asub"], "") == ["bsub"] - assert choices_without_help(cli, ["asub", "bsub"], "-") == ["--bsub-opt", "--help"] - assert choices_without_help(cli, ["asub", "bsub"], "") == ["csub"] - assert choices_without_help(cli, ["asub", "bsub", "csub"], "-") == [ - "--csub-opt", - "--csub", - "--search-color", - "--help", - ] - assert ( - choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "") - == CSUB_OPT_CHOICES - ) - assert choices_without_help(cli, ["asub", "bsub", "csub"], "--csub") == [ - "--csub-opt", - "--csub", - ] - assert ( - choices_without_help(cli, ["asub", "bsub", "csub", "--csub"], "") - == CSUB_CHOICES - ) - assert choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "f") == [ - "foo" - ] - assert choices_without_help(cli, ["asub", "bsub", "csub"], "") == COLORS - assert choices_without_help(cli, ["asub", "bsub", "csub"], "b") == ["blue"] - assert choices_without_help( - cli, ["asub", "bsub", "csub", "--search-color"], "een" - ) == ["green"] - - -def test_chaining(): - @click.group("cli", chain=True) - @click.option("--cli-opt") - @click.argument("arg", type=click.Choice(["cliarg1", "cliarg2"])) - def cli(cli_opt, arg): - pass - - @cli.command() - @click.option("--asub-opt") - def asub(asub_opt): - pass - - @cli.command(help="bsub help") - @click.option("--bsub-opt") - @click.argument("arg", type=click.Choice(["arg1", "arg2"])) - def bsub(bsub_opt, arg): - pass - - @cli.command() - @click.option("--csub-opt") - @click.argument("arg", type=click.Choice(["carg1", "carg2"]), default="carg1") - def csub(csub_opt, arg): - pass - - assert choices_without_help(cli, [], "-") == ["--cli-opt", "--help"] - assert choices_without_help(cli, [], "") == ["cliarg1", "cliarg2"] - assert choices_without_help(cli, ["cliarg1", "asub"], "-") == [ - "--asub-opt", - "--help", - ] - assert choices_without_help(cli, ["cliarg1", "asub"], "") == ["bsub", "csub"] - assert choices_without_help(cli, ["cliarg1", "bsub"], "") == ["arg1", "arg2"] - assert choices_without_help(cli, ["cliarg1", "asub", "--asub-opt"], "") == [] - assert choices_without_help( - cli, ["cliarg1", "asub", "--asub-opt", "5", "bsub"], "-" - ) == ["--bsub-opt", "--help"] - assert choices_without_help(cli, ["cliarg1", "asub", "bsub"], "-") == [ - "--bsub-opt", - "--help", - ] - assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "") == [ - "carg1", - "carg2", - ] - assert choices_without_help(cli, ["cliarg1", "bsub", "arg1", "csub"], "") == [ - "carg1", - "carg2", - ] - assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "-") == [ - "--csub-opt", - "--help", - ] - assert choices_with_help(cli, ["cliarg1", "asub"], "b") == [("bsub", "bsub help")] - - -def test_argument_choice(): - @click.command() - @click.argument("arg1", required=True, type=click.Choice(["arg11", "arg12"])) - @click.argument("arg2", type=click.Choice(["arg21", "arg22"]), default="arg21") - @click.argument("arg3", type=click.Choice(["arg", "argument"]), default="arg") - def cli(): - pass - - assert choices_without_help(cli, [], "") == ["arg11", "arg12"] - assert choices_without_help(cli, [], "arg") == ["arg11", "arg12"] - assert choices_without_help(cli, ["arg11"], "") == ["arg21", "arg22"] - assert choices_without_help(cli, ["arg12", "arg21"], "") == ["arg", "argument"] - assert choices_without_help(cli, ["arg12", "arg21"], "argu") == ["argument"] - - -def test_option_choice(): - @click.command() - @click.option("--opt1", type=click.Choice(["opt11", "opt12"]), help="opt1 help") - @click.option("--opt2", type=click.Choice(["opt21", "opt22"]), default="opt21") - @click.option("--opt3", type=click.Choice(["opt", "option"])) - def cli(): - pass - - assert choices_with_help(cli, [], "-") == [ - ("--opt1", "opt1 help"), - ("--opt2", None), - ("--opt3", None), - ("--help", "Show this message and exit."), - ] - assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2", "--opt3"] - assert choices_without_help(cli, [], "--opt1=") == ["opt11", "opt12"] - assert choices_without_help(cli, [], "--opt2=") == ["opt21", "opt22"] - assert choices_without_help(cli, ["--opt2"], "=") == ["opt21", "opt22"] - assert choices_without_help(cli, ["--opt2", "="], "opt") == ["opt21", "opt22"] - assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"] - assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"] - assert choices_without_help(cli, ["--opt1", "opt11", "--opt2"], "") == [ - "opt21", - "opt22", - ] - assert choices_without_help(cli, ["--opt2", "opt21"], "-") == [ - "--opt1", - "--opt3", - "--help", - ] - assert choices_without_help(cli, ["--opt1", "opt11"], "-") == [ - "--opt2", - "--opt3", - "--help", - ] - assert choices_without_help(cli, ["--opt1"], "opt") == ["opt11", "opt12"] - assert choices_without_help(cli, ["--opt3"], "opti") == ["option"] - - assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [ - "--opt2", - "--opt3", - "--help", - ] - - -def test_option_and_arg_choice(): - @click.command() - @click.option("--opt1", type=click.Choice(["opt11", "opt12"])) - @click.argument("arg1", required=False, type=click.Choice(["arg11", "arg12"])) - @click.option("--opt2", type=click.Choice(["opt21", "opt22"])) - def cli(): - pass - - assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"] - assert choices_without_help(cli, [""], "--opt1=") == ["opt11", "opt12"] - assert choices_without_help(cli, [], "") == ["arg11", "arg12"] - assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"] - assert choices_without_help(cli, ["arg11"], "--opt") == ["--opt1", "--opt2"] - assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2"] - - -def test_boolean_flag_choice(): - @click.command() - @click.option("--shout/--no-shout", default=False) - @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"])) - def cli(local_opt): - pass - - assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout", "--help"] - assert choices_without_help(cli, ["--shout"], "") == ["arg1", "arg2"] - - -def test_multi_value_option_choice(): - @click.command() - @click.option("--pos", nargs=2, type=click.Choice(["pos1", "pos2"])) - @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"])) - def cli(local_opt): - pass - - assert choices_without_help(cli, ["--pos"], "") == ["pos1", "pos2"] - assert choices_without_help(cli, ["--pos", "pos1"], "") == ["pos1", "pos2"] - assert choices_without_help(cli, ["--pos", "pos1", "pos2"], "") == ["arg1", "arg2"] - assert choices_without_help(cli, ["--pos", "pos1", "pos2", "arg1"], "") == [] - - -def test_multi_option_choice(): - @click.command() - @click.option("--message", "-m", multiple=True, type=click.Choice(["m1", "m2"])) - @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"])) - def cli(local_opt): - pass - - assert choices_without_help(cli, ["-m"], "") == ["m1", "m2"] - assert choices_without_help(cli, ["-m", "m1", "-m"], "") == ["m1", "m2"] - assert choices_without_help(cli, ["-m", "m1"], "") == ["arg1", "arg2"] - - -def test_variadic_argument_choice(): - @click.command() - @click.option("--opt", type=click.Choice(["opt1", "opt2"])) - @click.argument("src", nargs=-1, type=click.Choice(["src1", "src2"])) - def cli(local_opt): - pass - - assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"] - assert choices_without_help(cli, ["src1", "src2"], "--o") == ["--opt"] - assert choices_without_help(cli, ["src1", "src2", "--opt"], "") == ["opt1", "opt2"] - assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"] - - -def test_variadic_argument_complete(): - def _complete(ctx, args, incomplete): - return ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"] - - @click.group() - def entrypoint(): - pass - - @click.command() - @click.option("--opt", autocompletion=_complete) - @click.argument("arg", nargs=-1) - def subcommand(opt, arg): - pass - - entrypoint.add_command(subcommand) - - assert choices_without_help(entrypoint, ["subcommand", "--opt"], "") == _complete( - 0, 0, 0 - ) - assert choices_without_help( - entrypoint, ["subcommand", "whatever", "--opt"], "" - ) == _complete(0, 0, 0) - assert ( - choices_without_help(entrypoint, ["subcommand", "whatever", "--opt", "abc"], "") - == [] - ) - - -def test_long_chain_choice(): - @click.group() - def cli(): - pass - - @cli.group() - @click.option("--sub-opt", type=click.Choice(["subopt1", "subopt2"])) - @click.argument( - "sub-arg", required=False, type=click.Choice(["subarg1", "subarg2"]) - ) - def sub(sub_opt, sub_arg): - pass - - @sub.command(short_help="bsub help") - @click.option("--bsub-opt", type=click.Choice(["bsubopt1", "bsubopt2"])) - @click.argument( - "bsub-arg1", required=False, type=click.Choice(["bsubarg1", "bsubarg2"]) - ) - @click.argument( - "bbsub-arg2", required=False, type=click.Choice(["bbsubarg1", "bbsubarg2"]) - ) - def bsub(bsub_opt): - pass - - @sub.group("csub") - def csub(): - pass - - @csub.command() - def dsub(): - pass - - assert choices_with_help(cli, ["sub", "subarg1"], "") == [ - ("bsub", "bsub help"), - ("csub", ""), - ] - assert choices_without_help(cli, ["sub"], "") == ["subarg1", "subarg2"] - assert choices_without_help(cli, ["sub", "--sub-opt"], "") == ["subopt1", "subopt2"] - assert choices_without_help(cli, ["sub", "--sub-opt", "subopt1"], "") == [ - "subarg1", - "subarg2", - ] - assert choices_without_help( - cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], "-" - ) == ["--bsub-opt", "--help"] - assert choices_without_help( - cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], "" - ) == ["bsubarg1", "bsubarg2"] - assert choices_without_help( - cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub", "--bsub-opt"], "" - ) == ["bsubopt1", "bsubopt2"] - assert choices_without_help( - cli, - [ - "sub", - "--sub-opt", - "subopt1", - "subarg1", - "bsub", - "--bsub-opt", - "bsubopt1", - "bsubarg1", - ], - "", - ) == ["bbsubarg1", "bbsubarg2"] - assert choices_without_help( - cli, ["sub", "--sub-opt", "subopt1", "subarg1", "csub"], "" - ) == ["dsub"] - - -def test_chained_multi(): - @click.group() - def cli(): - pass - - @cli.group() - def sub(): - pass - - @sub.group() - def bsub(): - pass - - @sub.group(chain=True) - def csub(): - pass - - @csub.command() - def dsub(): - pass - - @csub.command() - def esub(): - pass - - assert choices_without_help(cli, ["sub"], "") == ["bsub", "csub"] - assert choices_without_help(cli, ["sub"], "c") == ["csub"] - assert choices_without_help(cli, ["sub", "csub"], "") == ["dsub", "esub"] - assert choices_without_help(cli, ["sub", "csub", "dsub"], "") == ["esub"] - - -def test_hidden(): - @click.group() - @click.option("--name", hidden=True) - @click.option("--choices", type=click.Choice([1, 2]), hidden=True) - def cli(name): - pass - - @cli.group(hidden=True) - def hgroup(): - pass - - @hgroup.group() - def hgroupsub(): - pass - - @cli.command() - def asub(): - pass - - @cli.command(hidden=True) - @click.option("--hname") - def hsub(): - pass - - assert choices_without_help(cli, [], "--n") == [] - assert choices_without_help(cli, [], "--c") == [] - # If the user exactly types out the hidden param, complete its options. - assert choices_without_help(cli, ["--choices"], "") == [1, 2] - assert choices_without_help(cli, [], "") == ["asub"] - assert choices_without_help(cli, [], "") == ["asub"] - assert choices_without_help(cli, [], "h") == [] - # If the user exactly types out the hidden command, complete its subcommands. - assert choices_without_help(cli, ["hgroup"], "") == ["hgroupsub"] - assert choices_without_help(cli, ["hsub"], "--h") == ["--hname", "--help"] - - [email protected]( - ("args", "part", "expect"), - [ - ([], "-", ["--opt", "--help"]), - (["value"], "--", ["--opt", "--help"]), - ([], "-o", []), - (["--opt"], "-o", []), - (["--"], "", ["name", "-o", "--opt", "--"]), - (["--"], "--o", ["--opt"]), - ], -) -def test_args_with_double_dash_complete(args, part, expect): - def _complete(ctx, args, incomplete): - values = ["name", "-o", "--opt", "--"] - return [x for x in values if x.startswith(incomplete)] - - @click.command() - @click.option("--opt") - @click.argument("args", nargs=-1, autocompletion=_complete) - def cli(opt, args): - pass - - assert choices_without_help(cli, args, part) == expect diff --git a/tests/test_compat.py b/tests/test_compat.py --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -4,23 +4,6 @@ from click._compat import WIN -def test_bash_func_name(): - from click._bashcomplete import get_completion_script - - script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip() - assert script.startswith("_foo_barbaz_blah_completion()") - assert "_COMPLETE_VAR=complete $1" in script - - -def test_zsh_func_name(): - from click._bashcomplete import get_completion_script - - script = get_completion_script("foo-bar", "_COMPLETE_VAR", "zsh").strip() - assert script.startswith("#compdef foo-bar") - assert "compdef _foo_bar_completion foo-bar;" in script - assert "(( ! $+commands[foo-bar] )) && return 1" in script - - @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows") def test_is_jupyter_kernel_output(): class JupyterKernelFakeStream: diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py new file mode 100644 --- /dev/null +++ b/tests/test_shell_completion.py @@ -0,0 +1,277 @@ +import sys + +import pytest + +from click.core import Argument +from click.core import Command +from click.core import Group +from click.core import Option +from click.shell_completion import CompletionItem +from click.shell_completion import ShellComplete +from click.types import Choice +from click.types import File +from click.types import Path + + +def _get_completions(cli, args, incomplete): + comp = ShellComplete(cli, cli.name, "_CLICK_COMPLETE") + return comp.get_completions(args, incomplete) + + +def _get_words(cli, args, incomplete): + return [c.value for c in _get_completions(cli, args, incomplete)] + + +def test_command(): + cli = Command("cli", params=[Option(["-t", "--test"])]) + assert _get_words(cli, [], "") == [] + assert _get_words(cli, [], "-") == ["-t", "--test", "--help"] + assert _get_words(cli, [], "--") == ["--test", "--help"] + assert _get_words(cli, [], "--t") == ["--test"] + # -t has been seen, so --test isn't suggested + assert _get_words(cli, ["-t", "a"], "-") == ["--help"] + + +def test_group(): + cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")]) + assert _get_words(cli, [], "") == ["x", "y"] + assert _get_words(cli, [], "-") == ["-a", "--help"] + + +def test_group_command_same_option(): + cli = Group( + "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])] + ) + assert _get_words(cli, [], "-") == ["-a", "--help"] + assert _get_words(cli, ["-a", "a"], "-") == ["--help"] + assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"] + assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"] + + +def test_chained(): + cli = Group( + "cli", + chain=True, + commands=[ + Command("set", params=[Option(["-y"])]), + Command("start"), + Group("get", commands=[Command("full")]), + ], + ) + assert _get_words(cli, [], "") == ["get", "set", "start"] + assert _get_words(cli, [], "s") == ["set", "start"] + assert _get_words(cli, ["set", "start"], "") == ["get"] + # subcommands and parent subcommands + assert _get_words(cli, ["get"], "") == ["full", "set", "start"] + assert _get_words(cli, ["get", "full"], "") == ["set", "start"] + assert _get_words(cli, ["get"], "s") == ["set", "start"] + + +def test_help_option(): + cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)]) + assert _get_words(cli, ["with"], "--") == ["--help"] + assert _get_words(cli, ["no"], "--") == [] + + +def test_argument_order(): + cli = Command( + "cli", + params=[ + Argument(["plain"]), + Argument(["c1"], type=Choice(["a1", "a2", "b"])), + Argument(["c2"], type=Choice(["c1", "c2", "d"])), + ], + ) + # first argument has no completions + assert _get_words(cli, [], "") == [] + assert _get_words(cli, [], "a") == [] + # first argument filled, now completion can happen + assert _get_words(cli, ["x"], "a") == ["a1", "a2"] + assert _get_words(cli, ["x", "b"], "d") == ["d"] + + +def test_type_choice(): + cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))]) + assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"] + assert _get_words(cli, ["-c"], "a") == ["a1", "a2"] + assert _get_words(cli, ["-c"], "a2") == ["a2"] + + [email protected]( + ("type", "expect"), + [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")], +) +def test_path_types(type, expect): + cli = Command("cli", params=[Option(["-f"], type=type)]) + out = _get_completions(cli, ["-f"], "ab") + assert len(out) == 1 + c = out[0] + assert c.value == "ab" + assert c.type == expect + + +def test_option_flag(): + cli = Command( + "cli", + add_help_option=False, + params=[ + Option(["--on/--off"]), + Argument(["a"], type=Choice(["a1", "a2", "b"])), + ], + ) + assert _get_words(cli, ["type"], "--") == ["--on", "--off"] + # flag option doesn't take value, use choice argument + assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"] + + +def test_option_custom(): + def custom(ctx, param, incomplete): + return [incomplete.upper()] + + cli = Command( + "cli", + params=[ + Argument(["x"]), + Argument(["y"]), + Argument(["z"], shell_complete=custom), + ], + ) + assert _get_words(cli, ["a", "b"], "") == [""] + assert _get_words(cli, ["a", "b"], "c") == ["C"] + + +def test_autocompletion_deprecated(): + # old function takes args and not param, returns all values, can mix + # strings and tuples + def custom(ctx, args, incomplete): + assert isinstance(args, list) + return [("art", "x"), "bat", "cat"] + + with pytest.deprecated_call(): + cli = Command("cli", params=[Argument(["x"], autocompletion=custom)]) + + assert _get_words(cli, [], "") == ["art", "bat", "cat"] + assert _get_words(cli, [], "c") == ["cat"] + + +def test_option_multiple(): + cli = Command( + "type", + params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])], + ) + assert _get_words(cli, ["-m"], "") == ["a", "b"] + assert "-m" in _get_words(cli, ["-m", "a"], "-") + assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"] + # used single options aren't suggested again + assert "-c" not in _get_words(cli, ["-c", "f"], "-") + + +def test_option_nargs(): + cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)]) + assert _get_words(cli, ["-c"], "") == ["a", "b"] + assert _get_words(cli, ["-c", "a"], "") == ["a", "b"] + assert _get_words(cli, ["-c", "a", "b"], "") == [] + + +def test_argument_nargs(): + cli = Command( + "cli", + params=[ + Argument(["x"], type=Choice(["a", "b"]), nargs=2), + Argument(["y"], type=Choice(["c", "d"]), nargs=-1), + Option(["-z"]), + ], + ) + assert _get_words(cli, [], "") == ["a", "b"] + assert _get_words(cli, ["a"], "") == ["a", "b"] + assert _get_words(cli, ["a", "b"], "") == ["c", "d"] + assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"] + assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"] + assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"] + assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"] + + +def test_double_dash(): + cli = Command( + "cli", + add_help_option=False, + params=[ + Option(["--opt"]), + Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])), + ], + ) + assert _get_words(cli, [], "-") == ["--opt"] + assert _get_words(cli, ["value"], "-") == ["--opt"] + assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"] + assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"] + + +def test_hidden(): + cli = Group( + "cli", + commands=[ + Command( + "hidden", + add_help_option=False, + hidden=True, + params=[ + Option(["-a"]), + Option(["-b"], type=Choice(["a", "b"]), hidden=True), + ], + ) + ], + ) + assert "hidden" not in _get_words(cli, [], "") + assert "hidden" not in _get_words(cli, [], "hidden") + assert _get_words(cli, ["hidden"], "-") == ["-a"] + assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"] + + +def test_add_different_name(): + cli = Group("cli", commands={"renamed": Command("original")}) + words = _get_words(cli, [], "") + assert "renamed" in words + assert "original" not in words + + +def test_completion_item_data(): + c = CompletionItem("test", a=1) + assert c.a == 1 + assert c.b is None + + [email protected]() +def _patch_for_completion(monkeypatch): + monkeypatch.setattr("click.core._fast_exit", sys.exit) + monkeypatch.setattr( + "click.shell_completion.BashComplete._check_version", lambda self: True + ) + + [email protected]( + "shell", ["bash", "zsh", "fish"], +) [email protected]("_patch_for_completion") +def test_full_source(runner, shell): + cli = Group("cli", commands=[Command("a"), Command("b")]) + result = runner.invoke(cli, env={"_CLI_COMPLETE": f"source_{shell}"}) + assert f"_CLI_COMPLETE=complete_{shell}" in result.output + + [email protected]( + ("shell", "env", "expect"), + [ + ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"), + ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"), + ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"), + ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"), + ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"), + ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"), + ], +) [email protected]("_patch_for_completion") +def test_full_complete(runner, shell, env, expect): + cli = Group("cli", commands=[Command("a"), Command("b", help="bee")]) + env["_CLI_COMPLETE"] = f"complete_{shell}" + result = runner.invoke(cli, env=env) + assert result.output == expect
Tab completion behavior for click.File and click.Path types Lets say this is related to #241 ... Recently support was added to have argument autocompletion, custom completion functions/lists and a special case for click.Choice options too. This is great ! I would like to see better support for filenames and directories, have been looking at the code and wanted to share my thoughts here... as far as I can see the problems with filename/directory are multiple but hopefully addressed with a couple of simple patches. ### Undesirable Autocompletion of paths In the case that the user is completing an option which takes one or more arguments, and those arguments cannot be completed (i.e. they are just a string or integer type), then the builtin completion mechanism correctly reports no results, however the bash completion glue ([here](https://github.com/pallets/click/blob/master/click/_bashcomplete.py#L22)) specifies *"-o default"* This parameter to the bash *complete* function tells bash to default to completing paths when the resulting COMPREPLY array is empty, and the side effect is undesirable filenames being completed. ### Filenames reported for directory arguments Because click does not do anything for filenames or directories itself, it instead falls back on the undesirable *complete -o default* behavior mentioned above for filenames and all arguments which did not supply any custom autocompletion list or function. This means that filenames are suggested when the argument is in fact a directory, and also directory names are suggested for filenames. ### Filename and directory completion has different behavior The default shell behavior is to take the reported list in COMPREPLY, and if there is only one element, it will append a space and the next TAB is ready to complete the next token, but this is not the desired behavior when completing paths, where you want to complete only one directory at a time. This can be addressed however by using the *"complete -o nospace ..."* option, which will just cause the shell to not append any space for a single available completion, allowing the program to continue completing the last completion on the next iteration. In this case, click can: * Append a space to the reported completion in the case that only one completion was available * Append a slash (if none is already there), in the case that the completion is a directory name ### Proposed Approach Instead of handling click.Choice explicitly in _bashcompletion.py, we should instead have the base ParamType cooperate in the process of completion, so that paths and filenames can have an opportunity to decide if the parameter is entirely complete or could be completed further (i.e. whether a space should be appended to the reported completion, or whether it should remain, as in the case for a filename which is a directory that could be completed further). click.Choice would implement completions by overriding an abstract method of click.ParamType, click.BOOL could also implement this, because why not. The new *autocompletion* attribute would be checked before ever consulting the click.ParamType abstract method, so the user can always override the default completions for any parameter. Also, we should change the completion script to not use *"-o default"* and use *"-o nospace"* instead, ensuring that filenames dont show up by default. Finally, the click.Path and click.File need to do the work we were previously offloading to the shell, this is the most tricky (or *"meaty"*) part of the patch I guess, hopefully a python implementation using *os.listdir()* and file concatenation would not slow down the completion process too much.
So I'm personally quite satisfied with #782 as a solution for this, sorry at first I missed the test cases and came back to adjust the existing ones and add some additional test cases for Path types. One thing I'm not sure of is if I'm entirely satisfied with the API surface, although it does work. In order to deal with completion of tree like data, we have two types of completion result; those with trailing spaces and those without. For the bash facing results in COMPREPLY, this must remain the case for reasons explained in the report above. However for the developer facing APIs of ParamType implementations and the `autocompletion` attribute now available in the decorators, this might not be the most comfortable. The options I could see for this are: * Let the implementors append a space for completely completed suggestions, and returning strings that lack a trailing space is an indicator that this completion could be completed further (that is the current approach) * Have the completion functions (ParamType->completions() and autocompletion callbacks) return a tuple of *two* lists instead of one With the second approach, we would append spaces to *completely completed suggestions* automatically inside `_bashcompletion.py` and have the implementors report results without the appended spaces, which may be a more comfortable API. Also, I agree with comments in #428 that `autocompletion` could be named better, either `suggests` or `completions` would be nicer words for this, but that is a separate issue. Would love to hear feedback from the click maintainership on this patch series :) Adding @untitaker on cc... I'm rather against removing `-o default`. It appears to be convention to allow filenames when the custom completion doesn't work, at least with git it does. >This can be addressed however by using the "complete -o nospace ..." option, which will just cause the shell to not append any space for a single available completion, allowing the program to continue completing the last completion on the next iteration. This appears to be inacceptable to me, since it affects completion of e.g. subcommands as well. I'd rather accept that files and directories are mixed up in the completion. If one were to implement custom completion for directories, that would mean one would have to recursively traverse and output all directories to avoid appending the space in the case of only one top-level directory name matching. That is slow. > I'm rather against removing -o default. It appears to be convention to allow > filenames when the custom completion doesn't work, at least with git it does. For what it's worth, git is not a great example. However the effort various applications have made vary quite widely, a lot of coreutils and standard gnu tools never complete option names for instance. Here are some comparisons: ```bash # -f is a file argument, completes directories and filenames $ make -f <TAB> dira/ dirb/ file1 file2 # -C/--directory is directory option, completes only directories $ make -C <TAB> dira/ dirb/ # tar's -C option is not as smart $ tar -C <TAB> dira/ dirb/ file1 file2 # tar's -f option is however smart, it will only complete filenames # of the expected filename extensions, it will even take the expected # compression algorithm into account if it was specified $ tar -f <TAB> tarball.tar tarball.tgz tarball.tar.bz2 $ tar -zxf <TAB> tarball.tgz # tar at least does not complete filenames when a string is expected $ tar --quote-chars <TAB> (no completeions here) # git's -C is like make's directory, but it fails to complete a directory # and goes on to complete subcommands $ git -C <TAB> add am annotate apply archive ... ``` > This appears to be inacceptable to me, since it affects completion of e.g. subcommands > as well. I'd rather accept that files and directories are mixed up in the completion. Behavior of subcommand and option name completion still works exactly as expected, in fact the user experience for this is unchanged. Note the test case is changed to expect the trailing spaces which are needed to report to the shell, but that is just the internal `get_choices()` api. > If one were to implement custom completion for directories, that would mean one would have to > recursively traverse and output all directories to avoid appending the space in the case of only one > top-level directory name matching. That is slow. In fact, without `-o nospace` your statement is true; with the *current API* it is impossible to efficiently implement custom completion of any large tree/path like data sets. Note that this is implemented in #782, what you do is *not* append a space to complete one directory at a time, in the next iteration the *incomplete* text contains to *so far* completed text. Currently, if you want to do completions in iteration on any tree/path like dataset, either: * You list one component, and bash appends a space, so all bets are off for the next iteration, you are already completing the next argument * You list every branch/leaf node recursively, which will * Be slow, as you mentioned * Have an unfriendly experience, bash will ask you if you really want to display all 11894 possibilities in the shell, for example +1 for having a way to customize argument expansion in particular. In the popular `git` multi command example, completing e.g. branches to checkout is very helpful, but you wouldn't want to add pseudo-subcommands for each and every one of them. Just having API to extend completion would be great! I also experienced the same issue. `main()` is never called, so the context is not properly populated, and you can't reuse the shared state for the autocomplete. In my case, `main()` has db connection settings. Defines a DB object in the context, and commands can use the db directly. But the autocomplete now doesn't have access to the DB without the proper context. What is status of this, is open for 2 years, anything blocking this from being merged? (#782) No news about this issue? This is not exactly solving this issue, but can take you a long way and hasn't been mentioned on this thread: check out https://github.com/click-contrib/click-completion Could I confirm that file completions aren't expected to work at all on master? I'm not able to get any file or directory completions working. When I monkey patch something like #1403, it does work. @max-sixty Work is being done on https://github.com/pallets/click/pull/1622 that should change that soon. The docs talk a bit more about completion support https://click.palletsprojects.com/en/7.x/bashcomplete/#what-it-completes (and what it supports currently) Thanks @kx-chen ! That looks very encouraging! Will this merge https://github.com/click-contrib/click-completion then? The new design is discussed in #1484. click-completion will not be merged, and may not be compatible with the new system at first. The new system will be much more extensible though, so click-completion or other extensions can add to it more easily.
2020-07-07T18:11:35Z
[]
[]
pallets/click
1,623
pallets__click-1623
[ "461" ]
a4bd11c2f9c18daa9c27508cc05073991e39ec9e
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -413,6 +413,27 @@ def __init__( self._source_by_paramname = {} self._exit_stack = ExitStack() + def to_info_dict(self): + """Gather information that could be useful for a tool generating + user-facing documentation. This traverses the entire CLI + structure. + + .. code-block:: python + + with Context(cli) as ctx: + info = ctx.to_info_dict() + + .. versionadded:: 8.0 + """ + return { + "command": self.command.to_info_dict(self), + "info_name": self.info_name, + "allow_extra_args": self.allow_extra_args, + "allow_interspersed_args": self.allow_interspersed_args, + "ignore_unknown_options": self.ignore_unknown_options, + "auto_envvar_prefix": self.auto_envvar_prefix, + } + def __enter__(self): self._depth += 1 push_context(self) @@ -632,6 +653,14 @@ def get_help(self): """ return self.command.get_help(self) + def _make_sub_context(self, command): + """Create a new context of the same type as this context, but + for a new command. + + :meta private: + """ + return type(self)(command, info_name=command.name, parent=self) + def invoke(*args, **kwargs): # noqa: B902 """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: @@ -663,8 +692,7 @@ def invoke(*args, **kwargs): # noqa: B902 "The given command does not have a callback that can be invoked." ) - # Create a new context of the same type as this context. - ctx = type(self)(other_cmd, info_name=other_cmd.name, parent=self) + ctx = self._make_sub_context(other_cmd) for param in other_cmd.params: if param.name not in kwargs and param.expose_value: @@ -766,6 +794,20 @@ def __init__(self, name, context_settings=None): #: an optional dictionary with defaults passed to the context. self.context_settings = context_settings + def to_info_dict(self, ctx): + """Gather information that could be useful for a tool generating + user-facing documentation. This traverses the entire structure + below this command. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + :param ctx: A :class:`Context` representing this command. + + .. versionadded:: 8.0 + """ + return {"name": self.name} + def __repr__(self): return f"<{self.__class__.__name__} {self.name}>" @@ -1000,6 +1042,18 @@ def __init__( self.hidden = hidden self.deprecated = deprecated + def to_info_dict(self, ctx): + info_dict = super().to_info_dict(ctx) + info_dict.update( + params=[param.to_info_dict() for param in self.get_params(ctx)], + help=self.help, + epilog=self.epilog, + short_help=self.short_help, + hidden=self.hidden, + deprecated=self.deprecated, + ) + return info_dict + def __repr__(self): return f"<{self.__class__.__name__} {self.name}>" @@ -1232,6 +1286,20 @@ def __init__( " optional arguments." ) + def to_info_dict(self, ctx): + info_dict = super().to_info_dict(ctx) + commands = {} + + for name in self.list_commands(ctx): + command = self.get_command(ctx, name) + sub_ctx = ctx._make_sub_context(command) + + with sub_ctx.scope(cleanup=False): + commands[name] = command.to_info_dict(sub_ctx) + + info_dict.update(commands=commands, chain=self.chain) + return info_dict + def collect_usage_pieces(self, ctx): rv = super().collect_usage_pieces(ctx) rv.append(self.subcommand_metavar) @@ -1661,6 +1729,28 @@ def __init__( self.envvar = envvar self.autocompletion = autocompletion + def to_info_dict(self): + """Gather information that could be useful for a tool generating + user-facing documentation. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + .. versionadded:: 8.0 + """ + return { + "name": self.name, + "param_type_name": self.param_type_name, + "opts": self.opts, + "secondary_opts": self.secondary_opts, + "type": self.type.to_info_dict(), + "required": self.required, + "nargs": self.nargs, + "multiple": self.multiple, + "default": self.default, + "envvar": self.envvar, + } + def __repr__(self): return f"<{self.__class__.__name__} {self.name}>" @@ -1955,6 +2045,18 @@ def __init__( "Options cannot be count and flags at the same time." ) + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict.update( + help=self.help, + prompt=self.prompt, + is_flag=self.is_flag, + flag_value=self.flag_value, + count=self.count, + hidden=self.hidden, + ) + return info_dict + def _parse_decls(self, decls, expose_value): opts = [] secondary_opts = [] diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -43,6 +43,20 @@ class ParamType: #: Windows). envvar_list_splitter = None + def to_info_dict(self): + """Gather information that could be useful for a tool generating + user-facing documentation. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + .. versionadded:: 8.0 + """ + # The class name without the "ParamType" suffix. + param_type = type(self).__name__.partition("ParamType")[0] + param_type = param_type.partition("ParameterType")[0] + return {"param_type": param_type, "name": self.name} + def __call__(self, value, param=None, ctx=None): if value is not None: return self.convert(value, param, ctx) @@ -107,6 +121,11 @@ def __init__(self, func): self.name = func.__name__ self.func = func + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict["func"] = self.func + return info_dict + def convert(self, value, param, ctx): try: return self.func(value) @@ -176,6 +195,12 @@ def __init__(self, choices, case_sensitive=True): self.choices = choices self.case_sensitive = case_sensitive + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict["choices"] = self.choices + info_dict["case_sensitive"] = self.case_sensitive + return info_dict + def get_metavar(self, param): choices_str = "|".join(self.choices) @@ -251,6 +276,11 @@ class DateTime(ParamType): def __init__(self, formats=None): self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"] + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict["formats"] = self.formats + return info_dict + def get_metavar(self, param): return f"[{'|'.join(self.formats)}]" @@ -293,6 +323,17 @@ def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=Fal self.max_open = max_open self.clamp = clamp + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict.update( + min=self.min, + max=self.max, + min_open=self.min_open, + max_open=self.max_open, + clamp=self.clamp, + ) + return info_dict + def convert(self, value, param, ctx): import operator @@ -492,6 +533,11 @@ def __init__( self.lazy = lazy self.atomic = atomic + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict.update(mode=self.mode, encoding=self.encoding) + return info_dict + def resolve_lazy_flag(self, value): if self.lazy is not None: return self.lazy @@ -601,6 +647,18 @@ def __init__( self.name = "path" self.path_type = "Path" + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict.update( + exists=self.exists, + file_okay=self.file_okay, + dir_okay=self.dir_okay, + writable=self.writable, + readable=self.readable, + allow_dash=self.allow_dash, + ) + return info_dict + def coerce_path_result(self, rv): if self.type is not None and not isinstance(rv, self.type): if self.type is str: @@ -674,6 +732,11 @@ class Tuple(CompositeParamType): def __init__(self, types): self.types = [convert_type(ty) for ty in types] + def to_info_dict(self): + info_dict = super().to_info_dict() + info_dict["types"] = [t.to_info_dict() for t in self.types] + return info_dict + @property def name(self): return f"<{' '.join(ty.name for ty in self.types)}>"
diff --git a/tests/test_info_dict.py b/tests/test_info_dict.py new file mode 100644 --- /dev/null +++ b/tests/test_info_dict.py @@ -0,0 +1,268 @@ +import pytest + +import click.types + +# Common (obj, expect) pairs used to construct multiple tests. +STRING_PARAM_TYPE = (click.STRING, {"param_type": "String", "name": "text"}) +INT_PARAM_TYPE = (click.INT, {"param_type": "Int", "name": "integer"}) +BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"}) +HELP_OPTION = ( + None, + { + "name": "help", + "param_type_name": "option", + "opts": ["--help"], + "secondary_opts": [], + "type": BOOL_PARAM_TYPE[1], + "required": False, + "nargs": 1, + "multiple": False, + "default": False, + "envvar": None, + "help": "Show this message and exit.", + "prompt": None, + "is_flag": True, + "flag_value": True, + "count": False, + "hidden": False, + }, +) +NAME_ARGUMENT = ( + click.Argument(["name"]), + { + "name": "name", + "param_type_name": "argument", + "opts": ["name"], + "secondary_opts": [], + "type": STRING_PARAM_TYPE[1], + "required": True, + "nargs": 1, + "multiple": False, + "default": None, + "envvar": None, + }, +) +NUMBER_OPTION = ( + click.Option(["-c", "--count", "number"], default=1), + { + "name": "number", + "param_type_name": "option", + "opts": ["-c", "--count"], + "secondary_opts": [], + "type": INT_PARAM_TYPE[1], + "required": False, + "nargs": 1, + "multiple": False, + "default": 1, + "envvar": None, + "help": None, + "prompt": None, + "is_flag": False, + "flag_value": False, + "count": False, + "hidden": False, + }, +) +HELLO_COMMAND = ( + click.Command("hello", params=[NUMBER_OPTION[0]]), + { + "name": "hello", + "params": [NUMBER_OPTION[1], HELP_OPTION[1]], + "help": None, + "epilog": None, + "short_help": None, + "hidden": False, + "deprecated": False, + }, +) +HELLO_GROUP = ( + click.Group("cli", [HELLO_COMMAND[0]]), + { + "name": "cli", + "params": [HELP_OPTION[1]], + "help": None, + "epilog": None, + "short_help": None, + "hidden": False, + "deprecated": False, + "commands": {"hello": HELLO_COMMAND[1]}, + "chain": False, + }, +) + + [email protected]( + ("obj", "expect"), + [ + pytest.param( + click.types.FuncParamType(range), + {"param_type": "Func", "name": "range", "func": range}, + id="Func ParamType", + ), + pytest.param( + click.UNPROCESSED, + {"param_type": "Unprocessed", "name": "text"}, + id="UNPROCESSED ParamType", + ), + pytest.param(*STRING_PARAM_TYPE, id="STRING ParamType"), + pytest.param( + click.Choice(["a", "b"]), + { + "param_type": "Choice", + "name": "choice", + "choices": ["a", "b"], + "case_sensitive": True, + }, + id="Choice ParamType", + ), + pytest.param( + click.DateTime(["%Y-%m-%d"]), + {"param_type": "DateTime", "name": "datetime", "formats": ["%Y-%m-%d"]}, + id="DateTime ParamType", + ), + pytest.param(*INT_PARAM_TYPE, id="INT ParamType"), + pytest.param( + click.IntRange(0, 10, clamp=True), + { + "param_type": "IntRange", + "name": "integer range", + "min": 0, + "max": 10, + "min_open": False, + "max_open": False, + "clamp": True, + }, + id="IntRange ParamType", + ), + pytest.param( + click.FLOAT, {"param_type": "Float", "name": "float"}, id="FLOAT ParamType" + ), + pytest.param( + click.FloatRange(-0.5, 0.5), + { + "param_type": "FloatRange", + "name": "float range", + "min": -0.5, + "max": 0.5, + "min_open": False, + "max_open": False, + "clamp": False, + }, + id="FloatRange ParamType", + ), + pytest.param(*BOOL_PARAM_TYPE, id="Bool ParamType"), + pytest.param( + click.UUID, {"param_type": "UUID", "name": "uuid"}, id="UUID ParamType" + ), + pytest.param( + click.File(), + {"param_type": "File", "name": "filename", "mode": "r", "encoding": None}, + id="File ParamType", + ), + pytest.param( + click.Path(), + { + "param_type": "Path", + "name": "path", + "exists": False, + "file_okay": True, + "dir_okay": True, + "writable": False, + "readable": True, + "allow_dash": False, + }, + id="Path ParamType", + ), + pytest.param( + click.Tuple((click.STRING, click.INT)), + { + "param_type": "Tuple", + "name": "<text integer>", + "types": [STRING_PARAM_TYPE[1], INT_PARAM_TYPE[1]], + }, + id="Tuple ParamType", + ), + pytest.param(*NUMBER_OPTION, id="Option"), + pytest.param( + click.Option(["--cache/--no-cache", "-c/-u"]), + { + "name": "cache", + "param_type_name": "option", + "opts": ["--cache", "-c"], + "secondary_opts": ["--no-cache", "-u"], + "type": BOOL_PARAM_TYPE[1], + "required": False, + "nargs": 1, + "multiple": False, + "default": False, + "envvar": None, + "help": None, + "prompt": None, + "is_flag": True, + "flag_value": True, + "count": False, + "hidden": False, + }, + id="Flag Option", + ), + pytest.param(*NAME_ARGUMENT, id="Argument"), + ], +) +def test_parameter(obj, expect): + out = obj.to_info_dict() + assert out == expect + + [email protected]( + ("obj", "expect"), + [ + pytest.param(*HELLO_COMMAND, id="Command"), + pytest.param(*HELLO_GROUP, id="Group"), + pytest.param( + click.Group( + "base", + [click.Command("test", params=[NAME_ARGUMENT[0]]), HELLO_GROUP[0]], + ), + { + "name": "base", + "params": [HELP_OPTION[1]], + "help": None, + "epilog": None, + "short_help": None, + "hidden": False, + "deprecated": False, + "commands": { + "cli": HELLO_GROUP[1], + "test": { + "name": "test", + "params": [NAME_ARGUMENT[1], HELP_OPTION[1]], + "help": None, + "epilog": None, + "short_help": None, + "hidden": False, + "deprecated": False, + }, + }, + "chain": False, + }, + id="Nested Group", + ), + ], +) +def test_command(obj, expect): + ctx = click.Context(obj) + out = obj.to_info_dict(ctx) + assert out == expect + + +def test_context(): + ctx = click.Context(HELLO_COMMAND[0]) + out = ctx.to_info_dict() + assert out == { + "command": HELLO_COMMAND[1], + "info_name": None, + "allow_extra_args": False, + "allow_interspersed_args": True, + "ignore_unknown_options": False, + "auto_envvar_prefix": None, + }
Export JSON Data of Click Structure For external tools it would be nice if one could export the entire data of a click command into a JSON format. For instance that way one could generate externally hosted documentation pages for commands that use better formatting than what `--help` generates.
If we were to do this in Click core, as opposed to a separate project, I'd imagine we'd add a `to_info_dict()` method to `BaseCommand`, `Parameter`, and `ParamType`, overriding as necessary. Is there something specific that's not easy to introspect currently, though? And how detailed should the dict be? Should it include every parameter? Computed attributes like `auto_envvar_prefix`? A separate project could take advantage of other libraries like Marshmallow to give the serialized data more structure as well. I guess I'm not opposed to it, and implementing it here in some form doesn't prevent another project from extending it or offering a different method. @chrisngyn and I will be working on this! For example, `group.to_info_dict()` would put the group name, help, etc. in, then call `command.to_info_dict()` for each command returned by `list_commands()`, and put that list under a "commands" key. So any given object would build itself plus anything under it, and a subclass could override what happens. I think there are some other open issues about being able to traverse the structure without triggering prompts and validation, since that functionality exists but isn't perfect. As a first pass, don't worry about these, note them down and they can be addressed separately.
2020-07-09T16:52:59Z
[]
[]
pallets/click
1,630
pallets__click-1630
[ "1629" ]
5eaa4c5cba417fb4b65e5b9f5810e6043a312594
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -387,11 +387,11 @@ def convert(self, value, param, ctx): if isinstance(value, bool): return bool(value) value = value.lower() - if value in ("true", "t", "1", "yes", "y"): + if value in {"1", "true", "t", "yes", "y", "on"}: return True - elif value in ("false", "f", "0", "no", "n"): + elif value in {"0", "false", "f", "no", "n", "off"}: return False - self.fail(f"{value} is not a valid boolean", param, ctx) + self.fail(f"{value!r} is not a valid boolean value.", param, ctx) def __repr__(self): return "BOOL"
diff --git a/tests/test_basic.py b/tests/test_basic.py --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -1,5 +1,8 @@ import os import uuid +from itertools import chain + +import pytest import click @@ -198,27 +201,24 @@ def cli(flag): assert result.output == f"{default}\n" -def test_boolean_conversion(runner): - for default in True, False: - - @click.command() - @click.option("--flag", default=default, type=bool) - def cli(flag): - click.echo(flag) - - for value in "true", "t", "1", "yes", "y": - result = runner.invoke(cli, ["--flag", value]) - assert not result.exception - assert result.output == "True\n" [email protected]( + ("value", "expect"), + chain( + ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")), + ((x, "False") for x in ("0", "false", "f", "no", "n", "off")), + ), +) +def test_boolean_conversion(runner, value, expect): + @click.command() + @click.option("--flag", type=bool) + def cli(flag): + click.echo(flag, nl=False) - for value in "false", "f", "0", "no", "n": - result = runner.invoke(cli, ["--flag", value]) - assert not result.exception - assert result.output == "False\n" + result = runner.invoke(cli, ["--flag", value]) + assert result.output == expect - result = runner.invoke(cli, []) - assert not result.exception - assert result.output == f"{default}\n" + result = runner.invoke(cli, ["--flag", value.title()]) + assert result.output == expect def test_file_option(runner):
BOOL should accept "on" and "off" The `BOOL` parameter type should accept & convert the strings "on" and "off". With this change, `BOOL` would support all of the boolean strings that `configparser` supports.
2020-07-17T21:37:10Z
[]
[]
pallets/click
1,679
pallets__click-1679
[ "942" ]
6c8301e0ceeee124dc4ae3a51591c5810dc39840
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -950,7 +950,7 @@ def main( prog_name = _detect_program_name() # Process shell completion requests and exit early. - self._main_shell_completion(prog_name, complete_var) + self._main_shell_completion(extra, prog_name, complete_var) try: try: @@ -1000,7 +1000,7 @@ def main( echo("Aborted!", file=sys.stderr) sys.exit(1) - def _main_shell_completion(self, prog_name, complete_var=None): + def _main_shell_completion(self, ctx_args, prog_name, complete_var=None): """Check if the shell is asking for tab completion, process that, then exit early. Called from :meth:`main` before the program is invoked. @@ -1020,7 +1020,7 @@ def _main_shell_completion(self, prog_name, complete_var=None): from .shell_completion import shell_complete - rv = shell_complete(self, prog_name, complete_var, instruction) + rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) _fast_exit(rv) def __call__(self, *args, **kwargs): diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -8,10 +8,12 @@ from .utils import echo -def shell_complete(cli, prog_name, complete_var, instruction): +def shell_complete(cli, ctx_args, prog_name, complete_var, instruction): """Perform shell completion for the given CLI program. :param cli: Command being called. + :param ctx_args: Extra arguments to pass to + ``cli.make_context``. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. @@ -25,7 +27,7 @@ def shell_complete(cli, prog_name, complete_var, instruction): if comp_cls is None: return 1 - comp = comp_cls(cli, prog_name, complete_var) + comp = comp_cls(cli, ctx_args, prog_name, complete_var) if instruction == "source": echo(comp.source()) @@ -190,8 +192,9 @@ class ShellComplete: be provided by subclasses. """ - def __init__(self, cli, prog_name, complete_var): + def __init__(self, cli, ctx_args, prog_name, complete_var): self.cli = cli + self.ctx_args = ctx_args self.prog_name = prog_name self.complete_var = complete_var @@ -238,7 +241,7 @@ def get_completions(self, args, incomplete): :param args: List of complete args before the incomplete value. :param incomplete: Value being completed. May be empty. """ - ctx = _resolve_context(self.cli, self.prog_name, args) + ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args) if ctx is None: return [] @@ -446,7 +449,7 @@ def _is_incomplete_option(args, param): return last_option is not None and last_option in param.opts -def _resolve_context(cli, prog_name, args): +def _resolve_context(cli, ctx_args, prog_name, args): """Produce the context hierarchy starting with the command and traversing the complete arguments. This only follows the commands, it doesn't trigger input prompts or callbacks. @@ -455,7 +458,8 @@ def _resolve_context(cli, prog_name, args): :param prog_name: Name of the executable in the shell. :param args: List of complete args before the incomplete value. """ - ctx = cli.make_context(prog_name, args.copy(), resilient_parsing=True) + ctx_args["resilient_parsing"] = True + ctx = cli.make_context(prog_name, args.copy(), **ctx_args) args = ctx.protected_args + ctx.args while args:
diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py --- a/tests/test_shell_completion.py +++ b/tests/test_shell_completion.py @@ -14,7 +14,7 @@ def _get_completions(cli, args, incomplete): - comp = ShellComplete(cli, cli.name, "_CLICK_COMPLETE") + comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE") return comp.get_completions(args, incomplete) @@ -275,3 +275,17 @@ def test_full_complete(runner, shell, env, expect): env["_CLI_COMPLETE"] = f"complete_{shell}" result = runner.invoke(cli, env=env) assert result.output == expect + + [email protected]("_patch_for_completion") +def test_context_settings(runner): + def complete(ctx, param, incomplete): + return ctx.obj["choices"] + + cli = Command("cli", params=[Argument("x", shell_complete=complete)]) + result = runner.invoke( + cli, + obj={"choices": ["a", "b"]}, + env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "complete_bash"}, + ) + assert result.output == "plain,a\nplain,b\n"
With argument autocompletion, context is not passed properly I used the current master revision: $ pip3 install git+https://github.com/pallets/click.git@55682f6f5348f5220a557f89c3a796321a52aebf and an executable file `testclick`: ```python #!/usr/bin/env python3 import click def _complete(ctx, args, incomplete): return ctx.obj['completions'] @click.group() @click.pass_context def entrypoint(ctx): pass @entrypoint.command() @click.argument('arg', type=click.STRING, autocompletion=_complete) @click.pass_context def subcommand(ctx, arg): print('arg={}'.format(arg)) entrypoint(obj={'completions': ['abc', 'def', 'ghi', ]}) ``` and enabled bash completion with eval "$(_TESTCLICK_COMPLETE=source ./testclick)" Now I am getting an error when trying to use autocompletion: ``` $ ./testclick subcommand <TAB>Traceback (most recent call last): File "./testclick", line 23, in <module> entrypoint(obj={'completions': ['abc', 'def', 'ghi', ]}) File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 731, in __call__ return self.main(*args, **kwargs) File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 701, in main _bashcomplete(self, prog_name, complete_var) File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 46, in _bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 216, in bashcomplete return do_complete(cli, prog_name) File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 205, in do_complete for item in get_choices(cli, prog_name, args, incomplete): File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 186, in get_choices ctx, all_args, incomplete, param)) File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 124, in get_user_autocompletions incomplete=incomplete) File "./testclick", line 7, in _complete return ctx.obj['completions'] TypeError: 'NoneType' object is not subscriptable ``` Expected behavior was to get a list of completions `abc def ghi`. I am using Python 3.6.4
Im currently not able to test my idea, so please excuse me if for just thinking out loud. :wink: Instead of passing the settings dict to `entrypoint` you could try passing it to the `context_settings` kwarg of the `.group` or `.command` function. Refer to the documentation for details: http://click.pocoo.org/5/commands/#context-defaults @LuckyJosh: Thanks for the hint, but that won’t suffice as a workaround. In the above example, I provided completions as a static dictionary just for the sake of simplicity. In my case, a network connection object would be passed via the context, and the `_complete` function would use it to retrieve possible completions. I don’t think `context_settings` can be used for that. Alright, in that case I have another idea: Are you sure that the kwarg `obj` to `entrypoint` should get passed to the context? After having a glimps at the implementation of `pass_context` I would suspect, that `obj={...}` just get passed to the wrapped function and is not used any further. The context is passed as the first argument to the decorated function without any interaction with the other arguments it would seem. This would explain the missing (`None`) `ctx.obj` the ErrorMessage is about. The source code I am refering to is in `decorators.py`. I don't understand what LuckyJosh is trying to say. The custom context with `obj` attached is normally created in BaseCommand.main(). The problem is that in autocomplete mode, _bashcomplete() gets called before the context-creation code executes, and creates its own context (without `obj`) instead. It looks to me like we want BaseCommand.main() to create its context in all circumstances, and pass it to _bashcomplete(). Would there be any drawbacks to this? Possibly related: #930 +1 on this issue. I, too, am trying to get autocomplete working with completions that come from network calls. To be clear, this issue limits the utility of #755. Until it is fixed, autocompletion callbacks have no clean way to access shared network resources. anyone found a workaround on this ? for now i'm doing things like this to at least init state based on env variables before calling out: ``` def get_entities(ctx, args, incomplete): if not hasattr(ctx, 'server'): ctx.server = os.environ.get('HASS_SERVER', const.DEFAULT_SERVER) if not hasattr(ctx, 'token'): ctx.token = os.environ.get('HASS_TOKEN') if not hasattr(ctx, "timeout"): ctx.timeout = os.environ.get('HASS_TIMEOUT', const.DEFAULT_TIMEOUT) try: x = req(ctx, "get", "states") except HTTPError: x = None entities = [] if x is not None: for entity in x: entities.append((entity["entity_id"], '')) return [c for c in entities if incomplete in c[0]] else: return entities ``` this lets the autocompletion work but its unforunate I have to relist the defaults and env parameters here. would be so much nicer if there was a way click could pass the right context or i at least could call something to generate the proper config/context. thx! Is there any update on this issue? I'm facing this issue too. For now, my workaround is to factor out the `ctx.obj` creation code and call it from both `cli()` and the corresponding autocomplete methods. ```python # cli() function @click.group @click.pass_context def cli(ctx): ctx.obj = create_context_object() # example autocomplete function def get_completion(ctx, args, incomplete): if ctx.obj is None: ctx.obj = create_context_object() ```
2020-10-03T21:38:52Z
[]
[]
pallets/click
1,687
pallets__click-1687
[ "1285", "767" ]
b631e5a5794369f03d57719a446a65e423366f36
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -142,6 +142,9 @@ class ParameterSource(enum.Enum): .. versionchanged:: 8.0 Use :class:`~enum.Enum` and drop the ``validate`` method. + + .. versionchanged:: 8.0 + Added the ``PROMPT`` value. """ COMMANDLINE = enum.auto() @@ -152,6 +155,8 @@ class ParameterSource(enum.Enum): """Used the default specified by the parameter.""" DEFAULT_MAP = enum.auto() """Used a default provided by :attr:`Context.default_map`.""" + PROMPT = enum.auto() + """Used a prompt to confirm a default or provide a value.""" class Context: @@ -277,10 +282,6 @@ def __init__( #: Map of parameter names to their parsed values. Parameters #: with ``expose_value=False`` are not stored. self.params = {} - # This tracks the actual param objects that were parsed, even if - # they didn't expose a value. Used by completion system to know - # what parameters to exclude. - self._seen_params = set() #: the leftover arguments. self.args = [] #: protected arguments. These are arguments that are prepended @@ -737,8 +738,12 @@ def get_parameter_source(self, name): :param name: The name of the parameter. :rtype: ParameterSource + + .. versionchanged:: 8.0 + Returns ``None`` if the parameter was not provided from any + source. """ - return self._parameter_source[name] + return self._parameter_source.get(name) class BaseCommand: @@ -1283,7 +1288,11 @@ def shell_complete(self, ctx, incomplete): if ( not isinstance(param, Option) or param.hidden - or (not param.multiple and param in ctx._seen_params) + or ( + not param.multiple + and ctx.get_parameter_source(param.name) + is ParameterSource.COMMANDLINE + ) ): continue @@ -1779,6 +1788,15 @@ class Parameter: be removed in 8.1, until then it will be wrapped to match the new requirements. + .. versionchanged:: 8.0 + For ``multiple=True, nargs>1``, the default must be a list of + tuples. + + .. versionchanged:: 8.0 + Setting a default is no longer required for ``nargs>1``, it will + default to ``None``. ``multiple=True`` or ``nargs=-1`` will + default to ``()``. + .. versionchanged:: 7.1 Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear @@ -1926,16 +1944,20 @@ def consume_value(self, ctx, opts): value = ctx.lookup_default(self.name) source = ParameterSource.DEFAULT_MAP - if value is not None: - ctx.set_parameter_source(self.name, source) + if value is None: + value = self.get_default(ctx) + source = ParameterSource.DEFAULT - return value + return value, source def type_cast_value(self, ctx, value): """Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. """ + if value is None: + return () if self.multiple or self.nargs == -1 else None + if self.type.is_composite: if self.nargs <= 1: raise TypeError( @@ -1943,14 +1965,17 @@ def type_cast_value(self, ctx, value): f" been set to {self.nargs}. This is not supported;" " nargs needs to be set to a fixed value > 1." ) + if self.multiple: - return tuple(self.type(x or (), self, ctx) for x in value or ()) - return self.type(value or (), self, ctx) + return tuple(self.type(x, self, ctx) for x in value) + + return self.type(value, self, ctx) def _convert(value, level): if level == 0: return self.type(value, self, ctx) - return tuple(_convert(x, level - 1) for x in value or ()) + + return tuple(_convert(x, level - 1) for x in value) return _convert(value, (self.nargs != 1) + bool(self.multiple)) @@ -1975,12 +2000,6 @@ def value_is_missing(self, value): def full_process_value(self, ctx, value): value = self.process_value(ctx, value) - if value is None and not ctx.resilient_parsing: - value = self.get_default(ctx) - - if value is not None: - ctx.set_parameter_source(self.name, ParameterSource.DEFAULT) - if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) @@ -1988,8 +2007,12 @@ def full_process_value(self, ctx, value): if ( not ctx.resilient_parsing and self.nargs > 1 - and self.nargs != len(value) and isinstance(value, (tuple, list)) + and ( + any(len(v) != self.nargs for v in value) + if self.multiple + else len(value) != self.nargs + ) ): were = "was" if len(value) == 1 else "were" ctx.fail( @@ -2002,45 +2025,46 @@ def full_process_value(self, ctx, value): def resolve_envvar_value(self, ctx): if self.envvar is None: return + if isinstance(self.envvar, (tuple, list)): for envvar in self.envvar: rv = os.environ.get(envvar) - if rv is not None: + + if rv: return rv else: rv = os.environ.get(self.envvar) - if rv != "": + if rv: return rv def value_from_envvar(self, ctx): rv = self.resolve_envvar_value(ctx) + if rv is not None and self.nargs != 1: rv = self.type.split_envvar_value(rv) + return rv def handle_parse_result(self, ctx, opts, args): with augment_usage_errors(ctx, param=self): - value = self.consume_value(ctx, opts) + value, source = self.consume_value(ctx, opts) + ctx.set_parameter_source(self.name, source) + try: value = self.full_process_value(ctx, value) + + if self.callback is not None: + value = self.callback(ctx, self, value) except Exception: if not ctx.resilient_parsing: raise + value = None - if self.callback is not None: - try: - value = self.callback(ctx, self, value) - except Exception: - if not ctx.resilient_parsing: - raise if self.expose_value: ctx.params[self.name] = value - if value is not None: - ctx._seen_params.add(self) - return value, args def get_help_record(self, ctx): @@ -2404,26 +2428,44 @@ def resolve_envvar_value(self, ctx): if rv is not None: return rv + if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None: envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" - return os.environ.get(envvar) + rv = os.environ.get(envvar) + + if rv: + return rv def value_from_envvar(self, ctx): rv = self.resolve_envvar_value(ctx) + if rv is None: return None + value_depth = (self.nargs != 1) + bool(self.multiple) + if value_depth > 0 and rv is not None: rv = self.type.split_envvar_value(rv) + if self.multiple and self.nargs != 1: rv = batch(rv, self.nargs) + return rv - def full_process_value(self, ctx, value): - if value is None and self.prompt is not None and not ctx.resilient_parsing: - return self.prompt_for_value(ctx) + def consume_value(self, ctx, opts): + value, source = super().consume_value(ctx, opts) + + # The value wasn't set, or used the param's default, prompt if + # prompting is enabled. + if ( + source in {None, ParameterSource.DEFAULT} + and self.prompt is not None + and not ctx.resilient_parsing + ): + value = self.prompt_for_value(ctx) + source = ParameterSource.PROMPT - return super().full_process_value(ctx, value) + return value, source class Argument(Parameter): diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -4,6 +4,7 @@ from .core import Argument from .core import MultiCommand from .core import Option +from .core import ParameterSource from .parser import split_arg_string from .utils import echo @@ -395,29 +396,27 @@ def get_completion_class(shell): return _available_shells.get(shell) -def _is_incomplete_argument(values, param): +def _is_incomplete_argument(ctx, param): """Determine if the given parameter is an argument that can still accept values. - :param values: Dict of param names and values parsed from the - command line args. + :param ctx: Invocation context for the command represented by the + parsed complete args. :param param: Argument object being checked. """ if not isinstance(param, Argument): return False - value = values[param.name] - - if value is None: - return True - - if param.nargs == -1: - return True - - if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs: - return True - - return False + value = ctx.params[param.name] + return ( + param.nargs == -1 + or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE + or ( + param.nargs > 1 + and isinstance(value, (tuple, list)) + and len(value) < param.nargs + ) + ) def _start_of_option(value): @@ -523,16 +522,18 @@ def _resolve_incomplete(ctx, args, incomplete): if "--" not in args and _start_of_option(incomplete): return ctx.command, incomplete + params = ctx.command.get_params(ctx) + # If the last complete arg is an option name with an incomplete # value, the option will provide value completions. - for param in ctx.command.get_params(ctx): + for param in params: if _is_incomplete_option(args, param): return param, incomplete # It's not an option name or value. The first argument without a # parsed value will provide value completions. - for param in ctx.command.get_params(ctx): - if _is_incomplete_argument(ctx.params, param): + for param in params: + if _is_incomplete_argument(ctx, param): return param, incomplete # There were no unparsed arguments, the command may be a group that diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -181,7 +181,7 @@ def convert(self, value, param, ctx): else: value = value.decode("utf-8", "replace") return value - return value + return str(value) def __repr__(self): return "STRING" @@ -255,11 +255,9 @@ def convert(self, value, param, ctx): if normed_value in normed_choices: return normed_choices[normed_value] - self.fail( - f"invalid choice: {value}. (choose from {', '.join(self.choices)})", - param, - ctx, - ) + one_of = "one of " if len(self.choices) > 1 else "" + choices_str = ", ".join(repr(c) for c in self.choices) + self.fail(f"{value!r} is not {one_of}{choices_str}.", param, ctx) def __repr__(self): return f"Choice({list(self.choices)})" @@ -320,14 +318,19 @@ def _try_to_convert_date(self, value, format): return None def convert(self, value, param, ctx): - # Exact match + if isinstance(value, datetime): + return value + for format in self.formats: - dtime = self._try_to_convert_date(value, format) - if dtime: - return dtime + converted = self._try_to_convert_date(value, format) + + if converted is not None: + return converted + plural = "s" if len(self.formats) > 1 else "" + formats_str = ", ".join(repr(f) for f in self.formats) self.fail( - f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})" + f"{value!r} does not match the format{plural} {formats_str}.", param, ctx ) def __repr__(self): @@ -341,7 +344,7 @@ def convert(self, value, param, ctx): try: return self._number_class(value) except ValueError: - self.fail(f"{value} is not a valid {self.name}", param, ctx) + self.fail(f"{value!r} is not a valid {self.name}.", param, ctx) class _NumberRangeBase(_NumberParamTypeBase): @@ -495,7 +498,7 @@ class BoolParamType(ParamType): name = "boolean" def convert(self, value, param, ctx): - if isinstance(value, bool): + if value in {False, True}: return bool(value) norm = value.strip().lower() @@ -506,7 +509,7 @@ def convert(self, value, param, ctx): if norm in {"0", "false", "f", "no", "n", "off"}: return False - self.fail(f"{value!r} is not a valid boolean value.", param, ctx) + self.fail(f"{value!r} is not a valid boolean.", param, ctx) def __repr__(self): return "BOOL" @@ -518,10 +521,15 @@ class UUIDParameterType(ParamType): def convert(self, value, param, ctx): import uuid + if isinstance(value, uuid.UUID): + return value + + value = value.strip() + try: return uuid.UUID(value) except ValueError: - self.fail(f"{value} is not a valid UUID value", param, ctx) + self.fail(f"{value!r} is not a valid UUID.", param, ctx) def __repr__(self): return "UUID" @@ -610,11 +618,7 @@ def convert(self, value, param, ctx): ctx.call_on_close(safecall(f.flush)) return f except OSError as e: # noqa: B014 - self.fail( - f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}", - param, - ctx, - ) + self.fail(f"{filename_to_ui(value)!r}: {get_strerror(e)}", param, ctx) def shell_complete(self, ctx, param, incomplete): """Return a special completion marker that tells the completion @@ -818,37 +822,55 @@ def convert(self, value, param, ctx): def convert_type(ty, default=None): - """Converts a callable or python type into the most appropriate - param type. + """Find the most appropriate :class:`ParamType` for the given Python + type. If the type isn't provided, it can be inferred from a default + value. """ guessed_type = False + if ty is None and default is not None: - if isinstance(default, tuple): - ty = tuple(map(type, default)) + if isinstance(default, (tuple, list)): + # If the default is empty, ty will remain None and will + # return STRING. + if default: + item = default[0] + + # A tuple of tuples needs to detect the inner types. + # Can't call convert recursively because that would + # incorrectly unwind the tuple to a single type. + if isinstance(item, (tuple, list)): + ty = tuple(map(type, item)) + else: + ty = type(item) else: ty = type(default) + guessed_type = True if isinstance(ty, tuple): return Tuple(ty) + if isinstance(ty, ParamType): return ty + if ty is str or ty is None: return STRING + if ty is int: return INT - # Booleans are only okay if not guessed. This is done because for - # flags the default value is actually a bit of a lie in that it - # indicates which of the flags is the one we want. See get_default() - # for more information. - if ty is bool and not guessed_type: - return BOOL + if ty is float: return FLOAT + + # Booleans are only okay if not guessed. For is_flag options with + # flag_value, default=True indicates which flag_value is the + # default. + if ty is bool and not guessed_type: + return BOOL + if guessed_type: return STRING - # Catch a common mistake if __debug__: try: if issubclass(ty, ParamType): @@ -856,7 +878,9 @@ def convert_type(ty, default=None): f"Attempted to use an uninstantiated parameter type ({ty})." ) except TypeError: + # ty is an instance (correct), so issubclass fails. pass + return FuncParamType(ty)
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -164,17 +164,17 @@ def inout(output): @pytest.mark.parametrize( - ("nargs", "value", "code", "output"), + ("nargs", "value", "expect"), [ - (2, "", 2, "Argument 'arg' takes 2 values but 0 were given."), - (2, "a", 2, "Argument 'arg' takes 2 values but 1 was given."), - (2, "a b", 0, "len 2"), - (2, "a b c", 2, "Argument 'arg' takes 2 values but 3 were given."), - (-1, "a b c", 0, "len 3"), - (-1, "", 0, "len 0"), + (2, "", None), + (2, "a", "Argument 'arg' takes 2 values but 1 was given."), + (2, "a b", ("a", "b")), + (2, "a b c", "Argument 'arg' takes 2 values but 3 were given."), + (-1, "a b c", ("a", "b", "c")), + (-1, "", ()), ], ) -def test_nargs_envvar(runner, nargs, value, code, output): +def test_nargs_envvar(runner, nargs, value, expect): if nargs == -1: param = click.argument("arg", envvar="X", nargs=nargs) else: @@ -183,11 +183,14 @@ def test_nargs_envvar(runner, nargs, value, code, output): @click.command() @param def cmd(arg): - click.echo(f"len {len(arg)}") + return arg - result = runner.invoke(cmd, env={"X": value}) - assert result.exit_code == code - assert output in result.output + result = runner.invoke(cmd, env={"X": value}, standalone_mode=False) + + if isinstance(expect, str): + assert expect in str(result.exception) + else: + assert result.return_value == expect def test_empty_nargs(runner): diff --git a/tests/test_basic.py b/tests/test_basic.py --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -147,7 +147,7 @@ def cli(foo): result = runner.invoke(cli, ["--foo=bar"]) assert result.exception - assert "Invalid value for '--foo': bar is not a valid integer" in result.output + assert "Invalid value for '--foo': 'bar' is not a valid integer." in result.output def test_uuid_option(runner): @@ -169,7 +169,7 @@ def cli(u): result = runner.invoke(cli, ["--u=bar"]) assert result.exception - assert "Invalid value for '--u': bar is not a valid UUID value" in result.output + assert "Invalid value for '--u': 'bar' is not a valid UUID." in result.output def test_float_option(runner): @@ -189,7 +189,7 @@ def cli(foo): result = runner.invoke(cli, ["--foo=bar"]) assert result.exception - assert "Invalid value for '--foo': bar is not a valid float" in result.output + assert "Invalid value for '--foo': 'bar' is not a valid float." in result.output def test_boolean_option(runner): @@ -303,10 +303,7 @@ def input_non_lazy(file): os.mkdir("example.txt") result_in = runner.invoke(input_non_lazy, ["--file=example.txt"]) assert result_in.exit_code == 2 - assert ( - "Invalid value for '--file': Could not open file: example.txt" - in result_in.output - ) + assert "Invalid value for '--file': 'example.txt'" in result_in.output def test_path_option(runner): @@ -368,8 +365,8 @@ def cli(method): result = runner.invoke(cli, ["--method=meh"]) assert result.exit_code == 2 assert ( - "Invalid value for '--method': invalid choice: meh." - " (choose from foo, bar, baz)" in result.output + "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'." + in result.output ) result = runner.invoke(cli, ["--help"]) @@ -389,8 +386,8 @@ def cli(method): result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( - "Invalid value for '{foo|bar|baz}': invalid choice: meh. " - "(choose from foo, bar, baz)" in result.output + "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," + " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) @@ -414,9 +411,8 @@ def cli(start_date): result = runner.invoke(cli, ["--start_date=2015-09"]) assert result.exit_code == 2 assert ( - "Invalid value for '--start_date':" - " invalid datetime format: 2015-09." - " (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)" + "Invalid value for '--start_date': '2015-09' does not match the formats" + " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'." ) in result.output result = runner.invoke(cli, ["--help"]) diff --git a/tests/test_formatting.py b/tests/test_formatting.py --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -195,7 +195,7 @@ def cmd(arg): "Usage: cmd [OPTIONS] metavar", "Try 'cmd --help' for help.", "", - "Error: Invalid value for 'metavar': 3.14 is not a valid integer", + "Error: Invalid value for 'metavar': '3.14' is not a valid integer.", ] diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -188,21 +188,37 @@ def cmd(arg, arg2): assert "1, 2" in result.output -def test_multiple_default_type(runner): - @click.command() - @click.option("--arg1", multiple=True, default=("foo", "bar")) - @click.option("--arg2", multiple=True, default=(1, "a")) - def cmd(arg1, arg2): - assert all(isinstance(e[0], str) for e in arg1) - assert all(isinstance(e[1], str) for e in arg1) +def test_multiple_default_type(): + opt = click.Option(["-a"], multiple=True, default=(1, 2)) + assert opt.nargs == 1 + assert opt.multiple + assert opt.type is click.INT + ctx = click.Context(click.Command("test")) + assert opt.get_default(ctx) == (1, 2) - assert all(isinstance(e[0], int) for e in arg2) - assert all(isinstance(e[1], str) for e in arg2) - result = runner.invoke( - cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split() - ) - assert not result.exception +def test_multiple_default_composite_type(): + opt = click.Option(["-a"], multiple=True, default=[(1, "a")]) + assert opt.nargs == 2 + assert opt.multiple + assert isinstance(opt.type, click.Tuple) + assert opt.type.types == [click.INT, click.STRING] + ctx = click.Context(click.Command("test")) + assert opt.get_default(ctx) == ((1, "a"),) + + +def test_parse_multiple_default_composite_type(runner): + @click.command() + @click.option("-a", multiple=True, default=("a", "b")) + @click.option("-b", multiple=True, default=[(1, "a")]) + def cmd(a, b): + click.echo(a) + click.echo(b) + + # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split()) + # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n" + result = runner.invoke(cmd) + assert result.output == "('a', 'b')\n((1, 'a'),)\n" def test_dynamic_default_help_unset(runner): @@ -251,7 +267,7 @@ def cmd(username): ], ) def test_intrange_default_help_text(runner, type, expect): - option = click.Option(["--count"], type=type, show_default=True, default=1) + option = click.Option(["--count"], type=type, show_default=True, default=2) context = click.Context(click.Command("test")) result = option.get_help_record(context)[1] assert expect in result diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py --- a/tests/test_shell_completion.py +++ b/tests/test_shell_completion.py @@ -90,6 +90,21 @@ def test_argument_order(): assert _get_words(cli, ["x", "b"], "d") == ["d"] +def test_argument_default(): + cli = Command( + "cli", + add_help_option=False, + params=[ + Argument(["a"], type=Choice(["a"]), default="a"), + Argument(["b"], type=Choice(["b"]), default="b"), + ], + ) + assert _get_words(cli, [], "") == ["a"] + assert _get_words(cli, ["a"], "b") == ["b"] + # ignore type validation + assert _get_words(cli, ["x"], "b") == ["b"] + + def test_type_choice(): cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))]) assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"] @@ -119,9 +134,9 @@ def test_option_flag(): Argument(["a"], type=Choice(["a1", "a2", "b"])), ], ) - assert _get_words(cli, ["type"], "--") == ["--on", "--off"] + assert _get_words(cli, [], "--") == ["--on", "--off"] # flag option doesn't take value, use choice argument - assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"] + assert _get_words(cli, ["--on"], "a") == ["a1", "a2"] def test_option_custom(): diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -54,3 +54,27 @@ def test_float_range_no_clamp_open(): with pytest.raises(RuntimeError): sneaky.convert("1.5", None, None) + + [email protected]( + ("nargs", "multiple", "default", "expect"), + [ + (2, False, None, None), + (2, False, (None, None), (None, None)), + (None, True, None, ()), + (None, True, (None, None), (None, None)), + (2, True, None, ()), + (2, True, [(None, None)], ((None, None),)), + (-1, None, None, ()), + ], +) +def test_cast_multi_default(runner, nargs, multiple, default, expect): + if nargs == -1: + param = click.Argument(["a"], nargs=nargs, default=default) + else: + param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default) + + cli = click.Command("cli", params=[param], callback=lambda a: a) + result = runner.invoke(cli, standalone_mode=False) + assert result.exception is None + assert result.return_value == expect
Path(exists=True, envvar='FOO') tries to interpret FOO="" as an existing path Example: ```python @click.command() @click.option('--mypath', type=click.Path(exists=True), envvar='MYPATH') def cli(mypath): click.echo(f'mypath: {mypath}') ``` Test case: ``` ➜ env MYPATH= ./mycli.py ``` Observed output: ``` Usage: mycli.py [OPTIONS] Try "mycli.py --help" for help. Error: Invalid value for "--mypath": Path "" does not exist. ``` Expected output: ``` ➜ ./mycli.py mypath: None ``` i.e. Shouldn't Click special-case `envvar == ""` and treat it as though the option wasn't passed? This is more useful than failing with "`Path "" does not exist`", as it gives users who are inheriting an unwanted env var, and who can only set it to empty string rather than unset, a way to clear it. Allow unspecified values for composite types With this, behavior is (or should be) similar to when only `nargs` is used. The `Tuple` parameter type can't actually handle empty tuples and thus we get the `TypeError` exception about differing value length and type arity. Hopefully this fixes #472 but I'm not sure if this is the correct approach into fixing this since composite parameter types aren't exactly required to return tuples. Besides, ideally, for `nargs` unequal to 1 `nargs` parameters should be designed on top of the `Tuple` parameter type, in my opinion, and like any other type without defaults, composite types should return `None` when unspecified in the command line (unless `multiple` is `True`, which, as is already the case, should return an empty tuple). Of course that's a way different approach and I'd rather discuss that in here first. I'm definitely open to suggestions or something as I'm not really familiar with `click`'s internals. All tests runs passed for me so I hope I didn't break anything. (Also, last commit can be ignored if necessary, I just found it appropriate in this case.)
Is this a good first issue @davidism? I'm taking a look at this @Kamekameha Thanks for the PR. Could you add some inline comments to your changes, and perhaps some documentation? Thanks!
2020-10-12T01:18:09Z
[]
[]
pallets/click
1,693
pallets__click-1693
[ "1692" ]
acc91bc4f47e38f43277fcdfd8ca855734c4fbbc
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -274,7 +274,14 @@ def shell_complete(self, ctx, param, incomplete): from click.shell_completion import CompletionItem str_choices = map(str, self.choices) - return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)] + + if self.case_sensitive: + matched = (c for c in str_choices if c.startswith(incomplete)) + else: + incomplete = incomplete.lower() + matched = (c for c in str_choices if c.lower().startswith(incomplete)) + + return [CompletionItem(c) for c in matched] class DateTime(ParamType):
diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py --- a/tests/test_shell_completion.py +++ b/tests/test_shell_completion.py @@ -304,3 +304,13 @@ def complete(ctx, param, incomplete): env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"}, ) assert result.output == "plain,a\nplain,b\n" + + [email protected](("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])]) +def test_choice_case_sensitive(value, expect): + cli = Command( + "cli", + params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))], + ) + completions = _get_words(cli, ["-a"], "a") + assert completions == expect
shell completion is case sensitive, even with click.Choice(case_sensitive=False) ### Expected Behavior Since I set case_sensitive to False, I would expect shell completions to search without case sensitivity. ```python import click from click._bashcomplete import get_choices options = ['Paul', 'Simon', 'Art', 'Garfunkel'] @click.command() @click.option('--opt', type=click.Choice(options)) def demo(): pass completions = list(get_choices(demo, 'dummy', ['--opt'], 'gar')) assert len(completions) == 1, "expected to find 'Garfunkel' as a completion item" ``` ### Actual Behavior No completions are found. However, if I change the `incomplete` parameter to `"Gar"`, one completion is found as expected. ### Environment * Python version: 3.7.7 * Click version: 7.0 (but I've reviewed the code on master and it doesn't seem to have a fix)
Should be straightforward to fix, happy to review a PR. I'll be happy to look into this!
2020-10-17T10:38:18Z
[]
[]
pallets/click
1,695
pallets__click-1695
[ "1082" ]
297150c7566a38fb672828a36b681792513d99b0
diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -49,6 +49,9 @@ def make_str(value): def make_default_short_help(help, max_length=45): """Return a condensed version of help string.""" + line_ending = help.find("\n\n") + if line_ending != -1: + help = help[:line_ending] words = help.split() total_length = 0 result = []
diff --git a/tests/test_basic.py b/tests/test_basic.py --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -528,3 +528,22 @@ def nope(): assert result.exit_code == 0 assert "subgroup" not in result.output assert "nope" not in result.output + + +def test_summary_line(runner): + @click.group() + def cli(): + pass + + @cli.command() + def cmd(): + """ + Summary line without period + + Here is a sentence. And here too. + """ + pass + + result = runner.invoke(cli, ["--help"]) + assert "Summary line without period" in result.output + assert "Here is a sentence." not in result.output
Automatic short help should also take linebreak into account PEP257 defines a summary line for [multi-line docstrings](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings) just like a [one-line docstring](https://www.python.org/dev/peps/pep-0257/#one-line-docstrings) to be a phrase ending in a period. Click automatically uses everything up to the first period to be the short help, independent how many lines it spans. Consider the following: ``` import click @click.group() def grp(): pass @grp.command() def cmd1(): """First sentence. Second sentence.""" @grp.command() def cmd2(): """Summary line without a period First real sentence. Another sentence. """ ``` ``` $ python3 foo.py --help Usage: foo.py [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: cmd1 First sentence. cmd2 Summary line without a period First real... ``` To me it would feel more natural: 1. to take the first line as short help, independent of punctuation OR 1. to look for an ending of a phrase or linebreak, whichever comes first. Both would allow for summary lines without the requirement to end in a period. While this would violate PEP257, I would consider it a gray area, as that summary line is used as short help in a list of commands and I have a use case where a company style guide requires such lists **not** to end in periods. I'd be happy to provide a pull request for either solution, if it would be accepted.
I know this was from a while ago, but I think it's a good idea to stop at either a period or newline. If you guys think it's worth implementing can I code it as part of hacktoberfest? No need to ask to work on an issue. As long as the issue is not assigned to anyone and doesn't have have a linked open PR (both can be seen in the sidebar), anyone is welcome to work on any issue.
2020-10-22T23:50:19Z
[]
[]
pallets/click
1,698
pallets__click-1698
[ "676" ]
a4763ef93734ccfea497ea10bf0870d588132432
diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -62,6 +62,7 @@ def __init__( label=None, file=None, color=None, + update_min_steps=1, width=30, ): self.fill_char = fill_char @@ -77,6 +78,8 @@ def __init__( file = _default_text_stdout() self.file = file self.color = color + self.update_min_steps = update_min_steps + self._completed_intervals = 0 self.width = width self.autowidth = width == 0 @@ -290,13 +293,23 @@ def update(self, n_steps, current_item=None): :param current_item: Optional item to set as ``current_item`` for the updated position. - .. versionadded:: 8.0 + .. versionchanged:: 8.0 Added the ``current_item`` optional parameter. + + .. versionchanged:: 8.0 + Only render when the number of steps meets the + ``update_min_steps`` threshold. """ - self.make_step(n_steps) - if current_item is not None: - self.current_item = current_item - self.render_progress() + self._completed_intervals += n_steps + + if self._completed_intervals >= self.update_min_steps: + self.make_step(self._completed_intervals) + + if current_item is not None: + self.current_item = current_item + + self.render_progress() + self._completed_intervals = 0 def finish(self): self.eta_known = 0 diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -299,6 +299,7 @@ def progressbar( width=36, file=None, color=None, + update_min_steps=1, ): """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will @@ -353,12 +354,6 @@ def progressbar( archive.extract() bar.update(archive.size, archive) - .. versionadded:: 2.0 - - .. versionadded:: 4.0 - Added the `color` parameter. Added a `update` method to the - progressbar object. - :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the @@ -397,6 +392,17 @@ def progressbar( default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. + :param update_min_steps: Render only when this many updates have + completed. This allows tuning for very fast iterators. + + .. versionadded:: 8.0 + Added the ``update_min_steps`` parameter. + + .. versionchanged:: 4.0 + Added the ``color`` parameter. Added the ``update`` method to + the object. + + .. versionadded:: 2.0 """ from ._termui_impl import ProgressBar @@ -416,6 +422,7 @@ def progressbar( label=label, width=width, color=color, + update_min_steps=update_min_steps, )
diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -344,6 +344,16 @@ def cli(): assert "Custom 4" in lines[2] +def test_progress_bar_update_min_steps(runner): + bar = _create_progress(update_min_steps=5) + bar.update(3) + assert bar._completed_intervals == 3 + assert bar.pos == 0 + bar.update(2) + assert bar._completed_intervals == 0 + assert bar.pos == 5 + + @pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR")) @pytest.mark.parametrize("echo", [True, False]) @pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")
Avoid rendering on highly frequent updates in progressbar I am using a progressbar in a loop with short iterations, which negatively affects performance. It would be good to supply a chunk size such that the heavy part of an update is only performed every nth time. Currently I am using a small wrapper around it: ``` class ChunkProgressbar: def __init__(self, iterator, chunk_size=100, enabled=True, **kwargs): self.iterator = iterator self.chunk_size = chunk_size self.bar = progressbar(iterator, **kwargs) self.missed_updates = 0 def __enter__(self): if self.bar is not None: self.bar.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): self.bar.update(self.missed_updates) self.bar.__exit__(exc_type, exc_val, exc_tb) def __iter__(self): for index, elem in enumerate(self.iterator): yield elem self.missed_updates += 1 if index % self.chunk_size == self.chunk_size - 1: self.bar.update(self.missed_updates) self.missed_updates = 0 ``` One could also throttle the rendering based on timing information (like the eta calculation), but that might be costly again due to timing calls or mess with heterogeneous iteration times.
2020-10-26T00:15:33Z
[]
[]
pallets/click
1,709
pallets__click-1709
[ "1708" ]
f0cc87d491e98b8770af0f3be13fba4b688298b3
diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -21,7 +21,6 @@ # maintained by the Python Software Foundation. # Copyright 2001-2006 Gregory P. Ward # Copyright 2002-2006 Python Software Foundation -import re from collections import deque from .exceptions import BadArgumentUsage @@ -103,22 +102,37 @@ def normalize_opt(opt, ctx): def split_arg_string(string): - """Given an argument string this attempts to split it into small parts.""" - rv = [] - for match in re.finditer( - r"('([^'\\]*(?:\\.[^'\\]*)*)'|\"([^\"\\]*(?:\\.[^\"\\]*)*)\"|\S+)\s*", - string, - re.S, - ): - arg = match.group().strip() - if arg[:1] == arg[-1:] and arg[:1] in "\"'": - arg = arg[1:-1].encode("ascii", "backslashreplace").decode("unicode-escape") - try: - arg = type(string)(arg) - except UnicodeError: - pass - rv.append(arg) - return rv + """Split an argument string as with :func:`shlex.split`, but don't + fail if the string is incomplete. Ignores a missing closing quote or + incomplete escape sequence and uses the partial token as-is. + + .. code-block:: python + + split_arg_string("example 'my file") + ["example", "my file"] + + split_arg_string("example my\\") + ["example", "my"] + + :param string: String to split. + """ + import shlex + + lex = shlex.shlex(string, posix=True) + lex.whitespace_split = True + lex.commenters = "" + out = [] + + try: + for token in lex: + out.append(token) + except ValueError: + # Raised when end-of-string is reached in an invalid state. Use + # the partial token as-is. The quote or escape character is in + # lex.state, not lex.token. + out.append(lex.token) + + return out class Option:
diff --git a/tests/test_parser.py b/tests/test_parser.py new file mode 100644 --- /dev/null +++ b/tests/test_parser.py @@ -0,0 +1,17 @@ +import pytest + +from click.parser import split_arg_string + + [email protected]( + ("value", "expect"), + [ + ("cli a b c", ["cli", "a", "b", "c"]), + ("cli 'my file", ["cli", "my file"]), + ("cli 'my file'", ["cli", "my file"]), + ("cli my\\", ["cli", "my"]), + ("cli my\\ file", ["cli", "my file"]), + ], +) +def test_split_arg_string(value, expect): + assert split_arg_string(value) == expect
Shell completion does't parse escaped slashes or spaces correctly When a value with an escape string, for instance `my\ file`, is passed to a `click.ParamType`, the `incomplete` value which is passed to `click.ParamType.shell_complete` will only be `"my\ "` instead of `my file`. ### Expected Behavior ```python import click @click.command() @click.argument("name", type=click.Choice(["my file", "my folder", "my\\ file", "other"])) def cli(name): click.echo(name) if __name__ == '__main__': cli() ``` Completing `my\ f` should be interpreted as the Python string `"my f"` and match the first two values. ``` $ example my\ f<TAB> my\ file my\ folder ``` ### Actual Behavior Completing `my\ f` is interpreted as the string `"my\\ f"` and matches the third value. ```shell $ example my\ f<TAB> my\\\ file ``` ### Environment * Python version: 3.8.6 * Click version: 8.0.0.dev0
`"\ "` isn't a valid escape sequence in a Python string, so Python will escape the escape character. If you try it in the interpreter, you get. ```pycon >>> "\ " '\\ ' ``` Finally, the shell you're using escapes spaces on its own, so you get the third escape character. Maybe you misunderstood, my issues is not with the triple backslash. The issue is that `incomplete = "my\"` while it should be `incomplete = "my f"` because the actual argument to be completed is "my f". I've updated the issue with a simpler example and direct explanations for expected and actual behavior. The issue seems to be with how `split_arg_string` handles slashes and spaces. It's trying to emulate how `sys.argv` would be populated to apply it to the `CWORDS` env var, but doesn't get it right in all cases. Adding some debugging code to `ZshComplete.get_completion_args`, when `my\ f` is completed: ``` os.environ['COMP_WORDS']='example my\\ f' cwords=['example', 'my\\', 'f'] cword=1 args=[] incomplete='my\\' ``` The shell is passing `my\ a`, which is the Python string `"my\\ f"`. This is getting parsed into two values `"my\\"` and `"f"`. Instead, it should get parsed into one value `"my\\ f"`. You can find some other weird behaviors by tab completing earlier, or with a single opening quote, or within quotes. The splitter should be able to handle these. That's about the extent of the time I can devote to this for now though. Your best bet for getting this fixed before 8.0 is released is to make a PR. Ok, thanks. Yes, that example was a bit of a mess. From a quick look, `split_arg_string` attempts to do something similar to the quite complex `shlex.split`. Any reason why you are not using the latter? Bad performance? Because `shlex.split` expects a complete command line string, but completion by definition needs to work with an incomplete string. ```python shlex.split("example my\\") ``` ```pytb ValueError: No escaped character ``` ```python shlex.split("example 'my ") ``` ```pytb ValueError: No closing quotation ``` You might be able to get around that by manually iterating over a `shlex.shlex` object and doing some cleanup when it raises an error. I was about to propose exactly that! Any remainder after a `ValueError` can be taken as an incomplete argument. Those two examples should be the only cases where `shlex.split` gets into a failed state, so I think handling those cases with `shlex.shelx` should be enough. Hopefully. Also, unpaired quotes should ideally be preserved during the completion process: An input of `my\ f` should be completed to `my\ file` while an input of `'my f` should be completed to `'my file'`. I'll need to think a bit about this and see if can submit a PR that fixes more than it breaks. But not tonight, it's already late here.
2020-11-10T10:06:28Z
[]
[]
pallets/click
1,755
pallets__click-1755
[ "1732" ]
7dd9b12b0d22e5a8a8674488684fd2bb799f2945
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2405,9 +2405,12 @@ def _write_opts(opts): extra.append(f"env var: {var_str}") default_value = self.get_default(ctx, call=False) + show_default_is_str = isinstance(self.show_default, str) - if default_value is not None and (self.show_default or ctx.show_default): - if isinstance(self.show_default, str): + if show_default_is_str or ( + default_value is not None and (self.show_default or ctx.show_default) + ): + if show_default_is_str: default_string = f"({self.show_default})" elif isinstance(default_value, (list, tuple)): default_string = ", ".join(str(d) for d in default_value)
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -660,6 +660,14 @@ def test_show_default_boolean_flag_value(runner): assert "[default: False]" in message +def test_show_default_string(runner): + """When show_default is a string show that value as default.""" + opt = click.Option(["--limit"], show_default="unlimited") + ctx = click.Context(click.Command("cli")) + message = opt.get_help_record(ctx)[1] + assert "[default: (unlimited)]" in message + + @pytest.mark.parametrize( ("args", "expect"), [
Custom default label ignored if default is None I found out that custom default label is not shown when `default` is `None`. In some cases `default = None` is intentional, but custom default label would be still helpful. An example with `--limit` option, with `None` as `default` meaning no limit: ```python import click @click.command() @click.option('--limit', type=int, show_default='unlimited') def main(limit: int): print('Limit: {}'.format(limit)) if __name__ == '__main__': main() ``` ### Expected Behavior Tell us what should happen. ```sh $ python3 /tmp/foo.py --help Usage: foo.py [OPTIONS] Options: --limit INTEGER [default: unlimited] --help Show this message and exit. ``` ### Actual Behavior Tell us what happens instead. ```sh $ python3 /tmp/foo.py --help Usage: foo.py [OPTIONS] Options: --limit INTEGER --help Show this message and exit. ``` Default is not shown, making the description less useful. ### Environment * Python version: 3.9.1 * Click version: 7.1.2
`show_default` is supposed to be a Boolean, triggering to show the value in `default`. Since there is no default set I think the best would be to just set `help='[default: unlimited]'`. Otherwise you could achive your result with: ``` import click @click.command() @click.option('--limit', type=int, show_default='unlimited', default=-1) def main(limit: int): if limit >= 0: print('Limit: {}'.format(limit)) if __name__ == '__main__': main() ``` According to docs, string is a perfectly valid value for a `show_default`, see https://click.palletsprojects.com/en/7.x/api/?highlight=show_default#click.Option. Yes, I found out it works, when I change the default value to something else, but that's not something I want to do. It makes code less readable.
2021-01-15T10:56:57Z
[]
[]
pallets/click
1,784
pallets__click-1784
[ "1546" ]
ea3bb6f1bf5db675f2dec0350f57e704da6ea00b
diff --git a/examples/colors/colors.py b/examples/colors/colors.py --- a/examples/colors/colors.py +++ b/examples/colors/colors.py @@ -23,9 +23,8 @@ @click.command() def cli(): - """This script prints some colors. If colorama is installed this will - also work on Windows. It will also automatically remove all ANSI - styles if data is piped into a file. + """This script prints some colors. It will also automatically remove + all ANSI styles if data is piped into a file. Give it a try! """ diff --git a/examples/colors/setup.py b/examples/colors/setup.py --- a/examples/colors/setup.py +++ b/examples/colors/setup.py @@ -5,11 +5,7 @@ version="1.0", py_modules=["colors"], include_package_data=True, - install_requires=[ - "click", - # Colorama is only required for Windows. - "colorama", - ], + install_requires=["click"], entry_points=""" [console_scripts] colors=colors:cli diff --git a/examples/termui/setup.py b/examples/termui/setup.py --- a/examples/termui/setup.py +++ b/examples/termui/setup.py @@ -5,11 +5,7 @@ version="1.0", py_modules=["termui"], include_package_data=True, - install_requires=[ - "click", - # Colorama is only required for Windows. - "colorama", - ], + install_requires=["click"], entry_points=""" [console_scripts] termui=termui:cli diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,3 +1,3 @@ from setuptools import setup -setup(name="click") +setup(name="click", install_requires=["colorama; platform_system == 'Windows'"]) diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -490,9 +490,8 @@ def should_strip_ansi(stream=None, color=None): return not color -# If we're on Windows, we provide transparent integration through -# colorama. This will make ANSI colors through the echo function -# work automatically. +# On Windows, wrap the output streams with colorama to support ANSI +# color codes. # NOTE: double check is needed so mypy does not analyze this on Linux if sys.platform.startswith("win") and WIN: from ._winconsole import _get_windows_console_stream @@ -502,47 +501,44 @@ def _get_argv_encoding(): return locale.getpreferredencoding() - try: + _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def auto_wrap_for_ansi( + stream: t.TextIO, color: t.Optional[bool] = None + ) -> t.TextIO: + """Support ANSI color and style codes on Windows by wrapping a + stream with colorama. + """ + try: + cached = _ansi_stream_wrappers.get(stream) + except Exception: + cached = None + + if cached is not None: + return cached + import colorama - except ImportError: - pass - else: - _ansi_stream_wrappers: t.MutableMapping[ - t.TextIO, t.TextIO - ] = WeakKeyDictionary() - - def auto_wrap_for_ansi( - stream: t.TextIO, color: t.Optional[bool] = None - ) -> t.TextIO: - """This function wraps a stream so that calls through colorama - are issued to the win32 console API to recolor on demand. It - also ensures to reset the colors if a write call is interrupted - to not destroy the console afterwards. - """ - try: - cached = _ansi_stream_wrappers.get(stream) - except Exception: - cached = None - if cached is not None: - return cached - strip = should_strip_ansi(stream, color) - ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) - rv = ansi_wrapper.stream - _write = rv.write - - def _safe_write(s): - try: - return _write(s) - except BaseException: - ansi_wrapper.reset_all() - raise - - rv.write = _safe_write + + strip = should_strip_ansi(stream, color) + ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) + rv = ansi_wrapper.stream + _write = rv.write + + def _safe_write(s): try: - _ansi_stream_wrappers[stream] = rv - except Exception: - pass - return rv + return _write(s) + except BaseException: + ansi_wrapper.reset_all() + raise + + rv.write = _safe_write + + try: + _ansi_stream_wrappers[stream] = rv + except Exception: + pass + + return rv else: diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -418,9 +418,6 @@ def clear(): """ if not isatty(sys.stdout): return - # If we're on Windows and we don't have colorama available, then we - # clear the screen by shelling out. Otherwise we can use an escape - # sequence. if WIN: os.system("cls") else: diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -172,51 +172,43 @@ def __iter__(self): def echo(message=None, file=None, nl=True, err=False, color=None): - """Prints a message plus a newline to the given file or stdout. On - first sight, this looks like the print function, but it has improved - support for handling Unicode and binary data that does not fail no - matter how badly configured the system is. - - Primarily it means that you can print binary data as well as Unicode - data on both 2.x and 3.x to the given file in the most appropriate way - possible. This is a very carefree function in that it will try its - best to not fail. As of Click 6.0 this includes support for unicode - output on the Windows console. - - In addition to that, if `colorama`_ is installed, the echo function will - also support clever handling of ANSI codes. Essentially it will then - do the following: - - - add transparent handling of ANSI color codes on Windows. - - hide ANSI codes automatically if the destination file is not a - terminal. - - .. _colorama: https://pypi.org/project/colorama/ + """Print a message and newline to stdout or a file. This should be + used instead of :func:`print` because it provides better support + for different data, files, and environments. + + Compared to :func:`print`, this does the following: + + - Ensures that the output encoding is not misconfigured on Linux. + - Supports Unicode in the Windows console. + - Supports writing to binary outputs, and supports writing bytes + to text outputs. + - Supports colors and styles on Windows. + - Removes ANSI color and style codes if the output does not look + like an interactive terminal. + - Always flushes the output. + + :param message: The string or bytes to output. Other objects are + converted to strings. + :param file: The file to write to. Defaults to ``stdout``. + :param err: Write to ``stderr`` instead of ``stdout``. + :param nl: Print a newline after the message. Enabled by default. + :param color: Force showing or hiding colors and other styles. By + default Click will remove color if the output does not look like + an interactive terminal. .. versionchanged:: 6.0 - As of Click 6.0 the echo function will properly support unicode - output on the windows console. Not that click does not modify - the interpreter in any way which means that `sys.stdout` or the - print statement or function will still not provide unicode support. + Support Unicode output on the Windows console. Click does not + modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` + will still not support Unicode. - .. versionchanged:: 2.0 - Starting with version 2.0 of Click, the echo function will work - with colorama if it's installed. + .. versionchanged:: 4.0 + Added the ``color`` parameter. .. versionadded:: 3.0 - The `err` parameter was added. + Added the ``err`` parameter. - .. versionchanged:: 4.0 - Added the `color` flag. - - :param message: the message to print - :param file: the file to write to (defaults to ``stdout``) - :param err: if set to true the file defaults to ``stderr`` instead of - ``stdout``. This is faster and easier than calling - :func:`get_text_stderr` yourself. - :param nl: if set to `True` (the default) a newline is printed afterwards. - :param color: controls if the terminal supports ANSI colors or not. The - default is autodetection. + .. versionchanged:: 2.0 + Support colors on Windows if colorama is installed. """ if file is None: if err: @@ -247,11 +239,8 @@ def echo(message=None, file=None, nl=True, err=False, color=None): binary_file.flush() return - # ANSI-style support. If there is no message or we are dealing with - # bytes nothing is happening. If we are connected to a file we want - # to strip colors. If we are on windows we either wrap the stream - # to strip the color or we use the colorama support to translate the - # ansi codes to API calls. + # ANSI style code support. For no message or bytes, nothing happens. + # When outputting to a file instead of a terminal, strip codes. if message and not is_bytes(message): color = resolve_color_default(color) if should_strip_ansi(file, color):
diff --git a/requirements/tests.in b/requirements/tests.in --- a/requirements/tests.in +++ b/requirements/tests.in @@ -1,3 +1,2 @@ pytest -colorama importlib_metadata diff --git a/requirements/tests.txt b/requirements/tests.txt --- a/requirements/tests.txt +++ b/requirements/tests.txt @@ -6,8 +6,6 @@ # attrs==20.3.0 # via pytest -colorama==0.4.4 - # via -r requirements/tests.in importlib-metadata==3.4.0 # via -r requirements/tests.in iniconfig==1.1.1 diff --git a/tests/test_imports.py b/tests/test_imports.py --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -41,7 +41,6 @@ def tracking_import(module, locals=None, globals=None, fromlist=None, "itertools", "io", "threading", - "colorama", "errno", "fcntl", "datetime", @@ -51,7 +50,7 @@ def tracking_import(module, locals=None, globals=None, fromlist=None, } if WIN: - ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"]) + ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"]) def test_light_imports():
Use of Setuptools' "extras_require" for colorama? Might it make sense to use Setuptools' ["extras"](https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies) feature for automatically installing colorama on Windows? Currently the docs contain fragments to the effect of "_if_ colorama is installed," and advise the user to install colorama if they wish to lend click extra functionality on Windows. So, might a ```python extras_require={"wincolors": ["colorama"]} ``` allowing users to `pip install click[wincolors]` be a better option?
I think in this case I'd like to just make it an automatically installed dependency on Windows.
2021-02-16T02:34:22Z
[]
[]
pallets/click
1,785
pallets__click-1785
[ "457" ]
98e471fb871f211dd40b1bea80942acb7bb9f176
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1769,9 +1769,10 @@ class Parameter: :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. - :param callback: a callback that should be executed after the parameter - was matched. This is called as ``fn(ctx, param, - value)`` and needs to return the value. + :param callback: A function to further process or validate the value + after type conversion. It is called as ``f(ctx, param, value)`` + and must return the value. It is called for all sources, + including prompts. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's @@ -1792,6 +1793,12 @@ class Parameter: of :class:`~click.shell_completion.CompletionItem` or a list of strings. + .. versionchanged:: 8.0 + ``process_value`` validates required parameters and bounded + ``nargs``, and invokes the parameter callback before returning + the value. This allows the callback to validate prompts. + ``full_process_value`` is removed. + .. versionchanged:: 8.0 ``autocompletion`` is renamed to ``shell_complete`` and has new semantics described above. The old name is deprecated and will @@ -2008,17 +2015,6 @@ def _convert(value, level): return _convert(value, (self.nargs != 1) + bool(self.multiple)) - def process_value(self, ctx, value): - """Given a value and context this runs the logic to convert the - value as necessary. - """ - # If the value we were given is None we do nothing. This way - # code that calls this can easily figure out if something was - # not provided. Otherwise it would be converted into an empty - # tuple for multiple invocations which is inconvenient. - if value is not None: - return self.type_cast_value(ctx, value) - def value_is_missing(self, value): if value is None: return True @@ -2026,8 +2022,9 @@ def value_is_missing(self, value): return True return False - def full_process_value(self, ctx, value): - value = self.process_value(ctx, value) + def process_value(self, ctx, value): + if value is not None: + value = self.type_cast_value(ctx, value) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) @@ -2049,6 +2046,9 @@ def full_process_value(self, ctx, value): f" {len(value)} {were} given." ) + if self.callback is not None: + value = self.callback(ctx, self, value) + return value def resolve_envvar_value(self, ctx): @@ -2081,10 +2081,7 @@ def handle_parse_result(self, ctx, opts, args): ctx.set_parameter_source(self.name, source) try: - value = self.full_process_value(ctx, value) - - if self.callback is not None: - value = self.callback(ctx, self, value) + value = self.process_value(ctx, value) except Exception: if not ctx.resilient_parsing: raise
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -228,7 +228,7 @@ def test_missing_argument_string_cast(): ctx = click.Context(click.Command("")) with pytest.raises(click.MissingParameter) as excinfo: - click.Argument(["a"], required=True).full_process_value(ctx, None) + click.Argument(["a"], required=True).process_value(ctx, None) assert str(excinfo.value) == "missing parameter: a" diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -376,6 +376,22 @@ def cmd(foo): assert result.output == "42\n" +def test_callback_validates_prompt(runner, monkeypatch): + def validate(ctx, param, value): + if value < 0: + raise click.BadParameter("should be positive") + + return value + + @click.command() + @click.option("-a", type=int, callback=validate, prompt=True) + def cli(a): + click.echo(a) + + result = runner.invoke(cli, input="-12\n60\n") + assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n" + + def test_winstyle_options(runner): @click.command() @click.option("/debug;/no-debug", help="Enables or disables debug mode.") @@ -409,7 +425,7 @@ def test_missing_option_string_cast(): ctx = click.Context(click.Command("")) with pytest.raises(click.MissingParameter) as excinfo: - click.Option(["-a"], required=True).full_process_value(ctx, None) + click.Option(["-a"], required=True).process_value(ctx, None) assert str(excinfo.value) == "missing parameter: a"
Sanitization for click inputs I would like to see some method of easy sanitation after an input. I guess I could define a type and require that type for the input but that seems a little extravagant if I want to make sure that say a field entered is a valid email address during input or to strip out spaces automatically. I know I can do this in the code but it should be possible inside prompt.
Can you not use our callback system for this? Oh I see. We might only invoke the type conversion but not the callbacks for prompts currently. I wonder if that can be changed though. It would be a good feature indeed. Yeah in the code I wrote I ended up just calling strip to sanitize it somewhat and prevent spaces at the beginning and the end but that does not actually validate the data. It does fix the issue I had of people using copy and paste and grabbing a space but not the underlying problem of allowing a complete input sanitization check. `Parameter.callback` is already called for the result of `prompt` (or any other parameter source), but it's called *after* `prompt` returns, not inside it. So while it's possible to perform extra processing, if that processing raises a `click.UsageError` it exits instead of prompting again. I'm not sure if this was always the case or if it was due to recent refactors to the type processing pipeline. I think we can extend that refactoring a bit further though to address this issue. `prompt` is passed `self.process_value`, which only does type conversion. However, `handle_parse_result` calls `full_process_value` (which calls `process_value`) then applies the callback separately. There's no reason to have that separate anymore, and along with that there's no reason to have both `process_value` and `full_process_value`. 1. Inline `Parameter.process_value` into `Parameter.full_process_value`. 2. Rename `full_process_value` to `process_value`. 2. Move the `if self.callback:` block from `Parameter.handle_parse_result` to the bottom of `process_value`.
2021-02-16T19:28:19Z
[]
[]
pallets/click
1,786
pallets__click-1786
[ "723" ]
0805f60cfc7a48b9a951733a81639e7fda430152
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2146,8 +2146,9 @@ class Option(Parameter): :param prompt: if set to `True` or a non empty string then the user will be prompted for input. If set to `True` the prompt will be the option name capitalized. - :param confirmation_prompt: if set then the value will need to be confirmed - if it was prompted for. + :param confirmation_prompt: Prompt a second time to confirm the + value if it was prompted for. Can be set to a string instead of + ``True`` to customize the message. :param prompt_required: If set to ``False``, the user will be prompted for input only when the option was specified as a flag without a value. @@ -2203,6 +2204,7 @@ def __init__( prompt_text = None else: prompt_text = prompt + self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.prompt_required = prompt_required diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -85,21 +85,14 @@ def prompt( If the user aborts the input by sending a interrupt signal, this function will catch it and raise a :exc:`Abort` exception. - .. versionadded:: 7.0 - Added the show_choices parameter. - - .. versionadded:: 6.0 - Added unicode support for cmd.exe on Windows. - - .. versionadded:: 4.0 - Added the `err` parameter. - :param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. - :param confirmation_prompt: asks for confirmation for the value. + :param confirmation_prompt: Prompt a second time to confirm the + value. Can be set to a string instead of ``True`` to customize + the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to @@ -112,6 +105,19 @@ def prompt( For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ". + + .. versionadded:: 8.0 + ``confirmation_prompt`` can be a custom string. + + .. versionadded:: 7.0 + Added the ``show_choices`` parameter. + + .. versionadded:: 6.0 + Added unicode support for cmd.exe on Windows. + + .. versionadded:: 4.0 + Added the `err` parameter. + """ result = None @@ -137,6 +143,12 @@ def prompt_func(text): text, prompt_suffix, show_default, default, show_choices, type ) + if confirmation_prompt: + if confirmation_prompt is True: + confirmation_prompt = "Repeat for confirmation" + + confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) + while 1: while 1: value = prompt_func(prompt) @@ -156,7 +168,7 @@ def prompt_func(text): if not confirmation_prompt: return result while 1: - value2 = prompt_func("Repeat for confirmation: ") + value2 = prompt_func(confirmation_prompt) if value2: break if value == value2:
diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -446,3 +446,27 @@ def cli(value, o): result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False) assert result.exception is None assert result.return_value == expect + + [email protected]( + ("prompt", "input", "expect"), + [ + (True, "password\npassword", "password"), + ("Confirm Password", "password\npassword\n", "password"), + (False, None, None), + ], +) +def test_confirmation_prompt(runner, prompt, input, expect): + @click.command() + @click.option( + "--password", prompt=prompt, hide_input=True, confirmation_prompt=prompt + ) + def cli(password): + return password + + result = runner.invoke(cli, input=input, standalone_mode=False) + assert result.exception is None + assert result.return_value == expect + + if prompt == "Confirm Password": + assert "Confirm Password: " in result.output
Configurable "Repeat for confirmation:" text It would be nice to be able to set this prompt confirmation text.
This is also something I'd like, and I'd be willing to submit a PR for this if it can make things faster, but I wonder if it would have any chance to be merged when I see the amount of unanswered issues and PR's. If the repo owner passes by, do you think it would be worth it to work on a PR? I can't comment on whether it will be merged in or not, but you are welcome to submit a PR.
2021-02-18T19:01:04Z
[]
[]
pallets/click
1,793
pallets__click-1793
[ "1271" ]
80086c4b393f2e5532c9ad35b79fee653aa47730
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -471,11 +471,6 @@ def strip_ansi(value): def _is_jupyter_kernel_output(stream): - if WIN: - # TODO: Couldn't test on Windows, should't try to support until - # someone tests the details wrt colorama. - return - while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): stream = stream._stream @@ -521,7 +516,7 @@ def auto_wrap_for_ansi( strip = should_strip_ansi(stream, color) ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) - rv = ansi_wrapper.stream + rv = t.cast(t.TextIO, ansi_wrapper.stream) _write = rv.write def _safe_write(s):
diff --git a/tests/test_compat.py b/tests/test_compat.py --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -1,10 +1,6 @@ -import pytest - from click._compat import should_strip_ansi -from click._compat import WIN [email protected](WIN, reason="Jupyter not tested/supported on Windows") def test_is_jupyter_kernel_output(): class JupyterKernelFakeStream: pass
Styled output support for JupyterLab Not sure if this's a goal. But some issues mention support for Jupyter Notebook, and I'm not sure why it doesn't work in Jupyter Lab. It prints fine, but with no styling. * Python 3.7.1 * Click 7.0 * Jupyter Lab 0.35.4
duplicate of #1186 based on the comment in #1186 this one has to reopen as its a different kernel with a different io stream I have successfully duplicated the issue on JupyterLab in Windows: Input: ```python import click print(click.style('Hello World!', fg='green', bold=True, underline=True)) click.echo(click.style('Hello World!', fg='green', bold=True, underline=True)) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) ``` Output: ![image](https://user-images.githubusercontent.com/35740094/96667930-a712df80-1377-11eb-8047-fd678f2f627d.png) So we don't have any styling whatsoever here, which is expected. Interestingly enough I found another inconsistency that's not just limited to JupyterLab, passing the same input into a test file gives us the following result. ![image](https://user-images.githubusercontent.com/35740094/96668043-e9d4b780-1377-11eb-8a3e-a278c25b0f88.png) Using `print` leads to the expected style, with bold and underline, whereas using `click.echo` does not enable them. This was pointed out in the following comment -> https://github.com/pallets/click/pull/1186#issuecomment-478637599 You'll have to be more specific about how you're writing to a file for me to say, but at least the `print` behavior is expected. `click.echo` checks the stream to see if it should strip the color codes, `print` does not. That's the whole issue, there's a special check to tell it that Jupyter kernel streams are ok, but it still doesn't detect JupyterLab streams. Roger that! I'll get right on it, thanks for the clarification.
2021-02-24T21:30:03Z
[]
[]
pallets/click
1,796
pallets__click-1796
[ "1597" ]
81bddecfd32fda82fc8421cd316e55a2db8575d1
diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -57,6 +57,9 @@ def make_default_short_help(help, max_length=45): result = [] done = False + if words[0] == "\b": + words = words[1:] + for word in words: if word[-1:] == ".": done = True
diff --git a/tests/test_formatting.py b/tests/test_formatting.py --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -296,6 +296,25 @@ def cli(ctx): ] +def test_removing_multiline_marker(runner): + @click.group() + def cli(): + pass + + @cli.command() + def cmd1(): + """\b + This is command with a multiline help text + which should not be rewrapped. + The output of the short help text should + not contain the multiline marker. + """ + pass + + result = runner.invoke(cli, ["--help"]) + assert "\b" not in result.output + + def test_global_show_default(runner): @click.command(context_settings=dict(show_default=True)) @click.option("-f", "in_file", default="out.txt", help="Output file name")
get help does not remove multiline marker if You have commands with a multi-line help, the `\b` is not brushed off the help output if You use -h it looks correct in the terminal : ``` $> cli_command -h Usage: test_cli_help.py [OPTIONS] COMMAND [ARGS]... some help Options: --version Show the version and exit. -h, --help Show this message and exit. Commands: command1 command1 without arguments and options command2 command2 with arguments command3 command3 with multi line help arguments and options command4 command4 with arguments, options and sub_command and a very... ``` but if You parse the text, You will see that the `\b` is not brushed off, where it should be, see the ` ` near command3, command4. instead of brushing off the `\b`, You just added one whitespace. ``` $> cli_command -h > ./help.txt # Content of ./help.txt : Usage: test_cli_help.py [OPTIONS] COMMAND [ARGS]... some help Options: --version Show the version and exit. -h, --help Show this message and exit. Commands: command1 command1 without arguments and options command2 command2 with arguments command3  command3 with multi line help arguments and options command4  command4 with arguments, options and sub_command and a very... ``` this is my example: ```python # EXT import click # CONSTANTS CLICK_CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) CLICK_CONTEXT_SETTINGS_NO_HELP = dict(help_option_names=[]) @click.group(help='some help', context_settings=CLICK_CONTEXT_SETTINGS) @click.version_option(version='1.1.1', prog_name='program name', message='{} version %(version)s'.format('cli command')) def cli_main() -> None: # pragma: no cover pass # pragma: no cover # command1 without arguments and options @cli_main.command('command1', context_settings=CLICK_CONTEXT_SETTINGS_NO_HELP) def cli_command1() -> None: # pragma: no cover """ command1 without arguments and options """ pass # command2 with arguments @cli_main.command('command2', context_settings=CLICK_CONTEXT_SETTINGS) @click.argument('argument1') @click.argument('argument2') def cli_command2(argument1: str, argument2: str) -> None: """ command2 with arguments """ pass # pragma: no cover # command3 with arguments and options @cli_main.command('command3', context_settings=CLICK_CONTEXT_SETTINGS) @click.argument('argument1') @click.argument('argument2') @click.option('-a', '--a_option', is_flag=True) # no help here @click.option('-b', '--b_option', type=int, default=-1, help='help for b_option') @click.option('-c', '--c_option', help='help for c_option') def cli_command3(argument1: str, argument2: str, a_option: bool, b_option: int, c_option: str) -> None: """\b command3 with multi line help arguments and options """ pass # pragma: no cover # command4 with arguments, options and sub_command # groups must not have arguments or we can not parse them # because to get help for the sub command we need to put : # program command4 arg1 arg2 command5 -h # and we dont know the correct type of arg1, arg2 @cli_main.group('command4', context_settings=CLICK_CONTEXT_SETTINGS) @click.argument('argument1') @click.argument('argument2') @click.option('-a', '--a_option', is_flag=True) # no help here @click.option('-b', '--b_option', type=int, default=-1, help='help for b_option') @click.option('-c', '--c_option', help='help for c_option') def cli_command4(argument1: str, argument2: str, a_option: bool, b_option: int, c_option: str) -> None: """\b command4 with arguments, options and sub_command and a very long multiline help what for sure will not fit into one terminal line what for sure will not fit into one terminal line what for sure will not fit into one terminal line what for sure will not fit into one terminal line """ pass # pragma: no cover # command5, sub_command of command4 with arguments, options @cli_command4.command('command5', context_settings=CLICK_CONTEXT_SETTINGS) @click.argument('argument1') @click.argument('argument2') @click.option('-a', '--a_option', is_flag=True) # no help here @click.option('-b', '--b_option', type=int, default=-1, help='help for b_option') @click.option('-c', '--c_option', help='help for c_option') def cli_command5(argument1: str, argument2: str, a_option: bool, b_option: int, c_option: str) -> None: """command5, sub_command of command4 with arguments, options""" pass # pragma: no cover # entry point if main if __name__ == '__main__': cli_main() ``` * Click version: latest
This can be avoided by adding a short_help or a summary at the start of the doc string. Below is a patch that would handle the example: ```diff diff --git a/src/click/utils.py b/src/click/utils.py index 0bff5c0..89d726d 100644 --- a/src/click/utils.py +++ b/src/click/utils.py @@ -54,6 +54,13 @@ def make_default_short_help(help, max_length=45): result = [] done = False + # Use only the first line when string shouldn't be rewrapped. + if words[0] == '\b': + for line in help.splitlines(): + if line and line != '\b': + words = line.split() + break + for word in words: if word[-1:] == ".": done = True ``` Hey, I'm a fellow from MLH. I'd like to work on this issue.
2021-03-01T12:20:43Z
[]
[]
pallets/click
1,803
pallets__click-1803
[ "1648" ]
3018f577cc1d5e7682fd091845df999b86007a6c
diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -102,7 +102,6 @@ def __init__( self.current_item = None self.is_hidden = not isatty(self.file) self._last_line = None - self.short_limit = 0.5 def __enter__(self): self.entered = True @@ -126,11 +125,8 @@ def __next__(self): # twice works and does "what you want". return next(iter(self)) - def is_fast(self): - return time.time() - self.start <= self.short_limit - def render_finish(self): - if self.is_hidden or self.is_fast(): + if self.is_hidden: return self.file.write(AFTER_BAR) self.file.flush() @@ -263,7 +259,7 @@ def render_progress(self): line = "".join(buf) # Render the line only if it changed. - if line != self._last_line and not self.is_fast(): + if line != self._last_line: self._last_line = line echo(line, file=self.file, color=self.color, nl=False) self.file.flush() diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -390,6 +390,9 @@ def progressbar( :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators. + .. versionchanged:: 8.0 + Output is shown even if execution time is less than 0.5 seconds. + .. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output.
diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -27,16 +27,14 @@ def _create_progress(length=10, length_known=True, **kwargs): def test_progressbar_strip_regression(runner, monkeypatch): - fake_clock = FakeClock() label = " padded line" @click.command() def cli(): with _create_progress(label=label) as progress: for _ in progress: - fake_clock.advance_time() + pass - monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) assert label in runner.invoke(cli, []).output @@ -60,30 +58,24 @@ def __next__(self): next = __next__ - fake_clock = FakeClock() - @click.command() def cli(): with click.progressbar(Hinted(10), label="test") as progress: for _ in progress: - fake_clock.advance_time() + pass - monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) result = runner.invoke(cli, []) assert result.exception is None def test_progressbar_hidden(runner, monkeypatch): - fake_clock = FakeClock() - @click.command() def cli(): with _create_progress(label="working") as progress: for _ in progress: - fake_clock.advance_time() + pass - monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False) assert runner.invoke(cli, []).output == "working\n" @@ -193,21 +185,16 @@ def test_progressbar_iter_outside_with_exceptions(runner): def test_progressbar_is_iterator(runner, monkeypatch): - fake_clock = FakeClock() - @click.command() def cli(): with click.progressbar(range(10), label="test") as progress: while True: try: next(progress) - fake_clock.advance_time() except StopIteration: break - monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) - result = runner.invoke(cli, []) assert result.exception is None @@ -289,50 +276,42 @@ def cli(): lines = [line for line in output.split("\n") if "[" in line] - assert " 25% 00:00:03" in lines[0] - assert " 50% 00:00:02" in lines[1] - assert " 75% 00:00:01" in lines[2] - assert "100% " in lines[3] + assert " 0%" in lines[0] + assert " 25% 00:00:03" in lines[1] + assert " 50% 00:00:02" in lines[2] + assert " 75% 00:00:01" in lines[3] + assert "100% " in lines[4] def test_progressbar_item_show_func(runner, monkeypatch): - fake_clock = FakeClock() - @click.command() def cli(): with click.progressbar( - range(4), item_show_func=lambda x: f"Custom {x}" + range(3), item_show_func=lambda x: f"Custom {x}" ) as progress: for _ in progress: - fake_clock.advance_time() - print("") + click.echo() - monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) output = runner.invoke(cli, []).output - - lines = [line for line in output.split("\n") if "[" in line] - - assert "Custom 0" in lines[0] - assert "Custom 1" in lines[1] - assert "Custom 2" in lines[2] - assert "Custom None" in lines[3] + lines = [line for line in output.splitlines() if "[" in line] + assert "Custom None" in lines[0] + assert "Custom 0" in lines[1] + assert "Custom 1" in lines[2] + assert "Custom 2" in lines[3] + assert "Custom None" in lines[4] def test_progressbar_update_with_item_show_func(runner, monkeypatch): - fake_clock = FakeClock() - @click.command() def cli(): with click.progressbar( length=6, item_show_func=lambda x: f"Custom {x}" ) as progress: while not progress.finished: - fake_clock.advance_time() progress.update(2, progress.pos) - print("") + click.echo() - monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) output = runner.invoke(cli, []).output
Progress bar does not display until after the first item is complete Take this example: ```python with click.progressbar(length=6, label="Doing something") as bar: for thing in [3, 2, 1]: time.sleep(thing) bar.update(thing) ``` This shows nothing until three seconds, at which point it shows: ``` Doing something [##################------------------] 50% 00:00:03 ``` Would it be reasonable for it to display a `0%` at first? This is mostly an issue with a small number of items which take a long time.
Duplicate of #1353. I saw that issue – fine if you prefer to group them. It's not necessarily the same issue though: would be possible to display the last item _and_ start showing from the 0th item. This was introduced in #487. I just ran into the same confusion when fixing the tests for #1353/#1354, the first line of progress wasn't shown and it wasn't clear why. Reading #487, I'm not convinced by the reasoning, if you have a fast machine or fast process, it doesn't hurt to output the progress bar. I'm going to revert that. *Maybe* it would make sense to somehow hide the progress bar if *all* iterations finish quickly, but otherwise you end up in this weird situation where the bar displays late because the first iteration is always "fast". I don't see a simple way to implement that though, and in general want to avoid adding complexity to Click's progress bar at this point.
2021-03-04T02:32:57Z
[]
[]
pallets/click
1,804
pallets__click-1804
[ "405", "1234" ]
1472e3d697215039f499cb0b51d8bea6a9aa3144
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -649,9 +649,6 @@ class Path(ParamType): handle it returns just the filename. Secondly, it can perform various basic checks about what the file or directory should be. - .. versionchanged:: 6.0 - `allow_dash` was added. - :param exists: if set to true, the file or directory needs to exist for this value to be valid. If this is not required and a file does indeed not exist, then all further checks are @@ -667,11 +664,15 @@ class Path(ParamType): supposed to be done by the shell only. :param allow_dash: If this is set to `True`, a single dash to indicate standard streams is permitted. - :param path_type: optionally a string type that should be used to - represent the path. The default is `None` which - means the return value will be either bytes or - unicode depending on what makes most sense given the - input data Click deals with. + :param path_type: Convert the incoming path value to this type. If + ``None``, keep Python's default, which is ``str``. Useful to + convert to :class:`pathlib.Path`. + + .. versionchanged:: 8.0 + Allow passing ``type=pathlib.Path``. + + .. versionchanged:: 6.0 + Added the ``allow_dash`` parameter. """ envvar_list_splitter = os.path.pathsep @@ -698,13 +699,10 @@ def __init__( if self.file_okay and not self.dir_okay: self.name = "file" - self.path_type = "File" elif self.dir_okay and not self.file_okay: self.name = "directory" - self.path_type = "Directory" else: self.name = "path" - self.path_type = "Path" def to_info_dict(self): info_dict = super().to_info_dict() @@ -721,9 +719,12 @@ def to_info_dict(self): def coerce_path_result(self, rv): if self.type is not None and not isinstance(rv, self.type): if self.type is str: - rv = rv.decode(get_filesystem_encoding()) + rv = os.fsdecode(rv) + elif self.type is bytes: + rv = os.fsencode(rv) else: - rv = rv.encode(get_filesystem_encoding()) + rv = self.type(rv) + return rv def convert(self, value, param, ctx): @@ -741,32 +742,32 @@ def convert(self, value, param, ctx): if not self.exists: return self.coerce_path_result(rv) self.fail( - f"{self.path_type} {filename_to_ui(value)!r} does not exist.", + f"{self.name.title()} {filename_to_ui(value)!r} does not exist.", param, ctx, ) if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( - f"{self.path_type} {filename_to_ui(value)!r} is a file.", + f"{self.name.title()} {filename_to_ui(value)!r} is a file.", param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( - f"{self.path_type} {filename_to_ui(value)!r} is a directory.", + f"{self.name.title()} {filename_to_ui(value)!r} is a directory.", param, ctx, ) if self.writable and not os.access(value, os.W_OK): self.fail( - f"{self.path_type} {filename_to_ui(value)!r} is not writable.", + f"{self.name.title()} {filename_to_ui(value)!r} is not writable.", param, ctx, ) if self.readable and not os.access(value, os.R_OK): self.fail( - f"{self.path_type} {filename_to_ui(value)!r} is not readable.", + f"{self.name.title()} {filename_to_ui(value)!r} is not readable.", param, ctx, )
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1,3 +1,5 @@ +import pathlib + import pytest import click @@ -78,3 +80,23 @@ def test_cast_multi_default(runner, nargs, multiple, default, expect): result = runner.invoke(cli, standalone_mode=False) assert result.exception is None assert result.return_value == expect + + [email protected]( + ("cls", "expect"), + [ + (None, "a/b/c.txt"), + (str, "a/b/c.txt"), + (bytes, b"a/b/c.txt"), + (pathlib.Path, pathlib.Path("a", "b", "c.txt")), + ], +) +def test_path_type(runner, cls, expect): + cli = click.Command( + "cli", + params=[click.Argument(["p"], type=click.Path(path_type=cls))], + callback=lambda p: p, + ) + result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False) + assert result.exception is None + assert result.return_value == expect
click.Path returns str, not pathlib.Path It’s surprising that `INT` returns an `int`, `File` a `file`, `STRING` a `str`, but `Path` a …`str`? A `click.Path` parameter should return a `pathlib.Path` object. Allow path_type of the Path type to accept a callable (`#405`_) This would allow to convert path names to pathlib.Path instances for example. closes #405
pathlib is Python 3 only afaict, Click isn't. FWIW I'm certain that an option to return a Path object is useful, but I can't see it becoming the default. [it’s backported](https://pypi.python.org/pypi/pathlib/) It's still not possible to make this a default since this would mean that the behavior of Click would depend on whether that backport is installed. And depending on that backport is not worth the added value. > depending on that backport is not worth the added value. what cost/value function evaluates to this result? :smile: In this case, new functionality. Pathlib is merely a new API for the same thing. Sorry, but I don't think this is going to happen. I'll gladly accept PRs for a non-default option though. On Mon, Aug 10, 2015 at 06:28:08AM -0700, Philipp A. wrote: > > depending on that backport is not worth the added value. > > what cost/value function evaluates to this result? :smile: > > --- > > Reply to this email directly or view it on GitHub: > https://github.com/mitsuhiko/click/issues/405#issuecomment-129451586 What do you mean with “non-default option”? Opt-in for returning a pathlib.Path object instead of a string. The user has to depend on the pathlib library themselves unless it's in the stdlib. I think that's doable. On Mon, Aug 10, 2015 at 06:37:04AM -0700, Philipp A. wrote: > What do you mean with “non-default option”? > > --- > > Reply to this email directly or view it on GitHub: > https://github.com/mitsuhiko/click/issues/405#issuecomment-129457794 got it, makes sense. best would be to do it on arbitrary levels, right? e.g. you could create a group that is configured to do it, passing it down to all subcommands and parameters, or on single parameters or even options. the interaction of this with `click.CommandCollection` is obvious, but bad: merging a non-pathlib group with a pathlib group would simply behave as if each individual command would have been configured, and result in a mess, but that’s not really a problem i guess, and there’s no alternative anyway > got it, makes sense. best would be to do it on arbitrary levels, right? Honestly I don't think that's a good idea, it makes it hard to trace why a particular option is returning this particular type. If you want to avoid repetition/verbosity, you can still bind the created decorator to a new name for reuse, or create a new decorator that has it as default. hmm, yeah, using `partial`. only commands are defined on the group, so this would be easy. Not going to happen. A custom path implementation might be something for addon packages. Welp- worth reevaluating in the light of [PEP 519](https://www.python.org/dev/peps/pep-0519/)? also are you going to sign the [python 3 statement](http://www.python3statement.org/)? if so, we can tackle this in 2020. That PEP makes a lot of things easier, but AFAICT it doesn't even apply to all versions of Python 3. I'd personally love to drop Python 2 at some point, but even for me 2020 is way too soon. It's not (only) my decision to make. On Mon, Jan 23, 2017 at 02:26:37AM -0800, Philipp A. wrote: > worth reevaluating in the light of [PEP 519](https://www.python.org/dev/peps/pep-0519/)? > > also are you going to sign the [python statement](http://www.python3statement.org/)? if so, we can tackle this in 2020. > > -- > You are receiving this because you modified the open/close state. > Reply to this email directly or view it on GitHub: > https://github.com/pallets/click/issues/405#issuecomment-274450716 i didn’t want to propose that, just ask 😉 the PEP partly applies to everything, as it describes a protocol, not just an API. checking for the existence of `__fspath__` works in any version! It would be really confusing to get a `pathlib.Path` object in 3.6+, but not in 3.5 or lower. Is gating this on a (non-default) flag on `click.Path` still out per https://github.com/pallets/click/issues/405#issuecomment-140582568? Since `PATH` does not exist anyways we can do two things. One is we set up a default mapping for `pathlib.Path` as input type (similar to how we have a default type for `str`) being passed to `click.Path(convert=pathlib.Path)` and then add support for `convert` being passed to `click.Path`. That way someone can also pass it through something else that does something interesting with the path. I understand finding time for reviews is hard but I wanted to make sure I didn't need to be doing something else for ~~#405~~ #1148. I think it fits within the suggested approach of having a generic converter which a developer could pass `pathlib.Path` to if they so chose. err, #1148 I'd love to see this. I expected `click.Path(path_type=pathlib.PurePath)` would cast my result to a `PurePath`, but @altendky's `converter` is even more clear. Would love to see this pulled ASAP so I can start using it in my app. I 'd agree with @NotTheEconomist version without new arguments. Please consider #1234 . For the impatient, I defined my own like this. It accepts all the same options as `click.Path`: ```python class PathPath(click.Path): """A Click path argument that returns a pathlib Path, not a string""" def convert(self, value, param, ctx): return Path(super().convert(value, param, ctx)) ``` ```python @click.argument('input', type=PathPath(dir_okay=False)) def ... ``` (this usage style also feels cleaner to me than `click.Path(...., converter=pathlib.Path)`, as well as more easily remembered. Path is built into Python's standard library and widely used, so I think it's worth a dedicated type.) Thanks @jeremyh ! I have packaged this solution into https://pypi.org/project/click-pathlib, so you can use: ``` $ pip install click-pathlib ``` ```python import click import click_pathlib @click.command('delete') @click.argument( 'existing_file', type=click_pathlib.Path(exists=True), ) def delete(existing_file): existing_file.unlink() ``` Seeing as Python 2 is now dead and all, does it maybe make sense to now transition to using pathlib.Path as a default instead of a str value? Pretty sure that would require a major release, and while pathlib is awesome, I think it's the kind of change that would be a pain in the ass for any downstream user who doesn't already use pathlib. Also, even if Path is available on Python 3.x it's not mandatory to use it, a developer can still choose to use plain string or a Path instance Any request for making this the default basically asks for two things: * New major version of click, break all existing code * Drop Python 2 *or* pull in dependency on backport Each of those points in isolation is an extreme measure to make this happen, combined even more. The second one isn’t, Python 2 isn’t supported anymore so you’re free to move on and get rid of all hideous compatibility hacks :tada: About the first … click has a lot of major version releases, and derive from your reluctance that they’re all less intrusive than this one? Click supports Python 2. You know I mean that Python 2 is unmaintained as of 2 weeks ago. Supporting something that’s unmaintained is pretty futile. I'm saying that this is a completely separate decision to make. But I forgot that we already announced dropped support for Python 2 so this would probably be fine to land in Click 8. https://palletsproject.com/blog/ending-python2-support/ Hmm, just spitballing here, but maybe a transitional release could be done (after #1148 is merged). In Click 8, the following would raise a `FutureWarning` like this: ```py @click.argument('filename', type=click.Path()) ``` > You specified no Path converter. `click.Path(converter=None)` will result in a `pathlib.Path` object in Click 9. To avoid this warning, specify `converter=str` or `converter=pathlib.Path`. And consequently, in Click 9 (or 10), the warning would be gone and the default changed. An alternative (also depending on #1148) would be to follow @mitsuhiko’s idea in https://github.com/pallets/click/issues/405#issuecomment-324987608: We just add `click.PATH` and use it in examples instead of `click.Path`, therefore encouraging `click.PATH` without breaking changes. This would be less disruptive. Ran `tox` on this locally ``` py37: commands succeeded SKIPPED: py36: InterpreterNotFound: python3.6 py35: commands succeeded SKIPPED: py34: InterpreterNotFound: python3.4 py27: commands succeeded SKIPPED: pypy3: InterpreterNotFound: pypy3 SKIPPED: pypy: InterpreterNotFound: pypy ``` I also tested this with an application I'm developing by adding `git+https://github.com/termim/click.git@I405#egg=click` to my `requirements.txt` and it works as advertised. However, using `pathlib.Path` as the `path_type` with [Click7.0](https://github.com/pallets/click/commit/a936b99212c69a36a2cc2828252b2c4280c0c88c) ``` @click.option('--config', '-c', type=click.Path(exists=True,dir_okay=False,path_type=pathlib.Path), required=False, help='Config file') ``` sets `config` to type `bytes` though backwards compatibility can be maintained as needed with ``` config = pathlib.Path(config.decode()) if isinstance(config,bytes) else config ``` as `pathlib.Path(None)` isn't accepted. Also, I'm not sure if there would be an advantage to setting [this](https://github.com/pallets/click/pull/1234/files#diff-9de36928a31dc2292c5f42ea1a3afbb4R141) to `isinstance(input,os.PathLike)` but it may be worth considering. Aside from the above it looks good to me, I would like to see this merged. > I looks like [this assertion](https://github.com/pallets/click/pull/1234/files#diff-9de36928a31dc2292c5f42ea1a3afbb4R157) needs to be uncommented. Done. > However, using `pathlib.Path` as the `path_type` with [Click7.0](https://github.com/pallets/click/commit/a936b99212c69a36a2cc2828252b2c4280c0c88c) > > ``` > @click.option('--config', '-c', type=click.Path(exists=True,dir_okay=False,path_type=pathlib.Path), required=False, help='Config file') > ``` > > sets `config` to type `bytes` though backwards compatibility can be maintained as needed with I can't reproduce this: ``` click>$ python3 --version Python 3.5.2 click>$ grep __version__ ./click/click/__init__.py __version__ = '7.1.dev' click>$ cat t.py import click import pathlib @click.command() @click.option('--config', '-c', type=click.Path(exists=True,dir_okay=False,path_type=pathlib.Path), required=False, help='Config file') def hello(config): click.echo('Hello %s!' % type(config)) if __name__ == '__main__': hello() click>$ click>$ PYTHONPATH=./click python3 ./t.py -c ./t.py Hello <class 'pathlib.PosixPath'>! click>$ ``` > > ``` > config = pathlib.Path(config.decode()) if isinstance(config,bytes) else config > ``` > > as `pathlib.Path(None)` isn't accepted. > > Also, I'm not sure if there would be an advantage to setting [this](https://github.com/pallets/click/pull/1234/files#diff-9de36928a31dc2292c5f42ea1a3afbb4R141) to `isinstance(input,os.PathLike)` but it may be worth considering. > That would make click require pathlib2 for python2 ... > > However, using `pathlib.Path` as the `path_type` with [Click7.0](https://github.com/pallets/click/commit/a936b99212c69a36a2cc2828252b2c4280c0c88c) > > ``` > > @click.option('--config', '-c', type=click.Path(exists=True,dir_okay=False,path_type=pathlib.Path), required=False, help='Config file') > > ``` > > sets `config` to type `bytes` though backwards compatibility can be maintained as needed with > > I can't reproduce this: > > ``` > click>$ python3 --version > Python 3.5.2 > click>$ grep __version__ ./click/click/__init__.py > __version__ = '7.1.dev' > click>$ cat t.py > import click > import pathlib > > @click.command() > @click.option('--config', '-c', type=click.Path(exists=True,dir_okay=False,path_type=pathlib.Path), required=False, help='Config file') > def hello(config): > click.echo('Hello %s!' % type(config)) > > if __name__ == '__main__': > hello() > click>$ > click>$ PYTHONPATH=./click python3 ./t.py -c ./t.py > Hello <class 'pathlib.PosixPath'>! > click>$ > ``` I was getting `bytes` using `path_type=pathlib.Path` without your PR on version 7.0. ``` $ python t.py -c t.py Hello <class 'bytes'>! ``` > I was getting `bytes` using `path_type=pathlib.Path` without your PR on version 7.0. Ah, yes, without this #1234 it always returns bytes if path_type is not a string ... `config = pathlib.Path(config.decode()) if isinstance(config,bytes) else config` provides backwards compatibility, so application developers can move to `pathlib` while waiting for your PR to make it downstream.
2021-03-05T04:36:03Z
[]
[]
pallets/click
1,805
pallets__click-1805
[ "1749" ]
4c7399eaeb77fae762a96e6aaa714ac591d6661a
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2011,7 +2011,15 @@ def _convert(value, level): if level == 0: return self.type(value, self, ctx) - return tuple(_convert(x, level - 1) for x in value) + try: + iter_value = iter(value) + except TypeError: + raise TypeError( + "Value for parameter with multiple = True or nargs > 1" + " should be an iterable." + ) + + return tuple(_convert(x, level - 1) for x in iter_value) return _convert(value, (self.nargs != 1) + bool(self.multiple))
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -117,6 +117,20 @@ def cli(message): assert "Error: Missing option '-m' / '--message'." in result.output +def test_multiple_bad_default(runner): + @click.command() + @click.option("--flags", multiple=True, default=False) + def cli(flags): + pass + + result = runner.invoke(cli, []) + assert result.exception + assert ( + "Value for parameter with multiple = True or nargs > 1 should be an iterable." + in result.exception.args + ) + + def test_empty_envvar(runner): @click.command() @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")
Traceback when CLI option has bad default could be more helpful ### Expected Behavior In the following command, I add an option `--multiple` with the metadata `multiple=True`, but the default `False` instead of `[False]`. Ideally, the traceback should indicate that the `--multiple` option has a bad default. ```python #!/usr/bin/env python import click @click.command() @click.option("--multiple", multiple=True, default=False, show_default=True) def cli(debug): pass if __name__ == '__main__': cli() ``` ### Actual Behavior Tell us what happens instead. ```pytb Traceback (most recent call last): File "./test_click.py", line 12, in <module> cli() File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 1025, in __call__ return self.main(*args, **kwargs) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 954, in main with self.make_context(prog_name, args, **extra) as ctx: File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 852, in make_context self.parse_args(ctx, args) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 1261, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 2078, in handle_parse_result value, source = self.consume_value(ctx, opts) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 2509, in consume_value value, source = super().consume_value(ctx, opts) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 1975, in consume_value value = self.get_default(ctx) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 2453, in get_default return super().get_default(ctx, call=call) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 1957, in get_default return self.type_cast_value(ctx, value) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 2007, in type_cast_value return _convert(value, (self.nargs != 1) + bool(self.multiple)) File "/home/user/anaconda3/envs/pybids-pre/lib/python3.8/site-packages/click/core.py", line 2005, in _convert return tuple(_convert(x, level - 1) for x in value) TypeError: 'bool' object is not iterable ``` I discovered this while running tests on pre-released dependencies, picking up click 8.0.0a1, which no longer accepts the above. The offending case was in a subcommand with many options, so it was not as obvious as it would be with a good error message. ### Environment * Python version: 3.8 * Click version: 8.0.0a1
I'm from MLH and I'm thinking of working on this issue, however I'm unsure of what type does `default` take when `multiple` is `True` or when `nargs` is set. Does it expect list/tuple or basically any iterable? Also will just putting the `return` statement causing the TypeError inside a `try` block suffice or do I add checks before returning? `multiple` or `nargs` expect a list/tuple. `multiple` *and* `nargs` together expect a list/tuple of lists/tuples, although that's not particularly important here. For now any iterable should be allowed, that code is checking all value sources, not only the default. A `try` block sounds fine, but I would isolate checking that it's iterable from doing the conversion, since the `ParamType` might raise `TypeError` for its own reasons: ```python try: iter_value = iter(value) except TypeError: raise TypeError(...) return tuple(... for x in iter_value) ```
2021-03-05T09:02:44Z
[]
[]
pallets/click
1,807
pallets__click-1807
[ "1739" ]
1cb86096124299579156f2c983efe05585f1a01b
diff --git a/docs/conf.py b/docs/conf.py --- a/docs/conf.py +++ b/docs/conf.py @@ -24,6 +24,7 @@ "sphinx_issues", "sphinx_tabs.tabs", ] +autodoc_typehints = "description" intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)} issues_github_path = "pallets/click" diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -1,4 +1,5 @@ import inspect +import typing as t from functools import update_wrapper from .core import Argument @@ -8,8 +9,11 @@ from .globals import get_current_context from .utils import echo +if t.TYPE_CHECKING: + F = t.TypeVar("F", bound=t.Callable[..., t.Any]) -def pass_context(f): + +def pass_context(f: "F") -> "F": """Marks a callback as wanting to receive the current context object as first argument. """ @@ -17,10 +21,10 @@ def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) - return update_wrapper(new_func, f) + return update_wrapper(t.cast("F", new_func), f) -def pass_obj(f): +def pass_obj(f: "F") -> "F": """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. @@ -29,10 +33,12 @@ def pass_obj(f): def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) - return update_wrapper(new_func, f) + return update_wrapper(t.cast("F", new_func), f) -def make_pass_decorator(object_type, ensure=False): +def make_pass_decorator( + object_type: t.Type, ensure: bool = False +) -> "t.Callable[[F], F]": """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type @@ -55,23 +61,59 @@ def new_func(ctx, *args, **kwargs): remembered on the context if it's not there yet. """ - def decorator(f): + def decorator(f: "F") -> "F": def new_func(*args, **kwargs): ctx = get_current_context() + if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) + if obj is None: raise RuntimeError( "Managed to invoke callback without a context" f" object of type {object_type.__name__!r}" " existing." ) + return ctx.invoke(f, obj, *args, **kwargs) - return update_wrapper(new_func, f) + return update_wrapper(t.cast("F", new_func), f) + + return decorator + + +def pass_meta_key( + key: str, *, doc_description: t.Optional[str] = None +) -> "t.Callable[[F], F]": + """Create a decorator that passes a key from + :attr:`click.Context.meta` as the first argument to the decorated + function. + + :param key: Key in ``Context.meta`` to pass. + :param doc_description: Description of the object being passed, + inserted into the decorator's docstring. Defaults to "the 'key' + key from Context.meta". + .. versionadded:: 8.0 + """ + + def decorator(f: "F") -> "F": + def new_func(*args, **kwargs): + ctx = get_current_context() + obj = ctx.meta[key] + return ctx.invoke(f, obj, *args, **kwargs) + + return update_wrapper(t.cast("F", new_func), f) + + if doc_description is None: + doc_description = f"the {key!r} key from :attr:`click.Context.meta`" + + decorator.__doc__ = ( + f"Decorator that passes {doc_description} as the first argument" + " to the decorated function." + ) return decorator
diff --git a/tests/test_context.py b/tests/test_context.py --- a/tests/test_context.py +++ b/tests/test_context.py @@ -4,6 +4,7 @@ import click from click.core import ParameterSource +from click.decorators import pass_meta_key def test_ensure_context_objects(runner): @@ -151,6 +152,28 @@ def cli(ctx): runner.invoke(cli, [], catch_exceptions=False) +def test_make_pass_meta_decorator(runner): + @click.group() + @click.pass_context + def cli(ctx): + ctx.meta["value"] = "good" + + @cli.command() + @pass_meta_key("value") + def show(value): + return value + + result = runner.invoke(cli, ["show"], standalone_mode=False) + assert result.return_value == "good" + + +def test_make_pass_meta_decorator_doc(): + pass_value = pass_meta_key("value") + assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__ + pass_value = pass_meta_key("value", doc_description="the test value") + assert "passes the test value" in pass_value.__doc__ + + def test_context_pushing(): rv = []
@pass_meta_key decorator ### Idea Proposal: As a click's plugin developer, we use the `click.Context.meta` dictionary to store any state. So IMHO, click could provide another decorator: `@click.pass_metavar(key="foo")` similar to `@click.pass_obj`. **Example implementation:** ```python def pass_metavar(key: str): """Similar to :func:`click.pass_obj`, this passes the ctx.meta[key] variable instead as the first argument. """ def decorator(f): @click.pass_context def new_func(ctx: click.Context, *args, **kwargs): var = ctx.meta[key] return ctx.invoke(f, var, *args, **kwargs) return update_wrapper(new_func, f) return decorator ``` **Example usage:** ```python @click.pass_metavar(key="foo") def bar(var): click.echo(var) ``` I think this would be beneficial for click's plugin developers and naturally anyone building a complex CLI app which requires using the `click.Context.meta` to store state. If you like the idea, I will be glad to raise a PR for it asap.
2021-03-05T16:53:01Z
[]
[]
pallets/click
1,816
pallets__click-1816
[ "1791" ]
bf3a945b3a220589c67d55dcb73cc1c9a9a175b3
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -40,14 +40,6 @@ SUBCOMMAND_METAVAR = "COMMAND [ARGS]..." SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." -DEPRECATED_HELP_NOTICE = " (DEPRECATED)" -DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated." - - -def _maybe_show_deprecated_notice(cmd): - if cmd.deprecated: - echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True) - def _fast_exit(code): """Low-level exit that skips Python's cleanup but speeds up exit by @@ -1193,12 +1185,15 @@ def get_short_help_str(self, limit=45): """Gets short help for the command or makes it by shortening the long help string. """ - return ( - self.short_help - or self.help - and make_default_short_help(self.help, limit) - or "" - ) + text = self.short_help or "" + + if not text and self.help: + text = make_default_short_help(self.help, limit) + + if self.deprecated: + text = f"(Deprecated) {text}" + + return text.strip() def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. @@ -1219,17 +1214,16 @@ def format_help(self, ctx, formatter): def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" - if self.help: - formatter.write_paragraph() - with formatter.indentation(): - help_text = self.help - if self.deprecated: - help_text += DEPRECATED_HELP_NOTICE - formatter.write_text(help_text) - elif self.deprecated: + text = self.help or "" + + if self.deprecated: + text = f"(Deprecated) {text}" + + if text: formatter.write_paragraph() + with formatter.indentation(): - formatter.write_text(DEPRECATED_HELP_NOTICE) + formatter.write_text(text) def format_options(self, ctx, formatter): """Writes all the options into the formatter if they exist.""" @@ -1275,7 +1269,15 @@ def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ - _maybe_show_deprecated_notice(self) + if self.deprecated: + echo( + style( + f"DeprecationWarning: The command {self.name!r} is deprecated.", + fg="red", + ), + err=True, + ) + if self.callback is not None: return ctx.invoke(self.callback, **ctx.params)
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -297,14 +297,14 @@ def cmd_with_help(): pass result = runner.invoke(cmd_with_help, ["--help"]) - assert "(DEPRECATED)" in result.output + assert "(Deprecated)" in result.output @click.command(deprecated=True) def cmd_without_help(): pass result = runner.invoke(cmd_without_help, ["--help"]) - assert "(DEPRECATED)" in result.output + assert "(Deprecated)" in result.output def test_deprecated_in_invocation(runner):
Deprecated notice in help text can be hard to see The current `(DEPRECATED)` deprecation notice added to help text can be hard to see plainly since it can't consider the existing format of the help text. For example: I use sphinx style formatting in my help text and if this help text ends with a Note block like below: ```python def encrypt(ctx, **kwargs): """Encrypt archives. .. Note:: Here is a notice. """ ``` Then a deprecation notice would append to the Note block, making it look like part of the Note and not that the command itself is deprecated. ```shell Usage: cmd encrypt [OPTIONS] Encrypt archives. .. Note:: Here is a notice. (DEPRECATED) ``` I would have expected the deprecation notice to be at the top of my help text making it clear to the user that this command is deprecated. Or at the least a couple a new lines added to differentiate the notice from any existing help text. Environment: - Python version: Python 3.7.9 - Click version: click==7.1.2
This is something you could change by sub-classing `Command` and overriding the `format_help_text` method [here.](https://github.com/pallets/click/blob/1b1578dbbc706538914221352edc84d532cdd3a4/src/click/core.py#L1220) @davidism I'm an MLH Fellow. I'm working on this Issue, notified here.
2021-03-17T19:17:44Z
[]
[]
pallets/click
1,822
pallets__click-1822
[ "1821" ]
d334d8220a96e6488deded07a7a41ad80dfa3dc5
diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -464,6 +464,8 @@ def style( bold=None, dim=None, underline=None, + overline=None, + italic=None, blink=None, reverse=None, strikethrough=None, @@ -518,6 +520,8 @@ def style( :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. + :param overline: if provided this will enable or disable overline. + :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the @@ -535,7 +539,8 @@ def style( Added support for 256 and RGB color codes. .. versionchanged:: 8.0 - Added the ``strikethrough`` parameter. + Added the ``strikethrough``, ``italic``, and ``overline`` + parameters. .. versionchanged:: 7.0 Added support for bright colors. @@ -565,6 +570,10 @@ def style( bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") + if overline is not None: + bits.append(f"\033[{53 if underline else 55}m") + if italic is not None: + bits.append(f"\033[{5 if underline else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None:
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -64,10 +64,15 @@ def test_echo_custom_file(): ({"bg": "white"}, "\x1b[47mx y\x1b[0m"), ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"), ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"), - ({"blink": True}, "\x1b[5mx y\x1b[0m"), - ({"underline": True}, "\x1b[4mx y\x1b[0m"), ({"bold": True}, "\x1b[1mx y\x1b[0m"), ({"dim": True}, "\x1b[2mx y\x1b[0m"), + ({"underline": True}, "\x1b[4mx y\x1b[0m"), + ({"overline": True}, "\x1b[55mx y\x1b[0m"), + ({"italic": True}, "\x1b[23mx y\x1b[0m"), + ({"blink": True}, "\x1b[5mx y\x1b[0m"), + ({"reverse": True}, "\x1b[7mx y\x1b[0m"), + ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"), + ({"fg": "black", "reset": False}, "\x1b[30mx y"), ], ) def test_styling(styles, ref):
Italic and overline aren't supported in `style` Most terminal programs are capable of presenting italic and overlined fonts. This is solvable with a relatively trivial change to termui.style
2021-03-23T22:10:55Z
[]
[]
pallets/click
1,829
pallets__click-1829
[ "303" ]
c0f9c06aa123e75466829bd41985a44a70b6c625
diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -8,6 +8,7 @@ import os import sys import time +from gettext import gettext as _ from ._compat import _default_text_stdout from ._compat import CYGWIN @@ -489,9 +490,13 @@ def edit_file(self, filename): c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True) exit_code = c.wait() if exit_code != 0: - raise ClickException(f"{editor}: Editing failed!") + raise ClickException( + _("{editor}: Editing failed").format(editor=editor) + ) except OSError as e: - raise ClickException(f"{editor}: Editing failed: {e}") + raise ClickException( + _("{editor}: Editing failed: {e}").format(editor=editor, e=e) + ) def edit(self, text): import tempfile diff --git a/src/click/_unicodefun.py b/src/click/_unicodefun.py --- a/src/click/_unicodefun.py +++ b/src/click/_unicodefun.py @@ -1,5 +1,6 @@ import codecs import os +from gettext import gettext as _ def _verify_python_env(): @@ -13,7 +14,15 @@ def _verify_python_env(): if fs_enc != "ascii": return - extra = "" + extra = [ + _( + "Click will abort further execution because Python was" + " configured to use ASCII as encoding for the environment." + " Consult https://click.palletsprojects.com/unicode-support/" + " for mitigation steps." + ) + ] + if os.name == "posix": import subprocess @@ -37,27 +46,32 @@ def _verify_python_env(): if locale.lower() in ("c.utf8", "c.utf-8"): has_c_utf8 = True - extra += "\n\n" if not good_locales: - extra += ( - "Additional information: on this system no suitable" - " UTF-8 locales were discovered. This most likely" - " requires resolving by reconfiguring the locale" - " system." + extra.append( + _( + "Additional information: on this system no suitable" + " UTF-8 locales were discovered. This most likely" + " requires resolving by reconfiguring the locale" + " system." + ) ) elif has_c_utf8: - extra += ( - "This system supports the C.UTF-8 locale which is" - " recommended. You might be able to resolve your issue" - " by exporting the following environment variables:\n\n" - " export LC_ALL=C.UTF-8\n" - " export LANG=C.UTF-8" + extra.append( + _( + "This system supports the C.UTF-8 locale which is" + " recommended. You might be able to resolve your" + " issue by exporting the following environment" + " variables:" + ) ) + extra.append(" export LC_ALL=C.UTF-8\n export LANG=C.UTF-8") else: - extra += ( - "This system lists some UTF-8 supporting locales that" - " you can pick from. The following suitable locales" - f" were discovered: {', '.join(sorted(good_locales))}" + extra.append( + _( + "This system lists some UTF-8 supporting locales" + " that you can pick from. The following suitable" + " locales were discovered: {locales}" + ).format(locales=", ".join(sorted(good_locales))) ) bad_locale = None @@ -67,16 +81,13 @@ def _verify_python_env(): if locale is not None: break if bad_locale is not None: - extra += ( - "\n\nClick discovered that you exported a UTF-8 locale" - " but the locale system could not pick up from it" - " because it does not exist. The exported locale is" - f" {bad_locale!r} but it is not supported" + extra.append( + _( + "Click discovered that you exported a UTF-8 locale" + " but the locale system could not pick up from it" + " because it does not exist. The exported locale is" + " {locale!r} but it is not supported." + ).format(locale=bad_locale) ) - raise RuntimeError( - "Click will abort further execution because Python was" - " configured to use ASCII as encoding for the environment." - " Consult https://click.palletsprojects.com/unicode-support/" - f" for mitigation steps.{extra}" - ) + raise RuntimeError("\n\n".join(extra)) diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -6,6 +6,8 @@ from contextlib import contextmanager from contextlib import ExitStack from functools import update_wrapper +from gettext import gettext as _ +from gettext import ngettext from itertools import repeat from ._unicodefun import _verify_python_env @@ -995,7 +997,7 @@ def main( except Abort: if not standalone_mode: raise - echo("Aborted!", file=sys.stderr) + echo(_("Aborted!"), file=sys.stderr) sys.exit(1) def _main_shell_completion(self, ctx_args, prog_name, complete_var=None): @@ -1170,7 +1172,7 @@ def show_help(ctx, param, value): is_eager=True, expose_value=False, callback=show_help, - help="Show this message and exit.", + help=_("Show this message and exit."), ) def make_parser(self, ctx): @@ -1199,7 +1201,7 @@ def get_short_help_str(self, limit=45): text = make_default_short_help(self.help, limit) if self.deprecated: - text = f"(Deprecated) {text}" + text = _("(Deprecated) {text}").format(text=text) return text.strip() @@ -1225,7 +1227,7 @@ def format_help_text(self, ctx, formatter): text = self.help or "" if self.deprecated: - text = f"(Deprecated) {text}" + text = _("(Deprecated) {text}").format(text=text) if text: formatter.write_paragraph() @@ -1242,7 +1244,7 @@ def format_options(self, ctx, formatter): opts.append(rv) if opts: - with formatter.section("Options"): + with formatter.section(_("Options")): formatter.write_dl(opts) def format_epilog(self, ctx, formatter): @@ -1265,9 +1267,11 @@ def parse_args(self, ctx, args): if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail( - "Got unexpected extra" - f" argument{'s' if len(args) != 1 else ''}" - f" ({' '.join(map(make_str, args))})" + ngettext( + "Got unexpected extra argument ({args})", + "Got unexpected extra arguments ({args})", + len(args), + ).format(args=" ".join(map(str, args))) ) ctx.args = args @@ -1280,7 +1284,9 @@ def invoke(self, ctx): if self.deprecated: echo( style( - f"DeprecationWarning: The command {self.name!r} is deprecated.", + _("DeprecationWarning: The command {name!r} is deprecated.").format( + name=self.name + ), fg="red", ), err=True, @@ -1474,7 +1480,7 @@ def format_commands(self, ctx, formatter): rows.append((subcommand, help)) if rows: - with formatter.section("Commands"): + with formatter.section(_("Commands")): formatter.write_dl(rows) def parse_args(self, ctx, args): @@ -1506,7 +1512,7 @@ def _process_result(value): with ctx: super().invoke(ctx) return _process_result([] if self.chain else None) - ctx.fail("Missing command.") + ctx.fail(_("Missing command.")) # Fetch args back out args = ctx.protected_args + ctx.args @@ -1580,7 +1586,7 @@ def resolve_command(self, ctx, args): if cmd is None and not ctx.resilient_parsing: if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) - ctx.fail(f"No such command '{original_cmd_name}'.") + ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) return cmd.name if cmd else None, cmd, args[1:] def get_command(self, ctx, cmd_name): @@ -2058,10 +2064,12 @@ def process_value(self, ctx, value): else len(value) != self.nargs ) ): - were = "was" if len(value) == 1 else "were" ctx.fail( - f"Argument {self.name!r} takes {self.nargs} values but" - f" {len(value)} {were} given." + ngettext( + "Argument {name!r} takes {nargs} values but 1 was given.", + "Argument {name!r} takes {nargs} values but {len} were given.", + len(value), + ).format(name=self.name, nargs=self.nargs, len=len(value)) ) if self.callback is not None: @@ -2421,7 +2429,7 @@ def _write_opts(opts): if isinstance(envvar, (list, tuple)) else envvar ) - extra.append(f"env var: {var_str}") + extra.append(_("env var: {var}").format(var=var_str)) default_value = self.get_default(ctx, call=False) show_default_is_str = isinstance(self.show_default, str) @@ -2434,7 +2442,7 @@ def _write_opts(opts): elif isinstance(default_value, (list, tuple)): default_string = ", ".join(str(d) for d in default_value) elif callable(default_value): - default_string = "(dynamic)" + default_string = _("(dynamic)") elif self.is_bool_flag and self.secondary_opts: # For boolean flags that have distinct True/False opts, # use the opt without prefix instead of the value. @@ -2444,7 +2452,7 @@ def _write_opts(opts): else: default_string = default_value - extra.append(f"default: {default_string}") + extra.append(_("default: {default}").format(default=default_string)) if isinstance(self.type, _NumberRangeBase): range_str = self.type._describe_range() @@ -2453,7 +2461,7 @@ def _write_opts(opts): extra.append(range_str) if self.required: - extra.append("required") + extra.append(_("required")) if extra: extra_str = ";".join(extra) help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -1,6 +1,7 @@ import inspect import typing as t from functools import update_wrapper +from gettext import gettext as _ from .core import Argument from .core import Command @@ -280,7 +281,7 @@ def version_option( *param_decls, package_name=None, prog_name=None, - message="%(prog)s, version %(version)s", + message=None, **kwargs, ): """Add a ``--version`` option which immediately prints the version @@ -304,7 +305,8 @@ def version_option( :param prog_name: The name of the CLI to show in the message. If not provided, it will be detected from the command. :param message: The message to show. The values ``%(prog)s``, - ``%(package)s``, and ``%(version)s`` are available. + ``%(package)s``, and ``%(version)s`` are available. Defaults to + ``"%(prog)s, version %(version)s"``. :param kwargs: Extra arguments are passed to :func:`option`. :raise RuntimeError: ``version`` could not be detected. @@ -315,6 +317,9 @@ def version_option( .. versionchanged:: 8.0 Use :mod:`importlib.metadata` instead of ``pkg_resources``. """ + if message is None: + message = _("%(prog)s, version %(version)s") + if version is None and package_name is None: frame = inspect.currentframe() f_globals = frame.f_back.f_globals if frame is not None else None @@ -381,7 +386,7 @@ def callback(ctx, param, value): kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) - kwargs.setdefault("help", "Show the version and exit.") + kwargs.setdefault("help", _("Show the version and exit.")) kwargs["callback"] = callback return option(*param_decls, **kwargs) @@ -412,6 +417,6 @@ def callback(ctx, param, value): kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) - kwargs.setdefault("help", "Show this message and exit.") + kwargs.setdefault("help", _("Show this message and exit.")) kwargs["callback"] = callback return option(*param_decls, **kwargs) diff --git a/src/click/exceptions.py b/src/click/exceptions.py --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -1,3 +1,6 @@ +from gettext import gettext as _ +from gettext import ngettext + from ._compat import filename_to_ui from ._compat import get_text_stderr from .utils import echo @@ -28,7 +31,7 @@ def __str__(self): def show(self, file=None): if file is None: file = get_text_stderr() - echo(f"Error: {self.format_message()}", file=file) + echo(_("Error: {message}").format(message=self.format_message()), file=file) class UsageError(ClickException): @@ -53,14 +56,18 @@ def show(self, file=None): color = None hint = "" if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None: - hint = ( - f"Try '{self.ctx.command_path}" - f" {self.ctx.help_option_names[0]}' for help.\n" + hint = _("Try '{command} {option}' for help.").format( + command=self.ctx.command_path, option=self.ctx.help_option_names[0] ) + hint = f"{hint}\n" if self.ctx is not None: color = self.ctx.color echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) - echo(f"Error: {self.format_message()}", file=file, color=color) + echo( + _("Error: {message}").format(message=self.format_message()), + file=file, + color=color, + ) class BadParameter(UsageError): @@ -92,10 +99,11 @@ def format_message(self): elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) else: - return f"Invalid value: {self.message}" - param_hint = _join_param_hints(param_hint) + return _("Invalid value: {message}").format(message=self.message) - return f"Invalid value for {param_hint}: {self.message}" + return _("Invalid value for {param_hint}: {message}").format( + param_hint=_join_param_hints(param_hint), message=self.message + ) class MissingParameter(BadParameter): @@ -123,7 +131,9 @@ def format_message(self): param_hint = self.param.get_error_hint(self.ctx) else: param_hint = None + param_hint = _join_param_hints(param_hint) + param_hint = f" {param_hint}" if param_hint else "" param_type = self.param_type if param_type is None and self.param is not None: @@ -134,17 +144,28 @@ def format_message(self): msg_extra = self.param.type.get_missing_message(self.param) if msg_extra: if msg: - msg += f". {msg_extra}" + msg += f". {msg_extra}" else: msg = msg_extra - hint_str = f" {param_hint}" if param_hint else "" - return f"Missing {param_type}{hint_str}.{' ' if msg else ''}{msg or ''}" + msg = f" {msg}" if msg else "" + + # Translate param_type for known types. + if param_type == "argument": + missing = _("Missing argument") + elif param_type == "option": + missing = _("Missing option") + elif param_type == "parameter": + missing = _("Missing parameter") + else: + missing = _("Missing {param_type}").format(param_type=param_type) + + return f"{missing}{param_hint}.{msg}" def __str__(self): if self.message is None: param_name = self.param.name if self.param else None - return f"missing parameter: {param_name}" + return _("Missing parameter: {param_name}").format(param_name=param_name) else: return self.message @@ -158,21 +179,23 @@ class NoSuchOption(UsageError): def __init__(self, option_name, message=None, possibilities=None, ctx=None): if message is None: - message = f"no such option: {option_name}" + message = _("No such option: {name}").format(name=option_name) super().__init__(message, ctx) self.option_name = option_name self.possibilities = possibilities def format_message(self): - bits = [self.message] - if self.possibilities: - if len(self.possibilities) == 1: - bits.append(f"Did you mean {self.possibilities[0]}?") - else: - possibilities = sorted(self.possibilities) - bits.append(f"(Possible options: {', '.join(possibilities)})") - return " ".join(bits) + if not self.possibilities: + return self.message + + possibility_str = ", ".join(sorted(self.possibilities)) + suggest = ngettext( + "Did you mean {possibility}?", + "(Possible options: {possibilities})", + len(self.possibilities), + ).format(possibility=possibility_str, possibilities=possibility_str) + return f"{self.message} {suggest}" class BadOptionUsage(UsageError): @@ -205,14 +228,16 @@ class FileError(ClickException): def __init__(self, filename, hint=None): ui_filename = filename_to_ui(filename) if hint is None: - hint = "unknown error" + hint = _("unknown error") super().__init__(hint) self.ui_filename = ui_filename self.filename = filename def format_message(self): - return f"Could not open file {self.ui_filename}: {self.message}" + return _("Could not open file {filename!r}: {message}").format( + filename=self.ui_filename, message=self.message + ) class Abort(RuntimeError): diff --git a/src/click/formatting.py b/src/click/formatting.py --- a/src/click/formatting.py +++ b/src/click/formatting.py @@ -1,5 +1,6 @@ import typing as t from contextlib import contextmanager +from gettext import gettext as _ from ._compat import term_len from .parser import split_opt @@ -129,13 +130,17 @@ def dedent(self): """Decreases the indentation.""" self.current_indent -= self.indent_increment - def write_usage(self, prog, args="", prefix="Usage: "): + def write_usage(self, prog, args="", prefix=None): """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. - :param prefix: the prefix for the first line. + :param prefix: The prefix for the first line. Defaults to + ``"Usage: "``. """ + if prefix is None: + prefix = f"{_('Usage:')} " + usage_prefix = f"{prefix:>{self.current_indent}}{prog} " text_width = self.width - self.current_indent diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -22,6 +22,8 @@ # Copyright 2001-2006 Gregory P. Ward # Copyright 2002-2006 Python Software Foundation from collections import deque +from gettext import gettext as _ +from gettext import ngettext from .exceptions import BadArgumentUsage from .exceptions import BadOptionUsage @@ -194,7 +196,9 @@ def process(self, value, state): value = None elif holes != 0: raise BadArgumentUsage( - f"argument {self.dest} takes {self.nargs} values" + _("Argument {name!r} takes {nargs} values.").format( + name=self.dest, nargs=self.nargs + ) ) if self.nargs == -1 and self.obj.envvar is not None: @@ -359,7 +363,9 @@ def _match_long_opt(self, opt, explicit_value, state): value = self._get_value_from_state(opt, option, state) elif explicit_value is not None: - raise BadOptionUsage(opt, f"{opt} option does not take a value") + raise BadOptionUsage( + opt, _("Option {name!r} does not take a value.").format(name=opt) + ) else: value = None @@ -414,9 +420,13 @@ def _get_value_from_state(self, option_name, option, state): # Option allows omitting the value. value = _flag_needs_value else: - n_str = "an argument" if nargs == 1 else f"{nargs} arguments" raise BadOptionUsage( - option_name, f"{option_name} option requires {n_str}." + option_name, + ngettext( + "Option {name!r} requires an argument.", + "Option {name!r} requires {nargs} arguments.", + nargs, + ).format(name=option_name, nargs=nargs), ) elif nargs == 1: next_rarg = state.rargs[0] diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -1,6 +1,7 @@ import os import re import typing as t +from gettext import gettext as _ from .core import Argument from .core import MultiCommand @@ -289,12 +290,14 @@ def _check_version(self): if major < "4" or major == "4" and minor < "4": raise RuntimeError( - "Shell completion is not supported for Bash" - " versions older than 4.4." + _( + "Shell completion is not supported for Bash" + " versions older than 4.4." + ) ) else: raise RuntimeError( - "Couldn't detect Bash version, shell completion is not supported." + _("Couldn't detect Bash version, shell completion is not supported.") ) def source(self): diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -4,6 +4,7 @@ import os import sys import typing as t +from gettext import gettext as _ from ._compat import is_bytes from ._compat import isatty @@ -145,7 +146,7 @@ def prompt_func(text): if confirmation_prompt: if confirmation_prompt is True: - confirmation_prompt = "Repeat for confirmation" + confirmation_prompt = _("Repeat for confirmation") confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) @@ -161,9 +162,9 @@ def prompt_func(text): result = value_proc(value) except UsageError as e: if hide_input: - echo("Error: the value you entered was invalid", err=err) + echo(_("Error: The value you entered was invalid."), err=err) else: - echo(f"Error: {e.message}", err=err) # noqa: B306 + echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306 continue if not confirmation_prompt: return result @@ -173,7 +174,7 @@ def prompt_func(text): break if value == value2: return result - echo("Error: the two entered values do not match", err=err) + echo(_("Error: The two entered values do not match."), err=err) def confirm( @@ -222,7 +223,7 @@ def confirm( elif default is not None and value == "": rv = default else: - echo("Error: invalid input", err=err) + echo(_("Error: invalid input"), err=err) continue break if abort and not rv: @@ -731,7 +732,7 @@ def raw_terminal(): return f() -def pause(info="Press any key to continue ...", err=False): +def pause(info=None, err=False): """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command @@ -742,12 +743,17 @@ def pause(info="Press any key to continue ...", err=False): .. versionadded:: 4.0 Added the `err` parameter. - :param info: the info string to print before pausing. + :param info: The message to print before pausing. Defaults to + ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return + + if info is None: + info = _("Press any key to continue...") + try: if info: echo(info, nl=False, err=err) diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -2,6 +2,8 @@ import stat import typing as t from datetime import datetime +from gettext import gettext as _ +from gettext import ngettext from ._compat import _get_argv_encoding from ._compat import filename_to_ui @@ -228,8 +230,7 @@ def get_metavar(self, param): return f"[{choices_str}]" def get_missing_message(self, param): - choice_str = ",\n\t".join(self.choices) - return f"Choose from:\n\t{choice_str}" + return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices)) def convert(self, value, param, ctx): # Match through normalization and case sensitivity @@ -256,9 +257,16 @@ def convert(self, value, param, ctx): if normed_value in normed_choices: return normed_choices[normed_value] - one_of = "one of " if len(self.choices) > 1 else "" - choices_str = ", ".join(repr(c) for c in self.choices) - self.fail(f"{value!r} is not {one_of}{choices_str}.", param, ctx) + choices_str = ", ".join(map(repr, self.choices)) + self.fail( + ngettext( + "{value!r} is not {choice}.", + "{value!r} is not one of {choices}.", + len(self.choices), + ).format(value=value, choice=choices_str, choices=choices_str), + param, + ctx, + ) def __repr__(self): return f"Choice({list(self.choices)})" @@ -335,10 +343,15 @@ def convert(self, value, param, ctx): if converted is not None: return converted - plural = "s" if len(self.formats) > 1 else "" - formats_str = ", ".join(repr(f) for f in self.formats) + formats_str = ", ".join(map(repr, self.formats)) self.fail( - f"{value!r} does not match the format{plural} {formats_str}.", param, ctx + ngettext( + "{value!r} does not match the format {format}.", + "{value!r} does not match the formats {formats}.", + len(self.formats), + ).format(value=value, format=formats_str, formats=formats_str), + param, + ctx, ) def __repr__(self): @@ -352,7 +365,13 @@ def convert(self, value, param, ctx): try: return self._number_class(value) except ValueError: - self.fail(f"{value!r} is not a valid {self.name}.", param, ctx) + self.fail( + _("{value!r} is not a valid {number_type}.").format( + value=value, number_type=self.name + ), + param, + ctx, + ) class _NumberRangeBase(_NumberParamTypeBase): @@ -393,7 +412,13 @@ def convert(self, value, param, ctx): return self._clamp(self.max, -1, self.max_open) if lt_min or gt_max: - self.fail(f"{rv} is not in the range {self._describe_range()}.", param, ctx) + self.fail( + _("{value} is not in the range {range}.").format( + value=rv, range=self._describe_range() + ), + param, + ctx, + ) return rv @@ -517,7 +542,9 @@ def convert(self, value, param, ctx): if norm in {"0", "false", "f", "no", "n", "off"}: return False - self.fail(f"{value!r} is not a valid boolean.", param, ctx) + self.fail( + _("{value!r} is not a valid boolean.").format(value=value), param, ctx + ) def __repr__(self): return "BOOL" @@ -537,7 +564,9 @@ def convert(self, value, param, ctx): try: return uuid.UUID(value) except ValueError: - self.fail(f"{value!r} is not a valid UUID.", param, ctx) + self.fail( + _("{value!r} is not a valid UUID.").format(value=value), param, ctx + ) def __repr__(self): return "UUID" @@ -698,11 +727,11 @@ def __init__( self.type = path_type if self.file_okay and not self.dir_okay: - self.name = "file" + self.name = _("file") elif self.dir_okay and not self.file_okay: - self.name = "directory" + self.name = _("directory") else: - self.name = "path" + self.name = _("path") def to_info_dict(self): info_dict = super().to_info_dict() @@ -746,32 +775,42 @@ def convert(self, value, param, ctx): if not self.exists: return self.coerce_path_result(rv) self.fail( - f"{self.name.title()} {filename_to_ui(value)!r} does not exist.", + _("{name} {filename!r} does not exist.").format( + name=self.name.title(), filename=filename_to_ui(value) + ), param, ctx, ) if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( - f"{self.name.title()} {filename_to_ui(value)!r} is a file.", + _("{name} {filename!r} is a file.").format( + name=self.name.title(), filename=filename_to_ui(value) + ), param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( - f"{self.name.title()} {filename_to_ui(value)!r} is a directory.", + _("{name} {filename!r} is a directory.").format( + name=self.name.title(), filename=filename_to_ui(value) + ), param, ctx, ) if self.writable and not os.access(value, os.W_OK): self.fail( - f"{self.name.title()} {filename_to_ui(value)!r} is not writable.", + _("{name} {filename!r} is not writable.").format( + name=self.name.title(), filename=filename_to_ui(value) + ), param, ctx, ) if self.readable and not os.access(value, os.R_OK): self.fail( - f"{self.name.title()} {filename_to_ui(value)!r} is not readable.", + _("{name} {filename!r} is not readable.").format( + name=self.name.title(), filename=filename_to_ui(value) + ), param, ctx, )
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -230,7 +230,7 @@ def test_missing_argument_string_cast(): with pytest.raises(click.MissingParameter) as excinfo: click.Argument(["a"], required=True).process_value(ctx, None) - assert str(excinfo.value) == "missing parameter: a" + assert str(excinfo.value) == "Missing parameter: a" def test_implicit_non_required(runner): @@ -301,7 +301,7 @@ def cmd(a): result = runner.invoke(cmd, ["3"]) assert result.exception is not None - assert "argument a takes 2 values" in result.output + assert "Argument 'a' takes 2 values." in result.output def test_multiple_param_decls_not_allowed(runner): diff --git a/tests/test_basic.py b/tests/test_basic.py --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -120,7 +120,7 @@ def cli(foo): result = runner.invoke(cli, ["--foo"]) assert result.exception - assert "--foo option requires an argument" in result.output + assert "Option '--foo' requires an argument." in result.output result = runner.invoke(cli, ["--foo="]) assert not result.exception diff --git a/tests/test_imports.py b/tests/test_imports.py --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -47,6 +47,7 @@ def tracking_import(module, locals=None, globals=None, fromlist=None, "enum", "typing", "types", + "gettext", } if WIN: diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -83,7 +83,7 @@ def cli(): result = runner.invoke(cli, [unknown_flag]) assert result.exception - assert f"no such option: {unknown_flag}" in result.output + assert f"No such option: {unknown_flag}" in result.output @pytest.mark.parametrize( @@ -441,7 +441,7 @@ def test_missing_option_string_cast(): with pytest.raises(click.MissingParameter) as excinfo: click.Option(["-a"], required=True).process_value(ctx, None) - assert str(excinfo.value) == "missing parameter: a" + assert str(excinfo.value) == "Missing parameter: a" def test_missing_choice(runner): diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -376,7 +376,7 @@ def test_fast_edit(runner): ("prompt_required", "required", "args", "expect"), [ (True, False, None, "prompt"), - (True, False, ["-v"], "-v option requires an argument"), + (True, False, ["-v"], "Option '-v' requires an argument."), (False, True, None, "prompt"), (False, True, ["-v"], "prompt"), ],
Provide i18n with gettext It would be useful to wrap every public message with gettext function to allow i18n for application.
+ 1 +1 For those interrested, I've made a gist showing how to catch click exceptions and translate them. It's **quick and dirty** (use regexps), but right now it does the job: https://gist.github.com/lapause/ed148b2b1481f83f39c5 To core developers: if you don't want to implement i18n, you could create one exception class by error type (±3 inheriting from UsageError, ±14 from BadParameter) and use attributes to store dynamic elements (parameter and file names/types.... By doing so it would allow developers to just trap exceptions of interrest to them and re-raise them with customized messages without having to mess with regexps depending of the exact messages used by the library. To core developers (2): I'm pretty sure my monkey patching of the click.Command.main is not the best way to go, but http://click.pocoo.org/4/exceptions/ could really benefit from a real life example of how to invoke directly a command declared with multiple arguments, decorators... 1. Agreed, I'd like to see this too. However, I suppose this would also require a much more fine-grained exception hierarchy, one class for each error message. Right now some parts of click raise such generic ones as `RuntimeError`. 2. I think you're supposed to subclass `Command` so you can override `main` properly, and then pass the subclass like `@click.command(cls=TranslatingCommand)`. +1 I'm playing around with click in Mailman 3 to replace our homegrown cli parsing code. All of our help text is marked with `_()` and we use [flufl.i18n](http://flufli18n.readthedocs.io/en/latest/) to do the actual run time translations. I may have more opinions as I get farther along, but for now I don't see any real problem with option help text. E.g. this works fine: ```python @click.option( '-v', '--verbose', is_flag=True, default=False, help=_('Display more debugging information to the log file.')) ``` It gets tricky in one place: use of the function's docstring for the help prologue. Python only assigns unadorned strings to `__doc__`. So there's no good way to mark the help prologue for translation, extraction and also use it in click. Of course, I might be missing a lot as I've just started digging in. ;) Should this be implemented in click itself or as part of click-contrib? Also, `command()` and `group()` have `help` parameters so you could do ```python @click.command(cls=TranslatingCommand, help=_('translatable string')) def func(): # No docstring here. pass ``` This issue appears to be asking for i18n on Click's internal messages, such as exception strings. There should be nothing preventing use of i18n on your own strings. What I meant was should this be built into click or should there be a separate library? What you're showing isn't related to what's being asked for. Nothing has to change for what you're showing. Internal message have to be wrapped for what's being asked for. I'm asking if translating the strings should be built in. So I think what needs to be done is to wrap messages that the user might see with `_` (`gettext`) and leave it at that for now. I'd like to work on this.
2021-04-01T13:12:10Z
[]
[]
pallets/click
1,830
pallets__click-1830
[ "1096" ]
08583da150d9df25f1566c7390ebf7fa4a2a9395
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -30,6 +30,7 @@ from .types import convert_type from .types import IntRange from .utils import _detect_program_name +from .utils import _expand_args from .utils import echo from .utils import make_default_short_help from .utils import make_str @@ -903,9 +904,6 @@ def main( This method is also available by directly calling the instance of a :class:`Command`. - .. versionadded:: 3.0 - Added the `standalone_mode` flag to control the standalone mode. - :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default @@ -926,6 +924,13 @@ def main( of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. + + .. versionchanged:: 8.0 + When taking arguments from ``sys.argv`` on Windows, glob + patterns, user dir, and env vars are expanded. + + .. versionchanged:: 3.0 + Added the ``standalone_mode`` parameter. """ # Verify that the environment is configured correctly, or reject # further execution to avoid a broken script. @@ -933,6 +938,9 @@ def main( if args is None: args = sys.argv[1:] + + if os.name == "nt": + args = _expand_args(args) else: args = list(args) diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -1,5 +1,6 @@ import os import sys +import typing as t from ._compat import _default_text_stderr from ._compat import _default_text_stdout @@ -482,3 +483,48 @@ def _detect_program_name(path=None, _main=sys.modules["__main__"]): py_module = f"{py_module}.{name}" return f"python -m {py_module.lstrip('.')}" + + +def _expand_args( + args: t.Iterable[str], + *, + user: bool = True, + env: bool = True, + glob_recursive: bool = True, +) -> t.List[str]: + """Simulate Unix shell expansion with Python functions. + + See :func:`glob.glob`, :func:`os.path.expanduser`, and + :func:`os.path.expandvars`. + + This intended for use on Windows, where the shell does not do any + expansion. It may not exactly match what a Unix shell would do. + + :param args: List of command line arguments to expand. + :param user: Expand user home directory. + :param env: Expand environment variables. + :param glob_recursive: ``**`` matches directories recursively. + + .. versionadded:: 8.0 + + :meta private: + """ + from glob import glob + + out = [] + + for arg in args: + if user: + arg = os.path.expanduser(arg) + + if env: + arg = os.path.expandvars(arg) + + matches = glob(arg, recursive=glob_recursive) + + if not matches: + out.append(arg) + else: + out.extend(matches) + + return out
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -429,3 +429,13 @@ def __init__(self, package_name): ) def test_detect_program_name(path, main, expected): assert click.utils._detect_program_name(path, _main=main) == expected + + +def test_expand_args(monkeypatch): + user = os.path.expanduser("~") + assert user in click.utils._expand_args(["~"]) + monkeypatch.setenv("CLICK_TEST", "hello") + assert "hello" in click.utils._expand_args(["$CLICK_TEST"]) + assert "setup.cfg" in click.utils._expand_args(["*.cfg"]) + assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"]) + assert "*.not-found" in click.utils._expand_args(["*.not-found"])
Expand globs in arguments on Windows? I'm using a variadic `Path` argument: ```python @click.command() @click.argument( "paths", nargs=-1, type=click.Path(exists=True, dir_okay=False) ) def whatever(paths) ... ``` When I run `myprogram.py *.txt`, then on unix of course it works, because the shell expands on the glob. But on Windows, glob expansion is the responsibility of the program being invoked, and click doesn't appear to do it – even in a case like this where it has all the information needed to tell that glob expansion is appropriate. And click kind of has to do it, because click wants to validate the paths, and this has to happen *after* glob expansion – if I pass `*.txt`, it says `Error: Invalid value for "paths": Path "*.txt" does not exist.`, and my code doesn't even get invoked, so I can't even fix up the globs myself, except by disabling all of click's validation and then doing it all myself.
* Should it be Click's (built-in) job to make up for cmd not having globs? * How can we safely tell that a name is a glob? There are other patterns besides `*`. * What if the name comes from Bash and `*.txt` was actually the name of the file after expansion? * Do we also want to expand `~`? * If we add glob expansion to parameters, do we also need to do it for env vars on Unix too? For example, if a parameter has an env var `NAME="*.txt"`, no expansion is done, Click currently expects you to handle that. My first reaction is that this shouldn't be done by Click, although it should be possible to subclass `Argument.process_value()` or `Path` to work with globs. > What if the name comes from Bash and *.txt was actually the name of the file after expansion? IMHO such behavior would have to be completely disabled on non-Windows systems. Maybe the least strange/error-prone solution would be to have a `windows_expand_globs` argument that can be set to True if you want glob expansion on Windows. > Should it be Click's (built-in) job to make up for cmd not having globs? The Windows convention that it is every program's job to make up for cmd not having globs, yes. "Annoying thing that every cli app has to do" seems like it falls within click's scope. > How can we safely tell that a name is a glob? There are other patterns besides *. I believe in traditional Windows globbing the metacharacters are `*`, `?` only. The python `glob` module also does `[]`. You probably can't exactly match what, like, MSVC would do, but that's ok, it's Windows, it's not your fault and no one expects everything to work consistently. > What if the name comes from Bash and *.txt was actually the name of the file after expansion? As @thiefmaster notes, you'd only enable enable this on Windows. But what if someone is using mingw bash on Windows? Well, then you might double-expand, just like every other traditional Windows cli program would in the same situation. > Do we also want to expand `~`? That would be an interesting option for `File` and `Path` arguments yeah, though it's more of a Unix thing so the history is a bit different. I can see a good argument for doing `expanduser` by default on `File` and `Path` arguments, with a switch available to turn it off. > If we add glob expansion to parameters, do we also need to do it for env vars on Unix too? For example, if a parameter has an env var NAME="*.txt", no expansion is done, Click currently expects you to handle that. I'm not really familiar with how click uses envvars. As a Unix user I would expect `NAME=~/foo.txt` to work, and be surprised if `NAME=*.txt` worked. I don't know what people would expect for envvar handling on Windows. > "Annoying thing that every cli app has to do" seems like it falls within click's scope. Agree. > I believe in traditional Windows globbing the metacharacters are *, ? only. It would be less efficient, but the easiest way would be to always pass values through expanduser and glob first. Is there a way to signal that something glob-like *isn't* a glob, like single quotes on Unix? One last thing I thought of. What happens when using `invoke` (for testing or for dispatching other commands) now? On Windows, `invoke(args=["subcommand", "*.txt"])` would expand, but on Unix it wouldn't, which I can see causing inconsistent behavior. > Is there a way to signal that something glob-like isn't a glob, like single quotes on Unix? I'm not sure. In Windows, quote handling is also done in process (basically you just get a raw command line string and are free to do whatever with it), so in principle you could use quotes to disable globbing for specific arguments. But in Python, the quote handling happens early in interpreter startup, so you can't see them in `sys.argv`. I guess if you're really masochistic you could call [`GetCommandLine`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156(v=vs.85).aspx) and try to reparse it, but i can't imagine this working well given all the ways you python can be invoked (e.g. `python -m mycli`), plus it'd be a ton of fiddly work for unclear benefit. Python's glob module lets you use `[]` for quoting. (E.g., the pattern `[*].txt` matches the literal filename `*.txt`.) Not very intuitive, but it is possible, and I guess Windows users are used to weird edge cases when trying to use the cli to refer to files with `*` in the name? > One last thing I thought of. What happens when using invoke (for testing or for dispatching other commands) now? On Windows, `invoke(args=["subcommand", "*.txt"])` would expand, but on Unix it wouldn't, which I can see causing inconsistent behavior. I don't know enough about click and `invoke` to say anything useful here. (I've spent about an hour with click so far :-).) Tough I guess you could make the argument that the behavior *is* inconsistent on the two platforms, intentionally so, and your tests should reflect that? Hello, I came here from the Black project, because running `black *.py` doesn't work on Windows Command Prompt or PowerShell and I've traced the problem to how Click handles wildcards. Click not handling this results in wildcards simply not working on Windows for **every** program that uses Click, which seems like a large hole. > How can we safely tell that a name is a glob? There are other patterns besides *. I think leaning on Python's `glob` module is suitable enough for handling * and ? (njsmith is correct that [] isn't used on Windows, but we'd get it for free with `glob`.) And anyways, let's not let perfect be the enemy of good; even just getting some features working would be good. I just want `black *.py` to work on Windows. > What if the name comes from Bash and *.txt was actually the name of the file after expansion? To reiterate njsmith, this would have to be a Windows-only feature. The * and ? characters are illegal to have in files on Windows anyway (I assume this is an NTFS thing.) > Do we also want to expand `~`? Nah. This isn't a Windows command line idiom. It'd be easier to leave it unimplemented, given that `glob` also doesn't implement it. Anyway, my comments mostly reiterate what njsmith said. I'd just like to shed more light on this issue because "wildcards don't work on Windows" seems like a pretty big deal for every program that uses Click. > What happens when using `invoke` (for testing or for dispatching other commands) now? On Windows, `invoke(args=["subcommand", "*.txt"])` would expand, but on Unix it wouldn't, which I can see causing inconsistent behavior. Thinking about this again, processing should only happen in `BaseCommand.main`, so `Context.invoke` isn't affected. `invoke` is already expected to be passed Python values, not unparsed command line values. So the solution for this is to add a call to `glob` in `BaseCommand.main` only on Windows. I'll like to pick this up Note that `*.txt` will only expand if there actually are any `.txt` files, otherwise Unix shells pass on the literal `*.txt` and you get the same error as in the op. Not going to do anything about this, since it's standard shell behavior, but it can be unexpected so I wanted to mention it. `glob.glob` returns an empty list if nothing matches, so I'll replace that with the original pattern in that case to match this behavior. I think we should also call `os.path.expanduser` and `os.path.expandvars` on each argument. If we're expanding globs for better consistency between Windows and Unix, it makes sense to do the other expansions that Unix shells do and Python provides. I'll also enable `recursive=True` for `glob` so that `**` is expanded.
2021-04-01T18:16:46Z
[]
[]
pallets/click
1,832
pallets__click-1832
[ "1831" ]
9330dbad806a1a76e0c514333cf32fce58e72e86
diff --git a/src/click/formatting.py b/src/click/formatting.py --- a/src/click/formatting.py +++ b/src/click/formatting.py @@ -225,10 +225,6 @@ def write_dl(self, rows, col_max=30, col_spacing=2): for line in lines[1:]: self.write(f"{'':>{first_col + self.current_indent}}{line}\n") - - if len(lines) > 1: - # separate long help from next option - self.write("\n") else: self.write("\n")
diff --git a/tests/test_formatting.py b/tests/test_formatting.py --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -331,42 +331,6 @@ def cli(): ] -def test_formatting_usage_multiline_option_padding(runner): - @click.command("foo") - @click.option("--bar", help="This help message will be padded if it wraps.") - def cli(): - pass - - result = runner.invoke(cli, "--help", terminal_width=45) - assert not result.exception - assert result.output.splitlines() == [ - "Usage: foo [OPTIONS]", - "", - "Options:", - " --bar TEXT This help message will be", - " padded if it wraps.", - "", - " --help Show this message and exit.", - ] - - -def test_formatting_usage_no_option_padding(runner): - @click.command("foo") - @click.option("--bar", help="This help message will be padded if it wraps.") - def cli(): - pass - - result = runner.invoke(cli, "--help", terminal_width=80) - assert not result.exception - assert result.output.splitlines() == [ - "Usage: foo [OPTIONS]", - "", - "Options:", - " --bar TEXT This help message will be padded if it wraps.", - " --help Show this message and exit.", - ] - - def test_formatting_with_options_metavar_empty(runner): cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])]) result = runner.invoke(cli, ["--help"])
Reconsider the choice of adding a newline after multi-line option definitions First, thanks for your work. I ask you to reconsider the feature introduced with PR https://github.com/pallets/click/pull/1081. 1. Adding a newline only to some options feels inconsistent and leads to a weird-looking "non-uniform" help strings. It's even worse when you use an extension that adds new help sections (e.g. [Cloup](https://github.com/janluke/cloup) for option groups), since some sections are not clearly demarked or too much demarked. It looks like a complete mess. 2. I'm pretty sure it's non-standard. Why should it be the default? As a consequence, it feels like a bug. I did mistake it for a bug. Another developer reported it as a bug (issue https://github.com/pallets/click/issues/1559). The few people I asked don't like it and consider it a problem worth the effort of writing additional code to get rid of it. Most people in the original issue (https://github.com/pallets/click/issues/1075) are for an all-or-nothing behavior and described the current behviour as inconsistent as well. Here's some alternative proposals. 1. Remove the feature. 2. Make it possible but non-default. Two solutions here: 1. Add a parameter to `HelpFormatter`. It can be made as simple as a boolean or as complex as a "list item separation strategy". A user can pass a custom factory function as `Context.formatter_class` (which probably could be called `formatter_factory`). 2. Refactor `HelpFormatter` to make it easy for people to override without copying, pasting and modiyfing the current code of `HelpFormatter.write_dl`. Thank you again.
> Refactor HelpFormatter to make it easy for people to override without copying, pasting and modiyfing the current code of HelpFormatter.write_dl. Yes, as stated in https://github.com/pallets/click/issues/1075#issuecomment-644964531, making the formatting overridable is what I want. That said, I'm not sure why I accepted it so quickly in the first place, but that was 3 years ago. Feel free to revert it.
2021-04-02T15:49:42Z
[]
[]
pallets/click
1,836
pallets__click-1836
[ "665" ]
b625b9f39082f366dd85ad13024e43c8f5e78b87
diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -127,8 +127,10 @@ def prompt_func(text): try: # Write the prompt separately so that we get nice # coloring through colorama on Windows - echo(text, nl=False, err=err) - return f("") + echo(text.rstrip(" "), nl=False, err=err) + # Echo a space to stdout to work around an issue where + # readline causes backspace to clear the whole line. + return f(" ") except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3).
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -154,10 +154,10 @@ def f(_): try: click.prompt("Password", hide_input=True) except click.Abort: - click.echo("Screw you.") + click.echo("interrupted") out, err = capsys.readouterr() - assert out == "Password: \nScrew you.\n" + assert out == "Password:\ninterrupted\n" def _test_gen_func(): @@ -255,8 +255,8 @@ def emulate_input(text): emulate_input("asdlkj\n") click.prompt("Prompt to stderr", err=True) out, err = capfd.readouterr() - assert out == "" - assert err == "Prompt to stderr: " + assert out == " " + assert err == "Prompt to stderr:" emulate_input("y\n") click.confirm("Prompt to stdin")
Click prompts do not cooperate with readline module When readline is imported and a user presses backspace during a Click prompt, the entire prompt message is erased and cursor goes to beginning of the line. This can be reproduced with the following code: ``` import click, readline click.prompt("Input") ``` This is due to [Python issue 12833](https://bugs.python.org/issue12833). The official recommendation is that the prompt should be displayed with raw_input. I noticed that Click first displays the prompt message using echo() and then uses raw_input("") for the prompt. There is also a workaround by passing " " to raw_input, however, that may be ugly in the display.
Any feedback about this particular issue? The click-shell package relies on readline, so this issue causes problems when using that. What I've done to patch this is: - edit `click/termui.py` and go to the `f("")` line. - Replace `f("")` with `f(" ")` (notice the space) - In the line above, add an `rstrip(" ")` to remove ugly display: `echo(text.rstrip(" "), nl=False, err=err)` How about echoing the prompt as usual, but displaying the prefix in the input-method (like `f(prefix)`) ?
2021-04-06T15:38:06Z
[]
[]
pallets/click
1,840
pallets__click-1840
[ "1568" ]
6c7624491911f0b18f869e5d0a989506e7b416f8
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -678,6 +678,10 @@ def invoke(*args, **kwargs): # noqa: B902 in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. + + .. versionchanged:: 8.0 + All ``kwargs`` are tracked in :attr:`params` so they will be + passed if :meth:`forward` is called at multiple levels. """ self, callback = args[:2] ctx = self @@ -700,6 +704,10 @@ def invoke(*args, **kwargs): # noqa: B902 if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) + # Track all kwargs as params, so that forward() will pass + # them on in subsequent calls. + ctx.params.update(kwargs) + args = args[2:] with augment_usage_errors(self): with ctx: @@ -709,6 +717,10 @@ def forward(*args, **kwargs): # noqa: B902 """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. + + .. versionchanged:: 8.0 + All ``kwargs`` are tracked in :attr:`params` so they will be + passed if ``forward`` is called at multiple levels. """ self, cmd = args[:2]
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -39,6 +39,28 @@ def dist(ctx, count): assert result.output == "Count: 1\nCount: 42\n" +def test_forwarded_params_consistency(runner): + cli = click.Group() + + @cli.command() + @click.option("-a") + @click.pass_context + def first(ctx, **kwargs): + click.echo(f"{ctx.params}") + + @cli.command() + @click.option("-a") + @click.option("-b") + @click.pass_context + def second(ctx, **kwargs): + click.echo(f"{ctx.params}") + ctx.forward(first) + + result = runner.invoke(cli, ["second", "-a", "foo", "-b", "bar"]) + assert not result.exception + assert result.output == "{'a': 'foo', 'b': 'bar'}\n{'a': 'foo', 'b': 'bar'}\n" + + def test_auto_shorthelp(runner): @click.group() def cli():
context.forward inconsistently removes undeclared options ### Expected Behavior Three commands. The first takes a subset of the options that the last two take. Each prints the arguments they were called with. All but the first call the one before it via `context.forward`. ```python import click from pprint import pprint @click.group() def main(): pass @main.command() @click.option('-a') def first(**kwargs): print('first') pprint(kwargs) @main.command() @click.option('-a') @click.option('-b') @click.pass_context def second(context, **kwargs): print('second') pprint(kwargs) context.forward(first) @main.command() @click.option('-a') @click.option('-b') @click.pass_context def third(context, **kwargs): print('third') pprint(kwargs) context.forward(second) main() ``` Here's the behavior I expect from each command. Notably, `first` is called with the same arguments, its declared options, each time. ``` $ python main.py first first {'a': None} $ python main.py second second {'a': None, 'b': None} first {'a': None} $ python main.py third third {'a': None, 'b': None} second {'a': None, 'b': None} first {'a': None} ``` ### Actual Behavior ``` $ python main.py first first {'a': None} $ python main.py second second {'a': None, 'b': None} first {'a': None, 'b': None} # 'first' is called with 'b' here $ python main.py third third {'a': None, 'b': None} second {'a': None, 'b': None} first {'a': None} # but not here ``` ### Environment * Python version: 3.7.5 * Click version: 7.1.2
@thejohnfreeman I am looking into this. Doing preliminary investigations on why this is happening. `Context.forward` uses `Context.params` to fill in the options and passes the `kwargs` to `Context.invoke` which creates a new `Context` for the sub command but doesn't pass the params to the new `Context` nor does it remove unused `kwargs`. I'm not sure it should remove unused `kwargs`. Below I've expanded your example to show the current behavior and a patch that would provide the behavior you are expecting: <details> ```python import click @click.group() def main(): pass @main.command() @click.option('-a') @click.pass_context def first(context, **kwargs): pp_kwargs('first', kwargs, context) @main.command() @click.option('-a') @click.option('-b') @click.pass_context def second(context, **kwargs): pp_kwargs('second', kwargs, context) context.forward(first) @main.command() @click.option('-a') @click.option('-b') @click.pass_context def third(context, **kwargs): pp_kwargs('third', kwargs, context) context.forward(second) def pp_kwargs(f, kw, c): click.echo(f'\nin {f} callback: {kw}') click.echo(f'have context for {c.command}') click.echo(f'Context.params:{c.params}') ``` Current behavior: ``` % forward third -a foo -b bar in third callback: {'a': 'foo', 'b': 'bar'} have context for <Command third> Context.params:{'a': 'foo', 'b': 'bar'} in second callback: {'a': 'foo', 'b': 'bar'} have context for <Command second> Context.params:{} in first callback: {'a': None} have context for <Command first> Context.params:{} ``` A possible patch: ```diff diff --git a/src/click/core.py b/src/click/core.py index 3bbc120..2accfbe 100644 --- a/src/click/core.py +++ b/src/click/core.py @@ -694,10 +694,19 @@ class Context: ctx = self._make_sub_context(other_cmd) + names = [p.name for p in other_cmd.params] + clean_kwargs = {} + for k, v in kwargs.items(): + if k in names: + clean_kwargs[k] = v + kwargs = clean_kwargs + for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) + ctx.params.update(kwargs) + args = args[2:] with augment_usage_errors(self): with ctx: ``` New output: ``` % forward third -a foo -b bar in third callback: {'a': 'foo', 'b': 'bar'} have context for <Command third> Context.params:{'a': 'foo', 'b': 'bar'} in second callback: {'a': 'foo', 'b': 'bar'} have context for <Command second> Context.params:{'a': 'foo', 'b': 'bar'} in first callback: {'a': 'foo'} have context for <Command first> Context.params:{'a': 'foo'} ``` </details> I've got a similar bug again. Might just be another instance of the same bug. It's been awhile since I revisited this code, stuck as I was on this bug with no workaround last time. Three commands: `project`, `configure`, `build`. Each calls the one "before" it via `context.forward`. Thus, each takes the options that the first one takes. This time, that option is a ["feature switch"](https://click.palletsprojects.com/en/7.x/options/#feature-switches) in the Click documentation parlance: three options targeting the same parameter, but each option sets a different value for that parameter. Each command just prints the value for that parameter after forwarding. <details> ```python import click from toolz.functoolz import compose flavor_option = compose( click.option( '--debug', 'flavor', flag_value='debug', help='Shorthand for --flavor debug.', ), click.option( '--release', 'flavor', flag_value='release', help='Shorthand for --flavor release.', ), # This must be composed last # because `flag_value` sets the default to `False`. click.option( '--flavor', 'flavor', default='debug', help='The configuration flavor.', ), ) @click.group() def main(): pass @main.command() @flavor_option def project(flavor): print(flavor, 'project') @main.command() @flavor_option @click.pass_context def configure(context, flavor): context.forward(project) print(flavor, 'configure') @main.command() @flavor_option @click.pass_context def build(context, flavor): context.forward(configure) print(flavor, 'build') if __name__ == '__main__': main() ``` ```shell $ poetry run python test.py project debug project $ poetry run python test.py configure debug project debug configure $ poetry run python test.py build False project # I was expecting 'debug' here debug configure debug build ``` </details> Its another instance of the same bug. You might try to work around it by moving the options up to the group and handle the shared logic outside the callback functions: <details> ```python import inspect import attr import click @click.group() @click.option('--debug', 'flavor', flag_value='debug', help='Shorthand for --flavor debug') @click.option('--release', 'flavor', flag_value='release', help='Shorthand for --flavor release') @click.option('--flavor', 'flavor', default='debug', help='The configuration flavor') @click.pass_context def main(context, flavor): context.obj = Handler(flavor=flavor) @main.command() @click.pass_obj def project(obj): click.echo(obj.project()) @main.command() @click.pass_obj def configure(obj): click.echo(obj.configure()) @main.command() @click.pass_obj def build(obj): click.echo(obj.build()) @attr.s class Handler(): flavor = attr.ib() def format(self, frame): method_name = frame.f_code.co_name return f'{method_name}: {self.flavor}' def project(self): return self.format(inspect.currentframe()) def configure(self): rv = [self.format(inspect.currentframe()), self.project()] return '\n'.join(rv) def build(self): rv = [self.format(inspect.currentframe()), self.configure()] return '\n'.join(rv) ``` ``` % test --flavor=blah build build: blah configure: blah project: blah % test build build: debug configure: debug project: debug % test project project: debug ``` </details>
2021-04-09T12:45:33Z
[]
[]
pallets/click
1,846
pallets__click-1846
[ "1844" ]
3f7319081113a0bdfa8fa0b8c4ff018a8f5e5278
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -333,14 +333,6 @@ def get_text_stderr(encoding=None, errors=None): return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) -def filename_to_ui(value): - if isinstance(value, bytes): - value = value.decode(get_filesystem_encoding(), "replace") - else: - value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace") - return value - - def get_strerror(e, default=None): if hasattr(e, "strerror"): msg = e.strerror diff --git a/src/click/exceptions.py b/src/click/exceptions.py --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -1,7 +1,7 @@ +import os from gettext import gettext as _ from gettext import ngettext -from ._compat import filename_to_ui from ._compat import get_text_stderr from .utils import echo @@ -226,12 +226,11 @@ class FileError(ClickException): """Raised if a file cannot be opened.""" def __init__(self, filename, hint=None): - ui_filename = filename_to_ui(filename) if hint is None: hint = _("unknown error") super().__init__(hint) - self.ui_filename = ui_filename + self.ui_filename = os.fsdecode(filename) self.filename = filename def format_message(self): diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -6,7 +6,6 @@ from gettext import ngettext from ._compat import _get_argv_encoding -from ._compat import filename_to_ui from ._compat import get_filesystem_encoding from ._compat import get_strerror from ._compat import open_stream @@ -655,7 +654,7 @@ def convert(self, value, param, ctx): ctx.call_on_close(safecall(f.flush)) return f except OSError as e: # noqa: B014 - self.fail(f"{filename_to_ui(value)!r}: {get_strerror(e)}", param, ctx) + self.fail(f"{os.fsdecode(value)!r}: {get_strerror(e)}", param, ctx) def shell_complete(self, ctx, param, incomplete): """Return a special completion marker that tells the completion @@ -776,7 +775,7 @@ def convert(self, value, param, ctx): return self.coerce_path_result(rv) self.fail( _("{name} {filename!r} does not exist.").format( - name=self.name.title(), filename=filename_to_ui(value) + name=self.name.title(), filename=os.fsdecode(value) ), param, ctx, @@ -785,7 +784,7 @@ def convert(self, value, param, ctx): if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( _("{name} {filename!r} is a file.").format( - name=self.name.title(), filename=filename_to_ui(value) + name=self.name.title(), filename=os.fsdecode(value) ), param, ctx, @@ -793,7 +792,7 @@ def convert(self, value, param, ctx): if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( _("{name} {filename!r} is a directory.").format( - name=self.name.title(), filename=filename_to_ui(value) + name=self.name.title(), filename=os.fsdecode(value) ), param, ctx, @@ -801,7 +800,7 @@ def convert(self, value, param, ctx): if self.writable and not os.access(value, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( - name=self.name.title(), filename=filename_to_ui(value) + name=self.name.title(), filename=os.fsdecode(value) ), param, ctx, @@ -809,7 +808,7 @@ def convert(self, value, param, ctx): if self.readable and not os.access(value, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( - name=self.name.title(), filename=filename_to_ui(value) + name=self.name.title(), filename=os.fsdecode(value) ), param, ctx, diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -7,7 +7,6 @@ from ._compat import _find_binary_writer from ._compat import auto_wrap_for_ansi from ._compat import binary_streams -from ._compat import filename_to_ui from ._compat import get_filesystem_encoding from ._compat import get_strerror from ._compat import is_bytes @@ -355,7 +354,8 @@ def format_filename(filename, shorten=False): """ if shorten: filename = os.path.basename(filename) - return filename_to_ui(filename) + + return os.fsdecode(filename) def get_app_dir(app_name, roaming=True, force_posix=False):
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -93,7 +93,7 @@ def test_filename_formatting(): # filesystem encoding on windows permits this. if not WIN: - assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\ufffd.txt" + assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt" def test_prompts(runner):
AttributeError when using Path with option default <!-- This issue tracker is a tool to address bugs in Click itself. Please use Pallets Discord or Stack Overflow for questions about your own code. Replace this comment with a clear outline of what the bug is. --> Although maybe not intended, `click.option` usually works well with `pathlib.Path`, as the API is fairly compatible with good old strings. When using an option with a `Path` for the default value, things work most of the time, but they don't in one case I ran into. When a verification of a file property (`exists`, `dir_okay`, etc) fails, a call is made to `filename_to_ui` to display the filename of whatever failed the check. This call function handles bytes and str objects but not `pathlib.Path`. Here's an MVCE (assuming `somefile` isn't a file that exists in the current dir): ``` from pathlib import Path import click @click.command() @click.option("--foo", type=click.Path(exists=True), default=Path("./somefile")) def run(foo): print(foo) if __name__ == "__main__": run() ``` TB: ``` Traceback (most recent call last): File "/home/pedro/.local/lib/python3.8/site-packages/click/types.py", line 608, in convert st = os.stat(rv) FileNotFoundError: [Errno 2] No such file or directory: 'somefile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "todo_submit_click_pr.py", line 13, in <module> run() File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 781, in main with self.make_context(prog_name, args, **extra) as ctx: File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 700, in make_context self.parse_args(ctx, args) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1048, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1623, in handle_parse_result value = self.full_process_value(ctx, value) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1965, in full_process_value return Parameter.full_process_value(self, ctx, value) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1592, in full_process_value value = self.get_default(ctx) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1917, in get_default return Parameter.get_default(self, ctx) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1534, in get_default return self.type_cast_value(ctx, rv) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1568, in type_cast_value return _convert(value, (self.nargs != 1) + bool(self.multiple)) File "/home/pedro/.local/lib/python3.8/site-packages/click/core.py", line 1565, in _convert return self.type(value, self, ctx) File "/home/pedro/.local/lib/python3.8/site-packages/click/types.py", line 46, in __call__ return self.convert(value, param, ctx) File "/home/pedro/.local/lib/python3.8/site-packages/click/types.py", line 614, in convert self.path_type, filename_to_ui(value) File "/home/pedro/.local/lib/python3.8/site-packages/click/_compat.py", line 478, in filename_to_ui value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace") AttributeError: 'PosixPath' object has no attribute 'encode' ``` The naive fix is simple, here's a tweaked version of `filename_to_ui` in `_compat.py`: ``` else: import io import pathlib # import only if not PY2 (but see below) ... def filename_to_ui(value): if isinstance(value, bytes): return value.decode(get_filesystem_encoding(), "replace") if isinstance(value, pathlib.PurePath): value = str(value) value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace") return value ``` I did a quick search on the codebase for similar patterns where this would happen and didn't find other cases. The issue I see is that `pathlib` was introduced in Python 3.4, so the PY2 check may not be enough to guarantee compatibility. Not sure how to best handle this. Environment: - Python version: 3.8.5 - Click version: 7.1.2
2021-04-12T14:38:48Z
[]
[]
pallets/click
1,848
pallets__click-1848
[ "1160" ]
e3594e7f8a76dd15109d29570a6f263e56e412f2
diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -20,7 +20,7 @@ def cli(): """ [email protected]() [email protected]_callback() def process_commands(processors): """This result callback is invoked with an iterable of all the chained subcommands. As in this example each subcommand returns a function diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -309,7 +309,7 @@ def __init__( #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you - #: should use a :func:`resultcallback`. + #: should use a :func:`result_callback`. self.invoked_subcommand = None if terminal_width is None and parent is not None: @@ -1363,8 +1363,9 @@ class MultiCommand(Command): is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together. - :param result_callback: the result callback to attach to this multi - command. + :param result_callback: The result callback to attach to this multi + command. This can be set or changed later with the + :meth:`result_callback` decorator. """ allow_extra_args = True @@ -1392,9 +1393,9 @@ def __init__( subcommand_metavar = SUBCOMMAND_METAVAR self.subcommand_metavar = subcommand_metavar self.chain = chain - #: The result callback that is stored. This can be set or - #: overridden with the :func:`resultcallback` decorator. - self.result_callback = result_callback + # The result callback that is stored. This can be set or + # overridden with the :func:`result_callback` decorator. + self._result_callback = result_callback if self.chain: for param in self.params: @@ -1427,7 +1428,7 @@ def format_options(self, ctx, formatter): super().format_options(ctx, formatter) self.format_commands(ctx, formatter) - def resultcallback(self, replace=False): + def result_callback(self, replace=False): """Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result @@ -1443,30 +1444,45 @@ def resultcallback(self, replace=False): def cli(input): return 42 - @cli.resultcallback() + @cli.result_callback() def process_result(result, input): return result + input :param replace: if set to `True` an already existing result callback will be removed. + .. versionchanged:: 8.0 + Renamed from ``resultcallback``. + .. versionadded:: 3.0 """ def decorator(f): - old_callback = self.result_callback + old_callback = self._result_callback + if old_callback is None or replace: - self.result_callback = f + self._result_callback = f return f def function(__value, *args, **kwargs): return f(old_callback(__value, *args, **kwargs), *args, **kwargs) - self.result_callback = rv = update_wrapper(function, f) + self._result_callback = rv = update_wrapper(function, f) return rv return decorator + def resultcallback(self, replace=False): + import warnings + + warnings.warn( + "'resultcallback' has been renamed to 'result_callback'." + " The old name will be removed in Click 8.1.", + DeprecationWarning, + stacklevel=2, + ) + return self.result_callback(replace=replace) + def format_commands(self, ctx, formatter): """Extra format methods for multi methods that adds all the commands after the options. @@ -1512,8 +1528,8 @@ def parse_args(self, ctx, args): def invoke(self, ctx): def _process_result(value): - if self.result_callback is not None: - value = ctx.invoke(self.result_callback, value, **ctx.params) + if self._result_callback is not None: + value = ctx.invoke(self._result_callback, value, **ctx.params) return value if not ctx.protected_args:
diff --git a/tests/test_chain.py b/tests/test_chain.py --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -99,7 +99,7 @@ def test_no_command_result_callback(runner, chain, expect): def cli(): pass - @cli.resultcallback() + @cli.result_callback() def process_result(result): click.echo(str(result), nl=False) @@ -133,7 +133,7 @@ def test_pipeline(runner): def cli(input): pass - @cli.resultcallback() + @cli.result_callback() def process_pipeline(processors, input): iterator = (x.rstrip("\r\n") for x in input) for processor in processors:
Docs: MultiCommand.resultcallback vs MultiCommand.result_callback The [commands](https://click.palletsprojects.com/en/7.x/commands/) doc page shows usage of `MultiCommand.resultcallback` under the header "Multi Command Pipelines" as being a callable itself, that is passed all the associated callbacks with the `chain`ed group. >Where do the returned functions go? The chained multicommand can register a callback with `MultiCommand.resultcallback()` that goes over all these functions and then invoke them. However, at the bottom of that same doc page, it seems to imply that `MultiCommand.result_callback` is the same. >Return values of groups can be processed through a `MultiCommand.result_callback`. This is invoked with the list of all return values in chain mode, or the single return value in case of non chained commands. The API seems to show that [`result_callback`](https://click.palletsprojects.com/en/7.x/api/#click.MultiCommand.result_callback) is an attribute that stores the callback itself, while [`resultcallback`](https://click.palletsprojects.com/en/7.x/api/#click.MultiCommand.resultcallback) is a function that sets what the callback should be. The naming here is confusing, and it's not clear which one is which. In addition: referring to *both* of them in the documentation (without clarifying which is which and why) throws an additional spanner into the works. I recommend a rename for a permanent solution (`result_callback -> _result_callback`) and more explicit documentation in the short-term.
I don't think adding a _ really improves clarity. The parentheses imply resultcallback is a function, and the dot lookup implies result_callback is an attribute. How would you suggest the documentation be improved? I'm renaming the decorator to `@result_callback()` and the attribute to `_result_callback`, since it's only used to store the callback, it doesn't appear to be intended to be set directly as a public API. The docs will not mention the attribute and will only mention the renamed decorator.
2021-04-13T03:14:29Z
[]
[]
pallets/click
1,850
pallets__click-1850
[ "1849" ]
30e7f76a383b7ddba23f564f96871261d6f8800e
diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -47,35 +47,54 @@ def make_str(value): return str(value) -def make_default_short_help(help, max_length=45): - """Return a condensed version of help string.""" - line_ending = help.find("\n\n") - if line_ending != -1: - help = help[:line_ending] +def make_default_short_help(help: str, max_length: int = 45) -> str: + """Returns a condensed version of help string.""" + # Consider only the first paragraph. + paragraph_end = help.find("\n\n") + + if paragraph_end != -1: + help = help[:paragraph_end] + + # Collapse newlines, tabs, and spaces. words = help.split() - total_length = 0 - result = [] - done = False + if not words: + return "" + + # The first paragraph started with a "no rewrap" marker, ignore it. if words[0] == "\b": words = words[1:] - for word in words: - if word[-1:] == ".": - done = True - new_length = 1 + len(word) if result else len(word) - if total_length + new_length > max_length: - result.append("...") - done = True - else: - if result: - result.append(" ") - result.append(word) - if done: + total_length = 0 + last_index = len(words) - 1 + + for i, word in enumerate(words): + total_length += len(word) + (i > 0) + + if total_length > max_length: # too long, truncate break - total_length += new_length - return "".join(result) + if word[-1] == ".": # sentence end, truncate without "..." + return " ".join(words[: i + 1]) + + if total_length == max_length and i != last_index: + break # not at sentence end, truncate with "..." + else: + return " ".join(words) # no truncation needed + + # Account for the length of the suffix. + total_length += len("...") + + # remove words until the length is short enough + while i > 0: + total_length -= len(words[i]) + (i > 0) + + if total_length <= max_length: + break + + i -= 1 + + return " ".join(words[:i]) + "..." class LazyFile:
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -444,3 +444,39 @@ def test_expand_args(monkeypatch): assert "setup.cfg" in click.utils._expand_args(["*.cfg"]) assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"]) assert "*.not-found" in click.utils._expand_args(["*.not-found"]) + + [email protected]( + ("value", "max_length", "expect"), + [ + pytest.param("", 10, "", id="empty"), + pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"), + pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"), + pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"), + pytest.param("123 567 90123.", 10, "123 567...", id="truncate"), + pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"), + pytest.param( + "token in ~/.netrc ciao ciao", + 20, + "token in ~/.netrc...", + id="ignore dot in word", + ), + ], +) [email protected]( + "alter", + [ + pytest.param(None, id=""), + pytest.param( + lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark" + ), + ], +) +def test_make_default_short_help(value, max_length, alter, expect): + assert len(expect) <= max_length + + if alter: + value = alter(value) + + out = click.utils.make_default_short_help(value, max_length) + assert out == expect
Bug: `make_default_short_help` can return strings as long as `max_length + 3` ## The bug The current algorithm doesn't take into account the length of "..." properly: ```python from click.utils import make_default_short_help out = make_default_short_help('1234 67890 xxxxxx', max_length=10) print(out) print('Length:', len(out)) ``` Prints: ``` 1234 67890... Length: 13 ``` Expected output: `1234...` ## Environment - Click version: 7.2 and master ## Solution I'm going to open a PR. ## Related issue (or: why this bug has never been reported) The reason this bug has not been reported is because another "issue" compensates for it, making sure it never manifests itself in the terminal. The following code is from `Group.format_commands`: https://github.com/pallets/click/blob/0dc6d74df5c984ff923f5d17e97bf94a21b3a3cd/src/click/core.py#L1501-L1508 `Group.format_commands` needs to know `col_spacing` to calculate the width of the 2nd column (i.e. the short help `limit`). But it: - doesn't set `col_spacing` in `formatter.write_dl` and, - it assumes that the formatter won't necessarily use the default `col_spacing` value (note that the only way to change it is to subclass `HelpFormatter` and override `write_dl`; not a very clean use of inheritance). As a consequence, it makes the conservative choice of "allowing for 3 times the default `col_spacing`" subtracting 6 to `limit` (i.e. `max_length`). Because `col_spacing` will always be 2, the `limit` will always be 4 characters smaller than needed, compensating for the eventual excess of 3 characters due to the bug reported in this issue. Let me know if I misunderstood something.
2021-04-14T15:43:53Z
[]
[]
pallets/click
1,852
pallets__click-1852
[ "1806" ]
82a83fda1fafd4a43c67755140555bfd5afbd592
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -5,6 +5,7 @@ import typing as t from contextlib import contextmanager from contextlib import ExitStack +from functools import partial from functools import update_wrapper from gettext import gettext as _ from gettext import ngettext @@ -1795,6 +1796,16 @@ def list_commands(self, ctx): return sorted(rv) +def _check_iter(value): + """Check if the value is iterable but not a string. Raises a type + error, or return an iterator over the value. + """ + if isinstance(value, str): + raise TypeError + + return iter(value) + + class Parameter: r"""A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently @@ -1879,6 +1890,7 @@ def __init__( default=None, callback=None, nargs=None, + multiple=False, metavar=None, expose_value=True, is_eager=False, @@ -1903,7 +1915,7 @@ def __init__( self.required = required self.callback = callback self.nargs = nargs - self.multiple = False + self.multiple = multiple self.expose_value = expose_value self.default = default self.is_eager = is_eager @@ -1939,6 +1951,47 @@ def shell_complete(ctx, param, incomplete): self._custom_shell_complete = shell_complete + if __debug__: + if self.type.is_composite and nargs != self.type.arity: + raise ValueError( + f"'nargs' must be {self.type.arity} (or None) for" + f" type {self.type!r}, but it was {nargs}." + ) + + # Skip no default or callable default. + check_default = default if not callable(default) else None + + if check_default is not None: + if multiple: + try: + # Only check the first value against nargs. + check_default = next(_check_iter(check_default), None) + except TypeError: + raise ValueError( + "'default' must be a list when 'multiple' is true." + ) from None + + # Can be None for multiple with empty default. + if nargs != 1 and check_default is not None: + try: + _check_iter(check_default) + except TypeError: + if multiple: + message = ( + "'default' must be a list of lists when 'multiple' is" + " true and 'nargs' != 1." + ) + else: + message = "'default' must be a list when 'nargs' != 1." + + raise ValueError(message) from None + + if nargs > 1 and len(check_default) != nargs: + subject = "item length" if multiple else "length" + raise ValueError( + f"'default' {subject} must match nargs={nargs}." + ) + def to_info_dict(self): """Gather information that could be useful for a tool generating user-facing documentation. @@ -2031,47 +2084,60 @@ def consume_value(self, ctx, opts): return value, source def type_cast_value(self, ctx, value): - """Given a value this runs it properly through the type system. - This automatically handles things like `nargs` and `multiple` as - well as composite types. + """Convert and validate a value against the option's + :attr:`type`, :attr:`multiple`, and :attr:`nargs`. """ if value is None: return () if self.multiple or self.nargs == -1 else None - if self.type.is_composite: - if self.nargs <= 1: - raise TypeError( - "Attempted to invoke composite type but nargs has" - f" been set to {self.nargs}. This is not supported;" - " nargs needs to be set to a fixed value > 1." - ) - - if self.multiple: - return tuple(self.type(x, self, ctx) for x in value) - - return self.type(value, self, ctx) - - def _convert(value, level): - if level == 0: - return self.type(value, self, ctx) - + def check_iter(value): try: - iter_value = iter(value) + return _check_iter(value) except TypeError: - raise TypeError( - "Value for parameter with multiple = True or nargs > 1" - " should be an iterable." - ) + # This should only happen when passing in args manually, + # the parser should construct an iterable when parsing + # the command line. + raise BadParameter( + _("Value must be an iterable."), ctx=ctx, param=self + ) from None + + if self.nargs == 1 or self.type.is_composite: + convert = partial(self.type, param=self, ctx=ctx) + elif self.nargs == -1: + + def convert(value): + return tuple(self.type(x, self, ctx) for x in check_iter(value)) + + else: # nargs > 1 + + def convert(value): + value = tuple(check_iter(value)) + + if len(value) != self.nargs: + raise BadParameter( + ngettext( + "Takes {nargs} values but 1 was given.", + "Takes {nargs} values but {len} were given.", + len(value), + ).format(nargs=self.nargs, len=len(value)), + ctx=ctx, + param=self, + ) + + return tuple(self.type(x, self, ctx) for x in value) - return tuple(_convert(x, level - 1) for x in iter_value) + if self.multiple: + return tuple(convert(x) for x in check_iter(value)) - return _convert(value, (self.nargs != 1) + bool(self.multiple)) + return convert(value) def value_is_missing(self, value): if value is None: return True + if (self.nargs != 1 or self.multiple) and value == (): return True + return False def process_value(self, ctx, value): @@ -2081,25 +2147,6 @@ def process_value(self, ctx, value): if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) - # For bounded nargs (!= -1), validate the number of values. - if ( - not ctx.resilient_parsing - and self.nargs > 1 - and isinstance(value, (tuple, list)) - and ( - any(len(v) != self.nargs for v in value) - if self.multiple - else len(value) != self.nargs - ) - ): - ctx.fail( - ngettext( - "Argument {name!r} takes {nargs} values but 1 was given.", - "Argument {name!r} takes {nargs} values but {len} were given.", - len(value), - ).format(name=self.name, nargs=self.nargs, len=len(value)) - ) - if self.callback is not None: value = self.callback(ctx, self, value) @@ -2250,7 +2297,7 @@ def __init__( **attrs, ): default_is_missing = attrs.get("default", _missing) is _missing - super().__init__(param_decls, type=type, **attrs) + super().__init__(param_decls, type=type, multiple=multiple, **attrs) if prompt is True: prompt_text = self.name.replace("_", " ").capitalize() @@ -2307,32 +2354,33 @@ def __init__( if default_is_missing: self.default = 0 - self.multiple = multiple self.allow_from_autoenv = allow_from_autoenv self.help = help self.show_default = show_default self.show_choices = show_choices self.show_envvar = show_envvar - # Sanity check for stuff we don't support if __debug__: - if self.nargs < 0: - raise TypeError("Options cannot have nargs < 0") + if self.nargs == -1: + raise TypeError("nargs=-1 is not supported for options.") + if self.prompt and self.is_flag and not self.is_bool_flag: - raise TypeError("Cannot prompt for flags that are not bools.") + raise TypeError("'prompt' is not valid for non-boolean flag.") + if not self.is_bool_flag and self.secondary_opts: - raise TypeError("Got secondary option for non boolean flag.") + raise TypeError("Secondary flag is not valid for non-boolean flag.") + if self.is_bool_flag and self.hide_input and self.prompt is not None: - raise TypeError("Hidden input does not work with boolean flag prompts.") + raise TypeError( + "'prompt' with 'hide_input' is not valid for boolean flag." + ) + if self.count: if self.multiple: - raise TypeError( - "Options cannot be multiple and count at the same time." - ) - elif self.is_flag: - raise TypeError( - "Options cannot be count and flags at the same time." - ) + raise TypeError("'count' is not valid with 'multiple'.") + + if self.is_flag: + raise TypeError("'count' is not valid with 'is_flag'.") def to_info_dict(self): info_dict = super().to_info_dict() @@ -2608,12 +2656,14 @@ def __init__(self, param_decls, required=None, **attrs): else: required = attrs.get("nargs", 1) > 0 + if "multiple" in attrs: + raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") + super().__init__(param_decls, required=required, **attrs) - if self.default is not None and self.nargs < 0: - raise TypeError( - "nargs=-1 in combination with a default value is not supported." - ) + if __debug__: + if self.default is not None and self.nargs == -1: + raise TypeError("'default' is not supported for nargs=-1.") @property def human_readable_name(self): diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -864,11 +864,20 @@ def arity(self): return len(self.types) def convert(self, value, param, ctx): - if len(value) != len(self.types): - raise TypeError( - "It would appear that nargs is set to conflict with the" - " composite type arity." + len_type = len(self.types) + len_value = len(value) + + if len_value != len_type: + self.fail( + ngettext( + "{len_type} values are required, but {len_value} was given.", + "{len_type} values are required, but {len_value} were given.", + len_value, + ).format(len_type=len_type, len_value=len_value), + param=param, + ctx=ctx, ) + return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -22,7 +22,7 @@ def test_argument_unbounded_nargs_cant_have_default(runner): with pytest.raises(TypeError, match="nargs=-1"): @click.command() - @click.argument("src", nargs=-1, default=42) + @click.argument("src", nargs=-1, default=["42"]) def copy(src): pass @@ -167,9 +167,9 @@ def inout(output): ("nargs", "value", "expect"), [ (2, "", None), - (2, "a", "Argument 'arg' takes 2 values but 1 was given."), + (2, "a", "Takes 2 values but 1 was given."), (2, "a b", ("a", "b")), - (2, "a b c", "Argument 'arg' takes 2 values but 3 were given."), + (2, "a b c", "Takes 2 values but 3 were given."), (-1, "a b c", ("a", "b", "c")), (-1, "", ()), ], @@ -188,7 +188,8 @@ def cmd(arg): result = runner.invoke(cmd, env={"X": value}, standalone_mode=False) if isinstance(expect, str): - assert expect in str(result.exception) + assert isinstance(result.exception, click.BadParameter) + assert expect in result.exception.format_message() else: assert result.return_value == expect @@ -313,24 +314,15 @@ def copy(x): click.echo(x) [email protected]( - ("value", "code", "output"), - [ - ((), 2, "Argument 'arg' takes 2 values but 0 were given."), - (("a",), 2, "Argument 'arg' takes 2 values but 1 was given."), - (("a", "b"), 0, "len 2"), - (("a", "b", "c"), 2, "Argument 'arg' takes 2 values but 3 were given."), - ], -) -def test_nargs_default(runner, value, code, output): - @click.command() - @click.argument("arg", nargs=2, default=value) - def cmd(arg): - click.echo(f"len {len(arg)}") +def test_multiple_not_allowed(): + with pytest.raises(TypeError, match="multiple"): + click.Argument(["a"], multiple=True) + - result = runner.invoke(cmd) - assert result.exit_code == code - assert output in result.output [email protected]("value", [(), ("a",), ("a", "b", "c")]) +def test_nargs_bad_default(runner, value): + with pytest.raises(ValueError, match="nargs=2"): + click.Argument(["a"], nargs=2, default=value) def test_subcommand_help(runner): diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -33,7 +33,7 @@ def test_invalid_option(runner): def test_invalid_nargs(runner): - with pytest.raises(TypeError, match="nargs < 0"): + with pytest.raises(TypeError, match="nargs=-1"): @click.command() @click.option("--foo", nargs=-1) @@ -117,18 +117,39 @@ def cli(message): assert "Error: Missing option '-m' / '--message'." in result.output -def test_multiple_bad_default(runner): - @click.command() - @click.option("--flags", multiple=True, default=False) - def cli(flags): - pass [email protected]( + ("multiple", "nargs", "default"), + [ + (True, 1, []), + (True, 1, [1]), + # (False, -1, []), + # (False, -1, [1]), + (False, 2, [1, 2]), + # (True, -1, [[]]), + # (True, -1, []), + # (True, -1, [[1]]), + (True, 2, []), + (True, 2, [[1, 2]]), + ], +) +def test_init_good_default_list(runner, multiple, nargs, default): + click.Option(["-a"], multiple=multiple, nargs=nargs, default=default) - result = runner.invoke(cli, []) - assert result.exception - assert ( - "Value for parameter with multiple = True or nargs > 1 should be an iterable." - in result.exception.args - ) + [email protected]( + ("multiple", "nargs", "default"), + [ + (True, 1, 1), + # (False, -1, 1), + (False, 2, [1]), + (True, 2, [[1]]), + ], +) +def test_init_bad_default_list(runner, multiple, nargs, default): + type = (str, str) if nargs == 2 else None + + with pytest.raises(ValueError, match="default"): + click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default) def test_empty_envvar(runner):
Move iterable checks from type_cast_value to __init__ Both the errors raised in `type_cast_value` should be in `__init__` instead. The composite error should be removed from `type_cast_value`, it makes no sense at runtime. Both places that `value` is iterated in `type_cast_value` should raise a `BadParameter` error instead of `TypeError`. _Originally posted by @davidism in https://github.com/pallets/click/issues/1805#issuecomment-791522850_
@Saif807380 want to work on this? Sure. I'll have a go at it.
2021-04-15T21:54:54Z
[]
[]
pallets/click
1,872
pallets__click-1872
[ "1871" ]
5215fc1030ed911c0c67b18e2fcad95fc173dd0e
diff --git a/src/click/formatting.py b/src/click/formatting.py --- a/src/click/formatting.py +++ b/src/click/formatting.py @@ -195,12 +195,11 @@ def write_text(self, text: str) -> None: """Writes re-indented text into the buffer. This rewraps and preserves paragraphs. """ - text_width = max(self.width - self.current_indent, 11) indent = " " * self.current_indent self.write( wrap_text( text, - text_width, + self.width, initial_indent=indent, subsequent_indent=indent, preserve_paragraphs=True,
diff --git a/tests/test_formatting.py b/tests/test_formatting.py --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -335,3 +335,13 @@ def test_formatting_with_options_metavar_empty(runner): cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])]) result = runner.invoke(cli, ["--help"]) assert "Usage: cli VAR\n" in result.output + + +def test_help_formatter_write_text(): + text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" + formatter = click.HelpFormatter(width=len(" Lorem ipsum dolor sit amet,")) + formatter.current_indent = 2 + formatter.write_text(text) + actual = formatter.getvalue() + expected = " Lorem ipsum dolor sit amet,\n consectetur adipiscing elit\n" + assert actual == expected
`HelpFormatter.write_text()` is not using all the available line width `HelpFormatter.write_text()` uses the function `wrap_text(text, width, initial_indent, ...)` internally. This function expects `width` to be the line width **including** the eventual indentation. `HelpFormatter.write_text()` gets this wrong and passes `self.width - self.current_indent` instead of just `self.width`.
2021-05-07T15:50:44Z
[]
[]
pallets/click
1,890
pallets__click-1890
[ "1889" ]
b03a0432d05ffb2802efb69c23f3e444fb363b0e
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,3 +1,9 @@ from setuptools import setup -setup(name="click", install_requires=["colorama; platform_system == 'Windows'"]) +setup( + name="click", + install_requires=[ + "colorama; platform_system == 'Windows'", + "importlib-metadata; python_version < '3.8'", + ], +) diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -370,15 +370,7 @@ def callback(ctx: Context, param: Parameter, value: bool) -> None: from importlib import metadata # type: ignore except ImportError: # Python < 3.8 - try: - import importlib_metadata as metadata # type: ignore - except ImportError: - metadata = None - - if metadata is None: - raise RuntimeError( - "Install 'importlib_metadata' to get the version on Python < 3.8." - ) + import importlib_metadata as metadata # type: ignore try: version = metadata.version(package_name) # type: ignore
diff --git a/requirements/tests.in b/requirements/tests.in --- a/requirements/tests.in +++ b/requirements/tests.in @@ -1,2 +1 @@ pytest -importlib_metadata diff --git a/requirements/tests.txt b/requirements/tests.txt --- a/requirements/tests.txt +++ b/requirements/tests.txt @@ -6,8 +6,6 @@ # attrs==21.2.0 # via pytest -importlib-metadata==4.0.1 - # via -r requirements/tests.in iniconfig==1.1.1 # via pytest packaging==20.9 @@ -22,5 +20,3 @@ pytest==6.2.4 # via -r requirements/tests.in toml==0.10.2 # via pytest -zipp==3.4.1 - # via importlib-metadata
install importlib_metadata on Python < 3.8 `click 8.0.0` now relies on `importlib.metadata` under certain conditions. On Python 3.8, click will raise an error and ask the user to install the `importlib_metadata` backport package. Ex: ``` Traceback (most recent call last): File "/path_to_my_venv/bin/myexecutable", line 8, in <module> sys.exit(cli()) File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 1134, in __call__ return self.main(*args, **kwargs) File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 1058, in main with self.make_context(prog_name, args, **extra) as ctx: File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 927, in make_context self.parse_args(ctx, args) File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 1621, in parse_args rest = super().parse_args(ctx, args) File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 1376, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 2352, in handle_parse_result value = self.process_value(ctx, value) File "/path_to_my_venv/lib/python3.6/site-packages/click/core.py", line 2314, in process_value value = self.callback(ctx, self, value) File "/path_to_my_venv/lib/python3.6/site-packages/click/decorators.py", line 380, in callback "Install 'importlib_metadata' to get the version on Python < 3.8." RuntimeError: Install 'importlib_metadata' to get the version on Python < 3.8. ``` The user can install `importlib_metadata`, but I think Click could use environment markers to install the `importlib_metadata` backport package on Python 3.8, in the same manner that `colorama` is installed on Windows. I will send a PR soon. Feel free to express any concerns, doubts or considerations to the project context that I've missed. Environment: - Python version: 3.6 - Click version: 8.0.0
2021-05-12T20:12:35Z
[]
[]
pallets/click
1,896
pallets__click-1896
[ "1359" ]
77961478cdaf9cf55c8b15fd1db0681ff75ffcfb
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1797,7 +1797,7 @@ def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: def command( self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], Command]: + ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]: """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` and immediately registers the created command with this group by @@ -1806,6 +1806,9 @@ def command( To customize the command class used, set the :attr:`command_class` attribute. + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + .. versionchanged:: 8.0 Added the :attr:`command_class` attribute. """ @@ -1814,16 +1817,25 @@ def command( if self.command_class is not None and "cls" not in kwargs: kwargs["cls"] = self.command_class + func: t.Optional[t.Callable] = None + + if args and callable(args[0]): + func = args[0] + args = args[1:] + def decorator(f: t.Callable[..., t.Any]) -> Command: - cmd = command(*args, **kwargs)(f) + cmd: Command = command(*args, **kwargs)(f) self.add_command(cmd) return cmd + if func is not None: + return decorator(func) + return decorator def group( self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]: + ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by @@ -1832,11 +1844,20 @@ def group( To customize the group class used, set the :attr:`group_class` attribute. + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + .. versionchanged:: 8.0 Added the :attr:`group_class` attribute. """ from .decorators import group + func: t.Optional[t.Callable] = None + + if args and callable(args[0]): + func = args[0] + args = args[1:] + if self.group_class is not None and "cls" not in kwargs: if self.group_class is type: kwargs["cls"] = type(self) @@ -1844,10 +1865,13 @@ def group( kwargs["cls"] = self.group_class def decorator(f: t.Callable[..., t.Any]) -> "Group": - cmd = group(*args, **kwargs)(f) + cmd: Group = group(*args, **kwargs)(f) self.add_command(cmd) return cmd + if func is not None: + return decorator(func) + return decorator def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -153,11 +153,29 @@ def _make_command( ) [email protected] def command( name: t.Optional[str] = None, cls: t.Optional[t.Type[Command]] = None, **attrs: t.Any, ) -> t.Callable[[F], Command]: + ... + + [email protected] +def command( + name: t.Callable, + cls: t.Optional[t.Type[Command]] = None, + **attrs: t.Any, +) -> Command: + ... + + +def command( + name: t.Union[str, t.Callable, None] = None, + cls: t.Optional[t.Type[Command]] = None, + **attrs: t.Any, +) -> t.Union[Command, t.Callable[[F], Command]]: r"""Creates a new :class:`Command` and uses the decorated function as callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command. @@ -176,24 +194,62 @@ def command( name with underscores replaced by dashes. :param cls: the command class to instantiate. This defaults to :class:`Command`. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. """ if cls is None: cls = Command + func: t.Optional[t.Callable] = None + + if callable(name): + func = name + name = None + def decorator(f: t.Callable[..., t.Any]) -> Command: cmd = _make_command(f, name, attrs, cls) # type: ignore cmd.__doc__ = f.__doc__ return cmd + if func is not None: + return decorator(func) + return decorator -def group(name: t.Optional[str] = None, **attrs: t.Any) -> t.Callable[[F], Group]: [email protected] +def group( + name: t.Optional[str] = None, + **attrs: t.Any, +) -> t.Callable[[F], Group]: + ... + + [email protected] +def group( + name: t.Callable, + **attrs: t.Any, +) -> Group: + ... + + +def group( + name: t.Union[str, t.Callable, None] = None, **attrs: t.Any +) -> t.Union[Group, t.Callable[[F], Group]]: """Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. """ attrs.setdefault("cls", Group) + + if callable(name): + grp: t.Callable[[F], Group] = t.cast(Group, command(**attrs)) + return grp(name) + return t.cast(Group, command(name, **attrs))
diff --git a/tests/test_command_decorators.py b/tests/test_command_decorators.py new file mode 100644 --- /dev/null +++ b/tests/test_command_decorators.py @@ -0,0 +1,37 @@ +import click + + +def test_command_no_parens(runner): + @click.command + def cli(): + click.echo("hello") + + result = runner.invoke(cli) + assert result.exception is None + assert result.output == "hello\n" + + +def test_group_no_parens(runner): + @click.group + def grp(): + click.echo("grp1") + + @grp.command + def cmd1(): + click.echo("cmd1") + + @grp.group + def grp2(): + click.echo("grp2") + + @grp2.command + def cmd2(): + click.echo("cmd2") + + result = runner.invoke(grp, ["cmd1"]) + assert result.exception is None + assert result.output == "grp1\ncmd1\n" + + result = runner.invoke(grp, ["grp2", "cmd2"]) + assert result.exception is None + assert result.output == "grp1\ngrp2\ncmd2\n"
raise a more descriptive exception when @command decorator isn't called Click 7.0, Python 3.7.4 Having done `pip install -e .` on my package to set up the CLI command, this error is raised because I decorated the main CLI function with `click.command` instead of `click.command()`: ``` Traceback (most recent call last): File "/Users/zev/.local/share/virtualenvs/myvirtualenvname-CI6hzx9c/bin/capture", line 11, in <module> load_entry_point('myvirtualenvname', 'console_scripts', 'my_module_name')() TypeError: decorator() missing 1 required positional argument: 'f' ``` Would it be possible to raise a more informative exception referring to the decorator not having been called?
2021-05-14T14:21:34Z
[]
[]
pallets/click
1,910
pallets__click-1910
[ "1903" ]
6c9179c93435853bd7bd6fde2b0609641fb2df5c
diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -233,7 +233,9 @@ def process( ) ) - if self.nargs == -1 and self.obj.envvar is not None: + if self.nargs == -1 and self.obj.envvar is not None and value == (): + # Replace empty tuple with None so that a value from the + # environment may be tried. value = None state.opts[self.dest] = value # type: ignore
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -194,6 +194,19 @@ def cmd(arg): assert result.return_value == expect +def test_nargs_envvar_only_if_values_empty(runner): + @click.command() + @click.argument("arg", envvar="X", nargs=-1) + def cli(arg): + return arg + + result = runner.invoke(cli, ["a", "b"], standalone_mode=False) + assert result.return_value == ("a", "b") + + result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False) + assert result.return_value == ("a",) + + def test_empty_nargs(runner): @click.command() @click.argument("arg", nargs=-1)
argument with nargs=-1 and envvar ignores values from command line Since click 8.0, the value(s) provided on the command line for a nargs=-1 argument are ignored if the argument has `envvar` set. Example: ```python #!/usr/bin/env python import click @click.command() @click.argument("foo", nargs=-1, envvar="FOO") def cli(foo): click.echo(foo) if __name__ == "__main__": cli() ``` ``` $ ./clickbug arg1 arg2 () ``` When arguments are passed on the command line, the `foo` value remains empty. Removing the `envvar` option makes it work again. Values from the environment variable are picked up, though. Reverting to `click<8` also fixes the problem. The cause of the bug is possibly [here](https://github.com/pallets/click/commit/3d3ea9c64420fd8978a41ce8b4db3ac2d245849c#diff-948f9e0cc733616a6b18aa152ac6703e819fec61dd752d1efa40e5736c3bdce7): The incoming `value` (which at this point still contains the correct arguments) is overwritten with `None` if `nargs` is -1 and the argument has an envvar set. Environment: - Python version: 3.8.5 - Click version: 8.0.0
2021-05-19T01:47:23Z
[]
[]
pallets/click
1,913
pallets__click-1913
[ "1886" ]
b131f71de8bba96e367da7c7e9b5fbf721670e28
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -13,6 +13,7 @@ from gettext import ngettext from itertools import repeat +from . import types from ._unicodefun import _verify_python_env from .exceptions import Abort from .exceptions import BadParameter @@ -30,11 +31,6 @@ from .termui import confirm from .termui import prompt from .termui import style -from .types import _NumberRangeBase -from .types import BOOL -from .types import convert_type -from .types import IntRange -from .types import ParamType from .utils import _detect_program_name from .utils import _expand_args from .utils import echo @@ -2010,7 +2006,7 @@ class Parameter: def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, - type: t.Optional[t.Union["ParamType", t.Any]] = None, + type: t.Optional[t.Union[types.ParamType, t.Any]] = None, required: bool = False, default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None, callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None, @@ -2035,8 +2031,7 @@ def __init__( self.name, self.opts, self.secondary_opts = self._parse_decls( param_decls or (), expose_value ) - - self.type = convert_type(type, default) + self.type = types.convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. @@ -2439,6 +2434,9 @@ class Option(Parameter): context. :param help: the help string. :param hidden: hide this option from help outputs. + + .. versionchanged:: 8.0.1 + ``type`` is detected from ``flag_value`` if given. """ param_type_name = "option" @@ -2456,7 +2454,7 @@ def __init__( multiple: bool = False, count: bool = False, allow_from_autoenv: bool = True, - type: t.Optional[t.Union["ParamType", t.Any]] = None, + type: t.Optional[t.Union[types.ParamType, t.Any]] = None, help: t.Optional[str] = None, hidden: bool = False, show_choices: bool = True, @@ -2507,20 +2505,20 @@ def __init__( if flag_value is None: flag_value = not self.default + if is_flag and type is None: + # Re-guess the type from the flag value instead of the + # default. + self.type = types.convert_type(None, flag_value) + self.is_flag: bool = is_flag + self.is_bool_flag = isinstance(self.type, types.BoolParamType) self.flag_value: t.Any = flag_value - if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]: - self.type: "ParamType" = BOOL - self.is_bool_flag = True - else: - self.is_bool_flag = False - # Counting self.count = count if count: if type is None: - self.type = IntRange(min=0) + self.type = types.IntRange(min=0) if default_is_missing: self.default = 0 @@ -2725,7 +2723,7 @@ def _write_opts(opts: t.Sequence[str]) -> str: extra.append(_("default: {default}").format(default=default_string)) - if isinstance(self.type, _NumberRangeBase): + if isinstance(self.type, types._NumberRangeBase): range_str = self.type._describe_range() if range_str: diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -1000,10 +1000,7 @@ def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> Pa if ty is float: return FLOAT - # Booleans are only okay if not guessed. For is_flag options with - # flag_value, default=True indicates which flag_value is the - # default. - if ty is bool and not guessed_type: + if ty is bool: return BOOL if guessed_type:
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -756,3 +756,10 @@ def cli(opt, a, b): result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False) assert result.return_value == expect + + +def test_type_from_flag_value(): + param = click.Option(["-a", "x"], default=True, flag_value=4) + assert param.type is click.INT + param = click.Option(["-b", "x"], flag_value=8) + assert param.type is click.INT
flag_value converted to str in Click 8 Consider the following code: ```python import click @click.command() @click.option("--answer", flag_value=42) def main(answer): click.echo(repr(answer)) if __name__ == '__main__': main() ``` Under click 7, passing the `--answer` option to this script prints `42` (an int), as expected. Under click 8, it prints `'42'` (a str). Environment: - Python version: 3.9.5 - Click version: 7.1.2 vs. 8.0.0
The default type of parameters is `str`. You need to specify `type=int` if you want int values. @davidism OK, but in my actual use case, the `flag_value` is an instance of a class with a zero-argument constructor. How am I expected to get that to work? Trying `@click.option("--answer", is_flag=True, type=Klass)` (and also with `flag_value=None`) results in a `Klass() takes no arguments` TypeError. Then it should use `type=click.UNPROCESSED` to pass the value through unchanged. I think what's affecting this is that we now apply type casting consistently to any value coming through the pipeline. I wonder if setting the type to unprocessed automatically for flag values is safe. @davidism Using `type=click.UNPROCESSED` works, thanks. > The most basic option is a value option. These options accept one argument which is a value. *If no type is provided, the type of the default value is used.* Click 8.0.0 appears to ignore the type of the default value of options if `type` is not given: ```python bugval = functools.partial(range, 10) @click.command() @click.option('-b', 'bug', default=bugval, flag_value=bugval) def cli(bug): print("type of bug:", type(bug), "value of bug", bug) ``` ```bash $ python click_bug.py type of bug: <class 'str'> value of bug functools.partial(<class 'range'>, 10) ``` I'm sorry, I can't tell what you're trying to demonstrate with that example. It seems at best tangentially related to this issue, but it's not clear at all. Sorry, I thought the example was fairly obvious: as per the documentation (quoted from 8.0.0), and as it works in 7.1.2, Click should infer the type of the value from what's given to `default`, but in 8.0.0 the type of the `default` value is ignored and the flag value is cast to `str` instead. This is pretty clearly a bug; the same bug for which the issue was opened, in fact. The default you gave is dynamic, so it wouldn't be able to infer a type anyway. It's not dynamic, it's the value of `bugval` - a `functools.partial` object. Which is a callable, not a literal value. A callable is dynamic... A `functools.partial` is a callable, literal value that has a type (`functools.partial`, specifically.) @crashfrog sorry, it sounds like we're having trouble explaining the difference. You're going to have to trust us that there is, in fact, a difference, this tangent is derailing this issue. I'm not sure what you're having trouble explaining - in 7.1.2 it works to pass callable values as `default` and `flag_value`, which is extremely useful for things like flags that set output formats (TSV vs. JSON vs. XML, for instance.) In 8.0.0 this behavior is broken because `click.option` now ignores the `default` argument's type and converts callable values to strings when there's no type argument. Since this isn't described in the documentation and it's a breaking change from 7.1.2, it's pretty obviously a bug and it's exactly the bug described in the issue; this is an example of it. https://click.palletsprojects.com/en/8.0.x/changes/#version-8-0-0 Here's the patch notes; I don't see where it says "we now convert all callable values to `str`" or something, and even if that were in the notes, that's undesirable behavior.
2021-05-19T04:23:56Z
[]
[]
pallets/click
1,915
pallets__click-1915
[ "1895" ]
329b1001755452c96dcefcf4a3c799a2463710e0
diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -67,6 +67,11 @@ def get_command(self, ctx, cmd_name): return click.Group.get_command(self, ctx, matches[0]) ctx.fail(f"Too many matches: {', '.join(sorted(matches))}") + def resolve_command(self, ctx, args): + # always return the command's name, not the alias + _, cmd, args = super().resolve_command(ctx, args) + return cmd.name, cmd, args + def read_config(ctx, param, value): """Callback that is used whenever --config is passed. We use this to diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1717,7 +1717,7 @@ def resolve_command( if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) - return cmd.name if cmd else None, cmd, args[1:] + return cmd_name if cmd else None, cmd, args[1:] def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: """Given a context and a command name, this returns a
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -285,6 +285,10 @@ class AliasedGroup(click.Group): def get_command(self, ctx, cmd_name): return push + def resolve_command(self, ctx, args): + _, command, args = super().resolve_command(ctx, args) + return command.name, command, args + cli = AliasedGroup() @cli.command() @@ -296,6 +300,16 @@ def push(): assert result.output.startswith("Usage: root push [OPTIONS]") +def test_group_add_command_name(runner): + cli = click.Group("cli") + cmd = click.Command("a", params=[click.Option(["-x"], required=True)]) + cli.add_command(cmd, "b") + # Check that the command is accessed through the registered name, + # not the original name. + result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}}) + assert result.exit_code == 0 + + def test_unprocessed_options(runner): @click.command(context_settings=dict(ignore_unknown_options=True)) @click.argument("args", nargs=-1, type=click.UNPROCESSED)
Click 8.0.0 `group.add_command(..)` does not replace name in description and when looking up defaults With click 8.0.0 `click.group.add_command(..)` changed the behavior in how new command names are used: Both the help text for the command as well as when looking up default values in `default_map` the previous command name instead of the one added by the group are shown. Minimal example: ``` # test.py import click @click.command() @click.option( "--qux", required=True ) def foo(qux): print(qux) @click.group() def group(): pass group.add_command(foo, "bar") group(default_map={"bar": {"qux": "val"}}) ``` Run the above: * with click 7.x: > $ python3 test.py bar --help > Usage: test.py bar [OPTIONS] > // and > $ python3 test.py bar > val * with click 8.0.0: > $ python3 test.py bar --help > Usage: test.py foo [OPTIONS] > // and > $ python3 test.py bar > Usage: test.py foo [OPTIONS] > Try 'test.py foo --help' for help. > > Error: Missing option '--qux'. I would have expected that both the help shows the name of the command as "bar" (as using "foo" will result in an error) and the lookup for the default using "bar" as a key. Environment: - Python version: 3.9.5 - Click version: 8.0.0
This was due to #1422, which was intended to return the "real" command name when using aliases. However, I think the use case you've shown here is much more common, so I'll revert that change. The aliased command issue can be addressed by updating the docs to override `resolve_command` and return the desired command name instead.
2021-05-19T17:49:17Z
[]
[]
pallets/click
1,916
pallets__click-1916
[ "1899" ]
1b4915931c1b32ad1bcd043132a0831d71be3aa4
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2196,6 +2196,10 @@ def get_default( :param call: If the default is a callable, call it. Disable to return the callable instead. + .. versionchanged:: 8.0.1 + Type casting can fail in resilient parsing mode. Invalid + defaults will not prevent showing help text. + .. versionchanged:: 8.0 Looks at ``ctx.default_map`` first. @@ -2214,7 +2218,13 @@ def get_default( value = value() - return self.type_cast_value(ctx, value) + try: + return self.type_cast_value(ctx, value) + except BadParameter: + if ctx.resilient_parsing: + return value + + raise def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: raise NotImplementedError() @@ -2700,14 +2710,24 @@ def _write_opts(opts: t.Sequence[str]) -> str: ) extra.append(_("env var: {var}").format(var=var_str)) - default_value = self.get_default(ctx, call=False) + # Temporarily enable resilient parsing to avoid type casting + # failing for the default. Might be possible to extend this to + # help formatting in general. + resilient = ctx.resilient_parsing + ctx.resilient_parsing = True + + try: + default_value = self.get_default(ctx, call=False) + finally: + ctx.resilient_parsing = resilient + show_default_is_str = isinstance(self.show_default, str) if show_default_is_str or ( default_value is not None and (self.show_default or ctx.show_default) ): if show_default_is_str: - default_string: t.Union[str, t.Any] = f"({self.show_default})" + default_string = f"({self.show_default})" elif isinstance(default_value, (list, tuple)): default_string = ", ".join(str(d) for d in default_value) elif callable(default_value): @@ -2719,7 +2739,7 @@ def _write_opts(opts: t.Sequence[str]) -> str: (self.opts if self.default else self.secondary_opts)[0] )[1] else: - default_string = default_value + default_string = str(default_value) extra.append(_("default: {default}").format(default=default_string))
diff --git a/tests/test_basic.py b/tests/test_basic.py --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -547,3 +547,20 @@ def cmd(): result = runner.invoke(cli, ["--help"]) assert "Summary line without period" in result.output assert "Here is a sentence." not in result.output + + +def test_help_invalid_default(runner): + cli = click.Command( + "cli", + params=[ + click.Option( + ["-a"], + type=click.Path(exists=True), + default="not found", + show_default=True, + ), + ], + ) + result = runner.invoke(cli, ["--help"]) + assert result.exit_code == 0 + assert "default: not found" in result.output diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -553,7 +553,7 @@ def cmd(config): def test_argument_custom_class(runner): class CustomArgument(click.Argument): - def get_default(self, ctx): + def get_default(self, ctx, call=True): """a dumb override of a default value for testing""" return "I am a default"
Arguments may break `--help` Using `click.Path` for an argument may prevent the `--help` from showing up. A simple example is the following: ``` @click.command() @click.option( "-f", type=click.Path(exists=True, file_okay=True), default="this does not exist", help="Output file name", show_default=True, ) def cli(): pass ``` When trying to print the `--help` the default argument will be checked for validity and instead print an error that `-f` is an invalid value. Environment: - Python version: Python 3.8.9 - Click version: 8.0.0
Hard to say whether this should be an issue. If you're going to give a default to `Path(exists=True)` that doesn't exist, you're going to have to address that anyway, as it will fail when not using `--help` too. @davidism as an end user if you're not using `--help` it's still going to print what you need to fix. If you still don't understand the message, the current behavior blocks even looking at the `--help` to see if there's anything more that would be helpful or look at what all the arguments mean. I understand the value will need to be addressed by the developer and potentially the end user, but how should a developer handle catching the error in the `--help` path and allow or unset defaults that might be problematic / allow printing the default as given as I did in the PR? Regarding your comment (mentioning here just to keep the discussion in one place): > I don't think it's the correct fix, `call=False` is used for more than generating help, ignoring errors in that case has wider potential effects. https://github.com/pallets/click/pull/1900#issuecomment-843673138 It didn't look to be the case when I scanned the code, but I may have missed something and I understand this may be overloading the `call` argument more than is desired. Is the only option moving either the default or the existence check into the beginning of the command? I couldn't tell if this code was new as I was simply contributing to a library which already used `click` and I was upgrading it to `click` 8 to allow it to use the typing that is provided, but I would have expected since `click` is auto-generating the `--help` it's `click`'s responsibility to _try_ to render the help as much as it can. Falling back to the default as given doesn't seem like a very big ask, but I understand it may need to be done in a different manner than I had implemented in #1900. OK, so the issue is that you want to provide a default value that may or may not exist and show that in help text. The problem is that the processing pipeline changed to apply type casting consistently to parameter values, including when getting defaults.
2021-05-19T18:38:37Z
[]
[]
pallets/click
1,930
pallets__click-1930
[ "1929" ]
2184ab1fdaf2956457c866dc68f87d09ca9af101
diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -450,7 +450,12 @@ def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: def _start_of_option(value: str) -> bool: """Check if the value looks like the start of an option.""" - return not value[0].isalnum() if value else False + if not value: + return False + + c = value[0] + # Allow "/" since that starts a path. + return not c.isalnum() and c != "/" def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool:
diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py --- a/tests/test_shell_completion.py +++ b/tests/test_shell_completion.py @@ -125,6 +125,14 @@ def test_path_types(type, expect): assert c.type == expect +def test_absolute_path(): + cli = Command("cli", params=[Option(["-f"], type=Path())]) + out = _get_completions(cli, ["-f"], "/ab") + assert len(out) == 1 + c = out[0] + assert c.value == "/ab" + + def test_option_flag(): cli = Command( "cli",
Shell completion fails with for arguments starting with "/" After enabling shell completion support, arguments which start with a leading forward slash "/" fail to complete. After a bit of debugging, it appears that if the argument starts with a "/", the completions are generated for the command itself instead of for the argument. For example, `my_app open /fold⇥` would generate completions for `open` instead of `/fold` whereas `my_app open fold⇥` correctly generates completions for `fold`. Edit: To clarify the above, in both cases either "/fold" or "fold" is correctly picked up as the incomplete string. But in the first case, `obj.shell_complete(ctx, "/fold")` is called with the "open" command as the `obj`. Environment: - Python version: 3.9 - Click version: 8.0.1 - Shell: zsh, bash
Further debugging shows that an argument starting with "/" is incorrectly identified as the start of an option by `click.shell_completion._start_of_option()`: https://github.com/pallets/click/blob/af0af571cbbd921d3974a0ff9cf58a4b26bb852b/src/click/shell_completion.py#L449-L451 This causes the wrong object to be chosen to provide the completion in `_resolve_incomplete()`: https://github.com/pallets/click/blob/af0af571cbbd921d3974a0ff9cf58a4b26bb852b/src/click/shell_completion.py#L555-L556
2021-05-23T20:05:58Z
[]
[]
pallets/click
1,934
pallets__click-1934
[ "1925" ]
da2b658e6185b5ae69abcefe755077336024a5e6
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2528,7 +2528,7 @@ def __init__( self.type = types.convert_type(None, flag_value) self.is_flag: bool = is_flag - self.is_bool_flag = isinstance(self.type, types.BoolParamType) + self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType) self.flag_value: t.Any = flag_value # Counting
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -4,6 +4,7 @@ import pytest import click +from click import Option def test_prefixes(runner): @@ -763,3 +764,22 @@ def test_type_from_flag_value(): assert param.type is click.INT param = click.Option(["-b", "x"], flag_value=8) assert param.type is click.INT + + [email protected]( + ("option", "expected"), + [ + # Not boolean flags + pytest.param(Option(["-a"], type=int), False, id="int option"), + pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"), + pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"), + pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"), + pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"), + # Boolean flags + pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"), + pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"), + pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"), + ], +) +def test_is_bool_flag_is_correctly_set(option, expected): + assert option.is_bool_flag is expected
Option.is_bool_flag is set to True even if the option is not a flag This is relevant only for Click 8.0.1, since the following line was introduced in PR https://github.com/pallets/click/pull/1913: https://github.com/pallets/click/blob/af0af571cbbd921d3974a0ff9cf58a4b26bb852b/src/click/core.py#L2531 The solution is as easy as: ```python self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType) ``` Available to open a PR. ## Demonstration code ```python import click @click.command() @click.option('--switch', type=bool) def f(switch): print(switch) if __name__ == '__main__': assert not f.params[0].is_flag assert f.params[0].is_bool_flag f('--switch'.split()) ``` ``` Error: Option '--switch' requires an argument. ```
2021-05-24T15:57:28Z
[]
[]
pallets/click
1,964
pallets__click-1964
[ "1963" ]
08ecfd0e7c238a2444886d239de6d0e9d83530ec
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -223,9 +223,14 @@ class Context: codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. - :param show_default: Show defaults for all options. If not set, - defaults to the value from a parent context. Overrides an - option's ``show_default`` argument. + :param show_default: Show the default value for commands. If this + value is not set, it defaults to the value from the parent + context. ``Command.show_default`` overrides this default for the + specific command. + + .. versionchanged:: 8.1 + The ``show_default`` parameter is overridden by + ``Command.show_default``, instead of the other way around. .. versionchanged:: 8.0 The ``show_default`` parameter defaults to the value from the @@ -2372,14 +2377,15 @@ class Option(Parameter): All other parameters are passed onwards to the parameter constructor. - :param show_default: Controls if the default value should be shown - on the help page. Normally, defaults are not shown. If this - value is a string, it shows that string in parentheses instead - of the actual value. This is particularly useful for dynamic - options. For single option boolean flags, the default remains - hidden if its value is ``False``. + :param show_default: Show the default value for this option in its + help text. Values are not shown by default, unless + :attr:`Context.show_default` is ``True``. If this value is a + string, it shows that string in parentheses instead of the + actual value. This is particularly useful for dynamic options. + For single option boolean flags, the default remains hidden if + its value is ``False``. :param show_envvar: Controls if an environment variable should be - shown on the help page. Normally, environment ariables are not + shown on the help page. Normally, environment variables are not shown. :param prompt: If set to ``True`` or a non empty string then the user will be prompted for input. If set to ``True`` the prompt @@ -2409,6 +2415,10 @@ class Option(Parameter): :param help: the help string. :param hidden: hide this option from help outputs. + .. versionchanged:: 8.1.0 + The ``show_default`` parameter overrides + ``Context.show_default``. + .. versionchanged:: 8.1.0 The default of a single option boolean flag is not shown if the default value is ``False``. @@ -2422,7 +2432,7 @@ class Option(Parameter): def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, - show_default: t.Union[bool, str] = False, + show_default: t.Union[bool, str, None] = None, prompt: t.Union[bool, str] = False, confirmation_prompt: t.Union[bool, str] = False, prompt_required: bool = True, @@ -2689,11 +2699,18 @@ def _write_opts(opts: t.Sequence[str]) -> str: finally: ctx.resilient_parsing = resilient - show_default_is_str = isinstance(self.show_default, str) + show_default = False + show_default_is_str = False - if show_default_is_str or ( - default_value is not None and (self.show_default or ctx.show_default) - ): + if self.show_default is not None: + if isinstance(self.show_default, str): + show_default_is_str = show_default = True + else: + show_default = self.show_default + elif ctx.show_default is not None: + show_default = ctx.show_default + + if show_default_is_str or (show_default and (default_value is not None)): if show_default_is_str: default_string = f"({self.show_default})" elif isinstance(default_value, (list, tuple)):
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -643,7 +643,6 @@ def cmd2(testoption): # Both of the commands should have the --help option now. for cmd in (cmd1, cmd2): - result = runner.invoke(cmd, ["--help"]) assert "I am a help text" in result.output assert "you wont see me" not in result.output @@ -795,6 +794,28 @@ def test_do_not_show_default_empty_multiple(): assert message == "values" [email protected]( + ("ctx_value", "opt_value", "expect"), + [ + (None, None, False), + (None, False, False), + (None, True, True), + (False, None, False), + (False, False, False), + (False, True, True), + (True, None, True), + (True, False, False), + (True, True, True), + (False, "one", True), + ], +) +def test_show_default_precedence(ctx_value, opt_value, expect): + ctx = click.Context(click.Command("test"), show_default=ctx_value) + opt = click.Option("-a", default=1, help="value", show_default=opt_value) + help = opt.get_help_record(ctx)[1] + assert ("default:" in help) is expect + + @pytest.mark.parametrize( ("args", "expect"), [
Give `Option.show_default` higher priority wrt `Context.show_default` Currently, `Context.show_default` (a global setting) overrides `Option.show_default` (a local setting). This is counterintuitive and limit expressiveness: once `Context.show_default` is set to `True`, it's impossible to disable `show_default` for a specific option.
2021-06-18T17:09:37Z
[]
[]
pallets/click
1,970
pallets__click-1970
[ "1969" ]
10611b5fc36e68f33765a07b7690fbfbdb1fea84
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2461,7 +2461,7 @@ class Option(Parameter): def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, - show_default: bool = False, + show_default: t.Union[bool, str] = False, prompt: t.Union[bool, str] = False, confirmation_prompt: t.Union[bool, str] = False, prompt_required: bool = True, @@ -2748,7 +2748,8 @@ def _write_opts(opts: t.Sequence[str]) -> str: else: default_string = str(default_value) - extra.append(_("default: {default}").format(default=default_string)) + if default_string: + extra.append(_("default: {default}").format(default=default_string)) if isinstance(self.type, types._NumberRangeBase): range_str = self.type._describe_range()
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -728,6 +728,16 @@ def test_do_not_show_no_default(runner): assert "[default: None]" not in message +def test_do_not_show_default_empty_multiple(): + """When show_default is True and multiple=True is set, it should not + print empty default value in --help output. + """ + opt = click.Option(["-a"], multiple=True, help="values", show_default=True) + ctx = click.Context(click.Command("cli")) + message = opt.get_help_record(ctx)[1] + assert message == "values" + + @pytest.mark.parametrize( ("args", "expect"), [
Empty default value in --help output for option with multiple=True ## Minimal reproducible example that demonstrates the bug ```python #!/usr/bin/env python3 import click @click.command() @click.option('--multioption', multiple=True, default=None, help='My help', show_default=True) def info(_multioption): pass if __name__ == '__main__': info() ``` Notice `multiple=True` which is crucial. If you replace it with `multiple=False` it will work just fine. ### What I get ```console $ ./test.py --help Usage: test.py [OPTIONS] Options: --multioption TEXT My help [default: ] --help Show this message and exit. [default: False] ``` ### Expected output ```console $ ./test.py --help Usage: test.py [OPTIONS] Options: --multioption TEXT My help --help Show this message and exit. [default: False] ``` ## Environment ### Python version ```console $ python3 --version Python 3.9.2 ``` ### Click version ```console $ python -c "import click; print(click.__version__)" 8.0.1 ``` (I checked that `8.0.2.dev0` is also affected)
2021-06-22T14:00:52Z
[]
[]
pallets/click
1,990
pallets__click-1990
[ "1978" ]
422cb2064eed146dbe03ba3aed5be35daeb70414
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2511,7 +2511,7 @@ def __init__( # flag if flag_value is set. self._flag_needs_value = flag_value is not None - if is_flag and default_is_missing: + if is_flag and default_is_missing and not self.required: self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False if flag_value is None:
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -502,6 +502,15 @@ def test_missing_option_string_cast(): assert str(excinfo.value) == "Missing parameter: a" +def test_missing_required_flag(runner): + cli = click.Command( + "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)] + ) + result = runner.invoke(cli) + assert result.exit_code == 2 + assert "Error: Missing option '--on'." in result.output + + def test_missing_choice(runner): @click.command() @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)
`required=True` does not work for flags When using a flag option, setting `required=True` has no effect unless I also include `default=None`. I would expect there to be no default if the flag is required. **Steps to reproduce:** ``` import click @click.command() @click.option('--foo/--no_foo', is_flag=True, required=True) def bar(foo): pass if __name__ == '__main__': bar() ``` `python test.py` runs without raising an error. I would expect `python test.py` to raise: ``` Usage: test.py [OPTIONS] Try 'test.py --help' for help. Error: Missing option '--foo'. ``` Environment: - Python version: 3.9.5 - Click version: 8.0.1
2021-07-05T16:37:21Z
[]
[]
pallets/click
1,998
pallets__click-1998
[ "1971" ]
68e65ee2bf3e057a99d1192cc256cc2cb2a12203
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2416,25 +2416,26 @@ class Option(Parameter): All other parameters are passed onwards to the parameter constructor. - :param show_default: controls if the default value should be shown on the - help page. Normally, defaults are not shown. If this - value is a string, it shows the string instead of the - value. This is particularly useful for dynamic options. - :param show_envvar: controls if an environment variable should be shown on - the help page. Normally, environment variables - are not shown. - :param prompt: if set to `True` or a non empty string then the user will be - prompted for input. If set to `True` the prompt will be the - option name capitalized. + :param show_default: Controls if the default value should be shown + on the help page. Normally, defaults are not shown. If this + value is a string, it shows that string in parentheses instead + of the actual value. This is particularly useful for dynamic + options. For single option boolean flags, the default remains + hidden if its value is ``False``. + :param show_envvar: Controls if an environment variable should be + shown on the help page. Normally, environment ariables are not + shown. + :param prompt: If set to ``True`` or a non empty string then the + user will be prompted for input. If set to ``True`` the prompt + will be the option name capitalized. :param confirmation_prompt: Prompt a second time to confirm the value if it was prompted for. Can be set to a string instead of ``True`` to customize the message. :param prompt_required: If set to ``False``, the user will be prompted for input only when the option was specified as a flag without a value. - :param hide_input: if this is `True` then the input on the prompt will be - hidden from the user. This is useful for password - input. + :param hide_input: If this is ``True`` then the input on the prompt + will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's @@ -2452,6 +2453,10 @@ class Option(Parameter): :param help: the help string. :param hidden: hide this option from help outputs. + .. versionchanged:: 8.1.0 + The default of a single option boolean flag is not shown if the + default value is ``False``. + .. versionchanged:: 8.0.1 ``type`` is detected from ``flag_value`` if given. """ @@ -2745,6 +2750,8 @@ def _write_opts(opts: t.Sequence[str]) -> str: default_string = split_opt( (self.opts if self.default else self.secondary_opts)[0] )[1] + elif self.is_bool_flag and not self.secondary_opts and not default_value: + default_string = "" else: default_string = str(default_value)
diff --git a/tests/test_formatting.py b/tests/test_formatting.py --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -322,12 +322,13 @@ def cli(): pass result = runner.invoke(cli, ["--help"]) + # the default to "--help" is not shown because it is False assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", "Options:", " -f TEXT Output file name [default: out.txt]", - " --help Show this message and exit. [default: False]", + " --help Show this message and exit.", ] diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -700,16 +700,37 @@ def test_show_default_boolean_flag_name(runner, default, expect): assert f"[default: {expect}]" in message -def test_show_default_boolean_flag_value(runner): - """When a boolean flag only has one opt, it will show the default - value, not the opt name. +def test_show_true_default_boolean_flag_value(runner): + """When a boolean flag only has one opt and its default is True, + it will show the default value, not the opt name. """ opt = click.Option( - ("--cache",), is_flag=True, show_default=True, help="Enable the cache." + ("--cache",), + is_flag=True, + show_default=True, + default=True, + help="Enable the cache.", + ) + ctx = click.Context(click.Command("test")) + message = opt.get_help_record(ctx)[1] + assert "[default: True]" in message + + [email protected]("default", [False, None]) +def test_hide_false_default_boolean_flag_value(runner, default): + """When a boolean flag only has one opt and its default is False or + None, it will not show the default + """ + opt = click.Option( + ("--cache",), + is_flag=True, + show_default=True, + default=default, + help="Enable the cache.", ) ctx = click.Context(click.Command("test")) message = opt.get_help_record(ctx)[1] - assert "[default: False]" in message + assert "[default: " not in message def test_show_default_string(runner):
Consider not showing the default value of boolean flags without a secondary option (False) Unless I'm missing something, the default value of such options should be obvious: `False`. As a consequence, `[default: False]` feels like superfluous noise. This is certainly true for the `--help` option, which should never show a default.
2021-07-08T08:05:52Z
[]
[]
pallets/click
2,004
pallets__click-2004
[ "2001" ]
0905156e0f9b3bb1eabf50173982add053e23ddf
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2853,6 +2853,14 @@ def consume_value( value = self.flag_value source = ParameterSource.COMMANDLINE + elif ( + self.multiple + and value is not None + and any(v is _flag_needs_value for v in value) + ): + value = [self.flag_value if v is _flag_needs_value else v for v in value] + source = ParameterSource.COMMANDLINE + # The value wasn't set, or used the param's default, prompt if # prompting is enabled. elif (
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -792,6 +792,29 @@ def cli(opt, a, b): assert result.return_value == expect +def test_multiple_option_with_optional_value(runner): + cli = click.Command( + "cli", + params=[ + click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True), + click.Option(["-a"]), + click.Argument(["b"], nargs=-1), + ], + callback=lambda **kwargs: kwargs, + ) + result = runner.invoke( + cli, + ["-f", "-f", "other", "-f", "-a", "1", "a", "b"], + standalone_mode=False, + catch_exceptions=False, + ) + assert result.return_value == { + "f": ("flag", "other", "flag"), + "a": "1", + "b": ("a", "b"), + } + + def test_type_from_flag_value(): param = click.Option(["-a", "x"], default=True, flag_value=4) assert param.type is click.INT
Can't set the default value for multiple options with optional values <!-- Describe how to replicate the bug. Include a minimal reproducible example that demonstrates the bug. Include the full traceback if there was an exception. --> The following example combines [optional values](https://click.palletsprojects.com/en/8.0.x/options/#optional-value) with [multiple options](https://click.palletsprojects.com/en/8.0.x/options/#multiple-options): ```python #!/usr/bin/env python3 import click @click.command() @click.option('--label', multiple=True, is_flag=False, flag_value='default') def cli(label): print(label) print(f"click.core._flag_needs_value: {click.core._flag_needs_value}") cli() ``` ``` $ ./test.py --label --label test ('<object object at 0x7f5ef63ec250>', 'test') click.core._flag_needs_value: <object object at 0x7f5ef63ec250> ``` <!-- Describe the expected behavior that should have happened but didn't. --> Expected result: `('default', 'test')` Looks like when `multiple=True`, the sentinel value (`click.core._flag_needs_value`) is never substituted with the default value specified by `flag_value`. Environment: - Python version: 3.7.3 - Click version: 8.0.1
2021-07-13T19:57:03Z
[]
[]
pallets/click
2,006
pallets__click-2006
[ "1921" ]
76cc18d1f0bd5854f14526e3ccbce631d8344cce
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -836,11 +836,20 @@ def convert( if not is_dash: if self.resolve_path: - # realpath on Windows Python < 3.8 doesn't resolve symlinks + # Get the absolute directory containing the path. + dir_ = os.path.dirname(os.path.abspath(rv)) + + # Resolve a symlink. realpath on Windows Python < 3.9 + # doesn't resolve symlinks. This might return a relative + # path even if the path to the link is absolute. if os.path.islink(rv): rv = os.readlink(rv) - rv = os.path.realpath(rv) + # Join dir_ with the resolved symlink. If the resolved + # path is relative, this will make it relative to the + # original containing directory. If it is absolute, this + # has no effect. + rv = os.path.join(dir_, rv) try: st = os.stat(rv) @@ -871,7 +880,7 @@ def convert( param, ctx, ) - if self.writable and not os.access(value, os.W_OK): + if self.writable and not os.access(rv, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( name=self.name.title(), filename=os.fsdecode(value) @@ -879,7 +888,7 @@ def convert( param, ctx, ) - if self.readable and not os.access(value, os.R_OK): + if self.readable and not os.access(rv, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( name=self.name.title(), filename=os.fsdecode(value)
diff --git a/tests/conftest.py b/tests/conftest.py --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,7 @@ +import os +import shutil +import tempfile + import pytest from click.testing import CliRunner @@ -6,3 +10,22 @@ @pytest.fixture(scope="function") def runner(request): return CliRunner() + + +def check_symlink_impl(): + """This function checks if using symlinks is allowed + on the host machine""" + tempdir = tempfile.mkdtemp(prefix="click-") + test_pth = os.path.join(tempdir, "check_sym_impl") + sym_pth = os.path.join(tempdir, "link") + open(test_pth, "w").close() + rv = True + try: + os.symlink(test_pth, sym_pth) + except (NotImplementedError, OSError): + # Creating symlinks on Windows require elevated access. + # OSError is thrown if the function is called without it. + rv = False + finally: + shutil.rmtree(tempdir, ignore_errors=True) + return rv diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1,6 +1,8 @@ +import os.path import pathlib import pytest +from conftest import check_symlink_impl import click @@ -100,3 +102,28 @@ def test_path_type(runner, cls, expect): result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False) assert result.exception is None assert result.return_value == expect + + [email protected](not check_symlink_impl(), reason="symlink not allowed on device") [email protected]( + ("sym_file", "abs_fun"), + [ + (("relative_symlink",), os.path.basename), + (("test", "absolute_symlink"), lambda x: x), + ], +) +def test_symlink_resolution(tmpdir, sym_file, abs_fun): + """This test ensures symlinks are properly resolved by click""" + tempdir = str(tmpdir) + real_path = os.path.join(tempdir, "test_file") + sym_path = os.path.join(tempdir, *sym_file) + + # create dirs and files + os.makedirs(os.path.join(tempdir, "test"), exist_ok=True) + open(real_path, "w").close() + os.symlink(abs_fun(real_path), sym_path) + + # test + ctx = click.Context(click.Command("do_stuff")) + rv = click.Path(resolve_path=True).convert(sym_path, None, ctx) + assert rv == real_path
Regression in click>=8; click.Path says file doesn't exist when it does <!-- This issue tracker is a tool to address bugs in Click itself. Please use Pallets Discord or Stack Overflow for questions about your own code. Replace this comment with a clear outline of what the bug is. --> https://github.com/pallets/click/pull/1825 seems to introduce a regression. A script which worked with `click<8` does not work when upgraded to `click>=8`, and the call to `os.readlink` this PR introduces seems to be the cause. I.e. it looks like fixing symlinks in this case for old Pythons on Windows has broken symlinks for more current Pythons on Linux, however I have not tested as thoroughly as I should be making that claims like that! I have a kubernetes "secret" (could just as easily be a configmap) and these create multiple symlinks do enable atomic replacement of all files in a secret or config map at once. An example secret might look like this: ``` # ls -lart total 0 lrwxrwxrwx 1 root root 14 May 20 14:12 mysecret -> ..data/mysecret lrwxrwxrwx 1 root root 31 May 20 14:12 ..data -> ..2021_05_20_14_12_50.273872148 drwxr-xr-x 2 root root 100 May 20 14:12 ..2021_05_20_14_12_50.273872148 drwxrwxrwt 3 root root 140 May 20 14:12 . drwxr-xr-x 1 root root 50 May 20 14:12 .. ``` (Yes, those files and folders have a `..` prefix which is confusing, and no I can't make kubernetes not do that). Lets say this secret was mounted as `/foo`. Prior to https://github.com/pallets/click/pull/1825, the code would call `os.path.realpath` on `/foo/mysecret` it would resolve the symlink correctly and end up with `/foo/..2021_05_20_14_12_50.273872148/mysecret` After https://github.com/pallets/click/pull/1825, it calls `os.readlink` and gets `..data/mysecret` (not an abspath). When you call `os.path.realpath` on that it prefixes the current directory, so if you are in `/` you get `/..data/tls.crt`. `os.stat` on `/..data/mysecret` fails. But `os.stat` on `/foo/mysecret` does not. So definitely a regression, and I think a wrong behaviour. I think calling `os.readlink` is not a replacement for a proper symlink resolver. Given click only supports Python 3.6 or later, I wonder if using `pathlib.Path(...).resolve()` here would be a better option. It does have a Windows symlink resolver (https://github.com/python/cpython/blob/3.6/Lib/pathlib.py#L181) and a Posix one (https://github.com/python/cpython/blob/3.6/Lib/pathlib.py#L303). Though I don't have a Windows machine to test it out. <!-- Describe how to replicate the bug. Include a minimal reproducible example that demonstrates the bug. Include the full traceback if there was an exception. --> For a reproducer I took the example for `click.Path` from the docs and enabled the resolve_path and exists checks: ``` import click @click.command() @click.argument('filename', type=click.Path(exists=True, resolve_path=True)) def touch(filename): """Print FILENAME if the file exists.""" click.echo(click.format_filename(filename)) if __name__ == '__main__': touch() ``` Then I made an empty file with a symlink pointing to it: ``` # mkdir tst # cd tst # touch foo # ln -s foo bar # ls -rw-r--r-- 1 root root 0 May 20 15:10 foo lrwxrwxrwx 1 root root 3 May 20 15:10 bar -> foo ``` ``` / # /app/bin/python /app/test.py /tst/bar Usage: test.py [OPTIONS] FILENAME Try 'test.py --help' for help. Error: Invalid value for 'FILENAME': Path '/tst/bar' does not exist. ``` However if I downgrade click: ``` / # /app/bin/pip install 'click<8' Collecting click<8 Using cached click-7.1.2-py2.py3-none-any.whl (82 kB) Installing collected packages: click Attempting uninstall: click Found existing installation: click 8.0.1 Uninstalling click-8.0.1: Successfully uninstalled click-8.0.1 Successfully installed click-7.1.2 ``` ``` / # /app/bin/python /app/test.py /tst/bar /tst/foo ``` Because i'm paranoid, i upgraded click again and confirmed the reproducer fails again. It does. <!-- Describe the expected behavior that should have happened but didn't. --> Environment: - Linux (Alpine) - Python version: 3.8.10 - Click version: >8 PS, transcript from running the reproducer on macOS Catalina too, with python 3.9 from brew: ``` % mkdir click-bug % cd click-bug % python3 -m venv venv % source venv/bin/activate (venv) % pip install click Collecting click Downloading click-8.0.1-py3-none-any.whl (97 kB) |████████████████████████████████| 97 kB 5.7 MB/s Installing collected packages: click Successfully installed click-8.0.1 (venv) % mkdir tst (venv) % cd tst (venv) % touch foo (venv) % ln -s foo bar (venv) % cd .. (venv) % vi test.py (venv) % python test.py tst/bar Usage: test.py [OPTIONS] FILENAME Try 'test.py --help' for help. Error: Invalid value for 'FILENAME': Path 'tst/bar' does not exist. (venv) % pip install "click<8" Collecting click<8 Downloading click-7.1.2-py2.py3-none-any.whl (82 kB) |████████████████████████████████| 82 kB 3.0 MB/s Installing collected packages: click Attempting uninstall: click Found existing installation: click 8.0.1 Uninstalling click-8.0.1: Successfully uninstalled click-8.0.1 Successfully installed click-7.1.2 (venv) % python test.py tst/bar /Users/me/click-bug/tst/foo ```
@Jc2k we could as well reproduce reported by you with click "8.0.1" (see https://github.com/dask/distributed/issues/4889) Glad to hear it's not just me. Are you able to test my proposed fix? https://github.com/pallets/click/pull/1825/files adds this: ``` if os.path.islink(rv): rv = os.readlink(rv) ``` to `click/types.py`. What if you replace both lines with just `rv = str(pathlib.Path(rv).resolve())`? This might also get rid of the need for the call to `os.path.realpath` as well but I haven't checked that. Note the module currently doesn't import `pathlib` so you'll need to add an `import pathlib` in `click/types.py` too. Another fix would be to just revert #1825. That PR breaks symlinks on all posix pythons (i think...) to fix it on old windows pythons (AIUI the latest python releases work fine). So in my mind the old way is the better choice going forward, if the maintainers don't like the idea of using pathlib here. See #1813 for the original motivation, Python < 3.8 didn't resolve symlinks on Windows. #1958 seems to indicate even @Jc2k's change wouldn't work as expected for relative links (regardless of platform). I'm inclined to simply revert the change, it seems to cause more issues than it solves. If someone wants to dig into it further and propose a different solution, I'm open to that too. cc @ulope Sounds good to me 👍 @davidism I think @Jc2k 's suggestion should work (as long as the `readlink` call is removed). Whether that will still fix the <3.8 on windows bug 🤷‍♂️ I think the reason I didn't use `Path.resolve` is that it doesn't have the same behavior as `os.path.realpath`, but I can't remember the exact details. If someone wants to submit a PR, there's detail in https://github.com/tiangolo/typer/issues/244#issuecomment-792455309 for checking Windows behavior.
2021-07-15T08:01:06Z
[]
[]
pallets/click
2,030
pallets__click-2030
[ "2017" ]
6aff09eeb48d1d805c903b58ba393565a0cfd3e1
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -46,17 +46,6 @@ V = t.TypeVar("V") -def _fast_exit(code: int) -> "te.NoReturn": - """Low-level exit that skips Python's cleanup but speeds up exit by - about 10ms for things like shell completion. - - :param code: Exit code. - """ - sys.stdout.flush() - sys.stderr.flush() - os._exit(code) - - def _complete_visible_commands( ctx: "Context", incomplete: str ) -> t.Iterator[t.Tuple[str, "Command"]]: @@ -1130,7 +1119,7 @@ def _main_shell_completion( from .shell_completion import shell_complete rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) - _fast_exit(rv) + sys.exit(rv) def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: """Alias for :meth:`main`."""
diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py --- a/tests/test_shell_completion.py +++ b/tests/test_shell_completion.py @@ -1,5 +1,3 @@ -import sys - import pytest from click.core import Argument @@ -265,7 +263,6 @@ def test_completion_item_data(): @pytest.fixture() def _patch_for_completion(monkeypatch): - monkeypatch.setattr("click.core._fast_exit", sys.exit) monkeypatch.setattr( "click.shell_completion.BashComplete._check_version", lambda self: True )
Resource tracker warning on fish completion Issue: I am having the same issue described in #1738 although I am using `fish`. Essentially, I get an error from `resource_tracker.py` related to "leaked semaphore objects," when I run the completion. The completion still works, but the text of the error is garbled along with the completion information before tabbing between options. This does not happen when I use Python 3.7, but does when I use Python 3.8. The error I am getting ends up looking like this after pressing `tab` to get completion text (the third line starting with `❯` is where I pressed `tab`): ``` ---- ❯ poetry shell Spawning shell within ----.p3d-sRVjZJIG-py3.8 source ----.p3d-sRVjZJIG-py3.8/bin/activate.fish Welcome to fish, the friendly interactive shell ---- ❯ source ----.p3d-sRVjZJIG-py3.8/bin/activate.fish ---- ❯ p3d /Users/----/.asdf/installs/python/3.8.8/lib/python3.8/multiprocessing/resource_tracker.py:216: UserWarning: resource_tracker: There appear to be 32 leaked semaphore objects to clean up at shutdownz API calls.) pipeline (Run pipeline processes.) warnings.warn('resource_tracker: There appear to be %d ' ``` Reproduce: I don't have a cut down example that I can provide, but I am wondering if maybe the fact that I am using `poetry` and trying to run completion in a virtualenv is causing an issue? As noted above, this works for Python 3.7 but has an issue with 3.8. I am also using `click-didyoumean` and I manage my Python installations using `asdf`. Expected Behavior: I would expect the same behavior (no error) across different supported versions of Python. Environment: - Python version: 3.8.8 - OS: macOS 10.15.7 - Click version: 8.0.1 - click-didyoumean version: 0.0.3 - asdf version: 0.8.1 - Poetry version: 1.1.7
Closing for the same reason as the linked issue. I can't reproduce this. This does not appear to be an issue with Click, but with something else about your project. @davidism So, I have been trying to track down this error further. I am talking with @Delgan who is the dev for `loguru` which appeared to be where the error was coming from (this is our discussion so far: https://github.com/Delgan/loguru/issues/477). We have actually been able to narrow it down to the use of `multiprocessing.SimpleQueue()` on macOS. This simple test produces the error reliably for me: `cli.py`: ```python #!/usr/bin/env python # -*- coding: utf-8 -*- """Simple example of issue caused by click completion + multiprocessing.SimpleQueue().""" #################################################################################################### # Imports #################################################################################################### # ==Standard Library== import multiprocessing # ==Site-Packages== import click #################################################################################################### # Trigger Issue #################################################################################################### my_queue = multiprocessing.SimpleQueue() #################################################################################################### # Main #################################################################################################### @click.command() def sub_a() -> None: """Subcommand A.""" print("A") @click.command() def sub_b() -> None: """Subcommand B.""" print("B") @click.group("tool") def command() -> None: """Root command group.""" pass # ------------------------------------------------------------------------------------------------ # # Assemble subcommands command.add_command(sub_a) command.add_command(sub_b) ``` `pyproject.toml`: ```toml [tool.poetry] name = "tool" version = "1.0.0" description = "" authors = ["---- <---->"] packages = [ {include = "tool", from = "src"}, ] [tool.poetry.dependencies] python = "^3.7" click = "^8.0.1" [tool.poetry.dev-dependencies] [tool.poetry.scripts] tool = "tool.cli:command" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" ``` `tool.fish`: ```fish #!/usr/bin/env fish function _tool_completion; set -l response; for value in (env _TOOL_COMPLETE=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) tool); set response $response $value; end; for completion in $response; set -l metadata (string split "," $completion); if test $metadata[1] = "dir"; __fish_complete_directories $metadata[2]; else if test $metadata[1] = "file"; __fish_complete_path $metadata[2]; else if test $metadata[1] = "plain"; echo $metadata[2]; end; end; end; complete --no-files --command tool --arguments "(_tool_completion)"; ``` The error only shows up when I try to run the completion. If I run `cli.py` directly, there are no errors. Try replacing this line with `sys.exit()`, that's the only meaningful difference between normal and completion mode that I can think of: https://github.com/pallets/click/blob/ddcabdd4f22f438c0c963150b930d0d09b04dea7/src/click/core.py#L1133 @davidism Hey, that fixed the issue. I can get the error to trigger just by running this simple script: ```python #!/usr/bin/env python # -*- coding: utf-8 -*- import multiprocessing import os import sys my_queue = multiprocessing.SimpleQueue() os._exit(0) ``` The issue definitely appears to be due to some sort of resources not being freed when using `os._exit()` as opposed to the usual `sys.exit()`. Seems like it may have something to do with this (from the `multiprocessing` docs: > Contexts and start methods > Depending on the platform, multiprocessing supports three ways to start a process. These start methods are > > spawn > The parent process starts a fresh python interpreter process. The child process will only inherit those resources necessary to run the process object’s run() method. In particular, unnecessary file descriptors and handles from the parent process will not be inherited. Starting a process using this method is rather slow compared to using fork or forkserver. > > Available on Unix and Windows. The default on Windows and macOS. > > fork > The parent process uses os.fork() to fork the Python interpreter. The child process, when it begins, is effectively identical to the parent process. All resources of the parent are inherited by the child process. Note that safely forking a multithreaded process is problematic. > > Available on Unix only. The default on Unix. > > forkserver > When the program starts and selects the forkserver start method, a server process is started. From then on, whenever a new process is needed, the parent process connects to the server and requests that it fork a new process. The fork server process is single threaded so it is safe for it to use os.fork(). No unnecessary resources are inherited. > > Available on Unix platforms which support passing file descriptors over Unix pipes. Also, this seems to confirm it: > os._exit(n) > Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc. > > Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork(). I feel like we've discussed whether `_fast_exit` was good before, but I can't find the discussion. It sounds like we should remove it, it's bypassing Python cleanup for potentially slightly faster completion responses. Would you mind submitting a PR?
2021-08-03T17:43:32Z
[]
[]
pallets/click
2,041
pallets__click-2041
[ "2040" ]
d251cb0abc9b0dbda2402d4d831c18718cfb51bf
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -292,6 +292,8 @@ def __init__( #: must be never propagated to another arguments. This is used #: to implement nested parsing. self.protected_args: t.List[str] = [] + #: the collected prefixes of the command's options. + self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set() if obj is None and parent is not None: obj = parent.obj @@ -1385,6 +1387,7 @@ def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: ) ctx.args = args + ctx._opt_prefixes.update(parser._opt_prefixes) return args def invoke(self, ctx: Context) -> t.Any: diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -448,17 +448,16 @@ def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: ) -def _start_of_option(value: str) -> bool: +def _start_of_option(ctx: Context, value: str) -> bool: """Check if the value looks like the start of an option.""" if not value: return False c = value[0] - # Allow "/" since that starts a path. - return not c.isalnum() and c != "/" + return c in ctx._opt_prefixes -def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool: +def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool: """Determine if the given parameter is an option that needs a value. :param args: List of complete args before the incomplete value. @@ -467,7 +466,7 @@ def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool: if not isinstance(param, Option): return False - if param.is_flag: + if param.is_flag or param.count: return False last_option = None @@ -476,7 +475,7 @@ def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool: if index + 1 > param.nargs: break - if _start_of_option(arg): + if _start_of_option(ctx, arg): last_option = arg return last_option is not None and last_option in param.opts @@ -551,7 +550,7 @@ def _resolve_incomplete( # split and discard the "=" to make completion easier. if incomplete == "=": incomplete = "" - elif "=" in incomplete and _start_of_option(incomplete): + elif "=" in incomplete and _start_of_option(ctx, incomplete): name, _, incomplete = incomplete.partition("=") args.append(name) @@ -559,7 +558,7 @@ def _resolve_incomplete( # even if they start with the option character. If it hasn't been # given and the incomplete arg looks like an option, the current # command will provide option name completions. - if "--" not in args and _start_of_option(incomplete): + if "--" not in args and _start_of_option(ctx, incomplete): return ctx.command, incomplete params = ctx.command.get_params(ctx) @@ -567,7 +566,7 @@ def _resolve_incomplete( # If the last complete arg is an option name with an incomplete # value, the option will provide value completions. for param in params: - if _is_incomplete_option(args, param): + if _is_incomplete_option(ctx, args, param): return param, incomplete # It's not an option name or value. The first argument without a
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -352,3 +352,62 @@ def deprecated_cmd(): result = runner.invoke(deprecated_cmd) assert "DeprecationWarning:" in result.output + + +def test_command_parse_args_collects_option_prefixes(): + @click.command() + @click.option("+p", is_flag=True) + @click.option("!e", is_flag=True) + def test(p, e): + pass + + ctx = click.Context(test) + test.parse_args(ctx, []) + + assert ctx._opt_prefixes == {"-", "--", "+", "!"} + + +def test_group_parse_args_collects_base_option_prefixes(): + @click.group() + @click.option("~t", is_flag=True) + def group(t): + pass + + @group.command() + @click.option("+p", is_flag=True) + def command1(p): + pass + + @group.command() + @click.option("!e", is_flag=True) + def command2(e): + pass + + ctx = click.Context(group) + group.parse_args(ctx, ["command1", "+p"]) + + assert ctx._opt_prefixes == {"-", "--", "~"} + + +def test_group_invoke_collects_used_option_prefixes(runner): + opt_prefixes = set() + + @click.group() + @click.option("~t", is_flag=True) + def group(t): + pass + + @group.command() + @click.option("+p", is_flag=True) + @click.pass_context + def command1(ctx, p): + nonlocal opt_prefixes + opt_prefixes = ctx._opt_prefixes + + @group.command() + @click.option("!e", is_flag=True) + def command2(e): + pass + + runner.invoke(group, ["command1"]) + assert opt_prefixes == {"-", "--", "~", "+"} diff --git a/tests/test_context.py b/tests/test_context.py --- a/tests/test_context.py +++ b/tests/test_context.py @@ -365,3 +365,11 @@ def cli(ctx, option): rv = runner.invoke(cli, standalone_mode=False, **invoke_args) assert rv.return_value == expect + + +def test_propagate_opt_prefixes(): + parent = click.Context(click.Command("test")) + parent._opt_prefixes = {"-", "--", "!"} + ctx = click.Context(click.Command("test2"), parent=parent) + + assert ctx._opt_prefixes == {"-", "--", "!"} diff --git a/tests/test_parser.py b/tests/test_parser.py --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -1,5 +1,7 @@ import pytest +import click +from click.parser import OptionParser from click.parser import split_arg_string @@ -15,3 +17,16 @@ ) def test_split_arg_string(value, expect): assert split_arg_string(value) == expect + + +def test_parser_default_prefixes(): + parser = OptionParser() + assert parser._opt_prefixes == {"-", "--"} + + +def test_parser_collects_prefixes(): + ctx = click.Context(click.Command("test")) + parser = OptionParser(ctx) + click.Option("+p", is_flag=True).add_to_parser(parser, ctx) + click.Option("!e", is_flag=True).add_to_parser(parser, ctx) + assert parser._opt_prefixes == {"-", "--", "+", "!"} diff --git a/tests/test_shell_completion.py b/tests/test_shell_completion.py --- a/tests/test_shell_completion.py +++ b/tests/test_shell_completion.py @@ -110,6 +110,45 @@ def test_type_choice(): assert _get_words(cli, ["-c"], "a2") == ["a2"] +def test_choice_special_characters(): + cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))]) + assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"] + assert _get_words(cli, ["-c"], "!") == ["!1", "!2"] + assert _get_words(cli, ["-c"], "!2") == ["!2"] + + +def test_choice_conflicting_prefix(): + cli = Command( + "cli", + params=[ + Option(["-c"], type=Choice(["!1", "!2", "+3"])), + Option(["+p"], is_flag=True), + ], + ) + assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"] + assert _get_words(cli, ["-c"], "+") == ["+p"] + + +def test_option_count(): + cli = Command("cli", params=[Option(["-c"], count=True)]) + assert _get_words(cli, ["-c"], "") == [] + assert _get_words(cli, ["-c"], "-") == ["--help"] + + +def test_option_optional(): + cli = Command( + "cli", + add_help_option=False, + params=[ + Option(["--name"], is_flag=False, flag_value="value"), + Option(["--flag"], is_flag=True), + ], + ) + assert _get_words(cli, ["--name"], "") == [] + assert _get_words(cli, ["--name"], "-") == ["--flag"] + assert _get_words(cli, ["--name", "--flag"], "-") == [] + + @pytest.mark.parametrize( ("type", "expect"), [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],
Shell completion fails for option values that start with symbols Running into the same case as #1929, except specific to option values that may start with symbols such as '+', '~', and '!'. Shell completion treats these values as the start of new options, so doesn't complete them. Reproduction script with the cli command referenced by setuptools: ```python @command() @option("-c", type=Choice(["+1", "+2", "!1", "!2"])) def cli(c): echo(f"Value is {c}") ``` With shell completion enabled: ```sh $ click-bug -c <TAB><TAB> +1 +2 !1 !2 $ click-bug -c +<TAB><TAB> # Nothing happens ``` I was looking at the discussion on #1930, and it makes sense that '+' may be considered the start of an option. I'm wondering if it would be valid for completion to prioritize option values over new option names. As in, within shell_completion.py's _resolve_incomplete function, moving the `_is_incomplete_option` check above the `if "--" not in args and _start_of_option(incomplete)` call allows the tab completion in this example to work as expected: ```sh $ click-bug -c +<TAB><TAB> +1 +2 ``` I can look into putting up a PR to do that if it seems valid. Environment: - Python version: 3.6.9 - Click version: 8.0.1
2021-08-09T20:40:27Z
[]
[]
pallets/click
2,084
pallets__click-2084
[ "2072" ]
3e88d3dcadbe357c90059bbaeb691f4a2d20d9e6
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2740,7 +2740,11 @@ def _write_opts(opts: t.Sequence[str]) -> str: if default_string: extra.append(_("default: {default}").format(default=default_string)) - if isinstance(self.type, types._NumberRangeBase): + if ( + isinstance(self.type, types._NumberRangeBase) + # skip count with default range type + and not (self.count and self.type.min == 0 and self.type.max is None) + ): range_str = self.type._describe_range() if range_str:
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -314,13 +314,21 @@ def cmd(username): (click.IntRange(max=32), "x<=32"), ], ) -def test_intrange_default_help_text(runner, type, expect): - option = click.Option(["--count"], type=type, show_default=True, default=2) +def test_intrange_default_help_text(type, expect): + option = click.Option(["--num"], type=type, show_default=True, default=2) context = click.Context(click.Command("test")) result = option.get_help_record(context)[1] assert expect in result +def test_count_default_type_help(): + """A count option with the default type should not show >=0 in help.""" + option = click.Option(["--couunt"], count=True, help="some words") + context = click.Context(click.Command("test")) + result = option.get_help_record(context)[1] + assert result == "some words" + + def test_toupper_envvar_prefix(runner): @click.command() @click.option("--arg")
Help text for `count` options has `[x>=0]` appended Consider this example, taken more or less verbatim from the documentation: ```python import click @click.command() @click.option('-v', '--verbose', count=True, help='Increase verbosity.') def log(verbose): click.echo(f"Verbosity: {verbose}") if __name__ == '__main__': log() ``` The help text for this command is: ``` Usage: count.py [OPTIONS] Options: -v, --verbose Increase verbosity. [x>=0] --help Show this message and exit. ``` I don't know what the `[x>=0]` part is trying to convey, and I think it should not be there. I don't know when Click started adding it, but it was definitely not there with older versions. Environment: - Python version: 3.9.7 - Click version: 8.0.1
Adding `type=int` to the option declaration removed the `[x>=0]` part from the help text, although I think this is more a work around than a solution. If this is how `count` options should be declared, the documentation should be updated.
2021-10-07T14:05:02Z
[]
[]
pallets/click
2,086
pallets__click-2086
[ "2085" ]
f74dbbbca52d02ba2f6fec098cd5778a542e1e18
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2192,6 +2192,9 @@ def get_default( :param call: If the default is a callable, call it. Disable to return the callable instead. + .. versionchanged:: 8.0.2 + Type casting is no longer performed when getting a default. + .. versionchanged:: 8.0.1 Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text. @@ -2207,20 +2210,10 @@ def get_default( if value is None: value = self.default - if callable(value): - if not call: - # Don't type cast the callable. - return value - + if call and callable(value): value = value() - try: - return self.type_cast_value(ctx, value) - except BadParameter: - if ctx.resilient_parsing: - return value - - raise + return value def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: raise NotImplementedError() @@ -2305,8 +2298,7 @@ def value_is_missing(self, value: t.Any) -> bool: return False def process_value(self, ctx: Context, value: t.Any) -> t.Any: - if value is not None: - value = self.type_cast_value(ctx, value) + value = self.type_cast_value(ctx, value) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self)
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -252,7 +252,7 @@ def test_multiple_default_composite_type(): assert isinstance(opt.type, click.Tuple) assert opt.type.types == [click.INT, click.STRING] ctx = click.Context(click.Command("test")) - assert opt.get_default(ctx) == ((1, "a"),) + assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),) def test_parse_multiple_default_composite_type(runner): @@ -323,12 +323,27 @@ def test_intrange_default_help_text(type, expect): def test_count_default_type_help(): """A count option with the default type should not show >=0 in help.""" - option = click.Option(["--couunt"], count=True, help="some words") + option = click.Option(["--count"], count=True, help="some words") context = click.Context(click.Command("test")) result = option.get_help_record(context)[1] assert result == "some words" +def test_file_type_help_default(): + """The default for a File type is a filename string. The string + should be displayed in help, not an open file object. + + Type casting is only applied to defaults in processing, not when + getting the default value. + """ + option = click.Option( + ["--in"], type=click.File(), default=__file__, show_default=True + ) + context = click.Context(click.Command("test")) + result = option.get_help_record(context)[1] + assert __file__ in result + + def test_toupper_envvar_prefix(runner): @click.command() @click.option("--arg")
don't type cast when getting default Click 8 changed the processing pipeline in an effort to be more consistent. Part of that made fetching the default value happen in the same area of code as fetching the value from other sources, then processing whatever value was fetched. However, `get_default` still calls `type_cast_value`, which was a holdover from the previous code. This causes default values to be type cast twice, once when fetching the default value, then again when processing the value. It also causes the default to be type cast when showing the help text, which can lead to unexpected output, such as the string representation of an open file object instead of the filename. In general, custom parameter types *should* still be able to handle being passed a value of the correct type. This can still happen if the default is the correct type, or when prompting (which converts the value to the type for validation before returning), or when passing arguments to `main()` from Python instead of the command line. Fetching the default value should behave more like the other source handled in `consume_value`. Env vars and context defaults are not type cast, so the default should not be either. This should prevent the most common source of issues with existing custom types (although they should still be updated to work as described above). Related to: - #1898 - #1951 - #1976 - #1999 - #2035 - #2081 There are still some other unexpected behaviors, such as type casting `flag_value`, but that will have to be handled separately.
2021-10-08T17:26:32Z
[]
[]
pallets/click
2,093
pallets__click-2093
[ "2092" ]
3737511d399d3910ce65450358f3bde065acf8f1
diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -231,8 +231,10 @@ def confirm( try: # Write the prompt separately so that we get nice # coloring through colorama on Windows - echo(prompt, nl=False, err=err) - value = visible_prompt_func("").lower().strip() + echo(prompt.rstrip(" "), nl=False, err=err) + # Echo a space to stdout to work around an issue where + # readline causes backspace to clear the whole line. + value = visible_prompt_func(" ").lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() from None if value in ("y", "yes"):
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -275,8 +275,8 @@ def emulate_input(text): emulate_input("y\n") click.confirm("Prompt to stderr", err=True) out, err = capfd.readouterr() - assert out == "" - assert err == "Prompt to stderr [y/N]: " + assert out == " " + assert err == "Prompt to stderr [y/N]:" monkeypatch.setattr(click.termui, "isatty", lambda x: True) monkeypatch.setattr(click.termui, "getchar", lambda: " ")
click.confirm does not cooperate with readline This follows on from #665. Consider this code again, using `click.confirm` instead of `click.prompt`: ```python import click, readline click.confirm("Input") ``` - Type anything then backspace - **Actual behaviour:** the entire line is erased - **Expected behaviour:** only the entered character is erased - Type return only - **Actual behaviour:** no newline is printed to the terminal (a following `click.echo()` or `print()` will appear to be ignored) - **Expected behaviour:** a newline is printed to the terminal The solution from PR #1836 seems to work in the case of `click.confirm` as well: ```python while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt.rstrip(" "), nl=False, err=err) value = visible_prompt_func(" ").lower().strip() ``` Environment: - Python version: 3.8.10 - Click version: 8.0.1
Happy to review a PR
2021-10-10T16:14:17Z
[]
[]
pallets/click
2,094
pallets__click-2094
[ "2088" ]
96146c9d0b25d700d00b65c916739bd491dd15e0
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -836,20 +836,11 @@ def convert( if not is_dash: if self.resolve_path: - # Get the absolute directory containing the path. - dir_ = os.path.dirname(os.path.abspath(rv)) - - # Resolve a symlink. realpath on Windows Python < 3.9 - # doesn't resolve symlinks. This might return a relative - # path even if the path to the link is absolute. - if os.path.islink(rv): - rv = os.readlink(rv) - - # Join dir_ with the resolved symlink if the resolved - # path is relative. This will make it relative to the - # original containing directory. - if not os.path.isabs(rv): - rv = os.path.join(dir_, rv) + # os.path.realpath doesn't resolve symlinks on Windows + # until Python 3.8. Use pathlib for now. + import pathlib + + rv = os.fsdecode(pathlib.Path(rv).resolve()) try: st = os.stat(rv)
diff --git a/tests/conftest.py b/tests/conftest.py --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,4 @@ import os -import shutil import tempfile import pytest @@ -12,20 +11,17 @@ def runner(request): return CliRunner() -def check_symlink_impl(): - """This function checks if using symlinks is allowed - on the host machine""" - tempdir = tempfile.mkdtemp(prefix="click-") - test_pth = os.path.join(tempdir, "check_sym_impl") - sym_pth = os.path.join(tempdir, "link") - open(test_pth, "w").close() - rv = True - try: - os.symlink(test_pth, sym_pth) - except (NotImplementedError, OSError): - # Creating symlinks on Windows require elevated access. - # OSError is thrown if the function is called without it. - rv = False - finally: - shutil.rmtree(tempdir, ignore_errors=True) - return rv +def _check_symlinks_supported(): + with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: + target = os.path.join(tempdir, "target") + open(target, "w").close() + link = os.path.join(tempdir, "link") + + try: + os.symlink(target, link) + return True + except OSError: + return False + + +symlinks_supported = _check_symlinks_supported() diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -2,7 +2,7 @@ import pathlib import pytest -from conftest import check_symlink_impl +from conftest import symlinks_supported import click @@ -104,37 +104,27 @@ def test_path_type(runner, cls, expect): assert result.return_value == expect [email protected](not check_symlink_impl(), reason="symlink not allowed on device") [email protected]( - ("sym_file", "abs_fun"), - [ - (("relative_symlink",), os.path.basename), - (("test", "absolute_symlink"), lambda x: x), - ], [email protected]( + not symlinks_supported, reason="The current OS or FS doesn't support symlinks." ) -def test_symlink_resolution(tmpdir, sym_file, abs_fun): - """This test ensures symlinks are properly resolved by click""" - tempdir = str(tmpdir) - real_path = os.path.join(tempdir, "test_file") - sym_path = os.path.join(tempdir, *sym_file) - - # create dirs and files - os.makedirs(os.path.join(tempdir, "test"), exist_ok=True) - open(real_path, "w").close() - os.symlink(abs_fun(real_path), sym_path) - - # test - ctx = click.Context(click.Command("do_stuff")) - rv = click.Path(resolve_path=True).convert(sym_path, None, ctx) - - # os.readlink prepends path prefixes to absolute - # links in windows. - # https://docs.microsoft.com/en-us/windows/win32/ - # ... fileio/naming-a-file#win32-file-namespaces - # - # Here we strip win32 path prefix from the resolved path - rv_drive, rv_path = os.path.splitdrive(rv) - stripped_rv_drive = rv_drive.split(os.path.sep)[-1] - rv = os.path.join(stripped_rv_drive, rv_path) - - assert rv == real_path +def test_path_resolve_symlink(tmp_path, runner): + test_file = tmp_path / "file" + test_file_str = os.fsdecode(test_file) + test_file.write_text("") + + path_type = click.Path(resolve_path=True) + param = click.Argument(["a"], type=path_type) + ctx = click.Context(click.Command("cli", params=[param])) + + test_dir = tmp_path / "dir" + test_dir.mkdir() + + abs_link = test_dir / "abs" + abs_link.symlink_to(test_file) + abs_rv = path_type.convert(os.fsdecode(abs_link), param, ctx) + assert abs_rv == test_file_str + + rel_link = test_dir / "rel" + rel_link.symlink_to(pathlib.Path("..") / "file") + rel_rv = path_type.convert(os.fsdecode(rel_link), param, ctx) + assert rel_rv == test_file_str
8.0.2 doesn't validate paths correctly Path arguments with a directory fail validation with "file not exists", despite existing, when resolve_path=True is specified It looks like the code here concats the passed-in-path to its resolved directory, which means if the path contains a directory, the directory part gets duplicated https://github.com/pallets/click/blob/0a81393fdf41edb0ab9d2f527eccdc8ce38d7d42/src/click/types.py#L852 e.g. ```$ mkdir relative-dir $ touch relative-dir/myfile $ python3 Python 3.9.7 (default, Sep 28 2021, 18:41:28) [GCC 10.2.1 20210110] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from click import Path >>> p = Path(dir_okay=False, exists=True, writable=False, resolve_path=True) >>> p.convert("relative-dir/myfile", None, None) Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/click/types.py", line 855, in convert st = os.stat(rv) FileNotFoundError: [Errno 2] No such file or directory: '/relative-dir/relative-dir/myfile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.9/site-packages/click/types.py", line 859, in convert self.fail( File "/usr/local/lib/python3.9/site-packages/click/types.py", line 128, in fail raise BadParameter(message, ctx=ctx, param=param) click.exceptions.BadParameter: File 'relative-dir/myfile' does not exist. ``` Environment: - Python version: 3.9.7 - Click version: 8.0.2
Seems that the fix for resolving across symlinks caused this. See #1813 (original discussion), #1825 (reverted), #1921 (next discussion), #2006 (currently applied), #2046. Now that I look at the current code again, `os.readlink` really isn't a replacement for `os.path.realpath` the way it's used there, it's only being applied to one directory, not the entire path. Another suggestion was to use `pathlib.Path(rv).resolve()` instead, which has a different implementation than `realpath` which behaves the same on all supported Python versions. Pathlib has some overhead, but I think it's the best solution until we only support Python >= 3.8.
2021-10-10T17:17:54Z
[]
[]
pallets/click
2,095
pallets__click-2095
[ "2090" ]
3dde6c51c5015b7eba552348488c2f7bcaa16c69
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -739,7 +739,9 @@ def invoke( for param in other_cmd.params: if param.name not in kwargs and param.expose_value: - kwargs[param.name] = param.get_default(ctx) # type: ignore + kwargs[param.name] = param.type_cast_value( # type: ignore + ctx, param.get_default(ctx) + ) # Track all kwargs as params, so that forward() will pass # them on in subsequent calls.
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -246,15 +246,17 @@ def cli(ctx): return ctx.invoke(other_cmd) @click.command() - @click.option("--foo", type=click.INT, default=42) + @click.option("-a", type=click.INT, default=42) + @click.option("-b", type=click.INT, default="15") + @click.option("-c", multiple=True) @click.pass_context - def other_cmd(ctx, foo): - assert ctx.info_name == "other-cmd" - click.echo(foo) + def other_cmd(ctx, a, b, c): + return ctx.info_name, a, b, c - result = runner.invoke(cli, []) - assert not result.exception - assert result.output == "42\n" + result = runner.invoke(cli, standalone_mode=False) + # invoke should type cast default values, str becomes int, empty + # multiple should be empty tuple instead of None + assert result.return_value == ("other-cmd", 42, 15, ()) def test_invoked_subcommand(runner):
Type conversion no longer applied to defaults when invoking a default subcommand in 8.0.2 Consider the following code: ```python import click @click.group(invoke_without_command=True) @click.pass_context def main(ctx): if ctx.invoked_subcommand is None: ctx.invoke(ctx.command.commands["foo"]) @main.command() @click.option("--bar", type=int, default="42") def foo(bar): click.echo(repr(bar)) if __name__ == "__main__": main() ``` Prior to Click 8.0.2, this worked correctly; invoking the script with just `python3 scriptname.py` output `42`. However, with the release of v8.0.2, the `type=int` is no longer applied to `--bar`'s default when invoking the command without a subcommand; in that case, the output is `'42'` (a string). (Yes, I know that, in this specific case, it would be better to set `default=42`, but in my actual use-case, the `default` is a callable that does I/O, and I'd like to avoid evaluating it unless it's needed.) Environment: - Python version: 3.9.7 - Click version: 8.0.2
Duplicate of #2089
2021-10-10T17:57:28Z
[]
[]
pallets/click
2,107
pallets__click-2107
[ "2106" ]
41f5b7a7967bb65910e8837bd4e8542a18feec6c
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -388,9 +388,9 @@ def open_stream( ) -> t.Tuple[t.IO, bool]: binary = "b" in mode - # Standard streams first. These are simple because they don't need - # special handling for the atomic flag. It's entirely ignored. - if filename == "-": + # Standard streams first. These are simple because they ignore the + # atomic flag. Use fsdecode to handle Path("-"). + if os.fsdecode(filename) == "-": if any(m in mode for m in ["w", "a", "x"]): if binary: return get_binary_stdout(), False diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -744,26 +744,23 @@ def shell_complete( class Path(ParamType): - """The path type is similar to the :class:`File` type but it performs - different checks. First of all, instead of returning an open file - handle it returns just the filename. Secondly, it can perform various - basic checks about what the file or directory should be. - - :param exists: if set to true, the file or directory needs to exist for - this value to be valid. If this is not required and a - file does indeed not exist, then all further checks are - silently skipped. - :param file_okay: controls if a file is a possible value. - :param dir_okay: controls if a directory is a possible value. - :param writable: if true, a writable check is performed. - :param readable: if true, a readable check is performed. - :param resolve_path: if this is true, then the path is fully resolved - before the value is passed onwards. This means - that it's absolute and symlinks are resolved. It - will not expand a tilde-prefix, as this is - supposed to be done by the shell only. - :param allow_dash: If this is set to `True`, a single dash to indicate - standard streams is permitted. + """The ``Path`` type is similar to the :class:`File` type, but + returns the filename instead of an open file. Various checks can be + enabled to validate the type of file and permissions. + + :param exists: The file or directory needs to exist for the value to + be valid. If this is not set to ``True``, and the file does not + exist, then all further checks are silently skipped. + :param file_okay: Allow a file as a value value. + :param dir_okay: Allow a directory as a value. + :param writable: The file or directory must be writable. + :param readable: The file or directory must be readable. + :param resolve_path: Make the value absolute and resolve any + symlinks. A ``~`` is not expanded, as this is supposed to be + done by the shell only. + :param allow_dash: Allow a single dash as a value, which indicates + a standard stream (but does not open it). Use + :func:`~click.open_file` to handle opening this value. :param path_type: Convert the incoming path value to this type. If ``None``, keep Python's default, which is ``str``. Useful to convert to :class:`pathlib.Path`. diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -340,33 +340,42 @@ def open_file( lazy: bool = False, atomic: bool = False, ) -> t.IO: - """This is similar to how the :class:`File` works but for manual - usage. Files are opened non lazy by default. This can open regular - files as well as stdin/stdout if ``'-'`` is passed. + """Open a file, with extra behavior to handle ``'-'`` to indicate + a standard stream, lazy open on write, and atomic write. Similar to + the behavior of the :class:`~click.File` param type. - If stdin/stdout is returned the stream is wrapped so that the context - manager will not close the stream accidentally. This makes it possible - to always use the function like this without having to worry to - accidentally close a standard stream:: + If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is + wrapped so that using it in a context manager will not close it. + This makes it possible to use the function without accidentally + closing a standard stream: + + .. code-block:: python with open_file(filename) as f: ... - .. versionadded:: 3.0 + :param filename: The name of the file to open, or ``'-'`` for + ``stdin``/``stdout``. + :param mode: The mode in which to open the file. + :param encoding: The encoding to decode or encode a file opened in + text mode. + :param errors: The error handling mode. + :param lazy: Wait to open the file until it is accessed. For read + mode, the file is temporarily opened to raise access errors + early, then closed until it is read again. + :param atomic: Write to a temporary file and replace the given file + on close. - :param filename: the name of the file to open (or ``'-'`` for stdin/stdout). - :param mode: the mode in which to open the file. - :param encoding: the encoding to use. - :param errors: the error handling for this file. - :param lazy: can be flipped to true to open the file lazily. - :param atomic: in atomic mode writes go into a temporary file and it's - moved on close. + .. versionadded:: 3.0 """ if lazy: return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic)) + f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) + if not should_close: f = t.cast(t.IO, KeepOpenFile(f)) + return f
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -120,9 +120,9 @@ def inout(input, output): assert result.exit_code == 0 -def test_path_args(runner): +def test_path_allow_dash(runner): @click.command() - @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True)) + @click.argument("input", type=click.Path(allow_dash=True)) def foo(input): click.echo(input) diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -320,6 +320,22 @@ def cli(filename): assert result.output == "foobar\nmeep\n" +def test_open_file_pathlib_dash(runner): + @click.command() + @click.argument( + "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path) + ) + def cli(filename): + click.echo(str(type(filename))) + + with click.open_file(filename) as f: + click.echo(f.read()) + + result = runner.invoke(cli, ["-"], input="value") + assert result.exception is None + assert result.output == "pathlib.Path\nvalue\n" + + def test_open_file_ignore_errors_stdin(runner): @click.command() @click.argument("filename")
`open_file` doesn't handle `Path("-")` If `click.Path(allow_dash=True, path_type=pathlib.Path)` is used, it can return `pathlib.Path("-")`. Open file only checks `filename == "-"`. If `pathlib.Path("-")` is passed, it will cause a file named `"-"` to be opened instead of a standard stream.
2021-10-25T15:42:28Z
[]
[]
pallets/click
2,151
pallets__click-2151
[ "2149" ]
4262661a0fffabe3803f1bd876b19244f587dafa
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1156,9 +1156,9 @@ class Command(BaseCommand): the command is deprecated. .. versionchanged:: 8.1 - Indentation in ``help`` is cleaned here instead of only in the - ``@command`` decorator. ``epilog`` and ``short_help`` are also - cleaned. + ``help``, ``epilog``, and ``short_help`` are stored unprocessed, + all formatting is done when outputting help text, not at init, + and is done even if not using the ``@command`` decorator. .. versionchanged:: 8.0 Added a ``repr`` showing the command name. @@ -1193,22 +1193,6 @@ def __init__( #: should show up in the help page and execute. Eager parameters #: will automatically be handled before non eager ones. self.params: t.List["Parameter"] = params or [] - - if help: - help = inspect.cleandoc(help) - - # Discard help text after a first form feed (page break) - # character, to allow writing longer documentation in - # docstrings that does not show in help output. - if "\f" in help: - help = help.partition("\f")[0] - - if epilog: - epilog = inspect.cleandoc(epilog) - - if short_help: - short_help = inspect.cleandoc(short_help) - self.help = help self.epilog = epilog self.options_metavar = options_metavar @@ -1316,10 +1300,12 @@ def get_short_help_str(self, limit: int = 45) -> str: """Gets short help for the command or makes it by shortening the long help string. """ - text = self.short_help or "" - - if not text and self.help: + if self.short_help: + text = inspect.cleandoc(self.short_help) + elif self.help: text = make_default_short_help(self.help, limit) + else: + text = "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) @@ -1345,12 +1331,13 @@ def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help text to the formatter if it exists.""" - text = self.help or "" + text = self.help if self.help is not None else "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) if text: + text = inspect.cleandoc(text).partition("\f")[0] formatter.write_paragraph() with formatter.indentation(): @@ -1371,9 +1358,11 @@ def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the epilog into the formatter if it exists.""" if self.epilog: + epilog = inspect.cleandoc(self.epilog) formatter.write_paragraph() + with formatter.indentation(): - formatter.write_text(self.epilog) + formatter.write_text(epilog) def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: if not args and self.no_args_is_help and not ctx.resilient_parsing:
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -95,6 +95,20 @@ def long(): ) +def test_help_truncation(runner): + @click.command() + def cli(): + """This is a command with truncated help. + \f + + This text should be truncated. + """ + + result = runner.invoke(cli, ["--help"]) + assert result.exit_code == 0 + assert "This is a command with truncated help." in result.output + + def test_no_args_is_help(runner): @click.command(no_args_is_help=True) def cli():
Access untruncated help string There's an [open feature request against sphinx-click](https://github.com/click-contrib/sphinx-click/issues/56), asking that we stop ignoring truncation of help strings when generating the documentation. Unfortunately, a quick look suggests [this is not currently possible](https://github.com/click-contrib/sphinx-click/issues/56#issuecomment-988996878) because we don't store the help string before we truncate it. This RFE ask that we provide some mechanism to access the raw help string. I suspect this will involve either (a) storing the "raw" help string in a different attribute or (b) storing this in the `help` attribute and truncating on load rather than on store.
2021-12-09T09:46:06Z
[]
[]
pallets/click
2,158
pallets__click-2158
[ "2157" ]
c01e2b8ed17d3ea65981bc62784363d0e38e3092
diff --git a/src/click/termui.py b/src/click/termui.py --- a/src/click/termui.py +++ b/src/click/termui.py @@ -181,7 +181,8 @@ def prompt_func(text: str) -> str: return result while True: value2 = prompt_func(confirmation_prompt) - if value2: + is_empty = not value and not value2 + if value2 or is_empty: break if value == value2: return result
diff --git a/tests/test_termui.py b/tests/test_termui.py --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -420,17 +420,22 @@ def cli(value, o): @pytest.mark.parametrize( - ("prompt", "input", "expect"), + ("prompt", "input", "default", "expect"), [ - (True, "password\npassword", "password"), - ("Confirm Password", "password\npassword\n", "password"), - (False, None, None), + (True, "password\npassword", None, "password"), + ("Confirm Password", "password\npassword\n", None, "password"), + (True, "", "", ""), + (False, None, None, None), ], ) -def test_confirmation_prompt(runner, prompt, input, expect): +def test_confirmation_prompt(runner, prompt, input, default, expect): @click.command() @click.option( - "--password", prompt=prompt, hide_input=True, confirmation_prompt=prompt + "--password", + prompt=prompt, + hide_input=True, + default=default, + confirmation_prompt=prompt, ) def cli(password): return password
Unable to allow empty str in prompt when confirmation_prompt=True When you use the `click.prompt()` method and you specify `confirmation_prompt=True`, there is no way to allow the user to just hit ENTER (empty str). ```python passphrase = click.prompt( "Create Passphrase", hide_input=True, confirmation_prompt=True, default="" ) ``` Hit ENTER for the first passphrase. Then, when it asks you to confirm, hit ENTER again. It repeats forever and never lets you exit. After hitting ENTER the second time, I expect it to save return `""` as the user's prompt answer. Environment: - Python version: 3.9.7 - Click version: 8.0.3
2021-12-24T00:36:01Z
[]
[]
pallets/click
2,201
pallets__click-2201
[ "2195" ]
deb1f0e1d736774ae17ce423ba452de937ffa402
diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -1,4 +1,5 @@ import os +import re import sys import typing as t from functools import update_wrapper @@ -536,7 +537,7 @@ def _expand_args( See :func:`glob.glob`, :func:`os.path.expanduser`, and :func:`os.path.expandvars`. - This intended for use on Windows, where the shell does not do any + This is intended for use on Windows, where the shell does not do any expansion. It may not exactly match what a Unix shell would do. :param args: List of command line arguments to expand. @@ -544,6 +545,10 @@ def _expand_args( :param env: Expand environment variables. :param glob_recursive: ``**`` matches directories recursively. + .. versionchanged:: 8.1 + Invalid glob patterns are treated as empty expansions rather + than raising an error. + .. versionadded:: 8.0 :meta private: @@ -559,7 +564,10 @@ def _expand_args( if env: arg = os.path.expandvars(arg) - matches = glob(arg, recursive=glob_recursive) + try: + matches = glob(arg, recursive=glob_recursive) + except re.error: + matches = [] if not matches: out.append(arg)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -468,6 +468,8 @@ def test_expand_args(monkeypatch): assert "setup.cfg" in click.utils._expand_args(["*.cfg"]) assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"]) assert "*.not-found" in click.utils._expand_args(["*.not-found"]) + # a bad glob pattern, such as a pytest identifier, should return itself + assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad" @pytest.mark.parametrize(
windows argument expansion is failing with a regex parsing error I'm using pipenv to run pytest which is calling into click and attempting to expand arguments and failing. The command I'm running in context is ```text pipenv run pytest tests/test_thing.py::test_something[e-a] ``` but it can replicated without using pipenv or pytest and produce the same exception. Running ```python from click.utils import _expand_args _expand_args(['tests/test_thing.py::test_something[e-a]']) ``` results in ```text File "C:\Users\xxx\.virtualenvs\xxx-3g_HEZBh\lib\site-packages\click\utils.py", line 572, in _expand_args matches = glob(arg, recursive=glob_recursive) File "C:\Program Files\Python39\lib\glob.py", line 22, in glob return list(iglob(pathname, recursive=recursive)) File "C:\Program Files\Python39\lib\glob.py", line 75, in _iglob for name in glob_in_dir(dirname, basename, dironly): File "C:\Program Files\Python39\lib\glob.py", line 86, in _glob1 return fnmatch.filter(names, pattern) File "C:\Program Files\Python39\lib\fnmatch.py", line 58, in filter match = _compile_pattern(pat) File "C:\Program Files\Python39\lib\fnmatch.py", line 52, in _compile_pattern return re.compile(res).match File "C:\Program Files\Python39\lib\re.py", line 252, in compile return _compile(pattern, flags) File "C:\Program Files\Python39\lib\re.py", line 304, in _compile p = sre_compile.compile(pattern, flags) File "C:\Program Files\Python39\lib\sre_compile.py", line 764, in compile p = sre_parse.parse(p, flags) File "C:\Program Files\Python39\lib\sre_parse.py", line 948, in parse p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0) File "C:\Program Files\Python39\lib\sre_parse.py", line 443, in _parse_sub itemsappend(_parse(source, state, verbose, nested + 1, File "C:\Program Files\Python39\lib\sre_parse.py", line 834, in _parse p = _parse_sub(source, state, sub_verbose, nested + 1) File "C:\Program Files\Python39\lib\sre_parse.py", line 443, in _parse_sub itemsappend(_parse(source, state, verbose, nested + 1, File "C:\Program Files\Python39\lib\sre_parse.py", line 598, in _parse raise source.error(msg, len(this) + 1 + len(that)) re.error: bad character range e-a at position 35 ``` Expected behavior - if expansion fails, treat it as an empty glob match. Something like this but without the bare except catch. ```python def _expand_args(args): from glob import glob out = [] for arg in args: if user: arg = os.path.expanduser(arg) if env: arg = os.path.expandvars(arg) try: matches = glob(arg, recursive=glob_recursive) except: matches = [] if not matches: out.append(arg) else: out.extend(matches) return out ``` Environment: - Python version: 3.9.7 - Click version: 8.0.3
Related to #1901 and #2135
2022-02-21T21:27:48Z
[]
[]
pallets/click
2,203
pallets__click-2203
[ "2131" ]
f6a681adc13d5961073c00e57044e3855c3b76bd
diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -153,6 +153,8 @@ def command( pass the intended name as the first argument. All keyword arguments are forwarded to the underlying command class. + For the ``params`` argument, any decorated params are appended to + the end of the list. Once decorated the function turns into a :class:`Command` instance that can be invoked as a command line utility or be attached to a @@ -165,6 +167,10 @@ def command( .. versionchanged:: 8.1 This decorator can be applied without parentheses. + + .. versionchanged:: 8.1 + The ``params`` argument can be used. Decorated params are + appended to the end of the list. """ if cls is None: cls = Command @@ -179,13 +185,16 @@ def decorator(f: t.Callable[..., t.Any]) -> Command: if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") + attr_params = attrs.pop("params", None) + params = attr_params if attr_params is not None else [] + try: - params = f.__click_params__ # type: ignore + decorator_params = f.__click_params__ # type: ignore except AttributeError: - params = [] + pass else: - params.reverse() del f.__click_params__ # type: ignore + params.extend(reversed(decorator_params)) if attrs.get("help") is None: attrs["help"] = f.__doc__
diff --git a/tests/test_command_decorators.py b/tests/test_command_decorators.py --- a/tests/test_command_decorators.py +++ b/tests/test_command_decorators.py @@ -35,3 +35,17 @@ def cmd2(): result = runner.invoke(grp, ["grp2", "cmd2"]) assert result.exception is None assert result.output == "grp1\ngrp2\ncmd2\n" + + +def test_params_argument(runner): + opt = click.Argument(["a"]) + + @click.command(params=[opt]) + @click.argument("b") + def cli(a, b): + click.echo(f"{a} {b}") + + assert cli.params[0].name == "a" + assert cli.params[1].name == "b" + result = runner.invoke(cli, ["1", "2"]) + assert result.output == "1 2\n"
Allow `params` attribute in decorators Currently it is not possible to pass `params` attribute to `@command()` and `@group()` decorators. This would be really simple implementation, which can be seen in [this forked commit](https://github.com/kristianheljas/click/commit/4e908df69ab11eb333fa14bcf4f3b54b77810ef4) Although, this allows to mix decorator and class patterns, there are a few advantages as well: 1. Share same option spec between (sub)commands (consider CRUD subcommands which all have `--force` option, except `read`) It can be done with nested decorators, which hurt readability 2. Take advantage of IDE auto-completion when using `Option()` class instead of decorator ([PEP-612](https://www.python.org/dev/peps/pep-0612/) would resolve this, but it requires python >=3.10) If this is something to be considered, I can follow up with a PR. Example usage: ```python import click @click.group() def crud(): ... write_args = [ click.Option(['--force'], is_flag=True) ] @crud.command(params=write_args) def create(): ... @crud.command(params=write_args) @click.option('--create', is_flag=True) # Should this be appended or prepended to `write_args`? def update(): ... @crud.command(params=write_args) def delete(): ... @crud.command() def read(): ... ```
2022-02-22T04:08:41Z
[]
[]
pallets/click
2,217
pallets__click-2217
[ "2124" ]
bf9da4838986af3bc09a1b16974d154c61dcbe3f
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1626,11 +1626,11 @@ def _process_result(value: t.Any) -> t.Any: if not ctx.protected_args: if self.invoke_without_command: # No subcommand was invoked, so the result callback is - # invoked with None for regular groups, or an empty list - # for chained groups. + # invoked with the group return value for regular + # groups, or an empty list for chained groups. with ctx: - super().invoke(ctx) - return _process_result([] if self.chain else None) + rv = super().invoke(ctx) + return _process_result([] if self.chain else rv) ctx.fail(_("Missing command.")) # Fetch args back out
diff --git a/tests/test_chain.py b/tests/test_chain.py --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -85,20 +85,20 @@ def bdist(format): assert result.output.splitlines() == ["bdist called 1", "sdist called 2"] [email protected](("chain", "expect"), [(False, "None"), (True, "[]")]) [email protected](("chain", "expect"), [(False, "1"), (True, "[]")]) def test_no_command_result_callback(runner, chain, expect): """When a group has ``invoke_without_command=True``, the result callback is always invoked. A regular group invokes it with - ``None``, a chained group with ``[]``. + its return value, a chained group with ``[]``. """ @click.group(invoke_without_command=True, chain=chain) def cli(): - pass + return 1 @cli.result_callback() def process_result(result): - click.echo(str(result), nl=False) + click.echo(result, nl=False) result = runner.invoke(cli, []) assert result.output == expect
group return value is ignored Calling a command defined as `@click.group()` with `standalone_mode=False` does not propagate the return value as expected. For instance: ```python import click import sys @click.group(invoke_without_command=True) @click.option("-l", "--local-configuration", type=str) def main(local_configuration): print('Inside main') return 1 if __name__ == '__main__': print(main(sys.argv[1:], standalone_mode=False)) ``` ``` $ python test.py Inside main None ``` It does work when the command is defined with `@click.command()`, hence I suppose this is a bug. Environment: - Python version: 3.7.5 - Click version: 8.0.3
Thanks for opening the issue, I ran a git bisect to see where this behavior changed. It showed https://github.com/pallets/click/commit/079f91a2396c5c9264f34f95894259b7b15eb89c as when the behavior changed I'm not sure why moving to a src directory would cause this. It seems related to https://github.com/pallets/click/blob/d5932d674d804cf67b20e4f1c3546abf5aa65494/src/click/core.py#L1633-L1638 where return value of `super().invoke(ctx)` is replaced with `[]` or `None` before passed to `_process_result`. Return value propagation (without subcommand invocation) stops here with `invoke_without_command=True`, regardless of `standalone_mode`. Not sure what to do with this one. The difference in behavior between groups and commands wasn't documented, and it's not clear why group returns weren't used when adding support for command return values. I think it could make sense to use the group's return value as well though. The problem is making sure existing code continues to work after the change, at least for a deprecation period. The return value of a command is the return value, if any. The return value of a *group* is the result of calling its `result_callback` on the return value(s) of it subcommand(s). `result_callback` only gets the subcommand result, it won't get a value returned by the group itself. * A group can be invoked without a subcommand, and returns a value. Would the value be returned directly, or still passed through the result callback? What if the callback only expects values returned by subcommands? * A subcommand is required, and only the subcommand returns a value. This is the current expected behavior. * A subcommand is required, and both the group and the subcommand return values. This is tricky because the result callback would only be expecting one value based on current behavior. Should the subcommand value overwrite the group value? * The group is in chain mode, the return value of each subcommand is collected in a list. Should the return value of the group be the first item in the list? What if the group doesn't return anything, and the result callback expects that every item is not None (that's how the example in the docs works)? A possible solution that sidesteps the questions above: only use the group return value if invoked without subcommand. That is, if the group is treated like a command itself, return its value as if it were a command. Regardless of the solution, the behavior of return values needs to be much better documented. For now, you could add a result callback to the group that returns what you would have returned from the group if it was used without a subcommand. ```python @main.result_callback @click.pass_context def group_result(ctx, value): if ctx.invoked_subcommand is None: return 1 ``` For #1178, in 8.0 we changed the behavior so that the result callback was called even if there was no subcommand, passing `None`. Previously, the group return value *was* returned, as long as the group wasn't in chain mode and was called without a subcommand. In chain mode, the group return was always ignored since the intention in that mode was to have a pipeline of return values. The behavior before 8.0 was basically what I just described as a possible solution to this issue. Now that I've looked over this more, I think that makes more sense, I think the change should be reverted in 8.1. A compromise that should satisfy that issue and this one would be to pass the group return value to the result callback if it's invoked directly. As shown in the workaround I posted above, you can tell whether the value is from a subcommand or not based on `ctx.invoked_subcommand`.
2022-03-19T18:03:57Z
[]
[]
pallets/click
2,219
pallets__click-2219
[ "2168" ]
19be092b6db4e4300e31906498e354ec0adf870c
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -63,7 +63,14 @@ def to_info_dict(self) -> t.Dict[str, t.Any]: # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] - return {"param_type": param_type, "name": self.name} + + # Custom subclasses might not remember to set a name. + if hasattr(self, "name"): + name = self.name + else: + name = param_type + + return {"param_type": param_type, "name": name} def __call__( self,
diff --git a/tests/test_info_dict.py b/tests/test_info_dict.py --- a/tests/test_info_dict.py +++ b/tests/test_info_dict.py @@ -266,3 +266,10 @@ def test_context(): "ignore_unknown_options": False, "auto_envvar_prefix": None, } + + +def test_paramtype_no_name(): + class TestType(click.ParamType): + pass + + assert TestType().to_info_dict()["name"] == "TestType"
`ParamType` missing `name` errors on `to_info_dict` When calling `to_info_dict` on a `ParamType` instance which doesn't have a `name` attribute, an exception is raised. While this is a bug in the downstream code, only `to_info_dict` is affected, so the bug often goes unnoticed. ```py3 class TestType(click.ParamType): pass TestType().to_info_dict() ``` ``` > return {"param_type": param_type, "name": self.name} E AttributeError: 'TestType' object has no attribute 'name' src/click/types.py:66: AttributeError ``` It would be nice to have some sort of reasonable fallback. I've put coded such possibility at https://github.com/pallets/click/compare/main...phy1729:fix-ParamType-no-name . I also fixed where the docs neglected to specify `name` in an example. Environment: - Python version: Python 3.9.9 - Click version: 8.0.3
2022-03-19T18:28:51Z
[]
[]
pallets/click
2,223
pallets__click-2223
[ "2146" ]
ef11be6e49e19a055fe7e5a89f0f1f4062c68dba
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2834,7 +2834,10 @@ def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" rv = os.environ.get(envvar) - return rv + if rv: + return rv + + return None def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]: rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -153,14 +153,15 @@ def test_init_bad_default_list(runner, multiple, nargs, default): click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default) -def test_empty_envvar(runner): [email protected]("env_key", ["MYPATH", "AUTO_MYPATH"]) +def test_empty_envvar(runner, env_key): @click.command() @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH") def cli(mypath): click.echo(f"mypath: {mypath}") - result = runner.invoke(cli, [], env={"MYPATH": ""}) - assert result.exit_code == 0 + result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO") + assert result.exception is None assert result.output == "mypath: None\n"
Inconsistent handling of option values from environment variables There are 2 ways of configuring Click to load a value of a specific option from an environment variable: "automatic" via `auto_envvar_prefix` and "explicit" via passing `envvar` keyword argument to the option definition. When a name of an environment variable is set explicitly, Click treats empty string values (i.e. `export MY_OPTION=`) as not set and keeps a default value (`None` if not configured otherwise). But when a name is inferred from `auto_envvar_prefix` configuration, Click treats empty string values as valid values, does not set a default and passes the option to `ParamType.convert()` if `type` keyword argument is specified for that option. This is inconsistent. ```python import click @click.command() @click.option('--auto') @click.option('--ex', envvar="EXEV") def cli(auto, ex): click.echo(f"{auto=} {type(auto)=}") click.echo(f"{ex=} {type(ex)=}") if __name__ == '__main__': cli(auto_envvar_prefix='MY') ``` Actual output: ```shell $ MY_AUTO= EXEV= ./cli.py auto='' type(auto)=<class 'str'> ex=None type(ex)=<class 'NoneType'> ``` Expected output: ```shell $ MY_AUTO= EXEV= ./cli.py auto=None type(auto)=<class 'NoneType'> ex=None type(ex)=<class 'NoneType'> ``` Environment: - Python version: `3.9.7` - Click version: `8.0.3` It's being a nuisance for quite a while at my company, we have `.env.example` file with variables containing multiple `export FOO=` lines for each project. When my colleagues work on the project, they just copy `.env.example` to `.env`, fill out required values (not all of the values) and then do a test run. Then for variables like export `OPTIONAL_VALUE=` that are left as is, click loads them as empty strings and calls type validators `TypeInstance.convert()` with that value, which usually fails as an empty string is not a valid value for the majority of options. Now when I go diving into the code base, it seems like it's handled "correctly" here: https://github.com/pallets/click/blob/6411f425fae545f42795665af4162006b36c5e4a/src/click/core.py#L2267-L2283 (i.e. if value is an empty string, `None` is returned) But then here it is fetched as is without checking for an empty string: https://github.com/pallets/click/blob/6411f425fae545f42795665af4162006b36c5e4a/src/click/core.py#L2777-L2783 The most obvious fix would be to add the following 2 lines ``` python if rv: return rv ``` after https://github.com/pallets/click/blob/6411f425fae545f42795665af4162006b36c5e4a/src/click/core.py#L2783
This seems reasonable to me, I would go ahead and make a PR. Previous PRs were merged to make empty env vars be treated as None: * https://github.com/pallets/click/pull/1304 * https://github.com/pallets/click/pull/1687
2022-03-28T17:22:01Z
[]
[]
pallets/click
2,248
pallets__click-2248
[ "2246" ]
afdfb120fff5cb5f8d0184d411369f5dddaed5b3
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2580,6 +2580,9 @@ def __init__( if self.is_flag: raise TypeError("'count' is not valid with 'is_flag'.") + if self.multiple and self.is_flag: + raise TypeError("'multiple' is not valid with 'is_flag', use 'count'.") + def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = super().to_info_dict() info_dict.update(
diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -904,3 +904,21 @@ def test_type_from_flag_value(): ) def test_is_bool_flag_is_correctly_set(option, expected): assert option.is_bool_flag is expected + + [email protected]( + ("kwargs", "message"), + [ + ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."), + ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."), + ( + {"multiple": True, "is_flag": True}, + "'multiple' is not valid with 'is_flag', use 'count'.", + ), + ], +) +def test_invalid_flag_combinations(runner, kwargs, message): + with pytest.raises(TypeError) as e: + click.Option(["-a"], **kwargs) + + assert message in str(e.value)
Flags with `multiple=True` trigger `TypeError` Adding an option with `is_flag=True` and `multiple=True` will trigger a `TypeError` in `Parameter.consume_value()` due to bad default value. ```py import click @click.command() @click.option("-v", is_flag=True, multiple=True) def main(v): click.echo(v) if __name__ == "__main__": main() ``` When run without the flag, a TypeError is raised: ``` (venv39) jreese@butterfree ~/scratch » python foo.py Traceback (most recent call last): File "/Users/jreese/scratch/foo.py", line 25, in <module> main() File "/Users/jreese/scratch/venv39/lib/python3.9/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/Users/jreese/scratch/venv39/lib/python3.9/site-packages/click/core.py", line 1054, in main with self.make_context(prog_name, args, **extra) as ctx: File "/Users/jreese/scratch/venv39/lib/python3.9/site-packages/click/core.py", line 920, in make_context self.parse_args(ctx, args) File "/Users/jreese/scratch/venv39/lib/python3.9/site-packages/click/core.py", line 1378, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/Users/jreese/scratch/venv39/lib/python3.9/site-packages/click/core.py", line 2356, in handle_parse_result value, source = self.consume_value(ctx, opts) File "/Users/jreese/scratch/venv39/lib/python3.9/site-packages/click/core.py", line 2903, in consume_value and any(v is _flag_needs_value for v in value) TypeError: 'bool' object is not iterable ``` Manually setting a better default value, like `default=()`, avoids the type error, but this used to work on 7.x without setting the default value. Environment: - Python version: tested on 3.8.6 and 3.9.3 - Click version: worked on 7.1.2; errors on 8.0.4 and 8.1.2
2022-04-05T19:59:01Z
[]
[]
pallets/click
2,269
pallets__click-2269
[ "2268" ]
6c3a1fcc19963bcc9422bf98f1c56108193ab232
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -367,7 +367,7 @@ def get_text_stderr( def _wrap_io_open( - file: t.Union[str, "os.PathLike[t.AnyStr]", int], + file: t.Union[str, "os.PathLike[str]", int], mode: str, encoding: t.Optional[str], errors: t.Optional[str], diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -10,6 +10,7 @@ import time import typing as t from gettext import gettext as _ +from types import TracebackType from ._compat import _default_text_stdout from ._compat import CYGWIN @@ -59,15 +60,15 @@ def __init__( self.show_percent = show_percent self.show_pos = show_pos self.item_show_func = item_show_func - self.label = label or "" + self.label: str = label or "" if file is None: file = _default_text_stdout() self.file = file self.color = color self.update_min_steps = update_min_steps self._completed_intervals = 0 - self.width = width - self.autowidth = width == 0 + self.width: int = width + self.autowidth: bool = width == 0 if length is None: from operator import length_hint @@ -80,17 +81,19 @@ def __init__( if length is None: raise TypeError("iterable or length is required") iterable = t.cast(t.Iterable[V], range(length)) - self.iter = iter(iterable) + self.iter: t.Iterable[V] = iter(iterable) self.length = length self.pos = 0 self.avg: t.List[float] = [] + self.last_eta: float + self.start: float self.start = self.last_eta = time.time() - self.eta_known = False - self.finished = False + self.eta_known: bool = False + self.finished: bool = False self.max_width: t.Optional[int] = None - self.entered = False + self.entered: bool = False self.current_item: t.Optional[V] = None - self.is_hidden = not isatty(self.file) + self.is_hidden: bool = not isatty(self.file) self._last_line: t.Optional[str] = None def __enter__(self) -> "ProgressBar[V]": @@ -98,7 +101,12 @@ def __enter__(self) -> "ProgressBar[V]": self.render_progress() return self - def __exit__(self, *_: t.Any) -> None: + def __exit__( + self, + exc_type: t.Optional[t.Type[BaseException]], + exc_value: t.Optional[BaseException], + tb: t.Optional[TracebackType], + ) -> None: self.render_finish() def __iter__(self) -> t.Iterator[V]: diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -7,11 +7,11 @@ from collections import abc from contextlib import contextmanager from contextlib import ExitStack -from functools import partial from functools import update_wrapper from gettext import gettext as _ from gettext import ngettext from itertools import repeat +from types import TracebackType from . import types from .exceptions import Abort @@ -455,7 +455,12 @@ def __enter__(self) -> "Context": push_context(self) return self - def __exit__(self, *_: t.Any) -> None: + def __exit__( + self, + exc_type: t.Optional[t.Type[BaseException]], + exc_value: t.Optional[BaseException], + tb: t.Optional[TracebackType], + ) -> None: self._depth -= 1 if self._depth == 0: self.close() @@ -2097,10 +2102,13 @@ def __init__( ] ] = None, ) -> None: + self.name: t.Optional[str] + self.opts: t.List[str] + self.secondary_opts: t.List[str] self.name, self.opts, self.secondary_opts = self._parse_decls( param_decls or (), expose_value ) - self.type = types.convert_type(type, default) + self.type: types.ParamType = types.convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. @@ -2300,17 +2308,18 @@ def check_iter(value: t.Any) -> t.Iterator[t.Any]: ) from None if self.nargs == 1 or self.type.is_composite: - convert: t.Callable[[t.Any], t.Any] = partial( - self.type, param=self, ctx=ctx - ) + + def convert(value: t.Any) -> t.Any: + return self.type(value, param=self, ctx=ctx) + elif self.nargs == -1: - def convert(value: t.Any) -> t.Tuple[t.Any, ...]: + def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...] return tuple(self.type(x, self, ctx) for x in check_iter(value)) else: # nargs > 1 - def convert(value: t.Any) -> t.Tuple[t.Any, ...]: + def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...] value = tuple(check_iter(value)) if len(value) != self.nargs: @@ -2564,13 +2573,14 @@ def __init__( if flag_value is None: flag_value = not self.default + self.type: types.ParamType if is_flag and type is None: # Re-guess the type from the flag value instead of the # default. self.type = types.convert_type(None, flag_value) self.is_flag: bool = is_flag - self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType) + self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType) self.flag_value: t.Any = flag_value # Counting diff --git a/src/click/exceptions.py b/src/click/exceptions.py --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -7,6 +7,7 @@ from .utils import echo if t.TYPE_CHECKING: + from .core import Command from .core import Context from .core import Parameter @@ -57,7 +58,7 @@ class UsageError(ClickException): def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: super().__init__(message) self.ctx = ctx - self.cmd = self.ctx.command if self.ctx else None + self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: @@ -261,7 +262,7 @@ def __init__(self, filename: str, hint: t.Optional[str] = None) -> None: hint = _("unknown error") super().__init__(hint) - self.ui_filename = os.fsdecode(filename) + self.ui_filename: str = os.fsdecode(filename) self.filename = filename def format_message(self) -> str: @@ -284,4 +285,4 @@ class Exit(RuntimeError): __slots__ = ("exit_code",) def __init__(self, code: int = 0) -> None: - self.exit_code = code + self.exit_code: int = code diff --git a/src/click/parser.py b/src/click/parser.py --- a/src/click/parser.py +++ b/src/click/parser.py @@ -168,7 +168,7 @@ def __init__( ): self._short_opts = [] self._long_opts = [] - self.prefixes = set() + self.prefixes: t.Set[str] = set() for opt in opts: prefix, value = split_opt(opt) @@ -194,7 +194,7 @@ def __init__( def takes_value(self) -> bool: return self.action in ("store", "append") - def process(self, value: str, state: "ParsingState") -> None: + def process(self, value: t.Any, state: "ParsingState") -> None: if self.action == "store": state.opts[self.dest] = value # type: ignore elif self.action == "store_const": @@ -272,12 +272,12 @@ def __init__(self, ctx: t.Optional["Context"] = None) -> None: #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. - self.allow_interspersed_args = True + self.allow_interspersed_args: bool = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. - self.ignore_unknown_options = False + self.ignore_unknown_options: bool = False if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -80,9 +80,9 @@ def __init__( help: t.Optional[str] = None, **kwargs: t.Any, ) -> None: - self.value = value - self.type = type - self.help = help + self.value: t.Any = value + self.type: str = type + self.help: t.Optional[str] = help self._info = kwargs def __getattr__(self, name: str) -> t.Any: @@ -517,6 +517,8 @@ def _resolve_context( ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True) args = ctx.protected_args + ctx.args else: + sub_ctx = ctx + while args: name, cmd, args = command.resolve_command(ctx, args) diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -162,7 +162,7 @@ def arity(self) -> int: # type: ignore class FuncParamType(ParamType): def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None: - self.name = func.__name__ + self.name: str = func.__name__ self.func = func def to_info_dict(self) -> t.Dict[str, t.Any]: @@ -353,7 +353,11 @@ class DateTime(ParamType): name = "datetime" def __init__(self, formats: t.Optional[t.Sequence[str]] = None): - self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"] + self.formats: t.Sequence[str] = formats or [ + "%Y-%m-%d", + "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%d %H:%M:%S", + ] def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = super().to_info_dict() @@ -662,7 +666,7 @@ class File(ParamType): """ name = "filename" - envvar_list_splitter = os.path.pathsep + envvar_list_splitter: t.ClassVar[str] = os.path.pathsep def __init__( self, @@ -780,7 +784,7 @@ class Path(ParamType): Added the ``allow_dash`` parameter. """ - envvar_list_splitter = os.path.pathsep + envvar_list_splitter: t.ClassVar[str] = os.path.pathsep def __init__( self, @@ -805,7 +809,7 @@ def __init__( self.type = path_type if self.file_okay and not self.dir_okay: - self.name = _("file") + self.name: str = _("file") elif self.dir_okay and not self.file_okay: self.name = _("directory") else: @@ -942,7 +946,7 @@ class Tuple(CompositeParamType): """ def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None: - self.types = [convert_type(ty) for ty in types] + self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types] def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = super().to_info_dict() diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -4,6 +4,7 @@ import typing as t from functools import update_wrapper from types import ModuleType +from types import TracebackType from ._compat import _default_text_stderr from ._compat import _default_text_stdout @@ -124,6 +125,7 @@ def __init__( self.errors = errors self.atomic = atomic self._f: t.Optional[t.IO[t.Any]] + self.should_close: bool if filename == "-": self._f, self.should_close = open_stream(filename, mode, encoding, errors) @@ -177,7 +179,12 @@ def close_intelligently(self) -> None: def __enter__(self) -> "LazyFile": return self - def __exit__(self, *_: t.Any) -> None: + def __exit__( + self, + exc_type: t.Optional[t.Type[BaseException]], + exc_value: t.Optional[BaseException], + tb: t.Optional[TracebackType], + ) -> None: self.close_intelligently() def __iter__(self) -> t.Iterator[t.AnyStr]: @@ -187,7 +194,7 @@ def __iter__(self) -> t.Iterator[t.AnyStr]: class KeepOpenFile: def __init__(self, file: t.IO[t.Any]) -> None: - self._file = file + self._file: t.IO[t.Any] = file def __getattr__(self, name: str) -> t.Any: return getattr(self._file, name) @@ -195,7 +202,12 @@ def __getattr__(self, name: str) -> t.Any: def __enter__(self) -> "KeepOpenFile": return self - def __exit__(self, *_: t.Any) -> None: + def __exit__( + self, + exc_type: t.Optional[t.Type[BaseException]], + exc_value: t.Optional[BaseException], + tb: t.Optional[TracebackType], + ) -> None: pass def __repr__(self) -> str:
diff --git a/src/click/testing.py b/src/click/testing.py --- a/src/click/testing.py +++ b/src/click/testing.py @@ -183,7 +183,7 @@ def __init__( mix_stderr: bool = True, ) -> None: self.charset = charset - self.env = env or {} + self.env: t.Mapping[str, t.Optional[str]] = env or {} self.echo_stdin = echo_stdin self.mix_stderr = mix_stderr
fix `pyright --verifytypes` findings Pyright returns different findings than mypy, and can be more strict in some cases. Users are seeing these issue because vscode python uses pyright. Run the following command to see findings and address them: ``` pip install pyright pyright --verifytypes click ```
I'll take this
2022-05-02T20:14:06Z
[]
[]
pallets/click
2,312
pallets__click-2312
[ "2294" ]
c77966e092edc9b8835e7327294b9177059fc90e
diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -329,7 +329,9 @@ def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: f.__click_params__.append(param) # type: ignore -def argument(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]: +def argument( + *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any +) -> _Decorator[FC]: """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). @@ -345,16 +347,19 @@ def argument(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]: ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ + if cls is None: + cls = Argument def decorator(f: FC) -> FC: - ArgumentClass = attrs.pop("cls", None) or Argument - _param_memo(f, ArgumentClass(param_decls, **attrs)) + _param_memo(f, cls(param_decls, **attrs)) return f return decorator -def option(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]: +def option( + *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any +) -> _Decorator[FC]: """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). @@ -370,12 +375,11 @@ def option(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]: ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ + if cls is None: + cls = Option def decorator(f: FC) -> FC: - # Issue 926, copy attrs, so pre-defined options can re-use the same cls= - option_attrs = attrs.copy() - OptionClass = option_attrs.pop("cls", None) or Option - _param_memo(f, OptionClass(param_decls, **option_attrs)) + _param_memo(f, cls(param_decls, **attrs)) return f return decorator
diff --git a/tests/test_arguments.py b/tests/test_arguments.py --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -381,3 +381,23 @@ def subcmd(): result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"]) assert not result.exception assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output + + +def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved(): + class CustomArgument(click.Argument): + pass + + reusable_argument = click.argument("art", cls=CustomArgument) + + @click.command() + @reusable_argument + def foo(arg): + pass + + @click.command() + @reusable_argument + def bar(arg): + pass + + assert isinstance(foo.params[0], CustomArgument) + assert isinstance(bar.params[0], CustomArgument)
Parameter decorator factories shouldn't pop `cls` from `attrs` Popping `cls` introduces a side-effect that prevents the reuse of the returned decorator. For example, consider the code below. The function `my_shared_argument` is a decorator that is expected to register an argument of type `ArgumentWithHelp`. Instead, what happens is: - the first time the decorator is used, `cls=ArgumentWithHelp` will be popped from `attrs` -> `attrs` is now modified in-place - the following times the decorator is used, `cls` won't be in `attrs`. ```python import click class ArgumentWithHelp(click.Argument): def __init__(self, *args, help=None, **attrs): super().__init__(*args, **attrs) self.help = help def argument_with_help(*args, cls=ArgumentWithHelp, **kwargs): return click.argument(*args, cls=cls, **kwargs) my_shared_argument = argument_with_help("pippo", help="very useful help") @click.command() @my_shared_argument def foo(pippo): print(pippo) @click.command() @my_shared_argument def bar(pippo): print(pippo) ``` Running this file as it is: ```python Traceback (most recent call last): File "C:/Users/sboby/AppData/Roaming/JetBrains/PyCharmCE2022.1/scratches/scratch_4.py", line 27, in <module> def bar(pippo): File "H:\Repo\unbox\UnboxTranslate\venv\lib\site-packages\click\decorators.py", line 287, in decorator _param_memo(f, ArgumentClass(param_decls, **attrs)) File "H:\Repo\unbox\UnboxTranslate\venv\lib\site-packages\click\core.py", line 2950, in __init__ super().__init__(param_decls, required=required, **attrs) TypeError: __init__() got an unexpected keyword argument 'help' Process finished with exit code 1 ``` <strike>The `@option` decorator is affected by the same problem but it won't crash in a similar situation because `click.Option.__init__` ignore extra arguments: it will just silently use `click.Option` as class.</strike> The `@option` decorator is actually not affected because `attrs` is copied. This copy is nonetheless unnecessary, since adding `cls` to the signature of the function would be a more straightforward solution. Environment: - Python version: irrelevant - Click version: 8.1.3 (but all versions are affected)
2022-06-18T22:37:29Z
[]
[]
pallets/click
2,333
pallets__click-2333
[ "2332" ]
6e704050f1149b00f3b3e7576e25b1e28c76ccf3
diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -523,7 +523,8 @@ def _detect_program_name( # The value of __package__ indicates how Python was called. It may # not exist if a setuptools script is installed as an egg. It may be # set incorrectly for entry points created with pip on Windows. - if getattr(_main, "__package__", None) is None or ( + # It is set to "" inside a Shiv or PEX zipapp. + if getattr(_main, "__package__", None) in {None, ""} or ( os.name == "nt" and _main.__package__ == "" and not os.path.exists(path)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -446,6 +446,7 @@ def __init__(self, package_name): ("example", None, "example"), (str(pathlib.Path("example/__main__.py")), "example", "python -m example"), (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"), + (str(pathlib.Path("./example")), "", "example"), ], ) def test_detect_program_name(path, main, expected):
Invalid info_name with shiv and pex ## Summary When Click is used inside zipapps produced by Shiv or PEX, it displays an invalid "Usage" string. Instead of "Usage: program" it says "Usage: python -m program". I did some digging and found that this is due to *info_name* being guessed incorrectly in the code introduced by #1609. There is a [test for `__package__` being set to `None`](https://github.com/MLH-Fellowship/click/blob/faaec8294eb819e9f8e6f568ae81b711a861ebbe/src/click/utils.py#L470); however, in the case when the script is run inside Shiv or PEX, `__package__` is instead set to the empty string (""). This is allowed by PEP 366: > Note that setting __package__ to the empty string explicitly is permitted, and has the effect of disabling all relative imports from that module (since the import machinery will consider it to be a top level module in that case). ## Reproducing Follow the basic [Shiv hello world example](https://shiv.readthedocs.io/en/latest/#hello-world), but add Click: _hello.py_: ```python import click @click.command() def main(): print("Hello world") if __name__ == "__main__": main() ``` _setup.py_: ```python from setuptools import setup setup( name="hello-world", version="0.0.1", description="Greet the world.", py_modules=["hello"], entry_points={ "console_scripts": ["hello=hello:main"], }, install_requires=['Click==8.1.3'], ) ``` Build the executable zipapps and run them: ```text $ shiv . -c hello -o hello1.pyz $ pex . -c hello -o hello2.pyz $ ./hello1.pyz --help Usage: python -m hello1 [OPTIONS] $ ./hello2.pyz foo Usage: python -m hello2 [OPTIONS] Try 'python -m hello2 --help' for help. ``` ## Expected behavior Click should not print the Usage string as "python -m hello"; it should just be "hello". ## Environment: - Python version: 3.10.5 - Click version: 8.1.3 - Shiv version: 1.0.1 - Pex version: 2.1.102
If you know you're packaging your app with those tools, you can set the program name directly: ```python main(prog_name="my-command") ```
2022-08-02T16:25:33Z
[]
[]
pallets/click
2,369
pallets__click-2369
[ "2368" ]
a4f5450a2541e2f2f8cacf57f50435eb78422f99
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1360,13 +1360,16 @@ def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help text to the formatter if it exists.""" - text = self.help if self.help is not None else "" + if self.help is not None: + # truncate the help text to the first form feed + text = inspect.cleandoc(self.help).partition("\f")[0] + else: + text = "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) if text: - text = inspect.cleandoc(text).partition("\f")[0] formatter.write_paragraph() with formatter.indentation():
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -95,20 +95,6 @@ def long(): ) -def test_help_truncation(runner): - @click.command() - def cli(): - """This is a command with truncated help. - \f - - This text should be truncated. - """ - - result = runner.invoke(cli, ["--help"]) - assert result.exit_code == 0 - assert "This is a command with truncated help." in result.output - - def test_no_args_is_help(runner): @click.command(no_args_is_help=True) def cli(): diff --git a/tests/test_formatting.py b/tests/test_formatting.py --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -296,6 +296,26 @@ def cli(ctx): ] +def test_truncating_docstring_no_help(runner): + @click.command() + @click.pass_context + def cli(ctx): + """ + \f + + This text should be truncated. + """ + + result = runner.invoke(cli, ["--help"], terminal_width=60) + assert not result.exception + assert result.output.splitlines() == [ + "Usage: cli [OPTIONS]", + "", + "Options:", + " --help Show this message and exit.", + ] + + def test_removing_multiline_marker(runner): @click.group() def cli():
Spurious empty lines in the help output (regression) Click since version 8.1.0 doesn't properly account for a scenario that the callback's docstring can have no "help text" part, like so: ```python @click.command() def callback(): """ \f More stuff. """ ``` This results in empty lines in the output: ``` % python3 test --help Usage: test [OPTIONS] Options: --help Show this message and exit. ``` Before 8.1.0: ``` % python3 test --help Usage: test [OPTIONS] Options: --help Show this message and exit. ``` Environment: - Python version: 3.9.2 - Click version: 8.1.3
2022-10-05T12:39:42Z
[]
[]
pallets/click
2,380
pallets__click-2380
[ "2379" ]
df9ad4085d60710b507b54c8fc369ee186eb1d64
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1086,9 +1086,9 @@ def main( # even always obvious that `rv` indicates success/failure # by its truthiness/falsiness ctx.exit() - except (EOFError, KeyboardInterrupt): + except (EOFError, KeyboardInterrupt) as e: echo(file=sys.stderr) - raise Abort() from None + raise Abort() from e except ClickException as e: if not standalone_mode: raise
diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -397,3 +397,15 @@ def command2(e): runner.invoke(group, ["command1"]) assert opt_prefixes == {"-", "--", "~", "+"} + + [email protected]("exc", (EOFError, KeyboardInterrupt)) +def test_abort_exceptions_with_disabled_standalone_mode(runner, exc): + @click.command() + def cli(): + raise exc("catch me!") + + rv = runner.invoke(cli, standalone_mode=False) + assert rv.exit_code == 1 + assert isinstance(rv.exception.__cause__, exc) + assert rv.exception.__cause__.args == ("catch me!",)
Unable to see EOFError exception in the traceback with disabled standalone mode According to the [docs](https://click.palletsprojects.com/en/8.0.x/exceptions/?highlight=standalone%20mode#what-if-i-don-t-want-that) disabled standalone mode disables exception handling. However, click still suppresses `EOFError` (as well as `KeyboardInterrupt`) exceptions from the stack trace due to the `raise ... from None` construction, see: https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L1066-L1068 I'd suggest changing the [line](https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L1068) to `raise Abort() from e`, so that users can see the original exception in the stack trace. Real world example. I use asyncio streams that can [raise IncompleteReadError](https://github.com/python/cpython/blob/d03acd7270d66ddb8e987f9743405147ecc15087/Lib/asyncio/exceptions.py#L29) which inherited from `EOFError`, but I can't see the exception in the stack trace even with disabled standalone mode which looks like a bug to me. **How to replicate the bug:** 1. Create the following script: ```python # t.py import click @click.command() def cli(): raise EOFError('I want to see this exception') if __name__ == '__main__': cli.main(standalone_mode=False) ``` 2. Run module `python -m t` **Actual behavior:** ```python Traceback (most recent call last): File "/Users/albert/.pyenv/versions/3.10.4/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/Users/albert/.pyenv/versions/3.10.4/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/t.py", line 10, in <module> cli.main(standalone_mode=False) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/.venv/lib/python3.10/site-packages/click/core.py", line 1068, in main raise Abort() from None click.exceptions.Abort ``` **Expected behavior:** ```python Traceback (most recent call last): File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/.venv/lib/python3.10/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/.venv/lib/python3.10/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/.venv/lib/python3.10/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/t.py", line 6, in cli raise EOFError('I want to see this exception') EOFError: I want to see this exception The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/albert/.pyenv/versions/3.10.4/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/Users/albert/.pyenv/versions/3.10.4/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/t.py", line 10, in <module> cli.main(standalone_mode=False) File "/private/var/folders/l0/lnq1ghps5yqc4vkgszlcz92m0000gp/T/tmp.X1tRYLrm/.venv/lib/python3.10/site-packages/click/core.py", line 1068, in main raise Abort() from e click.exceptions.Abort ``` Environment: - Python version: 3.10.4 - Click version: 8.1.3
2022-10-17T18:57:10Z
[]
[]
pallets/click
2,401
pallets__click-2401
[ "2398" ]
a6c7ee060b02eaa62fd15264a669220914cfad4c
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -50,7 +50,7 @@ def is_ascii_encoding(encoding: str) -> bool: return False -def get_best_encoding(stream: t.IO) -> str: +def get_best_encoding(stream: t.IO[t.Any]) -> str: """Returns the default stream encoding if not found.""" rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() if is_ascii_encoding(rv): @@ -153,7 +153,7 @@ def seekable(self) -> bool: return True -def _is_binary_reader(stream: t.IO, default: bool = False) -> bool: +def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: try: return isinstance(stream.read(0), bytes) except Exception: @@ -162,7 +162,7 @@ def _is_binary_reader(stream: t.IO, default: bool = False) -> bool: # closed. In this case, we assume the default. -def _is_binary_writer(stream: t.IO, default: bool = False) -> bool: +def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: try: stream.write(b"") except Exception: @@ -175,7 +175,7 @@ def _is_binary_writer(stream: t.IO, default: bool = False) -> bool: return True -def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]: +def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]: # We need to figure out if the given stream is already binary. # This can happen because the official docs recommend detaching # the streams to get binary streams. Some code might do this, so @@ -193,7 +193,7 @@ def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]: return None -def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]: +def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]: # We need to figure out if the given stream is already binary. # This can happen because the official docs recommend detaching # the streams to get binary streams. Some code might do this, so @@ -241,11 +241,11 @@ def _is_compatible_text_stream( def _force_correct_text_stream( - text_stream: t.IO, + text_stream: t.IO[t.Any], encoding: t.Optional[str], errors: t.Optional[str], - is_binary: t.Callable[[t.IO, bool], bool], - find_binary: t.Callable[[t.IO], t.Optional[t.BinaryIO]], + is_binary: t.Callable[[t.IO[t.Any], bool], bool], + find_binary: t.Callable[[t.IO[t.Any]], t.Optional[t.BinaryIO]], force_readable: bool = False, force_writable: bool = False, ) -> t.TextIO: @@ -287,7 +287,7 @@ def _force_correct_text_stream( def _force_correct_text_reader( - text_reader: t.IO, + text_reader: t.IO[t.Any], encoding: t.Optional[str], errors: t.Optional[str], force_readable: bool = False, @@ -303,7 +303,7 @@ def _force_correct_text_reader( def _force_correct_text_writer( - text_writer: t.IO, + text_writer: t.IO[t.Any], encoding: t.Optional[str], errors: t.Optional[str], force_writable: bool = False, @@ -367,11 +367,11 @@ def get_text_stderr( def _wrap_io_open( - file: t.Union[str, os.PathLike, int], + file: t.Union[str, "os.PathLike[t.AnyStr]", int], mode: str, encoding: t.Optional[str], errors: t.Optional[str], -) -> t.IO: +) -> t.IO[t.Any]: """Handles not passing ``encoding`` and ``errors`` in binary mode.""" if "b" in mode: return open(file, mode) @@ -385,7 +385,7 @@ def open_stream( encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", atomic: bool = False, -) -> t.Tuple[t.IO, bool]: +) -> t.Tuple[t.IO[t.Any], bool]: binary = "b" in mode # Standard streams first. These are simple because they ignore the @@ -456,11 +456,11 @@ def open_stream( f = _wrap_io_open(fd, mode, encoding, errors) af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) - return t.cast(t.IO, af), True + return t.cast(t.IO[t.Any], af), True class _AtomicFile: - def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None: + def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: self._f = f self._tmp_filename = tmp_filename self._real_filename = real_filename @@ -483,7 +483,7 @@ def __getattr__(self, name: str) -> t.Any: def __enter__(self) -> "_AtomicFile": return self - def __exit__(self, exc_type, exc_value, tb): # type: ignore + def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None: self.close(delete=exc_type is not None) def __repr__(self) -> str: @@ -494,7 +494,7 @@ def strip_ansi(value: str) -> str: return _ansi_re.sub("", value) -def _is_jupyter_kernel_output(stream: t.IO) -> bool: +def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): stream = stream._stream @@ -502,7 +502,7 @@ def _is_jupyter_kernel_output(stream: t.IO) -> bool: def should_strip_ansi( - stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None + stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None ) -> bool: if color is None: if stream is None: @@ -576,7 +576,7 @@ def term_len(x: str) -> int: return len(strip_ansi(x)) -def isatty(stream: t.IO) -> bool: +def isatty(stream: t.IO[t.Any]) -> bool: try: return stream.isatty() except Exception: diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -93,12 +93,12 @@ def __init__( self.is_hidden = not isatty(self.file) self._last_line: t.Optional[str] = None - def __enter__(self) -> "ProgressBar": + def __enter__(self) -> "ProgressBar[V]": self.entered = True self.render_progress() return self - def __exit__(self, exc_type, exc_value, tb): # type: ignore + def __exit__(self, *_: t.Any) -> None: self.render_finish() def __iter__(self) -> t.Iterator[V]: diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -455,7 +455,7 @@ def __enter__(self) -> "Context": push_context(self) return self - def __exit__(self, exc_type, exc_value, tb): # type: ignore + def __exit__(self, *_: t.Any) -> None: self._depth -= 1 if self._depth == 0: self.close() @@ -706,12 +706,30 @@ def _make_sub_context(self, command: "Command") -> "Context": """ return type(self)(command, info_name=command.name, parent=self) + @t.overload + def invoke( + __self, # noqa: B902 + __callback: "t.Callable[..., V]", + *args: t.Any, + **kwargs: t.Any, + ) -> V: + ... + + @t.overload def invoke( __self, # noqa: B902 - __callback: t.Union["Command", t.Callable[..., t.Any]], + __callback: "Command", *args: t.Any, **kwargs: t.Any, ) -> t.Any: + ... + + def invoke( + __self, # noqa: B902 + __callback: t.Union["Command", "t.Callable[..., V]"], + *args: t.Any, + **kwargs: t.Any, + ) -> t.Union[t.Any, V]: """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: @@ -739,7 +757,7 @@ def invoke( "The given command does not have a callback that can be invoked." ) else: - __callback = other_cmd.callback + __callback = t.cast("t.Callable[..., V]", other_cmd.callback) ctx = __self._make_sub_context(other_cmd) @@ -1841,7 +1859,7 @@ def command( if self.command_class and kwargs.get("cls") is None: kwargs["cls"] = self.command_class - func: t.Optional[t.Callable] = None + func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( @@ -1889,7 +1907,7 @@ def group( """ from .decorators import group - func: t.Optional[t.Callable] = None + func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( @@ -2260,7 +2278,7 @@ def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: if value is None: return () if self.multiple or self.nargs == -1 else None - def check_iter(value: t.Any) -> t.Iterator: + def check_iter(value: t.Any) -> t.Iterator[t.Any]: try: return _check_iter(value) except TypeError: @@ -2277,12 +2295,12 @@ def check_iter(value: t.Any) -> t.Iterator: ) elif self.nargs == -1: - def convert(value: t.Any) -> t.Tuple: + def convert(value: t.Any) -> t.Tuple[t.Any, ...]: return tuple(self.type(x, self, ctx) for x in check_iter(value)) else: # nargs > 1 - def convert(value: t.Any) -> t.Tuple: + def convert(value: t.Any) -> t.Tuple[t.Any, ...]: value = tuple(check_iter(value)) if len(value) != self.nargs: @@ -2817,7 +2835,7 @@ def get_default( if self.is_flag and not self.is_bool_flag: for param in ctx.command.params: if param.name == self.name and param.default: - return param.flag_value # type: ignore + return t.cast(Option, param).flag_value return None diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -13,36 +13,44 @@ from .globals import get_current_context from .utils import echo -F = t.TypeVar("F", bound=t.Callable[..., t.Any]) -FC = t.TypeVar("FC", bound=t.Union[t.Callable[..., t.Any], Command]) +if t.TYPE_CHECKING: + import typing_extensions as te + P = te.ParamSpec("P") -def pass_context(f: F) -> F: +R = t.TypeVar("R") +T = t.TypeVar("T") +_AnyCallable = t.Callable[..., t.Any] +_Decorator: "te.TypeAlias" = t.Callable[[T], T] +FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command]) + + +def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]": """Marks a callback as wanting to receive the current context object as first argument. """ - def new_func(*args, **kwargs): # type: ignore + def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R": return f(get_current_context(), *args, **kwargs) - return update_wrapper(t.cast(F, new_func), f) + return update_wrapper(new_func, f) -def pass_obj(f: F) -> F: +def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]": """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ - def new_func(*args, **kwargs): # type: ignore + def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R": return f(get_current_context().obj, *args, **kwargs) - return update_wrapper(t.cast(F, new_func), f) + return update_wrapper(new_func, f) def make_pass_decorator( - object_type: t.Type, ensure: bool = False -) -> "t.Callable[[F], F]": + object_type: t.Type[T], ensure: bool = False +) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]: """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type @@ -65,10 +73,11 @@ def new_func(ctx, *args, **kwargs): remembered on the context if it's not there yet. """ - def decorator(f: F) -> F: - def new_func(*args, **kwargs): # type: ignore + def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]": + def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R": ctx = get_current_context() + obj: t.Optional[T] if ensure: obj = ctx.ensure_object(object_type) else: @@ -83,14 +92,14 @@ def new_func(*args, **kwargs): # type: ignore return ctx.invoke(f, obj, *args, **kwargs) - return update_wrapper(t.cast(F, new_func), f) + return update_wrapper(new_func, f) return decorator def pass_meta_key( key: str, *, doc_description: t.Optional[str] = None -) -> "t.Callable[[F], F]": +) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]": """Create a decorator that passes a key from :attr:`click.Context.meta` as the first argument to the decorated function. @@ -103,13 +112,13 @@ def pass_meta_key( .. versionadded:: 8.0 """ - def decorator(f: F) -> F: - def new_func(*args, **kwargs): # type: ignore + def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]": + def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R: ctx = get_current_context() obj = ctx.meta[key] return ctx.invoke(f, obj, *args, **kwargs) - return update_wrapper(t.cast(F, new_func), f) + return update_wrapper(new_func, f) if doc_description is None: doc_description = f"the {key!r} key from :attr:`click.Context.meta`" @@ -124,35 +133,51 @@ def new_func(*args, **kwargs): # type: ignore CmdType = t.TypeVar("CmdType", bound=Command) +# variant: no call, directly as decorator for a function. @t.overload -def command( - __func: t.Callable[..., t.Any], -) -> Command: +def command(name: _AnyCallable) -> Command: ... +# variant: with positional name and with positional or keyword cls argument: +# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...) @t.overload def command( - name: t.Optional[str] = None, + name: t.Optional[str], + cls: t.Type[CmdType], **attrs: t.Any, -) -> t.Callable[..., Command]: +) -> t.Callable[[_AnyCallable], CmdType]: ... +# variant: name omitted, cls _must_ be a keyword argument, @command(cmd=CommandCls, ...) +# The correct way to spell this overload is to use keyword-only argument syntax: +# def command(*, cls: t.Type[CmdType], **attrs: t.Any) -> ... +# However, mypy thinks this doesn't fit the overloaded function. Pyright does +# accept that spelling, and the following work-around makes pyright issue a +# warning that CmdType could be left unsolved, but mypy sees it as fine. *shrug* @t.overload def command( - name: t.Optional[str] = None, + name: None = None, cls: t.Type[CmdType] = ..., **attrs: t.Any, -) -> t.Callable[..., CmdType]: +) -> t.Callable[[_AnyCallable], CmdType]: + ... + + +# variant: with optional string name, no cls argument provided. [email protected] +def command( + name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any +) -> t.Callable[[_AnyCallable], Command]: ... def command( - name: t.Union[str, t.Callable[..., t.Any], None] = None, - cls: t.Optional[t.Type[Command]] = None, + name: t.Union[t.Optional[str], _AnyCallable] = None, + cls: t.Optional[t.Type[CmdType]] = None, **attrs: t.Any, -) -> t.Union[Command, t.Callable[..., Command]]: +) -> t.Union[Command, t.Callable[[_AnyCallable], t.Union[Command, CmdType]]]: r"""Creates a new :class:`Command` and uses the decorated function as callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command. @@ -182,7 +207,7 @@ def command( appended to the end of the list. """ - func: t.Optional[t.Callable[..., t.Any]] = None + func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None if callable(name): func = name @@ -191,9 +216,9 @@ def command( assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments." if cls is None: - cls = Command + cls = t.cast(t.Type[CmdType], Command) - def decorator(f: t.Callable[..., t.Any]) -> Command: + def decorator(f: _AnyCallable) -> CmdType: if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") @@ -211,8 +236,12 @@ def decorator(f: t.Callable[..., t.Any]) -> Command: if attrs.get("help") is None: attrs["help"] = f.__doc__ - cmd = cls( # type: ignore[misc] - name=name or f.__name__.lower().replace("_", "-"), # type: ignore[arg-type] + if t.TYPE_CHECKING: + assert cls is not None + assert not callable(name) + + cmd = cls( + name=name or f.__name__.lower().replace("_", "-"), callback=f, params=params, **attrs, @@ -226,24 +255,54 @@ def decorator(f: t.Callable[..., t.Any]) -> Command: return decorator +GrpType = t.TypeVar("GrpType", bound=Group) + + +# variant: no call, directly as decorator for a function. [email protected] +def group(name: _AnyCallable) -> Group: + ... + + +# variant: with positional name and with positional or keyword cls argument: +# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...) @t.overload def group( - __func: t.Callable[..., t.Any], -) -> Group: + name: t.Optional[str], + cls: t.Type[GrpType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], GrpType]: ... +# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...) +# The _correct_ way to spell this overload is to use keyword-only argument syntax: +# def group(*, cls: t.Type[GrpType], **attrs: t.Any) -> ... +# However, mypy thinks this doesn't fit the overloaded function. Pyright does +# accept that spelling, and the following work-around makes pyright issue a +# warning that GrpType could be left unsolved, but mypy sees it as fine. *shrug* @t.overload def group( - name: t.Optional[str] = None, + name: None = None, + cls: t.Type[GrpType] = ..., **attrs: t.Any, -) -> t.Callable[[F], Group]: +) -> t.Callable[[_AnyCallable], GrpType]: ... +# variant: with optional string name, no cls argument provided. [email protected] def group( - name: t.Union[str, t.Callable[..., t.Any], None] = None, **attrs: t.Any -) -> t.Union[Group, t.Callable[[F], Group]]: + name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any +) -> t.Callable[[_AnyCallable], Group]: + ... + + +def group( + name: t.Union[str, _AnyCallable, None] = None, + cls: t.Optional[t.Type[GrpType]] = None, + **attrs: t.Any, +) -> t.Union[Group, t.Callable[[_AnyCallable], t.Union[Group, GrpType]]]: """Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. @@ -251,17 +310,16 @@ def group( .. versionchanged:: 8.1 This decorator can be applied without parentheses. """ - if attrs.get("cls") is None: - attrs["cls"] = Group + if cls is None: + cls = t.cast(t.Type[GrpType], Group) if callable(name): - grp: t.Callable[[F], Group] = t.cast(Group, command(**attrs)) - return grp(name) + return command(cls=cls, **attrs)(name) - return t.cast(Group, command(name, **attrs)) + return command(name, cls, **attrs) -def _param_memo(f: FC, param: Parameter) -> None: +def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: if isinstance(f, Command): f.params.append(param) else: @@ -271,7 +329,7 @@ def _param_memo(f: FC, param: Parameter) -> None: f.__click_params__.append(param) # type: ignore -def argument(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]: +def argument(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]: """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). @@ -290,7 +348,7 @@ def decorator(f: FC) -> FC: return decorator -def option(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]: +def option(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]: """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). @@ -311,7 +369,7 @@ def decorator(f: FC) -> FC: return decorator -def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: +def confirmation_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]: """Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit. @@ -335,7 +393,7 @@ def callback(ctx: Context, param: Parameter, value: bool) -> None: return option(*param_decls, **kwargs) -def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: +def password_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]: """Add a ``--password`` option which prompts for a password, hiding input and asking to enter the value again for confirmation. @@ -359,7 +417,7 @@ def version_option( prog_name: t.Optional[str] = None, message: t.Optional[str] = None, **kwargs: t.Any, -) -> t.Callable[[FC], FC]: +) -> _Decorator[FC]: """Add a ``--version`` option which immediately prints the version number and exits the program. @@ -466,7 +524,7 @@ def callback(ctx: Context, param: Parameter, value: bool) -> None: return option(*param_decls, **kwargs) -def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: +def help_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]: """Add a ``--help`` option which immediately prints the help page and exits the program. diff --git a/src/click/exceptions.py b/src/click/exceptions.py --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -36,7 +36,7 @@ def format_message(self) -> str: def __str__(self) -> str: return self.message - def show(self, file: t.Optional[t.IO] = None) -> None: + def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: file = get_text_stderr() @@ -59,7 +59,7 @@ def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: self.ctx = ctx self.cmd = self.ctx.command if self.ctx else None - def show(self, file: t.Optional[t.IO] = None) -> None: + def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: file = get_text_stderr() color = None diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -397,7 +397,7 @@ def __repr__(self) -> str: class _NumberParamTypeBase(ParamType): - _number_class: t.ClassVar[t.Type] + _number_class: t.ClassVar[t.Type[t.Any]] def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] @@ -702,17 +702,14 @@ def convert( lazy = self.resolve_lazy_flag(value) if lazy: - f: t.IO = t.cast( - t.IO, - LazyFile( - value, self.mode, self.encoding, self.errors, atomic=self.atomic - ), + lf = LazyFile( + value, self.mode, self.encoding, self.errors, atomic=self.atomic ) if ctx is not None: - ctx.call_on_close(f.close_intelligently) # type: ignore + ctx.call_on_close(lf.close_intelligently) - return f + return t.cast(t.IO[t.Any], lf) f, should_close = open_stream( value, self.mode, self.encoding, self.errors, atomic=self.atomic @@ -794,7 +791,7 @@ def __init__( readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, - path_type: t.Optional[t.Type] = None, + path_type: t.Optional[t.Type[t.Any]] = None, executable: bool = False, ): self.exists = exists @@ -944,7 +941,7 @@ class Tuple(CompositeParamType): :param types: a list of types that should be used for the tuple items. """ - def __init__(self, types: t.Sequence[t.Union[t.Type, ParamType]]) -> None: + def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None: self.types = [convert_type(ty) for ty in types] def to_info_dict(self) -> t.Dict[str, t.Any]: diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -21,23 +21,26 @@ if t.TYPE_CHECKING: import typing_extensions as te -F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + P = te.ParamSpec("P") + +R = t.TypeVar("R") def _posixify(name: str) -> str: return "-".join(name.split()).lower() -def safecall(func: F) -> F: +def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]": """Wraps a function so that it swallows exceptions.""" - def wrapper(*args, **kwargs): # type: ignore + def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]: try: return func(*args, **kwargs) except Exception: pass + return None - return update_wrapper(t.cast(F, wrapper), func) + return update_wrapper(wrapper, func) def make_str(value: t.Any) -> str: @@ -120,7 +123,7 @@ def __init__( self.encoding = encoding self.errors = errors self.atomic = atomic - self._f: t.Optional[t.IO] + self._f: t.Optional[t.IO[t.Any]] if filename == "-": self._f, self.should_close = open_stream(filename, mode, encoding, errors) @@ -141,7 +144,7 @@ def __repr__(self) -> str: return repr(self._f) return f"<unopened file '{self.name}' {self.mode}>" - def open(self) -> t.IO: + def open(self) -> t.IO[t.Any]: """Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows. @@ -174,7 +177,7 @@ def close_intelligently(self) -> None: def __enter__(self) -> "LazyFile": return self - def __exit__(self, exc_type, exc_value, tb): # type: ignore + def __exit__(self, *_: t.Any) -> None: self.close_intelligently() def __iter__(self) -> t.Iterator[t.AnyStr]: @@ -183,7 +186,7 @@ def __iter__(self) -> t.Iterator[t.AnyStr]: class KeepOpenFile: - def __init__(self, file: t.IO) -> None: + def __init__(self, file: t.IO[t.Any]) -> None: self._file = file def __getattr__(self, name: str) -> t.Any: @@ -192,7 +195,7 @@ def __getattr__(self, name: str) -> t.Any: def __enter__(self) -> "KeepOpenFile": return self - def __exit__(self, exc_type, exc_value, tb): # type: ignore + def __exit__(self, *_: t.Any) -> None: pass def __repr__(self) -> str: @@ -340,7 +343,7 @@ def open_file( errors: t.Optional[str] = "strict", lazy: bool = False, atomic: bool = False, -) -> t.IO: +) -> t.IO[t.Any]: """Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. @@ -370,18 +373,20 @@ def open_file( .. versionadded:: 3.0 """ if lazy: - return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic)) + return t.cast( + t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic) + ) f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) if not should_close: - f = t.cast(t.IO, KeepOpenFile(f)) + f = t.cast(t.IO[t.Any], KeepOpenFile(f)) return f def format_filename( - filename: t.Union[str, bytes, os.PathLike], shorten: bool = False + filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False ) -> str: """Formats a filename for user display. The main purpose of this function is to ensure that the filename can be displayed at all. This @@ -458,7 +463,7 @@ class PacifyFlushWrapper: pipe, all calls and attributes are proxied. """ - def __init__(self, wrapped: t.IO) -> None: + def __init__(self, wrapped: t.IO[t.Any]) -> None: self.wrapped = wrapped def flush(self) -> None:
diff --git a/src/click/testing.py b/src/click/testing.py --- a/src/click/testing.py +++ b/src/click/testing.py @@ -79,11 +79,11 @@ def mode(self) -> str: def make_input_stream( - input: t.Optional[t.Union[str, bytes, t.IO]], charset: str + input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]], charset: str ) -> t.BinaryIO: # Is already an input stream. if hasattr(input, "read"): - rv = _find_binary_reader(t.cast(t.IO, input)) + rv = _find_binary_reader(t.cast(t.IO[t.Any], input)) if rv is not None: return rv @@ -206,7 +206,7 @@ def make_env( @contextlib.contextmanager def isolation( self, - input: t.Optional[t.Union[str, bytes, t.IO]] = None, + input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None, env: t.Optional[t.Mapping[str, t.Optional[str]]] = None, color: bool = False, ) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]: @@ -301,7 +301,7 @@ def _getchar(echo: bool) -> str: default_color = color def should_strip_ansi( - stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None + stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None ) -> bool: if color is None: return not default_color @@ -350,7 +350,7 @@ def invoke( self, cli: "BaseCommand", args: t.Optional[t.Union[str, t.Sequence[str]]] = None, - input: t.Optional[t.Union[str, bytes, t.IO]] = None, + input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None, env: t.Optional[t.Mapping[str, t.Optional[str]]] = None, catch_exceptions: bool = True, color: bool = False, @@ -449,7 +449,7 @@ def invoke( @contextlib.contextmanager def isolated_filesystem( - self, temp_dir: t.Optional[t.Union[str, os.PathLike]] = None + self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None ) -> t.Iterator[str]: """A context manager that creates a temporary directory and changes the current working directory to it. This isolates tests
Type hints: public API uses generic hints without parameters There are several methods in the click API that uses generic types that leave out the parameter. To name two specific examples: ``` # click/decorators.py def make_pass_decorator( object_type: t.Type, ensure: bool = False ) -> "t.Callable[[F], F]": ``` ``` # click/utils.py class KeepOpenFile: def __init__(self, file: t.IO) -> None: ``` `Type` and `IO` are generic types here, both take a single parameter. Anyone using the pyright type checker _in strict mode_ can't easily use these functions or classes as the type hints are incomplete: ``` import click class Foo: pass pass_foo = click.make_pass_decorator(Foo) # Type of "make_pass_decorator" is partially unknown # Type of "make_pass_decorator" is "(object_type: Unknown, ensure: bool = False) -> ((F@make_pass_decorator) -> F@make_pass_decorator)" ``` Please fill in generic parameters wherever possible, even if it is just `Any`. Environment: - Python version: 3.10 - Click version: 8.1.3
2022-11-08T22:27:49Z
[]
[]
pallets/click
2,417
pallets__click-2417
[ "2416" ]
e4066e1f325088ee42ae7bc0bc6c2e47533ff2c3
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -1871,9 +1871,6 @@ def command( """ from .decorators import command - if self.command_class and kwargs.get("cls") is None: - kwargs["cls"] = self.command_class - func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): @@ -1883,6 +1880,9 @@ def command( (func,) = args args = () + if self.command_class and kwargs.get("cls") is None: + kwargs["cls"] = self.command_class + def decorator(f: t.Callable[..., t.Any]) -> Command: cmd: Command = command(*args, **kwargs)(f) self.add_command(cmd)
diff --git a/tests/test_command_decorators.py b/tests/test_command_decorators.py --- a/tests/test_command_decorators.py +++ b/tests/test_command_decorators.py @@ -11,6 +11,26 @@ def cli(): assert result.output == "hello\n" +def test_custom_command_no_parens(runner): + class CustomCommand(click.Command): + pass + + class CustomGroup(click.Group): + command_class = CustomCommand + + @click.group(cls=CustomGroup) + def grp(): + pass + + @grp.command + def cli(): + click.echo("hello custom command class") + + result = runner.invoke(cli) + assert result.exception is None + assert result.output == "hello custom command class\n" + + def test_group_no_parens(runner): @click.group def grp():
Cannot use parameterless command decorator with custom command_class Click throws an assertion error if you try to use the parameterless command decorator on a group with a command_class defined. The error is due to the command_class being added to kwargs before the assertion for no kwargs. # minimal repro ``` import click class CustomCommand(click.Command): pass class CustomGroup(click.Group): command_class = CustomCommand @click.group(cls=CustomGroup) def grp(): pass @grp.command def cli(): click.echo("hello custom command class") ``` ## error ``` ewilliamson@ip-192-168-50-39 ~ % python minimal_repro.py Traceback (most recent call last): File "/Users/ewilliamson/minimal_repro.py", line 14, in <module> def cli(): File "/Users/ewilliamson/.pyenv/versions/3.10.7/lib/python3.10/site-packages/click/core.py", line 1847, in command assert ( AssertionError: Use 'command(**kwargs)(callable)' to provide arguments. ``` ## expected The `@grp.command` would be successfully parsed the same as without using `CustomGroup` <!-- Describe the expected behavior that should have happened but didn't. --> Environment: - Python version: `Python 3.10.7` - Click version: `click==8.1.3`
2022-12-15T22:06:00Z
[]
[]
pallets/click
2,543
pallets__click-2543
[ "2444" ]
2de3b317733f3510d18143328124202ff3d46670
diff --git a/examples/aliases/setup.py b/examples/aliases/setup.py deleted file mode 100644 --- a/examples/aliases/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-aliases", - version="1.0", - py_modules=["aliases"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - aliases=aliases:cli - """, -) diff --git a/examples/colors/setup.py b/examples/colors/setup.py deleted file mode 100644 --- a/examples/colors/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-colors", - version="1.0", - py_modules=["colors"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - colors=colors:cli - """, -) diff --git a/examples/completion/setup.py b/examples/completion/setup.py deleted file mode 100644 --- a/examples/completion/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-completion", - version="1.0", - py_modules=["completion"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - completion=completion:cli - """, -) diff --git a/examples/complex/setup.py b/examples/complex/setup.py deleted file mode 100644 --- a/examples/complex/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-complex", - version="1.0", - packages=["complex", "complex.commands"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - complex=complex.cli:cli - """, -) diff --git a/examples/imagepipe/setup.py b/examples/imagepipe/setup.py deleted file mode 100644 --- a/examples/imagepipe/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-imagepipe", - version="1.0", - py_modules=["imagepipe"], - include_package_data=True, - install_requires=["click", "pillow"], - entry_points=""" - [console_scripts] - imagepipe=imagepipe:cli - """, -) diff --git a/examples/inout/setup.py b/examples/inout/setup.py deleted file mode 100644 --- a/examples/inout/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-inout", - version="0.1", - py_modules=["inout"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - inout=inout:cli - """, -) diff --git a/examples/naval/setup.py b/examples/naval/setup.py deleted file mode 100644 --- a/examples/naval/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-naval", - version="2.0", - py_modules=["naval"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - naval=naval:cli - """, -) diff --git a/examples/repo/setup.py b/examples/repo/setup.py deleted file mode 100644 --- a/examples/repo/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-repo", - version="0.1", - py_modules=["repo"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - repo=repo:cli - """, -) diff --git a/examples/termui/setup.py b/examples/termui/setup.py deleted file mode 100644 --- a/examples/termui/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-termui", - version="1.0", - py_modules=["termui"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - termui=termui:cli - """, -) diff --git a/examples/validation/setup.py b/examples/validation/setup.py deleted file mode 100644 --- a/examples/validation/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup - -setup( - name="click-example-validation", - version="1.0", - py_modules=["validation"], - include_package_data=True, - install_requires=["click"], - entry_points=""" - [console_scripts] - validation=validation:cli - """, -)
diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -41,11 +41,6 @@ jobs: python-version: ${{ matrix.python }} cache: 'pip' cache-dependency-path: 'requirements/*.txt' - - name: update pip - run: | - pip install -U wheel - pip install -U setuptools - python -m pip install -U pip - name: cache mypy uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8 with:
Transition docs from setup.py to pyproject.toml Is there any issue transitioning the "Setuptools Integration" doc section from referencing a notional `setup.py` to instead reference a `pyproject.toml`? I can submit a PR if there's no objection.
Just an FYI, @BrennanBarker is referring to this - https://github.com/pallets/click/blob/main/docs/setuptools.rst. Which probably is antiquated at this point like they say.
2023-06-28T18:50:38Z
[]
[]
pallets/click
2,550
pallets__click-2550
[ "2295" ]
d34d31f6dde4350f9508f0327698f851c595d91c
diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -2570,8 +2570,13 @@ def __init__( # flag if flag_value is set. self._flag_needs_value = flag_value is not None + self.default: t.Union[t.Any, t.Callable[[], t.Any]] + if is_flag and default_is_missing and not self.required: - self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False + if multiple: + self.default = () + else: + self.default = False if flag_value is None: flag_value = not self.default @@ -2622,9 +2627,6 @@ def __init__( if self.is_flag: raise TypeError("'count' is not valid with 'is_flag'.") - if self.multiple and self.is_flag: - raise TypeError("'multiple' is not valid with 'is_flag', use 'count'.") - def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = super().to_info_dict() info_dict.update(
diff --git a/tests/test_defaults.py b/tests/test_defaults.py --- a/tests/test_defaults.py +++ b/tests/test_defaults.py @@ -38,3 +38,24 @@ def cli(arg): result = runner.invoke(cli, []) assert not result.exception assert result.output.splitlines() == ["<1|2>", "<3|4>"] + + +def test_multiple_flag_default(runner): + """Default default for flags when multiple=True should be empty tuple.""" + + @click.command + # flag due to secondary token + @click.option("-y/-n", multiple=True) + # flag due to is_flag + @click.option("-f", is_flag=True, multiple=True) + # flag due to flag_value + @click.option("-v", "v", flag_value=1, multiple=True) + @click.option("-q", "v", flag_value=-1, multiple=True) + def cli(y, f, v): + return y, f, v + + result = runner.invoke(cli, standalone_mode=False) + assert result.return_value == ((), (), ()) + + result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False) + assert result.return_value == ((True, False), (True,), (1, -1)) diff --git a/tests/test_options.py b/tests/test_options.py --- a/tests/test_options.py +++ b/tests/test_options.py @@ -911,10 +911,6 @@ def test_is_bool_flag_is_correctly_set(option, expected): [ ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."), ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."), - ( - {"multiple": True, "is_flag": True}, - "'multiple' is not valid with 'is_flag', use 'count'.", - ), ], ) def test_invalid_flag_combinations(runner, kwargs, message):
can't get list of bools using multiple flag I have an option that is a list of `bool`s, but I'm pairing each boolean value with another `multiple` option. So I do actually need a list of booleans and not just a count of values because order matters. I'm not using `is_flag`, but I assume this translates to the same under the hood. ``` @click.option( "--collection/--single", "-c/-s", type=bool, default=[False], count=True, help=( "Is a file a collection of books? Add once for every file included. " "Consumed in order of files." ), ) @click.option( "--file", "-f", required=True, type=click.Path( exists=True, readable=True, dir_okay=False, allow_dash=True, path_type=str ), multiple=True, help=( "The path of the input file. Note: Every file must be paired with a language. " "And the pairs will be processed left to right." ), ) ``` Environment: Python version: 3.9.7.1 Click version: 8.1.3 Is there an alternative way I should be doing this? If not #2246 breaks my code.
2023-07-03T16:10:28Z
[]
[]
pallets/click
2,553
pallets__click-2553
[ "2395" ]
0c8f301d2a28b67451eef872e327ef67e3993ec6
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -17,10 +17,6 @@ _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") -def get_filesystem_encoding() -> str: - return sys.getfilesystemencoding() or sys.getdefaultencoding() - - def _make_text_stream( stream: t.BinaryIO, encoding: t.Optional[str], @@ -380,13 +376,14 @@ def _wrap_io_open( def open_stream( - filename: str, + filename: "t.Union[str, os.PathLike[str]]", mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", atomic: bool = False, ) -> t.Tuple[t.IO[t.Any], bool]: binary = "b" in mode + filename = os.fspath(filename) # Standard streams first. These are simple because they ignore the # atomic flag. Use fsdecode to handle Path("-"). @@ -564,7 +561,7 @@ def _safe_write(s): else: def _get_argv_encoding() -> str: - return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding() + return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding() def _get_windows_console_stream( f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str] diff --git a/src/click/exceptions.py b/src/click/exceptions.py --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -1,10 +1,10 @@ -import os import typing as t from gettext import gettext as _ from gettext import ngettext from ._compat import get_text_stderr from .utils import echo +from .utils import format_filename if t.TYPE_CHECKING: from .core import Command @@ -262,7 +262,7 @@ def __init__(self, filename: str, hint: t.Optional[str] = None) -> None: hint = _("unknown error") super().__init__(hint) - self.ui_filename: str = os.fsdecode(filename) + self.ui_filename: str = format_filename(filename) self.filename = filename def format_message(self) -> str: diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -1,14 +1,15 @@ import os import stat +import sys import typing as t from datetime import datetime from gettext import gettext as _ from gettext import ngettext from ._compat import _get_argv_encoding -from ._compat import get_filesystem_encoding from ._compat import open_stream from .exceptions import BadParameter +from .utils import format_filename from .utils import LazyFile from .utils import safecall @@ -207,7 +208,7 @@ def convert( try: value = value.decode(enc) except UnicodeError: - fs_enc = get_filesystem_encoding() + fs_enc = sys.getfilesystemencoding() if fs_enc != enc: try: value = value.decode(fs_enc) @@ -687,22 +688,27 @@ def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict.update(mode=self.mode, encoding=self.encoding) return info_dict - def resolve_lazy_flag(self, value: t.Any) -> bool: + def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool: if self.lazy is not None: return self.lazy - if value == "-": + if os.fspath(value) == "-": return False elif "w" in self.mode: return True return False def convert( - self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] - ) -> t.Any: - try: - if hasattr(value, "read") or hasattr(value, "write"): - return value + self, + value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]], + param: t.Optional["Parameter"], + ctx: t.Optional["Context"], + ) -> t.IO[t.Any]: + if _is_file_like(value): + return value + + value = t.cast("t.Union[str, os.PathLike[str]]", value) + try: lazy = self.resolve_lazy_flag(value) if lazy: @@ -732,7 +738,7 @@ def convert( return f except OSError as e: # noqa: B014 - self.fail(f"'{os.fsdecode(value)}': {e.strerror}", param, ctx) + self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx) def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str @@ -751,6 +757,10 @@ def shell_complete( return [CompletionItem(incomplete, type="file")] +def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]": + return hasattr(value, "read") or hasattr(value, "write") + + class Path(ParamType): """The ``Path`` type is similar to the :class:`File` type, but returns the filename instead of an open file. Various checks can be @@ -827,20 +837,25 @@ def to_info_dict(self) -> t.Dict[str, t.Any]: ) return info_dict - def coerce_path_result(self, rv: t.Any) -> t.Any: - if self.type is not None and not isinstance(rv, self.type): + def coerce_path_result( + self, value: "t.Union[str, os.PathLike[str]]" + ) -> "t.Union[str, bytes, os.PathLike[str]]": + if self.type is not None and not isinstance(value, self.type): if self.type is str: - rv = os.fsdecode(rv) + return os.fsdecode(value) elif self.type is bytes: - rv = os.fsencode(rv) + return os.fsencode(value) else: - rv = self.type(rv) + return t.cast("os.PathLike[str]", self.type(value)) - return rv + return value def convert( - self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] - ) -> t.Any: + self, + value: "t.Union[str, os.PathLike[str]]", + param: t.Optional["Parameter"], + ctx: t.Optional["Context"], + ) -> "t.Union[str, bytes, os.PathLike[str]]": rv = value is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") @@ -860,7 +875,7 @@ def convert( return self.coerce_path_result(rv) self.fail( _("{name} {filename!r} does not exist.").format( - name=self.name.title(), filename=os.fsdecode(value) + name=self.name.title(), filename=format_filename(value) ), param, ctx, @@ -869,7 +884,7 @@ def convert( if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( _("{name} {filename!r} is a file.").format( - name=self.name.title(), filename=os.fsdecode(value) + name=self.name.title(), filename=format_filename(value) ), param, ctx, @@ -877,7 +892,7 @@ def convert( if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( _("{name} '{filename}' is a directory.").format( - name=self.name.title(), filename=os.fsdecode(value) + name=self.name.title(), filename=format_filename(value) ), param, ctx, @@ -886,7 +901,7 @@ def convert( if self.readable and not os.access(rv, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( - name=self.name.title(), filename=os.fsdecode(value) + name=self.name.title(), filename=format_filename(value) ), param, ctx, @@ -895,7 +910,7 @@ def convert( if self.writable and not os.access(rv, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( - name=self.name.title(), filename=os.fsdecode(value) + name=self.name.title(), filename=format_filename(value) ), param, ctx, @@ -904,7 +919,7 @@ def convert( if self.executable and not os.access(value, os.X_OK): self.fail( _("{name} {filename!r} is not executable.").format( - name=self.name.title(), filename=os.fsdecode(value) + name=self.name.title(), filename=format_filename(value) ), param, ctx, diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -11,7 +11,6 @@ from ._compat import _find_binary_writer from ._compat import auto_wrap_for_ansi from ._compat import binary_streams -from ._compat import get_filesystem_encoding from ._compat import open_stream from ._compat import should_strip_ansi from ._compat import strip_ansi @@ -48,7 +47,7 @@ def make_str(value: t.Any) -> str: """Converts a value into a valid string.""" if isinstance(value, bytes): try: - return value.decode(get_filesystem_encoding()) + return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode("utf-8", "replace") return str(value) @@ -113,13 +112,13 @@ class LazyFile: def __init__( self, - filename: str, + filename: t.Union[str, "os.PathLike[str]"], mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", atomic: bool = False, ): - self.name = filename + self.name: str = os.fspath(filename) self.mode = mode self.encoding = encoding self.errors = errors @@ -127,7 +126,7 @@ def __init__( self._f: t.Optional[t.IO[t.Any]] self.should_close: bool - if filename == "-": + if self.name == "-": self._f, self.should_close = open_stream(filename, mode, encoding, errors) else: if "r" in mode: @@ -144,7 +143,7 @@ def __getattr__(self, name: str) -> t.Any: def __repr__(self) -> str: if self._f is not None: return repr(self._f) - return f"<unopened file '{self.name}' {self.mode}>" + return f"<unopened file '{format_filename(self.name)}' {self.mode}>" def open(self) -> t.IO[t.Any]: """Opens the file if it's not yet open. This call might fail with @@ -398,13 +397,26 @@ def open_file( def format_filename( - filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False + filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]", + shorten: bool = False, ) -> str: - """Formats a filename for user display. The main purpose of this - function is to ensure that the filename can be displayed at all. This - will decode the filename to unicode if necessary in a way that it will - not fail. Optionally, it can shorten the filename to not include the - full path to the filename. + """Format a filename as a string for display. Ensures the filename can be + displayed by replacing any invalid bytes or surrogate escapes in the name + with the replacement character ``�``. + + Invalid bytes or surrogate escapes will raise an error when written to a + stream with ``errors="strict". This will typically happen with ``stdout`` + when the locale is something like ``en_GB.UTF-8``. + + Many scenarios *are* safe to write surrogates though, due to PEP 538 and + PEP 540, including: + + - Writing to ``stderr``, which uses ``errors="backslashreplace"``. + - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens + stdout and stderr with ``errors="surrogateescape"``. + - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. + - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. + Python opens stdout and stderr with ``errors="surrogateescape"``. :param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. @@ -413,8 +425,17 @@ def format_filename( """ if shorten: filename = os.path.basename(filename) + else: + filename = os.fspath(filename) + + if isinstance(filename, bytes): + filename = filename.decode(sys.getfilesystemencoding(), "replace") + else: + filename = filename.encode("utf-8", "surrogateescape").decode( + "utf-8", "replace" + ) - return os.fsdecode(filename) + return filename def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
diff --git a/tests/conftest.py b/tests/conftest.py --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,3 @@ -import os -import tempfile - import pytest from click.testing import CliRunner @@ -9,19 +6,3 @@ @pytest.fixture(scope="function") def runner(request): return CliRunner() - - -def _check_symlinks_supported(): - with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: - target = os.path.join(tempdir, "target") - open(target, "w").close() - link = os.path.join(tempdir, "link") - - try: - os.symlink(target, link) - return True - except OSError: - return False - - -symlinks_supported = _check_symlinks_supported() diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1,10 +1,11 @@ import os.path import pathlib +import tempfile import pytest -from conftest import symlinks_supported import click +from click import FileError @pytest.mark.parametrize( @@ -104,12 +105,25 @@ def test_path_type(runner, cls, expect): assert result.return_value == expect +def _symlinks_supported(): + with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: + target = os.path.join(tempdir, "target") + open(target, "w").close() + link = os.path.join(tempdir, "link") + + try: + os.symlink(target, link) + return True + except OSError: + return False + + @pytest.mark.skipif( - not symlinks_supported, reason="The current OS or FS doesn't support symlinks." + not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks." ) def test_path_resolve_symlink(tmp_path, runner): test_file = tmp_path / "file" - test_file_str = os.fsdecode(test_file) + test_file_str = os.fspath(test_file) test_file.write_text("") path_type = click.Path(resolve_path=True) @@ -121,10 +135,100 @@ def test_path_resolve_symlink(tmp_path, runner): abs_link = test_dir / "abs" abs_link.symlink_to(test_file) - abs_rv = path_type.convert(os.fsdecode(abs_link), param, ctx) + abs_rv = path_type.convert(os.fspath(abs_link), param, ctx) assert abs_rv == test_file_str rel_link = test_dir / "rel" rel_link.symlink_to(pathlib.Path("..") / "file") - rel_rv = path_type.convert(os.fsdecode(rel_link), param, ctx) + rel_rv = path_type.convert(os.fspath(rel_link), param, ctx) assert rel_rv == test_file_str + + +def _non_utf8_filenames_supported(): + with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: + try: + f = open(os.path.join(tempdir, "\udcff"), "w") + except OSError: + return False + + f.close() + return True + + [email protected]( + not _non_utf8_filenames_supported(), + reason="The current OS or FS doesn't support non-UTF-8 filenames.", +) +def test_path_surrogates(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + type = click.Path(exists=True) + path = pathlib.Path("\udcff") + + with pytest.raises(click.BadParameter, match="'�' does not exist"): + type.convert(path, None, None) + + type = click.Path(file_okay=False) + path.touch() + + with pytest.raises(click.BadParameter, match="'�' is a file"): + type.convert(path, None, None) + + path.unlink() + type = click.Path(dir_okay=False) + path.mkdir() + + with pytest.raises(click.BadParameter, match="'�' is a directory"): + type.convert(path, None, None) + + path.rmdir() + + def no_access(*args, **kwargs): + """Test environments may be running as root, so we have to fake the result of + the access tests that use os.access + """ + p = args[0] + assert p == path, f"unexpected os.access call on file not under test: {p!r}" + return False + + path.touch() + type = click.Path(readable=True) + + with pytest.raises(click.BadParameter, match="'�' is not readable"): + with monkeypatch.context() as m: + m.setattr(os, "access", no_access) + type.convert(path, None, None) + + type = click.Path(readable=False, writable=True) + + with pytest.raises(click.BadParameter, match="'�' is not writable"): + with monkeypatch.context() as m: + m.setattr(os, "access", no_access) + type.convert(path, None, None) + + type = click.Path(readable=False, executable=True) + + with pytest.raises(click.BadParameter, match="'�' is not executable"): + with monkeypatch.context() as m: + m.setattr(os, "access", no_access) + type.convert(path, None, None) + + path.unlink() + + [email protected]( + "type", + [ + click.File(mode="r"), + click.File(mode="r", lazy=True), + ], +) +def test_file_surrogates(type, tmp_path): + path = tmp_path / "\udcff" + + with pytest.raises(click.BadParameter, match="�': No such file or directory"): + type.convert(path, None, None) + + +def test_file_error_surrogates(): + message = FileError(filename="\udcff").format_message() + assert message == "Could not open file '�': unknown error" diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -98,10 +98,7 @@ def test_filename_formatting(): assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt" assert click.format_filename("/x/foo.txt") == "/x/foo.txt" assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt" - - # filesystem encoding on windows permits this. - if not WIN: - assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt" + assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt" def test_prompts(runner):
click.format_filename regression in click 8 for non-unicode paths ## Summary On non-Windows platforms, Python uses the `"surrogateescape"` error handler by default for filesystem encoding (`sys.getfilesystemencodeerrors()`). The docstring for `format_filename` says this (emphasis mine) > Formats a filename for user display. The main purpose of this function is to **ensure that the filename can be displayed at all**. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename. and under [Printing Filenames](https://click.palletsprojects.com/en/8.1.x/utils/?highlight=format_filename#printing-filenames) (emphasis mine): > Because filenames might not be Unicode, formatting them can be a bit tricky. > > The way this works with click is through the [format_filename()](https://click.palletsprojects.com/en/8.1.x/api/#click.format_filename) function. It does a best-effort conversion of the filename to Unicode and will never fail. This makes it possible to use **these filenames in the context of a full Unicode string.** But on Click 8, `format_filename` will always return a string with surrogates intact. Strings in this form are destined for functions which have to operate on the file like `open`, not for printing to the user. When you try to do so, you get a UnicodeEncodeError. ## Reproducer **You have to run this example on an OS like Linux which allows non-unicode filenames.** This script ```python import os import click @click.command() @click.argument('path', type=click.Path(), required=False) def cli(path): if path is not None: click.echo(f"printing {path!r} as {click.format_filename(path)}") filename_bytes = b'foo\xe9' filename_str = os.fsdecode(filename_bytes) # We can open filename_bytes or filename_str, the result is the same. # When filename_str (which contains surrogates) is given, Python encodes # it back using os.fsencode to get the original bytes. with open(filename_str, 'w') as fp: fp.write('Hello, world!') # I'm just using scandir to demonstrate that paths come from the standard # library in this surrogateescaped form. # # This is equivalent to click.echo(click.format_filename(filename_str)) for entry in os.scandir('.'): if entry.name != filename_str: continue click.echo(click.format_filename(entry.name)) if __name__ == '__main__': cli() ``` Save this file as `cli.py` and run it: ``` python cli.py ``` On Click 8 you get an exception: ``` Traceback (most recent call last): File "cli.py", line 25, in <module> cli() File "<redacted>/python3.7/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "<redacted>/python3.7/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "<redacted>/python3.7/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "<redacted>/python3.7/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "cli.py", line 22, in cli click.echo(click.format_filename(entry.name)) File "<redacted>/python3.7/site-packages/click/utils.py", line 299, in echo file.write(out) # type: ignore UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 3: surrogates not allowed ``` On Click 7 you get the expected output: ``` foo� ``` You can also run it with a filename argument to see how it passes through click.Path. Using shell completion to complete the filename is the easiest thing to do, in case this escape sequence is unique to my shell (probably not, but I'm not sure). ``` python cli.py 'foo'$'\351' ``` Environment: - Python version: 3.7 and 3.10 tested - Click version: 8.1.3 - OS: Linux ## Cause Implementation on Click 7.1.2: https://github.com/pallets/click/blob/1784558ed7c75c65764d2a434bd9cbb206ca939d/src/click/_compat.py#L470-L475 Implementation on Click 8: https://github.com/pallets/click/blob/9c6f4c8e1bb8670ce827c98559f57f6ee5935cd0/src/click/utils.py#L400 This means that on Click 8, `format_filename` is a no-op, since `os.fsdecode` returns strings unchanged. ## Other issues Under [File Path Arguments](https://click.palletsprojects.com/en/8.1.x/arguments#file-path-arguments) (emphasis mine): > In the previous example, the files were opened immediately. But what if we just want the filename? The naïve way is to use the default string argument type. However, remember that Click is Unicode-based, so the string will always be a Unicode value. Unfortunately, filenames can be Unicode or bytes depending on which operating system is being used. As such, the type is insufficient. > > Instead, you should be using the [Path](https://click.palletsprojects.com/en/8.1.x/api/#click.Path) type, which **automatically handles this ambiguity**. Not only will **it return either bytes or Unicode depending on what makes more sense**, but it will also be able to do some basic checks for you such as existence checks. `click.Path` always returns `str` as far as I can tell, unless you explicitly give `type=bytes` so I'm not sure which automatic handling this is referring to. I tried all the way back to Click 1 and didn't see it ever returning bytes. Maybe it's something related to Python 2 and the docs are outdated? --- These should use fspath. fsdecode calls fspath for you but the decoding part is a no-op since the input is a str. https://github.com/pallets/click/blob/9c6f4c8e1bb8670ce827c98559f57f6ee5935cd0/src/click/_compat.py#L391-L393 https://github.com/pallets/click/blob/8.1.3/src/click/types.py#L853 --- This fsdecode is a no-op if the `filename: str` type annotation is correct. The `!r` conversion means it gets printed with surrogate escape sequences visible which probably isn't what we want (I think it's probably better to print a replacement character — this is arguable because a technical user could in principle use the repr in Python). https://github.com/pallets/click/blob/9c6f4c8e1bb8670ce827c98559f57f6ee5935cd0/src/click/exceptions.py#L264-L268 click.File doesn't use the repr: https://github.com/pallets/click/blob/9c6f4c8e1bb8670ce827c98559f57f6ee5935cd0/src/click/types.py#L734 This works because sys.stderr.errors defaults to `"backslashreplace"`. If you caught this exception and tried to print it to stdout, it would cause a UnicodeEncodeError
I'd like to contribute a fix here if you agree it's an issue > This means that on Click 8, `format_filename` is a no-op, since `os.fsdecode` returns strings unchanged. Seems like it should always do that `encode(surrogate).decode()` instead? > Maybe it's something related to Python 2 and the docs are outdated? Yes. In general anything str/bytes related that looks confusing is due to adding Python 3 support then later dropping Python 2 support. It all needs to be cleaned up, and is a huge job. > The `!r` conversion means it gets printed with surrogate escape sequences visible Using `!r` everywhere was a mistaken way to put quotes around values in messages. It should use quotes explicitly instead `f"file '{filename}'"`. > I'd like to contribute a fix here if you agree it's an issue Sure! That said, I'm in the middle of a massive str/bytes/encoding refactor in Werkzeug right now, so I won't have time to also reason about how Click is doing things or review a PR for a while.
2023-07-05T18:27:21Z
[]
[]
pallets/click
2,555
pallets__click-2555
[ "2415" ]
9a536eebd958558c2cd24c17fb66fac112f1ac91
diff --git a/src/click/_compat.py b/src/click/_compat.py --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -576,12 +576,17 @@ def isatty(stream: t.IO[t.Any]) -> bool: def _make_cached_stream_func( - src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO] -) -> t.Callable[[], t.TextIO]: + src_func: t.Callable[[], t.Optional[t.TextIO]], + wrapper_func: t.Callable[[], t.TextIO], +) -> t.Callable[[], t.Optional[t.TextIO]]: cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() - def func() -> t.TextIO: + def func() -> t.Optional[t.TextIO]: stream = src_func() + + if stream is None: + return None + try: rv = cache.get(stream) except Exception: diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -10,6 +10,7 @@ import time import typing as t from gettext import gettext as _ +from io import StringIO from types import TracebackType from ._compat import _default_text_stdout @@ -61,8 +62,15 @@ def __init__( self.show_pos = show_pos self.item_show_func = item_show_func self.label: str = label or "" + if file is None: file = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if file is None: + file = StringIO() + self.file = file self.color = color self.update_min_steps = update_min_steps @@ -352,6 +360,12 @@ def generator(self) -> t.Iterator[V]: def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None: """Decide what method to use for paging through text.""" stdout = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if stdout is None: + stdout = StringIO() + if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, generator, color) pager_cmd = (os.environ.get("PAGER", None) or "").strip() diff --git a/src/click/utils.py b/src/click/utils.py --- a/src/click/utils.py +++ b/src/click/utils.py @@ -267,6 +267,11 @@ def echo( else: file = _default_text_stdout() + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if file is None: + return + # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, (str, bytes, bytearray)): out: t.Optional[t.Union[str, bytes]] = str(message)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -43,6 +43,15 @@ def test_echo_custom_file(): assert f.getvalue() == "hello\n" +def test_echo_no_streams(monkeypatch, runner): + """echo should not fail when stdout and stderr are None with pythonw on Windows.""" + with runner.isolation(): + sys.stdout = None + sys.stderr = None + click.echo("test") + click.echo("test", err=True) + + @pytest.mark.parametrize( ("styles", "ref"), [
Error in click.utils.echo() when console is unavailable The `click.utils.echo()` function does not seem to account for the case when the console is not available on Windows, i.e., when running under `pythonw.exe` interpreter instead of the `python.exe` one. Minimal example: ```python # program.py import sys import os try: import click click.utils.echo("Hello world") except Exception: import traceback error_file = os.path.join(os.path.dirname(__file__), "error_log.txt") with open(error_file, "w") as fp: traceback.print_exc(file=fp) ``` Running this program with `pythonw.exe program.py` produces the `error_log.txt`: ``` Traceback (most recent call last): File "C:\Users\Rok\Development\pyi-click\program.py", line 6, in <module> click.utils.echo("Hello world") File "C:\Users\Rok\Development\pyi-click\venv\lib\site-packages\click\utils.py", line 299, in echo file.write(out) # type: ignore AttributeError: 'NoneType' object has no attribute 'write' ``` In contrast, standard `print()` function gracefully handles situations when console is unavailable and `sys.stdout` and `sys.stderr` are `None`. This attempt at retrieving stdout/stderr: https://github.com/pallets/click/blob/c65c6ad18471448c0fcc59ef53088787288c02cc/src/click/utils.py#L250-L254 should be followed by another `None` check, and if the stream is unavailable, the function should become a no-op (exit immediately). Environment: - OS: Windows - Python version: any - Click version: 8.1.3 (and earlier)
A workaround for this problem is setting `stdout` and `stdin` to `/dev/null`, here is an example that works for linux and windows: ``` import os import sys f = open(os.devnull, 'w') sys.stdin = f sys.stdout = f ```
2023-07-06T16:43:54Z
[]
[]
pallets/click
2,591
pallets__click-2591
[ "2590" ]
f5e47a6fc29c515c5c23bab297e1454c054844cb
diff --git a/examples/complex/complex/cli.py b/examples/complex/complex/cli.py --- a/examples/complex/complex/cli.py +++ b/examples/complex/complex/cli.py @@ -28,7 +28,7 @@ def vlog(self, msg, *args): cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands")) -class ComplexCLI(click.MultiCommand): +class ComplexCLI(click.Group): def list_commands(self, ctx): rv = [] for filename in os.listdir(cmd_folder): diff --git a/src/click/__init__.py b/src/click/__init__.py --- a/src/click/__init__.py +++ b/src/click/__init__.py @@ -5,12 +5,10 @@ composable. """ from .core import Argument as Argument -from .core import BaseCommand as BaseCommand from .core import Command as Command from .core import CommandCollection as CommandCollection from .core import Context as Context from .core import Group as Group -from .core import MultiCommand as MultiCommand from .core import Option as Option from .core import Parameter as Parameter from .decorators import argument as argument @@ -71,3 +69,31 @@ from .utils import open_file as open_file __version__ = "8.2.0.dev0" + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + from .core import _BaseCommand + + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + from .core import _MultiCommand + + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + raise AttributeError(name) diff --git a/src/click/core.py b/src/click/core.py --- a/src/click/core.py +++ b/src/click/core.py @@ -54,7 +54,7 @@ def _complete_visible_commands( :param ctx: Invocation context for the group. :param incomplete: Value being completed. May be empty. """ - multi = t.cast(MultiCommand, ctx.command) + multi = t.cast(Group, ctx.command) for name in multi.list_commands(ctx): if name.startswith(incomplete): @@ -64,28 +64,24 @@ def _complete_visible_commands( yield name, command -def _check_multicommand( - base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False +def _check_nested_chain( + base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False ) -> None: - if not base_command.chain or not isinstance(cmd, MultiCommand): + if not base_command.chain or not isinstance(cmd, Group): return + if register: - hint = ( - "It is not possible to add multi commands as children to" - " another multi command that is in chain mode." + message = ( + f"It is not possible to add the group {cmd_name!r} to another" + f" group {base_command.name!r} that is in chain mode." ) else: - hint = ( - "Found a multi command as subcommand to a multi command" - " that is in chain mode. This is not supported." + message = ( + f"Found the group {cmd_name!r} as subcommand to another group " + f" {base_command.name!r} that is in chain mode. This is not supported." ) - raise RuntimeError( - f"{hint}. Command {base_command.name!r} is set to chain and" - f" {cmd_name!r} was added as a subcommand but it in itself is a" - f" multi command. ({cmd_name!r} is a {type(cmd).__name__}" - f" within a chained {type(base_command).__name__} named" - f" {base_command.name!r})." - ) + + raise RuntimeError(message) def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]: @@ -831,36 +827,62 @@ def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]: return self._parameter_source.get(name) -class BaseCommand: - """The base command implements the minimal API contract of commands. - Most code will never use this as it does not implement a lot of useful - functionality but it can act as the direct subclass of alternative - parsing methods that do not depend on the Click parser. - - For instance, this can be used to bridge Click and other systems like - argparse or docopt. - - Because base commands do not implement a lot of the API that other - parts of Click take for granted, they are not supported for all - operations. For instance, they cannot be used with the decorators - usually and they have no built-in callback system. - - .. versionchanged:: 2.0 - Added the `context_settings` parameter. +class Command: + """Commands are the basic building block of command line interfaces in + Click. A basic command handles command line parsing and might dispatch + more parsing to commands nested below it. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. + :param callback: the callback to invoke. This is optional. + :param params: the parameters to register with this command. This can + be either :class:`Option` or :class:`Argument` objects. + :param help: the help string to use for this command. + :param epilog: like the help string but it's printed at the end of the + help page after everything else. + :param short_help: the short help to use for this command. This is + shown on the command listing of the parent command. + :param add_help_option: by default each command registers a ``--help`` + option. This can be disabled by this parameter. + :param no_args_is_help: this controls what happens if no arguments are + provided. This option is disabled by default. + If enabled this will add ``--help`` as argument + if no arguments are passed + :param hidden: hide this command from help outputs. + + :param deprecated: issues a message indicating that + the command is deprecated. + + .. versionchanged:: 8.2 + This is the base class for all commands, not ``BaseCommand``. + + .. versionchanged:: 8.1 + ``help``, ``epilog``, and ``short_help`` are stored unprocessed, + all formatting is done when outputting help text, not at init, + and is done even if not using the ``@command`` decorator. + + .. versionchanged:: 8.0 + Added a ``repr`` showing the command name. + + .. versionchanged:: 7.1 + Added the ``no_args_is_help`` parameter. + + .. versionchanged:: 2.0 + Added the ``context_settings`` parameter. """ #: The context class to create with :meth:`make_context`. #: #: .. versionadded:: 8.0 context_class: t.Type[Context] = Context + #: the default for the :attr:`Context.allow_extra_args` flag. allow_extra_args = False + #: the default for the :attr:`Context.allow_interspersed_args` flag. allow_interspersed_args = True + #: the default for the :attr:`Context.ignore_unknown_options` flag. ignore_unknown_options = False @@ -868,6 +890,16 @@ def __init__( self, name: t.Optional[str], context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, + callback: t.Optional[t.Callable[..., t.Any]] = None, + params: t.Optional[t.List["Parameter"]] = None, + help: t.Optional[str] = None, + epilog: t.Optional[str] = None, + short_help: t.Optional[str] = None, + options_metavar: t.Optional[str] = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool = False, ) -> None: #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name @@ -881,28 +913,188 @@ def __init__( #: an optional dictionary with defaults passed to the context. self.context_settings: t.MutableMapping[str, t.Any] = context_settings + #: the callback to execute when the command fires. This might be + #: `None` in which case nothing happens. + self.callback = callback + #: the list of parameters for this command in the order they + #: should show up in the help page and execute. Eager parameters + #: will automatically be handled before non eager ones. + self.params: t.List["Parameter"] = params or [] + self.help = help + self.epilog = epilog + self.options_metavar = options_metavar + self.short_help = short_help + self.add_help_option = add_help_option + self.no_args_is_help = no_args_is_help + self.hidden = hidden + self.deprecated = deprecated + def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: - """Gather information that could be useful for a tool generating - user-facing documentation. This traverses the entire structure - below this command. + return { + "name": self.name, + "params": [param.to_info_dict() for param in self.get_params(ctx)], + "help": self.help, + "epilog": self.epilog, + "short_help": self.short_help, + "hidden": self.hidden, + "deprecated": self.deprecated, + } - Use :meth:`click.Context.to_info_dict` to traverse the entire - CLI structure. + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self.name}>" - :param ctx: A :class:`Context` representing this command. + def get_usage(self, ctx: Context) -> str: + """Formats the usage line into a string and returns it. - .. versionadded:: 8.0 + Calls :meth:`format_usage` internally. """ - return {"name": self.name} + formatter = ctx.make_formatter() + self.format_usage(ctx, formatter) + return formatter.getvalue().rstrip("\n") - def __repr__(self) -> str: - return f"<{self.__class__.__name__} {self.name}>" + def get_params(self, ctx: Context) -> t.List["Parameter"]: + rv = self.params + help_option = self.get_help_option(ctx) - def get_usage(self, ctx: Context) -> str: - raise NotImplementedError("Base commands cannot get usage") + if help_option is not None: + rv = [*rv, help_option] + + return rv + + def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the usage line into the formatter. + + This is a low-level method called by :meth:`get_usage`. + """ + pieces = self.collect_usage_pieces(ctx) + formatter.write_usage(ctx.command_path, " ".join(pieces)) + + def collect_usage_pieces(self, ctx: Context) -> t.List[str]: + """Returns all the pieces that go into the usage line and returns + it as a list of strings. + """ + rv = [self.options_metavar] if self.options_metavar else [] + + for param in self.get_params(ctx): + rv.extend(param.get_usage_pieces(ctx)) + + return rv + + def get_help_option_names(self, ctx: Context) -> t.List[str]: + """Returns the names for the help option.""" + all_names = set(ctx.help_option_names) + for param in self.params: + all_names.difference_update(param.opts) + all_names.difference_update(param.secondary_opts) + return list(all_names) + + def get_help_option(self, ctx: Context) -> t.Optional["Option"]: + """Returns the help option object.""" + help_options = self.get_help_option_names(ctx) + + if not help_options or not self.add_help_option: + return None + + def show_help(ctx: Context, param: "Parameter", value: str) -> None: + if value and not ctx.resilient_parsing: + echo(ctx.get_help(), color=ctx.color) + ctx.exit() + + return Option( + help_options, + is_flag=True, + is_eager=True, + expose_value=False, + callback=show_help, + help=_("Show this message and exit."), + ) + + def make_parser(self, ctx: Context) -> OptionParser: + """Creates the underlying option parser for this command.""" + parser = OptionParser(ctx) + for param in self.get_params(ctx): + param.add_to_parser(parser, ctx) + return parser def get_help(self, ctx: Context) -> str: - raise NotImplementedError("Base commands cannot get help") + """Formats the help into a string and returns it. + + Calls :meth:`format_help` internally. + """ + formatter = ctx.make_formatter() + self.format_help(ctx, formatter) + return formatter.getvalue().rstrip("\n") + + def get_short_help_str(self, limit: int = 45) -> str: + """Gets short help for the command or makes it by shortening the + long help string. + """ + if self.short_help: + text = inspect.cleandoc(self.short_help) + elif self.help: + text = make_default_short_help(self.help, limit) + else: + text = "" + + if self.deprecated: + text = _("(Deprecated) {text}").format(text=text) + + return text.strip() + + def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the help into the formatter if it exists. + + This is a low-level method called by :meth:`get_help`. + + This calls the following methods: + + - :meth:`format_usage` + - :meth:`format_help_text` + - :meth:`format_options` + - :meth:`format_epilog` + """ + self.format_usage(ctx, formatter) + self.format_help_text(ctx, formatter) + self.format_options(ctx, formatter) + self.format_epilog(ctx, formatter) + + def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the help text to the formatter if it exists.""" + if self.help is not None: + # truncate the help text to the first form feed + text = inspect.cleandoc(self.help).partition("\f")[0] + else: + text = "" + + if self.deprecated: + text = _("(Deprecated) {text}").format(text=text) + + if text: + formatter.write_paragraph() + + with formatter.indentation(): + formatter.write_text(text) + + def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes all the options into the formatter if they exist.""" + opts = [] + for param in self.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + opts.append(rv) + + if opts: + with formatter.section(_("Options")): + formatter.write_dl(opts) + + def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the epilog into the formatter if it exists.""" + if self.epilog: + epilog = inspect.cleandoc(self.epilog) + formatter.write_paragraph() + + with formatter.indentation(): + formatter.write_text(epilog) def make_context( self, @@ -935,37 +1127,58 @@ def make_context( if key not in extra: extra[key] = value - ctx = self.context_class( - self, info_name=info_name, parent=parent, **extra # type: ignore - ) + ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) with ctx.scope(cleanup=False): self.parse_args(ctx, args) return ctx def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: - """Given a context and a list of arguments this creates the parser - and parses the arguments, then modifies the context as necessary. - This is automatically invoked by :meth:`make_context`. - """ - raise NotImplementedError("Base commands do not know how to parse arguments.") + if not args and self.no_args_is_help and not ctx.resilient_parsing: + echo(ctx.get_help(), color=ctx.color) + ctx.exit() - def invoke(self, ctx: Context) -> t.Any: - """Given a context, this invokes the command. The default - implementation is raising a not implemented error. - """ - raise NotImplementedError("Base commands are not invocable by default") + parser = self.make_parser(ctx) + opts, args, param_order = parser.parse_args(args=args) - def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: - """Return a list of completions for the incomplete value. Looks - at the names of chained multi-commands. + for param in iter_params_for_processing(param_order, self.get_params(ctx)): + value, args = param.handle_parse_result(ctx, opts, args) - Any command could be part of a chained multi-command, so sibling - commands are valid at any point during command completion. Other - command classes will return more completions. + if args and not ctx.allow_extra_args and not ctx.resilient_parsing: + ctx.fail( + ngettext( + "Got unexpected extra argument ({args})", + "Got unexpected extra arguments ({args})", + len(args), + ).format(args=" ".join(map(str, args))) + ) - :param ctx: Invocation context for this command. - :param incomplete: Value being completed. May be empty. + ctx.args = args + ctx._opt_prefixes.update(parser._opt_prefixes) + return args + + def invoke(self, ctx: Context) -> t.Any: + """Given a context, this invokes the attached callback (if it exists) + in the right way. + """ + if self.deprecated: + message = _( + "DeprecationWarning: The command {name!r} is deprecated." + ).format(name=self.name) + echo(style(message, fg="red"), err=True) + + if self.callback is not None: + return ctx.invoke(self.callback, **ctx.params) + + def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: + """Return a list of completions for the incomplete value. Looks + at the names of options and chained multi-commands. + + Any command could be part of a chained multi-command, so sibling + commands are valid at any point during command completion. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ @@ -973,10 +1186,29 @@ def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionIte results: t.List["CompletionItem"] = [] + if incomplete and not incomplete[0].isalnum(): + for param in self.get_params(ctx): + if ( + not isinstance(param, Option) + or param.hidden + or ( + not param.multiple + and ctx.get_parameter_source(param.name) # type: ignore + is ParameterSource.COMMANDLINE + ) + ): + continue + + results.extend( + CompletionItem(name, help=param.help) + for name in [*param.opts, *param.secondary_opts] + if name.startswith(incomplete) + ) + while ctx.parent is not None: ctx = ctx.parent - if isinstance(ctx.command, MultiCommand) and ctx.command.chain: + if isinstance(ctx.command, Group) and ctx.command.chain: results.extend( CompletionItem(name, help=command.get_short_help_str()) for name, command in _complete_visible_commands(ctx, incomplete) @@ -1157,411 +1389,254 @@ def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: return self.main(*args, **kwargs) -class Command(BaseCommand): - """Commands are the basic building block of command line interfaces in - Click. A basic command handles command line parsing and might dispatch - more parsing to commands nested below it. +class _FakeSubclassCheck(type): + def __subclasscheck__(cls, subclass: type) -> bool: + return issubclass(subclass, cls.__bases__[0]) - :param name: the name of the command to use unless a group overrides it. - :param context_settings: an optional dictionary with defaults that are - passed to the context object. - :param callback: the callback to invoke. This is optional. - :param params: the parameters to register with this command. This can - be either :class:`Option` or :class:`Argument` objects. - :param help: the help string to use for this command. - :param epilog: like the help string but it's printed at the end of the - help page after everything else. - :param short_help: the short help to use for this command. This is - shown on the command listing of the parent command. - :param add_help_option: by default each command registers a ``--help`` - option. This can be disabled by this parameter. - :param no_args_is_help: this controls what happens if no arguments are - provided. This option is disabled by default. - If enabled this will add ``--help`` as argument - if no arguments are passed - :param hidden: hide this command from help outputs. + def __instancecheck__(cls, instance: t.Any) -> bool: + return isinstance(instance, cls.__bases__[0]) - :param deprecated: issues a message indicating that - the command is deprecated. - .. versionchanged:: 8.1 - ``help``, ``epilog``, and ``short_help`` are stored unprocessed, - all formatting is done when outputting help text, not at init, - and is done even if not using the ``@command`` decorator. - - .. versionchanged:: 8.0 - Added a ``repr`` showing the command name. - - .. versionchanged:: 7.1 - Added the ``no_args_is_help`` parameter. - - .. versionchanged:: 2.0 - Added the ``context_settings`` parameter. +class _BaseCommand(Command, metaclass=_FakeSubclassCheck): + """ + .. deprecated:: 8.2 + Will be removed in Click 9.0. Use ``Command`` instead. """ - def __init__( - self, - name: t.Optional[str], - context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, - callback: t.Optional[t.Callable[..., t.Any]] = None, - params: t.Optional[t.List["Parameter"]] = None, - help: t.Optional[str] = None, - epilog: t.Optional[str] = None, - short_help: t.Optional[str] = None, - options_metavar: t.Optional[str] = "[OPTIONS]", - add_help_option: bool = True, - no_args_is_help: bool = False, - hidden: bool = False, - deprecated: bool = False, - ) -> None: - super().__init__(name, context_settings) - #: the callback to execute when the command fires. This might be - #: `None` in which case nothing happens. - self.callback = callback - #: the list of parameters for this command in the order they - #: should show up in the help page and execute. Eager parameters - #: will automatically be handled before non eager ones. - self.params: t.List["Parameter"] = params or [] - self.help = help - self.epilog = epilog - self.options_metavar = options_metavar - self.short_help = short_help - self.add_help_option = add_help_option - self.no_args_is_help = no_args_is_help - self.hidden = hidden - self.deprecated = deprecated - - def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: - info_dict = super().to_info_dict(ctx) - info_dict.update( - params=[param.to_info_dict() for param in self.get_params(ctx)], - help=self.help, - epilog=self.epilog, - short_help=self.short_help, - hidden=self.hidden, - deprecated=self.deprecated, - ) - return info_dict - - def get_usage(self, ctx: Context) -> str: - """Formats the usage line into a string and returns it. - - Calls :meth:`format_usage` internally. - """ - formatter = ctx.make_formatter() - self.format_usage(ctx, formatter) - return formatter.getvalue().rstrip("\n") - - def get_params(self, ctx: Context) -> t.List["Parameter"]: - rv = self.params - help_option = self.get_help_option(ctx) - - if help_option is not None: - rv = [*rv, help_option] - return rv +class Group(Command): + """A group is a command that nests other commands (or more groups). - def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the usage line into the formatter. + :param name: The name of the group command. + :param commands: Map names to :class:`Command` objects. Can be a list, which + will use :attr:`Command.name` as the keys. + :param invoke_without_command: Invoke the group's callback even if a + subcommand is not given. + :param no_args_is_help: If no arguments are given, show the group's help and + exit. Defaults to the opposite of ``invoke_without_command``. + :param subcommand_metavar: How to represent the subcommand argument in help. + The default will represent whether ``chain`` is set or not. + :param chain: Allow passing more than one subcommand argument. After parsing + a command's arguments, if any arguments remain another command will be + matched, and so on. + :param result_callback: A function to call after the group's and + subcommand's callbacks. The value returned by the subcommand is passed. + If ``chain`` is enabled, the value will be a list of values returned by + all the commands. If ``invoke_without_command`` is enabled, the value + will be the value returned by the group's callback, or an empty list if + ``chain`` is enabled. + :param kwargs: Other arguments passed to :class:`Command`. + + .. versionchanged:: 8.2 + Merged with and replaces the ``MultiCommand`` base class. - This is a low-level method called by :meth:`get_usage`. - """ - pieces = self.collect_usage_pieces(ctx) - formatter.write_usage(ctx.command_path, " ".join(pieces)) + .. versionchanged:: 8.0 + The ``commands`` argument can be a list of command objects. + """ - def collect_usage_pieces(self, ctx: Context) -> t.List[str]: - """Returns all the pieces that go into the usage line and returns - it as a list of strings. - """ - rv = [self.options_metavar] if self.options_metavar else [] + allow_extra_args = True + allow_interspersed_args = False - for param in self.get_params(ctx): - rv.extend(param.get_usage_pieces(ctx)) + #: If set, this is used by the group's :meth:`command` decorator + #: as the default :class:`Command` class. This is useful to make all + #: subcommands use a custom command class. + #: + #: .. versionadded:: 8.0 + command_class: t.Optional[t.Type[Command]] = None - return rv + #: If set, this is used by the group's :meth:`group` decorator + #: as the default :class:`Group` class. This is useful to make all + #: subgroups use a custom group class. + #: + #: If set to the special value :class:`type` (literally + #: ``group_class = type``), this group's class will be used as the + #: default class. This makes a custom group class continue to make + #: custom groups. + #: + #: .. versionadded:: 8.0 + group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None + # Literal[type] isn't valid, so use Type[type] - def get_help_option_names(self, ctx: Context) -> t.List[str]: - """Returns the names for the help option.""" - all_names = set(ctx.help_option_names) - for param in self.params: - all_names.difference_update(param.opts) - all_names.difference_update(param.secondary_opts) - return list(all_names) + def __init__( + self, + name: t.Optional[str] = None, + commands: t.Optional[ + t.Union[t.MutableMapping[str, Command], t.Sequence[Command]] + ] = None, + invoke_without_command: bool = False, + no_args_is_help: t.Optional[bool] = None, + subcommand_metavar: t.Optional[str] = None, + chain: bool = False, + result_callback: t.Optional[t.Callable[..., t.Any]] = None, + **kwargs: t.Any, + ) -> None: + super().__init__(name, **kwargs) - def get_help_option(self, ctx: Context) -> t.Optional["Option"]: - """Returns the help option object.""" - help_options = self.get_help_option_names(ctx) + if commands is None: + commands = {} + elif isinstance(commands, abc.Sequence): + commands = {c.name: c for c in commands if c.name is not None} - if not help_options or not self.add_help_option: - return None + #: The registered subcommands by their exported names. + self.commands: t.MutableMapping[str, Command] = commands - def show_help(ctx: Context, param: "Parameter", value: str) -> None: - if value and not ctx.resilient_parsing: - echo(ctx.get_help(), color=ctx.color) - ctx.exit() + if no_args_is_help is None: + no_args_is_help = not invoke_without_command - return Option( - help_options, - is_flag=True, - is_eager=True, - expose_value=False, - callback=show_help, - help=_("Show this message and exit."), - ) + self.no_args_is_help = no_args_is_help + self.invoke_without_command = invoke_without_command - def make_parser(self, ctx: Context) -> OptionParser: - """Creates the underlying option parser for this command.""" - parser = OptionParser(ctx) - for param in self.get_params(ctx): - param.add_to_parser(parser, ctx) - return parser + if subcommand_metavar is None: + if chain: + subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." + else: + subcommand_metavar = "COMMAND [ARGS]..." - def get_help(self, ctx: Context) -> str: - """Formats the help into a string and returns it. + self.subcommand_metavar = subcommand_metavar + self.chain = chain + # The result callback that is stored. This can be set or + # overridden with the :func:`result_callback` decorator. + self._result_callback = result_callback - Calls :meth:`format_help` internally. - """ - formatter = ctx.make_formatter() - self.format_help(ctx, formatter) - return formatter.getvalue().rstrip("\n") + if self.chain: + for param in self.params: + if isinstance(param, Argument) and not param.required: + raise RuntimeError( + "A group in chain mode cannot have optional arguments." + ) - def get_short_help_str(self, limit: int = 45) -> str: - """Gets short help for the command or makes it by shortening the - long help string. - """ - if self.short_help: - text = inspect.cleandoc(self.short_help) - elif self.help: - text = make_default_short_help(self.help, limit) - else: - text = "" + def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: + info_dict = super().to_info_dict(ctx) + commands = {} - if self.deprecated: - text = _("(Deprecated) {text}").format(text=text) + for name in self.list_commands(ctx): + command = self.get_command(ctx, name) - return text.strip() + if command is None: + continue - def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the help into the formatter if it exists. + sub_ctx = ctx._make_sub_context(command) - This is a low-level method called by :meth:`get_help`. + with sub_ctx.scope(cleanup=False): + commands[name] = command.to_info_dict(sub_ctx) - This calls the following methods: + info_dict.update(commands=commands, chain=self.chain) + return info_dict - - :meth:`format_usage` - - :meth:`format_help_text` - - :meth:`format_options` - - :meth:`format_epilog` + def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: + """Registers another :class:`Command` with this group. If the name + is not provided, the name of the command is used. """ - self.format_usage(ctx, formatter) - self.format_help_text(ctx, formatter) - self.format_options(ctx, formatter) - self.format_epilog(ctx, formatter) - - def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the help text to the formatter if it exists.""" - if self.help is not None: - # truncate the help text to the first form feed - text = inspect.cleandoc(self.help).partition("\f")[0] - else: - text = "" - - if self.deprecated: - text = _("(Deprecated) {text}").format(text=text) - - if text: - formatter.write_paragraph() - - with formatter.indentation(): - formatter.write_text(text) - - def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes all the options into the formatter if they exist.""" - opts = [] - for param in self.get_params(ctx): - rv = param.get_help_record(ctx) - if rv is not None: - opts.append(rv) - - if opts: - with formatter.section(_("Options")): - formatter.write_dl(opts) - - def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the epilog into the formatter if it exists.""" - if self.epilog: - epilog = inspect.cleandoc(self.epilog) - formatter.write_paragraph() - - with formatter.indentation(): - formatter.write_text(epilog) - - def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: - if not args and self.no_args_is_help and not ctx.resilient_parsing: - echo(ctx.get_help(), color=ctx.color) - ctx.exit() - - parser = self.make_parser(ctx) - opts, args, param_order = parser.parse_args(args=args) - - for param in iter_params_for_processing(param_order, self.get_params(ctx)): - value, args = param.handle_parse_result(ctx, opts, args) - - if args and not ctx.allow_extra_args and not ctx.resilient_parsing: - ctx.fail( - ngettext( - "Got unexpected extra argument ({args})", - "Got unexpected extra arguments ({args})", - len(args), - ).format(args=" ".join(map(str, args))) - ) + name = name or cmd.name + if name is None: + raise TypeError("Command has no name.") + _check_nested_chain(self, name, cmd, register=True) + self.commands[name] = cmd - ctx.args = args - ctx._opt_prefixes.update(parser._opt_prefixes) - return args + @t.overload + def command(self, __func: t.Callable[..., t.Any]) -> Command: + ... - def invoke(self, ctx: Context) -> t.Any: - """Given a context, this invokes the attached callback (if it exists) - in the right way. - """ - if self.deprecated: - message = _( - "DeprecationWarning: The command {name!r} is deprecated." - ).format(name=self.name) - echo(style(message, fg="red"), err=True) + @t.overload + def command( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Command]: + ... - if self.callback is not None: - return ctx.invoke(self.callback, **ctx.params) + def command( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]: + """A shortcut decorator for declaring and attaching a command to + the group. This takes the same arguments as :func:`command` and + immediately registers the created command with this group by + calling :meth:`add_command`. - def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: - """Return a list of completions for the incomplete value. Looks - at the names of options and chained multi-commands. + To customize the command class used, set the + :attr:`command_class` attribute. - :param ctx: Invocation context for this command. - :param incomplete: Value being completed. May be empty. + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. - .. versionadded:: 8.0 + .. versionchanged:: 8.0 + Added the :attr:`command_class` attribute. """ - from click.shell_completion import CompletionItem - - results: t.List["CompletionItem"] = [] - - if incomplete and not incomplete[0].isalnum(): - for param in self.get_params(ctx): - if ( - not isinstance(param, Option) - or param.hidden - or ( - not param.multiple - and ctx.get_parameter_source(param.name) # type: ignore - is ParameterSource.COMMANDLINE - ) - ): - continue - - results.extend( - CompletionItem(name, help=param.help) - for name in [*param.opts, *param.secondary_opts] - if name.startswith(incomplete) - ) - - results.extend(super().shell_complete(ctx, incomplete)) - return results + from .decorators import command + func: t.Optional[t.Callable[..., t.Any]] = None -class MultiCommand(Command): - """A multi command is the basic implementation of a command that - dispatches to subcommands. The most common version is the - :class:`Group`. + if args and callable(args[0]): + assert ( + len(args) == 1 and not kwargs + ), "Use 'command(**kwargs)(callable)' to provide arguments." + (func,) = args + args = () - :param invoke_without_command: this controls how the multi command itself - is invoked. By default it's only invoked - if a subcommand is provided. - :param no_args_is_help: this controls what happens if no arguments are - provided. This option is enabled by default if - `invoke_without_command` is disabled or disabled - if it's enabled. If enabled this will add - ``--help`` as argument if no arguments are - passed. - :param subcommand_metavar: the string that is used in the documentation - to indicate the subcommand place. - :param chain: if this is set to `True` chaining of multiple subcommands - is enabled. This restricts the form of commands in that - they cannot have optional arguments but it allows - multiple commands to be chained together. - :param result_callback: The result callback to attach to this multi - command. This can be set or changed later with the - :meth:`result_callback` decorator. - :param attrs: Other command arguments described in :class:`Command`. - """ + if self.command_class and kwargs.get("cls") is None: + kwargs["cls"] = self.command_class - allow_extra_args = True - allow_interspersed_args = False + def decorator(f: t.Callable[..., t.Any]) -> Command: + cmd: Command = command(*args, **kwargs)(f) + self.add_command(cmd) + return cmd - def __init__( - self, - name: t.Optional[str] = None, - invoke_without_command: bool = False, - no_args_is_help: t.Optional[bool] = None, - subcommand_metavar: t.Optional[str] = None, - chain: bool = False, - result_callback: t.Optional[t.Callable[..., t.Any]] = None, - **attrs: t.Any, - ) -> None: - super().__init__(name, **attrs) + if func is not None: + return decorator(func) - if no_args_is_help is None: - no_args_is_help = not invoke_without_command + return decorator - self.no_args_is_help = no_args_is_help - self.invoke_without_command = invoke_without_command + @t.overload + def group(self, __func: t.Callable[..., t.Any]) -> "Group": + ... - if subcommand_metavar is None: - if chain: - subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." - else: - subcommand_metavar = "COMMAND [ARGS]..." + @t.overload + def group( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]: + ... - self.subcommand_metavar = subcommand_metavar - self.chain = chain - # The result callback that is stored. This can be set or - # overridden with the :func:`result_callback` decorator. - self._result_callback = result_callback + def group( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: + """A shortcut decorator for declaring and attaching a group to + the group. This takes the same arguments as :func:`group` and + immediately registers the created group with this group by + calling :meth:`add_command`. - if self.chain: - for param in self.params: - if isinstance(param, Argument) and not param.required: - raise RuntimeError( - "Multi commands in chain mode cannot have" - " optional arguments." - ) + To customize the group class used, set the :attr:`group_class` + attribute. - def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: - info_dict = super().to_info_dict(ctx) - commands = {} + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. - for name in self.list_commands(ctx): - command = self.get_command(ctx, name) + .. versionchanged:: 8.0 + Added the :attr:`group_class` attribute. + """ + from .decorators import group - if command is None: - continue + func: t.Optional[t.Callable[..., t.Any]] = None - sub_ctx = ctx._make_sub_context(command) + if args and callable(args[0]): + assert ( + len(args) == 1 and not kwargs + ), "Use 'group(**kwargs)(callable)' to provide arguments." + (func,) = args + args = () - with sub_ctx.scope(cleanup=False): - commands[name] = command.to_info_dict(sub_ctx) + if self.group_class is not None and kwargs.get("cls") is None: + if self.group_class is type: + kwargs["cls"] = type(self) + else: + kwargs["cls"] = self.group_class - info_dict.update(commands=commands, chain=self.chain) - return info_dict + def decorator(f: t.Callable[..., t.Any]) -> "Group": + cmd: Group = group(*args, **kwargs)(f) + self.add_command(cmd) + return cmd - def collect_usage_pieces(self, ctx: Context) -> t.List[str]: - rv = super().collect_usage_pieces(ctx) - rv.append(self.subcommand_metavar) - return rv + if func is not None: + return decorator(func) - def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: - super().format_options(ctx, formatter) - self.format_commands(ctx, formatter) + return decorator def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: """Adds a result callback to the command. By default if a @@ -1608,6 +1683,25 @@ def function(__value, *args, **kwargs): # type: ignore return decorator + def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: + """Given a context and a command name, this returns a :class:`Command` + object if it exists or returns ``None``. + """ + return self.commands.get(cmd_name) + + def list_commands(self, ctx: Context) -> t.List[str]: + """Returns a list of subcommand names in the order they should appear.""" + return sorted(self.commands) + + def collect_usage_pieces(self, ctx: Context) -> t.List[str]: + rv = super().collect_usage_pieces(ctx) + rv.append(self.subcommand_metavar) + return rv + + def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: + super().format_options(ctx, formatter) + self.format_commands(ctx, formatter) + def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: """Extra format methods for multi methods that adds all the commands after the options. @@ -1746,18 +1840,6 @@ def resolve_command( ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) return cmd_name if cmd else None, cmd, args[1:] - def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: - """Given a context and a command name, this returns a - :class:`Command` object if it exists or returns `None`. - """ - raise NotImplementedError - - def list_commands(self, ctx: Context) -> t.List[str]: - """Returns a list of subcommand names in the order they should - appear. - """ - return [] - def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: """Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained @@ -1778,220 +1860,62 @@ def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionIte return results -class Group(MultiCommand): - """A group allows a command to have subcommands attached. This is - the most common way to implement nesting in Click. - - :param name: The name of the group command. - :param commands: A dict mapping names to :class:`Command` objects. - Can also be a list of :class:`Command`, which will use - :attr:`Command.name` to create the dict. - :param attrs: Other command arguments described in - :class:`MultiCommand`, :class:`Command`, and - :class:`BaseCommand`. - - .. versionchanged:: 8.0 - The ``commands`` argument can be a list of command objects. +class _MultiCommand(Group, metaclass=_FakeSubclassCheck): + """ + .. deprecated:: 8.2 + Will be removed in Click 9.0. Use ``Group`` instead. """ - #: If set, this is used by the group's :meth:`command` decorator - #: as the default :class:`Command` class. This is useful to make all - #: subcommands use a custom command class. - #: - #: .. versionadded:: 8.0 - command_class: t.Optional[t.Type[Command]] = None - - #: If set, this is used by the group's :meth:`group` decorator - #: as the default :class:`Group` class. This is useful to make all - #: subgroups use a custom group class. - #: - #: If set to the special value :class:`type` (literally - #: ``group_class = type``), this group's class will be used as the - #: default class. This makes a custom group class continue to make - #: custom groups. - #: - #: .. versionadded:: 8.0 - group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None - # Literal[type] isn't valid, so use Type[type] - - def __init__( - self, - name: t.Optional[str] = None, - commands: t.Optional[ - t.Union[t.MutableMapping[str, Command], t.Sequence[Command]] - ] = None, - **attrs: t.Any, - ) -> None: - super().__init__(name, **attrs) - - if commands is None: - commands = {} - elif isinstance(commands, abc.Sequence): - commands = {c.name: c for c in commands if c.name is not None} - - #: The registered subcommands by their exported names. - self.commands: t.MutableMapping[str, Command] = commands - - def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: - """Registers another :class:`Command` with this group. If the name - is not provided, the name of the command is used. - """ - name = name or cmd.name - if name is None: - raise TypeError("Command has no name.") - _check_multicommand(self, name, cmd, register=True) - self.commands[name] = cmd - - @t.overload - def command(self, __func: t.Callable[..., t.Any]) -> Command: - ... - - @t.overload - def command( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], Command]: - ... - - def command( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]: - """A shortcut decorator for declaring and attaching a command to - the group. This takes the same arguments as :func:`command` and - immediately registers the created command with this group by - calling :meth:`add_command`. - - To customize the command class used, set the - :attr:`command_class` attribute. - - .. versionchanged:: 8.1 - This decorator can be applied without parentheses. - - .. versionchanged:: 8.0 - Added the :attr:`command_class` attribute. - """ - from .decorators import command - - func: t.Optional[t.Callable[..., t.Any]] = None - - if args and callable(args[0]): - assert ( - len(args) == 1 and not kwargs - ), "Use 'command(**kwargs)(callable)' to provide arguments." - (func,) = args - args = () - - if self.command_class and kwargs.get("cls") is None: - kwargs["cls"] = self.command_class - - def decorator(f: t.Callable[..., t.Any]) -> Command: - cmd: Command = command(*args, **kwargs)(f) - self.add_command(cmd) - return cmd - - if func is not None: - return decorator(func) - - return decorator - - @t.overload - def group(self, __func: t.Callable[..., t.Any]) -> "Group": - ... - - @t.overload - def group( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]: - ... - - def group( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: - """A shortcut decorator for declaring and attaching a group to - the group. This takes the same arguments as :func:`group` and - immediately registers the created group with this group by - calling :meth:`add_command`. - - To customize the group class used, set the :attr:`group_class` - attribute. - - .. versionchanged:: 8.1 - This decorator can be applied without parentheses. - - .. versionchanged:: 8.0 - Added the :attr:`group_class` attribute. - """ - from .decorators import group - - func: t.Optional[t.Callable[..., t.Any]] = None - - if args and callable(args[0]): - assert ( - len(args) == 1 and not kwargs - ), "Use 'group(**kwargs)(callable)' to provide arguments." - (func,) = args - args = () - - if self.group_class is not None and kwargs.get("cls") is None: - if self.group_class is type: - kwargs["cls"] = type(self) - else: - kwargs["cls"] = self.group_class - - def decorator(f: t.Callable[..., t.Any]) -> "Group": - cmd: Group = group(*args, **kwargs)(f) - self.add_command(cmd) - return cmd - - if func is not None: - return decorator(func) - - return decorator - - def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: - return self.commands.get(cmd_name) - - def list_commands(self, ctx: Context) -> t.List[str]: - return sorted(self.commands) +class CommandCollection(Group): + """A :class:`Group` that looks up subcommands on other groups. If a command + is not found on this group, each registered source is checked in order. + Parameters on a source are not added to this group, and a source's callback + is not invoked when invoking its commands. In other words, this "flattens" + commands in many groups into this one group. -class CommandCollection(MultiCommand): - """A command collection is a multi command that merges multiple multi - commands together into one. This is a straightforward implementation - that accepts a list of different multi commands as sources and - provides all the commands for each of them. + :param name: The name of the group command. + :param sources: A list of :class:`Group` objects to look up commands from. + :param kwargs: Other arguments passed to :class:`Group`. - See :class:`MultiCommand` and :class:`Command` for the description of - ``name`` and ``attrs``. + .. versionchanged:: 8.2 + This is a subclass of ``Group``. Commands are looked up first on this + group, then each of its sources. """ def __init__( self, name: t.Optional[str] = None, - sources: t.Optional[t.List[MultiCommand]] = None, - **attrs: t.Any, + sources: t.Optional[t.List[Group]] = None, + **kwargs: t.Any, ) -> None: - super().__init__(name, **attrs) - #: The list of registered multi commands. - self.sources: t.List[MultiCommand] = sources or [] + super().__init__(name, **kwargs) + #: The list of registered groups. + self.sources: t.List[Group] = sources or [] - def add_source(self, multi_cmd: MultiCommand) -> None: - """Adds a new multi command to the chain dispatcher.""" - self.sources.append(multi_cmd) + def add_source(self, group: Group) -> None: + """Add a group as a source of commands.""" + self.sources.append(group) def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: + rv = super().get_command(ctx, cmd_name) + + if rv is not None: + return rv + for source in self.sources: rv = source.get_command(ctx, cmd_name) if rv is not None: if self.chain: - _check_multicommand(self, cmd_name, rv) + _check_nested_chain(self, cmd_name, rv) return rv return None def list_commands(self, ctx: Context) -> t.List[str]: - rv: t.Set[str] = set() + rv: t.Set[str] = set(super().list_commands(ctx)) for source in self.sources: rv.update(source.list_commands(ctx)) @@ -3040,3 +2964,27 @@ def get_error_hint(self, ctx: Context) -> str: def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + raise AttributeError(name) diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -4,9 +4,9 @@ from gettext import gettext as _ from .core import Argument -from .core import BaseCommand +from .core import Command from .core import Context -from .core import MultiCommand +from .core import Group from .core import Option from .core import Parameter from .core import ParameterSource @@ -15,7 +15,7 @@ def shell_complete( - cli: BaseCommand, + cli: Command, ctx_args: t.MutableMapping[str, t.Any], prog_name: str, complete_var: str, @@ -215,7 +215,7 @@ class ShellComplete: def __init__( self, - cli: BaseCommand, + cli: Command, ctx_args: t.MutableMapping[str, t.Any], prog_name: str, complete_var: str, @@ -493,7 +493,7 @@ def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> def _resolve_context( - cli: BaseCommand, + cli: Command, ctx_args: t.MutableMapping[str, t.Any], prog_name: str, args: t.List[str], @@ -513,7 +513,7 @@ def _resolve_context( while args: command = ctx.command - if isinstance(command, MultiCommand): + if isinstance(command, Group): if not command.chain: name, cmd, args = command.resolve_command(ctx, args) @@ -551,7 +551,7 @@ def _resolve_context( def _resolve_incomplete( ctx: Context, args: t.List[str], incomplete: str -) -> t.Tuple[t.Union[BaseCommand, Parameter], str]: +) -> t.Tuple[t.Union[Command, Parameter], str]: """Find the Click object that will handle the completion of the incomplete value. Return the object and the incomplete value.
diff --git a/src/click/testing.py b/src/click/testing.py --- a/src/click/testing.py +++ b/src/click/testing.py @@ -14,7 +14,7 @@ from ._compat import _find_binary_reader if t.TYPE_CHECKING: - from .core import BaseCommand + from .core import Command class EchoingStdin: @@ -187,7 +187,7 @@ def __init__( self.echo_stdin = echo_stdin self.mix_stderr = mix_stderr - def get_default_prog_name(self, cli: "BaseCommand") -> str: + def get_default_prog_name(self, cli: "Command") -> str: """Given a command object it will return the default program name for it. The default is the `name` attribute or ``"root"`` if not set. @@ -348,7 +348,7 @@ def should_strip_ansi( def invoke( self, - cli: "BaseCommand", + cli: "Command", args: t.Optional[t.Union[str, t.Sequence[str]]] = None, input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None, env: t.Optional[t.Mapping[str, t.Optional[str]]] = None, diff --git a/tests/test_chain.py b/tests/test_chain.py --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -189,7 +189,7 @@ def c(): assert result.output.splitlines() == ["cli=", "a=", "b=", "c="] -def test_multicommand_arg_behavior(runner): +def test_group_arg_behavior(runner): with pytest.raises(RuntimeError): @click.group(chain=True) @@ -219,7 +219,7 @@ def a(): @pytest.mark.xfail -def test_multicommand_chaining(runner): +def test_group_chaining(runner): @click.group(chain=True) def cli(): debug() diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -145,14 +145,14 @@ def move(): assert expect in result.output -def test_base_command(runner): +def test_custom_parser(runner): import optparse @click.group() def cli(): pass - class OptParseCommand(click.BaseCommand): + class OptParseCommand(click.Command): def __init__(self, name, parser, callback): super().__init__(name) self.parser = parser
deprecate `MultiCommand`, merge into `Group` As part of rewriting the parser in #2205, I was looking at the complexities of Click's definitions and processing. `MultiCommand` and `CommandCollection` could be combined with `Group` to simplify to a single way of working with multiple commands. This is a little more difficult than #2589 removing `BaseCommand`. Currently, they're distinct because `Group` provides further `group` and `command` decorators. `MultiCommand` is the base and doesn't specify how commands are registered, and `CommandCollection` "flattens" multiple `MultiCommands` instead of nesting like `Group.group`. The docs occasionally refer to "mulitcommand" instead of "group" in situations where the user would probably understand "group" better. There are very few examples in the docs of either class, and all of them can be reasonably implemented with `Group` instead. #347 (and many linked issues) show a confusion over how `CommandCollection` is supposed to work. It doesn't use each source's parameters, and doesn't invoke the source's callback before a command. In other words, currently the collection only collects the commands in each source, but users expect it to _merge_ the behavior of all sources. I'm not entirely convinced that we should continue to support either of these things. But we could continue to support the current behavior by adding `Group.add_source` or `extend_commands` with the same behavior, where the command is looked up first on the group, then on each source. In the future we could also add a `merge_group` method.
2023-08-19T19:52:35Z
[]
[]
pallets/click
2,604
pallets__click-2604
[ "2322" ]
b63ace28d50b53e74b5260f6cb357ccfe5560133
diff --git a/src/click/decorators.py b/src/click/decorators.py --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -178,9 +178,10 @@ def command( callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command. - The name of the command defaults to the name of the function with - underscores replaced by dashes. If you want to change that, you can - pass the intended name as the first argument. + The name of the command defaults to the name of the function, converted to + lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes + ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example, + ``init_data_command`` becomes ``init-data``. All keyword arguments are forwarded to the underlying command class. For the ``params`` argument, any decorated params are appended to @@ -190,10 +191,13 @@ def command( that can be invoked as a command line utility or be attached to a command :class:`Group`. - :param name: the name of the command. This defaults to the function - name with underscores replaced by dashes. - :param cls: the command class to instantiate. This defaults to - :class:`Command`. + :param name: The name of the command. Defaults to modifying the function's + name as described above. + :param cls: The command class to create. Defaults to :class:`Command`. + + .. versionchanged:: 8.2 + The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are + removed when generating the name. .. versionchanged:: 8.1 This decorator can be applied without parentheses. @@ -236,12 +240,16 @@ def decorator(f: _AnyCallable) -> CmdType: assert cls is not None assert not callable(name) - cmd = cls( - name=name or f.__name__.lower().replace("_", "-"), - callback=f, - params=params, - **attrs, - ) + if name is not None: + cmd_name = name + else: + cmd_name = f.__name__.lower().replace("_", "-") + cmd_left, sep, suffix = cmd_name.rpartition("-") + + if sep and suffix in {"command", "cmd", "group", "grp"}: + cmd_name = cmd_left + + cmd = cls(name=cmd_name, callback=f, params=params, **attrs) cmd.__doc__ = f.__doc__ return cmd
diff --git a/tests/test_command_decorators.py b/tests/test_command_decorators.py --- a/tests/test_command_decorators.py +++ b/tests/test_command_decorators.py @@ -1,3 +1,5 @@ +import pytest + import click @@ -69,3 +71,22 @@ def cli(a, b): assert cli.params[1].name == "b" result = runner.invoke(cli, ["1", "2"]) assert result.output == "1 2\n" + + [email protected]( + "name", + [ + "init_data", + "init_data_command", + "init_data_cmd", + "init_data_group", + "init_data_grp", + ], +) +def test_generate_name(name: str) -> None: + def f(): + pass + + f.__name__ = name + f = click.command(f) + assert f.name == "init-data" diff --git a/tests/test_commands.py b/tests/test_commands.py --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -249,7 +249,7 @@ def other_cmd(ctx, a, b, c): result = runner.invoke(cli, standalone_mode=False) # invoke should type cast default values, str becomes int, empty # multiple should be empty tuple instead of None - assert result.return_value == ("other-cmd", 42, 15, ()) + assert result.return_value == ("other", 42, 15, ()) def test_invoked_subcommand(runner):
strip "_command" suffix when generating command name You often want a command to have the same name as a function it is wrapping. However, this will cause a name collision, if your command is going to call `init_data` its function can't also be called `init_data`. So instead it's written as `init_data_command`, and then the command name has to be specified manually `@command("init-data")`. Click should remove a `_command` suffix when generating the command name from the function name. ```python def init_data(external=False): ... @cli.command @click.option("--external/--internal") def init_data_command(external): init_data(external=external) ``` Currently this command would be named `init-data-command`. After the change, it would be `init-data`.
Hi @davidism, Am I right in assuming the expected behaviour would be that both `_command` and `_cmd` suffixes are dropped? An example using `_cmd` as a suffix: https://github.com/pallets/click/blob/fb4327216543d751e2654a0d3bf6ce3d31c435cc/examples/imagepipe/imagepipe.py#L74-L98
2023-09-01T21:14:41Z
[]
[]
pallets/click
2,728
pallets__click-2728
[ "2697" ]
e88c11239971d309744fd3f9139259f64787f45a
diff --git a/src/click/types.py b/src/click/types.py --- a/src/click/types.py +++ b/src/click/types.py @@ -892,7 +892,7 @@ def convert( ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( - _("{name} '{filename}' is a directory.").format( + _("{name} {filename!r} is a directory.").format( name=self.name.title(), filename=format_filename(value) ), param,
diff --git a/tests/test_types.py b/tests/test_types.py --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1,5 +1,6 @@ import os.path import pathlib +import platform import tempfile import pytest @@ -232,3 +233,14 @@ def test_file_surrogates(type, tmp_path): def test_file_error_surrogates(): message = FileError(filename="\udcff").format_message() assert message == "Could not open file '�': unknown error" + + [email protected]( + platform.system() == "Windows", reason="Filepath syntax differences." +) +def test_invalid_path_with_esc_sequence(): + with pytest.raises(click.BadParameter) as exc_info: + with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir: + click.Path(dir_okay=False).convert(tempdir, None, None) + + assert "my\\ndir" in exc_info.value.message
Broken message about invalid argument value for template "File ... is a directory" **User Actions** ```sh mkdir $'my\ndir' my-tool $'my\ndir' ``` **Expected Output** ``` Invalid value for 'PATH': File 'my\ndir' is a directory. ``` **Actual Output** ``` Invalid value for 'PATH': File 'my dir' is a directory. ``` **Code** ```python from pathlib import Path from typing import Annotated import typer def main(path: Annotated[Path, typer.Argument(dir_okay=False)]) -> None: pass if __name__ == '__main__': typer.run(main) ``` **Cause** You clearly forgot `!r` on [this](https://github.com/pallets/click/blob/f8857cb03268b5b952b88b2acb3e11d9f0f7b6e4/src/click/types.py#L896) line and are using quotes instead. Just compare these lines in [click.types](https://github.com/pallets/click/blob/f8857cb03268b5b952b88b2acb3e11d9f0f7b6e4/src/click/types.py#L870-L928): ```python _("{name} {filename!r} does not exist.").format( _("{name} {filename!r} is a file.").format( _("{name} '{filename}' is a directory.").format( _("{name} {filename!r} is not readable.").format( _("{name} {filename!r} is not writable.").format( _("{name} {filename!r} is not executable.").format( ```
I'm going to work on this at the PyCon 2024 sprints.
2024-05-20T23:23:43Z
[]
[]