cli

package module
v0.0.0-...-0f41777 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2020 License: Apache-2.0 Imports: 7 Imported by: 0

README

cli - Versatile and lightweight cli package for go

GoDoc

The goal with this package is to provide a versatile git-style commandline interface while at the same time keep the overhead as small as possible.

Documentation

Overview

cli is an easy-to-use and fairly lightweight commandline parser inspired by python argparse and github.com/urfave/cli.

Index

Examples

Constants

View Source
const NewLine = "\n"

NewLine is OS specific.

Variables

View Source
var (
	HelpOption = &Flag{
		Name:  "help",
		Char:  'h',
		Type:  Bool,
		Usage: "Display this help message",
	}
	HelpCommand = &Command{
		Name:                "help",
		Usage:               "Show help for command given as argument",
		PositionalArguments: []string{"<command>"},
		Action:              helpCmd,
	}
)

Functions

This section is empty.

Types

type App

type App struct {
	// Name of the application - will also appear as the usage executable
	// in the help text.
	Name string
	// Description should give a short description of the application.
	Description string

	// Action defines the default action (main application) of the program.
	Action func(ctx *Context) error
	// Flags are the flags accessible at the root scope.
	Flags []*Flag
	// Commands are commands accessible at the root scope.
	Commands []*Command

	// DisableHelpOption disables the default <-h/--help> flag.
	DisableHelpOption bool
	// DisableHelpCommand disable the default <help> command.
	DisableHelpCommand bool
}
Example
// Getting Started with cli:
// There are only two steps for using this package:
// 1 - Define your App structure
// 2 - Run your app by passing commandline arguments to App.Run()

exampleAction := func(ctx *Context) error {
	fmt.Println("Hello World")
	// ctx.String/ctx.Bool/ctx.Int/ctx.Float returns the flag value
	// and whether the flag was explicitly set.
	val, set := ctx.String("example-boi")
	fmt.Printf("This is my flag value: %s\n", val)
	fmt.Printf("Was this flag set? %v\n", set)

	fmt.Println()
	fmt.Println("This is the main help text:")
	fmt.Println("```")
	ctx.GetParent().PrintHelp()

	fmt.Println("```")
	fmt.Println("Where as this is the usage text:")
	fmt.Println("````")
	ctx.GetParent().PrintUsage()
	fmt.Println("```")

	return nil
}

app := App{
	Name:        "example",
	Description: "Describe your app here...",
	Flags: []*Flag{
		{
			Name: "example-boi",
			Char: 'e',
			// String is default type if none is specified.
			Type:     String,
			MetaVar:  "STR",
			Default:  "default value",
			Choices:  []string{"must", "include", "default value"},
			EnvVar:   "INIT_FROM_ENVIRONMENT_VAR_IF_DEFINED",
			Required: false, // false is default
			Usage:    "Doesn't do much...",
		},
	},
	Commands: []*Command{
		{
			Name:               "example-cmd",
			Action:             exampleAction,
			Description:        "Describe me here...",
			Usage:              "Short summary of Description",
			InheritParentFlags: false,
			PositionalArguments: []string{"these", "will",
				"appear", "in", "usage", "text"},
			SubCommands: nil,
		},
	},
}
app.Run([]string{"example", "-e", "include", "example-cmd"})
Output:

Hello World
This is my flag value: include
Was this flag set? true

