command.go
This file
Path
command.go
415 lines · 9.9 KiB · Go
Last changed by
Shorter message when invalid flags providedspf13before adoption6b3d2f2
History of this fileTake it
Organize the files a bit betterspf13before adoption62fb674
lines 1–54why, one step back1// 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.1314// Commands similar to git, go tools and other modern CLI tools15// inspired by go, go-Commander, gh and subcommand1617package cobra1819import (20 "bytes"21 "fmt"22 flag "github.com/spf13/pflag"23 "io"24 "strings"25)2627// 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.31type 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}54Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 55–77why, one step back55// Convert a Command into an (initialized) Commander56func (cmd *Command) ToCommander() (c *Commander) {57 c = NewCommander()58 c.name = cmd.Name()59 c.Use = cmd.Use60 c.Short = cmd.Short61 c.Long = cmd.Long62 c.flags = cmd.flags63 c.pflags = cmd.pflags64 c.Run = cmd.Run65 c.commands = cmd.commands66 c.resetChildrensParents()67 c.flagErrorBuf = cmd.flagErrorBuf68 return69}7071// Really only used when casting a command to a commander72func (c *Command) resetChildrensParents() {73 for _, x := range c.commands {74 x.parent = c75 }76}77Organize the files a bit betterspf13before adoption62fb674
line 78why, one step back78// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 79why, one step back79// Meant to be run on the highest node. Only searches down.Finding command based on args cleaned upspf13before adoption55ff474
line 80why, one step back80func (c *Command) Find(arrs []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 81–84why, one step back81 if c == nil {82 return nil, nil, fmt.Errorf("Called find() on a nil Command")83 }84Finding command based on args cleaned upspf13before adoption55ff474
lines 85–96why, one step back85 if len(arrs) == 0 {86 return c.Commander().cmd, arrs, nil87 }8889 var innerfind func(*Command, []string) (*Command, []string)9091 innerfind = func(c *Command, args []string) (*Command, []string) {92 if len(args) > 0 && c.HasSubCommands() {93 for _, cmd := range c.commands {94 if cmd.Name() == args[0] {95 return innerfind(cmd, args[1:])96 }Organize the files a bit betterspf13before adoption62fb674
lines 97–98why, one step back97 }98 }Finding command based on args cleaned upspf13before adoption55ff474
lines 99–100why, one step back99100 return c, argsOrganize the files a bit betterspf13before adoption62fb674
line 101why, one step back101 }Finding command based on args cleaned upspf13before adoption55ff474
lines 102–107why, one step back102103 commandFound, a := innerfind(c, arrs)104105 // if commander returned and not appropriately matched return nil & error106 if commandFound.Name() == c.Name() && commandFound.Name() != arrs[0] {107 return nil, a, fmt.Errorf("Command not found")Organize the files a bit betterspf13before adoption62fb674
lines 108–109why, one step back108 }109Finding command based on args cleaned upspf13before adoption55ff474
line 110why, one step back110 return commandFound, a, nilOrganize the files a bit betterspf13before adoption62fb674
lines 111–112why, one step back111}112Add support for help commandspf13before adoptionfb2146e
line 113why, one step back113func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 114–122why, one step back114 var findRoot func(*Command) *Command115116 findRoot = func(x *Command) *Command {117 if x.HasParent() {118 return findRoot(x.parent)119 } else {120 return x121 }122 }Add support for help commandspf13before adoptionfb2146e
lines 123–128why, one step back123124 return findRoot(c)125}126127func (c *Command) Commander() *Commander {128 cmdr := c.Root()Organize the files a bit betterspf13before adoption62fb674
lines 129–207why, one step back129 if cmdr.cmdr != nil {130 return cmdr.cmdr131 } else {132 panic("commander not found")133 }134}135136func (c *Command) Out() io.Writer {137 return c.Commander().out()138}139140// execute the command determined by args and the command tree141func (c *Command) execute(args []string) (err error) {142 err = fmt.Errorf("unknown subcommand %q\nRun 'help' for usage.\n", args[0])143144 if c == nil {145 return fmt.Errorf("Called Execute() on a nil Command")146 }147148 cmd, a, e := c.Find(args)149 if e == nil {150 err = cmd.ParseFlags(a)151 if err != nil {152 return err153 } else {154 argWoFlags := cmd.Flags().Args()155 cmd.Run(cmd, argWoFlags)156 return nil157 }158 }159 err = e160 return err161}162163// Used for testing164func (c *Command) ResetCommands() {165 c.commands = nil166}167168func (c *Command) Commands() []*Command {169 return c.commands170}171172// Add one or many commands as children of this173func (c *Command) AddCommand(cmds ...*Command) {174 for i, x := range cmds {175 if cmds[i] == c {176 panic("Command can't be a child of itself")177 }178 cmds[i].parent = c179 c.commands = append(c.commands, x)180 }181}182183// Convenience method to Print to the defined output184func (c *Command) Print(i ...interface{}) {185 c.Commander().PrintOut(i...)186}187188// Convenience method to Println to the defined output189func (c *Command) Println(i ...interface{}) {190 str := fmt.Sprintln(i...)191 c.Print(str)192}193194// Convenience method to Printf to the defined output195func (c *Command) Printf(format string, i ...interface{}) {196 str := fmt.Sprintf(format, i...)197 c.Print(str)198}199200// Output the usage for the command201// Used when a user provides invalid input202// Can be defined by user by overriding Commander.UsageFunc203func (c *Command) Usage() error {204 err := c.Commander().UsageFunc(c)205 return err206}207fix trailing <nil> on help outputspf13before adoption3958385
lines 208–216why, one step back208func (c *Command) UsageString() string {209 tmpOutput := c.Commander().cmdr.output210 bb := new(bytes.Buffer)211 c.Commander().SetOutput(bb)212 c.Usage()213 c.Commander().cmdr.output = tmpOutput214 return bb.String()215}216Organize the files a bit betterspf13before adoption62fb674
lines 217–384why, one step back217// The full path to this command218func (c *Command) CommandPath() string {219 str := c.Name()220 x := c221 for x.HasParent() {222 str = x.parent.Name() + " " + str223 x = x.parent224 }225 return str226}227228//The full usage for a given command (including parents)229func (c *Command) UseLine() string {230 str := ""231 if c.HasParent() {232 str = c.parent.CommandPath() + " "233 }234 return str + c.Use235}236237// For use in determining which flags have been assigned to which commands238// and which persist239func (c *Command) DebugFlags() {240 c.Println("DebugFlags called on", c.Name())241 var debugflags func(*Command)242243 debugflags = func(x *Command) {244 if x.HasFlags() || x.HasPersistentFlags() {245 c.Println(x.Name())246 }247 if x.HasFlags() {248 x.flags.VisitAll(func(f *flag.Flag) {249 if x.HasPersistentFlags() {250 if x.persistentFlag(f.Name) == nil {251 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")252 } else {253 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")254 }255 } else {256 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")257 }258 })259 }260 if x.HasPersistentFlags() {261 x.pflags.VisitAll(func(f *flag.Flag) {262 if x.HasFlags() {263 if x.flags.Lookup(f.Name) == nil {264 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")265 }266 } else {267 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")268 }269 })270 }271 c.Println(x.flagErrorBuf)272 if x.HasSubCommands() {273 for _, y := range x.commands {274 debugflags(y)275 }276 }277 }278279 debugflags(c)280}281282// Name returns the command's name: the first word in the use line.283func (c *Command) Name() string {284 if c.name != "" {285 return c.name286 }287 name := c.Use288 i := strings.Index(name, " ")289 if i >= 0 {290 name = name[:i]291 }292 return name293}294295// Determine if the command is itself runnable296func (c *Command) Runnable() bool {297 return c.Run != nil298}299300// Determine if the command has children commands301func (c *Command) HasSubCommands() bool {302 return len(c.commands) > 0303}304305// Determine if the command is a child command306func (c *Command) HasParent() bool {307 return c.parent != nil308}309310// Get the Commands FlagSet311func (c *Command) Flags() *flag.FlagSet {312 if c.flags == nil {313 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)314 if c.flagErrorBuf == nil {315 c.flagErrorBuf = new(bytes.Buffer)316 }317 c.flags.SetOutput(c.flagErrorBuf)318 }319 return c.flags320}321322// Get the Commands Persistent FlagSet323func (c *Command) PersistentFlags() *flag.FlagSet {324 if c.pflags == nil {325 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)326 if c.flagErrorBuf == nil {327 c.flagErrorBuf = new(bytes.Buffer)328 }329 c.pflags.SetOutput(c.flagErrorBuf)330 }331 return c.pflags332}333334// For use in testing335func (c *Command) ResetFlags() {336 c.flagErrorBuf = new(bytes.Buffer)337 c.flagErrorBuf.Reset()338 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)339 c.flags.SetOutput(c.flagErrorBuf)340 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)341 c.pflags.SetOutput(c.flagErrorBuf)342}343344// Does the command contain flags (local not persistent)345func (c *Command) HasFlags() bool {346 return c.Flags().HasFlags()347}348349// Does the command contain persistent flags350func (c *Command) HasPersistentFlags() bool {351 return c.PersistentFlags().HasFlags()352}353354// Climbs up the command tree looking for matching flag355func (c *Command) Flag(name string) (flag *flag.Flag) {356 flag = c.Flags().Lookup(name)357358 if flag == nil {359 flag = c.persistentFlag(name)360 }361362 return363}364365// recursively find matching persistent flag366func (c *Command) persistentFlag(name string) (flag *flag.Flag) {367 if c.HasPersistentFlags() {368 flag = c.PersistentFlags().Lookup(name)369 }370371 if flag == nil && c.HasParent() {372 flag = c.parent.persistentFlag(name)373 }374 return375}376377// Parses persistent flag tree & local flags378func (c *Command) ParseFlags(args []string) (err error) {379 c.mergePersistentFlags()380381 err = c.Flags().Parse(args)382 if err != nil {383 return err384 }Proper handling of flag error messages. Fixing test that wasn't passing.spf13before adoption68f3c66
lines 385–389why, one step back385 // The upstream library adds spaces to the error386 // response regardless of success.387 // Handling it here until fixing upstream388 if len(strings.TrimSpace(c.flagErrorBuf.String())) > 1 {389 return fmt.Errorf("%s", c.flagErrorBuf.String())Organize the files a bit betterspf13before adoption62fb674
lines 390–415why, one step back390 }391 return nil392}393394func (c *Command) mergePersistentFlags() {395 var rmerge func(x *Command)396397 rmerge = func(x *Command) {398 if x.HasPersistentFlags() {399 x.PersistentFlags().VisitAll(func(f *flag.Flag) {400 if c.Flags().Lookup(f.Name) == nil {401 c.Flags().AddFlag(f)402 }403 })404 }405 if x.HasParent() {406 rmerge(x.parent)407 }408 }409410 rmerge(c)411}412413func (c *Command) Parent() *Command {414 return c.parent415}