0
# Click API Re-exports
1
2
Complete Click API re-exported for drop-in compatibility. Rich-Click re-exports the entire Click API unchanged, enabling it to serve as a direct replacement for Click while adding rich formatting capabilities.
3
4
## Capabilities
5
6
### Core Classes
7
8
Essential Click classes for building command-line interfaces, re-exported without modification.
9
10
```python { .api }
11
class Command:
12
"""Base class for Click commands."""
13
14
class Group:
15
"""Base class for Click command groups."""
16
17
class CommandCollection:
18
"""Collection of multiple command sources."""
19
20
class Context:
21
"""Click context object for passing state."""
22
23
class Parameter:
24
"""Base class for command parameters."""
25
26
class Option:
27
"""Command option parameter."""
28
29
class Argument:
30
"""Command argument parameter."""
31
```
32
33
### Decorators
34
35
Click decorators for building command-line interfaces, providing the foundation for CLI creation.
36
37
```python { .api }
38
def option(*param_decls, **attrs):
39
"""
40
Decorator for adding options to commands.
41
42
Parameters:
43
- *param_decls: Parameter declarations (e.g., '-v', '--verbose')
44
- **attrs: Option attributes (type, help, default, etc.)
45
46
Returns:
47
Callable: Decorator function
48
"""
49
50
def argument(*param_decls, **attrs):
51
"""
52
Decorator for adding arguments to commands.
53
54
Parameters:
55
- *param_decls: Parameter declarations
56
- **attrs: Argument attributes (type, help, etc.)
57
58
Returns:
59
Callable: Decorator function
60
"""
61
62
def confirmation_option(*param_decls, **attrs):
63
"""
64
Decorator for adding confirmation options.
65
66
Parameters:
67
- *param_decls: Parameter declarations
68
- **attrs: Option attributes
69
70
Returns:
71
Callable: Decorator function
72
"""
73
74
def help_option(*param_decls, **attrs):
75
"""
76
Decorator for adding help options.
77
78
Parameters:
79
- *param_decls: Parameter declarations
80
- **attrs: Option attributes
81
82
Returns:
83
Callable: Decorator function
84
"""
85
86
def password_option(*param_decls, **attrs):
87
"""
88
Decorator for adding password options.
89
90
Parameters:
91
- *param_decls: Parameter declarations
92
- **attrs: Option attributes
93
94
Returns:
95
Callable: Decorator function
96
"""
97
98
def version_option(*param_decls, **attrs):
99
"""
100
Decorator for adding version options.
101
102
Parameters:
103
- *param_decls: Parameter declarations
104
- **attrs: Option attributes
105
106
Returns:
107
Callable: Decorator function
108
"""
109
110
def make_pass_decorator(object_type):
111
"""
112
Create a decorator that passes an object of the given type.
113
114
Parameters:
115
- object_type: Type of object to pass
116
117
Returns:
118
Callable: Pass decorator function
119
"""
120
121
def pass_obj(f):
122
"""
123
Decorator that passes the context object.
124
125
Parameters:
126
- f (Callable): Function to decorate
127
128
Returns:
129
Callable: Decorated function
130
"""
131
```
132
133
### Exception Classes
134
135
Click exception hierarchy for error handling in command-line applications.
136
137
```python { .api }
138
class ClickException(Exception):
139
"""
140
Base exception for all Click-related errors.
141
142
Attributes:
143
- message (str): Error message
144
- exit_code (int): Process exit code
145
"""
146
147
class UsageError(ClickException):
148
"""
149
Exception raised for usage errors.
150
151
Raised when command usage is incorrect, such as missing
152
required parameters or invalid option combinations.
153
"""
154
155
class BadParameter(UsageError):
156
"""
157
Exception raised for bad parameter values.
158
159
Raised when a parameter value is invalid or cannot be
160
converted to the expected type.
161
"""
162
163
class BadArgumentUsage(BadParameter):
164
"""Exception raised for bad argument usage."""
165
166
class BadOptionUsage(BadParameter):
167
"""Exception raised for bad option usage."""
168
169
class MissingParameter(BadParameter):
170
"""Exception raised when required parameter is missing."""
171
172
class NoSuchOption(UsageError):
173
"""Exception raised when an unknown option is used."""
174
175
class FileError(ClickException):
176
"""Exception raised for file-related errors."""
177
178
class Abort(RuntimeError):
179
"""Exception raised to abort command execution."""
180
```
181
182
### Type System
183
184
Click's parameter type system for validating and converting command-line arguments.
185
186
```python { .api }
187
# Built-in type constants
188
BOOL: ParamType
189
"""Boolean parameter type."""
190
191
INT: ParamType
192
"""Integer parameter type."""
193
194
FLOAT: ParamType
195
"""Float parameter type."""
196
197
STRING: ParamType
198
"""String parameter type."""
199
200
UNPROCESSED: ParamType
201
"""Unprocessed parameter type."""
202
203
UUID: ParamType
204
"""UUID parameter type."""
205
206
# Type classes
207
class ParamType:
208
"""Base class for parameter types."""
209
210
def convert(self, value, param, ctx):
211
"""Convert parameter value."""
212
213
def fail(self, message, param, ctx):
214
"""Fail with error message."""
215
216
class Choice(ParamType):
217
"""
218
Parameter type for choosing from a list of values.
219
220
Parameters:
221
- choices (Sequence[str]): Available choices
222
- case_sensitive (bool): Whether choices are case sensitive
223
"""
224
225
class IntRange(ParamType):
226
"""
227
Parameter type for integers within a range.
228
229
Parameters:
230
- min (int, optional): Minimum value
231
- max (int, optional): Maximum value
232
- clamp (bool): Whether to clamp values to range
233
"""
234
235
class FloatRange(ParamType):
236
"""
237
Parameter type for floats within a range.
238
239
Parameters:
240
- min (float, optional): Minimum value
241
- max (float, optional): Maximum value
242
- clamp (bool): Whether to clamp values to range
243
"""
244
245
class DateTime(ParamType):
246
"""
247
Parameter type for datetime values.
248
249
Parameters:
250
- formats (List[str]): Accepted datetime formats
251
"""
252
253
class File(ParamType):
254
"""
255
Parameter type for file objects.
256
257
Parameters:
258
- mode (str): File mode ('r', 'w', 'rb', etc.)
259
- encoding (str, optional): File encoding
260
- errors (str): Error handling strategy
261
- lazy (bool): Whether to open file lazily
262
- atomic (bool): Whether to use atomic writes
263
"""
264
265
class Path(ParamType):
266
"""
267
Parameter type for filesystem paths.
268
269
Parameters:
270
- exists (bool): Whether path must exist
271
- file_okay (bool): Whether files are allowed
272
- dir_okay (bool): Whether directories are allowed
273
- writable (bool): Whether path must be writable
274
- readable (bool): Whether path must be readable
275
- resolve_path (bool): Whether to resolve relative paths
276
- allow_dash (bool): Whether to allow '-' for stdin/stdout
277
- path_type (type): Path type to return
278
"""
279
280
class Tuple(ParamType):
281
"""
282
Parameter type for tuples of values.
283
284
Parameters:
285
- types (Sequence[ParamType]): Types for tuple elements
286
"""
287
```
288
289
### Terminal UI Functions
290
291
Click's terminal user interface utilities for interactive command-line applications.
292
293
```python { .api }
294
def echo(message=None, file=None, nl=True, err=False, color=None):
295
"""
296
Print message to terminal.
297
298
Parameters:
299
- message: Message to print
300
- file: File to write to
301
- nl (bool): Whether to add newline
302
- err (bool): Whether to write to stderr
303
- color: Color setting
304
"""
305
306
def secho(message=None, file=None, nl=True, err=False, color=None, **styles):
307
"""
308
Print styled message to terminal.
309
310
Parameters:
311
- message: Message to print
312
- file: File to write to
313
- nl (bool): Whether to add newline
314
- err (bool): Whether to write to stderr
315
- color: Color setting
316
- **styles: Style attributes (fg, bg, bold, etc.)
317
"""
318
319
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
320
overline=None, italic=None, blink=None, reverse=None,
321
strikethrough=None, reset=True):
322
"""
323
Style text with ANSI codes.
324
325
Parameters:
326
- text (str): Text to style
327
- fg: Foreground color
328
- bg: Background color
329
- bold (bool): Bold text
330
- dim (bool): Dim text
331
- underline (bool): Underlined text
332
- italic (bool): Italic text
333
- blink (bool): Blinking text
334
- reverse (bool): Reverse colors
335
- strikethrough (bool): Strikethrough text
336
- reset (bool): Reset styles after text
337
338
Returns:
339
str: Styled text
340
"""
341
342
def unstyle(text):
343
"""
344
Remove ANSI styling from text.
345
346
Parameters:
347
- text (str): Styled text
348
349
Returns:
350
str: Unstyled text
351
"""
352
353
def clear():
354
"""Clear the terminal screen."""
355
356
def confirm(text, default=False, abort=False, prompt_suffix=': ',
357
show_default=True, err=False):
358
"""
359
Show confirmation prompt.
360
361
Parameters:
362
- text (str): Prompt text
363
- default (bool): Default value
364
- abort (bool): Whether to abort on negative response
365
- prompt_suffix (str): Suffix for prompt
366
- show_default (bool): Whether to show default value
367
- err (bool): Whether to write to stderr
368
369
Returns:
370
bool: User response
371
"""
372
373
def prompt(text, default=None, hide_input=False, confirmation_prompt=False,
374
type=None, value_proc=None, prompt_suffix=': ', show_default=True,
375
err=False, show_choices=True):
376
"""
377
Show input prompt.
378
379
Parameters:
380
- text (str): Prompt text
381
- default: Default value
382
- hide_input (bool): Whether to hide input (password)
383
- confirmation_prompt (bool): Whether to ask for confirmation
384
- type: Parameter type for validation
385
- value_proc: Value processing function
386
- prompt_suffix (str): Suffix for prompt
387
- show_default (bool): Whether to show default
388
- err (bool): Whether to write to stderr
389
- show_choices (bool): Whether to show choices
390
391
Returns:
392
Any: User input value
393
"""
394
395
def pause(info='Press any key to continue...', err=False):
396
"""
397
Pause execution until key press.
398
399
Parameters:
400
- info (str): Info message to display
401
- err (bool): Whether to write to stderr
402
"""
403
404
def getchar(echo=False):
405
"""
406
Get single character from terminal.
407
408
Parameters:
409
- echo (bool): Whether to echo character
410
411
Returns:
412
str: Character pressed
413
"""
414
415
def edit(text=None, editor=None, env=None, require_save=True,
416
extension='.txt', filename=None):
417
"""
418
Launch text editor.
419
420
Parameters:
421
- text (str): Initial text content
422
- editor (str): Editor command to use
423
- env (dict): Environment variables
424
- require_save (bool): Whether save is required
425
- extension (str): File extension for temp file
426
- filename (str): Specific filename to use
427
428
Returns:
429
str: Edited text content
430
"""
431
432
def launch(url, wait=False, locate=False):
433
"""
434
Launch URL or file in default application.
435
436
Parameters:
437
- url (str): URL or file path to launch
438
- wait (bool): Whether to wait for application
439
- locate (bool): Whether to locate file instead of opening
440
441
Returns:
442
int: Return code
443
"""
444
445
def echo_via_pager(text_or_generator, color=None):
446
"""
447
Display text via system pager.
448
449
Parameters:
450
- text_or_generator: Text or generator yielding text
451
- color: Color setting
452
"""
453
454
def progressbar(iterable=None, length=None, label=None, show_eta=True,
455
show_percent=None, show_pos=False, item_show_func=None,
456
fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s',
457
info_sep=' ', width=36, file=None, color=None):
458
"""
459
Display progress bar.
460
461
Parameters:
462
- iterable: Iterable to track progress
463
- length (int): Total length if iterable has no len()
464
- label (str): Label to display
465
- show_eta (bool): Whether to show ETA
466
- show_percent (bool): Whether to show percentage
467
- show_pos (bool): Whether to show position
468
- item_show_func: Function to format current item
469
- fill_char (str): Character for filled portion
470
- empty_char (str): Character for empty portion
471
- bar_template (str): Template for bar format
472
- info_sep (str): Separator for info section
473
- width (int): Width of progress bar
474
- file: File to write to
475
- color: Color setting
476
477
Returns:
478
ProgressBar: Progress bar context manager
479
"""
480
```
481
482
### Utility Functions
483
484
Click utility functions for common command-line tasks.
485
486
```python { .api }
487
def get_current_context(silent=False):
488
"""
489
Get the current Click context.
490
491
Parameters:
492
- silent (bool): Whether to fail silently if no context
493
494
Returns:
495
Context: Current context object
496
497
Raises:
498
RuntimeError: If no context available and not silent
499
"""
500
501
def format_filename(filename, shorten=False):
502
"""
503
Format filename for display.
504
505
Parameters:
506
- filename (str): Filename to format
507
- shorten (bool): Whether to shorten long paths
508
509
Returns:
510
str: Formatted filename
511
"""
512
513
def get_app_dir(app_name, roaming=True, force_posix=False):
514
"""
515
Get application directory for storing data.
516
517
Parameters:
518
- app_name (str): Application name
519
- roaming (bool): Whether to use roaming directory
520
- force_posix (bool): Whether to force POSIX behavior
521
522
Returns:
523
str: Application directory path
524
"""
525
526
def get_binary_stream(name):
527
"""
528
Get binary stream (stdin/stdout/stderr).
529
530
Parameters:
531
- name (str): Stream name ('stdin', 'stdout', 'stderr')
532
533
Returns:
534
BinaryIO: Binary stream
535
"""
536
537
def get_text_stream(name, encoding=None, errors='strict'):
538
"""
539
Get text stream (stdin/stdout/stderr).
540
541
Parameters:
542
- name (str): Stream name ('stdin', 'stdout', 'stderr')
543
- encoding (str): Text encoding
544
- errors (str): Error handling
545
546
Returns:
547
TextIO: Text stream
548
"""
549
550
def open_file(filename, mode='r', encoding=None, errors='strict', lazy=False, atomic=False):
551
"""
552
Open file with Click's file handling.
553
554
Parameters:
555
- filename (str): File to open
556
- mode (str): File mode
557
- encoding (str): Text encoding
558
- errors (str): Error handling
559
- lazy (bool): Whether to open lazily
560
- atomic (bool): Whether to use atomic writes
561
562
Returns:
563
IO: File object
564
"""
565
```
566
567
### Help Formatting
568
569
Click's help formatting system.
570
571
```python { .api }
572
class HelpFormatter:
573
"""
574
Help formatter for Click commands.
575
576
Formats help text with proper indentation and wrapping.
577
"""
578
579
def write_usage(self, prog, args=None, prefix=None):
580
"""Write usage line."""
581
582
def write_heading(self, heading):
583
"""Write section heading."""
584
585
def write_paragraph(self):
586
"""Write paragraph break."""
587
588
def write_text(self, text):
589
"""Write formatted text."""
590
591
def write_dl(self, rows):
592
"""Write definition list."""
593
594
def wrap_text(text, width=78, initial_indent='', subsequent_indent='',
595
preserve_paragraphs=False):
596
"""
597
Wrap text to specified width.
598
599
Parameters:
600
- text (str): Text to wrap
601
- width (int): Maximum line width
602
- initial_indent (str): Indent for first line
603
- subsequent_indent (str): Indent for continuation lines
604
- preserve_paragraphs (bool): Whether to preserve paragraph breaks
605
606
Returns:
607
str: Wrapped text
608
"""
609
```