Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

SimilarityRenameDetector.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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.errors.CancelledException;
  54. import org.eclipse.jgit.internal.JGitText;
  55. import org.eclipse.jgit.lib.FileMode;
  56. import org.eclipse.jgit.lib.NullProgressMonitor;
  57. import org.eclipse.jgit.lib.ProgressMonitor;
  58. class SimilarityRenameDetector {
  59. /**
  60. * Number of bits we need to express an index into src or dst list.
  61. * <p>
  62. * This must be 28, giving us a limit of 2^28 entries in either list, which
  63. * is an insane limit of 536,870,912 file names being considered in a single
  64. * rename pass. The other 8 bits are used to store the score, while staying
  65. * under 127 so the long doesn't go negative.
  66. */
  67. private static final int BITS_PER_INDEX = 28;
  68. private static final int INDEX_MASK = (1 << BITS_PER_INDEX) - 1;
  69. private static final int SCORE_SHIFT = 2 * BITS_PER_INDEX;
  70. private ContentSource.Pair reader;
  71. /**
  72. * All sources to consider for copies or renames.
  73. * <p>
  74. * A source is typically a {@link ChangeType#DELETE} change, but could be
  75. * another type when trying to perform copy detection concurrently with
  76. * rename detection.
  77. */
  78. private List<DiffEntry> srcs;
  79. /**
  80. * All destinations to consider looking for a rename.
  81. * <p>
  82. * A destination is typically an {@link ChangeType#ADD}, as the name has
  83. * just come into existence, and we want to discover where its initial
  84. * content came from.
  85. */
  86. private List<DiffEntry> dsts;
  87. /**
  88. * Matrix of all examined file pairs, and their scores.
  89. * <p>
  90. * The upper 8 bits of each long stores the score, but the score is bounded
  91. * to be in the range (0, 128] so that the highest bit is never set, and all
  92. * entries are therefore positive.
  93. * <p>
  94. * List indexes to an element of {@link #srcs} and {@link #dsts} are encoded
  95. * as the lower two groups of 28 bits, respectively, but the encoding is
  96. * inverted, so that 0 is expressed as {@code (1 << 28) - 1}. This sorts
  97. * lower list indices later in the matrix, giving precedence to files whose
  98. * names sort earlier in the tree.
  99. */
  100. private long[] matrix;
  101. /** Score a pair must exceed to be considered a rename. */
  102. private int renameScore = 60;
  103. /** Set if any {@link SimilarityIndex.TableFullException} occurs. */
  104. private boolean tableOverflow;
  105. private List<DiffEntry> out;
  106. SimilarityRenameDetector(ContentSource.Pair reader, List<DiffEntry> srcs,
  107. List<DiffEntry> dsts) {
  108. this.reader = reader;
  109. this.srcs = srcs;
  110. this.dsts = dsts;
  111. }
  112. void setRenameScore(int score) {
  113. renameScore = score;
  114. }
  115. void compute(ProgressMonitor pm) throws IOException, CancelledException {
  116. if (pm == null)
  117. pm = NullProgressMonitor.INSTANCE;
  118. pm.beginTask(JGitText.get().renamesFindingByContent, //
  119. 2 * srcs.size() * dsts.size());
  120. int mNext = buildMatrix(pm);
  121. out = new ArrayList<>(Math.min(mNext, dsts.size()));
  122. // Match rename pairs on a first come, first serve basis until
  123. // we have looked at everything that is above our minimum score.
  124. //
  125. for (--mNext; mNext >= 0; mNext--) {
  126. if (pm.isCancelled()) {
  127. // TODO(ms): use org.eclipse.jgit.api.errors.CanceledException
  128. // in next major version
  129. throw new CancelledException(JGitText.get().renameCancelled);
  130. }
  131. long ent = matrix[mNext];
  132. int sIdx = srcFile(ent);
  133. int dIdx = dstFile(ent);
  134. DiffEntry s = srcs.get(sIdx);
  135. DiffEntry d = dsts.get(dIdx);
  136. if (d == null) {
  137. pm.update(1);
  138. continue; // was already matched earlier
  139. }
  140. ChangeType type;
  141. if (s.changeType == ChangeType.DELETE) {
  142. // First use of this source file. Tag it as a rename so we
  143. // later know it is already been used as a rename, other
  144. // matches (if any) will claim themselves as copies instead.
  145. //
  146. s.changeType = ChangeType.RENAME;
  147. type = ChangeType.RENAME;
  148. } else {
  149. type = ChangeType.COPY;
  150. }
  151. out.add(DiffEntry.pair(type, s, d, score(ent)));
  152. dsts.set(dIdx, null); // Claim the destination was matched.
  153. pm.update(1);
  154. }
  155. srcs = compactSrcList(srcs);
  156. dsts = compactDstList(dsts);
  157. pm.endTask();
  158. }
  159. List<DiffEntry> getMatches() {
  160. return out;
  161. }
  162. List<DiffEntry> getLeftOverSources() {
  163. return srcs;
  164. }
  165. List<DiffEntry> getLeftOverDestinations() {
  166. return dsts;
  167. }
  168. boolean isTableOverflow() {
  169. return tableOverflow;
  170. }
  171. private static List<DiffEntry> compactSrcList(List<DiffEntry> in) {
  172. ArrayList<DiffEntry> r = new ArrayList<>(in.size());
  173. for (DiffEntry e : in) {
  174. if (e.changeType == ChangeType.DELETE)
  175. r.add(e);
  176. }
  177. return r;
  178. }
  179. private static List<DiffEntry> compactDstList(List<DiffEntry> in) {
  180. ArrayList<DiffEntry> r = new ArrayList<>(in.size());
  181. for (DiffEntry e : in) {
  182. if (e != null)
  183. r.add(e);
  184. }
  185. return r;
  186. }
  187. private int buildMatrix(ProgressMonitor pm)
  188. throws IOException, CancelledException {
  189. // Allocate for the worst-case scenario where every pair has a
  190. // score that we need to consider. We might not need that many.
  191. //
  192. matrix = new long[srcs.size() * dsts.size()];
  193. long[] srcSizes = new long[srcs.size()];
  194. long[] dstSizes = new long[dsts.size()];
  195. BitSet dstTooLarge = null;
  196. // Consider each pair of files, if the score is above the minimum
  197. // threshold we need record that scoring in the matrix so we can
  198. // later find the best matches.
  199. //
  200. int mNext = 0;
  201. SRC: for (int srcIdx = 0; srcIdx < srcs.size(); srcIdx++) {
  202. DiffEntry srcEnt = srcs.get(srcIdx);
  203. if (!isFile(srcEnt.oldMode)) {
  204. pm.update(dsts.size());
  205. continue;
  206. }
  207. SimilarityIndex s = null;
  208. for (int dstIdx = 0; dstIdx < dsts.size(); dstIdx++) {
  209. if (pm.isCancelled()) {
  210. // TODO(ms): use
  211. // org.eclipse.jgit.api.errors.CanceledException in next
  212. // major version
  213. throw new CancelledException(
  214. JGitText.get().renameCancelled);
  215. }
  216. DiffEntry dstEnt = dsts.get(dstIdx);
  217. if (!isFile(dstEnt.newMode)) {
  218. pm.update(1);
  219. continue;
  220. }
  221. if (!RenameDetector.sameType(srcEnt.oldMode, dstEnt.newMode)) {
  222. pm.update(1);
  223. continue;
  224. }
  225. if (dstTooLarge != null && dstTooLarge.get(dstIdx)) {
  226. pm.update(1);
  227. continue;
  228. }
  229. long srcSize = srcSizes[srcIdx];
  230. if (srcSize == 0) {
  231. srcSize = size(OLD, srcEnt) + 1;
  232. srcSizes[srcIdx] = srcSize;
  233. }
  234. long dstSize = dstSizes[dstIdx];
  235. if (dstSize == 0) {
  236. dstSize = size(NEW, dstEnt) + 1;
  237. dstSizes[dstIdx] = dstSize;
  238. }
  239. long max = Math.max(srcSize, dstSize);
  240. long min = Math.min(srcSize, dstSize);
  241. if (min * 100 / max < renameScore) {
  242. // Cannot possibly match, as the file sizes are so different
  243. pm.update(1);
  244. continue;
  245. }
  246. if (s == null) {
  247. try {
  248. s = hash(OLD, srcEnt);
  249. } catch (TableFullException tableFull) {
  250. tableOverflow = true;
  251. continue SRC;
  252. }
  253. }
  254. SimilarityIndex d;
  255. try {
  256. d = hash(NEW, dstEnt);
  257. } catch (TableFullException tableFull) {
  258. if (dstTooLarge == null)
  259. dstTooLarge = new BitSet(dsts.size());
  260. dstTooLarge.set(dstIdx);
  261. tableOverflow = true;
  262. pm.update(1);
  263. continue;
  264. }
  265. int contentScore = s.score(d, 10000);
  266. // nameScore returns a value between 0 and 100, but we want it
  267. // to be in the same range as the content score. This allows it
  268. // to be dropped into the pretty formula for the final score.
  269. int nameScore = nameScore(srcEnt.oldPath, dstEnt.newPath) * 100;
  270. int score = (contentScore * 99 + nameScore * 1) / 10000;
  271. if (score < renameScore) {
  272. pm.update(1);
  273. continue;
  274. }
  275. matrix[mNext++] = encode(score, srcIdx, dstIdx);
  276. pm.update(1);
  277. }
  278. }
  279. // Sort everything in the range we populated, which might be the
  280. // entire matrix, or just a smaller slice if we had some bad low
  281. // scoring pairs.
  282. //
  283. Arrays.sort(matrix, 0, mNext);
  284. return mNext;
  285. }
  286. static int nameScore(String a, String b) {
  287. int aDirLen = a.lastIndexOf('/') + 1;
  288. int bDirLen = b.lastIndexOf('/') + 1;
  289. int dirMin = Math.min(aDirLen, bDirLen);
  290. int dirMax = Math.max(aDirLen, bDirLen);
  291. final int dirScoreLtr;
  292. final int dirScoreRtl;
  293. if (dirMax == 0) {
  294. dirScoreLtr = 100;
  295. dirScoreRtl = 100;
  296. } else {
  297. int dirSim = 0;
  298. for (; dirSim < dirMin; dirSim++) {
  299. if (a.charAt(dirSim) != b.charAt(dirSim))
  300. break;
  301. }
  302. dirScoreLtr = (dirSim * 100) / dirMax;
  303. if (dirScoreLtr == 100) {
  304. dirScoreRtl = 100;
  305. } else {
  306. for (dirSim = 0; dirSim < dirMin; dirSim++) {
  307. if (a.charAt(aDirLen - 1 - dirSim) != b.charAt(bDirLen - 1
  308. - dirSim))
  309. break;
  310. }
  311. dirScoreRtl = (dirSim * 100) / dirMax;
  312. }
  313. }
  314. int fileMin = Math.min(a.length() - aDirLen, b.length() - bDirLen);
  315. int fileMax = Math.max(a.length() - aDirLen, b.length() - bDirLen);
  316. int fileSim = 0;
  317. for (; fileSim < fileMin; fileSim++) {
  318. if (a.charAt(a.length() - 1 - fileSim) != b.charAt(b.length() - 1
  319. - fileSim))
  320. break;
  321. }
  322. int fileScore = (fileSim * 100) / fileMax;
  323. return (((dirScoreLtr + dirScoreRtl) * 25) + (fileScore * 50)) / 100;
  324. }
  325. private SimilarityIndex hash(DiffEntry.Side side, DiffEntry ent)
  326. throws IOException, TableFullException {
  327. SimilarityIndex r = new SimilarityIndex();
  328. r.hash(reader.open(side, ent));
  329. r.sort();
  330. return r;
  331. }
  332. private long size(DiffEntry.Side side, DiffEntry ent) throws IOException {
  333. return reader.size(side, ent);
  334. }
  335. private static int score(long value) {
  336. return (int) (value >>> SCORE_SHIFT);
  337. }
  338. static int srcFile(long value) {
  339. return decodeFile(((int) (value >>> BITS_PER_INDEX)) & INDEX_MASK);
  340. }
  341. static int dstFile(long value) {
  342. return decodeFile(((int) value) & INDEX_MASK);
  343. }
  344. static long encode(int score, int srcIdx, int dstIdx) {
  345. return (((long) score) << SCORE_SHIFT) //
  346. | (encodeFile(srcIdx) << BITS_PER_INDEX) //
  347. | encodeFile(dstIdx);
  348. }
  349. private static long encodeFile(int idx) {
  350. // We invert the index so that the first file in the list sorts
  351. // later in the table. This permits us to break ties favoring
  352. // earlier names over later ones.
  353. //
  354. return INDEX_MASK - idx;
  355. }
  356. private static int decodeFile(int v) {
  357. return INDEX_MASK - v;
  358. }
  359. private static boolean isFile(FileMode mode) {
  360. return (mode.getBits() & FileMode.TYPE_MASK) == FileMode.TYPE_FILE;
  361. }
  362. }