From 6f3e92a170b4c8fc214131716258533cf9e83efd Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 17 Jul 2022 16:12:48 +0800 Subject: [PATCH] [add] yao.system.Exec process --- main.go | 1 + system/process.go | 42 ++++++++++++++++++++++++++++++++++++++++++ system/process_test.go | 16 ++++++++++++++++ system/system.go | 4 ++++ 4 files changed, 63 insertions(+) create mode 100644 system/process.go create mode 100644 system/process_test.go create mode 100644 system/system.go diff --git a/main.go b/main.go index 2cf755e5..64609582 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( _ "github.com/yaoapp/yao/crypto" _ "github.com/yaoapp/yao/helper" _ "github.com/yaoapp/yao/network" + _ "github.com/yaoapp/yao/system" _ "github.com/yaoapp/yao/user" _ "github.com/yaoapp/yao/xfs" ) diff --git a/system/process.go b/system/process.go new file mode 100644 index 00000000..555de4e5 --- /dev/null +++ b/system/process.go @@ -0,0 +1,42 @@ +package system + +import ( + "fmt" + "os/exec" + "strings" + + "github.com/yaoapp/gou" + "github.com/yaoapp/kun/exception" +) + +func init() { + gou.RegisterProcessHandler("yao.system.Exec", processExec) +} + +// processExec execute the system command +func processExec(process *gou.Process) interface{} { + process.ValidateArgNums(1) + cmd := process.ArgsString(0) + + _, err := exec.LookPath(cmd) + if err != nil { + exception.New("command %s not found: %s", 400, cmd, err.Error()).Throw() + return nil + } + + args := []string{} + for i, arg := range process.Args { + if i == 0 { + continue + } + args = append(args, fmt.Sprintf("%v", arg)) + } + + res, err := exec.Command(cmd, args...).Output() + if err != nil { + exception.New("command %s error: %s", 500, cmd, err.Error()).Throw() + return nil + } + + return strings.TrimRight(string(res), "\n") +} diff --git a/system/process_test.go b/system/process_test.go new file mode 100644 index 00000000..054fd6d0 --- /dev/null +++ b/system/process_test.go @@ -0,0 +1,16 @@ +package system + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/yaoapp/gou" +) + +func TestProcessReturn(t *testing.T) { + output, err := gou.NewProcess("yao.system.Exec", "echo", "hello").Exec() + if err != nil { + t.Fatal(err) + } + assert.Equal(t, "hello", output) +} diff --git a/system/system.go b/system/system.go new file mode 100644 index 00000000..61e66e43 --- /dev/null +++ b/system/system.go @@ -0,0 +1,4 @@ +package system + +// Exec call system command +func Exec(cmd string, args ...string) {}