Organize the files a bit better
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by spf13 · committed by spf13 · parent 88b9d2e · Browse files · 3 files·+487 added−445 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+487 added−445 removed
- other:+487 added−445 removed
Provenance
- Commit
62fb674- Tree
00cbb87- Author
spf13 <steve.francia@gmail.com>- Committer
spf13 <steve.francia@gmail.com>- Parent
88b9d2e
3 files changed+487 added−445 removed
modified:cobra.go-445 removed
15 unmodified lines16 17 package cobra18 19 import (20- "bytes"21- "fmt"22- flag "github.com/spf13/pflag"20 "io"24- "os"21 "reflect"22 "strconv"23 "strings"24 "text/template"25 )26 31-var _ = flag.ContinueOnError32-33-// A Commander holds the configuration for the command line tool.34-type Commander struct {35- // A Commander is also a Command for top level and global help & flags36- Command37-38- args []string39- output *io.Writer // nil means stderr; use out() accessor40- UsageFunc func(*Command) error // Usage can be defined by application41- UsageTemplate string // Can be defined by Application42- HelpTemplate string // Can be defined by Application43-}44-45-// Provide the user with a new commander.46-func NewCommander() (c *Commander) {47- c = new(Commander)48- c.cmdr = c49- c.UsageFunc = c.defaultUsage50- c.initTemplates()51- return52-}53-54-// Name for commander, should match application name55-func (c *Commander) SetName(name string) {56- c.name = name57-}58-59-// os.Args[1:] by default, if desired, can be overridden60-// particularly useful when testing.61-func (c *Commander) SetArgs(a []string) {62- c.args = a63-}64-65-// Call execute to use the args (os.Args[1:] by default)66-// and run through the command tree finding appropriate matches67-// for commands and then corresponding flags.68-func (c *Commander) Execute() (err error) {69- if len(c.args) == 0 {70- err = c.execute(os.Args[1:])71- } else {72- err = c.execute(c.args)73- }74- return75-}76-77-func (c *Commander) out() io.Writer {78- if c.output == nil {79- return os.Stderr80- }81- return *c.output82-}83-84-func (cmdr *Commander) defaultUsage(c *Command) error {85- err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)86- if err != nil {87- c.Println(err)88- }89- return err90-}91-92-//Print to out93-func (c *Commander) PrintOut(i ...interface{}) {94- fmt.Fprint(c.out(), i...)95-}96-97-// SetOutput sets the destination for usage and error messages.98-// If output is nil, os.Stderr is used.99-func (c *Commander) SetOutput(output io.Writer) {100- c.output = &output101- //*c.output = output102-}103-104-func (c *Commander) initTemplates() {105- c.UsageTemplate = `{{ $cmd := . }}106-Usage: {{if .Runnable}}107- {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}108- {{ .CommandPath}} [command]{{end}}109-{{ if .HasSubCommands}}110-Available Commands: {{range .Commands}}{{if .Runnable}}111- {{.Use | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}112-{{end}}113-{{ if .HasFlags}} Available Flags:114-{{.Flags.FlagUsages}}{{end}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}115-Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}}116- {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}117- {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}118-119-{{end}}120-Use "{{.Commander.Name}} help [command]" for more information about that command.121-`122-123- c.HelpTemplate = `{{if .Runnable}}Usage: {{.ProgramName}} {{.UsageLine}}124-125-{{end}}{{.Long | trim}}126-`127-}128-129-// Command is just that, a command for your application.130-// eg. 'go run' ... 'run' is the command. Cobra requires131-// you to define the usage and description as part of your command132-// definition to ensure usability.133-type Command struct {134- // Name is the command name, usually the executable's name.135- name string136- // The one-line usage message.137- Use string138- // The short description shown in the 'help' output.139- Short string140- // The long message shown in the 'help <this-command>' output.141- Long string142- // Set of flags specific to this command.143- flags *flag.FlagSet144- // Set of flags children commands will inherit145- pflags *flag.FlagSet146- // Run runs the command.147- // The args are the arguments after the command name.148- Run func(cmd *Command, args []string)149- // Commands is the list of commands supported by this Commander program.150- commands []*Command151- // Parent Command for this command152- parent *Command153- cmdr *Commander154- flagErrorBuf *bytes.Buffer155-}156-157-// find the target command given the args and command tree158-func (c *Command) Find(args []string) (cmd *Command, a []string, err error) {159- if c == nil {160- return nil, nil, fmt.Errorf("Called find() on a nil Command")161- }162-163- validSubCommand := false164- if len(args) > 1 && c.HasSubCommands() {165- for _, cmd := range c.commands {166- if cmd.Name() == args[0] {167- validSubCommand = true168- return cmd.Find(args[1:])169- }170- }171- }172- if !validSubCommand && c.Runnable() {173- return c, args, nil174- }175-176- return nil, nil, nil177-}178-179-func (c *Command) Commander() *Commander {180- var findRoot func(*Command) *Command181-182- findRoot = func(x *Command) *Command {183- if x.HasParent() {184- return findRoot(x.parent)185- } else {186- return x187- }188- }189- cmdr := findRoot(c)190- if cmdr.cmdr != nil {191- return cmdr.cmdr192- } else {193- panic("commander not found")194- }195-}196-197-func (c *Command) Out() io.Writer {198- return c.Commander().out()199-}200-201-// execute the command determined by args and the command tree202-func (c *Command) execute(args []string) (err error) {203- err = fmt.Errorf("unknown subcommand %q\nRun 'help' for usage.\n", args[0])204-205- if c == nil {206- return fmt.Errorf("Called Execute() on a nil Command")207- }208-209- cmd, a, e := c.Find(args)210- if e == nil {211- err = cmd.ParseFlags(a)212- if err != nil {213- cmd.Usage()214- return err215- } else {216- argWoFlags := cmd.Flags().Args()217- cmd.Run(cmd, argWoFlags)218- return nil219- }220- }221- err = e222- return err223-}224-225-// Used for testing226-func (c *Command) ResetCommands() {227- c.commands = nil228-}229-230-func (c *Command) Commands() []*Command {231- return c.commands232-}233-234-// Add one or many commands as children of this235-func (c *Command) AddCommand(cmds ...*Command) {236- for i, x := range cmds {237- if cmds[i] == c {238- panic("Command can't be a child of itself")239- }240- cmds[i].parent = c241- c.commands = append(c.commands, x)242- }243-}244-245-// Convenience method to Print to the defined output246-func (c *Command) Print(i ...interface{}) {247- c.Commander().PrintOut(i...)248-}249-250-// Convenience method to Println to the defined output251-func (c *Command) Println(i ...interface{}) {252- str := fmt.Sprintln(i...)253- c.Print(str)254-}255-256-// Convenience method to Printf to the defined output257-func (c *Command) Printf(format string, i ...interface{}) {258- str := fmt.Sprintf(format, i...)259- c.Print(str)260-}261-262-// Output the usage for the command263-// Used when a user provides invalid input264-// Can be defined by user by overriding Commander.UsageFunc265-func (c *Command) Usage() error {266- err := c.Commander().UsageFunc(c)267- if err != nil {268- fmt.Println(err)269- }270- return err271-}272-273-// The full path to this command274-func (c *Command) CommandPath() string {275- str := c.Name()276- x := c277- for x.HasParent() {278- str = x.parent.Name() + " " + str279- x = x.parent280- }281- return str282-}283-284-//The full usage for a given command (including parents)285-func (c *Command) UseLine() string {286- str := ""287- if c.HasParent() {288- str = c.parent.CommandPath() + " "289- }290- return str + c.Use291-}292-293-// For use in determining which flags have been assigned to which commands294-// and which persist295-func (c *Command) DebugFlags() {296- c.Println("DebugFlags called on", c.Name())297- var debugflags func(*Command)298-299- debugflags = func(x *Command) {300- if x.HasFlags() || x.HasPersistentFlags() {301- c.Println(x.Name())302- }303- if x.HasFlags() {304- x.flags.VisitAll(func(f *flag.Flag) {305- if x.HasPersistentFlags() {306- if x.persistentFlag(f.Name) == nil {307- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")308- } else {309- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")310- }311- } else {312- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")313- }314- })315- }316- if x.HasPersistentFlags() {317- x.pflags.VisitAll(func(f *flag.Flag) {318- if x.HasFlags() {319- if x.flags.Lookup(f.Name) == nil {320- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")321- }322- } else {323- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")324- }325- })326- }327- c.Println(x.flagErrorBuf)328- if x.HasSubCommands() {329- for _, y := range x.commands {330- debugflags(y)331- }332- }333- }334-335- debugflags(c)336-}337-338-// Name returns the command's name: the first word in the use line.339-func (c *Command) Name() string {340- if c.name != "" {341- return c.name342- }343- name := c.Use344- i := strings.Index(name, " ")345- if i >= 0 {346- name = name[:i]347- }348- return name349-}350-351-// Determine if the command is itself runnable352-func (c *Command) Runnable() bool {353- return c.Run != nil354-}355-356-// Determine if the command has children commands357-func (c *Command) HasSubCommands() bool {358- return len(c.commands) > 0359-}360-361-// Determine if the command is a child command362-func (c *Command) HasParent() bool {363- return c.parent != nil364-}365-366-// Get the Commands FlagSet367-func (c *Command) Flags() *flag.FlagSet {368- if c.flags == nil {369- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)370- if c.flagErrorBuf == nil {371- c.flagErrorBuf = new(bytes.Buffer)372- }373- c.flags.SetOutput(c.flagErrorBuf)374- }375- return c.flags376-}377-378-// Get the Commands Persistent FlagSet379-func (c *Command) PersistentFlags() *flag.FlagSet {380- if c.pflags == nil {381- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)382- if c.flagErrorBuf == nil {383- c.flagErrorBuf = new(bytes.Buffer)384- }385- c.pflags.SetOutput(c.flagErrorBuf)386- }387- return c.pflags388-}389-390-// For use in testing391-func (c *Command) ResetFlags() {392- c.flagErrorBuf = new(bytes.Buffer)393- c.flagErrorBuf.Reset()394- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)395- c.flags.SetOutput(c.flagErrorBuf)396- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)397- c.pflags.SetOutput(c.flagErrorBuf)398-}399-400-// Does the command contain flags (local not persistent)401-func (c *Command) HasFlags() bool {402- return c.Flags().HasFlags()403-}404-405-// Does the command contain persistent flags406-func (c *Command) HasPersistentFlags() bool {407- return c.PersistentFlags().HasFlags()408-}409-410-// Climbs up the command tree looking for matching flag411-func (c *Command) Flag(name string) (flag *flag.Flag) {412- flag = c.Flags().Lookup(name)413-414- if flag == nil {415- flag = c.persistentFlag(name)416- }417-418- return419-}420-421-// recursively find matching persistent flag422-func (c *Command) persistentFlag(name string) (flag *flag.Flag) {423- if c.HasPersistentFlags() {424- flag = c.PersistentFlags().Lookup(name)425- }426-427- if flag == nil && c.HasParent() {428- flag = c.parent.persistentFlag(name)429- }430- return431-}432-433-// Parses persistent flag tree & local flags434-func (c *Command) ParseFlags(args []string) (err error) {435- c.mergePersistentFlags()436-437- err = c.Flags().Parse(args)438- if err != nil {439- return err440- }441- if c.flagErrorBuf != nil {442- //fmt.Println(c.flagErrorBuf.String())443- return nil444- //return fmt.Errorf("%s", c.flagErrorBuf.String())445- }446- return nil447-}448-449-func (c *Command) mergePersistentFlags() {450- var rmerge func(x *Command)451-452- rmerge = func(x *Command) {453- if x.HasPersistentFlags() {454- x.PersistentFlags().VisitAll(func(f *flag.Flag) {455- if c.Flags().Lookup(f.Name) == nil {456- c.Flags().AddFlag(f)457- }458- })459- }460- if x.HasParent() {461- rmerge(x.parent)462- }463- }464-465- rmerge(c)466-}467-468-func (c *Command) Parent() *Command {469- return c.parent470-}471-27 func Gt(a interface{}, b interface{}) bool {28 var left, right int6429 av := reflect.ValueOf(a)30 49 unmodified linesadded:command.go+368 added
1+// Copyright © 2013 Steve Francia <spf@spf13.com>.2+//3+// Licensed under the Apache License, Version 2.0 (the "License");4+// you may not use this file except in compliance with the License.5+// You may obtain a copy of the License at6+// http://www.apache.org/licenses/LICENSE-2.07+//8+// Unless required by applicable law or agreed to in writing, software9+// distributed under the License is distributed on an "AS IS" BASIS,10+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11+// See the License for the specific language governing permissions and12+// limitations under the License.13+14+// Commands similar to git, go tools and other modern CLI tools15+// inspired by go, go-Commander, gh and subcommand16+17+package cobra18+19+import (20+ "bytes"21+ "fmt"22+ flag "github.com/spf13/pflag"23+ "io"24+ "strings"25+)26+27+// Command is just that, a command for your application.28+// eg. 'go run' ... 'run' is the command. Cobra requires29+// you to define the usage and description as part of your command30+// definition to ensure usability.31+type Command struct {32+ // Name is the command name, usually the executable's name.33+ name string34+ // The one-line usage message.35+ Use string36+ // The short description shown in the 'help' output.37+ Short string38+ // The long message shown in the 'help <this-command>' output.39+ Long string40+ // Set of flags specific to this command.41+ flags *flag.FlagSet42+ // Set of flags children commands will inherit43+ pflags *flag.FlagSet44+ // Run runs the command.45+ // The args are the arguments after the command name.46+ Run func(cmd *Command, args []string)47+ // Commands is the list of commands supported by this Commander program.48+ commands []*Command49+ // Parent Command for this command50+ parent *Command51+ cmdr *Commander52+ flagErrorBuf *bytes.Buffer53+}54+55+// find the target command given the args and command tree56+func (c *Command) Find(args []string) (cmd *Command, a []string, err error) {57+ if c == nil {58+ return nil, nil, fmt.Errorf("Called find() on a nil Command")59+ }60+61+ validSubCommand := false62+ if len(args) > 1 && c.HasSubCommands() {63+ for _, cmd := range c.commands {64+ if cmd.Name() == args[0] {65+ validSubCommand = true66+ return cmd.Find(args[1:])67+ }68+ }69+ }70+ if !validSubCommand && c.Runnable() {71+ return c, args, nil72+ }73+74+ return nil, nil, nil75+}76+77+func (c *Command) Commander() *Commander {78+ var findRoot func(*Command) *Command79+80+ findRoot = func(x *Command) *Command {81+ if x.HasParent() {82+ return findRoot(x.parent)83+ } else {84+ return x85+ }86+ }87+ cmdr := findRoot(c)88+ if cmdr.cmdr != nil {89+ return cmdr.cmdr90+ } else {91+ panic("commander not found")92+ }93+}94+95+func (c *Command) Out() io.Writer {96+ return c.Commander().out()97+}98+99+// execute the command determined by args and the command tree100+func (c *Command) execute(args []string) (err error) {101+ err = fmt.Errorf("unknown subcommand %q\nRun 'help' for usage.\n", args[0])102+103+ if c == nil {104+ return fmt.Errorf("Called Execute() on a nil Command")105+ }106+107+ cmd, a, e := c.Find(args)108+ if e == nil {109+ err = cmd.ParseFlags(a)110+ if err != nil {111+ cmd.Usage()112+ return err113+ } else {114+ argWoFlags := cmd.Flags().Args()115+ cmd.Run(cmd, argWoFlags)116+ return nil117+ }118+ }119+ err = e120+ return err121+}122+123+// Used for testing124+func (c *Command) ResetCommands() {125+ c.commands = nil126+}127+128+func (c *Command) Commands() []*Command {129+ return c.commands130+}131+132+// Add one or many commands as children of this133+func (c *Command) AddCommand(cmds ...*Command) {134+ for i, x := range cmds {135+ if cmds[i] == c {136+ panic("Command can't be a child of itself")137+ }138+ cmds[i].parent = c139+ c.commands = append(c.commands, x)140+ }141+}142+143+// Convenience method to Print to the defined output144+func (c *Command) Print(i ...interface{}) {145+ c.Commander().PrintOut(i...)146+}147+148+// Convenience method to Println to the defined output149+func (c *Command) Println(i ...interface{}) {150+ str := fmt.Sprintln(i...)151+ c.Print(str)152+}153+154+// Convenience method to Printf to the defined output155+func (c *Command) Printf(format string, i ...interface{}) {156+ str := fmt.Sprintf(format, i...)157+ c.Print(str)158+}159+160+// Output the usage for the command161+// Used when a user provides invalid input162+// Can be defined by user by overriding Commander.UsageFunc163+func (c *Command) Usage() error {164+ err := c.Commander().UsageFunc(c)165+ if err != nil {166+ fmt.Println(err)167+ }168+ return err169+}170+171+// The full path to this command172+func (c *Command) CommandPath() string {173+ str := c.Name()174+ x := c175+ for x.HasParent() {176+ str = x.parent.Name() + " " + str177+ x = x.parent178+ }179+ return str180+}181+182+//The full usage for a given command (including parents)183+func (c *Command) UseLine() string {184+ str := ""185+ if c.HasParent() {186+ str = c.parent.CommandPath() + " "187+ }188+ return str + c.Use189+}190+191+// For use in determining which flags have been assigned to which commands192+// and which persist193+func (c *Command) DebugFlags() {194+ c.Println("DebugFlags called on", c.Name())195+ var debugflags func(*Command)196+197+ debugflags = func(x *Command) {198+ if x.HasFlags() || x.HasPersistentFlags() {199+ c.Println(x.Name())200+ }201+ if x.HasFlags() {202+ x.flags.VisitAll(func(f *flag.Flag) {203+ if x.HasPersistentFlags() {204+ if x.persistentFlag(f.Name) == nil {205+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")206+ } else {207+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")208+ }209+ } else {210+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")211+ }212+ })213+ }214+ if x.HasPersistentFlags() {215+ x.pflags.VisitAll(func(f *flag.Flag) {216+ if x.HasFlags() {217+ if x.flags.Lookup(f.Name) == nil {218+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")219+ }220+ } else {221+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")222+ }223+ })224+ }225+ c.Println(x.flagErrorBuf)226+ if x.HasSubCommands() {227+ for _, y := range x.commands {228+ debugflags(y)229+ }230+ }231+ }232+233+ debugflags(c)234+}235+236+// Name returns the command's name: the first word in the use line.237+func (c *Command) Name() string {238+ if c.name != "" {239+ return c.name240+ }241+ name := c.Use242+ i := strings.Index(name, " ")243+ if i >= 0 {244+ name = name[:i]245+ }246+ return name247+}248+249+// Determine if the command is itself runnable250+func (c *Command) Runnable() bool {251+ return c.Run != nil252+}253+254+// Determine if the command has children commands255+func (c *Command) HasSubCommands() bool {256+ return len(c.commands) > 0257+}258+259+// Determine if the command is a child command260+func (c *Command) HasParent() bool {261+ return c.parent != nil262+}263+264+// Get the Commands FlagSet265+func (c *Command) Flags() *flag.FlagSet {266+ if c.flags == nil {267+ c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)268+ if c.flagErrorBuf == nil {269+ c.flagErrorBuf = new(bytes.Buffer)270+ }271+ c.flags.SetOutput(c.flagErrorBuf)272+ }273+ return c.flags274+}275+276+// Get the Commands Persistent FlagSet277+func (c *Command) PersistentFlags() *flag.FlagSet {278+ if c.pflags == nil {279+ c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)280+ if c.flagErrorBuf == nil {281+ c.flagErrorBuf = new(bytes.Buffer)282+ }283+ c.pflags.SetOutput(c.flagErrorBuf)284+ }285+ return c.pflags286+}287+288+// For use in testing289+func (c *Command) ResetFlags() {290+ c.flagErrorBuf = new(bytes.Buffer)291+ c.flagErrorBuf.Reset()292+ c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)293+ c.flags.SetOutput(c.flagErrorBuf)294+ c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)295+ c.pflags.SetOutput(c.flagErrorBuf)296+}297+298+// Does the command contain flags (local not persistent)299+func (c *Command) HasFlags() bool {300+ return c.Flags().HasFlags()301+}302+303+// Does the command contain persistent flags304+func (c *Command) HasPersistentFlags() bool {305+ return c.PersistentFlags().HasFlags()306+}307+308+// Climbs up the command tree looking for matching flag309+func (c *Command) Flag(name string) (flag *flag.Flag) {310+ flag = c.Flags().Lookup(name)311+312+ if flag == nil {313+ flag = c.persistentFlag(name)314+ }315+316+ return317+}318+319+// recursively find matching persistent flag320+func (c *Command) persistentFlag(name string) (flag *flag.Flag) {321+ if c.HasPersistentFlags() {322+ flag = c.PersistentFlags().Lookup(name)323+ }324+325+ if flag == nil && c.HasParent() {326+ flag = c.parent.persistentFlag(name)327+ }328+ return329+}330+331+// Parses persistent flag tree & local flags332+func (c *Command) ParseFlags(args []string) (err error) {333+ c.mergePersistentFlags()334+335+ err = c.Flags().Parse(args)336+ if err != nil {337+ return err338+ }339+ if c.flagErrorBuf != nil {340+ //fmt.Println(c.flagErrorBuf.String())341+ return nil342+ //return fmt.Errorf("%s", c.flagErrorBuf.String())343+ }344+ return nil345+}346+347+func (c *Command) mergePersistentFlags() {348+ var rmerge func(x *Command)349+350+ rmerge = func(x *Command) {351+ if x.HasPersistentFlags() {352+ x.PersistentFlags().VisitAll(func(f *flag.Flag) {353+ if c.Flags().Lookup(f.Name) == nil {354+ c.Flags().AddFlag(f)355+ }356+ })357+ }358+ if x.HasParent() {359+ rmerge(x.parent)360+ }361+ }362+363+ rmerge(c)364+}365+366+func (c *Command) Parent() *Command {367+ return c.parent368+}added:commander.go+119 added
1+// Copyright © 2013 Steve Francia <spf@spf13.com>.2+//3+// Licensed under the Apache License, Version 2.0 (the "License");4+// you may not use this file except in compliance with the License.5+// You may obtain a copy of the License at6+// http://www.apache.org/licenses/LICENSE-2.07+//8+// Unless required by applicable law or agreed to in writing, software9+// distributed under the License is distributed on an "AS IS" BASIS,10+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11+// See the License for the specific language governing permissions and12+// limitations under the License.13+14+// Commands similar to git, go tools and other modern CLI tools15+// inspired by go, go-Commander, gh and subcommand16+17+package cobra18+19+import (20+ "fmt"21+ "io"22+ "os"23+)24+25+// A Commander holds the configuration for the command line tool.26+type Commander struct {27+ // A Commander is also a Command for top level and global help & flags28+ Command29+30+ args []string31+ output *io.Writer // nil means stderr; use out() accessor32+ UsageFunc func(*Command) error // Usage can be defined by application33+ UsageTemplate string // Can be defined by Application34+ HelpTemplate string // Can be defined by Application35+}36+37+// Provide the user with a new commander.38+func NewCommander() (c *Commander) {39+ c = new(Commander)40+ c.cmdr = c41+ c.UsageFunc = c.defaultUsage42+ c.initTemplates()43+ return44+}45+46+// Name for commander, should match application name47+func (c *Commander) SetName(name string) {48+ c.name = name49+}50+51+// os.Args[1:] by default, if desired, can be overridden52+// particularly useful when testing.53+func (c *Commander) SetArgs(a []string) {54+ c.args = a55+}56+57+// Call execute to use the args (os.Args[1:] by default)58+// and run through the command tree finding appropriate matches59+// for commands and then corresponding flags.60+func (c *Commander) Execute() (err error) {61+ if len(c.args) == 0 {62+ err = c.execute(os.Args[1:])63+ } else {64+ err = c.execute(c.args)65+ }66+ return67+}68+69+func (c *Commander) out() io.Writer {70+ if c.output == nil {71+ return os.Stderr72+ }73+ return *c.output74+}75+76+func (cmdr *Commander) defaultUsage(c *Command) error {77+ err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)78+ if err != nil {79+ c.Println(err)80+ }81+ return err82+}83+84+//Print to out85+func (c *Commander) PrintOut(i ...interface{}) {86+ fmt.Fprint(c.out(), i...)87+}88+89+// SetOutput sets the destination for usage and error messages.90+// If output is nil, os.Stderr is used.91+func (c *Commander) SetOutput(output io.Writer) {92+ c.output = &output93+ //*c.output = output94+}95+96+func (c *Commander) initTemplates() {97+ c.UsageTemplate = `{{ $cmd := . }}98+Usage: {{if .Runnable}}99+ {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}100+ {{ .CommandPath}} [command]{{end}}101+{{ if .HasSubCommands}}102+Available Commands: {{range .Commands}}{{if .Runnable}}103+ {{.Use | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}104+{{end}}105+{{ if .HasFlags}} Available Flags:106+{{.Flags.FlagUsages}}{{end}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}107+Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}}108+ {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}109+ {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}110+111+{{end}}112+Use "{{.Commander.Name}} help [command]" for more information about that command.113+`114+115+ c.HelpTemplate = `{{if .Runnable}}Usage: {{.ProgramName}} {{.UsageLine}}116+117+{{end}}{{.Long | trim}}118+`119+}