cmd

package module
v0.0.0-...-8e43f3f Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2020 License: LGPL-3.0 Imports: 18 Imported by: 368

README

cmd

import "github.com/juju/cmd"

Variables

var DefaultFormatters = map[string]Formatter{
    "smart": FormatSmart,
    "yaml":  FormatYaml,
    "json":  FormatJson,
}

DefaultFormatters holds the formatters that can be specified with the --format flag.

var ErrNoPath = errors.New("path not set")
var ErrSilent = errors.New("cmd: error out silently")

ErrSilent can be returned from Run to signal that Main should exit with code 1 without producing error output.

var FormatJson = json.Marshal

FormatJson marshals value to a json-formatted []byte.

func CheckEmpty

func CheckEmpty(args []string) error

CheckEmpty is a utility function that returns an error if args is not empty.

func FormatSmart

func FormatSmart(value interface{}) ([]byte, error)

FormatSmart marshals value into a []byte according to the following rules:

* string:        untouched
* bool:          converted to `True` or `False` (to match pyjuju)
* int or float:  converted to sensible strings
* []string:      joined by `\n`s into a single string
* anything else: delegate to FormatYaml

func FormatYaml

func FormatYaml(value interface{}) ([]byte, error)

FormatYaml marshals value to a yaml-formatted []byte, unless value is nil.

func IsErrSilent

func IsErrSilent(err error) bool

IsErrSilent returns whether the error should be logged from cmd.Main.

func IsRcPassthroughError

func IsRcPassthroughError(err error) bool

IsRcPassthroughError returns whether the error is an RcPassthroughError.

func Main

func Main(c Command, ctx *Context, args []string) int

Main runs the given Command in the supplied Context with the given arguments, which should not include the command name. It returns a code suitable for passing to os.Exit.

func NewCommandLogWriter

func NewCommandLogWriter(name string, out, err io.Writer) loggo.Writer

NewCommandLogWriter creates a loggo writer for registration by the callers of a command. This way the logged output can also be displayed otherwise, e.g. on the screen.

func NewRcPassthroughError

func NewRcPassthroughError(code int) error

NewRcPassthroughError creates an error that will have the code used at the return code from the cmd.Main function rather than the default of 1 if there is an error.

func ParseAliasFile

func ParseAliasFile(aliasFilename string) map[string][]string

 ParseAliasFile will read the specified file and convert the content to a map of names to the command line arguments they relate to. The function will always return a valid map, even if it is empty.

func ZeroOrOneArgs

func ZeroOrOneArgs(args []string) (string, error)

ZeroOrOneArgs checks to see that there are zero or one args, and returns the value of the arg if provided, or the empty string if not.

type AppendStringsValue

type AppendStringsValue []string

AppendStringsValue implements gnuflag.Value for a value that can be set multiple times, and it appends each value to the slice.

func NewAppendStringsValue
func NewAppendStringsValue(target *[]string) *AppendStringsValue

NewAppendStringsValue is used to create the type passed into the gnuflag.FlagSet Var function. f.Var(cmd.NewAppendStringsValue(&someMember), "name", "help")

func (*AppendStringsValue) Set
func (v *AppendStringsValue) Set(s string) error

Implements gnuflag.Value Set.

func (*AppendStringsValue) String
func (v *AppendStringsValue) String() string

Implements gnuflag.Value String.

type Command

type Command interface {
    // IsSuperCommand returns true if the command is a super command.
    IsSuperCommand() bool

    // Info returns information about the Command.
    Info() *Info

    // SetFlags adds command specific flags to the flag set.
    SetFlags(f *gnuflag.FlagSet)

    // Init initializes the Command before running.
    Init(args []string) error

    // Run will execute the Command as directed by the options and positional
    // arguments passed to Init.
    Run(ctx *Context) error

    // AllowInterspersedFlags returns whether the command allows flag
    // arguments to be interspersed with non-flag arguments.
    AllowInterspersedFlags() bool
}

Command is implemented by types that interpret command-line arguments.

type CommandBase

type CommandBase struct{}

CommandBase provides the default implementation for SetFlags, Init, and Help.

func (*CommandBase) AllowInterspersedFlags
func (c *CommandBase) AllowInterspersedFlags() bool

AllowInterspersedFlags returns true by default. Some subcommands may want to override this.

func (*CommandBase) Init
func (c *CommandBase) Init(args []string) error

Init in the simplest case makes sure there are no args.

func (*CommandBase) IsSuperCommand
func (c *CommandBase) IsSuperCommand() bool

IsSuperCommand implements Command.IsSuperCommand

func (*CommandBase) SetFlags
func (c *CommandBase) SetFlags(f *gnuflag.FlagSet)

