aboutsummaryrefslogtreecommitdiff
path: root/internal/testgit/repo_run.go
blob: 448b88f0d967b5d335147e44dd68182e33699330 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package testgit

import (
	"bytes"
	"os/exec"
	"strings"
	"testing"
)

// Run executes git and returns trimmed textual output.
func (testRepo *TestRepo) Run(tb testing.TB, args ...string) string {
	tb.Helper()
	out := testRepo.runBytes(tb, nil, testRepo.dir, args...)

	return strings.TrimSpace(string(out))
}

// RunBytes executes git and returns raw output bytes.
func (testRepo *TestRepo) RunBytes(tb testing.TB, args ...string) []byte {
	tb.Helper()

	return testRepo.runBytes(tb, nil, testRepo.dir, args...)
}

// RunE executes git and returns trimmed textual output plus any command error.
func (testRepo *TestRepo) RunE(tb testing.TB, args ...string) (string, error) {
	tb.Helper()

	out, err := testRepo.runBytesE(nil, testRepo.dir, args...)

	return strings.TrimSpace(string(out)), err
}

// RunInput executes git with stdin and returns trimmed textual output.
func (testRepo *TestRepo) RunInput(tb testing.TB, stdin []byte, args ...string) string {
	tb.Helper()
	out := testRepo.runBytes(tb, stdin, testRepo.dir, args...)

	return strings.TrimSpace(string(out))
}

// RunInputBytes executes git with stdin and returns raw output bytes.
func (testRepo *TestRepo) RunInputBytes(tb testing.TB, stdin []byte, args ...string) []byte {
	tb.Helper()

	return testRepo.runBytes(tb, stdin, testRepo.dir, args...)
}

func (testRepo *TestRepo) runBytes(tb testing.TB, stdin []byte, dir string, args ...string) []byte {
	tb.Helper()

	out, err := testRepo.runBytesE(stdin, dir, args...)
	if err != nil {
		tb.Fatalf("git %v failed: %v\n%s", args, err, out)
	}

	return out
}

func (testRepo *TestRepo) runBytesE(stdin []byte, dir string, args ...string) ([]byte, error) {
	return testRepo.runBytesWithEnvNoHelper(stdin, dir, testRepo.env, args...)
}

// runBytesWithEnv executes git using the supplied environment.
func (testRepo *TestRepo) runBytesWithEnv(
	tb testing.TB,
	stdin []byte,
	dir string,
	env []string,
	args ...string,
) ([]byte, error) {
	tb.Helper()

	return testRepo.runBytesWithEnvNoHelper(stdin, dir, env, args...)
}

// runBytesWithEnvNoHelper executes git using the supplied environment without
// touching testing helper state.
func (testRepo *TestRepo) runBytesWithEnvNoHelper(
	stdin []byte,
	dir string,
	env []string,
	args ...string,
) ([]byte, error) {
	//nolint:noctx
	cmd := exec.Command("git", args...) //#nosec G204
	cmd.Dir = dir

	cmd.Env = env
	if stdin != nil {
		cmd.Stdin = bytes.NewReader(stdin)
	}

	return cmd.CombinedOutput()
}