broccli

package module
v3.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2025 License: BSD-2-Clause Imports: 15 Imported by: 6

README

broccli

Go Reference Go Report Card


The keenbytes/broccli/v3 package simplifies command line interface management. It allows you to define commands complete with arguments and flags, and attach handlers to them. The package handles all the parsing automatically.

v3 is not compatible with v2. The latest version requires a context in handlers and when calling Run method. Also methods for adding commands, args etc. have been shortened to Command, Arg, Flag and Env.


Table of Contents

Sample code

Example dummy application can be found in cmd/example1 directory.

However, the following code snippet from another tiny project shows how the module can be used.

Import the code with the following URL:

import "github.com/keenbytes/broccli/v3"
// create new CLI object
cli := broccli.NewBroccli("snakey-letters", "Classic snake but with letters and words!", "")

// add a command and attach a function to it
cmd := cli.Command("start", "Starts the game", startHandler)
// add a flag to the command
cmd.Flag("words", "f", "", 
    "Text file with wordlist", 
    // should be a path to a file
    broccli.TypePathFile,
    // flag is required (cannot be empty) and path must exist
    broccli.IsExistent|broccli.IsRequired,
)

// add another command to print version number
_ = cli.Command("version", "Shows version", versionHandler)

// run cli
os.Exit(cli.Run(context.Background()))

// handlers for each command
func startHandler(ctx context.Context, c *broccli.CLI) int {
	fmt.Fprint(os.Stdout, "Starting with file %s...", c.Flag("words"))
	return 0
}

func versionHandler(ctx context.Context, c *broccli.CLI) int {
    fmt.Fprintf(os.Stdout, VERSION+"\n")
    return 0
}

Structs explained

Broccli

The main Broccli object has three arguments such as name, usage and author. These guys are displayed when syntax is printed out.

Commands

Method AddCmd creates a new command which has the following properties.

  • a name, used to call it
  • short usage - few words to display what the command does on the syntax screen
  • handler function that is executed when the command is called and all its flags and argument are valid
Command Options

Optionally, after command flags and arguments are successfully validated, and just before the execution of handler, additional code (func) can be executed. This can be passed as a last argument.

cmd := cli.Command("start", "Starts the game", startHandler, 
    broccli.OnPostValidation(func(c *broccli.Cmd) {
        // do something, even with the command
    }),
)

See cmd_options.go for all available options.

Flags and Arguments

Each command can have arguments and flags, as shown below.

program some-command -f flag1 -g flag2 ARGUMENT1 ARGUMENT2

To setup a flag in a command, method AddFlag is used. It takes the following arguments:

  • name and alias that are used to call the flag (eg. --help and -h, without the hyphens in the func args)
  • valuePlaceholder, a placeholder that is printed out on the syntax screen, eg. in -f PATH_TO_FILE it is the PATH_TO_FILE
  • usage - few words telling what the command does (syntax screen again)
  • types, an int64 value that defines the value type, currently one of TypeString, TypeBool, TypeInt, TypeFloat, TypeAlphanumeric or TypePathFile (see flags.go for more information)
  • flags, an int64 value containing validation requirement, eg. IsRequired|IsExistent|IsDirectory could be used with TypePathFile to require the flag to be a non-empty path to an existing directory (again, navigate to flags.go for more detailed information)

Optionally, a function can be attached to a boolean flag that is triggered when a flag is true. The motivation behind that was a use case when setting a certain flag to true would make another string flag required. However, it's not recommended to be used.

To add an argument for a command, method Arg shall be used. It has almost the same arguments, apart from the fact that alias is not there.

Environment variables to check

Command may require environment variables. Env can be called to setup environment variables that should be verified before running the command. For example, a variable might need to contain a path to an existing regular file.

Accessing flag and arg values

See sample code that does that below.

func startHandler(ctx context.Context, c *broccli.CLI) int {
	fmt.Fprint(os.Stdout, "Starting with level %s...", c.Arg("level"))
    fmt.Fprint(os.Stdout, "Writing moves to file %s...", c.Flag("somefile"))
	return 0
}

level and somefile are names of the argument (sometimes they are uppercase) and flag.

Features

  • Flags and arguments support
  • Validation for basic value types such as integer, float, string, bool
  • Additional value types of alpha-numeric and file path
  • Validation for multiple values, separated with colon or semicolon, eg. -t val1,val2,val3
  • Check for file existence and its type (can be directory, regular file or other)
  • Post validation hook
  • Boolean flag on-true hook before validation
  • Handlers require context

Documentation

Overview

Package broccli is meant to make handling command line interface easier. Define commands with arguments, flags, attach a handler to it and package will do all the parsing.

Index

Constants

View Source
const (

	// ParamFlag sets param to be a command flag.
	ParamFlag
	// ParamFlag sets param to be a command arg.
	ParamArg
	// ParamFlag sets param to be an environment variable.
	ParamEnvVar
)

Command param type.

View Source
const (
	// TypeString requires param to be a string.
	TypeString = iota * 1
	// TypeBool requires param to be a boolean.
	TypeBool
	// TypeInt requires param to be an integer.
	TypeInt
	// TypeFloat requires param to be a float.
	TypeFloat
	// TypeAlphanumeric requires param to contain numbers and latin letters only.
	TypeAlphanumeric
	// TypePathFile requires param to be a path to a file.
	TypePathFile
)

