github.com/v2fly/tools@v0.100.0/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  
    12  	"github.com/v2fly/tools/internal/tool"
    13  )
    14  
    15  // subcommands is a helper that may be embedded for commands that delegate to
    16  // subcommands.
    17  type subcommands []tool.Application
    18  
    19  func (s subcommands) DetailedHelp(f *flag.FlagSet) {
    20  	fmt.Fprint(f.Output(), "\nsubcommands:\n")
    21  	for _, c := range s {
    22  		fmt.Fprintf(f.Output(), "  %s: %s\n", c.Name(), c.ShortHelp())
    23  	}
    24  	f.PrintDefaults()
    25  }
    26  
    27  func (s subcommands) Usage() string { return "<subcommand> [args...]" }
    28  
    29  func (s subcommands) Run(ctx context.Context, args ...string) error {
    30  	if len(args) == 0 {
    31  		return tool.CommandLineErrorf("must provide subcommand")
    32  	}
    33  	command, args := args[0], args[1:]
    34  	for _, c := range s {
    35  		if c.Name() == command {
    36  			return tool.Run(ctx, c, args)
    37  		}
    38  	}
    39  	return tool.CommandLineErrorf("unknown subcommand %v", command)
    40  }