cli

package module
v0.0.0-...-f9dec40 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2019 License: Apache-2.0 Imports: 22 Imported by: 1

README

go-cli GoDoc Build Status Build status codecov

A thin wrapper around common libraries used in our CLI apps (jessevdk/go-flags, src-d/go-log, pprof) to reduce boilerplate code and help in being more homogeneous with respect how our CLI work and look like.

It provides:

  • Struct tags to specify command names and descriptions (see below).
  • Default version subcommand.
  • Default completion subcommand for bash completion.
  • Flags and environment variables to setup logging with src-d/go-log.
  • Flags and environment variables to setup a http/pprof endpoint.
  • Signal handling.

For further details, look at doc.go.

License

Apache License Version 2.0, see LICENSE.

Documentation

Overview

Package cli provides scaffolding for CLI applications. It is a convenience wrapper for jessevdk/go-flags reducing boilerplate code.

The main entry point is the App type, created with the New function.

It provides:

  • Struct tags to specify command names and descriptions (see below).
  • Default version subcommand.
  • Default completion subcommand for bash completion.
  • Flags and environment variables to setup logging with src-d/go-log.
  • Flags and environment variables to setup a http/pprof endpoint.
  • Signal handling.

Commands

Commands are defined with structs. For the general available struct tags, refer to jessevdk/go-flags documentation at https://github.com/jessevdk/go-flags.

Additionally, every command struct must embed PlainCommand directly, or indirectly through other struct (e.g. Command). The embedded field must be defined with the struct tags name, short-description and long-description. For example:

type helloCommand struct {
  Command `name:"hello" short-description:"prints Hello World" long-description:"prints Hello World to standard output"`
}

This will also work if nested:

type myBaseCommand struct {
  Command
  Somethig string
}

type helloCommand struct {
  myBaseCommand `name:"hello" short-description:"prints Hello World" long-description:"prints Hello World to standard output"`
}

Each defined command must be added to the application with the AddCommand function.

Signal Handling

Signal handling is setup for any cancellable command. Cancellable commands implement the ContextCommander interface instead of flags.Commander.

Examples

See full examples in the examples subpackage.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handler

func Handler(name string) http.Handler

Handler returns an HTTP handler that serves the named profile.

func InitCompletionCommand

func InitCompletionCommand(appname string) func(*flags.Command)

InitCompletionCommand returns an additional AddCommand function that fills the CompletionCommand long description

Types

type App

type App struct {
	Parser *flags.Parser

	// DebugServeMux is serves debug endpoints. It used to attach the http/pprof
	// endpoint if enabled, and can be used to handle other debug endpoints.
	DebugServeMux *http.ServeMux
	// contains filtered or unexported fields
}

App defines the CLI application that will be run.

func New

func New(name, version, build, description string) *App

New creates a new App, including default values and sub commands.

func NewNoDefaults

func NewNoDefaults(name, description string) *App

NewNoDefaults creates a new App, without any of the default sub commands.

func (*App) AddCommand

func (a *App) AddCommand(cmd interface{}, cfs ...func(*flags.Command)) CommandAdder

AddCommand adds a new command to the application. The command must have a special field defining name, short-description and long-description (see package documentation). It panics if the command is not valid. Returned CommandAdder can be used to add subcommands.

Additional functions can be passed to manipulate the resulting *flags.Command after its initialization.

func (*App) Defer

func (a *App) Defer(d DeferFunc)

Defer adds a function to be called after the command is executed. The functions added are called in reverse order.

func (*App) Run

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

Run runs the app with the given command line arguments. In order to reduce boilerplate, RunMain should be used instead.

func (*App) RunMain

func (a *App) RunMain()

RunMain runs the application with os.Args and if there is any error, it exits with error code 1.

type Command

type Command struct {
	PlainCommand
	LogOptions      `group:"Log Options"`
	ProfilerOptions `group:"Profiler Options"`
}

Command implements the default group flags. It is meant to be embedded into other application commands to provide default behavior for logging, profiling, etc.

func (Command) Init

func (c Command) Init(a *App) error

