File: exec.go

package info (click to toggle)
glab 1.53.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,936 kB
  • sloc: sh: 295; makefile: 153; perl: 99; ruby: 68; javascript: 67
file content (56 lines) | stat: -rw-r--r-- 1,121 bytes parent folder | download
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package bootstrap

import (
	"fmt"
	"io"
	"os/exec"
)

type Cmd interface {
	RunWithOutput(name string, arg ...string) ([]byte, error)
	Run(name string, arg ...string) error
}

type cmdWrapper struct {
	stdout, stderr io.Writer
	env            []string
}

type errorWithOutput struct {
	output []byte
	err    error
}

func (e errorWithOutput) Error() string {
	return fmt.Sprintf("command failed with %q and output:\n%s", e.err, e.output)
}

func (e errorWithOutput) Unwrap() error {
	return e.err
}

func NewCmd(stdout, stderr io.Writer, env []string) Cmd {
	return &cmdWrapper{
		stdout: stdout,
		stderr: stderr,
		env:    env,
	}
}

func (c *cmdWrapper) RunWithOutput(name string, arg ...string) ([]byte, error) {
	command := exec.Command(name, arg...)
	command.Env = c.env
	output, err := command.CombinedOutput()
	if err != nil {
		return output, &errorWithOutput{output: output, err: err}
	}
	return output, nil
}

func (c *cmdWrapper) Run(name string, arg ...string) error {
	command := exec.Command(name, arg...)
	command.Stdout = c.stdout
	command.Stderr = c.stderr
	command.Env = c.env
	return command.Run()
}