aboutsummaryrefslogtreecommitdiffstats
path: root/doc.go
blob: d38be35738a8868efcf723e33bf5379d2d5b6a09 (plain) (blame)
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
// Package subcmd provides a simple and flexible subcommand framework built on
// top of the standard library's flag package.
//
// This package makes it easy to build command-line applications with multiple
// subcommands, similar to tools like git, docker, or kubectl. Each subcommand
// can have its own flags and logic while sharing common top-level flags.
//
// # Basic Usage
//
// To use subcmd, implement the Command interface for each subcommand and
// register them with a Registry. The framework handles parsing, flag management,
// and command execution.
//
//	type greetCmd struct {
//		name string
//	}
//
//	func (g *greetCmd) Name() string { return "greet" }
//	func (g *greetCmd) Synopsis() string { return "greet a person" }
//	func (g *greetCmd) Usage() string {
//		return `greet -name <name>:
//		Prints a greeting message.
//	`
//	}
//
//	func (g *greetCmd) SetFlags(f *flag.FlagSet) {
//		f.StringVar(&g.name, "name", "World", "name to greet")
//	}
//
//	func (g *greetCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
//		fmt.Printf("Hello, %s!\n", g.name)
//		return subcmd.ExitSuccess
//	}
//
//	func main() {
//		subcmd.Register(&greetCmd{}, "")
//		subcmd.Register(subcmd.HelpCommand(), "")
//		os.Exit(int(subcmd.Execute(context.Background())))
//	}
//
// # Command Groups
//
// Commands can be organized into groups for better help output:
//
//	subcmd.Register(&listCmd{}, "Database Commands")
//	subcmd.Register(&migrateCmd{}, "Database Commands")
//	subcmd.Register(&statusCmd{}, "Utility Commands")
//
// # Built-in Commands
//
// The package provides several built-in commands:
//
//   - HelpCommand() - Display help for all commands or a specific command
//   - ManHelpCommand(prefix) - Open man pages for commands (e.g., "myapp" and "myapp-subcommand")
//   - CommandsCommand() - List all available command names
//   - FlagsCommand() - List all top-level flags
//
// # Registry
//
// While the package provides a default registry for convenience, you can
// create custom registries for more control:
//
//	registry := subcmd.NewRegistry(subcmd.WithOutput(customWriter))
//	registry.Register(&myCmd{}, "")
//	status := registry.Execute(ctx)
//
// This is useful for testing or when building applications that need multiple
// independent command sets.
//
// # Top-level Flags
//
// To add top-level flags (flags that apply before the subcommand), use the
// Flags() accessor:
//
//	verbose := subcmd.Flags().Bool("v", false, "verbose output")
//	subcmd.Register(&myCmd{}, "")
//	os.Exit(int(subcmd.Execute(context.Background())))
package subcmd