[add] yao.system.Exec process

This commit is contained in:
Max 2022-07-17 16:12:48 +08:00
parent ae4529009e
commit 6f3e92a170
4 changed files with 63 additions and 0 deletions

View file

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

42
system/process.go Normal file
View file

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

16
system/process_test.go Normal file
View file

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

4
system/system.go Normal file
View file

@ -0,0 +1,4 @@
package system
// Exec call system command
func Exec(cmd string, args ...string) {}