You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimilarityRenameDetector.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.diff;
  44. import static org.eclipse.jgit.diff.DiffEntry.Side.NEW;
  45. import static org.eclipse.jgit.diff.DiffEntry.Side.OLD;
  46. import java.io.IOException;
  47. import java.util.ArrayList;
  48. import java.util.Arrays;
  49. import java.util.BitSet;
  50. import java.util.List;
  51. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  52. import org.eclipse.jgit.diff.SimilarityIndex.TableFullException;
  53. import org.eclipse.jgit.internal.JGitText;
  54. import org.eclipse.jgit.lib.FileMode;
  55. import org.eclipse.jgit.lib.NullProgressMonitor;
  56. import org.eclipse.jgit.lib.ProgressMonitor;
  57. class SimilarityRenameDetector {
  58. /**
  59. * Number of bits we need to express an index into src or dst list.
  60. * <p>
  61. * This must be 28, giving us a limit of 2^28 entries in either list, which
  62. * is an insane limit of 536,870,912 file names being considered in a single
  63. * rename pass. The other 8 bits are used to store the score, while staying
  64. * under 127 so the long doesn't go negative.
  65. */
  66. private static final int BITS_PER_INDEX = 28;
  67. private static final int INDEX_MASK = (1 << BITS_PER_INDEX) - 1;
  68. private static final int SCORE_SHIFT = 2 * BITS_PER_INDEX;
  69. private ContentSource.Pair reader;
  70. /**
  71. * All sources to consider for copies or renames.
  72. * <p>
  73. * A source is typically a {@link ChangeType#DELETE} change, but could be
  74. * another type when trying to perform copy detection concurrently with
  75. * rename detection.
  76. */
  77. private List<DiffEntry> srcs;
  78. /**
  79. * All destinations to consider looking for a rename.
  80. * <p>
  81. * A destination is typically an {@link ChangeType#ADD}, as the name has
  82. * just come into existence, and we want to discover where its initial
  83. * content came from.
  84. */
  85. private List<DiffEntry> dsts;
  86. /**
  87. * Matrix of all examined file pairs, and their scores.
  88. * <p>
  89. * The upper 8 bits of each long stores the score, but the score is bounded
  90. * to be in the range (0, 128] so that the highest bit is never set, and all
  91. * entries are therefore positive.
  92. * <p>
  93. * List indexes to an element of {@link #srcs} and {@link #dsts} are encoded
  94. * as the lower two groups of 28 bits, respectively, but the encoding is
  95. * inverted, so that 0 is expressed as {@code (1 << 28) - 1}. This sorts
  96. * lower list indices later in the matrix, giving precedence to files whose
  97. * names sort earlier in the tree.
  98. */
  99. private long[] matrix;
  100. /** Score a pair must exceed to be considered a rename. */
  101. private int renameScore = 60;
  102. /** Set if any {@link SimilarityIndex.TableFullException} occurs. */
  103. private boolean tableOverflow;
  104. private List<DiffEntry> out;
  105. SimilarityRenameDetector(ContentSource.Pair reader, List<DiffEntry> srcs,
  106. List<DiffEntry> dsts) {
  107. this.reader = reader;
  108. this.srcs = srcs;
  109. this.dsts = dsts;
  110. }
  111. void setRenameScore(int score) {
  112. renameScore = score;
  113. }
  114. void compute(ProgressMonitor pm) throws IOException {
  115. if (pm == null)
  116. pm = NullProgressMonitor.INSTANCE;
  117. pm.beginTask(JGitText.get().renamesFindingByContent, //
  118. 2 * srcs.size() * dsts.size());
  119. int mNext = buildMatrix(pm);
  120. out = new ArrayList<DiffEntry>(Math.min(mNext, dsts.size()));
  121. // Match rename pairs on a first come, first serve basis until
  122. // we have looked at everything that is above our minimum score.
  123. //
  124. for (--mNext; mNext >= 0; mNext--) {
  125. long ent = matrix[mNext];
  126. int sIdx = srcFile(ent);
  127. int dIdx = dstFile(ent);
  128. DiffEntry s = srcs.get(sIdx);
  129. DiffEntry d = dsts.get(dIdx);
  130. if (d == null) {
  131. pm.update(1);
  132. continue; // was already matched earlier
  133. }
  134. ChangeType type;
  135. if (s.changeType == ChangeType.DELETE) {
  136. // First use of this source file. Tag it as a rename so we
  137. // later know it is already been used as a rename, other
  138. // matches (if any) will claim themselves as copies instead.
  139. //
  140. s.changeType = ChangeType.RENAME;
  141. type = ChangeType.RENAME;
  142. } else {
  143. type = ChangeType.COPY;
  144. }
  145. out.add(DiffEntry.pair(type, s, d, score(ent)));
  146. dsts.set(dIdx, null); // Claim the destination was matched.
  147. pm.update(1);
  148. }
  149. srcs = compactSrcList(srcs);
  150. dsts = compactDstList(dsts);
  151. pm.endTask();
  152. }
  153. List<DiffEntry> getMatches() {
  154. return out;
  155. }
  156. List<DiffEntry> getLeftOverSources() {
  157. return srcs;
  158. }
  159. List<DiffEntry> getLeftOverDestinations() {
  160. return dsts;
  161. }
  162. boolean isTableOverflow() {
  163. return tableOverflow;
  164. }
  165. private static List<DiffEntry> compactSrcList(List<DiffEntry> in) {
  166. ArrayList<DiffEntry> r = new ArrayList<DiffEntry>(in.size());
  167. for (DiffEntry e : in) {
  168. if (e.changeType == ChangeType.DELETE)
  169. r.add(e);
  170. }
  171. return r;
  172. }
  173. private static List<DiffEntry> compactDstList(List<DiffEntry> in) {
  174. ArrayList<DiffEntry> r = new ArrayList<DiffEntry>(in.size());
  175. for (DiffEntry e : in) {
  176. if (e != null)
  177. r.add(e);
  178. }
  179. return r;
  180. }
  181. private int buildMatrix(ProgressMonitor pm) throws IOException {
  182. // Allocate for the worst-case scenario where every pair has a
  183. // score that we need to consider. We might not need that many.
  184. //
  185. matrix = new long[srcs.size() * dsts.size()];
  186. long[] srcSizes = new long[srcs.size()];
  187. long[] dstSizes = new long[dsts.size()];
  188. BitSet dstTooLarge = null;
  189. // Consider each pair of files, if the score is above the minimum
  190. // threshold we need record that scoring in the matrix so we can
  191. // later find the best matches.
  192. //
  193. int mNext = 0;
  194. SRC: for (int srcIdx = 0; srcIdx < srcs.size(); srcIdx++) {
  195. DiffEntry srcEnt = srcs.get(srcIdx);
  196. if (!isFile(srcEnt.oldMode)) {
  197. pm.update(dsts.size());
  198. continue;
  199. }
  200. SimilarityIndex s = null;
  201. for (int dstIdx = 0; dstIdx < dsts.size(); dstIdx++) {
  202. DiffEntry dstEnt = dsts.get(dstIdx);
  203. if (!isFile(dstEnt.newMode)) {
  204. pm.update(1);
  205. continue;
  206. }
  207. if (!RenameDetector.sameType(srcEnt.oldMode, dstEnt.newMode)) {
  208. pm.update(1);
  209. continue;
  210. }
  211. if (dstTooLarge != null && dstTooLarge.get(dstIdx)) {
  212. pm.update(1);
  213. continue;
  214. }
  215. long srcSize = srcSizes[srcIdx];
  216. if (srcSize == 0) {
  217. srcSize = size(OLD, srcEnt) + 1;
  218. srcSizes[srcIdx] = srcSize;
  219. }
  220. long dstSize = dstSizes[dstIdx];
  221. if (dstSize == 0) {
  222. dstSize = size(NEW, dstEnt) + 1;
  223. dstSizes[dstIdx] = dstSize;
  224. }
  225. long max = Math.max(srcSize, dstSize);
  226. long min = Math.min(srcSize, dstSize);
  227. if (min * 100 / max < renameScore) {
  228. // Cannot possibly match, as the file sizes are so different
  229. pm.update(1);
  230. continue;
  231. }
  232. if (s == null) {
  233. try {
  234. s = hash(OLD, srcEnt);
  235. } catch (TableFullException tableFull) {
  236. tableOverflow = true;
  237. continue SRC;
  238. }
  239. }
  240. SimilarityIndex d;
  241. try {
  242. d = hash(NEW, dstEnt);
  243. } catch (TableFullException tableFull) {
  244. if (dstTooLarge == null)
  245. dstTooLarge = new BitSet(dsts.size());
  246. dstTooLarge.set(dstIdx);
  247. tableOverflow = true;
  248. pm.update(1);
  249. continue;
  250. }
  251. int contentScore = s.score(d, 10000);
  252. // nameScore returns a value between 0 and 100, but we want it
  253. // to be in the same range as the content score. This allows it
  254. // to be dropped into the pretty formula for the final score.
  255. int nameScore = nameScore(srcEnt.oldPath, dstEnt.newPath) * 100;
  256. int score = (contentScore * 99 + nameScore * 1) / 10000;
  257. if (score < renameScore) {
  258. pm.update(1);
  259. continue;
  260. }
  261. matrix[mNext++] = encode(score, srcIdx, dstIdx);
  262. pm.update(1);
  263. }
  264. }
  265. // Sort everything in the range we populated, which might be the
  266. // entire matrix, or just a smaller slice if we had some bad low
  267. // scoring pairs.
  268. //
  269. Arrays.sort(matrix, 0, mNext);
  270. return mNext;
  271. }
  272. static int nameScore(String a, String b) {
  273. int aDirLen = a.lastIndexOf("/") + 1; //$NON-NLS-1$
  274. int bDirLen = b.lastIndexOf("/") + 1; //$NON-NLS-1$
  275. int dirMin = Math.min(aDirLen, bDirLen);
  276. int dirMax = Math.max(aDirLen, bDirLen);
  277. final int dirScoreLtr;
  278. final int dirScoreRtl;
  279. if (dirMax == 0) {
  280. dirScoreLtr = 100;
  281. dirScoreRtl = 100;
  282. } else {
  283. int dirSim = 0;
  284. for (; dirSim < dirMin; dirSim++) {
  285. if (a.charAt(dirSim) != b.charAt(dirSim))
  286. break;
  287. }
  288. dirScoreLtr = (dirSim * 100) / dirMax;
  289. if (dirScoreLtr == 100) {
  290. dirScoreRtl = 100;
  291. } else {
  292. for (dirSim = 0; dirSim < dirMin; dirSim++) {
  293. if (a.charAt(aDirLen - 1 - dirSim) != b.charAt(bDirLen - 1
  294. - dirSim))
  295. break;
  296. }
  297. dirScoreRtl = (dirSim * 100) / dirMax;
  298. }
  299. }
  300. int fileMin = Math.min(a.length() - aDirLen, b.length() - bDirLen);
  301. int fileMax = Math.max(a.length() - aDirLen, b.length() - bDirLen);
  302. int fileSim = 0;
  303. for (; fileSim < fileMin; fileSim++) {
  304. if (a.charAt(a.length() - 1 - fileSim) != b.charAt(b.length() - 1
  305. - fileSim))
  306. break;
  307. }
  308. int fileScore = (fileSim * 100) / fileMax;
  309. return (((dirScoreLtr + dirScoreRtl) * 25) + (fileScore * 50)) / 100;
  310. }
  311. private SimilarityIndex hash(DiffEntry.Side side, DiffEntry ent)
  312. throws IOException, TableFullException {
  313. SimilarityIndex r = new SimilarityIndex();
  314. r.hash(reader.open(side, ent));
  315. r.sort();
  316. return r;
  317. }
  318. private long size(DiffEntry.Side side, DiffEntry ent) throws IOException {
  319. return reader.size(side, ent);
  320. }
  321. private static int score(long value) {
  322. return (int) (value >>> SCORE_SHIFT);
  323. }
  324. static int srcFile(long value) {
  325. return decodeFile(((int) (value >>> BITS_PER_INDEX)) & INDEX_MASK);
  326. }
  327. static int dstFile(long value) {
  328. return decodeFile(((int) value) & INDEX_MASK);
  329. }
  330. static long encode(int score, int srcIdx, int dstIdx) {
  331. return (((long) score) << SCORE_SHIFT) //
  332. | (encodeFile(srcIdx) << BITS_PER_INDEX) //
  333. | encodeFile(dstIdx);
  334. }
  335. private static long encodeFile(int idx) {
  336. // We invert the index so that the first file in the list sorts
  337. // later in the table. This permits us to break ties favoring
  338. // earlier names over later ones.
  339. //
  340. return INDEX_MASK - idx;
  341. }
  342. private static int decodeFile(int v) {
  343. return INDEX_MASK - v;
  344. }
  345. private static boolean isFile(FileMode mode) {
  346. return (mode.getBits() & FileMode.TYPE_MASK) == FileMode.TYPE_FILE;
  347. }
  348. }