aboutsummaryrefslogtreecommitdiffstats
path: root/README.md
blob: 75b58a9d425fbb6786743fa9e7dc25dd4e769b24 (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
# subcmd

[![GoDoc](https://pkg.go.dev/badge/git.eugenetriguba.com/subcmd.svg)](https://pkg.go.dev/git.eugenetriguba.com/subcmd)
![Version](https://img.shields.io/badge/version-0.5.0-blue)

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 more complex features,
those would be a better solution.

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.eugenetriguba.com/subcmd
```

## Example

```go
package main

import (
    "context"
    "flag"
    "fmt"
    "os"

    "git.eugenetriguba.com/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://pkg.go.dev/git.eugenetriguba.com/subcmd)
for full documentation.