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
|
# subcmd
[](https://godoc.org/git.sr.ht/~eugenetriguba/subcmd)

[](https://builds.sr.ht/~eugenetriguba/subcmd/commits/main?)
A simple and flexible subcommand framework for Go, built on top of the standard library's `flag` package.
## Why subcmd?
There are more full-featured CLI libraries for Go, like
[cobra](https://github.com/spf13/cobra). If you need complex features, use one
of those.
subcmd is a lightweight wrapper around Go's standard library `flag` package.
The entire implementation is a single file with zero production dependencies.
It provides subcommand registration and execution, built-in help and flag
listing commands, and command groups for organization. Because it wraps
`flag.FlagSet`, you use the standard library APIs you already know.
## Installation
```bash
go get git.sr.ht/~eugenetriguba/subcmd
```
## Example
```go
package main
import (
"context"
"flag"
"fmt"
"os"
"git.sr.ht/~eugenetriguba/subcmd"
)
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" }
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())))
}
```
```bash
$ go run main.go greet -name Alice
Hello, Alice!
```
## Documentation
See the [GoDoc documentation](https://godoc.org/git.sr.ht/~eugenetriguba/subcmd)
for full documentation.
|