aboutsummaryrefslogtreecommitdiff
path: root/internal/testgit/command.go
blob: dc96087770aa9a3770eab06973d21fa74ae64447 (about) (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package testgit

import (
	"io"
	"os/exec"
	"slices"
	"strings"
	"testing"
)

func (repo *Repo) Command(
	tb testing.TB,
	command string,
	args ...string,
) *exec.Cmd {
	tb.Helper()

	cmd := exec.CommandContext(tb.Context(), command, args...) //nolint:gosec // Test helper runs caller-selected commands.
	cmd.Dir = repo.path
	cmd.Env = repo.env

	return cmd
}

func (repo *Repo) Run(
	tb testing.TB,
	stdin io.Reader,
	command string,
	args ...string,
) (stdout []byte, err error) {
	tb.Helper()

	cmd := repo.Command(tb, command, args...)

	cmd.Stdin = stdin

	return cmd.Output() //nolint:wrapcheck
}

func setEnv(env []string, key string, value string) []string {
	prefix := key + "="
	i := slices.IndexFunc(env, func(entry string) bool {
		return strings.HasPrefix(entry, prefix)
	})
	if i >= 0 {
		env[i] = prefix + value

		return env
	}

	return append(env, prefix+value)
}