From 07f5e0697fd603fbc4af8d865a80b9598d53715f Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 19 Apr 2023 14:25:31 +0800 Subject: [PATCH] feat: add option support for ExecCommand --- docs/system.md | 7 +++++-- docs/system_zh-CN.md | 7 +++++-- system/os.go | 13 ++++++++++++- system/os_test.go | 2 +- 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/docs/system.md b/docs/system.md index 1b8ade4..8b1a737 100644 --- a/docs/system.md +++ b/docs/system.md @@ -207,14 +207,17 @@ func main() { } ``` -### CompareOsEnv +### ExecCommand

use shell /bin/bash -c(linux) or cmd (windows) to execute command.

Signature: ```go -func ExecCommand(command string) (stdout, stderr string, err error) +type ( + Option func(*exec.Cmd) +) +func ExecCommand(command string, opts ...Option) (stdout, stderr string, err error) ``` Example: diff --git a/docs/system_zh-CN.md b/docs/system_zh-CN.md index b00e68e..95ef795 100644 --- a/docs/system_zh-CN.md +++ b/docs/system_zh-CN.md @@ -207,14 +207,17 @@ func main() { } ``` -### CompareOsEnv +### ExecCommand

使用shell /bin/bash -c(linux) 或 cmd (windows) 执行shell命令

Signature: ```go -func ExecCommand(command string) (stdout, stderr string, err error) +type ( + Option func(*exec.Cmd) +) +func ExecCommand(command string, opts ...Option) (stdout, stderr string, err error) ``` Example: diff --git a/system/os.go b/system/os.go index 5d41718..faa95f3 100644 --- a/system/os.go +++ b/system/os.go @@ -15,6 +15,10 @@ import ( "golang.org/x/text/encoding/simplifiedchinese" ) +type ( + Option func(*exec.Cmd) +) + // IsWindows check if current os is windows func IsWindows() bool { return runtime.GOOS == "windows" @@ -58,7 +62,7 @@ func CompareOsEnv(key, comparedEnv string) bool { // param `command` is a complete command string, like, ls -a (linux), dir(windows), ping 127.0.0.1 // in linux, use /bin/bash -c to execute command // in windows, use powershell.exe to execute command -func ExecCommand(command string) (stdout, stderr string, err error) { +func ExecCommand(command string, opts ...Option) (stdout, stderr string, err error) { var out bytes.Buffer var errOut bytes.Buffer @@ -66,6 +70,13 @@ func ExecCommand(command string) (stdout, stderr string, err error) { if IsWindows() { cmd = exec.Command("powershell.exe", command) } + + for _, opt := range opts { + if opt != nil { + opt(cmd) + } + } + cmd.Stdout = &out cmd.Stderr = &errOut diff --git a/system/os_test.go b/system/os_test.go index 911605f..1e8a138 100644 --- a/system/os_test.go +++ b/system/os_test.go @@ -45,7 +45,7 @@ func TestExecCommand(t *testing.T) { assert := internal.NewAssert(t, "TestExecCommand") // linux or mac - stdout, stderr, err := ExecCommand("ls") + stdout, stderr, err := ExecCommand("ls", WithForeground()) t.Log("std out: ", stdout) t.Log("std err: ", stderr) assert.Equal("", stderr)