cli

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2019 License: MIT Imports: 3 Imported by: 3

README

cli

Simple library for building command line programs in Go.

Quick Start

To get started, simply add the repository to your project as an import path.

package main

import (
    "fmt"
    "os"

    "github.com/andrewpillar/cli"
)

func main() {
    c := cli.New()

    c.MainCommand(func(cmd cli.Command) {
        fmt.Println("Say something!")
    })

    helloCmd := c.Command("hello", func(cmd cli.Command) {
        count, err := cmd.Flags.GetInt("count")

        if err != nil {
            fmt.Fprintf(os.Stderr, "%s\n", err)
            os.Exit(1)
        }

        for i := 0; i < count; i++ {
            fmt.Println("Hello", cmd.Args.Get(0))
        }
    })

    helloCmd.AddFlag(&cli.Flag{
        Name:     "count",
        Short:    "-c",
        Long:     "--count",
        Argument: true,
        Default:  1,
    })

    if err := c.Run(os.Args[1:]); err != nil {
        fmt.Fprintf(os.Stderr, "%s\n", err)
        os.Exit(1)
    }
}

And here is what the above program will produce once it has been built and run.

$ say hello world --count 5
Hello world
Hello world
Hello world
Hello world
Hello world

Creating a Program

Before defining commands and flags for your program, we must first create a new one. This is done by calling the New function. This will return a pointer to the cli.Cli type, from which we will be able to define commands and flags for our program.

package main

import (
    "fmt"
    "os"

    "github.com/andrewpillar/cli"
)

func main() {
    c := cli.New()
}

Defining Commands

Within this library there are two types of commands, a single main command, and a regular command. The single main command has no name, and is run when no other command is specified for the program. Regular commands on the other hand, do have names.

Each command that is defined on the program will have a command handler associated with it. This handler is a simple callback function that takes a cli.Command type as its only argument. From this type, you will be able to access the arguments and flags that have been passed to the command.

The program's main command can be defined by calling the MainCommand method on the cli.Cli type we were returned from the New function. This method takes the command handler as its only argument.

c := cli.New()

c.MainCommand(func(cmd cli.Command) {
    fmt.Println("Say something!")
})

Regular commands are defined bu calling the Command method on the cli.Cli type. Unlike the MainCommand method, this takes two parameters, the name of the command and the command handler.

helloCmd := c.Command("hello", func(cmd cli.Command) {

})

Adding Flags

Flags can either be added to the entire program or individual commands. When a flag is added to the entire program, it will be passed down to every command and sub-command in the program.

Each time a command is defined with either the MainCommand or Command method, a pointer to the recently created command will be returned. The AddFlag method can then be called on the returned command to add a flag to that specific command.

helloCmd := c.Command("hello", func(cmd cli.Command) {

})

helloCmd.AddFlag(&cli.Flag{
    Name:     "count",
    Short:    "-c",
    Long:     "--count",
    Argument: true,
    Default:  1,
})

Program wide flags can be added by calling AddFlag directly on the cli.Cli type returned by New.

c := cli.New()

c.AddFlag(&cli.Flag{
    Name: "help",
    Long: "--help",
})

Working with Flags

Each flag added to a command will be given a name, along with a long and short version of that flag. The flag's name is what is used for accessing the underlying cli.Flag type. There are multiple methods on the Flags property on the cli.Command type. Each of the methods take the flag's name as their only argument.

If a flag has a value, then you would call the Get<Type> method on the Flags property to get the underlying value. A flag's value can either be string, int, int8, int16, int32, int64, float32, or float64.

helloCmd := c.Command("hello", func(cmd cli.Command) {
    count, err := cmd.Flags.GetInt("count")
})

The methods that involved returning number types, return multiple values, the parsed value, and an error.

Boolean flags can be checked against by calling IsSet, this method takes the flag's name much like the prior Get<Type> methods. However this will return true or false depending on whether the flag was set on the command.

helloCmd := c.Command("hello", func(cmd cli.Command) {
    if cmd.Flags.IsSet("help") {
    }

    count, err := cmd.Flags.GetInt("count")
})

If the same flag is passed multiple times to a single command, then you can retrieve all occurences of that flag with the GetAll method.

helloCmd := c.Command("hello", func(cmd cli.Command) {
    for _, flag := range cmd.Flags.GetAll("count") {
        count, err := flag.GetInt()
    }
})

The cli.Flag type has a Get<Type> method for each type the flag could be, along with an IsSet method.

Arguments

Arguments passed to the program, or an individual command, can be accessed via the Args property on the passed command. This type can be looped over, or individual arguments can be accessed by calling the Get method and passing the index of the argument you want.

