broccli

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2023 License: BSD-2-Clause Imports: 12 Imported by: 1

README

go-broccli

Go Reference


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

You define commands with 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
Example

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

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

    cmdInit    := myCLI.AddCmd("init", "Initialises the project", InitHandler)
    cmdStart   := myCLI.AddCmd("start", "Start the application", StartHandler)
}

Next, let's add flags to our commands:

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

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

Fifth argument to NewCLIFlag is used to define what is the type of flag, is it required etc. It's an integer value and the following consts are available:

  • TypePathFile - flag is a path to a file (string);
  • MustExist - if added along with CLIFlagTypePathFile then path must exist;
  • Required - flag is required (this does not work with bool flag);
  • TypeString - flag is a string;
  • TypeBool - flag is boolean and will have a value of "true" or "false";
  • TypeAlphanumeric - flag is string and have to match [0-9a-zA-Z]+.

Check cli_flag.go for more information on flag types.

Finally, let's create functions to handle our commands. In below code, you can see that method Flag on CLI instance (passed as first argument) can be used to get a flag value.

func InitHandler(c *broccli.CLI) int {
    fmt.Fprintf(os.Stdout, "Template path: %s\n", c.Flag("template"))
    return 0
}

func StartHandler(c *broccli.CLI) int {
    fmt.Fprintf(os.Stdout, "Username: %s\n", c.Flag("username"))
    return 0
}

And in the end of main() func:

    os.Exit(myCLI.Run(os.Stdout, os.Stderr))

Documentation

Overview

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

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

Install

Ensure you have your workspace directory created.

Example

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

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

    cmdInit    := myCLI.AddCmd("init", "Initialises the project", InitHandler)
    cmdStart   := myCLI.AddCmd("start", "Start the application", StartHandler)
}

Next, let's add flags to our commands (inside main()):

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

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

Fifth argument to `NewCLIFlag` is used to define what is the type of flag, is it required etc. It's an integer value and the following `const`s are available:

  • TypePathFile - flag is a path to a file (string);
  • MustExist - if added along with CLIFlagTypePathFile then path must exist;
  • Required - flag is required (this does not work with bool flag);
  • TypeString - flag is a string;
  • TypeBool - flag is boolean and will have a value of "true" or "false".

Check cli_flag.go for more information on flag types.

Finally, let's create functions to handle our commands. In below code, you can see that method Flag on CLI instance (passed as first argument) can be used to get a flag value.

func InitHandler(c *broccli.CLI) int {
    fmt.Fprintf(os.Stdout, "Template path: %s\n", c.Flag("template"))
    return 0
}

func StartHandler(c *broccli.CLI) int {
    fmt.Fprintf(os.Stdout, "Username: %s\n", c.Flag("username"))
    return 0
}

And in the end of main() func:

os.Exit(myCLI.Run(os.Stdout, os.Stderr))

Index

Constants

View Source
const (
	// Required sets flag to be required.
	Required = 1
	// TypeString sets flag to be string.
	TypeString = 8
	// TypePathFile sets flag to be path to a file.
	TypePathFile = 16
	// TypeBool sets flag to be boolean.
	TypeBool = 32
	// TypeInt sets flag to be integer.
	TypeInt = 64
	// TypeFloat sets flag to be float.
	TypeFloat = 128
	// TypeAlphanumeric sets flag to be alphanumeric.
	TypeAlphanumeric = 256
	// MustExist sets flag must point to an existing file (required TypePathFile to be added as well).
	MustExist = 512
	// AllowMany allows flag 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.
	AllowMany = 1024
	// ManySeparatorColon works with AllowMany and sets colon to be the value separator, instead of colon.
	ManySeparatorColon = 2048
	// ManySeparatorSemiColon works with AllowMany and sets semi-colon to be the value separator.
	ManySeparatorSemiColon = 4096
	// AllowDots can be used only with TypeAlphanumeric and additionally allows flag to have dots.
	AllowDots = 8192
	// AllowUnderscore can be used only with TypeAlphanumeric and additionally allows flag to have underscore chars.
	AllowUnderscore = 16384
	// AllowHyphen can be used only with TypeAlphanumeric and additionally allows flag to have hyphen chars.
	AllowHyphen = 32768
	// TypeEmail sets flag to be an email (value is checked against a regular expression)
	TypeEmail = 65536
	// TypeFQDN sets flag to be a FQDN
	TypeFQDN = 131072
	// TypePathDir sets flag to be a directory
	TypePathDir = 262144
	// TypePathRegularFile sets flag to be a regular file
	TypePathRegularFile = 524288
	// ValidJSON sets flag to be a valid JSON. If it's a file then it's contents is checked. Otherwise it's the value
	ValidJSON = 1048576
)
View Source
const VERSION = "1.0.0"

Variables

This section is empty.

Functions

This section is empty.

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 used only when printing usage syntax), commands and pointers to File instances to which standard output or errors are printed (named respectively stdout and stderr).

func NewCLI

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

NewCLI creates new instance of CLI with name n, description d and author a and returns it.

func (*CLI) AddArgToCmds

func (c *CLI) AddArgToCmds(n string, hv string, d string, nf int32)

AddArg adds an argument to all attached commands.

func (*CLI) AddCmd

func (c *CLI) AddCmd(n string, d string, f func(cli *CLI) int) *CLICmd

AddCmd creates a new command with name n, description d and handler of f. It creates instance of CLICmd, attaches it to CLI and returns it.

func (*CLI) AddFlagToCmds

