This repository has been archived by the owner on Dec 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpatchutils.go
1114 lines (970 loc) · 36.9 KB
/
patchutils.go
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package patchutils provides tools to compute the diff between source and diff files.
package patchutils
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"sync"
dbd "github.com/kylelemons/godebug/diff"
"github.com/sourcegraph/go-diff/diff"
"golang.org/x/sync/errgroup"
)
// InterDiff computes the diff of a source file patched with oldDiff
// and the same source file patched with newDiff.
// oldDiff and newDiff should be in unified format.
func InterDiff(oldDiff, newDiff io.Reader) (string, error) {
oldFileDiffs, err := diff.NewMultiFileDiffReader(oldDiff).ReadAllFiles()
if err != nil {
return "", fmt.Errorf("parsing oldDiff: %w", err)
}
if len(oldFileDiffs) == 0 {
return "", fmt.Errorf("oldDiff: %w", ErrEmptyDiffFile)
}
newFileDiffs, err := diff.NewMultiFileDiffReader(newDiff).ReadAllFiles()
if err != nil {
return "", fmt.Errorf("parsing newDiff: %w", err)
}
if len(newFileDiffs) == 0 {
return "", fmt.Errorf("newDiff: %w", ErrEmptyDiffFile)
}
resultFiles := make(map[string]string)
// Iterate over files in FileDiff arrays
i, j := 0, 0
eg, _ := errgroup.WithContext(context.Background())
Loop:
for i < len(oldFileDiffs) && j < len(newFileDiffs) {
switch {
case oldFileDiffs[i].OrigName == newFileDiffs[j].OrigName:
switch {
case oldFileDiffs[i].NewName == "" && newFileDiffs[j].NewName == "":
// In both versions file has been added/deleted
i++
j++
continue Loop
case oldFileDiffs[i].NewName == "":
// File was deleted in old version
resultFiles[newFileDiffs[j].OrigName] = fmt.Sprintf("Only in %s: %s\n", filepath.Dir(newFileDiffs[j].NewName),
filepath.Base(newFileDiffs[j].NewName))
case newFileDiffs[j].NewName == "":
// File deleted in new version
resultFiles[oldFileDiffs[i].OrigName] = fmt.Sprintf("Only in %s: %s\n", filepath.Dir(oldFileDiffs[i].NewName),
filepath.Base(oldFileDiffs[i].NewName))
default:
// interdiff of two versions
var mu sync.Mutex
i, j := i, j
eg.Go(func() error {
interFileDiff, err := interFileDiff(oldFileDiffs[i], newFileDiffs[j])
if err != nil {
return fmt.Errorf("merging diffs for file %q: %w", oldFileDiffs[i].OrigName, err)
}
fileDiffContent, err := diff.PrintFileDiff(interFileDiff)
if err != nil {
return fmt.Errorf("printing merged diffs for file %q: %w", oldFileDiffs[i].OrigName, err)
}
mu.Lock()
defer mu.Unlock()
resultFiles[oldFileDiffs[i].OrigName] = string(fileDiffContent)
return nil
})
}
i++
j++
case oldFileDiffs[i].OrigName < newFileDiffs[j].OrigName:
// current file is only mentioned in oldDiff
// determine if file has been added or just changed in only one version
revertHunks(oldFileDiffs[i])
oldD, err := interPrintSingleFileDiff(oldFileDiffs[i])
if err != nil {
return "", fmt.Errorf("printing oldDiff: %w", err)
}
resultFiles[oldFileDiffs[i].OrigName] = oldD
i++
case oldFileDiffs[i].OrigName > newFileDiffs[j].OrigName:
// current file is only mentioned in newDiff
// determine if file has been added or just changed in only one version
newD, err := interPrintSingleFileDiff(newFileDiffs[j])
if err != nil {
return "", fmt.Errorf("printing newDiff: %w", err)
}
resultFiles[newFileDiffs[j].OrigName] = newD
j++
}
}
// In case there are more oldFileDiffs, while newFileDiffs are run out
for i < len(oldFileDiffs) {
oldD, err := interPrintSingleFileDiff(oldFileDiffs[i])
if err != nil {
return "", fmt.Errorf("printing oldDiff: %w", err)
}
resultFiles[oldFileDiffs[i].OrigName] = oldD
i++
}
// In case there are more newFileDiffs, while oldFileDiffs are run out
for j < len(newFileDiffs) {
newD, err := interPrintSingleFileDiff(newFileDiffs[j])
if err != nil {
return "", fmt.Errorf("printing newDiff: %w", err)
}
resultFiles[newFileDiffs[j].OrigName] = newD
j++
}
if err := eg.Wait(); err != nil {
return "", fmt.Errorf("wait all routines: %w", err)
}
// Add diff files to result in order
var originalFilenames []string
for f := range resultFiles {
originalFilenames = append(originalFilenames, f)
}
sort.Strings(originalFilenames)
var result string
for _, k := range originalFilenames {
result += resultFiles[k]
}
return result, nil
}
// mixedMode computes the diff of a oldSource file patched with oldDiff
// and the newSource file patched with newDiff.
// Check if files are added/deleted in old/new versions is skipped.
func mixedMode(oldSource, newSource io.Reader, oldFileDiff, newFileDiff *diff.FileDiff) (string, error) {
// Skip check if in some version the file has been added/deleted as this is already done in MixedModeFilePath,
// before opening oldSource and newSource files
oldSourceContent, err := readContent(oldSource)
if err != nil {
return "", fmt.Errorf("reading content of OldSource: %w", err)
}
newSourceContent, err := readContent(newSource)
if err != nil {
return "", fmt.Errorf("reading content of NewSource: %w", err)
}
updatedOldSource, err := applyDiff(oldSourceContent, oldFileDiff)
if err != nil {
return "", fmt.Errorf("applying diff to OldSource: %w", err)
}
updatedNewSource, err := applyDiff(newSourceContent, newFileDiff)
if err != nil {
return "", fmt.Errorf("applying diff to NewSource: %w", err)
}
ch := dbd.DiffChunks(strings.Split(strings.TrimSuffix(updatedOldSource, "\n"), "\n"),
strings.Split(strings.TrimSuffix(updatedNewSource, "\n"), "\n"))
// TODO: something with extended (extended header lines)
resultFileDiff := &diff.FileDiff{
OrigName: oldFileDiff.NewName,
OrigTime: oldFileDiff.NewTime,
NewName: newFileDiff.NewName,
NewTime: newFileDiff.NewTime,
Extended: []string{},
Hunks: []*diff.Hunk{},
}
convertChunksIntoFileDiff(ch, resultFileDiff)
result, err := diff.PrintFileDiff(resultFileDiff)
if err != nil {
return "", fmt.Errorf("printing result diff for file %q: %w",
oldFileDiff.NewName, err)
}
return string(result), nil
}
// MixedModeFile computes the diff of an oldSource file patched with oldDiff and
// newSource file patched with newDiff.
func MixedModeFile(oldSource, newSource, oldDiff, newDiff io.Reader) (string, error) {
oldD, err := diff.NewFileDiffReader(oldDiff).Read()
if err != nil {
return "", fmt.Errorf("parsing oldDiff: %w", err)
}
newD, err := diff.NewFileDiffReader(newDiff).Read()
if err != nil {
return "", fmt.Errorf("parsing newDiff: %w", err)
}
result, err := mixedMode(oldSource, newSource, oldD, newD)
if err != nil {
return "", fmt.Errorf("mixedMode: %w", err)
}
return result, nil
}
// MixedModePath recursively computes the diff of an oldSource patched with oldDiff
// and the newSource patched with newDiff, recursively if OldSource and NewSource are directories.
func MixedModePath(oldSourcePath, newSourcePath string, oldDiff, newDiff io.Reader) (string, error) {
// Get stats of sources
oldSourceStat, err := os.Stat(oldSourcePath)
if err != nil {
return "", fmt.Errorf("get stat from oldSourcePath %q: %w",
oldSourcePath, err)
}
newSourceStat, err := os.Stat(newSourcePath)
if err != nil {
return "", fmt.Errorf("get stat from newSourcePath %q: %w",
newSourcePath, err)
}
// Check mode of sources
switch {
case !oldSourceStat.IsDir() && !newSourceStat.IsDir():
// Both sources are files
oldD, err := diff.NewFileDiffReader(oldDiff).Read()
if err != nil {
return "", fmt.Errorf("parsing oldDiff for %q: %w",
oldSourcePath, err)
}
if oldSourcePath != oldD.OrigName {
return "", fmt.Errorf("filenames mismatch for oldSourcePath: %q and oldDiff: %q",
oldSourcePath, oldD.OrigName)
}
newD, err := diff.NewFileDiffReader(newDiff).Read()
if err != nil {
return "", fmt.Errorf("parsing newDiff for %q: %w",
newSourcePath, err)
}
if newSourcePath != newD.OrigName {
return "", fmt.Errorf("filenames mismatch for newSourcePath: %q and newDiff: %q",
newSourcePath, newD.OrigName)
}
resultString, err := mixedModeFilePath(oldSourcePath, newSourcePath, oldD, newD)
return resultString, err
case oldSourceStat.IsDir() && newSourceStat.IsDir():
// Both paths are directories
resultString, err := mixedModeDirPath(oldSourcePath, newSourcePath, oldDiff, newDiff)
if err != nil {
return "", fmt.Errorf("compute diff for %q and %q: %w",
oldSourcePath, newSourcePath, err)
}
return resultString, nil
}
return "", errors.New("sources should be both dirs or files")
}
// readContent returns content of source as string
func readContent(source io.Reader) (string, error) {
buf := new(strings.Builder)
_, err := io.Copy(buf, source)
if err != nil {
return "", fmt.Errorf("copying source: %w", err)
}
return buf.String(), nil
}
// applyDiff returns applied changes from diffFile to source
func applyDiff(source string, diffFile *diff.FileDiff) (string, error) {
sourceBody := strings.Split(source, "\n")
// currentOrgSourceI = 1 -- In diff lines started counting from 1
var currentOrgSourceI int32 = 1
var newBody []string
for _, hunk := range diffFile.Hunks {
// Add untouched part of source
newBody = append(newBody, sourceBody[currentOrgSourceI-1:hunk.OrigStartLine-1]...)
currentOrgSourceI = hunk.OrigStartLine
hunkBody := strings.Split(strings.TrimSuffix(string(hunk.Body), "\n"), "\n")
for _, line := range hunkBody {
if currentOrgSourceI > int32(len(sourceBody)) {
return "", errors.New("diff content is out of source content")
}
if strings.HasPrefix(line, "+") {
newBody = append(newBody, line[1:])
} else {
if line[1:] != sourceBody[currentOrgSourceI-1] {
return "", fmt.Errorf(
"line %d in source (%q) and diff (%q): %w",
currentOrgSourceI, sourceBody[currentOrgSourceI-1], line[1:], ErrContentMismatch)
}
if strings.HasPrefix(line, " ") {
newBody = append(newBody, sourceBody[currentOrgSourceI-1])
}
currentOrgSourceI++
}
}
}
newBody = append(newBody, sourceBody[currentOrgSourceI-1:]...)
return strings.Join(newBody, "\n"), nil
}
// mixedModeFilePath computes the diff of a oldSourcePath file patched with oldFileDiff
// and the newSourcePath file patched with newFileDiff.
func mixedModeFilePath(oldSourcePath, newSourcePath string, oldFileDiff, newFileDiff *diff.FileDiff) (string, error) {
if oldFileDiff.OrigName != "" && oldFileDiff.NewName == "" && newFileDiff.OrigName != "" && newFileDiff.NewName == "" {
// In both updated version file has been deleted
return "", nil
}
if oldFileDiff.OrigName != "" && oldFileDiff.NewName == "" {
// File has been deleted in updated old version
return fmt.Sprintf("Only in %s: %s\n", filepath.Dir(newFileDiff.NewName),
filepath.Base(newFileDiff.NewName)), nil
}
if newFileDiff.OrigName != "" && newFileDiff.NewName == "" {
// File has been deleted in updated new version
return fmt.Sprintf("Only in %s: %s\n", filepath.Dir(oldFileDiff.NewName),
filepath.Base(oldFileDiff.NewName)), nil
}
oldSourceFile, err := os.Open(oldSourcePath)
if err != nil {
return "", fmt.Errorf("opening oldSource file %q: %w",
oldSourcePath, err)
}
newSourceFile, err := os.Open(newSourcePath)
if err != nil {
return "", fmt.Errorf("opening newSource file %q: %w",
newSourcePath, err)
}
resultString, err := mixedMode(oldSourceFile, newSourceFile, oldFileDiff, newFileDiff)
if err != nil {
return "", fmt.Errorf("compute diff for %q: %w",
oldFileDiff.OrigName, err)
}
return resultString, nil
}
// mixedModeDirPath computes the diff of a oldSourcePath directory patched with oldDiff
// and the newSourcePath directory patched with newDiff.
func mixedModeDirPath(oldSourcePath, newSourcePath string, oldDiff, newDiff io.Reader) (string, error) {
oldFileNames, err := getAllFileNamesInDir(oldSourcePath)
if err != nil {
return "", fmt.Errorf("get all filenames for oldSource: %w", err)
}
newFileNames, err := getAllFileNamesInDir(newSourcePath)
if err != nil {
return "", fmt.Errorf("get all filenames for newSourcePath: %w", err)
}
oldFileDiffReader := diff.NewMultiFileDiffReader(oldDiff)
newFileDiffReader := diff.NewMultiFileDiffReader(newDiff)
lastOldFileDiff, err := oldFileDiffReader.ReadFile()
if err != nil && !errors.Is(err, io.EOF) {
return "", fmt.Errorf("parsing next FileDiff in oldDiff: %w", err)
}
lastNewFileDiff, err := newFileDiffReader.ReadFile()
if err != nil && !errors.Is(err, io.EOF) {
return "", fmt.Errorf("parsing next FileDiff in newDiff: %w", err)
}
result := ""
updateOldDiff, updateNewDiff := false, false
onlyOldFile, onlyNewFile := false, false
// Iterate over files in FileDiff arrays
i, j := 0, 0
for i < len(oldFileNames) || j < len(newFileNames) {
if lastOldFileDiff != nil && i < len(oldFileNames) && oldFileNames[i] > lastOldFileDiff.OrigName {
if lastOldFileDiff.NewName != "" {
return "", fmt.Errorf("oldFileDiff: %q doesn't have relative file in oldSource",
lastOldFileDiff.OrigName)
}
// File has been added in old version
result += fmt.Sprintf("Only in %s: %s\n", filepath.Dir(lastOldFileDiff.OrigName),
filepath.Base(lastOldFileDiff.OrigName))
}
if lastNewFileDiff != nil && j < len(newFileNames) && newFileNames[j] > lastNewFileDiff.OrigName {
if lastNewFileDiff.NewName != "" {
return "", fmt.Errorf("newFileDiff: %q doesn't have relative file in newSource",
lastNewFileDiff.OrigName)
}
// File has been added in new version
result += fmt.Sprintf("Only in %s: %s\n", filepath.Dir(lastNewFileDiff.OrigName),
filepath.Base(lastNewFileDiff.OrigName))
}
switch {
case i < len(oldFileNames) && j < len(newFileNames):
switch {
// Comparing parts after oldSourcePath and newSourcePath
case strings.TrimPrefix(oldFileNames[i], oldSourcePath) == strings.TrimPrefix(newFileNames[j], newSourcePath):
switch {
case lastOldFileDiff != nil && lastNewFileDiff != nil &&
oldFileNames[i] == lastOldFileDiff.OrigName && newFileNames[j] == lastNewFileDiff.OrigName:
// Both oldFile and newFile have updates
currentResult, err := mixedModeFilePath(oldFileNames[i], newFileNames[j], lastOldFileDiff, lastNewFileDiff)
if err != nil {
return "", fmt.Errorf("mixedModeFilePath for oldFile: %q and newFile: %q: %w",
oldFileNames[i], newFileNames[j], err)
}
result += currentResult
updateOldDiff = true
updateNewDiff = true
case lastOldFileDiff != nil && oldFileNames[i] == lastOldFileDiff.OrigName:
// Only oldFile has updates
// Empty FileDiff instead of lastNewFileDiff
currentResult, err := mixedModeFilePath(oldFileNames[i], newFileNames[j], lastOldFileDiff, &diff.FileDiff{})
if err != nil {
return "", fmt.Errorf("mixedModeFilePath for oldFile: %q and newFile: %q: %w",
oldFileNames[i], newFileNames[j], err)
}
result += currentResult
updateOldDiff = true
case lastNewFileDiff != nil && newFileNames[j] == lastNewFileDiff.OrigName:
// Only newFile has updates
// Empty FileDiff instead of lastOldFileDiff
currentResult, err := mixedModeFilePath(oldFileNames[i], newFileNames[j], &diff.FileDiff{}, lastNewFileDiff)
if err != nil {
return "", fmt.Errorf("mixedModeFilePath for oldFile: %q and newFile: %q: %w",
oldFileNames[i], newFileNames[j], err)
}
result += currentResult
updateNewDiff = true
default:
// None of oldFile and newFile have updates
currentResult, err := mixedModeFilePath(oldFileNames[i], newFileNames[j], &diff.FileDiff{}, &diff.FileDiff{})
if err != nil {
return "", fmt.Errorf("mixedModeFilePath for oldFile: %q and newFile: %q: %w",
oldFileNames[i], newFileNames[j], err)
}
result += currentResult
}
i++
j++
case strings.TrimPrefix(oldFileNames[i], oldSourcePath) < strings.TrimPrefix(newFileNames[j], newSourcePath):
onlyOldFile = true
default:
onlyNewFile = true
}
case i < len(oldFileNames):
// In case there are more oldFileDiffs, while newFileDiffs are run out
onlyOldFile = true
default:
// In case there are more newFileDiffs, while oldFileDiffs are run out
onlyNewFile = true
}
if onlyOldFile {
// mark to update oldFileDiff if last one was related to current oldFile
if lastOldFileDiff != nil && oldFileNames[i] == lastOldFileDiff.OrigName {
updateOldDiff = true
// If file was deleted in oldFileDiff, don't add "Only in" message later
if lastOldFileDiff.NewName == "" {
onlyOldFile = false
}
}
if onlyOldFile {
result += fmt.Sprintf("Only in %s: %s\n", filepath.Dir(oldFileNames[i]),
filepath.Base(oldFileNames[i]))
}
i++
onlyOldFile = false
}
if onlyNewFile {
// mark to update newFileDiff if last one was related to current newFile
if lastNewFileDiff != nil && newFileNames[j] == lastNewFileDiff.OrigName {
updateNewDiff = true
// If file was deleted in newFileDiff, don't add "Only in" message later
if lastNewFileDiff.NewName == "" {
onlyNewFile = true
}
}
if onlyNewFile {
result += fmt.Sprintf("Only in %s: %s\n", filepath.Dir(newFileNames[j]),
filepath.Base(newFileNames[j]))
}
j++
onlyNewFile = false
}
if updateOldDiff {
// get next lastOldFileDiff
lastOldFileDiff, err = oldFileDiffReader.ReadFile()
if err != nil {
if !errors.Is(err, io.EOF) {
return "", fmt.Errorf("parsing next FileDiff in oldDiff: %w", err)
}
lastOldFileDiff = nil
}
updateOldDiff = false
}
if updateNewDiff {
// get next lastNewFileDiff
lastNewFileDiff, err = newFileDiffReader.ReadFile()
if err != nil {
if !errors.Is(err, io.EOF) {
return "", fmt.Errorf("parsing next FileDiff in newDiff: %w", err)
}
lastNewFileDiff = nil
}
updateNewDiff = false
}
}
// Check if more files have been added in old version
for lastOldFileDiff != nil {
if lastOldFileDiff.NewName != "" {
return "", fmt.Errorf("oldFileDiff: %q doesn't have relative file in oldSource",
lastOldFileDiff.OrigName)
}
// File has been added
result += fmt.Sprintf("Only in %s: %s\n", filepath.Dir(lastOldFileDiff.OrigName),
filepath.Base(lastOldFileDiff.OrigName))
// Update lastOldFileDiff
lastOldFileDiff, err = oldFileDiffReader.ReadFile()
if err != nil {
if !errors.Is(err, io.EOF) {
return "", fmt.Errorf("parsing next FileDiff in oldDiff: %w", err)
}
lastOldFileDiff = nil
}
}
// Check if more files have been added in new version
for lastNewFileDiff != nil {
if lastNewFileDiff.NewName != "" {
return "", fmt.Errorf("newFileDiff: %q doesn't have relative file in newSource",
lastNewFileDiff.OrigName)
}
// File has been added
result += fmt.Sprintf("Only in %s: %s\n", filepath.Dir(lastNewFileDiff.OrigName),
filepath.Base(lastNewFileDiff.OrigName))
// Update lastNewFileDiff
lastNewFileDiff, err = newFileDiffReader.ReadFile()
if err != nil {
if !errors.Is(err, io.EOF) {
return "", fmt.Errorf("parsing next FileDiff in newDiff: %w", err)
}
lastNewFileDiff = nil
}
}
return result, nil
}
// getAllFileNamesInDir returns array of paths to files in root recursively.
func getAllFileNamesInDir(root string) ([]string, error) {
var allFiles []string
err := filepath.Walk(root,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk into %q: %w",
path, err)
}
if !info.IsDir() {
allFiles = append(allFiles, path)
}
return nil
})
return allFiles, err
}
const contextLines = 2
// convertChunksIntoFileDiff adds the given chunks to the fileDiff struct.
func convertChunksIntoFileDiff(chunks []dbd.Chunk, fileDiff *diff.FileDiff) {
var currentOldI, currentNewI int32 = 1, 1
currentHunk := &diff.Hunk{
OrigStartLine: currentOldI,
NewStartLine: currentNewI,
}
// Delete empty chunks in the beginning
for len(chunks) > 0 && len(chunks[0].Added) == 0 && len(chunks[0].Deleted) == 0 && len(chunks[0].Equal) == 0 {
chunks = chunks[1:]
}
// Delete empty chunks in the end
last := len(chunks) - 1
for len(chunks) > 0 && len(chunks[last].Added) == 0 && len(chunks[last].Deleted) == 0 && len(chunks[last].Equal) == 0 {
chunks = chunks[:last]
last--
}
// If chunks contains only one element with only unchanged lines
if len(chunks) == 1 && len(chunks[0].Added) == 0 && len(chunks[0].Deleted) == 0 {
return
}
var currentHunkBody []string
// If array of chunks is already empty
if len(chunks) == 0 {
return
}
// If first chunk contains only equal lines, we are adding last contextLines to currentHunk
if len(chunks[0].Added) == 0 && len(chunks[0].Deleted) == 0 {
currentOldI += int32(len(chunks[0].Equal))
currentNewI += int32(len(chunks[0].Equal))
if len(chunks[0].Equal) > contextLines {
for _, line := range chunks[0].Equal[len(chunks[0].Equal)-contextLines:] {
currentHunkBody = append(currentHunkBody, " "+line)
currentHunk.OrigStartLine = currentOldI - contextLines
currentHunk.NewStartLine = currentNewI - contextLines
}
} else {
for _, line := range chunks[0].Equal {
currentHunkBody = append(currentHunkBody, " "+line)
}
}
// Removing processed first hunk
chunks = chunks[1:]
}
var lastLines []string
last = len(chunks) - 1
// If last chunk contains equal lines, save first contextLines of equal lines for further processing
if len(chunks[last].Equal) > 0 {
if len(chunks[last].Equal) > contextLines {
for _, line := range chunks[last].Equal[:contextLines] {
lastLines = append(lastLines, " "+line)
}
} else {
for _, line := range chunks[last].Equal {
lastLines = append(lastLines, " "+line)
}
}
// Removing processed equal lines from last chunk
chunks[last].Equal = []string{}
}
for _, c := range chunks {
// A chunk will not have both added and deleted lines.
for _, line := range c.Added {
currentHunkBody = append(currentHunkBody, "+"+line)
currentNewI++
}
for _, line := range c.Deleted {
currentHunkBody = append(currentHunkBody, "-"+line)
currentOldI++
}
// Next piece of content contains too many unchanged lines.
// Current hunk will be 'closed' and started new one.
if len(c.Equal) > 2*contextLines+1 {
if len(currentHunkBody) > 0 {
for _, line := range c.Equal[:contextLines] {
currentHunkBody = append(currentHunkBody, " "+line)
}
currentHunk.OrigLines = currentOldI + contextLines + 1 - currentHunk.OrigStartLine
currentHunk.NewLines = currentNewI + contextLines + 1 - currentHunk.NewStartLine
currentHunk.Body = []byte(strings.Join(currentHunkBody, "\n") + "\n")
fileDiff.Hunks = append(fileDiff.Hunks, currentHunk)
}
currentOldI += int32(len(c.Equal))
currentNewI += int32(len(c.Equal))
currentHunk = &diff.Hunk{
OrigStartLine: currentOldI - contextLines,
NewStartLine: currentNewI - contextLines,
}
// Clean currentHunkBody
currentHunkBody = []string{}
for _, line := range c.Equal[len(c.Equal)-contextLines-1:] {
currentHunkBody = append(currentHunkBody, " "+line)
}
} else {
for _, line := range c.Equal {
currentHunkBody = append(currentHunkBody, " "+line)
currentOldI++
currentNewI++
}
}
}
// Add lastLines (equal) to last hunk
for _, line := range lastLines {
currentHunkBody = append(currentHunkBody, line)
currentOldI++
currentNewI++
}
// currentHunkBody contains some lines. It need to be 'closed' and added to fileDiff.Hunks
currentHunk.OrigLines = currentOldI - currentHunk.OrigStartLine
currentHunk.NewLines = currentNewI - currentHunk.NewStartLine
currentHunk.Body = []byte(strings.Join(currentHunkBody, "\n") + "\n")
fileDiff.Hunks = append(fileDiff.Hunks, currentHunk)
}
// interPrintSingleFileDiff returns printed version of diffFile, which was found only in one out of two versions.
func interPrintSingleFileDiff(diffFile *diff.FileDiff) (string, error) {
if diffFile.NewName == "" {
// File has been added in current version
return fmt.Sprintf("Only in %s: %s\n", filepath.Dir(diffFile.OrigName),
filepath.Base(diffFile.OrigName)), nil
}
// File has been changed in current version and left unchanged in other version
oldD, err := diff.PrintFileDiff(diffFile)
if err != nil {
return "", fmt.Errorf("printing diff for file %q: %w",
diffFile.NewName, err)
}
return string(oldD), nil
}
// interFileDiff returns a new diff.FileDiff that is a diff of a source file patched with oldFileDiff
// and the same source file patched with newFileDiff.
func interFileDiff(oldFileDiff, newFileDiff *diff.FileDiff) (*diff.FileDiff, error) {
// Configuration of result FileDiff
// TODO: something with extended (extended header lines)
resultFileDiff := &diff.FileDiff{
OrigName: oldFileDiff.NewName,
OrigTime: oldFileDiff.NewTime,
NewName: newFileDiff.NewName,
NewTime: newFileDiff.NewTime,
Extended: []string{},
Hunks: []*diff.Hunk{}}
// Iterating over hunks in order they start in origin
i, j := 0, 0
for i < len(oldFileDiff.Hunks) && j < len(newFileDiff.Hunks) {
switch {
case oldFileDiff.Hunks[i].OrigStartLine+oldFileDiff.Hunks[i].OrigLines < newFileDiff.Hunks[j].OrigStartLine:
// Whole oldHunk is before starting of newHunk
resultFileDiff.Hunks = append(resultFileDiff.Hunks,
revertedHunkBody(oldFileDiff.Hunks[i]))
i++
case newFileDiff.Hunks[j].OrigStartLine+newFileDiff.Hunks[j].OrigLines < oldFileDiff.Hunks[i].OrigStartLine:
// Whole newHunk is before starting of oldHunk
resultFileDiff.Hunks = append(resultFileDiff.Hunks, newFileDiff.Hunks[j])
j++
default:
// oldHunk and newHunk are overlapping somehow
// Collecting a whole set of overlapping hunks to produce one continuous hunk
oldHunks, newHunks := findOverlappingHunkSet(oldFileDiff, newFileDiff, &i, &j)
mergedOverlappingHunk, err := mergeOverlappingHunks(oldHunks, newHunks)
if err != nil {
return nil, fmt.Errorf("merging overlapping hunks: %w", err)
}
// In case opposite hunks aren't doing same changes.
if mergedOverlappingHunk != nil {
resultFileDiff.Hunks = append(resultFileDiff.Hunks, mergedOverlappingHunk)
}
}
}
// In case there are more hunks in oldFileDiff, while hunks of newFileDiff are run out
for i < len(oldFileDiff.Hunks) {
resultFileDiff.Hunks = append(resultFileDiff.Hunks,
revertedHunkBody(oldFileDiff.Hunks[i]))
i++
}
// In case there are more hunks in newFileDiff, while hunks of oldFileDiff are run out
for j < len(newFileDiff.Hunks) {
resultFileDiff.Hunks = append(resultFileDiff.Hunks, newFileDiff.Hunks[j])
j++
}
return resultFileDiff, nil
}
// findOverlappingHunkSet finds next set (two arrays: oldHunks and newHunks) of
// overlapping hunks in oldFileDiff and newFileDiff, starting from position i, j relatively.
func findOverlappingHunkSet(oldFileDiff, newFileDiff *diff.FileDiff, i, j *int) (oldHunks, newHunks []*diff.Hunk) {
// Collecting overlapped hunks into two arrays
oldHunks = append(oldHunks, oldFileDiff.Hunks[*i])
newHunks = append(newHunks, newFileDiff.Hunks[*j])
*i++
*j++
Loop:
for {
switch {
// Starting line of oldHunk is in previous newHunk body (between start and last lines)
case *i < len(oldFileDiff.Hunks) && oldFileDiff.Hunks[*i].OrigStartLine >= newFileDiff.Hunks[*j-1].OrigStartLine &&
oldFileDiff.Hunks[*i].OrigStartLine < newFileDiff.Hunks[*j-1].OrigStartLine+newFileDiff.Hunks[*j-1].OrigLines:
oldHunks = append(oldHunks, oldFileDiff.Hunks[*i])
*i++
// Starting line of newHunk is in previous oldHunk body (between start and last lines)
case *j < len(newFileDiff.Hunks) && newFileDiff.Hunks[*j].OrigStartLine >= oldFileDiff.Hunks[*i-1].OrigStartLine &&
newFileDiff.Hunks[*j].OrigStartLine < oldFileDiff.Hunks[*i-1].OrigStartLine+oldFileDiff.Hunks[*i-1].OrigLines:
newHunks = append(newHunks, newFileDiff.Hunks[*j])
*j++
default:
// No overlapping hunks left
break Loop
}
}
return oldHunks, newHunks
}
// mergeOverlappingHunks returns a new diff.Hunk that is a diff hunk between overlapping oldHunks and newHunks,
// related to the same source file.
func mergeOverlappingHunks(oldHunks, newHunks []*diff.Hunk) (*diff.Hunk, error) {
resultHunk, currentOrgI, err := configureResultHunk(oldHunks, newHunks)
if err != nil {
return nil, fmt.Errorf("configuring result hunk: %w", err)
}
// Indexes of hunks
currentOldHunkI, currentNewHunkJ := 0, 0
// Indexes of lines in body hunks
// if indexes == -1 -- we don't have relevant hunk, which contains changes nearby currentOrgI
i, j := -1, -1
// Body of hunks
var newBody []string
var oldHunkBody, newHunkBody []string
// Iterating through the hunks in the order they're appearing in origin file.
// Using number of line in origin (currentOrgI) as an anchor to process line by line.
// By using currentOrgI as anchor it is easier to see how changes have been applied step by step.
// Merge, while there are hunks to process
for currentOldHunkI < len(oldHunks) || currentNewHunkJ < len(newHunks) {
// Entering next hunk in oldHunks
if currentOldHunkI < len(oldHunks) && i == -1 && currentOrgI == oldHunks[currentOldHunkI].OrigStartLine {
i = 0
oldHunkBody = strings.Split(strings.TrimSuffix(string(oldHunks[currentOldHunkI].Body), "\n"), "\n")
}
// Entering next hunk in newHunks
if currentNewHunkJ < len(newHunks) && j == -1 && currentOrgI == newHunks[currentNewHunkJ].OrigStartLine {
j = 0
newHunkBody = strings.Split(strings.TrimSuffix(string(newHunks[currentNewHunkJ].Body), "\n"), "\n")
}
switch {
case i == -1 && j == -1:
case i >= 0 && j == -1:
// Changes are only in oldHunk
newBody = append(newBody, revertedLine(oldHunkBody[i]))
// In case current line haven't been added, we have processed anchor line.
if !strings.HasPrefix(oldHunkBody[i], "+") {
// Updating index of anchor line.
currentOrgI++
}
i++
case i == -1 && j >= 0:
// Changes are only in newHunk
newBody = append(newBody, newHunkBody[j])
// In case current line haven't been added, we have processed anchor line.
if !strings.HasPrefix(newHunkBody[j], "+") {
// Updating index of anchor line.
currentOrgI++
}
j++
default:
// Changes are in old and new hunks.
switch {
// Firstly proceeding added lines,
// because added lines are between previous currentOrgI and currentOrgI.
case strings.HasPrefix(oldHunkBody[i], "+") || strings.HasPrefix(newHunkBody[j], "+"):
newBody = append(newBody, interAddedLines(&i, &j, &oldHunkBody, &newHunkBody)...)
default:
// Checking if original content is the same
if oldHunkBody[i][1:] != newHunkBody[j][1:] {
return nil, fmt.Errorf(
"line in original %d in oldDiff (%q) and newDiff (%q): %w",
currentOrgI, oldHunkBody[i][1:], newHunkBody[j][1:], ErrContentMismatch)
}
switch {
case strings.HasPrefix(oldHunkBody[i], " ") && strings.HasPrefix(newHunkBody[j], " "):
newBody = append(newBody, oldHunkBody[i])
case strings.HasPrefix(oldHunkBody[i], "-") && strings.HasPrefix(newHunkBody[j], " "):
newBody = append(newBody, revertedLine(oldHunkBody[i]))
case strings.HasPrefix(oldHunkBody[i], " ") && strings.HasPrefix(newHunkBody[j], "-"):
newBody = append(newBody, newHunkBody[j])
// If both have deleted same line, no need to append it to newBody
}
// Updating currentOrgI since we have processed anchor line.
currentOrgI++
i++
j++
}
}
if i >= len(oldHunkBody) {
// Proceed whole oldHunkBody
i = -1
currentOldHunkI++
}
if j >= len(newHunkBody) {
// Proceed whole newHunkBody
j = -1
currentNewHunkJ++
}
}
resultHunk.Body = []byte(strings.Join(newBody, "\n") + "\n")
for _, line := range newBody {
if !strings.HasPrefix(line, " ") {
// resultHunkBody contains some changes
return resultHunk, nil
}
}
return nil, nil
}
// interAddedLines finds interdiff between added lines in oldHunkBody (after i) and newHunkBody (after j)
func interAddedLines(i, j *int, oldHunkBody, newHunkBody *[]string) []string {
var result, oldAddedLines, newAddedLines []string
// Collect added lines in oldHunkBody
for (*i < len(*oldHunkBody)) && (strings.HasPrefix((*oldHunkBody)[*i], "+")) {
oldAddedLines = append(oldAddedLines, (*oldHunkBody)[*i][1:])
*i++
}
// Collect added lines in newHunkBody
for (*j < len(*newHunkBody)) && (strings.HasPrefix((*newHunkBody)[*j], "+")) {
newAddedLines = append(newAddedLines, (*newHunkBody)[*j][1:])
*j++
}
// Difference between collected added lines
chunks := dbd.DiffChunks(oldAddedLines, newAddedLines)
for _, c := range chunks {
// A chunk will not have both added and deleted lines.
for _, line := range c.Added {
result = append(result, "+"+line)
}
for _, line := range c.Deleted {
result = append(result, "-"+line)
}
for _, line := range c.Equal {
result = append(result, " "+line)
}
}
return result
}
// configureResultHunk returns a new diff.Hunk (with configured StartLines and NumberLines)
// and currentOrgI (number of anchor line) based on oldHunks and newHunks, for their further merge.
func configureResultHunk(oldHunks, newHunks []*diff.Hunk) (*diff.Hunk, int32, error) {
if len(oldHunks) == 0 || len(newHunks) == 0 {
return nil, 0, errors.New("one of the hunks array is empty")
}