c.Command("hello", func(cmd cli.Command) {
    fmt.Println("Hello", cmd.Args.Get(0))

    for _, arg := range cmd.Args {
        fmt.Println("Hello", arg)
    }
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cli

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

The CLI program itself, this stores all of the program commands, and program level flags.

func New

func New() *Cli

Create a new CLI program.

func (*Cli) AddFlag

func (c *Cli) AddFlag(f *Flag)

Add a flag to the entire program. This will be passed down to every other command in the program.

func (*Cli) Command

func (c *Cli) Command(name string, handler commandHandler) *Command

Add a command to the program, with the given name.

func (*Cli) MainCommand added in v1.1.0

func (c *Cli) MainCommand(handler commandHandler) *Command

Set the program's main command. This is invoked if no command can be found for running the program.

func (*Cli) Run

func (c *Cli) Run(argv []string) error

Run the CLI program using the given slice of argument strings. This assumes that the programs name itself has been removed from the start of the input slice.

if err := c.Run(os.Args[1:]); err != nil {
}

The errors returned from this method will be about unknown program commands or unknown flags.

type Command

type Command struct {

	// The name of the command that will be passed to the program for command
	// invocation.
	Name string

	// The arguments passed to the individual command. Starting out this will
	// be empty, and will be populated once the command's flags have been parsed
	// from the programs input arguments.
	Args args

	// The flags that have been added to the command. Starting out this will be
	// empty much like the command arguments. During parsing the command flags
	// will be set accordingly, whether they be value flags or boolean flags.
	Flags Flags
	// contains filtered or unexported fields
}

A command for your program, this can either be a main command, regular command or a sub-command.

func (*Command) AddFlag

func (c *Command) AddFlag(f *Flag) *Command

Add a flag to the current command. If the given flag is a global program flag, then set it on each of the command's sub-commands.

func (*Command) Command

func (c *Command) Command(name string, handler commandHandler) *Command

Create a new command with the given name, and given command handler.

func (Command) FullName

func (c Command) FullName() string

Get the full name of the current command. If the current command is a sub-command, then the command's name, and all grandparent command names will be concatenated into a hyphenated string.

func (Command) Run

func (c Command) Run()

Invoke the command's handler, and any flag handlers that are set on the flags on the command. If any of the flags on the command are exclusive then the command handle will not be invoked.

type Flag

type Flag struct {

	// The name of the flag. This is used to retrieve the flag from the flags
	// type that stores either the program's flags, or a command's flags.
	Name string

	// The short version of the flag. Typically a single letter value preprended
	// with a single '-'.
	Short string

	// The long version of the flag. Typically a hyphenated string value
	// prepended with a '--'.
	Long string

	// Whether the flag takes an argument. If set to true, then the flag's
	// argument will be parsed from the input strings. Listed below are the
	// three valid ways of specifying a flag's value:
	//
	//  -f arg
	//  --flag arg
	//  --flag=arg
	Argument bool

	// The default value of the flag if no value is given to the flag itself
	// during program program invocation.
	Default interface{}

	// The handler to invoke whenever the flag is set.
	Handler flagHandler

	// If a flag is exclusive then the flag's handler will be invoked, and the
	// flag's command will not be invoked.
	Exclusive bool
	// contains filtered or unexported fields
}

A flag for your program, or for the program's individual command.

func (Flag) GetFloat32 added in v1.1.0

func (f Flag) GetFloat32() (float32, error)

Attempt to parse the underlying flag string value to a float32 type.

func (Flag) GetFloat64 added in v1.1.0

func (f Flag) GetFloat64() (float64, error)

Attempt to parse the underlying flag string value to a float64 type.

func (Flag) GetInt added in v1.1.0

func (f Flag) GetInt() (int, error)

Attempt to parse the underlying flag string value to an int type.

func (Flag) GetInt16 added in v1.1.0

func (f Flag) GetInt16() (int16, error)

Attempt to parse the underlying flag string value to an int16 type.

func (Flag) GetInt32 added in v1.1.0

func (f Flag) GetInt32() (int32, error)

Attempt to parse the underlying flag string value to an int32 type.

func (Flag) GetInt64 added in v1.1.0

func (f Flag) GetInt64() (int64, error)

Attempt to parse the underlying flag string value to an int64 type.

func (Flag) GetInt8 added in v1.1.0

func (f Flag) GetInt8() (int8, error)

Attempt to parse the underlying flag string value to an int8 type.

func (Flag) GetString added in v1.1.0

func (f Flag) GetString() string

Get the underlying flag value as a string.

func (Flag) IsSet added in v1.1.0

func (f Flag) IsSet() bool

Return whether the flag has been set.

type Flags added in v1.1.0

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

func (Flags) GetAll added in v1.1.0

func (f Flags) GetAll(name string) []Flag

Get all of the flags for the given flag name.

func (Flags) GetFloat32 added in v1.1.0

func (f Flags) GetFloat32(name string) (float32, error)

Attempt to parse the first flag's value as a float32 for the given flag name.

func (Flags) GetFloat64 added in v1.1.0

func (f Flags) GetFloat64(name string) (float64, error)

Attempt to parse the first flag's value as a float64 for the given flag name.

func (Flags) GetInt added in v1.1.0

func (f Flags) GetInt(name string) (int, error)

Attempt to parse the first flag's value as an int for the given flag name.

func (Flags) GetInt16 added in v1.1.0

func (f Flags) GetInt16(name string) (int16, error)

Attempt to parse the first flag's value as an int16 for the given flag name.

func (Flags) GetInt32 added in v1.1.0

func (f Flags) GetInt32(name string) (int32, error)

Attempt to parse the first flag's value as an int32 for the given flag name.

func (Flags) GetInt64 added in v1.1.0

func (f Flags) GetInt64(name string) (int64, error)

Attempt to parse the first flag's value as an int64 for the given flag name.

func (Flags) GetInt8 added in v1.1.0

func (f Flags) GetInt8(name string) (int8, error)

Attempt to parse the first flag's value as an int8 for the given flag name.

func (Flags) GetString added in v1.1.0

func (f Flags) GetString(name string) string

Get the underlying flag value as a string for the given flag name.

func (Flags) IsSet added in v1.1.0

func (f Flags) IsSet(name string) bool

Return whether the flag has been set for the given flag name.

Jump to

Keyboard shortcuts

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