From 02ea49b0675d8304adb38e9e1632ccec1572dbad Mon Sep 17 00:00:00 2001 From: wener Date: Sun, 1 Nov 2020 04:08:24 +0800 Subject: [PATCH] cmd add Options --- cmd.go | 20 ++++++++++++++------ cmd_test.go | 12 ++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/cmd.go b/cmd.go index 8902d11..01e695d 100644 --- a/cmd.go +++ b/cmd.go @@ -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 @@ -177,6 +181,7 @@ func (c *Cmd) Clone() *Cmd { ) clone.Dir = c.Dir clone.Env = c.Env + clone.Options = c.Options return clone } @@ -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 diff --git a/cmd_test.go b/cmd_test.go index d3e5036..d197ad5 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -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") + } +}