cli

package module
v0.0.0-...-46e7580 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2023 License: MIT Imports: 25 Imported by: 8

README

CLI

Documentation License Build Status Coverage Go Report Card

A simple package for building command line applications in Go. The API is influenced by https://github.com/urfave/cli package, but it is way more flexible. It provides the following features:

  • More extensible flag types such as URL, IP, JSON, YAML and so on. For more information see the docs
  • Data providers that allow setting the flag's value from different sources such as command line arguments, environment variables and etc.
  • Data conversion that allow conversion of data to a compatible data type accepted by the declared flag

Installation

Make sure you have a working Go environment. Go version 1.16.x is supported.

See the install instructions for Go.

To install CLI, simply run:

$ go get github.com/phogolabs/cli

Getting Started

package main

import (
	"fmt"
	"os"
	"syscall"

	"github.com/phogolabs/cli"
)

var flags = []cli.Flag{
	&cli.YAMLFlag{
		Name:     "config",
		Usage:    "Application Config",
		Path:     "/etc/app/default.conf",
		EnvVar:   "APP_CONFIG",
		Value:    &Config{},
		Required: true,
	},
	&cli.StringFlag{
		Name:     "listen-addr",
		Usage:    "Application TCP Listen Address",
		EnvVar:   "APP_LISTEN_ADDR",
		Value:    ":8080",
		Required: true,
	},
}

func main() {
	app := &cli.App{
		Name:      "prana",
		HelpName:  "prana",
		Usage:     "Golang Database Manager",
		UsageText: "prana [global options]",
		Version:   "1.0-beta-04",
		Flags:     flags,
		Action:    run,
		Signals:   []os.Signal{syscall.SIGTERM},
		OnSignal:  signal,
	}

	app.Run(os.Args)
}

// run executes the application
func run(ctx *cli.Context) error {
	fmt.Println("Application started")
	return nil
}

// signal handles OS signal
func signal(ctx *cli.Context, signal os.Signal) error {
	fmt.Println("Application signal", signal)
	return nil
}

Validation

You can set the Required field to true if you want to make some flags mandatory. If you need some customized validation, you can create a custom validator in the following way:

As a struct that has a Validate function:

type Validator struct{}

func (v *Validator) Validate(ctx *cli.Context, value interface{}) error {
	//TODO: your validation logic
	return nil
}

Then you can set the validator like that:

var flags = []cli.Flag{
	&cli.StringFlag{
		Name:      "name",
		EnvVar:    "APP_NAME",
		Validator: &Validator{},
	},
}

Contributing

We are open for any contributions. Just fork the project.

Documentation

Index

Constants

View Source
const (
	// ExitCodeErrorApp is the exit code on application error
	ExitCodeErrorApp = 1001
	// ExitCodeErrorFlag is the exit code on flag error
	ExitCodeErrorFlag = 1002
	// ExitCodeNotFoundFlag is the exit code when a flag is not found
	ExitCodeNotFoundFlag = 1003
	// ExitCodeNotFoundCommand is the exit code when a command is not found
	ExitCodeNotFoundCommand = 1004
)

Variables

This section is empty.

Functions

func Copyright(name string) string

Copyright creates a copyright message

func EnvOf

func EnvOf(items ...string) string

EnvOf formats a list of environment variables

func FlagFormat

func FlagFormat(flag Flag) string

FlagFormat formats a flag

Types

type ActionFunc

type ActionFunc func(*Context) error

ActionFunc is the action to execute when no subcommands are specified

type AfterFunc

type AfterFunc func(*Context) error

AfterFunc is an action to execute after any subcommands are run, but after the subcommand has finished it is run even if Action() panics

type App

