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 11KB

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