forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
100 lines (88 loc) · 2.1 KB
/
command.go
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
96
97
98
99
100
package git
import (
"bytes"
"context"
"errors"
"io"
"os/exec"
"github.com/cli/cli/v2/internal/run"
)
type commandCtx = func(ctx context.Context, name string, args ...string) *exec.Cmd
type gitCommand struct {
*exec.Cmd
}
func (gc *gitCommand) Run() error {
stderr := &bytes.Buffer{}
if gc.Cmd.Stderr == nil {
gc.Cmd.Stderr = stderr
}
// This is a hack in order to not break the hundreds of
// existing tests that rely on `run.PrepareCmd` to be invoked.
err := run.PrepareCmd(gc.Cmd).Run()
if err != nil {
ge := GitError{err: err, Stderr: stderr.String()}
var exitError *exec.ExitError
if errors.As(err, &exitError) {
ge.ExitCode = exitError.ExitCode()
}
return &ge
}
return nil
}
func (gc *gitCommand) Output() ([]byte, error) {
gc.Stdout = nil
gc.Stderr = nil
// This is a hack in order to not break the hundreds of
// existing tests that rely on `run.PrepareCmd` to be invoked.
out, err := run.PrepareCmd(gc.Cmd).Output()
if err != nil {
ge := GitError{err: err}
var exitError *exec.ExitError
if errors.As(err, &exitError) {
ge.Stderr = string(exitError.Stderr)
ge.ExitCode = exitError.ExitCode()
}
err = &ge
}
return out, err
}
func (gc *gitCommand) setRepoDir(repoDir string) {
for i, arg := range gc.Args {
if arg == "-C" {
gc.Args[i+1] = repoDir
return
}
}
// Handle "--" invocations for testing purposes.
var index int
for i, arg := range gc.Args {
if arg == "--" {
index = i + 1
}
}
gc.Args = append(gc.Args[:index+3], gc.Args[index+1:]...)
gc.Args[index+1] = "-C"
gc.Args[index+2] = repoDir
}
// Allow individual commands to be modified from the default client options.
type CommandModifier func(*gitCommand)
func WithStderr(stderr io.Writer) CommandModifier {
return func(gc *gitCommand) {
gc.Stderr = stderr
}
}
func WithStdout(stdout io.Writer) CommandModifier {
return func(gc *gitCommand) {
gc.Stdout = stdout
}
}
func WithStdin(stdin io.Reader) CommandModifier {
return func(gc *gitCommand) {
gc.Stdin = stdin
}
}
func WithRepoDir(repoDir string) CommandModifier {
return func(gc *gitCommand) {
gc.setRepoDir(repoDir)
}
}