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

cmd add Options #53 #54

Merged
merged 1 commit into from
Oct 29, 2021
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
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")
}
}