-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdiff.go
More file actions
310 lines (258 loc) · 7.5 KB
/
diff.go
File metadata and controls
310 lines (258 loc) · 7.5 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
// Package diff provides utilities for comparing package versions.
package diff
import (
"bufio"
"bytes"
"fmt"
"io"
"sort"
"strings"
"github.com/git-pkgs/archives"
)
// FileDiff represents the diff for a single file.
type FileDiff struct {
Path string `json:"path"`
Type string `json:"type"` // "modified", "added", "deleted", "renamed"
OldPath string `json:"old_path,omitempty"`
Diff string `json:"diff,omitempty"`
IsBinary bool `json:"is_binary,omitempty"`
LinesAdded int `json:"lines_added"`
LinesDeleted int `json:"lines_deleted"`
}
// CompareResult contains the complete comparison between two versions.
type CompareResult struct {
Files []FileDiff `json:"files"`
TotalAdded int `json:"total_added"`
TotalDeleted int `json:"total_deleted"`
FilesChanged int `json:"files_changed"`
FilesAdded int `json:"files_added"`
FilesDeleted int `json:"files_deleted"`
}
// Compare generates a diff between two archive readers.
func Compare(oldReader, newReader archives.Reader) (*CompareResult, error) {
// Get file listings
oldFiles, err := oldReader.List()
if err != nil {
return nil, fmt.Errorf("listing old archive: %w", err)
}
newFiles, err := newReader.List()
if err != nil {
return nil, fmt.Errorf("listing new archive: %w", err)
}
// Create maps for quick lookup
oldMap := make(map[string]archives.FileInfo)
newMap := make(map[string]archives.FileInfo)
for _, f := range oldFiles {
if !f.IsDir {
oldMap[f.Path] = f
}
}
for _, f := range newFiles {
if !f.IsDir {
newMap[f.Path] = f
}
}
result := &CompareResult{
Files: []FileDiff{},
}
// Find all unique paths
allPaths := make(map[string]bool)
for path := range oldMap {
allPaths[path] = true
}
for path := range newMap {
allPaths[path] = true
}
// Convert to sorted slice
paths := make([]string, 0, len(allPaths))
for path := range allPaths {
paths = append(paths, path)
}
sort.Strings(paths)
// Compare each file
for _, path := range paths {
oldExists := oldMap[path]
newExists := newMap[path]
var fileDiff FileDiff
if oldExists.Path != "" && newExists.Path == "" {
// File was deleted
fileDiff = FileDiff{
Path: path,
Type: "deleted",
}
result.FilesDeleted++
} else if oldExists.Path == "" && newExists.Path != "" {
// File was added
fileDiff = FileDiff{
Path: path,
Type: "added",
}
result.FilesAdded++
// Try to get content for added files
if content, err := readFileContent(newReader, path); err == nil {
if isBinary(content) {
fileDiff.IsBinary = true
} else {
fileDiff.Diff = generateAddedDiff(path, content)
fileDiff.LinesAdded = countLines(content)
}
}
} else {
// File exists in both - check if modified
oldContent, err1 := readFileContent(oldReader, path)
newContent, err2 := readFileContent(newReader, path)
if err1 != nil || err2 != nil {
continue // Skip files we can't read
}
if bytes.Equal(oldContent, newContent) {
continue // No change
}
fileDiff = FileDiff{
Path: path,
Type: "modified",
}
result.FilesChanged++
if isBinary(oldContent) || isBinary(newContent) {
fileDiff.IsBinary = true
} else {
diffText, added, deleted := generateUnifiedDiff(path, oldContent, newContent)
fileDiff.Diff = diffText
fileDiff.LinesAdded = added
fileDiff.LinesDeleted = deleted
result.TotalAdded += added
result.TotalDeleted += deleted
}
}
result.Files = append(result.Files, fileDiff)
}
return result, nil
}
// readFileContent reads a file's content from an archive reader.
func readFileContent(reader archives.Reader, path string) ([]byte, error) {
rc, err := reader.Extract(path)
if err != nil {
return nil, err
}
defer func() { _ = rc.Close() }()
return io.ReadAll(rc)
}
// isBinary checks if content appears to be binary.
func isBinary(content []byte) bool {
if len(content) == 0 {
return false
}
// Check first 8KB for null bytes
checkLen := len(content)
if checkLen > 8192 {
checkLen = 8192
}
for i := 0; i < checkLen; i++ {
if content[i] == 0 {
return true
}
}
return false
}
// generateUnifiedDiff generates a unified diff between two file contents.
// Uses line-based diffing for proper unified diff output.
func generateUnifiedDiff(path string, oldContent, newContent []byte) (string, int, int) {
return generateSimpleDiff(path, oldContent, newContent)
}
// generateSimpleDiff generates a line-based unified diff.
func generateSimpleDiff(path string, oldContent, newContent []byte) (string, int, int) {
oldLines := strings.Split(string(oldContent), "\n")
newLines := strings.Split(string(newContent), "\n")
// Simple line-by-line comparison (can be improved with Myers algorithm)
var buf strings.Builder
fmt.Fprintf(&buf, "--- a/%s\n", path)
fmt.Fprintf(&buf, "+++ b/%s\n", path)
linesAdded := 0
linesDeleted := 0
// Find common prefix
commonPrefix := 0
maxCommon := len(oldLines)
if len(newLines) < maxCommon {
maxCommon = len(newLines)
}
for commonPrefix < maxCommon && oldLines[commonPrefix] == newLines[commonPrefix] {
commonPrefix++
}
// Find common suffix
commonSuffix := 0
oldEnd := len(oldLines) - 1
newEnd := len(newLines) - 1
for commonSuffix < maxCommon-commonPrefix &&
oldEnd-commonSuffix >= commonPrefix &&
newEnd-commonSuffix >= commonPrefix &&
oldLines[oldEnd-commonSuffix] == newLines[newEnd-commonSuffix] {
commonSuffix++
}
// Calculate range
oldStart := commonPrefix
oldCount := len(oldLines) - commonPrefix - commonSuffix
newStart := commonPrefix
newCount := len(newLines) - commonPrefix - commonSuffix
if oldCount == 0 && newCount == 0 {
return "", 0, 0
}
// Context lines
contextBefore := 3
contextAfter := 3
hunkOldStart := oldStart - contextBefore
if hunkOldStart < 0 {
hunkOldStart = 0
}
hunkNewStart := newStart - contextBefore
if hunkNewStart < 0 {
hunkNewStart = 0
}
// Build hunk
var hunk strings.Builder
// Context before
for i := hunkOldStart; i < oldStart && i < len(oldLines); i++ {
hunk.WriteString(" " + oldLines[i] + "\n")
}
// Deleted lines
for i := oldStart; i < oldStart+oldCount && i < len(oldLines); i++ {
hunk.WriteString("-" + oldLines[i] + "\n")
linesDeleted++
}
// Added lines
for i := newStart; i < newStart+newCount && i < len(newLines); i++ {
hunk.WriteString("+" + newLines[i] + "\n")
linesAdded++
}
// Context after
afterStart := oldStart + oldCount
for i := 0; i < contextAfter && afterStart+i < len(oldLines); i++ {
hunk.WriteString(" " + oldLines[afterStart+i] + "\n")
}
// Calculate hunk size
hunkOldCount := (oldStart - hunkOldStart) + oldCount + contextAfter
hunkNewCount := (newStart - hunkNewStart) + newCount + contextAfter
// Write hunk header
fmt.Fprintf(&buf, "@@ -%d,%d +%d,%d @@\n", hunkOldStart+1, hunkOldCount, hunkNewStart+1, hunkNewCount)
buf.WriteString(hunk.String())
return buf.String(), linesAdded, linesDeleted
}
// generateAddedDiff generates a diff for a newly added file.
func generateAddedDiff(path string, content []byte) string {
var buf strings.Builder
buf.WriteString("--- /dev/null\n")
fmt.Fprintf(&buf, "+++ b/%s\n", path)
lines := bytes.Split(content, []byte("\n"))
fmt.Fprintf(&buf, "@@ -0,0 +1,%d @@\n", len(lines))
for _, line := range lines {
buf.WriteString("+" + string(line) + "\n")
}
return buf.String()
}
// countLines counts the number of lines in content.
func countLines(content []byte) int {
scanner := bufio.NewScanner(bytes.NewReader(content))
count := 0
for scanner.Scan() {
count++
}
return count
}