Skip to content

Commit

Permalink
chore: add shell helpers to cmder package
Browse files Browse the repository at this point in the history
  • Loading branch information
fufuok committed Oct 31, 2024
1 parent 1ca8a12 commit a1c87c8
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
10 changes: 6 additions & 4 deletions cmder/helper.go → cmder/cmder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ import (
"github.com/go-cmd/cmd"
)

// 命令执行超时时间默认值
const cmdTimeout = 3 * time.Second
var (
// DefaultCMDTimeout 命令执行超时时间默认值
DefaultCMDTimeout = 3 * time.Second

var ErrCMDTimeout = errors.New("command execution timed out")
ErrCMDTimeout = errors.New("command execution timed out")
)

// RunCmd 运行命令, 返回结果和状态
func RunCmd(cmdArgs []string, timeout ...time.Duration) cmd.Status {
Expand All @@ -29,7 +31,7 @@ func RunCmdCombinedOutput(cmdArgs []string, timeout ...time.Duration) cmd.Status
}

func RunCmdWithOptions(cmdArgs []string, opts cmd.Options, timeout ...time.Duration) cmd.Status {
dur := cmdTimeout
dur := DefaultCMDTimeout
if len(timeout) > 0 {
dur = timeout[0]
}
Expand Down
55 changes: 55 additions & 0 deletions cmder/shell.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package cmder

import (
"fmt"
"strings"
"time"
)

var (
// DefaultShellTimeout Shell 执行默认超时时间
DefaultShellTimeout = 10 * time.Second

// BashCmd 主命令绝对路径
BashCmd = []string{"/bin/bash"}
)

// RunShell 运行 Shell 脚本返回是否执行成功
func RunShell(sh string, args ...string) (ok bool) {
_, _, ok = RunShellTimeoutWithResult(sh, DefaultShellTimeout, args...)
return
}

// RunShellTimeout 运行 Shell 脚本返回是否执行成功
func RunShellTimeout(sh string, timeout time.Duration, args ...string) (ok bool) {
_, _, ok = RunShellTimeoutWithResult(sh, timeout, args...)
return
}

// RunShellWithResult 运行 Shell 脚本并返回输出结果
func RunShellWithResult(sh string, args ...string) (stdout, errout string, ok bool) {
stdout, errout, ok = RunShellTimeoutWithResult(sh, DefaultShellTimeout, args...)
return
}

// RunShellTimeoutWithResult 运行 Shell 脚本并返回标准输出和错误输出, 以及是否执行成功
// 示例命令: /bin/bash /opt/app/script/echo.sh my-app
// 示例调用: RunShellTimeoutWithResult("/opt/app/script/echo.sh", 3*time.Second, []string{"my-app"})
func RunShellTimeoutWithResult(sh string, timeout time.Duration, args ...string) (stdout, errout string, ok bool) {
cmd := append(BashCmd, sh)
if len(args) > 0 {
cmd = append(cmd, args...)
}

status := RunCmd(cmd, timeout)
stdout = strings.Join(status.Stdout, "\n")
stdout = strings.TrimSpace(stdout)
errout = ""
if status.Error != nil {
errout += fmt.Sprintf("error: %v\n", status.Error)
}
errout += strings.Join(status.Stderr, "\n")
errout = strings.TrimSpace(errout)
ok = status.Exit == 0 && status.Error == nil
return
}

0 comments on commit a1c87c8

Please sign in to comment.