diff options
author | wxiaoguang <wxiaoguang@gmail.com> | 2022-04-01 10:55:30 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-04-01 10:55:30 +0800 |
commit | 124b072f0b69650baff086b9688d198f5a6761af (patch) | |
tree | fa18f7930053a8408e124875b5dec20e0309332b /modules/git | |
parent | 3a73645502392110369b5d78fa2c9136e77e4aa2 (diff) | |
download | gitea-124b072f0b69650baff086b9688d198f5a6761af.tar.gz gitea-124b072f0b69650baff086b9688d198f5a6761af.zip |
Remove `git.Command.Run` and `git.Command.RunInDir*` (#19280)
Follows #19266, #8553, Close #18553, now there are only three `Run..(&RunOpts{})` functions.
* before: `stdout, err := RunInDir(path)`
* now: `stdout, _, err := RunStdString(&git.RunOpts{Dir:path})`
Diffstat (limited to 'modules/git')
34 files changed, 302 insertions, 350 deletions
diff --git a/modules/git/batch_reader.go b/modules/git/batch_reader.go index 66ca118de5..5a0a82b13a 100644 --- a/modules/git/batch_reader.go +++ b/modules/git/batch_reader.go @@ -34,10 +34,9 @@ func EnsureValidGitRepository(ctx context.Context, repoPath string) error { stderr := strings.Builder{} err := NewCommand(ctx, "rev-parse"). SetDescription(fmt.Sprintf("%s rev-parse [repo_path: %s]", GitExecutable, repoPath)). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repoPath, - Stderr: &stderr, + Run(&RunOpts{ + Dir: repoPath, + Stderr: &stderr, }) if err != nil { return ConcatenateError(err, (&stderr).String()) @@ -65,12 +64,11 @@ func CatFileBatchCheck(ctx context.Context, repoPath string) (WriteCloserError, stderr := strings.Builder{} err := NewCommand(ctx, "cat-file", "--batch-check"). SetDescription(fmt.Sprintf("%s cat-file --batch-check [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repoPath, - Stdin: batchStdinReader, - Stdout: batchStdoutWriter, - Stderr: &stderr, + Run(&RunOpts{ + Dir: repoPath, + Stdin: batchStdinReader, + Stdout: batchStdoutWriter, + Stderr: &stderr, }) if err != nil { _ = batchStdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String())) @@ -110,12 +108,11 @@ func CatFileBatch(ctx context.Context, repoPath string) (WriteCloserError, *bufi stderr := strings.Builder{} err := NewCommand(ctx, "cat-file", "--batch"). SetDescription(fmt.Sprintf("%s cat-file --batch [repo_path: %s] (%s:%d)", GitExecutable, repoPath, filename, line)). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repoPath, - Stdin: batchStdinReader, - Stdout: batchStdoutWriter, - Stderr: &stderr, + Run(&RunOpts{ + Dir: repoPath, + Stdin: batchStdinReader, + Stdout: batchStdoutWriter, + Stderr: &stderr, }) if err != nil { _ = batchStdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String())) diff --git a/modules/git/command.go b/modules/git/command.go index 764114a3b1..3dd12e421e 100644 --- a/modules/git/command.go +++ b/modules/git/command.go @@ -94,8 +94,8 @@ func (c *Command) AddArguments(args ...string) *Command { return c } -// RunContext represents parameters to run the command -type RunContext struct { +// RunOpts represents parameters to run the command +type RunOpts struct { Env []string Timeout time.Duration Dir string @@ -104,16 +104,19 @@ type RunContext struct { PipelineFunc func(context.Context, context.CancelFunc) error } -// RunWithContext run the command with context -func (c *Command) RunWithContext(rc *RunContext) error { - if rc.Timeout <= 0 { - rc.Timeout = defaultCommandExecutionTimeout +// Run runs the command with the RunOpts +func (c *Command) Run(opts *RunOpts) error { + if opts == nil { + opts = &RunOpts{} + } + if opts.Timeout <= 0 { + opts.Timeout = defaultCommandExecutionTimeout } - if len(rc.Dir) == 0 { + if len(opts.Dir) == 0 { log.Debug("%s", c) } else { - log.Debug("%s: %v", rc.Dir, c) + log.Debug("%s: %v", opts.Dir, c) } desc := c.desc @@ -132,17 +135,17 @@ func (c *Command) RunWithContext(rc *RunContext) error { args[urlArgIndex] = util.SanitizeCredentialURLs(args[urlArgIndex]) } } - desc = fmt.Sprintf("%s %s [repo_path: %s]", c.name, strings.Join(args, " "), rc.Dir) + desc = fmt.Sprintf("%s %s [repo_path: %s]", c.name, strings.Join(args, " "), opts.Dir) } - ctx, cancel, finished := process.GetManager().AddContextTimeout(c.parentContext, rc.Timeout, desc) + ctx, cancel, finished := process.GetManager().AddContextTimeout(c.parentContext, opts.Timeout, desc) defer finished() cmd := exec.CommandContext(ctx, c.name, c.args...) - if rc.Env == nil { + if opts.Env == nil { cmd.Env = os.Environ() } else { - cmd.Env = rc.Env + cmd.Env = opts.Env } cmd.Env = append( @@ -154,16 +157,16 @@ func (c *Command) RunWithContext(rc *RunContext) error { "GIT_NO_REPLACE_OBJECTS=1", ) - cmd.Dir = rc.Dir - cmd.Stdout = rc.Stdout - cmd.Stderr = rc.Stderr - cmd.Stdin = rc.Stdin + cmd.Dir = opts.Dir + cmd.Stdout = opts.Stdout + cmd.Stderr = opts.Stderr + cmd.Stdin = opts.Stdin if err := cmd.Start(); err != nil { return err } - if rc.PipelineFunc != nil { - err := rc.PipelineFunc(ctx, cancel) + if opts.PipelineFunc != nil { + err := opts.PipelineFunc(ctx, cancel) if err != nil { cancel() _ = cmd.Wait() @@ -178,18 +181,18 @@ func (c *Command) RunWithContext(rc *RunContext) error { return ctx.Err() } -type RunError interface { +type RunStdError interface { error Stderr() string } -type runError struct { +type runStdError struct { err error stderr string errMsg string } -func (r *runError) Error() string { +func (r *runStdError) Error() string { // the stderr must be in the returned error text, some code only checks `strings.Contains(err.Error(), "git error")` if r.errMsg == "" { r.errMsg = ConcatenateError(r.err, r.stderr).Error() @@ -197,11 +200,11 @@ func (r *runError) Error() string { return r.errMsg } -func (r *runError) Unwrap() error { +func (r *runStdError) Unwrap() error { return r.err } -func (r *runError) Stderr() string { +func (r *runStdError) Stderr() string { return r.stderr } @@ -209,64 +212,40 @@ func bytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) // that's what Golang's strings.Builder.String() does (go/src/strings/builder.go) } -// RunWithContextString run the command with context and returns stdout/stderr as string. and store stderr to returned error (err combined with stderr). -func (c *Command) RunWithContextString(rc *RunContext) (stdout, stderr string, runErr RunError) { - stdoutBytes, stderrBytes, err := c.RunWithContextBytes(rc) +// RunStdString runs the command with options and returns stdout/stderr as string. and store stderr to returned error (err combined with stderr). +func (c *Command) RunStdString(opts *RunOpts) (stdout, stderr string, runErr RunStdError) { + stdoutBytes, stderrBytes, err := c.RunStdBytes(opts) stdout = bytesToString(stdoutBytes) stderr = bytesToString(stderrBytes) if err != nil { - return stdout, stderr, &runError{err: err, stderr: stderr} + return stdout, stderr, &runStdError{err: err, stderr: stderr} } // even if there is no err, there could still be some stderr output, so we just return stdout/stderr as they are return stdout, stderr, nil } -// RunWithContextBytes run the command with context and returns stdout/stderr as bytes. and store stderr to returned error (err combined with stderr). -func (c *Command) RunWithContextBytes(rc *RunContext) (stdout, stderr []byte, runErr RunError) { - if rc.Stdout != nil || rc.Stderr != nil { +// RunStdBytes runs the command with options and returns stdout/stderr as bytes. and store stderr to returned error (err combined with stderr). +func (c *Command) RunStdBytes(opts *RunOpts) (stdout, stderr []byte, runErr RunStdError) { + if opts == nil { + opts = &RunOpts{} + } + if opts.Stdout != nil || opts.Stderr != nil { // we must panic here, otherwise there would be bugs if developers set Stdin/Stderr by mistake, and it would be very difficult to debug - panic("stdout and stderr field must be nil when using RunWithContextBytes") + panic("stdout and stderr field must be nil when using RunStdBytes") } stdoutBuf := &bytes.Buffer{} stderrBuf := &bytes.Buffer{} - rc.Stdout = stdoutBuf - rc.Stderr = stderrBuf - err := c.RunWithContext(rc) + opts.Stdout = stdoutBuf + opts.Stderr = stderrBuf + err := c.Run(opts) stderr = stderrBuf.Bytes() if err != nil { - return nil, stderr, &runError{err: err, stderr: string(stderr)} + return nil, stderr, &runStdError{err: err, stderr: bytesToString(stderr)} } // even if there is no err, there could still be some stderr output return stdoutBuf.Bytes(), stderr, nil } -// RunInDirBytes executes the command in given directory -// and returns stdout in []byte and error (combined with stderr). -func (c *Command) RunInDirBytes(dir string) ([]byte, error) { - stdout, _, err := c.RunWithContextBytes(&RunContext{Dir: dir}) - return stdout, err -} - -// RunInDir executes the command in given directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunInDir(dir string) (string, error) { - return c.RunInDirWithEnv(dir, nil) -} - -// RunInDirWithEnv executes the command in given directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunInDirWithEnv(dir string, env []string) (string, error) { - stdout, _, err := c.RunWithContextString(&RunContext{Env: env, Dir: dir}) - return stdout, err -} - -// Run executes the command in default working directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) Run() (string, error) { - stdout, _, err := c.RunWithContextString(&RunContext{}) - return stdout, err -} - // AllowLFSFiltersArgs return globalCommandArgs with lfs filter, it should only be used for tests func AllowLFSFiltersArgs() []string { // Now here we should explicitly allow lfs filters to run diff --git a/modules/git/command_race_test.go b/modules/git/command_race_test.go index 2c975860dd..9eb29fcfab 100644 --- a/modules/git/command_race_test.go +++ b/modules/git/command_race_test.go @@ -19,7 +19,7 @@ func TestRunWithContextNoTimeout(t *testing.T) { // 'git --version' does not block so it must be finished before the timeout triggered. cmd := NewCommand(context.Background(), "--version") for i := 0; i < maxLoops; i++ { - if err := cmd.RunWithContext(&RunContext{}); err != nil { + if err := cmd.Run(&RunOpts{}); err != nil { t.Fatal(err) } } @@ -31,7 +31,7 @@ func TestRunWithContextTimeout(t *testing.T) { // 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered. cmd := NewCommand(context.Background(), "hash-object", "--stdin") for i := 0; i < maxLoops; i++ { - if err := cmd.RunWithContext(&RunContext{Timeout: 1 * time.Millisecond}); err != nil { + if err := cmd.Run(&RunOpts{Timeout: 1 * time.Millisecond}); err != nil { if err != context.DeadlineExceeded { t.Fatalf("Testing %d/%d: %v", i, maxLoops, err) } diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 33a6661d45..67d4ca388e 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -13,13 +13,13 @@ import ( func TestRunWithContextStd(t *testing.T) { cmd := NewCommand(context.Background(), "--version") - stdout, stderr, err := cmd.RunWithContextString(&RunContext{}) + stdout, stderr, err := cmd.RunStdString(&RunOpts{}) assert.NoError(t, err) assert.Empty(t, stderr) assert.Contains(t, stdout, "git version") cmd = NewCommand(context.Background(), "--no-such-arg") - stdout, stderr, err = cmd.RunWithContextString(&RunContext{}) + stdout, stderr, err = cmd.RunStdString(&RunOpts{}) if assert.Error(t, err) { assert.Equal(t, stderr, err.Stderr()) assert.Contains(t, err.Stderr(), "unknown option:") diff --git a/modules/git/commit.go b/modules/git/commit.go index 340a7e21dd..8337e54fef 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -94,7 +94,7 @@ func AddChangesWithArgs(repoPath string, globalArgs []string, all bool, files .. cmd.AddArguments("--all") } cmd.AddArguments("--") - _, err := cmd.AddArguments(files...).RunInDir(repoPath) + _, _, err := cmd.AddArguments(files...).RunStdString(&RunOpts{Dir: repoPath}) return err } @@ -130,7 +130,7 @@ func CommitChangesWithArgs(repoPath string, args []string, opts CommitChangesOpt } cmd.AddArguments("-m", opts.Message) - _, err := cmd.RunInDir(repoPath) + _, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) // No stderr but exit status 1 means nothing to commit. if err != nil && err.Error() == "exit status 1" { return nil @@ -151,7 +151,7 @@ func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, file cmd.AddArguments(files...) } - stdout, err := cmd.RunInDir(repoPath) + stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return 0, err } @@ -168,7 +168,7 @@ func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath [ cmd.AddArguments(relpath...) } - stdout, err := cmd.RunInDir(repoPath) + stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return 0, err } @@ -206,7 +206,7 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) { } if err := CheckGitVersionAtLeast("1.8"); err == nil { - _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunInDir(c.repo.Path) + _, _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunStdString(&RunOpts{Dir: c.repo.Path}) if err == nil { return true, nil } @@ -219,7 +219,7 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) { return false, err } - result, err := NewCommand(c.repo.Ctx, "rev-list", "--ancestry-path", "-n1", that+".."+this, "--").RunInDir(c.repo.Path) + result, _, err := NewCommand(c.repo.Ctx, "rev-list", "--ancestry-path", "-n1", that+".."+this, "--").RunStdString(&RunOpts{Dir: c.repo.Path}) if err != nil { return false, err } @@ -381,7 +381,7 @@ func (c *Commit) GetBranchName() (string, error) { } args = append(args, "--name-only", "--no-undefined", c.ID.String()) - data, err := NewCommand(c.repo.Ctx, args...).RunInDir(c.repo.Path) + data, _, err := NewCommand(c.repo.Ctx, args...).RunStdString(&RunOpts{Dir: c.repo.Path}) if err != nil { // handle special case where git can not describe commit 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 func (c *Commit) GetTagName() (string, error) { - data, err := NewCommand(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()).RunStdString(&RunOpts{Dir: c.repo.Path}) if err != nil { // handle special case where there is no tag for this commit if strings.Contains(err.Error(), "no tag exactly matches") { @@ -486,11 +486,10 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi stderr := new(bytes.Buffer) args := []string{"log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1", commitID} - err := NewCommand(ctx, args...).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repoPath, - Stdout: w, - Stderr: stderr, + err := NewCommand(ctx, args...).Run(&RunOpts{ + Dir: repoPath, + Stdout: w, + Stderr: stderr, }) w.Close() // Close writer to exit parsing goroutine if err != nil { @@ -503,7 +502,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. func GetFullCommitID(ctx context.Context, repoPath, shortID string) (string, error) { - commitID, err := NewCommand(ctx, "rev-parse", shortID).RunInDir(repoPath) + commitID, _, err := NewCommand(ctx, "rev-parse", shortID).RunStdString(&RunOpts{Dir: repoPath}) if err != nil { if strings.Contains(err.Error(), "exit status 128") { return "", ErrNotExist{shortID, ""} diff --git a/modules/git/diff.go b/modules/git/diff.go index e15b2aa410..e11f63cabd 100644 --- a/modules/git/diff.go +++ b/modules/git/diff.go @@ -36,11 +36,10 @@ func GetRawDiff(ctx context.Context, repoPath, commitID string, diffType RawDiff func GetReverseRawDiff(ctx context.Context, repoPath, commitID string, writer io.Writer) error { stderr := new(bytes.Buffer) cmd := NewCommand(ctx, "show", "--pretty=format:revert %H%n", "-R", commitID) - if err := cmd.RunWithContext(&RunContext{ - Timeout: -1, - Dir: repoPath, - Stdout: writer, - Stderr: stderr, + if err := cmd.Run(&RunOpts{ + Dir: repoPath, + Stdout: writer, + Stderr: stderr, }); err != nil { return fmt.Errorf("Run: %v - %s", err, stderr) } @@ -97,11 +96,10 @@ func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diff stderr := new(bytes.Buffer) cmd := NewCommand(repo.Ctx, args...) - if err = cmd.RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: writer, - Stderr: stderr, + if err = cmd.Run(&RunOpts{ + Dir: repo.Path, + Stdout: writer, + Stderr: stderr, }); err != nil { return fmt.Errorf("Run: %v - %s", err, stderr) } @@ -301,11 +299,10 @@ func GetAffectedFiles(repo *Repository, oldCommitID, newCommitID string, env []s // Run `git diff --name-only` to get the names of the changed files err = NewCommand(repo.Ctx, "diff", "--name-only", oldCommitID, newCommitID). - RunWithContext(&RunContext{ - Env: env, - Timeout: -1, - Dir: repo.Path, - Stdout: stdoutWriter, + Run(&RunOpts{ + Env: env, + Dir: repo.Path, + Stdout: stdoutWriter, PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error { // Close the writer end of the pipe to begin processing _ = stdoutWriter.Close() diff --git a/modules/git/git.go b/modules/git/git.go index 6b7dbfd169..b97bb14900 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -54,9 +54,9 @@ func LoadGitVersion() error { return nil } - stdout, err := NewCommand(context.Background(), "version").Run() - if err != nil { - return err + stdout, _, runErr := NewCommand(context.Background(), "version").RunStdString(nil) + if runErr != nil { + return runErr } fields := strings.Fields(stdout) @@ -74,6 +74,7 @@ func LoadGitVersion() error { versionString = fields[2] } + var err error gitVersion, err = version.NewVersion(versionString) return err } @@ -297,5 +298,5 @@ func checkAndRemoveConfig(key, value string) error { // Fsck verifies the connectivity and validity of the objects in the database func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args ...string) error { - return NewCommand(ctx, "fsck").AddArguments(args...).RunWithContext(&RunContext{Timeout: timeout, Dir: repoPath}) + return NewCommand(ctx, "fsck").AddArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath}) } diff --git a/modules/git/log_name_status.go b/modules/git/log_name_status.go index 0571a4dd20..ffd0a0991b 100644 --- a/modules/git/log_name_status.go +++ b/modules/git/log_name_status.go @@ -55,11 +55,10 @@ func LogNameStatusRepo(ctx context.Context, repository, head, treepath string, p go func() { stderr := strings.Builder{} - err := NewCommand(ctx, args...).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repository, - Stdout: stdoutWriter, - Stderr: &stderr, + err := NewCommand(ctx, args...).Run(&RunOpts{ + Dir: repository, + Stdout: stdoutWriter, + Stderr: &stderr, }) if err != nil { _ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String())) diff --git a/modules/git/pipeline/catfile.go b/modules/git/pipeline/catfile.go index 6948131e46..40dd2bca29 100644 --- a/modules/git/pipeline/catfile.go +++ b/modules/git/pipeline/catfile.go @@ -27,12 +27,11 @@ func CatFileBatchCheck(ctx context.Context, shasToCheckReader *io.PipeReader, ca stderr := new(bytes.Buffer) var errbuf strings.Builder cmd := git.NewCommand(ctx, "cat-file", "--batch-check") - if err := cmd.RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: tmpBasePath, - Stdin: shasToCheckReader, - Stdout: catFileCheckWriter, - Stderr: stderr, + if err := cmd.Run(&git.RunOpts{ + Dir: tmpBasePath, + Stdin: shasToCheckReader, + Stdout: catFileCheckWriter, + Stderr: stderr, }); err != nil { _ = catFileCheckWriter.CloseWithError(fmt.Errorf("git cat-file --batch-check [%s]: %v - %s", tmpBasePath, err, errbuf.String())) } @@ -46,11 +45,10 @@ func CatFileBatchCheckAllObjects(ctx context.Context, catFileCheckWriter *io.Pip stderr := new(bytes.Buffer) var errbuf strings.Builder cmd := git.NewCommand(ctx, "cat-file", "--batch-check", "--batch-all-objects") - if err := cmd.RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: tmpBasePath, - Stdout: catFileCheckWriter, - Stderr: stderr, + if err := cmd.Run(&git.RunOpts{ + Dir: tmpBasePath, + Stdout: catFileCheckWriter, + Stderr: stderr, }); err != nil { 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()) @@ -67,12 +65,11 @@ func CatFileBatch(ctx context.Context, shasToBatchReader *io.PipeReader, catFile stderr := new(bytes.Buffer) var errbuf strings.Builder - if err := git.NewCommand(ctx, "cat-file", "--batch").RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: tmpBasePath, - Stdout: catFileBatchWriter, - Stdin: shasToBatchReader, - Stderr: stderr, + if err := git.NewCommand(ctx, "cat-file", "--batch").Run(&git.RunOpts{ + Dir: tmpBasePath, + Stdout: catFileBatchWriter, + Stdin: shasToBatchReader, + Stderr: stderr, }); err != nil { _ = shasToBatchReader.CloseWithError(fmt.Errorf("git rev-list [%s]: %v - %s", tmpBasePath, err, errbuf.String())) } diff --git a/modules/git/pipeline/lfs_nogogit.go b/modules/git/pipeline/lfs_nogogit.go index 1d43080a5a..31c10c6002 100644 --- a/modules/git/pipeline/lfs_nogogit.go +++ b/modules/git/pipeline/lfs_nogogit.go @@ -53,11 +53,10 @@ func FindLFSFile(repo *git.Repository, hash git.SHA1) ([]*LFSResult, error) { go func() { stderr := strings.Builder{} - err := git.NewCommand(repo.Ctx, "rev-list", "--all").RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: revListWriter, - Stderr: &stderr, + err := git.NewCommand(repo.Ctx, "rev-list", "--all").Run(&git.RunOpts{ + Dir: repo.Path, + Stdout: revListWriter, + Stderr: &stderr, }) if err != nil { _ = revListWriter.CloseWithError(git.ConcatenateError(err, (&stderr).String())) diff --git a/modules/git/pipeline/namerev.go b/modules/git/pipeline/namerev.go index 357322070e..8356e70234 100644 --- a/modules/git/pipeline/namerev.go +++ b/modules/git/pipeline/namerev.go @@ -23,12 +23,11 @@ func NameRevStdin(ctx context.Context, shasToNameReader *io.PipeReader, nameRevS stderr := new(bytes.Buffer) var errbuf strings.Builder - if err := git.NewCommand(ctx, "name-rev", "--stdin", "--name-only", "--always").RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: tmpBasePath, - Stdout: nameRevStdinWriter, - Stdin: shasToNameReader, - Stderr: stderr, + if err := git.NewCommand(ctx, "name-rev", "--stdin", "--name-only", "--always").Run(&git.RunOpts{ + Dir: tmpBasePath, + Stdout: nameRevStdinWriter, + Stdin: shasToNameReader, + Stderr: stderr, }); err != nil { _ = shasToNameReader.CloseWithError(fmt.Errorf("git name-rev [%s]: %v - %s", tmpBasePath, err, errbuf.String())) } diff --git a/modules/git/pipeline/revlist.go b/modules/git/pipeline/revlist.go index a1f8f079f9..02619cb583 100644 --- a/modules/git/pipeline/revlist.go +++ b/modules/git/pipeline/revlist.go @@ -25,11 +25,10 @@ func RevListAllObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sy stderr := new(bytes.Buffer) var errbuf strings.Builder cmd := git.NewCommand(ctx, "rev-list", "--objects", "--all") - if err := cmd.RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: basePath, - Stdout: revListWriter, - Stderr: stderr, + if err := cmd.Run(&git.RunOpts{ + Dir: basePath, + Stdout: revListWriter, + Stderr: stderr, }); err != nil { 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()) @@ -45,11 +44,10 @@ func RevListObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sync. stderr := new(bytes.Buffer) var errbuf strings.Builder cmd := git.NewCommand(ctx, "rev-list", "--objects", headSHA, "--not", baseSHA) - if err := cmd.RunWithContext(&git.RunContext{ - Timeout: -1, - Dir: tmpBasePath, - Stdout: revListWriter, - Stderr: stderr, + if err := cmd.Run(&git.RunOpts{ + Dir: tmpBasePath, + Stdout: revListWriter, + Stderr: stderr, }); err != nil { 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()) diff --git a/modules/git/remote.go b/modules/git/remote.go index dfd0686d8b..536b1681ce 100644 --- a/modules/git/remote.go +++ b/modules/git/remote.go @@ -22,7 +22,7 @@ func GetRemoteAddress(ctx context.Context, repoPath, remoteName string) (*url.UR cmd = NewCommand(ctx, "config", "--get", "remote."+remoteName+".url") } - result, err := cmd.RunInDir(repoPath) + result, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return nil, err } diff --git a/modules/git/repo.go b/modules/git/repo.go index b06b7feea2..3176e27695 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -59,7 +59,7 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro // IsRepoURLAccessible checks if given repository URL is accessible. func IsRepoURLAccessible(ctx context.Context, url string) bool { - _, err := NewCommand(ctx, "ls-remote", "-q", "-h", url, "HEAD").Run() + _, _, err := NewCommand(ctx, "ls-remote", "-q", "-h", url, "HEAD").RunStdString(nil) return err == nil } @@ -74,7 +74,7 @@ func InitRepository(ctx context.Context, repoPath string, bare bool) error { if bare { cmd.AddArguments("--bare") } - _, err = cmd.RunInDir(repoPath) + _, _, err = cmd.RunStdString(&RunOpts{Dir: repoPath}) return err } @@ -82,11 +82,10 @@ func InitRepository(ctx context.Context, repoPath string, bare bool) error { func (repo *Repository) IsEmpty() (bool, error) { var errbuf, output strings.Builder if err := NewCommand(repo.Ctx, "show-ref", "--head", "^HEAD$"). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: &output, - Stderr: &errbuf, + Run(&RunOpts{ + Dir: repo.Path, + Stdout: &output, + Stderr: &errbuf, }); err != nil { if err.Error() == "exit status 1" && errbuf.String() == "" { return true, nil @@ -174,7 +173,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo } stderr := new(bytes.Buffer) - if err = cmd.RunWithContext(&RunContext{ + if err = cmd.Run(&RunOpts{ Timeout: opts.Timeout, Env: envs, Stdout: io.Discard, @@ -219,7 +218,7 @@ func Push(ctx context.Context, repoPath string, opts PushOptions) error { opts.Timeout = -1 } - err := cmd.RunWithContext(&RunContext{ + err := cmd.Run(&RunOpts{ Env: opts.Env, Timeout: opts.Timeout, Dir: repoPath, @@ -261,7 +260,7 @@ func Push(ctx context.Context, repoPath string, opts PushOptions) error { // GetLatestCommitTime returns time for latest commit in repository (across all branches) func GetLatestCommitTime(ctx context.Context, repoPath string) (time.Time, error) { cmd := NewCommand(ctx, "for-each-ref", "--sort=-committerdate", BranchPrefix, "--count", "1", "--format=%(committerdate)") - stdout, err := cmd.RunInDir(repoPath) + stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return time.Time{}, err } @@ -278,7 +277,7 @@ type DivergeObject struct { func checkDivergence(ctx context.Context, repoPath, baseBranch, targetBranch string) (int, error) { branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) cmd := NewCommand(ctx, "rev-list", "--count", branches) - stdout, err := cmd.RunInDir(repoPath) + stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return -1, err } @@ -315,23 +314,23 @@ func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io. defer os.RemoveAll(tmp) env := append(os.Environ(), "GIT_OBJECT_DIRECTORY="+filepath.Join(repo.Path, "objects")) - _, err = NewCommand(ctx, "init", "--bare").RunInDirWithEnv(tmp, env) + _, _, err = NewCommand(ctx, "init", "--bare").RunStdString(&RunOpts{Dir: tmp, Env: env}) if err != nil { return err } - _, err = NewCommand(ctx, "reset", "--soft", commit).RunInDirWithEnv(tmp, env) + _, _, err = NewCommand(ctx, "reset", "--soft", commit).RunStdString(&RunOpts{Dir: tmp, Env: env}) if err != nil { return err } - _, err = NewCommand(ctx, "branch", "-m", "bundle").RunInDirWithEnv(tmp, env) + _, _, err = NewCommand(ctx, "branch", "-m", "bundle").RunStdString(&RunOpts{Dir: tmp, Env: env}) if err != nil { return err } tmpFile := filepath.Join(tmp, "bundle") - _, err = NewCommand(ctx, "bundle", "create", tmpFile, "bundle", "HEAD").RunInDirWithEnv(tmp, env) + _, _, err = NewCommand(ctx, "bundle", "create", tmpFile, "bundle", "HEAD").RunStdString(&RunOpts{Dir: tmp, Env: env}) if err != nil { return err } diff --git a/modules/git/repo_archive.go b/modules/git/repo_archive.go index b7c339c271..4a97989949 100644 --- a/modules/git/repo_archive.go +++ b/modules/git/repo_archive.go @@ -57,11 +57,10 @@ func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, t ) var stderr strings.Builder - err := NewCommand(ctx, args...).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: target, - Stderr: &stderr, + err := NewCommand(ctx, args...).Run(&RunOpts{ + Dir: repo.Path, + Stdout: target, + Stderr: &stderr, }) if err != nil { return ConcatenateError(err, stderr.String()) diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index ce24b0a7a3..6481474a96 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -76,12 +76,11 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[ cmd := NewCommand(repo.Ctx, cmdArgs...) - if err := cmd.RunWithContext(&RunContext{ - Env: env, - Timeout: -1, - Dir: repo.Path, - Stdout: stdOut, - Stderr: stdErr, + if err := cmd.Run(&RunOpts{ + Env: env, + Dir: repo.Path, + Stdout: stdOut, + Stderr: stdErr, }); err != nil { return nil, fmt.Errorf("failed to run check-attr: %v\n%s\n%s", err, stdOut.String(), stdErr.String()) } @@ -189,13 +188,12 @@ func (c *CheckAttributeReader) Run() error { _ = c.stdOut.Close() }() stdErr := new(bytes.Buffer) - err := c.cmd.RunWithContext(&RunContext{ - Env: c.env, - Timeout: -1, - Dir: c.Repo.Path, - Stdin: c.stdinReader, - Stdout: c.stdOut, - Stderr: stdErr, + err := c.cmd.Run(&RunOpts{ + Env: c.env, + Dir: c.Repo.Path, + Stdin: c.stdinReader, + Stdout: c.stdOut, + Stderr: stdErr, PipelineFunc: func(_ context.Context, _ context.CancelFunc) error { select { case <-c.running: diff --git a/modules/git/repo_blame.go b/modules/git/repo_blame.go index a71122527f..6fe6d235ba 100644 --- a/modules/git/repo_blame.go +++ b/modules/git/repo_blame.go @@ -8,12 +8,13 @@ import "fmt" // FileBlame return the Blame object of file func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { - return NewCommand(repo.Ctx, "blame", "--root", "--", file).RunInDirBytes(path) + stdout, _, err := NewCommand(repo.Ctx, "blame", "--root", "--", file).RunStdBytes(&RunOpts{Dir: path}) + return stdout, err } // LineBlame returns the latest commit at the given line func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { - res, err := NewCommand(repo.Ctx, "blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) + res, _, err := NewCommand(repo.Ctx, "blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunStdString(&RunOpts{Dir: path}) if err != nil { return nil, err } diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go index e0d47ad7ac..8e455480e7 100644 --- a/modules/git/repo_branch.go +++ b/modules/git/repo_branch.go @@ -24,7 +24,7 @@ const PullRequestPrefix = "refs/for/" // IsReferenceExist returns true if given reference exists in the repository. func IsReferenceExist(ctx context.Context, repoPath, name string) bool { - _, err := NewCommand(ctx, "show-ref", "--verify", "--", name).RunInDir(repoPath) + _, _, err := NewCommand(ctx, "show-ref", "--verify", "--", name).RunStdString(&RunOpts{Dir: repoPath}) return err == nil } @@ -46,7 +46,7 @@ func (repo *Repository) GetHEADBranch() (*Branch, error) { if repo == nil { return nil, fmt.Errorf("nil repo") } - stdout, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -65,13 +65,14 @@ func (repo *Repository) GetHEADBranch() (*Branch, error) { // SetDefaultBranch sets default branch of repository. func (repo *Repository) SetDefaultBranch(name string) error { - _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD", BranchPrefix+name).RunStdString(&RunOpts{Dir: repo.Path}) return err } // GetDefaultBranch gets default branch of repository. func (repo *Repository) GetDefaultBranch() (string, error) { - return NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").RunStdString(&RunOpts{Dir: repo.Path}) + return stdout, err } // GetBranch returns a branch by it's name @@ -133,7 +134,7 @@ func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) erro } cmd.AddArguments("--", name) - _, err := cmd.RunInDir(repo.Path) + _, _, err := cmd.RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -143,7 +144,7 @@ func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error { cmd := NewCommand(repo.Ctx, "branch") cmd.AddArguments("--", branch, oldbranchOrCommit) - _, err := cmd.RunInDir(repo.Path) + _, _, err := cmd.RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -156,13 +157,13 @@ func (repo *Repository) AddRemote(name, url string, fetch bool) error { } cmd.AddArguments(name, url) - _, err := cmd.RunInDir(repo.Path) + _, _, err := cmd.RunStdString(&RunOpts{Dir: repo.Path}) return err } // RemoveRemote removes a remote from repository. func (repo *Repository) RemoveRemote(name string) error { - _, err := NewCommand(repo.Ctx, "remote", "rm", name).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "remote", "rm", name).RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -173,6 +174,6 @@ func (branch *Branch) GetCommit() (*Commit, error) { // RenameBranch rename a branch func (repo *Repository) RenameBranch(from, to string) error { - _, err := NewCommand(repo.Ctx, "branch", "-m", from, to).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "branch", "-m", from, to).RunStdString(&RunOpts{Dir: repo.Path}) return err } diff --git a/modules/git/repo_branch_nogogit.go b/modules/git/repo_branch_nogogit.go index f595b6d9a8..4393db10f9 100644 --- a/modules/git/repo_branch_nogogit.go +++ b/modules/git/repo_branch_nogogit.go @@ -112,11 +112,10 @@ func walkShowRef(ctx context.Context, repoPath, arg string, skip, limit int, wal if arg != "" { args = append(args, arg) } - err := NewCommand(ctx, args...).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repoPath, - Stdout: stdoutWriter, - Stderr: stderrBuilder, + err := NewCommand(ctx, args...).Run(&RunOpts{ + Dir: repoPath, + Stdout: stdoutWriter, + Stderr: stderrBuilder, }) if err != nil { if stderrBuilder.Len() == 0 { diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index 8e059ce0ea..e6fec4d1a3 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -58,12 +58,12 @@ func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, relpath = `\` + relpath } - stdout, err := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) - if err != nil { - return nil, err + stdout, _, runErr := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, id.String(), "--", relpath).RunStdString(&RunOpts{Dir: repo.Path}) + if runErr != nil { + return nil, runErr } - id, err = NewIDFromString(stdout) + id, err := NewIDFromString(stdout) if err != nil { return nil, err } @@ -73,9 +73,9 @@ func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, // GetCommitByPath returns the last commit of relative path. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { - stdout, err := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path) - if err != nil { - return nil, err + stdout, _, runErr := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat, "--", relpath).RunStdBytes(&RunOpts{Dir: repo.Path}) + if runErr != nil { + return nil, runErr } commits, err := repo.parsePrettyFormatLogToList(stdout) @@ -86,8 +86,8 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { } func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) { - stdout, err := NewCommand(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize), - "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize), + "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -139,7 +139,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co // search for commits matching given constraints and keywords in commit msg cmd.AddArguments(args...) - stdout, err := cmd.RunInDirBytes(repo.Path) + stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -161,7 +161,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co hashCmd.AddArguments(v) // search with given constraints for commit matching sha hash of v - hashMatching, err := hashCmd.RunInDirBytes(repo.Path) + hashMatching, _, err := hashCmd.RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil || bytes.Contains(stdout, hashMatching) { continue } @@ -175,7 +175,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co } func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) { - stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", id1, id2).RunInDirBytes(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only", id1, id2).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { 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 // You must ensure that id1 and id2 are valid commit ids. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) { - stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only", "-z", id1, id2, "--", filename).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return false, err } @@ -211,11 +211,10 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) ( err := NewCommand(repo.Ctx, "log", revision, "--follow", "--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize*page), prettyLogFormat, "--", file). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: stdoutWriter, - Stderr: &stderr, + Run(&RunOpts{ + Dir: repo.Path, + Stdout: stdoutWriter, + Stderr: &stderr, }) if err != nil { _ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String())) @@ -244,8 +243,8 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) ( // CommitsByFileAndRangeNoFollow return the commits according revision file and the page func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) ([]*Commit, error) { - 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) + stdout, _, err := NewCommand(repo.Ctx, "log", revision, "--skip="+strconv.Itoa((page-1)*50), + "--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize), prettyLogFormat, "--", file).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -254,11 +253,11 @@ func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, pag // FilesCountBetween return the number of files changed between two commits func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { - stdout, err := NewCommand(repo.Ctx, "diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only", startCommitID+"..."+endCommitID).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil && strings.Contains(err.Error(), "no merge base") { // git >= 2.28 now returns an error if startCommitID and endCommitID have become unrelated. // previously it would return the results of git diff --name-only startCommitID endCommitID so let's try that... - stdout, err = NewCommand(repo.Ctx, "diff", "--name-only", startCommitID, endCommitID).RunInDir(repo.Path) + stdout, _, err = NewCommand(repo.Ctx, "diff", "--name-only", startCommitID, endCommitID).RunStdString(&RunOpts{Dir: repo.Path}) } if err != nil { return 0, err @@ -272,13 +271,13 @@ func (repo *Repository) CommitsBetween(last, before *Commit) ([]*Commit, error) var stdout []byte var err error if before == nil { - stdout, err = NewCommand(repo.Ctx, "rev-list", last.ID.String()).RunInDirBytes(repo.Path) + stdout, _, err = NewCommand(repo.Ctx, "rev-list", last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) } else { - stdout, err = NewCommand(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()).RunStdBytes(&RunOpts{Dir: repo.Path}) 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. // previously it would return the results of git rev-list before last so let's try that... - stdout, err = NewCommand(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()).RunStdBytes(&RunOpts{Dir: repo.Path}) } } if err != nil { @@ -292,13 +291,13 @@ func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip in var stdout []byte var err error if before == nil { - stdout, err = NewCommand(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()).RunStdBytes(&RunOpts{Dir: repo.Path}) } else { - 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) + stdout, _, err = NewCommand(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String()+".."+last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) 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. // previously it would return the results of git rev-list --max-count n before last so let's try that... - 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) + stdout, _, err = NewCommand(repo.Ctx, "rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) } } if err != nil { @@ -344,9 +343,9 @@ func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) { cmd.AddArguments(prettyLogFormat, id.String()) } - stdout, err := cmd.RunInDirBytes(repo.Path) - if err != nil { - return nil, err + stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path}) + if runErr != nil { + return nil, runErr } formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) @@ -381,7 +380,7 @@ func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) ([]*Commit, erro func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { if CheckGitVersionAtLeast("2.7.0") == nil { - stdout, err := NewCommand(repo.Ctx, "for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -390,7 +389,7 @@ func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) return branches, nil } - stdout, err := NewCommand(repo.Ctx, "branch", "--contains", commit.ID.String()).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains", commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -429,7 +428,7 @@ func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit { // IsCommitInBranch check if the commit is on the branch func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) { - stdout, err := NewCommand(repo.Ctx, "branch", "--contains", commitID, branch).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains", commitID, branch).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return false, err } diff --git a/modules/git/repo_commit_gogit.go b/modules/git/repo_commit_gogit.go index 3693f7883f..f3504f25d8 100644 --- a/modules/git/repo_commit_gogit.go +++ b/modules/git/repo_commit_gogit.go @@ -50,7 +50,7 @@ func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) { } } - actualCommitID, err := NewCommand(repo.Ctx, "rev-parse", "--verify", commitID).RunInDir(repo.Path) + actualCommitID, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify", commitID).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { if strings.Contains(err.Error(), "unknown revision or path") || strings.Contains(err.Error(), "fatal: Needed a single revision") { diff --git a/modules/git/repo_commit_nogogit.go b/modules/git/repo_commit_nogogit.go index b65565c98c..c9afe35b1a 100644 --- a/modules/git/repo_commit_nogogit.go +++ b/modules/git/repo_commit_nogogit.go @@ -18,7 +18,7 @@ import ( // ResolveReference resolves a name to a reference func (repo *Repository) ResolveReference(name string) (string, error) { - stdout, err := NewCommand(repo.Ctx, "show-ref", "--hash", name).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "show-ref", "--hash", name).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { if strings.Contains(err.Error(), "not a valid ref") { 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). func (repo *Repository) SetReference(name, commitID string) error { - _, err := NewCommand(repo.Ctx, "update-ref", name, commitID).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "update-ref", name, commitID).RunStdString(&RunOpts{Dir: repo.Path}) return err } // RemoveReference removes the given reference (e.g. branch or tag). func (repo *Repository) RemoveReference(name string) error { - _, err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d", name).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d", name).RunStdString(&RunOpts{Dir: repo.Path}) return err } // IsCommitExist returns true if given commit exists in current repository. func (repo *Repository) IsCommitExist(name string) bool { - _, err := NewCommand(repo.Ctx, "cat-file", "-e", name).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "cat-file", "-e", name).RunStdString(&RunOpts{Dir: repo.Path}) return err == nil } diff --git a/modules/git/repo_commitgraph.go b/modules/git/repo_commitgraph.go index 5549c92591..075b59ad06 100644 --- a/modules/git/repo_commitgraph.go +++ b/modules/git/repo_commitgraph.go @@ -13,7 +13,7 @@ import ( // this requires git v2.18 to be installed func WriteCommitGraph(ctx context.Context, repoPath string) error { if CheckGitVersionAtLeast("2.18") == nil { - if _, err := NewCommand(ctx, "commit-graph", "write").RunInDir(repoPath); err != nil { + if _, _, err := NewCommand(ctx, "commit-graph", "write").RunStdString(&RunOpts{Dir: repoPath}); err != nil { return fmt.Errorf("unable to write commit-graph for '%s' : %w", repoPath, err) } } diff --git a/modules/git/repo_compare.go b/modules/git/repo_compare.go index aa8015af14..f6b4f77645 100644 --- a/modules/git/repo_compare.go +++ b/modules/git/repo_compare.go @@ -40,13 +40,13 @@ func (repo *Repository) GetMergeBase(tmpRemote, base, head string) (string, stri if tmpRemote != "origin" { tmpBaseName := RemotePrefix + tmpRemote + "/tmp_" + base // Fetch commit into a temporary branch in order to be able to handle commits and tags - _, err := NewCommand(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunStdString(&RunOpts{Dir: repo.Path}) if err == nil { base = tmpBaseName } } - stdout, err := NewCommand(repo.Ctx, "merge-base", "--", base, head).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "merge-base", "--", base, head).RunStdString(&RunOpts{Dir: repo.Path}) return strings.TrimSpace(stdout), base, err } @@ -93,7 +93,8 @@ func (repo *Repository) GetCompareInfo(basePath, baseBranch, headBranch string, // We have a common base - therefore we know that ... should work if !fileOnly { - logs, err := NewCommand(repo.Ctx, "log", baseCommitID+separator+headBranch, prettyLogFormat).RunInDirBytes(repo.Path) + var logs []byte + logs, _, err = NewCommand(repo.Ctx, "log", baseCommitID+separator+headBranch, prettyLogFormat).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -147,22 +148,20 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis } if err := NewCommand(repo.Ctx, "diff", "-z", "--name-only", base+separator+head). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, - Stderr: stderr, + Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, + Stderr: stderr, }); err != nil { if strings.Contains(stderr.String(), "no merge base") { // 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... w = &lineCountWriter{} stderr.Reset() - if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only", base, head).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, - Stderr: stderr, + if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only", base, head).Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, + Stderr: stderr, }); err == nil { return w.numLines, nil } @@ -192,7 +191,7 @@ func GetDiffShortStat(ctx context.Context, repoPath string, args ...string) (num "--shortstat", }, args...) - stdout, err := NewCommand(ctx, args...).RunInDir(repoPath) + stdout, _, err := NewCommand(ctx, args...).RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return 0, 0, 0, err } @@ -248,26 +247,23 @@ 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 func (repo *Repository) GetDiff(base, head string, w io.Writer) error { - return NewCommand(repo.Ctx, "diff", "-p", base, head).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, + return NewCommand(repo.Ctx, "diff", "-p", base, head).Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, }) } // GetDiffBinary generates and returns patch data between given revisions, including binary diffs. func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error { if CheckGitVersionAtLeast("1.7.7") == nil { - return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram", base, head).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, + return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram", base, head).Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, }) } - return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--patience", base, head).RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, + return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--patience", base, head).Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, }) } @@ -275,18 +271,16 @@ func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error { func (repo *Repository) GetPatch(base, head string, w io.Writer) error { stderr := new(bytes.Buffer) err := NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout", base+"..."+head). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, - Stderr: stderr, + Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, + Stderr: stderr, }) if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) { return NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout", base, head). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, + Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, }) } return err @@ -296,11 +290,10 @@ func (repo *Repository) GetPatch(base, head string, w io.Writer) error { func (repo *Repository) GetDiffFromMergeBase(base, head string, w io.Writer) error { stderr := new(bytes.Buffer) err := NewCommand(repo.Ctx, "diff", "-p", "--binary", base+"..."+head). - RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: w, - Stderr: stderr, + Run(&RunOpts{ + Dir: repo.Path, + Stdout: w, + Stderr: stderr, }) if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) { return repo.GetDiffBinary(base, head, w) diff --git a/modules/git/repo_gpg.go b/modules/git/repo_gpg.go index 14eb894be6..abbb349159 100644 --- a/modules/git/repo_gpg.go +++ b/modules/git/repo_gpg.go @@ -34,7 +34,7 @@ func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, Sign: true, } - value, _ := NewCommand(repo.Ctx, "config", "--get", "commit.gpgsign").RunInDir(repo.Path) + value, _, _ := NewCommand(repo.Ctx, "config", "--get", "commit.gpgsign").RunStdString(&RunOpts{Dir: repo.Path}) sign, valid := ParseBool(strings.TrimSpace(value)) if !sign || !valid { gpgSettings.Sign = false @@ -42,13 +42,13 @@ func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, return gpgSettings, nil } - signingKey, _ := NewCommand(repo.Ctx, "config", "--get", "user.signingkey").RunInDir(repo.Path) + signingKey, _, _ := NewCommand(repo.Ctx, "config", "--get", "user.signingkey").RunStdString(&RunOpts{Dir: repo.Path}) gpgSettings.KeyID = strings.TrimSpace(signingKey) - defaultEmail, _ := NewCommand(repo.Ctx, "config", "--get", "user.email").RunInDir(repo.Path) + defaultEmail, _, _ := NewCommand(repo.Ctx, "config", "--get", "user.email").RunStdString(&RunOpts{Dir: repo.Path}) gpgSettings.Email = strings.TrimSpace(defaultEmail) - defaultName, _ := NewCommand(repo.Ctx, "config", "--get", "user.name").RunInDir(repo.Path) + defaultName, _, _ := NewCommand(repo.Ctx, "config", "--get", "user.name").RunStdString(&RunOpts{Dir: repo.Path}) gpgSettings.Name = strings.TrimSpace(defaultName) if err := gpgSettings.LoadPublicKeyContent(); err != nil { diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index 53de0f1cb8..ae68dcaa87 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -18,7 +18,7 @@ import ( // ReadTreeToIndex reads a treeish to the index func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error { if len(treeish) != 40 { - res, err := NewCommand(repo.Ctx, "rev-parse", "--verify", treeish).RunInDir(repo.Path) + res, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify", treeish).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return err } @@ -38,7 +38,7 @@ func (repo *Repository) readTreeToIndex(id SHA1, indexFilename ...string) error if len(indexFilename) > 0 { env = append(os.Environ(), "GIT_INDEX_FILE="+indexFilename[0]) } - _, err := NewCommand(repo.Ctx, "read-tree", id.String()).RunInDirWithEnv(repo.Path, env) + _, _, err := NewCommand(repo.Ctx, "read-tree", id.String()).RunStdString(&RunOpts{Dir: repo.Path, Env: env}) if err != nil { return err } @@ -69,7 +69,7 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename, tmpD // EmptyIndex empties the index func (repo *Repository) EmptyIndex() error { - _, err := NewCommand(repo.Ctx, "read-tree", "--empty").RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "read-tree", "--empty").RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -81,7 +81,7 @@ func (repo *Repository) LsFiles(filenames ...string) ([]string, error) { cmd.AddArguments(arg) } } - res, err := cmd.RunInDirBytes(repo.Path) + res, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -106,29 +106,28 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error { buffer.WriteByte('\000') } } - return cmd.RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdin: bytes.NewReader(buffer.Bytes()), - Stdout: stdout, - Stderr: stderr, + return cmd.Run(&RunOpts{ + Dir: repo.Path, + Stdin: bytes.NewReader(buffer.Bytes()), + Stdout: stdout, + Stderr: stderr, }) } // AddObjectToIndex adds the provided object hash to the index at the provided filename func (repo *Repository) AddObjectToIndex(mode string, object SHA1, filename string) error { cmd := NewCommand(repo.Ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, object.String(), filename) - _, err := cmd.RunInDir(repo.Path) + _, _, err := cmd.RunStdString(&RunOpts{Dir: repo.Path}) return err } // WriteTree writes the current index as a tree to the object db and returns its hash func (repo *Repository) WriteTree() (*Tree, error) { - res, err := NewCommand(repo.Ctx, "write-tree").RunInDir(repo.Path) - if err != nil { - return nil, err + stdout, _, runErr := NewCommand(repo.Ctx, "write-tree").RunStdString(&RunOpts{Dir: repo.Path}) + if runErr != nil { + return nil, runErr } - id, err := NewIDFromString(strings.TrimSpace(res)) + id, err := NewIDFromString(strings.TrimSpace(stdout)) if err != nil { return nil, err } diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index 378e657ce4..af448b0110 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -45,12 +45,11 @@ func (repo *Repository) hashObject(reader io.Reader) (string, error) { cmd := NewCommand(repo.Ctx, "hash-object", "-w", "--stdin") stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) - err := cmd.RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdin: reader, - Stdout: stdout, - Stderr: stderr, + err := cmd.Run(&RunOpts{ + Dir: repo.Path, + Stdin: reader, + Stdout: stdout, + Stderr: stderr, }) if err != nil { return "", err diff --git a/modules/git/repo_ref_nogogit.go b/modules/git/repo_ref_nogogit.go index 42295e43ac..40e8a247c7 100644 --- a/modules/git/repo_ref_nogogit.go +++ b/modules/git/repo_ref_nogogit.go @@ -23,11 +23,10 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) { go func() { stderrBuilder := &strings.Builder{} - err := NewCommand(repo.Ctx, "for-each-ref").RunWithContext(&RunContext{ - Timeout: -1, - Dir: repo.Path, - Stdout: stdoutWriter, - Stderr: stderrBuilder, + err := NewCommand(repo.Ctx, "for-each-ref").Run(&RunOpts{ + Dir: repo.Path, + Stdout: stdoutWriter, + Stderr: stderrBuilder, }) if err != nil { _ = stdoutWriter.CloseWithError(ConcatenateError(err, stderrBuilder.String())) diff --git a/modules/git/repo_stats.go b/modules/git/repo_stats.go index 598ec37a2c..c0c91c6fc6 100644 --- a/modules/git/repo_stats.go +++ b/modules/git/repo_stats.go @@ -39,12 +39,12 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string) since := fromTime.Format(time.RFC3339) - stdout, err := NewCommand(repo.Ctx, "rev-list", "--count", "--no-merges", "--branches=*", "--date=iso", fmt.Sprintf("--since='%s'", since)).RunInDirBytes(repo.Path) - if err != nil { - return nil, err + stdout, _, runErr := NewCommand(repo.Ctx, "rev-list", "--count", "--no-merges", "--branches=*", "--date=iso", fmt.Sprintf("--since='%s'", since)).RunStdString(&RunOpts{Dir: repo.Path}) + if runErr != nil { + return nil, runErr } - c, err := strconv.ParseInt(strings.TrimSpace(string(stdout)), 10, 64) + c, err := strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) if err != nil { return nil, err } @@ -67,12 +67,11 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string) } stderr := new(strings.Builder) - err = NewCommand(repo.Ctx, args...).RunWithContext(&RunContext{ - Env: []string{}, - Timeout: -1, - Dir: repo.Path, - Stdout: stdoutWriter, - Stderr: stderr, + err = NewCommand(repo.Ctx, args...).Run(&RunOpts{ + Env: []string{}, + Dir: repo.Path, + Stdout: stdoutWriter, + Stderr: stderr, PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error { _ = stdoutWriter.Close() scanner := bufio.NewScanner(stdoutReader) diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 8886ad0a6b..8444e8d035 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -25,13 +25,13 @@ func IsTagExist(ctx context.Context, repoPath, name string) bool { // CreateTag create one tag in the repository func (repo *Repository) CreateTag(name, revision string) error { - _, err := NewCommand(repo.Ctx, "tag", "--", name, revision).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "tag", "--", name, revision).RunStdString(&RunOpts{Dir: repo.Path}) return err } // CreateAnnotatedTag create one annotated tag in the repository func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error { - _, err := NewCommand(repo.Ctx, "tag", "-a", "-m", message, "--", name, revision).RunInDir(repo.Path) + _, _, err := NewCommand(repo.Ctx, "tag", "-a", "-m", message, "--", name, revision).RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -41,7 +41,7 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) { return "", fmt.Errorf("SHA is too short: %s", sha) } - stdout, err := NewCommand(repo.Ctx, "show-ref", "--tags", "-d").RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "show-ref", "--tags", "-d").RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return "", err } @@ -64,7 +64,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) func (repo *Repository) GetTagID(name string) (string, error) { - stdout, err := NewCommand(repo.Ctx, "show-ref", "--tags", "--", name).RunInDir(repo.Path) + stdout, _, err := NewCommand(repo.Ctx, "show-ref", "--tags", "--", name).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return "", err } @@ -119,10 +119,10 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { defer stdoutReader.Close() defer stdoutWriter.Close() stderr := strings.Builder{} - rc := &RunContext{Dir: repo.Path, Stdout: stdoutWriter, Stderr: &stderr, Timeout: -1} + rc := &RunOpts{Dir: repo.Path, Stdout: stdoutWriter, Stderr: &stderr} go func() { - err := NewCommand(repo.Ctx, "for-each-ref", "--format", forEachRefFmt.Flag(), "--sort", "-*creatordate", "refs/tags").RunWithContext(rc) + err := NewCommand(repo.Ctx, "for-each-ref", "--format", forEachRefFmt.Flag(), "--sort", "-*creatordate", "refs/tags").Run(rc) if err != nil { _ = stdoutWriter.CloseWithError(ConcatenateError(err, stderr.String())) } else { diff --git a/modules/git/repo_tree.go b/modules/git/repo_tree.go index 3219b569a5..3e7a9c2cfb 100644 --- a/modules/git/repo_tree.go +++ b/modules/git/repo_tree.go @@ -60,13 +60,12 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) - err = cmd.RunWithContext(&RunContext{ - Env: env, - Timeout: -1, - Dir: repo.Path, - Stdin: messageBytes, - Stdout: stdout, - Stderr: stderr, + err = cmd.Run(&RunOpts{ + Env: env, + Dir: repo.Path, + Stdin: messageBytes, + Stdout: stdout, + Stderr: stderr, }) if err != nil { diff --git a/modules/git/repo_tree_gogit.go b/modules/git/repo_tree_gogit.go index 0089d2c9a4..cc156ea916 100644 --- a/modules/git/repo_tree_gogit.go +++ b/modules/git/repo_tree_gogit.go @@ -22,7 +22,7 @@ func (repo *Repository) getTree(id SHA1) (*Tree, error) { // GetTree find the tree object in the repository. func (repo *Repository) GetTree(idStr string) (*Tree, error) { if len(idStr) != 40 { - res, err := NewCommand(repo.Ctx, "rev-parse", "--verify", idStr).RunInDir(repo.Path) + res, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify", idStr).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } diff --git a/modules/git/tree.go b/modules/git/tree.go index f34e0554d7..a83336f3db 100644 --- a/modules/git/tree.go +++ b/modules/git/tree.go @@ -55,7 +55,7 @@ func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error cmd.AddArguments(arg) } } - res, err := cmd.RunInDirBytes(repo.Path) + res, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } diff --git a/modules/git/tree_nogogit.go b/modules/git/tree_nogogit.go index d02fe8a006..f852c5a51e 100644 --- a/modules/git/tree_nogogit.go +++ b/modules/git/tree_nogogit.go @@ -81,16 +81,17 @@ func (t *Tree) ListEntries() (Entries, error) { } } - stdout, err := NewCommand(t.repo.Ctx, "ls-tree", "-l", t.ID.String()).RunInDirBytes(t.repo.Path) - if err != nil { - if strings.Contains(err.Error(), "fatal: Not a valid object name") || strings.Contains(err.Error(), "fatal: not a tree object") { + stdout, _, runErr := NewCommand(t.repo.Ctx, "ls-tree", "-l", t.ID.String()).RunStdBytes(&RunOpts{Dir: t.repo.Path}) + if runErr != nil { + if strings.Contains(runErr.Error(), "fatal: Not a valid object name") || strings.Contains(runErr.Error(), "fatal: not a tree object") { return nil, ErrNotExist{ ID: t.ID.String(), } } - return nil, err + return nil, runErr } + var err error t.entries, err = parseTreeEntries(stdout, t) if err == nil { t.entriesParsed = true @@ -104,11 +105,13 @@ func (t *Tree) ListEntriesRecursive() (Entries, error) { if t.entriesRecursiveParsed { return t.entriesRecursive, nil } - stdout, err := NewCommand(t.repo.Ctx, "ls-tree", "-t", "-l", "-r", t.ID.String()).RunInDirBytes(t.repo.Path) - if err != nil { - return nil, err + + stdout, _, runErr := NewCommand(t.repo.Ctx, "ls-tree", "-t", "-l", "-r", t.ID.String()).RunStdBytes(&RunOpts{Dir: t.repo.Path}) + if runErr != nil { + return nil, runErr } + var err error t.entriesRecursive, err = parseTreeEntries(stdout, t) if err == nil { t.entriesRecursiveParsed = true |