type App struct {
	// The name of the program. Defaults to path.Base(os.Args[0])
	Name string
	// A short description of the usage of this command
	Usage string
	// Custom text to show on USAGE section of help
	UsageText string
	// A longer explanation of how the command works
	Description string
	// A short description of the arguments of this command
	ArgsUsage string
	// Compilation date
	Compiled time.Time
	// List of all authors who contributed
	Authors []*Author
	// Copyright of the binary if any
	Copyright string
	// Full name of command for help, defaults to full command name, including parent commands.
	HelpName string
	// Boolean to hide built-in help command
	HideHelp bool
	// Version of the program
	Version string
	// Boolean to hide built-in version flag and the VERSION section of help
	HideVersion bool
	// Signals are the signals that we want to handle
	Signals []os.Signal
	// List of commands to execute
	Commands []*Command
	// List of flags to parse
	Flags []Flag
	// Providers contains a list of all providers
	Providers []Provider
	// An action to execute before any subcommands are run, but after the context is ready
	// If a non-nil error is returned, no subcommands are run
	Before BeforeFunc
	// An action to execute after any subcommands are run, but after the subcommand has finished
	// It is run even if Action() panics
	After AfterFunc
	// An action to execute before provider execution
	BeforeInit BeforeFunc
	// An action to execute after provider execution
	AfterInit AfterFunc
	// The action to execute when no subcommands are specified
	// Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
	Action ActionFunc
	// Strategy enables comman retry logic
	Strategy BackOffStrategy
	// OnSignal occurs on system signal
	OnSignal SignalFunc
	// Execute this function if a usage error occurs.
	OnUsageError UsageErrorFunc
	// OnCommandNotFound is executed if the proper command cannot be found
	OnCommandNotFound CommandNotFoundFunc
	// Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to
	// function as a default, so this is optional.
	OnExitError ExitErrorHandlerFunc
	// Exit is the function used when the app exits. If not set defaults to os.Exit.
	Exit ExitFunc
	// Writer writer to write output to
	Writer io.Writer
	// ErrWriter writes error output
	ErrWriter io.Writer
}

App is the main structure of a cli application. It is recommended that an app be created with the cli.NewApp() function

func (*App) Run

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

Run is the entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination

type Author

type Author struct {
	// Name of the author
	Name string
	// Email of the author
	Email string
}

Author represents someone who has contributed to a cli project.

func (*Author) String

func (author *Author) String() string

String makes Author comply to the Stringer interface, to allow an easy print in the templating process

type BackOffProvider

type BackOffProvider struct {
	Provider Provider
	Strategy BackOffStrategy
}

BackOffProvider backoff the provider

func (*BackOffProvider) Provide

func (m *BackOffProvider) Provide(ctx *Context) error

Provide parses the args

type BackOffStrategy

type BackOffStrategy backoff.BackOff

BackOffStrategy represents the backoff strategy

type BeforeFunc

type BeforeFunc func(*Context) error

BeforeFunc is an action to execute before any subcommands are run, but after the context is ready if a non-nil error is returned, no subcommands are run

type BoolFlag

type BoolFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     bool
	Hidden    bool
	Validator Validator
}

BoolFlag is a flag with type bool

func (*BoolFlag) Get

func (f *BoolFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*BoolFlag) IsBoolFlag

func (f *BoolFlag) IsBoolFlag() bool

IsBoolFlag returns true if the flag is bool

func (*BoolFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*BoolFlag) String

func (f *BoolFlag) String() string

String returns the value as string

func (*BoolFlag) Validate

func (f *BoolFlag) Validate(ctx *Context) error

Validate validates the flag

type Command