Init implements initializer interface.

type CommandAdder

type CommandAdder interface {
	// AddCommand adds the given commands as subcommands of the
	// cuurent one.
	AddCommand(interface{}, ...func(*flags.Command)) CommandAdder
}

CommandAdder can be used to add subcommands.

type CompletionCommand

type CompletionCommand struct {
	PlainCommand `name:"completion" short-description:"print bash completion script"`
	Name         string
}

CompletionCommand defines the default completion command. Most of the time, it should not be used directly, since it will be added by default to the App.

func (CompletionCommand) Execute

func (c CompletionCommand) Execute(args []string) error

Execute runs the install command.

type ContextCommander

type ContextCommander interface {
	// ExecuteContext executes the command with a context.
	ExecuteContext(context.Context, []string) error
}

ContextCommander is a cancellable commander. By default, receiving SIGTERM or SIGINT will cancel the context. For overriding the default behaviour, see the SignalHandler interface.

type DeferFunc

type DeferFunc func()

type Initializer

type Initializer interface {
	// Init initializes the command.
	Init(*App) error
}

Initializer interface provides an Init function.

type LogOptions

type LogOptions struct {
	LogLevel       string `` /* 136-byte string literal not displayed */
	LogFormat      string `` /* 138-byte string literal not displayed */
	LogFields      string `long:"log-fields" env:"LOG_FIELDS" description:"default fields for the logger, specified in json"`
	LogForceFormat bool   `long:"log-force-format" env:"LOG_FORCE_FORMAT" description:"ignore if it is running on a terminal or not"`
}

LogOptions defines logging flags. It is meant to be embedded in a command struct.

func (LogOptions) Init

func (c LogOptions) Init(a *App) error

Init initializes the default logger factory.

type PlainCommand

type PlainCommand struct{}

PlainCommand should be embedded in a struct to indicate that it implements a command. See package documentation for its usage.

func (PlainCommand) Execute

func (c PlainCommand) Execute(args []string) error

Execute is a placeholder for the function that runs the command.

type ProfilerOptions

type ProfilerOptions struct {
	ProfilerHTTP          bool   `long:"profiler-http" env:"PROFILER_HTTP" description:"start HTTP profiler endpoint"`
	ProfilerBlockRate     int    `long:"profiler-block-rate" env:"PROFILER_BLOCK_RATE" default:"0" description:"runtime.SetBlockProfileRate parameter"`
	ProfilerMutexFraction int    `long:"profiler-mutex-rate" env:"PROFILER_MUTEX_FRACTION" default:"0" description:"runtime.SetMutexProfileFraction parameter"`
	ProfilerEndpoint      string `long:"profiler-endpoint" env:"PROFILER_ENDPOINT" description:"address to bind HTTP pprof endpoint to" default:"0.0.0.0:6061"`
	ProfilerCPU           string `long:"profiler-cpu" env:"PROFILER_CPU" description:"file where to write the whole execution CPU profile" default:""`
}

ProfilerOptions defines profiling flags. It is meant to be embedded in a command struct.

func (ProfilerOptions) Init

func (c ProfilerOptions) Init(a *App) error

Init initializes the profiler.

type SignalHandler

type SignalHandler interface {
	// HandleSignal takes the received signal (SIGTERM or SIGINT) and the
	// CancelFunc of the context.Context passed to ExecuteContext.
	HandleSignal(os.Signal, context.CancelFunc)
}

SignalHandler can be implemented by a ContextCommander to override default signal handling (which is logging the signal and cancelling the context). If this interface is implemented, HandleSignal will be called when SIGTERM or SIGINT is received, and no other signal handling will be performed.

type VersionCommand

type VersionCommand struct {
	PlainCommand `name:"version" short-description:"print version" long-description:"print version and exit"`
	Name         string
	Version      string
	Build        string
}

VersionCommand defines he default version command. Most if the time, it should not be used directly, since it will be added by default to the App.

func (VersionCommand) Execute

func (c VersionCommand) Execute(args []string) error

Execute runs the version command.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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