1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 23:22:28 +08:00

feat: add option support for ExecCommand

This commit is contained in:
dudaodong
2023-04-19 14:25:31 +08:00
parent 4ba91d7e4c
commit 07f5e0697f
4 changed files with 23 additions and 6 deletions

View File

@@ -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

View File

@@ -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)