Welcome to mirror list, hosted at ThFree Co, Russian Federation.

command.go « gittest « git « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 90cd73ce8a0ca483329ed677af37c26ba7b1fee1 (plain)
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
package gittest

import (
	"io"
	"os"
	"os/exec"
	"testing"

	"gitlab.com/gitlab-org/gitaly/internal/command"
	"gitlab.com/gitlab-org/gitaly/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/internal/testhelper"
)

// ExecConfig contains configuration for ExecOpts.
type ExecConfig struct {
	// Stdin sets up stdin of the spawned command.
	Stdin io.Reader
	// Stdout sets up stdout of the spawned command. Note that `ExecOpts()` will not return any
	// output anymore if this field is set.
	Stdout io.Writer
	// Env contains environment variables that should be appended to the spawned command's
	// environment.
	Env []string
}

// Exec runs a git command and returns the standard output, or fails.
func Exec(t testing.TB, cfg config.Cfg, args ...string) []byte {
	t.Helper()
	return ExecOpts(t, cfg, ExecConfig{}, args...)
}

// ExecOpts runs a git command with the given configuration.
func ExecOpts(t testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) []byte {
	t.Helper()

	cmd := createCommand(t, cfg, execCfg, args...)

	output, err := cmd.Output()
	if err != nil {
		t.Log(cfg.Git.BinPath, args)
		if ee, ok := err.(*exec.ExitError); ok {
			t.Logf("%s: %s\n", ee.Stderr, output)
		}
		t.Fatal(err)
	}

	return output
}

// NewCommand creates a new Git command ready for execution.
func NewCommand(t testing.TB, cfg config.Cfg, args ...string) *exec.Cmd {
	t.Helper()
	return createCommand(t, cfg, ExecConfig{}, args...)
}

func createCommand(t testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) *exec.Cmd {
	t.Helper()

	ctx := testhelper.Context(t)

	execEnv := NewCommandFactory(t, cfg).GetExecutionEnvironment(ctx)

	cmd := exec.CommandContext(ctx, execEnv.BinaryPath, args...)
	cmd.Env = command.AllowedEnvironment(os.Environ())
	cmd.Env = append(command.GitEnv, cmd.Env...)
	cmd.Env = append(cmd.Env,
		"GIT_AUTHOR_DATE=1572776879 +0100",
		"GIT_COMMITTER_DATE=1572776879 +0100",
		"GIT_CONFIG_COUNT=4",
		"GIT_CONFIG_KEY_0=init.defaultBranch",
		"GIT_CONFIG_VALUE_0=master",
		"GIT_CONFIG_KEY_1=init.templateDir",
		"GIT_CONFIG_VALUE_1=",
		"GIT_CONFIG_KEY_2=user.name",
		"GIT_CONFIG_VALUE_2=Your Name",
		"GIT_CONFIG_KEY_3=user.email",
		"GIT_CONFIG_VALUE_3=you@example.com",
	)
	cmd.Env = append(cmd.Env, execEnv.EnvironmentVariables...)
	cmd.Env = append(cmd.Env, execCfg.Env...)

	cmd.Stdout = execCfg.Stdout
	cmd.Stdin = execCfg.Stdin

	return cmd
}