This is the main help text:
```
Usage: example [-e STR] [-h] {example-cmd,help}

Description:
  Describe your app here...

Commands:
  example-cmd           Short summary of Description
  help                  Show help for command given as argument

Optional flags:
  --example-boi/-e STR  Doesn't do much... {must, include, default value}
  --help/-h             Display this help message
```
Where as this is the usage text:
````
Usage: example [-e STR] [-h] {example-cmd,help}
```

func (*App) Run

func (app *App) Run(args []string) error

Run starts parsing the command-line arguments passed as args, and executes the action corresponding with the sequence of arguments. Any errors during parsing triggers the usage to be printed to the terminal.

type Command

type Command struct {
	// Name of the command.
	Name string

	// Action is the bootstrapping function of the command.
	Action func(*Context) error

	// Description contains a *longer* description of the command.
	Description string
	// Usage should give a short summary of the description.
	Usage string

	// Flags that the command accepts.
	Flags []*Flag
	// InheritParentFlags toggles whether the flags of the parent command (or
	// app) is accessible at the command's scope.
	InheritParentFlags bool
	// PositionalArguments notifies the help printer about positional
	// arguments.
	PositionalArguments []string
	// SubCommands are commands that are accessible under this scope.
	SubCommands []*Command
}

Command describes git-style commands such as `git <log|diff|commit>` etc. Each Command has it's own scope of flags and possible SubCommands.

func (*Command) Validate

func (cmd *Command) Validate() error

type Context

type Context struct {
	App     *App
	Command *Command
	// contains filtered or unexported fields
}

Context provides an interface to the parsed command and arguments. After parsing the command can be identified with the Context.Command.Name and the flag values are retrieved by the Context.<FlagType>(<Flag.Name>), where FlagType is one of the predefined FlagType constants and Flag.Name is the string value of flag; this set of functions also return a boolean describing whether the flag was parsed or explicitly set using the Context.Set function.

func NewContext

func NewContext(app *App, parent *Context, cmd *Command) (*Context, error)

NewContext creates a new context. The app argument is required and can't be nil, where as the parent context and command are optionally non-nil. The context is initialized from configurations specified in the app. Furthermore, the presence of a command argument determines the scope of the context (which flags will be reachable from the context).

func (*Context) Bool

func (ctx *Context) Bool(name string) (bool, bool)

Bool gets the value of the flag with the given name and returns whether the flag is set.

func (*Context) Float

func (ctx *Context) Float(name string) (float64, bool)

Int gets the value of the flag with the given name and returns whether the flag is set

func (*Context) Free

func (ctx *Context) Free()

Free releases all internal lookup maps for garbage collection, after Free is called this context will always return empty value and false on flag queries.

func (*Context) GetParent

func (ctx *Context) GetParent() *Context

GetParent returns the parent context

func (*Context) GetPositionals

func (ctx *Context) GetPositionals() []string

GetPositionals returns the positional arguments under the scope of the context.

func (*Context) Int

func (ctx *Context) Int(name string) (int, bool)

Int gets the value of the flag with the given name and returns whether the flag is set

func (*Context) PrintHelp

func (ctx *Context) PrintHelp() error

PrintHelp prints the help prompt of the context's scope (command/app).

func (*Context) PrintUsage

func (ctx *Context) PrintUsage() error

PrintUsage prints the usage string given the context's scope (command/app).

func (*Context) Set

func (ctx *Context) Set(flag, value string) error

Set flag to value as parsed from the command-line.

func (*Context) String

func (ctx *Context) String(name string) (string, bool)

String gets the value of the flag with the given name and returns whether the flag is set.

type Flag

type Flag struct {
	// Name of the flag, for a given Name the command-line option
	// becomes --Name.
	Name string
	// Char is an optional single-char alternative
	Char rune
	// The meta variable name that will displayed on help.
	MetaVar string
	// The type of the flag's value.
	Type FlagType
	// Default holds the default value of the flag.
	Default interface{}

	// Choices restricts the Values this flag can take to this set.
	Choices interface{}
	// Initialize default value from an environment variable the variable
	// is non-empty.
	EnvVar string
	// Required makes the flag required.
	Required bool
	// Usage is printed to the help screen - short summary of function.
	Usage string
	// contains filtered or unexported fields
}

func (*Flag) Set

func (f *Flag) Set(value string) error

func (*Flag) String

func (f *Flag) String() string

func (*Flag) Validate

func (f *Flag) Validate() error

type FlagType

type FlagType uint8
const (
	String FlagType = iota
	Bool
	Int
	Float
)

func (FlagType) CastSlice

func (ft FlagType) CastSlice(slice interface{}) ([]interface{}, bool)

func (FlagType) Equal

func (ft FlagType) Equal(value interface{}) bool

func (FlagType) Nil

func (ft FlagType) Nil() interface{}

func (FlagType) String

func (ft FlagType) String() string

type HelpPrinter

type HelpPrinter struct {

	// RightMargin and LeftMargin specifies the margins for the Write func.
	RightMargin int
	LeftMargin  int
	// contains filtered or unexported fields
}

HelpPrinter provides an interface for printing the help message.

func NewHelpPrinter

func NewHelpPrinter(ctx *Context, out io.Writer) *HelpPrinter

NewHelpPrinter creates a help printer initialized with the context ctx. Using PrintHelp will create a help prompt based on ctx that will be written to out.

func (*HelpPrinter) PrintHelp

func (hp *HelpPrinter) PrintHelp() error

PrintHelp prints a verbose formatted help message with usage strings and description. If the flag has a default value, the value is appended to the usage string in square brackets.

func (*HelpPrinter) PrintUsage

func (hp *HelpPrinter) PrintUsage() error

PrintUsage prints the usage string hinting all available and required flags and commands without the usage strings.

func (*HelpPrinter) Write

func (hp *HelpPrinter) Write(p []byte) (int, error)

Write function which makes the HelpPrinter conform with the io.Writer interface. The printer attempts to insert newlines at word boundaries and satisfy the margin constrains in the HelpPrinter structure.

NOTE: The returned length is that of the bytes written to the buffer
      that includes indentation and inserted newlines.

Jump to

Keyboard shortcuts

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