-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc.go
More file actions
673 lines (673 loc) · 25.9 KB
/
doc.go
File metadata and controls
673 lines (673 loc) · 25.9 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
// Package cli provides a composable CLI framework built on small interfaces.
//
// Small interfaces. Big CLIs.
//
// Commands are structs. Capabilities are interfaces. The framework discovers
// what your command can do through type assertions on 30+ optional interfaces —
// no base struct to embed, no configuration DSL.
//
// # Core Interface
//
// Every command must implement [Commander]:
//
// type Commander interface {
// Run(ctx context.Context) error
// }
//
// [RunFunc] adapts a plain function into a Commander for simple cases.
// Positional arguments are injected via [Args] struct fields or accessed
// via [bind.Get] from the context.
//
// # Discovery Interfaces
//
// Implement any combination of these optional interfaces to declare
// metadata, subcommands, aliases, examples, and hidden status:
//
// - [Namer] — override the command name (default: lowercase struct type name)
// - [Descriptor] — provide a one-line description
// - [LongDescriptor] — provide extended description for help output
// - [Aliaser] — declare alternate names
// - [Subcommander] — return subcommands
// - [Hider] — hide the command from help output
// - [Exampler] — provide usage examples
// - [Versioner] — report a version string via --version / -V
// - [Deprecator] — mark a command as deprecated with a warning message
// - [Categorizer] — group subcommands under headings in help output
// - [Fallbacker] — provide a fallback subcommand when no name matches
// - [Exiter] — control error printing and process exit in [ExecuteAndExit]
// - [Discoverer] — provide runtime-discovered commands (plugins)
//
// # Lifecycle Interfaces
//
// Execution order: Init → [parse] → Default → Validate → Before → Run → After
//
// - [Initializer] — run setup before parsing (parent-first), returns modified context
// - [Defaulter] — compute defaults after parsing, before validation
// - [Validator] — validate state after defaulting, before Before hooks
// - [Beforer] — run setup logic before Run (parent-first), returns modified context
// - [Afterer] — run teardown logic after Run (child-first, always runs)
//
// # Flags
//
// The default flag parser reads struct tags:
//
// type ServeCmd struct {
// Port int `flag:"port" short:"p" default:"8080" help:"Port to listen on" env:"PORT"`
// Host string `flag:"host" default:"localhost" help:"Host to bind to"`
// Tags []string `flag:"tag" short:"t" help:"Tags to apply (repeatable)"`
// Env map[string]string `flag:"env" help:"Environment variables as key=value"`
// Format string `flag:"format" enum:"text,json,yaml" default:"text" help:"Output format"`
// Verbose int `flag:"verbose" short:"v" counter:"" help:"Increase verbosity"`
// Color bool `flag:"color" default:"true" negate:"" help:"Colorize output"`
// }
//
// Supported types: string, int, int64, float64, bool, time.Duration,
// time.Time, *url.URL, net.IP, slices of any scalar type, map[string]string,
// and any type implementing [FlagUnmarshaler].
//
// Struct tag keys:
//
// - flag — the flag name (if empty, derived from field name: OutputFormat → output-format)
// - short — single-character short form
// - default — default value if not provided
// - help — description shown in help output
// - env — environment variable name; standalone (without flag/arg) for env/config/default-only fields
// - enum — comma-separated list of allowed values
// - required — require the flag (presence-based: `required:""`)
// - counter — increment an int on each occurrence (-vvv) (presence-based)
// - negate — add a --no- prefix that sets a bool to false (presence-based)
// - alt — comma-separated additional long flag names (e.g. "output,out")
// - sep — separator for splitting a single value into slice elements (e.g. ",")
// - hidden — hide the flag from help output (presence-based)
// - deprecated — message shown when the flag is used; prints a warning to stderr
// - category — group heading for the flag in help output
// - mask — displayed instead of default in help (e.g. "****" for secrets)
// - placeholder — value name shown in help (e.g. "PORT" in --port PORT)
// - prefix — flag name prefix for named struct fields (e.g. "db-" yields --db-host)
//
// Priority: explicit flag > env var > config > default > zero value.
//
// Flags are optional by default. Use `required:""` to make a flag mandatory.
// This contrasts with positional arguments, which are required by default.
//
// Use [WithEnvVarPrefix] to scope all env var lookups under a common prefix.
// For example, WithEnvVarPrefix("APP_") causes `env:"PORT"` to look up APP_PORT.
//
// Flags can appear anywhere — before or after subcommand names.
//
// The framework performs strict tag validation at parse time. Invalid
// combinations (flag + arg, required + default, flag-only tags without
// flag, etc.) return [ErrInvalidTag].
//
// # Env-Only Fields
//
// A field with an env tag but no flag or arg tag is env/config/default-only.
// It does not appear in help output and cannot be passed via command-line
// arguments. This is useful for secrets that should never appear in shell
// history:
//
// type DeployCmd struct {
// Token string `env:"DEPLOY_TOKEN" required:""`
// Env string `flag:"env" enum:"prod,staging,dev" help:"Target environment"`
// }
//
// The logical name is derived from the field name (Token → token) and is used
// for config resolver lookups and context storage via [Set]/[Get].
//
// Priority for env-only fields: env var > config > default > zero value.
//
// # Positional Arguments
//
// Named positional arguments use the arg struct tag:
//
// type CopyCmd struct {
// Src string `arg:"src" help:"Source file"`
// Dst string `arg:"dst" help:"Destination file"`
// }
//
// Arguments are assigned in struct field order. Non-slice args are required
// by default (use `required:"false"` to make optional). A slice field consumes
// all remaining arguments.
//
// To capture remaining arguments after named args, use a [cli.Args] field
// (no tag needed):
//
// type CopyCmd struct {
// Src string `arg:"src"` // args[0]
// Dst string `arg:"dst"` // args[1]
// Args cli.Args // args[2:] — no tag required
// }
//
// [Args] provides convenience methods: [Args.First], [Args.Last], [Args.Get],
// [Args.Len], [Args.Empty], [Args.Contains], [Args.Index], and [Args.Tail].
//
// Only one [Args] field is allowed per command.
//
// # Subcommands
//
// Subcommands can be declared via the [Subcommander] interface or by embedding
// struct fields that implement [Commander]:
//
// type AppCmd struct {
// Verbose bool `flag:"verbose"`
// Serve ServeCmd // implements Commander → subcommand
// Config ConfigCmd // implements Commander → subcommand
// }
//
// Named struct fields whose type implements [Commander] become subcommands.
// The command name comes from the embedded type (via [Namer] or derived from
// the type name). Anonymous embedded structs are for flag promotion, not
// subcommands.
//
// Embedded subcommands, [Subcommander] interface, and [Discoverer] interface
// can be used together. Name collisions between embedded fields and Subcommander
// return an error — fix by removing the duplicate. Discovered plugins silently
// yield to built-in commands since users don't control plugin names.
//
// # Branching Arguments
//
// When a command has both positional arg fields and embedded Commander fields,
// it becomes a "branching" command. Positional args are consumed before
// subcommand resolution, enabling patterns like:
//
// app user 42 delete --force
// app user 42 rename newname
//
// Definition:
//
// type UserCmd struct {
// ID int `arg:"id"` // consumed first
// Delete DeleteCmd // subcommand, resolved after ID
// Rename RenameCmd // subcommand, resolved after ID
// }
//
// Subcommands access parent arg values via context:
//
// func (d *DeleteCmd) Run(ctx context.Context) error {
// userID := cli.Get[int](ctx, "id")
// // ...
// }
//
// Branching is automatic — no special tag required. The framework detects
// the presence of both arg-tagged fields and Commander fields.
//
// # Embedded Structs and Prefix
//
// Anonymous embedded structs have their flags promoted, just like Go's own
// field promotion:
//
// type OutputFlags struct {
// Format string `flag:"format" enum:"json,table" default:"table" help:"Output format"`
// }
// type ListCmd struct {
// OutputFlags // promoted: --format works as if declared on ListCmd
// Limit int `flag:"limit" default:"50"`
// }
//
// Named struct fields with the prefix tag namespace their flags:
//
// type DBFlags struct {
// Host string `flag:"host" default:"localhost" help:"Database host"`
// Port int `flag:"port" default:"5432" help:"Database port"`
// }
// type ServeCmd struct {
// DB DBFlags `prefix:"db-"` // --db-host, --db-port
// Port int `flag:"port" default:"8080" help:"Listen port"`
// }
//
// Prefixes nest: a prefix:"a-" containing prefix:"b-" yields --a-b-name.
// When an outer and embedded field share a flag name, the outer field wins
// (matching Go's own promotion semantics).
//
// # Inheritance
//
// Flags flow from parent commands to child subcommands via automatic flag
// inheritance: when a parent and child both declare a flag with the same
// name and type, the child inherits the parent's parsed value if the
// child's flag was not explicitly provided via CLI args or env var.
// The child's flag still appears in help output and accepts CLI args normally.
//
// type App struct {
// Env string `flag:"env" required:"" enum:"dev,qa,prod" help:"Target environment"`
// }
// type ServeCmd struct {
// Env string `flag:"env" help:"Target environment"`
// Port int `flag:"port" default:"8080" help:"Listen port"`
// }
//
// To inherit a parent flag without exposing it as a child flag, use a
// hidden flag with the same name:
//
// type ServeCmd struct {
// Env string `flag:"env" hidden:""`
// Port int `flag:"port" default:"8080" help:"Listen port"`
// }
//
// Priority for automatic flag inheritance:
// explicit child flag > child env var > inherited from parent > child default > zero value.
//
// # Context Values
//
// The framework provides [Set], [Get], and [Lookup] for sharing values between
// commands via context. Use these in [Beforer.Before] hooks to share computed
// values (database connections, loggers, etc.) with downstream commands:
//
// func (a *App) Before(ctx context.Context) (context.Context, error) {
// db, _ := sql.Open("postgres", a.DSN)
// return cli.Set(ctx, "db", db), nil
// }
//
// func (s *ServeCmd) Run(ctx context.Context) error {
// db := cli.Get[*sql.DB](ctx, "db")
// // ...
// }
//
// Three functions are provided:
//
// - [Set] — store a named value in the context (returns new context)
// - [Get] — retrieve a value by name; returns zero value if missing or type mismatch
// - [Lookup] — retrieve a value by name; returns (value, ok) for safe checking
//
// Note: Flag values are NOT stored in context. Access flags via struct fields
// directly, using flag inheritance for child commands that need parent values.
// Positional arg values ARE stored in context to support branching command
// patterns (e.g., "app user 42 delete") where child commands need parent args.
//
// # Config
//
// Flag values can be loaded from external configuration sources via a
// [ConfigResolver]. A resolver is a single function:
//
// type ConfigResolver func(key ConfigKey) (value string, found bool)
//
// Given a [ConfigKey], it returns the string value and whether it was found.
// The key provides both the full flag name ([ConfigKey.Name]) and decomposed
// parts ([ConfigKey.Parts]) for resolvers backed by nested formats.
// The framework handles all type conversion, validation, required checks,
// and enum enforcement — the resolver only needs to return strings.
//
// Priority chain: explicit CLI flag > env var > config > default > zero value.
//
// Set a global resolver via [WithConfigResolver]:
//
// f, _ := os.Open("config.json")
// resolver, _ := config.FromJSON(f)
// cli.Execute(ctx, root, os.Args[1:],
// cli.WithConfigResolver(resolver),
// )
//
// Or implement [ConfigProvider] on a command for per-command resolvers:
//
// func (c *ServeCmd) ConfigResolver() cli.ConfigResolver {
// return config.FromMap(map[string]string{"port": "9090"})
// }
//
// [ConfigProvider.ConfigResolver] is called after CLI args are parsed, so
// a --config flag can specify the config file path dynamically:
//
// type App struct {
// ConfigPath string `flag:"config" help:"Path to config file"`
// Port int `flag:"port" help:"Port to listen on"`
// }
//
// func (a *App) ConfigResolver() cli.ConfigResolver {
// if a.ConfigPath == "" {
// return nil
// }
// f, _ := os.Open(a.ConfigPath)
// resolver, _ := config.FromJSON(f)
// return resolver
// }
//
// Command-level resolvers take priority over the global resolver. Use
// [config.Chain] to try multiple sources in order:
//
// resolver := config.Chain(
// config.FromMap(overrides),
// jsonResolver,
// )
//
// The [config] subpackage ships [config.FromMap], [config.FromJSON], and
// [config.Chain]. Because [ConfigResolver] is a plain function and
// [config.FromMap] accepts any map[string]string, adding support for any
// configuration format — YAML, TOML, HCL, .env files, remote stores —
// is a matter of decoding into a map and calling [config.FromMap].
// See the [config] package documentation for copy-paste adapter examples.
//
// # Flag Groups
//
// Flags can be constrained to enforce relationships using [FlagGrouper]:
//
// func (c *Cmd) FlagGroups() []cli.FlagGroup {
// return []cli.FlagGroup{
// cli.MutuallyExclusive("json", "yaml", "text"),
// cli.RequiredTogether("username", "password"),
// cli.OneRequired("file", "stdin"),
// }
// }
//
// Three constraint kinds are supported:
//
// - [MutuallyExclusive] — at most one flag in the group may be set
// - [RequiredTogether] — if any flag in the group is set, all must be set
// - [OneRequired] — exactly one flag in the group must be set
//
// Validation runs after flag parsing and inheritance, before [Validator].
//
// # Plugins
//
// Commands can be extended at runtime with external executables (plugins).
// A command that implements [Discoverer] provides additional subcommands
// discovered at runtime, merged with any static subcommands from [Subcommander].
// Built-in commands always take priority on name collisions.
//
// The [Discover] function scans directories and optionally the system
// PATH for plugin executables:
//
// func (a *App) Discover() ([]cli.Commander, error) {
// return cli.Discover(
// cli.WithDirs(cli.DefaultDirs("myapp")...),
// cli.WithPATH("myapp"),
// )
// }
//
// [DefaultDirs] returns conventional plugin directories in priority order:
//
// 1. ./<name>/plugins — project-level (highest priority)
// 2. $HOME/.config/<name>/plugins — user-level
// 3. /etc/<name>/plugins — system-level (Unix only)
//
// These paths are configurable. Use [WithDir] and [WithDirs] to specify
// custom directories in any order, and [WithPATH] to optionally scan PATH
// for executables matching "<prefix>-<command>".
//
// # Plugin Metadata Protocol
//
// When a plugin is discovered, the framework executes it with the --cli-info
// flag (customizable via [WithInfoFlag]) and expects optional JSON:
//
// {"name":"deploy","description":"Deploy to cloud","aliases":["d"]}
//
// If the plugin does not support the flag or returns invalid JSON, it still
// works — it just has no description or aliases in help output. The only
// requirement for a plugin is that it be an executable file.
//
// This means plugins can be written in any language:
//
// #!/bin/bash
// if [ "$1" = "--cli-info" ]; then
// echo '{"name":"deploy","description":"Deploy to cloud environments"}'
// exit 0
// fi
// echo "deploying to $1..."
//
// # Plugin Discovery Modes
//
// Directory-based discovery (primary): all executable files in the scanned
// directories become plugins. The filename is the command name.
//
// PATH-based discovery (via [WithPATH]): executables matching "<prefix>-*"
// on the system PATH are discovered. The prefix and hyphen are stripped to
// derive the command name (e.g., "myapp-deploy" → "deploy").
//
// Priority: directories are scanned first in the order added. PATH results
// have lower priority than any directory result. First match wins on name
// collision.
//
// # Enumerating All Subcommands
//
// [AllSubcommands] returns the merged set of static and discovered
// subcommands for a command. This is useful for custom [HelpRenderer]
// implementations, documentation generators, and shell completion scripts:
//
// subs, err := cli.AllSubcommands(cmd)
//
// # Extensibility
//
// Every major subsystem is replaceable:
//
// - [FlagParser] — replace the flag parsing engine per-command or globally
// - [HelpRenderer] — replace help rendering per-command or globally
// - [Helper] — override help text for a single command
// - [HelpAppender] / [HelpPrepender] — add custom sections to the default help output
// - [Middlewarer] — wrap the run function with middleware
// - [Suggester] — custom "did you mean?" per-command
//
// Global overrides are set via [Option] functions passed to [Execute]:
//
// cli.Execute(ctx, root, os.Args[1:],
// cli.WithStdout(os.Stdout),
// cli.WithFlagParser(myParser),
// cli.WithShortOptionHandling(true),
// cli.WithPrefixMatching(true),
// )
//
// # Documentation Generation
//
// The doc subpackage generates documentation from the command tree:
//
// doc.GenMarkdown(root) // markdown for a single command
// doc.GenMarkdownTree(root, "docs/") // markdown files for all commands
// doc.GenManPage(root, header) // man page for a single command
// doc.GenManTree(root, "man/", header) // man pages for all commands
//
// Hidden commands and flags are excluded from generated documentation.
//
// # Shell Completion
//
// The completion subpackage generates shell completion scripts:
//
// completion.Bash(root, "myapp") // bash completion script
// completion.Zsh(root, "myapp") // zsh completion script
// completion.Fish(root, "myapp") // fish completion script
// completion.PowerShell(root, "myapp") // PowerShell completion script
//
// Generated scripts call the binary at runtime via the __complete protocol:
// when the binary receives "__complete" as the first argument, it runs
// [RuntimeComplete] instead of normal execution. This avoids side effects
// (no lifecycle hooks, flag parsing, or validation) and provides dynamic
// completions based on the current command tree.
//
// Commands implementing [Completer] can provide custom completion candidates.
// When a command implements Completer, its Complete method is called during
// tab-completion. Return a [CompletionResult] with candidates, optional active
// help messages, and a directive. Use the convenience constructors [Completions],
// [CompletionsWithDesc], and [NoCompletions] to build results:
//
// func (c *DeployCmd) Complete(ctx context.Context, args []string) cli.CompletionResult {
// return cli.Completions("dev", "staging", "prod").
// WithActiveHelp("Select deployment environment")
// }
//
// Active help messages are displayed by the shell as guidance during completion.
// If Complete returns an empty result (or [NoCompletions]), the framework falls
// back to static completion of subcommands and flags.
//
// For dynamic flag value completion, implement [FlagCompleter]:
//
// func (c *DeployCmd) CompleteFlag(ctx context.Context, flag, value string) cli.CompletionResult {
// if flag == "region" {
// return cli.CompletionsWithDesc(
// cli.Completion{Value: "us-east-1", Description: "N. Virginia"},
// cli.Completion{Value: "us-west-2", Description: "Oregon"},
// )
// }
// return cli.NoCompletions()
// }
//
// Use [FlagNameFor] to safely reference flags without hardcoding names:
//
// if flag == cli.FlagNameFor(c, &c.Region) {
// return cli.Completions("us-east-1", "us-west-2")
// }
//
// # Error Handling
//
// The framework provides hierarchical sentinel errors for precise error handling.
// Each specific error wraps a parent category, enabling checks at any granularity:
//
// // Check specific error
// if errors.Is(err, cli.ErrRequiredArg) { /* missing argument */ }
//
// // Check error category
// if errors.Is(err, cli.ErrArgument) { /* any argument error */ }
//
// Error categories and their specific errors:
//
// - [ErrFlag] → [ErrUnknownFlag], [ErrFlagRequiresVal], [ErrRequiredFlag], [ErrInvalidFlagValue]
// - [ErrArgument] → [ErrRequiredArg], [ErrInvalidArgValue], [ErrArgCount]
// - [ErrCommand] → [ErrUnknownCommand]
// - [ErrFlagGroup] → [ErrMutuallyExclusive], [ErrRequiredTogether], [ErrOneRequired]
//
// # Help and Usage Signals
//
// Commands can return special signals to display help or usage:
//
// func (c *Cmd) Run(ctx context.Context) error {
// if len(c.Args) == 0 {
// return cli.ErrShowHelp // show help, exit 1
// }
// return nil
// }
//
// Four signals control help/usage display:
//
// - [ShowHelp] — full help, exit code 0 (explicit help request)
// - [ErrShowHelp] — full help, exit code 1 (error condition)
// - [ShowUsage] — brief usage line, exit code 0
// - [ErrShowUsage] — brief usage line, exit code 1
//
// Use [ShowHelp] for explicit help requests (e.g., a "help" subcommand).
// Use [ErrShowHelp] when showing help due to an error (e.g., missing required
// subcommand on bare invocation).
//
// # Custom Exit Codes
//
// Return an error implementing [ExitCoder] to control the process exit code:
//
// func (c *Cmd) Run(ctx context.Context) error {
// if err := doWork(); err != nil {
// return cli.Exit("operation failed", 2)
// }
// return nil
// }
//
// Use [Exit] for simple messages or [Exitf] for formatted messages:
//
// return cli.Exitf(3, "port %d already in use", port)
//
// # Silencing Output
//
// Control error output with [WithSilenceErrors] and [WithSilenceUsage]:
//
// cli.Execute(ctx, root, args,
// cli.WithSilenceErrors(true), // suppress "Error: ..." message
// cli.WithSilenceUsage(true), // suppress "Run 'app --help' for usage" hint
// )
//
// For complete control over error handling, implement [Exiter] on the root
// command. When ExecuteAndExit encounters an error and the root implements
// Exiter, it delegates entirely to Exit(err) instead of printing the error
// and calling os.Exit.
//
// # Execution Functions
//
// Two functions run the command tree:
//
// - [Execute] — runs the command and returns the error (for testing)
// - [ExecuteAndExit] — runs the command, prints errors, and calls os.Exit
//
// Use Execute in tests for direct error inspection. Use ExecuteAndExit in
// main() for proper exit code handling.
//
// # Dependency Injection
//
// The framework provides built-in dependency injection via [WithBindings]:
//
// db, _ := sql.Open("postgres", connStr)
// cli.Execute(ctx, root, args,
// cli.WithBindings(
// bind.Value(db), // bind by concrete type
// bind.Interface(cache, (*Cache)(nil)), // bind to interface
// bind.Singleton(newLogger), // lazy singleton
// ),
// )
//
// Bound values are injected into struct fields across all commands in the
// chain. Fields with flag, arg, or env tags are skipped. The injector matches
// by exact type first, then by interface compatibility.
//
// Four binding modes are available:
//
// - bind.Value(v) — register a value matched by concrete type
// - bind.Interface(v, (*Iface)(nil)) — register a value as an interface type
// - bind.Provider(func() (T, error)) — lazy factory called on each injection
// - bind.Singleton(func() (T, error)) — lazy factory called once, cached
//
// [Args] is auto-bound, so commands can declare an Args field without tags:
//
// type GrepCmd struct {
// Pattern string `arg:"pattern"`
// Args cli.Args // automatically populated with remaining args
// }
//
// Bound values are also accessible via context lookup in Run:
//
// func (c *Cmd) Run(ctx context.Context) error {
// db := bind.Get[*sql.DB](ctx)
// // ...
// }
//
// # Middleware
//
// Commands implementing [Middlewarer] can wrap their Run function:
//
// func (c *Cmd) Middleware() []func(cli.RunFunc) cli.RunFunc {
// return []func(cli.RunFunc) cli.RunFunc{
// loggingMiddleware,
// timingMiddleware,
// }
// }
//
// Middleware is applied in order (first wraps outermost). This enables
// cross-cutting concerns like logging, timing, error recovery, and
// transaction management without modifying Run.
//
// # Leaf Inspection
//
// Parent [Beforer.Before] hooks can inspect the resolved leaf command:
//
// func (a *App) Before(ctx context.Context) (context.Context, error) {
// leaf := cli.Leaf(ctx)
// if _, ok := leaf.(Authenticated); ok {
// return authenticate(ctx)
// }
// return ctx, nil
// }
//
// This enables interface-based routing: define a marker interface like
// Authenticated, implement it on commands that require auth, and handle
// the concern in a single parent Before hook. The pattern avoids duplicating
// authentication logic across every command that needs it.
//
// # Meta Struct
//
// For rapid prototyping, embed [Meta] to get default implementations for
// common metadata interfaces:
//
// type ServeCmd struct {
// cli.Meta
// Port int `flag:"port" default:"8080"`
// }
//
// cmd := &ServeCmd{
// Meta: cli.Meta{}.
// WithName("serve").
// WithDescription("Start the server").
// WithAliases("s"),
// }
//
// [Meta] implements [Namer], [Descriptor], [LongDescriptor], [Aliaser],
// [Categorizer], [Hider], [Deprecator], and [Exampler]. Override any method
// by defining it on your command type.
package cli