cmdrec

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: GPL-3.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Description

cmdrec is a library for implementing command-line interfaces.

Specifically, cmdrec is an API that allows the developer to leverage the built-in flag package to define subcommands, including nested ones.

The flag package provides an example involving a single layer of subcommand, but the manner of implementing nested ones is less obvious. This library solves that.

Usage

Add cmdrec to your project in the usual manner:

go get codeberg.org/bci/cmdrec

Else, inculde the "codeberg.org/bci/cmdrec" import in your source, like so:

import _ "codeberg.org/bci/cmdrec"

Then, run go mod tidy, then remove the underscore. The underscore protects against a tool like goimports removing the import if unused.

Further documentation can be found at https://pkg.go.dev/codeberg.org/bci/cmdrec.

Goals

Stay within the confines of the built-in flag package's own design philosophy.

In other words, no attempt is made to conform with an existing command-line aesthetic other than that implied by flag itself.

Provide a user-friendly help system.

The number one cardinal rule of a command line application is that -h should display help for that application. To this end, I've spent a great deal of time adding features to cmdrec that encourage application programmers to write good documentation for their programs:

  • The -h or -help flags have been augmented to list available subcommands for a given command.

  • Command help pages now include a description taken from a user-supplied documentation directory. This directory must be embedded by the user into the client application's binary (cmdrec itself is a library, and therefore incapable of itself fulfilling this role on behalf of the user, unfortunately.) While entailing a bit of extra work, it obviates the need for storing the documentation in an OS system directory (e.g. /usr/share/doc.)

  • Client applications can generate a browseable set of HTML pages based on the Markdown files in the documentation directory. This creates a modern-looking and attractive view of a client application's documentation, which can be then included alongside any other online documentation for that application. The pages are styled using Simple CSS, with a few extra tweaks here and there.

  • The Glamour library is used to add minimalistic but sensible styling (e.g. boldface and underlining) to -h output printed on the terminal.

Motivation — why a new CLI args package?

While working on a separate CLI project, I experimented with different command-line libraries, including both the built-in flag package as well as third-party options like urfave. However, I found the latter overkill, and the former wanting. I only needed a slight improvement over what flag provides. In particular, I wanted to be able to support nested subcommands.

I was stumped over how to realize this improvement myself, so I consulted ChatGPT for some help (see full conversation here.) It turns out flag is perfectly up to the task.

Here's a relevant excerpt from that conversation, where the LLM makes a key point:

There is, however, an important distinction between: APP COMMAND -flag

and: APP COMMAND SUBCOMMAND -flag

In the latter case, SUBCOMMAND isn't a flag. It's a positional argument that selects another command parser. The nesting is therefore something you build around FlagSet, rather than something FlagSet itself understands.

I then set to build that nesting around FlagSet, and this package was born.

It should be noted that this library is completely hand-coded.

To be fair, my original goal, which led me to design this library was to build a CLI prototype of a more user-friendly GUI-style app (for example, something Web or mobile-based.) As a prototype, it need not obey all the expected niceties of modern Go command-line apps. In such a case, I may consider then looking into something like urfave or cobra once again.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func ScopedBool(name string) (bool, error)

ScopedBool retrieves the value of the bool flag associated with the given name. If no such flag exists, an error is returned.

func ScopedInt

func ScopedInt(name string) (int, error)

ScopedInt retrieves the value of the int flag associated with the given name. If no such flag exists, an error is returned.

func ScopedInt64

func ScopedInt64(name string) (int64, error)

ScopedInt64 retrieves the value of the int64 flag associated with the given name. If no such flag exists, an error is returned.

func ScopedString

func ScopedString(name string) (string, error)

ScopedString retrieves the value of the string flag associated with the given name. If no such flag exists, an error is returned.

func Start

func Start(action Action, docFS fs.FS, args ...string) error

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

type Action func([]string) error

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 ActionMap

type ActionMap map[string]Action

ActionMap declares the subcommands executed by a given command.

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

func Define(name, descriptionPath, argsLabel string, actionMap ActionMap) (*Command, error)

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

func (cmd Command) Args() []string

Args returns the non-flag arguments of this subcommand. This should only be called after calling Command.Parse.

func (Command) DelimitedValues

func (cmd Command) DelimitedValues(name, usage string, defaultValues []string) *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

func (cmd Command) Dispatch() error

Dispatch runs the subcommand provided to this command, forwarding that subcommand's error to the caller of Dispatch.

func (Command) Error

func (cmd Command) Error() string

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

func (cmd *Command) Parse(args []string) error

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

func (cmd *Command) Run(args []string) error

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

func (cmd Command) SetScopedBool(name string, defaultValue bool, usage string)

SetScopedBool sets a scoped boolean flag.

func (Command) SetScopedInt

func (cmd Command) SetScopedInt(name string, defaultValue int, usage string)

SetScopedInt sets a scoped int flag.

func (Command) SetScopedInt64

func (cmd Command) SetScopedInt64(name string, defaultValue int64, usage string)

SetScopedInt64 sets a scoped int64 flag.

func (Command) SetScopedString

func (cmd Command) SetScopedString(name string, defaultValue string, usage string)

SetScopedString sets a scoped string flag.

Directories

Path Synopsis
examples
todo command
Program todo is a mock CLI-based todo-app.
Program todo is a mock CLI-based todo-app.
internal
mock
Package todolist is a mock todo app used by the test suite.
Package todolist is a mock todo app used by the test suite.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL