Debian Codegraph @

src/rich_click/rich_click.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import inspect
2 import re
3 from os import getenv
4 from typing import Dict, List, Optional, Union
5
6 import click
7 import rich.markdown
8 from rich import box
9 from rich.align import Align
10 from rich.columns import Columns
11 from rich.console import Console
12 from rich.emoji import Emoji
13 from rich.highlighter import RegexHighlighter
14 from rich.markdown import Markdown
15 from rich.padding import Padding
16 from rich.panel import Panel
17 from rich.table import Table
18 from rich.text import Text
19 from rich.theme import Theme
20
21 # Support rich <= 10.6.0
22 try:
23 from rich.console import group
24 except ImportError:
25 from rich.console import render_group as group
26
27 # Default styles
28 STYLE_OPTION = "bold cyan"
29 STYLE_ARGUMENT = "bold cyan"
30 STYLE_SWITCH = "bold green"
31 STYLE_METAVAR = "bold yellow"
32 STYLE_METAVAR_APPEND = "dim yellow"
33 STYLE_METAVAR_SEPARATOR = "dim"
34 STYLE_HEADER_TEXT = ""
35 STYLE_FOOTER_TEXT = ""
36 STYLE_USAGE = "yellow"
37 STYLE_USAGE_COMMAND = "bold"
38 STYLE_DEPRECATED = "red"
39 STYLE_HELPTEXT_FIRST_LINE = ""
40 STYLE_HELPTEXT = "dim"
41 STYLE_OPTION_HELP = ""
42 STYLE_OPTION_DEFAULT = "dim"
43 STYLE_OPTION_ENVVAR = "dim yellow"
44 STYLE_REQUIRED_SHORT = "red"
45 STYLE_REQUIRED_LONG = "dim red"
46 STYLE_OPTIONS_PANEL_BORDER = "dim"
47 ALIGN_OPTIONS_PANEL = "left"
48 STYLE_OPTIONS_TABLE_SHOW_LINES = False
49 STYLE_OPTIONS_TABLE_LEADING = 0
50 STYLE_OPTIONS_TABLE_PAD_EDGE = False
51 STYLE_OPTIONS_TABLE_PADDING = (0, 1)
52 STYLE_OPTIONS_TABLE_BOX = ""
53 STYLE_OPTIONS_TABLE_ROW_STYLES = None
54 STYLE_OPTIONS_TABLE_BORDER_STYLE = None
55 STYLE_COMMANDS_PANEL_BORDER = "dim"
56 ALIGN_COMMANDS_PANEL = "left"
57 STYLE_COMMANDS_TABLE_SHOW_LINES = False
58 STYLE_COMMANDS_TABLE_LEADING = 0
59 STYLE_COMMANDS_TABLE_PAD_EDGE = False
60 STYLE_COMMANDS_TABLE_PADDING = (0, 1)
61 STYLE_COMMANDS_TABLE_BOX = ""
62 STYLE_COMMANDS_TABLE_ROW_STYLES = None
63 STYLE_COMMANDS_TABLE_BORDER_STYLE = None
64 STYLE_ERRORS_PANEL_BORDER = "red"
65 ALIGN_ERRORS_PANEL = "left"
66 STYLE_ERRORS_SUGGESTION = "dim"
67 STYLE_ABORTED = "red"
68 MAX_WIDTH = int(getenv("TERMINAL_WIDTH")) if getenv("TERMINAL_WIDTH") else None # type: ignore
69 COLOR_SYSTEM = "auto" # Set to None to disable colors
70 FORCE_TERMINAL = True if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS") else None
71
72 # Fixed strings
73 HEADER_TEXT: Optional[str] = None
74 FOOTER_TEXT: Optional[str] = None
75 DEPRECATED_STRING = "(Deprecated) "
76 DEFAULT_STRING = "[default: {}]"
77 ENVVAR_STRING = "[env var: {}]"
78 REQUIRED_SHORT_STRING = "*"
79 REQUIRED_LONG_STRING = "[required]"
80 RANGE_STRING = " [{}]"
81 APPEND_METAVARS_HELP_STRING = "({})"
82 ARGUMENTS_PANEL_TITLE = "Arguments"
83 OPTIONS_PANEL_TITLE = "Options"
84 COMMANDS_PANEL_TITLE = "Commands"
85 ERRORS_PANEL_TITLE = "Error"
86 ERRORS_SUGGESTION: Optional[str] = None # Default: Try 'cmd -h' for help. Set to False to disable.
87 ERRORS_EPILOGUE: Optional[str] = None
88 ABORTED_TEXT = "Aborted."
89
90 # Behaviours
91 SHOW_ARGUMENTS = False # Show positional arguments
92 SHOW_METAVARS_COLUMN = True # Show a column with the option metavar (eg. INTEGER)
93 APPEND_METAVARS_HELP = False # Append metavar (eg. [TEXT]) after the help text
94 GROUP_ARGUMENTS_OPTIONS = False # Show arguments with options instead of in own panel
95 OPTION_ENVVAR_FIRST = False # Show env vars before option help text instead of avert
96 USE_MARKDOWN = False # Parse help strings as markdown
97 USE_MARKDOWN_EMOJI = True # Parse emoji codes in markdown :smile:
98 USE_RICH_MARKUP = False # Parse help strings for rich markup (eg. [red]my text[/])
99 # Define sorted groups of panels to display subcommands
100 COMMAND_GROUPS: Dict[str, List[Dict[str, Union[str, List[str]]]]] = {}
101 # Define sorted groups of panels to display options and arguments
102 OPTION_GROUPS: Dict[str, List[Dict[str, Union[str, List[str]]]]] = {}
103 USE_CLICK_SHORT_HELP = False # Use click's default function to truncate help text
104
105
106 # Rich regex highlighter
107 class OptionHighlighter(RegexHighlighter):
108 """Highlights our special options."""
109
110 highlights = [
111 r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",
112 r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
113 r"(^|\W)(?P<argument>[A-Z0-9\_]+)(?![_a-zA-Z0-9])",
114 r"(?P<metavar>\<[^\>]+\>)",
115 r"(?P<usage>Usage: )",
116 ]
117
118
119 highlighter = OptionHighlighter()
120
121
122 def _get_rich_console() -> Console:
123 return Console(
124 theme=Theme(
125 {
126 "option": STYLE_OPTION,
127 "argument": STYLE_ARGUMENT,
128 "switch": STYLE_SWITCH,
129 "metavar": STYLE_METAVAR,
130 "metavar_sep": STYLE_METAVAR_SEPARATOR,
131 "usage": STYLE_USAGE,
132 }
133 ),
134 highlighter=highlighter,
135 color_system=COLOR_SYSTEM,
136 force_terminal=FORCE_TERMINAL,
137 width=MAX_WIDTH,
138 )
139
140
141 def _make_rich_rext(text: str, style: str = "") -> Union[rich.markdown.Markdown, rich.text.Text]:
142 """Take a string, remove indentations, and return styled text.
143
144 By default, return the text as a Rich Text with the request style.
145 If USE_RICH_MARKUP is True, also parse the text for Rich markup strings.
146 If USE_MARKDOWN is True, parse as Markdown.
147
148 Only one of USE_MARKDOWN or USE_RICH_MARKUP can be True.
149 If both are True, USE_MARKDOWN takes precedence.
150
151 Args:
152 text (str): Text to style
153 style (str): Rich style to apply
154
155 Returns:
156 MarkdownElement or Text: Styled text object
157 """
158 # Remove indentations from input text
159 text = inspect.cleandoc(text)
160 if USE_MARKDOWN:
161 if USE_MARKDOWN_EMOJI:
162 text = Emoji.replace(text)
163 return Markdown(text, style=style)
164 if USE_RICH_MARKUP:
165 return highlighter(Text.from_markup(text, style=style))
166 else:
167 return highlighter(Text(text, style=style))
168
169
170 @group()
171 def _get_help_text(obj: Union[click.Command, click.Group]) -> Union[rich.markdown.Markdown, rich.text.Text]:
172 """Build primary help text for a click command or group.
173
174 Returns the prose help text for a command or group, rendered either as a
175 Rich Text object or as Markdown.
176 If the command is marked as depreciated, the depreciated string will be prepended.
177
178 Args:
179 obj (click.Command or click.Group): Command or group to build help text for
180
181 Yields:
182 Text or Markdown: Multiple styled objects (depreciated, usage)
183 """
184 # Prepend deprecated status
185 if obj.deprecated:
186 yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)
187
188 # Fetch and dedent the help text
189 help_text = inspect.cleandoc(obj.help)
190
191 # Trim off anything that comes after \f on its own line
192 help_text = help_text.partition("\f")[0]
193
194 # Get the first paragraph
195 first_line = help_text.split("\n\n")[0]
196 # Remove single linebreaks
197 if not USE_MARKDOWN and not first_line.startswith("\b"):
198 first_line = first_line.replace("\n", " ")
199 yield _make_rich_rext(first_line.strip(), STYLE_HELPTEXT_FIRST_LINE)
200
201 # Get remaining lines, remove single line breaks and format as dim
202 remaining_paragraphs = help_text.split("\n\n")[1:]
203 if len(remaining_paragraphs) > 0:
204 if not USE_MARKDOWN:
205 # Remove single linebreaks
206 remaining_paragraphs = [
207 x.replace("\n", " ").strip() if not x.startswith("\b") else "{}\n".format(x.strip("\b\n"))
208 for x in remaining_paragraphs
209 ]
210 # Join back together
211 remaining_lines = "\n".join(remaining_paragraphs)
212 else:
213 # Join with double linebreaks if markdown
214 remaining_lines = "\n\n".join(remaining_paragraphs)
215
216 yield _make_rich_rext(remaining_lines, STYLE_HELPTEXT)
217
218
219 def _get_parameter_help(param: Union[click.Option, click.Argument], ctx: click.Context) -> rich.columns.Columns:
220 """Build primary help text for a click option or argument.
221
222 Returns the prose help text for an option or argument, rendered either
223 as a Rich Text object or as Markdown.
224 Additional elements are appended to show the default and required status if applicable.
225
226 Args:
227 param (click.Option or click.Argument): Option or argument to build help text for
228 ctx (click.Context): Click Context object
229
230 Returns:
231 Columns: A columns element with multiple styled objects (help, default, required)
232 """
233 items = []
234
235 # Get the environment variable first
236 envvar = getattr(param, "envvar", None)
237 # https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726
238 if envvar is None:
239 if (
240 getattr(param, "allow_from_autoenv", None)
241 and getattr(ctx, "auto_envvar_prefix", None) is not None
242 and param.name is not None
243 ):
244 envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}"
245 if envvar is not None:
246 envvar = ", ".join(param.envvar) if type(envvar) is list else envvar
247
248 # Environment variable BEFORE help text
249 if getattr(param, "show_envvar", None) and OPTION_ENVVAR_FIRST and envvar is not None:
250 items.append(Text(ENVVAR_STRING.format(envvar), style=STYLE_OPTION_ENVVAR))
251
252 # Main help text
253 if getattr(param, "help", None):
254 paragraphs = param.help.split("\n\n")
255 # Remove single linebreaks
256 if not USE_MARKDOWN:
257 paragraphs = [
258 x.replace("\n", " ").strip() if not x.startswith("\b") else "{}\n".format(x.strip("\b\n"))
259 for x in paragraphs
260 ]
261 items.append(_make_rich_rext("\n".join(paragraphs).strip(), STYLE_OPTION_HELP))
262
263 # Append metavar if requested
264 if APPEND_METAVARS_HELP:
265 metavar_str = param.make_metavar()
266 # Do it ourselves if this is a positional argument
267 if isinstance(param, click.core.Argument) and re.match(rf"\[?{param.name.upper()}]?", metavar_str):
268 metavar_str = param.type.name.upper()
269 # Skip booleans
270 if metavar_str != "BOOLEAN" or isinstance(param, click.core.Argument):
271 metavar_str = metavar_str.replace("[", "").replace("]", "")
272 items.append(
273 Text(
274 APPEND_METAVARS_HELP_STRING.format(metavar_str),
275 style=STYLE_METAVAR_APPEND,
276 overflow="fold",
277 )
278 )
279
280 # Environment variable AFTER help text
281 if getattr(param, "show_envvar", None) and not OPTION_ENVVAR_FIRST and envvar is not None:
282 items.append(Text(ENVVAR_STRING.format(envvar), style=STYLE_OPTION_ENVVAR))
283
284 # Default value
285 if getattr(param, "show_default", None):
286 # param.default is the value, but click is a bit clever in choosing what to show here
287 # eg. --debug/--no-debug, default=False will show up as [default: no-debug] instead of [default: False]
288 # To avoid duplicating loads of code, let's just pull out the string from click with a regex
289 # Example outputs from param.get_help_record(ctx)[-1] are:
290 # [default: foo]
291 # [env var: EMAIL, EMAIL_ADDRESS; default: foo]
292 default_str_match = re.search(r"\[(?:.+; )?default: (.*)\]", param.get_help_record(ctx)[-1])
293 if default_str_match:
294 # Don't show the required string, as we show that afterwards anyway
295 default_str = default_str_match.group(1).replace("; required", "")
296 items.append(
297 Text(
298 DEFAULT_STRING.format(default_str),
299 style=STYLE_OPTION_DEFAULT,
300 )
301 )
302
303 # Required?
304 if param.required:
305 items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))
306
307 # Use Columns - this allows us to group different renderable types
308 # (Text, Markdown) onto a single line.
309 return Columns(items)
310
311
312 def _make_command_help(help_text: str) -> Union[rich.text.Text, rich.markdown.Markdown]:
313 """Build cli help text for a click group command.
314
315 That is, when calling help on groups with multiple subcommands
316 (not the main help text when calling the subcommand help).
317
318 Returns the first paragraph of help text for a command, rendered either as a
319 Rich Text object or as Markdown.
320 Ignores single newlines as paragraph markers, looks for double only.
321
322 Args:
323 help_text (str): Help text
324
325 Returns:
326 Text or Markdown: Styled object
327 """
328 paragraphs = inspect.cleandoc(help_text).split("\n\n")
329 # Remove single linebreaks
330 if not USE_MARKDOWN and not paragraphs[0].startswith("\b"):
331 paragraphs[0] = paragraphs[0].replace("\n", " ")
332 elif paragraphs[0].startswith("\b"):
333 paragraphs[0] = paragraphs[0].replace("\b\n", "")
334 return _make_rich_rext(paragraphs[0].strip(), STYLE_OPTION_HELP)
335
336
337 def rich_format_help(
338 obj: Union[click.Command, click.Group],
339 ctx: click.Context,
340 formatter: click.HelpFormatter,
341 ) -> None:
342 """Print nicely formatted help text using rich.
343
344 Based on original code from rich-cli, by @willmcgugan.
345 https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236
346
347 Replacement for the click function format_help().
348 Takes a command or group and builds the help text output.
349
350 Args:
351 obj (click.Command or click.Group): Command or group to build help text for
352 ctx (click.Context): Click Context object
353 formatter (click.HelpFormatter): Click HelpFormatter object
354 """
355 console = _get_rich_console()
356 # Header text if we have it
357 if HEADER_TEXT:
358 console.print(Padding(_make_rich_rext(HEADER_TEXT, STYLE_HEADER_TEXT), (1, 1, 0, 1)))
359
360 # Print usage
361 console.print(Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND)
362
363 # Print command / group help if we have some
364 if obj.help:
365
366 # Print with some padding
367 console.print(
368 Padding(
369 Align(_get_help_text(obj), pad=False),
370 (0, 1, 1, 1),
371 )
372 )
373
374 # Look through OPTION_GROUPS for this command
375 # stick anything unmatched into a default group at the end
376 option_groups = OPTION_GROUPS.get(ctx.command_path, []).copy()
377 option_groups.append({"options": []})
378 argument_group_options = []
379
380 for param in obj.get_params(ctx):
381
382 # Skip positional arguments - they don't have opts or helptext and are covered in usage
383 # See https://click.palletsprojects.com/en/8.0.x/documentation/#documenting-arguments
384 if isinstance(param, click.core.Argument) and not SHOW_ARGUMENTS:
385 continue
386
387 # Skip if option is hidden
388 if getattr(param, "hidden", False):
389 continue
390
391 # Already mentioned in a config option group
392 for option_group in option_groups:
393 if any([opt in option_group.get("options", []) for opt in param.opts]):
394 break
395
396 # No break, no mention - add to the default group
397 else:
398 if isinstance(param, click.core.Argument) and not GROUP_ARGUMENTS_OPTIONS:
399 argument_group_options.append(param.opts[0])
400 else:
401 list_of_option_groups: List = option_groups[-1]["options"] # type: ignore
402 list_of_option_groups.append(param.opts[0])
403
404 # If we're not grouping arguments and we got some, prepend before default options
405 if len(argument_group_options) > 0:
406 extra_option_group = {"name": ARGUMENTS_PANEL_TITLE, "options": argument_group_options}
407 option_groups.insert(len(option_groups) - 1, extra_option_group) # type: ignore
408
409 # Print each option group panel
410 for option_group in option_groups:
411
412 options_rows = []
413 for opt in option_group.get("options", []):
414
415 # Get the param
416 for param in obj.get_params(ctx):
417 if any([opt in param.opts]):
418 break
419 # Skip if option is not listed in this group
420 else:
421 continue
422
423 # Short and long form
424 opt_long_strs = []
425 opt_short_strs = []
426 for idx, opt in enumerate(param.opts):
427 opt_str = opt
428 try:
429 opt_str += "/" + param.secondary_opts[idx]
430 except IndexError:
431 pass
432
433 if isinstance(param, click.core.Argument):
434 opt_long_strs.append(opt_str.upper())
435 elif "--" in opt:
436 opt_long_strs.append(opt_str)
437 else:
438 opt_short_strs.append(opt_str)
439
440 # Column for a metavar, if we have one
441 metavar = Text(style=STYLE_METAVAR, overflow="fold")
442 metavar_str = param.make_metavar()
443
444 # Do it ourselves if this is a positional argument
445 if isinstance(param, click.core.Argument) and re.match(rf"\[?{param.name.upper()}]?", metavar_str):
446 metavar_str = param.type.name.upper()
447
448 # Skip booleans and choices (handled above)
449 if metavar_str != "BOOLEAN" or isinstance(param, click.core.Argument):
450 metavar.append(metavar_str)
451
452 # Range - from
453 # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501
454 try:
455 # skip count with default range type
456 if isinstance(param.type, click.types._NumberRangeBase) and not (
457 param.count and param.type.min == 0 and param.type.max is None
458 ):
459 range_str = param.type._describe_range()
460 if range_str:
461 metavar.append(RANGE_STRING.format(range_str))
462 except AttributeError:
463 # click.types._NumberRangeBase is only in Click 8x onwards
464 pass
465
466 # Required asterisk
467 required = ""
468 if param.required:
469 required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)
470
471 # Highlighter to make [ | ] and <> dim
472 class MetavarHighlighter(RegexHighlighter):
473 highlights = [
474 r"^(?P<metavar_sep>(\[|<))",
475 r"(?P<metavar_sep>\|)",
476 r"(?P<metavar_sep>(\]|>)$)",
477 ]
478
479 metavar_highlighter = MetavarHighlighter()
480
481 rows = [
482 required,
483 highlighter(highlighter(",".join(opt_long_strs))),
484 highlighter(highlighter(",".join(opt_short_strs))),
485 metavar_highlighter(metavar),
486 _get_parameter_help(param, ctx),
487 ]
488
489 # Remove metavar if specified in config
490 if not SHOW_METAVARS_COLUMN:
491 rows.pop(3)
492
493 options_rows.append(rows)
494
495 if len(options_rows) > 0:
496 t_styles = {
497 "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,
498 "leading": STYLE_OPTIONS_TABLE_LEADING,
499 "box": STYLE_OPTIONS_TABLE_BOX,
500 "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,
501 "row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES,
502 "pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE,
503 "padding": STYLE_OPTIONS_TABLE_PADDING,
504 }
505 t_styles.update(option_group.get("table_styles", {})) # type: ignore
506 box_style = getattr(box, t_styles.pop("box"), None) # type: ignore
507
508 options_table = Table(
509 highlight=True,
510 show_header=False,
511 expand=True,
512 box=box_style,
513 **t_styles,
514 )
515 # Strip the required column if none are required
516 if all([x[0] == "" for x in options_rows]):
517 options_rows = [x[1:] for x in options_rows]
518 for row in options_rows:
519 options_table.add_row(*row)
520 console.print(
521 Panel(
522 options_table,
523 border_style=STYLE_OPTIONS_PANEL_BORDER,
524 title=option_group.get("name", OPTIONS_PANEL_TITLE),
525 title_align=ALIGN_OPTIONS_PANEL,
526 )
527 )
528
529 #
530 # Groups only:
531 # List click command groups
532 #
533 if hasattr(obj, "list_commands"):
534 # Look through COMMAND_GROUPS for this command
535 # stick anything unmatched into a default group at the end
536 cmd_groups = COMMAND_GROUPS.get(ctx.command_path, []).copy()
537 cmd_groups.append({"commands": []})
538 for command in obj.list_commands(ctx):
539 for cmd_group in cmd_groups:
540 if command in cmd_group.get("commands", []):
541 break
542 else:
543 commands: List = cmd_groups[-1]["commands"] # type: ignore
544 commands.append(command)
545
546 # Print each command group panel
547 for cmd_group in cmd_groups:
548 t_styles = {
549 "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,
550 "leading": STYLE_COMMANDS_TABLE_LEADING,
551 "box": STYLE_COMMANDS_TABLE_BOX,
552 "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,
553 "row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES,
554 "pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE,
555 "padding": STYLE_COMMANDS_TABLE_PADDING,
556 }
557 t_styles.update(cmd_group.get("table_styles", {})) # type: ignore
558 box_style = getattr(box, t_styles.pop("box"), None) # type: ignore
559
560 commands_table = Table(
561 highlight=False,
562 show_header=False,
563 expand=True,
564 box=box_style,
565 **t_styles,
566 )
567 # Define formatting in first column, as commands don't match highlighter regex
568 commands_table.add_column(style="bold cyan", no_wrap=True)
569 for command in cmd_group.get("commands", []):
570 # Skip if command does not exist
571 if command not in obj.list_commands(ctx):
572 continue
573 cmd = obj.get_command(ctx, command)
574 if cmd.hidden:
575 continue
576 # Use the truncated short text as with vanilla text if requested
577 if USE_CLICK_SHORT_HELP:
578 helptext = cmd.get_short_help_str()
579 else:
580 # Use short_help function argument if used, or the full help
581 helptext = cmd.short_help or cmd.help or ""
582 commands_table.add_row(command, _make_command_help(helptext))
583 if commands_table.row_count > 0:
584 console.print(
585 Panel(
586 commands_table,
587 border_style=STYLE_COMMANDS_PANEL_BORDER,
588 title=cmd_group.get("name", COMMANDS_PANEL_TITLE),
589 title_align=ALIGN_COMMANDS_PANEL,
590 )
591 )
592
593 # Epilogue if we have it
594 if obj.epilog:
595 # Remove single linebreaks, replace double with single
596 lines = obj.epilog.split("\n\n")
597 epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines])
598 console.print(Padding(Align(highlighter(epilogue), pad=False), 1))
599
600 # Footer text if we have it
601 if FOOTER_TEXT:
602 console.print(Padding(_make_rich_rext(FOOTER_TEXT, STYLE_FOOTER_TEXT), (1, 1, 0, 1)))
603
604
605 def rich_format_error(self: click.ClickException):
606 """Print richly formatted click errors.
607
608 Called by custom exception handler to print richly formatted click errors.
609 Mimics original click.ClickException.echo() function but with rich formatting.
610
611 Args:
612 click.ClickException: Click exception to format.
613 """
614 console = _get_rich_console()
615 if getattr(self, "ctx", None) is not None:
616 console.print(Padding(self.ctx.get_usage(), 1))
617 if ERRORS_SUGGESTION:
618 console.print(
619 Padding(
620 ERRORS_SUGGESTION,
621 (0, 1, 0, 1),
622 ),
623 style=STYLE_ERRORS_SUGGESTION,
624 )
625 elif (
626 ERRORS_SUGGESTION is None
627 and getattr(self, "ctx", None) is not None
628 and self.ctx.command.get_help_option(self.ctx) is not None
629 ):
630 console.print(
631 Padding(
632 "Try [blue]'{command} {option}'[/] for help.".format(
633 command=self.ctx.command_path, option=self.ctx.help_option_names[0]
634 ),
635 (0, 1, 0, 1),
636 ),
637 style=STYLE_ERRORS_SUGGESTION,
638 )
639
640 console.print(
641 Padding(
642 Panel(
643 highlighter(self.format_message()),
644 border_style=STYLE_ERRORS_PANEL_BORDER,
645 title=ERRORS_PANEL_TITLE,
646 title_align=ALIGN_ERRORS_PANEL,
647 ),
648 (0, 0, 1, 0),
649 )
650 )
651 if ERRORS_EPILOGUE:
652 console.print(Padding(ERRORS_EPILOGUE, (0, 1, 1, 1)))
653
654
655 def rich_abort_error() -> None:
656 """Print richly formatted abort error."""
657 console = _get_rich_console()
658 console.print(ABORTED_TEXT, style=STYLE_ABORTED)