cmd

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2022 License: MIT Imports: 13 Imported by: 11

README

CI GoDoc Test Coverage Maintainability Go Report Card

cmd package

A simple package to execute shell commands on linux, darwin and windows.

Installation

$ go get -u github.com/commander-cli/cmd@v1.5.0

Usage

c := cmd.NewCommand("echo hello")

err := c.Execute()
if err != nil {
    panic(err.Error())    
}

fmt.Println(c.Stdout())
fmt.Println(c.Stderr())
Configure the command

To configure the command a option function will be passed which receives the command object as an argument passed by reference.

Default option functions:

  • cmd.WithCustomBaseCommand(*exec.Cmd)
  • cmd.WithStandardStreams
  • cmd.WithCustomStdout(...io.Writers)
  • cmd.WithCustomStderr(...io.Writers)
  • cmd.WithTimeout(time.Duration)
  • cmd.WithoutTimeout
  • cmd.WithWorkingDir(string)
  • cmd.WithEnvironmentVariables(cmd.EnvVars)
  • cmd.WithInheritedEnvironment(cmd.EnvVars)
Example
c := cmd.NewCommand("echo hello", cmd.WithStandardStreams)
c.Execute()
Set custom options
setWorkingDir := func (c *Command) {
    c.WorkingDir = "/tmp/test"
}

c := cmd.NewCommand("pwd", setWorkingDir)
c.Execute()
Testing

You can catch output streams to stdout and stderr with cmd.CaptureStandardOut.

// caputred is the captured output from all executed source code
// fnResult contains the result of the executed function
captured, fnResult := cmd.CaptureStandardOut(func() interface{} {
    c := NewCommand("echo hello", cmd.WithStandardStream)
    err := c.Execute()
    return err
})

// prints "hello"
fmt.Println(captured)

Development

Running tests
make test
ToDo
  • os.Stdout and os.Stderr output access after execution via c.Stdout() and c.Stderr()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptureStandardOutput

func CaptureStandardOutput(f func() interface{}) (string, interface{})

CaptureStandardOutput allows to capture the output which will be written to os.Stdout and os.Stderr. It returns the captured output and the return value of the called function

func WithCustomBaseCommand added in v1.5.0

func WithCustomBaseCommand(baseCommand *exec.Cmd) func(c *Command)

WithCustomBaseCommand allows the OS specific generated baseCommand to be overridden by an *os/exec.Cmd.

Example:

c := cmd.NewCommand(
  "echo hello",
  cmd.WithCustomBaseCommand(exec.Command("/bin/bash", "-c")),
)
c.Execute()

func WithCustomStderr

func WithCustomStderr(writers ...io.Writer) func(c *Command)

WithCustomStderr allows to add custom writers to stderr

func WithCustomStdout

func WithCustomStdout(writers ...io.Writer) func(c *Command)

WithCustomStdout allows to add custom writers to stdout

func WithEnvironmentVariables

func WithEnvironmentVariables(env EnvVars) func(c *Command)

WithEnvironmentVariables sets environment variables for the executed command

func WithInheritedEnvironment

func WithInheritedEnvironment(env EnvVars) func(c *Command)

WithInheritedEnvironment uses the env from the current process and allow to add more variables.

func WithStandardStreams

func WithStandardStreams(c *Command)

WithStandardStreams is used as an option by the NewCommand constructor function and writes the output streams to stderr and stdout of the operating system

Example:

c := cmd.NewCommand("echo hello", cmd.WithStandardStreams)
c.Execute()

func WithTimeout

func WithTimeout(t time.Duration) func(c *Command)

WithTimeout sets the timeout of the command

Example:

cmd.NewCommand("sleep 10;", cmd.WithTimeout(500))

func WithUser added in v1.6.0

func WithUser(credential syscall.Credential) func(c *Command)

WithUser allows the command to be run as a different user.

Example:

cred := syscall.Credential{Uid: 1000, Gid: 1000}
c := NewCommand("echo hello", cred)
c.Execute()

func WithWorkingDir

func WithWorkingDir(dir string) func(c *Command)

WithWorkingDir sets the current working directory

func WithoutTimeout

func WithoutTimeout(c *Command)

WithoutTimeout disables the timeout for the command

Types

type Command

type Command struct {
	Command      string
	Env          []string
	Dir          string
	Timeout      time.Duration
	StderrWriter io.Writer
	StdoutWriter io.Writer
	WorkingDir   string
	// contains filtered or unexported fields
}

Command represents a single command which can be executed

func NewCommand

func NewCommand(cmd string, options ...func(*Command)) *Command

NewCommand creates a new command You can add option with variadic option argument Default timeout is set to 30 minutes

Example:

     c := cmd.NewCommand("echo hello", function (c *Command) {
		    c.WorkingDir = "/tmp"
     })
     c.Execute()

or you can use existing options functions

c := cmd.NewCommand("echo hello", cmd.WithStandardStreams)
c.Execute()

func (*Command) AddEnv

func (c *Command) AddEnv(key, value string)

AddEnv adds an environment variable to the command If a variable gets passed like ${VAR_NAME} the env variable will be read out by the current shell

func (*Command) Combined

func (c *Command) Combined() string

Combined returns the combined output of stderr and stdout according to their timeline

func (*Command) Execute

func (c *Command) Execute() error

Execute executes the command and writes the results into it's own instance The results can be received with the Stdout(), Stderr() and ExitCode() methods

func (*Command) ExecuteContext added in v1.4.0

func (c *Command) ExecuteContext(ctx context.Context) error

ExecuteContext runs Execute but with Context

func (*Command) Executed

func (c *Command) Executed() bool

Executed returns if the command was already executed

func (*Command) ExitCode

func (c *Command) ExitCode() int

ExitCode returns the exit code of the command

func (*Command) Stderr

func (c *Command) Stderr() string

Stderr returns the output to stderr

func (*Command) Stdout

func (c *Command) Stdout() string

Stdout returns the output to stdout

type CommandInterface added in v1.6.0

type CommandInterface interface {
	AddEnv(string, string)
	Stdout() string
	Stderr() string
	Combined() string
	ExitCode() int
	Executed() bool
	ExecuteContext(context.Context) error
	Execute() error
}

type EnvVars

type EnvVars map[string]string

EnvVars represents a map where the key is the name of the env variable and the value is the value of the variable

Example:

env := map[string]string{"ENV": "VALUE"}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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