Delete old git.NewCommand() and use it as git.NewCommandContext() (#18552)

This commit is contained in:
6543 2022-02-06 20:01:47 +01:00 committed by GitHub
parent 8ae5e6d7fd
commit 3043eb36bf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
74 changed files with 258 additions and 263 deletions

View file

@ -309,7 +309,7 @@ func runHookPostReceive(c *cli.Context) error {
defer cancel() defer cancel()
// First of all run update-server-info no matter what // First of all run update-server-info no matter what
if _, err := git.NewCommandContext(ctx, "update-server-info").Run(); err != nil { if _, err := git.NewCommand(ctx, "update-server-info").Run(); err != nil {
return fmt.Errorf("Failed to call 'git update-server-info': %v", err) return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
} }

View file

@ -28,8 +28,8 @@ func TestAPIGitTags(t *testing.T) {
token := getTokenForLoggedInUser(t, session) token := getTokenForLoggedInUser(t, session)
// Set up git config for the tagger // Set up git config for the tagger
git.NewCommand("config", "user.name", user.Name).RunInDir(repo.RepoPath()) git.NewCommand(git.DefaultContext, "config", "user.name", user.Name).RunInDir(repo.RepoPath())
git.NewCommand("config", "user.email", user.Email).RunInDir(repo.RepoPath()) git.NewCommand(git.DefaultContext, "config", "user.email", user.Email).RunInDir(repo.RepoPath())
gitRepo, _ := git.OpenRepository(repo.RepoPath()) gitRepo, _ := git.OpenRepository(repo.RepoPath())
defer gitRepo.Close() defer gitRepo.Close()

View file

@ -134,7 +134,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
// Init repository in dstPath // Init repository in dstPath
assert.NoError(t, git.InitRepository(git.DefaultContext, dstPath, false)) assert.NoError(t, git.InitRepository(git.DefaultContext, dstPath, false))
// forcibly set default branch to master // forcibly set default branch to master
_, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath)
assert.NoError(t, err) 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, 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)) assert.NoError(t, git.AddChanges(dstPath, true))
@ -153,28 +153,28 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) { func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
_, err := git.NewCommand("remote", "add", remoteName, u.String()).RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, "remote", "add", remoteName, u.String()).RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
} }
} }
func doGitPushTestRepository(dstPath string, args ...string) func(*testing.T) { func doGitPushTestRepository(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
_, err := git.NewCommand(append([]string{"push", "-u"}, args...)...).RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, append([]string{"push", "-u"}, args...)...).RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
} }
} }
func doGitPushTestRepositoryFail(dstPath string, args ...string) func(*testing.T) { func doGitPushTestRepositoryFail(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
_, err := git.NewCommand(append([]string{"push"}, args...)...).RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, append([]string{"push"}, args...)...).RunInDir(dstPath)
assert.Error(t, err) assert.Error(t, err)
} }
} }
func doGitCreateBranch(dstPath, branch string) func(*testing.T) { func doGitCreateBranch(dstPath, branch string) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
_, err := git.NewCommand("checkout", "-b", branch).RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, "checkout", "-b", branch).RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
} }
} }
@ -188,7 +188,7 @@ func doGitCheckoutBranch(dstPath string, args ...string) func(*testing.T) {
func doGitMerge(dstPath string, args ...string) func(*testing.T) { func doGitMerge(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
_, err := git.NewCommand(append([]string{"merge"}, args...)...).RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, append([]string{"merge"}, args...)...).RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
} }
} }

View file

@ -160,9 +160,9 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin
return return
} }
prefix := "lfs-data-file-" prefix := "lfs-data-file-"
_, err := git.NewCommand("lfs").AddArguments("install").RunInDir(dstPath) _, err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("install").RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
_, err = git.NewCommand("lfs").AddArguments("track", prefix+"*").RunInDir(dstPath) _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("track", prefix+"*").RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
err = git.AddChanges(dstPath, false, ".gitattributes") err = git.AddChanges(dstPath, false, ".gitattributes")
assert.NoError(t, err) assert.NoError(t, err)
@ -292,20 +292,20 @@ func lockTest(t *testing.T, repoPath string) {
} }
func lockFileTest(t *testing.T, filename, repoPath string) { func lockFileTest(t *testing.T, filename, repoPath string) {
_, err := git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath) _, err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunInDir(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
_, err = git.NewCommand("lfs").AddArguments("lock", filename).RunInDir(repoPath) _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("lock", filename).RunInDir(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
_, err = git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath) _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunInDir(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
_, err = git.NewCommand("lfs").AddArguments("unlock", filename).RunInDir(repoPath) _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("unlock", filename).RunInDir(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
} }
func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string { func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix) name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
assert.NoError(t, err) assert.NoError(t, err)
_, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) // Push _, err = git.NewCommand(git.DefaultContext, "push", "origin", "master").RunInDir(repoPath) // Push
assert.NoError(t, err) assert.NoError(t, err)
return name return name
} }
@ -671,7 +671,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
}) })
t.Run("Push", func(t *testing.T) { t.Run("Push", func(t *testing.T) {
_, err := git.NewCommand("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).RunInDir(dstPath)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
@ -692,7 +692,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
assert.Contains(t, "Testing commit 1", prMsg.Body) assert.Contains(t, "Testing commit 1", prMsg.Body)
assert.Equal(t, commit, prMsg.Head.Sha) assert.Equal(t, commit, prMsg.Head.Sha)
_, err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath) _, err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
@ -745,7 +745,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
}) })
t.Run("Push2", func(t *testing.T) { t.Run("Push2", func(t *testing.T) {
_, err := git.NewCommand("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).RunInDir(dstPath)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
@ -757,7 +757,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
assert.Equal(t, false, prMsg.HasMerged) assert.Equal(t, false, prMsg.HasMerged)
assert.Equal(t, commit, prMsg.Head.Sha) assert.Equal(t, commit, prMsg.Head.Sha)
_, err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath) _, err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }

View file

@ -269,19 +269,19 @@ func TestCantMergeUnrelated(t *testing.T) {
}).(*repo_model.Repository) }).(*repo_model.Repository)
path := repo_model.RepoPath(user1.Name, repo1.Name) path := repo_model.RepoPath(user1.Name, repo1.Name)
_, err := git.NewCommand("read-tree", "--empty").RunInDir(path) _, err := git.NewCommand(git.DefaultContext, "read-tree", "--empty").RunInDir(path)
assert.NoError(t, err) assert.NoError(t, err)
stdin := bytes.NewBufferString("Unrelated File") stdin := bytes.NewBufferString("Unrelated File")
var stdout strings.Builder var stdout strings.Builder
err = git.NewCommand("hash-object", "-w", "--stdin").RunInDirFullPipeline(path, &stdout, nil, stdin) err = git.NewCommand(git.DefaultContext, "hash-object", "-w", "--stdin").RunInDirFullPipeline(path, &stdout, nil, stdin)
assert.NoError(t, err) assert.NoError(t, err)
sha := strings.TrimSpace(stdout.String()) sha := strings.TrimSpace(stdout.String())
_, err = git.NewCommand("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").RunInDir(path)
assert.NoError(t, err) assert.NoError(t, err)
treeSha, err := git.NewCommand("write-tree").RunInDir(path) treeSha, err := git.NewCommand(git.DefaultContext, "write-tree").RunInDir(path)
assert.NoError(t, err) assert.NoError(t, err)
treeSha = strings.TrimSpace(treeSha) treeSha = strings.TrimSpace(treeSha)
@ -301,11 +301,11 @@ func TestCantMergeUnrelated(t *testing.T) {
_, _ = messageBytes.WriteString("\n") _, _ = messageBytes.WriteString("\n")
stdout.Reset() stdout.Reset()
err = git.NewCommand("commit-tree", treeSha).RunInDirTimeoutEnvFullPipeline(env, -1, path, &stdout, nil, messageBytes) err = git.NewCommand(git.DefaultContext, "commit-tree", treeSha).RunInDirTimeoutEnvFullPipeline(env, -1, path, &stdout, nil, messageBytes)
assert.NoError(t, err) assert.NoError(t, err)
commitSha := strings.TrimSpace(stdout.String()) commitSha := strings.TrimSpace(stdout.String())
_, err = git.NewCommand("branch", "unrelated", commitSha).RunInDir(path) _, err = git.NewCommand(git.DefaultContext, "branch", "unrelated", commitSha).RunInDir(path)
assert.NoError(t, err) assert.NoError(t, err)
testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n")

View file

@ -66,10 +66,10 @@ func TestCreateNewTagProtected(t *testing.T) {
doGitClone(dstPath, u)(t) doGitClone(dstPath, u)(t)
_, err = git.NewCommand("tag", "v-2").RunInDir(dstPath) _, err = git.NewCommand(git.DefaultContext, "tag", "v-2").RunInDir(dstPath)
assert.NoError(t, err) assert.NoError(t, err)
_, err = git.NewCommand("push", "--tags").RunInDir(dstPath) _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunInDir(dstPath)
assert.Error(t, err) assert.Error(t, err)
assert.Contains(t, err.Error(), "Tag v-2 is protected") assert.Contains(t, err.Error(), "Tag v-2 is protected")
}) })

View file

