xe

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: BSD-3-Clause Imports: 10 Imported by: 0

README

xe

xe provides an easy way to execute commands, handling errors and parsing full command strings.

    err := xe.Run("git", xe.Args("commit -am"))

This version allows a full command string to be used:

    err := xe.RunSh("git commit -am")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Args

func Args(cfg *Config, str string) []string

Args returns a string parsed into separate args that can be passed into run commands.

func CmdRan

func CmdRan(err error) bool

CmdRan examines the error to determine if it was generated as a result of a command running via os/exec.Command. If the error is nil, or the command ran (even if it exited with a non-zero exit code), CmdRan reports true. If the error is an unrecognized type, or it is an error from exec.Command that says the command failed to run (usually due to the command not existing or not being executable), it reports false.

func Exec

func Exec(cmd string, args ...string) (ran bool, err error)

Exec calls Config.Exec on Major

func ExitStatus

func ExitStatus(err error) int

ExitStatus returns the exit status of the error if it is an exec.ExitError or if it implements ExitStatus() int. 0 if it is nil or 1 if it is a different error.

func MkdirAll

func MkdirAll(path string, perm os.FileMode) error

MkdirAll calls Config.MkdirAll on Major

func Output

func Output(cmd string, args ...string) (string, error)

Output calls Config.Output on Major

func PrintCmd

func PrintCmd(cmd string, err error)

PrintCmd calls Config.PrintCmd on Major

func RemoveAll

func RemoveAll(path string) error

RemoveAll calls Config.RemoveAll on Major

func Run

func Run(cmd string, args ...string) error

Run calls Config.Run on Major

func RunSh

func RunSh(cstr string) error

RunSh calls Config.RunSh on Major

func SetMajor

func SetMajor(c *Config)

SetMajor sets the config object that Major returns. It should be used sparingly, and only in cases where there is a clear property that should be set for all commands. If the given config object is nil, Major will go back to returning its default value.

func SetMinor

func SetMinor(c *Config)

SetMinor sets the config object that Minor returns. It should be used sparingly, and only in cases where there is a clear property that should be set for all commands. If the given config object is nil, Minor will go back to returning its default value.

func SetSilent

func SetSilent(c *Config)

SetSilent sets the config object that Silent returns. It should be used sparingly, and only in cases where there is a clear property that should be set for all commands. If the given config object is nil, Silent will go back to returning its default value.

func SetVerbose

func SetVerbose(c *Config)

SetVerbose sets the config object that Verbose returns. It should be used sparingly, and only in cases where there is a clear property that should be set for all commands. If the given config object is nil, Verbose will go back to returning its default value.

Types

type Config

type Config struct {
	// Buffer is whether to buffer the output of Stdout and Stderr,
	// which is necessary for the correct printing of commands and output
	// when there is an error with a command, and for correct coloring
	// on Windows. Therefore, it should be kept at the default value of
	// true in most cases, except for when a command will run for a log
	// time and print output throughout (eg: a log command).
	Buffer bool
	// Fatal is whether to fatally exit programs with [os.Exit] and an
	// exit code of 1 when there is an error running a command. It should
	// only be used by end-user apps, not libraries, which should use more
	// robust and idiomatic error handling.
	Fatal bool
	// PrintOnly is whether to only print commands that would be run and
	// not actually run them. It can be used, for example, for safely testing
	// an app.
	PrintOnly bool

	// The directory to execute commands in. If it is unset,
	// commands are run in the current directory.
	Dir string
	// Env contains any additional environment variables specified.
	// The current environment variables will also be passed to the
	// command, but they will be overridden by any variables here
	// if there are conflicts.
	Env map[string]string `set:"-"`

	// Stdout is the writer to write the standard output of called commands to.
	// It can be set to nil to disable the writing of the standard output.
	Stdout io.Writer
	// Stderr is the writer to write the standard error of called commands to.
	// It can be set to nil to disable the writing of the standard error.
	Stderr io.Writer
	// Stdin is the reader to use as the standard input.
	Stdin io.Reader
	// Commands is the writer to write the string representation of the called commands to.
	// It can be set to nil to disable the writing of the string representations of the called commands.
	Commands io.Writer
	// Errors is the writer to write program errors to.
	// It can be set to nil to disable the writing of program errors.
	Errors io.Writer
}

Config contains the configuration information that controls the behavior of xe. It is passed to most high-level functions, and a default version of it can be easily constructed using [DefaultConfig].

func Major

func Major() *Config

Major returns the default Config object for a major command, based on grog.UserLevel. It should be used for commands that are central to an app's logic and are more important for the user to know about and be able to see the output of. It results in commands and output being printed with a grog.UserLevel of slog.LevelInfo or below, whereas Minor results in that when it is slog.LevelDebug or below. Most commands in a typical use case should be Major, which is why the global helper functions operate on it. The object returned by Major is guaranteed to be unique, so it can be modified directly.

func Minor

func Minor() *Config

Minor returns the default Config object for a minor command, based on grog.UserLevel. It should be used for commands that support an app behind the scenes and are less important for the user to know about and be able to see the output of. It results in commands and output being printed with a grog.UserLevel of slog.LevelDebug or below, whereas Major results in that when it is slog.LevelInfo or below. The object returned by Minor is guaranteed to be unique, so it can be modified directly.

func Silent

func Silent() *Config

Silent returns the default Config object for a silent command, based on grog.UserLevel. It should be used for commands that whose output/input is private and needs to be always hidden from the user; for example, for a command that involves passwords. It results in commands and output never being printed. The object returned by Silent is guaranteed to be unique, so it can be modified directly.

