forked from alibaba/open-code-review
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
344 lines (302 loc) · 9.55 KB
/
Copy pathgit.go
File metadata and controls
344 lines (302 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package diff
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"github.com/open-code-review/open-code-review/internal/gitcmd"
"github.com/open-code-review/open-code-review/internal/model"
)
// DiffContextLines defines the number of context lines around each changed hunk.
const DiffContextLines = 3
// providerDirIgnoreDirs: directory prefixes to always exclude from diff results.
var providerDirIgnoreDirs = []string{
".idea/",
".vscode/",
".svn/",
".git/",
"vendor/",
"node_modules/",
"target/",
".happypack/",
".cachefile/",
"_packages/",
"rpm/",
"pkgs/",
}
// Mode defines how the diff is retrieved.
type Mode int
const (
ModeWorkspace Mode = iota // current workspace (staged + unstaged + untracked)
ModeCommit // single commit vs its parent
ModeRange // merge-base(from,to)..to
)
// Provider retrieves and parse git diffs from a repository.
type Provider struct {
repoDir string
mode Mode
runner *gitcmd.Runner
// Range mode parameters
from, to string // from/to refs for range comparison
// Commit mode parameter
commit string // single commit hash/ref
mergeBase string // cached common ancestor for range mode
}
// NewProvider creates a Provider for range mode: from..to (via merge-base).
func NewProvider(repoDir, from, to string, runner *gitcmd.Runner) *Provider {
return &Provider{
repoDir: repoDir,
mode: ModeRange,
from: from,
to: to,
runner: runner,
}
}
// NewCommitProvider creates a Provider for commit mode: show changes introduced by a single commit.
func NewCommitProvider(repoDir, commit string, runner *gitcmd.Runner) *Provider {
return &Provider{
repoDir: repoDir,
mode: ModeCommit,
commit: commit,
runner: runner,
}
}
// NewWorkspaceProvider creates a Provider for workspace mode (current uncommitted changes).
func NewWorkspaceProvider(repoDir string, runner *gitcmd.Runner) *Provider {
return &Provider{
repoDir: repoDir,
mode: ModeWorkspace,
runner: runner,
}
}
// IsRangeMode returns true when comparing two refs.
func (p *Provider) IsRangeMode() bool {
return p.mode == ModeRange
}
// IsCommitMode returns true when analyzing a single commit.
func (p *Provider) IsCommitMode() bool {
return p.mode == ModeCommit
}
// MergeBase returns the computed merge-base commit hash for range mode.
func (p *Provider) MergeBase(ctx context.Context) string {
if p.mode != ModeRange || p.mergeBase != "" {
return p.mergeBase
}
p.mergeBase = p.computeMergeBase(ctx, p.from, p.to)
return p.mergeBase
}
// GetDiff returns all changes as parsed model.Diff structs.
func (p *Provider) GetDiff(ctx context.Context) ([]model.Diff, error) {
var combined strings.Builder
switch p.mode {
case ModeRange:
base := p.MergeBase(ctx)
if base == "" {
return nil, fmt.Errorf("cannot find merge-base between %s and %s", p.from, p.to)
}
out, err := p.runGit(ctx, "-c", "core.quotepath=false", "diff", "--no-ext-diff", "--no-textconv", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--no-color", "-U"+fmt.Sprint(DiffContextLines), "--end-of-options", base, p.to, "--")
if err != nil {
return nil, fmt.Errorf("git diff failed: %w", err)
}
combined.WriteString(out)
case ModeCommit:
out, err := p.runGit(ctx, "-c", "core.quotepath=false", "show", "--no-ext-diff", "--no-textconv", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--no-color", "-U"+fmt.Sprint(DiffContextLines), "--end-of-options", p.commit)
if err != nil {
return nil, fmt.Errorf("git show failed: %w", err)
}
combined.WriteString(out)
case ModeWorkspace:
tracked, err := p.workspaceTrackedDiff(ctx)
if err != nil {
return nil, fmt.Errorf("workspace tracked diff failed: %w", err)
}
combined.WriteString(tracked)
untracked, err := p.untrackedFileDiffs(ctx)
if err != nil {
return nil, fmt.Errorf("untracked file diff failed: %w", err)
}
for _, ud := range untracked {
combined.WriteString(ud)
combined.WriteString("\n\n")
}
}
var ref string
switch p.mode {
case ModeRange:
ref = p.to
case ModeCommit:
ref = p.commit
}
diffs, err := ParseDiffText(ctx, combined.String(), p.repoDir, ref, p.runner)
if err != nil {
return nil, err
}
return p.filterDiffs(diffs), nil
}
// loadGitignorePatterns reads and parses .gitignore patterns from the repo root.
func (p *Provider) loadGitignorePatterns() []string {
data, err := os.ReadFile(filepath.Join(p.repoDir, ".gitignore"))
if err != nil {
return nil
}
var patterns []string
for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
patterns = append(patterns, line)
}
return patterns
}
// isPathExcluded returns true when the given relative file path should be skipped
// based on hardcoded dir rules or .gitignore patterns.
func (p *Provider) isPathExcluded(relPath string, gitignorePatterns []string) bool {
// Hardcoded directory prefix checks
for _, prefix := range providerDirIgnoreDirs {
dirPart := strings.TrimSuffix(prefix, "/")
if relPath == dirPart || strings.HasPrefix(relPath, prefix) {
return true
}
}
// .gitignore pattern matching
for _, pat := range gitignorePatterns {
if matchGitignorePattern(relPath, pat) {
return true
}
}
return false
}
// matchGitignorePattern checks if relPath matches a single .gitignore pattern.
func matchGitignorePattern(relPath, pat string) bool {
// Directory-only patterns (trailing /)
if before, ok := strings.CutSuffix(pat, "/"); ok {
dirName := before
// Match if any path segment equals the dir name
segments := strings.Split(relPath, "/")
return slices.Contains(segments, dirName)
}
// Negation patterns are not needed for exclusion purposes
if strings.HasPrefix(pat, "!") {
return false
}
// Patterns without / match basename
if !strings.Contains(pat, "/") {
base := filepath.Base(relPath)
if matched, _ := filepath.Match(pat, base); matched {
return true
}
return false
}
// Patterns with / match against the full relative path
if matched, _ := filepath.Match(pat, relPath); matched {
return true
}
// Also try matching against suffix of path
if strings.HasSuffix(relPath, pat) {
return true
}
return false
}
// filterDiffs removes diffs whose file paths are excluded.
func (p *Provider) filterDiffs(diffs []model.Diff) []model.Diff {
patterns := p.loadGitignorePatterns()
var result []model.Diff
for _, d := range diffs {
path := d.NewPath
if path == "/dev/null" {
path = d.OldPath
}
if !p.isPathExcluded(path, patterns) {
result = append(result, d)
}
}
return result
}
// ---- Internal helpers ----
func (p *Provider) computeMergeBase(ctx context.Context, from, to string) string {
out, err := p.runGit(ctx, "merge-base", "--end-of-options", from, to)
if err != nil {
return ""
}
return strings.TrimSpace(out)
}
func (p *Provider) workspaceTrackedDiff(ctx context.Context) (string, error) {
out, err := p.runGit(ctx, "-c", "core.quotepath=false", "diff", "--no-ext-diff", "--no-textconv", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--no-color", "-U"+fmt.Sprint(DiffContextLines), "--end-of-options", "HEAD", "--")
if err == nil && out != "" {
return out, nil
}
if ctx.Err() != nil {
return "", ctx.Err()
}
// Fall back to the staged diff when `git diff HEAD` errored or was empty. This is
// not redundant with the call above: in a repository with no commits yet there is no
// HEAD, so `git diff HEAD` fails with "bad revision 'HEAD'", but `git diff --staged`
// still surfaces staged changes by diffing the index against the empty tree — the only
// way to review a workspace before its first commit.
return p.runGit(ctx, "-c", "core.quotepath=false", "diff", "--no-ext-diff", "--no-textconv", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--no-color", "-U"+fmt.Sprint(DiffContextLines), "--staged", "--")
}
func (p *Provider) untrackedFileDiffs(ctx context.Context) ([]string, error) {
files, err := p.untrackedFilesList(ctx)
if err != nil {
return nil, err
}
var results []string
for _, f := range files {
content, rerr := readWorkspaceFileForDiff(p.repoDir, f)
if rerr != nil {
continue
}
lineCount := bytes.Count(content, []byte{'\n'})
if len(content) > 0 && content[len(content)-1] != '\n' {
lineCount++
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("diff --git a/%s b/%s\n", f, f))
sb.WriteString("--- /dev/null\n")
sb.WriteString(fmt.Sprintf("+++ b/%s\n", f))
sb.WriteString(fmt.Sprintf("@@ -0,0 +1,%d @@\n", lineCount))
lines := bytes.Split(content, []byte{'\n'})
if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
for _, line := range lines {
sb.WriteByte('+')
sb.Write(line)
sb.WriteByte('\n')
}
results = append(results, sb.String())
}
return results, nil
}
func (p *Provider) untrackedFilesList(ctx context.Context) ([]string, error) {
out, err := p.runGit(ctx, "-c", "core.quotepath=false", "ls-files", "--others", "--exclude-standard")
if err != nil || out == "" {
return nil, nil
}
patterns := p.loadGitignorePatterns()
var files []string
for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
if !p.isPathExcluded(line, patterns) {
files = append(files, line)
}
}
return files, nil
}
func (p *Provider) runGit(ctx context.Context, args ...string) (string, error) {
if p.runner != nil {
return p.runner.Run(ctx, p.repoDir, args...)
}
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Dir = p.repoDir
out, err := cmd.CombinedOutput()
return string(out), err
}