type Command struct {
	// The name of the command
	Name string
	// A list of aliases for the command
	Aliases []string
	// A short description of the usage of this command
	Usage string
	// Custom text to show on USAGE section of help
	UsageText string
	// A longer explanation of how the command works
	Description string
	// A short description of the arguments of this command
	ArgsUsage string
	// The category the command is part of
	Category string
	// Boolean to hide this command from help or completion
	Hidden bool
	// Full name of command for help, defaults to full command name, including parent commands.
	HelpName string
	// Boolean to hide built-in help command
	HideHelp bool
	// Metadata information
	Metadata map[string]interface{}
	// List of child commands
	Commands []*Command
	// Treat all flags as normal arguments if true
	SkipFlagParsing bool
	// List of flags to parse
	Flags []Flag
	// Providers contains a list of all providers
	Providers []Provider
	// An action to execute before any subcommands are run, but after the context is ready
	// If a non-nil error is returned, no subcommands are run
	Before BeforeFunc
	// An action to execute after any subcommands are run, but after the subcommand has finished
	After AfterFunc
	// An action to execute before provider execution
	BeforeInit BeforeFunc
	// An action to execute after provider execution
	AfterInit AfterFunc
	// The action to execute when no subcommands are specified
	// Expects a cli.ActionFunc
	Action ActionFunc
	// Strategy enables comman retry logic
	Strategy BackOffStrategy
	// Execute this function if a usage error occurs.
	OnUsageError UsageErrorFunc
	// OnCommandNotFound is executed if the proper command cannot be found
	OnCommandNotFound CommandNotFoundFunc
}

Command is a command for a cli.App.

func NewHelpCommand

func NewHelpCommand() *Command

NewHelpCommand creates a new help command

func NewVersionCommand

func NewVersionCommand() *Command

NewVersionCommand creates a version command

func (*Command) Names

func (cmd *Command) Names() []string

Names returns the names including short names and aliases.

func (*Command) RunWithContext

func (cmd *Command) RunWithContext(ctx *Context) error

RunWithContext runs the command

func (*Command) VisibleCategories

func (cmd *Command) VisibleCategories() []*CommandCategory

VisibleCategories returns a slice of categories and commands that are Hidden=false

func (*Command) VisibleCommands

func (cmd *Command) VisibleCommands() []*Command

VisibleCommands returns a slice of the Commands with Hidden=false

func (*Command) VisibleFlags

func (cmd *Command) VisibleFlags() []Flag

VisibleFlags returns a slice of the Flags with Hidden=false

type CommandCategory

type CommandCategory struct {
	Name     string
	Commands []*Command
}

CommandCategory is a category containing commands.

func (*CommandCategory) VisibleCommands

func (category *CommandCategory) VisibleCommands() []*Command

VisibleCommands returns a slice of the Commands with Hidden=false

type CommandNotFoundFunc

type CommandNotFoundFunc func(*Context, string)

OnCommandNotFoundFunc is executed if the proper command cannot be found

type CommandsByName

type CommandsByName []*Command

CommandsByName is a slice of Command

func (CommandsByName) Len

func (c CommandsByName) Len() int

Len returns the length of the slice

func (CommandsByName) Less

func (c CommandsByName) Less(i, j int) bool

Less returns true if item at index i < item at index j

func (CommandsByName) Swap

func (c CommandsByName) Swap(i, j int)

Swap swaps two items

type Context

type Context struct {
	// Args are the command line arguments
	Args []string
	// Signal from the system
	Signal os.Signal
	// Command that owns the context
	Command *Command
	// Parent Context
	Parent *Context
	// Writer writer to write output to
	Writer io.Writer
	// ErrWriter writes error output
	ErrWriter io.Writer
	// Metadata store
	Metadata map[string]interface{}
}

Context represents the execution context

func (*Context) Bool

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

Bool looks up the value of a local BoolFlag, returns false if not found

func (*Context) Duration

func (ctx *Context) Duration(name string) time.Duration

Duration looks up the value of a local DurationFlag, returns 0 if not found

func (*Context) EnvVars

func (ctx *Context) EnvVars() map[string]string

EnvVars returns the environment variables.

func (*Context) Float32

func (ctx *Context) Float32(name string) float32

Float32 looks up the value of a local Float32Flag, returns 0 if not found

func (*Context) Float64

func (ctx *Context) Float64(name string) float64