func Verbose

func Verbose() *Config

Verbose returns the default Config object for a verbose command, based on grog.UserLevel. It should be used for commands whose output are central to an application; for example, for a logger or app runner. It results in commands and output being printed with a grog.UserLevel of slog.LevelWarn or below, whereas Major and Minor result in that when it is slog.LevelInfo and [slog.levelDebug] or below, respectively. The object returned by Verbose is guaranteed to be unique, so it can be modified directly.

func (*Config) Exec

func (c *Config) Exec(cmd string, args ...string) (ran bool, err error)

Exec executes the command, piping its stdout and stderr to the config writers. If the command fails, it will return an error with the command output. The given cmd and args may include references to environment variables in $FOO format, in which case these will be expanded before the command is run.

Ran reports if the command ran (rather than was not found or not executable). Code reports the exit code the command returned if it ran. If err == nil, ran is always true and code is always 0.

func (*Config) GetWriter

func (c *Config) GetWriter(w io.Writer, err error) io.Writer

GetWriter returns the appropriate writer to use based on the given writer and error. If the given error is non-nil, the returned writer is guaranteed to be non-nil, with [Config.Stderr] used as a backup. Otherwise, the returned writer will only be non-nil if the passed one is.

func (*Config) MkdirAll

func (c *Config) MkdirAll(path string, perm os.FileMode) error

MkdirAll is a helper function that calls os.MkdirAll and Config.PrintCmd.

func (*Config) OutCmd

func (c *Config) OutCmd(cmd string, args ...string) func(args ...string) (string, error)

OutCmd is like RunCmd except the command returns the output of the command.

func (*Config) Output

func (c *Config) Output(cmd string, args ...string) (string, error)

Output runs the command and returns the text from stdout.

func (*Config) PrintCmd

func (c *Config) PrintCmd(cmd string, err error)

PrintCmd uses [GetWriter] to print the given command to [Config.Commands] or [Config.Stderr], based on the given error and the config settings. A newline is automatically inserted.

func (*Config) RemoveAll

func (c *Config) RemoveAll(path string) error

RemoveAll is a helper function that calls os.RemoveAll and Config.PrintCmd.

func (*Config) Run

func (c *Config) Run(cmd string, args ...string) error

Run runs the given command using the given configuration information and arguments.

func (*Config) RunCmd

func (c *Config) RunCmd(cmd string, args ...string) func(args ...string) error

RunCmd returns a function that will call Run with the given command. This is useful for creating command aliases to make your scripts easier to read, like this:

 // in a helper file somewhere
 var g0 = sh.RunCmd("go")  // go is a keyword :(

 // somewhere in your main code
	if err := g0("install", "github.com/gohugo/hugo"); err != nil {
		return err
 }

Args passed to command get baked in as args to the command when you run it. Any args passed in when you run the returned function will be appended to the original args. For example, this is equivalent to the above:

var goInstall = sh.RunCmd("go", "install") goInstall("github.com/gohugo/hugo")

RunCmd uses Exec underneath, so see those docs for more details.

func (*Config) RunSh

func (c *Config) RunSh(cstr string) error

RunSh runs given full command string with args formatted as in a standard shell command

func (*Config) SetBuffer

func (t *Config) SetBuffer(v bool) *Config

SetBuffer sets the [Config.Buffer]: Buffer is whether to buffer the output of Stdout and Stderr, which is necessary for the correct printing of commands and output when there is an error with a command, and for correct coloring on Windows. Therefore, it should be kept at the default value of true in most cases, except for when a command will run for a log time and print output throughout (eg: a log command).

func (*Config) SetCommands

func (t *Config) SetCommands(v io.Writer) *Config

SetCommands sets the [Config.Commands]: Commands is the writer to write the string representation of the called commands to. It can be set to nil to disable the writing of the string representations of the called commands.

func (*Config) SetDir

func (t *Config) SetDir(v string) *Config

SetDir sets the [Config.Dir]: The directory to execute commands in. If it is unset, commands are run in the current directory.

func (*Config) SetEnv

func (c *Config) SetEnv(key, val string) *Config

SetEnv sets the given environment variable.

func (*Config) SetErrors

func (t *Config) SetErrors(v io.Writer) *Config

SetErrors sets the [Config.Errors]: Errors is the writer to write program errors to. It can be set to nil to disable the writing of program errors.

func (*Config) SetFatal

func (t *Config) SetFatal(v bool) *Config

SetFatal sets the [Config.Fatal]: Fatal is whether to fatally exit programs with os.Exit and an exit code of 1 when there is an error running a command. It should only be used by end-user apps, not libraries, which should use more robust and idiomatic error handling.

func (*Config) SetPrintOnly

func (t *Config) SetPrintOnly(v bool) *Config

SetPrintOnly sets the [Config.PrintOnly]: PrintOnly is whether to only print commands that would be run and not actually run them. It can be used, for example, for safely testing an app.

func (*Config) SetStderr

func (t *Config) SetStderr(v io.Writer) *Config

SetStderr sets the [Config.Stderr]: Stderr is the writer to write the standard error of called commands to. It can be set to nil to disable the writing of the standard error.

func (*Config) SetStdin

func (t *Config) SetStdin(v io.Reader) *Config

SetStdin sets the [Config.Stdin]: Stdin is the reader to use as the standard input.

func (*Config) SetStdout

func (t *Config) SetStdout(v io.Writer) *Config

SetStdout sets the [Config.Stdout]: Stdout is the writer to write the standard output of called commands to. It can be set to nil to disable the writing of the standard output.

Jump to

Keyboard shortcuts

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