Best Testkube code snippet using commands.NewHelpCmd
cmd.go
Source:cmd.go
1package cmndr2import (3 "fmt"4 "os"5 "sort"6 "text/tabwriter"7 "github.com/pkg/errors"8 flag "github.com/spf13/pflag"9)10// RunFunc defines the arity and return signatures of a function that a Cmd11// will run.12type RunFunc func(cmd *Cmd, args []string) error13// Cmd defines the structure of a command that can be run.14type Cmd struct {15 // The name of the command.16 Name string17 // A brief, single line description of the command.18 Description string19 // A *flag.FlagSet for registering command-line flags for the command.20 Flags *flag.FlagSet21 // Will be nil unless subcommands are registered with the AddCmd()22 // method.23 Commands map[string]*Cmd24 // The function to run.25 Run RunFunc26}27func newUsage(c *Cmd) func() {28 return func() {29 if c.Flags == nil {30 c.Flags = flag.NewFlagSet(c.Name, flag.ExitOnError)31 }32 fmt.Fprintf(os.Stderr, "%s - %s\n", c.Name, c.Description)33 printSubcommands(c)34 fmt.Fprintln(os.Stderr, "\nFlags")35 c.Flags.SortFlags = true36 c.Flags.PrintDefaults()37 }38}39// newHelpCmd is called by New() to add a "help" subcommand to parent.40func newHelpCmd(parent *Cmd) *Cmd {41 descr := fmt.Sprintf("Print the help message for %s or a subcommand", parent.Name)42 return &Cmd{43 Name: "help",44 Description: descr,45 Run: func(cmd *Cmd, args []string) error {46 // The command to print the help message for.47 var pp *Cmd48 if len(args) == 0 || parent.Commands == nil {49 // In this situation, the user has just run50 //51 // $ cmd help52 //53 // or, they have run54 //55 // $ cmd help foo56 //57 // but "cmd" has no registered subcommands.58 pp = parent59 } else if sub, ok := parent.Commands[args[0]]; ok {60 // The user has run61 //62 // $ cmd help foo63 //64 // and the "foo" subcommand has been65 // registered.66 pp = sub67 }68 // If pp hasn't been set, this means that the user has69 // intended to print the help message of a subcommand,70 // but that subcommand does not exist.71 if pp == nil {72 return errors.Errorf("no such command: %q", args[0])73 }74 if pp.Flags == nil {75 fmt.Fprintf(os.Stderr, "%s - %s\n", pp.Name, pp.Description)76 printSubcommands(pp)77 } else {78 pp.Flags.Usage()79 }80 return nil81 },82 }83}84// printSubcommands is a helper function, used when calling a "help"85// subcommand; it prints all of the registered subcommands of c, if any.86func printSubcommands(c *Cmd) {87 if c.Commands == nil {88 return89 }90 fmt.Fprintln(os.Stderr, "\nCommands")91 // Gather a list of all subcommand names, and sort them (for92 // consistent output).93 var subNames []string94 for name, _ := range c.Commands {95 subNames = append(subNames, name)96 }97 sort.Strings(subNames)98 tw := tabwriter.NewWriter(os.Stderr, 0, 4, 1, ' ', 0)99 defer tw.Flush()100 for _, name := range subNames {101 fmt.Fprintf(tw, "\t\t%s\t%s\n", name, c.Commands[name].Description)102 }103}104// New is a convenience function for creating and returning a new *Cmd.105//106// New will automatically add a "help" subcommand that, when called with no107// arguments, will print the help message for its parent command. If any108// arguments are provided to the "help" subcommand, only the first argument109// will be consulted, and it will print the help message for the specified110// subcommand.111//112// Note, that the following two command-line calls are effectively the same:113//114// $ my-command help <subcommand>115// $ my-command <subcommand> help116//117func New(name string, run RunFunc) *Cmd {118 c := &Cmd{119 Name: name,120 Flags: flag.NewFlagSet(name, flag.ExitOnError),121 Run: run,122 }123 c.Flags.Usage = newUsage(c)124 c.AddCmd(newHelpCmd(c))125 return c126}127// AddCmd registers a subcommand.128//129// AddCmd will panic if the given cmd's Name field is an empty string.130// If there is a subcommand already registered with the same name, it will be131// replaced.132func (c *Cmd) AddCmd(cmd *Cmd) {133 if c.Commands == nil {134 c.Commands = make(map[string]*Cmd)135 }136 if cmd.Name == "" {137 panic("cannot add nameless subcommand")138 }139 c.Commands[cmd.Name] = cmd140}141// Exec parses the arguments provided on the command line. This is the142// method that should be called from the outer-most command (e.g. the143// "root" command).144//145// It is essentially a short-hand invocation of146//147// c.ExecArgs(os.Args[1:])148//149func (c *Cmd) Exec() {150 c.ExecArgs(os.Args[1:])151}152// ExecArgs executes c.Run with the given arguments. If c.Run == nil,153// and no subcommand was provided as a positional argument, this method will154// print a usage message, and exit.155//156// To customize the usage message that is printed, set c.Flags.Usage (refer to157// the documentation for flag.FlagSet).158func (c *Cmd) ExecArgs(args []string) {159 // Make sure there is a non-nil flag set.160 if c.Flags == nil {161 c.Flags = flag.NewFlagSet(os.Args[0], flag.ExitOnError)162 }163 // Parse the given arguments.164 if err := c.Flags.Parse(args); err != nil {165 fmt.Fprintln(os.Stderr, "error parsing arguments:", err)166 os.Exit(2)167 }168 // If we have some registered subcommands, and the first positional169 // argument matches the name of one of the registered subcommands,170 // execute it.171 if c.Commands != nil && c.Flags.Arg(0) != "" {172 if sub, ok := c.Commands[c.Flags.Arg(0)]; ok {173 // Our first positional argument refers to a registered174 // subcommand.175 //176 // Run that subcommand.177 if c.Flags.NArg() > 1 {178 sub.ExecArgs(c.Flags.Args()[1:])179 } else {180 sub.ExecArgs(nil)181 }182 return183 }184 }185 // No subcommand was provided, and our main RunFunc is nil. Print a186 // usage message, and exit.187 if c.Run == nil {188 c.Flags.Usage()189 os.Exit(1)190 }191 // Call our RunFunc.192 if err := c.Run(c, c.Flags.Args()); err != nil {193 fmt.Fprintln(os.Stderr, "error:", err)194 os.Exit(1)195 }196}...
help.go
Source:help.go
...9type commandGroup struct {10 Title string11 Commands []*cobra.Command12}13// NewHelpCmd returns the help command14func NewHelpCmd(ec *cli.ExecutionContext) *cobra.Command {15 opts := &helpOptions{16 EC: ec,17 }18 var helpCmd = &cobra.Command{19 Use: "help",20 Short: "Help about any command",21 Long: "Help provides help for any command in the CLI",22 Run: func(cmd *cobra.Command, args []string) {23 opts.Cmd = cmd24 opts.Args = args25 opts.run()26 },27 }28 return helpCmd...
NewHelpCmd
Using AI Code Generation
1import (2func main() {3 app := cli.NewApp()4 app.Commands = []cli.Command{5 commands.NewHelpCmd(),6 }7 app.Run(os.Args)8}9import (10type Commands struct{}11func (c *Commands) NewHelpCmd() cli.Command {12 return cli.Command{13 Aliases: []string{"h"},14 Action: func(c *cli.Context) error {15 fmt.Println("Help action")16 },17 }18}19func NewCommands() *Commands {20 return &Commands{}21}22import (23func TestNewHelpCmd(t *testing.T) {24 c := NewCommands()25 cmd := c.NewHelpCmd()26 if cmd.Name != "help" {27 t.Errorf("Expected command name to be 'help', got %s", cmd.Name)28 }29 if cmd.Usage != "Show help" {30 t.Errorf("Expected command usage to be 'Show help', got %s", cmd.Usage)31 }32 os.Args = []string{"test", "help"}33 cmd.Action(nil)34}35--- FAIL: TestNewHelpCmd (0.00s)36func GetMap() map[string]func() {
NewHelpCmd
Using AI Code Generation
1cmd := commands.NewHelpCmd()2cmd.Execute()3cmd := commands.NewHelpCmd()4cmd.Execute()5cmd := commands.NewHelpCmd()6cmd.Execute()7cmd := commands.NewHelpCmd()8cmd.Execute()9cmd := commands.NewHelpCmd()10cmd.Execute()11cmd := commands.NewHelpCmd()12cmd.Execute()13cmd := commands.NewHelpCmd()14cmd.Execute()15cmd := commands.NewHelpCmd()16cmd.Execute()17cmd := commands.NewHelpCmd()
NewHelpCmd
Using AI Code Generation
1import (2func main() {3 fs := flag.NewFlagSet("help", flag.ExitOnError)4 helpCmd := commands.NewHelpCmd(fs, os.Stdout)5 fs.Var(helpCmd, "help", "Show help")6 fs.Parse(os.Args[1:])7 helpCmd.Print()8}9import (10func main() {11 fs := flag.NewFlagSet("help", flag.ExitOnError)12 helpCmd := commands.NewHelpCmd(fs, os.Stdout)13 fs.Var(helpCmd, "help", "Show help")14 fs.Parse(os.Args[1:])15 helpCmd.Print()16}17import (18func main() {19 fs := flag.NewFlagSet("help", flag.ExitOnError)20 helpCmd := commands.NewHelpCmd(fs, os.Stdout)21 fs.Var(helpCmd, "help", "Show help")22 fs.Parse(os.Args[1:])23 helpCmd.Print()24}25import (26func main() {27 fs := flag.NewFlagSet("help", flag.ExitOnError)
NewHelpCmd
Using AI Code Generation
1func main() {2 cli := &cli.Cli{}3 helpCmd := commands.NewHelpCmd(cli)4 cli.AddCommand(helpCmd)5 cli.Run()6}7func main() {8 cli := &cli.Cli{}9 helpCmd := &commands.HelpCmd{10 }11 cli.AddCommand(helpCmd)12 cli.Run()13}14func main() {15 cli := &cli.Cli{}16 cli.AddCommand(&commands.HelpCmd{17 })18 cli.Run()19}20func main() {21 cli := &cli.Cli{}22 cli.AddHelpCommand()23 cli.Run()24}25func main() {26 cli := &cli.Cli{}27 cli.AddHelpCommand("
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!