func (c *CLI) AddFlagToCmds(n string, a string, hv string, d string, nf int32, fn func(*CLICmd))

AddFlagToCmds adds a flag to all attached commands. It creates CLIFlag instance and attaches it.

func (*CLI) AddRequiredEnv added in v1.1.0

func (c *CLI) AddRequiredEnv(n string, d string, nf int32)

AddRequiredEnv create a new flag

func (*CLI) Arg

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

Arg returns value of arg.

func (*CLI) AttachCmd

func (c *CLI) AttachCmd(cmd *CLICmd)

AttachCmd attaches instance of CLICmd to CLI.

func (*CLI) AttachEnv added in v1.1.0

func (c *CLI) AttachEnv(flg *CLIFlag)

AttachEnv attaches instance of CLIFlag as a required env.

func (*CLI) Flag

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

Flag returns value of flag.

func (*CLI) GetCmd

func (c *CLI) GetCmd(k string) *CLICmd

GetCmd returns instance of CLICmd of command k.

func (*CLI) GetSortedCmds

func (c *CLI) GetSortedCmds() []string

GetSortedCmds returns sorted list of command names.

func (*CLI) PrintHelp

func (c *CLI) PrintHelp()

PrintHelp prints usage info to stdout file.

func (*CLI) PrintInvalidCmd

func (c *CLI) PrintInvalidCmd(cmd string)

PrintInvalidCmd prints invalid command error to stderr file.

func (*CLI) Run

func (c *CLI) Run(stdout *os.File, stderr *os.File) 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 behaves like exit code.

func (*CLI) SetStdin

func (c *CLI) SetStdin(stdin *os.File)

SetStdin sets stdin

type CLICmd

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

CLICmd represent a command which has a name (used in args when calling app), description, a handler and flags attached to it.

func NewCLICmd

func NewCLICmd(n string, d string, f func(cli *CLI) int) *CLICmd

NewCLICmd creates CLICmd instance with name n, description d and handler f and returns it.

func (*CLICmd) AddArg

func (c *CLICmd) AddArg(n string, hv string, d string, nf int32)

AddArg adds an argument to a command.

func (*CLICmd) AddFlag

func (c *CLICmd) AddFlag(n string, a string, hv string, d string, nf int32, fn func(*CLICmd))

AddFlag adds a flag to a command. It creates CLIFlag instance and attaches it.

func (*CLICmd) AddPostValidation

func (c *CLICmd) AddPostValidation(fn func(*CLI) error)

AddPostValidation attaches an additional validation function that is executed after the default CLI validation

func (*CLICmd) AddRequiredEnv added in v1.1.0

func (c *CLICmd) AddRequiredEnv(n string, d string, nf int32)

AddRequiredEnv adds a required environment variable to a command. It creates CLIFlag instance and attaches it.

func (*CLICmd) AttachArg

func (c *CLICmd) AttachArg(flag *CLIFlag)

AttachArg attaches instance of CLIFlag to CLICmd but as an argument.

func (*CLICmd) AttachEnv added in v1.1.0

func (c *CLICmd) AttachEnv(flag *CLIFlag)

AttachEnv attaches instance of CLIFlag to CLICmd as a required env.

func (*CLICmd) AttachFlag

func (c *CLICmd) AttachFlag(flag *CLIFlag)

AttachFlag attaches instance of CLIFlag to CLICmd.

func (*CLICmd) GetArg

func (c *CLICmd) GetArg(k string) *CLIFlag

GetArg returns instance of CLIFlag of argument k.

func (*CLICmd) GetFlag

func (c *CLICmd) GetFlag(k string) *CLIFlag

GetFlag returns instance of CLIFlag of flag k.

func (*CLICmd) GetFlags

func (c *CLICmd) GetFlags() []reflect.Value

GetFlags returns list of flag names.

func (*CLICmd) GetPostValidation

func (c *CLICmd) GetPostValidation() (fn func(*CLI) error)

GetPostValidation returns post validation function

func (*CLICmd) GetSortedArgs

func (c *CLICmd) GetSortedArgs() []string

GetSortedArgs returns arguments list of arg names sorted how they were added but required ones are first.

func (*CLICmd) GetSortedFlags

func (c *CLICmd) GetSortedFlags() []string

GetSortedFlags returns sorted list of flag names.

func (*CLICmd) PrintHelp

func (c *CLICmd) PrintHelp(cli *CLI)

PrintHelp prints command usage information to stdout file.

func (*CLICmd) Run

func (c *CLICmd) Run(cli *CLI) int

Run calls command handler.

type CLIFlag

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

CLIFlag represends flag. It has a name, alias, description, value that is shown when printing help and configuration which is an integer value. It can be for example Required|TypePathFile|MustExist.

func NewCLIFlag

func NewCLIFlag(n string, a string, hv string, d string, nf int32, fn func(*CLICmd)) *CLIFlag

NewCLIFlag creates instance of CLIFlag and returns it.

func (*CLIFlag) GetHelpLine

func (c *CLIFlag) GetHelpLine() string

GetHelpLine returns flag usage info that is used when printing help.

func (*CLIFlag) IsRequireValue

func (c *CLIFlag) IsRequireValue() bool

IsRequireValue returns true when flag requires a value (only bool one returns false).

func (*CLIFlag) ValidateValue

func (c *CLIFlag) ValidateValue(isArg bool, nz string, az string) error

ValidateValue takes value coming from --NAME and -ALIAS and validates it.

Jump to

Keyboard shortcuts

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