Debian Codegraph @

examples/annotated_example.py

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