| 9 | |
| 10 | bashpkg "LuminaCode/tools/bash" |
| 11 | ) |
| 12 | |
| 13 | func RunShellCommand(ctx context.Context, dir string, command string, timeout time.Duration) CommandResult { |
| 14 | if timeout <= 0 { |
| 15 | timeout = time.Duration(DefaultCaseTimeout) * time.Second |
| 16 | } |
| 17 | start := time.Now() |
| 18 | cmdCtx, cancel := context.WithTimeout(ctx, timeout) |
| 19 | defer cancel() |
| 20 | argv := bashpkg.ShellArgv(command, "") |
| 21 | cmd := exec.CommandContext(cmdCtx, argv[0], argv[1:]...) |
| 22 | cmd.Dir = dir |
| 23 | var stdout bytes.Buffer |
| 24 | var stderr bytes.Buffer |
| 25 | cmd.Stdout = &stdout |
| 26 | cmd.Stderr = &stderr |
| 27 | result := CommandResult{ |
| 28 | Command: command, |
| 29 | } |
| 30 | err := cmd.Run() |
| 31 | result.DurationSecond = time.Since(start).Seconds() |
| 32 | result.Stdout = stdout.String() |
| 33 | result.Stderr = stderr.String() |
| 34 | if cmdCtx.Err() != nil { |
| 35 | result.TimedOut = errors.Is(cmdCtx.Err(), context.DeadlineExceeded) |
| 36 | } |
| 37 | if err != nil { |
| 38 | result.Error = err.Error() |
| 39 | if exitErr, ok := err.(*exec.ExitError); ok { |
| 40 | result.ExitCode = exitErr.ExitCode() |
| 41 | } else { |
| 42 | result.ExitCode = 1 |
| 43 | } |
| 44 | return result |
| 45 | } |
| 46 | result.ExitCode = 0 |
| 47 | return result |
| 48 | } |