Clone this repo:
  1. 24aea2b Fix struct comment typo (#28) by Shawn Smith · 4 years, 8 months ago main master 1.2.0 v1.2.0
  2. dd7622c Only print "<cmd> flags" suggestion when flags were defined (#27) by Eli Bendersky · 4 years, 8 months ago
  3. 636abe8 Allow users to override default help behavior. (#23) by Ian Lewis · 5 years ago
  4. d47216c Add a go.mod file for basic Go modules support. (#20) by M. J. Fromberger · 5 years ago 1.0.1 v1.0.1
  5. 46f0354 minor typo fix (#17) by nguyen-phillip · 6 years ago 1.0.0

subcommands

GoDoc
Subcommands is a Go package that implements a simple way for a single command to have many subcommands, each of which takes arguments and so forth.

This is not an official Google product.

Usage

Set up a ‘print’ subcommand:

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

  "github.com/google/subcommands"
)

type printCmd struct {
  capitalize bool
}

func (*printCmd) Name() string     { return "print" }
func (*printCmd) Synopsis() string { return "Print args to stdout." }
func (*printCmd) Usage() string {
  return `print [-capitalize] <some text>:
  Print args to stdout.
`
}

func (p *printCmd) SetFlags(f *flag.FlagSet) {
  f.BoolVar(&p.capitalize, "capitalize", false, "capitalize output")
}

func (p *printCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
  for _, arg := range f.Args() {
    if p.capitalize {
      arg = strings.ToUpper(arg)
    }
    fmt.Printf("%s ", arg)
  }
  fmt.Println()
  return subcommands.ExitSuccess
}

Register using the default Commander, also use some built in subcommands, finally run Execute using ExitStatus as the exit code:

func main() {
  subcommands.Register(subcommands.HelpCommand(), "")
  subcommands.Register(subcommands.FlagsCommand(), "")
  subcommands.Register(subcommands.CommandsCommand(), "")
  subcommands.Register(&printCmd{}, "")

  flag.Parse()
  ctx := context.Background()
  os.Exit(int(subcommands.Execute(ctx)))
}