Bug: 159984719

Clone this repo:
  1. dae325e Fix METADATA format for tools/external_updater by Dan Willemsen · 2 years, 10 months ago main master
  2. 409adeb Add go-subcommands module. by Sasha Smundak · 4 years ago
  3. a89b7af Merge upstream master, add mandatory files by Sasha Smundak · 4 years ago
  4. 4d740d6 Initial empty repository by Thomas Joseph Avila · 4 years ago
  5. 24aea2b Fix struct comment typo (#28) by Shawn Smith · 4 years, 9 months ago


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.


Set up a ‘print’ subcommand:

import (


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)
  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{}, "")

  ctx := context.Background()