SetFlags does nothing in the simplest case.

type Context

type Context struct {
    Dir    string
    Env    map[string]string
    Stdin  io.Reader
    Stdout io.Writer
    Stderr io.Writer
    // contains filtered or unexported fields
}

Context represents the run context of a Command. Command implementations should interpret file names relative to Dir (see AbsPath below), and print output and errors to Stdout and Stderr respectively.

func DefaultContext
func DefaultContext() (*Context, error)

DefaultContext returns a Context suitable for use in non-hosted situations.

func (*Context) AbsPath
func (ctx *Context) AbsPath(path string) string

AbsPath returns an absolute representation of path, with relative paths interpreted as relative to ctx.Dir.

func (*Context) GetStderr
func (ctx *Context) GetStderr() io.Writer

GetStderr satisfies environs.BootstrapContext

func (*Context) GetStdin
func (ctx *Context) GetStdin() io.Reader

GetStdin satisfies environs.BootstrapContext

func (*Context) GetStdout
func (ctx *Context) GetStdout() io.Writer

GetStdout satisfies environs.BootstrapContext

func (*Context) Getenv
func (ctx *Context) Getenv(key string) string

Getenv looks up an environment variable in the context. It mirrors os.Getenv. An empty string is returned if the key is not set.

func (*Context) Infof
func (ctx *Context) Infof(format string, params ...interface{})

Infof will write the formatted string to Stderr if quiet is false, but if quiet is true the message is logged.

func (*Context) InterruptNotify
func (ctx *Context) InterruptNotify(c chan<- os.Signal)

InterruptNotify satisfies environs.BootstrapContext

func (*Context) Setenv
func (ctx *Context) Setenv(key, value string) error

Setenv sets an environment variable in the context. It mirrors os.Setenv.

func (*Context) StopInterruptNotify
func (ctx *Context) StopInterruptNotify(c chan<- os.Signal)

StopInterruptNotify satisfies environs.BootstrapContext

func (*Context) Verbosef
func (ctx *Context) Verbosef(format string, params ...interface{})

Verbosef will write the formatted string to Stderr if the verbose is true, and to the logger if not.

type DeprecationCheck

type DeprecationCheck interface {

    // Deprecated aliases emit a warning when executed. If the command is
    // deprecated, the second return value recommends what to use instead.
    Deprecated() (bool, string)

    // Obsolete aliases are not actually registered. The purpose of this
    // is to allow code to indicate ahead of time some way to determine
    // that the command should stop working.
    Obsolete() bool
}

DeprecationCheck is used to provide callbacks to determine if a command is deprecated or obsolete.

type FileVar

type FileVar struct {
    // Path is the path to the file.
    Path string

    // StdinMarkers are the Path values that should be interpreted as
    // stdin. If it is empty then stdin is not supported.
    StdinMarkers []string
}

FileVar represents a path to a file.

func (FileVar) IsStdin
func (f FileVar) IsStdin() bool

IsStdin determines whether or not the path represents stdin.

func (*FileVar) Open
func (f *FileVar) Open(ctx *Context) (io.ReadCloser, error)

Open opens the file.

func (*FileVar) Read
func (f *FileVar) Read(ctx *Context) ([]byte, error)

Read returns the contents of the file.

func (*FileVar) Set
func (f *FileVar) Set(v string) error

Set stores the chosen path name in f.Path.

func (*FileVar) SetStdin
func (f *FileVar) SetStdin(markers ...string)

SetStdin sets StdinMarkers to the provided strings. If none are provided then the default of "-" is used.

func (*FileVar) String
func (f *FileVar) String() string

String returns the path to the file.

type Formatter

type Formatter func(value interface{}) ([]byte, error)

Formatter converts an arbitrary object into a []byte.

type Info

type Info struct {
    // Name is the Command's name.
    Name string

    // Args describes the command's expected positional arguments.
    Args string

    // Purpose is a short explanation of the Command's purpose.
    Purpose string

    // Doc is the long documentation for the Command.
    Doc string

    // Aliases are other names for the Command.
    Aliases []string
}

Info holds some of the usage documentation of a Command.

func (*Info) Help
func (i *Info) Help(f *gnuflag.FlagSet) []byte

Help renders i's content, along with documentation for any flags defined in f. It calls f.SetOutput(ioutil.Discard).

type Log

type Log struct {
    // If DefaultConfig is set, it will be used for the
    // default logging configuration.
    DefaultConfig string
    Path          string
    Verbose       bool
    Quiet         bool
    Debug         bool
    ShowLog       bool
    Config        string
    Factory       WriterFactory
}

Log supplies the necessary functionality for Commands that wish to set up logging.

func (*Log) AddFlags
func (l *Log) AddFlags(f *gnuflag.FlagSet)

