Documentation
¶
Overview ¶
Package cmdrec provides facilities for implementing a CLI application with subcommands.
Example ¶
package main
import (
"fmt"
"log"
"testing/fstest"
"codeberg.org/bci/cmdrec"
"github.com/google/shlex"
)
// Config manages the mocked database handle to our todo app's
// persistent internal state. Subcommands by nature must interact with
// the database, and are therefore implemented as methods of Config in
// this example.
type Config struct {
db map[string]bool
}
// The add command adds the specified items to the todo list.
func (cfg Config) add(args []string) error {
addCmd, err := cmdrec.Define("add", "docs/add.md", "", nil)
if err != nil {
return err
}
items := addCmd.DelimitedValues("items", "items to do later", nil)
if err := addCmd.Parse(args); err != nil {
return err
}
log.Print(items)
numItems := 0
for _, item := range items.All() {
cfg.db[item] = true
numItems++
}
// Report the number of items added.
fmt.Printf("Added %d items to todo list\n", numItems)
return nil
}
// addargs is an alternate implementation of the "add" subcommand that
// accepts todo-list items as raw positional arguments instead of
// using a flag to consume them. The "ITEMS" string is used solely by
// the documentation to indicate that this command does in fact accept
// raw positional arguments.
func (cfg Config) addargs(args []string) error {
addCmd, err := cmdrec.Define("addargs", "docs/addargs.md", "ITEMS", nil)
if err != nil {
return err
}
if err := addCmd.Parse(args); err != nil {
return err
}
numItems := 0
for _, item := range addCmd.Args() {
cfg.db[item] = true
numItems++
}
// Report the number of items added.
fmt.Printf("Added %d items to todo list\n", numItems)
return nil
}
// The list command lists our todo items. While no args are used by
// the command itself, we still call [*cmdrec.Command.Parse] to enable
// use of the help flag (-h/-help).
func (cfg Config) list(args []string) error {
listCmd, err := cmdrec.Define("list", "docs/list.md", "", nil)
if err != nil {
return err
}
if err := listCmd.Parse(args); err != nil {
return err
}
for item := range cfg.db {
fmt.Println(item)
}
return nil
}
// The reset command resets our database to a clean state with no
// items. Again, args are parsed so that we have access to -h/-help.
func (cfg Config) reset(args []string) error {
resetCmd, err := cmdrec.Define("reset", "docs/reset.md", "", nil)
if err != nil {
return err
}
if err := resetCmd.Parse(args); err != nil {
return err
}
numCleared := len(cfg.db)
cfg.db = make(map[string]bool)
fmt.Printf("Cleared %d rows\n", numCleared)
return nil
}
// The todo_demo command is our top-level application. It drives all
// the other todo-list commands.
func (cfg Config) todo_demo(args []string) error {
// Depending on how we organize our code, each subcommand can
// also be defined under its own package, and thus is free to
// define a package-level ActionMap specifying its
// subcommands.
commands := cmdrec.ActionMap{
"add": cfg.add,
"addargs": cfg.addargs,
"list": cfg.list,
"reset": cfg.reset,
}
todoCmd, err := cmdrec.Define("todo_demo", "docs/todo_demo.md", "", commands)
if err != nil {
return err
}
displayWelcome := todoCmd.Fs.Bool("w", false, "Display a welcome message")
if err := todoCmd.Parse(args); err != nil {
return err
}
if *displayWelcome {
fmt.Println("Welcome to TODO")
}
return todoCmd.Dispatch()
}
func runCommandLine(cfg Config, commandLine string) {
tokens, err := shlex.Split(commandLine)
if err != nil {
panic(err)
}
// Kick off the application logic. For the command
// documentation files, use a mock filesystem in place of the
// usual embedded one.
fsys := fstest.MapFS{
"docs/add.md": {},
"docs/addargs.md": {},
"docs/list.md": {},
"docs/reset.md": {},
"docs/todo_demo.md": {},
}
args := tokens[1:]
if err := cmdrec.Start(cfg.todo_demo, fsys, args...); err != nil {
panic(err)
}
}
func main() {
// Set up all the database administrivia.
dbEmpty := make(map[string]bool)
runCommandLine(Config{dbEmpty}, "todo_demo add -items cook,clean")
dbFull := map[string]bool{
"cook": true,
"clean": true,
}
runCommandLine(Config{dbFull}, "todo_demo list")
runCommandLine(Config{dbFull}, "todo_demo addargs cook clean")
}
Output: Added 2 items to todo list cook clean Added 2 items to todo list
Index ¶
- Variables
- func ParentCommandName() string
- func ScopedBool(name string) (bool, error)
- func ScopedInt(name string) (int, error)
- func ScopedInt64(name string) (int64, error)
- func ScopedString(name string) (string, error)
- func Start(action Action, docFS fs.FS, args ...string) error
- type Action
- type ActionMap
- type Command
- func (cmd Command) Args() []string
- func (cmd Command) DelimitedValues(name, usage string, defaultValues []string) *delimitedValues
- func (cmd Command) Dispatch() error
- func (cmd Command) Error() string
- func (cmd *Command) Parse(args []string) error
- func (cmd *Command) Run(args []string) error
- func (cmd Command) SetScopedBool(name string, defaultValue bool, usage string)
- func (cmd Command) SetScopedInt(name string, defaultValue int, usage string)
- func (cmd Command) SetScopedInt64(name string, defaultValue int64, usage string)
- func (cmd Command) SetScopedString(name string, defaultValue string, usage string)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrMissingSubcommand = fmt.Errorf("missing subcommand (see available subcommands)")
ErrMissingSubcommand flags a missing subcommand. It can be intercepted by callers of Command.Dispatch to handle a special case where a command has subcommands, but can also work with positional arguments (or else have some other effect) in case no subcommand is provided.
Functions ¶
func ParentCommandName ¶
func ParentCommandName() string
ParentCommandName returns the name of the last command that was dispatched, i.e., the name of the current command's parent command.
func ScopedBool ¶
ScopedBool retrieves the value of the bool flag associated with the given name. If no such flag exists, an error is returned.
func ScopedInt ¶
ScopedInt retrieves the value of the int flag associated with the given name. If no such flag exists, an error is returned.
func ScopedInt64 ¶
ScopedInt64 retrieves the value of the int64 flag associated with the given name. If no such flag exists, an error is returned.
func ScopedString ¶
ScopedString retrieves the value of the string flag associated with the given name. If no such flag exists, an error is returned.
func Start ¶
Start initiates the applications entry point, represented by the action parameter, which is assumed to define the top-level subcommand.
If there are no args parameters, it is assumed that os.Args[1:] is the intended set of command-line arguments. A non-empty list of args parameters is mainly used in the context of black-box testing.
While it is entirely possible to start a program by running the application programmer's top-level action function directly, calling Start is recommended, for several reasons:
1. Start ensures that os.Args[1:] is used as the argument passed to the given top-level action (see Action.)
2. Start takes care of printing a help page to the console when applicable (e.g. when -h is given.)
3. Start generates HTML documentation for the client application, depending on whether CMDREC_HTMLDOC_DIR is set in the environment.
Types ¶
type Action ¶
Action is a programmer-defined function that accepts the command's arguments as a string slice. It returns any error that the programmer deems appropriate.
type Command ¶
type Command struct {
// Fs is used for adding local flags to this Command's
// underlying FlagSet.
Fs *flag.FlagSet
// contains filtered or unexported fields
}
Command represents a CLI command. A Command can have more subcommands underneath it, or else be a leaf command.
The Fs field is exported to allow client code to add local flags to a subcommand.
func Define ¶
Define creates and returns a new Command. The name parameter is passed directly to the underlying flag set.
The descriptionPath parameter is the path to this command's documentation in the configured filesystem.
The actionMap parameter defines the subcommands supported by the new Command (see Action and ActionMap).
func (Command) Args ¶
Args returns the non-flag arguments of this subcommand. This should only be called after calling Command.Parse.
func (Command) DelimitedValues ¶
DelimitedValues is syntactic sugar for using [delimitedValues] as a custom flag. Because it sets a flag on the Command object's underlying flag set, DelimitedValues must be called before the parsing step.
The default delimiter is a comma (","). Note that the empty string is an acceptable delimiter, in which case the input string to the corresponding flag gets exploded, viz.,
-flag boom
would result in the values "b", "o", "o", and "m".
Certain strings (like "&") are reserved by command shells, and shouldn't be used without surrounding the given argument with single-quotes, for example,
-flag 'a&b&c'
Delimited values with spaces also require single-quotes:
- flag 'birthday cake,gift card,presents'
It's also possible to configure a pre-loaded set of values to DelimitedValues, that serve as the default in case the respective flag isn't supplied. Suppose we've built an app called "count" which takes a values flag that accepts a comma-separated list of numbers and then prints them, viz.,
./count -values 3,1,4,1,5,9
→ 314159
./count -values 2,7,1,8,2,8
→ 271828
As the author of "count", I might feel inclined to supply a default set of numbers, say, "5,4,3,2,1":
./count
→ 54321
Such default values are appropriately reported in the command's usage (i.e. -h or -help) output.
func (Command) Dispatch ¶
Dispatch runs the subcommand provided to this command, forwarding that subcommand's error to the caller of Dispatch.
func (Command) Error ¶
Error implements the error interface for Command. This helps Start detect whether the usage page needs to be displayed to the user.
func (*Command) Parse ¶
Parse parses the given subarguments with respect to the Command's underlying flag set. If the underlying FlagSet parse operation encounters an error — or else if help is requested via -h — the Command's err field is set to an appropriate error, and the Command itself is returned as the error value.
Otherwise the parsed set of non-flag arguments is returned.
func (*Command) Run ¶
Run is an abbreviation for Command.Parse followed by Command.Dispatch. This is useful in cases where a command doesn't use any flags, and thus nothing need happen between the parsing and dispatching steps.
func (Command) SetScopedBool ¶
SetScopedBool sets a scoped boolean flag.
func (Command) SetScopedInt ¶
SetScopedInt sets a scoped int flag.
func (Command) SetScopedInt64 ¶
SetScopedInt64 sets a scoped int64 flag.