diff --git a/integrations/api_repo_git_tags_test.go b/integrations/api_repo_git_tags_test.go index 6aa2f9f642c5f..e110f5e9d1566 100644 --- a/integrations/api_repo_git_tags_test.go +++ b/integrations/api_repo_git_tags_test.go @@ -28,8 +28,8 @@ func TestAPIGitTags(t *testing.T) { token := getTokenForLoggedInUser(t, session) // Set up git config for the tagger - git.NewCommand(git.DefaultContext, "config", "user.name", user.Name).RunInDir(repo.RepoPath()) - git.NewCommand(git.DefaultContext, "config", "user.email", user.Email).RunInDir(repo.RepoPath()) + git.NewCommand(git.DefaultContext, "config", "user.name", user.Name).RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1}) + git.NewCommand(git.DefaultContext, "config", "user.email", user.Email).RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1}) gitRepo, _ := git.OpenRepository(repo.RepoPath()) defer gitRepo.Close() diff --git a/integrations/git_helper_for_declarative_test.go b/integrations/git_helper_for_declarative_test.go index 674fad5f18bfe..c74434d6ded0b 100644 --- a/integrations/git_helper_for_declarative_test.go +++ b/integrations/git_helper_for_declarative_test.go @@ -134,7 +134,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) { // Init repository in dstPath assert.NoError(t, git.InitRepository(git.DefaultContext, dstPath, false)) // forcibly set default branch to master - _, err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) @@ -153,49 +153,49 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) { func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, "remote", "add", remoteName, u.String()).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, "remote", "add", remoteName, u.String()).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) } } func doGitPushTestRepository(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, append([]string{"push", "-u"}, args...)...).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, append([]string{"push", "-u"}, args...)...).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) } } func doGitPushTestRepositoryFail(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, append([]string{"push"}, args...)...).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, append([]string{"push"}, args...)...).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.Error(t, err) } } func doGitCreateBranch(dstPath, branch string) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, "checkout", "-b", branch).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, "checkout", "-b", branch).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) } } func doGitCheckoutBranch(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommandNoGlobals(append(append(git.AllowLFSFiltersArgs(), "checkout"), args...)...).RunInDir(dstPath) + err := git.NewCommandNoGlobals(append(append(git.AllowLFSFiltersArgs(), "checkout"), args...)...).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) } } func doGitMerge(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, append([]string{"merge"}, args...)...).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, append([]string{"merge"}, args...)...).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) } } func doGitPull(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { - _, err := git.NewCommandNoGlobals(append(append(git.AllowLFSFiltersArgs(), "pull"), args...)...).RunInDir(dstPath) + err := git.NewCommandNoGlobals(append(append(git.AllowLFSFiltersArgs(), "pull"), args...)...).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) } } diff --git a/integrations/git_test.go b/integrations/git_test.go index 675b1879fafc9..020f9e69f3d3f 100644 --- a/integrations/git_test.go +++ b/integrations/git_test.go @@ -160,9 +160,9 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin return } prefix := "lfs-data-file-" - _, err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("install").RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("install").RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) - _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("track", prefix+"*").RunInDir(dstPath) + err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("track", prefix+"*").RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) err = git.AddChanges(dstPath, false, ".gitattributes") assert.NoError(t, err) @@ -292,20 +292,20 @@ func lockTest(t *testing.T, repoPath string) { } func lockFileTest(t *testing.T, filename, repoPath string) { - _, err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunInDir(repoPath) + err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) assert.NoError(t, err) - _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("lock", filename).RunInDir(repoPath) + err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("lock", filename).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) assert.NoError(t, err) - _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunInDir(repoPath) + err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) assert.NoError(t, err) - _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("unlock", filename).RunInDir(repoPath) + err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("unlock", filename).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) assert.NoError(t, err) } func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string { name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix) assert.NoError(t, err) - _, err = git.NewCommand(git.DefaultContext, "push", "origin", "master").RunInDir(repoPath) // Push + err = git.NewCommand(git.DefaultContext, "push", "origin", "master").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) // Push assert.NoError(t, err) return name } @@ -671,7 +671,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB }) t.Run("Push", func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o", "topic="+headBranch).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o", "topic="+headBranch).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) if !assert.NoError(t, err) { return } @@ -692,7 +692,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB assert.Contains(t, "Testing commit 1", prMsg.Body) assert.Equal(t, commit, prMsg.Head.Sha) - _, err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath) + err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) if !assert.NoError(t, err) { return } @@ -745,7 +745,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB }) t.Run("Push2", func(t *testing.T) { - _, err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o", "topic="+headBranch).RunInDir(dstPath) + err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o", "topic="+headBranch).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) if !assert.NoError(t, err) { return } @@ -757,7 +757,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB assert.Equal(t, false, prMsg.HasMerged) assert.Equal(t, commit, prMsg.Head.Sha) - _, err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath) + err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) if !assert.NoError(t, err) { return } diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index 2e33d7095f050..8291f05931c74 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -269,7 +269,7 @@ func TestCantMergeUnrelated(t *testing.T) { }).(*repo_model.Repository) path := repo_model.RepoPath(user1.Name, repo1.Name) - _, err := git.NewCommand(git.DefaultContext, "read-tree", "--empty").RunInDir(path) + err := git.NewCommand(git.DefaultContext, "read-tree", "--empty").RunWithContext(&git.RunContext{Dir: path, Timeout: -1}) assert.NoError(t, err) stdin := bytes.NewBufferString("Unrelated File") @@ -284,12 +284,13 @@ func TestCantMergeUnrelated(t *testing.T) { assert.NoError(t, err) sha := strings.TrimSpace(stdout.String()) - _, err = git.NewCommand(git.DefaultContext, "update-index", "--add", "--replace", "--cacheinfo", "100644", sha, "somewher-over-the-rainbow").RunInDir(path) + err = git.NewCommand(git.DefaultContext, "update-index", "--add", "--replace", "--cacheinfo", "100644", sha, "somewher-over-the-rainbow").RunWithContext(&git.RunContext{Dir: path, Timeout: -1}) assert.NoError(t, err) - treeSha, err := git.NewCommand(git.DefaultContext, "write-tree").RunInDir(path) + stdoutTreeSha := new(strings.Builder) + err = git.NewCommand(git.DefaultContext, "write-tree").RunWithContext(&git.RunContext{Dir: path, Timeout: -1, Stdout: stdoutTreeSha}) assert.NoError(t, err) - treeSha = strings.TrimSpace(treeSha) + treeSha := strings.TrimSpace(stdoutTreeSha.String()) commitTimeStr := time.Now().Format(time.RFC3339) doerSig := user1.NewGitSig() @@ -318,7 +319,7 @@ func TestCantMergeUnrelated(t *testing.T) { assert.NoError(t, err) commitSha := strings.TrimSpace(stdout.String()) - _, err = git.NewCommand(git.DefaultContext, "branch", "unrelated", commitSha).RunInDir(path) + err = git.NewCommand(git.DefaultContext, "branch", "unrelated", commitSha).RunWithContext(&git.RunContext{Dir: path, Timeout: -1}) assert.NoError(t, err) testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") diff --git a/integrations/repo_tag_test.go b/integrations/repo_tag_test.go index 20bfc555b87d9..e9e13d0501b17 100644 --- a/integrations/repo_tag_test.go +++ b/integrations/repo_tag_test.go @@ -7,6 +7,7 @@ package integrations import ( "net/url" "os" + "strings" "testing" "code.gitea.io/gitea/models" @@ -66,12 +67,14 @@ func TestCreateNewTagProtected(t *testing.T) { doGitClone(dstPath, u)(t) - _, err = git.NewCommand(git.DefaultContext, "tag", "v-2").RunInDir(dstPath) + err = git.NewCommand(git.DefaultContext, "tag", "v-2").RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1}) assert.NoError(t, err) - _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunInDir(dstPath) - assert.Error(t, err) - assert.Contains(t, err.Error(), "Tag v-2 is protected") + stderr := new(strings.Builder) + err = git.NewCommand(git.DefaultContext, "push", "--tags").RunWithContext(&git.RunContext{Dir: dstPath, Timeout: -1, Stderr: stderr}) + if assert.Error(t, err) { + assert.Contains(t, stderr.String(), "Tag v-2 is protected") + } }) }) diff --git a/models/migrations/v128.go b/models/migrations/v128.go index 1454088c89a74..f522b196e8ab6 100644 --- a/models/migrations/v128.go +++ b/models/migrations/v128.go @@ -80,20 +80,23 @@ func fixMergeBase(x *xorm.Engine) error { repoPath := filepath.Join(userPath, strings.ToLower(baseRepo.Name)+".git") gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index) + stdout := new(strings.Builder) if !pr.HasMerged { - var err error - pr.MergeBase, err = git.NewCommand(git.DefaultContext, "merge-base", "--", pr.BaseBranch, gitRefName).RunInDir(repoPath) + err := git.NewCommand(git.DefaultContext, "merge-base", "--", pr.BaseBranch, gitRefName).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err != nil { - var err2 error - pr.MergeBase, err2 = git.NewCommand(git.DefaultContext, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath) + stdout.Reset() + err2 := git.NewCommand(git.DefaultContext, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err2 != nil { log.Error("Unable to get merge base for PR ID %d, Index %d in %s/%s. Error: %v & %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err, err2) continue } } } else { - parentsString, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath) + err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + parentsString := stdout.String() if err != nil { log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err) continue @@ -106,7 +109,9 @@ func fixMergeBase(x *xorm.Engine) error { args := append([]string{"merge-base", "--"}, parents[1:]...) args = append(args, gitRefName) - pr.MergeBase, err = git.NewCommand(git.DefaultContext, args...).RunInDir(repoPath) + stdout.Reset() + err = git.NewCommand(git.DefaultContext, args...).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err != nil { log.Error("Unable to get merge base for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err) continue diff --git a/models/migrations/v134.go b/models/migrations/v134.go index 3a8fd96b7c0f7..b0822fa87b973 100644 --- a/models/migrations/v134.go +++ b/models/migrations/v134.go @@ -80,7 +80,9 @@ func refixMergeBase(x *xorm.Engine) error { gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index) - parentsString, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath) + stdout := new(strings.Builder) + err = git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + parentsString := stdout.String() if err != nil { log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err) continue @@ -94,7 +96,9 @@ func refixMergeBase(x *xorm.Engine) error { args := append([]string{"merge-base", "--"}, parents[1:]...) args = append(args, gitRefName) - pr.MergeBase, err = git.NewCommand(git.DefaultContext, args...).RunInDir(repoPath) + stdout.Reset() + err = git.NewCommand(git.DefaultContext, args...).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err != nil { log.Error("Unable to get merge base for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err) continue diff --git a/modules/doctor/mergebase.go b/modules/doctor/mergebase.go index 5a780ed2a215d..a2840b5289daf 100644 --- a/modules/doctor/mergebase.go +++ b/modules/doctor/mergebase.go @@ -41,20 +41,23 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro repoPath := repo.RepoPath() oldMergeBase := pr.MergeBase + stdout := new(strings.Builder) if !pr.HasMerged { - var err error - pr.MergeBase, err = git.NewCommand(ctx, "merge-base", "--", pr.BaseBranch, pr.GetGitRefName()).RunInDir(repoPath) + err := git.NewCommand(ctx, "merge-base", "--", pr.BaseBranch, pr.GetGitRefName()).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err != nil { - var err2 error - pr.MergeBase, err2 = git.NewCommand(ctx, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath) + stdout.Reset() + err2 := git.NewCommand(ctx, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err2 != nil { logger.Warn("Unable to get merge base for PR ID %d, #%d onto %s in %s/%s. Error: %v & %v", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err, err2) return nil } } } else { - parentsString, err := git.NewCommand(ctx, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath) + err := git.NewCommand(ctx, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + parentsString := stdout.String() if err != nil { logger.Warn("Unable to get parents for merged PR ID %d, #%d onto %s in %s/%s. Error: %v", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err) return nil @@ -67,7 +70,9 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro args := append([]string{"merge-base", "--"}, parents[1:]...) args = append(args, pr.GetGitRefName()) - pr.MergeBase, err = git.NewCommand(ctx, args...).RunInDir(repoPath) + stdout.Reset() + err = git.NewCommand(ctx, args...).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err != nil { logger.Warn("Unable to get merge base for merged PR ID %d, #%d onto %s in %s/%s. Error: %v", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err) return nil diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index e96890fbab4d8..c7aee18743e50 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -95,11 +95,13 @@ func checkEnablePushOptions(ctx context.Context, logger log.Logger, autofix bool defer r.Close() if autofix { - _, err := git.NewCommand(ctx, "config", "receive.advertisePushOptions", "true").RunInDir(r.Path) + err := git.NewCommand(ctx, "config", "receive.advertisePushOptions", "true").RunWithContext(&git.RunContext{Dir: r.Path, Timeout: -1}) return err } - value, err := git.NewCommand(ctx, "config", "receive.advertisePushOptions").RunInDir(r.Path) + stdout := new(strings.Builder) + err = git.NewCommand(ctx, "config", "receive.advertisePushOptions").RunWithContext(&git.RunContext{Dir: r.Path, Timeout: -1, Stdout: stdout}) + value := stdout.String() if err != nil { return err } diff --git a/modules/git/command.go b/modules/git/command.go index 8199498a2b2b8..b8010d696b458 100644 --- a/modules/git/command.go +++ b/modules/git/command.go @@ -239,30 +239,12 @@ func (c *Command) RunInDirTimeoutEnv(env []string, timeout time.Duration, dir st return stdout.Bytes(), nil } -// RunInDirPipeline executes the command in given directory, -// it pipes stdout and stderr to given io.Writer. -func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error { - return c.RunInDirFullPipeline(dir, stdout, stderr, nil) -} - -// RunInDirFullPipeline executes the command in given directory, -// it pipes stdout and stderr to given io.Writer. -func (c *Command) RunInDirFullPipeline(dir string, stdout, stderr io.Writer, stdin io.Reader) error { - return c.RunInDirTimeoutFullPipeline(-1, dir, stdout, stderr, stdin) -} - // RunInDirBytes executes the command in given directory // and returns stdout in []byte and error (combined with stderr). func (c *Command) RunInDirBytes(dir string) ([]byte, error) { return c.RunInDirTimeout(-1, dir) } -// RunInDir executes the command in given directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunInDir(dir string) (string, error) { - return c.RunInDirWithEnv(dir, nil) -} - // RunInDirWithEnv executes the command in given directory // and returns stdout in string and error (combined with stderr). func (c *Command) RunInDirWithEnv(dir string, env []string) (string, error) { diff --git a/modules/git/commit.go b/modules/git/commit.go index 340a7e21dd643..5af6930630000 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -94,7 +94,7 @@ func AddChangesWithArgs(repoPath string, globalArgs []string, all bool, files .. cmd.AddArguments("--all") } cmd.AddArguments("--") - _, err := cmd.AddArguments(files...).RunInDir(repoPath) + err := cmd.AddArguments(files...).RunWithContext(&RunContext{Dir: repoPath, Timeout: -1}) return err } @@ -130,7 +130,7 @@ func CommitChangesWithArgs(repoPath string, args []string, opts CommitChangesOpt } cmd.AddArguments("-m", opts.Message) - _, err := cmd.RunInDir(repoPath) + err := cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1}) // No stderr but exit status 1 means nothing to commit. if err != nil && err.Error() == "exit status 1" { return nil @@ -151,12 +151,13 @@ func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, file cmd.AddArguments(files...) } - stdout, err := cmd.RunInDir(repoPath) + stdout := new(strings.Builder) + err := cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) if err != nil { return 0, err } - return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) + return strconv.ParseInt(strings.TrimSpace(stdout.String()), 10, 64) } // CommitsCountFiles returns number of total commits of until given revision. @@ -168,12 +169,13 @@ func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath [ cmd.AddArguments(relpath...) } - stdout, err := cmd.RunInDir(repoPath) + stdout := new(strings.Builder) + err := cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) if err != nil { return 0, err } - return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) + return strconv.ParseInt(strings.TrimSpace(stdout.String()), 10, 64) } // CommitsCount returns number of total commits of until given revision. @@ -206,7 +208,7 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) { } if err := CheckGitVersionAtLeast("1.8"); err == nil { - _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunInDir(c.repo.Path) + err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunWithContext(&RunContext{Dir: c.repo.Path, Timeout: -1}) if err == nil { return true, nil } @@ -219,7 +221,9 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) { return false, err } - result, err := NewCommand(c.repo.Ctx, "rev-list", "--ancestry-path", "-n1", that+".."+this, "--").RunInDir(c.repo.Path) + stdout := new(strings.Builder) + err := NewCommand(c.repo.Ctx, "rev-list", "--ancestry-path", "-n1", that+".."+this, "--").RunWithContext(&RunContext{Dir: c.repo.Path, Timeout: -1, Stdout: stdout}) + result := stdout.String() if err != nil { return false, err } @@ -381,7 +385,9 @@ func (c *Commit) GetBranchName() (string, error) { } args = append(args, "--name-only", "--no-undefined", c.ID.String()) - data, err := NewCommand(c.repo.Ctx, args...).RunInDir(c.repo.Path) + stdout := new(strings.Builder) + err = NewCommand(c.repo.Ctx, args...).RunWithContext(&RunContext{Dir: c.repo.Path, Timeout: -1, Stdout: stdout}) + data := stdout.String() if err != nil { // handle special case where git can not describe commit if strings.Contains(err.Error(), "cannot describe") { @@ -407,7 +413,9 @@ func (c *Commit) LoadBranchName() (err error) { // GetTagName gets the current tag name for given commit func (c *Commit) GetTagName() (string, error) { - data, err := NewCommand(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always", c.ID.String()).RunInDir(c.repo.Path) + stdout := new(strings.Builder) + err := NewCommand(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always", c.ID.String()).RunWithContext(&RunContext{Dir: c.repo.Path, Timeout: -1, Stdout: stdout}) + data := stdout.String() if err != nil { // handle special case where there is no tag for this commit if strings.Contains(err.Error(), "no tag exactly matches") { @@ -503,7 +511,9 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository. func GetFullCommitID(ctx context.Context, repoPath, shortID string) (string, error) { - commitID, err := NewCommand(ctx, "rev-parse", shortID).RunInDir(repoPath) + stdout := new(strings.Builder) + err := NewCommand(ctx, "rev-parse", shortID).RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + commitID := stdout.String() if err != nil { if strings.Contains(err.Error(), "exit status 128") { return "", ErrNotExist{shortID, ""} diff --git a/modules/git/remote.go b/modules/git/remote.go index dfd0686d8befd..50d0e5790a32c 100644 --- a/modules/git/remote.go +++ b/modules/git/remote.go @@ -7,6 +7,7 @@ package git import ( "context" "net/url" + "strings" ) // GetRemoteAddress returns the url of a specific remote of the repository. @@ -22,7 +23,9 @@ func GetRemoteAddress(ctx context.Context, repoPath, remoteName string) (*url.UR cmd = NewCommand(ctx, "config", "--get", "remote."+remoteName+".url") } - result, err := cmd.RunInDir(repoPath) + stdout := new(strings.Builder) + err = cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + result := stdout.String() if err != nil { return nil, err } diff --git a/modules/git/repo.go b/modules/git/repo.go index b886d5ed45a86..888cca465bd48 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -74,7 +74,7 @@ func InitRepository(ctx context.Context, repoPath string, bare bool) error { if bare { cmd.AddArguments("--bare") } - _, err = cmd.RunInDir(repoPath) + err = cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1}) return err } @@ -261,11 +261,12 @@ func Push(ctx context.Context, repoPath string, opts PushOptions) error { // GetLatestCommitTime returns time for latest commit in repository (across all branches) func GetLatestCommitTime(ctx context.Context, repoPath string) (time.Time, error) { cmd := NewCommand(ctx, "for-each-ref", "--sort=-committerdate", BranchPrefix, "--count", "1", "--format=%(committerdate)") - stdout, err := cmd.RunInDir(repoPath) + stdout := new(strings.Builder) + err := cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) if err != nil { return time.Time{}, err } - commitTime := strings.TrimSpace(stdout) + commitTime := strings.TrimSpace(stdout.String()) return time.Parse(GitTimeLayout, commitTime) } @@ -278,11 +279,12 @@ type DivergeObject struct { func checkDivergence(ctx context.Context, repoPath, baseBranch, targetBranch string) (int, error) { branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) cmd := NewCommand(ctx, "rev-list", "--count", branches) - stdout, err := cmd.RunInDir(repoPath) + stdout := new(strings.Builder) + err := cmd.RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) if err != nil { return -1, err } - outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n")) + outInteger, errInteger := strconv.Atoi(strings.Trim(stdout.String(), "\n")) if errInteger != nil { return -1, errInteger } diff --git a/modules/git/repo_blame.go b/modules/git/repo_blame.go index a71122527f29e..b33c712fab8fa 100644 --- a/modules/git/repo_blame.go +++ b/modules/git/repo_blame.go @@ -4,7 +4,10 @@ package git -import "fmt" +import ( + "fmt" + "strings" +) // FileBlame return the Blame object of file func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { @@ -13,7 +16,9 @@ func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { // LineBlame returns the latest commit at the given line func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { - res, err := NewCommand(repo.Ctx, "blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunWithContext(&RunContext{Dir: path, Timeout: -1, Stdout: stdout}) + res := stdout.String() if err != nil { return nil, err } diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go index d9a7a4777176a..1d021f00f4f47 100644 --- a/modules/git/repo_branch.go +++ b/modules/git/repo_branch.go @@ -24,7 +24,7 @@ const PullRequestPrefix = "refs/for/" // IsReferenceExist returns true if given reference exists in the repository. func IsReferenceExist(ctx context.Context, repoPath, name string) bool { - _, err := NewCommand(ctx, "show-ref", "--verify", "--", name).RunInDir(repoPath) + err := NewCommand(ctx, "show-ref", "--verify", "--", name).RunWithContext(&RunContext{Dir: repoPath, Timeout: -1}) return err == nil } @@ -46,32 +46,35 @@ func (repo *Repository) GetHEADBranch() (*Branch, error) { if repo == nil { return nil, fmt.Errorf("nil repo") } - stdout, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return nil, err } - stdout = strings.TrimSpace(stdout) + stdoutS := strings.TrimSpace(stdout.String()) - if !strings.HasPrefix(stdout, BranchPrefix) { + if !strings.HasPrefix(stdoutS, BranchPrefix) { return nil, fmt.Errorf("invalid HEAD branch: %v", stdout) } return &Branch{ - Name: stdout[len(BranchPrefix):], - Path: stdout, + Name: stdoutS[len(BranchPrefix):], + Path: stdoutS, gitRepo: repo, }, nil } // SetDefaultBranch sets default branch of repository. func (repo *Repository) SetDefaultBranch(name string) error { - _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD", BranchPrefix+name).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } // GetDefaultBranch gets default branch of repository. func (repo *Repository) GetDefaultBranch() (string, error) { - return NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + return stdout.String(), err } // GetBranch returns a branch by it's name @@ -133,7 +136,7 @@ func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) erro } cmd.AddArguments("--", name) - _, err := cmd.RunInDir(repo.Path) + err := cmd.RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } @@ -143,7 +146,7 @@ func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error { cmd := NewCommand(repo.Ctx, "branch") cmd.AddArguments("--", branch, oldbranchOrCommit) - _, err := cmd.RunInDir(repo.Path) + err := cmd.RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } @@ -156,13 +159,13 @@ func (repo *Repository) AddRemote(name, url string, fetch bool) error { } cmd.AddArguments(name, url) - _, err := cmd.RunInDir(repo.Path) + err := cmd.RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } // RemoveRemote removes a remote from repository. func (repo *Repository) RemoveRemote(name string) error { - _, err := NewCommand(repo.Ctx, "remote", "rm", name).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "remote", "rm", name).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } @@ -173,6 +176,6 @@ func (branch *Branch) GetCommit() (*Commit, error) { // RenameBranch rename a branch func (repo *Repository) RenameBranch(from, to string) error { - _, err := NewCommand(repo.Ctx, "branch", "-m", from, to).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "branch", "-m", from, to).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index 8e059ce0ea252..23f3838279386 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -58,12 +58,13 @@ func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, relpath = `\` + relpath } - stdout, err := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, id.String(), "--", relpath).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return nil, err } - id, err = NewIDFromString(stdout) + id, err = NewIDFromString(stdout.String()) if err != nil { return nil, err } @@ -254,16 +255,18 @@ func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, pag // FilesCountBetween return the number of files changed between two commits func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { - stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "diff", "--name-only", startCommitID+"..."+endCommitID).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil && strings.Contains(err.Error(), "no merge base") { // git >= 2.28 now returns an error if startCommitID and endCommitID have become unrelated. // previously it would return the results of git diff --name-only startCommitID endCommitID so let's try that... - stdout, err = NewCommand(repo.Ctx, "diff", "--name-only", startCommitID, endCommitID).RunInDir(repo.Path) + stdout.Reset() + err = NewCommand(repo.Ctx, "diff", "--name-only", startCommitID, endCommitID).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) } if err != nil { return 0, err } - return len(strings.Split(stdout, "\n")) - 1, nil + return len(strings.Split(stdout.String(), "\n")) - 1, nil } // CommitsBetween returns a list that contains commits between [before, last). @@ -380,22 +383,24 @@ func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) ([]*Commit, erro } func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { + stdout := new(strings.Builder) if CheckGitVersionAtLeast("2.7.0") == nil { - stdout, err := NewCommand(repo.Ctx, "for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return nil, err } - branches := strings.Fields(stdout) + branches := strings.Fields(stdout.String()) return branches, nil } - stdout, err := NewCommand(repo.Ctx, "branch", "--contains", commit.ID.String()).RunInDir(repo.Path) + stdout.Reset() + err := NewCommand(repo.Ctx, "branch", "--contains", commit.ID.String()).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return nil, err } - refs := strings.Split(stdout, "\n") + refs := strings.Split(stdout.String(), "\n") var max int if len(refs) > limit { @@ -429,9 +434,10 @@ func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit { // IsCommitInBranch check if the commit is on the branch func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) { - stdout, err := NewCommand(repo.Ctx, "branch", "--contains", commitID, branch).RunInDir(repo.Path) + stdout := new(strings.Builder) + err = NewCommand(repo.Ctx, "branch", "--contains", commitID, branch).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return false, err } - return len(stdout) > 0, err + return len(stdout.String()) > 0, err } diff --git a/modules/git/repo_commit_gogit.go b/modules/git/repo_commit_gogit.go index 3693f7883fbbb..5c51295f2d341 100644 --- a/modules/git/repo_commit_gogit.go +++ b/modules/git/repo_commit_gogit.go @@ -50,7 +50,9 @@ func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) { } } - actualCommitID, err := NewCommand(repo.Ctx, "rev-parse", "--verify", commitID).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "rev-parse", "--verify", commitID).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + actualCommitID := stdout.String() if err != nil { if strings.Contains(err.Error(), "unknown revision or path") || strings.Contains(err.Error(), "fatal: Needed a single revision") { diff --git a/modules/git/repo_commit_nogogit.go b/modules/git/repo_commit_nogogit.go index b65565c98c979..bc2ae8fa7f036 100644 --- a/modules/git/repo_commit_nogogit.go +++ b/modules/git/repo_commit_nogogit.go @@ -18,19 +18,20 @@ import ( // ResolveReference resolves a name to a reference func (repo *Repository) ResolveReference(name string) (string, error) { - stdout, err := NewCommand(repo.Ctx, "show-ref", "--hash", name).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "show-ref", "--hash", name).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { if strings.Contains(err.Error(), "not a valid ref") { return "", ErrNotExist{name, ""} } return "", err } - stdout = strings.TrimSpace(stdout) - if stdout == "" { + stdoutS := strings.TrimSpace(stdout.String()) + if stdoutS == "" { return "", ErrNotExist{name, ""} } - return stdout, nil + return stdoutS, nil } // GetRefCommitID returns the last commit ID string of given reference (branch or tag). @@ -51,19 +52,19 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) { // SetReference sets the commit ID string of given reference (e.g. branch or tag). func (repo *Repository) SetReference(name, commitID string) error { - _, err := NewCommand(repo.Ctx, "update-ref", name, commitID).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "update-ref", name, commitID).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } // RemoveReference removes the given reference (e.g. branch or tag). func (repo *Repository) RemoveReference(name string) error { - _, err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d", name).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d", name).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } // IsCommitExist returns true if given commit exists in current repository. func (repo *Repository) IsCommitExist(name string) bool { - _, err := NewCommand(repo.Ctx, "cat-file", "-e", name).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "cat-file", "-e", name).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err == nil } diff --git a/modules/git/repo_compare.go b/modules/git/repo_compare.go index aa8015af14e50..b7dbc691cda38 100644 --- a/modules/git/repo_compare.go +++ b/modules/git/repo_compare.go @@ -40,14 +40,15 @@ func (repo *Repository) GetMergeBase(tmpRemote, base, head string) (string, stri if tmpRemote != "origin" { tmpBaseName := RemotePrefix + tmpRemote + "/tmp_" + base // Fetch commit into a temporary branch in order to be able to handle commits and tags - _, err := NewCommand(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) if err == nil { base = tmpBaseName } } - stdout, err := NewCommand(repo.Ctx, "merge-base", "--", base, head).RunInDir(repo.Path) - return strings.TrimSpace(stdout), base, err + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "merge-base", "--", base, head).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + return strings.TrimSpace(stdout.String()), base, err } // GetCompareInfo generates and returns compare information between base and head branches of repositories. @@ -192,12 +193,13 @@ func GetDiffShortStat(ctx context.Context, repoPath string, args ...string) (num "--shortstat", }, args...) - stdout, err := NewCommand(ctx, args...).RunInDir(repoPath) + stdout := new(strings.Builder) + err = NewCommand(ctx, args...).RunWithContext(&RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) if err != nil { return 0, 0, 0, err } - return parseDiffStat(stdout) + return parseDiffStat(stdout.String()) } var shortStatFormat = regexp.MustCompile( diff --git a/modules/git/repo_gpg.go b/modules/git/repo_gpg.go index 14eb894be626f..ba59b460e7015 100644 --- a/modules/git/repo_gpg.go +++ b/modules/git/repo_gpg.go @@ -34,22 +34,26 @@ func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, Sign: true, } - value, _ := NewCommand(repo.Ctx, "config", "--get", "commit.gpgsign").RunInDir(repo.Path) - sign, valid := ParseBool(strings.TrimSpace(value)) + stdout := new(strings.Builder) + _ = NewCommand(repo.Ctx, "config", "--get", "commit.gpgsign").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + sign, valid := ParseBool(strings.TrimSpace(stdout.String())) if !sign || !valid { gpgSettings.Sign = false repo.gpgSettings = gpgSettings return gpgSettings, nil } - signingKey, _ := NewCommand(repo.Ctx, "config", "--get", "user.signingkey").RunInDir(repo.Path) - gpgSettings.KeyID = strings.TrimSpace(signingKey) + stdout.Reset() + _ = NewCommand(repo.Ctx, "config", "--get", "user.signingkey").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + gpgSettings.KeyID = strings.TrimSpace(stdout.String()) - defaultEmail, _ := NewCommand(repo.Ctx, "config", "--get", "user.email").RunInDir(repo.Path) - gpgSettings.Email = strings.TrimSpace(defaultEmail) + stdout.Reset() + _ = NewCommand(repo.Ctx, "config", "--get", "user.email").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + gpgSettings.Email = strings.TrimSpace(stdout.String()) - defaultName, _ := NewCommand(repo.Ctx, "config", "--get", "user.name").RunInDir(repo.Path) - gpgSettings.Name = strings.TrimSpace(defaultName) + stdout.Reset() + _ = NewCommand(repo.Ctx, "config", "--get", "user.name").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + gpgSettings.Name = strings.TrimSpace(stdout.String()) if err := gpgSettings.LoadPublicKeyContent(); err != nil { return nil, err diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index 53de0f1cb8ec1..764954ba3d660 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -18,7 +18,9 @@ import ( // ReadTreeToIndex reads a treeish to the index func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error { if len(treeish) != 40 { - res, err := NewCommand(repo.Ctx, "rev-parse", "--verify", treeish).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "rev-parse", "--verify", treeish).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + res := stdout.String() if err != nil { return err } @@ -69,7 +71,7 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename, tmpD // EmptyIndex empties the index func (repo *Repository) EmptyIndex() error { - _, err := NewCommand(repo.Ctx, "read-tree", "--empty").RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "read-tree", "--empty").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } @@ -118,13 +120,15 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error { // AddObjectToIndex adds the provided object hash to the index at the provided filename func (repo *Repository) AddObjectToIndex(mode string, object SHA1, filename string) error { cmd := NewCommand(repo.Ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, object.String(), filename) - _, err := cmd.RunInDir(repo.Path) + err := cmd.RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } // WriteTree writes the current index as a tree to the object db and returns its hash func (repo *Repository) WriteTree() (*Tree, error) { - res, err := NewCommand(repo.Ctx, "write-tree").RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "write-tree").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + res := stdout.String() if err != nil { return nil, err } diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index afeb7f5df8a37..e881f04e42227 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -6,6 +6,7 @@ package git import ( + "bytes" "context" "fmt" "strings" @@ -24,13 +25,13 @@ func IsTagExist(ctx context.Context, repoPath, name string) bool { // CreateTag create one tag in the repository func (repo *Repository) CreateTag(name, revision string) error { - _, err := NewCommand(repo.Ctx, "tag", "--", name, revision).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "tag", "--", name, revision).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } // CreateAnnotatedTag create one annotated tag in the repository func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error { - _, err := NewCommand(repo.Ctx, "tag", "-a", "-m", message, "--", name, revision).RunInDir(repo.Path) + err := NewCommand(repo.Ctx, "tag", "-a", "-m", message, "--", name, revision).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1}) return err } @@ -103,12 +104,13 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) { return "", fmt.Errorf("SHA is too short: %s", sha) } - stdout, err := NewCommand(repo.Ctx, "show-ref", "--tags", "-d").RunInDir(repo.Path) + stdout := new(bytes.Buffer) + err := NewCommand(repo.Ctx, "show-ref", "--tags", "-d").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return "", err } - tagRefs := strings.Split(stdout, "\n") + tagRefs := strings.Split(stdout.String(), "\n") for _, tagRef := range tagRefs { if len(strings.TrimSpace(tagRef)) > 0 { fields := strings.Fields(tagRef) @@ -126,12 +128,13 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) { // GetTagID returns the object ID for a tag (annotated tags have both an object SHA AND a commit SHA) func (repo *Repository) GetTagID(name string) (string, error) { - stdout, err := NewCommand(repo.Ctx, "show-ref", "--tags", "--", name).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "show-ref", "--tags", "--", name).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return "", err } // Make sure exact match is used: "v1" != "release/v1" - for _, line := range strings.Split(stdout, "\n") { + for _, line := range strings.Split(stdout.String(), "\n") { fields := strings.Fields(line) if len(fields) == 2 && fields[1] == "refs/tags/"+name { return fields[0], nil @@ -162,12 +165,13 @@ func (repo *Repository) GetTag(name string) (*Tag, error) { // GetTagInfos returns all tag infos of the repository. func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { // TODO this a slow implementation, makes one git command per tag - stdout, err := NewCommand(repo.Ctx, "tag").RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "tag").RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return nil, 0, err } - tagNames := strings.Split(strings.TrimRight(stdout, "\n"), "\n") + tagNames := strings.Split(strings.TrimRight(stdout.String(), "\n"), "\n") tagsTotal := len(tagNames) if page != 0 { @@ -195,14 +199,15 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { // GetTagType gets the type of the tag, either commit (simple) or tag (annotated) func (repo *Repository) GetTagType(id SHA1) (string, error) { // Get tag type - stdout, err := NewCommand(repo.Ctx, "cat-file", "-t", id.String()).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "cat-file", "-t", id.String()).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) if err != nil { return "", err } - if len(stdout) == 0 { + if len(stdout.String()) == 0 { return "", ErrNotExist{ID: id.String()} } - return strings.TrimSpace(stdout), nil + return strings.TrimSpace(stdout.String()), nil } // GetAnnotatedTag returns a Git tag by its SHA, must be an annotated tag diff --git a/modules/git/repo_tree_gogit.go b/modules/git/repo_tree_gogit.go index 0089d2c9a4f25..73776fcdb2fba 100644 --- a/modules/git/repo_tree_gogit.go +++ b/modules/git/repo_tree_gogit.go @@ -8,6 +8,8 @@ package git +import "strings" + func (repo *Repository) getTree(id SHA1) (*Tree, error) { gogitTree, err := repo.gogitRepo.TreeObject(id) if err != nil { @@ -22,7 +24,9 @@ func (repo *Repository) getTree(id SHA1) (*Tree, error) { // GetTree find the tree object in the repository. func (repo *Repository) GetTree(idStr string) (*Tree, error) { if len(idStr) != 40 { - res, err := NewCommand(repo.Ctx, "rev-parse", "--verify", idStr).RunInDir(repo.Path) + stdout := new(strings.Builder) + err := NewCommand(repo.Ctx, "rev-parse", "--verify", idStr).RunWithContext(&RunContext{Dir: repo.Path, Timeout: -1, Stdout: stdout}) + res := stdout.String() if err != nil { return nil, err } diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 309b33bedf1f7..19f039ef9b35c 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -192,12 +192,13 @@ func (b *BleveIndexer) addUpdate(ctx context.Context, batchWriter git.WriteClose size := update.Size if !update.Sized { - stdout, err := git.NewCommand(ctx, "cat-file", "-s", update.BlobSha). - RunInDir(repo.RepoPath()) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "cat-file", "-s", update.BlobSha). + RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1, Stdout: stdout}) if err != nil { return err } - if size, err = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64); err != nil { + if size, err = strconv.ParseInt(strings.TrimSpace(stdout.String()), 10, 64); err != nil { return fmt.Errorf("Misformatted git cat-file output: %v", err) } } diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index dd6ba19995cae..257d51c6f4d86 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -222,12 +222,13 @@ func (b *ElasticSearchIndexer) addUpdate(ctx context.Context, batchWriter git.Wr size := update.Size if !update.Sized { - stdout, err := git.NewCommand(ctx, "cat-file", "-s", update.BlobSha). - RunInDir(repo.RepoPath()) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "cat-file", "-s", update.BlobSha). + RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1, Stdout: stdout}) if err != nil { return nil, err } - if size, err = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64); err != nil { + if size, err = strconv.ParseInt(strings.TrimSpace(stdout.String()), 10, 64); err != nil { return nil, fmt.Errorf("misformatted git cat-file output: %v", err) } } diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 62444f6251dd0..09b1e379c1503 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -29,11 +29,12 @@ type repoChanges struct { } func getDefaultBranchSha(ctx context.Context, repo *repo_model.Repository) (string, error) { - stdout, err := git.NewCommand(ctx, "show-ref", "-s", git.BranchPrefix+repo.DefaultBranch).RunInDir(repo.RepoPath()) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "show-ref", "-s", git.BranchPrefix+repo.DefaultBranch).RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1, Stdout: stdout}) if err != nil { return "", err } - return strings.TrimSpace(stdout), nil + return strings.TrimSpace(stdout.String()), nil } // getRepoChanges returns changes to repo since last indexer update @@ -103,9 +104,10 @@ func genesisChanges(ctx context.Context, repo *repo_model.Repository, revision s // nonGenesisChanges get changes since the previous indexer update func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) { + stdout := new(strings.Builder) diffCmd := git.NewCommand(ctx, "diff", "--name-status", repo.CodeIndexerStatus.CommitSha, revision) - stdout, err := diffCmd.RunInDir(repo.RepoPath()) + err := diffCmd.RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1, Stdout: stdout}) if err != nil { // previous commit sha may have been removed by a force push, so // try rebuilding from scratch @@ -117,7 +119,7 @@ func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revisio } var changes repoChanges updatedFilenames := make([]string, 0, 10) - for _, line := range strings.Split(stdout, "\n") { + for _, line := range strings.Split(stdout.String(), "\n") { line = strings.TrimSpace(line) if len(line) == 0 { continue diff --git a/modules/repository/create.go b/modules/repository/create.go index 6409cc55ce4f9..a008ddb6c20e7 100644 --- a/modules/repository/create.go +++ b/modules/repository/create.go @@ -111,10 +111,11 @@ func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) ( return fmt.Errorf("checkDaemonExportOK: %v", err) } - if stdout, err := git.NewCommand(ctx, "update-server-info"). + stdout := new(strings.Builder) + if err := git.NewCommand(ctx, "update-server-info"). SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)). - RunInDir(repoPath); err != nil { - log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err) + RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}); err != nil { + log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout.String(), err) rollbackRepo = repo rollbackRepo.OwnerID = u.ID return fmt.Errorf("CreateRepository(git update-server-info): %v", err) diff --git a/modules/repository/generate.go b/modules/repository/generate.go index cf219f4c26b73..3fb7244ff22d8 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -292,10 +292,11 @@ func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templ return generateRepo, fmt.Errorf("checkDaemonExportOK: %v", err) } - if stdout, err := git.NewCommand(ctx, "update-server-info"). + stdout := new(strings.Builder) + if err := git.NewCommand(ctx, "update-server-info"). SetDescription(fmt.Sprintf("GenerateRepository(git update-server-info): %s", repoPath)). - RunInDir(repoPath); err != nil { - log.Error("GenerateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", generateRepo, stdout, err) + RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}); err != nil { + log.Error("GenerateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", generateRepo, stdout.String(), err) return generateRepo, fmt.Errorf("error in GenerateRepository(git update-server-info): %v", err) } diff --git a/modules/repository/init.go b/modules/repository/init.go index 66d464ef137e3..366db0a42e07e 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -117,10 +117,11 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi committerName := sig.Name committerEmail := sig.Email - if stdout, err := git.NewCommand(ctx, "add", "--all"). + stdout := new(strings.Builder) + if err := git.NewCommand(ctx, "add", "--all"). SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)). - RunInDir(tmpPath); err != nil { - log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err) + RunWithContext(&git.RunContext{Dir: tmpPath, Timeout: -1, Stdout: stdout}); err != nil { + log.Error("git add --all failed: Stdout: %s\nError: %v", stdout.String(), err) return fmt.Errorf("git add --all: %v", err) } diff --git a/modules/repository/push.go b/modules/repository/push.go index aa94a3e2429e2..210629e143d18 100644 --- a/modules/repository/push.go +++ b/modules/repository/push.go @@ -104,11 +104,12 @@ func IsForcePush(ctx context.Context, opts *PushUpdateOptions) (bool, error) { return false, nil } - output, err := git.NewCommand(ctx, "rev-list", "--max-count=1", opts.OldCommitID, "^"+opts.NewCommitID). - RunInDir(repo_model.RepoPath(opts.RepoUserName, opts.RepoName)) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "rev-list", "--max-count=1", opts.OldCommitID, "^"+opts.NewCommitID). + RunWithContext(&git.RunContext{Dir: repo_model.RepoPath(opts.RepoUserName, opts.RepoName), Timeout: -1, Stdout: stdout}) if err != nil { return false, err - } else if len(output) > 0 { + } else if len(stdout.String()) > 0 { return true, nil } return false, nil diff --git a/modules/repository/repo.go b/modules/repository/repo.go index 98388bbd7b2ef..ddc5c631f4d4a 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -111,11 +111,13 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, return repo, fmt.Errorf("checkDaemonExportOK: %v", err) } - if stdout, err := git.NewCommand(ctx, "update-server-info"). + stdout := new(strings.Builder) + stderr := new(strings.Builder) + if err := git.NewCommand(ctx, "update-server-info"). SetDescription(fmt.Sprintf("MigrateRepositoryGitData(git update-server-info): %s", repoPath)). - RunInDir(repoPath); err != nil { - log.Error("MigrateRepositoryGitData(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err) - return repo, fmt.Errorf("error in MigrateRepositoryGitData(git update-server-info): %v", err) + RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout, Stderr: stderr}); err != nil { + log.Error("MigrateRepositoryGitData(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout.String(), stderr.String()) + return repo, fmt.Errorf("error in MigrateRepositoryGitData(git update-server-info): %v", stderr.String()) } gitRepo, err := git.OpenRepositoryCtx(ctx, repoPath) @@ -230,7 +232,7 @@ func CleanUpMigrateInfo(ctx context.Context, repo *repo_model.Repository) (*repo } } - _, err := git.NewCommand(ctx, "remote", "rm", "origin").RunInDir(repoPath) + err := git.NewCommand(ctx, "remote", "rm", "origin").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err) } diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index d149d4f89fa5e..b797e557f5ba3 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -397,11 +397,12 @@ func (h *serviceHandler) sendFile(contentType, file string) { var safeGitProtocolHeader = regexp.MustCompile(`^[0-9a-zA-Z]+=[0-9a-zA-Z]+(:[0-9a-zA-Z]+=[0-9a-zA-Z]+)*$`) func getGitConfig(ctx gocontext.Context, option, dir string) string { - out, err := git.NewCommand(ctx, "config", option).RunInDir(dir) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "config", option).RunWithContext(&git.RunContext{Dir: dir, Timeout: -1, Stdout: stdout}) if err != nil { - log.Error("%v - %s", err, out) + log.Error("%v - %s", err, stdout.String()) } - return out[0 : len(out)-1] + return stdout.String()[0 : len(stdout.String())-1] } func getConfigSetting(ctx gocontext.Context, service, dir string) bool { diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index a4edfd9ee42ef..2757285da8299 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -338,7 +338,9 @@ func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) *git.C } if commitSHA != "" { // Get immediate parent of the first commit in the patch, grab history back - parentCommit, err = git.NewCommand(ctx, "rev-list", "-1", "--skip=1", commitSHA).RunInDir(ctx.Repo.GitRepo.Path) + stdout := new(strings.Builder) + err = git.NewCommand(ctx, "rev-list", "-1", "--skip=1", commitSHA).RunWithContext(&git.RunContext{Dir: ctx.Repo.GitRepo.Path, Timeout: -1, Stdout: stdout}) + parentCommit = stdout.String() if err == nil { parentCommit = strings.TrimSpace(parentCommit) } diff --git a/services/asymkey/sign.go b/services/asymkey/sign.go index fa0afe0a5723c..00a6094a06765 100644 --- a/services/asymkey/sign.go +++ b/services/asymkey/sign.go @@ -90,15 +90,26 @@ func SigningKey(ctx context.Context, repoPath string) (string, *git.Signature) { if setting.Repository.Signing.SigningKey == "default" || setting.Repository.Signing.SigningKey == "" { // Can ignore the error here as it means that commit.gpgsign is not set - value, _ := git.NewCommand(ctx, "config", "--get", "commit.gpgsign").RunInDir(repoPath) + stdout := new(strings.Builder) + _ = git.NewCommand(ctx, "config", "--get", "commit.gpgsign").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + value := stdout.String() sign, valid := git.ParseBool(strings.TrimSpace(value)) if !sign || !valid { return "", nil } - signingKey, _ := git.NewCommand(ctx, "config", "--get", "user.signingkey").RunInDir(repoPath) - signingName, _ := git.NewCommand(ctx, "config", "--get", "user.name").RunInDir(repoPath) - signingEmail, _ := git.NewCommand(ctx, "config", "--get", "user.email").RunInDir(repoPath) + stdout.Reset() + _ = git.NewCommand(ctx, "config", "--get", "user.signingkey").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + signingKey := stdout.String() + + stdout.Reset() + _ = git.NewCommand(ctx, "config", "--get", "user.name").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + signingName := stdout.String() + + stdout.Reset() + _ = git.NewCommand(ctx, "config", "--get", "user.email").RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}) + signingEmail := stdout.String() + return strings.TrimSpace(signingKey), &git.Signature{ Name: strings.TrimSpace(signingName), Email: strings.TrimSpace(signingEmail), diff --git a/services/migrations/dump.go b/services/migrations/dump.go index 594b78511ac4c..9efcecd6be1cd 100644 --- a/services/migrations/dump.go +++ b/services/migrations/dump.go @@ -479,7 +479,7 @@ func (g *RepositoryDumper) CreatePullRequests(prs ...*base.PullRequest) error { } if ok { - _, err = git.NewCommand(g.ctx, "fetch", remote, pr.Head.Ref).RunInDir(g.gitPath()) + err = git.NewCommand(g.ctx, "fetch", remote, pr.Head.Ref).RunWithContext(&git.RunContext{Dir: g.gitPath(), Timeout: -1}) if err != nil { log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err) } else { diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index 607dd0a076575..709aa435a9833 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -552,7 +552,7 @@ func (g *GiteaLocalUploader) updateGitForPullRequest(pr *base.PullRequest) (head } if ok { - _, err = git.NewCommand(g.ctx, "fetch", remote, pr.Head.Ref).RunInDir(g.repo.RepoPath()) + err = git.NewCommand(g.ctx, "fetch", remote, pr.Head.Ref).RunWithContext(&git.RunContext{Dir: g.repo.RepoPath(), Timeout: -1}) if err != nil { log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err) } else { @@ -576,7 +576,7 @@ func (g *GiteaLocalUploader) updateGitForPullRequest(pr *base.PullRequest) (head } else { head = pr.Head.Ref // Ensure the closed PR SHA still points to an existing ref - _, err = git.NewCommand(g.ctx, "rev-list", "--quiet", "-1", pr.Head.SHA).RunInDir(g.repo.RepoPath()) + err = git.NewCommand(g.ctx, "rev-list", "--quiet", "-1", pr.Head.SHA).RunWithContext(&git.RunContext{Dir: g.repo.RepoPath(), Timeout: -1}) if err != nil { if pr.Head.SHA != "" { // Git update-ref remove bad references with a relative path diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 34107b7f6ad5e..4686f8d32280f 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -233,7 +233,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { fromRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) baseRef := "master" assert.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false)) - _, err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+baseRef).RunInDir(fromRepo.RepoPath()) + err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+baseRef).RunWithContext(&git.RunContext{Dir: fromRepo.RepoPath(), Timeout: -1}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath())), 0o644)) assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) @@ -257,7 +257,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { // fromRepo branch1 // headRef := "branch1" - _, err = git.NewCommand(git.DefaultContext, "checkout", "-b", headRef).RunInDir(fromRepo.RepoPath()) + err = git.NewCommand(git.DefaultContext, "checkout", "-b", headRef).RunWithContext(&git.RunContext{Dir: fromRepo.RepoPath(), Timeout: -1}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("SOMETHING"), 0o644)) assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) @@ -281,7 +281,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { assert.NoError(t, git.CloneWithArgs(git.DefaultContext, fromRepo.RepoPath(), forkRepo.RepoPath(), []string{}, git.CloneRepoOptions{ Branch: headRef, })) - _, err = git.NewCommand(git.DefaultContext, "checkout", "-b", forkHeadRef).RunInDir(forkRepo.RepoPath()) + err = git.NewCommand(git.DefaultContext, "checkout", "-b", forkHeadRef).RunWithContext(&git.RunContext{Dir: forkRepo.RepoPath(), Timeout: -1}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# branch2 %s", forkRepo.RepoPath())), 0o644)) assert.NoError(t, git.AddChanges(forkRepo.RepoPath(), true)) diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go index d142a48ca0760..53c70e47195b9 100644 --- a/services/mirror/mirror_pull.go +++ b/services/mirror/mirror_pull.go @@ -33,7 +33,7 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error remoteName := m.GetRemoteName() repoPath := m.Repo.RepoPath() // Remove old remote - _, err := git.NewCommand(ctx, "remote", "rm", remoteName).RunInDir(repoPath) + err := git.NewCommand(ctx, "remote", "rm", remoteName).RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return err } @@ -44,7 +44,7 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error } else { cmd.SetDescription(fmt.Sprintf("remote add %s --mirror=fetch %s [repo_path: %s]", remoteName, addr, repoPath)) } - _, err = cmd.RunInDir(repoPath) + err = cmd.RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return err } @@ -53,7 +53,7 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error wikiPath := m.Repo.WikiPath() wikiRemotePath := repo_module.WikiRemoteURL(ctx, addr) // Remove old remote of wiki - _, err := git.NewCommand(ctx, "remote", "rm", remoteName).RunInDir(wikiPath) + err := git.NewCommand(ctx, "remote", "rm", remoteName).RunWithContext(&git.RunContext{Dir: wikiPath, Timeout: -1}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return err } @@ -64,7 +64,7 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error } else { cmd.SetDescription(fmt.Sprintf("remote add %s --mirror=fetch %s [repo_path: %s]", remoteName, wikiRemotePath, wikiPath)) } - _, err = cmd.RunInDir(wikiPath) + err = cmd.RunWithContext(&git.RunContext{Dir: wikiPath, Timeout: -1}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return err } diff --git a/services/mirror/mirror_push.go b/services/mirror/mirror_push.go index b619f9ab32344..dc6036963dc84 100644 --- a/services/mirror/mirror_push.go +++ b/services/mirror/mirror_push.go @@ -35,16 +35,13 @@ func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr str } else { cmd.SetDescription(fmt.Sprintf("remote add %s --mirror=push %s [repo_path: %s]", m.RemoteName, addr, path)) } - if _, err := cmd.RunInDir(path); err != nil { + if err := cmd.RunWithContext(&git.RunContext{Dir: path, Timeout: -1}); err != nil { return err } - if _, err := git.NewCommand(ctx, "config", "--add", "remote."+m.RemoteName+".push", "+refs/heads/*:refs/heads/*").RunInDir(path); err != nil { + if err := git.NewCommand(ctx, "config", "--add", "remote."+m.RemoteName+".push", "+refs/heads/*:refs/heads/*").RunWithContext(&git.RunContext{Dir: path, Timeout: -1}); err != nil { return err } - if _, err := git.NewCommand(ctx, "config", "--add", "remote."+m.RemoteName+".push", "+refs/tags/*:refs/tags/*").RunInDir(path); err != nil { - return err - } - return nil + return git.NewCommand(ctx, "config", "--add", "remote."+m.RemoteName+".push", "+refs/tags/*:refs/tags/*").RunWithContext(&git.RunContext{Dir: path, Timeout: -1}) } if err := addRemoteAndConfig(addr, m.Repo.RepoPath()); err != nil { @@ -67,12 +64,12 @@ func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr str func RemovePushMirrorRemote(ctx context.Context, m *repo_model.PushMirror) error { cmd := git.NewCommand(ctx, "remote", "rm", m.RemoteName) - if _, err := cmd.RunInDir(m.Repo.RepoPath()); err != nil { + if err := cmd.RunWithContext(&git.RunContext{Dir: m.Repo.RepoPath(), Timeout: -1}); err != nil { return err } if m.Repo.HasWiki() { - if _, err := cmd.RunInDir(m.Repo.WikiPath()); err != nil { + if err := cmd.RunWithContext(&git.RunContext{Dir: m.Repo.WikiPath(), Timeout: -1}); err != nil { // The wiki remote may not exist log.Warn("Wiki Remote[%d] could not be removed: %v", m.ID, err) } diff --git a/services/pull/merge.go b/services/pull/merge.go index 6108a7956e1d6..b8482f784f26e 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -141,7 +141,9 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User stagingBranch := "staging" if expectedHeadCommitID != "" { - trackingCommitID, err := git.NewCommand(ctx, "show-ref", "--hash", git.BranchPrefix+trackingBranch).RunInDir(tmpBasePath) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "show-ref", "--hash", git.BranchPrefix+trackingBranch).RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) + trackingCommitID := stdout.String() if err != nil { log.Error("show-ref[%s] --hash refs/heads/trackingn: %v", tmpBasePath, git.BranchPrefix+trackingBranch, err) return "", fmt.Errorf("getDiffTree: %v", err) diff --git a/services/pull/patch.go b/services/pull/patch.go index f401b85345ebe..ccfd3ad9c02db 100644 --- a/services/pull/patch.go +++ b/services/pull/patch.go @@ -76,7 +76,9 @@ func TestPatch(pr *models.PullRequest) error { defer gitRepo.Close() // 1. update merge base - pr.MergeBase, err = git.NewCommand(ctx, "merge-base", "--", "base", "tracking").RunInDir(tmpBasePath) + stdout := new(strings.Builder) + err = git.NewCommand(ctx, "merge-base", "--", "base", "tracking").RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) + pr.MergeBase = stdout.String() if err != nil { var err2 error pr.MergeBase, err2 = gitRepo.GetRefCommitID(git.BranchPrefix + "base") @@ -166,44 +168,48 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g } // Need to get the objects from the object db to attempt to merge - root, err := git.NewCommand(ctx, "unpack-file", file.stage1.sha).RunInDir(tmpBasePath) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "unpack-file", file.stage1.sha).RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) if err != nil { return fmt.Errorf("unable to get root object: %s at path: %s for merging. Error: %w", file.stage1.sha, file.stage1.path, err) } - root = strings.TrimSpace(root) + root := strings.TrimSpace(stdout.String()) defer func() { _ = util.Remove(filepath.Join(tmpBasePath, root)) }() - base, err := git.NewCommand(ctx, "unpack-file", file.stage2.sha).RunInDir(tmpBasePath) + stdout.Reset() + err = git.NewCommand(ctx, "unpack-file", file.stage2.sha).RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) if err != nil { return fmt.Errorf("unable to get base object: %s at path: %s for merging. Error: %w", file.stage2.sha, file.stage2.path, err) } - base = strings.TrimSpace(filepath.Join(tmpBasePath, base)) + base := strings.TrimSpace(filepath.Join(tmpBasePath, stdout.String())) defer func() { _ = util.Remove(base) }() - head, err := git.NewCommand(ctx, "unpack-file", file.stage3.sha).RunInDir(tmpBasePath) + stdout.Reset() + err = git.NewCommand(ctx, "unpack-file", file.stage3.sha).RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) if err != nil { return fmt.Errorf("unable to get head object:%s at path: %s for merging. Error: %w", file.stage3.sha, file.stage3.path, err) } - head = strings.TrimSpace(head) + head := strings.TrimSpace(stdout.String()) defer func() { _ = util.Remove(filepath.Join(tmpBasePath, head)) }() // now git merge-file annoyingly takes a different order to the merge-tree ... - _, conflictErr := git.NewCommand(ctx, "merge-file", base, root, head).RunInDir(tmpBasePath) + conflictErr := git.NewCommand(ctx, "merge-file", base, root, head).RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1}) if conflictErr != nil { return &errMergeConflict{file.stage2.path} } // base now contains the merged data - hash, err := git.NewCommand(ctx, "hash-object", "-w", "--path", file.stage2.path, base).RunInDir(tmpBasePath) + stdout.Reset() + err = git.NewCommand(ctx, "hash-object", "-w", "--path", file.stage2.path, base).RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) if err != nil { return err } - hash = strings.TrimSpace(hash) + hash := strings.TrimSpace(stdout.String()) return gitRepo.AddObjectToIndex(file.stage2.mode, git.MustIDFromString(hash), file.stage2.path) default: if file.stage1 != nil { @@ -223,7 +229,7 @@ func AttemptThreeWayMerge(ctx context.Context, gitPath string, gitRepo *git.Repo defer cancel() // First we use read-tree to do a simple three-way merge - if _, err := git.NewCommand(ctx, "read-tree", "-m", base, ours, theirs).RunInDir(gitPath); err != nil { + if err := git.NewCommand(ctx, "read-tree", "-m", base, ours, theirs).RunWithContext(&git.RunContext{Dir: gitPath, Timeout: -1}); err != nil { log.Error("Unable to run read-tree -m! Error: %v", err) return false, nil, fmt.Errorf("unable to run read-tree -m! Error: %v", err) } @@ -278,11 +284,12 @@ func checkConflicts(ctx context.Context, pr *models.PullRequest, gitRepo *git.Re } if !conflict { - treeHash, err := git.NewCommand(ctx, "write-tree").RunInDir(tmpBasePath) + stdout := new(strings.Builder) + err := git.NewCommand(ctx, "write-tree").RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1, Stdout: stdout}) if err != nil { return false, err } - treeHash = strings.TrimSpace(treeHash) + treeHash := strings.TrimSpace(stdout.String()) baseTree, err := gitRepo.GetTree("base") if err != nil { return false, err @@ -337,7 +344,7 @@ func checkConflicts(ctx context.Context, pr *models.PullRequest, gitRepo *git.Re pr.Status = models.PullRequestStatusChecking // 3. Read the base branch in to the index of the temporary repository - _, err = git.NewCommand(gitRepo.Ctx, "read-tree", "base").RunInDir(tmpBasePath) + err = git.NewCommand(gitRepo.Ctx, "read-tree", "base").RunWithContext(&git.RunContext{Dir: tmpBasePath, Timeout: -1}) if err != nil { return false, fmt.Errorf("git read-tree %s: %v", pr.BaseBranch, err) } diff --git a/services/pull/pull.go b/services/pull/pull.go index 7a746d937faab..98c51b33b0108 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -479,7 +479,7 @@ func UpdateRef(ctx context.Context, pr *models.PullRequest) (err error) { return err } - _, err = git.NewCommand(ctx, "update-ref", pr.GetGitRefName(), pr.HeadCommitID).RunInDir(pr.BaseRepo.RepoPath()) + err = git.NewCommand(ctx, "update-ref", pr.GetGitRefName(), pr.HeadCommitID).RunWithContext(&git.RunContext{Dir: pr.BaseRepo.RepoPath(), Timeout: -1}) if err != nil { log.Error("Unable to update ref in base repository for PR[%d] Error: %v", pr.ID, err) } diff --git a/services/release/release.go b/services/release/release.go index 4d16e66aec98e..1a566f6a14e13 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -297,11 +297,13 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del } if delTag { - if stdout, err := git.NewCommand(ctx, "tag", "-d", rel.TagName). + stdout := new(strings.Builder) + stderr := new(strings.Builder) + if err := git.NewCommand(ctx, "tag", "-d", rel.TagName). SetDescription(fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID)). - RunInDir(repo.RepoPath()); err != nil && !strings.Contains(err.Error(), "not found") { - log.Error("DeleteReleaseByID (git tag -d): %d in %v Failed:\nStdout: %s\nError: %v", rel.ID, repo, stdout, err) - return fmt.Errorf("git tag -d: %v", err) + RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1, Stdout: stdout, Stderr: stderr}); err != nil && !strings.Contains(stderr.String(), "not found") { + log.Error("DeleteReleaseByID (git tag -d): %d in %v Failed:\nStdout: %s\nError: %v", rel.ID, repo, stdout.String(), stderr.String()) + return fmt.Errorf("git tag -d: %v", stderr.String()) } notification.NotifyPushCommits( diff --git a/services/repository/adopt.go b/services/repository/adopt.go index 2af01e973aebc..dff4a8078dcd0 100644 --- a/services/repository/adopt.go +++ b/services/repository/adopt.go @@ -84,10 +84,11 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (* } } - if stdout, err := git.NewCommand(ctx, "update-server-info"). + stdout := new(strings.Builder) + if err := git.NewCommand(ctx, "update-server-info"). SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)). - RunInDir(repoPath); err != nil { - log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err) + RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}); err != nil { + log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout.String(), err) return fmt.Errorf("CreateRepository(git update-server-info): %v", err) } return nil diff --git a/services/repository/check.go b/services/repository/check.go index 6962090f8441e..ad2fa76d60781 100644 --- a/services/repository/check.go +++ b/services/repository/check.go @@ -75,20 +75,20 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro log.Trace("Running git gc on %v", repo) command := git.NewCommand(ctx, args...). SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName())) - var stdout string + stdout := new(strings.Builder) var err error if timeout > 0 { var stdoutBytes []byte stdoutBytes, err = command.RunInDirTimeout( timeout, repo.RepoPath()) - stdout = string(stdoutBytes) + stdout.Write(stdoutBytes) } else { - stdout, err = command.RunInDir(repo.RepoPath()) + err = command.RunWithContext(&git.RunContext{Dir: repo.RepoPath(), Timeout: -1, Stdout: stdout}) } if err != nil { - log.Error("Repository garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err) + log.Error("Repository garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout.String(), err) desc := fmt.Sprintf("Repository garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) if err = admin_model.CreateRepositoryNotice(desc); err != nil { log.Error("CreateRepositoryNotice: %v", err) diff --git a/services/repository/files/diff_test.go b/services/repository/files/diff_test.go index c0a378dc4b0ad..b4d7c726cb80a 100644 --- a/services/repository/files/diff_test.go +++ b/services/repository/files/diff_test.go @@ -167,6 +167,7 @@ func TestGetDiffPreviewErrors(t *testing.T) { t.Run("empty treePath", func(t *testing.T) { diff, err := GetDiffPreview(ctx, ctx.Repo.Repository, branch, "", content) assert.Nil(t, diff) + assert.Error(t, err) assert.EqualError(t, err, "path is invalid [path: ]") }) } diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go index 2223e1c8fda3f..5169ed71647d2 100644 --- a/services/repository/files/temp_repo.go +++ b/services/repository/files/temp_repo.go @@ -79,7 +79,7 @@ func (t *TemporaryUploadRepository) Clone(branch string) error { // SetDefaultIndex sets the git index to our HEAD func (t *TemporaryUploadRepository) SetDefaultIndex() error { - if _, err := git.NewCommand(t.ctx, "read-tree", "HEAD").RunInDir(t.basePath); err != nil { + if err := git.NewCommand(t.ctx, "read-tree", "HEAD").RunWithContext(&git.RunContext{Dir: t.basePath, Timeout: -1}); err != nil { return fmt.Errorf("SetDefaultIndex: %v", err) } return nil @@ -164,11 +164,14 @@ func (t *TemporaryUploadRepository) HashObject(content io.Reader) (string, error return strings.TrimSpace(stdOut.String()), nil } +var regexInvalidPath = regexp.MustCompile(".*Invalid path '.*") + // AddObjectToIndex adds the provided object hash to the index with the provided mode and path func (t *TemporaryUploadRepository) AddObjectToIndex(mode, objectHash, objectPath string) error { - if _, err := git.NewCommand(t.ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash, objectPath).RunInDir(t.basePath); err != nil { - stderr := err.Error() - if matched, _ := regexp.MatchString(".*Invalid path '.*", stderr); matched { + stderr := new(strings.Builder) + if err := git.NewCommand(t.ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash, objectPath). + RunWithContext(&git.RunContext{Dir: t.basePath, Timeout: -1, Stderr: stderr}); err != nil { + if matched := regexInvalidPath.MatchString(stderr.String()); matched { return models.ErrFilePathInvalid{ Message: objectPath, Path: objectPath, @@ -182,12 +185,13 @@ func (t *TemporaryUploadRepository) AddObjectToIndex(mode, objectHash, objectPat // WriteTree writes the current index as a tree to the object db and returns its hash func (t *TemporaryUploadRepository) WriteTree() (string, error) { - stdout, err := git.NewCommand(t.ctx, "write-tree").RunInDir(t.basePath) + stdout := new(strings.Builder) + err := git.NewCommand(t.ctx, "write-tree").RunWithContext(&git.RunContext{Dir: t.basePath, Timeout: -1, Stdout: stdout}) if err != nil { log.Error("Unable to write tree in temporary repo: %s(%s): Error: %v", t.repo.FullName(), t.basePath, err) return "", fmt.Errorf("Unable to write-tree in temporary repo for: %s Error: %v", t.repo.FullName(), err) } - return strings.TrimSpace(stdout), nil + return strings.TrimSpace(stdout.String()), nil } // GetLastCommit gets the last commit ID SHA of the repo @@ -200,12 +204,13 @@ func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, erro if ref == "" { ref = "HEAD" } - stdout, err := git.NewCommand(t.ctx, "rev-parse", ref).RunInDir(t.basePath) + stdout := new(strings.Builder) + err := git.NewCommand(t.ctx, "rev-parse", ref).RunWithContext(&git.RunContext{Dir: t.basePath, Timeout: -1, Stdout: stdout}) if err != nil { log.Error("Unable to get last ref for %s in temporary repo: %s(%s): Error: %v", ref, t.repo.FullName(), t.basePath, err) return "", fmt.Errorf("Unable to rev-parse %s in temporary repo for: %s Error: %v", ref, t.repo.FullName(), err) } - return strings.TrimSpace(stdout), nil + return strings.TrimSpace(stdout.String()), nil } // CommitTree creates a commit from a given tree for the user with provided message diff --git a/services/repository/fork.go b/services/repository/fork.go index ec8fb1a09e708..6ccebd2ffce48 100644 --- a/services/repository/fork.go +++ b/services/repository/fork.go @@ -120,10 +120,11 @@ func ForkRepository(doer, owner *user_model.User, opts ForkRepoOptions) (_ *repo return fmt.Errorf("checkDaemonExportOK: %v", err) } - if stdout, err := git.NewCommand(ctx, "update-server-info"). + stdout := new(strings.Builder) + if err := git.NewCommand(ctx, "update-server-info"). SetDescription(fmt.Sprintf("ForkRepository(git update-server-info): %s", repo.FullName())). - RunInDir(repoPath); err != nil { - log.Error("Fork Repository (git update-server-info) failed for %v:\nStdout: %s\nError: %v", repo, stdout, err) + RunWithContext(&git.RunContext{Dir: repoPath, Timeout: -1, Stdout: stdout}); err != nil { + log.Error("Fork Repository (git update-server-info) failed for %v:\nStdout: %s\nError: %v", repo, stdout.String(), err) return fmt.Errorf("git update-server-info: %v", err) } diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index 919753726ffa5..24493bfd89c7d 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -81,7 +81,7 @@ func InitWiki(ctx context.Context, repo *repo_model.Repository) error { return fmt.Errorf("InitRepository: %v", err) } else if err = repo_module.CreateDelegateHooks(repo.WikiPath()); err != nil { return fmt.Errorf("createDelegateHooks: %v", err) - } else if _, err = git.NewCommand(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(repo.WikiPath()); err != nil { + } else if err = git.NewCommand(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunWithContext(&git.RunContext{Dir: repo.WikiPath(), Timeout: -1}); err != nil { return fmt.Errorf("unable to set default wiki branch to master: %v", err) } return nil