AddFlags adds appropriate flags to f.

func (*Log) GetLogWriter
func (l *Log) GetLogWriter(target io.Writer) loggo.Writer

GetLogWriter returns a logging writer for the specified target.

func (*Log) Start
func (log *Log) Start(ctx *Context) error

Start starts logging using the given Context.

type MissingCallback

type MissingCallback func(ctx *Context, subcommand string, args []string) error

MissingCallback defines a function that will be used by the SuperCommand if the requested subcommand isn't found.

type Output

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

Output is responsible for interpreting output-related command line flags and writing a value to a file or to stdout as directed.

func (*Output) AddFlags
func (c *Output) AddFlags(f *gnuflag.FlagSet, defaultFormatter string, formatters map[string]Formatter)

AddFlags injects the --format and --output command line flags into f.

func (*Output) Name
func (c *Output) Name() string
func (*Output) Write
func (c *Output) Write(ctx *Context, value interface{}) (err error)

Write formats and outputs the value as directed by the --format and --output command line flags.

type RcPassthroughError

type RcPassthroughError struct {
    Code int
}

RcPassthroughError indicates that a Juju plugin command exited with a non-zero exit code. This error is used to exit with the return code.

func (*RcPassthroughError) Error
func (e *RcPassthroughError) Error() string

Error implements error.

type StringsValue

type StringsValue []string

StringsValue implements gnuflag.Value for a comma separated list of strings. This allows flags to be created where the target is []string, and the caller is after comma separated values.

func NewStringsValue
func NewStringsValue(defaultValue []string, target *[]string) *StringsValue

NewStringsValue is used to create the type passed into the gnuflag.FlagSet Var function. f.Var(cmd.NewStringsValue(defaultValue, &someMember), "name", "help")

func (*StringsValue) Set
func (v *StringsValue) Set(s string) error

Implements gnuflag.Value Set.

func (*StringsValue) String
func (v *StringsValue) String() string

Implements gnuflag.Value String.

type SuperCommand

type SuperCommand struct {
    CommandBase
    Name    string
    Purpose string
    Doc     string
    Log     *Log
    Aliases []string
    // contains filtered or unexported fields
}

SuperCommand is a Command that selects a subcommand and assumes its properties; any command line arguments that were not used in selecting the subcommand are passed down to it, and to Run a SuperCommand is to run its selected subcommand.

func NewSuperCommand
func NewSuperCommand(params SuperCommandParams) *SuperCommand

NewSuperCommand creates and initializes a new SuperCommand, and returns the fully initialized structure.

func (*SuperCommand) AddHelpTopic
func (c *SuperCommand) AddHelpTopic(name, short, long string, aliases ...string)

AddHelpTopic adds a new help topic with the description being the short param, and the full text being the long param. The description is shown in 'help topics', and the full text is shown when the command 'help ' is called.

func (*SuperCommand) AddHelpTopicCallback
func (c *SuperCommand) AddHelpTopicCallback(name, short string, longCallback func() string)

AddHelpTopicCallback adds a new help topic with the description being the short param, and the full text being defined by the callback function.

func (*SuperCommand) AllowInterspersedFlags
func (c *SuperCommand) AllowInterspersedFlags() bool

For a SuperCommand, we want to parse the args with allowIntersperse=false. This will mean that the args may contain other options that haven't been defined yet, and that only options that relate to the SuperCommand itself can come prior to the subcommand name.

func (*SuperCommand) Info
func (c *SuperCommand) Info() *Info

Info returns a description of the currently selected subcommand, or of the SuperCommand itself if no subcommand has been specified.

func (*SuperCommand) Init
func (c *SuperCommand) Init(args []string) error

Init initializes the command for running.

func (*SuperCommand) IsSuperCommand
func (c *SuperCommand) IsSuperCommand() bool

IsSuperCommand implements Command.IsSuperCommand

func (*SuperCommand) Register
func (c *SuperCommand) Register(subcmd Command)

Register makes a subcommand available for use on the command line. The command will be available via its own name, and via any supplied aliases.

func (*SuperCommand) RegisterAlias
func (c *SuperCommand) RegisterAlias(name, forName string, check DeprecationCheck)

RegisterAlias makes an existing subcommand available under another name. If check is supplied, and the result of the Obsolete call is true, then the alias is not registered.

func (*SuperCommand) RegisterDeprecated
func (c *SuperCommand) RegisterDeprecated(subcmd Command, check DeprecationCheck)

RegisterDeprecated makes a subcommand available for use on the command line if it is not obsolete. It inserts the command with the specified DeprecationCheck so that a warning is displayed if the command is deprecated.

