This repository was archived by the owner on Apr 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdiff.go
More file actions
356 lines (300 loc) Β· 9.91 KB
/
diff.go
File metadata and controls
356 lines (300 loc) Β· 9.91 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
345
346
347
348
349
350
351
352
353
354
355
356
package main
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/alecthomas/kong"
"github.com/mgutz/ansi"
bolt "go.etcd.io/bbolt"
"gopkg.in/src-d/go-git.v4/plumbing/format/gitignore"
"github.com/falzm/fsdiff/internal/snapshot"
)
const (
diffTypeNew = iota
diffTypeModified
diffTypeDeleted
)
type fileDiff struct {
diffType int
fileBefore *snapshot.FileInfo
fileAfter *snapshot.FileInfo
changes map[string][2]interface{}
}
type diffCmdOutput struct {
summary struct {
new int
modified int
deleted int
}
changes []fileDiff
}
type diffCmd struct {
Before string `arg:"" type:"existingfile" help:"Path to \"before\" snapshot file."`
After string `arg:"" type:"existingfile" help:"Path to \"after\" snapshot file."`
Exclude []string `placeholder:"PATTERN" help:"gitignore-compatible exclusion pattern (see https://git-scm.com/docs/gitignore)."`
Ignore []string `placeholder:"PROPERTY" enum:"${diff_file_properties}" help:"File property to ignore (${diff_file_properties})."`
IgnoreNew bool `help:"Ignore any new file."`
IgnoreModified bool `help:"Ignore any modified file."`
IgnoreDeleted bool `help:"Ignore any deleted file."`
NoColor bool `name:"nocolor" help:"Disable output coloring."`
Quiet bool `short:"q" help:"Disable any output.'"`
SummaryOnly bool `name:"summary" help:"Only display changes summary."`
}
func (c *diffCmd) Help() string {
return `Similar to the traditional "diff" tool, this command's exit
status has a specific meaning: 0 means no differences were found, 1 means
some differences were found, and 2 means trouble.`
}
var diffFileProperties = []string{
"size",
"mtime",
"uid",
"gid",
"mode",
"checksum",
}
func (c *diffCmd) run() (diffCmdOutput, error) {
var (
moved = make(map[string]struct{}) // Used to track file renamings.
shallow bool
)
excludedPatterns := make([]gitignore.Pattern, len(c.Exclude))
for i, p := range c.Exclude {
excludedPatterns[i] = gitignore.ParsePattern(p, nil)
}
excluded := gitignore.NewMatcher(excludedPatterns)
snapBefore, err := snapshot.Open(c.Before)
if err != nil {
return diffCmdOutput{}, fmt.Errorf(`unable to open "before" snapshot file: %w`, err)
}
defer snapBefore.Close()
snapAfter, err := snapshot.Open(c.After)
if err != nil {
return diffCmdOutput{}, fmt.Errorf(`unable to open "after" snapshot file: %w`, err)
}
defer snapAfter.Close()
out := diffCmdOutput{
changes: make([]fileDiff, 0),
}
/*
The diff logic is implemented as follows:
1) For each file in _after_ snapshot, check if it existed at the same path in the _before_ snapshot:
- if it existed, check if its properties match the _before_ ones
* if they don't, mark the file [modified]
- if it didn't, check if a file with a matching checksum existed at a different path:
* if found, mark the file [moved] and check if its properties match the _before_ ones
* if none found, mark the file [new]
2) For each file in _before_ snapshot, check if it exists in the *after* snapshot:
- if it doesn't, mark the file [deleted]
*/
err = snapBefore.Read(func(byPathBefore, byCSBefore *bolt.Bucket) error {
return snapAfter.Read(func(byPathAfter, byCSAfter *bolt.Bucket) error {
// If either one of the before/after snapshots is shallow, diff in shallow mode.
if snapBefore.Metadata().Shallow || snapAfter.Metadata().Shallow {
shallow = true
}
err := byPathAfter.ForEach(func(path, data []byte) error {
fileInfoAfter := snapshot.FileInfo{}
if err := snapshot.Unmarshal(data, &fileInfoAfter); err != nil {
return fmt.Errorf("unable to read snapshot data: %w", err)
}
// Skip files matching the excluded patterns.
if excluded.Match(strings.Split(fileInfoAfter.Path, "/"), fileInfoAfter.IsDir) {
return nil
}
if beforeData := byPathBefore.Get(path); beforeData != nil {
// The file existed before, check if its properties have changed.
fileInfoBefore := snapshot.FileInfo{}
if err := snapshot.Unmarshal(beforeData, &fileInfoBefore); err != nil {
return fmt.Errorf("unable to read snapshot data: %w", err)
}
changes := c.compareFiles(&fileInfoBefore, &fileInfoAfter)
if len(changes) > 0 && !c.IgnoreModified {
out.changes = append(out.changes, fileDiff{
diffType: diffTypeModified,
fileBefore: &fileInfoBefore,
fileAfter: &fileInfoAfter,
changes: changes,
})
out.summary.modified++
}
return nil
}
// No file existed before at this path, check by checksum to see if it's a previous file moved
// elsewhere -- unless we're in shallow mode, since we don't have the files' checksum.
// We skip empty files, as they cause false positives by having identical checksum.
if fileInfoAfter.Size > 0 && !shallow {
if beforeData := byCSBefore.Get(fileInfoAfter.Checksum); beforeData != nil && !c.IgnoreModified {
// The file existed before elsewhere, also check if its properties have changed.
fileInfoBefore := snapshot.FileInfo{}
if err := snapshot.Unmarshal(beforeData, &fileInfoBefore); err != nil {
return fmt.Errorf("unable to read snapshot data: %w", err)
}
moved[fileInfoBefore.Path] = struct{}{}
changes := c.compareFiles(&fileInfoBefore, &fileInfoAfter)
out.changes = append(out.changes, fileDiff{
diffType: diffTypeModified,
fileBefore: &fileInfoBefore,
fileAfter: &fileInfoAfter,
changes: changes,
})
out.summary.modified++
return nil
}
}
// No "before" file matches this checksum: this is a new file.
if !c.IgnoreNew {
out.changes = append(out.changes, fileDiff{
diffType: diffTypeNew,
fileAfter: &fileInfoAfter,
})
out.summary.new++
}
return nil
})
if err != nil {
return err
}
// Perform reverse lookup to detect deleted files.
if err := byPathBefore.ForEach(func(path, data []byte) error {
if afterData := byPathAfter.Get(path); afterData == nil {
// Before marking a file as deleted, check if it is not the result of a renaming.
if _, ok := moved[string(path)]; !ok {
fileInfoBefore := snapshot.FileInfo{}
if err := snapshot.Unmarshal(data, &fileInfoBefore); err != nil {
return fmt.Errorf("unable to read snapshot data: %w", err)
}
if excluded.Match(strings.Split(fileInfoBefore.Path, "/"), fileInfoBefore.IsDir) {
return nil
}
if !c.IgnoreDeleted {
out.changes = append(out.changes, fileDiff{
diffType: diffTypeDeleted,
fileAfter: &snapshot.FileInfo{Path: string(path)},
})
out.summary.deleted++
}
}
}
return nil
}); err != nil {
return fmt.Errorf("bolt: unable to loop on bucket keys: %w", err)
}
return nil
})
})
if err != nil {
return diffCmdOutput{}, err
}
return out, nil
}
func (c *diffCmd) compareFiles(before, after *snapshot.FileInfo) map[string][2]interface{} {
diff := make(map[string][2]interface{})
if !c.ignored("size") {
if before.Size != after.Size {
diff["size"] = [2]interface{}{before.Size, after.Size}
}
}
if !c.ignored("mtime") {
if !before.Mtime.Equal(after.Mtime) {
diff["mtime"] = [2]interface{}{before.Mtime, after.Mtime}
}
}
if !c.ignored("uid") {
if before.Uid != after.Uid {
diff["uid"] = [2]interface{}{before.Uid, after.Uid}
}
}
if !c.ignored("gid") {
if before.Gid != after.Gid {
diff["gid"] = [2]interface{}{before.Gid, after.Gid}
}
}
if !c.ignored("mode") {
if before.Mode != after.Mode {
diff["mode"] = [2]interface{}{before.Mode, after.Mode}
}
}
if before.LinkTo != after.LinkTo {
diff["link"] = [2]interface{}{before.LinkTo, after.LinkTo}
}
if before.IsDir != after.IsDir {
diff["dir"] = [2]interface{}{before.IsDir, after.IsDir}
}
if before.IsSock != after.IsSock {
diff["sock"] = [2]interface{}{before.IsSock, after.IsSock}
}
if before.IsPipe != after.IsPipe {
diff["pipe"] = [2]interface{}{before.IsPipe, after.IsPipe}
}
if before.IsDev != after.IsDev {
diff["dev"] = [2]interface{}{before.IsDev, after.IsDev}
}
if !c.ignored("checksum") && (before.Checksum != nil && after.Checksum != nil) {
if !bytes.Equal(before.Checksum, after.Checksum) {
diff["checksum"] = [2]interface{}{before.Checksum, after.Checksum}
}
}
return diff
}
// ignored returns true if property p is in the ignored list, otherwise false.
func (c *diffCmd) ignored(p string) bool {
for i := range c.Ignore {
if c.Ignore[i] == p {
return true
}
}
return false
}
func (c *diffCmd) printNew(w io.Writer, f string) {
_, _ = fmt.Fprintln(w, ansi.Color("+", "green"), f)
}
func (c *diffCmd) printModified(w io.Writer, before, after *snapshot.FileInfo, diff map[string][2]interface{}) {
if before.Path != after.Path {
_, _ = fmt.Fprintf(w, "%s %s => %s\n", ansi.Color(">", "cyan"), before.Path, after.Path)
} else {
_, _ = fmt.Fprintf(w, "%s %s\n", ansi.Color("~", "yellow"), after.Path)
}
if len(diff) > 0 {
_, _ = fmt.Fprintf(w, " %s\n %s\n", before.String(), after.String())
}
}
func (c *diffCmd) printDeleted(w io.Writer, f string) {
_, _ = fmt.Fprintln(w, ansi.Color("-", "red"), f)
}
func (c *diffCmd) Run(ctx kong.Context) error {
if c.NoColor {
ansi.DisableColors(true)
}
out, err := c.run()
if err != nil {
ctx.Exit(2)
}
if !c.SummaryOnly {
for _, fc := range out.changes {
switch fc.diffType {
case diffTypeNew:
c.printNew(ctx.Stdout, fc.fileAfter.Path)
case diffTypeModified:
c.printModified(ctx.Stdout, fc.fileBefore, fc.fileAfter, fc.changes)
case diffTypeDeleted:
c.printDeleted(ctx.Stdout, fc.fileAfter.Path)
}
}
_, _ = fmt.Fprintln(ctx.Stdout)
}
if out.summary.new > 0 || out.summary.modified > 0 || out.summary.deleted > 0 {
if !c.Quiet {
_, _ = fmt.Fprintf(
ctx.Stdout,
"%d new, %d modified, %d deleted\n",
out.summary.new,
out.summary.modified,
out.summary.deleted,
)
}
ctx.Exit(1)
}
return nil
}