aboutsummaryrefslogtreecommitdiff
path: root/executor.go
blob: ca8e5e2dd30cc1646959d549ca4c850fe23ae1e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package monzero

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"syscall"
)

// CheckExec runs a command line string.
// The output is recorded completely and returned as one message.
func CheckExec(check Check, ctx context.Context) CheckResult {
	result := CheckResult{}

	cmd := exec.CommandContext(ctx, check.Command[0], check.Command[1:]...)
	output := bytes.NewBuffer([]byte{})
	cmd.Stdout = output
	cmd.Stderr = output
	err := cmd.Run()
	if err != nil {
		if cmd.ProcessState == nil {
			result.Message = fmt.Sprintf("unknown error when running command: %w", err)
			result.ExitCode = 3
			return result
		}

		status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus)
		if !ok {
			result.Message = fmt.Sprintf("error running check: %w", err)
			result.ExitCode = 2
		} else {
			result.ExitCode = status.ExitStatus()
		}
	}
	result.Message = output.String()
	return result
}