func (*SuperCommand) RegisterSuperAlias
func (c *SuperCommand) RegisterSuperAlias(name, super, forName string, check DeprecationCheck)

RegisterSuperAlias makes a subcommand of a registered supercommand available under another name. This is useful when the command structure is being refactored. If check is supplied, and the result of the Obsolete call is true, then the alias is not registered.

func (*SuperCommand) Run
func (c *SuperCommand) Run(ctx *Context) error

Run executes the subcommand that was selected in Init.

func (*SuperCommand) SetCommonFlags
func (c *SuperCommand) SetCommonFlags(f *gnuflag.FlagSet)

SetCommonFlags creates a new "commonflags" flagset, whose flags are shared with the argument f; this enables us to add non-global flags to f, which do not carry into subcommands.

func (*SuperCommand) SetFlags
func (c *SuperCommand) SetFlags(f *gnuflag.FlagSet)

SetFlags adds the options that apply to all commands, particularly those due to logging.

type SuperCommandParams

type SuperCommandParams struct {
    // UsagePrefix should be set when the SuperCommand is
    // actually a subcommand of some other SuperCommand;
    // if NotifyRun is called, it name will be prefixed accordingly,
    // unless UsagePrefix is identical to Name.
    UsagePrefix string

    // Notify, if not nil, is called when the SuperCommand
    // is about to run a sub-command.
    NotifyRun func(cmdName string)

    Name            string
    Purpose         string
    Doc             string
    Log             *Log
    MissingCallback MissingCallback
    Aliases         []string
    Version         string

    // UserAliasesFilename refers to the location of a file that contains
    //   name = cmd [args...]
    // values, that is used to change default behaviour of commands in order
    // to add flags, or provide short cuts to longer commands.
    UserAliasesFilename string
}

SuperCommandParams provides a way to have default parameter to the NewSuperCommand call.

type UnrecognizedCommand

type UnrecognizedCommand struct {
    Name string
}
func (*UnrecognizedCommand) Error
func (e *UnrecognizedCommand) Error() string

type WriterFactory

type WriterFactory interface {
    NewWriter(target io.Writer) loggo.Writer
}

WriterFactory defines the single method to create a new logging writer for a specified output target.


Generated by godoc2md

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultFormatters = formatters{
	"smart": TypeFormatter{Formatter: FormatSmart, Serialisable: false},
	"yaml":  TypeFormatter{Formatter: FormatYaml, Serialisable: true},
	"json":  TypeFormatter{Formatter: FormatJson, Serialisable: true},
}

DefaultFormatters holds the formatters that can be specified with the --format flag.

View Source
var ErrNoPath = errors.New("path not set")
View Source
var ErrSilent = errors.New("cmd: error out silently")

ErrSilent can be returned from Run to signal that Main should exit with code 1 without producing error output.

Functions

func CheckEmpty

func CheckEmpty(args []string) error

CheckEmpty is a utility function that returns an error if args is not empty.

func FlagAlias

func FlagAlias(c Command, akaDefault string) string

func FormatJson

func FormatJson(writer io.Writer, value interface{}) error

FormatJson writes out value as json.

func FormatSmart

func FormatSmart(writer io.Writer, value interface{}) error

FormatSmart marshals value into a []byte according to the following rules:

  • string: untouched
  • bool: converted to `True` or `False` (to match pyjuju)
  • int or float: converted to sensible strings
  • []string: joined by `\n`s into a single string
  • anything else: delegate to FormatYaml

func FormatYaml

func FormatYaml(writer io.Writer, value interface{}) error

FormatYaml writes out value as yaml to the writer, unless value is nil.

func IsErrSilent

func IsErrSilent(err error) bool

IsErrSilent returns whether the error should be logged from cmd.Main.

func IsRcPassthroughError

func IsRcPassthroughError(err error) bool

IsRcPassthroughError returns whether the error is an RcPassthroughError.

func Main

func Main(c Command, ctx *Context, args []string) int

Main runs the given Command in the supplied Context with the given arguments, which should not include the command name. It returns a code suitable for passing to os.Exit.

func NewCommandLogWriter

func NewCommandLogWriter(name string, out, err io.Writer) loggo.Writer

NewCommandLogWriter creates a loggo writer for registration by the callers of a command. This way the logged output can also be displayed otherwise, e.g. on the screen.

func NewRcPassthroughError

func NewRcPassthroughError(code int) error

NewRcPassthroughError creates an error that will have the code used at the return code from the cmd.Main function rather than the default of 1 if there is an error.

func NewWarningWriter

func NewWarningWriter(writer io.Writer) loggo.Writer

NewWarningWriter will write out colored severity levels if the writer is outputting to a terminal.

func ParseAliasFile

