Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ Unreleased

- Fix handling of ``flag_value`` when ``is_flag=False`` to allow such options to be
used without an explicit value. :issue:`3084`
- Fix unknown-option error reporting for malformed multi-character options
with a single-character prefix so ``-dbgwrong`` reports ``-dbg`` instead of
``-d`` when ``-dbg`` exists. :issue:`2779`

Version 8.3.1
--------------
Expand Down
18 changes: 16 additions & 2 deletions src/click/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,8 +490,22 @@ def _process_opts(self, arg: str, state: _ParsingState) -> None:
# short option code and will instead raise the no option
# error.
if arg[:2] not in self._opt_prefixes:
self._match_short_opt(arg, state)
return
try:
self._match_short_opt(arg, state)
return
except NoSuchOption:
# Preserve the longest known option prefix in errors for
# multi-character options with a single-character prefix.
possible_opt = max(
(opt for opt in self._long_opt if arg.startswith(opt)),
key=len,
default=None,
)

if possible_opt is not None:
raise NoSuchOption(possible_opt, ctx=self.ctx) from None

raise

if not self.ignore_unknown_options:
raise
Expand Down
12 changes: 12 additions & 0 deletions tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,18 @@ def cli():
assert f"No such option: {unknown_flag}" in result.output


def test_unknown_option_for_multichar_short_option(runner):
@click.command()
@click.option("-dbg", is_flag=True)
def cli(dbg):
del dbg

result = runner.invoke(cli, ["-dbgwrong"])
assert result.exception
assert "No such option: -dbg" in result.output
assert "No such option: -d" not in result.output


@pytest.mark.parametrize(
("value", "expect"),
[
Expand Down
Loading