-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathannotated_example.py
More file actions
executable file
·734 lines (601 loc) · 27.3 KB
/
Copy pathannotated_example.py
File metadata and controls
executable file
·734 lines (601 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#!/usr/bin/env python3
"""Annotated decorator example -- type-hint-driven argument parsing.
Shows how ``@with_annotated`` eliminates boilerplate compared to
``@with_argparser``. The focus is on features that are unique to
the annotated style -- type inference, auto-completion from types, and
typed function parameters -- while also demonstrating that all of cmd2's
advanced completion features (choices_provider, completer, table_columns,
arg_tokens) remain available via ``Annotated`` metadata, as does argparse's
optional-value idiom (``nargs='?'`` with ``const``).
Compare with ``argparse_completion.py`` which uses ``@with_argparser``
for the same completion features.
Usage::
python examples/annotated_example.py
"""
import datetime
import os
import sys
from argparse import Namespace
from collections.abc import Callable
from dataclasses import dataclass
from decimal import Decimal
from enum import StrEnum
from pathlib import Path
from typing import (
Annotated,
Any,
Literal,
)
import cmd2
from cmd2 import (
Choices,
Cmd,
CompletionItem,
)
from cmd2.annotated import (
Argument,
ArgumentBlock,
Group,
Option,
with_annotated,
)
class Color(StrEnum):
red = "red"
green = "green"
blue = "blue"
yellow = "yellow"
class LogLevel(StrEnum):
debug = "debug"
info = "info"
warning = "warning"
error = "error"
class VerbatimHelpFormatter(cmd2.RawDescriptionCmd2HelpFormatter):
"""Custom help formatter: keeps the description's line breaks verbatim."""
class StrictArgumentParser(cmd2.Cmd2ArgumentParser):
"""Custom parser class: disables ``--opt`` prefix abbreviation."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.setdefault("allow_abbrev", False)
super().__init__(*args, **kwargs)
ANNOTATED_CATEGORY = "Annotated Commands"
_SIZE_SUFFIXES = {"K": 1_000, "M": 1_000_000, "G": 1_000_000_000}
def parse_size(value: str) -> int:
"""Parse an integer with an optional K/M/G suffix (a custom ``converter=``)."""
multiplier = _SIZE_SUFFIXES.get(value[-1:].upper(), 1)
digits = value[:-1] if multiplier != 1 else value
return int(digits) * multiplier
def parse_iso(value: str) -> datetime.datetime:
"""Parse an ISO-8601 timestamp (a ``converter=`` for an otherwise-unsupported type)."""
return datetime.datetime.fromisoformat(value)
@dataclass
class OutputOpts(ArgumentBlock):
"""A reusable argument block: subclass ``ArgumentBlock`` on a ``@dataclass``.
Each field becomes a flat command-line argument and the parsed values arrive
reconstructed as an ``OutputOpts`` instance. Several commands share these output
flags without repeating them, and a subcommand can inherit them from its parent
(see ``trace`` / ``cmd2_parent_args``).
"""
verbose: Annotated[bool, Option("-v", "--verbose", help_text="show detail")] = False
indent: Annotated[int, Option("--indent", help_text="indent width")] = 0
@dataclass
class RunOpts(ArgumentBlock):
"""A second block, declared *directly* on a subcommand alongside an inherited one.
A subcommand can combine its own block (whose flags live on the subcommand) with a
``cmd2_parent_args`` block inherited from its parent -- see ``trace_run``.
"""
retries: Annotated[int, Option("--retries", help_text="retry attempts on failure")] = 0
dry_run: Annotated[bool, Option("--dry-run", help_text="don't actually run")] = False
class AnnotatedExample(Cmd):
"""Demonstrates @with_annotated strengths over @with_argparser."""
intro = "Welcome! Try tab-completing the commands below.\n"
prompt = "annotated> "
def __init__(self) -> None:
super().__init__(include_ipy=True)
self._sports = ["Basketball", "Football", "Tennis", "Hockey"]
self._default_region = "staging"
# -- Type inference + typed parameters -----------------------------------
# With @with_argparser you'd set type=int and action='store_true', then read
# args.a / args.verbose off a Namespace. Here the types are inferred from the
# annotations and each parameter arrives as an ordinary typed local variable.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_add(self, a: int, b: int = 0, verbose: bool = False) -> None:
"""Add two integers. Types are inferred; parameters are typed locals.
``a``/``b`` infer ``type=int`` and ``verbose: bool`` infers a flag -- and
each is a normal typed argument, not a ``Namespace`` attribute to unpack.
Examples:
add 2 --b 3
add 10 --b 5 --verbose
"""
result = a + b
if verbose:
self.poutput(f"{a} + {b} = {result}")
else:
self.poutput(str(result))
# -- Enum auto-completion ------------------------------------------------
# With @with_argparser you'd list every member in choices=[...].
# Here the Enum type provides choices and validation automatically.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_paint(
self,
item: str,
color: Annotated[Color, Option("--color", "-c", help_text="Color to use")] = Color.blue,
level: LogLevel = LogLevel.info,
) -> None:
"""Paint an item. Enum types auto-complete their member values.
Try:
paint wall --color <TAB>
paint wall --level <TAB>
"""
self.poutput(f"[{level.value}] Painting {item} {color.value}")
# -- Path auto-completion ------------------------------------------------
# With @with_argparser you'd wire completer=Cmd.path_complete on each arg.
# Here the Path type triggers filesystem completion automatically.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_copy(self, src: Path, dst: Path) -> None:
"""Copy a file. Path parameters auto-complete filesystem paths.
Try:
copy ./<TAB> /tmp/<TAB>
"""
self.poutput(f"Copying {src} -> {dst}")
# -- Bool flags ----------------------------------------------------------
# With @with_argparser you'd spell out the action.
# Here bool defaults drive the generated boolean option.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_build(
self,
target: str,
verbose: bool = False,
color: bool = True,
) -> None:
"""Build a target. Bool flags are inferred from defaults.
``verbose: bool = False`` becomes a boolean optional flag.
``color: bool = True`` becomes a ``--color`` / ``--no-color`` style option.
Try:
build app --verbose --no-color
"""
parts = [f"Building {target}"]
if verbose:
parts.append("(verbose)")
if not color:
parts.append("(no color)")
self.poutput(" ".join(parts))
# -- Count action (-vvv) -------------------------------------------------
# action='count' turns a flag into a repeatable counter: each occurrence
# adds one, so ``-vvv`` arrives as 3. Set explicitly via Option(action=).
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_log(
self,
message: str,
verbosity: Annotated[int, Option("-v", "--verbose", action="count", help_text="raise verbosity; repeatable")] = 0,
) -> None:
"""Log a message. Repeat ``-v`` to raise verbosity (``-vvv`` -> 3).
Try:
log hello
log hello -vvv
"""
self.poutput(f"[v={verbosity}] {message}")
# -- List arguments ------------------------------------------------------
# With @with_argparser you'd set type=float and nargs='+'.
# Here list[float] does both at once.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_sum(self, numbers: list[float]) -> None:
"""Sum numbers. ``list[T]`` becomes ``nargs='+'`` automatically.
Try:
sum 1.5 2.5 3.0
"""
self.poutput(f"{' + '.join(str(n) for n in numbers)} = {sum(numbers)}")
# -- Variadic positional (*args) -----------------------------------------
# ``*args: T`` becomes a variadic positional (nargs='*') collected into a
# tuple -- zero or more values. A keyword-only option after ``*args`` stays
# an ordinary ``--flag``.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_cat(self, *files: str, number: bool = False) -> None:
"""Concatenate file names. ``*args`` accepts zero or more values.
Try:
cat a.txt b.txt c.txt
cat a.txt b.txt --number
cat
"""
if not files:
self.poutput("(no files)")
for index, name in enumerate(files, start=1):
self.poutput(f"{index}: {name}" if number else name)
# -- Optional positional (T | None) --------------------------------------
# A scalar annotated ``T | None`` becomes an optional positional (nargs='?'):
# zero or one value, defaulting to None when omitted. A very common CLI shape.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_status(self, service: str | None) -> None:
"""Show status for one service, or for all when the positional is omitted.
Try:
status
status web
"""
self.poutput(f"status: {service or 'all services'}")
# -- Ranged nargs (cmd2 extension) ---------------------------------------
# cmd2's patched argparse accepts a (min, max) nargs tuple. ``nargs=(2, 4)``
# takes 2 to 4 values; fewer or more is rejected. Plain argparse cannot do this.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_plot(self, points: Annotated[list[int], Argument(nargs=(2, 4))]) -> None:
"""Plot 2 to 4 integer points. cmd2 allows a ``(min, max)`` nargs range.
Try:
plot 1 2
plot 1 2 3 4
plot 1 # rejected: needs at least 2
"""
self.poutput(f"plotting {len(points)} points: {points}")
# -- Literal + Decimal ---------------------------------------------------
# Literal values become validated choices. Decimal values preserve precision.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_deploy(
self,
service: str,
mode: Literal["safe", "fast"] = "safe",
budget: Decimal = Decimal("1.50"),
timeout: Literal[0, 1, 2] = 1,
) -> None:
"""Deploy using Literal choices and Decimal parsing.
Try:
deploy api --mode <TAB>
deploy api --mode fast --budget 2.75
"""
self.poutput(f"Deploying {service} in {mode} mode with budget {budget} and timeout {timeout}")
# -- Optional value with const (nargs='?') + completion ------------------
# A scalar Option with nargs='?' + const is argparse's optional-value idiom:
# flag absent -> default, bare flag -> const, ``flag VALUE`` -> converted VALUE.
# A completion provider tab-completes that optional value -- because the
# option still consumes a value, a completer/choices_provider is kept (it is
# only rejected on value-less actions like store_true). The provider suggests
# common sizes without restricting input: ``--size 999`` is still accepted.
def common_sizes(self) -> Choices:
"""choices_provider suggesting common cache sizes (suggestions only, not a constraint)."""
return Choices.from_values(["32", "64", "128", "256", "512"])
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_cache(
self,
name: str,
size: Annotated[
int,
Option("--size", nargs="?", const=64, choices_provider=common_sizes, help_text="cache size in MB"),
] = 0,
) -> None:
"""Configure caching. ``--size`` takes an optional value and tab-completes it.
``--size`` absent -> 0; bare ``--size`` -> 64 (the const); ``--size 256``
-> 256 (the supplied value, converted to int).
Try:
cache build
cache build --size
cache build --size <TAB> # suggests 32 64 128 256 512
cache build --size 256
"""
self.poutput(f"{name}: cache size = {size} MB")
# -- Advanced: choices_provider + arg_tokens -----------------------------
# These cmd2-specific features still work via Annotated metadata.
def sport_choices(self) -> Choices:
"""choices_provider using instance data."""
return Choices.from_values(self._sports)
def context_choices(self, arg_tokens: dict[str, list[str]]) -> Choices:
"""arg_tokens-aware completion -- choices depend on prior arguments."""
sport = arg_tokens.get("sport", [""])[0]
if sport == "Basketball":
return Choices.from_values(["3-pointer", "dunk", "layup"])
if sport == "Football":
return Choices.from_values(["touchdown", "field-goal", "punt"])
return Choices.from_values(["play"])
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_score(
self,
sport: Annotated[
str,
Argument(
choices_provider=sport_choices,
help_text="Sport to score",
),
],
play: Annotated[
str,
Argument(
choices_provider=context_choices,
help_text="Type of play (depends on sport)",
),
],
points: int = 1,
) -> None:
"""Score a play. Demonstrates choices_provider and arg_tokens.
Try:
score <TAB>
score Basketball <TAB>
score Football <TAB>
"""
self.poutput(f"{sport}: {play} for {points} point(s)")
# -- Advanced: explicit completer ----------------------------------------
# A completer wires a completion function onto an argument directly. Unlike
# the Path type (which auto-completes), here a plain ``str`` gets filesystem
# completion only because ``completer=Cmd.path_complete`` asks for it.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_load(
self,
config: Annotated[str, Argument(completer=Cmd.path_complete, help_text="config file to load")],
) -> None:
"""Load a config. ``completer=`` attaches a completer to a ``str`` arg.
Try:
load ./<TAB>
"""
self.poutput(f"Loading config from {config}")
# -- Advanced: table_columns ---------------------------------------------
# A choices_provider can return CompletionItems carrying extra data, and
# table_columns names the columns shown alongside each completion.
def package_choices(self) -> Choices:
"""choices_provider returning CompletionItems with a description column."""
return Choices(
items=[
CompletionItem("numpy", table_data=["numerical computing"]),
CompletionItem("rich", table_data=["terminal formatting"]),
CompletionItem("cmd2", table_data=["interactive CLIs"]),
]
)
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_install(
self,
package: Annotated[
str,
Argument(
choices_provider=package_choices,
table_columns=["Description"],
help_text="package to install",
),
],
) -> None:
"""Install a package. ``table_columns`` adds context columns to completions.
Try:
install <TAB>
"""
self.poutput(f"Installing {package}")
# -- Advanced: converter (custom string -> value) ------------------------
# ``converter=`` replaces the inferred type= converter, giving parity with a
# hand-built ``add_argument(type=...)``: ``size`` parses a K/M/G suffix into an
# int, and ``--until`` makes the otherwise-unsupported ``datetime`` type legal
# (the converter owns the conversion, so any annotation type is allowed).
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_alloc(
self,
size: Annotated[int, Argument(converter=parse_size, help_text="size with optional K/M/G suffix")],
until: Annotated[
datetime.datetime | None,
Option("--until", converter=parse_iso, help_text="ISO-8601 expiry (an unsupported type)"),
] = None,
) -> None:
"""Allocate memory. ``converter=`` parses ``64K`` / ``2M`` into an int and ``--until`` into a datetime.
Try:
alloc 64K
alloc 2M --until 2025-06-16T09:30
"""
msg = f"Allocating {size} bytes"
self.poutput(f"{msg} until {until:%Y-%m-%d %H:%M}" if until else msg)
# -- Advanced: preprocess (normalize the raw token) ----------------------
# ``preprocess=`` only transforms the raw token before the inferred converter,
# so the inferred type, choices, and completion all survive: ``str.lower`` lets
# the ``Color`` Enum accept ``RED`` (keeping its choices), and
# ``os.path.expanduser`` expands ``~`` while ``Path`` keeps its completer.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_tag(
self,
color: Annotated[Color, Argument(preprocess=str.lower, help_text="color (case-insensitive)")],
path: Annotated[Path, Argument(preprocess=os.path.expanduser, help_text="file to tag (~ is expanded)")],
) -> None:
"""Tag a file with a color. ``preprocess=`` normalizes input while keeping Enum/Path inference.
Try:
tag RED ~/notes.txt
tag <TAB> # Color choices
tag red <TAB> # path completion
"""
self.poutput(f"Tagged {path} {color.value}")
# -- Namespace provider --------------------------------------------------
# This mirrors one of @with_argparser's advanced features.
def default_namespace(self) -> Namespace:
return Namespace(region=self._default_region)
@with_annotated(ns_provider=default_namespace)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_ship(self, package: str, region: str = "local") -> None:
"""Use ns_provider to prepopulate parser defaults at runtime.
Try:
ship parcel
ship parcel --region remote
"""
self.poutput(f"Shipping {package} to {region}")
# -- Unknown args --------------------------------------------------------
@with_annotated(with_unknown_args=True)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_flex(self, name: str, _unknown: list[str] | None = None) -> None:
"""Capture unknown arguments instead of failing parse.
Try:
flex alice --future-flag value
"""
self.poutput(f"name={name}")
if _unknown:
self.poutput(f"unknown={_unknown}")
# -- Subcommands ---------------------------------------------------------
# @with_annotated also supports typed subcommand trees.
@with_annotated(base_command=True)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_manage(self, verbose: bool = False, *, cmd2_subcommand_func: Callable[[], Any] | None = None) -> None:
"""Base command for annotated subcommands.
Try:
help manage
manage project add demo
"""
if verbose:
self.poutput("verbose mode")
if cmd2_subcommand_func:
cmd2_subcommand_func()
@with_annotated(subcommand_to="manage", base_command=True, help="manage projects")
def manage_project(self, *, cmd2_subcommand_func: Callable[[], Any] | None = None) -> None:
if cmd2_subcommand_func:
cmd2_subcommand_func()
@with_annotated(subcommand_to="manage project", help="add a project")
def manage_project_add(self, name: str) -> None:
self.poutput(f"project added: {name}")
@with_annotated(subcommand_to="manage project", help="list projects")
def manage_project_list(self) -> None:
self.poutput("project list: demo")
# -- Argument blocks: reuse a shared set of flags ------------------------
# A parameter typed as an ``ArgumentBlock`` dataclass expands its fields into
# flat arguments and arrives reconstructed as an instance. ``describe`` and
# ``dump`` reuse the same ``OutputOpts`` block instead of redeclaring its flags.
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_describe(self, item: str, out: OutputOpts) -> None:
"""Describe an item. ``out: OutputOpts`` expands a reusable argument block.
The block's fields (``--verbose``, ``--indent``) become flat options and
arrive as an ``OutputOpts`` instance -- the same block ``dump`` reuses.
Try:
describe widget --verbose --indent 4
"""
self.poutput(" " * out.indent + item + (" (verbose)" if out.verbose else ""))
@with_annotated
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_dump(self, path: str, out: OutputOpts) -> None:
"""Dump a path. Reuses the same ``OutputOpts`` block as ``describe`` -- no duplicated flags.
Try:
dump /etc/hosts --verbose
"""
self.poutput(" " * out.indent + f"dumping {path}" + (" (verbose)" if out.verbose else ""))
# -- Sharing a block with subcommands (cmd2_base_args / cmd2_parent_args) -
# A base command and its subcommands share one namespace. The parent names the
# inheritable block ``cmd2_base_args`` (its flags land on the parent parser); a
# subcommand receives the same block, reconstructed from what the parent parsed,
# by naming its parameter ``cmd2_parent_args`` -- without redeclaring the flags.
# The flags are supplied on the parent: ``trace --verbose run job``. The subcommand
# can also declare its own block (``RunOpts`` below), whose flags live on it.
@with_annotated(base_command=True)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_trace(self, cmd2_base_args: OutputOpts, *, cmd2_subcommand_func: Callable[[], Any] | None = None) -> None:
"""Base command whose subcommands inherit its ``OutputOpts`` block via ``cmd2_parent_args``.
Try:
help trace
trace --verbose --indent 2 run nightly
"""
if cmd2_base_args.verbose:
self.poutput("tracing enabled")
if cmd2_subcommand_func:
cmd2_subcommand_func()
@with_annotated(subcommand_to="trace", help="run a traced job")
def trace_run(self, name: str, cmd2_parent_args: OutputOpts, run: RunOpts) -> None:
"""Run a job, combining an inherited block with the subcommand's own ``RunOpts`` block.
``--verbose`` / ``--indent`` are parsed on ``trace`` (inherited via ``cmd2_parent_args``);
``--retries`` / ``--dry-run`` are this subcommand's own flags (the ``run`` block).
Try:
trace --verbose run nightly --retries 3
trace --indent 2 run nightly --dry-run
"""
mode = "dry-run" if run.dry_run else f"{run.retries} retries"
suffix = " (verbose)" if cmd2_parent_args.verbose else ""
self.poutput(" " * cmd2_parent_args.indent + f"run {name} [{mode}]" + suffix)
# -- Parser customization ------------------------------------------------
# The generated parser's help text and argument grouping are configurable
# without dropping down to a hand-built parser.
@with_annotated(
description="Open a network connection.",
epilog="Example: connect example.com --port 2222",
groups=(Group("host", "port", title="connection", description="where to connect"),),
)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_connect(self, host: str, port: int = 22, verbose: bool = False) -> None:
"""Connect to a host.
Try:
help connect
connect example.com --port 2222 --verbose
"""
msg = f"Connecting to {host}:{port}"
self.poutput(f"{msg} (verbose)" if verbose else msg)
# -- Mutually exclusive groups -------------------------------------------
# A plain (untitled) mutex rejects combinations of its members; required=True
# makes exactly one of them mandatory.
@with_annotated(
description="Export data in exactly one format.",
mutually_exclusive_groups=(Group("json", "csv", required=True),),
)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_export(
self,
name: str,
json: Annotated[str | None, Option(help_text="write JSON to this path")] = None,
csv: Annotated[str | None, Option(help_text="write CSV to this path")] = None,
) -> None:
"""Export a dataset to exactly one of --json PATH or --csv PATH (exclusive, required).
Try:
export sales --json out.json
export sales # rejected: one of --json/--csv is required
export sales --json a --csv b # rejected: not allowed together
"""
target = json or csv
fmt = "json" if json else "csv"
self.poutput(f"Exporting {name} to {target} as {fmt}")
# -- Custom formatter and parser classes ---------------------------------
# A custom help formatter or Cmd2ArgumentParser subclass can be supplied.
@with_annotated(
description="Generate a report.\n - line breaks here are preserved\n - thanks to the custom formatter",
formatter_class=VerbatimHelpFormatter,
parser_class=StrictArgumentParser,
)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_report(self, source: str, level: int = 1, verbose: bool = False) -> None:
"""Generate a report.
``help report`` shows the description with its line breaks intact
(VerbatimHelpFormatter), and StrictArgumentParser rejects abbreviated flags.
Try:
help report
report db --level 2 --verbose
report db --lev 2 # rejected: abbreviation disabled
"""
msg = f"Report for {source} at level {level}"
self.poutput(f"{msg} (verbose)" if verbose else msg)
# -- Preserve quotes -----------------------------------------------------
@with_annotated(preserve_quotes=True)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_echo(self, text: str) -> None:
"""Echo text with quotes preserved.
Try:
echo "hello world"
"""
self.poutput(text)
# -- Mutually exclusive group as a titled section ---------------------------
# A title/description on the mutex group renders it as a titled help section
# and nests it there in one declaration -- no paired groups= entry needed.
# The format flags are store_true so the mutex stays a clean [--json | --csv]
# (a bool flag would expand to --json/--no-json and make the group 4-way).
@with_annotated(
mutually_exclusive_groups=(Group("json", "csv", title="output", description="how to write results"),),
)
@cmd2.with_category(ANNOTATED_CATEGORY)
def do_render(
self,
name: str = "report",
json: Annotated[bool, Option(action="store_true")] = False,
csv: Annotated[bool, Option(action="store_true")] = False,
) -> None:
"""Render output; --json/--csv are exclusive and listed under 'output' in help.
Try:
help render
render --json
render
"""
fmt = "json" if json else "csv" if csv else "text"
self.poutput(f"Rendering {name} as {fmt}")
if __name__ == "__main__":
app = AnnotatedExample()
sys.exit(app.cmdloop())