Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix duplicate options #74

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/rich_cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ class OptionHighlighter(RegexHighlighter):
help="Display last [b]LINES[/] of the file (requires --syntax or --csv).",
)
@click.option(
"--emoji", "-j", is_flag=True, help="Enable emoji code. [dim]e.g. :sparkle:"
"--emoji", "-J", is_flag=True, help="Enable emoji code. [dim]e.g. :sparkle:"
)
@click.option("--left", "-l", is_flag=True, help="Align to left.")
@click.option("--right", "-r", is_flag=True, help="Align to right.")
Expand Down
Empty file added tests/__init.py__
Empty file.
41 changes: 41 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import click
from click import Command
from click.decorators import FC, Parameter
from click.testing import CliRunner


class DuplicateOptionsError(ValueError):
pass


def test_duplicate_option_flags_raises_exception(monkeypatch):
"""Create a test that will monkeypatch the click.option decorators
so that they fail noisily when options are duplicated for a command
"""

def _param_memo_safe(f: FC, param: Parameter) -> None:
if isinstance(f, Command):
f.params.append(param)
else:
if not hasattr(f, "__click_params__"):
f.__click_params__ = [] # type: ignore
else:
for opt in param.opts:
for preexisting_param in f.__click_params__:
if opt in preexisting_param.opts:
raise DuplicateOptionsError(
"Duplicate option added to command."
+ " The following option appears more than once:\n"
+ f"{opt} (used for {param.human_readable_name}"
+ f" and {preexisting_param.human_readable_name})"
)

f.__click_params__.append(param) # type: ignore

monkeypatch.setattr(click.decorators, "_param_memo", _param_memo_safe)

# import here (after monkeypatch) because decorators are run on import
from rich_cli.__main__ import main

runner = CliRunner()
runner.invoke(main)