func ParseAliasFile(aliasFilename string) map[string][]string

 ParseAliasFile will read the specified file and convert the content to a map of names to the command line arguments they relate to. The function will always return a valid map, even if it is empty.

func WriteError

func WriteError(writer io.Writer, err error)

WriteError will output the formatted text to the writer with a colored ERROR like the logging would.

func ZeroOrOneArgs

func ZeroOrOneArgs(args []string) (string, error)

ZeroOrOneArgs checks to see that there are zero or one args, and returns the value of the arg if provided, or the empty string if not.

Types

type AppendStringsValue

type AppendStringsValue []string

AppendStringsValue implements gnuflag.Value for a value that can be set multiple times, and it appends each value to the slice.

func NewAppendStringsValue

func NewAppendStringsValue(target *[]string) *AppendStringsValue

NewAppendStringsValue is used to create the type passed into the gnuflag.FlagSet Var function. f.Var(cmd.NewAppendStringsValue(&someMember), "name", "help")

func (*AppendStringsValue) Set

func (v *AppendStringsValue) Set(s string) error

Implements gnuflag.Value Set.

func (*AppendStringsValue) String

func (v *AppendStringsValue) String() string

Implements gnuflag.Value String.

type Command

type Command interface {
	// IsSuperCommand returns true if the command is a super command.
	IsSuperCommand() bool

	// Info returns information about the Command.
	Info() *Info

	// SetFlags adds command specific flags to the flag set.
	SetFlags(f *gnuflag.FlagSet)

	// Init initializes the Command before running.
	Init(args []string) error

	// Run will execute the Command as directed by the options and positional
	// arguments passed to Init.
	Run(ctx *Context) error

	// AllowInterspersedFlags returns whether the command allows flag
	// arguments to be interspersed with non-flag arguments.
	AllowInterspersedFlags() bool
}

Command is implemented by types that interpret command-line arguments.

type CommandBase

type CommandBase struct{}

CommandBase provides the default implementation for SetFlags, Init, and Help.

func (*CommandBase) AllowInterspersedFlags

func (c *CommandBase) AllowInterspersedFlags() bool

AllowInterspersedFlags returns true by default. Some subcommands may want to override this.

func (*CommandBase) Init

func (c *CommandBase) Init(args []string) error

Init in the simplest case makes sure there are no args.

func (*CommandBase) IsSuperCommand

func (c *CommandBase) IsSuperCommand() bool

IsSuperCommand implements Command.IsSuperCommand

func (*CommandBase) SetFlags

func (c *CommandBase) SetFlags(f *gnuflag.FlagSet)

SetFlags does nothing in the simplest case.

type Context

