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

🐛 Ensure rich_markup_mode=None disables Rich formatting #859

Merged
merged 6 commits into from
Aug 24, 2024
Merged
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
2 changes: 1 addition & 1 deletion docs/tutorial/commands/help.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Then you can use more formatting in the docstrings and the `help` parameter for

/// info

By default, `rich_markup_mode` is `None`, which disables any rich text formatting.
By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed. In the latter case, you can set `rich_markup_mode` to `None` to disable rich text formatting.

///

Expand Down
40 changes: 40 additions & 0 deletions tests/test_rich_markup_mode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import typer
import typer.completion
from typer.testing import CliRunner

runner = CliRunner()
rounded = ["╭", "─", "┬", "╮", "│", "├", "┼", "┤", "╰", "┴", "╯"]


def test_rich_markup_mode_none():
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test currently fails on master, which is clearly a bug IMO.

app = typer.Typer(rich_markup_mode=None)

@app.command()
def main(arg: str):
"""Main function"""
print(f"Hello {arg}")

assert app.rich_markup_mode is None

result = runner.invoke(app, ["World"])
assert "Hello World" in result.stdout

result = runner.invoke(app, ["--help"])
assert all(c not in result.stdout for c in rounded)


def test_rich_markup_mode_rich():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test fails with 0.12.5 release

def test_rich_markup_mode_rich():
        app = typer.Typer(rich_markup_mode="rich")

        @app.command()
        def main(arg: str):
            """Main function"""
            print(f"Hello {arg}")

        assert app.rich_markup_mode == "rich"

        result = runner.invoke(app, ["World"])
        assert "Hello World" in result.stdout

        result = runner.invoke(app, ["--help"])
>       assert any(c in result.stdout for c in rounded)
E       assert False
E        +  where False = any(<generator object test_rich_markup_mode_rich.<locals>.<genexpr> at 0x7f931ae59d80>)

tests/test_rich_markup_mode.py:40: AssertionError

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @kraj, thanks for the comment. That's odd - I can't reproduce the test failure locally and the CI goes green with this change as well.

Could you please open a new discussion thread to look into this more, and provide us there with more information about your system setup and the failure you're seeing? 🙏

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I build a minimal image which just have a kernel+busybox+typer and its dependencies. So perhaps thats the difference, some implicit dependency coming in indirectly on full distributions like ubuntu, fedora etc in CI

app = typer.Typer(rich_markup_mode="rich")

@app.command()
def main(arg: str):
"""Main function"""
print(f"Hello {arg}")

assert app.rich_markup_mode == "rich"

result = runner.invoke(app, ["World"])
assert "Hello World" in result.stdout

result = runner.invoke(app, ["--help"])
assert any(c in result.stdout for c in rounded)
22 changes: 14 additions & 8 deletions typer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,18 @@
else:
from typing_extensions import Literal

MarkupMode = Literal["markdown", "rich", None]

try:
import rich

from . import rich_utils

DEFAULT_MARKUP_MODE: MarkupMode = "rich"

except ImportError: # pragma: no cover
rich = None # type: ignore

MarkupMode = Literal["markdown", "rich", None]
DEFAULT_MARKUP_MODE = None


# Copy from click.parser._split_opt
Expand Down Expand Up @@ -167,6 +170,7 @@ def _main(
complete_var: Optional[str] = None,
standalone_mode: bool = True,
windows_expand_args: bool = True,
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
**extra: Any,
) -> Any:
# Typer override, duplicated from click.main() to handle custom rich exceptions
Expand Down Expand Up @@ -208,7 +212,7 @@ def _main(
if not standalone_mode:
raise
# Typer override
if rich:
if rich and rich_markup_mode is not None:
rich_utils.rich_format_error(e)
else:
e.show()
Expand Down Expand Up @@ -238,7 +242,7 @@ def _main(
if not standalone_mode:
raise
# Typer override
if rich:
if rich and rich_markup_mode is not None:
rich_utils.rich_abort_error()
else:
click.echo(_("Aborted!"), file=sys.stderr)
Expand Down Expand Up @@ -614,7 +618,7 @@ def __init__(
hidden: bool = False,
deprecated: bool = False,
# Rich settings
rich_markup_mode: MarkupMode = None,
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
rich_help_panel: Union[str, None] = None,
) -> None:
super().__init__(
Expand Down Expand Up @@ -665,11 +669,12 @@ def main(
complete_var=complete_var,
standalone_mode=standalone_mode,
windows_expand_args=windows_expand_args,
rich_markup_mode=self.rich_markup_mode,
**extra,
)

def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
if not rich:
if not rich or self.rich_markup_mode is None:
return super().format_help(ctx, formatter)
return rich_utils.rich_format_help(
obj=self,
Expand All @@ -687,7 +692,7 @@ def __init__(
Union[Dict[str, click.Command], Sequence[click.Command]]
] = None,
# Rich settings
rich_markup_mode: MarkupMode = None,
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
rich_help_panel: Union[str, None] = None,
**attrs: Any,
) -> None:
Expand Down Expand Up @@ -727,11 +732,12 @@ def main(
complete_var=complete_var,
standalone_mode=standalone_mode,
windows_expand_args=windows_expand_args,
rich_markup_mode=self.rich_markup_mode,
**extra,
)

def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
if not rich:
if not rich or self.rich_markup_mode is None:
return super().format_help(ctx, formatter)
return rich_utils.rich_format_help(
obj=self,
Expand Down
11 changes: 9 additions & 2 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,14 @@
import click

from .completion import get_completion_inspect_parameters
from .core import MarkupMode, TyperArgument, TyperCommand, TyperGroup, TyperOption
from .core import (
DEFAULT_MARKUP_MODE,
MarkupMode,
TyperArgument,
TyperCommand,
TyperGroup,
TyperOption,
)
from .models import (
AnyType,
ArgumentInfo,
Expand Down Expand Up @@ -132,7 +139,7 @@ def __init__(
deprecated: bool = Default(False),
add_completion: bool = True,
# Rich settings
rich_markup_mode: MarkupMode = None,
rich_markup_mode: MarkupMode = Default(DEFAULT_MARKUP_MODE),
rich_help_panel: Union[str, None] = Default(None),
pretty_exceptions_enable: bool = True,
pretty_exceptions_show_locals: bool = True,
Expand Down
Loading