Debian Codegraph @

plumbing/object/rename.go

raw
1 package object
2
3 import (
4 "errors"
5 "io"
6 "sort"
7 "strings"
8
9 "github.com/go-git/go-git/v5/plumbing"
10 "github.com/go-git/go-git/v5/plumbing/filemode"
11 "github.com/go-git/go-git/v5/utils/ioutil"
12 "github.com/go-git/go-git/v5/utils/merkletrie"
13 )
14
15 // DetectRenames detects the renames in the given changes on two trees with
16 // the given options. It will return the given changes grouping additions and
17 // deletions into modifications when possible.
18 // If options is nil, the default diff tree options will be used.
19 func DetectRenames(
20 changes Changes,
21 opts *DiffTreeOptions,
22 ) (Changes, error) {
23 if opts == nil {
24 opts = DefaultDiffTreeOptions
25 }
26
27 detector := &renameDetector{
28 renameScore: int(opts.RenameScore),
29 renameLimit: int(opts.RenameLimit),
30 onlyExact: opts.OnlyExactRenames,
31 }
32
33 for _, c := range changes {
34 action, err := c.Action()
35 if err != nil {
36 return nil, err
37 }
38
39 switch action {
40 case merkletrie.Insert:
41 detector.added = append(detector.added, c)
42 case merkletrie.Delete:
43 detector.deleted = append(detector.deleted, c)
44 default:
45 detector.modified = append(detector.modified, c)
46 }
47 }
48
49 return detector.detect()
50 }
51
52 // renameDetector will detect and resolve renames in a set of changes.
53 // see: https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/eclipse/jgit/diff/RenameDetector.java
54 type renameDetector struct {
55 added []*Change
56 deleted []*Change
57 modified []*Change
58
59 renameScore int
60 renameLimit int
61 onlyExact bool
62 }
63
64 // detectExactRenames detects matches files that were deleted with files that
65 // were added where the hash is the same on both. If there are multiple targets
66 // the one with the most similar path will be chosen as the rename and the
67 // rest as either deletions or additions.
68 func (d *renameDetector) detectExactRenames() {
69 added := groupChangesByHash(d.added)
70 deletes := groupChangesByHash(d.deleted)
71 var uniqueAdds []*Change
72 var nonUniqueAdds [][]*Change
73 var addedLeft []*Change
74
75 for _, cs := range added {
76 if len(cs) == 1 {
77 uniqueAdds = append(uniqueAdds, cs[0])
78 } else {
79 nonUniqueAdds = append(nonUniqueAdds, cs)
80 }
81 }
82
83 for _, c := range uniqueAdds {
84 hash := changeHash(c)
85 deleted := deletes[hash]
86
87 if len(deleted) == 1 {
88 if sameMode(c, deleted[0]) {
89 d.modified = append(d.modified, &Change{From: deleted[0].From, To: c.To})
90 delete(deletes, hash)
91 } else {
92 addedLeft = append(addedLeft, c)
93 }
94 } else if len(deleted) > 1 {
95 bestMatch := bestNameMatch(c, deleted)
96 if bestMatch != nil && sameMode(c, bestMatch) {
97 d.modified = append(d.modified, &Change{From: bestMatch.From, To: c.To})
98 delete(deletes, hash)
99
100 var newDeletes = make([]*Change, 0, len(deleted)-1)
101 for _, d := range deleted {
102 if d != bestMatch {
103 newDeletes = append(newDeletes, d)
104 }
105 }
106 deletes[hash] = newDeletes
107 }
108 } else {
109 addedLeft = append(addedLeft, c)
110 }
111 }
112
113 for _, added := range nonUniqueAdds {
114 hash := changeHash(added[0])
115 deleted := deletes[hash]
116
117 if len(deleted) == 1 {
118 deleted := deleted[0]
119 bestMatch := bestNameMatch(deleted, added)
120 if bestMatch != nil && sameMode(deleted, bestMatch) {
121 d.modified = append(d.modified, &Change{From: deleted.From, To: bestMatch.To})
122 delete(deletes, hash)
123
124 for _, c := range added {
125 if c != bestMatch {
126 addedLeft = append(addedLeft, c)
127 }
128 }
129 } else {
130 addedLeft = append(addedLeft, added...)
131 }
132 } else if len(deleted) > 1 {
133 maxSize := len(deleted) * len(added)
134 if d.renameLimit > 0 && d.renameLimit < maxSize {
135 maxSize = d.renameLimit
136 }
137
138 matrix := make(similarityMatrix, 0, maxSize)
139
140 for delIdx, del := range deleted {
141 deletedName := changeName(del)
142
143 for addIdx, add := range added {
144 addedName := changeName(add)
145
146 score := nameSimilarityScore(addedName, deletedName)
147 matrix = append(matrix, similarityPair{added: addIdx, deleted: delIdx, score: score})
148
149 if len(matrix) >= maxSize {
150 break
151 }
152 }
153
154 if len(matrix) >= maxSize {
155 break
156 }
157 }
158
159 sort.Stable(matrix)
160
161 usedAdds := make(map[*Change]struct{})
162 usedDeletes := make(map[*Change]struct{})
163 for i := len(matrix) - 1; i >= 0; i-- {
164 del := deleted[matrix[i].deleted]
165 add := added[matrix[i].added]
166
167 if add == nil || del == nil {
168 // it was already matched
169 continue
170 }
171
172 usedAdds[add] = struct{}{}
173 usedDeletes[del] = struct{}{}
174 d.modified = append(d.modified, &Change{From: del.From, To: add.To})
175 added[matrix[i].added] = nil
176 deleted[matrix[i].deleted] = nil
177 }
178
179 for _, c := range added {
180 if _, ok := usedAdds[c]; !ok && c != nil {
181 addedLeft = append(addedLeft, c)
182 }
183 }
184
185 var newDeletes = make([]*Change, 0, len(deleted)-len(usedDeletes))
186 for _, c := range deleted {
187 if _, ok := usedDeletes[c]; !ok && c != nil {
188 newDeletes = append(newDeletes, c)
189 }
190 }
191 deletes[hash] = newDeletes
192 } else {
193 addedLeft = append(addedLeft, added...)
194 }
195 }
196
197 d.added = addedLeft
198 d.deleted = nil
199 for _, dels := range deletes {
200 d.deleted = append(d.deleted, dels...)
201 }
202 }
203
204 // detectContentRenames detects renames based on the similarity of the content
205 // in the files by building a matrix of pairs between sources and destinations
206 // and matching by the highest score.
207 // see: https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityRenameDetector.java
208 func (d *renameDetector) detectContentRenames() error {
209 cnt := max(len(d.added), len(d.deleted))
210 if d.renameLimit > 0 && cnt > d.renameLimit {
211 return nil
212 }
213
214 srcs, dsts := d.deleted, d.added
215 matrix, err := buildSimilarityMatrix(srcs, dsts, d.renameScore)
216 if err != nil {
217 return err
218 }
219 renames := make([]*Change, 0, min(len(matrix), len(dsts)))
220
221 // Match rename pairs on a first come, first serve basis until
222 // we have looked at everything that is above the minimum score.
223 for i := len(matrix) - 1; i >= 0; i-- {
224 pair := matrix[i]
225 src := srcs[pair.deleted]
226 dst := dsts[pair.added]
227
228 if dst == nil || src == nil {
229 // It was already matched before
230 continue
231 }
232
233 renames = append(renames, &Change{From: src.From, To: dst.To})
234
235 // Claim destination and source as matched
236 dsts[pair.added] = nil
237 srcs[pair.deleted] = nil
238 }
239
240 d.modified = append(d.modified, renames...)
241 d.added = compactChanges(dsts)
242 d.deleted = compactChanges(srcs)
243
244 return nil
245 }
246
247 func (d *renameDetector) detect() (Changes, error) {
248 if len(d.added) > 0 && len(d.deleted) > 0 {
249 d.detectExactRenames()
250
251 if !d.onlyExact {
252 if err := d.detectContentRenames(); err != nil {
253 return nil, err
254 }
255 }
256 }
257
258 result := make(Changes, 0, len(d.added)+len(d.deleted)+len(d.modified))
259 result = append(result, d.added...)
260 result = append(result, d.deleted...)
261 result = append(result, d.modified...)
262
263 sort.Stable(result)
264
265 return result, nil
266 }
267
268 func bestNameMatch(change *Change, changes []*Change) *Change {
269 var best *Change
270 var bestScore int
271
272 cname := changeName(change)
273
274 for _, c := range changes {
275 score := nameSimilarityScore(cname, changeName(c))
276 if score > bestScore {
277 bestScore = score
278 best = c
279 }
280 }
281
282 return best
283 }
284
285 func nameSimilarityScore(a, b string) int {
286 aDirLen := strings.LastIndexByte(a, '/') + 1
287 bDirLen := strings.LastIndexByte(b, '/') + 1
288
289 dirMin := min(aDirLen, bDirLen)
290 dirMax := max(aDirLen, bDirLen)
291
292 var dirScoreLtr, dirScoreRtl int
293 if dirMax == 0 {
294 dirScoreLtr = 100
295 dirScoreRtl = 100
296 } else {
297 var dirSim int
298
299 for ; dirSim < dirMin; dirSim++ {
300 if a[dirSim] != b[dirSim] {
301 break
302 }
303 }
304
305 dirScoreLtr = dirSim * 100 / dirMax
306
307 if dirScoreLtr == 100 {
308 dirScoreRtl = 100
309 } else {
310 for dirSim = 0; dirSim < dirMin; dirSim++ {
311 if a[aDirLen-1-dirSim] != b[bDirLen-1-dirSim] {
312 break
313 }
314 }
315 dirScoreRtl = dirSim * 100 / dirMax
316 }
317 }
318
319 fileMin := min(len(a)-aDirLen, len(b)-bDirLen)
320 fileMax := max(len(a)-aDirLen, len(b)-bDirLen)
321
322 fileSim := 0
323 for ; fileSim < fileMin; fileSim++ {
324 if a[len(a)-1-fileSim] != b[len(b)-1-fileSim] {
325 break
326 }
327 }
328 fileScore := fileSim * 100 / fileMax
329
330 return (((dirScoreLtr + dirScoreRtl) * 25) + (fileScore * 50)) / 100
331 }
332
333 func changeName(c *Change) string {
334 if c.To != empty {
335 return c.To.Name
336 }
337 return c.From.Name
338 }
339
340 func changeHash(c *Change) plumbing.Hash {
341 if c.To != empty {
342 return c.To.TreeEntry.Hash
343 }
344
345 return c.From.TreeEntry.Hash
346 }
347
348 func changeMode(c *Change) filemode.FileMode {
349 if c.To != empty {
350 return c.To.TreeEntry.Mode
351 }
352
353 return c.From.TreeEntry.Mode
354 }
355
356 func sameMode(a, b *Change) bool {
357 return changeMode(a) == changeMode(b)
358 }
359
360 func groupChangesByHash(changes []*Change) map[plumbing.Hash][]*Change {
361 var result = make(map[plumbing.Hash][]*Change)
362 for _, c := range changes {
363 hash := changeHash(c)
364 result[hash] = append(result[hash], c)
365 }
366 return result
367 }
368
369 type similarityMatrix []similarityPair
370
371 func (m similarityMatrix) Len() int { return len(m) }
372 func (m similarityMatrix) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
373 func (m similarityMatrix) Less(i, j int) bool {
374 if m[i].score == m[j].score {
375 if m[i].added == m[j].added {
376 return m[i].deleted < m[j].deleted
377 }
378 return m[i].added < m[j].added
379 }
380 return m[i].score < m[j].score
381 }
382
383 type similarityPair struct {
384 // index of the added file
385 added int
386 // index of the deleted file
387 deleted int
388 // similarity score
389 score int
390 }
391
392 func max(a, b int) int {
393 if a > b {
394 return a
395 }
396 return b
397 }
398
399 func min(a, b int) int {
400 if a < b {
401 return a
402 }
403 return b
404 }
405
406 const maxMatrixSize = 10000
407
408 func buildSimilarityMatrix(srcs, dsts []*Change, renameScore int) (similarityMatrix, error) {
409 // Allocate for the worst-case scenario where every pair has a score
410 // that we need to consider. We might not need that many.
411 matrixSize := len(srcs) * len(dsts)
412 if matrixSize > maxMatrixSize {
413 matrixSize = maxMatrixSize
414 }
415 matrix := make(similarityMatrix, 0, matrixSize)
416 srcSizes := make([]int64, len(srcs))
417 dstSizes := make([]int64, len(dsts))
418 dstTooLarge := make(map[int]bool)
419
420 // Consider each pair of files, if the score is above the minimum
421 // threshold we need to record that scoring in the matrix so we can
422 // later find the best matches.
423 outerLoop:
424 for srcIdx, src := range srcs {
425 if changeMode(src) != filemode.Regular {
426 continue
427 }
428
429 // Declare the from file and the similarity index here to be able to
430 // reuse it inside the inner loop. The reason to not initialize them
431 // here is so we can skip the initialization in case they happen to
432 // not be needed later. They will be initialized inside the inner
433 // loop if and only if they're needed and reused in subsequent passes.
434 var from *File
435 var s *similarityIndex
436 var err error
437 for dstIdx, dst := range dsts {
438 if changeMode(dst) != filemode.Regular {
439 continue
440 }
441
442 if dstTooLarge[dstIdx] {
443 continue
444 }
445
446 var to *File
447 srcSize := srcSizes[srcIdx]
448 if srcSize == 0 {
449 from, _, err = src.Files()
450 if err != nil {
451 return nil, err
452 }
453 srcSize = from.Size + 1
454 srcSizes[srcIdx] = srcSize
455 }
456
457 dstSize := dstSizes[dstIdx]
458 if dstSize == 0 {
459 _, to, err = dst.Files()
460 if err != nil {
461 return nil, err
462 }
463 dstSize = to.Size + 1
464 dstSizes[dstIdx] = dstSize
465 }
466
467 min, max := srcSize, dstSize
468 if dstSize < srcSize {
469 min = dstSize
470 max = srcSize
471 }
472
473 if int(min*100/max) < renameScore {
474 // File sizes are too different to be a match
475 continue
476 }
477
478 if s == nil {
479 s, err = fileSimilarityIndex(from)
480 if err != nil {
481 if err == errIndexFull {
482 continue outerLoop
483 }
484 return nil, err
485 }
486 }
487
488 if to == nil {
489 _, to, err = dst.Files()
490 if err != nil {
491 return nil, err
492 }
493 }
494
495 di, err := fileSimilarityIndex(to)
496 if err != nil {
497 if err == errIndexFull {
498 dstTooLarge[dstIdx] = true
499 }
500
501 return nil, err
502 }
503
504 contentScore := s.score(di, 10000)
505 // The name score returns a value between 0 and 100, so we need to
506 // convert it to the same range as the content score.
507 nameScore := nameSimilarityScore(src.From.Name, dst.To.Name) * 100
508 score := (contentScore*99 + nameScore*1) / 10000
509
510 if score < renameScore {
511 continue
512 }
513
514 matrix = append(matrix, similarityPair{added: dstIdx, deleted: srcIdx, score: score})
515 }
516 }
517
518 sort.Stable(matrix)
519
520 return matrix, nil
521 }
522
523 func compactChanges(changes []*Change) []*Change {
524 var result []*Change
525 for _, c := range changes {
526 if c != nil {
527 result = append(result, c)
528 }
529 }
530 return result
531 }
532
533 const (
534 keyShift = 32
535 maxCountValue = (1 << keyShift) - 1
536 )
537
538 var errIndexFull = errors.New("index is full")
539
540 // similarityIndex is an index structure of lines/blocks in one file.
541 // This structure can be used to compute an approximation of the similarity
542 // between two files.
543 // To save space in memory, this index uses a space efficient encoding which
544 // will not exceed 1MiB per instance. The index starts out at a smaller size
545 // (closer to 2KiB), but may grow as more distinct blocks within the scanned
546 // file are discovered.
547 // see: https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityIndex.java
548 type similarityIndex struct {
549 hashed uint64
550 // number of non-zero entries in hashes
551 numHashes int
552 growAt int
553 hashes []keyCountPair
554 hashBits int
555 }
556
557 func fileSimilarityIndex(f *File) (*similarityIndex, error) {
558 idx := newSimilarityIndex()
559 if err := idx.hash(f); err != nil {
560 return nil, err
561 }
562
563 sort.Stable(keyCountPairs(idx.hashes))
564
565 return idx, nil
566 }
567
568 func newSimilarityIndex() *similarityIndex {
569 return &similarityIndex{
570 hashBits: 8,
571 hashes: make([]keyCountPair, 1<<8),
572 growAt: shouldGrowAt(8),
573 }
574 }
575
576 func (i *similarityIndex) hash(f *File) error {
577 isBin, err := f.IsBinary()
578 if err != nil {
579 return err
580 }
581
582 r, err := f.Reader()
583 if err != nil {
584 return err
585 }
586
587 defer ioutil.CheckClose(r, &err)
588
589 return i.hashContent(r, f.Size, isBin)
590 }
591
592 func (i *similarityIndex) hashContent(r io.Reader, size int64, isBin bool) error {
593 var buf = make([]byte, 4096)
594 var ptr, cnt int
595 remaining := size
596
597 for 0 < remaining {
598 hash := 5381
599 var blockHashedCnt uint64
600
601 // Hash one line or block, whatever happens first
602 n := int64(0)
603 for {
604 if ptr == cnt {
605 ptr = 0
606 var err error
607 cnt, err = io.ReadFull(r, buf)
608 if err != nil && err != io.ErrUnexpectedEOF {
609 return err
610 }
611
612 if cnt == 0 {
613 return io.EOF
614 }
615 }
616 n++
617 c := buf[ptr] & 0xff
618 ptr++
619
620 // Ignore CR in CRLF sequence if it's text
621 if !isBin && c == '\r' && ptr < cnt && buf[ptr] == '\n' {
622 continue
623 }
624 blockHashedCnt++
625
626 if c == '\n' {
627 break
628 }
629
630 hash = (hash << 5) + hash + int(c)
631
632 if n >= 64 || n >= remaining {
633 break
634 }
635 }
636 i.hashed += blockHashedCnt
637 if err := i.add(hash, blockHashedCnt); err != nil {
638 return err
639 }
640 remaining -= n
641 }
642
643 return nil
644 }
645
646 // score computes the similarity score between this index and another one.
647 // A region of a file is defined as a line in a text file or a fixed-size
648 // block in a binary file. To prepare an index, each region in the file is
649 // hashed; the values and counts of hashes are retained in a sorted table.
650 // Define the similarity fraction F as the count of matching regions between
651 // the two files divided between the maximum count of regions in either file.
652 // The similarity score is F multiplied by the maxScore constant, yielding a
653 // range [0, maxScore]. It is defined as maxScore for the degenerate case of
654 // two empty files.
655 // The similarity score is symmetrical; i.e. a.score(b) == b.score(a).
656 func (i *similarityIndex) score(other *similarityIndex, maxScore int) int {
657 var maxHashed = i.hashed
658 if maxHashed < other.hashed {
659 maxHashed = other.hashed
660 }
661 if maxHashed == 0 {
662 return maxScore
663 }
664
665 return int(i.common(other) * uint64(maxScore) / maxHashed)
666 }
667
668 func (i *similarityIndex) common(dst *similarityIndex) uint64 {
669 srcIdx, dstIdx := 0, 0
670 if i.numHashes == 0 || dst.numHashes == 0 {
671 return 0
672 }
673
674 var common uint64
675 srcKey, dstKey := i.hashes[srcIdx].key(), dst.hashes[dstIdx].key()
676
677 for {
678 if srcKey == dstKey {
679 srcCnt, dstCnt := i.hashes[srcIdx].count(), dst.hashes[dstIdx].count()
680 if srcCnt < dstCnt {
681 common += srcCnt
682 } else {
683 common += dstCnt
684 }
685
686 srcIdx++
687 if srcIdx == len(i.hashes) {
688 break
689 }
690 srcKey = i.hashes[srcIdx].key()
691
692 dstIdx++
693 if dstIdx == len(dst.hashes) {
694 break
695 }
696 dstKey = dst.hashes[dstIdx].key()
697 } else if srcKey < dstKey {
698 // Region of src that is not in dst
699 srcIdx++
700 if srcIdx == len(i.hashes) {
701 break
702 }
703 srcKey = i.hashes[srcIdx].key()
704 } else {
705 // Region of dst that is not in src
706 dstIdx++
707 if dstIdx == len(dst.hashes) {
708 break
709 }
710 dstKey = dst.hashes[dstIdx].key()
711 }
712 }
713
714 return common
715 }
716
717 func (i *similarityIndex) add(key int, cnt uint64) error {
718 key = int(uint32(key) * 0x9e370001 >> 1)
719
720 j := i.slot(key)
721 for {
722 v := i.hashes[j]
723 if v == 0 {
724 // It's an empty slot, so we can store it here.
725 if i.growAt <= i.numHashes {
726 if err := i.grow(); err != nil {
727 return err
728 }
729 j = i.slot(key)
730 continue
731 }
732
733 var err error
734 i.hashes[j], err = newKeyCountPair(key, cnt)
735 if err != nil {
736 return err
737 }
738 i.numHashes++
739 return nil
740 } else if v.key() == key {
741 // It's the same key, so increment the counter.
742 var err error
743 i.hashes[j], err = newKeyCountPair(key, v.count()+cnt)
744 return err
745 } else if j+1 >= len(i.hashes) {
746 j = 0
747 } else {
748 j++
749 }
750 }
751 }
752
753 type keyCountPair uint64
754
755 func newKeyCountPair(key int, cnt uint64) (keyCountPair, error) {
756 if cnt > maxCountValue {
757 return 0, errIndexFull
758 }
759
760 return keyCountPair((uint64(key) << keyShift) | cnt), nil
761 }
762
763 func (p keyCountPair) key() int {
764 return int(p >> keyShift)
765 }
766
767 func (p keyCountPair) count() uint64 {
768 return uint64(p) & maxCountValue
769 }
770
771 func (i *similarityIndex) slot(key int) int {
772 // We use 31 - hashBits because the upper bit was already forced
773 // to be 0 and we want the remaining high bits to be used as the
774 // table slot.
775 return int(uint32(key) >> uint(31-i.hashBits))
776 }
777
778 func shouldGrowAt(hashBits int) int {
779 return (1 << uint(hashBits)) * (hashBits - 3) / hashBits
780 }
781
782 func (i *similarityIndex) grow() error {
783 if i.hashBits == 30 {
784 return errIndexFull
785 }
786
787 old := i.hashes
788
789 i.hashBits++
790 i.growAt = shouldGrowAt(i.hashBits)
791
792 // TODO(erizocosmico): find a way to check if it will OOM and return
793 // errIndexFull instead.
794 i.hashes = make([]keyCountPair, 1<<uint(i.hashBits))
795
796 for _, v := range old {
797 if v != 0 {
798 j := i.slot(v.key())
799 for i.hashes[j] != 0 {
800 j++
801 if j >= len(i.hashes) {
802 j = 0
803 }
804 }
805 i.hashes[j] = v
806 }
807 }
808
809 return nil
810 }
811
812 type keyCountPairs []keyCountPair
813
814 func (p keyCountPairs) Len() int { return len(p) }
815 func (p keyCountPairs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
816 func (p keyCountPairs) Less(i, j int) bool { return p[i] < p[j] }