Float64 looks up the value of a local Float64Flag, returns 0 if not found

func (*Context) Get

func (ctx *Context) Get(name string) interface{}

Get looks up the value of a local flag, returns nil if not found

func (*Context) GlobalBool

func (ctx *Context) GlobalBool(name string) bool

GlobalBool looks up the value of a global BoolFlag, returns false if not found

func (*Context) GlobalDuration

func (ctx *Context) GlobalDuration(name string) time.Duration

GlobalDuration looks up the value of a global DurationFlag, returns 0 if not found

func (*Context) GlobalFloat32

func (ctx *Context) GlobalFloat32(name string) float32

GlobalFloat32 looks up the value of a global Float64Flag, returns 0 if not found

func (*Context) GlobalFloat64

func (ctx *Context) GlobalFloat64(name string) float64

GlobalFloat64 looks up the value of a global Float64Flag, returns 0 if not found

func (*Context) GlobalGet

func (ctx *Context) GlobalGet(name string) interface{}

GlobalGet looks up the value of a global flag, returns nil if not found

func (*Context) GlobalHardwareAddr

func (ctx *Context) GlobalHardwareAddr(name string) net.HardwareAddr

GlobalHardwareAddr looks up the value of a global HardwareAddrFlag, returns nil if not found

func (*Context) GlobalIP

func (ctx *Context) GlobalIP(name string) net.IP

GlobalIP looks up the value of a global IPFlag, returns nil if not found

func (*Context) GlobalInt

func (ctx *Context) GlobalInt(name string) int

GlobalInt looks up the value of a global IntFlag, returns 0 if not found

func (*Context) GlobalInt64

func (ctx *Context) GlobalInt64(name string) int64

GlobalInt64 looks up the value of a global Int64Flag, returns 0 if not found

func (*Context) GlobalString

func (ctx *Context) GlobalString(name string) string

GlobalString looks up the value of a global StringFlag, returns "" if not found

func (*Context) GlobalStringSlice

func (ctx *Context) GlobalStringSlice(name string) []string

GlobalStringSlice looks up the value of a global StringSliceFlag, returns nil if not found

func (*Context) GlobalTime

func (ctx *Context) GlobalTime(name string) time.Time

GlobalTime looks up the value of a global TimeFlag, returns 0 if not found

func (*Context) GlobalUInt

func (ctx *Context) GlobalUInt(name string) uint

GlobalUInt looks up the value of a global UIntFlag, returns 0 if not found

func (*Context) GlobalUInt64

func (ctx *Context) GlobalUInt64(name string) uint64

GlobalUInt64 looks up the value of a global UInt64Flag, returns 0 if not found

func (*Context) GlobalURL

func (ctx *Context) GlobalURL(name string) *url.URL

GlobalURL looks up the value of a global URLFlag, returns nil if not found

func (*Context) HardwareAddr

func (ctx *Context) HardwareAddr(name string) net.HardwareAddr

HardwareAddr looks up the value of a local HardwareddrFlag, returns nil if not found

func (*Context) IP

func (ctx *Context) IP(name string) net.IP

IP looks up the value of a local IPFlag, returns nil if not found

func (*Context) Int

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

Int looks up the value of a local IntFlag, returns 0 if not found

func (*Context) Int64

func (ctx *Context) Int64(name string) int64

Int64 looks up the value of a local Int64Flag, returns 0 if not found

func (*Context) String

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

String looks up the value of a local StringFlag, returns "" if not found

func (*Context) StringSlice

func (ctx *Context) StringSlice(name string) []string

StringSlice looks up the value of a local StringSliceFlag, returns nil if not found

func (*Context) Time

func (ctx *Context) Time(name string) time.Time

Time looks up the value of a local TimeFlag, returns 0 if not found

func (*Context) UInt

func (ctx *Context) UInt(name string) uint

UInt looks up the value of a local UIntFlag, returns 0 if not found

