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 package org.eclipse.jgit.diff;
45
46 import static org.eclipse.jgit.diff.DiffEntry.Side.NEW;
47 import static org.eclipse.jgit.diff.DiffEntry.Side.OLD;
48
49 import java.io.IOException;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.Collection;
53 import java.util.Collections;
54 import java.util.Comparator;
55 import java.util.HashMap;
56 import java.util.List;
57
58 import org.eclipse.jgit.diff.DiffEntry.ChangeType;
59 import org.eclipse.jgit.diff.SimilarityIndex.TableFullException;
60 import org.eclipse.jgit.internal.JGitText;
61 import org.eclipse.jgit.lib.AbbreviatedObjectId;
62 import org.eclipse.jgit.lib.FileMode;
63 import org.eclipse.jgit.lib.NullProgressMonitor;
64 import org.eclipse.jgit.lib.ObjectReader;
65 import org.eclipse.jgit.lib.ProgressMonitor;
66 import org.eclipse.jgit.lib.Repository;
67
68
69 public class RenameDetector {
70 private static final int EXACT_RENAME_SCORE = 100;
71
72 private static final Comparator<DiffEntry> DIFF_COMPARATOR = new Comparator<DiffEntry>() {
73 @Override
74 public int compare(DiffEntry a, DiffEntry b) {
75 int cmp = nameOf(a).compareTo(nameOf(b));
76 if (cmp == 0)
77 cmp = sortOf(a.getChangeType()) - sortOf(b.getChangeType());
78 return cmp;
79 }
80
81 private String nameOf(DiffEntry ent) {
82
83
84
85
86 if (ent.changeType == ChangeType.DELETE)
87 return ent.oldPath;
88 return ent.newPath;
89 }
90
91 private int sortOf(ChangeType changeType) {
92
93
94
95
96 switch (changeType) {
97 case DELETE:
98 return 1;
99 case ADD:
100 return 2;
101 default:
102 return 10;
103 }
104 }
105 };
106
107 private List<DiffEntry> entries;
108
109 private List<DiffEntry> deleted;
110
111 private List<DiffEntry> added;
112
113 private boolean done;
114
115 private final ObjectReader objectReader;
116
117
118 private int renameScore = 60;
119
120
121
122
123
124
125 private int breakScore = -1;
126
127
128 private int renameLimit;
129
130
131 private boolean overRenameLimit;
132
133
134
135
136
137
138
139 public RenameDetector(Repository repo) {
140 this(repo.newObjectReader(), repo.getConfig().get(DiffConfig.KEY));
141 }
142
143
144
145
146
147
148
149
150
151
152 public RenameDetector(ObjectReader reader, DiffConfig cfg) {
153 objectReader = reader.newReader();
154 renameLimit = cfg.getRenameLimit();
155 reset();
156 }
157
158
159
160
161
162 public int getRenameScore() {
163 return renameScore;
164 }
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179 public void setRenameScore(int score) {
180 if (score < 0 || score > 100)
181 throw new IllegalArgumentException(
182 JGitText.get().similarityScoreMustBeWithinBounds);
183 renameScore = score;
184 }
185
186
187
188
189
190
191
192
193 public int getBreakScore() {
194 return breakScore;
195 }
196
197
198
199
200
201
202
203
204
205 public void setBreakScore(int breakScore) {
206 this.breakScore = breakScore;
207 }
208
209
210 public int getRenameLimit() {
211 return renameLimit;
212 }
213
214
215
216
217
218
219
220
221
222
223
224
225 public void setRenameLimit(int limit) {
226 renameLimit = limit;
227 }
228
229
230
231
232
233
234
235
236
237
238
239 public boolean isOverRenameLimit() {
240 if (done)
241 return overRenameLimit;
242 int cnt = Math.max(added.size(), deleted.size());
243 return getRenameLimit() != 0 && getRenameLimit() < cnt;
244 }
245
246
247
248
249
250
251
252
253
254 public void addAll(Collection<DiffEntry> entriesToAdd) {
255 if (done)
256 throw new IllegalStateException(JGitText.get().renamesAlreadyFound);
257
258 for (DiffEntry entry : entriesToAdd) {
259 switch (entry.getChangeType()) {
260 case ADD:
261 added.add(entry);
262 break;
263
264 case DELETE:
265 deleted.add(entry);
266 break;
267
268 case MODIFY:
269 if (sameType(entry.getOldMode(), entry.getNewMode())) {
270 entries.add(entry);
271 } else {
272 List<DiffEntry> tmp = DiffEntry.breakModify(entry);
273 deleted.add(tmp.get(0));
274 added.add(tmp.get(1));
275 }
276 break;
277
278 case COPY:
279 case RENAME:
280 default:
281 entries.add(entry);
282 }
283 }
284 }
285
286
287
288
289
290
291
292
293
294 public void add(DiffEntry entry) {
295 addAll(Collections.singletonList(entry));
296 }
297
298
299
300
301
302
303
304
305
306
307
308 public List<DiffEntry> compute() throws IOException {
309 return compute(NullProgressMonitor.INSTANCE);
310 }
311
312
313
314
315
316
317
318
319
320
321
322 public List<DiffEntry> compute(ProgressMonitor pm) throws IOException {
323 if (!done) {
324 try {
325 return compute(objectReader, pm);
326 } finally {
327 objectReader.close();
328 }
329 }
330 return Collections.unmodifiableList(entries);
331 }
332
333
334
335
336
337
338
339
340
341
342
343
344
345 public List<DiffEntry> compute(ObjectReader reader, ProgressMonitor pm)
346 throws IOException {
347 final ContentSource cs = ContentSource.create(reader);
348 return compute(new ContentSource.Pair(cs, cs), pm);
349 }
350
351
352
353
354
355
356
357
358
359
360
361
362
363 public List<DiffEntry> compute(ContentSource.Pair reader, ProgressMonitor pm)
364 throws IOException {
365 if (!done) {
366 done = true;
367
368 if (pm == null)
369 pm = NullProgressMonitor.INSTANCE;
370
371 if (0 < breakScore)
372 breakModifies(reader, pm);
373
374 if (!added.isEmpty() && !deleted.isEmpty())
375 findExactRenames(pm);
376
377 if (!added.isEmpty() && !deleted.isEmpty())
378 findContentRenames(reader, pm);
379
380 if (0 < breakScore && !added.isEmpty() && !deleted.isEmpty())
381 rejoinModifies(pm);
382
383 entries.addAll(added);
384 added = null;
385
386 entries.addAll(deleted);
387 deleted = null;
388
389 Collections.sort(entries, DIFF_COMPARATOR);
390 }
391 return Collections.unmodifiableList(entries);
392 }
393
394
395 public void reset() {
396 entries = new ArrayList<>();
397 deleted = new ArrayList<>();
398 added = new ArrayList<>();
399 done = false;
400 }
401
402 private void breakModifies(ContentSource.Pair reader, ProgressMonitor pm)
403 throws IOException {
404 ArrayList<DiffEntry> newEntries = new ArrayList<>(entries.size());
405
406 pm.beginTask(JGitText.get().renamesBreakingModifies, entries.size());
407
408 for (int i = 0; i < entries.size(); i++) {
409 DiffEntry e = entries.get(i);
410 if (e.getChangeType() == ChangeType.MODIFY) {
411 int score = calculateModifyScore(reader, e);
412 if (score < breakScore) {
413 List<DiffEntry> tmp = DiffEntry.breakModify(e);
414 DiffEntry del = tmp.get(0);
415 del.score = score;
416 deleted.add(del);
417 added.add(tmp.get(1));
418 } else {
419 newEntries.add(e);
420 }
421 } else {
422 newEntries.add(e);
423 }
424 pm.update(1);
425 }
426
427 entries = newEntries;
428 }
429
430 private void rejoinModifies(ProgressMonitor pm) {
431 HashMap<String, DiffEntry> nameMap = new HashMap<>();
432 ArrayList<DiffEntry> newAdded = new ArrayList<>(added.size());
433
434 pm.beginTask(JGitText.get().renamesRejoiningModifies, added.size()
435 + deleted.size());
436
437 for (DiffEntry src : deleted) {
438 nameMap.put(src.oldPath, src);
439 pm.update(1);
440 }
441
442 for (DiffEntry dst : added) {
443 DiffEntry src = nameMap.remove(dst.newPath);
444 if (src != null) {
445 if (sameType(src.oldMode, dst.newMode)) {
446 entries.add(DiffEntry.pair(ChangeType.MODIFY, src, dst,
447 src.score));
448 } else {
449 nameMap.put(src.oldPath, src);
450 newAdded.add(dst);
451 }
452 } else {
453 newAdded.add(dst);
454 }
455 pm.update(1);
456 }
457
458 added = newAdded;
459 deleted = new ArrayList<>(nameMap.values());
460 }
461
462 private int calculateModifyScore(ContentSource.Pair reader, DiffEntry d)
463 throws IOException {
464 try {
465 SimilarityIndex src = new SimilarityIndex();
466 src.hash(reader.open(OLD, d));
467 src.sort();
468
469 SimilarityIndex dst = new SimilarityIndex();
470 dst.hash(reader.open(NEW, d));
471 dst.sort();
472 return src.score(dst, 100);
473 } catch (TableFullException tableFull) {
474
475
476
477
478 overRenameLimit = true;
479 return breakScore + 1;
480 }
481 }
482
483 private void findContentRenames(ContentSource.Pair reader,
484 ProgressMonitor pm)
485 throws IOException {
486 int cnt = Math.max(added.size(), deleted.size());
487 if (getRenameLimit() == 0 || cnt <= getRenameLimit()) {
488 SimilarityRenameDetector d;
489
490 d = new SimilarityRenameDetector(reader, deleted, added);
491 d.setRenameScore(getRenameScore());
492 d.compute(pm);
493 overRenameLimit |= d.isTableOverflow();
494 deleted = d.getLeftOverSources();
495 added = d.getLeftOverDestinations();
496 entries.addAll(d.getMatches());
497 } else {
498 overRenameLimit = true;
499 }
500 }
501
502 @SuppressWarnings("unchecked")
503 private void findExactRenames(ProgressMonitor pm) {
504 pm.beginTask(JGitText.get().renamesFindingExact,
505 added.size() + added.size() + deleted.size()
506 + added.size() * deleted.size());
507
508 HashMap<AbbreviatedObjectId, Object> deletedMap = populateMap(deleted, pm);
509 HashMap<AbbreviatedObjectId, Object> addedMap = populateMap(added, pm);
510
511 ArrayList<DiffEntry> uniqueAdds = new ArrayList<>(added.size());
512 ArrayList<List<DiffEntry>> nonUniqueAdds = new ArrayList<>();
513
514 for (Object o : addedMap.values()) {
515 if (o instanceof DiffEntry)
516 uniqueAdds.add((DiffEntry) o);
517 else
518 nonUniqueAdds.add((List<DiffEntry>) o);
519 }
520
521 ArrayList<DiffEntry> left = new ArrayList<>(added.size());
522
523 for (DiffEntry a : uniqueAdds) {
524 Object del = deletedMap.get(a.newId);
525 if (del instanceof DiffEntry) {
526
527
528 DiffEntry e = (DiffEntry) del;
529 if (sameType(e.oldMode, a.newMode)) {
530 e.changeType = ChangeType.RENAME;
531 entries.add(exactRename(e, a));
532 } else {
533 left.add(a);
534 }
535 } else if (del != null) {
536
537
538 List<DiffEntry> list = (List<DiffEntry>) del;
539 DiffEntry best = bestPathMatch(a, list);
540 if (best != null) {
541 best.changeType = ChangeType.RENAME;
542 entries.add(exactRename(best, a));
543 } else {
544 left.add(a);
545 }
546 } else {
547 left.add(a);
548 }
549 pm.update(1);
550 }
551
552 for (List<DiffEntry> adds : nonUniqueAdds) {
553 Object o = deletedMap.get(adds.get(0).newId);
554 if (o instanceof DiffEntry) {
555
556
557
558 DiffEntry d = (DiffEntry) o;
559 DiffEntry best = bestPathMatch(d, adds);
560 if (best != null) {
561 d.changeType = ChangeType.RENAME;
562 entries.add(exactRename(d, best));
563 for (DiffEntry a : adds) {
564 if (a != best) {
565 if (sameType(d.oldMode, a.newMode)) {
566 entries.add(exactCopy(d, a));
567 } else {
568 left.add(a);
569 }
570 }
571 }
572 } else {
573 left.addAll(adds);
574 }
575 } else if (o != null) {
576
577
578
579 List<DiffEntry> dels = (List<DiffEntry>) o;
580 long[] matrix = new long[dels.size() * adds.size()];
581 int mNext = 0;
582 for (int delIdx = 0; delIdx < dels.size(); delIdx++) {
583 String deletedName = dels.get(delIdx).oldPath;
584
585 for (int addIdx = 0; addIdx < adds.size(); addIdx++) {
586 String addedName = adds.get(addIdx).newPath;
587
588 int score = SimilarityRenameDetector.nameScore(addedName, deletedName);
589 matrix[mNext] = SimilarityRenameDetector.encode(score, delIdx, addIdx);
590 mNext++;
591 }
592 }
593
594 Arrays.sort(matrix);
595
596 for (--mNext; mNext >= 0; mNext--) {
597 long ent = matrix[mNext];
598 int delIdx = SimilarityRenameDetector.srcFile(ent);
599 int addIdx = SimilarityRenameDetector.dstFile(ent);
600 DiffEntry d = dels.get(delIdx);
601 DiffEntry a = adds.get(addIdx);
602
603 if (a == null) {
604 pm.update(1);
605 continue;
606 }
607
608 ChangeType type;
609 if (d.changeType == ChangeType.DELETE) {
610
611
612
613
614 d.changeType = ChangeType.RENAME;
615 type = ChangeType.RENAME;
616 } else {
617 type = ChangeType.COPY;
618 }
619
620 entries.add(DiffEntry.pair(type, d, a, 100));
621 adds.set(addIdx, null);
622 pm.update(1);
623 }
624 } else {
625 left.addAll(adds);
626 }
627 }
628 added = left;
629
630 deleted = new ArrayList<>(deletedMap.size());
631 for (Object o : deletedMap.values()) {
632 if (o instanceof DiffEntry) {
633 DiffEntry e = (DiffEntry) o;
634 if (e.changeType == ChangeType.DELETE)
635 deleted.add(e);
636 } else {
637 List<DiffEntry> list = (List<DiffEntry>) o;
638 for (DiffEntry e : list) {
639 if (e.changeType == ChangeType.DELETE)
640 deleted.add(e);
641 }
642 }
643 }
644 pm.endTask();
645 }
646
647
648
649
650
651
652
653
654
655
656
657
658
659 private static DiffEntry bestPathMatch(DiffEntry src, List<DiffEntry> list) {
660 DiffEntry best = null;
661 int score = -1;
662
663 for (DiffEntry d : list) {
664 if (sameType(mode(d), mode(src))) {
665 int tmp = SimilarityRenameDetector
666 .nameScore(path(d), path(src));
667 if (tmp > score) {
668 best = d;
669 score = tmp;
670 }
671 }
672 }
673
674 return best;
675 }
676
677 @SuppressWarnings("unchecked")
678 private HashMap<AbbreviatedObjectId, Object> populateMap(
679 List<DiffEntry> diffEntries, ProgressMonitor pm) {
680 HashMap<AbbreviatedObjectId, Object> map = new HashMap<>();
681 for (DiffEntry de : diffEntries) {
682 Object old = map.put(id(de), de);
683 if (old instanceof DiffEntry) {
684 ArrayList<DiffEntry> list = new ArrayList<>(2);
685 list.add((DiffEntry) old);
686 list.add(de);
687 map.put(id(de), list);
688 } else if (old != null) {
689
690 ((List<DiffEntry>) old).add(de);
691 map.put(id(de), old);
692 }
693 pm.update(1);
694 }
695 return map;
696 }
697
698 private static String path(DiffEntry de) {
699 return de.changeType == ChangeType.DELETE ? de.oldPath : de.newPath;
700 }
701
702 private static FileMode mode(DiffEntry de) {
703 return de.changeType == ChangeType.DELETE ? de.oldMode : de.newMode;
704 }
705
706 private static AbbreviatedObjectId id(DiffEntry de) {
707 return de.changeType == ChangeType.DELETE ? de.oldId : de.newId;
708 }
709
710 static boolean sameType(FileMode a, FileMode b) {
711
712
713
714
715 int aType = a.getBits() & FileMode.TYPE_MASK;
716 int bType = b.getBits() & FileMode.TYPE_MASK;
717 return aType == bType;
718 }
719
720 private static DiffEntry exactRename(DiffEntry src, DiffEntry dst) {
721 return DiffEntry.pair(ChangeType.RENAME, src, dst, EXACT_RENAME_SCORE);
722 }
723
724 private static DiffEntry exactCopy(DiffEntry src, DiffEntry dst) {
725 return DiffEntry.pair(ChangeType.COPY, src, dst, EXACT_RENAME_SCORE);
726 }
727 }