@ -83,17 +83,17 @@ func fixMergeBase(x *xorm.Engine) error {
if !pr.HasMerged { if !pr.HasMerged {
var err error var err error
pr.MergeBase, err = git.NewCommand("merge-base", "--", pr.BaseBranch, gitRefName).RunInDir(repoPath) pr.MergeBase, err = git.NewCommand(git.DefaultContext, "merge-base", "--", pr.BaseBranch, gitRefName).RunInDir(repoPath)
if err != nil { if err != nil {
var err2 error var err2 error
pr.MergeBase, err2 = git.NewCommand("rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath) pr.MergeBase, err2 = git.NewCommand(git.DefaultContext, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath)
if err2 != nil { 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) 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 continue
} }
} }
} else { } else {
parentsString, err := git.NewCommand("rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath) parentsString, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath)
if err != nil { 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) 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 continue
@ -106,7 +106,7 @@ func fixMergeBase(x *xorm.Engine) error {
args := append([]string{"merge-base", "--"}, parents[1:]...) args := append([]string{"merge-base", "--"}, parents[1:]...)
args = append(args, gitRefName) args = append(args, gitRefName)
pr.MergeBase, err = git.NewCommand(args...).RunInDir(repoPath) pr.MergeBase, err = git.NewCommand(git.DefaultContext, args...).RunInDir(repoPath)
if err != nil { 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) 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 continue

View file

@ -80,7 +80,7 @@ func refixMergeBase(x *xorm.Engine) error {
gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index) gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index)
parentsString, err := git.NewCommand("rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath) parentsString, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath)
if err != nil { 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) 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 continue
@ -94,7 +94,7 @@ func refixMergeBase(x *xorm.Engine) error {
args := append([]string{"merge-base", "--"}, parents[1:]...) args := append([]string{"merge-base", "--"}, parents[1:]...)
args = append(args, gitRefName) args = append(args, gitRefName)
pr.MergeBase, err = git.NewCommand(args...).RunInDir(repoPath) pr.MergeBase, err = git.NewCommand(git.DefaultContext, args...).RunInDir(repoPath)
if err != nil { 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) 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 continue

View file

@ -44,17 +44,17 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro
if !pr.HasMerged { if !pr.HasMerged {
var err error var err error
pr.MergeBase, err = git.NewCommandContext(ctx, "merge-base", "--", pr.BaseBranch, pr.GetGitRefName()).RunInDir(repoPath) pr.MergeBase, err = git.NewCommand(ctx, "merge-base", "--", pr.BaseBranch, pr.GetGitRefName()).RunInDir(repoPath)
if err != nil { if err != nil {
var err2 error var err2 error
pr.MergeBase, err2 = git.NewCommandContext(ctx, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath) pr.MergeBase, err2 = git.NewCommand(ctx, "rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath)
if err2 != nil { 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) 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 return nil
} }
} }
} else { } else {
parentsString, err := git.NewCommandContext(ctx, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath) parentsString, err := git.NewCommand(ctx, "rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath)
if err != nil { 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) 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 return nil
@ -67,7 +67,7 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro
args := append([]string{"merge-base", "--"}, parents[1:]...) args := append([]string{"merge-base", "--"}, parents[1:]...)
args = append(args, pr.GetGitRefName()) args = append(args, pr.GetGitRefName())
pr.MergeBase, err = git.NewCommandContext(ctx, args...).RunInDir(repoPath) pr.MergeBase, err = git.NewCommand(ctx, args...).RunInDir(repoPath)
if err != nil { 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) 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 return nil

View file

@ -95,11 +95,11 @@ func checkEnablePushOptions(ctx context.Context, logger log.Logger, autofix bool
defer r.Close() defer r.Close()
if autofix { if autofix {
_, err := git.NewCommandContext(ctx, "config", "receive.advertisePushOptions", "true").RunInDir(r.Path) _, err := git.NewCommand(ctx, "config", "receive.advertisePushOptions", "true").RunInDir(r.Path)
return err return err
} }
value, err := git.NewCommandContext(ctx, "config", "receive.advertisePushOptions").RunInDir(r.Path) value, err := git.NewCommand(ctx, "config", "receive.advertisePushOptions").RunInDir(r.Path)
if err != nil { if err != nil {
return err return err
} }

View file

@ -32,7 +32,7 @@ type WriteCloserError interface {
// This is needed otherwise the git cat-file will hang for invalid repositories. // This is needed otherwise the git cat-file will hang for invalid repositories.
func EnsureValidGitRepository(ctx context.Context, repoPath string) error { func EnsureValidGitRepository(ctx context.Context, repoPath string) error {
stderr := strings.Builder{} stderr := strings.Builder{}
err := NewCommandContext(ctx, "rev-parse"). err := NewCommand(ctx, "rev-parse").
SetDescription(fmt.Sprintf("%s rev-parse [repo_path: %s]", GitExecutable, repoPath)). SetDescription(fmt.Sprintf("%s rev-parse [repo_path: %s]", GitExecutable, repoPath)).
RunInDirFullPipeline(repoPath, nil, &stderr, nil) RunInDirFullPipeline(repoPath, nil, &stderr, nil)
if err != nil { if err != nil {
@ -59,7 +59,7 @@ func CatFileBatchCheck(ctx context.Context, repoPath string) (WriteCloserError,
go func() { go func() {
stderr := strings.Builder{} stderr := strings.Builder{}
err := NewCommandContext(ctx, "cat-file", "--batch-check"). err := NewCommand(ctx, "cat-file", "--batch-check").
SetDescription(fmt.Sprintf("%s cat-file --batch-check [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)). SetDescription(fmt.Sprintf("%s cat-file --batch-check [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)).
RunInDirFullPipeline(repoPath, batchStdoutWriter, &stderr, batchStdinReader) RunInDirFullPipeline(repoPath, batchStdoutWriter, &stderr, batchStdinReader)
if err != nil { if err != nil {
@ -98,7 +98,7 @@ func CatFileBatch(ctx context.Context, repoPath string) (WriteCloserError, *bufi
go func() { go func() {
stderr := strings.Builder{} stderr := strings.Builder{}
err := NewCommandContext(ctx, "cat-file", "--batch"). err := NewCommand(ctx, "cat-file", "--batch").
SetDescription(fmt.Sprintf("%s cat-file --batch [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)). SetDescription(fmt.Sprintf("%s cat-file --batch [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)).
RunInDirFullPipeline(repoPath, batchStdoutWriter, &stderr, batchStdinReader) RunInDirFullPipeline(repoPath, batchStdoutWriter, &stderr, batchStdinReader)
if err != nil { if err != nil {

View file

@ -46,12 +46,7 @@ func (c *Command) String() string {
} }
// NewCommand creates and returns a new Git Command based on given command and arguments. // NewCommand creates and returns a new Git Command based on given command and arguments.
func NewCommand(args ...string) *Command { func NewCommand(ctx context.Context, args ...string) *Command {
return NewCommandContext(DefaultContext, args...)
}
// NewCommandContext creates and returns a new Git Command based on given command and arguments.
func NewCommandContext(ctx context.Context, args ...string) *Command {
// Make an explicit copy of globalCommandArgs, otherwise append might overwrite it // Make an explicit copy of globalCommandArgs, otherwise append might overwrite it
cargs := make([]string, len(globalCommandArgs)) cargs := make([]string, len(globalCommandArgs))
copy(cargs, globalCommandArgs) copy(cargs, globalCommandArgs)

View file

@ -17,7 +17,7 @@ func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) {
maxLoops := 1000 maxLoops := 1000
// 'git --version' does not block so it must be finished before the timeout triggered. // 'git --version' does not block so it must be finished before the timeout triggered.
cmd := NewCommand("--version") cmd := NewCommand(context.Background(), "--version")
for i := 0; i < maxLoops; i++ { for i := 0; i < maxLoops; i++ {
if err := cmd.RunInDirTimeoutPipeline(-1, "", nil, nil); err != nil { if err := cmd.RunInDirTimeoutPipeline(-1, "", nil, nil); err != nil {
t.Fatal(err) t.Fatal(err)
@ -29,7 +29,7 @@ func TestRunInDirTimeoutPipelineAlwaysTimeout(t *testing.T) {
maxLoops := 1000 maxLoops := 1000
// 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered. // 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered.
cmd := NewCommand("hash-object", "--stdin") cmd := NewCommand(context.Background(), "hash-object", "--stdin")
for i := 0; i < maxLoops; i++ { for i := 0; i < maxLoops; i++ {
if err := cmd.RunInDirTimeoutPipeline(1*time.Microsecond, "", nil, nil); err != nil { if err := cmd.RunInDirTimeoutPipeline(1*time.Microsecond, "", nil, nil); err != nil {
if err != context.DeadlineExceeded { if err != context.DeadlineExceeded {

View file

@ -144,7 +144,7 @@ func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, file
if hidePRRefs { if hidePRRefs {
args = append([]string{"--exclude=" + PullPrefix + "*"}, args...) args = append([]string{"--exclude=" + PullPrefix + "*"}, args...)
} }
cmd := NewCommandContext(ctx, "rev-list") cmd := NewCommand(ctx, "rev-list")
cmd.AddArguments(args...) cmd.AddArguments(args...)
if len(files) > 0 { if len(files) > 0 {
cmd.AddArguments("--") cmd.AddArguments("--")
@ -161,7 +161,7 @@ func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, file
// CommitsCountFiles returns number of total commits of until given revision. // CommitsCountFiles returns number of total commits of until given revision.
func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath []string) (int64, error) { func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath []string) (int64, error) {
cmd := NewCommandContext(ctx, "rev-list", "--count") cmd := NewCommand(ctx, "rev-list", "--count")
cmd.AddArguments(revision...) cmd.AddArguments(revision...)
if len(relpath) > 0 { if len(relpath) > 0 {
cmd.AddArguments("--") cmd.AddArguments("--")
@ -206,7 +206,7 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) {
} }
if err := CheckGitVersionAtLeast("1.8"); err == nil { if err := CheckGitVersionAtLeast("1.8"); err == nil {
_, err := NewCommandContext(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunInDir(c.repo.Path) _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunInDir(c.repo.Path)
if err == nil { if err == nil {
return true, nil return true, nil
} }
@ -219,7 +219,7 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) {
return false, err return false, err
} }
result, err := NewCommandContext(c.repo.Ctx, "rev-list", "--ancestry-path", "-n1", that+".."+this, "--").RunInDir(c.repo.Path) result, err := NewCommand(c.repo.Ctx, "rev-list", "--ancestry-path", "-n1", that+".."+this, "--").RunInDir(c.repo.Path)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -381,7 +381,7 @@ func (c *Commit) GetBranchName() (string, error) {
} }
args = append(args, "--name-only", "--no-undefined", c.ID.String()) args = append(args, "--name-only", "--no-undefined", c.ID.String())
data, err := NewCommandContext(c.repo.Ctx, args...).RunInDir(c.repo.Path) data, err := NewCommand(c.repo.Ctx, args...).RunInDir(c.repo.Path)
if err != nil { if err != nil {
// handle special case where git can not describe commit // handle special case where git can not describe commit
if strings.Contains(err.Error(), "cannot describe") { if strings.Contains(err.Error(), "cannot describe") {
@ -407,7 +407,7 @@ func (c *Commit) LoadBranchName() (err error) {
// GetTagName gets the current tag name for given commit // GetTagName gets the current tag name for given commit
func (c *Commit) GetTagName() (string, error) { func (c *Commit) GetTagName() (string, error) {
data, err := NewCommandContext(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always", c.ID.String()).RunInDir(c.repo.Path) data, err := NewCommand(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always", c.ID.String()).RunInDir(c.repo.Path)
if err != nil { if err != nil {
// handle special case where there is no tag for this commit // handle special case where there is no tag for this commit
if strings.Contains(err.Error(), "no tag exactly matches") { if strings.Contains(err.Error(), "no tag exactly matches") {
@ -486,7 +486,7 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
args := []string{"log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1", commitID} args := []string{"log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1", commitID}
err := NewCommandContext(ctx, args...).RunInDirPipeline(repoPath, w, stderr) err := NewCommand(ctx, args...).RunInDirPipeline(repoPath, w, stderr)
w.Close() // Close writer to exit parsing goroutine w.Close() // Close writer to exit parsing goroutine
if err != nil { if err != nil {
return nil, ConcatenateError(err, stderr.String()) return nil, ConcatenateError(err, stderr.String())
@ -498,7 +498,7 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi
// GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository. // 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) { func GetFullCommitID(ctx context.Context, repoPath, shortID string) (string, error) {
commitID, err := NewCommandContext(ctx, "rev-parse", shortID).RunInDir(repoPath) commitID, err := NewCommand(ctx, "rev-parse", shortID).RunInDir(repoPath)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "exit status 128") { if strings.Contains(err.Error(), "exit status 128") {
return "", ErrNotExist{shortID, ""} return "", ErrNotExist{shortID, ""}

View file

@ -81,7 +81,7 @@ func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diff
} }
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
cmd := NewCommandContext(repo.Ctx, args...) cmd := NewCommand(repo.Ctx, args...)
if err = cmd.RunWithContext(&RunContext{ if err = cmd.RunWithContext(&RunContext{
Timeout: -1, Timeout: -1,
Dir: repo.Path, Dir: repo.Path,
@ -286,7 +286,7 @@ func GetAffectedFiles(repo *Repository, oldCommitID, newCommitID string, env []s
affectedFiles := make([]string, 0, 32) affectedFiles := make([]string, 0, 32)
// Run `git diff --name-only` to get the names of the changed files // Run `git diff --name-only` to get the names of the changed files
err = NewCommandContext(repo.Ctx, "diff", "--name-only", oldCommitID, newCommitID). err = NewCommand(repo.Ctx, "diff", "--name-only", oldCommitID, newCommitID).
RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path, RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
stdoutWriter, nil, nil, stdoutWriter, nil, nil,
func(ctx context.Context, cancel context.CancelFunc) error { func(ctx context.Context, cancel context.CancelFunc) error {

View file

@ -54,7 +54,7 @@ func LoadGitVersion() error {
return nil return nil
} }
stdout, err := NewCommand("version").Run() stdout, err := NewCommand(context.Background(), "version").Run()
if err != nil { if err != nil {
return err return err
} }
@ -299,6 +299,6 @@ func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args ...s
if timeout <= 0 { if timeout <= 0 {
timeout = -1 timeout = -1
} }
_, err := NewCommandContext(ctx, "fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath) _, err := NewCommand(ctx, "fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath)
return err return err
} }

View file

@ -55,7 +55,7 @@ func LogNameStatusRepo(ctx context.Context, repository, head, treepath string, p
go func() { go func() {
stderr := strings.Builder{} stderr := strings.Builder{}
err := NewCommandContext(ctx, args...).RunInDirFullPipeline(repository, stdoutWriter, &stderr, nil) err := NewCommand(ctx, args...).RunInDirFullPipeline(repository, stdoutWriter, &stderr, nil)
if err != nil { if err != nil {
_ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String())) _ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
} else { } else {

View file

@ -26,7 +26,7 @@ func CatFileBatchCheck(ctx context.Context, shasToCheckReader *io.PipeReader, ca
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
var errbuf strings.Builder var errbuf strings.Builder
cmd := git.NewCommandContext(ctx, "cat-file", "--batch-check") cmd := git.NewCommand(ctx, "cat-file", "--batch-check")
if err := cmd.RunInDirFullPipeline(tmpBasePath, catFileCheckWriter, stderr, shasToCheckReader); err != nil { if err := cmd.RunInDirFullPipeline(tmpBasePath, catFileCheckWriter, stderr, shasToCheckReader); err != nil {
_ = catFileCheckWriter.CloseWithError(fmt.Errorf("git cat-file --batch-check [%s]: %v - %s", tmpBasePath, err, errbuf.String())) _ = catFileCheckWriter.CloseWithError(fmt.Errorf("git cat-file --batch-check [%s]: %v - %s", tmpBasePath, err, errbuf.String()))
} }
@ -39,7 +39,7 @@ func CatFileBatchCheckAllObjects(ctx context.Context, catFileCheckWriter *io.Pip
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
var errbuf strings.Builder var errbuf strings.Builder
cmd := git.NewCommandContext(ctx, "cat-file", "--batch-check", "--batch-all-objects") cmd := git.NewCommand(ctx, "cat-file", "--batch-check", "--batch-all-objects")
if err := cmd.RunInDirPipeline(tmpBasePath, catFileCheckWriter, stderr); err != nil { if err := cmd.RunInDirPipeline(tmpBasePath, catFileCheckWriter, stderr); err != nil {
log.Error("git cat-file --batch-check --batch-all-object [%s]: %v - %s", tmpBasePath, err, errbuf.String()) log.Error("git cat-file --batch-check --batch-all-object [%s]: %v - %s", tmpBasePath, err, errbuf.String())
err = fmt.Errorf("git cat-file --batch-check --batch-all-object [%s]: %v - %s", tmpBasePath, err, errbuf.String()) err = fmt.Errorf("git cat-file --batch-check --batch-all-object [%s]: %v - %s", tmpBasePath, err, errbuf.String())
@ -56,7 +56,7 @@ func CatFileBatch(ctx context.Context, shasToBatchReader *io.PipeReader, catFile
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
var errbuf strings.Builder var errbuf strings.Builder
if err := git.NewCommandContext(ctx, "cat-file", "--batch").RunInDirFullPipeline(tmpBasePath, catFileBatchWriter, stderr, shasToBatchReader); err != nil { if err := git.NewCommand(ctx, "cat-file", "--batch").RunInDirFullPipeline(tmpBasePath, catFileBatchWriter, stderr, shasToBatchReader); err != nil {
_ = shasToBatchReader.CloseWithError(fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String())) _ = shasToBatchReader.CloseWithError(fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String()))
} }
} }

View file

@ -53,7 +53,7 @@ func FindLFSFile(repo *git.Repository, hash git.SHA1) ([]*LFSResult, error) {
go func() { go func() {
stderr := strings.Builder{} stderr := strings.Builder{}
err := git.NewCommandContext(repo.Ctx, "rev-list", "--all").RunInDirPipeline(repo.Path, revListWriter, &stderr) err := git.NewCommand(repo.Ctx, "rev-list", "--all").RunInDirPipeline(repo.Path, revListWriter, &stderr)
if err != nil { if err != nil {
_ = revListWriter.CloseWithError(git.ConcatenateError(err, (&stderr).String())) _ = revListWriter.CloseWithError(git.ConcatenateError(err, (&stderr).String()))
} else { } else {

View file

@ -23,7 +23,7 @@ func NameRevStdin(ctx context.Context, shasToNameReader *io.PipeReader, nameRevS
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
var errbuf strings.Builder var errbuf strings.Builder
if err := git.NewCommandContext(ctx, "name-rev", "--stdin", "--name-only", "--always").RunInDirFullPipeline(tmpBasePath, nameRevStdinWriter, stderr, shasToNameReader); err != nil { if err := git.NewCommand(ctx, "name-rev", "--stdin", "--name-only", "--always").RunInDirFullPipeline(tmpBasePath, nameRevStdinWriter, stderr, shasToNameReader); err != nil {
_ = shasToNameReader.CloseWithError(fmt.Errorf("git name-rev [%s]: %v - %s", tmpBasePath, err, errbuf.String())) _ = shasToNameReader.CloseWithError(fmt.Errorf("git name-rev [%s]: %v - %s", tmpBasePath, err, errbuf.String()))
} }
} }

View file

@ -24,7 +24,7 @@ func RevListAllObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sy
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
var errbuf strings.Builder var errbuf strings.Builder
cmd := git.NewCommandContext(ctx, "rev-list", "--objects", "--all") cmd := git.NewCommand(ctx, "rev-list", "--objects", "--all")
if err := cmd.RunInDirPipeline(basePath, revListWriter, stderr); err != nil { if err := cmd.RunInDirPipeline(basePath, revListWriter, stderr); err != nil {
log.Error("git rev-list --objects --all [%s]: %v - %s", basePath, err, errbuf.String()) log.Error("git rev-list --objects --all [%s]: %v - %s", basePath, err, errbuf.String())
err = fmt.Errorf("git rev-list --objects --all [%s]: %v - %s", basePath, err, errbuf.String()) err = fmt.Errorf("git rev-list --objects --all [%s]: %v - %s", basePath, err, errbuf.String())
@ -39,7 +39,7 @@ func RevListObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sync.
defer revListWriter.Close() defer revListWriter.Close()
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
var errbuf strings.Builder var errbuf strings.Builder
cmd := git.NewCommandContext(ctx, "rev-list", "--objects", headSHA, "--not", baseSHA) cmd := git.NewCommand(ctx, "rev-list", "--objects", headSHA, "--not", baseSHA)
if err := cmd.RunInDirPipeline(tmpBasePath, revListWriter, stderr); err != nil { if err := cmd.RunInDirPipeline(tmpBasePath, revListWriter, stderr); err != nil {
log.Error("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String()) log.Error("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String())
errChan <- fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String()) errChan <- fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String())

View file

@ -17,9 +17,9 @@ func GetRemoteAddress(ctx context.Context, repoPath, remoteName string) (*url.UR
} }
var cmd *Command var cmd *Command
if CheckGitVersionAtLeast("2.7") == nil { if CheckGitVersionAtLeast("2.7") == nil {
cmd = NewCommandContext(ctx, "remote", "get-url", remoteName) cmd = NewCommand(ctx, "remote", "get-url", remoteName)
} else { } else {
cmd = NewCommandContext(ctx, "config", "--get", "remote."+remoteName+".url") cmd = NewCommand(ctx, "config", "--get", "remote."+remoteName+".url")
} }
result, err := cmd.RunInDir(repoPath) result, err := cmd.RunInDir(repoPath)

View file

@ -58,7 +58,7 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro
// IsRepoURLAccessible checks if given repository URL is accessible. // IsRepoURLAccessible checks if given repository URL is accessible.
func IsRepoURLAccessible(ctx context.Context, url string) bool { func IsRepoURLAccessible(ctx context.Context, url string) bool {
_, err := NewCommandContext(ctx, "ls-remote", "-q", "-h", url, "HEAD").Run() _, err := NewCommand(ctx, "ls-remote", "-q", "-h", url, "HEAD").Run()
return err == nil return err == nil
} }
@ -69,7 +69,7 @@ func InitRepository(ctx context.Context, repoPath string, bare bool) error {
return err return err
} }
cmd := NewCommandContext(ctx, "init") cmd := NewCommand(ctx, "init")
if bare { if bare {
cmd.AddArguments("--bare") cmd.AddArguments("--bare")
} }
@ -80,7 +80,7 @@ func InitRepository(ctx context.Context, repoPath string, bare bool) error {
// IsEmpty Check if repository is empty. // IsEmpty Check if repository is empty.
func (repo *Repository) IsEmpty() (bool, error) { func (repo *Repository) IsEmpty() (bool, error) {
var errbuf, output strings.Builder var errbuf, output strings.Builder
if err := NewCommandContext(repo.Ctx, "rev-list", "--all", "--count", "--max-count=1"). if err := NewCommand(repo.Ctx, "rev-list", "--all", "--count", "--max-count=1").
RunWithContext(&RunContext{ RunWithContext(&RunContext{
Timeout: -1, Timeout: -1,
Dir: repo.Path, Dir: repo.Path,
@ -187,7 +187,7 @@ type PushOptions struct {
// Push pushs local commits to given remote branch. // Push pushs local commits to given remote branch.
func Push(ctx context.Context, repoPath string, opts PushOptions) error { func Push(ctx context.Context, repoPath string, opts PushOptions) error {
cmd := NewCommandContext(ctx, "push") cmd := NewCommand(ctx, "push")
if opts.Force { if opts.Force {
cmd.AddArguments("-f") cmd.AddArguments("-f")
} }
@ -239,7 +239,7 @@ func Push(ctx context.Context, repoPath string, opts PushOptions) error {
// GetLatestCommitTime returns time for latest commit in repository (across all branches) // GetLatestCommitTime returns time for latest commit in repository (across all branches)
func GetLatestCommitTime(ctx context.Context, repoPath string) (time.Time, error) { func GetLatestCommitTime(ctx context.Context, repoPath string) (time.Time, error) {
cmd := NewCommandContext(ctx, "for-each-ref", "--sort=-committerdate", BranchPrefix, "--count", "1", "--format=%(committerdate)") cmd := NewCommand(ctx, "for-each-ref", "--sort=-committerdate", BranchPrefix, "--count", "1", "--format=%(committerdate)")
stdout, err := cmd.RunInDir(repoPath) stdout, err := cmd.RunInDir(repoPath)
if err != nil { if err != nil {
return time.Time{}, err return time.Time{}, err
@ -256,7 +256,7 @@ type DivergeObject struct {
func checkDivergence(ctx context.Context, repoPath, baseBranch, targetBranch string) (int, error) { func checkDivergence(ctx context.Context, repoPath, baseBranch, targetBranch string) (int, error) {
branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
cmd := NewCommandContext(ctx, "rev-list", "--count", branches) cmd := NewCommand(ctx, "rev-list", "--count", branches)
stdout, err := cmd.RunInDir(repoPath) stdout, err := cmd.RunInDir(repoPath)
if err != nil { if err != nil {
return -1, err return -1, err
@ -294,23 +294,23 @@ func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io.
defer os.RemoveAll(tmp) defer os.RemoveAll(tmp)
env := append(os.Environ(), "GIT_OBJECT_DIRECTORY="+filepath.Join(repo.Path, "objects")) env := append(os.Environ(), "GIT_OBJECT_DIRECTORY="+filepath.Join(repo.Path, "objects"))
_, err = NewCommandContext(ctx, "init", "--bare").RunInDirWithEnv(tmp, env) _, err = NewCommand(ctx, "init", "--bare").RunInDirWithEnv(tmp, env)
if err != nil { if err != nil {
return err return err
} }
_, err = NewCommandContext(ctx, "reset", "--soft", commit).RunInDirWithEnv(tmp, env) _, err = NewCommand(ctx, "reset", "--soft", commit).RunInDirWithEnv(tmp, env)
if err != nil { if err != nil {
return err return err
} }
_, err = NewCommandContext(ctx, "branch", "-m", "bundle").RunInDirWithEnv(tmp, env) _, err = NewCommand(ctx, "branch", "-m", "bundle").RunInDirWithEnv(tmp, env)
if err != nil { if err != nil {
return err return err
} }
tmpFile := filepath.Join(tmp, "bundle") tmpFile := filepath.Join(tmp, "bundle")
_, err = NewCommandContext(ctx, "bundle", "create", tmpFile, "bundle", "HEAD").RunInDirWithEnv(tmp, env) _, err = NewCommand(ctx, "bundle", "create", tmpFile, "bundle", "HEAD").RunInDirWithEnv(tmp, env)
if err != nil { if err != nil {
return err return err
} }

View file

@ -57,7 +57,7 @@ func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, t
) )
var stderr strings.Builder var stderr strings.Builder
err := NewCommandContext(ctx, args...).RunInDirPipeline(repo.Path, target, &stderr) err := NewCommand(ctx, args...).RunInDirPipeline(repo.Path, target, &stderr)
if err != nil { if err != nil {
return ConcatenateError(err, stderr.String()) return ConcatenateError(err, stderr.String())
} }

View file

@ -74,7 +74,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[
} }
} }
cmd := NewCommandContext(repo.Ctx, cmdArgs...) cmd := NewCommand(repo.Ctx, cmdArgs...)
if err := cmd.RunInDirTimeoutEnvPipeline(env, -1, repo.Path, stdOut, stdErr); err != nil { if err := cmd.RunInDirTimeoutEnvPipeline(env, -1, repo.Path, stdOut, stdErr); err != nil {
return nil, fmt.Errorf("failed to run check-attr: %v\n%s\n%s", err, stdOut.String(), stdErr.String()) return nil, fmt.Errorf("failed to run check-attr: %v\n%s\n%s", err, stdOut.String(), stdErr.String())
@ -152,7 +152,7 @@ func (c *CheckAttributeReader) Init(ctx context.Context) error {
cmdArgs = append(cmdArgs, "--") cmdArgs = append(cmdArgs, "--")
c.ctx, c.cancel = context.WithCancel(ctx) c.ctx, c.cancel = context.WithCancel(ctx)
c.cmd = NewCommandContext(c.ctx, cmdArgs...) c.cmd = NewCommand(c.ctx, cmdArgs...)
var err error var err error

View file

@ -8,12 +8,12 @@ import "fmt"
// FileBlame return the Blame object of file // FileBlame return the Blame object of file
func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) {
return NewCommandContext(repo.Ctx, "blame", "--root", "--", file).RunInDirBytes(path) return NewCommand(repo.Ctx, "blame", "--root", "--", file).RunInDirBytes(path)
} }
// LineBlame returns the latest commit at the given line // LineBlame returns the latest commit at the given line
func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) {
res, err := NewCommandContext(repo.Ctx, "blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) res, err := NewCommand(repo.Ctx, "blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -24,7 +24,7 @@ const PullRequestPrefix = "refs/for/"
// IsReferenceExist returns true if given reference exists in the repository. // IsReferenceExist returns true if given reference exists in the repository.
func IsReferenceExist(ctx context.Context, repoPath, name string) bool { func IsReferenceExist(ctx context.Context, repoPath, name string) bool {
_, err := NewCommandContext(ctx, "show-ref", "--verify", "--", name).RunInDir(repoPath) _, err := NewCommand(ctx, "show-ref", "--verify", "--", name).RunInDir(repoPath)
return err == nil return err == nil
} }
@ -46,7 +46,7 @@ func (repo *Repository) GetHEADBranch() (*Branch, error) {
if repo == nil { if repo == nil {
return nil, fmt.Errorf("nil repo") return nil, fmt.Errorf("nil repo")
} }
stdout, err := NewCommandContext(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -65,13 +65,13 @@ func (repo *Repository) GetHEADBranch() (*Branch, error) {
// SetDefaultBranch sets default branch of repository. // SetDefaultBranch sets default branch of repository.
func (repo *Repository) SetDefaultBranch(name string) error { func (repo *Repository) SetDefaultBranch(name string) error {
_, err := NewCommandContext(repo.Ctx, "symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path)
return err return err
} }
// GetDefaultBranch gets default branch of repository. // GetDefaultBranch gets default branch of repository.
func (repo *Repository) GetDefaultBranch() (string, error) { func (repo *Repository) GetDefaultBranch() (string, error) {
return NewCommandContext(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path) return NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path)
} }
// GetBranch returns a branch by it's name // GetBranch returns a branch by it's name
@ -124,7 +124,7 @@ type DeleteBranchOptions struct {
// DeleteBranch delete a branch by name on repository. // DeleteBranch delete a branch by name on repository.
func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error { func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error {
cmd := NewCommandContext(repo.Ctx, "branch") cmd := NewCommand(repo.Ctx, "branch")
if opts.Force { if opts.Force {
cmd.AddArguments("-D") cmd.AddArguments("-D")
@ -140,7 +140,7 @@ func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) erro
// CreateBranch create a new branch // CreateBranch create a new branch
func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error { func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error {
cmd := NewCommandContext(repo.Ctx, "branch") cmd := NewCommand(repo.Ctx, "branch")
cmd.AddArguments("--", branch, oldbranchOrCommit) cmd.AddArguments("--", branch, oldbranchOrCommit)
_, err := cmd.RunInDir(repo.Path) _, err := cmd.RunInDir(repo.Path)
@ -150,7 +150,7 @@ func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error {
// AddRemote adds a new remote to repository. // AddRemote adds a new remote to repository.
func (repo *Repository) AddRemote(name, url string, fetch bool) error { func (repo *Repository) AddRemote(name, url string, fetch bool) error {
cmd := NewCommandContext(repo.Ctx, "remote", "add") cmd := NewCommand(repo.Ctx, "remote", "add")
if fetch { if fetch {
cmd.AddArguments("-f") cmd.AddArguments("-f")
} }
@ -162,7 +162,7 @@ func (repo *Repository) AddRemote(name, url string, fetch bool) error {
// RemoveRemote removes a remote from repository. // RemoveRemote removes a remote from repository.
func (repo *Repository) RemoveRemote(name string) error { func (repo *Repository) RemoveRemote(name string) error {
_, err := NewCommandContext(repo.Ctx, "remote", "rm", name).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "remote", "rm", name).RunInDir(repo.Path)
return err return err
} }
@ -173,6 +173,6 @@ func (branch *Branch) GetCommit() (*Commit, error) {
// RenameBranch rename a branch // RenameBranch rename a branch
func (repo *Repository) RenameBranch(from, to string) error { func (repo *Repository) RenameBranch(from, to string) error {
_, err := NewCommandContext(repo.Ctx, "branch", "-m", from, to).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "branch", "-m", from, to).RunInDir(repo.Path)
return err return err
} }

View file

@ -96,7 +96,7 @@ func walkShowRef(ctx context.Context, repoPath, arg string, skip, limit int, wal
if arg != "" { if arg != "" {
args = append(args, arg) args = append(args, arg)
} }
err := NewCommandContext(ctx, args...).RunInDirPipeline(repoPath, stdoutWriter, stderrBuilder) err := NewCommand(ctx, args...).RunInDirPipeline(repoPath, stdoutWriter, stderrBuilder)
if err != nil { if err != nil {
if stderrBuilder.Len() == 0 { if stderrBuilder.Len() == 0 {
_ = stdoutWriter.Close() _ = stdoutWriter.Close()

View file

@ -58,7 +58,7 @@ func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit,
relpath = `\` + relpath relpath = `\` + relpath
} }
stdout, err := NewCommandContext(repo.Ctx, "log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -73,7 +73,7 @@ func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit,
// GetCommitByPath returns the last commit of relative path. // GetCommitByPath returns the last commit of relative path.
func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
stdout, err := NewCommandContext(repo.Ctx, "log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path) stdout, err := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -86,7 +86,7 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
} }
func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) { func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) {
stdout, err := NewCommandContext(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize), stdout, err := NewCommand(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize),
"--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path) "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
@ -96,7 +96,7 @@ func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit,
func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Commit, error) { func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Commit, error) {
// create new git log command with limit of 100 commis // create new git log command with limit of 100 commis
cmd := NewCommandContext(repo.Ctx, "log", id.String(), "-100", prettyLogFormat) cmd := NewCommand(repo.Ctx, "log", id.String(), "-100", prettyLogFormat)
// ignore case // ignore case
args := []string{"-i"} args := []string{"-i"}
@ -154,7 +154,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co
// ignore anything below 4 characters as too unspecific // ignore anything below 4 characters as too unspecific
if len(v) >= 4 { if len(v) >= 4 {
// create new git log command with 1 commit limit // create new git log command with 1 commit limit
hashCmd := NewCommandContext(repo.Ctx, "log", "-1", prettyLogFormat) hashCmd := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat)
// add previous arguments except for --grep and --all // add previous arguments except for --grep and --all
hashCmd.AddArguments(args...) hashCmd.AddArguments(args...)
// add keyword as <commit> // add keyword as <commit>
@ -175,7 +175,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co
} }
func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) { func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
stdout, err := NewCommandContext(repo.Ctx, "diff", "--name-only", id1, id2).RunInDirBytes(repo.Path) stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -185,7 +185,7 @@ func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
// FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2 // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
// You must ensure that id1 and id2 are valid commit ids. // You must ensure that id1 and id2 are valid commit ids.
func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) { func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
stdout, err := NewCommandContext(repo.Ctx, "diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path) stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -208,7 +208,7 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
}() }()
go func() { go func() {
stderr := strings.Builder{} stderr := strings.Builder{}
err := NewCommandContext(repo.Ctx, "log", revision, "--follow", err := NewCommand(repo.Ctx, "log", revision, "--follow",
"--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize*page), "--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize*page),
prettyLogFormat, "--", file). prettyLogFormat, "--", file).
RunInDirPipeline(repo.Path, stdoutWriter, &stderr) RunInDirPipeline(repo.Path, stdoutWriter, &stderr)
@ -239,7 +239,7 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
// CommitsByFileAndRangeNoFollow return the commits according revision file and the page // CommitsByFileAndRangeNoFollow return the commits according revision file and the page
func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) ([]*Commit, error) { func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) ([]*Commit, error) {
stdout, err := NewCommandContext(repo.Ctx, "log", revision, "--skip="+strconv.Itoa((page-1)*50), stdout, err := NewCommand(repo.Ctx, "log", revision, "--skip="+strconv.Itoa((page-1)*50),
"--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path) "--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
@ -249,11 +249,11 @@ func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, pag
// FilesCountBetween return the number of files changed between two commits // FilesCountBetween return the number of files changed between two commits
func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
stdout, err := NewCommandContext(repo.Ctx, "diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
if err != nil && strings.Contains(err.Error(), "no merge base") { if err != nil && strings.Contains(err.Error(), "no merge base") {
// git >= 2.28 now returns an error if startCommitID and endCommitID have become unrelated. // 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... // previously it would return the results of git diff --name-only startCommitID endCommitID so let's try that...
stdout, err = NewCommandContext(repo.Ctx, "diff", "--name-only", startCommitID, endCommitID).RunInDir(repo.Path) stdout, err = NewCommand(repo.Ctx, "diff", "--name-only", startCommitID, endCommitID).RunInDir(repo.Path)
} }
if err != nil { if err != nil {
return 0, err return 0, err
@ -267,13 +267,13 @@ func (repo *Repository) CommitsBetween(last, before *Commit) ([]*Commit, error)
var stdout []byte var stdout []byte
var err error var err error
if before == nil { if before == nil {
stdout, err = NewCommandContext(repo.Ctx, "rev-list", last.ID.String()).RunInDirBytes(repo.Path) stdout, err = NewCommand(repo.Ctx, "rev-list", last.ID.String()).RunInDirBytes(repo.Path)
} else { } else {
stdout, err = NewCommandContext(repo.Ctx, "rev-list", before.ID.String()+".."+last.ID.String()).RunInDirBytes(repo.Path) stdout, err = NewCommand(repo.Ctx, "rev-list", before.ID.String()+".."+last.ID.String()).RunInDirBytes(repo.Path)
if err != nil && strings.Contains(err.Error(), "no merge base") { if err != nil && strings.Contains(err.Error(), "no merge base") {
// future versions of git >= 2.28 are likely to return an error if before and last have become unrelated. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
// previously it would return the results of git rev-list before last so let's try that... // previously it would return the results of git rev-list before last so let's try that...
stdout, err = NewCommandContext(repo.Ctx, "rev-list", before.ID.String(), last.ID.String()).RunInDirBytes(repo.Path) stdout, err = NewCommand(repo.Ctx, "rev-list", before.ID.String(), last.ID.String()).RunInDirBytes(repo.Path)
} }
} }
if err != nil { if err != nil {
@ -287,13 +287,13 @@ func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip in
var stdout []byte var stdout []byte
var err error var err error
if before == nil { if before == nil {
stdout, err = NewCommandContext(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), last.ID.String()).RunInDirBytes(repo.Path) stdout, err = NewCommand(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), last.ID.String()).RunInDirBytes(repo.Path)
} else { } else {
stdout, err = NewCommandContext(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String()+".."+last.ID.String()).RunInDirBytes(repo.Path) stdout, err = NewCommand(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String()+".."+last.ID.String()).RunInDirBytes(repo.Path)
if err != nil && strings.Contains(err.Error(), "no merge base") { if err != nil && strings.Contains(err.Error(), "no merge base") {
// future versions of git >= 2.28 are likely to return an error if before and last have become unrelated. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
// previously it would return the results of git rev-list --max-count n before last so let's try that... // previously it would return the results of git rev-list --max-count n before last so let's try that...
stdout, err = NewCommandContext(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String(), last.ID.String()).RunInDirBytes(repo.Path) stdout, err = NewCommand(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String(), last.ID.String()).RunInDirBytes(repo.Path)
} }
} }
if err != nil { if err != nil {
@ -332,7 +332,7 @@ func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
// commitsBefore the limit is depth, not total number of returned commits. // commitsBefore the limit is depth, not total number of returned commits.
func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) { func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) {
cmd := NewCommandContext(repo.Ctx, "log") cmd := NewCommand(repo.Ctx, "log")
if limit > 0 { if limit > 0 {
cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String()) cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
} else { } else {
@ -376,7 +376,7 @@ func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) ([]*Commit, erro
func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
if CheckGitVersionAtLeast("2.7.0") == nil { if CheckGitVersionAtLeast("2.7.0") == nil {
stdout, err := NewCommandContext(repo.Ctx, "for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -385,7 +385,7 @@ func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error)
return branches, nil return branches, nil
} }
stdout, err := NewCommandContext(repo.Ctx, "branch", "--contains", commit.ID.String()).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -424,7 +424,7 @@ func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit {
// IsCommitInBranch check if the commit is on the branch // IsCommitInBranch check if the commit is on the branch
func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) { func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) {
stdout, err := NewCommandContext(repo.Ctx, "branch", "--contains", commitID, branch).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "branch", "--contains", commitID, branch).RunInDir(repo.Path)
if err != nil { if err != nil {
return false, err return false, err
} }

View file

@ -50,7 +50,7 @@ func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) {
} }
} }
actualCommitID, err := NewCommandContext(repo.Ctx, "rev-parse", "--verify", commitID).RunInDir(repo.Path) actualCommitID, err := NewCommand(repo.Ctx, "rev-parse", "--verify", commitID).RunInDir(repo.Path)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "unknown revision or path") || if strings.Contains(err.Error(), "unknown revision or path") ||
strings.Contains(err.Error(), "fatal: Needed a single revision") { strings.Contains(err.Error(), "fatal: Needed a single revision") {

View file

@ -18,7 +18,7 @@ import (
// ResolveReference resolves a name to a reference // ResolveReference resolves a name to a reference
func (repo *Repository) ResolveReference(name string) (string, error) { func (repo *Repository) ResolveReference(name string) (string, error) {
stdout, err := NewCommandContext(repo.Ctx, "show-ref", "--hash", name).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "show-ref", "--hash", name).RunInDir(repo.Path)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "not a valid ref") { if strings.Contains(err.Error(), "not a valid ref") {
return "", ErrNotExist{name, ""} return "", ErrNotExist{name, ""}
@ -51,19 +51,19 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) {
// SetReference sets the commit ID string of given reference (e.g. branch or tag). // SetReference sets the commit ID string of given reference (e.g. branch or tag).
func (repo *Repository) SetReference(name, commitID string) error { func (repo *Repository) SetReference(name, commitID string) error {
_, err := NewCommandContext(repo.Ctx, "update-ref", name, commitID).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "update-ref", name, commitID).RunInDir(repo.Path)
return err return err
} }
// RemoveReference removes the given reference (e.g. branch or tag). // RemoveReference removes the given reference (e.g. branch or tag).
func (repo *Repository) RemoveReference(name string) error { func (repo *Repository) RemoveReference(name string) error {
_, err := NewCommandContext(repo.Ctx, "update-ref", "--no-deref", "-d", name).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d", name).RunInDir(repo.Path)
return err return err
} }
// IsCommitExist returns true if given commit exists in current repository. // IsCommitExist returns true if given commit exists in current repository.
func (repo *Repository) IsCommitExist(name string) bool { func (repo *Repository) IsCommitExist(name string) bool {
_, err := NewCommandContext(repo.Ctx, "cat-file", "-e", name).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "cat-file", "-e", name).RunInDir(repo.Path)
return err == nil return err == nil
} }

View file

@ -40,13 +40,13 @@ func (repo *Repository) GetMergeBase(tmpRemote, base, head string) (string, stri
if tmpRemote != "origin" { if tmpRemote != "origin" {
tmpBaseName := RemotePrefix + tmpRemote + "/tmp_" + base tmpBaseName := RemotePrefix + tmpRemote + "/tmp_" + base
// Fetch commit into a temporary branch in order to be able to handle commits and tags // Fetch commit into a temporary branch in order to be able to handle commits and tags
_, err := NewCommandContext(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunInDir(repo.Path)
if err == nil { if err == nil {
base = tmpBaseName base = tmpBaseName
} }
} }
stdout, err := NewCommandContext(repo.Ctx, "merge-base", "--", base, head).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "merge-base", "--", base, head).RunInDir(repo.Path)
return strings.TrimSpace(stdout), base, err return strings.TrimSpace(stdout), base, err
} }
@ -93,7 +93,7 @@ func (repo *Repository) GetCompareInfo(basePath, baseBranch, headBranch string,
// We have a common base - therefore we know that ... should work // We have a common base - therefore we know that ... should work
if !fileOnly { if !fileOnly {
logs, err := NewCommandContext(repo.Ctx, "log", baseCommitID+separator+headBranch, prettyLogFormat).RunInDirBytes(repo.Path) logs, err := NewCommand(repo.Ctx, "log", baseCommitID+separator+headBranch, prettyLogFormat).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -146,14 +146,14 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
separator = ".." separator = ".."
} }
if err := NewCommandContext(repo.Ctx, "diff", "-z", "--name-only", base+separator+head). if err := NewCommand(repo.Ctx, "diff", "-z", "--name-only", base+separator+head).
RunInDirPipeline(repo.Path, w, stderr); err != nil { RunInDirPipeline(repo.Path, w, stderr); err != nil {
if strings.Contains(stderr.String(), "no merge base") { if strings.Contains(stderr.String(), "no merge base") {
// git >= 2.28 now returns an error if base and head have become unrelated. // git >= 2.28 now returns an error if base and head have become unrelated.
// previously it would return the results of git diff -z --name-only base head so let's try that... // previously it would return the results of git diff -z --name-only base head so let's try that...
w = &lineCountWriter{} w = &lineCountWriter{}
stderr.Reset() stderr.Reset()
if err = NewCommandContext(repo.Ctx, "diff", "-z", "--name-only", base, head).RunInDirPipeline(repo.Path, w, stderr); err == nil { if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only", base, head).RunInDirPipeline(repo.Path, w, stderr); err == nil {
return w.numLines, nil return w.numLines, nil
} }
} }
@ -182,7 +182,7 @@ func GetDiffShortStat(ctx context.Context, repoPath string, args ...string) (num
"--shortstat", "--shortstat",
}, args...) }, args...)
stdout, err := NewCommandContext(ctx, args...).RunInDir(repoPath) stdout, err := NewCommand(ctx, args...).RunInDir(repoPath)
if err != nil { if err != nil {
return 0, 0, 0, err return 0, 0, 0, err
} }
@ -238,27 +238,27 @@ func (repo *Repository) GetDiffOrPatch(base, head string, w io.Writer, patch, bi
// GetDiff generates and returns patch data between given revisions, optimized for human readability // GetDiff generates and returns patch data between given revisions, optimized for human readability
func (repo *Repository) GetDiff(base, head string, w io.Writer) error { func (repo *Repository) GetDiff(base, head string, w io.Writer) error {
return NewCommandContext(repo.Ctx, "diff", "-p", base, head). return NewCommand(repo.Ctx, "diff", "-p", base, head).
RunInDirPipeline(repo.Path, w, nil) RunInDirPipeline(repo.Path, w, nil)
} }
// GetDiffBinary generates and returns patch data between given revisions, including binary diffs. // GetDiffBinary generates and returns patch data between given revisions, including binary diffs.
func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error { func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error {
if CheckGitVersionAtLeast("1.7.7") == nil { if CheckGitVersionAtLeast("1.7.7") == nil {
return NewCommandContext(repo.Ctx, "diff", "-p", "--binary", "--histogram", base, head). return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram", base, head).
RunInDirPipeline(repo.Path, w, nil) RunInDirPipeline(repo.Path, w, nil)
} }
return NewCommandContext(repo.Ctx, "diff", "-p", "--binary", "--patience", base, head). return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--patience", base, head).
RunInDirPipeline(repo.Path, w, nil) RunInDirPipeline(repo.Path, w, nil)
} }
// GetPatch generates and returns format-patch data between given revisions, able to be used with `git apply` // GetPatch generates and returns format-patch data between given revisions, able to be used with `git apply`
func (repo *Repository) GetPatch(base, head string, w io.Writer) error { func (repo *Repository) GetPatch(base, head string, w io.Writer) error {
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
err := NewCommandContext(repo.Ctx, "format-patch", "--binary", "--stdout", base+"..."+head). err := NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout", base+"..."+head).
RunInDirPipeline(repo.Path, w, stderr) RunInDirPipeline(repo.Path, w, stderr)
if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) { if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) {
return NewCommandContext(repo.Ctx, "format-patch", "--binary", "--stdout", base, head). return NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout", base, head).
RunInDirPipeline(repo.Path, w, nil) RunInDirPipeline(repo.Path, w, nil)
} }
return err return err
@ -267,7 +267,7 @@ func (repo *Repository) GetPatch(base, head string, w io.Writer) error {
// GetDiffFromMergeBase generates and return patch data from merge base to head // GetDiffFromMergeBase generates and return patch data from merge base to head
func (repo *Repository) GetDiffFromMergeBase(base, head string, w io.Writer) error { func (repo *Repository) GetDiffFromMergeBase(base, head string, w io.Writer) error {
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
err := NewCommandContext(repo.Ctx, "diff", "-p", "--binary", base+"..."+head). err := NewCommand(repo.Ctx, "diff", "-p", "--binary", base+"..."+head).
RunInDirPipeline(repo.Path, w, stderr) RunInDirPipeline(repo.Path, w, stderr)
if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) { if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) {
return repo.GetDiffBinary(base, head, w) return repo.GetDiffBinary(base, head, w)

View file

@ -34,7 +34,7 @@ func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings,
Sign: true, Sign: true,
} }
value, _ := NewCommandContext(repo.Ctx, "config", "--get", "commit.gpgsign").RunInDir(repo.Path) value, _ := NewCommand(repo.Ctx, "config", "--get", "commit.gpgsign").RunInDir(repo.Path)
sign, valid := ParseBool(strings.TrimSpace(value)) sign, valid := ParseBool(strings.TrimSpace(value))
if !sign || !valid { if !sign || !valid {
gpgSettings.Sign = false gpgSettings.Sign = false
@ -42,13 +42,13 @@ func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings,
return gpgSettings, nil return gpgSettings, nil
} }
signingKey, _ := NewCommandContext(repo.Ctx, "config", "--get", "user.signingkey").RunInDir(repo.Path) signingKey, _ := NewCommand(repo.Ctx, "config", "--get", "user.signingkey").RunInDir(repo.Path)
gpgSettings.KeyID = strings.TrimSpace(signingKey) gpgSettings.KeyID = strings.TrimSpace(signingKey)
defaultEmail, _ := NewCommandContext(repo.Ctx, "config", "--get", "user.email").RunInDir(repo.Path) defaultEmail, _ := NewCommand(repo.Ctx, "config", "--get", "user.email").RunInDir(repo.Path)
gpgSettings.Email = strings.TrimSpace(defaultEmail) gpgSettings.Email = strings.TrimSpace(defaultEmail)
defaultName, _ := NewCommandContext(repo.Ctx, "config", "--get", "user.name").RunInDir(repo.Path) defaultName, _ := NewCommand(repo.Ctx, "config", "--get", "user.name").RunInDir(repo.Path)
gpgSettings.Name = strings.TrimSpace(defaultName) gpgSettings.Name = strings.TrimSpace(defaultName)
if err := gpgSettings.LoadPublicKeyContent(); err != nil { if err := gpgSettings.LoadPublicKeyContent(); err != nil {

View file

@ -18,7 +18,7 @@ import (
// ReadTreeToIndex reads a treeish to the index // ReadTreeToIndex reads a treeish to the index
func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error { func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error {
if len(treeish) != 40 { if len(treeish) != 40 {
res, err := NewCommandContext(repo.Ctx, "rev-parse", "--verify", treeish).RunInDir(repo.Path) res, err := NewCommand(repo.Ctx, "rev-parse", "--verify", treeish).RunInDir(repo.Path)
if err != nil { if err != nil {
return err return err
} }
@ -38,7 +38,7 @@ func (repo *Repository) readTreeToIndex(id SHA1, indexFilename ...string) error
if len(indexFilename) > 0 { if len(indexFilename) > 0 {
env = append(os.Environ(), "GIT_INDEX_FILE="+indexFilename[0]) env = append(os.Environ(), "GIT_INDEX_FILE="+indexFilename[0])
} }
_, err := NewCommandContext(repo.Ctx, "read-tree", id.String()).RunInDirWithEnv(repo.Path, env) _, err := NewCommand(repo.Ctx, "read-tree", id.String()).RunInDirWithEnv(repo.Path, env)
if err != nil { if err != nil {
return err return err
} }
@ -69,13 +69,13 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename, tmpD
// EmptyIndex empties the index // EmptyIndex empties the index
func (repo *Repository) EmptyIndex() error { func (repo *Repository) EmptyIndex() error {
_, err := NewCommandContext(repo.Ctx, "read-tree", "--empty").RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "read-tree", "--empty").RunInDir(repo.Path)
return err return err
} }
// LsFiles checks if the given filenames are in the index // LsFiles checks if the given filenames are in the index
func (repo *Repository) LsFiles(filenames ...string) ([]string, error) { func (repo *Repository) LsFiles(filenames ...string) ([]string, error) {
cmd := NewCommandContext(repo.Ctx, "ls-files", "-z", "--") cmd := NewCommand(repo.Ctx, "ls-files", "-z", "--")
for _, arg := range filenames { for _, arg := range filenames {
if arg != "" { if arg != "" {
cmd.AddArguments(arg) cmd.AddArguments(arg)
@ -95,7 +95,7 @@ func (repo *Repository) LsFiles(filenames ...string) ([]string, error) {
// RemoveFilesFromIndex removes given filenames from the index - it does not check whether they are present. // RemoveFilesFromIndex removes given filenames from the index - it does not check whether they are present.
func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error { func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error {
cmd := NewCommandContext(repo.Ctx, "update-index", "--remove", "-z", "--index-info") cmd := NewCommand(repo.Ctx, "update-index", "--remove", "-z", "--index-info")
stdout := new(bytes.Buffer) stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
buffer := new(bytes.Buffer) buffer := new(bytes.Buffer)
@ -111,14 +111,14 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error {
// AddObjectToIndex adds the provided object hash to the index at the provided filename // AddObjectToIndex adds the provided object hash to the index at the provided filename
func (repo *Repository) AddObjectToIndex(mode string, object SHA1, filename string) error { func (repo *Repository) AddObjectToIndex(mode string, object SHA1, filename string) error {
cmd := NewCommandContext(repo.Ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, object.String(), filename) cmd := NewCommand(repo.Ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, object.String(), filename)
_, err := cmd.RunInDir(repo.Path) _, err := cmd.RunInDir(repo.Path)
return err return err
} }
// WriteTree writes the current index as a tree to the object db and returns its hash // WriteTree writes the current index as a tree to the object db and returns its hash
func (repo *Repository) WriteTree() (*Tree, error) { func (repo *Repository) WriteTree() (*Tree, error) {
res, err := NewCommandContext(repo.Ctx, "write-tree").RunInDir(repo.Path) res, err := NewCommand(repo.Ctx, "write-tree").RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -42,7 +42,7 @@ func (repo *Repository) HashObject(reader io.Reader) (SHA1, error) {
} }
func (repo *Repository) hashObject(reader io.Reader) (string, error) { func (repo *Repository) hashObject(reader io.Reader) (string, error) {
cmd := NewCommandContext(repo.Ctx, "hash-object", "-w", "--stdin") cmd := NewCommand(repo.Ctx, "hash-object", "-w", "--stdin")
stdout := new(bytes.Buffer) stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
err := cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, reader) err := cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, reader)

View file

@ -23,7 +23,7 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
go func() { go func() {
stderrBuilder := &strings.Builder{} stderrBuilder := &strings.Builder{}
err := NewCommandContext(repo.Ctx, "for-each-ref").RunInDirPipeline(repo.Path, stdoutWriter, stderrBuilder) err := NewCommand(repo.Ctx, "for-each-ref").RunInDirPipeline(repo.Path, stdoutWriter, stderrBuilder)
if err != nil { if err != nil {
_ = stdoutWriter.CloseWithError(ConcatenateError(err, stderrBuilder.String())) _ = stdoutWriter.CloseWithError(ConcatenateError(err, stderrBuilder.String()))
} else { } else {

View file

@ -39,7 +39,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
since := fromTime.Format(time.RFC3339) since := fromTime.Format(time.RFC3339)
stdout, err := NewCommandContext(repo.Ctx, "rev-list", "--count", "--no-merges", "--branches=*", "--date=iso", fmt.Sprintf("--since='%s'", since)).RunInDirBytes(repo.Path) stdout, err := NewCommand(repo.Ctx, "rev-list", "--count", "--no-merges", "--branches=*", "--date=iso", fmt.Sprintf("--since='%s'", since)).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -67,7 +67,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
} }
stderr := new(strings.Builder) stderr := new(strings.Builder)
err = NewCommandContext(repo.Ctx, args...).RunInDirTimeoutEnvFullPipelineFunc( err = NewCommand(repo.Ctx, args...).RunInDirTimeoutEnvFullPipelineFunc(
nil, -1, repo.Path, nil, -1, repo.Path,
stdoutWriter, stderr, nil, stdoutWriter, stderr, nil,
func(ctx context.Context, cancel context.CancelFunc) error { func(ctx context.Context, cancel context.CancelFunc) error {

View file

@ -24,13 +24,13 @@ func IsTagExist(ctx context.Context, repoPath, name string) bool {
// CreateTag create one tag in the repository // CreateTag create one tag in the repository
func (repo *Repository) CreateTag(name, revision string) error { func (repo *Repository) CreateTag(name, revision string) error {
_, err := NewCommandContext(repo.Ctx, "tag", "--", name, revision).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "tag", "--", name, revision).RunInDir(repo.Path)
return err return err
} }
// CreateAnnotatedTag create one annotated tag in the repository // CreateAnnotatedTag create one annotated tag in the repository
func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error { func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error {
_, err := NewCommandContext(repo.Ctx, "tag", "-a", "-m", message, "--", name, revision).RunInDir(repo.Path) _, err := NewCommand(repo.Ctx, "tag", "-a", "-m", message, "--", name, revision).RunInDir(repo.Path)
return err return err
} }
@ -79,7 +79,7 @@ func (repo *Repository) getTag(tagID SHA1, name string) (*Tag, error) {
} }
// The tag is an annotated tag with a message. // The tag is an annotated tag with a message.
data, err := NewCommandContext(repo.Ctx, "cat-file", "-p", tagID.String()).RunInDirBytes(repo.Path) data, err := NewCommand(repo.Ctx, "cat-file", "-p", tagID.String()).RunInDirBytes(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -103,7 +103,7 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) {
return "", fmt.Errorf("SHA is too short: %s", sha) return "", fmt.Errorf("SHA is too short: %s", sha)
} }
stdout, err := NewCommandContext(repo.Ctx, "show-ref", "--tags", "-d").RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "show-ref", "--tags", "-d").RunInDir(repo.Path)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -126,7 +126,7 @@ 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) // 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) { func (repo *Repository) GetTagID(name string) (string, error) {
stdout, err := NewCommandContext(repo.Ctx, "show-ref", "--tags", "--", name).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "show-ref", "--tags", "--", name).RunInDir(repo.Path)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -162,7 +162,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) {
// GetTagInfos returns all tag infos of the repository. // GetTagInfos returns all tag infos of the repository.
func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) {
// TODO this a slow implementation, makes one git command per tag // TODO this a slow implementation, makes one git command per tag
stdout, err := NewCommandContext(repo.Ctx, "tag").RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "tag").RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
@ -195,7 +195,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) {
// GetTagType gets the type of the tag, either commit (simple) or tag (annotated) // GetTagType gets the type of the tag, either commit (simple) or tag (annotated)
func (repo *Repository) GetTagType(id SHA1) (string, error) { func (repo *Repository) GetTagType(id SHA1) (string, error) {
// Get tag type // Get tag type
stdout, err := NewCommandContext(repo.Ctx, "cat-file", "-t", id.String()).RunInDir(repo.Path) stdout, err := NewCommand(repo.Ctx, "cat-file", "-t", id.String()).RunInDir(repo.Path)
if err != nil { if err != nil {
return "", err return "", err
} }

View file

@ -40,7 +40,7 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt
"GIT_COMMITTER_EMAIL="+committer.Email, "GIT_COMMITTER_EMAIL="+committer.Email,
"GIT_COMMITTER_DATE="+commitTimeStr, "GIT_COMMITTER_DATE="+commitTimeStr,
) )
cmd := NewCommandContext(repo.Ctx, "commit-tree", tree.ID.String()) cmd := NewCommand(repo.Ctx, "commit-tree", tree.ID.String())
for _, parent := range opts.Parents { for _, parent := range opts.Parents {
cmd.AddArguments("-p", parent) cmd.AddArguments("-p", parent)

View file

@ -22,7 +22,7 @@ func (repo *Repository) getTree(id SHA1) (*Tree, error) {
// GetTree find the tree object in the repository. // GetTree find the tree object in the repository.
func (repo *Repository) GetTree(idStr string) (*Tree, error) { func (repo *Repository) GetTree(idStr string) (*Tree, error) {
if len(idStr) != 40 { if len(idStr) != 40 {
res, err := NewCommandContext(repo.Ctx, "rev-parse", "--verify", idStr).RunInDir(repo.Path) res, err := NewCommand(repo.Ctx, "rev-parse", "--verify", idStr).RunInDir(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -49,7 +49,7 @@ func (t *Tree) SubTree(rpath string) (*Tree, error) {
// LsTree checks if the given filenames are in the tree // LsTree checks if the given filenames are in the tree
func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error) { func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error) {
cmd := NewCommandContext(repo.Ctx, "ls-tree", "-z", "--name-only", "--", ref) cmd := NewCommand(repo.Ctx, "ls-tree", "-z", "--name-only", "--", ref)
for _, arg := range filenames { for _, arg := range filenames {
if arg != "" { if arg != "" {
cmd.AddArguments(arg) cmd.AddArguments(arg)

View file

@ -81,7 +81,7 @@ func (t *Tree) ListEntries() (Entries, error) {
} }
} }
stdout, err := NewCommandContext(t.repo.Ctx, "ls-tree", "-l", t.ID.String()).RunInDirBytes(t.repo.Path) stdout, err := NewCommand(t.repo.Ctx, "ls-tree", "-l", t.ID.String()).RunInDirBytes(t.repo.Path)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "fatal: Not a valid object name") || strings.Contains(err.Error(), "fatal: not a tree object") { if strings.Contains(err.Error(), "fatal: Not a valid object name") || strings.Contains(err.Error(), "fatal: not a tree object") {
return nil, ErrNotExist{ return nil, ErrNotExist{
@ -104,7 +104,7 @@ func (t *Tree) ListEntriesRecursive() (Entries, error) {
if t.entriesRecursiveParsed { if t.entriesRecursiveParsed {
return t.entriesRecursive, nil return t.entriesRecursive, nil
} }
stdout, err := NewCommandContext(t.repo.Ctx, "ls-tree", "-t", "-l", "-r", t.ID.String()).RunInDirBytes(t.repo.Path) stdout, err := NewCommand(t.repo.Ctx, "ls-tree", "-t", "-l", "-r", t.ID.String()).RunInDirBytes(t.repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -51,7 +51,7 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo
args = append(args, files...) args = append(args, files...)
} }
graphCmd := git.NewCommandContext(r.Ctx, "log") graphCmd := git.NewCommand(r.Ctx, "log")
graphCmd.AddArguments(args...) graphCmd.AddArguments(args...)
graph := NewGraph() graph := NewGraph()

View file

@ -191,7 +191,7 @@ func (b *BleveIndexer) addUpdate(ctx context.Context, batchWriter git.WriteClose
size := update.Size size := update.Size
if !update.Sized { if !update.Sized {
stdout, err := git.NewCommandContext(ctx, "cat-file", "-s", update.BlobSha). stdout, err := git.NewCommand(ctx, "cat-file", "-s", update.BlobSha).
RunInDir(repo.RepoPath()) RunInDir(repo.RepoPath())
if err != nil { if err != nil {
return err return err

View file

@ -222,7 +222,7 @@ func (b *ElasticSearchIndexer) addUpdate(ctx context.Context, batchWriter git.Wr
size := update.Size size := update.Size
if !update.Sized { if !update.Sized {
stdout, err := git.NewCommandContext(ctx, "cat-file", "-s", update.BlobSha). stdout, err := git.NewCommand(ctx, "cat-file", "-s", update.BlobSha).
RunInDir(repo.RepoPath()) RunInDir(repo.RepoPath())
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -29,7 +29,7 @@ type repoChanges struct {
} }
func getDefaultBranchSha(ctx context.Context, repo *repo_model.Repository) (string, error) { func getDefaultBranchSha(ctx context.Context, repo *repo_model.Repository) (string, error) {
stdout, err := git.NewCommandContext(ctx, "show-ref", "-s", git.BranchPrefix+repo.DefaultBranch).RunInDir(repo.RepoPath()) stdout, err := git.NewCommand(ctx, "show-ref", "-s", git.BranchPrefix+repo.DefaultBranch).RunInDir(repo.RepoPath())
if err != nil { if err != nil {
return "", err return "", err
} }
@ -92,7 +92,7 @@ func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) {
// genesisChanges get changes to add repo to the indexer for the first time // genesisChanges get changes to add repo to the indexer for the first time
func genesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) { func genesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) {
var changes repoChanges var changes repoChanges
stdout, err := git.NewCommandContext(ctx, "ls-tree", "--full-tree", "-l", "-r", revision). stdout, err := git.NewCommand(ctx, "ls-tree", "--full-tree", "-l", "-r", revision).
RunInDirBytes(repo.RepoPath()) RunInDirBytes(repo.RepoPath())
if err != nil { if err != nil {
return nil, err return nil, err
@ -103,7 +103,7 @@ func genesisChanges(ctx context.Context, repo *repo_model.Repository, revision s
// nonGenesisChanges get changes since the previous indexer update // nonGenesisChanges get changes since the previous indexer update
func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) { func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) {
diffCmd := git.NewCommandContext(ctx, "diff", "--name-status", diffCmd := git.NewCommand(ctx, "diff", "--name-status",
repo.CodeIndexerStatus.CommitSha, revision) repo.CodeIndexerStatus.CommitSha, revision)
stdout, err := diffCmd.RunInDir(repo.RepoPath()) stdout, err := diffCmd.RunInDir(repo.RepoPath())
if err != nil { if err != nil {
@ -167,7 +167,7 @@ func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revisio
} }
} }
cmd := git.NewCommandContext(ctx, "ls-tree", "--full-tree", "-l", revision, "--") cmd := git.NewCommand(ctx, "ls-tree", "--full-tree", "-l", revision, "--")
cmd.AddArguments(updatedFilenames...) cmd.AddArguments(updatedFilenames...)
lsTreeStdout, err := cmd.RunInDirBytes(repo.RepoPath()) lsTreeStdout, err := cmd.RunInDirBytes(repo.RepoPath())
if err != nil { if err != nil {

View file

@ -111,7 +111,7 @@ func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (
return fmt.Errorf("checkDaemonExportOK: %v", err) return fmt.Errorf("checkDaemonExportOK: %v", err)
} }
if stdout, err := git.NewCommandContext(ctx, "update-server-info"). if stdout, err := git.NewCommand(ctx, "update-server-info").
SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)). SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)).
RunInDir(repoPath); err != nil { RunInDir(repoPath); err != nil {
log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err) log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err)

View file

@ -177,7 +177,7 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *r
} }
repoPath := repo.RepoPath() repoPath := repo.RepoPath()
if stdout, err := git.NewCommandContext(ctx, "remote", "add", "origin", repoPath). if stdout, err := git.NewCommand(ctx, "remote", "add", "origin", repoPath).
SetDescription(fmt.Sprintf("generateRepoCommit (git remote add): %s to %s", templateRepoPath, tmpDir)). SetDescription(fmt.Sprintf("generateRepoCommit (git remote add): %s to %s", templateRepoPath, tmpDir)).
RunInDirWithEnv(tmpDir, env); err != nil { RunInDirWithEnv(tmpDir, env); err != nil {
log.Error("Unable to add %v as remote origin to temporary repo to %s: stdout %s\nError: %v", repo, tmpDir, stdout, err) log.Error("Unable to add %v as remote origin to temporary repo to %s: stdout %s\nError: %v", repo, tmpDir, stdout, err)
@ -281,7 +281,7 @@ func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templ
return generateRepo, fmt.Errorf("checkDaemonExportOK: %v", err) return generateRepo, fmt.Errorf("checkDaemonExportOK: %v", err)
} }
if stdout, err := git.NewCommandContext(ctx, "update-server-info"). if stdout, err := git.NewCommand(ctx, "update-server-info").
SetDescription(fmt.Sprintf("GenerateRepository(git update-server-info): %s", repoPath)). SetDescription(fmt.Sprintf("GenerateRepository(git update-server-info): %s", repoPath)).
RunInDir(repoPath); err != nil { RunInDir(repoPath); err != nil {
log.Error("GenerateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", generateRepo, stdout, err) log.Error("GenerateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", generateRepo, stdout, err)

View file

@ -40,7 +40,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,
) )
// Clone to temporary path and do the init commit. // Clone to temporary path and do the init commit.
if stdout, err := git.NewCommandContext(ctx, "clone", repoPath, tmpDir). if stdout, err := git.NewCommand(ctx, "clone", repoPath, tmpDir).
SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)). SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)).
RunInDirWithEnv("", env); err != nil { RunInDirWithEnv("", env); err != nil {
log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err) log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err)
@ -117,7 +117,7 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi
committerName := sig.Name committerName := sig.Name
committerEmail := sig.Email committerEmail := sig.Email
if stdout, err := git.NewCommandContext(ctx, "add", "--all"). if stdout, err := git.NewCommand(ctx, "add", "--all").
SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)). SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
RunInDir(tmpPath); err != nil { RunInDir(tmpPath); err != nil {
log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err) log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
@ -154,7 +154,7 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi
"GIT_COMMITTER_EMAIL="+committerEmail, "GIT_COMMITTER_EMAIL="+committerEmail,
) )
if stdout, err := git.NewCommandContext(ctx, args...). if stdout, err := git.NewCommand(ctx, args...).
SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)). SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
RunInDirWithEnv(tmpPath, env); err != nil { RunInDirWithEnv(tmpPath, env); err != nil {
log.Error("Failed to commit: %v: Stdout: %s\nError: %v", args, stdout, err) log.Error("Failed to commit: %v: Stdout: %s\nError: %v", args, stdout, err)
@ -165,7 +165,7 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi
defaultBranch = setting.Repository.DefaultBranch defaultBranch = setting.Repository.DefaultBranch
} }
if stdout, err := git.NewCommandContext(ctx, "push", "origin", "HEAD:"+defaultBranch). if stdout, err := git.NewCommand(ctx, "push", "origin", "HEAD:"+defaultBranch).
SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)). SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
RunInDirWithEnv(tmpPath, models.InternalPushingEnvironment(u, repo)); err != nil { RunInDirWithEnv(tmpPath, models.InternalPushingEnvironment(u, repo)); err != nil {
log.Error("Failed to push back to HEAD: Stdout: %s\nError: %v", stdout, err) log.Error("Failed to push back to HEAD: Stdout: %s\nError: %v", stdout, err)

View file

@ -104,7 +104,7 @@ func IsForcePush(ctx context.Context, opts *PushUpdateOptions) (bool, error) {
return false, nil return false, nil
} }
output, err := git.NewCommandContext(ctx, "rev-list", "--max-count=1", opts.OldCommitID, "^"+opts.NewCommitID). output, err := git.NewCommand(ctx, "rev-list", "--max-count=1", opts.OldCommitID, "^"+opts.NewCommitID).
RunInDir(repo_model.RepoPath(opts.RepoUserName, opts.RepoName)) RunInDir(repo_model.RepoPath(opts.RepoUserName, opts.RepoName))
if err != nil { if err != nil {
return false, err return false, err

View file

@ -109,7 +109,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User,
return repo, fmt.Errorf("checkDaemonExportOK: %v", err) return repo, fmt.Errorf("checkDaemonExportOK: %v", err)
} }
if stdout, err := git.NewCommandContext(ctx, "update-server-info"). if stdout, err := git.NewCommand(ctx, "update-server-info").
SetDescription(fmt.Sprintf("MigrateRepositoryGitData(git update-server-info): %s", repoPath)). SetDescription(fmt.Sprintf("MigrateRepositoryGitData(git update-server-info): %s", repoPath)).
RunInDir(repoPath); err != nil { RunInDir(repoPath); err != nil {
log.Error("MigrateRepositoryGitData(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err) log.Error("MigrateRepositoryGitData(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err)
@ -228,7 +228,7 @@ func CleanUpMigrateInfo(ctx context.Context, repo *repo_model.Repository) (*repo
} }
} }
_, err := git.NewCommandContext(ctx, "remote", "rm", "origin").RunInDir(repoPath) _, err := git.NewCommand(ctx, "remote", "rm", "origin").RunInDir(repoPath)
if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err) return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err)
} }

View file

@ -183,7 +183,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN
// 2. Disallow force pushes to protected branches // 2. Disallow force pushes to protected branches
if git.EmptySHA != oldCommitID { if git.EmptySHA != oldCommitID {
output, err := git.NewCommandContext(ctx, "rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), ctx.env) output, err := git.NewCommand(ctx, "rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), ctx.env)
if err != nil { if err != nil {
log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err) log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{

View file

@ -44,7 +44,7 @@ func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env []
}() }()
// This is safe as force pushes are already forbidden // This is safe as force pushes are already forbidden
err = git.NewCommandContext(repo.Ctx, "rev-list", oldCommitID+"..."+newCommitID). err = git.NewCommand(repo.Ctx, "rev-list", oldCommitID+"..."+newCommitID).
RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path, RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
stdoutWriter, nil, nil, stdoutWriter, nil, nil,
func(ctx context.Context, cancel context.CancelFunc) error { func(ctx context.Context, cancel context.CancelFunc) error {
@ -88,7 +88,7 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
}() }()
hash := git.MustIDFromString(sha) hash := git.MustIDFromString(sha)
return git.NewCommandContext(repo.Ctx, "cat-file", "commit", sha). return git.NewCommand(repo.Ctx, "cat-file", "commit", sha).
RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path, RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
stdoutWriter, nil, nil, stdoutWriter, nil, nil,
func(ctx context.Context, cancel context.CancelFunc) error { func(ctx context.Context, cancel context.CancelFunc) error {

View file

@ -328,7 +328,7 @@ func dummyInfoRefs(ctx *context.Context) {
return return
} }
refs, err := git.NewCommandContext(ctx, "receive-pack", "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(tmpDir) refs, err := git.NewCommand(ctx, "receive-pack", "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(tmpDir)
if err != nil { if err != nil {
log.Error(fmt.Sprintf("%v - %s", err, string(refs))) log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
} }
@ -412,7 +412,7 @@ 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]+)*$`) 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 { func getGitConfig(ctx gocontext.Context, option, dir string) string {
out, err := git.NewCommandContext(ctx, "config", option).RunInDir(dir) out, err := git.NewCommand(ctx, "config", option).RunInDir(dir)
if err != nil { if err != nil {
log.Error("%v - %s", err, out) log.Error("%v - %s", err, out)
} }
@ -485,7 +485,7 @@ func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) {
} }
var stderr bytes.Buffer var stderr bytes.Buffer
cmd := git.NewCommandContext(h.r.Context(), service, "--stateless-rpc", h.dir) cmd := git.NewCommand(h.r.Context(), service, "--stateless-rpc", h.dir)
cmd.SetDescription(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir)) cmd.SetDescription(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir))
if err := cmd.RunWithContext(&git.RunContext{ if err := cmd.RunWithContext(&git.RunContext{
Timeout: -1, Timeout: -1,
@ -525,7 +525,7 @@ func getServiceType(r *http.Request) string {
} }
func updateServerInfo(ctx gocontext.Context, dir string) []byte { func updateServerInfo(ctx gocontext.Context, dir string) []byte {
out, err := git.NewCommandContext(ctx, "update-server-info").RunInDirBytes(dir) out, err := git.NewCommand(ctx, "update-server-info").RunInDirBytes(dir)
if err != nil { if err != nil {
log.Error(fmt.Sprintf("%v - %s", err, string(out))) log.Error(fmt.Sprintf("%v - %s", err, string(out)))
} }
@ -555,7 +555,7 @@ func GetInfoRefs(ctx *context.Context) {
} }
h.environ = append(os.Environ(), h.environ...) h.environ = append(os.Environ(), h.environ...)
refs, err := git.NewCommandContext(ctx, service, "--stateless-rpc", "--advertise-refs", ".").RunInDirTimeoutEnv(h.environ, -1, h.dir) refs, err := git.NewCommand(ctx, service, "--stateless-rpc", "--advertise-refs", ".").RunInDirTimeoutEnv(h.environ, -1, h.dir)
if err != nil { if err != nil {
log.Error(fmt.Sprintf("%v - %s", err, string(refs))) log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
} }

View file

@ -338,7 +338,7 @@ func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) *git.C
} }
if commitSHA != "" { if commitSHA != "" {
// Get immediate parent of the first commit in the patch, grab history back // Get immediate parent of the first commit in the patch, grab history back
parentCommit, err = git.NewCommandContext(ctx, "rev-list", "-1", "--skip=1", commitSHA).RunInDir(ctx.Repo.GitRepo.Path) parentCommit, err = git.NewCommand(ctx, "rev-list", "-1", "--skip=1", commitSHA).RunInDir(ctx.Repo.GitRepo.Path)
if err == nil { if err == nil {
parentCommit = strings.TrimSpace(parentCommit) parentCommit = strings.TrimSpace(parentCommit)
} }

View file

@ -205,7 +205,7 @@ func ProcRecive(ctx *context.PrivateContext, opts *private.HookOptions) []privat
} }
if !forcePush { if !forcePush {
output, err := git.NewCommandContext(ctx, "rev-list", "--max-count=1", oldCommitID, "^"+opts.NewCommitIDs[i]).RunInDirWithEnv(repo.RepoPath(), os.Environ()) output, err := git.NewCommand(ctx, "rev-list", "--max-count=1", oldCommitID, "^"+opts.NewCommitIDs[i]).RunInDirWithEnv(repo.RepoPath(), os.Environ())
if err != nil { if err != nil {
log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, opts.NewCommitIDs[i], repo, err) log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, opts.NewCommitIDs[i], repo, err)
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{

View file

@ -90,15 +90,15 @@ func SigningKey(ctx context.Context, repoPath string) (string, *git.Signature) {
if setting.Repository.Signing.SigningKey == "default" || setting.Repository.Signing.SigningKey == "" { if setting.Repository.Signing.SigningKey == "default" || setting.Repository.Signing.SigningKey == "" {
// Can ignore the error here as it means that commit.gpgsign is not set // Can ignore the error here as it means that commit.gpgsign is not set
value, _ := git.NewCommandContext(ctx, "config", "--get", "commit.gpgsign").RunInDir(repoPath) value, _ := git.NewCommand(ctx, "config", "--get", "commit.gpgsign").RunInDir(repoPath)
sign, valid := git.ParseBool(strings.TrimSpace(value)) sign, valid := git.ParseBool(strings.TrimSpace(value))
if !sign || !valid { if !sign || !valid {
return "", nil return "", nil
} }
signingKey, _ := git.NewCommandContext(ctx, "config", "--get", "user.signingkey").RunInDir(repoPath) signingKey, _ := git.NewCommand(ctx, "config", "--get", "user.signingkey").RunInDir(repoPath)
signingName, _ := git.NewCommandContext(ctx, "config", "--get", "user.name").RunInDir(repoPath) signingName, _ := git.NewCommand(ctx, "config", "--get", "user.name").RunInDir(repoPath)
signingEmail, _ := git.NewCommandContext(ctx, "config", "--get", "user.email").RunInDir(repoPath) signingEmail, _ := git.NewCommand(ctx, "config", "--get", "user.email").RunInDir(repoPath)
return strings.TrimSpace(signingKey), &git.Signature{ return strings.TrimSpace(signingKey), &git.Signature{
Name: strings.TrimSpace(signingName), Name: strings.TrimSpace(signingName),
Email: strings.TrimSpace(signingEmail), Email: strings.TrimSpace(signingEmail),

View file

@ -1376,7 +1376,7 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
}() }()
go func(ctx context.Context, diffArgs []string, repoPath string, writer *io.PipeWriter) { go func(ctx context.Context, diffArgs []string, repoPath string, writer *io.PipeWriter) {
cmd := git.NewCommandContext(ctx, diffArgs...) cmd := git.NewCommand(ctx, diffArgs...)
cmd.SetDescription(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath)) cmd.SetDescription(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath))
if err := cmd.RunWithContext(&git.RunContext{ if err := cmd.RunWithContext(&git.RunContext{
Timeout: time.Duration(setting.Git.Timeout.Default) * time.Second, Timeout: time.Duration(setting.Git.Timeout.Default) * time.Second,

View file

@ -476,7 +476,7 @@ func (g *RepositoryDumper) CreatePullRequests(prs ...*base.PullRequest) error {
} }
if ok { if ok {
_, err = git.NewCommandContext(g.ctx, "fetch", remote, pr.Head.Ref).RunInDir(g.gitPath()) _, err = git.NewCommand(g.ctx, "fetch", remote, pr.Head.Ref).RunInDir(g.gitPath())
if err != nil { if err != nil {
log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err) log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err)
} else { } else {

View file

@ -559,7 +559,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR
} }
if ok { if ok {
_, err = git.NewCommandContext(g.ctx, "fetch", remote, pr.Head.Ref).RunInDir(g.repo.RepoPath()) _, err = git.NewCommand(g.ctx, "fetch", remote, pr.Head.Ref).RunInDir(g.repo.RepoPath())
if err != nil { if err != nil {
log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err) log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err)
} else { } else {
@ -583,7 +583,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR
} else { } else {
head = pr.Head.Ref head = pr.Head.Ref
// Ensure the closed PR SHA still points to an existing ref // Ensure the closed PR SHA still points to an existing ref
_, err = git.NewCommandContext(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).RunInDir(g.repo.RepoPath())
if err != nil { if err != nil {
if pr.Head.SHA != "" { if pr.Head.SHA != "" {
// Git update-ref remove bad references with a relative path // Git update-ref remove bad references with a relative path

View file

@ -34,12 +34,12 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error
remoteName := m.GetRemoteName() remoteName := m.GetRemoteName()
repoPath := m.Repo.RepoPath() repoPath := m.Repo.RepoPath()
// Remove old remote // Remove old remote
_, err := git.NewCommandContext(ctx, "remote", "rm", remoteName).RunInDir(repoPath) _, err := git.NewCommand(ctx, "remote", "rm", remoteName).RunInDir(repoPath)
if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
return err return err
} }
_, err = git.NewCommandContext(ctx, "remote", "add", remoteName, "--mirror=fetch", addr).RunInDir(repoPath) _, err = git.NewCommand(ctx, "remote", "add", remoteName, "--mirror=fetch", addr).RunInDir(repoPath)
if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
return err return err
} }
@ -48,12 +48,12 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error
wikiPath := m.Repo.WikiPath() wikiPath := m.Repo.WikiPath()
wikiRemotePath := repo_module.WikiRemoteURL(ctx, addr) wikiRemotePath := repo_module.WikiRemoteURL(ctx, addr)
// Remove old remote of wiki // Remove old remote of wiki
_, err := git.NewCommandContext(ctx, "remote", "rm", remoteName).RunInDir(wikiPath) _, err := git.NewCommand(ctx, "remote", "rm", remoteName).RunInDir(wikiPath)
if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
return err return err
} }
_, err = git.NewCommandContext(ctx, "remote", "add", remoteName, "--mirror=fetch", wikiRemotePath).RunInDir(wikiPath) _, err = git.NewCommand(ctx, "remote", "add", remoteName, "--mirror=fetch", wikiRemotePath).RunInDir(wikiPath)
if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
return err return err
} }
@ -159,7 +159,7 @@ func pruneBrokenReferences(ctx context.Context,
stderrBuilder.Reset() stderrBuilder.Reset()
stdoutBuilder.Reset() stdoutBuilder.Reset()
pruneErr := git.NewCommandContext(ctx, "remote", "prune", m.GetRemoteName()). pruneErr := git.NewCommand(ctx, "remote", "prune", m.GetRemoteName()).
SetDescription(fmt.Sprintf("Mirror.runSync %ssPrune references: %s ", wiki, m.Repo.FullName())). SetDescription(fmt.Sprintf("Mirror.runSync %ssPrune references: %s ", wiki, m.Repo.FullName())).
RunInDirTimeoutPipeline(timeout, repoPath, stdoutBuilder, stderrBuilder) RunInDirTimeoutPipeline(timeout, repoPath, stdoutBuilder, stderrBuilder)
if pruneErr != nil { if pruneErr != nil {
@ -201,7 +201,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
stdoutBuilder := strings.Builder{} stdoutBuilder := strings.Builder{}
stderrBuilder := strings.Builder{} stderrBuilder := strings.Builder{}
if err := git.NewCommandContext(ctx, gitArgs...). if err := git.NewCommand(ctx, gitArgs...).
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())). SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
RunInDirTimeoutPipeline(timeout, repoPath, &stdoutBuilder, &stderrBuilder); err != nil { RunInDirTimeoutPipeline(timeout, repoPath, &stdoutBuilder, &stderrBuilder); err != nil {
stdout := stdoutBuilder.String() stdout := stdoutBuilder.String()
@ -224,7 +224,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
// Successful prune - reattempt mirror // Successful prune - reattempt mirror
stderrBuilder.Reset() stderrBuilder.Reset()
stdoutBuilder.Reset() stdoutBuilder.Reset()
if err = git.NewCommandContext(ctx, gitArgs...). if err = git.NewCommand(ctx, gitArgs...).
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())). SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
RunInDirTimeoutPipeline(timeout, repoPath, &stdoutBuilder, &stderrBuilder); err != nil { RunInDirTimeoutPipeline(timeout, repoPath, &stdoutBuilder, &stderrBuilder); err != nil {
stdout := stdoutBuilder.String() stdout := stdoutBuilder.String()
@ -280,7 +280,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
log.Trace("SyncMirrors [repo: %-v Wiki]: running git remote update...", m.Repo) log.Trace("SyncMirrors [repo: %-v Wiki]: running git remote update...", m.Repo)
stderrBuilder.Reset() stderrBuilder.Reset()
stdoutBuilder.Reset() stdoutBuilder.Reset()
if err := git.NewCommandContext(ctx, "remote", "update", "--prune", m.GetRemoteName()). if err := git.NewCommand(ctx, "remote", "update", "--prune", m.GetRemoteName()).
SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())). SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())).
RunInDirTimeoutPipeline(timeout, wikiPath, &stdoutBuilder, &stderrBuilder); err != nil { RunInDirTimeoutPipeline(timeout, wikiPath, &stdoutBuilder, &stderrBuilder); err != nil {
stdout := stdoutBuilder.String() stdout := stdoutBuilder.String()
@ -312,7 +312,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
stderrBuilder.Reset() stderrBuilder.Reset()
stdoutBuilder.Reset() stdoutBuilder.Reset()
if err = git.NewCommandContext(ctx, "remote", "update", "--prune", m.GetRemoteName()). if err = git.NewCommand(ctx, "remote", "update", "--prune", m.GetRemoteName()).
SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())). SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())).
RunInDirTimeoutPipeline(timeout, wikiPath, &stdoutBuilder, &stderrBuilder); err != nil { RunInDirTimeoutPipeline(timeout, wikiPath, &stdoutBuilder, &stderrBuilder); err != nil {
stdout := stdoutBuilder.String() stdout := stdoutBuilder.String()

View file

@ -28,13 +28,13 @@ var stripExitStatus = regexp.MustCompile(`exit status \d+ - `)
// AddPushMirrorRemote registers the push mirror remote. // AddPushMirrorRemote registers the push mirror remote.
func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr string) error { func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr string) error {
addRemoteAndConfig := func(addr, path string) error { addRemoteAndConfig := func(addr, path string) error {
if _, err := git.NewCommandContext(ctx, "remote", "add", "--mirror=push", m.RemoteName, addr).RunInDir(path); err != nil { if _, err := git.NewCommand(ctx, "remote", "add", "--mirror=push", m.RemoteName, addr).RunInDir(path); err != nil {
return err return err
} }
if _, err := git.NewCommandContext(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/*").RunInDir(path); err != nil {
return err return err
} }
if _, err := git.NewCommandContext(ctx, "config", "--add", "remote."+m.RemoteName+".push", "+refs/tags/*:refs/tags/*").RunInDir(path); err != nil { if _, err := git.NewCommand(ctx, "config", "--add", "remote."+m.RemoteName+".push", "+refs/tags/*:refs/tags/*").RunInDir(path); err != nil {
return err return err
} }
return nil return nil
@ -58,7 +58,7 @@ func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr str
// RemovePushMirrorRemote removes the push mirror remote. // RemovePushMirrorRemote removes the push mirror remote.
func RemovePushMirrorRemote(ctx context.Context, m *repo_model.PushMirror) error { func RemovePushMirrorRemote(ctx context.Context, m *repo_model.PushMirror) error {
cmd := git.NewCommandContext(ctx, "remote", "rm", m.RemoteName) cmd := git.NewCommand(ctx, "remote", "rm", m.RemoteName)
if _, err := cmd.RunInDir(m.Repo.RepoPath()); err != nil { if _, err := cmd.RunInDir(m.Repo.RepoPath()); err != nil {
return err return err

View file

@ -92,7 +92,7 @@ func getMergeCommit(ctx context.Context, pr *models.PullRequest) (*git.Commit, e
headFile := pr.GetGitRefName() headFile := pr.GetGitRefName()
// Check if a pull request is merged into BaseBranch // Check if a pull request is merged into BaseBranch
_, err = git.NewCommandContext(ctx, "merge-base", "--is-ancestor", headFile, pr.BaseBranch). _, err = git.NewCommand(ctx, "merge-base", "--is-ancestor", headFile, pr.BaseBranch).
RunInDirWithEnv(pr.BaseRepo.RepoPath(), []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()}) RunInDirWithEnv(pr.BaseRepo.RepoPath(), []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
if err != nil { if err != nil {
// Errors are signaled by a non-zero status that is not 1 // Errors are signaled by a non-zero status that is not 1
@ -113,7 +113,7 @@ func getMergeCommit(ctx context.Context, pr *models.PullRequest) (*git.Commit, e
cmd := commitID[:40] + ".." + pr.BaseBranch cmd := commitID[:40] + ".." + pr.BaseBranch
// Get the commit from BaseBranch where the pull request got merged // Get the commit from BaseBranch where the pull request got merged
mergeCommit, err := git.NewCommandContext(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd). mergeCommit, err := git.NewCommand(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd).
RunInDirWithEnv("", []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()}) RunInDirWithEnv("", []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
if err != nil { if err != nil {
return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v", err) return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v", err)

View file

@ -142,7 +142,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
stagingBranch := "staging" stagingBranch := "staging"
if expectedHeadCommitID != "" { if expectedHeadCommitID != "" {
trackingCommitID, err := git.NewCommandContext(ctx, "show-ref", "--hash", git.BranchPrefix+trackingBranch).RunInDir(tmpBasePath) trackingCommitID, err := git.NewCommand(ctx, "show-ref", "--hash", git.BranchPrefix+trackingBranch).RunInDir(tmpBasePath)
if err != nil { if err != nil {
log.Error("show-ref[%s] --hash refs/heads/trackingn: %v", tmpBasePath, git.BranchPrefix+trackingBranch, err) log.Error("show-ref[%s] --hash refs/heads/trackingn: %v", tmpBasePath, git.BranchPrefix+trackingBranch, err)
return "", fmt.Errorf("getDiffTree: %v", err) return "", fmt.Errorf("getDiffTree: %v", err)
@ -179,11 +179,11 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
var gitConfigCommand func() *git.Command var gitConfigCommand func() *git.Command
if git.CheckGitVersionAtLeast("1.8.0") == nil { if git.CheckGitVersionAtLeast("1.8.0") == nil {
gitConfigCommand = func() *git.Command { gitConfigCommand = func() *git.Command {
return git.NewCommandContext(ctx, "config", "--local") return git.NewCommand(ctx, "config", "--local")
} }
} else { } else {
gitConfigCommand = func() *git.Command { gitConfigCommand = func() *git.Command {
return git.NewCommandContext(ctx, "config") return git.NewCommand(ctx, "config")
} }
} }
@ -224,7 +224,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
errbuf.Reset() errbuf.Reset()
// Read base branch index // Read base branch index
if err := git.NewCommandContext(ctx, "read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
return "", fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) return "", fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
} }
@ -263,7 +263,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
// Merge commits. // Merge commits.
switch mergeStyle { switch mergeStyle {
case repo_model.MergeStyleMerge: case repo_model.MergeStyleMerge:
cmd := git.NewCommandContext(ctx, "merge", "--no-ff", "--no-commit", trackingBranch) cmd := git.NewCommand(ctx, "merge", "--no-ff", "--no-commit", trackingBranch)
if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
log.Error("Unable to merge tracking into base: %v", err) log.Error("Unable to merge tracking into base: %v", err)
return "", err return "", err
@ -279,7 +279,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
fallthrough fallthrough
case repo_model.MergeStyleRebaseMerge: case repo_model.MergeStyleRebaseMerge:
// Checkout head branch // Checkout head branch
if err := git.NewCommandContext(ctx, "checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
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()) 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())
} }
@ -287,7 +287,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
errbuf.Reset() errbuf.Reset()
// Rebase before merging // Rebase before merging
if err := git.NewCommandContext(ctx, "rebase", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "rebase", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
// Rebase will leave a REBASE_HEAD file in .git if there is a conflict // Rebase will leave a REBASE_HEAD file in .git if there is a conflict
if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "REBASE_HEAD")); statErr == nil { if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "REBASE_HEAD")); statErr == nil {
var commitSha string var commitSha string
@ -335,14 +335,14 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
} }
// Checkout base branch again // Checkout base branch again
if err := git.NewCommandContext(ctx, "checkout", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "checkout", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
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()) 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())
} }
outbuf.Reset() outbuf.Reset()
errbuf.Reset() errbuf.Reset()
cmd := git.NewCommandContext(ctx, "merge") cmd := git.NewCommand(ctx, "merge")
if mergeStyle == repo_model.MergeStyleRebase { if mergeStyle == repo_model.MergeStyleRebase {
cmd.AddArguments("--ff-only") cmd.AddArguments("--ff-only")
} else { } else {
@ -363,7 +363,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
} }
case repo_model.MergeStyleSquash: case repo_model.MergeStyleSquash:
// Merge with squash // Merge with squash
cmd := git.NewCommandContext(ctx, "merge", "--squash", trackingBranch) cmd := git.NewCommand(ctx, "merge", "--squash", trackingBranch)
if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
log.Error("Unable to merge --squash tracking into base: %v", err) log.Error("Unable to merge --squash tracking into base: %v", err)
return "", err return "", err
@ -375,7 +375,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
} }
sig := pr.Issue.Poster.NewGitSig() sig := pr.Issue.Poster.NewGitSig()
if signArg == "" { if signArg == "" {
if err := git.NewCommandContext(ctx, "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil { 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 {
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()) 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())
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()) 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())
} }
@ -384,7 +384,7 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
// add trailer // add trailer
message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String()) message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String())
} }
if err := git.NewCommandContext(ctx, "commit", signArg, fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil { 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 {
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()) 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())
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()) 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())
} }
@ -442,9 +442,9 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
var pushCmd *git.Command var pushCmd *git.Command
if mergeStyle == repo_model.MergeStyleRebaseUpdate { if mergeStyle == repo_model.MergeStyleRebaseUpdate {
// force push the rebase result to head branch // force push the rebase result to head branch
pushCmd = git.NewCommandContext(ctx, "push", "-f", "head_repo", stagingBranch+":"+git.BranchPrefix+pr.HeadBranch) pushCmd = git.NewCommand(ctx, "push", "-f", "head_repo", stagingBranch+":"+git.BranchPrefix+pr.HeadBranch)
} else { } else {
pushCmd = git.NewCommandContext(ctx, "push", "origin", baseBranch+":"+git.BranchPrefix+pr.BaseBranch) pushCmd = git.NewCommand(ctx, "push", "origin", baseBranch+":"+git.BranchPrefix+pr.BaseBranch)
} }
// Push back to upstream. // Push back to upstream.
@ -475,12 +475,12 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
func commitAndSignNoAuthor(ctx context.Context, pr *models.PullRequest, message, signArg, tmpBasePath string, env []string) error { func commitAndSignNoAuthor(ctx context.Context, pr *models.PullRequest, message, signArg, tmpBasePath string, env []string) error {
var outbuf, errbuf strings.Builder var outbuf, errbuf strings.Builder
if signArg == "" { if signArg == "" {
if err := git.NewCommandContext(ctx, "commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
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()) 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())
} }
} else { } else {
if err := git.NewCommandContext(ctx, "commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
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()) 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())
} }
@ -523,7 +523,7 @@ func getDiffTree(ctx context.Context, repoPath, baseBranch, headBranch string) (
getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) { getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
var outbuf, errbuf strings.Builder var outbuf, errbuf strings.Builder
// Compute the diff-tree for sparse-checkout // Compute the diff-tree for sparse-checkout
if err := git.NewCommandContext(ctx, "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String()) return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
} }
return outbuf.String(), nil return outbuf.String(), nil

View file

@ -76,7 +76,7 @@ func TestPatch(pr *models.PullRequest) error {
defer gitRepo.Close() defer gitRepo.Close()
// 1. update merge base // 1. update merge base
pr.MergeBase, err = git.NewCommandContext(ctx, "merge-base", "--", "base", "tracking").RunInDir(tmpBasePath) pr.MergeBase, err = git.NewCommand(ctx, "merge-base", "--", "base", "tracking").RunInDir(tmpBasePath)
if err != nil { if err != nil {
var err2 error var err2 error
pr.MergeBase, err2 = gitRepo.GetRefCommitID(git.BranchPrefix + "base") pr.MergeBase, err2 = gitRepo.GetRefCommitID(git.BranchPrefix + "base")
@ -166,7 +166,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
} }
// Need to get the objects from the object db to attempt to merge // Need to get the objects from the object db to attempt to merge
root, err := git.NewCommandContext(ctx, "unpack-file", file.stage1.sha).RunInDir(tmpBasePath) root, err := git.NewCommand(ctx, "unpack-file", file.stage1.sha).RunInDir(tmpBasePath)
if err != nil { 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) return fmt.Errorf("unable to get root object: %s at path: %s for merging. Error: %w", file.stage1.sha, file.stage1.path, err)
} }
@ -175,7 +175,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
_ = util.Remove(filepath.Join(tmpBasePath, root)) _ = util.Remove(filepath.Join(tmpBasePath, root))
}() }()
base, err := git.NewCommandContext(ctx, "unpack-file", file.stage2.sha).RunInDir(tmpBasePath) base, err := git.NewCommand(ctx, "unpack-file", file.stage2.sha).RunInDir(tmpBasePath)
if err != nil { 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) return fmt.Errorf("unable to get base object: %s at path: %s for merging. Error: %w", file.stage2.sha, file.stage2.path, err)
} }
@ -183,7 +183,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
defer func() { defer func() {
_ = util.Remove(base) _ = util.Remove(base)
}() }()
head, err := git.NewCommandContext(ctx, "unpack-file", file.stage3.sha).RunInDir(tmpBasePath) head, err := git.NewCommand(ctx, "unpack-file", file.stage3.sha).RunInDir(tmpBasePath)
if err != nil { 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) return fmt.Errorf("unable to get head object:%s at path: %s for merging. Error: %w", file.stage3.sha, file.stage3.path, err)
} }
@ -193,13 +193,13 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
}() }()
// now git merge-file annoyingly takes a different order to the merge-tree ... // now git merge-file annoyingly takes a different order to the merge-tree ...
_, conflictErr := git.NewCommandContext(ctx, "merge-file", base, root, head).RunInDir(tmpBasePath) _, conflictErr := git.NewCommand(ctx, "merge-file", base, root, head).RunInDir(tmpBasePath)
if conflictErr != nil { if conflictErr != nil {
return &errMergeConflict{file.stage2.path} return &errMergeConflict{file.stage2.path}
} }
// base now contains the merged data // base now contains the merged data
hash, err := git.NewCommandContext(ctx, "hash-object", "-w", "--path", file.stage2.path, base).RunInDir(tmpBasePath) hash, err := git.NewCommand(ctx, "hash-object", "-w", "--path", file.stage2.path, base).RunInDir(tmpBasePath)
if err != nil { if err != nil {
return err return err
} }
@ -222,7 +222,7 @@ func checkConflicts(pr *models.PullRequest, gitRepo *git.Repository, tmpBasePath
defer finished() defer finished()
// First we use read-tree to do a simple three-way merge // First we use read-tree to do a simple three-way merge
if _, err := git.NewCommandContext(ctx, "read-tree", "-m", pr.MergeBase, "base", "tracking").RunInDir(tmpBasePath); err != nil { if _, err := git.NewCommand(ctx, "read-tree", "-m", pr.MergeBase, "base", "tracking").RunInDir(tmpBasePath); err != nil {
log.Error("Unable to run read-tree -m! Error: %v", err) log.Error("Unable to run read-tree -m! Error: %v", err)
return false, fmt.Errorf("unable to run read-tree -m! Error: %v", err) return false, fmt.Errorf("unable to run read-tree -m! Error: %v", err)
} }
@ -267,7 +267,7 @@ func checkConflicts(pr *models.PullRequest, gitRepo *git.Repository, tmpBasePath
} }
if !conflict { if !conflict {
treeHash, err := git.NewCommandContext(ctx, "write-tree").RunInDir(tmpBasePath) treeHash, err := git.NewCommand(ctx, "write-tree").RunInDir(tmpBasePath)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -326,7 +326,7 @@ func checkConflicts(pr *models.PullRequest, gitRepo *git.Repository, tmpBasePath
pr.Status = models.PullRequestStatusChecking pr.Status = models.PullRequestStatusChecking
// 3. Read the base branch in to the index of the temporary repository // 3. Read the base branch in to the index of the temporary repository
_, err = git.NewCommandContext(gitRepo.Ctx, "read-tree", "base").RunInDir(tmpBasePath) _, err = git.NewCommand(gitRepo.Ctx, "read-tree", "base").RunInDir(tmpBasePath)
if err != nil { if err != nil {
return false, fmt.Errorf("git read-tree %s: %v", pr.BaseBranch, err) return false, fmt.Errorf("git read-tree %s: %v", pr.BaseBranch, err)
} }
@ -371,7 +371,7 @@ func checkConflicts(pr *models.PullRequest, gitRepo *git.Repository, tmpBasePath
// 7. Run the check command // 7. Run the check command
conflict = false conflict = false
err = git.NewCommandContext(gitRepo.Ctx, args...). err = git.NewCommand(gitRepo.Ctx, args...).
RunInDirTimeoutEnvFullPipelineFunc( RunInDirTimeoutEnvFullPipelineFunc(
nil, -1, tmpBasePath, nil, -1, tmpBasePath,
nil, stderrWriter, nil, nil, stderrWriter, nil,

View file

@ -62,7 +62,7 @@ func readUnmergedLsFileLines(ctx context.Context, tmpBasePath string, outputChan
}() }()
stderr := &strings.Builder{} stderr := &strings.Builder{}
err = git.NewCommandContext(ctx, "ls-files", "-u", "-z"). err = git.NewCommand(ctx, "ls-files", "-u", "-z").
RunInDirTimeoutEnvFullPipelineFunc( RunInDirTimeoutEnvFullPipelineFunc(
nil, -1, tmpBasePath, nil, -1, tmpBasePath,
lsFilesWriter, stderr, nil, lsFilesWriter, stderr, nil,

View file

@ -479,7 +479,7 @@ func UpdateRef(ctx context.Context, pr *models.PullRequest) (err error) {
return err return err
} }
_, err = git.NewCommandContext(ctx, "update-ref", pr.GetGitRefName(), pr.HeadCommitID).RunInDir(pr.BaseRepo.RepoPath()) _, err = git.NewCommand(ctx, "update-ref", pr.GetGitRefName(), pr.HeadCommitID).RunInDir(pr.BaseRepo.RepoPath())
if err != nil { if err != nil {
log.Error("Unable to update ref in base repository for PR[%d] Error: %v", pr.ID, err) log.Error("Unable to update ref in base repository for PR[%d] Error: %v", pr.ID, err)
} }

View file

@ -93,7 +93,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
} }
var outbuf, errbuf strings.Builder var outbuf, errbuf strings.Builder
if err := git.NewCommandContext(ctx, "remote", "add", "-t", pr.BaseBranch, "-m", pr.BaseBranch, "origin", baseRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "remote", "add", "-t", pr.BaseBranch, "-m", pr.BaseBranch, "origin", baseRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err) log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@ -103,7 +103,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
outbuf.Reset() outbuf.Reset()
errbuf.Reset() errbuf.Reset()
if err := git.NewCommandContext(ctx, "fetch", "origin", "--no-tags", "--", pr.BaseBranch+":"+baseBranch, pr.BaseBranch+":original_"+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "fetch", "origin", "--no-tags", "--", pr.BaseBranch+":"+baseBranch, pr.BaseBranch+":original_"+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err) log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@ -113,7 +113,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
outbuf.Reset() outbuf.Reset()
errbuf.Reset() errbuf.Reset()
if err := git.NewCommandContext(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
log.Error("Unable to set HEAD as base branch [%s]: %v\n%s\n%s", tmpBasePath, err, outbuf.String(), errbuf.String()) log.Error("Unable to set HEAD as base branch [%s]: %v\n%s\n%s", tmpBasePath, err, outbuf.String(), errbuf.String())
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err) log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@ -131,7 +131,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
return "", fmt.Errorf("Unable to head base repository to temporary repo [%s -> tmpBasePath]: %v", pr.HeadRepo.FullName(), err) return "", fmt.Errorf("Unable to head base repository to temporary repo [%s -> tmpBasePath]: %v", pr.HeadRepo.FullName(), err)
} }
if err := git.NewCommandContext(ctx, "remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
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()) 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())
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err) log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
@ -151,7 +151,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
} else { } else {
headBranch = pr.GetGitRefName() headBranch = pr.GetGitRefName()
} }
if err := git.NewCommandContext(ctx, "fetch", "--no-tags", remoteRepoName, headBranch+":"+trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { if err := git.NewCommand(ctx, "fetch", "--no-tags", remoteRepoName, headBranch+":"+trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err) log.Error("CreateTempRepo: RemoveTemporaryPath: %s", err)
} }

View file

@ -296,7 +296,7 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del
} }
if delTag { if delTag {
if stdout, err := git.NewCommandContext(ctx, "tag", "-d", rel.TagName). if stdout, err := git.NewCommand(ctx, "tag", "-d", rel.TagName).
SetDescription(fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID)). SetDescription(fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID)).
RunInDir(repo.RepoPath()); err != nil && !strings.Contains(err.Error(), "not found") { 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) log.Error("DeleteReleaseByID (git tag -d): %d in %v Failed:\nStdout: %s\nError: %v", rel.ID, repo, stdout, err)

View file

@ -84,7 +84,7 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (*
} }
} }
if stdout, err := git.NewCommandContext(ctx, "update-server-info"). if stdout, err := git.NewCommand(ctx, "update-server-info").
SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)). SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)).
RunInDir(repoPath); err != nil { RunInDir(repoPath); err != nil {
log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err) log.Error("CreateRepository(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err)

View file

@ -73,7 +73,7 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro
default: default:
} }
log.Trace("Running git gc on %v", repo) log.Trace("Running git gc on %v", repo)
command := git.NewCommandContext(ctx, args...). command := git.NewCommand(ctx, args...).
SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName())) SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName()))
var stdout string var stdout string
var err error var err error

View file

@ -52,7 +52,7 @@ func (t *TemporaryUploadRepository) Close() {
// Clone the base repository to our path and set branch as the HEAD // Clone the base repository to our path and set branch as the HEAD
func (t *TemporaryUploadRepository) Clone(branch string) error { func (t *TemporaryUploadRepository) Clone(branch string) error {
if _, err := git.NewCommandContext(t.ctx, "clone", "-s", "--bare", "-b", branch, t.repo.RepoPath(), t.basePath).Run(); err != nil { if _, err := git.NewCommand(t.ctx, "clone", "-s", "--bare", "-b", branch, t.repo.RepoPath(), t.basePath).Run(); err != nil {
stderr := err.Error() stderr := err.Error()
if matched, _ := regexp.MatchString(".*Remote branch .* not found in upstream origin.*", stderr); matched { if matched, _ := regexp.MatchString(".*Remote branch .* not found in upstream origin.*", stderr); matched {
return git.ErrBranchNotExist{ return git.ErrBranchNotExist{
@ -79,7 +79,7 @@ func (t *TemporaryUploadRepository) Clone(branch string) error {
// SetDefaultIndex sets the git index to our HEAD // SetDefaultIndex sets the git index to our HEAD
func (t *TemporaryUploadRepository) SetDefaultIndex() error { func (t *TemporaryUploadRepository) SetDefaultIndex() error {
if _, err := git.NewCommandContext(t.ctx, "read-tree", "HEAD").RunInDir(t.basePath); err != nil { if _, err := git.NewCommand(t.ctx, "read-tree", "HEAD").RunInDir(t.basePath); err != nil {
return fmt.Errorf("SetDefaultIndex: %v", err) return fmt.Errorf("SetDefaultIndex: %v", err)
} }
return nil return nil
@ -97,7 +97,7 @@ func (t *TemporaryUploadRepository) LsFiles(filenames ...string) ([]string, erro
} }
} }
if err := git.NewCommandContext(t.ctx, cmdArgs...).RunInDirPipeline(t.basePath, stdOut, stdErr); err != nil { if err := git.NewCommand(t.ctx, cmdArgs...).RunInDirPipeline(t.basePath, stdOut, stdErr); err != nil {
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()) 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())
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()) 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())
return nil, err return nil, err
@ -124,7 +124,7 @@ func (t *TemporaryUploadRepository) RemoveFilesFromIndex(filenames ...string) er
} }
} }
if err := git.NewCommandContext(t.ctx, "update-index", "--remove", "-z", "--index-info").RunInDirFullPipeline(t.basePath, stdOut, stdErr, stdIn); err != nil { if err := git.NewCommand(t.ctx, "update-index", "--remove", "-z", "--index-info").RunInDirFullPipeline(t.basePath, stdOut, stdErr, stdIn); err != nil {
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()) 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())
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()) 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())
} }
@ -136,7 +136,7 @@ func (t *TemporaryUploadRepository) HashObject(content io.Reader) (string, error
stdOut := new(bytes.Buffer) stdOut := new(bytes.Buffer)
stdErr := new(bytes.Buffer) stdErr := new(bytes.Buffer)
if err := git.NewCommandContext(t.ctx, "hash-object", "-w", "--stdin").RunInDirFullPipeline(t.basePath, stdOut, stdErr, content); err != nil { if err := git.NewCommand(t.ctx, "hash-object", "-w", "--stdin").RunInDirFullPipeline(t.basePath, stdOut, stdErr, content); err != nil {
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()) 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())
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()) 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())
} }
@ -146,7 +146,7 @@ func (t *TemporaryUploadRepository) HashObject(content io.Reader) (string, error
// AddObjectToIndex adds the provided object hash to the index with the provided mode and 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 { func (t *TemporaryUploadRepository) AddObjectToIndex(mode, objectHash, objectPath string) error {
if _, err := git.NewCommandContext(t.ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash, objectPath).RunInDir(t.basePath); err != nil { if _, err := git.NewCommand(t.ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash, objectPath).RunInDir(t.basePath); err != nil {
stderr := err.Error() stderr := err.Error()
if matched, _ := regexp.MatchString(".*Invalid path '.*", stderr); matched { if matched, _ := regexp.MatchString(".*Invalid path '.*", stderr); matched {
return models.ErrFilePathInvalid{ return models.ErrFilePathInvalid{
@ -162,7 +162,7 @@ func (t *TemporaryUploadRepository) AddObjectToIndex(mode, objectHash, objectPat
// WriteTree writes the current index as a tree to the object db and returns its hash // WriteTree writes the current index as a tree to the object db and returns its hash
func (t *TemporaryUploadRepository) WriteTree() (string, error) { func (t *TemporaryUploadRepository) WriteTree() (string, error) {
stdout, err := git.NewCommandContext(t.ctx, "write-tree").RunInDir(t.basePath) stdout, err := git.NewCommand(t.ctx, "write-tree").RunInDir(t.basePath)
if err != nil { if err != nil {
log.Error("Unable to write tree in temporary repo: %s(%s): Error: %v", t.repo.FullName(), t.basePath, err) 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 "", fmt.Errorf("Unable to write-tree in temporary repo for: %s Error: %v", t.repo.FullName(), err)
@ -180,7 +180,7 @@ func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, erro
if ref == "" { if ref == "" {
ref = "HEAD" ref = "HEAD"
} }
stdout, err := git.NewCommandContext(t.ctx, "rev-parse", ref).RunInDir(t.basePath) stdout, err := git.NewCommand(t.ctx, "rev-parse", ref).RunInDir(t.basePath)
if err != nil { 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) 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 "", fmt.Errorf("Unable to rev-parse %s in temporary repo for: %s Error: %v", ref, t.repo.FullName(), err)
@ -254,7 +254,7 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *user_m
stdout := new(bytes.Buffer) stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer) stderr := new(bytes.Buffer)
if err := git.NewCommandContext(t.ctx, args...).RunInDirTimeoutEnvFullPipeline(env, -1, t.basePath, stdout, stderr, messageBytes); err != nil { if err := git.NewCommand(t.ctx, args...).RunInDirTimeoutEnvFullPipeline(env, -1, t.basePath, stdout, stderr, messageBytes); err != nil {
log.Error("Unable to commit-tree in temporary repo: %s (%s) Error: %v\nStdout: %s\nStderr: %s", log.Error("Unable to commit-tree in temporary repo: %s (%s) Error: %v\nStdout: %s\nStderr: %s",
t.repo.FullName(), t.basePath, err, stdout, stderr) t.repo.FullName(), t.basePath, err, stdout, stderr)
return "", fmt.Errorf("Unable to commit-tree in temporary repo: %s Error: %v\nStdout: %s\nStderr: %s", return "", fmt.Errorf("Unable to commit-tree in temporary repo: %s Error: %v\nStdout: %s\nStderr: %s",
@ -303,7 +303,7 @@ func (t *TemporaryUploadRepository) DiffIndex() (*gitdiff.Diff, error) {
var diff *gitdiff.Diff var diff *gitdiff.Diff
var finalErr error var finalErr error
if err := git.NewCommandContext(t.ctx, "diff-index", "--src-prefix=\\a/", "--dst-prefix=\\b/", "--cached", "-p", "HEAD"). if err := git.NewCommand(t.ctx, "diff-index", "--src-prefix=\\a/", "--dst-prefix=\\b/", "--cached", "-p", "HEAD").
RunInDirTimeoutEnvFullPipelineFunc(nil, 30*time.Second, t.basePath, stdoutWriter, stderr, nil, func(ctx context.Context, cancel context.CancelFunc) error { RunInDirTimeoutEnvFullPipelineFunc(nil, 30*time.Second, t.basePath, stdoutWriter, stderr, nil, func(ctx context.Context, cancel context.CancelFunc) error {
_ = stdoutWriter.Close() _ = stdoutWriter.Close()
diff, finalErr = gitdiff.ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "") diff, finalErr = gitdiff.ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "")

View file

@ -108,7 +108,7 @@ func ForkRepository(doer, owner *user_model.User, opts ForkRepoOptions) (_ *repo
needsRollback = true needsRollback = true
repoPath := repo_model.RepoPath(owner.Name, repo.Name) repoPath := repo_model.RepoPath(owner.Name, repo.Name)
if stdout, err := git.NewCommandContext(ctx, if stdout, err := git.NewCommand(ctx,
"clone", "--bare", oldRepoPath, repoPath). "clone", "--bare", oldRepoPath, repoPath).
SetDescription(fmt.Sprintf("ForkRepository(git clone): %s to %s", opts.BaseRepo.FullName(), repo.FullName())). SetDescription(fmt.Sprintf("ForkRepository(git clone): %s to %s", opts.BaseRepo.FullName(), repo.FullName())).
RunInDirTimeout(10*time.Minute, ""); err != nil { RunInDirTimeout(10*time.Minute, ""); err != nil {
@ -120,7 +120,7 @@ func ForkRepository(doer, owner *user_model.User, opts ForkRepoOptions) (_ *repo
return fmt.Errorf("checkDaemonExportOK: %v", err) return fmt.Errorf("checkDaemonExportOK: %v", err)
} }
if stdout, err := git.NewCommandContext(ctx, "update-server-info"). if stdout, err := git.NewCommand(ctx, "update-server-info").
SetDescription(fmt.Sprintf("ForkRepository(git update-server-info): %s", repo.FullName())). SetDescription(fmt.Sprintf("ForkRepository(git update-server-info): %s", repo.FullName())).
RunInDir(repoPath); err != nil { RunInDir(repoPath); err != nil {
log.Error("Fork Repository (git update-server-info) failed for %v:\nStdout: %s\nError: %v", repo, stdout, err) log.Error("Fork Repository (git update-server-info) failed for %v:\nStdout: %s\nError: %v", repo, stdout, err)

View file

@ -81,7 +81,7 @@ func InitWiki(ctx context.Context, repo *repo_model.Repository) error {
return fmt.Errorf("InitRepository: %v", err) return fmt.Errorf("InitRepository: %v", err)
} else if err = repo_module.CreateDelegateHooks(repo.WikiPath()); err != nil { } else if err = repo_module.CreateDelegateHooks(repo.WikiPath()); err != nil {
return fmt.Errorf("createDelegateHooks: %v", err) return fmt.Errorf("createDelegateHooks: %v", err)
} else if _, err = git.NewCommandContext(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(repo.WikiPath()); err != nil { } else if _, err = git.NewCommand(ctx, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(repo.WikiPath()); err != nil {
return fmt.Errorf("unable to set default wiki branch to master: %v", err) return fmt.Errorf("unable to set default wiki branch to master: %v", err)
} }
return nil return nil