Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework Cmd.Options as Options.SetCmd #75

Merged
merged 2 commits into from
Jan 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# go-cmd/cmd Changelog

## v1.4

### v1.4.0 (2022-01-01)

* Added `Options.BeforeExec` based on PR #53 #54 by @wenerme (issue #53)

## v1.3

### v1.3.1 (2021-10-13)
Expand Down
95 changes: 69 additions & 26 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,37 +53,55 @@ import (
"time"
)

// Apply ExecCmdOption before process start, used for customize SysProcAttr.
type ExecCmdOption func(cmd *exec.Cmd)

// Cmd represents an external command, similar to the Go built-in os/exec.Cmd.
// A Cmd cannot be reused after calling Start. Exported fields are read-only and
// should not be modified, except Env which can be set before calling Start.
// To create a new Cmd, call NewCmd or NewCmdOptions.
type Cmd struct {
Name string
Args []string
Env []string
Dir string
Options []ExecCmdOption
Stdout chan string // streaming STDOUT if enabled, else nil (see Options)
Stderr chan string // streaming STDERR if enabled, else nil (see Options)
// Name of binary (command) to run. This is the only required value.
// No path expansion is done.
// Used to set underlying os/exec.Cmd.Path.
Name string

// Commands line arguments passed to the command.
// Args are optional.
// Used to set underlying os/exec.Cmd.Args.
Args []string

// Environment variables set before running the command.
// Env is optional.
Env []string

// Current working directory from which to run the command.
// Dir is optional; default is current working directory
// of calling process.
// Used to set underlying os/exec.Cmd.Dir.
Dir string

// Stdout sets streaming STDOUT if enabled, else nil (see Options).
Stdout chan string

// Stderr sets streaming STDERR if enabled, else nil (see Options).
Stderr chan string

*sync.Mutex
started bool // cmd.Start called, no error
stopped bool // Stop called
done bool // run() done
final bool // status finalized in Status
startTime time.Time // if started true
stdoutBuf *OutputBuffer
stderrBuf *OutputBuffer
stdoutStream *OutputStream
stderrStream *OutputStream
status Status
statusChan chan Status // nil until Start() called
doneChan chan struct{} // closed when done running
started bool // cmd.Start called, no error
stopped bool // Stop called
done bool // run() done
final bool // status finalized in Status
startTime time.Time // if started true
stdoutBuf *OutputBuffer
stderrBuf *OutputBuffer
stdoutStream *OutputStream
stderrStream *OutputStream
status Status
statusChan chan Status // nil until Start() called
doneChan chan struct{} // closed when done running
beforeExecFuncs []func(cmd *exec.Cmd)
}

var (
// ErrNotStarted is returned by Stop if called before Start or StartWithStdin.
ErrNotStarted = errors.New("command not running")
)

Expand Down Expand Up @@ -134,14 +152,20 @@ type Options struct {
// faster and more efficient than polling Cmd.Status. The caller must read both
// streaming channels, else lines are dropped silently.
Streaming bool

// BeforeExec is a list of functions called immediately before starting
// the real command. These functions can be used to customize the underlying
// os/exec.Cmd. For example, to set SysProcAttr.
BeforeExec []func(cmd *exec.Cmd)
}

// NewCmdOptions creates a new Cmd with options. The command is not started
// until Start is called.
func NewCmdOptions(options Options, name string, args ...string) *Cmd {
c := &Cmd{
Name: name,
Args: args,
Name: name,
Args: args,
// --
Mutex: &sync.Mutex{},
status: Status{
Cmd: name,
Expand All @@ -167,6 +191,16 @@ func NewCmdOptions(options Options, name string, args ...string) *Cmd {
c.stderrStream = NewOutputStream(c.Stderr)
}

if len(options.BeforeExec) > 0 {
c.beforeExecFuncs = []func(cmd *exec.Cmd){}
for _, f := range options.BeforeExec {
if f == nil {
continue
}
c.beforeExecFuncs = append(c.beforeExecFuncs, f)
}
}

return c
}

Expand All @@ -185,7 +219,14 @@ func (c *Cmd) Clone() *Cmd {
)
clone.Dir = c.Dir
clone.Env = c.Env
clone.Options = c.Options

if len(c.beforeExecFuncs) > 0 {
clone.beforeExecFuncs = make([]func(cmd *exec.Cmd), len(c.beforeExecFuncs))
for i := range c.beforeExecFuncs {
clone.beforeExecFuncs[i] = c.beforeExecFuncs[i]
}
}

return clone
}

Expand Down Expand Up @@ -374,7 +415,9 @@ func (c *Cmd) run(in io.Reader) {
// is nil, use the current process' environment.
cmd.Env = c.Env
cmd.Dir = c.Dir
for _, f := range c.Options {

// Run all optional commands to customize underlying os/exe.Cmd.
for _, f := range c.beforeExecFuncs {
f(cmd)
}

Expand Down
39 changes: 34 additions & 5 deletions cmd_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build !windows
// +build !windows

package cmd_test
Expand Down Expand Up @@ -1128,14 +1129,42 @@ func TestStdinOk(t *testing.T) {
}
}

func TestExecCCmdOptions(t *testing.T) {
p := cmd.NewCmd("/bin/ls")
func TestOptionsBeforeExec(t *testing.T) {
handled := false
p.Options = append(p.Options, func(cmd *exec.Cmd) {
handled = true
})
p := cmd.NewCmdOptions(
cmd.Options{
BeforeExec: []func(cmd *exec.Cmd){
func(cmd *exec.Cmd) { handled = true },
},
},
"/bin/ls",
)
<-p.Start()
if !handled {
t.Error("exec cmd option not applied")
}

// nil funcs should be ignored, not cause a panic
handled = false
p = cmd.NewCmdOptions(
cmd.Options{
BeforeExec: []func(cmd *exec.Cmd){
nil,
func(cmd *exec.Cmd) { handled = true },
},
},
"/bin/ls",
)
<-p.Start()
if !handled {
t.Error("exec cmd option not applied")
}

// Cloning should copy the funcs
handled = false
p2 := p.Clone()
<-p2.Start()
if !handled {
t.Error("exec cmd option not applied")
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module github.com/go-cmd/cmd

go 1.16
go 1.17

require github.com/go-test/deep v1.0.7