broccli

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2023 License: BSD-2-Clause Imports: 12 Imported by: 0

README

go-broccli

Go Reference


Package bitsnops/broccli is meant to make handling command line interface easier.

You define commands with arguments, flags, attach a handler to it and package does all the parsing.


Install

Ensure you have your workspace directory created and run the following:

go get -u github.com/bitsnops/go-broccli/v2
Example

Let's start with an example covering everything. First, let's create main CLI instance and commands:

func main() {
    myCLI := broccli.NewCLI("Example", "App", "Author <a@example.com>")

    print := myCLI.AddCmd("print", "Prints out flags", func(c *CLI) int {
        fmt.Fprintf(os.Stdout, "Printing on the screen:\n%s\n%s\n\n", c.Flag("text1"), c.Arg("text2"))
        return 2
    })
    template := myCLI.AddCmd("template", "Process template", func(c *CLI) int {
        fmt.Fprintf(os.Stdout, "Do something here")
        return 0
    })
    start := myCLI.AddCmd("start", "Start the game", func(c *CLI) int {
        fmt.Fprintf(os.Stdout, "Do something here")
        return 0
    })
}

Next, let's add flags, args and required environments variables to our commands:

    print.AddFlag("text1", "a", "Text", "Text to print", TypeString, IsRequired)
    print.AddFlag("text2", "b", "Alphanum with dots", "Can have dots", TypeAlphanumeric, AllowDots)
    // If '-r' is passed, the '--text2'/'-b' flag is required
    print.AddFlag("make-text2-required", "r", "", "Make alphanumdots required", TypeBool, 0, OnTrue(func(c *Cmd) {
        c.flags["text2"].flags = c.flags["text2"].flags | IsRequired
    }))

    template.AddFlag("template", "t", "filepath", "Path to template file", TypePathFile, IsExistent|IsRequired)
    template.AddFlag("file-output", "o", "filepath", "Output to a specific file instead of stdout", TypePathFile, 0)
    template.AddFlag("number", "n", "int", "Number necessary for initialisation", TypeInt, IsRequired)

    start.AddFlag("verbose", "v", "", "Verbose mode", TypeBool, 0)
    start.AddFlag("username", "u", "username", "Username", TypeAlphanumeric, AllowDots|AllowUnderscore|IsRequired)
    start.AddFlag("threshold", "", "1.5", "Threshold, default 1.5", TypeFloat, 0)
    start.AddArg("input", "FILE", "Path to a file", TypePathFile, IRequired)
    start.AddArg("difficulty", "DIFFICULTY", "Level of difficulty (1-5), default 3", TypeInt, 0)

One of the arguments to AddFlag, AddArg or AddEnvVar is type of the value. It can be one of the Type* consts, eg. TypeInt, TypeBool, TypeString, TypePathFile etc.

Just next to the type, there is an argument that can contain additional validation flags, such as:

  • IsRequired when flag/arg is required;
  • AllowMultipleValues if flag/arg can have have multiple values, eg. 1,2,3, separated by comma or another character (there are flags for that such as SeparatorSemiColon etc.);
  • IsExistent which will cause a flag/arg to be checked if it exists;
  • IsRegularFile, IsDirectory, IsValidJSON and so on...

Check flags.go for more information on flag types.

And in the end of main() func:

    os.Exit(myCLI.Run())

Documentation

Index

Constants

View Source
const (
	// Command param type
	ParamFlag   = 1
	ParamArg    = 2
	ParamEnvVar = 3

	// Value types
	TypeString       = 0
	TypeBool         = 1
	TypeInt          = 2
	TypeFloat        = 3
	TypeAlphanumeric = 4
	TypePathFile     = 5

	// Validation
	// IsRequired means that the value is required
	IsRequired = 1
	// IsExistent is used with TypePathFile and requires file to exist
	IsExistent = 2
	// IsNotExistent is used with TypePathFile and requires file not to exist
	IsNotExistent = 4
	// IsDirectory is used with TypePathFile and requires file to be a directory
	IsDirectory = 8
	// IsRegularFile is used with TypePathFile and requires file to be a regular file
	IsRegularFile = 16
	// IsValidJSON is used with TypeString or TypePathFile with RegularFile to check if the contents are a valid JSON
	IsValidJSON = 32

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

	// 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 = 16384
	// SeparatorColon works with AllowMultipleValues and sets colon to be the value separator, instead of colon.
	SeparatorColon = 32768
	// SeparatorSemiColon works with AllowMultipleValues and sets semi-colon to be the value separator.
	SeparatorSemiColon = 65536
)
View Source
const VERSION = "2.0.0"

Variables

This section is empty.

Functions

func OnPostValidation

func OnPostValidation(fn func(c *Cmd) error) cmdOption

func OnTrue

func OnTrue(fn func(c *Cmd)) paramOption

Types

type CLI

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

CLI 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 Cmd). Optionally, it is possible to require environment variables.

func NewCLI

func NewCLI(n string, d string, a string) *CLI

NewCLI returns pointer to a new CLI instance with specified name, description and author. All these are used when displaying syntax help.

func (*CLI) AddCmd

func (c *CLI) AddCmd(n string, d string, h func(cli *CLI) int, opts ...cmdOption) *Cmd

AddCmd returns pointer to a new command with specified name, description 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 cmdOption for more info.

func (*CLI) AddEnvVar

func (c *CLI) AddEnvVar(n string, d string)

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

func (*CLI) Arg

func (c *CLI) Arg(n string) string

Arg returns value of arg.

func (*CLI) Flag

func (c *CLI) Flag(n string) string

Flag returns value of flag.

func (*CLI) Run

func (c *CLI) Run() 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 Cmd

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

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

func (*Cmd) AddArg

func (c *Cmd) AddArg(n string, hv string, d string, t int64, f int64, opts ...paramOption)

AddArg 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 (*Cmd) AddEnvVar

func (c *Cmd) AddEnvVar(n string, d string, t int64, f int64, opts ...paramOption)

AddEnvVar 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 (*Cmd) AddFlag

func (c *Cmd) AddFlag(n string, a string, hv string, d string, t int64, f int64, opts ...paramOption)

AddFlag 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, description, 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.

Jump to

Keyboard shortcuts

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