func (*Context) UInt64

func (ctx *Context) UInt64(name string) uint64

UInt64 looks up the value of a local UInt64Flag, returns 0 if not found

func (*Context) URL

func (ctx *Context) URL(name string) *url.URL

URL looks up the value of a local URLFlag, returns nil if not found

type DurationFlag

type DurationFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     time.Duration
	Hidden    bool
	Required  bool
	Validator Validator
}

DurationFlag is a flag with type time.Duration

func (*DurationFlag) Get

func (f *DurationFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*DurationFlag) Set

func (f *DurationFlag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*DurationFlag) String

func (f *DurationFlag) String() string

String returns the value as string

func (*DurationFlag) Validate

func (f *DurationFlag) Validate(ctx *Context) error

Validate validates the flag

type EnvProvider

type EnvProvider struct{}

EnvProvider parses environment variables

func (*EnvProvider) Provide

func (p *EnvProvider) Provide(ctx *Context) error

Provide parses the args

type ExitCoder

type ExitCoder interface {
	Error() string
	Code() int
}

ExitCoder is the interface checked by `App` and `Command` for a custom exit code

type ExitError

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

ExitError fulfills both the builtin `error` interface and `ExitCoder`

func FlagError

func FlagError(prefix, name string, err error) *ExitError

FlagError makes a new ExitError for missing command

func NewExitError

func NewExitError(text string, code int) *ExitError

NewExitError makes a new ExitError

func NotFoundCommandError

func NotFoundCommandError(name string) *ExitError

NotFoundCommandError makes a new ExitError for missing command

func NotFoundFlagError

func NotFoundFlagError(name string) *ExitError

NotFoundFlagError makes a new ExitError for missing flags

func WrapError

func WrapError(err error) *ExitError

WrapError wraps an error as ExitError

func (*ExitError) Code

func (x *ExitError) Code() int

Code returns the exit code, fulfilling the interface required by `ExitCoder`

func (*ExitError) Error

func (x *ExitError) Error() string

Error returns the string message, fulfilling the interface required by `error`

func (*ExitError) Unwrap

func (x *ExitError) Unwrap() error

Unwrap returns the underlying error

func (ExitError) WithCode

func (x ExitError) WithCode(code int) *ExitError

WithCode creates a copy of the error with a code

func (*ExitError) Wrap

func (x *ExitError) Wrap(err error)

Wrap wraps an error

type ExitErrorCollector

type ExitErrorCollector []error

ExitErrorCollector is an error that wraps multiple errors.

func (ExitErrorCollector) Code

func (errs ExitErrorCollector) Code() int

Code returns the exit code, fulfilling the interface required by ExitCoder

func (ExitErrorCollector) Error

func (errs ExitErrorCollector) Error() string

Error implements the error interface.

func (ExitErrorCollector) IsEmpty

func (errs ExitErrorCollector) IsEmpty() bool

IsEmpty returns true if the collector is empty

func (ExitErrorCollector) Unwrap

func (errs ExitErrorCollector) Unwrap() error

Unwrap unwraps the error

func (*ExitErrorCollector) Wrap

func (errs *ExitErrorCollector) Wrap(err error)

Wrap wraps an error

type ExitErrorHandlerFunc

type ExitErrorHandlerFunc func(err error) error

OnExitErrorHandlerFunc is executed if provided in order to handle ExitError values returned by Actions and Before/After functions.

type ExitFunc

type ExitFunc func(code int)

ExitFunc is an exit function

type Flag

type Flag interface {
	String() string
	Set(string) error
	Get() interface{}
}

Flag is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)

If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes -name equivalent to -name=true rather than using the next command-line argument.

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

type FlagAccessor

type FlagAccessor struct {
	Flag  Flag
	Text  string
	IsSet bool
}

FlagAccessor access the flag's field

func NewFlagAccessor

func NewFlagAccessor(flag Flag) *FlagAccessor

