github.com/cloudfoundry-incubator/stembuild@v0.0.0-20211223202937-5b61d62226c6/commandparser/help.go (about)

     1  package commandparser
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"path"
    10  
    11  	"github.com/cloudfoundry-incubator/stembuild/version"
    12  	. "github.com/google/subcommands"
    13  )
    14  
    15  /*
    16  This is a wrapper for Google's Subcommand's HelpCommand so that we can
    17  override the help text when the user just enters the `help` command in the command
    18  line.
    19  */
    20  
    21  type stembuildHelp struct {
    22  	topLevelFlags *flag.FlagSet
    23  	commands      *[]Command
    24  	commander     *Commander
    25  }
    26  
    27  func NewStembuildHelp(commander *Commander, topLevelFlags *flag.FlagSet, commands *[]Command) *stembuildHelp {
    28  	var sh = stembuildHelp{}
    29  	sh.commander = commander
    30  	sh.topLevelFlags = topLevelFlags
    31  	sh.commands = commands
    32  
    33  	return &sh
    34  }
    35  
    36  func (h *stembuildHelp) Name() string {
    37  	return h.commander.HelpCommand().Name()
    38  }
    39  
    40  func (h *stembuildHelp) Synopsis() string {
    41  	return "Describe commands and their syntax"
    42  }
    43  
    44  func (h *stembuildHelp) SetFlags(fs *flag.FlagSet) {
    45  	h.commander.HelpCommand().SetFlags(fs)
    46  }
    47  
    48  func (h *stembuildHelp) Usage() string {
    49  	return h.commander.HelpCommand().Usage()
    50  }
    51  
    52  func (h *stembuildHelp) Execute(c context.Context, f *flag.FlagSet, args ...interface{}) ExitStatus {
    53  	switch f.NArg() {
    54  	case 0:
    55  		h.Explain(h.commander.Output)
    56  		return ExitSuccess
    57  
    58  	default:
    59  		return h.commander.HelpCommand().Execute(c, f, args)
    60  	}
    61  }
    62  
    63  func (h *stembuildHelp) Explain(w io.Writer) {
    64  
    65  	_, _ = fmt.Fprintf(w, "%s version %s, Windows Stemcell Building Tool\n\n", path.Base(os.Args[0]), version.Version)
    66  	_, _ = fmt.Fprintf(w, "Usage: %s <global options> <command> <command flags>\n\n", path.Base(os.Args[0]))
    67  
    68  	_, _ = fmt.Fprint(w, "Commands:\n")
    69  	for _, command := range *h.commands {
    70  		if len(command.Name()) < 5 { // This help align the synopses when the commands are of different lengths
    71  			_, _ = fmt.Fprintf(w, "  %s\t\t%s\n", command.Name(), command.Synopsis())
    72  		} else {
    73  			_, _ = fmt.Fprintf(w, "  %s\t%s\n", command.Name(), command.Synopsis())
    74  		}
    75  	}
    76  
    77  	_, _ = fmt.Fprint(w, "\nGlobal Options:\n")
    78  	h.topLevelFlags.VisitAll(func(f *flag.Flag) {
    79  		if len(f.Name) > 1 {
    80  			_, _ = fmt.Fprintf(w, "  -%s\t%s\n", f.Name, f.Usage)
    81  		} else {
    82  			_, _ = fmt.Fprintf(w, "  -%s\t\t%s\n", f.Name, f.Usage)
    83  		}
    84  	})
    85  }