Merge branch 'stable' into unset-in-default-map
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 6de2121, c7e1ba8 · Browse files · 26 files·+1940 added−1069 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+1940 added−1069 removed
- tests:+295 added−9 removed
- other:+1645 added−1060 removed
Provenance
- Commit
c07bb93- Tree
1553d62- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
6de2121- Parent 2
c7e1ba8
26 files changed+1940 added−1069 removed
added:docs/arguments.md+166 added
1+(arguments)=2+3+# Arguments4+5+```{currentmodule} click6+```7+8+Arguments are:9+10+* Are positional in nature.11+* Similar to a limited version of {ref}`options <options>` that can take an arbitrary number of inputs12+* {ref}`Documented manually <documenting-arguments>`.13+14+Useful and often used kwargs are:15+16+* `default`: Passes a default.17+* `nargs`: Sets the number of arguments. Set to -1 to take an arbitrary number.18+19+## Basic Arguments20+21+A minimal {class}`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type `str`.22+23+Example:24+25+```{eval-rst}26+.. click:example::27+28+ @click.command()29+ @click.argument('filename')30+ def touch(filename: str):31+ """Print FILENAME."""32+ click.echo(filename)33+34+And from the command line:35+36+.. click:run::37+38+ invoke(touch, args=['foo.txt'])39+```40+41+An argument may be assigned a {ref}`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be {data}`STRING`.42+43+```{admonition} Note on Required Arguments44+:class: note45+46+ It is possible to make an argument required by setting `required=True`. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.47+```48+49+## Multiple Arguments50+51+To set the number of argument use the `nargs` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.52+53+```{eval-rst}54+.. click:example::55+56+ @click.command()57+ @click.argument('src', nargs=1)58+ @click.argument('dsts', nargs=-1)59+ def copy(src: str, dsts: tuple[str, ...]):60+ """Move file SRC to DST."""61+ for destination in dsts:62+ click.echo(f"Copy {src} to folder {destination}")63+64+And from the command line:65+66+.. click:run::67+68+ invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])69+```70+71+```{admonition} Note on Handling Files72+:class: note73+74+ This is not how you should handle files and files paths. This merely used as a simple example. See {ref}`handling-files` to learn more about how to handle files in parameters.75+```76+77+## Argument Escape Sequences78+79+If you want to process arguments that look like options, like a file named `-foo.txt` or `--foo.txt` , you must pass the `--` separator first. After you pass the `--`, you may only pass arguments. This is a common feature for POSIX command line tools.80+81+Example usage:82+83+```{eval-rst}84+.. click:example::85+86+ @click.command()87+ @click.argument('files', nargs=-1, type=click.Path())88+ def touch(files):89+ """Print all FILES file names."""90+ for filename in files:91+ click.echo(filename)92+93+And from the command line:94+95+.. click:run::96+97+ invoke(touch, ['--', '-foo.txt', 'bar.txt'])98+```99+100+If you don't like the `--` marker, you can set ignore_unknown_options to True to avoid checking unknown options:101+102+```{eval-rst}103+.. click:example::104+105+ @click.command(context_settings={"ignore_unknown_options": True})106+ @click.argument('files', nargs=-1, type=click.Path())107+ def touch(files):108+ """Print all FILES file names."""109+ for filename in files:110+ click.echo(filename)111+112+And from the command line:113+114+.. click:run::115+116+ invoke(touch, ['-foo.txt', 'bar.txt'])117+```118+119+(environment-variables)=120+121+## Environment Variables122+123+Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in `click.argument`.124+125+Checking one environment variable:126+127+```{eval-rst}128+.. click:example::129+130+ @click.command()131+ @click.argument('src', envvar='SRC', type=click.File('r'))132+ def echo(src):133+ """Print value of SRC environment variable."""134+ click.echo(src.read())135+136+And from the command line:137+138+.. click:run::139+140+ with isolated_filesystem():141+ # Writing the file in the filesystem.142+ with open('hello.txt', 'w') as f:143+ f.write('Hello World!')144+ invoke(echo, env={'SRC': 'hello.txt'})145+146+147+Checking multiple environment variables:148+149+.. click:example::150+151+ @click.command()152+ @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))153+ def echo(src):154+ """Print value of SRC environment variable."""155+ click.echo(src.read())156+157+And from the command line:158+159+.. click:run::160+161+ with isolated_filesystem():162+ # Writing the file in the filesystem.163+ with open('hello.txt', 'w') as f:164+ f.write('Hello World from second variable!')165+ invoke(echo, env={'SRC_2': 'hello.txt'})166+```deleted:docs/arguments.rst-158 removed
1-.. _arguments:2-3-Arguments4-=========5-6-.. currentmodule:: click7-8-Arguments are:9-10-* Are positional in nature.11-* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs12-* :ref:`Documented manually <documenting-arguments>`.13-14-Useful and often used kwargs are:15-16-* ``default``: Passes a default.17-* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.18-19-Basic Arguments20----------------21-22-A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``.23-24-Example:25-26-.. click:example::27-28- @click.command()29- @click.argument('filename')30- def touch(filename: str):31- """Print FILENAME."""32- click.echo(filename)33-34-And from the command line:35-36-.. click:run::37-38- invoke(touch, args=['foo.txt'])39-40-41-An argument may be assigned a :ref:`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`.42-43-.. admonition:: Note on Required Arguments44-45- It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.46-47-Multiple Arguments48------------------------------------49-50-To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.51-52-.. click:example::53-54- @click.command()55- @click.argument('src', nargs=1)56- @click.argument('dsts', nargs=-1)57- def copy(src: str, dsts: tuple[str, ...]):58- """Move file SRC to DST."""59- for destination in dsts:60- click.echo(f"Copy {src} to folder {destination}")61-62-And from the command line:63-64-.. click:run::65-66- invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])67-68-.. admonition:: Note on Handling Files69-70- This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters.71-72-Argument Escape Sequences73----------------------------74-75-If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools.76-77-Example usage:78-79-.. click:example::80-81- @click.command()82- @click.argument('files', nargs=-1, type=click.Path())83- def touch(files):84- """Print all FILES file names."""85- for filename in files:86- click.echo(filename)87-88-And from the command line:89-90-.. click:run::91-92- invoke(touch, ['--', '-foo.txt', 'bar.txt'])93-94-If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:95-96-.. click:example::97-98- @click.command(context_settings={"ignore_unknown_options": True})99- @click.argument('files', nargs=-1, type=click.Path())100- def touch(files):101- """Print all FILES file names."""102- for filename in files:103- click.echo(filename)104-105-And from the command line:106-107-.. click:run::108-109- invoke(touch, ['-foo.txt', 'bar.txt'])110-111-112-.. _environment-variables:113-114-Environment Variables115----------------------116-117-Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118-119-Checking one environment variable:120-121-.. click:example::122-123- @click.command()124- @click.argument('src', envvar='SRC', type=click.File('r'))125- def echo(src):126- """Print value of SRC environment variable."""127- click.echo(src.read())128-129-And from the command line:130-131-.. click:run::132-133- with isolated_filesystem():134- # Writing the file in the filesystem.135- with open('hello.txt', 'w') as f:136- f.write('Hello World!')137- invoke(echo, env={'SRC': 'hello.txt'})138-139-140-Checking multiple environment variables:141-142-.. click:example::143-144- @click.command()145- @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))146- def echo(src):147- """Print value of SRC environment variable."""148- click.echo(src.read())149-150-And from the command line:151-152-.. click:run::153-154- with isolated_filesystem():155- # Writing the file in the filesystem.156- with open('hello.txt', 'w') as f:157- f.write('Hello World from second variable!')158- invoke(echo, env={'SRC_2': 'hello.txt'})added:docs/click-concepts.md+68 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Click Concepts
This section covers concepts about Click's design.
```{contents}---depth: 1local: true---```
(callback-evaluation-order)=
## Callback Evaluation Order
Click works a bit differently than some other command line parsers in thatit attempts to reconcile the order of arguments as defined by theprogrammer with the order of arguments as defined by the user beforeinvoking any callbacks.
This is an important concept to understand when porting complexpatterns to Click from optparse or other systems. A parametercallback invocation in optparse happens as part of the parsing step,whereas a callback invocation in Click happens after the parsing.
The main difference is that in optparse, callbacks are invoked with the rawvalue as it happens, whereas a callback in Click is invoked after thevalue has been fully converted.
Generally, the order of invocation is driven by the order in which the userprovides the arguments to the script; if there is an option called `--foo`and an option called `--bar` and the user calls it as `--bar --foo`, thenthe callback for `bar` will fire before the one for `foo`.
There are three exceptions to this rule which are important to know:
Eagerness:> An option can be set to be "eager". All eager parameters are> evaluated before all non-eager parameters, but again in the order as> they were provided on the command line by the user.
> This is important for parameters that execute and exit like `--help`> and `--version`. Both are eager parameters, but whatever parameter> comes first on the command line will win and exit the program.
Repeated parameters:> If an option or argument is split up on the command line into multiple> places because it is repeated -- for instance, `--exclude foo --include> baz --exclude bar` -- the callback will fire based on the position of> the first option. In this case, the callback will fire for> `exclude` and it will be passed both options (`foo` and> `bar`), then the callback for `include` will fire with `baz`> only.
> Note that even if a parameter does not allow multiple versions, Click> will still accept the position of the first, but it will ignore every> value except the last. The reason for this is to allow composability> through shell aliases that set defaults.
Missing parameters:> If a parameter is not defined on the command line, the callback will> still fire. This is different from how it works in optparse where> undefined values do not fire the callback. Missing parameters fire> their callbacks at the very end which makes it possible for them to> default to values from a parameter that came before.
Most of the time you do not need to be concerned about any of this,but it is important to know how it works for some advanced cases.deleted:docs/click-concepts.rst-67 removed
1-Click Concepts2-================3-4-This section covers concepts about Click's design.5-6-.. contents::7- :depth: 18- :local:9-10-.. _callback-evaluation-order:11-12-Callback Evaluation Order13--------------------------14-15-Click works a bit differently than some other command line parsers in that16-it attempts to reconcile the order of arguments as defined by the17-programmer with the order of arguments as defined by the user before18-invoking any callbacks.19-20-This is an important concept to understand when porting complex21-patterns to Click from optparse or other systems. A parameter22-callback invocation in optparse happens as part of the parsing step,23-whereas a callback invocation in Click happens after the parsing.24-25-The main difference is that in optparse, callbacks are invoked with the raw26-value as it happens, whereas a callback in Click is invoked after the27-value has been fully converted.28-29-Generally, the order of invocation is driven by the order in which the user30-provides the arguments to the script; if there is an option called ``--foo``31-and an option called ``--bar`` and the user calls it as ``--bar32---foo``, then the callback for ``bar`` will fire before the one for ``foo``.33-34-There are three exceptions to this rule which are important to know:35-36-Eagerness:37- An option can be set to be "eager". All eager parameters are38- evaluated before all non-eager parameters, but again in the order as39- they were provided on the command line by the user.40-41- This is important for parameters that execute and exit like ``--help``42- and ``--version``. Both are eager parameters, but whatever parameter43- comes first on the command line will win and exit the program.44-45-Repeated parameters:46- If an option or argument is split up on the command line into multiple47- places because it is repeated -- for instance, ``--exclude foo --include48- baz --exclude bar`` -- the callback will fire based on the position of49- the first option. In this case, the callback will fire for50- ``exclude`` and it will be passed both options (``foo`` and51- ``bar``), then the callback for ``include`` will fire with ``baz``52- only.53-54- Note that even if a parameter does not allow multiple versions, Click55- will still accept the position of the first, but it will ignore every56- value except the last. The reason for this is to allow composability57- through shell aliases that set defaults.58-59-Missing parameters:60- If a parameter is not defined on the command line, the callback will61- still fire. This is different from how it works in optparse where62- undefined values do not fire the callback. Missing parameters fire63- their callbacks at the very end which makes it possible for them to64- default to values from a parameter that came before.65-66-Most of the time you do not need to be concerned about any of this,67-but it is important to know how it works for some advanced cases.added:docs/commands-and-groups.md+401 added
1+# Basic Commands, Groups, Context2+3+```{currentmodule} click4+```5+6+Commands and Groups are the building blocks for Click applications. {class}`Command` wraps a function to make it into a cli command. {class}`Group` wraps Commands and Groups to make them into applications. {class}`Context` is how groups and commands communicate.7+8+```{contents}9+---10+depth: 211+local: true12+---13+```14+15+## Commands16+17+### Basic Command Example18+19+A simple command decorator takes no arguments.20+21+```{eval-rst}22+.. click:example::23+24+ @click.command()25+ @click.option('--count', default=1)26+ def hello(count):27+ for x in range(count):28+ click.echo("Hello!")29+30+.. click:run::31+ invoke(hello, args=['--count', '2',])32+```33+34+### Renaming Commands35+36+By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.37+38+```{eval-rst}39+.. click:example::40+41+ @click.command('say-hello')42+ @click.option('--count', default=1)43+ def hello(count):44+ for x in range(count):45+ click.echo("Hello!")46+47+.. click:run::48+ invoke(hello, args=['--count', '2',])49+```50+51+### Deprecating Commands52+53+To mark a command as deprecated pass in `deprecated=True`54+55+```{eval-rst}56+.. click:example::57+58+ @click.command('say-hello', deprecated=True)59+ @click.option('--count', default=1)60+ def hello(count):61+ for x in range(count):62+ click.echo("Hello!")63+64+.. click:run::65+ invoke(hello, args=['--count', '2',])66+```67+68+## Groups69+70+### Basic Group Example71+72+A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.73+74+```{eval-rst}75+.. click:example::76+77+ @click.group()78+ def greeting():79+ click.echo('Starting greeting ...')80+81+ @greeting.command('say-hello')82+ @click.option('--count', default=1)83+ def hello(count):84+ for x in range(count):85+ click.echo("Hello!")86+87+At the top level:88+89+.. click:run::90+91+ invoke(greeting)92+93+At the command level:94+95+.. click:run::96+97+ invoke(greeting, args=['say-hello'])98+ invoke(greeting, args=['say-hello', '--help'])99+```100+101+As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).102+103+### Renaming Groups104+105+To have a name other than the decorated function name as the group name, pass it in as the first positional argument.106+107+```{eval-rst}108+.. click:example::109+110+ @click.group('greet-someone')111+ def greeting():112+ click.echo('Starting greeting ...')113+114+ @greeting.command('say-hello')115+ @click.option('--count', default=1)116+ def hello(count):117+ for x in range(count):118+ click.echo("Hello!")119+120+.. click:run::121+122+ invoke(greeting, args=['say-hello'])123+```124+125+### Group Invocation Without Command126+127+By default, if a group is passed without a command, the group is not invoked and a command automatically passes `--help`. To change this, pass `invoke_without_command=True` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.128+129+```{eval-rst}130+.. click:example::131+132+ @click.group(invoke_without_command=True)133+ @click.pass_context134+ def cli(ctx):135+ if ctx.invoked_subcommand is None:136+ click.echo('I was invoked without subcommand')137+ else:138+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")139+140+ @cli.command()141+ def sync():142+ click.echo('The subcommand')143+144+.. click:run::145+146+ invoke(cli, prog_name='tool', args=[])147+ invoke(cli, prog_name='tool', args=['sync'])148+```149+150+### Group Separation151+152+Command {ref}`parameters` attached to a command belong only to that command.153+154+```{eval-rst}155+.. click:example::156+157+ @click.group()158+ def greeting():159+ pass160+161+ @greeting.command()162+ @click.option('--count', default=1)163+ def hello(count):164+ for x in range(count):165+ click.echo("Hello!")166+167+ @greeting.command()168+ @click.option('--count', default=1)169+ def goodbye(count):170+ for x in range(count):171+ click.echo("Goodbye!")172+173+.. click:run::174+175+ invoke(greeting, args=['hello', '--count', '2'])176+ invoke(greeting, args=['goodbye', '--count', '2'])177+ invoke(greeting)178+```179+180+Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.181+182+This behavior is observable with the `--help` option. Suppose we have a group called `tool` containing a command called `sub`.183+184+- `tool --help` returns the help for the whole program (listing subcommands).185+- `tool sub --help` returns the help for the `sub` subcommand.186+- But `tool --help sub` treats `--help` as an argument for the main program. Click then invokes the callback for `--help`, which prints the help and aborts the program before click can process the subcommand.187+188+### Arbitrary Nesting189+190+{class}`Commands <Command>` are attached to a {class}`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.191+192+```{eval-rst}193+.. click:example::194+195+ @click.group()196+ def cli():197+ pass198+199+ # Not @click so that the group is registered now.200+ @cli.group()201+ def session():202+ click.echo('Starting session')203+204+ @session.command()205+ def initdb():206+ click.echo('Initialized the database')207+208+ @session.command()209+ def dropdb():210+ click.echo('Dropped the database')211+212+.. click:run::213+214+ invoke(cli, args=['session', 'initdb'])215+```216+217+### Lazily Attaching Commands218+219+Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.220+221+```{eval-rst}222+.. click:example::223+224+ @click.group()225+ def cli():226+ pass227+228+ @cli.command()229+ def initdb():230+ click.echo('Initialized the database')231+232+ @click.command()233+ def dropdb():234+ click.echo('Dropped the database')235+236+ cli.add_command(dropdb)237+238+.. click:run::239+240+ invoke(cli, args=['initdb'])241+ invoke(cli, args=['dropdb'])242+```243+244+## Context Object245+The {class}`Context` object is how commands and groups communicate.246+247+### Auto Envvar Prefix248+249+Automatically built environment variables are supported for options only. To enable this feature, the `auto_envvar_prefix` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand250+called `run` taking an option called `reload` and the prefix is `WEB`, then the variable is `WEB_RUN_RELOAD`.251+252+Example usage:253+254+```{eval-rst}255+.. click:example::256+257+ @click.command()258+ @click.option('--username')259+ def greet(username):260+ click.echo(f'Hello {username}!')261+262+ if __name__ == '__main__':263+ greet(auto_envvar_prefix='GREETER')264+265+And from the command line:266+267+.. click:run::268+269+ invoke(greet, env={'GREETER_USERNAME': 'john'},270+ auto_envvar_prefix='GREETER')271+```272+273+When using `auto_envvar_prefix` with command groups, the command name274+needs to be included in the environment variable, between the prefix and275+the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a276+subcommand called `run-server` taking an option called `host` and277+the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`.278+279+```{eval-rst}280+.. click:example::281+282+ @click.group()283+ @click.option('--debug/--no-debug')284+ def cli(debug):285+ click.echo(f"Debug mode is {'on' if debug else 'off'}")286+287+ @cli.command()288+ @click.option('--username')289+ def greet(username):290+ click.echo(f"Hello {username}!")291+292+ if __name__ == '__main__':293+ cli(auto_envvar_prefix='GREETER')294+295+.. click:run::296+297+ invoke(cli, args=['greet',],298+ env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},299+ auto_envvar_prefix='GREETER')300+```301+302+### Global Context Access303+304+```{versionadded} 5.0305+```306+307+Starting with Click 5.0 it is possible to access the current context from308+anywhere within the same thread through the use of the309+{func}`get_current_context` function which returns it. This is primarily310+useful for accessing the context bound object as well as some flags that311+are stored on it to customize the runtime behavior. For instance the312+{func}`echo` function does this to infer the default value of the `color`313+flag.314+315+Example usage:316+317+```python318+ def get_current_command_name():319+ return click.get_current_context().info_name320+```321+322+It should be noted that this only works within the current thread. If you323+spawn additional threads then those threads will not have the ability to324+refer to the current context. If you want to give another thread the325+ability to refer to this context you need to use the context within the326+thread as a context manager:327+328+```python329+ def spawn_thread(ctx, func):330+ def wrapper():331+ with ctx:332+ func()333+ t = threading.Thread(target=wrapper)334+ t.start()335+ return t336+```337+338+Now the thread function can access the context like the main thread would339+do. However if you do use this for threading you need to be very careful340+as the vast majority of the context is not thread safe! You are only341+allowed to read from the context, but not to perform any modifications on342+it.343+344+345+### Parameter Source Priority346+347+When a parameter's value is resolved, Click checks several sources348+in the following order of precedence:349+350+1. **Prompt** (`PROMPT`): interactively provided by the user at a prompt.351+2. **Command line** (`COMMANDLINE`): provided as a CLI argument or option.352+3. **Environment variable** (`ENVIRONMENT`): read from an environment variable.353+4. **Default map** (`DEFAULT_MAP`): looked up from {attr}`Context.default_map`.354+5. **Default** (`DEFAULT`): the default value defined on the parameter.355+356+{class}`~click.core.ParameterSource` members are ordered from most357+explicit to least explicit. Because it is an {class}`~enum.IntEnum`,358+you can use comparison operators to check how explicitly a value was359+provided:360+361+```python362+source = ctx.get_parameter_source("port")363+364+# True if the value was explicitly set (command line, prompt, or env var).365+if source < click.ParameterSource.DEFAULT_MAP:366+ ...367+368+# True if the value came from any kind of default.369+if source >= click.ParameterSource.DEFAULT_MAP:370+ ...371+```372+373+374+### Detecting the Source of a Parameter375+376+In some situations it's helpful to understand whether or not an option377+or parameter came from the command line, the environment, the default378+value, or {attr}`Context.default_map`. The379+{meth}`Context.get_parameter_source` method can be used to find this380+out. It will return a member of the {class}`~click.core.ParameterSource`381+enum.382+383+```{eval-rst}384+.. click:example::385+386+ @click.command()387+ @click.argument('port', nargs=1, default=8080, envvar="PORT")388+ @click.pass_context389+ def cli(ctx, port):390+ source = ctx.get_parameter_source("port")391+ click.echo(f"Port came from {source.name}")392+393+.. click:run::394+395+ invoke(cli, prog_name='cli', args=['8080'])396+ println()397+ invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})398+ println()399+ invoke(cli, prog_name='cli', args=[])400+ println()401+```deleted:docs/commands-and-groups.rst-342 removed
1-Basic Commands, Groups, Context2-================================3-4-.. currentmodule:: click5-6-Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.7-8-.. contents::9- :depth: 210- :local:11-12-Commands13---------------------14-15-Basic Command Example16-^^^^^^^^^^^^^^^^^^^^^^^17-A simple command decorator takes no arguments.18-19-.. click:example::20- @click.command()21- @click.option('--count', default=1)22- def hello(count):23- for x in range(count):24- click.echo("Hello!")25-26-.. click:run::27- invoke(hello, args=['--count', '2',])28-29-Renaming Commands30-^^^^^^^^^^^^^^^^^^^31-By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.32-33-.. click:example::34- @click.command('say-hello')35- @click.option('--count', default=1)36- def hello(count):37- for x in range(count):38- click.echo("Hello!")39-40-.. click:run::41- invoke(hello, args=['--count', '2',])42-43-Deprecating Commands44-^^^^^^^^^^^^^^^^^^^^^^45-To mark a command as deprecated pass in ``deprecated=True``46-47-.. click:example::48- @click.command('say-hello', deprecated=True)49- @click.option('--count', default=1)50- def hello(count):51- for x in range(count):52- click.echo("Hello!")53-54-.. click:run::55- invoke(hello, args=['--count', '2',])56-57-Groups58-------------59-60-Basic Group Example61-^^^^^^^^^^^^^^^^^^^^^62-A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.63-64-.. click:example::65- @click.group()66- def greeting():67- click.echo('Starting greeting ...')68-69- @greeting.command('say-hello')70- @click.option('--count', default=1)71- def hello(count):72- for x in range(count):73- click.echo("Hello!")74-75-At the top level:76-77-.. click:run::78-79- invoke(greeting)80-81-At the command level:82-83-.. click:run::84-85- invoke(greeting, args=['say-hello'])86- invoke(greeting, args=['say-hello', '--help'])87-88-As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).89-90-Renaming Groups91-^^^^^^^^^^^^^^^^^92-To have a name other than the decorated function name as the group name, pass it in as the first positional argument.93-94-.. click:example::95- @click.group('greet-someone')96- def greeting():97- click.echo('Starting greeting ...')98-99- @greeting.command('say-hello')100- @click.option('--count', default=1)101- def hello(count):102- for x in range(count):103- click.echo("Hello!")104-105-.. click:run::106-107- invoke(greeting, args=['say-hello'])108-109-Group Invocation Without Command110-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111-112-By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.113-114-.. click:example::115-116- @click.group(invoke_without_command=True)117- @click.pass_context118- def cli(ctx):119- if ctx.invoked_subcommand is None:120- click.echo('I was invoked without subcommand')121- else:122- click.echo(f"I am about to invoke {ctx.invoked_subcommand}")123-124- @cli.command()125- def sync():126- click.echo('The subcommand')127-128-.. click:run::129-130- invoke(cli, prog_name='tool', args=[])131- invoke(cli, prog_name='tool', args=['sync'])132-133-134-135-Group Separation136-^^^^^^^^^^^^^^^^^^^137-Command :ref:`parameters` attached to a command belong only to that command.138-139-.. click:example::140- @click.group()141- def greeting():142- pass143-144- @greeting.command()145- @click.option('--count', default=1)146- def hello(count):147- for x in range(count):148- click.echo("Hello!")149-150- @greeting.command()151- @click.option('--count', default=1)152- def goodbye(count):153- for x in range(count):154- click.echo("Goodbye!")155-156-.. click:run::157-158- invoke(greeting, args=['hello', '--count', '2'])159- invoke(greeting, args=['goodbye', '--count', '2'])160- invoke(greeting)161-162-Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.163-164-This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.165-166-- ``tool --help`` returns the help for the whole program (listing subcommands).167-- ``tool sub --help`` returns the help for the ``sub`` subcommand.168-- But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.169-170-Arbitrary Nesting171-^^^^^^^^^^^^^^^^^^^172-:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.173-174-.. click:example::175-176- @click.group()177- def cli():178- pass179-180- # Not @click so that the group is registered now.181- @cli.group()182- def session():183- click.echo('Starting session')184-185- @session.command()186- def initdb():187- click.echo('Initialized the database')188-189- @session.command()190- def dropdb():191- click.echo('Dropped the database')192-193-.. click:run::194-195- invoke(cli, args=['session', 'initdb'])196-197-Lazily Attaching Commands198-^^^^^^^^^^^^^^^^^^^^^^^^^^^199-Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.200-201-.. click:example::202-203- @click.group()204- def cli():205- pass206-207- @cli.command()208- def initdb():209- click.echo('Initialized the database')210-211- @click.command()212- def dropdb():213- click.echo('Dropped the database')214-215- cli.add_command(dropdb)216-217-.. click:run::218-219- invoke(cli, args=['initdb'])220- invoke(cli, args=['dropdb'])221-222-Context Object223--------------------224-The :class:`Context` object is how commands and groups communicate.225-226-Auto Envvar Prefix227-^^^^^^^^^^^^^^^^^^^^228-Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand229-called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230-231-Example usage:232-233-.. click:example::234-235- @click.command()236- @click.option('--username')237- def greet(username):238- click.echo(f'Hello {username}!')239-240- if __name__ == '__main__':241- greet(auto_envvar_prefix='GREETER')242-243-And from the command line:244-245-.. click:run::246-247- invoke(greet, env={'GREETER_USERNAME': 'john'},248- auto_envvar_prefix='GREETER')249-250-When using ``auto_envvar_prefix`` with command groups, the command name251-needs to be included in the environment variable, between the prefix and252-the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a253-subcommand called ``run-server`` taking an option called ``host`` and254-the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.255-256-.. click:example::257-258- @click.group()259- @click.option('--debug/--no-debug')260- def cli(debug):261- click.echo(f"Debug mode is {'on' if debug else 'off'}")262-263- @cli.command()264- @click.option('--username')265- def greet(username):266- click.echo(f"Hello {username}!")267-268- if __name__ == '__main__':269- cli(auto_envvar_prefix='GREETER')270-271-.. click:run::272-273- invoke(cli, args=['greet',],274- env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275- auto_envvar_prefix='GREETER')276-277-Global Context Access278-^^^^^^^^^^^^^^^^^^^^^^279-280-.. versionadded:: 5.0281-282-Starting with Click 5.0 it is possible to access the current context from283-anywhere within the same thread through the use of the284-:func:`get_current_context` function which returns it. This is primarily285-useful for accessing the context bound object as well as some flags that286-are stored on it to customize the runtime behavior. For instance the287-:func:`echo` function does this to infer the default value of the `color`288-flag.289-290-Example usage::291-292- def get_current_command_name():293- return click.get_current_context().info_name294-295-It should be noted that this only works within the current thread. If you296-spawn additional threads then those threads will not have the ability to297-refer to the current context. If you want to give another thread the298-ability to refer to this context you need to use the context within the299-thread as a context manager::300-301- def spawn_thread(ctx, func):302- def wrapper():303- with ctx:304- func()305- t = threading.Thread(target=wrapper)306- t.start()307- return t308-309-Now the thread function can access the context like the main thread would310-do. However if you do use this for threading you need to be very careful311-as the vast majority of the context is not thread safe! You are only312-allowed to read from the context, but not to perform any modifications on313-it.314-315-316-Detecting the Source of a Parameter317-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^318-319-In some situations it's helpful to understand whether or not an option320-or parameter came from the command line, the environment, the default321-value, or :attr:`Context.default_map`. The322-:meth:`Context.get_parameter_source` method can be used to find this323-out. It will return a member of the :class:`~click.core.ParameterSource`324-enum.325-326-.. click:example::327-328- @click.command()329- @click.argument('port', nargs=1, default=8080, envvar="PORT")330- @click.pass_context331- def cli(ctx, port):332- source = ctx.get_parameter_source("port")333- click.echo(f"Port came from {source.name}")334-335-.. click:run::336-337- invoke(cli, prog_name='cli', args=['8080'])338- println()339- invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})340- println()341- invoke(cli, prog_name='cli', args=[])342- println()added:docs/commands.md+437 added
1+# Advanced Groups and Context2+3+```{currentmodule} click4+```5+6+In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.7+8+```{contents}9+---10+depth: 111+local: true12+---13+```14+15+## Callback Invocation16+17+For a regular command, the callback is executed whenever the command runs.18+If the script is the only command, it will always fire (unless a parameter19+callback prevents it. This for instance happens if someone passes20+`--help` to the script).21+22+For groups, the situation looks different. In this case, the callback fires23+whenever a subcommand fires. What this means in practice is that an outer24+command runs when an inner command runs:25+26+```{eval-rst}27+.. click:example::28+29+ @click.group()30+ @click.option('--debug/--no-debug', default=False)31+ def cli(debug):32+ click.echo(f"Debug mode is {'on' if debug else 'off'}")33+34+ @cli.command() # @cli, not @click!35+ def sync():36+ click.echo('Syncing')37+38+Here is what this looks like:39+40+.. click:run::41+42+ invoke(cli, prog_name='tool.py')43+ println()44+ invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])45+```46+47+## Nested Handling and Contexts48+49+As you can see from the earlier example, the basic command group accepts a50+debug argument which is passed to its callback, but not to the sync51+command itself. The sync command only accepts its own arguments.52+53+This allows tools to act completely independent of each other, but how54+does one command talk to a nested one? The answer to this is the55+{class}`Context`.56+57+Each time a command is invoked, a new context is created and linked with the58+parent context. Normally, you can't see these contexts, but they are59+there. Contexts are passed to parameter callbacks together with the60+value automatically. Commands can also ask for the context to be passed61+by marking themselves with the {func}`pass_context` decorator. In that62+case, the context is passed as first argument.63+64+The context can also carry a program specified object that can be65+used for the program's purposes. What this means is that you can build a66+script like this:67+68+```{eval-rst}69+.. click:example::70+71+ @click.group()72+ @click.option('--debug/--no-debug', default=False)73+ @click.pass_context74+ def cli(ctx, debug):75+ # ensure that ctx.obj exists and is a dict (in case `cli()` is called76+ # by means other than the `if` block below)77+ ctx.ensure_object(dict)78+79+ ctx.obj['DEBUG'] = debug80+81+ @cli.command()82+ @click.pass_context83+ def sync(ctx):84+ click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")85+86+ if __name__ == '__main__':87+ cli(obj={})88+```89+90+If the object is provided, each context will pass the object onwards to91+its children, but at any level a context's object can be overridden. To92+reach to a parent, `context.parent` can be used.93+94+In addition to that, instead of passing an object down, nothing stops the95+application from modifying global state. For instance, you could just flip96+a global `DEBUG` variable and be done with it.97+98+## Decorating Commands99+100+As you have seen in the earlier example, a decorator can change how a101+command is invoked. What actually happens behind the scenes is that102+callbacks are always invoked through the {meth}`Context.invoke` method103+which automatically invokes a command correctly (by either passing the104+context or not).105+106+This is very useful when you want to write custom decorators. For107+instance, a common pattern would be to configure an object representing108+state and then storing it on the context and then to use a custom109+decorator to find the most recent object of this sort and pass it as first110+argument.111+112+For instance, the {func}`pass_obj` decorator can be implemented like this:113+114+```{eval-rst}115+.. click:example::116+117+ from functools import update_wrapper118+119+ def pass_obj(f):120+ @click.pass_context121+ def new_func(ctx, *args, **kwargs):122+ return ctx.invoke(f, ctx.obj, *args, **kwargs)123+ return update_wrapper(new_func, f)124+```125+126+The {meth}`Context.invoke` command will automatically invoke the function127+in the correct way, so the function will either be called with`f(ctx,128+obj)` or `f(obj)` depending on whether or not it itself is decorated with129+{func}`pass_context`.130+131+This is a very powerful concept that can be used to build very complex132+nested applications; see {ref}`complex-guide` for more information.133+134+(command-chaining)=135+136+## Command Chaining137+138+It is useful to invoke more than one subcommand in one call. For example,139+`my-app validate build upload` would invoke `validate`, then `build`, then140+`upload`. To implement this, pass `chain=True` when creating a group.141+142+```{eval-rst}143+.. click:example::144+145+ @click.group(chain=True)146+ def cli():147+ pass148+149+ @cli.command('validate')150+ def validate():151+ click.echo('validate')152+153+ @cli.command('build')154+ def build():155+ click.echo('build')156+157+You can invoke it like this:158+159+.. click:run::160+161+ invoke(cli, prog_name='my-app', args=['validate', 'build'])162+```163+164+When using chaining, there are a few restrictions:165+166+- Only the last command may use `nargs=-1` on an argument, otherwise the167+ parser will not be able to find further commands.168+- It is not possible to nest groups below a chain group.169+- On the command line, options must be specified before arguments for each170+ command in the chain.171+- The {attr}`Context.invoked_subcommand` attribute will be `'*'` because the172+ parser doesn't know the full list of commands that will run yet.173+174+(command-pipelines)=175+176+## Command Pipelines177+178+When using chaining, a common pattern is to have each command process the179+result of the previous command.180+181+A straightforward way to do this is to use {func}`make_pass_decorator` to pass182+a context object to each command, and store and read the data on that object.183+184+```{eval-rst}185+.. click:example::186+187+ pass_ns = click.make_pass_decorator(dict, ensure=True)188+189+ @click.group(chain=True)190+ @click.argument("name")191+ @pass_ns192+ def cli(ns, name):193+ ns["name"] = name194+195+ @cli.command196+ @pass_ns197+ def lower(ns):198+ ns["name"] = ns["name"].lower()199+200+ @cli.command201+ @pass_ns202+ def show(ns):203+ click.echo(ns["name"])204+205+.. click:run::206+207+ invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])208+```209+210+Another way to do this is to collect data returned by each command, then process211+it at the end of the chain. Use the group's {meth}`~Group.result_callback`212+decorator to register a function that is called after the chain is finished. It213+is passed the list of return values as well as any parameters registered on the214+group.215+216+A command can return anything, including a function. Here's an example of that,217+where each subcommand creates a function that processes the input, then the218+result callback calls each function. The command takes a file, processes each219+line, then outputs it. If no subcommands are given, it outputs the contents220+of the file unchanged.221+222+```python223+@click.group(chain=True, invoke_without_command=True)224+@click.argument("fin", type=click.File("r"))225+def cli(fin):226+ pass227+228+@cli.result_callback()229+def process_pipeline(processors, fin):230+ iterator = (x.rstrip("\r\n") for x in input)231+232+ for processor in processors:233+ iterator = processor(iterator)234+235+ for item in iterator:236+ click.echo(item)237+238+@cli.command("upper")239+def make_uppercase():240+ def processor(iterator):241+ for line in iterator:242+ yield line.upper()243+ return processor244+245+@cli.command("lower")246+def make_lowercase():247+ def processor(iterator):248+ for line in iterator:249+ yield line.lower()250+ return processor251+252+@cli.command("strip")253+def make_strip():254+ def processor(iterator):255+ for line in iterator:256+ yield line.strip()257+ return processor258+```259+260+That's a lot in one go, so let's go through it step by step.261+262+1. The first thing is to make a {func}`group` that is chainable. In263+ addition to that we also instruct Click to invoke even if no264+ subcommand is defined. If this would not be done, then invoking an265+ empty pipeline would produce the help page instead of running the266+ result callbacks.267+2. The next thing we do is to register a result callback on our group.268+ This callback will be invoked with an argument which is the list of269+ all return values of all subcommands and then the same keyword270+ parameters as our group itself. This means we can access the input271+ file easily there without having to use the context object.272+3. In this result callback we create an iterator of all the lines in the273+ input file and then pass this iterator through all the returned274+ callbacks from all subcommands and finally we print all lines to275+ stdout.276+277+After that point we can register as many subcommands as we want and each278+subcommand can return a processor function to modify the stream of lines.279+280+One important thing of note is that Click shuts down the context after281+each callback has been run. This means that for instance file types282+cannot be accessed in the `processor` functions as the files will already283+be closed there. This limitation is unlikely to change because it would284+make resource handling much more complicated. For such it's recommended285+to not use the file type and manually open the file through286+{func}`open_file`.287+288+For a more complex example that also improves upon handling of the pipelines,289+see the [imagepipe example](https://github.com/pallets/click/tree/main/examples/imagepipe)290+in the Click repository. It implements a pipeline based image editing tool291+that has a nice internal structure.292+293+## Overriding Defaults294+295+By default, the default value for a parameter is pulled from the296+`default` flag that is provided when it's defined, but that's not the297+only place defaults can be loaded from. The other place is the298+{attr}`Context.default_map` (a dictionary) on the context. This allows299+defaults to be loaded from a configuration file to override the regular300+defaults.301+302+This is useful if you plug in some commands from another package but303+you're not satisfied with the defaults.304+305+The default map can be nested arbitrarily for each subcommand:306+307+```python308+309+ default_map = {310+ "debug": True, # default for a top level option311+ "runserver": {"port": 5000} # default for a subcommand312+ }313+```314+315+The default map can be provided when the script is invoked, or316+overridden at any point by commands. For instance, a top-level command317+could load the defaults from a configuration file.318+319+Example usage:320+321+```{eval-rst}322+.. click:example::323+324+ import click325+326+ @click.group()327+ def cli():328+ pass329+330+ @cli.command()331+ @click.option('--port', default=8000)332+ def runserver(port):333+ click.echo(f"Serving on http://127.0.0.1:{port}/")334+335+ if __name__ == '__main__':336+ cli(default_map={337+ 'runserver': {338+ 'port': 5000339+ }340+ })341+342+And in action:343+344+.. click:run::345+346+ invoke(cli, prog_name='cli', args=['runserver'], default_map={347+ 'runserver': {348+ 'port': 5000349+ }350+ })351+```352+353+## Context Defaults354+355+```{versionadded} 2.0356+```357+358+Starting with Click 2.0 you can override defaults for contexts not just359+when calling your script, but also in the decorator that declares a360+command. For instance given the previous example which defines a custom361+`default_map` this can also be accomplished in the decorator now.362+363+This example does the same as the previous example:364+365+```{eval-rst}366+.. click:example::367+368+ import click369+370+ CONTEXT_SETTINGS = dict(371+ default_map={'runserver': {'port': 5000}}372+ )373+374+ @click.group(context_settings=CONTEXT_SETTINGS)375+ def cli():376+ pass377+378+ @cli.command()379+ @click.option('--port', default=8000)380+ def runserver(port):381+ click.echo(f"Serving on http://127.0.0.1:{port}/")382+383+ if __name__ == '__main__':384+ cli()385+386+And again the example in action:387+388+.. click:run::389+390+ invoke(cli, prog_name='cli', args=['runserver'])391+```392+393+## Command Return Values394+395+```{versionadded} 3.0396+```397+398+One of the new introductions in Click 3.0 is the full support for return399+values from command callbacks. This enables a whole range of features400+that were previously hard to implement.401+402+In essence any command callback can now return a value. This return value403+is bubbled to certain receivers. One usecase for this has already been404+show in the example of {ref}`command-chaining` where it has been405+demonstrated that chained groups can have callbacks that process406+all return values.407+408+When working with command return values in Click, this is what you need to409+know:410+411+- The return value of a command callback is generally returned from the412+ {meth}`Command.invoke` method. The exception to this rule has to413+ do with {class}`Group`s:414+415+ - In a group the return value is generally the return value of the416+ subcommand invoked. The only exception to this rule is that the417+ return value is the return value of the group callback if it's418+ invoked without arguments and `invoke_without_command` is enabled.419+ - If a group is set up for chaining then the return value is a list420+ of all subcommands' results.421+ - Return values of groups can be processed through a422+ {attr}`Group.result_callback`. This is invoked with the423+ list of all return values in chain mode, or the single return424+ value in case of non chained commands.425+426+- The return value is bubbled through from the {meth}`Context.invoke`427+ and {meth}`Context.forward` methods. This is useful in situations428+ where you internally want to call into another command.429+430+- Click does not have any hard requirements for the return values and431+ does not use them itself. This allows return values to be used for432+ custom decorators or workflows (like in the command chaining433+ example).434+435+- When a Click script is invoked as command line application (through436+ {meth}`Command.main`) the return value is ignored unless the437+ `standalone_mode` is disabled in which case it's bubbled through.deleted:docs/commands.rst-428 removed
1-Advanced Groups and Context2-=============================3-4-.. currentmodule:: click5-6-In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.7-8-.. contents::9- :depth: 110- :local:11-12-Callback Invocation13--------------------14-15-For a regular command, the callback is executed whenever the command runs.16-If the script is the only command, it will always fire (unless a parameter17-callback prevents it. This for instance happens if someone passes18-``--help`` to the script).19-20-For groups, the situation looks different. In this case, the callback fires21-whenever a subcommand fires. What this means in practice is that an outer22-command runs when an inner command runs:23-24-.. click:example::25-26- @click.group()27- @click.option('--debug/--no-debug', default=False)28- def cli(debug):29- click.echo(f"Debug mode is {'on' if debug else 'off'}")30-31- @cli.command() # @cli, not @click!32- def sync():33- click.echo('Syncing')34-35-Here is what this looks like:36-37-.. click:run::38-39- invoke(cli, prog_name='tool.py')40- println()41- invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])42-43-Nested Handling and Contexts44-----------------------------45-46-As you can see from the earlier example, the basic command group accepts a47-debug argument which is passed to its callback, but not to the sync48-command itself. The sync command only accepts its own arguments.49-50-This allows tools to act completely independent of each other, but how51-does one command talk to a nested one? The answer to this is the52-:class:`Context`.53-54-Each time a command is invoked, a new context is created and linked with the55-parent context. Normally, you can't see these contexts, but they are56-there. Contexts are passed to parameter callbacks together with the57-value automatically. Commands can also ask for the context to be passed58-by marking themselves with the :func:`pass_context` decorator. In that59-case, the context is passed as first argument.60-61-The context can also carry a program specified object that can be62-used for the program's purposes. What this means is that you can build a63-script like this:64-65-.. click:example::66-67- @click.group()68- @click.option('--debug/--no-debug', default=False)69- @click.pass_context70- def cli(ctx, debug):71- # ensure that ctx.obj exists and is a dict (in case `cli()` is called72- # by means other than the `if` block below)73- ctx.ensure_object(dict)74-75- ctx.obj['DEBUG'] = debug76-77- @cli.command()78- @click.pass_context79- def sync(ctx):80- click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")81-82- if __name__ == '__main__':83- cli(obj={})84-85-If the object is provided, each context will pass the object onwards to86-its children, but at any level a context's object can be overridden. To87-reach to a parent, ``context.parent`` can be used.88-89-In addition to that, instead of passing an object down, nothing stops the90-application from modifying global state. For instance, you could just flip91-a global ``DEBUG`` variable and be done with it.92-93-Decorating Commands94--------------------95-96-As you have seen in the earlier example, a decorator can change how a97-command is invoked. What actually happens behind the scenes is that98-callbacks are always invoked through the :meth:`Context.invoke` method99-which automatically invokes a command correctly (by either passing the100-context or not).101-102-This is very useful when you want to write custom decorators. For103-instance, a common pattern would be to configure an object representing104-state and then storing it on the context and then to use a custom105-decorator to find the most recent object of this sort and pass it as first106-argument.107-108-For instance, the :func:`pass_obj` decorator can be implemented like this:109-110-.. click:example::111-112- from functools import update_wrapper113-114- def pass_obj(f):115- @click.pass_context116- def new_func(ctx, *args, **kwargs):117- return ctx.invoke(f, ctx.obj, *args, **kwargs)118- return update_wrapper(new_func, f)119-120-The :meth:`Context.invoke` command will automatically invoke the function121-in the correct way, so the function will either be called with ``f(ctx,122-obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with123-:func:`pass_context`.124-125-This is a very powerful concept that can be used to build very complex126-nested applications; see :ref:`complex-guide` for more information.127-128-.. _command-chaining:129-130-Command Chaining131-----------------132-133-It is useful to invoke more than one subcommand in one call. For example,134-``my-app validate build upload`` would invoke ``validate``, then ``build``, then135-``upload``. To implement this, pass ``chain=True`` when creating a group.136-137-.. click:example::138-139- @click.group(chain=True)140- def cli():141- pass142-143- @cli.command('validate')144- def validate():145- click.echo('validate')146-147- @cli.command('build')148- def build():149- click.echo('build')150-151-You can invoke it like this:152-153-.. click:run::154-155- invoke(cli, prog_name='my-app', args=['validate', 'build'])156-157-When using chaining, there are a few restrictions:158-159-- Only the last command may use ``nargs=-1`` on an argument, otherwise the160- parser will not be able to find further commands.161-- It is not possible to nest groups below a chain group.162-- On the command line, options must be specified before arguments for each163- command in the chain.164-- The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the165- parser doesn't know the full list of commands that will run yet.166-167-.. _command-pipelines:168-169-Command Pipelines170-------------------171-172-When using chaining, a common pattern is to have each command process the173-result of the previous command.174-175-A straightforward way to do this is to use :func:`make_pass_decorator` to pass176-a context object to each command, and store and read the data on that object.177-178-.. click:example::179-180- pass_ns = click.make_pass_decorator(dict, ensure=True)181-182- @click.group(chain=True)183- @click.argument("name")184- @pass_ns185- def cli(ns, name):186- ns["name"] = name187-188- @cli.command189- @pass_ns190- def lower(ns):191- ns["name"] = ns["name"].lower()192-193- @cli.command194- @pass_ns195- def show(ns):196- click.echo(ns["name"])197-198-.. click:run::199-200- invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])201-202-Another way to do this is to collect data returned by each command, then process203-it at the end of the chain. Use the group's :meth:`~Group.result_callback`204-decorator to register a function that is called after the chain is finished. It205-is passed the list of return values as well as any parameters registered on the206-group.207-208-A command can return anything, including a function. Here's an example of that,209-where each subcommand creates a function that processes the input, then the210-result callback calls each function. The command takes a file, processes each211-line, then outputs it. If no subcommands are given, it outputs the contents212-of the file unchanged.213-214-.. code-block:: python215-216- @click.group(chain=True, invoke_without_command=True)217- @click.argument("fin", type=click.File("r"))218- def cli(fin):219- pass220-221- @cli.result_callback()222- def process_pipeline(processors, fin):223- iterator = (x.rstrip("\r\n") for x in input)224-225- for processor in processors:226- iterator = processor(iterator)227-228- for item in iterator:229- click.echo(item)230-231- @cli.command("upper")232- def make_uppercase():233- def processor(iterator):234- for line in iterator:235- yield line.upper()236- return processor237-238- @cli.command("lower")239- def make_lowercase():240- def processor(iterator):241- for line in iterator:242- yield line.lower()243- return processor244-245- @cli.command("strip")246- def make_strip():247- def processor(iterator):248- for line in iterator:249- yield line.strip()250- return processor251-252-That's a lot in one go, so let's go through it step by step.253-254-1. The first thing is to make a :func:`group` that is chainable. In255- addition to that we also instruct Click to invoke even if no256- subcommand is defined. If this would not be done, then invoking an257- empty pipeline would produce the help page instead of running the258- result callbacks.259-2. The next thing we do is to register a result callback on our group.260- This callback will be invoked with an argument which is the list of261- all return values of all subcommands and then the same keyword262- parameters as our group itself. This means we can access the input263- file easily there without having to use the context object.264-3. In this result callback we create an iterator of all the lines in the265- input file and then pass this iterator through all the returned266- callbacks from all subcommands and finally we print all lines to267- stdout.268-269-After that point we can register as many subcommands as we want and each270-subcommand can return a processor function to modify the stream of lines.271-272-One important thing of note is that Click shuts down the context after273-each callback has been run. This means that for instance file types274-cannot be accessed in the `processor` functions as the files will already275-be closed there. This limitation is unlikely to change because it would276-make resource handling much more complicated. For such it's recommended277-to not use the file type and manually open the file through278-:func:`open_file`.279-280-For a more complex example that also improves upon handling of the pipelines,281-see the `imagepipe example`_ in the Click repository. It implements a282-pipeline based image editing tool that has a nice internal structure.283-284-.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe285-286-287-Overriding Defaults288--------------------289-290-By default, the default value for a parameter is pulled from the291-``default`` flag that is provided when it's defined, but that's not the292-only place defaults can be loaded from. The other place is the293-:attr:`Context.default_map` (a dictionary) on the context. This allows294-defaults to be loaded from a configuration file to override the regular295-defaults.296-297-This is useful if you plug in some commands from another package but298-you're not satisfied with the defaults.299-300-The default map can be nested arbitrarily for each subcommand:301-302-.. code-block:: python303-304- default_map = {305- "debug": True, # default for a top level option306- "runserver": {"port": 5000} # default for a subcommand307- }308-309-The default map can be provided when the script is invoked, or310-overridden at any point by commands. For instance, a top-level command311-could load the defaults from a configuration file.312-313-Example usage:314-315-.. click:example::316-317- import click318-319- @click.group()320- def cli():321- pass322-323- @cli.command()324- @click.option('--port', default=8000)325- def runserver(port):326- click.echo(f"Serving on http://127.0.0.1:{port}/")327-328- if __name__ == '__main__':329- cli(default_map={330- 'runserver': {331- 'port': 5000332- }333- })334-335-And in action:336-337-.. click:run::338-339- invoke(cli, prog_name='cli', args=['runserver'], default_map={340- 'runserver': {341- 'port': 5000342- }343- })344-345-Context Defaults346-----------------347-348-.. versionadded:: 2.0349-350-Starting with Click 2.0 you can override defaults for contexts not just351-when calling your script, but also in the decorator that declares a352-command. For instance given the previous example which defines a custom353-``default_map`` this can also be accomplished in the decorator now.354-355-This example does the same as the previous example:356-357-.. click:example::358-359- import click360-361- CONTEXT_SETTINGS = dict(362- default_map={'runserver': {'port': 5000}}363- )364-365- @click.group(context_settings=CONTEXT_SETTINGS)366- def cli():367- pass368-369- @cli.command()370- @click.option('--port', default=8000)371- def runserver(port):372- click.echo(f"Serving on http://127.0.0.1:{port}/")373-374- if __name__ == '__main__':375- cli()376-377-And again the example in action:378-379-.. click:run::380-381- invoke(cli, prog_name='cli', args=['runserver'])382-383-384-Command Return Values385----------------------386-387-.. versionadded:: 3.0388-389-One of the new introductions in Click 3.0 is the full support for return390-values from command callbacks. This enables a whole range of features391-that were previously hard to implement.392-393-In essence any command callback can now return a value. This return value394-is bubbled to certain receivers. One usecase for this has already been395-show in the example of :ref:`command-chaining` where it has been396-demonstrated that chained groups can have callbacks that process397-all return values.398-399-When working with command return values in Click, this is what you need to400-know:401-402-- The return value of a command callback is generally returned from the403- :meth:`Command.invoke` method. The exception to this rule has to404- do with :class:`Group`\s:405-406- * In a group the return value is generally the return value of the407- subcommand invoked. The only exception to this rule is that the408- return value is the return value of the group callback if it's409- invoked without arguments and `invoke_without_command` is enabled.410- * If a group is set up for chaining then the return value is a list411- of all subcommands' results.412- * Return values of groups can be processed through a413- :attr:`Group.result_callback`. This is invoked with the414- list of all return values in chain mode, or the single return415- value in case of non chained commands.416-417-- The return value is bubbled through from the :meth:`Context.invoke`418- and :meth:`Context.forward` methods. This is useful in situations419- where you internally want to call into another command.420-421-- Click does not have any hard requirements for the return values and422- does not use them itself. This allows return values to be used for423- custom decorators or workflows (like in the command chaining424- example).425-426-- When a Click script is invoked as command line application (through427- :meth:`Command.main`) the return value is ignored unless the428- `standalone_mode` is disabled in which case it's bubbled through.added:docs/contributing.md+21 added
123456789101112131415161718192021# Contributing
This is a quick reference for Click-specific development tasks. For setting up the development environment and the general contribution workflow, see the Pallets [quick reference](https://palletsprojects.com/contributing/quick/) and the [detailed contributing guide](https://palletsprojects.com/contributing/).
## Extra Test Environments
Click includes some extra test environments:
- `tox r -e stress` runs stress tests for race conditions in Click's test runner.
```shell-session $ tox r -e stress ```
- `tox r -e random` runs tests in parallel in a random order to detect test pollution.
```shell-session $ tox r -e random ```
- A CI workflow (`.github/workflows/test-flask.yaml`) runs Flask's test suite to catch downstream regressions.modified:docs/index.rst+2 added-2 removed
77 unmodified lines78 :maxdepth: 179 80 entry-points81 setuptools82+ standalone-apps83 upgrade-guides84 support-multiple-versions85 86 Conceptual Guides46 unmodified lines133 * This documentation is structured according to `Diataxis <https://diataxis.fr/>`_ and written with `MyST <https://myst-parser.readthedocs.io/en/latest/>`_134 135 * `Version Policy <https://palletsprojects.com/versions>`_136 136-* `Contributing <https://palletsprojects.com/contributing/>`_137-137 * `Donate <https://palletsprojects.com/donate>`_138 139 .. toctree::140 :maxdepth: 1141 142+ contributing143 contrib144 license145 changesmodified:docs/options.md+92 added-5 removed
339 unmodified lines340 invoke(info, args=['--lower'])341 invoke(info)342 ```343 344-````{note}345-The `default` value is given to the decorated function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.344+### How `default` and `flag_value` interact345 347-But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the decorated function receiving the `True` Python value, it will receive the `flag_value`.346+The `default` value is given to the underlying function347+as-is. So if you set `default=None`, the function receives348+`None`. Same for any other type.349 349-Which means, in example above, this option:350+But there is a special case for **non-boolean** flags: if a351+flag has a non-boolean `flag_value` (like a string or a352+class), then `default=True` is interpreted as *the flag353+should be activated by default*. The function receives the354+`flag_value`, not the Python `True`.355 356+Which means, in the example above, this option:357+358 ```python359 @click.option('--upper', 'transformation', flag_value='upper', default=True)360 ```361 2 unmodified lines364 ```python365 @click.option('--upper', 'transformation', flag_value='upper', default='upper')366 ```367 361-Because the two are equivalent, it is recommended to always set `default` to the actual value you want to pass and avoid using the special `True` case. This makes the code more explicit and predictable.368+Because the two are equivalent, it is recommended to always369+use the second form and set `default` to the actual value370+you want. This makes code more explicit and predictable.371+372+This special case does **not** apply to boolean flags (where373+`flag_value` is `True` or `False`). For boolean flags,374+`default=True` is the literal Python value `True`.375+376+The tables below show the value received by the function for377+each combination of `default`, `flag_value`, and whether378+the flag was passed on the command line.379+380+#### Boolean flags (`is_flag=True`, boolean `flag_value`)381+382+These are flags where `flag_value` is `True` or `False`.383+The `default` value is always passed through literally384+without any special substitution.385+386+| `default` | `flag_value` | Not passed | `--flag` passed |387+|-----------|--------------|------------|-----------------|388+| *(unset)* | *(unset)* | `False` | `True` |389+| `True` | *(unset)* | `True` | `True` |390+| `False` | *(unset)* | `False` | `True` |391+| `None` | *(unset)* | `None` | `True` |392+| `True` | `True` | `True` | `True` |393+| `True` | `False` | `True` | `False` |394+| `False` | `True` | `False` | `True` |395+| `False` | `False` | `False` | `False` |396+| `None` | `True` | `None` | `True` |397+| `None` | `False` | `None` | `False` |398+399+````{tip}400+For a negative flag that defaults to off, prefer the401+explicit pair form `--with-xyz/--without-xyz` over the402+single-flag `flag_value=False, default=True`:403+404+```python405+@click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)406+```407 ````408 409+#### Boolean flag pairs (`--flag/--no-flag`)410+411+These use secondary option names to provide both an on and412+off switch. The `default` value is always literal.413+414+| `default` | Not passed | `--flag` | `--no-flag` |415+|-----------|------------|----------|-------------|416+| *(unset)* | `False` | `True` | `False` |417+| `True` | `True` | `True` | `False` |418+| `False` | `False` | `True` | `False` |419+| `None` | `None` | `True` | `False` |420+421+#### Non-boolean feature switches (`flag_value` is a string, class, etc.)422+423+For these flags, `default=True` is a **special case**: it424+means "activate this flag by default" and resolves to the425+`flag_value`. All other `default` values are passed through426+literally.427+428+| `default` | `flag_value` | Not passed | `--flag` passed |429+|------------|--------------|-------------|-----------------|430+| *(unset)* | `"upper"` | `None` | `"upper"` |431+| `True` | `"upper"` | `"upper"`¹ | `"upper"` |432+| `"lower"` | `"upper"` | `"lower"` | `"upper"` |433+| `None` | `"upper"` | `None` | `"upper"` |434+435+```{hint}436+¹: `default=True` is substituted with `flag_value`.437+```438+439+#### Feature switch groups (multiple flags sharing one variable)440+441+When multiple `flag_value` options target the same parameter442+name, `default=True` on one of them marks it as the default443+choice.444+445+| Definition | Not passed | `--upper` | `--lower` |446+|--------------------------------------------------------|------------|-----------|-----------|447+| `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |448+| `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |449+| Both without `default` | `None` | `"upper"` | `"lower"` |450+451 ## Values from Environment Variables452 453 To pass in a value from a specific environment variable use `envvar`.454 133 unmodified linesadded:docs/standalone-apps.md+148 added
1+# Standalone Application with Briefcase2+3+[Briefcase](https://briefcase.beeware.org/) is a tool for packaging Python4+projects as standalone native applications. It can produce installers and5+executables for macOS, Windows, and Linux that do not require the user to6+install Python or any dependencies.7+8+- Produces platform-native installers (``.pkg`` on macOS, ``.msi`` on9+ Windows, ``.deb``/``.rpm`` on Linux).10+- Bundles a Python interpreter and all dependencies.11+- Supports passing command line arguments to the app.12+13+This page outlines the basics of packaging a Click application with14+Briefcase. Be sure to read its15+[documentation](https://briefcase.beeware.org/en/stable/how-to/building/cli-apps/)16+and use ``briefcase --help`` to understand what features are available.17+18+## Installation19+20+Install Briefcase in the virtual environment:21+22+```console23+pip install briefcase24+```25+26+## Configuration27+28+Add a ``[tool.briefcase]`` section and a29+``[tool.briefcase.app.<app-name>]`` section to ``pyproject.toml``.30+Set ``console_app = true`` so Briefcase treats the project as a command31+line application rather than a GUI application.32+33+Given a Click application with the following project structure:34+35+```text36+hello-cli/37+ src/38+ hello_cli/39+ __init__.py40+ app.py41+ LICENSE42+ pyproject.toml43+```44+45+Where ``app.py`` contains a Click command:46+47+```python48+import click49+50+@click.command()51+@click.argument("name", default="World")52+@click.option("--count", default=1, help="Number of times to greet.")53+def main(name, count):54+ """Greet someone by NAME (default: World)."""55+ for _ in range(count):56+ click.echo(f"Hello, {name}!")57+```58+59+Add the following Briefcase configuration to ``pyproject.toml``:60+61+```toml62+[tool.briefcase]63+project_name = "Hello CLI"64+bundle = "com.example"65+version = "0.0.1"66+url = "https://example.com/hello-cli"67+license.file = "LICENSE"68+author = "Your Name"69+author_email = "you@example.com"70+71+[tool.briefcase.app.hello-cli]72+formal_name = "Hello CLI"73+description = "My first application"74+long_description = """More details about the app should go here.75+"""76+sources = [77+ "src/hello_cli",78+]79+console_app = true80+requires = [81+ "click",82+]83+```84+85+The key settings are:86+87+- ``console_app = true`` -- tells Briefcase this is a terminal88+ application, not a GUI.89+- ``sources`` -- the list of source packages to include.90+- ``requires`` -- the Python dependencies to bundle (Click and any other91+ libraries the project needs).92+93+## Entry Point94+95+Briefcase launches the application by running the package with96+``python -m <package>``, so a ``__main__.py`` file **must** exist in the97+package. Without it, Briefcase will not be able to start the application.98+99+Create ``__main__.py`` in the package directory and call the Click100+command:101+102+```python103+from hello_cli.app import main104+105+if __name__ == "__main__":106+ main()107+```108+109+## Running110+111+Use ``briefcase dev`` to run the application directly from the source112+tree. Pass command line arguments after ``--``:113+114+```console115+$ briefcase dev -- World116+Hello, World!117+$ briefcase dev -- World --count 2118+Hello, World!119+Hello, World!120+```121+122+## Building and Packaging123+124+To create a distributable executable, run the following commands:125+126+```console127+briefcase create128+briefcase build129+briefcase package130+```131+132+``briefcase create`` downloads a Python interpreter and installs133+dependencies into an isolated app bundle. ``briefcase build`` compiles134+the app, and ``briefcase package`` produces the final platform installer.135+136+On macOS, this produces a ``.pkg`` installer. On Windows, it produces a137+``.msi`` installer. On Linux, it produces a system package (``.deb``,138+``.rpm``, etc.) for the current distribution.139+140+Once installed, users can run the application directly from the terminal:141+142+```console143+$ hello-cli World144+Hello, World!145+$ hello-cli World --count 2146+Hello, World!147+Hello, World!148+```modified:docs/testing.md+48 added
194 unmodified lines195 196 Prompts will be emulated so they write the input data to197 the output stream as well. If hidden input is expected then this198 does not happen.199+200+## File Descriptors and Low-Level I/O201+202+{class}`CliRunner` captures output by replacing203+`sys.stdout` and `sys.stderr` with in-memory204+{class}`~io.BytesIO`-backed wrappers. This is205+Python-level redirection: calls to {func}`~click.echo`,206+{func}`print`, or `sys.stdout.write()` are captured, but207+the wrappers have no OS-level file descriptor.208+209+Code that calls `fileno()` on `sys.stdout` or210+`sys.stderr`, like {mod}`faulthandler`,211+{mod}`subprocess`, or C extensions, would normally crash212+with {exc}`io.UnsupportedOperation` inside213+{class}`CliRunner`.214+215+To avoid this, {class}`CliRunner` preserves the original216+stream's file descriptor and exposes it via `fileno()` on217+the replacement wrapper.218+219+This means:220+- **Python-level writes** (`print()`, `click.echo()`,221+ ...) are captured as usual.222+- **fd-level writes** (C code writing directly to the223+ file descriptor) go to the original terminal and are224+ **not** captured.225+226+This is the same trade-off that227+[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228+makes with its two capture modes:229+230+- `capsys`, which captures Python-level output, where231+ `fileno()` raises `UnsupportedOperation` and fd-level232+ writes are not captured.233+- `capfd`, which captures fd-level output via234+ `os.dup2()`, where `fileno()` works and fd-level235+ writes *are* captured.236+237+Rather than implementing a full `capfd`-style mechanism,238+{class}`CliRunner` takes the simpler path: expose the239+original `fd` so that standard library helpers keep240+working, while accepting that their output is not241+captured.242+243+```{versionchanged} 8.3.3244+`fileno()` on the redirected streams now returns the245+original stream's file descriptor instead of raising.246+```modified:src/click/__init__.py+1 added
12 unmodified lines13 from .core import Context as Context14 from .core import Group as Group15 from .core import Option as Option16 from .core import Parameter as Parameter17+from .core import ParameterSource as ParameterSource18 from .decorators import argument as argument19 from .decorators import command as command20 from .decorators import confirmation_option as confirmation_option21 from .decorators import group as group103 unmodified linesmodified:src/click/_termui_impl.py+10 added-28 removed
365 unmodified lines366 self.render_progress()367 368 369 def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:370- """Decide what method to use for paging through text.371-372- The ``PAGER`` environment variable is split into an ``argv`` list with373- :func:`shlex.split` in its default POSIX mode so that quotes are374- stripped from tokens and quoted Windows paths are preserved.375-376- .. note::377- ``posix=False`` `was considered but rejected378- <https://github.com/pallets/click/pull/1477#issuecomment-620231711>`_379- because it retains quote characters in tokens. The380- :func:`shlex.quote` approach was also reverted in :pr:`1543`.381-382- .. seealso::383- :issue:`1026`, :pr:`1477` and :pr:`2775`.384- """370+ """Decide what method to use for paging through text."""371 stdout = _default_text_stdout()372 373 # There are no standard streams attached to write to. For example,374 # pythonw on Windows.2 unmodified lines377 378 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)380 381+ # Split using POSIX mode (the default) so that quote characters are382+ # stripped from tokens and quoted Windows paths are preserved.383+ # posix=False was rejected (PR #1477) because it retains quotes in384+ # tokens, and the shlex.quote approach was also reverted (PR #1543).385+ # See also: issue #1026, PR #2775.386 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))387 if pager_cmd_parts:388 if WIN:389 if _tempfilepager(generator, pager_cmd_parts, color):37 unmodified lines427 automatically.428 429 Returns ``True`` if the command was found and executed, ``False``430 otherwise so another pager can be attempted.440-441- .. seealso::442- :pr:`2775` improved error handling: :exc:`BrokenPipeError` is443- caught specifically, generator exceptions terminate the pager, and444- ``stdin.close()`` is always called in a ``finally`` block.431 """432 # Split the command into the invoked CLI and its parameters.433 if not cmd_parts:434 return False173 unmodified lines608 return editor609 return "vi"610 611 def edit_files(self, filenames: cabc.Iterable[str]) -> None:626- """Open files in the user's editor.627-628- The editor command is split into an ``argv`` list with629- :func:`shlex.split` in POSIX mode; see :func:`pager` for rationale.630-631- .. seealso::632- :issue:`1026` and :pr:`1477`.633- """612+ """Open files in the user's editor."""613 import shlex614 import subprocess615 616 editor = self.get_editor()3 unmodified lines620 environ = os.environ.copy()621 environ.update(self.env)622 623 try:624+ # Split in POSIX mode (the default) for the same reasons as625+ # in pager(): strips quotes from tokens and preserves quoted626+ # Windows paths. See issue #1026, PR #1477.627 c = subprocess.Popen(628 args=shlex.split(editor) + list(filenames),629 env=environ,630 )241 unmodified linesmodified:src/click/core.py+50 added-21 removed
138 unmodified lines139 140 return sorted(declaration_order, key=sort_key)141 142 143-class ParameterSource(enum.Enum):144- """This is an :class:`~enum.Enum` that indicates the source of a143+class ParameterSource(enum.IntEnum):144+ """This is an :class:`~enum.IntEnum` that indicates the source of a145 parameter's value.146 147 Use :meth:`click.Context.get_parameter_source` to get the148 source for a parameter by name.149 150+ Members are ordered from most explicit to least explicit source.151+ This allows comparison to check if a value was explicitly provided:152+153+ .. code-block:: python154+155+ source = ctx.get_parameter_source("port")156+ if source < click.ParameterSource.DEFAULT_MAP:157+ ... # value was explicitly set158+159+ .. versionchanged:: 8.3.3160+ Use :class:`~enum.IntEnum` and reorder members from most to161+ least explicit. Supports comparison operators.162+163 .. versionchanged:: 8.0164 Use :class:`~enum.Enum` and drop the ``validate`` method.165 166 .. versionchanged:: 8.0167 Added the ``PROMPT`` value.168 """169 170+ PROMPT = enum.auto()171+ """Used a prompt to confirm a default or provide a value."""172 COMMANDLINE = enum.auto()173 """The value was provided by the command line args."""174 ENVIRONMENT = enum.auto()175 """The value was provided with an environment variable."""161- DEFAULT = enum.auto()162- """Used the default specified by the parameter."""176 DEFAULT_MAP = enum.auto()177 """Used a default provided by :attr:`Context.default_map`."""165- PROMPT = enum.auto()166- """Used a prompt to confirm a default or provide a value."""178+ DEFAULT = enum.auto()179+ """Used the default specified by the parameter."""180 181 182 class Context:183 """The context is a special internal object that holds state relevant2403 unmodified lines2587 # Display a deprecation warning if necessary.2588 if (2589 self.deprecated2590 and value is not UNSET2578- and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)2591+ and source < ParameterSource.DEFAULT_MAP2592 ):2593 extra_message = (2594 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2595 )319 unmodified lines2915 2916 def get_default(2917 self, ctx: Context, call: bool = True2918 ) -> t.Any | t.Callable[[], t.Any] | None:2919+ """For non-boolean flag options, ``default=True`` is treated as a2920+ sentinel meaning "activate this flag by default" and is resolved to2921+ :attr:`flag_value`. This resolution is performed lazily here (rather2922+ than eagerly in :meth:`__init__`) to prevent callable ``flag_value``2923+ values (like classes) from being instantiated prematurely.2924+2925+ For example, with ``--upper/--lower`` feature switches where2926+ ``flag_value="upper"`` and ``default=True``, the default resolves2927+ to ``"upper"``.2928+2929+ .. caution::2930+ This substitution only applies to **non-boolean** flags2931+ (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is2932+ not a sentinel but a legitimate Python value, so ``default=True`` is2933+ returned as-is. Without this distinction, ``flag_value=False,2934+ default=True`` would silently always return ``False``, regardless of2935+ whether the flag was passed or not.2936+2937+ .. versionchanged:: 8.3.32938+ ``default=True`` is no longer substituted with ``flag_value`` for2939+ boolean flags, fixing negative boolean flags like ``flag_value=False,2940+ default=True``.2941+ """2942 value = super().get_default(ctx, call=False)2943 2908- # Lazily resolve default=True to flag_value. Doing this here2909- # (instead of eagerly in __init__) prevents callable flag_values2910- # (like classes) from being instantiated by the callable check below.2911- # https://github.com/pallets/click/issues/31212912- if value is True and self.is_flag:2944+ if value is True and self.is_flag and not self.is_bool_flag:2945 value = self.flag_value2946 elif call and callable(value):2947 value = value()2948 258 unmodified lines3207 else:3208 default = bool(default)3209 return confirm(self.prompt, default)3210 3179- # If show_default is set to True/False, provide this to `prompt` as well. For3180- # non-bool values of `show_default`, we use `prompt`'s default behavior3211+ # If show_default is given, provide this to `prompt` as well,3212+ # otherwise we use `prompt`'s default behavior3213 prompt_kwargs: t.Any = {}3182- if isinstance(self.show_default, bool):3214+ if self.show_default is not None:3215 prompt_kwargs["show_default"] = self.show_default3216 3217 return prompt(3218 self.prompt,109 unmodified lines3328 elif (3329 self.is_flag3330 and value is True3331 and not self.is_bool_flag3300- and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3332+ and source < ParameterSource.DEFAULT_MAP3333 ):3334 value = self.flag_value3335 3336 # Re-interpret a multiple option which has been sent as-is by the parser.1 unmodified line3338 # FLAG_NEEDS_VALUE sentinel) with the flag_value.3339 elif (3340 self.multiple3341 and value is not UNSET3310- and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3342+ and source < ParameterSource.DEFAULT_MAP3343 and any(v is FLAG_NEEDS_VALUE for v in value)3344 ):3345 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]3346 source = ParameterSource.COMMANDLINE3347 3348 # The value wasn't set, or used the param's default, prompt for one to the user3349 # if prompting is enabled.3350 elif (3319- (3320- value is UNSET3321- or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3322- )3351+ (value is UNSET or source >= ParameterSource.DEFAULT_MAP)3352 and self.prompt is not None3353 and (self.required or self.prompt_required)3354 and not ctx.resilient_parsing3355 ):123 unmodified linesmodified:src/click/termui.py+10 added-2 removed
58 unmodified lines59 60 def _build_prompt(61 text: str,62 suffix: str,63- show_default: bool = False,63+ show_default: bool | str = False,64 default: t.Any | None = None,65 show_choices: bool = True,66 type: ParamType | None = None,67 ) -> str:68 prompt = text69 if type is not None and show_choices and isinstance(type, Choice):70 prompt += f" ({', '.join(map(str, type.choices))})"71+ if isinstance(show_default, str):72+ default = f"({show_default})"73 if default is not None and show_default:74 prompt = f"{prompt} [{_format_default(default)}]"75 return f"{prompt}{suffix}"76 12 unmodified lines89 confirmation_prompt: bool | str = False,90 type: ParamType | t.Any | None = None,91 value_proc: t.Callable[[str], t.Any] | None = None,92 prompt_suffix: str = ": ",91- show_default: bool = True,93+ show_default: bool | str = True,94 err: bool = False,95 show_choices: bool = True,96 ) -> t.Any:97 """Prompts a user for input. This is a convenience function that can15 unmodified lines113 is invoked instead of the type conversion to114 convert a value.115 :param prompt_suffix: a suffix that should be added to the prompt.116 :param show_default: shows or hides the default value in the prompt.117+ If this value is a string, it shows that string118+ in parentheses instead of the actual value.119 :param err: if set to true the file defaults to ``stderr`` instead of120 ``stdout``, the same as with echo.121 :param show_choices: Show or hide choices if the passed type is a Choice.122 For example if type is a Choice of either day or week,123 show_choices is true and text is "Group by" then the124 prompt will be "Group by (day, week): ".125 126+ .. versionchanged:: 8.3.3127+ ``show_default`` can be a string to show a custom value instead128+ of the actual default, matching the help text behavior.129+130 .. versionchanged:: 8.3.1131 A space is no longer appended to the prompt.132 133 .. versionadded:: 8.0758 unmodified linesmodified:src/click/testing.py+104 added-6 removed
2 unmodified lines3 import collections.abc as cabc4 import contextlib5 import io6 import os7+import pdb8 import shlex9 import sys10 import tempfile11 import typing as t88 unmodified lines100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101 102 103 class _NamedTextIOWrapper(io.TextIOWrapper):104+ """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``105+ that does not close its underlying buffer.106+107+ An optional ``original_fd`` preserves the file descriptor of the108+ stream being replaced, so that C-level consumers that call109+ :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.110+ Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`111+ for details.112+113+ .. versionchanged:: 8.3.3114+ Added ``original_fd`` parameter and :meth:`fileno` override.115+ """116+117 def __init__(104- self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any118+ self,119+ buffer: t.BinaryIO,120+ name: str,121+ mode: str,122+ *,123+ original_fd: int = -1,124+ **kwargs: t.Any,125 ) -> None:126 super().__init__(buffer, **kwargs)127 self._name = name128 self._mode = mode129+ self._original_fd = original_fd130 131 def close(self) -> None:111- """112- The buffer this object contains belongs to some other object, so113- prevent the default __del__ implementation from closing that buffer.132+ """The buffer this object contains belongs to some other object,133+ so prevent the default ``__del__`` implementation from closing134+ that buffer.135 136 .. versionadded:: 8.3.2137 """117- ...138 139+ def fileno(self) -> int:140+ """Return the file descriptor of the original stream, if one was141+ provided at construction time.142+143+ This allows C-level consumers (``faulthandler``, ``subprocess``,144+ signal handlers, ...) to obtain a valid fd without crashing, even145+ though the Python-level writes are redirected to an in-memory146+ buffer.147+148+ .. versionadded:: 8.3.3149+ """150+ if self._original_fd >= 0:151+ return self._original_fd152+ return super().fileno()153+154 @property155 def name(self) -> str:156 return self._name157 196 unmodified lines354 env = self.make_env(env)355 356 stream_mixer = StreamMixer()357 358+ # Preserve the original file descriptors so that C-level359+ # consumers (faulthandler, subprocess, etc.) can still obtain a360+ # valid fd from the redirected streams. The original streams361+ # may themselves lack a fileno() (e.g. when CliRunner is used362+ # inside pytest's capsys), so we fall back to -1.363+ def _safe_fileno(stream: t.IO[t.Any]) -> int:364+ try:365+ return stream.fileno()366+ except (AttributeError, io.UnsupportedOperation):367+ return -1368+369+ old_stdout_fd = _safe_fileno(old_stdout)370+ old_stderr_fd = _safe_fileno(old_stderr)371+372 if self.echo_stdin:373 bytes_input = echo_input = t.cast(374 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)375 )7 unmodified lines383 # large chunk which is echoed early.384 text_input._CHUNK_SIZE = 1 # type: ignore385 386 sys.stdout = _NamedTextIOWrapper(338- stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"387+ stream_mixer.stdout,388+ encoding=self.charset,389+ name="<stdout>",390+ mode="w",391+ original_fd=old_stdout_fd,392 )393 394 sys.stderr = _NamedTextIOWrapper(395 stream_mixer.stderr,396 encoding=self.charset,397 name="<stderr>",398 mode="w",399 errors="backslashreplace",400+ original_fd=old_stderr_fd,401 )402 403 @_pause_echo(echo_input) # type: ignore404 def visible_input(prompt: str | None = None) -> str:38 unmodified lines443 old_hidden_prompt_func = termui.hidden_prompt_func444 old__getchar_func = termui._getchar445 old_should_strip_ansi = utils.should_strip_ansi # type: ignore446 old__compat_should_strip_ansi = _compat.should_strip_ansi447+ old_pdb_init = pdb.Pdb.__init__448 termui.visible_prompt_func = visible_input449 termui.hidden_prompt_func = hidden_input450 termui._getchar = _getchar451 utils.should_strip_ansi = should_strip_ansi # type: ignore452 _compat.should_strip_ansi = should_strip_ansi453 454+ def _patched_pdb_init(455+ self: pdb.Pdb,456+ completekey: str = "tab",457+ stdin: t.IO[str] | None = None,458+ stdout: t.IO[str] | None = None,459+ **kwargs: t.Any,460+ ) -> None:461+ """Default ``pdb.Pdb`` to real terminal streams during462+ ``CliRunner`` isolation.463+464+ Without this patch, ``pdb.Pdb.__init__`` inherits from465+ ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout``466+ when no explicit streams are provided. During isolation467+ those are ``BytesIO``-backed wrappers, so the debugger468+ reads from an empty buffer and writes to captured output,469+ making interactive debugging impossible.470+471+ By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the472+ original terminal streams Python preserves regardless of473+ redirection), debuggers can interact with the user while474+ ``click.echo`` output is still captured normally.475+476+ This covers ``pdb.set_trace()``, ``breakpoint()``,477+ ``pdb.post_mortem()``, and debuggers that subclass478+ ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``479+ arguments are honored and not overridden. Debuggers that480+ do not subclass ``pdb.Pdb`` (pudb, debugpy) are not481+ covered.482+483+ See: https://github.com/pallets/click/issues/654 and484+ https://github.com/pallets/click/issues/824485+ """486+ if stdin is None:487+ stdin = sys.__stdin__488+ if stdout is None:489+ stdout = sys.__stdout__490+ old_pdb_init(491+ self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs492+ )493+494+ pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]495+496 old_env = {}497 try:498 for key, value in env.items():499 old_env[key] = os.environ.get(key)22 unmodified lines522 termui._getchar = old__getchar_func523 utils.should_strip_ansi = old_should_strip_ansi # type: ignore524 _compat.should_strip_ansi = old__compat_should_strip_ansi525 formatting.FORCED_WIDTH = old_forced_width526+ pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign]527 528 def invoke(529 self,530 cli: Command,142 unmodified linesmodified:src/click/utils.py+4 added-1 removed
55 unmodified lines56 return str(value)57 58 59 def make_default_short_help(help: str, max_length: int = 45) -> str:60- """Returns a condensed version of help string."""60+ """Returns a condensed version of help string.61+62+ :meta private:63+ """64 # Consider only the first paragraph.65 paragraph_end = help.find("\n\n")66 67 if paragraph_end != -1:563 unmodified linesmodified:tests/test_options.py+50 added-2 removed
1257 unmodified lines1258 message = opt.get_help_record(ctx)[1]1259 assert "[default: (unlimited)]" in message1260 1261 1262+def test_string_show_default_shows_custom_string_in_prompt(runner):1263+ @click.command()1264+ @click.option(1265+ "--arg1", show_default="custom", prompt=True, default="my-default-value"1266+ )1267+ def cmd(arg1):1268+ pass1269+1270+ result = runner.invoke(cmd, input="my-input", standalone_mode=False)1271+ assert "(custom)" in result.output1272+ assert "my-default-value" not in result.output1273+1274+1275 class _StrictEq:1276 """Object whose ``__eq__`` raises on string comparison (like semver.Version)."""1277 1278 def __eq__(self, other):190 unmodified lines1469 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1470 ({"type": str, "flag_value": None}, [], None),1471 ({"type": str, "flag_value": None}, ["--foo"], None),1472 # Not passing --foo returns the default value as-is, in its Python type, then1460- # converted by the option type.1473+ # converted by the option type. For boolean flags, default=True is a literal1474+ # value, not a sentinel meaning "activate flag". So it is NOT substituted with1475+ # flag_value. See: https://github.com/pallets/click/issues/31111476+ # https://github.com/pallets/click/pull/32391477 ({"type": bool, "default": True, "flag_value": True}, [], True),1462- ({"type": bool, "default": True, "flag_value": False}, [], False),1478+ ({"type": bool, "default": True, "flag_value": False}, [], True),1479 ({"type": bool, "default": False, "flag_value": True}, [], False),1480 ({"type": bool, "default": False, "flag_value": False}, [], False),1481 ({"type": bool, "default": None, "flag_value": True}, [], None),1482 ({"type": bool, "default": None, "flag_value": False}, [], None),1017 unmodified lines2500 assert result.exit_code == 02501 2502 2503 @pytest.mark.parametrize(2504+ ("default", "args", "expected"),2505+ [2506+ # default=None: 3-state pattern (e.g. Flask --reload/--no-reload).2507+ # https://github.com/pallets/click/issues/30242508+ (None, [], None),2509+ (None, ["--flag"], True),2510+ (None, ["--no-flag"], False),2511+ # default=True: literal value, not substituted with flag_value.2512+ # https://github.com/pallets/click/issues/31112513+ (True, [], True),2514+ (True, ["--flag"], True),2515+ (True, ["--no-flag"], False),2516+ ],2517+)2518+def test_bool_flag_pair_default(runner, default, args, expected):2519+ """Boolean flag pairs pass ``default`` through literally.2520+2521+ Ensures ``default=True`` is not replaced by ``flag_value`` for boolean2522+ flags, and that ``default=None`` enables 3-state logic.2523+ """2524+2525+ @click.command()2526+ @click.option("--flag/--no-flag", default=default)2527+ def cli(flag):2528+ click.echo(repr(flag), nl=False)2529+2530+ result = runner.invoke(cli, args)2531+ assert result.exit_code == 02532+ assert result.output == repr(expected)2533+2534+2535+@pytest.mark.parametrize(2536 ("flag_type", "args", "expect_output"),2537 [2538 (str, [], "Default\n"),2539 (str, ["--theflag"], "FlagValue\n"),36 unmodified linesmodified:tests/test_termui.py+169 added-7 removed
1 import platform2+import shlex3 import tempfile4 import time5 from unittest.mock import patch6 1 unmodified line8 9 import click._termui_impl10 from click._compat import WIN11 from click._termui_impl import Editor12+from click._utils import UNSET13 from click.exceptions import BadParameter14 from click.exceptions import MissingParameter15 16 410 unmodified lines427 pytest.param(428 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',429 ["f.txt"],430 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],429- id="quoted windows path with spaces (issue 1026)",431+ id="quoted windows path with spaces",432 ),433 # PR #1477: pager/editor command with flags, like ``less -FRSX``.434 pytest.param(435 "less -FRSX",436 ["f.txt"],437 ["less", "-FRSX", "f.txt"],436- id="command with flags (pr 1477)",438+ id="command with flags",439 ),440 # Issue #1026: quoted command with ``--wait`` flag.441 pytest.param(442 '"my command" --option value arg',443 ["f.txt"],444 ["my command", "--option", "value", "arg", "f.txt"],443- id="quoted command with args (issue 1026)",445+ id="quoted command with args",446 ),447 # PR #1477: unquoted unix path.448 pytest.param(449 "/usr/bin/vim",5 unmodified lines455 pytest.param(456 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",457 ["f.txt"],458 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],457- id="escaped space in unix path (issue 1026)",459+ id="escaped space in unix path",460 ),461+ pytest.param(462+ " vim ",463+ ["f.txt"],464+ ["vim", "f.txt"],465+ id="leading and trailing whitespace",466+ ),467+ pytest.param(468+ "vim\tf.txt",469+ [],470+ ["vim", "f.txt"],471+ id="tab-separated tokens",472+ ),473+ pytest.param(474+ "'/Applications/My Editor.app/Contents/MacOS/editor'",475+ ["f.txt"],476+ ["/Applications/My Editor.app/Contents/MacOS/editor", "f.txt"],477+ id="single-quoted path with spaces",478+ ),479+ pytest.param(480+ '"my editor" --wait --new-window',481+ ["file 1.txt", "file 2.txt"],482+ ["my editor", "--wait", "--new-window", "file 1.txt", "file 2.txt"],483+ id="quoted editor with multiple flags and filenames with spaces",484+ ),485+ pytest.param(486+ "vim -u NONE -N",487+ ["f.txt"],488+ ["vim", "-u", "NONE", "-N", "f.txt"],489+ id="multiple short flags",490+ ),491+ pytest.param(492+ "editor",493+ ['file"name.txt'],494+ ["editor", 'file"name.txt'],495+ id="filename with double quote",496+ ),497+ pytest.param(498+ "editor",499+ ["file'name.txt"],500+ ["editor", "file'name.txt"],501+ id="filename with single quote",502+ ),503 ],504 )505 def test_editor_path_normalization(editor_cmd, filenames, expected_args):506 with patch("subprocess.Popen") as mock_popen:57 unmodified lines564 Editor(editor="nonexistent").edit_files(["f.txt"])565 566 567 @pytest.mark.parametrize(568+ ("pager_env", "expected_parts"),569+ [570+ # Simple commands.571+ pytest.param("cat", ["cat"], id="simple command"),572+ pytest.param("less", ["less"], id="less"),573+ pytest.param("less -FRSX", ["less", "-FRSX"], id="command with flags"),574+ # Whitespace handling.575+ pytest.param("", [], id="empty string"),576+ pytest.param(" ", [], id="whitespace only"),577+ pytest.param(" less ", ["less"], id="leading and trailing spaces"),578+ pytest.param("less\t-R", ["less", "-R"], id="tab as separator"),579+ # Quoted Windows paths: quotes are stripped in POSIX mode (the580+ # default), preserving backslashes inside quoted tokens (issue #1026).581+ pytest.param(582+ '"C:\\Program Files\\Git\\usr\\bin\\less.exe"',583+ ["C:\\Program Files\\Git\\usr\\bin\\less.exe"],584+ id="quoted windows path with spaces",585+ ),586+ pytest.param(587+ '"C:\\Program Files\\Git\\usr\\bin\\less.exe" -R',588+ ["C:\\Program Files\\Git\\usr\\bin\\less.exe", "-R"],589+ id="quoted windows path with flag",590+ ),591+ # Single-quoted path.592+ pytest.param(593+ "'/usr/local/bin/my pager'",594+ ["/usr/local/bin/my pager"],595+ id="single-quoted path with spaces",596+ ),597+ # Unix paths.598+ pytest.param("/usr/bin/less", ["/usr/bin/less"], id="unix absolute path"),599+ pytest.param(600+ "/usr/bin/my\\ pager",601+ ["/usr/bin/my pager"],602+ id="escaped space in unix path",603+ ),604+ # PR #1477: POSIX mode (the default) eats unquoted backslashes.605+ # On Windows, users must quote paths that contain backslashes.606+ pytest.param(607+ "C:\\path\\to\\exe /test other\\path",608+ ["C:pathtoexe", "/test", "otherpath"],609+ id="unquoted backslashes eaten in POSIX mode",610+ ),611+ ],612+)613+def test_pager_shlex_split(pager_env, expected_parts):614+ """Verify shlex.split produces the expected argv for PAGER values.615+616+ Tests the splitting logic used by :func:`click._termui_impl.pager` to617+ turn the ``PAGER`` environment variable into an ``argv`` list. See618+ issue #1026, PR #1477, PR #1543, PR #2775.619+ """620+ assert shlex.split(pager_env) == expected_parts621+622+623+def test_editor_unclosed_quote():624+ """An unclosed quote in the editor command raises ValueError."""625+ with pytest.raises(ValueError, match="No closing quotation"):626+ Editor(editor='"unclosed').edit_files(["f.txt"])627+628+629+@pytest.mark.parametrize(630 ("prompt_required", "required", "args", "expect"),631 [632 (True, False, None, "prompt"),633 (True, False, ["-v"], "Option '-v' requires an argument."),83 unmodified lines717 result = runner.invoke(cmd, input="my-input", standalone_mode=False)718 assert "my-default-value" not in result.output719 720 721+@pytest.mark.parametrize(722+ ("show_default", "default", "user_input", "in_prompt", "not_in_prompt"),723+ [724+ # Regular string replaces the actual default in the prompt.725+ ("custom", "actual", "\n", "(custom)", "actual"),726+ # String with spaces.727+ ("custom label", "actual", "\n", "(custom label)", "actual"),728+ # Unicode characters.729+ ("∞", "0", "\n", "(∞)", None),730+ # Numeric default: custom string hides the number.731+ ("unlimited", 42, "\n", "(unlimited)", "42"),732+ # Explicit default=None: custom string still appears, must provide input.733+ ("computed at runtime", None, "value\n", "(computed at runtime)", None),734+ # No default kwarg at all (internal UNSET sentinel): same as None.735+ ("computed at runtime", UNSET, "value\n", "(computed at runtime)", None),736+ # Empty string is falsy: suppresses any default display.737+ ("", "actual", "\n", None, "actual"),738+ ],739+ ids=[740+ "simple-string",741+ "string-with-spaces",742+ "unicode",743+ "numeric-default",744+ "default-is-none",745+ "default-is-unset",746+ "empty-string-is-falsy",747+ ],748+)749+def test_string_show_default_in_prompt(750+ runner, show_default, default, user_input, in_prompt, not_in_prompt751+):752+ """When show_default is a string, the prompt should display that753+ string in parentheses instead of the actual default value,754+ matching the help text behavior. See pallets/click#2836."""755+756+ option_kwargs = {"show_default": show_default, "prompt": True}757+ if default is not UNSET:758+ option_kwargs["default"] = default759+760+ @click.command()761+ @click.option("--arg1", **option_kwargs)762+ def cmd(arg1):763+ click.echo(arg1)764+765+ result = runner.invoke(cmd, input=user_input, standalone_mode=False)766+ prompt_line = result.output.split("\n")[0]767+ if in_prompt is not None:768+ assert in_prompt in prompt_line769+ if not_in_prompt is not None:770+ assert not_in_prompt not in prompt_line771+772+773 REPEAT = object()774 """Sentinel value to indicate that the prompt is expected to be repeated.775 776 I.e. the value provided by the user is not satisfactory and need to be re-prompted.100 unmodified lines877 # default=True878 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),879 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),880 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),881+ # For boolean flags, default=True is a literal value, not a sentinel meaning882+ # "activate flag", so the prompt shows [Y/n] with default=True. See:883+ # https://github.com/pallets/click/issues/3111884+ # https://github.com/pallets/click/pull/3239723- ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),724- ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),725- ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),885+ ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),886+ ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),887+ ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),888 # default=False889 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),890 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),891 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),99 unmodified linesmodified:tests/test_testing.py+76 added
1+import faulthandler2 import os3+import pdb4 import sys5 from io import BytesIO6 7 import pytest462 unmodified lines470 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)471 472 result = runner.invoke(cli)473 assert result.stderr == "gyarados gyarados gyarados"474+475+476+def test_pdb_uses_real_streams():477+ """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams478+ so that interactive debuggers work instead of reading from the479+ captured ``BytesIO`` stdin.480+ """481+482+ @click.command()483+ def cli():484+ debugger = pdb.Pdb()485+ assert debugger.stdin is sys.__stdin__486+ assert debugger.stdout is sys.__stdout__487+ click.echo("after debugger")488+489+ runner = CliRunner()490+ result = runner.invoke(cli, catch_exceptions=False)491+ assert result.output == "after debugger\n"492+493+494+def test_pdb_explicit_streams_honored():495+ """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not496+ overridden by the ``CliRunner`` patch.497+ """498+499+ @click.command()500+ def cli():501+ custom_in = sys.stdin502+ custom_out = sys.stdout503+ debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)504+ assert debugger.stdin is custom_in505+ assert debugger.stdout is custom_out506+507+ runner = CliRunner()508+ runner.invoke(cli, catch_exceptions=False)509+510+511+def test_pdb_init_restored_after_invoke():512+ """``pdb.Pdb.__init__`` is restored to its original after invoke."""513+ original = pdb.Pdb.__init__514+515+ @click.command()516+ def cli():517+ pass518+519+ runner = CliRunner()520+ runner.invoke(cli)521+522+ assert pdb.Pdb.__init__ is original523+524+525+def test_faulthandler_enable(runner):526+ """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527+ ``io.UnsupportedOperation: fileno``.528+529+ ``faulthandler.enable()`` needs a real OS file descriptor to register530+ its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531+ ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.532+533+ Reproduce:https://github.com/pallets/click/issues/2865534+ """535+536+ @click.command()537+ @click.option("--flag", type=bool, default=True)538+ def cli(flag):539+ click.echo("Executing main function...")540+ if flag:541+ click.echo("Registering faulthandler")542+ faulthandler.enable()543+ click.echo("Finished executing main function.")544+545+ result = runner.invoke(cli, ["--flag", True])546+ assert result.exit_code == 0, result.output547+ assert "Finished executing main function." in result.outputmodified:.pre-commit-config.yaml+1 added
11 unmodified lines12 rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.013 hooks:14 - id: check-merge-conflict15 - id: debug-statements16+ exclude: ^(src/click/testing\.py|tests/test_testing\.py)$17 - id: fix-byte-order-marker18 - id: trailing-whitespace19 - id: end-of-file-fixermodified:CHANGES.rst+24 added
14 unmodified lines15 ``tmp_path`` fixture instead of a shared temporary file path. :pr:`3238`16 - Treat ``Sentinel.UNSET`` values in a ``default_map`` as absent, so they fall17 through to the next default source instead of being used as the value.18 :issue:`3224` :pr:`3240`19+- Patch ``pdb.Pdb`` in ``CliRunner`` isolation so ``pdb.set_trace()``,20+ ``breakpoint()``, and debuggers subclassing ``pdb.Pdb`` (ipdb, pdbpp) can21+ interact with the real terminal instead of the captured I/O streams.22+ :issue:`654` :issue:`824` :issue:`843` :pr:`951` :pr:`3235`23+- Add optional randomized parallel test execution using ``pytest-randomly`` and24+ ``pytest-xdist`` to detect test pollution and race conditions. :pr:`3151`25+- Add contributor documentation for running stress tests, randomized26+ parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`27+- Show custom ``show_default`` string in prompts, matching the existing28+ help text behavior. :issue:`2836` :pr:`2837` :pr:`3165` :pr:`3262` :pr:`3280`29+ :pr:`3328``30+- Fix ``default=True`` with boolean ``flag_value`` always returning the31+ ``flag_value`` instead of ``True``. The ``default=True`` to ``flag_value``32+ substitution now only applies to non-boolean flags, where ``True`` acts as a33+ sentinel meaning "activate this flag by default". For boolean flags,34+ ``default=True`` is returned as a literal value. :issue:`3111` :pr:`3239`35+- Mark ``make_default_short_help`` as private API. :issue:`3189` :pr:`3250`36+- ``CliRunner``'s redirected streams now expose the original file descriptor37+ via ``fileno()``, so that ``faulthandler``, ``subprocess``, and other38+ C-level consumers no longer crash with ``io.UnsupportedOperation``.39+ :issue:`2865`40+- Change :class:`ParameterSource` to an :class:`~enum.IntEnum` and reorder41+ its members from most to least explicit, so values can be compared to42+ check whether a parameter was explicitly provided. :issue:`2879` :pr:`3248`43 44 Version 8.3.245 -------------46 1323 unmodified linesmodified:pyproject.toml+14 added
49 unmodified lines50 ]51 tests = [52 "pytest",53 ]54+tests-random = [55+ "pytest",56+ "pytest-randomly",57+ "pytest-xdist",58+]59 typing = [60 "mypy",61 "pyright",62 "pytest",106 unmodified lines169 "pytest", "-v", "--tb=short", "--basetemp={env_tmp_dir}",170 {replace = "posargs", default = [], extend = true},171 ]]172 173+[tool.tox.env.random]174+description = "randomized parallel tests to detect test pollution and race conditions"175+dependency_groups = ["tests-random"]176+commands = [[177+ "pytest", "-v", "--tb=short", "--numprocesses=auto",178+ "--basetemp={env_tmp_dir}",179+ {replace = "posargs", default = [], extend = true},180+]]181+182 [tool.tox.env.stress]183 description = "stress tests for stream lifecycle race conditions"184 commands = [[185 "pytest", "-v", "--tb=short", "-x", "-m", "stress",51 unmodified linesmodified:uv.lock+44 added
207 unmodified lines208 ]209 tests = [210 { name = "pytest" },211 ]212+tests-random = [213+ { name = "pytest" },214+ { name = "pytest-randomly" },215+ { name = "pytest-xdist" },216+]217 typing = [218 { name = "mypy" },219 { name = "pyright" },220 { name = "pytest" },21 unmodified lines242 { name = "pre-commit" },243 { name = "pre-commit-uv" },244 ]245 tests = [{ name = "pytest" }]246+tests-random = [247+ { name = "pytest" },248+ { name = "pytest-randomly" },249+ { name = "pytest-xdist" },250+]251 typing = [252 { name = "mypy" },253 { name = "pyright" },254 { name = "pytest" },54 unmodified lines309 { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },310 ]311 312 [[package]]313+name = "execnet"314+version = "2.1.2"315+source = { registry = "https://pypi.org/simple" }316+sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" }317+wheels = [318+ { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" },319+]320+321+[[package]]322 name = "filelock"323 version = "3.25.2"324 source = { registry = "https://pypi.org/simple" }325 sdist = { url = "https://files.pythonhosted.org/packages/94/b8/00651a0f559862f3bb7d6f7477b192afe3f583cc5e26403b44e59a55ab34/filelock-3.25.2.tar.gz", hash = "sha256:b64ece2b38f4ca29dd3e810287aa8c48182bbecd1ae6e9ae126c9b35f1382694", size = 40480, upload-time = "2026-03-11T20:45:38.487Z" }587 unmodified lines913 { url = "https://files.pythonhosted.org/packages/67/0f/019d3949a40280f6193b62bc010177d4ce702d0fce424322286488569cd3/python_discovery-1.2.1-py3-none-any.whl", hash = "sha256:b6a957b24c1cd79252484d3566d1b49527581d46e789aaf43181005e56201502", size = 31674, upload-time = "2026-03-26T22:30:43.396Z" },914 ]915 916 [[package]]917+name = "pytest-randomly"918+version = "4.0.1"919+source = { registry = "https://pypi.org/simple" }920+dependencies = [921+ { name = "pytest" },922+]923+sdist = { url = "https://files.pythonhosted.org/packages/c4/1d/258a4bf1109258c00c35043f40433be5c16647387b6e7cd5582d638c116b/pytest_randomly-4.0.1.tar.gz", hash = "sha256:174e57bb12ac2c26f3578188490bd333f0e80620c3f47340158a86eca0593cd8", size = 14130, upload-time = "2025-09-12T15:23:00.085Z" }924+wheels = [925+ { url = "https://files.pythonhosted.org/packages/33/3e/a4a9227807b56869790aad3e24472a554b585974fe7e551ea350f50897ae/pytest_randomly-4.0.1-py3-none-any.whl", hash = "sha256:e0dfad2fd4f35e07beff1e47c17fbafcf98f9bf4531fd369d9260e2f858bfcb7", size = 8304, upload-time = "2025-09-12T15:22:58.946Z" },926+]927+928+[[package]]929+name = "pytest-xdist"930+version = "3.8.0"931+source = { registry = "https://pypi.org/simple" }932+dependencies = [933+ { name = "execnet" },934+ { name = "pytest" },935+]936+sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" }937+wheels = [938+ { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" },939+]940+941+[[package]]942 name = "pyyaml"943 version = "6.0.3"944 source = { registry = "https://pypi.org/simple" }945 sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }720 unmodified lines