NewFlagAccessor returns new flag accessor

func (*FlagAccessor) EnvVar

func (f *FlagAccessor) EnvVar() string

EnvVar of the flag

func (*FlagAccessor) Get

func (f *FlagAccessor) Get() interface{}

Get of the flag's value

func (*FlagAccessor) Hidden

func (f *FlagAccessor) Hidden() bool

Hidden of the flag

func (*FlagAccessor) IsBoolFlag

func (f *FlagAccessor) IsBoolFlag() bool

IsBoolFlag returns true if the flag is bool

func (*FlagAccessor) IsPathFlag

func (f *FlagAccessor) IsPathFlag() bool

IsPathFlag returns true if the flag is path

func (*FlagAccessor) Name

func (f *FlagAccessor) Name() string

Name of the flag

func (*FlagAccessor) Path

func (f *FlagAccessor) Path() string

Path of the flag

func (*FlagAccessor) ReadFrom

func (f *FlagAccessor) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads data from r until EOF or error. The return value n is the number of bytes read. Any error except EOF encountered during the read is also returned.

func (*FlagAccessor) Reset

func (f *FlagAccessor) Reset() error

Reset resets the value

func (*FlagAccessor) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*FlagAccessor) String

func (f *FlagAccessor) String() string

String returns the flag as string

func (*FlagAccessor) Usage

func (f *FlagAccessor) Usage() string

Usage of the flag

func (*FlagAccessor) Validate

func (f *FlagAccessor) Validate(ctx *Context) error

Validate validates the flag

func (*FlagAccessor) Value

func (f *FlagAccessor) Value() interface{}

Value of the flag

type FlagProvider

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

FlagProvider parses the CLI flags

func (*FlagProvider) Provide

func (p *FlagProvider) Provide(ctx *Context) error

Provide parses the args

type FlagsByName

type FlagsByName []Flag

FlagsByName is a slice of Flag

func (FlagsByName) Len

func (f FlagsByName) Len() int

Len returns the length of the slice

func (FlagsByName) Less

func (f FlagsByName) Less(i, j int) bool

Less returns true if item at index i < item at index j

func (FlagsByName) Swap

func (f FlagsByName) Swap(i, j int)

Swap swaps two items

type Float32Flag

type Float32Flag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     float32
	Hidden    bool
	Required  bool
	Validator Validator
}

Float32Flag is a flag with type float32

func (*Float32Flag) Get

func (f *Float32Flag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*Float32Flag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*Float32Flag) String

func (f *Float32Flag) String() string

String returns the value as string

func (*Float32Flag) Validate

func (f *Float32Flag) Validate(ctx *Context) error

Validate validates the flag

type Float64Flag

type Float64Flag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     float64
	Hidden    bool
	Required  bool
	Validator Validator
}

Float64Flag is a flag with type float64

func (*Float64Flag) Get

func (f *Float64Flag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*Float64Flag) Set

func (f *Float64Flag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*Float64Flag) String

func (f *Float64Flag) String() string

String returns the value as string

func (*Float64Flag) Validate

func (f *Float64Flag) Validate(ctx *Context) error

Validate validates the flag

type HardwareAddrFlag

type HardwareAddrFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     net.HardwareAddr
	Hidden    bool
	Required  bool
	Validator Validator
}

HardwareAddrFlag is a flag with type net.HardwareAddr

func (*HardwareAddrFlag) Get

func (f *HardwareAddrFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*HardwareAddrFlag) Set

func (f *HardwareAddrFlag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*HardwareAddrFlag) String

func (f *HardwareAddrFlag) String() string

String returns the value as string

func (*HardwareAddrFlag) Validate

func (f *HardwareAddrFlag) Validate(ctx *Context) error

Validate validates the flag

type IPFlag

type IPFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     net.IP
	Hidden    bool
	Required  bool
	Validator Validator
}

