Documentation ¶
Index ¶
- Constants
- Variables
- func AddDefaults(sf *FlagSet)
- func AddFlags(o output.Bus, c *Configuration, flags *pflag.FlagSet, sets ...*FlagSet)
- func ApplicationPath() string
- func AssignFileSystem(newFileSystem afero.Fs) afero.Fs
- func CopyFile(src, destination string) error
- func Copyright(o output.Bus, first int, timestamp, owner string) string
- func DecoratedAppName(applicationName, applicationVersion, timestamp string) string
- func DefaultConfigFileStatus() (string, bool)
- func DereferenceEnvVar(s string) (string, error)
- func DirExists(path string) bool
- func ErrorToString(e error) string
- func FileSystem() afero.Fs
- func FormatBuildDependencies(dependencies []string) []string
- func FormatGoVersion(version string) string
- func InitApplicationPath(o output.Bus, applicationName string) bool
- func InitLogging(o output.Bus, applicationName string) (ok bool)
- func InitLoggingWithLevel(o output.Bus, l output.Level, applicationName string) (ok bool)
- func InterpretBuildData(buildInfoReader func() (*debug.BuildInfo, bool)) (goVersion string, dependencies []string)deprecated
- func LogCommandStart(o output.Bus, name string, m map[string]any)
- func LogFileDeletionFailure(o output.Bus, s string, e error)
- func LogPath() string
- func Mkdir(path string) error
- func PlainFileExists(path string) bool
- func ProcessFlagErrors(o output.Bus, eSlice []error) bool
- func ProcessIsElevated() bool
- func ReadDirectory(o output.Bus, dir string) ([]fs.FileInfo, bool)
- func ReadFlags(producer FlagProducer, set *FlagSet) (map[string]*CommandFlag[any], []error)
- func ReportFileCreationFailure(o output.Bus, cmd, file string, e error)
- func SetApplicationPath(s string) (previous string)
- func StyledFlowerBox(lines []string, style FlowerBoxStyle) []string
- func ToErrorInterface(e *ExitError) error
- func WritableDefaults() []byte
- type BuildInformation
- type CommandFlag
- func GetBool(o output.Bus, results map[string]*CommandFlag[any], flagName string) (CommandFlag[bool], error)
- func GetInt(o output.Bus, results map[string]*CommandFlag[any], flagName string) (CommandFlag[int], error)
- func GetString(o output.Bus, results map[string]*CommandFlag[any], flagName string) (CommandFlag[string], error)
- type Configuration
- func (c *Configuration) BoolDefault(key string, defaultValue bool) (bool, error)
- func (c *Configuration) IntDefault(key string, b *IntBounds) (int, error)
- func (c *Configuration) String() string
- func (c *Configuration) StringDefault(key, defaultValue string) (string, error)
- func (c *Configuration) SubConfiguration(key string) *Configuration
- type ElevationControl
- type EnvVarMemento
- type ExitError
- type FlagDetails
- type FlagProducer
- type FlagSet
- type FlowerBoxStyle
- type IntBounds
Constants ¶
const ( // ASCIIFlowerBox uses ASCII characters ('+', '+', '+', '+', '-', and '|') ASCIIFlowerBox = iota // CurvedFlowerBox is uses light lines rounded corners ('╭', '╮', '╰', '╯', '─', and '│') CurvedFlowerBox // DoubleLinedFlowerBox uses double line characters ('╔', '╗', '╚', '╝', '═', and '║') DoubleLinedFlowerBox // HeavyLinedFlowerBox uses heavy lined characters ('┏', '┓', '┗', '┛', '━', and '┃') HeavyLinedFlowerBox // LightLinedFlowerBox uses heavy lined characters ('┌', '┐', '└', '┘', '─', and '│') LightLinedFlowerBox )
const ( // StdFilePermissions is the standard mode constant for plain files; it sets up the file // to be read/write for its owner, read only for everyone else StdFilePermissions = 0o644 // StdDirPermissions is the standard mode constant for directory files; it sets up the // directory to be read/write/executable for its owner, read/executable for everyone else; StdDirPermissions = 0o755 // -rwxr-xr-x )
const ( // BoolType represents a boolean flag type BoolType valueType // IntType represents an integer flag type IntType // StringType represents a string flag type StringType )
Variables ¶
var ( // Scanf is the standard function for reading and scanning a line from stdin; it is used by // the configured exit function to allow the user control over when to close the terminal // window Scanf = fmt.Scanf // IsCygwinTerminal determines whether a particular file descriptor (e.g., os.Stdin.Fd()) is a // Cygwin terminal IsCygwinTerminal = isatty.IsCygwinTerminal // IsTerminal determines whether a particular file descriptor (e.g., os.Stdin.Fd()) is a // terminal IsTerminal = isatty.IsTerminal // GetCurrentProcessToken gets the windows token representing the current process GetCurrentProcessToken = windows.GetCurrentProcessToken // ShellExecute is the windows function that runs the specified process with elevated // privileges ShellExecute = windows.ShellExecute // IsElevated determines whether a specified windows token represents a process running with // elevated privileges IsElevated = windows.Token.IsElevated )
var LogWriterInitFn = initWriter
LogWriterInitFn is a function to get an io.Writer with which to initialize the logger; this variable setting makes it easy to substitute another function in unit tests
var ( ProductionLogger = &simpleLogger{ exitFunction: os.Exit, currentLogLevel: defaultLoggingLevel, lock: &sync.RWMutex{}, } )
ProductionLogger is the production implementation of the output.Logger interface
Functions ¶
func AddDefaults ¶ added in v0.22.0
func AddDefaults(sf *FlagSet)
AddDefaults copies data from a FlagSet into the map of default configuration settings
func AddFlags ¶ added in v0.19.0
AddFlags adds collections of flags to a flag consumer (typically a cobra command flags instance)
func ApplicationPath ¶
func ApplicationPath() string
ApplicationPath returns the path to application-specific data (%APPDATA%\appName)
func AssignFileSystem ¶ added in v0.10.0
AssignFileSystem sets the current afero.Fs instance and returns the original pre-assignment value
func CopyFile ¶
CopyFile copies a file. Adapted from https://github.com/cleversoap/go-cp/blob/master/cp.go
func Copyright ¶ added in v0.8.0
Copyright returns an appropriately formatted copyright statement; see https://github.com/majohn-r/cmd-toolkit/issues/17
func DecoratedAppName ¶ added in v0.8.0
DecoratedAppName returns the app name with its version and build timestamp; see https://github.com/majohn-r/cmd-toolkit/issues/17
func DefaultConfigFileStatus ¶ added in v0.21.1
DefaultConfigFileStatus returns the path of the defaults config file and whether that file exists
func DereferenceEnvVar ¶
DereferenceEnvVar scans a string for environment variable references, looks up the values of those environment variables, and replaces the references with their values. If one or more of the referenced environment variables are undefined, they are all reported in the error return
func ErrorToString ¶ added in v0.23.0
ErrorToString converts an error into an easy-to-read string
func FileSystem ¶ added in v0.10.0
FileSystem returns the current afero.Fs instance
func FormatBuildDependencies ¶ added in v0.8.0
FormatBuildDependencies returns build dependency data formatted nicely; see https://github.com/majohn-r/cmd-toolkit/issues/17
func FormatGoVersion ¶ added in v0.8.0
FormatGoVersion returns the formatted go version; see https://github.com/majohn-r/cmd-toolkit/issues/17cmdtoolkit.
func InitApplicationPath ¶
InitApplicationPath ensures that the application path exists
func InitLogging ¶
InitLogging sets up logging at the default log level
func InitLoggingWithLevel ¶ added in v0.2.0
InitLoggingWithLevel initializes logging with a specific log level
func InterpretBuildData
deprecated
added in
v0.8.0
func InterpretBuildData(buildInfoReader func() (*debug.BuildInfo, bool)) (goVersion string, dependencies []string)
Deprecated: use GetBuildData instead and call GoVersion() and Dependencies() on the result. InterpretBuildData interprets the output of calling buildInfoReader() into easily consumed forms; see https://github.com/majohn-r/cmd-toolkit/issues/17. for production callers, pass in debug.ReadBuildInfo
func LogCommandStart ¶
LogCommandStart logs the beginning of command execution; if the provided map contains a "command" value, then the name parameter is ignored
func LogFileDeletionFailure ¶
LogFileDeletionFailure logs errors when a file cannot be deleted; does not write anything to the error output because that typically needs additional context
func LogPath ¶ added in v0.7.0
func LogPath() string
LogPath returns the path for log files; see https://github.com/majohn-r/cmd-toolkit/issues/16
func Mkdir ¶
Mkdir makes the specified directory; succeeds if the directory already exists. Fails if a plain file exists with the specified path.
func PlainFileExists ¶
PlainFileExists returns whether the specified file exists as a plain file (i.e., not a directory)
func ProcessFlagErrors ¶ added in v0.19.0
ProcessFlagErrors handles a slice of errors; returns true iff the slice is empty
func ProcessIsElevated ¶ added in v0.16.1
func ProcessIsElevated() bool
ProcessIsElevated determines whether the current process is running with elevated privileges
func ReadDirectory ¶
ReadDirectory returns the contents of a specified directory
func ReadFlags ¶ added in v0.19.0
func ReadFlags(producer FlagProducer, set *FlagSet) (map[string]*CommandFlag[any], []error)
ReadFlags reads the flags from a producer (typically a cobra commands flag structure)
func ReportFileCreationFailure ¶
ReportFileCreationFailure reports an error creating a file to error output and to the log
func SetApplicationPath ¶
SetApplicationPath is used to set applicationPath to a known value; intent is for use in testing scenarios
func StyledFlowerBox ¶ added in v0.17.0
func StyledFlowerBox(lines []string, style FlowerBoxStyle) []string
StyledFlowerBox draws a box around the provided slice of strings in a specified style
func ToErrorInterface ¶ added in v0.18.0
ToErrorInterface translates a nil ExitError instances to a nil error instances; non-nil ExitError instances are returned as is
func WritableDefaults ¶ added in v0.22.1
func WritableDefaults() []byte
WritableDefaults returns the current state of the defaults configuration as a slice of bytes
Types ¶
type BuildInformation ¶ added in v0.24.0
type BuildInformation interface { GoVersion() string Dependencies() []string MainVersion() string Settings() []string }
BuildInformation provides data about the build
func GetBuildData ¶ added in v0.24.0
func GetBuildData(reader func() (*debug.BuildInfo, bool)) BuildInformation
GetBuildData returns the build data, if any, obtained from the provided reader function
type CommandFlag ¶ added in v0.19.0
type CommandFlag[V commandFlagValue] struct { // Value is the flag's value Value V // UserSet is set if the flag value came from the command line UserSet bool }
CommandFlag captures a flag value and whether it was set by the user, i.e., on the command line
func GetBool ¶ added in v0.19.0
func GetBool(o output.Bus, results map[string]*CommandFlag[any], flagName string) (CommandFlag[bool], error)
GetBool gets the boolean value of a specific flag, handling common error conditions
type Configuration ¶
type Configuration struct { StringMap map[string]string BoolMap map[string]bool IntMap map[string]int ConfigurationMap map[string]*Configuration }
Configuration defines the data structure for configuration information.
func EmptyConfiguration ¶
func EmptyConfiguration() *Configuration
EmptyConfiguration creates an empty Configuration instance
func ReadDefaultsConfigFile ¶ added in v0.21.2
func ReadDefaultsConfigFile(o output.Bus) (*Configuration, bool)
ReadDefaultsConfigFile reads defaults.yaml from the specified path and returns a pointer to a cooked Configuration instance; if there is no such file, then an empty Configuration is returned and ok is true
func (*Configuration) BoolDefault ¶
func (c *Configuration) BoolDefault(key string, defaultValue bool) (bool, error)
BoolDefault returns a boolean value for a specified key
func (*Configuration) IntDefault ¶
func (c *Configuration) IntDefault(key string, b *IntBounds) (int, error)
IntDefault returns a default value for a specified key, which may or may not be defined in the Configuration instance
func (*Configuration) String ¶
func (c *Configuration) String() string
func (*Configuration) StringDefault ¶
func (c *Configuration) StringDefault(key, defaultValue string) (string, error)
StringDefault returns a string value for a specified key
func (*Configuration) SubConfiguration ¶
func (c *Configuration) SubConfiguration(key string) *Configuration
SubConfiguration returns a specified sub-configuration
type ElevationControl ¶ added in v0.16.0
type ElevationControl interface { // ConfigureExit sets up a new exit function that calls the original exit function, if // the process is running with elevated privileges; otherwise, it returns the original // exit function ConfigureExit(func(int)) func(int) // Log logs the elevationControl state Log(output.Bus, output.Level) // Status returns a slice of status data suitable to display to the user Status(string) []string // WillRunElevated checks whether the process can run with elevated privileges, and if so, // attempts to do so WillRunElevated() bool }
ElevationControl defines behavior for code pertaining to running a process with elevated privileges
func NewElevationControl ¶ added in v0.16.0
func NewElevationControl() ElevationControl
NewElevationControl creates a new instance of elevationControl that does not use an environment variable to determine whether execution with elevated privileges is desired
func NewElevationControlWithEnvVar ¶ added in v0.16.0
func NewElevationControlWithEnvVar(envVarName string, defaultEnvVarValue bool) ElevationControl
NewElevationControlWithEnvVar creates a new instance of elevationControl that uses an environment variable to determine whether execution with elevated privileges is desired
type EnvVarMemento ¶
type EnvVarMemento struct {
// contains filtered or unexported fields
}
EnvVarMemento encapsulates information about an environment variable: its name, its value, and whether it was set when accessed
func NewEnvVarMemento ¶
func NewEnvVarMemento(name string) *EnvVarMemento
NewEnvVarMemento creates a new instance of EnvVarMemento based on the state of the environment variable 'name'
func (*EnvVarMemento) Restore ¶
func (mem *EnvVarMemento) Restore()
Restore restores the environment variable encapsulated by the EnvVarMemento instance to its original state
type ExitError ¶ added in v0.18.0
type ExitError struct {
// contains filtered or unexported fields
}
ExitError encapsulates the command in which the error occurred, and the kind of error that terminated the command
func NewExitProgrammingError ¶ added in v0.18.0
NewExitProgrammingError creates an ExitError suitable for a programming error to have terminated the command
func NewExitSystemError ¶ added in v0.18.0
NewExitSystemError creates an ExitError suitable for a system call failure to have terminated the command
func NewExitUserError ¶ added in v0.18.0
NewExitUserError creates an ExitError suitable for a user error to have terminated the command
type FlagDetails ¶ added in v0.19.0
type FlagDetails struct { // AbbreviatedName is the flag's single character abbreviation, if any; typically empty AbbreviatedName string // Usage is a brief description of what the flag controls Usage string // ExpectedType describes whether the flag should be boolean, integer, or string ExpectedType valueType // DefaultValue gives the default value for the flag DefaultValue any }
FlagDetails captures the data needed by the cobra command code: a flag's abbreviated name (which may be empty), a usage string, its expected type, and its default value
func (*FlagDetails) Copy ¶ added in v0.19.0
func (fD *FlagDetails) Copy() *FlagDetails
Copy provides a copy of a FlagDetails instance - of primary use to test code.
type FlagProducer ¶ added in v0.19.0
type FlagProducer interface { // Changed returns true if the flag was set on the command line Changed(name string) bool // GetBool returns the boolean value of the named flag GetBool(name string) (bool, error) // GetInt returns the integer value of the named flag GetInt(name string) (int, error) // GetString returns the string value of the named flag GetString(name string) (string, error) }
FlagProducer encapsulates critical behavior of the cobra command flags for reading flag values and whether those values are changed (i.e., are defined on the command line)
type FlagSet ¶ added in v0.19.0
type FlagSet struct { // Name is the name of the set, typically, of a command Name string // Details provides a map of FlagDetails keyed by their flag names Details map[string]*FlagDetails // keys are flag names }
FlagSet captures a set of flags (typically, but not necessarily, associated with a cobra command) and the details of the flags for that set
type FlowerBoxStyle ¶ added in v0.17.0
type FlowerBoxStyle uint32
FlowerBoxStyle specifies a style of drawing flower box borders
type IntBounds ¶
IntBounds holds the bounds for an int value which has a minimum value, a maximum value, and a default that lies within those bounds
func NewIntBounds ¶
NewIntBounds creates an instance of IntBounds, sorting the provided value into reasonable fields