Skip to content

Commit

Permalink
cmd add Options
Browse files Browse the repository at this point in the history
  • Loading branch information
wenerme committed Oct 31, 2020
1 parent 6ae68a4 commit 02ea49b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
20 changes: 14 additions & 6 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,21 @@ 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
Stdout chan string // streaming STDOUT if enabled, else nil (see Options)
Stderr chan string // streaming STDERR if enabled, else nil (see Options)
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)
*sync.Mutex
started bool // cmd.Start called, no error
stopped bool // Stop called
Expand Down Expand Up @@ -177,6 +181,7 @@ func (c *Cmd) Clone() *Cmd {
)
clone.Dir = c.Dir
clone.Env = c.Env
clone.Options = c.Options
return clone
}

Expand Down Expand Up @@ -351,6 +356,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 {
f(cmd)
}

// //////////////////////////////////////////////////////////////////////
// Start command
Expand Down
12 changes: 12 additions & 0 deletions cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1127,3 +1127,15 @@ func TestStdinOk(t *testing.T) {
}
}
}

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

0 comments on commit 02ea49b

Please sign in to comment.