Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 26718a7

Browse files
martinscholz83Martin Scholz
andauthoredFeb 11, 2022
Change git.cmd to RunWithContext (#18693)
Change all `cmd...Pipeline` commands to `cmd.RunWithContext`. #18553 Co-authored-by: Martin Scholz <martin.scholz@versasec.com>
1 parent 393ea86 commit 26718a7

28 files changed

+530
-155
lines changed
 

‎integrations/pull_merge_test.go‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,13 @@ func TestCantMergeUnrelated(t *testing.T) {
274274

275275
stdin := bytes.NewBufferString("Unrelated File")
276276
var stdout strings.Builder
277-
err = git.NewCommand(git.DefaultContext, "hash-object", "-w", "--stdin").RunInDirFullPipeline(path, &stdout, nil, stdin)
277+
err = git.NewCommand(git.DefaultContext, "hash-object", "-w", "--stdin").RunWithContext(&git.RunContext{
278+
Timeout: -1,
279+
Dir: path,
280+
Stdin: stdin,
281+
Stdout: &stdout,
282+
})
283+
278284
assert.NoError(t, err)
279285
sha := strings.TrimSpace(stdout.String())
280286

@@ -301,7 +307,14 @@ func TestCantMergeUnrelated(t *testing.T) {
301307
_, _ = messageBytes.WriteString("\n")
302308

303309
stdout.Reset()
304-
err = git.NewCommand(git.DefaultContext, "commit-tree", treeSha).RunInDirTimeoutEnvFullPipeline(env, -1, path, &stdout, nil, messageBytes)
310+
err = git.NewCommand(git.DefaultContext, "commit-tree", treeSha).
311+
RunWithContext(&git.RunContext{
312+
Env: env,
313+
Timeout: -1,
314+
Dir: path,
315+
Stdin: messageBytes,
316+
Stdout: &stdout,
317+
})
305318
assert.NoError(t, err)
306319
commitSha := strings.TrimSpace(stdout.String())
307320

‎modules/git/batch_reader.go‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,11 @@ func EnsureValidGitRepository(ctx context.Context, repoPath string) error {
3434
stderr := strings.Builder{}
3535
err := NewCommand(ctx, "rev-parse").
3636
SetDescription(fmt.Sprintf("%s rev-parse [repo_path: %s]", GitExecutable, repoPath)).
37-
RunInDirFullPipeline(repoPath, nil, &stderr, nil)
37+
RunWithContext(&RunContext{
38+
Timeout: -1,
39+
Dir: repoPath,
40+
Stderr: &stderr,
41+
})
3842
if err != nil {
3943
return ConcatenateError(err, (&stderr).String())
4044
}
@@ -61,7 +65,13 @@ func CatFileBatchCheck(ctx context.Context, repoPath string) (WriteCloserError,
6165
stderr := strings.Builder{}
6266
err := NewCommand(ctx, "cat-file", "--batch-check").
6367
SetDescription(fmt.Sprintf("%s cat-file --batch-check [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)).
64-
RunInDirFullPipeline(repoPath, batchStdoutWriter, &stderr, batchStdinReader)
68+
RunWithContext(&RunContext{
69+
Timeout: -1,
70+
Dir: repoPath,
71+
Stdin: batchStdinReader,
72+
Stdout: batchStdoutWriter,
73+
Stderr: &stderr,
74+
})
6575
if err != nil {
6676
_ = batchStdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
6777
_ = batchStdinReader.CloseWithError(ConcatenateError(err, (&stderr).String()))
@@ -100,7 +110,13 @@ func CatFileBatch(ctx context.Context, repoPath string) (WriteCloserError, *bufi
100110
stderr := strings.Builder{}
101111
err := NewCommand(ctx, "cat-file", "--batch").
102112
SetDescription(fmt.Sprintf("%s cat-file --batch [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)).
103-
RunInDirFullPipeline(repoPath, batchStdoutWriter, &stderr, batchStdinReader)
113+
RunWithContext(&RunContext{
114+
Timeout: -1,
115+
Dir: repoPath,
116+
Stdin: batchStdinReader,
117+
Stdout: batchStdoutWriter,
118+
Stderr: &stderr,
119+
})
104120
if err != nil {
105121
_ = batchStdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
106122
_ = batchStdinReader.CloseWithError(ConcatenateError(err, (&stderr).String()))

‎modules/git/commit.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,12 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi
486486
stderr := new(bytes.Buffer)
487487
args := []string{"log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1", commitID}
488488

489-
err := NewCommand(ctx, args...).RunInDirPipeline(repoPath, w, stderr)
489+
err := NewCommand(ctx, args...).RunWithContext(&RunContext{
490+
Timeout: -1,
491+
Dir: repoPath,
492+
Stdout: w,
493+
Stderr: stderr,
494+
})
490495
w.Close() // Close writer to exit parsing goroutine
491496
if err != nil {
492497
return nil, ConcatenateError(err, stderr.String())

‎modules/git/diff.go‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -301,9 +301,12 @@ func GetAffectedFiles(repo *Repository, oldCommitID, newCommitID string, env []s
301301

302302
// Run `git diff --name-only` to get the names of the changed files
303303
err = NewCommand(repo.Ctx, "diff", "--name-only", oldCommitID, newCommitID).
304-
RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
305-
stdoutWriter, nil, nil,
306-
func(ctx context.Context, cancel context.CancelFunc) error {
304+
RunWithContext(&RunContext{
305+
Env: env,
306+
Timeout: -1,
307+
Dir: repo.Path,
308+
Stdout: stdoutWriter,
309+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
307310
// Close the writer end of the pipe to begin processing
308311
_ = stdoutWriter.Close()
309312
defer func() {
@@ -320,7 +323,8 @@ func GetAffectedFiles(repo *Repository, oldCommitID, newCommitID string, env []s
320323
affectedFiles = append(affectedFiles, path)
321324
}
322325
return scanner.Err()
323-
})
326+
},
327+
})
324328
if err != nil {
325329
log.Error("Unable to get affected files for commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
326330
}

‎modules/git/log_name_status.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,12 @@ func LogNameStatusRepo(ctx context.Context, repository, head, treepath string, p
5555

5656
go func() {
5757
stderr := strings.Builder{}
58-
err := NewCommand(ctx, args...).RunInDirFullPipeline(repository, stdoutWriter, &stderr, nil)
58+
err := NewCommand(ctx, args...).RunWithContext(&RunContext{
59+
Timeout: -1,
60+
Dir: repository,
61+
Stdout: stdoutWriter,
62+
Stderr: &stderr,
63+
})
5964
if err != nil {
6065
_ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
6166
} else {

‎modules/git/pipeline/catfile.go‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,13 @@ func CatFileBatchCheck(ctx context.Context, shasToCheckReader *io.PipeReader, ca
2727
stderr := new(bytes.Buffer)
2828
var errbuf strings.Builder
2929
cmd := git.NewCommand(ctx, "cat-file", "--batch-check")
30-
if err := cmd.RunInDirFullPipeline(tmpBasePath, catFileCheckWriter, stderr, shasToCheckReader); err != nil {
30+
if err := cmd.RunWithContext(&git.RunContext{
31+
Timeout: -1,
32+
Dir: tmpBasePath,
33+
Stdin: shasToCheckReader,
34+
Stdout: catFileCheckWriter,
35+
Stderr: stderr,
36+
}); err != nil {
3137
_ = catFileCheckWriter.CloseWithError(fmt.Errorf("git cat-file --batch-check [%s]: %v - %s", tmpBasePath, err, errbuf.String()))
3238
}
3339
}
@@ -40,7 +46,12 @@ func CatFileBatchCheckAllObjects(ctx context.Context, catFileCheckWriter *io.Pip
4046
stderr := new(bytes.Buffer)
4147
var errbuf strings.Builder
4248
cmd := git.NewCommand(ctx, "cat-file", "--batch-check", "--batch-all-objects")
43-
if err := cmd.RunInDirPipeline(tmpBasePath, catFileCheckWriter, stderr); err != nil {
49+
if err := cmd.RunWithContext(&git.RunContext{
50+
Timeout: -1,
51+
Dir: tmpBasePath,
52+
Stdout: catFileCheckWriter,
53+
Stderr: stderr,
54+
}); err != nil {
4455
log.Error("git cat-file --batch-check --batch-all-object [%s]: %v - %s", tmpBasePath, err, errbuf.String())
4556
err = fmt.Errorf("git cat-file --batch-check --batch-all-object [%s]: %v - %s", tmpBasePath, err, errbuf.String())
4657
_ = catFileCheckWriter.CloseWithError(err)
@@ -56,7 +67,13 @@ func CatFileBatch(ctx context.Context, shasToBatchReader *io.PipeReader, catFile
5667

5768
stderr := new(bytes.Buffer)
5869
var errbuf strings.Builder
59-
if err := git.NewCommand(ctx, "cat-file", "--batch").RunInDirFullPipeline(tmpBasePath, catFileBatchWriter, stderr, shasToBatchReader); err != nil {
70+
if err := git.NewCommand(ctx, "cat-file", "--batch").RunWithContext(&git.RunContext{
71+
Timeout: -1,
72+
Dir: tmpBasePath,
73+
Stdout: catFileBatchWriter,
74+
Stdin: shasToBatchReader,
75+
Stderr: stderr,
76+
}); err != nil {
6077
_ = shasToBatchReader.CloseWithError(fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String()))
6178
}
6279
}

‎modules/git/pipeline/lfs_nogogit.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,12 @@ func FindLFSFile(repo *git.Repository, hash git.SHA1) ([]*LFSResult, error) {
5353

5454
go func() {
5555
stderr := strings.Builder{}
56-
err := git.NewCommand(repo.Ctx, "rev-list", "--all").RunInDirPipeline(repo.Path, revListWriter, &stderr)
56+
err := git.NewCommand(repo.Ctx, "rev-list", "--all").RunWithContext(&git.RunContext{
57+
Timeout: -1,
58+
Dir: repo.Path,
59+
Stdout: revListWriter,
60+
Stderr: &stderr,
61+
})
5762
if err != nil {
5863
_ = revListWriter.CloseWithError(git.ConcatenateError(err, (&stderr).String()))
5964
} else {

‎modules/git/pipeline/namerev.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@ func NameRevStdin(ctx context.Context, shasToNameReader *io.PipeReader, nameRevS
2323

2424
stderr := new(bytes.Buffer)
2525
var errbuf strings.Builder
26-
if err := git.NewCommand(ctx, "name-rev", "--stdin", "--name-only", "--always").RunInDirFullPipeline(tmpBasePath, nameRevStdinWriter, stderr, shasToNameReader); err != nil {
26+
if err := git.NewCommand(ctx, "name-rev", "--stdin", "--name-only", "--always").RunWithContext(&git.RunContext{
27+
Timeout: -1,
28+
Dir: tmpBasePath,
29+
Stdout: nameRevStdinWriter,
30+
Stdin: shasToNameReader,
31+
Stderr: stderr,
32+
}); err != nil {
2733
_ = shasToNameReader.CloseWithError(fmt.Errorf("git name-rev [%s]: %v - %s", tmpBasePath, err, errbuf.String()))
2834
}
2935
}

‎modules/git/pipeline/revlist.go‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,12 @@ func RevListAllObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sy
2525
stderr := new(bytes.Buffer)
2626
var errbuf strings.Builder
2727
cmd := git.NewCommand(ctx, "rev-list", "--objects", "--all")
28-
if err := cmd.RunInDirPipeline(basePath, revListWriter, stderr); err != nil {
28+
if err := cmd.RunWithContext(&git.RunContext{
29+
Timeout: -1,
30+
Dir: basePath,
31+
Stdout: revListWriter,
32+
Stderr: stderr,
33+
}); err != nil {
2934
log.Error("git rev-list --objects --all [%s]: %v - %s", basePath, err, errbuf.String())
3035
err = fmt.Errorf("git rev-list --objects --all [%s]: %v - %s", basePath, err, errbuf.String())
3136
_ = revListWriter.CloseWithError(err)
@@ -40,7 +45,12 @@ func RevListObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sync.
4045
stderr := new(bytes.Buffer)
4146
var errbuf strings.Builder
4247
cmd := git.NewCommand(ctx, "rev-list", "--objects", headSHA, "--not", baseSHA)
43-
if err := cmd.RunInDirPipeline(tmpBasePath, revListWriter, stderr); err != nil {
48+
if err := cmd.RunWithContext(&git.RunContext{
49+
Timeout: -1,
50+
Dir: tmpBasePath,
51+
Stdout: revListWriter,
52+
Stderr: stderr,
53+
}); err != nil {
4454
log.Error("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String())
4555
errChan <- fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String())
4656
}

‎modules/git/repo.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,13 @@ func Push(ctx context.Context, repoPath string, opts PushOptions) error {
204204
opts.Timeout = -1
205205
}
206206

207-
err := cmd.RunInDirTimeoutEnvPipeline(opts.Env, opts.Timeout, repoPath, &outbuf, &errbuf)
207+
err := cmd.RunWithContext(&RunContext{
208+
Env: opts.Env,
209+
Timeout: opts.Timeout,
210+
Dir: repoPath,
211+
Stdout: &outbuf,
212+
Stderr: &errbuf,
213+
})
208214
if err != nil {
209215
if strings.Contains(errbuf.String(), "non-fast-forward") {
210216
return &ErrPushOutOfDate{

‎modules/git/repo_archive.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,12 @@ func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, t
5757
)
5858

5959
var stderr strings.Builder
60-
err := NewCommand(ctx, args...).RunInDirPipeline(repo.Path, target, &stderr)
60+
err := NewCommand(ctx, args...).RunWithContext(&RunContext{
61+
Timeout: -1,
62+
Dir: repo.Path,
63+
Stdout: target,
64+
Stderr: &stderr,
65+
})
6166
if err != nil {
6267
return ConcatenateError(err, stderr.String())
6368
}

‎modules/git/repo_attribute.go‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,13 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[
7676

7777
cmd := NewCommand(repo.Ctx, cmdArgs...)
7878

79-
if err := cmd.RunInDirTimeoutEnvPipeline(env, -1, repo.Path, stdOut, stdErr); err != nil {
79+
if err := cmd.RunWithContext(&RunContext{
80+
Env: env,
81+
Timeout: -1,
82+
Dir: repo.Path,
83+
Stdout: stdOut,
84+
Stderr: stdErr,
85+
}); err != nil {
8086
return nil, fmt.Errorf("failed to run check-attr: %v\n%s\n%s", err, stdOut.String(), stdErr.String())
8187
}
8288

@@ -182,9 +188,17 @@ func (c *CheckAttributeReader) Run() error {
182188
_ = c.Close()
183189
}()
184190
stdErr := new(bytes.Buffer)
185-
err := c.cmd.RunInDirTimeoutEnvFullPipelineFunc(c.env, -1, c.Repo.Path, c.stdOut, stdErr, c.stdinReader, func(_ context.Context, _ context.CancelFunc) error {
186-
close(c.running)
187-
return nil
191+
err := c.cmd.RunWithContext(&RunContext{
192+
Env: c.env,
193+
Timeout: -1,
194+
Dir: c.Repo.Path,
195+
Stdin: c.stdinReader,
196+
Stdout: c.stdOut,
197+
Stderr: stdErr,
198+
PipelineFunc: func(_ context.Context, _ context.CancelFunc) error {
199+
close(c.running)
200+
return nil
201+
},
188202
})
189203
if err != nil && c.ctx.Err() != nil && err.Error() != "signal: killed" {
190204
return fmt.Errorf("failed to run attr-check. Error: %w\nStderr: %s", err, stdErr.String())

‎modules/git/repo_branch_nogogit.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,12 @@ func walkShowRef(ctx context.Context, repoPath, arg string, skip, limit int, wal
9696
if arg != "" {
9797
args = append(args, arg)
9898
}
99-
err := NewCommand(ctx, args...).RunInDirPipeline(repoPath, stdoutWriter, stderrBuilder)
99+
err := NewCommand(ctx, args...).RunWithContext(&RunContext{
100+
Timeout: -1,
101+
Dir: repoPath,
102+
Stdout: stdoutWriter,
103+
Stderr: stderrBuilder,
104+
})
100105
if err != nil {
101106
if stderrBuilder.Len() == 0 {
102107
_ = stdoutWriter.Close()

‎modules/git/repo_commit.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,12 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
211211
err := NewCommand(repo.Ctx, "log", revision, "--follow",
212212
"--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize*page),
213213
prettyLogFormat, "--", file).
214-
RunInDirPipeline(repo.Path, stdoutWriter, &stderr)
214+
RunWithContext(&RunContext{
215+
Timeout: -1,
216+
Dir: repo.Path,
217+
Stdout: stdoutWriter,
218+
Stderr: &stderr,
219+
})
215220
if err != nil {
216221
_ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
217222
} else {

‎modules/git/repo_compare.go‎

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,23 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
147147
}
148148

149149
if err := NewCommand(repo.Ctx, "diff", "-z", "--name-only", base+separator+head).
150-
RunInDirPipeline(repo.Path, w, stderr); err != nil {
150+
RunWithContext(&RunContext{
151+
Timeout: -1,
152+
Dir: repo.Path,
153+
Stdout: w,
154+
Stderr: stderr,
155+
}); err != nil {
151156
if strings.Contains(stderr.String(), "no merge base") {
152157
// git >= 2.28 now returns an error if base and head have become unrelated.
153158
// previously it would return the results of git diff -z --name-only base head so let's try that...
154159
w = &lineCountWriter{}
155160
stderr.Reset()
156-
if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only", base, head).RunInDirPipeline(repo.Path, w, stderr); err == nil {
161+
if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only", base, head).RunWithContext(&RunContext{
162+
Timeout: -1,
163+
Dir: repo.Path,
164+
Stdout: w,
165+
Stderr: stderr,
166+
}); err == nil {
157167
return w.numLines, nil
158168
}
159169
}
@@ -238,28 +248,46 @@ func (repo *Repository) GetDiffOrPatch(base, head string, w io.Writer, patch, bi
238248

239249
// GetDiff generates and returns patch data between given revisions, optimized for human readability
240250
func (repo *Repository) GetDiff(base, head string, w io.Writer) error {
241-
return NewCommand(repo.Ctx, "diff", "-p", base, head).
242-
RunInDirPipeline(repo.Path, w, nil)
251+
return NewCommand(repo.Ctx, "diff", "-p", base, head).RunWithContext(&RunContext{
252+
Timeout: -1,
253+
Dir: repo.Path,
254+
Stdout: w,
255+
})
243256
}
244257

245258
// GetDiffBinary generates and returns patch data between given revisions, including binary diffs.
246259
func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error {
247260
if CheckGitVersionAtLeast("1.7.7") == nil {
248-
return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram", base, head).
249-
RunInDirPipeline(repo.Path, w, nil)
261+
return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram", base, head).RunWithContext(&RunContext{
262+
Timeout: -1,
263+
Dir: repo.Path,
264+
Stdout: w,
265+
})
250266
}
251-
return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--patience", base, head).
252-
RunInDirPipeline(repo.Path, w, nil)
267+
return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--patience", base, head).RunWithContext(&RunContext{
268+
Timeout: -1,
269+
Dir: repo.Path,
270+
Stdout: w,
271+
})
253272
}
254273

255274
// GetPatch generates and returns format-patch data between given revisions, able to be used with `git apply`
256275
func (repo *Repository) GetPatch(base, head string, w io.Writer) error {
257276
stderr := new(bytes.Buffer)
258277
err := NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout", base+"..."+head).
259-
RunInDirPipeline(repo.Path, w, stderr)
278+
RunWithContext(&RunContext{
279+
Timeout: -1,
280+
Dir: repo.Path,
281+
Stdout: w,
282+
Stderr: stderr,
283+
})
260284
if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) {
261285
return NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout", base, head).
262-
RunInDirPipeline(repo.Path, w, nil)
286+
RunWithContext(&RunContext{
287+
Timeout: -1,
288+
Dir: repo.Path,
289+
Stdout: w,
290+
})
263291
}
264292
return err
265293
}
@@ -268,7 +296,12 @@ func (repo *Repository) GetPatch(base, head string, w io.Writer) error {
268296
func (repo *Repository) GetDiffFromMergeBase(base, head string, w io.Writer) error {
269297
stderr := new(bytes.Buffer)
270298
err := NewCommand(repo.Ctx, "diff", "-p", "--binary", base+"..."+head).
271-
RunInDirPipeline(repo.Path, w, stderr)
299+
RunWithContext(&RunContext{
300+
Timeout: -1,
301+
Dir: repo.Path,
302+
Stdout: w,
303+
Stderr: stderr,
304+
})
272305
if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) {
273306
return repo.GetDiffBinary(base, head, w)
274307
}

‎modules/git/repo_index.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,13 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error {
106106
buffer.WriteByte('\000')
107107
}
108108
}
109-
return cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, bytes.NewReader(buffer.Bytes()))
109+
return cmd.RunWithContext(&RunContext{
110+
Timeout: -1,
111+
Dir: repo.Path,
112+
Stdin: bytes.NewReader(buffer.Bytes()),
113+
Stdout: stdout,
114+
Stderr: stderr,
115+
})
110116
}
111117

112118
// AddObjectToIndex adds the provided object hash to the index at the provided filename

‎modules/git/repo_object.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,13 @@ func (repo *Repository) hashObject(reader io.Reader) (string, error) {
4545
cmd := NewCommand(repo.Ctx, "hash-object", "-w", "--stdin")
4646
stdout := new(bytes.Buffer)
4747
stderr := new(bytes.Buffer)
48-
err := cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, reader)
48+
err := cmd.RunWithContext(&RunContext{
49+
Timeout: -1,
50+
Dir: repo.Path,
51+
Stdin: reader,
52+
Stdout: stdout,
53+
Stderr: stderr,
54+
})
4955
if err != nil {
5056
return "", err
5157
}

‎modules/git/repo_ref_nogogit.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
2323

2424
go func() {
2525
stderrBuilder := &strings.Builder{}
26-
err := NewCommand(repo.Ctx, "for-each-ref").RunInDirPipeline(repo.Path, stdoutWriter, stderrBuilder)
26+
err := NewCommand(repo.Ctx, "for-each-ref").RunWithContext(&RunContext{
27+
Timeout: -1,
28+
Dir: repo.Path,
29+
Stdout: stdoutWriter,
30+
Stderr: stderrBuilder,
31+
})
2732
if err != nil {
2833
_ = stdoutWriter.CloseWithError(ConcatenateError(err, stderrBuilder.String()))
2934
} else {

‎modules/git/repo_stats.go‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,14 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
6767
}
6868

6969
stderr := new(strings.Builder)
70-
err = NewCommand(repo.Ctx, args...).RunInDirTimeoutEnvFullPipelineFunc(
71-
nil, -1, repo.Path,
72-
stdoutWriter, stderr, nil,
73-
func(ctx context.Context, cancel context.CancelFunc) error {
70+
err = NewCommand(repo.Ctx, args...).RunWithContext(&RunContext{
71+
Env: []string{},
72+
Timeout: -1,
73+
Dir: repo.Path,
74+
Stdout: stdoutWriter,
75+
Stderr: stderr,
76+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
7477
_ = stdoutWriter.Close()
75-
7678
scanner := bufio.NewScanner(stdoutReader)
7779
scanner.Split(bufio.ScanLines)
7880
stats.CommitCount = 0
@@ -103,11 +105,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
103105
case 4: // E-mail
104106
email := strings.ToLower(l)
105107
if _, ok := authors[email]; !ok {
106-
authors[email] = &CodeActivityAuthor{
107-
Name: author,
108-
Email: email,
109-
Commits: 0,
110-
}
108+
authors[email] = &CodeActivityAuthor{Name: author, Email: email, Commits: 0}
111109
}
112110
authors[email].Commits++
113111
default: // Changed file
@@ -128,7 +126,6 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
128126
}
129127
}
130128
}
131-
132129
a := make([]*CodeActivityAuthor, 0, len(authors))
133130
for _, v := range authors {
134131
a = append(a, v)
@@ -137,14 +134,13 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
137134
sort.Slice(a, func(i, j int) bool {
138135
return a[i].Commits > a[j].Commits
139136
})
140-
141137
stats.AuthorCount = int64(len(authors))
142138
stats.ChangedFiles = int64(len(files))
143139
stats.Authors = a
144-
145140
_ = stdoutReader.Close()
146141
return nil
147-
})
142+
},
143+
})
148144
if err != nil {
149145
return nil, fmt.Errorf("Failed to get GetCodeActivityStats for repository.\nError: %w\nStderr: %s", err, stderr)
150146
}

‎modules/git/repo_tree.go‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,14 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt
6060

6161
stdout := new(bytes.Buffer)
6262
stderr := new(bytes.Buffer)
63-
err = cmd.RunInDirTimeoutEnvFullPipeline(env, -1, repo.Path, stdout, stderr, messageBytes)
63+
err = cmd.RunWithContext(&RunContext{
64+
Env: env,
65+
Timeout: -1,
66+
Dir: repo.Path,
67+
Stdin: messageBytes,
68+
Stdout: stdout,
69+
Stderr: stderr,
70+
})
6471

6572
if err != nil {
6673
return SHA1{}, ConcatenateError(err, stderr.String())

‎modules/gitgraph/graph.go‎

Lines changed: 48 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -64,57 +64,63 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo
6464

6565
scanner := bufio.NewScanner(stdoutReader)
6666

67-
if err := graphCmd.RunInDirTimeoutEnvFullPipelineFunc(nil, -1, r.Path, stdoutWriter, stderr, nil, func(ctx context.Context, cancel context.CancelFunc) error {
68-
_ = stdoutWriter.Close()
69-
defer stdoutReader.Close()
70-
parser := &Parser{}
71-
parser.firstInUse = -1
72-
parser.maxAllowedColors = maxAllowedColors
73-
if maxAllowedColors > 0 {
74-
parser.availableColors = make([]int, maxAllowedColors)
75-
for i := range parser.availableColors {
76-
parser.availableColors[i] = i + 1
77-
}
78-
} else {
79-
parser.availableColors = []int{1, 2}
80-
}
81-
for commitsToSkip > 0 && scanner.Scan() {
82-
line := scanner.Bytes()
83-
dataIdx := bytes.Index(line, []byte("DATA:"))
84-
if dataIdx < 0 {
85-
dataIdx = len(line)
67+
if err := graphCmd.RunWithContext(&git.RunContext{
68+
Timeout: -1,
69+
Dir: r.Path,
70+
Stdout: stdoutWriter,
71+
Stderr: stderr,
72+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
73+
_ = stdoutWriter.Close()
74+
defer stdoutReader.Close()
75+
parser := &Parser{}
76+
parser.firstInUse = -1
77+
parser.maxAllowedColors = maxAllowedColors
78+
if maxAllowedColors > 0 {
79+
parser.availableColors = make([]int, maxAllowedColors)
80+
for i := range parser.availableColors {
81+
parser.availableColors[i] = i + 1
82+
}
83+
} else {
84+
parser.availableColors = []int{1, 2}
8685
}
87-
starIdx := bytes.IndexByte(line, '*')
88-
if starIdx >= 0 && starIdx < dataIdx {
89-
commitsToSkip--
86+
for commitsToSkip > 0 && scanner.Scan() {
87+
line := scanner.Bytes()
88+
dataIdx := bytes.Index(line, []byte("DATA:"))
89+
if dataIdx < 0 {
90+
dataIdx = len(line)
91+
}
92+
starIdx := bytes.IndexByte(line, '*')
93+
if starIdx >= 0 && starIdx < dataIdx {
94+
commitsToSkip--
95+
}
96+
parser.ParseGlyphs(line[:dataIdx])
9097
}
91-
parser.ParseGlyphs(line[:dataIdx])
92-
}
9398

94-
row := 0
99+
row := 0
100+
101+
// Skip initial non-commit lines
102+
for scanner.Scan() {
103+
line := scanner.Bytes()
104+
if bytes.IndexByte(line, '*') >= 0 {
105+
if err := parser.AddLineToGraph(graph, row, line); err != nil {
106+
cancel()
107+
return err
108+
}
109+
break
110+
}
111+
parser.ParseGlyphs(line)
112+
}
95113

96-
// Skip initial non-commit lines
97-
for scanner.Scan() {
98-
line := scanner.Bytes()
99-
if bytes.IndexByte(line, '*') >= 0 {
114+
for scanner.Scan() {
115+
row++
116+
line := scanner.Bytes()
100117
if err := parser.AddLineToGraph(graph, row, line); err != nil {
101118
cancel()
102119
return err
103120
}
104-
break
105-
}
106-
parser.ParseGlyphs(line)
107-
}
108-
109-
for scanner.Scan() {
110-
row++
111-
line := scanner.Bytes()
112-
if err := parser.AddLineToGraph(graph, row, line); err != nil {
113-
cancel()
114-
return err
115121
}
116-
}
117-
return scanner.Err()
122+
return scanner.Err()
123+
},
118124
}); err != nil {
119125
return graph, err
120126
}

‎routers/private/hook_verification.go‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,12 @@ func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env []
4545

4646
// This is safe as force pushes are already forbidden
4747
err = git.NewCommand(repo.Ctx, "rev-list", oldCommitID+"..."+newCommitID).
48-
RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
49-
stdoutWriter, nil, nil,
50-
func(ctx context.Context, cancel context.CancelFunc) error {
48+
RunWithContext(&git.RunContext{
49+
Env: env,
50+
Timeout: -1,
51+
Dir: repo.Path,
52+
Stdout: stdoutWriter,
53+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
5154
_ = stdoutWriter.Close()
5255
err := readAndVerifyCommitsFromShaReader(stdoutReader, repo, env)
5356
if err != nil {
@@ -56,7 +59,8 @@ func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env []
5659
}
5760
_ = stdoutReader.Close()
5861
return err
59-
})
62+
},
63+
})
6064
if err != nil && !isErrUnverifiedCommit(err) {
6165
log.Error("Unable to check commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
6266
}
@@ -89,9 +93,12 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
8993
hash := git.MustIDFromString(sha)
9094

9195
return git.NewCommand(repo.Ctx, "cat-file", "commit", sha).
92-
RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
93-
stdoutWriter, nil, nil,
94-
func(ctx context.Context, cancel context.CancelFunc) error {
96+
RunWithContext(&git.RunContext{
97+
Env: env,
98+
Timeout: -1,
99+
Dir: repo.Path,
100+
Stdout: stdoutWriter,
101+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
95102
_ = stdoutWriter.Close()
96103
commit, err := git.CommitFromReader(repo, hash, stdoutReader)
97104
if err != nil {
@@ -105,7 +112,8 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
105112
}
106113
}
107114
return nil
108-
})
115+
},
116+
})
109117
}
110118

111119
type errUnverifiedCommit struct {

‎services/mirror/mirror_pull.go‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,12 @@ func pruneBrokenReferences(ctx context.Context,
161161
stdoutBuilder.Reset()
162162
pruneErr := git.NewCommand(ctx, "remote", "prune", m.GetRemoteName()).
163163
SetDescription(fmt.Sprintf("Mirror.runSync %ssPrune references: %s ", wiki, m.Repo.FullName())).
164-
RunInDirTimeoutPipeline(timeout, repoPath, stdoutBuilder, stderrBuilder)
164+
RunWithContext(&git.RunContext{
165+
Timeout: timeout,
166+
Dir: repoPath,
167+
Stdout: stdoutBuilder,
168+
Stderr: stderrBuilder,
169+
})
165170
if pruneErr != nil {
166171
stdout := stdoutBuilder.String()
167172
stderr := stderrBuilder.String()
@@ -203,7 +208,12 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
203208
stderrBuilder := strings.Builder{}
204209
if err := git.NewCommand(ctx, gitArgs...).
205210
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
206-
RunInDirTimeoutPipeline(timeout, repoPath, &stdoutBuilder, &stderrBuilder); err != nil {
211+
RunWithContext(&git.RunContext{
212+
Timeout: timeout,
213+
Dir: repoPath,
214+
Stdout: &stdoutBuilder,
215+
Stderr: &stderrBuilder,
216+
}); err != nil {
207217
stdout := stdoutBuilder.String()
208218
stderr := stderrBuilder.String()
209219

@@ -226,7 +236,12 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
226236
stdoutBuilder.Reset()
227237
if err = git.NewCommand(ctx, gitArgs...).
228238
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
229-
RunInDirTimeoutPipeline(timeout, repoPath, &stdoutBuilder, &stderrBuilder); err != nil {
239+
RunWithContext(&git.RunContext{
240+
Timeout: timeout,
241+
Dir: repoPath,
242+
Stdout: &stdoutBuilder,
243+
Stderr: &stderrBuilder,
244+
}); err != nil {
230245
stdout := stdoutBuilder.String()
231246
stderr := stderrBuilder.String()
232247

@@ -282,7 +297,12 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
282297
stdoutBuilder.Reset()
283298
if err := git.NewCommand(ctx, "remote", "update", "--prune", m.GetRemoteName()).
284299
SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())).
285-
RunInDirTimeoutPipeline(timeout, wikiPath, &stdoutBuilder, &stderrBuilder); err != nil {
300+
RunWithContext(&git.RunContext{
301+
Timeout: timeout,
302+
Dir: wikiPath,
303+
Stdout: &stdoutBuilder,
304+
Stderr: &stderrBuilder,
305+
}); err != nil {
286306
stdout := stdoutBuilder.String()
287307
stderr := stderrBuilder.String()
288308

@@ -314,7 +334,12 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
314334

315335
if err = git.NewCommand(ctx, "remote", "update", "--prune", m.GetRemoteName()).
316336
SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())).
317-
RunInDirTimeoutPipeline(timeout, wikiPath, &stdoutBuilder, &stderrBuilder); err != nil {
337+
RunWithContext(&git.RunContext{
338+
Timeout: timeout,
339+
Dir: wikiPath,
340+
Stdout: &stdoutBuilder,
341+
Stderr: &stderrBuilder,
342+
}); err != nil {
318343
stdout := stdoutBuilder.String()
319344
stderr := stderrBuilder.String()
320345
stderrMessage = sanitizer.Replace(stderr)

‎services/pull/merge.go‎

Lines changed: 115 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -188,43 +188,79 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
188188
}
189189

190190
// Switch off LFS process (set required, clean and smudge here also)
191-
if err := gitConfigCommand().AddArguments("filter.lfs.process", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
191+
if err := gitConfigCommand().AddArguments("filter.lfs.process", "").
192+
RunWithContext(&git.RunContext{
193+
Timeout: -1,
194+
Dir: tmpBasePath,
195+
Stdout: &outbuf,
196+
Stderr: &errbuf,
197+
}); err != nil {
192198
log.Error("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
193199
return "", fmt.Errorf("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
194200
}
195201
outbuf.Reset()
196202
errbuf.Reset()
197203

198-
if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
204+
if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").
205+
RunWithContext(&git.RunContext{
206+
Timeout: -1,
207+
Dir: tmpBasePath,
208+
Stdout: &outbuf,
209+
Stderr: &errbuf,
210+
}); err != nil {
199211
log.Error("git config [filter.lfs.required -> <false> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
200212
return "", fmt.Errorf("git config [filter.lfs.required -> <false> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
201213
}
202214
outbuf.Reset()
203215
errbuf.Reset()
204216

205-
if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
217+
if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").
218+
RunWithContext(&git.RunContext{
219+
Timeout: -1,
220+
Dir: tmpBasePath,
221+
Stdout: &outbuf,
222+
Stderr: &errbuf,
223+
}); err != nil {
206224
log.Error("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
207225
return "", fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
208226
}
209227
outbuf.Reset()
210228
errbuf.Reset()
211229

212-
if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
230+
if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").
231+
RunWithContext(&git.RunContext{
232+
Timeout: -1,
233+
Dir: tmpBasePath,
234+
Stdout: &outbuf,
235+
Stderr: &errbuf,
236+
}); err != nil {
213237
log.Error("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
214238
return "", fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
215239
}
216240
outbuf.Reset()
217241
errbuf.Reset()
218242

219-
if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
243+
if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").
244+
RunWithContext(&git.RunContext{
245+
Timeout: -1,
246+
Dir: tmpBasePath,
247+
Stdout: &outbuf,
248+
Stderr: &errbuf,
249+
}); err != nil {
220250
log.Error("git config [core.sparseCheckout -> true ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
221251
return "", fmt.Errorf("git config [core.sparsecheckout -> true]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
222252
}
223253
outbuf.Reset()
224254
errbuf.Reset()
225255

226256
// Read base branch index
227-
if err := git.NewCommand(ctx, "read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
257+
if err := git.NewCommand(ctx, "read-tree", "HEAD").
258+
RunWithContext(&git.RunContext{
259+
Timeout: -1,
260+
Dir: tmpBasePath,
261+
Stdout: &outbuf,
262+
Stderr: &errbuf,
263+
}); err != nil {
228264
log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
229265
return "", fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
230266
}
@@ -279,15 +315,27 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
279315
fallthrough
280316
case repo_model.MergeStyleRebaseMerge:
281317
// Checkout head branch
282-
if err := git.NewCommand(ctx, "checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
318+
if err := git.NewCommand(ctx, "checkout", "-b", stagingBranch, trackingBranch).
319+
RunWithContext(&git.RunContext{
320+
Timeout: -1,
321+
Dir: tmpBasePath,
322+
Stdout: &outbuf,
323+
Stderr: &errbuf,
324+
}); err != nil {
283325
log.Error("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
284326
return "", fmt.Errorf("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
285327
}
286328
outbuf.Reset()
287329
errbuf.Reset()
288330

289331
// Rebase before merging
290-
if err := git.NewCommand(ctx, "rebase", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
332+
if err := git.NewCommand(ctx, "rebase", baseBranch).
333+
RunWithContext(&git.RunContext{
334+
Timeout: -1,
335+
Dir: tmpBasePath,
336+
Stdout: &outbuf,
337+
Stderr: &errbuf,
338+
}); err != nil {
291339
// Rebase will leave a REBASE_HEAD file in .git if there is a conflict
292340
if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "REBASE_HEAD")); statErr == nil {
293341
var commitSha string
@@ -335,7 +383,13 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
335383
}
336384

337385
// Checkout base branch again
338-
if err := git.NewCommand(ctx, "checkout", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
386+
if err := git.NewCommand(ctx, "checkout", baseBranch).
387+
RunWithContext(&git.RunContext{
388+
Timeout: -1,
389+
Dir: tmpBasePath,
390+
Stdout: &outbuf,
391+
Stderr: &errbuf,
392+
}); err != nil {
339393
log.Error("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
340394
return "", fmt.Errorf("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
341395
}
@@ -375,7 +429,14 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
375429
}
376430
sig := pr.Issue.Poster.NewGitSig()
377431
if signArg == "" {
378-
if err := git.NewCommand(ctx, "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
432+
if err := git.NewCommand(ctx, "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).
433+
RunWithContext(&git.RunContext{
434+
Env: env,
435+
Timeout: -1,
436+
Dir: tmpBasePath,
437+
Stdout: &outbuf,
438+
Stderr: &errbuf,
439+
}); err != nil {
379440
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
380441
return "", fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
381442
}
@@ -384,7 +445,14 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
384445
// add trailer
385446
message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String())
386447
}
387-
if err := git.NewCommand(ctx, "commit", signArg, fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
448+
if err := git.NewCommand(ctx, "commit", signArg, fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).
449+
RunWithContext(&git.RunContext{
450+
Env: env,
451+
Timeout: -1,
452+
Dir: tmpBasePath,
453+
Stdout: &outbuf,
454+
Stderr: &errbuf,
455+
}); err != nil {
388456
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
389457
return "", fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
390458
}
@@ -448,7 +516,13 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
448516
}
449517

450518
// Push back to upstream.
451-
if err := pushCmd.RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
519+
if err := pushCmd.RunWithContext(&git.RunContext{
520+
Env: env,
521+
Timeout: -1,
522+
Dir: tmpBasePath,
523+
Stdout: &outbuf,
524+
Stderr: &errbuf,
525+
}); err != nil {
452526
if strings.Contains(errbuf.String(), "non-fast-forward") {
453527
return "", &git.ErrPushOutOfDate{
454528
StdOut: outbuf.String(),
@@ -475,12 +549,26 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
475549
func commitAndSignNoAuthor(ctx context.Context, pr *models.PullRequest, message, signArg, tmpBasePath string, env []string) error {
476550
var outbuf, errbuf strings.Builder
477551
if signArg == "" {
478-
if err := git.NewCommand(ctx, "commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
552+
if err := git.NewCommand(ctx, "commit", "-m", message).
553+
RunWithContext(&git.RunContext{
554+
Env: env,
555+
Timeout: -1,
556+
Dir: tmpBasePath,
557+
Stdout: &outbuf,
558+
Stderr: &errbuf,
559+
}); err != nil {
479560
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
480561
return fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
481562
}
482563
} else {
483-
if err := git.NewCommand(ctx, "commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
564+
if err := git.NewCommand(ctx, "commit", signArg, "-m", message).
565+
RunWithContext(&git.RunContext{
566+
Env: env,
567+
Timeout: -1,
568+
Dir: tmpBasePath,
569+
Stdout: &outbuf,
570+
Stderr: &errbuf,
571+
}); err != nil {
484572
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
485573
return fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
486574
}
@@ -490,7 +578,12 @@ func commitAndSignNoAuthor(ctx context.Context, pr *models.PullRequest, message,
490578

491579
func runMergeCommand(pr *models.PullRequest, mergeStyle repo_model.MergeStyle, cmd *git.Command, tmpBasePath string) error {
492580
var outbuf, errbuf strings.Builder
493-
if err := cmd.RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
581+
if err := cmd.RunWithContext(&git.RunContext{
582+
Timeout: -1,
583+
Dir: tmpBasePath,
584+
Stdout: &outbuf,
585+
Stderr: &errbuf,
586+
}); err != nil {
494587
// Merge will leave a MERGE_HEAD file in the .git folder if there is a conflict
495588
if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "MERGE_HEAD")); statErr == nil {
496589
// We have a merge conflict error
@@ -523,7 +616,13 @@ func getDiffTree(ctx context.Context, repoPath, baseBranch, headBranch string) (
523616
getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
524617
var outbuf, errbuf strings.Builder
525618
// Compute the diff-tree for sparse-checkout
526-
if err := git.NewCommand(ctx, "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
619+
if err := git.NewCommand(ctx, "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").
620+
RunWithContext(&git.RunContext{
621+
Timeout: -1,
622+
Dir: repoPath,
623+
Stdout: &outbuf,
624+
Stderr: &errbuf,
625+
}); err != nil {
527626
return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
528627
}
529628
return outbuf.String(), nil

‎services/pull/patch.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -383,10 +383,11 @@ func checkConflicts(ctx context.Context, pr *models.PullRequest, gitRepo *git.Re
383383
// 7. Run the check command
384384
conflict = false
385385
err = git.NewCommand(gitRepo.Ctx, args...).
386-
RunInDirTimeoutEnvFullPipelineFunc(
387-
nil, -1, tmpBasePath,
388-
nil, stderrWriter, nil,
389-
func(ctx context.Context, cancel context.CancelFunc) error {
386+
RunWithContext(&git.RunContext{
387+
Timeout: -1,
388+
Dir: tmpBasePath,
389+
Stderr: stderrWriter,
390+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
390391
// Close the writer end of the pipe to begin processing
391392
_ = stderrWriter.Close()
392393
defer func() {
@@ -444,7 +445,8 @@ func checkConflicts(ctx context.Context, pr *models.PullRequest, gitRepo *git.Re
444445
}
445446

446447
return nil
447-
})
448+
},
449+
})
448450

449451
// 8. If there is a conflict the `git apply` command will return a non-zero error code - so there will be a positive error.
450452
if err != nil {

‎services/pull/patch_unmerged.go‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,12 @@ func readUnmergedLsFileLines(ctx context.Context, tmpBasePath string, outputChan
6363

6464
stderr := &strings.Builder{}
6565
err = git.NewCommand(ctx, "ls-files", "-u", "-z").
66-
RunInDirTimeoutEnvFullPipelineFunc(
67-
nil, -1, tmpBasePath,
68-
lsFilesWriter, stderr, nil,
69-
func(_ context.Context, _ context.CancelFunc) error {
66+
RunWithContext(&git.RunContext{
67+
Timeout: -1,
68+
Dir: tmpBasePath,
69+
Stdout: lsFilesWriter,
70+
Stderr: stderr,
71+
PipelineFunc: func(_ context.Context, _ context.CancelFunc) error {
7072
_ = lsFilesWriter.Close()
7173
defer func() {
7274
_ = lsFilesReader.Close()
@@ -102,8 +104,8 @@ func readUnmergedLsFileLines(ctx context.Context, tmpBasePath string, outputChan
102104
toemit.path = split[2][2 : len(split[2])-1]
103105
outputChan <- toemit
104106
}
105-
})
106-
107+
},
108+
})
107109
if err != nil {
108110
outputChan <- &lsFileLine{err: fmt.Errorf("git ls-files -u -z: %v", git.ConcatenateError(err, stderr.String()))}
109111
}

‎services/pull/temp_repo.go‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,13 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
9393
}
9494

9595
var outbuf, errbuf strings.Builder
96-
if err := git.NewCommand(ctx, "remote", "add", "-t", pr.BaseBranch, "-m", pr.BaseBranch, "origin", baseRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
96+
if err := git.NewCommand(ctx, "remote", "add", "-t", pr.BaseBranch, "-m", pr.BaseBranch, "origin", baseRepoPath).
97+
RunWithContext(&git.RunContext{
98+
Timeout: -1,
99+
Dir: tmpBasePath,
100+
Stdout: &outbuf,
101+
Stderr: &errbuf,
102+
}); err != nil {
97103
log.Error("Unable to add base repository as origin [%s -> %s]: %v\n%s\n%s", pr.BaseRepo.FullName(), tmpBasePath, err, outbuf.String(), errbuf.String())
98104
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
99105
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@@ -103,7 +109,13 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
103109
outbuf.Reset()
104110
errbuf.Reset()
105111

106-
if err := git.NewCommand(ctx, "fetch", "origin", "--no-tags", "--", pr.BaseBranch+":"+baseBranch, pr.BaseBranch+":original_"+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
112+
if err := git.NewCommand(ctx, "fetch", "origin", "--no-tags", "--", pr.BaseBranch+":"+baseBranch, pr.BaseBranch+":original_"+baseBranch).
113+
RunWithContext(&git.RunContext{
114+
Timeout: -1,
115+
Dir: tmpBasePath,
116+
Stdout: &outbuf,
117+
Stderr: &errbuf,
118+
}); err != nil {
107119
log.Error("Unable to fetch origin base branch [%s:%s -> base, original_base in %s]: %v:\n%s\n%s", pr.BaseRepo.FullName(), pr.BaseBranch, tmpBasePath, err, outbuf.String(), errbuf.String())
108120
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
109121
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@@ -113,7 +125,13 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
113125
outbuf.Reset()
114126
errbuf.Reset()
115127

116-
if err := git.NewCommand(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
128+
if err := git.NewCommand(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+baseBranch).
129+
RunWithContext(&git.RunContext{
130+
Timeout: -1,
131+
Dir: tmpBasePath,
132+
Stdout: &outbuf,
133+
Stderr: &errbuf,
134+
}); err != nil {
117135
log.Error("Unable to set HEAD as base branch [%s]: %v\n%s\n%s", tmpBasePath, err, outbuf.String(), errbuf.String())
118136
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
119137
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@@ -131,7 +149,13 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
131149
return "", fmt.Errorf("Unable to head base repository to temporary repo [%s -> tmpBasePath]: %v", pr.HeadRepo.FullName(), err)
132150
}
133151

134-
if err := git.NewCommand(ctx, "remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
152+
if err := git.NewCommand(ctx, "remote", "add", remoteRepoName, headRepoPath).
153+
RunWithContext(&git.RunContext{
154+
Timeout: -1,
155+
Dir: tmpBasePath,
156+
Stdout: &outbuf,
157+
Stderr: &errbuf,
158+
}); err != nil {
135159
log.Error("Unable to add head repository as head_repo [%s -> %s]: %v\n%s\n%s", pr.HeadRepo.FullName(), tmpBasePath, err, outbuf.String(), errbuf.String())
136160
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
137161
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@@ -151,7 +175,13 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
151175
} else {
152176
headBranch = pr.GetGitRefName()
153177
}
154-
if err := git.NewCommand(ctx, "fetch", "--no-tags", remoteRepoName, headBranch+":"+trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
178+
if err := git.NewCommand(ctx, "fetch", "--no-tags", remoteRepoName, headBranch+":"+trackingBranch).
179+
RunWithContext(&git.RunContext{
180+
Timeout: -1,
181+
Dir: tmpBasePath,
182+
Stdout: &outbuf,
183+
Stderr: &errbuf,
184+
}); err != nil {
155185
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
156186
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
157187
}

‎services/repository/files/temp_repo.go‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,13 @@ func (t *TemporaryUploadRepository) LsFiles(filenames ...string) ([]string, erro
9797
}
9898
}
9999

100-
if err := git.NewCommand(t.ctx, cmdArgs...).RunInDirPipeline(t.basePath, stdOut, stdErr); err != nil {
100+
if err := git.NewCommand(t.ctx, cmdArgs...).
101+
RunWithContext(&git.RunContext{
102+
Timeout: -1,
103+
Dir: t.basePath,
104+
Stdout: stdOut,
105+
Stderr: stdErr,
106+
}); err != nil {
101107
log.Error("Unable to run git ls-files for temporary repo: %s (%s) Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), t.basePath, err, stdOut.String(), stdErr.String())
102108
err = fmt.Errorf("Unable to run git ls-files for temporary repo of: %s Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), err, stdOut.String(), stdErr.String())
103109
return nil, err
@@ -124,7 +130,14 @@ func (t *TemporaryUploadRepository) RemoveFilesFromIndex(filenames ...string) er
124130
}
125131
}
126132

127-
if err := git.NewCommand(t.ctx, "update-index", "--remove", "-z", "--index-info").RunInDirFullPipeline(t.basePath, stdOut, stdErr, stdIn); err != nil {
133+
if err := git.NewCommand(t.ctx, "update-index", "--remove", "-z", "--index-info").
134+
RunWithContext(&git.RunContext{
135+
Timeout: -1,
136+
Dir: t.basePath,
137+
Stdin: stdIn,
138+
Stdout: stdOut,
139+
Stderr: stdErr,
140+
}); err != nil {
128141
log.Error("Unable to update-index for temporary repo: %s (%s) Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), t.basePath, err, stdOut.String(), stdErr.String())
129142
return fmt.Errorf("Unable to update-index for temporary repo: %s Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), err, stdOut.String(), stdErr.String())
130143
}
@@ -136,7 +149,14 @@ func (t *TemporaryUploadRepository) HashObject(content io.Reader) (string, error
136149
stdOut := new(bytes.Buffer)
137150
stdErr := new(bytes.Buffer)
138151

139-
if err := git.NewCommand(t.ctx, "hash-object", "-w", "--stdin").RunInDirFullPipeline(t.basePath, stdOut, stdErr, content); err != nil {
152+
if err := git.NewCommand(t.ctx, "hash-object", "-w", "--stdin").
153+
RunWithContext(&git.RunContext{
154+
Timeout: -1,
155+
Dir: t.basePath,
156+
Stdin: content,
157+
Stdout: stdOut,
158+
Stderr: stdErr,
159+
}); err != nil {
140160
log.Error("Unable to hash-object to temporary repo: %s (%s) Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), t.basePath, err, stdOut.String(), stdErr.String())
141161
return "", fmt.Errorf("Unable to hash-object to temporary repo: %s Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), err, stdOut.String(), stdErr.String())
142162
}
@@ -254,7 +274,15 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *user_m
254274

255275
stdout := new(bytes.Buffer)
256276
stderr := new(bytes.Buffer)
257-
if err := git.NewCommand(t.ctx, args...).RunInDirTimeoutEnvFullPipeline(env, -1, t.basePath, stdout, stderr, messageBytes); err != nil {
277+
if err := git.NewCommand(t.ctx, args...).
278+
RunWithContext(&git.RunContext{
279+
Env: env,
280+
Timeout: -1,
281+
Dir: t.basePath,
282+
Stdin: messageBytes,
283+
Stdout: stdout,
284+
Stderr: stderr,
285+
}); err != nil {
258286
log.Error("Unable to commit-tree in temporary repo: %s (%s) Error: %v\nStdout: %s\nStderr: %s",
259287
t.repo.FullName(), t.basePath, err, stdout, stderr)
260288
return "", fmt.Errorf("Unable to commit-tree in temporary repo: %s Error: %v\nStdout: %s\nStderr: %s",
@@ -304,15 +332,21 @@ func (t *TemporaryUploadRepository) DiffIndex() (*gitdiff.Diff, error) {
304332
var finalErr error
305333

306334
if err := git.NewCommand(t.ctx, "diff-index", "--src-prefix=\\a/", "--dst-prefix=\\b/", "--cached", "-p", "HEAD").
307-
RunInDirTimeoutEnvFullPipelineFunc(nil, 30*time.Second, t.basePath, stdoutWriter, stderr, nil, func(ctx context.Context, cancel context.CancelFunc) error {
308-
_ = stdoutWriter.Close()
309-
diff, finalErr = gitdiff.ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "")
310-
if finalErr != nil {
311-
log.Error("ParsePatch: %v", finalErr)
312-
cancel()
313-
}
314-
_ = stdoutReader.Close()
315-
return finalErr
335+
RunWithContext(&git.RunContext{
336+
Timeout: 30 * time.Second,
337+
Dir: t.basePath,
338+
Stdout: stdoutWriter,
339+
Stderr: stderr,
340+
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
341+
_ = stdoutWriter.Close()
342+
diff, finalErr = gitdiff.ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "")
343+
if finalErr != nil {
344+
log.Error("ParsePatch: %v", finalErr)
345+
cancel()
346+
}
347+
_ = stdoutReader.Close()
348+
return finalErr
349+
},
316350
}); err != nil {
317351
if finalErr != nil {
318352
log.Error("Unable to ParsePatch in temporary repo %s (%s). Error: %v", t.repo.FullName(), t.basePath, finalErr)

0 commit comments

Comments
 (0)
Please sign in to comment.