Merge branch 'main' into changelog-3372
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 5dd4acd, ec82269 · Browse files · 4 files·+1066 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+1066 added−43 removed
- tests:+817 added−0 removed
- other:+249 added−43 removed
Provenance
- Commit
84a42d3- Tree
699f71c- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
5dd4acd- Parent 2
ec82269
4 files changed+1066 added−43 removed
modified:docs/options.md+162 added-4 removed
228 unmodified lines229 230 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])231 ```232 233+## Combining short options234+235+Short options made of a single character can be combined into one argument: `-abc` is equivalent to `-a -b -c`. This is the standard POSIX behavior for short option stacking, and it is the reason a repeated flag like `-vvv` works with the [Counting](#counting) feature.236+237+```{eval-rst}238+.. click:example::239+240+ @click.command()241+ @click.option('-a', is_flag=True)242+ @click.option('-b', is_flag=True)243+ @click.option('-c', is_flag=True)244+ def cli(a, b, c):245+ click.echo(f"a={a} b={b} c={c}")246+247+.. click:run::248+249+ invoke(cli, args=['-a', '-b', '-c'])250+ invoke(cli, args=['-abc'])251+```252+253+If the last option in the combination takes a value, the value can either follow as the next argument or be attached directly:254+255+```{eval-rst}256+.. click:example::257+258+ @click.command()259+ @click.option('-v', is_flag=True)260+ @click.option('-n', type=int)261+ def cli(v, n):262+ click.echo(f"v={v} n={n}")263+264+.. click:run::265+266+ invoke(cli, args=['-v', '-n', '5'])267+ invoke(cli, args=['-vn', '5'])268+ invoke(cli, args=['-vn5'])269+```270+271+```{note}272+Multi-character short option names are not supported. An argument like `-dbg` is interpreted as the combination of `-d`, `-b`, and `-g`, so Click reports `No such option: -d` if `-d` is not declared. For longer option names, use a long option with the `--` prefix (like `--debug`).273+```274+275 ## Counting276 277 To count the occurrence of an option, set `count=True`. If the option is not278 passed on the command line, then the count is 0. Counting is commonly used for231 unmodified lines510 ```511 512 #### Feature switch groups (multiple flags sharing one variable)513 472-When multiple `flag_value` options target the same parameter473-name, `default=True` on one of them marks it as the default474-choice.514+Several `flag_value` options can target the same parameter name to form a515+feature switch group. The user picks one flag on the command line, and the516+function receives the corresponding `flag_value`. When the user picks none,517+Click falls back to whichever option claims the slot under the arbitration518+rules described below.519 520+##### Non-boolean groups521+522+For non-boolean `flag_value` (strings, enum members, classes, ...), place523+`default=True` on the option that should win when no flag is passed. The524+substitution rule above resolves it to that option's `flag_value`. Any other525+explicit `default` is passed through literally.526+527 | Definition | Not passed | `--upper` | `--lower` |528 |--------------------------------------------------------|------------|-----------|-----------|529 | `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |530 | `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |480-| Both without `default` | `None` | `"upper"` | `"lower"` |531+| `--upper` with `flag_value='upper'`, `default=None` | `None` | `"upper"` | `"lower"` |532+| Neither option carries a `default` | `None` | `"upper"` | `"lower"` |533 534+The third row is the three-state pattern: the function receives `None` when no535+flag is passed, distinguishable from either explicit choice.536+537+##### Boolean groups538+539+When `flag_value` is `True` or `False`, the substitution rule does not apply:540+`default=True` is the literal Python `True`. To make one flag in an541+enable/disable pair the default, set its `default=True` explicitly:542+543+```python544+@click.option("--without-xyz", "enable_xyz", flag_value=False)545+@click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)546+```547+548+| Definition | Not passed | `--with-xyz` | `--without-xyz` |549+|---------------------------------------------------------|------------|--------------|-----------------|550+| `--with-xyz` with `flag_value=True`, `default=True` | `True` | `True` | `False` |551+| `--without-xyz` with `flag_value=False`, `default=False`| `False` | `True` | `False` |552+| `--with-xyz` with `flag_value=True`, `default=None` | `None` | `True` | `False` |553+| Neither option carries a `default` | `False` | `True` | `False` |554+555+```{tip}556+For most enable/disable cases, the pair form `--with-xyz/--without-xyz` is557+shorter and equivalent. The multi-flag group form is useful when the on and off558+flags need distinct names without a shared stem, or when each flag needs its559+own help text.560+```561+562+##### Arbitration rules563+564+When several options in a group resolve their values simultaneously, only one565+wins the parameter slot. The full arbitration policy (source precedence,566+explicit-beats-auto tie-break, first-declared fallback) is enumerated under567+[Option value resolution](#option-value-resolution).568+569+## Option value resolution570+571+This section enumerates the rules Click applies when computing the value572+delivered to the decorated function for every option. Rules are listed in the573+order they fire during the parsing pipeline.574+575+### Type inference576+577+Without an explicit `type=`, Click infers the parameter type at construction:578+579+1. If `flag_value` is `True` or `False`, the type is {class}`BoolParamType`.580+2. If `flag_value` is an `int`, `float`, or `str`, the type is the matching581+ basic type.582+3. If `flag_value` is any other Python object (a class, an enum member, a583+ `frozenset`, ...), the type is {data}`UNPROCESSED` so the value passes584+ through unchanged.585+4. Otherwise, the type is inferred from `default` if set, falling back to586+ {class}`StringParamType` when neither hint is available.587+588+### `default` interpretation589+590+The literal value passed as `default=` is interpreted differently depending on591+whether the option is a flag and what `flag_value` it carries:592+593+1. `default=UNSET` (the absence sentinel) is treated as if `default` was not594+ passed at all. It does not count as "the user picked nothing", and it does595+ not count as an explicit default for arbitration purposes.596+2. For a bare boolean flag (no `flag_value`, or `flag_value` of `True` or597+ `False`), an unset `default` auto-derives to `False`.598+3. For a non-boolean flag with a `flag_value`, `default=True` is substituted599+ with `flag_value`. This is the "activate this flag by default" shorthand.600+ Any non-`True` `default` is passed through literally.601+4. For a boolean flag with `flag_value` set, `default=True` is the literal602+ Python `True`. The substitution from rule 3 does not apply.603+5. `default=None` is always a real explicit value, distinct from `UNSET`604+ absence.605+6. Any other `default` is delivered to the function unchanged after conversion606+ through the parameter's type.607+608+### Value sources609+610+Click resolves the value of every option from the following611+sources, in order of decreasing precedence:612+613+1. **command line input** ({attr}`ParameterSource.COMMANDLINE`),614+2. **environment variable** named in `envvar=` or derived from `auto_envvar_prefix`615+ ({attr}`ParameterSource.ENVIRONMENT`),616+3. **`default_map` entry** matching the parameter name on the active {class}`Context`617+ ({attr}`ParameterSource.DEFAULT_MAP`),618+4. **parameter default** ({attr}`ParameterSource.DEFAULT`).619+620+The first source that produces a value wins. Environment variables and621+`default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through622+to the next source rather than supplying `UNSET` to the function.623+624+### Slot arbitration625+626+Several options can target the same `name` to form a feature switch group. When627+they do, only one option's value reaches the function. Arbitration applies628+these rules, in order:629+630+1. **By source.** Whichever option resolved its value from the most explicit631+ source wins, regardless of decorator order. Any command-line input beats any632+ default, an environment variable beats a `default_map` entry, and so on.633+2. **Within the default tier, explicit beats auto-derived.** An option that634+ received an explicit `default=` keyword wins over one whose default came635+ from `default` interpretation.636+3. **Otherwise, last declared wins.** When all options in the group resolved637+ from the same source and tier (all auto-derived defaults, or all explicit638+ defaults), the option declared last in the source code keeps the slot.639+640 ## Values from Environment Variables641 642 To pass in a value from a specific environment variable use `envvar`.643 151 unmodified linesmodified:src/click/core.py+72 added-39 removed
91 unmodified lines92 93 raise RuntimeError(message)94 95 96+def _format_deprecated_label(deprecated: bool | str) -> str:97+ """Return the parenthesized deprecation label shown in help text."""98+ label = _("deprecated").upper()99+ if isinstance(deprecated, str):100+ return f"({label}: {deprecated})"101+ return f"({label})"102+103+104+def _format_deprecated_suffix(deprecated: bool | str) -> str:105+ """Return the trailing reason for a ``DeprecationWarning`` message,106+ prefixed with a space, or an empty string when no reason was given.107+ """108+ if isinstance(deprecated, str):109+ return f" {deprecated}"110+ return ""111+112+113 def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:114 return list(zip(*repeat(iter(iterable), batch_size), strict=False))115 116 353 unmodified lines470 471 self._close_callbacks: list[t.Callable[[], t.Any]] = []472 self._depth = 0473 self._parameter_source: dict[str, ParameterSource] = {}474+ # Tracks whether the option that currently owns each parameter slot in475+ # :attr:`params` had its ``default`` set explicitly by the user. Used476+ # to tie-break feature-switch groups where multiple options share a477+ # parameter name and both fall back to their default value.478+ # Refs: https://github.com/pallets/click/issues/3403479+ self._param_default_explicit: dict[str, bool] = {}480 self._exit_stack = ExitStack()481 482 @property483 def protected_args(self) -> list[str]:674 unmodified lines1158 else:1159 text = ""1160 1161 if self.deprecated:1139- localised_deprectated = _("deprecated").upper()1140- deprecated_message = (1141- f"({localised_deprectated}: {self.deprecated})"1142- if isinstance(self.deprecated, str)1143- else f"({localised_deprectated})"1144- )1145- text = f"{_(text)} {deprecated_message}"1162+ text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"1163 1164 return text.strip()1165 1166 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:21 unmodified lines1188 else:1189 text = ""1190 1191 if self.deprecated:1175- localised_deprectated = _("deprecated").upper()1176- deprecated_message = (1177- f"({localised_deprectated}: {self.deprecated})"1178- if isinstance(self.deprecated, str)1179- else f"({localised_deprectated})"1180- )1181- text = f"{_(text)} {deprecated_message}"1192+ text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"1193 1194 if text:1195 formatter.write_paragraph()1196 98 unmodified lines1295 """Given a context, this invokes the attached callback (if it exists)1296 in the right way.1297 """1298 if self.deprecated:1288- extra_message = (1289- f" {self.deprecated}" if isinstance(self.deprecated, str) else ""1290- )1299 message = _(1300 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"1293- ).format(name=self.name, extra_message=extra_message)1301+ ).format(1302+ name=self.name,1303+ extra_message=_format_deprecated_suffix(self.deprecated),1304+ )1305 echo(style(message, fg="red"), err=True)1306 1307 if self.callback is not None:1308 return ctx.invoke(self.callback, **ctx.params)896 unmodified lines2205 self.nargs = nargs2206 self.multiple = multiple2207 self.expose_value = expose_value2208 self.default: t.Any | t.Callable[[], t.Any] | None = default2209+ # Whether the user passed ``default`` explicitly to the constructor.2210+ # Captured before any auto-derived default (like ``False`` for boolean2211+ # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2212+ # remains ``False`` when the default was inferred rather than chosen.2213+ # Refs: https://github.com/pallets/click/issues/34032214+ self._default_explicit: bool = default is not UNSET2215 self.is_eager = is_eager2216 self.metavar = metavar2217 self.envvar = envvar2218 self._custom_shell_complete = shell_complete378 unmodified lines2597 a default).2598 2599 :meta private:2600 """2601+ # Capture the slot's existing state before we mutate2602+ # ``_parameter_source`` so the write decision below can compare our2603+ # incoming source against the source of the option that already wrote2604+ # the slot (if any).2605+ existing_value = ctx.params.get(self.name, UNSET)2606+ existing_source = ctx.get_parameter_source(self.name)2607+ existing_default_explicit = ctx._param_default_explicit.get(self.name, False)2608+2609 with augment_usage_errors(ctx, param=self):2610 value, source = self.consume_value(ctx, opts)2611 2587- ctx.set_parameter_source(self.name, source)2588-2612 # Display a deprecation warning if necessary.2613 if (2614 self.deprecated2615 and value is not UNSET2616 and source < ParameterSource.DEFAULT_MAP2617 ):2595- extra_message = (2596- f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2597- )2618 message = _(2619 "DeprecationWarning: The {param_type} {name!r} is deprecated."2620 "{extra_message}"2621 ).format(2622 param_type=self.param_type_name,2623 name=self.human_readable_name,2604- extra_message=extra_message,2624+ extra_message=_format_deprecated_suffix(self.deprecated),2625 )2626 echo(style(message, fg="red"), err=True)2627 2628 # Process the value through the parameter's type.6 unmodified lines2635 # value is incompatible with the parameter type, so we reset the value2636 # to UNSET, which will be interpreted as a missing value.2637 value = UNSET2638 2619- # Add parameter's value to the context.2620- if (2621- self.expose_value2622- # We skip adding the value if it was previously set by another parameter2623- # targeting the same variable name. This prevents parameters competing for2624- # the same name to override each other.2625- and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2626- ):2627- ctx.params[self.name] = value2639+ # Arbitrate the slot when several parameters target the same variable2640+ # name (feature-switch groups). See: https://github.com/pallets/click/issues/34032641+ slot_empty = existing_value is UNSET2642+ more_explicit = existing_source is not None and source < existing_source2643+ same_source = existing_source is not None and source == existing_source2644+ auto_would_downgrade_explicit = (2645+ same_source2646+ and source == ParameterSource.DEFAULT2647+ and existing_default_explicit2648+ and not self._default_explicit2649+ )2650+ is_winner = (2651+ slot_empty2652+ or more_explicit2653+ or (same_source and not auto_would_downgrade_explicit)2654+ )2655 2656+ if is_winner:2657+ ctx.set_parameter_source(self.name, source)2658+ if self.expose_value:2659+ ctx.params[self.name] = value2660+ ctx._param_default_explicit[self.name] = self._default_explicit2661+ elif existing_source is None:2662+ # Nothing has claimed the slot yet. Record at least our source so downstream2663+ # lookups don't return ``None``.2664+ ctx.set_parameter_source(self.name, source)2665+2666 return value, args2667 2668 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2669 return None147 unmodified lines2817 else:2818 prompt_text = prompt2819 2820 if deprecated:2784- deprecated_message = (2785- f"(DEPRECATED: {deprecated})"2786- if isinstance(deprecated, str)2787- else "(DEPRECATED)"2788- )2789- help = help + deprecated_message if help is not None else deprecated_message2821+ label = _format_deprecated_label(deprecated)2822+ help = f"{help} {label}" if help is not None else label2823 2824 self.prompt = prompt_text2825 self.confirmation_prompt = confirmation_prompt2826 self.prompt_required = prompt_required709 unmodified linesmodified:tests/test_options.py+817 added
2580 unmodified lines2581 assert result.output == repr(expected)2582 2583 2584 @pytest.mark.parametrize(2585+ ("opts", "args", "expected"),2586+ [2587+ # #3403 reproducer: enable/disable pair with explicit ``default=True``2588+ # on the positive flag, declared after (inner decorator) the negative.2589+ # https://github.com/pallets/click/issues/34032590+ pytest.param(2591+ [2592+ ("--without-xyz", {"flag_value": False}),2593+ ("--with-xyz", {"flag_value": True, "default": True}),2594+ ],2595+ [],2596+ True,2597+ id="3403-reproducer-no-args",2598+ ),2599+ pytest.param(2600+ [2601+ ("--without-xyz", {"flag_value": False}),2602+ ("--with-xyz", {"flag_value": True, "default": True}),2603+ ],2604+ ["--with-xyz"],2605+ True,2606+ id="3403-reproducer-with-only",2607+ ),2608+ pytest.param(2609+ [2610+ ("--without-xyz", {"flag_value": False}),2611+ ("--with-xyz", {"flag_value": True, "default": True}),2612+ ],2613+ ["--without-xyz"],2614+ False,2615+ id="3403-reproducer-without-only",2616+ ),2617+ # When both flags are passed, the parser keeps the last value seen.2618+ pytest.param(2619+ [2620+ ("--without-xyz", {"flag_value": False}),2621+ ("--with-xyz", {"flag_value": True, "default": True}),2622+ ],2623+ ["--with-xyz", "--without-xyz"],2624+ False,2625+ id="3403-reproducer-with-then-without",2626+ ),2627+ pytest.param(2628+ [2629+ ("--without-xyz", {"flag_value": False}),2630+ ("--with-xyz", {"flag_value": True, "default": True}),2631+ ],2632+ ["--without-xyz", "--with-xyz"],2633+ True,2634+ id="3403-reproducer-without-then-with",2635+ ),2636+ # Order-independence: explicit ``default=True`` on the OUTER2637+ # decorator (declared first) must produce the same behavior.2638+ pytest.param(2639+ [2640+ ("--with-xyz", {"flag_value": True, "default": True}),2641+ ("--without-xyz", {"flag_value": False}),2642+ ],2643+ [],2644+ True,2645+ id="explicit-default-outer-no-args",2646+ ),2647+ pytest.param(2648+ [2649+ ("--with-xyz", {"flag_value": True, "default": True}),2650+ ("--without-xyz", {"flag_value": False}),2651+ ],2652+ ["--without-xyz"],2653+ False,2654+ id="explicit-default-outer-cmdline-overrides",2655+ ),2656+ # Explicit ``default=False`` on the negative flag wins over the2657+ # auto-derived default of the positive one. Result value is False2658+ # either way, but the assertion still guards source tracking.2659+ pytest.param(2660+ [2661+ ("--with-xyz", {"flag_value": True}),2662+ ("--without-xyz", {"flag_value": False, "default": False}),2663+ ],2664+ [],2665+ False,2666+ id="explicit-default-false-on-negative",2667+ ),2668+ # Explicit ``default=True`` on the negative flag is unusual but2669+ # legal: post-#3239, it is a literal Python value, not a sentinel.2670+ pytest.param(2671+ [2672+ ("--with-xyz", {"flag_value": True}),2673+ ("--without-xyz", {"flag_value": False, "default": True}),2674+ ],2675+ [],2676+ True,2677+ id="explicit-default-true-on-negative",2678+ ),2679+ # Both options carry an explicit default: last-wins, so the option2680+ # declared last in the source code keeps the slot. Confirms the2681+ # explicit-beats-auto tie-break does not also promote first-declared2682+ # over a later explicit default.2683+ pytest.param(2684+ [2685+ ("--with-xyz", {"flag_value": True, "default": True}),2686+ ("--without-xyz", {"flag_value": False, "default": False}),2687+ ],2688+ [],2689+ False,2690+ id="both-explicit-defaults-last-wins",2691+ ),2692+ pytest.param(2693+ [2694+ ("--without-xyz", {"flag_value": False, "default": False}),2695+ ("--with-xyz", {"flag_value": True, "default": True}),2696+ ],2697+ [],2698+ True,2699+ id="both-explicit-defaults-last-wins-swapped",2700+ ),2701+ # No option has an explicit default: every boolean flag2702+ # auto-derives ``default=False`` regardless of its ``flag_value``,2703+ # so the slot is False either way. Last-wins applies under the hood2704+ # but is not observable because both values are equal.2705+ pytest.param(2706+ [2707+ ("--with-xyz", {"flag_value": True}),2708+ ("--without-xyz", {"flag_value": False}),2709+ ],2710+ [],2711+ False,2712+ id="both-auto-defaults-positive-first",2713+ ),2714+ pytest.param(2715+ [2716+ ("--without-xyz", {"flag_value": False}),2717+ ("--with-xyz", {"flag_value": True}),2718+ ],2719+ [],2720+ False,2721+ id="both-auto-defaults-negative-first",2722+ ),2723+ # Explicit ``default=False`` matching the auto-derived value:2724+ # the explicit option still wins the slot. Confirms tracking is2725+ # source-based and not value-based.2726+ pytest.param(2727+ [2728+ ("--with-xyz", {"flag_value": True, "default": False}),2729+ ("--without-xyz", {"flag_value": False}),2730+ ],2731+ [],2732+ False,2733+ id="explicit-default-matches-auto-still-wins",2734+ ),2735+ # Three-flag group: the explicit default wins regardless of its2736+ # position in the decorator stack.2737+ pytest.param(2738+ [2739+ ("--auto-a", {"flag_value": True}),2740+ ("--explicit", {"flag_value": False, "default": False}),2741+ ("--auto-b", {"flag_value": True}),2742+ ],2743+ [],2744+ False,2745+ id="three-flags-explicit-in-middle",2746+ ),2747+ pytest.param(2748+ [2749+ ("--auto-a", {"flag_value": True}),2750+ ("--auto-b", {"flag_value": False}),2751+ ("--explicit", {"flag_value": True, "default": True}),2752+ ],2753+ [],2754+ True,2755+ id="three-flags-explicit-last",2756+ ),2757+ pytest.param(2758+ [2759+ ("--explicit", {"flag_value": False, "default": False}),2760+ ("--auto-a", {"flag_value": True}),2761+ ("--auto-b", {"flag_value": True}),2762+ ],2763+ [],2764+ False,2765+ id="three-flags-explicit-first",2766+ ),2767+ # Three-state pattern: explicit ``default=None`` on one option2768+ # must beat a sibling's auto-derived ``False``.2769+ pytest.param(2770+ [2771+ ("--without-xyz", {"flag_value": False}),2772+ ("--with-xyz", {"flag_value": True, "default": None}),2773+ ],2774+ [],2775+ None,2776+ id="explicit-default-none-three-state",2777+ ),2778+ pytest.param(2779+ [2780+ ("--without-xyz", {"flag_value": False}),2781+ ("--with-xyz", {"flag_value": True, "default": None}),2782+ ],2783+ ["--with-xyz"],2784+ True,2785+ id="explicit-default-none-three-state-with",2786+ ),2787+ pytest.param(2788+ [2789+ ("--without-xyz", {"flag_value": False}),2790+ ("--with-xyz", {"flag_value": True, "default": None}),2791+ ],2792+ ["--without-xyz"],2793+ False,2794+ id="explicit-default-none-three-state-without",2795+ ),2796+ # Command-line input always beats any default, regardless of2797+ # which option carried the explicit default.2798+ pytest.param(2799+ [2800+ ("--with-xyz", {"flag_value": True, "default": True}),2801+ ("--without-xyz", {"flag_value": False}),2802+ ],2803+ ["--without-xyz"],2804+ False,2805+ id="cmdline-beats-explicit-default",2806+ ),2807+ pytest.param(2808+ [2809+ ("--without-xyz", {"flag_value": False, "default": False}),2810+ ("--with-xyz", {"flag_value": True}),2811+ ],2812+ ["--with-xyz"],2813+ True,2814+ id="cmdline-beats-explicit-default-symmetric",2815+ ),2816+ ],2817+)2818+def test_bool_flag_group_competition(runner, opts, args, expected):2819+ """Competing boolean flags sharing a single parameter name.2820+2821+ Verifies the arbitration rules between options that target the same2822+ variable name in a feature-switch group.2823+2824+ Regression test for https://github.com/pallets/click/issues/34032825+ """2826+2827+ @click.command()2828+ def cli(enable_xyz):2829+ click.echo(repr(enable_xyz), nl=False)2830+2831+ for opt_name, opt_kwargs in opts:2832+ cli = click.option(opt_name, "enable_xyz", **opt_kwargs)(cli)2833+2834+ result = runner.invoke(cli, args)2835+ assert result.exit_code == 0, result.output2836+ assert result.output == repr(expected)2837+2838+2839+@pytest.mark.parametrize(2840+ ("envvar_value", "args", "expected"),2841+ [2842+ # An env var on one option in the group provides ENVIRONMENT source,2843+ # which beats any sibling's DEFAULT regardless of explicit-default.2844+ ("1", [], True),2845+ ("0", [], False),2846+ # Command-line still beats the env var.2847+ ("0", ["--with-xyz"], True),2848+ ("1", ["--without-xyz"], False),2849+ ],2850+)2851+def test_bool_flag_group_competition_with_envvar(2852+ runner, monkeypatch, envvar_value, args, expected2853+):2854+ monkeypatch.setenv("XYZ", envvar_value)2855+2856+ @click.command()2857+ @click.option("--without-xyz", "enable_xyz", flag_value=False)2858+ @click.option(2859+ "--with-xyz",2860+ "enable_xyz",2861+ flag_value=True,2862+ default=False,2863+ envvar="XYZ",2864+ )2865+ def cli(enable_xyz):2866+ click.echo(repr(enable_xyz), nl=False)2867+2868+ result = runner.invoke(cli, args)2869+ assert result.exit_code == 0, result.output2870+ assert result.output == repr(expected)2871+2872+2873+@pytest.mark.parametrize(2874+ ("default_map", "args", "expected"),2875+ [2876+ # ``default_map`` provides DEFAULT_MAP source, beating either default.2877+ ({"enable_xyz": True}, [], True),2878+ ({"enable_xyz": False}, [], False),2879+ # Command-line still beats default_map.2880+ ({"enable_xyz": False}, ["--with-xyz"], True),2881+ ({"enable_xyz": True}, ["--without-xyz"], False),2882+ ],2883+)2884+def test_bool_flag_group_competition_with_default_map(2885+ runner, default_map, args, expected2886+):2887+ @click.command()2888+ @click.option("--without-xyz", "enable_xyz", flag_value=False)2889+ @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)2890+ def cli(enable_xyz):2891+ click.echo(repr(enable_xyz), nl=False)2892+2893+ result = runner.invoke(cli, args, default_map=default_map)2894+ assert result.exit_code == 0, result.output2895+ assert result.output == repr(expected)2896+2897+2898+@pytest.mark.parametrize(2899+ ("opts", "args", "expected"),2900+ [2901+ # Non-boolean feature switch group: classic --upper/--lower2902+ # pattern. The option with ``default=True`` acts as the default2903+ # via the substitution rule (#3239) for non-boolean ``flag_value``.2904+ pytest.param(2905+ [2906+ ("--upper", {"flag_value": "upper", "default": True}),2907+ ("--lower", {"flag_value": "lower"}),2908+ ],2909+ [],2910+ "upper",2911+ id="string-default-true-substitutes-to-flag-value",2912+ ),2913+ pytest.param(2914+ [2915+ ("--upper", {"flag_value": "upper", "default": True}),2916+ ("--lower", {"flag_value": "lower"}),2917+ ],2918+ ["--upper"],2919+ "upper",2920+ id="string-default-true-cmdline-positive",2921+ ),2922+ pytest.param(2923+ [2924+ ("--upper", {"flag_value": "upper", "default": True}),2925+ ("--lower", {"flag_value": "lower"}),2926+ ],2927+ ["--lower"],2928+ "lower",2929+ id="string-default-true-cmdline-overrides",2930+ ),2931+ # Explicit literal string default beats sibling's absent default.2932+ # Confirms the explicit-beats-absent rule applies regardless of type.2933+ pytest.param(2934+ [2935+ ("--upper", {"flag_value": "upper", "default": "lower"}),2936+ ("--lower", {"flag_value": "lower"}),2937+ ],2938+ [],2939+ "lower",2940+ id="string-explicit-default-wins-over-absent",2941+ ),2942+ pytest.param(2943+ [2944+ ("--upper", {"flag_value": "upper"}),2945+ ("--lower", {"flag_value": "lower", "default": "upper"}),2946+ ],2947+ [],2948+ "upper",2949+ id="string-explicit-default-wins-from-second-position",2950+ ),2951+ # Empty string as ``flag_value``: still a legal value, including2952+ # under the ``default=True`` substitution rule.2953+ pytest.param(2954+ [2955+ ("--empty", {"flag_value": "", "default": True}),2956+ ("--filled", {"flag_value": "filled"}),2957+ ],2958+ [],2959+ "",2960+ id="empty-string-flag-value-default-true",2961+ ),2962+ pytest.param(2963+ [2964+ ("--empty", {"flag_value": "", "default": True}),2965+ ("--filled", {"flag_value": "filled"}),2966+ ],2967+ ["--empty"],2968+ "",2969+ id="empty-string-flag-value-cmdline",2970+ ),2971+ # Empty string as ``default``: explicit empty string beats2972+ # the sibling's absent default.2973+ pytest.param(2974+ [2975+ ("--upper", {"flag_value": "upper", "default": ""}),2976+ ("--lower", {"flag_value": "lower"}),2977+ ],2978+ [],2979+ "",2980+ id="empty-string-explicit-default",2981+ ),2982+ # ``flag_value=None`` is a legal flag value: when the option is2983+ # activated, the function receives ``None``.2984+ pytest.param(2985+ [2986+ ("--none", {"flag_value": None, "default": "fallback"}),2987+ ("--other", {"flag_value": "other"}),2988+ ],2989+ [],2990+ "fallback",2991+ id="none-flag-value-default-fallback",2992+ ),2993+ pytest.param(2994+ [2995+ ("--none", {"flag_value": None, "default": "fallback"}),2996+ ("--other", {"flag_value": "other"}),2997+ ],2998+ ["--none"],2999+ None,3000+ id="none-flag-value-cmdline-passes-none",3001+ ),3002+ pytest.param(3003+ [3004+ ("--none", {"flag_value": None, "default": "fallback"}),3005+ ("--other", {"flag_value": "other"}),3006+ ],3007+ ["--other"],3008+ "other",3009+ id="none-flag-value-cmdline-passes-other",3010+ ),3011+ # Explicit ``default=None`` is a real value (not absence) and3012+ # must beat a sibling's absent default. Three-state pattern for3013+ # non-boolean flag groups.3014+ pytest.param(3015+ [3016+ ("--upper", {"flag_value": "upper", "default": None}),3017+ ("--lower", {"flag_value": "lower"}),3018+ ],3019+ [],3020+ None,3021+ id="explicit-default-none-three-state",3022+ ),3023+ pytest.param(3024+ [3025+ ("--upper", {"flag_value": "upper", "default": None}),3026+ ("--lower", {"flag_value": "lower"}),3027+ ],3028+ ["--upper"],3029+ "upper",3030+ id="explicit-default-none-cmdline-upper",3031+ ),3032+ pytest.param(3033+ [3034+ ("--upper", {"flag_value": "upper", "default": None}),3035+ ("--lower", {"flag_value": "lower"}),3036+ ],3037+ ["--lower"],3038+ "lower",3039+ id="explicit-default-none-cmdline-lower",3040+ ),3041+ # Passing ``default=UNSET`` explicitly is the same as not passing3042+ # ``default`` at all, so the sibling's explicit default wins.3043+ pytest.param(3044+ [3045+ ("--upper", {"flag_value": "upper", "default": UNSET}),3046+ ("--lower", {"flag_value": "lower", "default": "lower"}),3047+ ],3048+ [],3049+ "lower",3050+ id="unset-default-equivalent-to-absent",3051+ ),3052+ pytest.param(3053+ [3054+ ("--upper", {"flag_value": "upper", "default": UNSET}),3055+ ("--lower", {"flag_value": "lower", "default": "lower"}),3056+ ],3057+ ["--upper"],3058+ "upper",3059+ id="unset-default-cmdline-still-works",3060+ ),3061+ # Neither option has a default: the slot resolves to ``None``3062+ # because non-boolean flags do not auto-derive a default.3063+ pytest.param(3064+ [3065+ ("--upper", {"flag_value": "upper"}),3066+ ("--lower", {"flag_value": "lower"}),3067+ ],3068+ [],3069+ None,3070+ id="non-boolean-no-defaults-resolves-to-none",3071+ ),3072+ pytest.param(3073+ [3074+ ("--upper", {"flag_value": "upper"}),3075+ ("--lower", {"flag_value": "lower"}),3076+ ],3077+ ["--upper"],3078+ "upper",3079+ id="non-boolean-no-defaults-cmdline-still-works",3080+ ),3081+ # Three-flag string group: explicit default wins from any3082+ # position in the decorator stack.3083+ pytest.param(3084+ [3085+ ("--upper", {"flag_value": "upper"}),3086+ ("--mixed", {"flag_value": "MiXeD", "default": "MiXeD"}),3087+ ("--lower", {"flag_value": "lower"}),3088+ ],3089+ [],3090+ "MiXeD",3091+ id="three-flags-explicit-default-in-middle",3092+ ),3093+ pytest.param(3094+ [3095+ ("--upper", {"flag_value": "upper"}),3096+ ("--lower", {"flag_value": "lower"}),3097+ ("--default-choice", {"flag_value": "chosen", "default": True}),3098+ ],3099+ [],3100+ "chosen",3101+ id="three-flags-default-true-substitution-last",3102+ ),3103+ # Both options have explicit defaults: last-wins, so the option3104+ # declared last keeps the slot, regardless of value type.3105+ pytest.param(3106+ [3107+ ("--upper", {"flag_value": "upper", "default": "first"}),3108+ ("--lower", {"flag_value": "lower", "default": "second"}),3109+ ],3110+ [],3111+ "second",3112+ id="both-explicit-defaults-string-last-wins",3113+ ),3114+ # Mixed boolean and non-boolean ``flag_value`` in the same group3115+ # is allowed. Both options here carry an explicit default, so last-wins3116+ # picks the option declared last regardless of value type. The boolean3117+ # ``default=False`` is a literal value (post-#3239), not a sentinel.3118+ pytest.param(3119+ [3120+ ("--bool-flag", {"flag_value": True, "default": False}),3121+ ("--str-flag", {"flag_value": "named", "default": "explicit"}),3122+ ],3123+ [],3124+ "explicit",3125+ id="mixed-bool-and-string-last-wins",3126+ ),3127+ pytest.param(3128+ [3129+ ("--str-flag", {"flag_value": "named", "default": "explicit"}),3130+ ("--bool-flag", {"flag_value": True, "default": False}),3131+ ],3132+ [],3133+ False,3134+ id="mixed-bool-and-string-last-wins-swapped",3135+ ),3136+ # Empty string default coexisting with ``default=True``3137+ # substitution: ``default=""`` is explicit, ``default=True`` is also3138+ # explicit (and substitutes to the option's ``flag_value``). Last-wins3139+ # picks the option declared last.3140+ pytest.param(3141+ [3142+ ("--upper", {"flag_value": "upper", "default": True}),3143+ ("--blank", {"flag_value": "blank", "default": ""}),3144+ ],3145+ [],3146+ "",3147+ id="default-true-vs-empty-string-last-wins",3148+ ),3149+ pytest.param(3150+ [3151+ ("--blank", {"flag_value": "blank", "default": ""}),3152+ ("--upper", {"flag_value": "upper", "default": True}),3153+ ],3154+ [],3155+ "upper",3156+ id="default-true-vs-empty-string-last-wins-swapped",3157+ ),3158+ ],3159+)3160+def test_flag_group_competition_non_boolean(runner, opts, args, expected):3161+ """Same arbitration rules as :func:`test_bool_flag_group_competition`,3162+ but for feature-switch groups with non-boolean ``flag_value``.3163+ """3164+3165+ @click.command()3166+ def cli(case):3167+ click.echo(repr(case), nl=False)3168+3169+ for opt_name, opt_kwargs in opts:3170+ cli = click.option(opt_name, "case", **opt_kwargs)(cli)3171+3172+ result = runner.invoke(cli, args)3173+ assert result.exit_code == 0, result.output3174+ assert result.output == repr(expected)3175+3176+3177+@pytest.mark.parametrize(3178+ ("default_a", "default_b", "args", "expected"),3179+ [3180+ # ``default=UNSET`` and an absent ``default`` keyword must produce3181+ # identical behavior. Both options here are bare boolean flags, so3182+ # both auto-derive ``False`` and last-wins applies (``--a`` is3183+ # processed last); the value is ``False`` either way.3184+ (UNSET, UNSET, [], False),3185+ # ``default=UNSET`` on one side, explicit on the other: the explicit3186+ # one wins regardless of decorator order.3187+ (UNSET, True, [], True),3188+ (True, UNSET, [], True),3189+ (UNSET, False, [], False),3190+ (False, UNSET, [], False),3191+ # ``default=None`` is a real value, distinct from ``UNSET``, and3192+ # remains explicit even when the sibling carries an explicit3193+ # boolean default (3-state).3194+ (None, UNSET, [], None),3195+ (UNSET, None, [], None),3196+ # Explicit ``None`` competing with explicit boolean. The decorator3197+ # order in this test puts ``--a`` last in ``params``, so the value3198+ # carried by ``default_a`` wins these "both explicit" ties under3199+ # last-wins.3200+ (None, True, [], None),3201+ (True, None, [], True),3202+ ],3203+)3204+def test_flag_group_unset_vs_none_vs_explicit(3205+ runner, default_a, default_b, args, expected3206+):3207+ """``UNSET`` as an explicit ``default`` must be indistinguishable from3208+ omitting ``default`` entirely, while ``None`` is a real explicit value.3209+ """3210+ a_kwargs = {"flag_value": True}3211+ if default_a is not UNSET:3212+ a_kwargs["default"] = default_a3213+ elif default_a is UNSET:3214+ # Pass UNSET explicitly to verify it's treated as absent. Skip when3215+ # the test wants the absent-keyword case (matches default behavior3216+ # because ``Parameter.__init__`` defaults ``default`` to ``UNSET``).3217+ a_kwargs["default"] = UNSET3218+3219+ b_kwargs = {"flag_value": False}3220+ if default_b is not UNSET:3221+ b_kwargs["default"] = default_b3222+ elif default_b is UNSET:3223+ b_kwargs["default"] = UNSET3224+3225+ @click.command()3226+ @click.option("--b", "state", **b_kwargs)3227+ @click.option("--a", "state", **a_kwargs)3228+ def cli(state):3229+ click.echo(repr(state), nl=False)3230+3231+ result = runner.invoke(cli, args)3232+ assert result.exit_code == 0, result.output3233+ assert result.output == repr(expected)3234+3235+3236+def test_flag_group_competition_duplicate_option_name(runner):3237+ """The same option name declared twice on the same command is a user3238+ error.3239+ """3240+3241+ @click.command()3242+ @click.option("--xyz", default="first")3243+ @click.option("--xyz", default="second")3244+ def cli(xyz):3245+ click.echo(repr(xyz), nl=False)3246+3247+ result = runner.invoke(cli, [])3248+ assert result.exit_code == 13249+ assert isinstance(result.exception, UserWarning)3250+ assert "used more than once" in str(result.exception)3251+3252+3253+@pytest.mark.parametrize(3254+ ("args", "expected"),3255+ [3256+ (["--with-xyz", "--with-xyz"], True),3257+ (["--without-xyz", "--without-xyz"], False),3258+ (["--with-xyz", "--without-xyz", "--with-xyz"], True),3259+ (["--without-xyz", "--with-xyz", "--without-xyz"], False),3260+ ],3261+)3262+def test_flag_group_competition_repeated_cmdline(runner, args, expected):3263+ """Duplicate flags passed in different order to the CLI."""3264+3265+ @click.command()3266+ @click.option("--without-xyz", "enable_xyz", flag_value=False)3267+ @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3268+ def cli(enable_xyz):3269+ click.echo(repr(enable_xyz), nl=False)3270+3271+ result = runner.invoke(cli, args)3272+ assert result.exit_code == 0, result.output3273+ assert result.output == repr(expected)3274+3275+3276+@pytest.mark.parametrize(3277+ ("opts", "args", "expected"),3278+ [3279+ pytest.param(3280+ [3281+ ("--a", {"flag_value": "a"}),3282+ ("--b", {"flag_value": "b"}),3283+ ("--c", {"flag_value": "c"}),3284+ ("--d", {"flag_value": "d"}),3285+ ],3286+ [],3287+ None,3288+ id="four-flags-no-defaults-resolves-to-none",3289+ ),3290+ pytest.param(3291+ [3292+ ("--a", {"flag_value": "a"}),3293+ ("--b", {"flag_value": "b", "default": "from-b"}),3294+ ("--c", {"flag_value": "c"}),3295+ ("--d", {"flag_value": "d"}),3296+ ],3297+ [],3298+ "from-b",3299+ id="four-flags-only-second-explicit-wins",3300+ ),3301+ pytest.param(3302+ [3303+ ("--a", {"flag_value": "a"}),3304+ ("--b", {"flag_value": "b", "default": "from-b"}),3305+ ("--c", {"flag_value": "c"}),3306+ ("--d", {"flag_value": "d", "default": "from-d"}),3307+ ],3308+ [],3309+ "from-d",3310+ id="four-flags-two-explicit-last-wins",3311+ ),3312+ pytest.param(3313+ [3314+ ("--a", {"flag_value": "a"}),3315+ ("--b", {"flag_value": "b"}),3316+ ("--c", {"flag_value": "c"}),3317+ ("--d", {"flag_value": "d"}),3318+ ],3319+ ["--c"],3320+ "c",3321+ id="four-flags-cmdline-beats-everything",3322+ ),3323+ ],3324+)3325+def test_flag_group_competition_four_flags(runner, opts, args, expected):3326+ """Arbitration rules applies to groups of any size."""3327+3328+ @click.command()3329+ def cli(case):3330+ click.echo(repr(case), nl=False)3331+3332+ for opt_name, opt_kwargs in opts:3333+ cli = click.option(opt_name, "case", **opt_kwargs)(cli)3334+3335+ result = runner.invoke(cli, args)3336+ assert result.exit_code == 0, result.output3337+ assert result.output == repr(expected)3338+3339+3340+@pytest.mark.parametrize(3341+ ("env", "default_map", "args", "expected"),3342+ [3343+ # ``auto_envvar_prefix`` produces an ``ENVIRONMENT`` source through a3344+ # different code path than an explicit ``envvar=`` keyword. It still3345+ # must beat any sibling default and be beaten by command-line input.3346+ pytest.param(3347+ {"AUTO_ENABLE_XYZ": "1"},3348+ None,3349+ [],3350+ True,3351+ id="auto-envvar-prefix-beats-default",3352+ ),3353+ pytest.param(3354+ {"AUTO_ENABLE_XYZ": "1"},3355+ None,3356+ ["--without-xyz"],3357+ False,3358+ id="auto-envvar-prefix-loses-to-cmdline",3359+ ),3360+ # ``Sentinel.UNSET`` in ``default_map`` must be skipped (#32243361+ # carve-out): the lookup falls through to the parameter default.3362+ # Inside a feature switch group, the explicit ``default=True`` on3363+ # ``--with-xyz`` then wins over the sibling's auto-``False``.3364+ pytest.param(3365+ {},3366+ {"enable_xyz": UNSET},3367+ [],3368+ True,3369+ id="unset-default-map-falls-through-to-explicit-default",3370+ ),3371+ pytest.param(3372+ {},3373+ {"enable_xyz": False},3374+ [],3375+ False,3376+ id="real-default-map-beats-explicit-default",3377+ ),3378+ ],3379+)3380+def test_flag_group_competition_envvar_prefix_and_unset_default_map(3381+ runner, monkeypatch, env, default_map, args, expected3382+):3383+ for name, value in env.items():3384+ monkeypatch.setenv(name, value)3385+3386+ @click.command()3387+ @click.option("--without-xyz", "enable_xyz", flag_value=False)3388+ @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3389+ def cli(enable_xyz):3390+ click.echo(repr(enable_xyz), nl=False)3391+3392+ invoke_kwargs = {"auto_envvar_prefix": "AUTO"}3393+ if default_map is not None:3394+ invoke_kwargs["default_map"] = default_map3395+3396+ result = runner.invoke(cli, args, **invoke_kwargs)3397+ assert result.exit_code == 0, result.output3398+ assert result.output == repr(expected)3399+3400+3401+@pytest.mark.parametrize(3402 ("flag_type", "args", "expect_output"),3403 [3404 (str, [], "Default\n"),3405 (str, ["--theflag"], "FlagValue\n"),36 unmodified linesmodified:CHANGES.rst+15 added
60 unmodified lines61 generic message. Built-in type messages mask the input value.62 :issue:`2809` :pr:`3256`63 - Mark additional built-in strings with ``gettext()`` to extend translation64 coverage. :pr:`2902`65+- Fix feature switch groups (several ``flag_value`` options sharing one66+ parameter name) silently dropping an explicit ``default`` when a sibling67+ option without an explicit default was declared first. Arbitration is now68+ source-aware: a more explicit :class:`ParameterSource` always wins, and69+ within ``ParameterSource.DEFAULT``, an option that received an explicit70+ ``default=`` keyword wins over a sibling whose default was auto-derived.71+ The 8.3.x first-wins fallback for remaining ties was reverted to the72+ pre-8.3.x last-wins fallback. :issue:`3403` :pr:`3404`73+- Fix missing space between option help text and the ``(DEPRECATED)``74+ label, and localize the option label so it matches the command label.75+ The label and the ``DeprecationWarning`` reason suffix are now produced76+ by shared helpers. :pr:`3423`77+- Document short option stacking (``-abc`` is parsed as ``-a -b -c``) and78+ clarify that multi-character short option names are not supported.79+ :issue:`2779` :pr:`3431`80 81 Version 8.3.382 -------------83 1364 unmodified lines