type Context struct {
	Dir    string
	Env    map[string]string
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

Context represents the run context of a Command. Command implementations should interpret file names relative to Dir (see AbsPath below), and print output and errors to Stdout and Stderr respectively.

func DefaultContext

func DefaultContext() (*Context, error)

DefaultContext returns a Context suitable for use in non-hosted situations.

func (*Context) AbsPath

func (ctx *Context) AbsPath(path string) string

AbsPath returns an absolute representation of path, with relative paths interpreted as relative to ctx.Dir and with "~/" replaced with users home dir.

func (*Context) GetStderr

func (ctx *Context) GetStderr() io.Writer

GetStderr satisfies environs.BootstrapContext

func (*Context) GetStdin

func (ctx *Context) GetStdin() io.Reader

GetStdin satisfies environs.BootstrapContext

func (*Context) GetStdout

func (ctx *Context) GetStdout() io.Writer

GetStdout satisfies environs.BootstrapContext

func (*Context) Getenv

func (ctx *Context) Getenv(key string) string

Getenv looks up an environment variable in the context. It mirrors os.Getenv. An empty string is returned if the key is not set.

func (*Context) Infof

func (ctx *Context) Infof(format string, params ...interface{})

Infof will write the formatted string to Stderr if quiet is false, but if quiet is true the message is logged.

func (*Context) InterruptNotify

func (ctx *Context) InterruptNotify(c chan<- os.Signal)

InterruptNotify satisfies environs.BootstrapContext

func (*Context) IsSerial

func (ctx *Context) IsSerial() bool

IsSerial reports whether the command is required to output to a "machine". This mode is intended to stop the proliferation of execessive writes to stdout and stderr, when the output is intended for machines.

func (*Context) Quiet

func (ctx *Context) Quiet() bool

Quiet reports whether the command is in "quiet" mode. When this is true, informational output should be suppressed (logger messages can be used instead).

func (*Context) Setenv

func (ctx *Context) Setenv(key, value string) error

Setenv sets an environment variable in the context. It mirrors os.Setenv.

func (*Context) StopInterruptNotify

func (ctx *Context) StopInterruptNotify(c chan<- os.Signal)

StopInterruptNotify satisfies environs.BootstrapContext

func (*Context) Verbosef

func (ctx *Context) Verbosef(format string, params ...interface{})

Verbosef will write the formatted string to Stderr if the verbose is true, and to the logger if not.

func (*Context) Warningf

func (ctx *Context) Warningf(format string, params ...interface{})

Warningf allows for the logging of messages, at the warning level, from a command's context. This is useful for logging errors which do not cause a command to fail (e.g. an error message used as a deprecation warning that will be upgraded to a real error message at some point in the future.)

type DeprecationCheck

type DeprecationCheck interface {
	// Deprecated aliases emit a warning when executed. If the command is
	// deprecated, the second return value recommends what to use instead.
	Deprecated() (bool, string)

	// Obsolete aliases are not actually registered. The purpose of this
	// is to allow code to indicate ahead of time some way to determine
	// that the command should stop working.
	Obsolete() bool
}

DeprecationCheck is used to provide callbacks to determine if a command is deprecated or obsolete.

type FileVar

type FileVar struct {
	// Path is the path to the file.
	Path string

	// StdinMarkers are the Path values that should be interpreted as
	// stdin. If it is empty then stdin is not supported.
	StdinMarkers []string
}

FileVar represents a path to a file.

func (FileVar) IsStdin

func (f FileVar) IsStdin() bool

IsStdin determines whether or not the path represents stdin.

func (*FileVar) Open

func (f *FileVar) Open(ctx *Context) (io.ReadCloser, error)

Open opens the file.

func (*FileVar) Read

func (f *FileVar) Read(ctx *Context) ([]byte, error)

Read returns the contents of the file.

func (*FileVar) Set

func (f *FileVar) Set(v string) error

Set stores the chosen path name in f.Path.

func (*FileVar) SetStdin

func (f *FileVar) SetStdin(markers ...string)

SetStdin sets StdinMarkers to the provided strings. If none are provided then the default of "-" is used.

func (*FileVar) String

func (f *FileVar) String() string

String returns the path to the file.

type FlagAdder

type FlagAdder interface {
	// AddsFlags adds the value's flags to the given flag set.
	AddFlags(*gnuflag.FlagSet)
}

FlagAdder represents a value that has associated flags.

type Formatter

type Formatter func(writer io.Writer, value interface{}) error

Formatter writes the arbitrary object into the writer.

type Info

type Info struct {
	// Name is the Command's name.
	Name string

	// Args describes the command's expected positional arguments.
	Args string

	// Purpose is a short explanation of the Command's purpose.
	Purpose string

	// Doc is the long documentation for the Command.
	Doc string

	// Aliases are other names for the Command.
	Aliases []string

	// FlagKnownAs allows different projects to customise what their flags are
	// known as, e.g. 'flag', 'option', 'item'. All error/log messages
	// will use that name when referring to an individual items/flags in this command.
	// For example, if this value is 'option', the default message 'value for flag'
	// will become 'value for option'.
	FlagKnownAs string

	// ShowSuperFlags contains the names of the 'super' command flags
	// that are desired to be shown in the sub-command help output.
	ShowSuperFlags []string
}

Info holds some of the usage documentation of a Command.

func (*Info) Help

func (i *Info) Help(f *gnuflag.FlagSet) []byte

Help renders i's content, along with documentation for any flags defined in f.

func (*Info) HelpWithSuperFlags

func (i *Info) HelpWithSuperFlags(superF *gnuflag.FlagSet, f *gnuflag.FlagSet) []byte

HelpWithSuperFlags renders i's content, along with documentation for any flags defined in both command and its super command flag sets. Only super command flags defined in i.ShowSuperFlags are displayed, if found.

type Log

type Log struct {
	// If DefaultConfig is set, it will be used for the
	// default logging configuration.
	DefaultConfig string
	Path          string
	Verbose       bool
	Quiet         bool
	Debug         bool
	ShowLog       bool
	Config        string

	// NewWriter creates a new logging writer for a specified target.
	NewWriter func(target io.Writer) loggo.Writer
}

Log supplies the necessary functionality for Commands that wish to set up logging.

func (*Log) AddFlags

func (l *Log) AddFlags(f *gnuflag.FlagSet)

AddFlags adds appropriate flags to f.

func (*Log) GetLogWriter

func (l *Log) GetLogWriter(target io.Writer) loggo.Writer

GetLogWriter returns a logging writer for the specified target.

func (*Log) Start

func (log *Log) Start(ctx *Context) error

Start starts logging using the given Context.

type MissingCallback

type MissingCallback func(ctx *Context, subcommand string, args []string) error

MissingCallback defines a function that will be used by the SuperCommand if the requested subcommand isn't found.

type Output

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

Output is responsible for interpreting output-related command line flags and writing a value to a file or to stdout as directed.

func (*Output) AddFlags

func (c *Output) AddFlags(f *gnuflag.FlagSet, defaultFormatter string, formatters map[string]Formatter)

AddFlags injects the --format and --output command line flags into f.

func (*Output) Name

func (c *Output) Name() string

Name returns the underlying name of the formatter.

func (*Output) Write

func (c *Output) Write(ctx *Context, value interface{}) (err error)

Write formats and outputs the value as directed by the --format and --output command line flags.

func (*Output) WriteFormatter

func (c *Output) WriteFormatter(ctx *Context, formatter Formatter, value interface{}) (err error)

WriteFormatter formats and outputs the value with the given formatter, to the output directed by the --output command line flag.

type RcPassthroughError

type RcPassthroughError struct {
	Code int
}

RcPassthroughError indicates that a Juju plugin command exited with a non-zero exit code. This error is used to exit with the return code.

func (*RcPassthroughError) Error

func (e *RcPassthroughError) Error() string

Error implements error.

type StringMap

type StringMap struct {
	Mapping *map[string]string
}

StringMap is a type that deserializes a CLI string using gnuflag's Value semantics. It expects a key=value pair, and supports multiple copies of the flag adding more pairs, though the keys must be unique, and both keys and values must be non-empty.

func (StringMap) Set

func (m StringMap) Set(s string) error

Set implements gnuflag.Value's Set method.

func (StringMap) String

func (m StringMap) String() string

String implements gnuflag.Value's String method

type StringsValue

type StringsValue []string

StringsValue implements gnuflag.Value for a comma separated list of strings. This allows flags to be created where the target is []string, and the caller is after comma separated values.

func NewStringsValue

func NewStringsValue(defaultValue []string, target *[]string) *StringsValue

NewStringsValue is used to create the type passed into the gnuflag.FlagSet Var function. f.Var(cmd.NewStringsValue(defaultValue, &someMember), "name", "help")

func (*StringsValue) Set

func (v *StringsValue) Set(s string) error

Implements gnuflag.Value Set.

func (*StringsValue) String

func (v *StringsValue) String() string

Implements gnuflag.Value String.

type SuperCommand

type SuperCommand struct {
	CommandBase
	Name    string
	Purpose string
	Doc     string
	Log     *Log
	Aliases []string

	// FlagKnownAs allows different projects to customise what their flags are
	// known as, e.g. 'flag', 'option', 'item'. All error/log messages
	// will use that name when referring to an individual items/flags in this command.
	// For example, if this value is 'option', the default message 'value for flag'
	// will become 'value for option'.
	FlagKnownAs string
	// contains filtered or unexported fields
}

SuperCommand is a Command that selects a subcommand and assumes its properties; any command line arguments that were not used in selecting the subcommand are passed down to it, and to Run a SuperCommand is to run its selected subcommand.

func NewSuperCommand

func NewSuperCommand(params SuperCommandParams) *SuperCommand

NewSuperCommand creates and initializes a new `SuperCommand`, and returns the fully initialized structure.

func (*SuperCommand) AddHelpTopic

func (c *SuperCommand) AddHelpTopic(name, short, long string, aliases ...string)

AddHelpTopic adds a new help topic with the description being the short param, and the full text being the long param. The description is shown in 'help topics', and the full text is shown when the command 'help <name>' is called.

func (*SuperCommand) AddHelpTopicCallback

func (c *SuperCommand) AddHelpTopicCallback(name, short string, longCallback func() string)

AddHelpTopicCallback adds a new help topic with the description being the short param, and the full text being defined by the callback function.

func (*SuperCommand) AllowInterspersedFlags

func (c *SuperCommand) AllowInterspersedFlags() bool

For a SuperCommand, we want to parse the args with allowIntersperse=false. This will mean that the args may contain other options that haven't been defined yet, and that only options that relate to the SuperCommand itself can come prior to the subcommand name.

func (*SuperCommand) FindClosestSubCommand

func (c *SuperCommand) FindClosestSubCommand(name string) (string, Command, bool)

FindClosestSubCommand attempts to find a sub command by a given name. This is used to help locate potential commands where the name isn't an exact match. If the resulting fuzzy match algorithm returns a value that is itself too far away from the size of the word, we disgard that and say a match isn't relavent i.e. "foo" "barsomethingfoo" would not match

func (*SuperCommand) Info

func (c *SuperCommand) Info() *Info

Info returns a description of the currently selected subcommand, or of the SuperCommand itself if no subcommand has been specified.

func (*SuperCommand) Init

func (c *SuperCommand) Init(args []string) error

Init initializes the command for running.

func (*SuperCommand) IsSuperCommand

func (c *SuperCommand) IsSuperCommand() bool

IsSuperCommand implements Command.IsSuperCommand

func (*SuperCommand) Register

func (c *SuperCommand) Register(subcmd Command)

Register makes a subcommand available for use on the command line. The command will be available via its own name, and via any supplied aliases.

func (*SuperCommand) RegisterAlias

func (c *SuperCommand) RegisterAlias(name, forName string, check DeprecationCheck)

RegisterAlias makes an existing subcommand available under another name. If `check` is supplied, and the result of the `Obsolete` call is true, then the alias is not registered.

func (*SuperCommand) RegisterDeprecated

func (c *SuperCommand) RegisterDeprecated(subcmd Command, check DeprecationCheck)

RegisterDeprecated makes a subcommand available for use on the command line if it is not obsolete. It inserts the command with the specified DeprecationCheck so that a warning is displayed if the command is deprecated.

func (*SuperCommand) RegisterSuperAlias

func (c *SuperCommand) RegisterSuperAlias(name, super, forName string, check DeprecationCheck)

RegisterSuperAlias makes a subcommand of a registered supercommand available under another name. This is useful when the command structure is being refactored. If `check` is supplied, and the result of the `Obsolete` call is true, then the alias is not registered.

func (*SuperCommand) Run

func (c *SuperCommand) Run(ctx *Context) error

Run executes the subcommand that was selected in Init.

func (*SuperCommand) SetCommonFlags

func (c *SuperCommand) SetCommonFlags(f *gnuflag.FlagSet)

SetCommonFlags creates a new "commonflags" flagset, whose flags are shared with the argument f; this enables us to add non-global flags to f, which do not carry into subcommands.

func (*SuperCommand) SetFlags

func (c *SuperCommand) SetFlags(f *gnuflag.FlagSet)

SetFlags adds the options that apply to all commands, particularly those due to logging.

type SuperCommandParams

type SuperCommandParams struct {
	// UsagePrefix should be set when the SuperCommand is
	// actually a subcommand of some other SuperCommand;
	// if NotifyRun is called, it name will be prefixed accordingly,
	// unless UsagePrefix is identical to Name.
	UsagePrefix string

	// Notify, if not nil, is called when the SuperCommand
	// is about to run a sub-command.
	NotifyRun func(cmdName string)

	// NotifyHelp is called just before help is printed, with the
	// arguments received by the help command. This can be
	// used, for example, to load command information for external
	// "plugin" commands, so that their documentation will show up
	// in the help output.
	NotifyHelp func([]string)

	Name    string
	Purpose string
	Doc     string
	// Log holds the Log value associated with the supercommand. If it's nil,
	// no logging flags will be configured.
	Log *Log
	// GlobalFlags specifies a value that can add more global flags to the
	// supercommand which will also be available on all subcommands.
	GlobalFlags     FlagAdder
	MissingCallback MissingCallback
	Aliases         []string
	Version         string
	// VersionDetail is a freeform information that is output when the default version
	// subcommand is passed --all. Output is formatted using the user-selected formatter.
	// Exported fields should specify yaml and json field tags.
	VersionDetail interface{}

	// UserAliasesFilename refers to the location of a file that contains
	//   name = cmd [args...]
	// values, that is used to change default behaviour of commands in order
	// to add flags, or provide short cuts to longer commands.
	UserAliasesFilename string

	// FlagKnownAs allows different projects to customise what their flags are
	// known as, e.g. 'flag', 'option', 'item'. All error/log messages
	// will use that name when referring to an individual items/flags in this command.
	// For example, if this value is 'option', the default message 'value for flag'
	// will become 'value for option'.
	FlagKnownAs string
}

SuperCommandParams provides a way to have default parameter to the `NewSuperCommand` call.

type TypeFormatter

type TypeFormatter struct {
	Formatter    Formatter
	Serialisable bool
}

TypeFormatter describes a formatting type that can define if a type is serialisable.

type UnrecognizedCommand

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

UnrecognizedCommand defines an error that specifies when a command is not found.

func DefaultUnrecognizedCommand

func DefaultUnrecognizedCommand(name string) *UnrecognizedCommand

DefaultUnrecognizedCommand creates a default message for using the UnrecognizedCommand.

func UnrecognizedCommandf

func UnrecognizedCommandf(format string, args ...interface{}) *UnrecognizedCommand

UnrecognizedCommandf creates a UnrecognizedCommand with additional arguments to create a bespoke message for the unrecognized command.

func (*UnrecognizedCommand) Error

func (e *UnrecognizedCommand) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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