github.com/richardwilkes/toolbox@v1.121.0/cmdline/cmd.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package cmdline
    11  
    12  import (
    13  	"github.com/richardwilkes/toolbox/errs"
    14  	"github.com/richardwilkes/toolbox/i18n"
    15  )
    16  
    17  // Cmd represents a sub-command available on the command-line.
    18  type Cmd interface {
    19  	// Name should return the name of the command as it needs to be entered on the command line.
    20  	Name() string
    21  	// Usage should return a description of what the command does.
    22  	Usage() string
    23  	// Run will be called to run the command. It will be passed a fresh command line created from the command line that
    24  	// was parsed to determine this command would be run, along with the arguments that have not yet been consumed. The
    25  	// first argument, much like an application called from main, will be the name of the command.
    26  	Run(cmdLine *CmdLine, args []string) error
    27  }
    28  
    29  func (cl *CmdLine) newWithCmd(cmd Cmd) *CmdLine {
    30  	cmdLine := New(false)
    31  	cmdLine.out = cl.out
    32  	cmdLine.parent = cl
    33  	cmdLine.cmd = cmd
    34  	return cmdLine
    35  }
    36  
    37  // AddCommand adds a command to the available commands.
    38  func (cl *CmdLine) AddCommand(cmd Cmd) {
    39  	if len(cl.cmds) == 0 {
    40  		hc := &helpCmd{}
    41  		cl.cmds[hc.Name()] = hc
    42  	}
    43  	cl.cmds[cmd.Name()] = cmd
    44  }
    45  
    46  // RunCommand attempts to run a command. Pass in the command line arguments, usually the result from calling Parse().
    47  func (cl *CmdLine) RunCommand(args []string) error {
    48  	if len(args) < 1 {
    49  		return errs.New(i18n.Text("Must specify a command name"))
    50  	}
    51  	cmd := cl.cmds[args[0]]
    52  	if cmd == nil {
    53  		return errs.Newf(i18n.Text("'%[1]s' is not a valid %[2]s command"), args[0], AppCmdName)
    54  	}
    55  	return cmd.Run(cl.newWithCmd(cmd), args[1:])
    56  }