cmd_toolkit

package module
v0.24.1 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2024 License: MIT Imports: 23 Imported by: 0

README

cmd-toolkit

GoDoc Reference go.mod LICENSE

Release Code Coverage Report Go Report Card Build Status

Basic code for windows command line tools; take a look at the GoDoc reference.

Documentation

Index

Constants

View Source
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
)
View Source
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
)
View Source
const (

	// BoolType represents a boolean flag type
	BoolType valueType
	// IntType represents an integer flag type
	IntType
	// StringType represents a string flag type
	StringType
)

Variables

View Source
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
)
View Source
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

View Source
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

func AddFlags(o output.Bus, c *Configuration, flags *pflag.FlagSet, sets ...*FlagSet)

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

func AssignFileSystem(newFileSystem afero.Fs) afero.Fs

AssignFileSystem sets the current afero.Fs instance and returns the original pre-assignment value

func CopyFile

func CopyFile(src, destination string) error

CopyFile copies a file. Adapted from https://github.com/cleversoap/go-cp/blob/master/cp.go

func Copyright(o output.Bus, first int, timestamp, owner string) string

Copyright returns an appropriately formatted copyright statement; see https://github.com/majohn-r/cmd-toolkit/issues/17

func DecoratedAppName added in v0.8.0

func DecoratedAppName(applicationName, applicationVersion, timestamp string) string

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

func DefaultConfigFileStatus() (string, bool)

DefaultConfigFileStatus returns the path of the defaults config file and whether that file exists

func DereferenceEnvVar

func DereferenceEnvVar(s string) (string, error)

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 DirExists

func DirExists(path string) bool

DirExists returns whether the specified file exists as a directory

func ErrorToString added in v0.23.0

func ErrorToString(e error) string

ErrorToString converts an error into an easy-to-read string

func FileSystem added in v0.10.0

func FileSystem() afero.Fs

FileSystem returns the current afero.Fs instance

func FormatBuildDependencies added in v0.8.0

func FormatBuildDependencies(dependencies []string) []string

FormatBuildDependencies returns build dependency data formatted nicely; see https://github.com/majohn-r/cmd-toolkit/issues/17

func FormatGoVersion added in v0.8.0

func FormatGoVersion(version string) string

FormatGoVersion returns the formatted go version; see https://github.com/majohn-r/cmd-toolkit/issues/17cmdtoolkit.

func InitApplicationPath

func InitApplicationPath(o output.Bus, applicationName string) bool

InitApplicationPath ensures that the application path exists

func InitLogging

func InitLogging(o output.Bus, applicationName string) (ok bool)

InitLogging sets up logging at the default log level

func InitLoggingWithLevel added in v0.2.0

func InitLoggingWithLevel(o output.Bus, l output.Level, applicationName string) (ok bool)

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

func LogCommandStart(o output.Bus, name string, m map[string]any)

LogCommandStart logs the beginning of command execution; if the provided map contains a "command" value, then the name parameter is ignored

func LogFileDeletionFailure

func LogFileDeletionFailure(o output.Bus, s string, e error)

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

func Mkdir(path string) error

Mkdir makes the specified directory; succeeds if the directory already exists. Fails if a plain file exists with the specified path.

func PlainFileExists

func PlainFileExists(path string) bool

PlainFileExists returns whether the specified file exists as a plain file (i.e., not a directory)

func ProcessFlagErrors added in v0.19.0

func ProcessFlagErrors(o output.Bus, eSlice []error) bool

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

func ReadDirectory(o output.Bus, dir string) ([]fs.FileInfo, bool)

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

func ReportFileCreationFailure(o output.Bus, cmd, file string, e error)

ReportFileCreationFailure reports an error creating a file to error output and to the log

func SetApplicationPath

func SetApplicationPath(s string) (previous string)

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

func ToErrorInterface(e *ExitError) error

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

func GetInt added in v0.19.0

func GetInt(o output.Bus, results map[string]*CommandFlag[any], flagName string) (CommandFlag[int], error)

GetInt gets the integer value of a specific flag, handling common error conditions

func GetString added in v0.19.0

func GetString(o output.Bus, results map[string]*CommandFlag[any], flagName string) (CommandFlag[string], error)

GetString gets the string 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

func NewExitProgrammingError(cmd string) *ExitError

NewExitProgrammingError creates an ExitError suitable for a programming error to have terminated the command

func NewExitSystemError added in v0.18.0

func NewExitSystemError(cmd string) *ExitError

NewExitSystemError creates an ExitError suitable for a system call failure to have terminated the command

func NewExitUserError added in v0.18.0

func NewExitUserError(cmd string) *ExitError

NewExitUserError creates an ExitError suitable for a user error to have terminated the command

func (*ExitError) Error added in v0.18.0

func (e *ExitError) Error() string

Error generates a description of what happened

func (*ExitError) Status added in v0.18.0

func (e *ExitError) Status() int

Status returns an int suitable to pass to os.Exit

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

type IntBounds struct {
	MinValue     int
	DefaultValue int
	MaxValue     int
}

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

func NewIntBounds(v1, v2, v3 int) *IntBounds

NewIntBounds creates an instance of IntBounds, sorting the provided value into reasonable fields

Directories

Path Synopsis
build module

Jump to

Keyboard shortcuts

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