pkg.tk-software.de/gotice@v0.4.1-0.20240224130243-6adec687b106/help.go (about)

     1  // Copyright 2023-2024 Tobias Koch. 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 main
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  )
    11  
    12  // HelpCommand implements the subcommand `help`.
    13  type HelpCommand struct {
    14  	fs *flag.FlagSet
    15  
    16  	// The requested help topic.
    17  	topic string
    18  }
    19  
    20  // NewHelpCommand creates and returns the subcommand `help`.
    21  func NewHelpCommand() *HelpCommand {
    22  	cmd := &HelpCommand{
    23  		fs:    flag.NewFlagSet("help", flag.ContinueOnError),
    24  		topic: "",
    25  	}
    26  
    27  	return cmd
    28  }
    29  
    30  // Name returns the name of the subcommand.
    31  func (h *HelpCommand) Name() string {
    32  	return h.fs.Name()
    33  }
    34  
    35  // Description returns the description of the subcommand.
    36  func (h *HelpCommand) Description() string {
    37  	return "Displays the command line help"
    38  }
    39  
    40  // Init initializes the subcommand with the given command line arguments.
    41  func (h *HelpCommand) Init(args []string) error {
    42  	if err := h.fs.Parse(args); err != nil {
    43  		return err
    44  	}
    45  
    46  	if h.fs.NArg() > 0 {
    47  		h.topic = h.fs.Arg(0)
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  // Usage prints a usage message documenting the subcommand.
    54  func (h *HelpCommand) Usage() {
    55  	fmt.Println("Usage: gotice help")
    56  	fmt.Println(h.Description())
    57  	fmt.Println()
    58  }
    59  
    60  // Run executes the subcommand.
    61  func (h *HelpCommand) Run() error {
    62  	if h.topic == "" {
    63  		fmt.Println("Usage: gotice [command]")
    64  		fmt.Println()
    65  		fmt.Println("Commands:")
    66  
    67  		for _, c := range commands {
    68  			fmt.Printf("  %-10s%s\n", c.Name(), c.Description())
    69  		}
    70  
    71  		fmt.Println()
    72  		fmt.Println("Use `gotice help [command]` for further information")
    73  
    74  		return nil
    75  	}
    76  
    77  	for _, c := range commands {
    78  		if c.Name() == h.topic {
    79  			c.Usage()
    80  			return nil
    81  		}
    82  	}
    83  
    84  	return nil
    85  }