IPFlag is a flag with type net.IP

func (*IPFlag) Get

func (f *IPFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*IPFlag) Set

func (f *IPFlag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*IPFlag) String

func (f *IPFlag) String() string

String returns the value as string

func (*IPFlag) Validate

func (f *IPFlag) Validate(ctx *Context) error

Validate validates the flag

type Int64Flag

type Int64Flag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     int64
	Hidden    bool
	Required  bool
	Validator Validator
}

Int64Flag is a flag with type int64

func (*Int64Flag) Get

func (f *Int64Flag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*Int64Flag) Set

func (f *Int64Flag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*Int64Flag) String

func (f *Int64Flag) String() string

String returns the value as string

func (*Int64Flag) Validate

func (f *Int64Flag) Validate(ctx *Context) error

Validate validates the flag

type IntFlag

type IntFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     int
	Hidden    bool
	Required  bool
	Validator Validator
}

IntFlag is a flag with type int

func (*IntFlag) Get

func (f *IntFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*IntFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*IntFlag) String

func (f *IntFlag) String() string

String returns the value as string

func (*IntFlag) Validate

func (f *IntFlag) Validate(ctx *Context) error

Validate validates the flag

type JSONFlag

type JSONFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     interface{}
	Hidden    bool
	Required  bool
	Validator Validator
}

JSONFlag is a flag with type json document

func (*JSONFlag) Get

func (f *JSONFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*JSONFlag) IsPathFlag

func (f *JSONFlag) IsPathFlag() bool

IsPathFlag returns true if the flag is path

func (*JSONFlag) ReadFrom

func (f *JSONFlag) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads data from r until EOF or error. The return value n is the number of bytes read. Any error except EOF encountered during the read is also returned.

func (*JSONFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*JSONFlag) String

func (f *JSONFlag) String() string

String returns the value as string

func (*JSONFlag) Validate

func (f *JSONFlag) Validate(ctx *Context) error

Validate validates the flag

type Map

type Map map[string]interface{}

Map of key value pairs

type PathProvider

type PathProvider struct {
	IsPathFlag bool
}

PathProvider parses flags from file

func (*PathProvider) Provide

func (p *PathProvider) Provide(ctx *Context) error

Provide parses the args

type Provider

type Provider interface {
	Provide(*Context) error
}

Provider is the interface that parses the flags

type SignalFunc

type SignalFunc func(*Context, os.Signal) error

SignalFunc is an action to execute after a system signal

type StringFlag

type StringFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     string
	Hidden    bool
	Required  bool
	Validator Validator
}

StringFlag is a flag with type string

func (*StringFlag) Get

func (f *StringFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*StringFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*StringFlag) String

func (f *StringFlag) String() string

String returns the value as string

func (*StringFlag) Validate

func (f *StringFlag) Validate(ctx *Context) error

Validate validates the flag

type StringSliceFlag

type StringSliceFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     []string
	Hidden    bool
	Required  bool
	Validator Validator
}

StringSliceFlag is a flag with type *StringSlice

func (*StringSliceFlag) Get

func (f *StringSliceFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*StringSliceFlag) Reset

func (f *StringSliceFlag) Reset() error

Reset resets the valle

func (*StringSliceFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*StringSliceFlag) String

func (f *StringSliceFlag) String() string

String returns the value as string

func (*StringSliceFlag) Validate

func (f *StringSliceFlag) Validate(ctx *Context) error

Validate validates the flag

type TimeFlag

type TimeFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Format    string
	Value     time.Time
	Hidden    bool
	Required  bool
	Validator Validator
}

TimeFlag is a flag with type time.Time

func (*TimeFlag) Get

func (f *TimeFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*TimeFlag) Set

func (f *TimeFlag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*TimeFlag) String

func (f *TimeFlag) String() string

String returns the value as string

func (*TimeFlag) Validate

func (f *TimeFlag) Validate(ctx *Context) error

