Files

116 lines
2.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package shell
import (
"bytes"
"context"
"errors"
"os/exec"
"runtime"
"strings"
"time"
"unicode/utf8"
)
// Runner 执行一段 shell。测试注入假实现。
type Runner interface {
Run(ctx context.Context, script string) (output string, err error)
}
// Interpreter 返回当前系统的解释器和参数。
// Windows 用 cmd.exe /c,macOS 和 Linux 用 /bin/sh -c。
func Interpreter(script string) (name string, args []string) {
if runtime.GOOS == "windows" {
return "cmd.exe", []string{"/c", script}
}
return "/bin/sh", []string{"-c", script}
}
// System 在当前登录用户的权限下执行。
type System struct {
Timeout time.Duration
}
func (s System) Run(ctx context.Context, script string) (string, error) {
timeout := s.Timeout
if timeout <= 0 {
timeout = 45 * time.Second
}
cctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
name, args := Interpreter(script)
cmd := exec.CommandContext(cctx, name, args...)
hide(cmd)
var buf limited
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Run()
out := strings.TrimSpace(buf.String())
if cctx.Err() == context.DeadlineExceeded {
return out, context.DeadlineExceeded
}
return out, err
}
// Summarize 把执行结果收成一句短话,不把系统内部错误原样抛出。
func Summarize(output string, err error) (ok bool, detail string) {
line := firstLine(output)
if err == nil {
if line == "" {
return true, "已完成"
}
return true, clip(line, 120)
}
if errors.Is(err, context.DeadlineExceeded) {
return false, "执行超时"
}
if line != "" {
return false, clip(line, 120)
}
return false, "没有成功"
}
func firstLine(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
if i := strings.IndexAny(s, "\r\n"); i >= 0 {
s = s[:i]
}
return strings.TrimSpace(s)
}
func clip(s string, n int) string {
if utf8.RuneCountInString(s) <= n {
return s
}
r := []rune(s)
return string(r[:n]) + "…"
}
// Summary 是日志里的命令摘要。
func Summary(script string) string {
s := firstLine(script)
return clip(s, 80)
}
type limited struct {
buf bytes.Buffer
}
func (l *limited) Write(p []byte) (int, error) {
const max = 8192
n := len(p)
if l.buf.Len() >= max {
return n, nil
}
room := max - l.buf.Len()
if len(p) > room {
p = p[:room]
}
_, _ = l.buf.Write(p)
return n, nil
}
func (l *limited) String() string { return l.buf.String() }