0
# Command Line Interface
1
2
Rich-Click CLI tool for enhancing external Click applications with rich formatting without modifying their source code. The CLI tool allows you to run any Click-based command-line application with Rich-Click's enhanced formatting by prefixing the command with `rich-click`.
3
4
## Capabilities
5
6
### Main CLI Function
7
8
The primary entry point for the Rich-Click command-line interface tool.
9
10
```python { .api }
11
def main(
12
ctx: RichContext,
13
script_and_args: List[str],
14
output: Literal[None, "html", "svg"],
15
errors_in_output_format: bool,
16
suppress_warnings: bool,
17
rich_config: Optional[RichHelpConfiguration],
18
show_help: bool,
19
) -> None:
20
"""
21
Rich-click CLI command entry point.
22
23
The rich-click CLI provides attractive help output from any tool using click,
24
formatted with rich. The command line tool can be prepended before any Python
25
package using native click to provide attractive richified click help output.
26
27
Parameters:
28
- ctx (RichContext): Rich context object
29
- script_and_args (List[str]): Script name and arguments to execute
30
- output (Literal[None, "html", "svg"], optional): Output format for help text (html/svg)
31
- errors_in_output_format (bool): Whether to format errors in output format
32
- suppress_warnings (bool): Whether to suppress entry point warnings
33
- rich_config (RichHelpConfiguration, optional): Rich configuration to apply
34
- show_help (bool): Whether to show help message
35
36
Examples:
37
- rich-click my_package --help
38
- rich-click my_module:my_function --version
39
- rich-click --output html my_app --help > help.html
40
"""
41
```
42
43
### CLI Configuration
44
45
Command-line options and configuration for the Rich-Click CLI tool.
46
47
The CLI tool is configured with the following options:
48
49
```bash
50
# Basic usage
51
rich-click [OPTIONS] [SCRIPT | MODULE:CLICK_COMMAND] [-- SCRIPT_ARGS...]
52
53
# Options:
54
--rich-config, -c JSON # Rich configuration (JSON or @file.json)
55
--output, -o [html|svg] # Output format (html or svg)
56
--errors-in-output-format # Format errors in output format
57
--suppress-warnings # Suppress entry point warnings
58
--help, -h # Show help message
59
```
60
61
### Entry Point Resolution
62
63
Functions for resolving and executing Click commands from various sources.
64
65
```python { .api }
66
def entry_points(*, group: str) -> "metadata.EntryPoints":
67
"""
68
Entry points function compatible with Python 3.7+.
69
70
Provides consistent entry point access across Python versions,
71
handling differences in the importlib.metadata API.
72
73
Parameters:
74
- group (str): Entry point group name (e.g., 'console_scripts')
75
76
Returns:
77
metadata.EntryPoints: Collection of entry points for the group
78
"""
79
80
def _get_module_path_and_function_name(script: str, suppress_warnings: bool) -> Tuple[str, str]:
81
"""
82
Parse script reference to module path and function name.
83
84
Resolves script names to module paths and function names, handling
85
both console_scripts entry points and direct module:function references.
86
87
Parameters:
88
- script (str): Script name or module:function reference
89
- suppress_warnings (bool): Whether to suppress duplicate warnings
90
91
Returns:
92
Tuple[str, str]: Module path and function name
93
94
Raises:
95
- ClickException: If script cannot be resolved
96
97
Examples:
98
- "mypackage" -> ("mypackage.cli", "main")
99
- "mymodule:myfunc" -> ("mymodule", "myfunc")
100
"""
101
```
102
103
### Parameter Types
104
105
Custom Click parameter types used by the CLI tool.
106
107
```python { .api }
108
class _RichHelpConfigurationParamType(click.ParamType):
109
"""
110
Click parameter type for RichHelpConfiguration.
111
112
Handles JSON configuration input from command line arguments,
113
supporting both inline JSON and file references (@file.json).
114
115
Attributes:
116
- name: str = "JSON"
117
"""
118
119
def convert(
120
self,
121
value: Optional[Union[RichHelpConfiguration, str]],
122
param: Optional[click.Parameter],
123
ctx: Optional[click.Context],
124
) -> Optional[RichHelpConfiguration]:
125
"""
126
Convert parameter value to RichHelpConfiguration.
127
128
Parameters:
129
- value (Union[RichHelpConfiguration, str, None]): Input value
130
- param (click.Parameter, optional): Parameter object
131
- ctx (click.Context, optional): Click context
132
133
Returns:
134
Optional[RichHelpConfiguration]: Parsed configuration
135
136
Supports:
137
- Direct JSON: '{"style_option": "bold red"}'
138
- File reference: '@config.json'
139
- None value: Returns None
140
- Existing RichHelpConfiguration: Returns as-is
141
142
Raises:
143
- Exception: If JSON parsing fails or file not found
144
"""
145
```
146
147
### Usage Examples
148
149
Common usage patterns for the Rich-Click CLI tool:
150
151
#### Basic Usage
152
153
```bash
154
# Enhance any Click-based tool
155
rich-click mypackage --help
156
157
# Run specific module function
158
rich-click mymodule:main --version
159
160
# Pass arguments to the target command
161
rich-click myapp -- --config config.json --verbose
162
```
163
164
#### Output Formatting
165
166
```bash
167
# Export help as HTML
168
rich-click --output html myapp --help > help.html
169
170
# Export help as SVG
171
rich-click --output svg myapp --help > help.svg
172
173
# Include errors in output format
174
rich-click --output html --errors-in-output-format myapp --invalid-option
175
```
176
177
#### Configuration
178
179
```bash
180
# Use inline JSON configuration
181
rich-click --rich-config '{"style_option": "bold red"}' myapp --help
182
183
# Use configuration file
184
rich-click --rich-config @rich_config.json myapp --help
185
186
# Configuration file example (rich_config.json):
187
{
188
"style_option": "bold blue",
189
"style_command": "bold green",
190
"show_arguments": true,
191
"options_panel_title": "Available Options"
192
}
193
```
194
195
#### Advanced Usage
196
197
```bash
198
# Suppress duplicate entry point warnings
199
rich-click --suppress-warnings myapp --help
200
201
# Chain with other commands
202
rich-click myapp --help | less
203
204
# Use in scripts
205
#!/bin/bash
206
if command -v rich-click >/dev/null 2>&1; then
207
rich-click myapp "$@"
208
else
209
myapp "$@"
210
fi
211
```
212
213
### Error Handling
214
215
The CLI tool provides comprehensive error handling for various scenarios:
216
217
```python
218
# Entry point resolution errors
219
try:
220
module_path, function_name = _get_module_path_and_function_name(script, suppress_warnings)
221
module = import_module(module_path)
222
except (ModuleNotFoundError, ClickException):
223
# Fallback: add current directory to Python path and retry
224
sys.path.append(os.path.abspath("."))
225
module_path, function_name = _get_module_path_and_function_name(script, suppress_warnings)
226
module = import_module(module_path)
227
228
# Configuration errors
229
try:
230
data = json.loads(config_string)
231
if not isinstance(data, dict):
232
raise ValueError("Configuration must be a JSON object")
233
return RichHelpConfiguration.load_from_globals(**data)
234
except Exception as e:
235
if ctx and ctx.params.get("show_help", False):
236
# Show help if configuration fails during help display
237
click.echo(ctx.get_help(), color=ctx.color)
238
ctx.exit()
239
else:
240
raise e
241
```
242
243
### Integration with Existing Applications
244
245
The CLI tool is designed to work seamlessly with existing Click applications:
246
247
#### Direct Integration
248
249
```python
250
# In your setup.py or pyproject.toml
251
[project.scripts]
252
myapp = "mypackage.cli:main"
253
myapp-rich = "rich_click.cli:main mypackage.cli:main"
254
```
255
256
#### Wrapper Scripts
257
258
```python
259
#!/usr/bin/env python3
260
"""Rich wrapper for existing Click app."""
261
import sys
262
from rich_click.cli import main as rich_main
263
from rich_click import RichContext
264
265
if __name__ == '__main__':
266
# Configure Rich-Click
267
ctx = RichContext()
268
sys.argv = ['rich-click', 'mypackage.cli:main'] + sys.argv[1:]
269
rich_main()
270
```
271
272
#### Conditional Enhancement
273
274
```python
275
"""Application that optionally uses Rich-Click."""
276
import sys
277
278
try:
279
import rich_click as click
280
# Patch for enhanced formatting
281
click.patch()
282
except ImportError:
283
import click
284
285
@click.command()
286
@click.option('--name', help='Your name')
287
def hello(name):
288
"""Say hello with optional rich formatting."""
289
click.echo(f'Hello, {name}!')
290
291
if __name__ == '__main__':
292
hello()
293
```
294
295
### Installation Script
296
297
The CLI tool is available as a console script after installing Rich-Click:
298
299
```toml
300
# From pyproject.toml
301
[project.scripts]
302
rich-click = "rich_click.cli:main"
303
```
304
305
This enables direct usage from the command line:
306
307
```bash
308
pip install rich-click
309
rich-click --help
310
rich-click myapp --help
311
```