Validate validates the flag

type UInt64Flag

type UInt64Flag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     uint64
	Hidden    bool
	Required  bool
	Validator Validator
}

UInt64Flag is a flag with type uint

func (*UInt64Flag) Get

func (f *UInt64Flag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*UInt64Flag) Set

func (f *UInt64Flag) Set(value string) (err error)

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*UInt64Flag) String

func (f *UInt64Flag) String() string

String returns the value as string

func (*UInt64Flag) Validate

func (f *UInt64Flag) Validate(ctx *Context) error

Validate validates the flag

type UIntFlag

type UIntFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     uint
	Hidden    bool
	Required  bool
	Validator Validator
}

UIntFlag is a flag with type uint64

func (*UIntFlag) Get

func (f *UIntFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*UIntFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*UIntFlag) String

func (f *UIntFlag) String() string

String returns the value as string

func (*UIntFlag) Validate

func (f *UIntFlag) Validate(ctx *Context) error

Validate validates the flag

type URLFlag

type URLFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     *url.URL
	Hidden    bool
	Required  bool
	Validator Validator
}

URLFlag is a flag with type url.URL

func (*URLFlag) Get

func (f *URLFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*URLFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*URLFlag) String

func (f *URLFlag) String() string

String returns the value as string

func (*URLFlag) Validate

func (f *URLFlag) Validate(ctx *Context) error

Validate validates the flag

type UsageErrorFunc

type UsageErrorFunc func(context *Context, err error) error

OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying customized usage error messages. This function is able to replace the original error messages. If this function is not set, the "Incorrect usage" is displayed and the execution is interrupted.

type Validator

type Validator interface {
	// Validate validates the value
	Validate(ctx *Context, value interface{}) error
}

Validator converts values

func OneOf

func OneOf(items ...interface{}) Validator

OneOf returns a validator that expectes the flag value to matches one of the provided values

type ValidatorFunc

type ValidatorFunc func(ctx *Context, value interface{}) error

ValidatorFunc validates a flag

func (ValidatorFunc) Validate

func (fn ValidatorFunc) Validate(ctx *Context, value interface{}) error

Validate validates the value

type XMLFlag

type XMLFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     interface{}
	Hidden    bool
	Required  bool
	Validator Validator
}

XMLFlag is a flag with type XMLDocument

func (*XMLFlag) Get

func (f *XMLFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*XMLFlag) IsPathFlag

func (f *XMLFlag) IsPathFlag() bool

IsPathFlag returns true if the flag is path

func (*XMLFlag) ReadFrom

func (f *XMLFlag) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads data from r until EOF or error. The return value n is the number of bytes read. Any error except EOF encountered during the read is also returned.

func (*XMLFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*XMLFlag) String

func (f *XMLFlag) String() string

String returns the value as string

func (*XMLFlag) Validate

func (f *XMLFlag) Validate(ctx *Context) error

Validate validates the flag

type YAMLFlag

type YAMLFlag struct {
	Name      string
	Path      string
	Usage     string
	EnvVar    string
	Value     interface{}
	Hidden    bool
	Required  bool
	Validator Validator
}

YAMLFlag is a flag with type yaml document

func (*YAMLFlag) Get

func (f *YAMLFlag) Get() interface{}

Get is a function that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

func (*YAMLFlag) IsPathFlag

func (f *YAMLFlag) IsPathFlag() bool

IsPathFlag returns true if the flag is path

func (*YAMLFlag) ReadFrom

func (f *YAMLFlag) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads data from r until EOF or error. The return value n is the number of bytes read. Any error except EOF encountered during the read is also returned.

func (*YAMLFlag) Set

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

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

func (*YAMLFlag) String

func (f *YAMLFlag) String() string

String returns the value as string

func (*YAMLFlag) Validate

func (f *YAMLFlag) Validate(ctx *Context) error

Validate validates the flag

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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