commit | 6d320cbca5f5d8baac833a124259fb9fa598f253 | [log] [tgz] |
---|---|---|
author | Timothy Cyrus <[email protected]> | Thu Feb 25 09:19:19 2016 -0500 |
committer | Timothy Cyrus <[email protected]> | Thu Feb 25 09:19:19 2016 -0500 |
tree | 5a882710b82441102926a29cdef13b99566fe6ba | |
parent | 24b16f685f730742358af168eb4670cecd40bb7d [diff] |
Update README.md Added Syntax Highlighting
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 (
"flag"
"fmt"
"os"
"strings"
"github.com/google/subcommands"
"golang.org/x/net/context"
)
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(&print{}, "")
ctx := context.Background()
os.Exit(int(subcommands.Execute(ctx)))
}