File: command.go

package info (click to toggle)
gh 2.23.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 18,040 kB
  • sloc: asm: 6,813; ansic: 258; sh: 100; makefile: 96
file content (100 lines) | stat: -rw-r--r-- 2,120 bytes parent folder | download | duplicates (2)
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 Command struct {
	*exec.Cmd
}

func (gc *Command) 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 *Command) 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 *Command) 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(*Command)

func WithStderr(stderr io.Writer) CommandModifier {
	return func(gc *Command) {
		gc.Stderr = stderr
	}
}

func WithStdout(stdout io.Writer) CommandModifier {
	return func(gc *Command) {
		gc.Stdout = stdout
	}
}

func WithStdin(stdin io.Reader) CommandModifier {
	return func(gc *Command) {
		gc.Stdin = stdin
	}
}

func WithRepoDir(repoDir string) CommandModifier {
	return func(gc *Command) {
		gc.setRepoDir(repoDir)
	}
}