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.

IndexDiff.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com>
  5. * Copyright (C) 2013, Robin Stocker <robin@nibor.org>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.lib;
  47. import java.io.IOException;
  48. import java.util.ArrayList;
  49. import java.util.Collection;
  50. import java.util.Collections;
  51. import java.util.HashMap;
  52. import java.util.HashSet;
  53. import java.util.Map;
  54. import java.util.Set;
  55. import org.eclipse.jgit.dircache.DirCache;
  56. import org.eclipse.jgit.dircache.DirCacheEntry;
  57. import org.eclipse.jgit.dircache.DirCacheIterator;
  58. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  59. import org.eclipse.jgit.errors.MissingObjectException;
  60. import org.eclipse.jgit.errors.StopWalkException;
  61. import org.eclipse.jgit.revwalk.RevTree;
  62. import org.eclipse.jgit.revwalk.RevWalk;
  63. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  64. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  65. import org.eclipse.jgit.treewalk.TreeWalk;
  66. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  67. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  68. import org.eclipse.jgit.treewalk.filter.IndexDiffFilter;
  69. import org.eclipse.jgit.treewalk.filter.SkipWorkTreeFilter;
  70. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  71. /**
  72. * Compares the index, a tree, and the working directory Ignored files are not
  73. * taken into account. The following information is retrieved:
  74. * <ul>
  75. * <li>added files</li>
  76. * <li>changed files</li>
  77. * <li>removed files</li>
  78. * <li>missing files</li>
  79. * <li>modified files</li>
  80. * <li>conflicting files</li>
  81. * <li>untracked files</li>
  82. * <li>files with assume-unchanged flag</li>
  83. * </ul>
  84. */
  85. public class IndexDiff {
  86. /**
  87. * Represents the state of the index for a certain path regarding the stages
  88. * - which stages exist for a path and which not (base, ours, theirs).
  89. * <p>
  90. * This is used for figuring out what kind of conflict occurred.
  91. *
  92. * @see IndexDiff#getConflictingStageStates()
  93. * @since 3.0
  94. */
  95. public static enum StageState {
  96. /**
  97. * Exists in base, but neither in ours nor in theirs.
  98. */
  99. BOTH_DELETED(1),
  100. /**
  101. * Only exists in ours.
  102. */
  103. ADDED_BY_US(2),
  104. /**
  105. * Exists in base and ours, but no in theirs.
  106. */
  107. DELETED_BY_THEM(3),
  108. /**
  109. * Only exists in theirs.
  110. */
  111. ADDED_BY_THEM(4),
  112. /**
  113. * Exists in base and theirs, but not in ours.
  114. */
  115. DELETED_BY_US(5),
  116. /**
  117. * Exists in ours and theirs, but not in base.
  118. */
  119. BOTH_ADDED(6),
  120. /**
  121. * Exists in all stages, content conflict.
  122. */
  123. BOTH_MODIFIED(7);
  124. private final int stageMask;
  125. private StageState(int stageMask) {
  126. this.stageMask = stageMask;
  127. }
  128. int getStageMask() {
  129. return stageMask;
  130. }
  131. /**
  132. * @return whether there is a "base" stage entry
  133. */
  134. public boolean hasBase() {
  135. return (stageMask & 1) != 0;
  136. }
  137. /**
  138. * @return whether there is an "ours" stage entry
  139. */
  140. public boolean hasOurs() {
  141. return (stageMask & 2) != 0;
  142. }
  143. /**
  144. * @return whether there is a "theirs" stage entry
  145. */
  146. public boolean hasTheirs() {
  147. return (stageMask & 4) != 0;
  148. }
  149. static StageState fromMask(int stageMask) {
  150. // bits represent: theirs, ours, base
  151. switch (stageMask) {
  152. case 1: // 0b001
  153. return BOTH_DELETED;
  154. case 2: // 0b010
  155. return ADDED_BY_US;
  156. case 3: // 0b011
  157. return DELETED_BY_THEM;
  158. case 4: // 0b100
  159. return ADDED_BY_THEM;
  160. case 5: // 0b101
  161. return DELETED_BY_US;
  162. case 6: // 0b110
  163. return BOTH_ADDED;
  164. case 7: // 0b111
  165. return BOTH_MODIFIED;
  166. default:
  167. return null;
  168. }
  169. }
  170. }
  171. private static final class ProgressReportingFilter extends TreeFilter {
  172. private final ProgressMonitor monitor;
  173. private int count = 0;
  174. private int stepSize;
  175. private final int total;
  176. private ProgressReportingFilter(ProgressMonitor monitor, int total) {
  177. this.monitor = monitor;
  178. this.total = total;
  179. stepSize = total / 100;
  180. if (stepSize == 0)
  181. stepSize = 1000;
  182. }
  183. @Override
  184. public boolean shouldBeRecursive() {
  185. return false;
  186. }
  187. @Override
  188. public boolean include(TreeWalk walker)
  189. throws MissingObjectException,
  190. IncorrectObjectTypeException, IOException {
  191. count++;
  192. if (count % stepSize == 0) {
  193. if (count <= total)
  194. monitor.update(stepSize);
  195. if (monitor.isCancelled())
  196. throw StopWalkException.INSTANCE;
  197. }
  198. return true;
  199. }
  200. @Override
  201. public TreeFilter clone() {
  202. throw new IllegalStateException(
  203. "Do not clone this kind of filter: "
  204. + getClass().getName());
  205. }
  206. }
  207. private final static int TREE = 0;
  208. private final static int INDEX = 1;
  209. private final static int WORKDIR = 2;
  210. private final Repository repository;
  211. private final RevTree tree;
  212. private TreeFilter filter = null;
  213. private final WorkingTreeIterator initialWorkingTreeIterator;
  214. private Set<String> added = new HashSet<String>();
  215. private Set<String> changed = new HashSet<String>();
  216. private Set<String> removed = new HashSet<String>();
  217. private Set<String> missing = new HashSet<String>();
  218. private Set<String> modified = new HashSet<String>();
  219. private Set<String> untracked = new HashSet<String>();
  220. private Map<String, StageState> conflicts = new HashMap<String, StageState>();
  221. private Set<String> ignored;
  222. private Set<String> assumeUnchanged;
  223. private DirCache dirCache;
  224. private IndexDiffFilter indexDiffFilter;
  225. /**
  226. * Construct an IndexDiff
  227. *
  228. * @param repository
  229. * @param revstr
  230. * symbolic name e.g. HEAD
  231. * An EmptyTreeIterator is used if <code>revstr</code> cannot be resolved.
  232. * @param workingTreeIterator
  233. * iterator for working directory
  234. * @throws IOException
  235. */
  236. public IndexDiff(Repository repository, String revstr,
  237. WorkingTreeIterator workingTreeIterator) throws IOException {
  238. this.repository = repository;
  239. ObjectId objectId = repository.resolve(revstr);
  240. if (objectId != null)
  241. tree = new RevWalk(repository).parseTree(objectId);
  242. else
  243. tree = null;
  244. this.initialWorkingTreeIterator = workingTreeIterator;
  245. }
  246. /**
  247. * Construct an Indexdiff
  248. *
  249. * @param repository
  250. * @param objectId
  251. * tree id. If null, an EmptyTreeIterator is used.
  252. * @param workingTreeIterator
  253. * iterator for working directory
  254. * @throws IOException
  255. */
  256. public IndexDiff(Repository repository, ObjectId objectId,
  257. WorkingTreeIterator workingTreeIterator) throws IOException {
  258. this.repository = repository;
  259. if (objectId != null)
  260. tree = new RevWalk(repository).parseTree(objectId);
  261. else
  262. tree = null;
  263. this.initialWorkingTreeIterator = workingTreeIterator;
  264. }
  265. /**
  266. * Sets a filter. Can be used e.g. for restricting the tree walk to a set of
  267. * files.
  268. *
  269. * @param filter
  270. */
  271. public void setFilter(TreeFilter filter) {
  272. this.filter = filter;
  273. }
  274. /**
  275. * Run the diff operation. Until this is called, all lists will be empty.
  276. * Use {@link #diff(ProgressMonitor, int, int, String)} if a progress
  277. * monitor is required.
  278. *
  279. * @return if anything is different between index, tree, and workdir
  280. * @throws IOException
  281. */
  282. public boolean diff() throws IOException {
  283. return diff(null, 0, 0, ""); //$NON-NLS-1$
  284. }
  285. /**
  286. * Run the diff operation. Until this is called, all lists will be empty.
  287. * <p>
  288. * The operation may be aborted by the progress monitor. In that event it
  289. * will report what was found before the cancel operation was detected.
  290. * Callers should ignore the result if monitor.isCancelled() is true. If a
  291. * progress monitor is not needed, callers should use {@link #diff()}
  292. * instead. Progress reporting is crude and approximate and only intended
  293. * for informing the user.
  294. *
  295. * @param monitor
  296. * for reporting progress, may be null
  297. * @param estWorkTreeSize
  298. * number or estimated files in the working tree
  299. * @param estIndexSize
  300. * number of estimated entries in the cache
  301. * @param title
  302. *
  303. * @return if anything is different between index, tree, and workdir
  304. * @throws IOException
  305. */
  306. public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
  307. int estIndexSize, final String title)
  308. throws IOException {
  309. dirCache = repository.readDirCache();
  310. TreeWalk treeWalk = new TreeWalk(repository);
  311. treeWalk.setRecursive(true);
  312. // add the trees (tree, dirchache, workdir)
  313. if (tree != null)
  314. treeWalk.addTree(tree);
  315. else
  316. treeWalk.addTree(new EmptyTreeIterator());
  317. treeWalk.addTree(new DirCacheIterator(dirCache));
  318. treeWalk.addTree(initialWorkingTreeIterator);
  319. Collection<TreeFilter> filters = new ArrayList<TreeFilter>(4);
  320. if (monitor != null) {
  321. // Get the maximum size of the work tree and index
  322. // and add some (quite arbitrary)
  323. if (estIndexSize == 0)
  324. estIndexSize = dirCache.getEntryCount();
  325. int total = Math.max(estIndexSize * 10 / 9,
  326. estWorkTreeSize * 10 / 9);
  327. monitor.beginTask(title, total);
  328. filters.add(new ProgressReportingFilter(monitor, total));
  329. }
  330. if (filter != null)
  331. filters.add(filter);
  332. filters.add(new SkipWorkTreeFilter(INDEX));
  333. indexDiffFilter = new IndexDiffFilter(INDEX, WORKDIR);
  334. filters.add(indexDiffFilter);
  335. treeWalk.setFilter(AndTreeFilter.create(filters));
  336. while (treeWalk.next()) {
  337. AbstractTreeIterator treeIterator = treeWalk.getTree(TREE,
  338. AbstractTreeIterator.class);
  339. DirCacheIterator dirCacheIterator = treeWalk.getTree(INDEX,
  340. DirCacheIterator.class);
  341. WorkingTreeIterator workingTreeIterator = treeWalk.getTree(WORKDIR,
  342. WorkingTreeIterator.class);
  343. if (dirCacheIterator != null) {
  344. final DirCacheEntry dirCacheEntry = dirCacheIterator
  345. .getDirCacheEntry();
  346. if (dirCacheEntry != null) {
  347. int stage = dirCacheEntry.getStage();
  348. if (stage > 0) {
  349. String path = treeWalk.getPathString();
  350. addConflict(path, stage);
  351. continue;
  352. }
  353. }
  354. }
  355. if (treeIterator != null) {
  356. if (dirCacheIterator != null) {
  357. if (!treeIterator.idEqual(dirCacheIterator)
  358. || treeIterator.getEntryRawMode()
  359. != dirCacheIterator.getEntryRawMode()) {
  360. // in repo, in index, content diff => changed
  361. changed.add(treeWalk.getPathString());
  362. }
  363. } else {
  364. // in repo, not in index => removed
  365. removed.add(treeWalk.getPathString());
  366. if (workingTreeIterator != null)
  367. untracked.add(treeWalk.getPathString());
  368. }
  369. } else {
  370. if (dirCacheIterator != null) {
  371. // not in repo, in index => added
  372. added.add(treeWalk.getPathString());
  373. } else {
  374. // not in repo, not in index => untracked
  375. if (workingTreeIterator != null
  376. && !workingTreeIterator.isEntryIgnored()) {
  377. untracked.add(treeWalk.getPathString());
  378. }
  379. }
  380. }
  381. if (dirCacheIterator != null) {
  382. if (workingTreeIterator == null) {
  383. // in index, not in workdir => missing
  384. missing.add(treeWalk.getPathString());
  385. } else {
  386. if (workingTreeIterator.isModified(
  387. dirCacheIterator.getDirCacheEntry(), true,
  388. treeWalk.getObjectReader())) {
  389. // in index, in workdir, content differs => modified
  390. modified.add(treeWalk.getPathString());
  391. }
  392. }
  393. }
  394. }
  395. // consume the remaining work
  396. if (monitor != null)
  397. monitor.endTask();
  398. ignored = indexDiffFilter.getIgnoredPaths();
  399. if (added.isEmpty() && changed.isEmpty() && removed.isEmpty()
  400. && missing.isEmpty() && modified.isEmpty()
  401. && untracked.isEmpty())
  402. return false;
  403. else
  404. return true;
  405. }
  406. private void addConflict(String path, int stage) {
  407. StageState existingStageStates = conflicts.get(path);
  408. byte stageMask = 0;
  409. if (existingStageStates != null)
  410. stageMask |= existingStageStates.getStageMask();
  411. // stage 1 (base) should be shifted 0 times
  412. int shifts = stage - 1;
  413. stageMask |= (1 << shifts);
  414. StageState stageState = StageState.fromMask(stageMask);
  415. conflicts.put(path, stageState);
  416. }
  417. /**
  418. * @return list of files added to the index, not in the tree
  419. */
  420. public Set<String> getAdded() {
  421. return added;
  422. }
  423. /**
  424. * @return list of files changed from tree to index
  425. */
  426. public Set<String> getChanged() {
  427. return changed;
  428. }
  429. /**
  430. * @return list of files removed from index, but in tree
  431. */
  432. public Set<String> getRemoved() {
  433. return removed;
  434. }
  435. /**
  436. * @return list of files in index, but not filesystem
  437. */
  438. public Set<String> getMissing() {
  439. return missing;
  440. }
  441. /**
  442. * @return list of files modified on disk relative to the index
  443. */
  444. public Set<String> getModified() {
  445. return modified;
  446. }
  447. /**
  448. * @return list of files that are not ignored, and not in the index.
  449. */
  450. public Set<String> getUntracked() {
  451. return untracked;
  452. }
  453. /**
  454. * @return list of files that are in conflict, corresponds to the keys of
  455. * {@link #getConflictingStageStates()}
  456. */
  457. public Set<String> getConflicting() {
  458. return conflicts.keySet();
  459. }
  460. /**
  461. * @return the map from each path of {@link #getConflicting()} to its
  462. * corresponding {@link StageState}
  463. * @since 3.0
  464. */
  465. public Map<String, StageState> getConflictingStageStates() {
  466. return conflicts;
  467. }
  468. /**
  469. * The method returns the list of ignored files and folders. Only the root
  470. * folder of an ignored folder hierarchy is reported. If a/b/c is listed in
  471. * the .gitignore then you should not expect a/b/c/d/e/f to be reported
  472. * here. Only a/b/c will be reported. Furthermore only ignored files /
  473. * folders are returned that are NOT in the index.
  474. *
  475. * @return list of files / folders that are ignored
  476. */
  477. public Set<String> getIgnoredNotInIndex() {
  478. return ignored;
  479. }
  480. /**
  481. * @return list of files with the flag assume-unchanged
  482. */
  483. public Set<String> getAssumeUnchanged() {
  484. if (assumeUnchanged == null) {
  485. HashSet<String> unchanged = new HashSet<String>();
  486. for (int i = 0; i < dirCache.getEntryCount(); i++)
  487. if (dirCache.getEntry(i).isAssumeValid())
  488. unchanged.add(dirCache.getEntry(i).getPathString());
  489. assumeUnchanged = unchanged;
  490. }
  491. return assumeUnchanged;
  492. }
  493. /**
  494. * @return list of folders containing only untracked files/folders
  495. */
  496. public Set<String> getUntrackedFolders() {
  497. return ((indexDiffFilter == null) ? Collections.<String> emptySet()
  498. : new HashSet<String>(indexDiffFilter.getUntrackedFolders()));
  499. }
  500. /**
  501. * Get the file mode of the given path in the index
  502. *
  503. * @param path
  504. * @return file mode
  505. */
  506. public FileMode getIndexMode(final String path) {
  507. final DirCacheEntry entry = dirCache.getEntry(path);
  508. return entry != null ? entry.getFileMode() : FileMode.MISSING;
  509. }
  510. }