Debian Codegraph @

src/rich_click/cli.py

raw
1 """The command line interface."""
2
3 import sys
4 from importlib import import_module
5 from textwrap import dedent
6 from typing import Any, List, Optional
7
8 try:
9 from importlib.metadata import entry_points
10 except ImportError:
11 # Support Python <3.8
12 from importlib_metadata import entry_points
13
14 import click
15 from rich.console import Console
16 from rich.padding import Padding
17 from rich.panel import Panel
18 from rich.text import Text
19
20 from rich_click import command as rich_command
21 from rich_click import group as rich_group
22 from rich_click import RichCommand, RichGroup
23 from rich_click.rich_click import (
24 ALIGN_ERRORS_PANEL,
25 ERRORS_PANEL_TITLE,
26 STYLE_ERRORS_PANEL_BORDER,
27 STYLE_HELPTEXT,
28 STYLE_HELPTEXT_FIRST_LINE,
29 STYLE_USAGE,
30 STYLE_USAGE_COMMAND,
31 )
32
33 console = Console()
34
35
36 def _print_usage() -> None:
37 console.print(
38 Padding(
39 Text.from_markup(f"[{STYLE_USAGE}]Usage[/]: rich-click [SCRIPT | MODULE:FUNCTION] [-- SCRIPT_ARGS...]"),
40 1,
41 ),
42 style=STYLE_USAGE_COMMAND,
43 )
44
45
46 def _print_help() -> None:
47 help_paragraphs = dedent(main.__doc__ or "").split("\n\n")
48 help_paragraphs = [x.replace("\n", " ").strip() for x in help_paragraphs]
49 console.print(
50 Padding(
51 Text.from_markup(help_paragraphs[0].strip()),
52 (0, 1),
53 ),
54 style=STYLE_HELPTEXT_FIRST_LINE,
55 )
56 console.print(
57 Padding(
58 Text.from_markup("\n\n".join(help_paragraphs[1:]).strip()),
59 (0, 1),
60 ),
61 style=STYLE_HELPTEXT,
62 )
63
64
65 def patch() -> None:
66 """Patch Click internals to use Rich-Click types."""
67 click.group = rich_group
68 click.command = rich_command
69 click.Group = RichGroup
70 click.Command = RichCommand
71
72
73 def main(args: Optional[List[str]] = None) -> Any:
74 """
75 The [link=https://github.com/ewels/rich-click]rich-click[/] CLI provides attractive help output from any
76 tool using [link=https://click.palletsprojects.com/]click[/], formatted with
77 [link=https://github.com/Textualize/rich]rich[/].
78
79 The rich-click command line tool can be prepended before any Python package
80 using native click to provide attractive richified click help output.
81
82 For example, if you have a package called [blue]my_package[/] that uses click,
83 you can run:
84
85 [blue] rich-click my_package --help [/]
86
87 It only works if the package is using vanilla click without customised [cyan]group()[/]
88 or [cyan]command()[/] classes.
89 If in doubt, please suggest to the authors that they use rich_click within their
90 tool natively - this will always give a better experience.
91 """ # noqa: D400, D401
92 args = args or sys.argv[1:]
93 if not args or args == ["--help"]:
94 # Print usage if we got no args, or only --help
95 _print_usage()
96 _print_help()
97 sys.exit(0)
98 else:
99 script_name = args[0]
100 scripts = {script.name: script for script in entry_points().get("console_scripts")}
101 if script_name in scripts:
102 # a valid script was passed
103 script = scripts[script_name]
104 module_path, function_name = script.value.split(":", 1)
105 prog = script_name
106 elif ":" in script_name:
107 # the path to a function was passed
108 module_path, function_name = args[0].split(":", 1)
109 prog = module_path.split(".", 1)[0]
110 else:
111 _print_usage()
112 console.print(
113 Panel(
114 Text.from_markup(f"No such script: [bold]{script_name}[/]"),
115 border_style=STYLE_ERRORS_PANEL_BORDER,
116 title=ERRORS_PANEL_TITLE,
117 title_align=ALIGN_ERRORS_PANEL,
118 )
119 )
120 console.print(
121 Padding(
122 "Please run [yellow bold]rich-click --help[/] for usage information.",
123 (0, 1),
124 ),
125 style="dim",
126 )
127 sys.exit(1)
128 if len(args) > 1:
129 if args[1] == "--":
130 del args[1]
131 sys.argv = [prog, *args[1:]]
132 # patch click before importing the program function
133 patch()
134 # import the program function
135 module = import_module(module_path)
136 function = getattr(module, function_name)
137 # simply run it: it should be patched as well
138 return function()