Chromium Code Reviews| Index: go/src/infra/tools/cr/lib/subcommand/subcommand.go |
| diff --git a/go/src/infra/tools/cr/lib/subcommand/subcommand.go b/go/src/infra/tools/cr/lib/subcommand/subcommand.go |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..956d831e16846ff320544c6f0128d647fec69da9 |
| --- /dev/null |
| +++ b/go/src/infra/tools/cr/lib/subcommand/subcommand.go |
| @@ -0,0 +1,56 @@ |
| +// Copyright 2016 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +/* |
| +Library for defining subcommands in a structured way. |
| +*/ |
| + |
| +// Package subcommand provides a simple framework for defining subcommands. |
| +package subcommand |
| + |
| +import ( |
| + "flag" |
| + "fmt" |
| +) |
| + |
| +// Subcommand represents a single subcommand, with short and long versions of |
| +// its help (usage) text, a function which adds command-line flags to a |
| +// pre-existing flag.FlagSet, and a function which will be called to actually |
| +// execute the subcommand. |
| +type Subcommand struct { |
|
seanmccullough1
2016/04/29 00:54:36
SubCmd would be a fine name too.
|
| + ShortHelp string |
|
seanmccullough1
2016/04/29 00:54:36
godoc for ShortHelp or don't export it (doesn't ap
agable
2016/05/05 23:59:43
main.go directly access ShortHelp to print the lis
|
| + LongHelp string |
| + flagFn func(*flag.FlagSet) |
| + runFn func(*flag.FlagSet) error |
| +} |
| + |
| +// New creates a new Subcommand struct and returns a reference to it. |
| +func New(shortHelp string, longHelp string, flagFn func(*flag.FlagSet), runFn func(*flag.FlagSet) error) *Subcommand { |
| + return &Subcommand{shortHelp, longHelp, flagFn, runFn} |
| +} |
| + |
| +// Help prints the short and long help messages, as well as the autogenerated |
| +// flags documentation. |
| +func (c *Subcommand) Help(flags *flag.FlagSet) { |
| + fmt.Println(c.ShortHelp) |
|
seanmccullough1
2016/04/29 00:54:36
fmt.Printf("%s\n\n%s\n\n", c.ShortHelp, c.LongHelp
agable
2016/05/05 23:59:43
Done.
|
| + fmt.Println("") |
| + fmt.Println(c.LongHelp) |
| + fmt.Println("") |
| + flags.PrintDefaults() |
| +} |
| + |
| +// InitFlags adds the subcommand's flags to a FlagSet, if flagFn is defined. |
| +func (c *Subcommand) InitFlags(flags *flag.FlagSet) { |
| + if c.flagFn != nil { |
| + c.flagFn(flags) |
| + } |
| +} |
| + |
| +// Run executes the subcommand's runFn, if it is defined. |
| +func (c *Subcommand) Run(flags *flag.FlagSet) error { |
| + if c.runFn != nil { |
| + return c.runFn(flags) |
| + } |
| + return nil |
| +} |