aboutsummaryrefslogtreecommitdiffstats

subcmd

GoDoc Version

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

subcmd is a lightweight wrapper around Go’s standard library flag package. 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 regular standard library APIs.

Installation

go get git.eugenetriguba.com/subcmd

Example

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())))
}
$ go run main.go greet -name Alice
Hello, Alice!

Documentation

See the GoDoc documentation for full documentation.