Skip to content

Commit d98c5db

Browse files
wxiaoguang6543
andauthored
alternative to PR "improve code quality" (#21464)
This PR doesn't require new git version, and can be backported easily. Co-authored-by: 6543 <[email protected]>
1 parent 7917123 commit d98c5db

File tree

6 files changed

+52
-25
lines changed

6 files changed

+52
-25
lines changed

modules/git/command.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,18 @@ func (c *Command) AddArguments(args ...string) *Command {
9595
return c
9696
}
9797

98+
// AddDynamicArguments adds new dynamic argument(s) to the command.
99+
// If the argument is invalid (it shouldn't happen in real life), it panics to caller
100+
func (c *Command) AddDynamicArguments(args ...string) *Command {
101+
for _, arg := range args {
102+
if arg != "" && arg[0] == '-' {
103+
panic("invalid argument: " + arg)
104+
}
105+
}
106+
c.args = append(c.args, args...)
107+
return c
108+
}
109+
98110
// RunOpts represents parameters to run the command. If UseContextTimeout is specified, then Timeout is ignored.
99111
type RunOpts struct {
100112
Env []string

modules/git/command_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,21 @@ func TestRunWithContextStd(t *testing.T) {
2626
assert.Contains(t, err.Error(), "exit status 129 - unknown option:")
2727
assert.Empty(t, stdout)
2828
}
29+
30+
assert.Panics(t, func() {
31+
cmd = NewCommand(context.Background())
32+
cmd.AddDynamicArguments("-test")
33+
})
34+
35+
assert.Panics(t, func() {
36+
cmd = NewCommand(context.Background())
37+
cmd.AddDynamicArguments("--test")
38+
})
39+
40+
subCmd := "version"
41+
cmd = NewCommand(context.Background()).AddDynamicArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production
42+
stdout, stderr, err = cmd.RunStdString(&RunOpts{})
43+
assert.NoError(t, err)
44+
assert.Empty(t, stderr)
45+
assert.Contains(t, stdout, "git version")
2946
}

modules/git/commit.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, file
166166
// CommitsCountFiles returns number of total commits of until given revision.
167167
func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath []string) (int64, error) {
168168
cmd := NewCommand(ctx, "rev-list", "--count")
169-
cmd.AddArguments(revision...)
169+
cmd.AddDynamicArguments(revision...)
170170
if len(relpath) > 0 {
171171
cmd.AddArguments("--")
172172
cmd.AddArguments(relpath...)

modules/git/repo_commit.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co
161161
// add previous arguments except for --grep and --all
162162
hashCmd.AddArguments(args...)
163163
// add keyword as <commit>
164-
hashCmd.AddArguments(v)
164+
hashCmd.AddDynamicArguments(v)
165165

166166
// search with given constraints for commit matching sha hash of v
167167
hashMatching, _, err := hashCmd.RunStdBytes(&RunOpts{Dir: repo.Path})
@@ -211,14 +211,17 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
211211
}()
212212
go func() {
213213
stderr := strings.Builder{}
214-
err := NewCommand(repo.Ctx, "rev-list", revision,
214+
gitCmd := NewCommand(repo.Ctx, "rev-list",
215215
"--max-count="+strconv.Itoa(setting.Git.CommitsRangeSize*page),
216-
"--skip="+strconv.Itoa(skip), "--", file).
217-
Run(&RunOpts{
218-
Dir: repo.Path,
219-
Stdout: stdoutWriter,
220-
Stderr: &stderr,
221-
})
216+
"--skip="+strconv.Itoa(skip),
217+
)
218+
gitCmd.AddDynamicArguments(revision)
219+
gitCmd.AddArguments("--", file)
220+
err := gitCmd.Run(&RunOpts{
221+
Dir: repo.Path,
222+
Stdout: stdoutWriter,
223+
Stderr: &stderr,
224+
})
222225
if err != nil {
223226
_ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
224227
} else {

modules/git/repo_stats.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,15 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
6161
_ = stdoutWriter.Close()
6262
}()
6363

64-
args := []string{"log", "--numstat", "--no-merges", "--pretty=format:---%n%h%n%aN%n%aE%n", "--date=iso", fmt.Sprintf("--since='%s'", since)}
64+
gitCmd := NewCommand(repo.Ctx, "log", "--numstat", "--no-merges", "--pretty=format:---%n%h%n%aN%n%aE%n", "--date=iso", fmt.Sprintf("--since='%s'", since))
6565
if len(branch) == 0 {
66-
args = append(args, "--branches=*")
66+
gitCmd.AddArguments("--branches=*")
6767
} else {
68-
args = append(args, "--first-parent", branch)
68+
gitCmd.AddArguments("--first-parent").AddDynamicArguments(branch)
6969
}
7070

7171
stderr := new(strings.Builder)
72-
err = NewCommand(repo.Ctx, args...).Run(&RunOpts{
72+
err = gitCmd.Run(&RunOpts{
7373
Env: []string{},
7474
Dir: repo.Path,
7575
Stdout: stdoutWriter,

modules/gitgraph/graph.go

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,35 +24,30 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo
2424
page = 1
2525
}
2626

27-
args := make([]string, 0, 12+len(branches)+len(files))
28-
29-
args = append(args, "--graph", "--date-order", "--decorate=full")
27+
graphCmd := git.NewCommand(r.Ctx, "log", "--graph", "--date-order", "--decorate=full")
3028

3129
if hidePRRefs {
32-
args = append(args, "--exclude="+git.PullPrefix+"*")
30+
graphCmd.AddArguments("--exclude=" + git.PullPrefix + "*")
3331
}
3432

3533
if len(branches) == 0 {
36-
args = append(args, "--all")
34+
graphCmd.AddArguments("--all")
3735
}
3836

39-
args = append(args,
37+
graphCmd.AddArguments(
4038
"-C",
4139
"-M",
4240
fmt.Sprintf("-n %d", setting.UI.GraphMaxCommitNum*page),
4341
"--date=iso",
4442
fmt.Sprintf("--pretty=format:%s", format))
4543

4644
if len(branches) > 0 {
47-
args = append(args, branches...)
45+
graphCmd.AddDynamicArguments(branches...)
4846
}
49-
args = append(args, "--")
5047
if len(files) > 0 {
51-
args = append(args, files...)
48+
graphCmd.AddArguments("--")
49+
graphCmd.AddArguments(files...)
5250
}
53-
54-
graphCmd := git.NewCommand(r.Ctx, "log")
55-
graphCmd.AddArguments(args...)
5651
graph := NewGraph()
5752

5853
stderr := new(strings.Builder)

0 commit comments

Comments
 (0)