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

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