Debian Codegraph @

src/rich_click/rich_click.py

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