Value types.

View Source
const (

	// IsRequired means that the value is required.
	IsRequired
	// IsExistent is used with TypePathFile and requires file to exist.
	IsExistent
	// IsNotExistent is used with TypePathFile and requires file not to exist.
	IsNotExistent
	// IsDirectory is used with TypePathFile and requires file to be a directory.
	IsDirectory
	// IsRegularFile is used with TypePathFile and requires file to be a regular file.
	IsRegularFile
	// IsValidJSON is used with TypeString or TypePathFile with RegularFile to check if the contents are a valid JSON.
	IsValidJSON

	// AllowDots can be used only with TypeAlphanumeric and additionally allows flag to have dots.
	AllowDots
	// AllowUnderscore can be used only with TypeAlphanumeric and additionally allows flag to have underscore chars.
	AllowUnderscore
	// AllowHyphen can be used only with TypeAlphanumeric and additionally allows flag to have hyphen chars.
	AllowHyphen

	// AllowMultipleValues allows param to have more than one value separated by comma by default.
	// For example: AllowMany with TypeInt allows values like: 123 or 123,455,666 or 12,222
	// AllowMany works only with TypeInt, TypeFloat and TypeAlphanumeric.
	AllowMultipleValues
	// SeparatorColon works with AllowMultipleValues and sets colon to be the value separator, instead of colon.
	SeparatorColon
	// SeparatorSemiColon works with AllowMultipleValues and sets semi-colon to be the value separator.
	SeparatorSemiColon
)

Validation.

View Source
const VERSION = "3.1.0"

VERSION is the current version of the module.

Variables

This section is empty.

Functions

This section is empty.

Types

type Broccli

type Broccli struct {
	// contains filtered or unexported fields
}

Broccli is main CLI application definition. It has a name, description, author which are printed out to the screen in the usage syntax. Each CLI have commands (represented by Command). Optionally, it is possible to require environment variables.

func NewBroccli

func NewBroccli(name, usage, author string) *Broccli

NewBroccli returns pointer to a new Broccli instance. Name, usage and author are displayed on the syntax screen.

func (*Broccli) Arg

func (c *Broccli) Arg(name string) string

Arg returns value of arg.

func (*Broccli) Command

func (c *Broccli) Command(
	name, usage string,
	handler func(ctx context.Context, cli *Broccli) int,
	opts ...CommandOption,
) *Command

Command returns pointer to a new command with specified name, usage and handler. Handler is a function that gets called when command is executed. Additionally, there is a set of options that can be passed as arguments. Search for commandOption for more info.

func (*Broccli) Env

func (c *Broccli) Env(name string, usage string)

Env returns pointer to a new environment variable that is required to run every command. Method requires name, eg. MY_VAR, and usage.

func (*Broccli) Flag

func (c *Broccli) Flag(name string) string

Flag returns value of flag.

func (*Broccli) Run

func (c *Broccli) Run(ctx context.Context) int

Run parses the arguments, validates them and executes command handler. In case of invalid arguments, error is printed to stderr and 1 is returned. Return value should be treated as exit code.

type Command

type Command struct {
	// contains filtered or unexported fields
}

Command represent a command which has a name (used in args when calling app), usage, a handler that is called. Such command can have flags and arguments. In addition to that, required environment variables can be set.

func (*Command) Arg

func (c *Command) Arg(
	name, valuePlaceholder, usage string,
	types, flags int64,
	opts ...ParamOption,
)

Arg adds an argument to a command and returns a pointer to Param instance. It is the same as adding flag except it does not have an alias.

func (*Command) Env

func (c *Command) Env(name, usage string, types, flags int64, _ ...ParamOption)

Env adds a required environment variable to a command and returns a pointer to Param. It's arguments are very similar to ones in previous AddArg and AddFlag methods.

func (*Command) Flag

func (c *Command) Flag(
	name, alias, valuePlaceholder, usage string,
	types, flags int64,
	opts ...ParamOption,
)

Flag adds a flag to a command and returns a pointer to Param instance. Method requires name (eg. 'data' for '--data', alias (eg. 'd' for '-d'), placeholder for the value displayed on the 'help' screen, usage, type of the value and additional validation that is set up with bit flags, eg. IsRequired or AllowMultipleValues. If no additional flags are required, 0 should be used.

type CommandOption added in v3.1.0

type CommandOption func(opts *commandOptions)

CommandOption defines an optional configuration function for commands, intended for specific use cases. It should not be created manually; use one of the predefined functions below.

func OnPostValidation

func OnPostValidation(fn func(c *Command) error) CommandOption

OnPostValidation attaches a function that is called once args, flags and env vars are validated.

type ParamOption added in v3.1.0

type ParamOption func(opts *paramOptions)

ParamOption defines an optional configuration function for args and flags, intended for specific use cases. It should not be created manually; use one of the predefined functions below.

func OnTrue

func OnTrue(fn func(command *Command)) ParamOption

OnTrue executes a specified function when boolean flag is true.

Directories

Path Synopsis
cmd
example1
main is an example broccli usage.
main is an example broccli usage.

Jump to

Keyboard shortcuts

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