github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/internal/lsp/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  	"github.com/jhump/golang-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  }