golang.org/x/tools/gopls@v0.15.3/internal/cmd/subcommands.go (about) 1 // Copyright 2021 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cmd 6 7 import ( 8 "context" 9 "flag" 10 "fmt" 11 "text/tabwriter" 12 13 "golang.org/x/tools/internal/tool" 14 ) 15 16 // subcommands is a helper that may be embedded for commands that delegate to 17 // subcommands. 18 type subcommands []tool.Application 19 20 func (s subcommands) DetailedHelp(f *flag.FlagSet) { 21 w := tabwriter.NewWriter(f.Output(), 0, 0, 2, ' ', 0) 22 defer w.Flush() 23 fmt.Fprint(w, "\nSubcommand:\n") 24 for _, c := range s { 25 fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp()) 26 } 27 printFlagDefaults(f) 28 } 29 30 func (s subcommands) Usage() string { return "<subcommand> [arg]..." } 31 32 func (s subcommands) Run(ctx context.Context, args ...string) error { 33 if len(args) == 0 { 34 return tool.CommandLineErrorf("must provide subcommand") 35 } 36 command, args := args[0], args[1:] 37 for _, c := range s { 38 if c.Name() == command { 39 s := flag.NewFlagSet(c.Name(), flag.ExitOnError) 40 return tool.Run(ctx, s, c, args) 41 } 42 } 43 return tool.CommandLineErrorf("unknown subcommand %v", command) 44 } 45 46 func (s subcommands) Commands() []tool.Application { return s } 47 48 // getSubcommands returns the subcommands of a given Application. 49 func getSubcommands(a tool.Application) []tool.Application { 50 // This interface is satisfied both by tool.Applications 51 // that embed subcommands, and by *cmd.Application. 52 type hasCommands interface { 53 Commands() []tool.Application 54 } 55 if sub, ok := a.(hasCommands); ok { 56 return sub.Commands() 57 } 58 return nil 59 }