-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathincremental.go
More file actions
254 lines (215 loc) · 6.77 KB
/
incremental.go
File metadata and controls
254 lines (215 loc) · 6.77 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
package sight
import (
"bufio"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// IncrementalState tracks the last-reviewed commit SHA for incremental reviews.
// It is safe for concurrent use.
type IncrementalState struct {
mu sync.Mutex
lastReviewedSHA string
}
// NewIncrementalState creates a new state tracker, optionally seeded with a
// previously reviewed SHA for resumption.
func NewIncrementalState(lastSHA string) *IncrementalState {
return &IncrementalState{lastReviewedSHA: lastSHA}
}
// LastReviewedSHA returns the SHA of the last reviewed commit.
func (s *IncrementalState) LastReviewedSHA() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.lastReviewedSHA
}
// SetLastReviewedSHA updates the last-reviewed SHA after a successful review.
func (s *IncrementalState) SetLastReviewedSHA(sha string) {
s.mu.Lock()
defer s.mu.Unlock()
s.lastReviewedSHA = sha
}
// ReviewIncremental reviews only the changes between base and head commits.
// It uses `git diff base...head` to obtain the diff, reviews it, and records
// the head SHA in the provided state for future incremental runs.
//
// If state is non-nil and has a LastReviewedSHA, that SHA is used as the base
// instead of the provided base argument (enabling resumption).
//
// Pass nil for state if you don't need resumption tracking.
//
// If contextLines > 0, the review includes surrounding file context around
// each changed hunk for better understanding of the change.
func ReviewIncremental(ctx context.Context, base, head string, state *IncrementalState, opts ...Option) (*Result, error) {
if state != nil {
if last := state.LastReviewedSHA(); last != "" {
base = last
}
}
diffText, err := gitDiffRange(ctx, base, head)
if err != nil {
return nil, fmt.Errorf("sight: incremental diff failed: %w", err)
}
if strings.TrimSpace(diffText) == "" {
result := &Result{Report: "No new changes since last review."}
if state != nil {
state.SetLastReviewedSHA(head)
}
return result, nil
}
// Enrich diff with surrounding file context
enrichedDiff := enrichDiffWithContext(ctx, diffText, 10)
r := NewReviewer(opts...)
result, err := r.Review(ctx, enrichedDiff)
if err != nil {
return nil, err
}
if state != nil {
state.SetLastReviewedSHA(head)
}
return result, nil
}
// ReviewIncrementalWithContext reviews changes with surrounding file context.
// contextLines specifies how many lines of context to include around each hunk.
func ReviewIncrementalWithContext(ctx context.Context, base, head string, state *IncrementalState, contextLines int, opts ...Option) (*Result, error) {
if state != nil {
if last := state.LastReviewedSHA(); last != "" {
base = last
}
}
diffText, err := gitDiffRange(ctx, base, head)
if err != nil {
return nil, fmt.Errorf("sight: incremental diff failed: %w", err)
}
if strings.TrimSpace(diffText) == "" {
result := &Result{Report: "No new changes since last review."}
if state != nil {
state.SetLastReviewedSHA(head)
}
return result, nil
}
if contextLines > 0 {
diffText = enrichDiffWithContext(ctx, diffText, contextLines)
}
r := NewReviewer(opts...)
result, err := r.Review(ctx, diffText)
if err != nil {
return nil, err
}
if state != nil {
state.SetLastReviewedSHA(head)
}
return result, nil
}
// hunkHeaderRe matches @@ -a,b +c,d @@ hunk headers.
var hunkHeaderRe = regexp.MustCompile(`@@ -(\d+),?\d* \+(\d+),?\d* @@`)
// enrichDiffWithContext adds surrounding file content around each changed hunk.
// This gives the reviewer more context about what the change means in the
// broader file structure.
func enrichDiffWithContext(ctx context.Context, diffText string, contextLines int) string {
var enriched strings.Builder
scanner := bufio.NewScanner(strings.NewReader(diffText))
var currentFile string
for scanner.Scan() {
line := scanner.Text()
// Track current file from +++ b/path lines
if strings.HasPrefix(line, "+++ b/") {
currentFile = strings.TrimPrefix(line, "+++ b/")
enriched.WriteString(line + "\n")
continue
}
// Detect hunk headers and add surrounding context
if matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil && currentFile != "" {
_ = true
startLine, _ := strconv.Atoi(matches[1])
// Add surrounding context before the hunk
contextBefore := loadFileLines(ctx, currentFile, startLine-contextLines, startLine-1)
if len(contextBefore) > 0 {
enriched.WriteString(fmt.Sprintf("\n--- Context before (lines %d-%d) ---\n", startLine-contextLines, startLine-1))
for i, cl := range contextBefore {
enriched.WriteString(fmt.Sprintf(" %d | %s\n", startLine-contextLines+i, cl))
}
}
enriched.WriteString(line + "\n")
continue
}
enriched.WriteString(line + "\n")
}
return enriched.String()
}
// loadFileLines reads specific line ranges from a file.
func loadFileLines(ctx context.Context, filePath string, startLine, endLine int) []string {
if startLine < 1 {
startLine = 1
}
// Sanitize the path to prevent path traversal attacks.
cleanPath := filepath.Clean(filePath)
if strings.Contains(cleanPath, "..") {
return nil
}
f, err := os.Open(cleanPath)
if err != nil {
// Try to find the file relative to git root
root, rerr := gitRoot(ctx)
if rerr != nil {
return nil
}
joinedPath := filepath.Join(root, cleanPath)
// Verify the resolved path is still within the git root.
if !strings.HasPrefix(filepath.Clean(joinedPath), filepath.Clean(root)) {
return nil
}
f, err = os.Open(joinedPath)
if err != nil {
return nil
}
}
defer f.Close()
var lines []string
scanner := bufio.NewScanner(f)
lineNum := 0
for scanner.Scan() {
lineNum++
if lineNum >= startLine && lineNum <= endLine {
lines = append(lines, scanner.Text())
}
if lineNum > endLine {
break
}
}
return lines
}
// gitRoot returns the root directory of the git repository.
func gitRoot(ctx context.Context) (string, error) {
out, err := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel").Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// gitDiffRange runs `git diff base...head` with a context timeout.
func gitDiffRange(ctx context.Context, base, head string) (string, error) {
// Default 30s timeout if context has no deadline
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()
}
// Try three-dot syntax first (merge-base diff)
out, err := exec.CommandContext(ctx, "git", "diff", base+"..."+head).Output()
if err == nil {
return string(out), nil
}
// Fall back to two-dot syntax
out, err = exec.CommandContext(ctx, "git", "diff", base, head).Output()
if err != nil {
return "", fmt.Errorf("git diff %s %s failed: %w", base, head, err)
}
return string(out), nil
}