Coverage for typer / rich_utils.py: 100%
306 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1# Extracted and modified from https://github.com/ewels/rich-click
3import inspect 1abcdefghij
4import io 1abcdefghij
5from collections import defaultdict 1abcdefghij
6from collections.abc import Iterable 1abcdefghij
7from gettext import gettext as _ 1abcdefghij
8from os import getenv 1abcdefghij
9from typing import Any, Literal 1abcdefghij
11from rich import box 1abcdefghij
12from rich.align import Align 1abcdefghij
13from rich.columns import Columns 1abcdefghij
14from rich.console import Console, RenderableType, group 1abcdefghij
15from rich.emoji import Emoji 1abcdefghij
16from rich.highlighter import RegexHighlighter 1abcdefghij
17from rich.markdown import Markdown 1abcdefghij
18from rich.markup import escape 1abcdefghij
19from rich.padding import Padding 1abcdefghij
20from rich.panel import Panel 1abcdefghij
21from rich.table import Table 1abcdefghij
22from rich.text import Text 1abcdefghij
23from rich.theme import Theme 1abcdefghij
24from rich.traceback import Traceback 1abcdefghij
25from typer.models import DeveloperExceptionConfig 1abcdefghij
27from . import _click 1abcdefghij
28from .core import TyperArgument, TyperGroup, TyperOption 1abcdefghij
30# Default styles
31STYLE_OPTION = "bold cyan" 1abcdefghij
32STYLE_SWITCH = "bold green" 1abcdefghij
33STYLE_NEGATIVE_OPTION = "bold magenta" 1abcdefghij
34STYLE_NEGATIVE_SWITCH = "bold red" 1abcdefghij
35STYLE_TYPES = "bold yellow" 1abcdefghij
36STYLE_TYPES_SEPARATOR = "dim" 1abcdefghij
37STYLE_USAGE = "yellow" 1abcdefghij
38STYLE_USAGE_COMMAND = "bold" 1abcdefghij
39STYLE_DEPRECATED = "red" 1abcdefghij
40STYLE_DEPRECATED_COMMAND = "dim" 1abcdefghij
41STYLE_HELPTEXT_FIRST_LINE = "" 1abcdefghij
42STYLE_HELPTEXT = "dim" 1abcdefghij
43STYLE_OPTION_HELP = "" 1abcdefghij
44STYLE_OPTION_DEFAULT = "dim" 1abcdefghij
45STYLE_OPTION_ENVVAR = "dim yellow" 1abcdefghij
46STYLE_REQUIRED_SHORT = "red" 1abcdefghij
47STYLE_REQUIRED_LONG = "dim red" 1abcdefghij
48STYLE_OPTIONS_PANEL_BORDER = "dim" 1abcdefghij
49ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left" 1abcdefghij
50STYLE_OPTIONS_TABLE_SHOW_LINES = False 1abcdefghij
51STYLE_OPTIONS_TABLE_LEADING = 0 1abcdefghij
52STYLE_OPTIONS_TABLE_PAD_EDGE = False 1abcdefghij
53STYLE_OPTIONS_TABLE_PADDING = (0, 1) 1abcdefghij
54STYLE_OPTIONS_TABLE_BOX = "" 1abcdefghij
55STYLE_OPTIONS_TABLE_ROW_STYLES = None 1abcdefghij
56STYLE_OPTIONS_TABLE_BORDER_STYLE = None 1abcdefghij
57STYLE_COMMANDS_PANEL_BORDER = "dim" 1abcdefghij
58ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left" 1abcdefghij
59STYLE_COMMANDS_TABLE_SHOW_LINES = False 1abcdefghij
60STYLE_COMMANDS_TABLE_LEADING = 0 1abcdefghij
61STYLE_COMMANDS_TABLE_PAD_EDGE = False 1abcdefghij
62STYLE_COMMANDS_TABLE_PADDING = (0, 1) 1abcdefghij
63STYLE_COMMANDS_TABLE_BOX = "" 1abcdefghij
64STYLE_COMMANDS_TABLE_ROW_STYLES = None 1abcdefghij
65STYLE_COMMANDS_TABLE_BORDER_STYLE = None 1abcdefghij
66STYLE_COMMANDS_TABLE_FIRST_COLUMN = "bold cyan" 1abcdefghij
67STYLE_ERRORS_PANEL_BORDER = "red" 1abcdefghij
68ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left" 1abcdefghij
69STYLE_ERRORS_SUGGESTION = "dim" 1abcdefghij
70STYLE_ABORTED = "red" 1abcdefghij
71_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH") 1abcdefghij
72MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None 1abcdefghij
73COLOR_SYSTEM: Literal["auto", "standard", "256", "truecolor", "windows"] | None = ( 1abcdefghij
74 "auto" # Set to None to disable colors
75)
76_TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL") 1abcdefghij
77FORCE_TERMINAL = ( 1abcdefghij
78 True
79 if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS")
80 else None
81)
82if _TYPER_FORCE_DISABLE_TERMINAL: 1abcdefghij
83 FORCE_TERMINAL = False 1abcdefghij
85# Fixed strings
86DEPRECATED_STRING = _("(deprecated) ") 1abcdefghij
87DEFAULT_STRING = _("[default: {}]") 1abcdefghij
88ENVVAR_STRING = _("[env var: {}]") 1abcdefghij
89REQUIRED_SHORT_STRING = "*" 1abcdefghij
90REQUIRED_LONG_STRING = _("[required]") 1abcdefghij
91RANGE_STRING = " [{}]" 1abcdefghij
92ARGUMENTS_PANEL_TITLE = _("Arguments") 1abcdefghij
93OPTIONS_PANEL_TITLE = _("Options") 1abcdefghij
94COMMANDS_PANEL_TITLE = _("Commands") 1abcdefghij
95ERRORS_PANEL_TITLE = _("Error") 1abcdefghij
96ABORTED_TEXT = _("Aborted.") 1abcdefghij
97RICH_HELP = _("Try [blue]'{command_path} {help_option}'[/] for help.") 1abcdefghij
99MARKUP_MODE_MARKDOWN = "markdown" 1abcdefghij
100MARKUP_MODE_RICH = "rich" 1abcdefghij
101_RICH_HELP_PANEL_NAME = "rich_help_panel" 1abcdefghij
102ANSI_PREFIX = "\033[" 1abcdefghij
104MarkupModeStrict = Literal["markdown", "rich"] 1abcdefghij
107# Rich regex highlighter
108class OptionHighlighter(RegexHighlighter): 1abcdefghij
109 """Highlights our special options."""
111 highlights = [ 1abcdefghij
112 r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",
113 r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
114 r"(?P<types>\<[^\>]+\>)",
115 r"(?P<usage>Usage: )",
116 ]
119class NegativeOptionHighlighter(RegexHighlighter): 1abcdefghij
120 highlights = [ 1abcdefghij
121 r"(^|\W)(?P<negative_switch>\-\w+)(?![a-zA-Z0-9])",
122 r"(^|\W)(?P<negative_option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
123 ]
126# Highlighter to make [ | ] and <> dim
127class TypesHighlighter(RegexHighlighter): 1abcdefghij
128 highlights = [ 1abcdefghij
129 r"^(?P<types_sep>(\[|<))",
130 r"(?P<types_sep>\|)",
131 r"(?P<types_sep>(\]|>))(\.\.\.)?$",
132 ]
135highlighter = OptionHighlighter() 1abcdefghij
136negative_highlighter = NegativeOptionHighlighter() 1abcdefghij
137types_highlighter = TypesHighlighter() 1abcdefghij
140def _has_ansi_character(text: str) -> bool: 1abcdefghij
141 return ANSI_PREFIX in text 1abcdefghij
144def _get_rich_console(stderr: bool = False) -> Console: 1abcdefghij
145 return Console( 1abcdefghij
146 theme=Theme(
147 {
148 "option": STYLE_OPTION,
149 "switch": STYLE_SWITCH,
150 "negative_option": STYLE_NEGATIVE_OPTION,
151 "negative_switch": STYLE_NEGATIVE_SWITCH,
152 "types": STYLE_TYPES,
153 "types_sep": STYLE_TYPES_SEPARATOR,
154 "usage": STYLE_USAGE,
155 },
156 ),
157 highlighter=highlighter,
158 color_system=COLOR_SYSTEM,
159 force_terminal=FORCE_TERMINAL,
160 width=MAX_WIDTH,
161 stderr=stderr,
162 )
165def _make_rich_text( 1abcdefghij
166 *, text: str, style: str = "", markup_mode: MarkupModeStrict
167) -> Markdown | Text:
168 """Take a string, remove indentations, and return styled text.
170 If `markup_mode` is `"rich"`, the text is parsed for Rich markup strings.
171 If `markup_mode` is `"markdown"`, parse as Markdown.
172 """
173 # Remove indentations from input text
174 text = inspect.cleandoc(text) 1abcdefghij
175 if markup_mode == MARKUP_MODE_MARKDOWN: 1abcdefghij
176 text = Emoji.replace(text) 1abcdefghij
177 return Markdown(text, style=style) 1abcdefghij
178 else:
179 assert markup_mode == MARKUP_MODE_RICH 1abcdefghij
180 if _has_ansi_character(text): 1abcdefghij
181 return highlighter(Text.from_ansi(text, style=style)) 1abcdefghij
182 else:
183 return highlighter(Text.from_markup(text, style=style)) 1abcdefghij
186@group() 1abcdefghij
187def _get_help_text( 1abcdefghij
188 *,
189 obj: _click.Command | TyperGroup,
190 markup_mode: MarkupModeStrict,
191) -> Iterable[Markdown | Text]:
192 """Build primary help text for a click command or group.
194 Returns the prose help text for a command or group, rendered either as a
195 Rich Text object or as Markdown.
196 If the command is marked as deprecated, the deprecated string will be prepended.
197 """
198 # Prepend deprecated status
199 if obj.deprecated: 1abcdefghij
200 yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED) 1abcdefghij
202 # Fetch and dedent the help text
203 help_text = inspect.cleandoc(obj.help or "") 1abcdefghij
205 # Trim off anything that comes after \f on its own line
206 help_text = help_text.partition("\f")[0] 1abcdefghij
208 # Get the first paragraph
209 first_line, *remaining_paragraphs = help_text.split("\n\n") 1abcdefghij
211 # Remove single linebreaks
212 if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"): 1abcdefghij
213 first_line = first_line.replace("\n", " ") 1abcdefghij
214 yield _make_rich_text( 1abcdefghij
215 text=first_line.strip(),
216 style=STYLE_HELPTEXT_FIRST_LINE,
217 markup_mode=markup_mode,
218 )
220 # Get remaining lines, remove single line breaks and format as dim
221 if remaining_paragraphs: 1abcdefghij
222 # Add a newline inbetween the header and the remaining paragraphs
223 yield Text("") 1abcdefghij
224 remaining_lines = _fix_linebreaks(remaining_paragraphs, markup_mode) 1abcdefghij
226 yield _make_rich_text( 1abcdefghij
227 text=remaining_lines,
228 style=STYLE_HELPTEXT,
229 markup_mode=markup_mode,
230 )
233def _fix_linebreaks(paragraphs: list[str], markup_mode: MarkupModeStrict) -> str: 1abcdefghij
234 # Join with double linebreaks for markdown and Rich markup
235 return "\n\n".join(paragraphs) 1abcdefghij
238def _get_parameter_help( 1abcdefghij
239 *,
240 param: TyperOption | TyperArgument | _click.Parameter,
241 ctx: _click.Context,
242 markup_mode: MarkupModeStrict,
243) -> Columns:
244 """Build primary help text for a click option or argument.
246 Returns the prose help text for an option or argument, rendered either
247 as a Rich Text object or as Markdown.
248 Additional elements are appended to show the default and required status if
249 applicable.
250 """
251 # import here to avoid cyclic imports
252 from .core import TyperArgument, TyperOption 1abcdefghij
254 items: list[Text | Markdown] = [] 1abcdefghij
256 # Get the environment variable first
258 envvar = getattr(param, "envvar", None) 1abcdefghij
259 var_str = "" 1abcdefghij
260 # https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726
261 if envvar is None: 1abcdefghij
262 if ( 1a
263 getattr(param, "allow_from_autoenv", None)
264 and getattr(ctx, "auto_envvar_prefix", None) is not None
265 and param.name
266 ):
267 envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}" 1abcdefghij
268 if envvar is not None: 1abcdefghij
269 var_str = ( 1abcdefghij
270 envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar)
271 )
273 # Main help text
274 help_value: str | None = getattr(param, "help", None) 1abcdefghij
275 if help_value: 1abcdefghij
276 paragraphs = help_value.split("\n\n") 1abcdefghij
277 # Remove single linebreaks
278 if markup_mode != MARKUP_MODE_MARKDOWN: 1abcdefghij
279 paragraphs = [ 1abcdefghij
280 x.replace("\n", " ").strip()
281 if not x.startswith("\b")
282 else "{}\n".format(x.strip("\b\n"))
283 for x in paragraphs
284 ]
285 items.append( 1abcdefghij
286 _make_rich_text(
287 text="\n".join(paragraphs).strip(),
288 style=STYLE_OPTION_HELP,
289 markup_mode=markup_mode,
290 )
291 )
293 # Environment variable AFTER help text
294 if envvar and getattr(param, "show_envvar", None): 1abcdefghij
295 items.append(Text(ENVVAR_STRING.format(var_str), style=STYLE_OPTION_ENVVAR)) 1abcdefghij
297 # Default value
298 # This uses Typer's specific param._get_default_string
299 if isinstance(param, (TyperOption, TyperArgument)): 1abcdefghij
300 default_value = param._extract_default_help_str(ctx=ctx) 1abcdefghij
301 show_default_is_str = isinstance(param.show_default, str) 1abcdefghij
302 if show_default_is_str or ( 1abcdefghij
303 default_value is not None and (param.show_default or ctx.show_default)
304 ):
305 default_str = param._get_default_string( 1abcdefghij
306 ctx=ctx,
307 show_default_is_str=show_default_is_str,
308 default_value=default_value,
309 )
310 if default_str: 1abcdefghij
311 items.append( 1abcdefghij
312 Text(
313 DEFAULT_STRING.format(default_str),
314 style=STYLE_OPTION_DEFAULT,
315 )
316 )
318 # Required?
319 if param.required: 1abcdefghij
320 items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG)) 1abcdefghij
322 # Use Columns - this allows us to group different renderable types
323 # (Text, Markdown) onto a single line.
324 return Columns(items) 1abcdefghij
327def _make_command_help( 1abcdefghij
328 *,
329 help_text: str,
330 markup_mode: MarkupModeStrict,
331) -> Text | Markdown:
332 """Build cli help text for a click group command.
334 That is, when calling help on groups with multiple subcommands
335 (not the main help text when calling the subcommand help).
337 Returns the first paragraph of help text for a command, rendered either as a
338 Rich Text object or as Markdown.
339 Ignores single newlines as paragraph markers, looks for double only.
340 """
341 paragraphs = inspect.cleandoc(help_text).split("\n\n") 1abcdefghij
342 # Remove single linebreaks
343 if markup_mode != MARKUP_MODE_RICH and not paragraphs[0].startswith("\b"): 1abcdefghij
344 paragraphs[0] = paragraphs[0].replace("\n", " ") 1abcdefghij
345 elif paragraphs[0].startswith("\b"): 1abcdefghij
346 paragraphs[0] = paragraphs[0].replace("\b\n", "") 1abcdefghij
347 return _make_rich_text( 1abcdefghij
348 text=paragraphs[0].strip(),
349 style=STYLE_OPTION_HELP,
350 markup_mode=markup_mode,
351 )
354def _print_options_panel( 1abcdefghij
355 *,
356 name: str,
357 params: list[TyperOption] | list[TyperArgument],
358 ctx: _click.Context,
359 markup_mode: MarkupModeStrict,
360 console: Console,
361) -> None:
362 options_rows: list[list[RenderableType]] = [] 1abcdefghij
363 required_rows: list[str | Text] = [] 1abcdefghij
364 for param in params: 1abcdefghij
365 # Short and long form
366 opt_long_strs = [] 1abcdefghij
367 opt_short_strs = [] 1abcdefghij
368 secondary_opt_long_strs = [] 1abcdefghij
369 secondary_opt_short_strs = [] 1abcdefghij
371 # Argument name label and option type display use separate APIs.
372 display_name: str | None = None 1abcdefghij
373 if isinstance(param, TyperArgument): 1abcdefghij
374 display_name = param.display_name_raw 1abcdefghij
375 if param.metavar is None and param.nargs != 1: 1abcdefghij
376 display_name += "..." 1abcdefghij
378 for opt_str in param.opts: 1abcdefghij
379 if "--" in opt_str: 1abcdefghij
380 opt_long_strs.append(opt_str) 1abcdefghij
381 elif display_name: 1abcdefghij
382 opt_short_strs.append(display_name) 1abcdefghij
383 else:
384 opt_short_strs.append(opt_str) 1abcdefghij
385 for opt_str in param.secondary_opts: 1abcdefghij
386 if "--" in opt_str: 1abcdefghij
387 secondary_opt_long_strs.append(opt_str) 1abcdefghij
388 elif display_name: # pragma: no cover 1abcdefghij
389 secondary_opt_short_strs.append(display_name)
390 else:
391 secondary_opt_short_strs.append(opt_str) 1abcdefghij
393 # Column for recording the type
394 types_data = Text(style=STYLE_TYPES, overflow="fold") 1abcdefghij
395 display_type_str = param.display_type_rich(ctx=ctx) 1abcdefghij
396 if display_type_str is not None: 1abcdefghij
397 types_data.append(display_type_str) 1abcdefghij
399 range_str = param._get_number_range_help_str() 1abcdefghij
400 if range_str: 1abcdefghij
401 types_data.append(RANGE_STRING.format(range_str)) 1abcdefghij
403 # Required asterisk
404 required: str | Text = "" 1abcdefghij
405 if param.required: 1abcdefghij
406 required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT) 1abcdefghij
408 required_rows.append(required) 1abcdefghij
409 options_rows.append( 1abcdefghij
410 [
411 highlighter(",".join(opt_long_strs)),
412 highlighter(",".join(opt_short_strs)),
413 negative_highlighter(",".join(secondary_opt_long_strs)),
414 negative_highlighter(",".join(secondary_opt_short_strs)),
415 types_highlighter(types_data),
416 _get_parameter_help(
417 param=param,
418 ctx=ctx,
419 markup_mode=markup_mode,
420 ),
421 ]
422 )
423 rows_with_required: list[list[RenderableType]] = [] 1abcdefghij
424 if any(required_rows): 1abcdefghij
425 for required, row in zip(required_rows, options_rows, strict=True): 1abcdefghij
426 rows_with_required.append([required, *row]) 1abcdefghij
427 else:
428 rows_with_required = options_rows 1abcdefghij
429 if options_rows: 1abcdefghij
430 t_styles: dict[str, Any] = { 1abcdefghij
431 "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,
432 "leading": STYLE_OPTIONS_TABLE_LEADING,
433 "box": STYLE_OPTIONS_TABLE_BOX,
434 "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,
435 "row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES,
436 "pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE,
437 "padding": STYLE_OPTIONS_TABLE_PADDING,
438 }
439 box_style = getattr(box, t_styles.pop("box"), None) 1abcdefghij
441 options_table = Table( 1abcdefghij
442 highlight=True,
443 show_header=False,
444 expand=True,
445 box=box_style,
446 **t_styles,
447 )
448 for row in rows_with_required: 1abcdefghij
449 options_table.add_row(*row) 1abcdefghij
450 console.print( 1abcdefghij
451 Panel(
452 options_table,
453 border_style=STYLE_OPTIONS_PANEL_BORDER,
454 title=name,
455 title_align=ALIGN_OPTIONS_PANEL,
456 )
457 )
460def _print_commands_panel( 1abcdefghij
461 *,
462 name: str,
463 commands: list[_click.Command],
464 markup_mode: MarkupModeStrict,
465 console: Console,
466 cmd_len: int,
467) -> None:
468 t_styles: dict[str, Any] = { 1abcdefghij
469 "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,
470 "leading": STYLE_COMMANDS_TABLE_LEADING,
471 "box": STYLE_COMMANDS_TABLE_BOX,
472 "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,
473 "row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES,
474 "pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE,
475 "padding": STYLE_COMMANDS_TABLE_PADDING,
476 }
477 box_style = getattr(box, t_styles.pop("box"), None) 1abcdefghij
479 commands_table = Table( 1abcdefghij
480 highlight=False,
481 show_header=False,
482 expand=True,
483 box=box_style,
484 **t_styles,
485 )
486 # Define formatting in first column, as commands don't match highlighter
487 # regex
488 commands_table.add_column( 1abcdefghij
489 style=STYLE_COMMANDS_TABLE_FIRST_COLUMN,
490 no_wrap=True,
491 width=cmd_len,
492 )
494 # A big ratio makes the description column be greedy and take all the space
495 # available instead of allowing the command column to grow and misalign with
496 # other panels.
497 commands_table.add_column("Description", justify="left", no_wrap=False, ratio=10) 1abcdefghij
498 rows: list[list[RenderableType | None]] = [] 1abcdefghij
499 deprecated_rows: list[RenderableType | None] = [] 1abcdefghij
500 for command in commands: 1abcdefghij
501 helptext = command.short_help or command.help or "" 1abcdefghij
502 command_name = command.name or "" 1abcdefghij
503 if command.deprecated: 1abcdefghij
504 command_name_text = Text(f"{command_name}", style=STYLE_DEPRECATED_COMMAND) 1abcdefghij
505 deprecated_rows.append(Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)) 1abcdefghij
506 else:
507 command_name_text = Text(command_name) 1abcdefghij
508 deprecated_rows.append(None) 1abcdefghij
509 rows.append( 1abcdefghij
510 [
511 command_name_text,
512 _make_command_help(
513 help_text=helptext,
514 markup_mode=markup_mode,
515 ),
516 ]
517 )
518 rows_with_deprecated = rows 1abcdefghij
519 if any(deprecated_rows): 1abcdefghij
520 rows_with_deprecated = [] 1abcdefghij
521 for row, deprecated_text in zip(rows, deprecated_rows, strict=True): 1abcdefghij
522 rows_with_deprecated.append([*row, deprecated_text]) 1abcdefghij
523 for row in rows_with_deprecated: 1abcdefghij
524 commands_table.add_row(*row) 1abcdefghij
525 if commands_table.row_count: 1abcdefghij
526 console.print( 1abcdefghij
527 Panel(
528 commands_table,
529 border_style=STYLE_COMMANDS_PANEL_BORDER,
530 title=name,
531 title_align=ALIGN_COMMANDS_PANEL,
532 )
533 )
536def rich_format_help( 1abcdefghij
537 *,
538 obj: _click.Command | TyperGroup,
539 ctx: _click.Context,
540 markup_mode: MarkupModeStrict,
541) -> None:
542 """Print nicely formatted help text using rich.
544 Based on original code from rich-cli, by @willmcgugan.
545 https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236
547 Replacement for the click function format_help().
548 Takes a command or group and builds the help text output.
549 """
550 console = _get_rich_console() 1abcdefghij
552 # Print usage
553 console.print( 1abcdefghij
554 Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND
555 )
557 # Print command / group help if we have some
558 if obj.help: 1abcdefghij
559 # Print with some padding
560 console.print( 1abcdefghij
561 Padding(
562 Align(
563 _get_help_text(
564 obj=obj,
565 markup_mode=markup_mode,
566 ),
567 pad=False,
568 ),
569 (0, 1, 1, 1),
570 )
571 )
572 panel_to_arguments: defaultdict[str, list[TyperArgument]] = defaultdict(list) 1abcdefghij
573 panel_to_options: defaultdict[str, list[TyperOption]] = defaultdict(list) 1abcdefghij
574 for param in obj.get_params(ctx): 1abcdefghij
575 # Skip if option is hidden
576 if getattr(param, "hidden", False): 1abcdefghij
577 continue 1abcdefghij
578 if isinstance(param, TyperArgument): 1abcdefghij
579 panel_name = ( 1abcdefghij
580 getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE
581 )
582 panel_to_arguments[panel_name].append(param) 1abcdefghij
583 elif isinstance(param, TyperOption): 1abcdefghij
584 panel_name = ( 1abcdefghij
585 getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE
586 )
587 panel_to_options[panel_name].append(param) 1abcdefghij
588 default_arguments = panel_to_arguments.get(ARGUMENTS_PANEL_TITLE, []) 1abcdefghij
589 _print_options_panel( 1abcdefghij
590 name=ARGUMENTS_PANEL_TITLE,
591 params=default_arguments,
592 ctx=ctx,
593 markup_mode=markup_mode,
594 console=console,
595 )
596 for panel_name, arguments in panel_to_arguments.items(): 1abcdefghij
597 if panel_name == ARGUMENTS_PANEL_TITLE: 1abcdefghij
598 # Already printed above
599 continue 1abcdefghij
600 _print_options_panel( 1abcdefghij
601 name=panel_name,
602 params=arguments,
603 ctx=ctx,
604 markup_mode=markup_mode,
605 console=console,
606 )
607 default_options = panel_to_options.get(OPTIONS_PANEL_TITLE, []) 1abcdefghij
608 _print_options_panel( 1abcdefghij
609 name=OPTIONS_PANEL_TITLE,
610 params=default_options,
611 ctx=ctx,
612 markup_mode=markup_mode,
613 console=console,
614 )
615 for panel_name, options in panel_to_options.items(): 1abcdefghij
616 if panel_name == OPTIONS_PANEL_TITLE: 1abcdefghij
617 # Already printed above
618 continue 1abcdefghij
619 _print_options_panel( 1abcdefghij
620 name=panel_name,
621 params=options,
622 ctx=ctx,
623 markup_mode=markup_mode,
624 console=console,
625 )
627 if isinstance(obj, TyperGroup): 1abcdefghij
628 panel_to_commands: defaultdict[str, list[_click.Command]] = defaultdict(list) 1abcdefghij
629 for command_name in obj.list_commands(ctx): 1abcdefghij
630 command = obj.get_command(ctx, command_name) 1abcdefghij
631 if command and not command.hidden: 1abcdefghij
632 panel_name = ( 1abcdefghij
633 getattr(command, _RICH_HELP_PANEL_NAME, None)
634 or COMMANDS_PANEL_TITLE
635 )
636 panel_to_commands[panel_name].append(command) 1abcdefghij
638 # Identify the longest command name in all panels
639 max_cmd_len = max( 1abcdefghij
640 [
641 len(command.name or "")
642 for commands in panel_to_commands.values()
643 for command in commands
644 ],
645 default=0,
646 )
648 # Print each command group panel
649 default_commands = panel_to_commands.get(COMMANDS_PANEL_TITLE, []) 1abcdefghij
650 _print_commands_panel( 1abcdefghij
651 name=COMMANDS_PANEL_TITLE,
652 commands=default_commands,
653 markup_mode=markup_mode,
654 console=console,
655 cmd_len=max_cmd_len,
656 )
657 for panel_name, commands in panel_to_commands.items(): 1abcdefghij
658 if panel_name == COMMANDS_PANEL_TITLE: 1abcdefghij
659 # Already printed above
660 continue 1abcdefghij
661 _print_commands_panel( 1abcdefghij
662 name=panel_name,
663 commands=commands,
664 markup_mode=markup_mode,
665 console=console,
666 cmd_len=max_cmd_len,
667 )
669 # Epilogue if we have it
670 if obj.epilog: 1abcdefghij
671 # Remove single linebreaks, replace double with single
672 lines = obj.epilog.split("\n\n") 1abcdefghij
673 epilogue = _fix_linebreaks(lines, markup_mode) 1abcdefghij
674 epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode) 1abcdefghij
675 console.print(Padding(Align(epilogue_text, pad=False), 1)) 1abcdefghij
678def rich_format_error(self: _click.ClickException) -> None: 1abcdefghij
679 """Print richly formatted click errors.
681 Called by custom exception handler to print richly formatted click errors.
682 Mimics original _click.ClickException.echo() function but with rich formatting.
683 """
684 # Don't do anything when it's a NoArgsIsHelpError (without importing it, cf. #1278)
685 if self.__class__.__name__ == "NoArgsIsHelpError": 1abcdefghij
686 return 1abcdefghij
688 console = _get_rich_console(stderr=True) 1abcdefghij
689 ctx: _click.Context | None = getattr(self, "ctx", None) 1abcdefghij
690 if ctx is not None: 1abcdefghij
691 # make sure that Rich won't treat [path] as markup
692 console.print(highlighter(ctx.get_usage()), style=STYLE_USAGE_COMMAND) 1abcdefghij
694 if ctx is not None and ctx.command.get_help_option(ctx) is not None: 1abcdefghij
695 console.print( 1abcdefghij
696 RICH_HELP.format(
697 command_path=escape(ctx.command_path),
698 help_option=ctx.help_option_names[0],
699 ),
700 style=STYLE_ERRORS_SUGGESTION,
701 )
703 console.print( 1abcdefghij
704 Panel(
705 highlighter(self.format_message()),
706 border_style=STYLE_ERRORS_PANEL_BORDER,
707 title=ERRORS_PANEL_TITLE,
708 title_align=ALIGN_ERRORS_PANEL,
709 )
710 )
713def rich_abort_error() -> None: 1abcdefghij
714 """Print richly formatted abort error."""
715 console = _get_rich_console(stderr=True) 1abcdefghij
716 console.print(ABORTED_TEXT, style=STYLE_ABORTED) 1abcdefghij
719def escape_before_html_export(input_text: str) -> str: 1abcdefghij
720 """Ensure that the input string can be used for HTML export."""
721 return escape(input_text).strip() 1abcdefghij
724def rich_to_html(input_text: str) -> str: 1abcdefghij
725 """Print the HTML version of a rich-formatted input string.
727 This function does not provide a full HTML page, but can be used to insert
728 HTML-formatted text spans into a markdown file.
729 """
730 console = Console(record=True, highlight=False, file=io.StringIO()) 1abcdefghij
732 console.print(input_text, overflow="ignore", crop=False) 1abcdefghij
734 return console.export_html(inline_styles=True, code_format="{code}").strip() 1abcdefghij
737def rich_render_text(text: str) -> str: 1abcdefghij
738 """Remove rich tags and render a pure text representation"""
739 console = _get_rich_console() 1abcdefghij
740 return "".join(segment.text for segment in console.render(text)).rstrip("\n") 1abcdefghij
743def get_traceback( 1abcdefghij
744 exc: BaseException,
745 exception_config: DeveloperExceptionConfig,
746 internal_dir_names: list[str],
747) -> Traceback:
748 rich_tb = Traceback.from_exception( 1abcdefghij
749 type(exc),
750 exc,
751 exc.__traceback__,
752 show_locals=exception_config.pretty_exceptions_show_locals,
753 suppress=internal_dir_names,
754 width=MAX_WIDTH,
755 code_width=None,
756 word_wrap=True,
757 )
758 return rich_tb 1abcdefghij