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.

DirCacheCheckout.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Roger C. Soares <rogersoares@intelinet.com.br>
  5. * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
  6. * Copyright (C) 2010, Chrisian Halstrick <christian.halstrick@sap.com> and
  7. * other copyright owners as documented in the project's IP log.
  8. *
  9. * This program and the accompanying materials are made available under the
  10. * terms of the Eclipse Distribution License v1.0 which accompanies this
  11. * distribution, is reproduced below, and is available at
  12. * http://www.eclipse.org/org/documents/edl-v10.php
  13. *
  14. * All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or without
  17. * modification, are permitted provided that the following conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright notice, this
  20. * list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above copyright notice,
  23. * this list of conditions and the following disclaimer in the documentation
  24. * and/or other materials provided with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the names of its
  27. * contributors may be used to endorse or promote products derived from this
  28. * software without specific prior written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  31. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  32. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  34. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  35. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  36. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  37. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  38. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  39. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  40. * POSSIBILITY OF SUCH DAMAGE.
  41. */
  42. package org.eclipse.jgit.dircache;
  43. import java.io.File;
  44. import java.io.FileOutputStream;
  45. import java.io.IOException;
  46. import java.text.MessageFormat;
  47. import java.util.ArrayList;
  48. import java.util.HashMap;
  49. import java.util.List;
  50. import java.util.Map;
  51. import org.eclipse.jgit.JGitText;
  52. import org.eclipse.jgit.errors.CheckoutConflictException;
  53. import org.eclipse.jgit.errors.CorruptObjectException;
  54. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  55. import org.eclipse.jgit.errors.IndexWriteException;
  56. import org.eclipse.jgit.errors.MissingObjectException;
  57. import org.eclipse.jgit.lib.FileMode;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.ObjectLoader;
  60. import org.eclipse.jgit.lib.ObjectReader;
  61. import org.eclipse.jgit.lib.Repository;
  62. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  63. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  64. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  65. import org.eclipse.jgit.treewalk.FileTreeIterator;
  66. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  67. import org.eclipse.jgit.treewalk.TreeWalk;
  68. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  69. import org.eclipse.jgit.treewalk.WorkingTreeOptions;
  70. import org.eclipse.jgit.treewalk.filter.PathFilter;
  71. import org.eclipse.jgit.util.FS;
  72. import org.eclipse.jgit.util.FileUtils;
  73. /**
  74. * This class handles checking out one or two trees merging with the index.
  75. */
  76. public class DirCacheCheckout {
  77. private Repository repo;
  78. private HashMap<String, ObjectId> updated = new HashMap<String, ObjectId>();
  79. private ArrayList<String> conflicts = new ArrayList<String>();
  80. private ArrayList<String> removed = new ArrayList<String>();
  81. private ObjectId mergeCommitTree;
  82. private DirCache dc;
  83. private DirCacheBuilder builder;
  84. private NameConflictTreeWalk walk;
  85. private ObjectId headCommitTree;
  86. private WorkingTreeIterator workingTree;
  87. private boolean failOnConflict = true;
  88. private ArrayList<String> toBeDeleted = new ArrayList<String>();
  89. /**
  90. * @return a list of updated paths and objectIds
  91. */
  92. public Map<String, ObjectId> getUpdated() {
  93. return updated;
  94. }
  95. /**
  96. * @return a list of conflicts created by this checkout
  97. */
  98. public List<String> getConflicts() {
  99. return conflicts;
  100. }
  101. /**
  102. * @return a list of paths (relative to the start of the working tree) of
  103. * files which couldn't be deleted during last call to
  104. * {@link #checkout()} . {@link #checkout()} detected that these
  105. * files should be deleted but the deletion in the filesystem failed
  106. * (e.g. because a file was locked). To have a consistent state of
  107. * the working tree these files have to be deleted by the callers of
  108. * {@link DirCacheCheckout}.
  109. */
  110. public List<String> getToBeDeleted() {
  111. return toBeDeleted;
  112. }
  113. /**
  114. * @return a list of all files removed by this checkout
  115. */
  116. public List<String> getRemoved() {
  117. return removed;
  118. }
  119. /**
  120. * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
  121. * and mergeCommitTree) and the index.
  122. *
  123. * @param repo
  124. * the repository in which we do the checkout
  125. * @param headCommitTree
  126. * the id of the tree of the head commit
  127. * @param dc
  128. * the (already locked) Dircache for this repo
  129. * @param mergeCommitTree
  130. * the id of the tree we want to fast-forward to
  131. * @param workingTree
  132. * an iterator over the repositories Working Tree
  133. * @throws IOException
  134. */
  135. public DirCacheCheckout(Repository repo, ObjectId headCommitTree, DirCache dc,
  136. ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
  137. throws IOException {
  138. this.repo = repo;
  139. this.dc = dc;
  140. this.headCommitTree = headCommitTree;
  141. this.mergeCommitTree = mergeCommitTree;
  142. this.workingTree = workingTree;
  143. }
  144. /**
  145. * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
  146. * and mergeCommitTree) and the index. As iterator over the working tree
  147. * this constructor creates a standard {@link FileTreeIterator}
  148. *
  149. * @param repo
  150. * the repository in which we do the checkout
  151. * @param headCommitTree
  152. * the id of the tree of the head commit
  153. * @param dc
  154. * the (already locked) Dircache for this repo
  155. * @param mergeCommitTree
  156. * the id of the tree of the
  157. * @throws IOException
  158. */
  159. public DirCacheCheckout(Repository repo, ObjectId headCommitTree,
  160. DirCache dc, ObjectId mergeCommitTree) throws IOException {
  161. this(repo, headCommitTree, dc, mergeCommitTree, new FileTreeIterator(repo));
  162. }
  163. /**
  164. * Constructs a DirCacheCeckout for checking out one tree, merging with the
  165. * index.
  166. *
  167. * @param repo
  168. * the repository in which we do the checkout
  169. * @param dc
  170. * the (already locked) Dircache for this repo
  171. * @param mergeCommitTree
  172. * the id of the tree we want to fast-forward to
  173. * @param workingTree
  174. * an iterator over the repositories Working Tree
  175. * @throws IOException
  176. */
  177. public DirCacheCheckout(Repository repo, DirCache dc,
  178. ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
  179. throws IOException {
  180. this(repo, null, dc, mergeCommitTree, workingTree);
  181. }
  182. /**
  183. * Constructs a DirCacheCeckout for checking out one tree, merging with the
  184. * index. As iterator over the working tree this constructor creates a
  185. * standard {@link FileTreeIterator}
  186. *
  187. * @param repo
  188. * the repository in which we do the checkout
  189. * @param dc
  190. * the (already locked) Dircache for this repo
  191. * @param mergeCommitTree
  192. * the id of the tree of the
  193. * @throws IOException
  194. */
  195. public DirCacheCheckout(Repository repo, DirCache dc,
  196. ObjectId mergeCommitTree) throws IOException {
  197. this(repo, null, dc, mergeCommitTree, new FileTreeIterator(repo));
  198. }
  199. /**
  200. * Scan head, index and merge tree. Used during normal checkout or merge
  201. * operations.
  202. *
  203. * @throws CorruptObjectException
  204. * @throws IOException
  205. */
  206. public void preScanTwoTrees() throws CorruptObjectException, IOException {
  207. removed.clear();
  208. updated.clear();
  209. conflicts.clear();
  210. walk = new NameConflictTreeWalk(repo);
  211. builder = dc.builder();
  212. addTree(walk, headCommitTree);
  213. addTree(walk, mergeCommitTree);
  214. walk.addTree(new DirCacheBuildIterator(builder));
  215. walk.addTree(workingTree);
  216. while (walk.next()) {
  217. processEntry(walk.getTree(0, CanonicalTreeParser.class),
  218. walk.getTree(1, CanonicalTreeParser.class),
  219. walk.getTree(2, DirCacheBuildIterator.class),
  220. walk.getTree(3, WorkingTreeIterator.class));
  221. if (walk.isSubtree())
  222. walk.enterSubtree();
  223. }
  224. }
  225. private void addTree(TreeWalk tw, ObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException {
  226. if (id == null)
  227. tw.addTree(new EmptyTreeIterator());
  228. else
  229. tw.addTree(id);
  230. }
  231. /**
  232. * Scan index and merge tree (no HEAD). Used e.g. for initial checkout when
  233. * there is no head yet.
  234. *
  235. * @throws MissingObjectException
  236. * @throws IncorrectObjectTypeException
  237. * @throws CorruptObjectException
  238. * @throws IOException
  239. */
  240. public void prescanOneTree()
  241. throws MissingObjectException, IncorrectObjectTypeException,
  242. CorruptObjectException, IOException {
  243. removed.clear();
  244. updated.clear();
  245. conflicts.clear();
  246. builder = dc.builder();
  247. walk = new NameConflictTreeWalk(repo);
  248. walk.addTree(mergeCommitTree);
  249. walk.addTree(new DirCacheBuildIterator(builder));
  250. walk.addTree(workingTree);
  251. while (walk.next()) {
  252. processEntry(walk.getTree(0, CanonicalTreeParser.class),
  253. walk.getTree(1, DirCacheBuildIterator.class),
  254. walk.getTree(2, WorkingTreeIterator.class));
  255. if (walk.isSubtree())
  256. walk.enterSubtree();
  257. }
  258. conflicts.removeAll(removed);
  259. }
  260. /**
  261. * Processing an entry in the context of {@link #prescanOneTree()} when only
  262. * one tree is given
  263. *
  264. * @param m the tree to merge
  265. * @param i the index
  266. * @param f the working tree
  267. * @throws IOException
  268. */
  269. void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i,
  270. WorkingTreeIterator f) throws IOException {
  271. if (m != null) {
  272. // There is an entry in the merge commit. Means: we want to update
  273. // what's currently in the index and working-tree to that one
  274. if (i == null) {
  275. // The index entry is missing
  276. if (f != null && !FileMode.TREE.equals(f.getEntryFileMode())
  277. && !f.isEntryIgnored()) {
  278. // don't overwrite an untracked and not ignored file
  279. conflicts.add(walk.getPathString());
  280. } else
  281. update(m.getEntryPathString(), m.getEntryObjectId(),
  282. m.getEntryFileMode());
  283. } else if (f == null || !m.idEqual(i)) {
  284. // The working tree file is missing or the merge content differs
  285. // from index content
  286. update(m.getEntryPathString(), m.getEntryObjectId(),
  287. m.getEntryFileMode());
  288. } else if (i.getDirCacheEntry() != null) {
  289. // The index contains a file (and not a folder)
  290. if (f.isModified(i.getDirCacheEntry(), true)
  291. || i.getDirCacheEntry().getStage() != 0)
  292. // The working tree file is dirty or the index contains a
  293. // conflict
  294. update(m.getEntryPathString(), m.getEntryObjectId(),
  295. m.getEntryFileMode());
  296. else
  297. keep(i.getDirCacheEntry());
  298. } else
  299. // The index contains a folder
  300. keep(i.getDirCacheEntry());
  301. } else {
  302. // There is no entry in the merge commit. Means: we want to delete
  303. // what's currently in the index and working tree
  304. if (f != null) {
  305. // There is a file/folder for that path in the working tree
  306. if (walk.isDirectoryFileConflict()) {
  307. conflicts.add(walk.getPathString());
  308. } else {
  309. // No file/folder conflict exists. All entries are files or
  310. // all entries are folders
  311. if (i != null) {
  312. // ... and the working tree contained a file or folder
  313. // -> add it to the removed set and remove it from
  314. // conflicts set
  315. remove(i.getEntryPathString());
  316. conflicts.remove(i.getEntryPathString());
  317. } else {
  318. // untracked file, neither contained in tree to merge
  319. // nor in index
  320. }
  321. }
  322. } else {
  323. // There is no file/folder for that path in the working tree.
  324. // The only entry we have is the index entry. If that entry is a
  325. // conflict simply remove it. Otherwise keep that entry in the
  326. // index
  327. if (i.getDirCacheEntry().getStage() == 0)
  328. keep(i.getDirCacheEntry());
  329. }
  330. }
  331. }
  332. /**
  333. * Execute this checkout
  334. *
  335. * @return <code>false</code> if this method could not delete all the files
  336. * which should be deleted (e.g. because of of the files was
  337. * locked). In this case {@link #getToBeDeleted()} lists the files
  338. * which should be tried to be deleted outside of this method.
  339. * Although <code>false</code> is returned the checkout was
  340. * successful and the working tree was updated for all other files.
  341. * <code>true</code> is returned when no such problem occurred
  342. *
  343. * @throws IOException
  344. */
  345. public boolean checkout() throws IOException {
  346. try {
  347. return doCheckout();
  348. } finally {
  349. dc.unlock();
  350. }
  351. }
  352. private boolean doCheckout() throws CorruptObjectException, IOException,
  353. MissingObjectException, IncorrectObjectTypeException,
  354. CheckoutConflictException, IndexWriteException {
  355. toBeDeleted.clear();
  356. ObjectReader objectReader = repo.getObjectDatabase().newReader();
  357. try {
  358. if (headCommitTree != null)
  359. preScanTwoTrees();
  360. else
  361. prescanOneTree();
  362. if (!conflicts.isEmpty()) {
  363. if (failOnConflict) {
  364. dc.unlock();
  365. throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]));
  366. } else
  367. cleanUpConflicts();
  368. }
  369. // update our index
  370. builder.finish();
  371. File file = null;
  372. String last = "";
  373. // when deleting files process them in the opposite order as they have
  374. // been reported. This ensures the files are deleted before we delete
  375. // their parent folders
  376. for (int i = removed.size() - 1; i >= 0; i--) {
  377. String r = removed.get(i);
  378. file = new File(repo.getWorkTree(), r);
  379. if (!file.delete() && file.exists()) {
  380. // The list of stuff to delete comes from the index
  381. // which will only contain a directory if it is
  382. // a submodule, in which case we shall not attempt
  383. // to delete it. A submodule is not empty, so it
  384. // is safe to check this after a failed delete.
  385. if (!file.isDirectory())
  386. toBeDeleted.add(r);
  387. } else {
  388. if (!isSamePrefix(r, last))
  389. removeEmptyParents(new File(repo.getWorkTree(), last));
  390. last = r;
  391. }
  392. }
  393. if (file != null)
  394. removeEmptyParents(file);
  395. for (String path : updated.keySet()) {
  396. // ... create/overwrite this file ...
  397. file = new File(repo.getWorkTree(), path);
  398. if (!file.getParentFile().mkdirs()) {
  399. // ignore
  400. }
  401. DirCacheEntry entry = dc.getEntry(path);
  402. // submodules are handled with separate operations
  403. if (FileMode.GITLINK.equals(entry.getRawMode()))
  404. continue;
  405. checkoutEntry(repo, file, entry, objectReader);
  406. }
  407. // commit the index builder - a new index is persisted
  408. if (!builder.commit()) {
  409. dc.unlock();
  410. throw new IndexWriteException();
  411. }
  412. } finally {
  413. objectReader.release();
  414. }
  415. return toBeDeleted.size() == 0;
  416. }
  417. private static boolean isSamePrefix(String a, String b) {
  418. int as = a.lastIndexOf('/');
  419. int bs = b.lastIndexOf('/');
  420. return a.substring(0, as + 1).equals(b.substring(0, bs + 1));
  421. }
  422. private void removeEmptyParents(File f) {
  423. File parentFile = f.getParentFile();
  424. while (!parentFile.equals(repo.getWorkTree())) {
  425. if (!parentFile.delete())
  426. break;
  427. parentFile = parentFile.getParentFile();
  428. }
  429. }
  430. /**
  431. * Here the main work is done. This method is called for each existing path
  432. * in head, index and merge. This method decides what to do with the
  433. * corresponding index entry: keep it, update it, remove it or mark a
  434. * conflict.
  435. *
  436. * @param h
  437. * the entry for the head
  438. * @param m
  439. * the entry for the merge
  440. * @param i
  441. * the entry for the index
  442. * @param f
  443. * the file in the working tree
  444. * @throws IOException
  445. */
  446. void processEntry(AbstractTreeIterator h, AbstractTreeIterator m,
  447. DirCacheBuildIterator i, WorkingTreeIterator f) throws IOException {
  448. DirCacheEntry dce;
  449. String name = walk.getPathString();
  450. if (i == null && m == null && h == null) {
  451. // File/Directory conflict case #20
  452. if (walk.isDirectoryFileConflict())
  453. // TODO: check whether it is always correct to report a conflict here
  454. conflict(name, null, null, null);
  455. // file only exists in working tree -> ignore it
  456. return;
  457. }
  458. ObjectId iId = (i == null ? null : i.getEntryObjectId());
  459. ObjectId mId = (m == null ? null : m.getEntryObjectId());
  460. ObjectId hId = (h == null ? null : h.getEntryObjectId());
  461. /**
  462. * <pre>
  463. * File/Directory conflicts:
  464. * the following table from ReadTreeTest tells what to do in case of directory/file
  465. * conflicts. I give comments here
  466. *
  467. * H I M Clean H==M H==I I==M Result
  468. * ------------------------------------------------------------------
  469. * 1 D D F Y N Y N Update
  470. * 2 D D F N N Y N Conflict
  471. * 3 D F D Y N N Update
  472. * 4 D F D N N N Update
  473. * 5 D F F Y N N Y Keep
  474. * 6 D F F N N N Y Keep
  475. * 7 F D F Y Y N N Update
  476. * 8 F D F N Y N N Conflict
  477. * 9 F D F Y N N N Update
  478. * 10 F D D N N Y Keep
  479. * 11 F D D N N N Conflict
  480. * 12 F F D Y N Y N Update
  481. * 13 F F D N N Y N Conflict
  482. * 14 F F D N N N Conflict
  483. * 15 0 F D N N N Conflict
  484. * 16 0 D F Y N N N Update
  485. * 17 0 D F N N N Conflict
  486. * 18 F 0 D Update
  487. * 19 D 0 F Update
  488. * 20 0 0 F N (worktree=dir) Conflict
  489. * </pre>
  490. */
  491. // The information whether head,index,merge iterators are currently
  492. // pointing to file/folder/non-existing is encoded into this variable.
  493. //
  494. // To decode write down ffMask in hexadecimal form. The last digit
  495. // represents the state for the merge iterator, the second last the
  496. // state for the index iterator and the third last represents the state
  497. // for the head iterator. The hexadecimal constant "F" stands for
  498. // "file",
  499. // an "D" stands for "directory" (tree), and a "0" stands for
  500. // non-existing
  501. //
  502. // Examples:
  503. // ffMask == 0xFFD -> Head=File, Index=File, Merge=Tree
  504. // ffMask == 0xDD0 -> Head=Tree, Index=Tree, Merge=Non-Existing
  505. int ffMask = 0;
  506. if (h != null)
  507. ffMask = FileMode.TREE.equals(h.getEntryFileMode()) ? 0xD00 : 0xF00;
  508. if (i != null)
  509. ffMask |= FileMode.TREE.equals(i.getEntryFileMode()) ? 0x0D0
  510. : 0x0F0;
  511. if (m != null)
  512. ffMask |= FileMode.TREE.equals(m.getEntryFileMode()) ? 0x00D
  513. : 0x00F;
  514. // Check whether we have a possible file/folder conflict. Therefore we
  515. // need a least one file and one folder.
  516. if (((ffMask & 0x222) != 0x000)
  517. && (((ffMask & 0x00F) == 0x00D) || ((ffMask & 0x0F0) == 0x0D0) || ((ffMask & 0xF00) == 0xD00))) {
  518. // There are 3*3*3=27 possible combinations of file/folder
  519. // conflicts. Some of them are not-relevant because
  520. // they represent no conflict, e.g. 0xFFF, 0xDDD, ... The following
  521. // switch processes all relevant cases.
  522. switch (ffMask) {
  523. case 0xDDF: // 1 2
  524. if (isModified(name)) {
  525. conflict(name, i.getDirCacheEntry(), h, m); // 1
  526. } else {
  527. update(name, m.getEntryObjectId(), m.getEntryFileMode()); // 2
  528. }
  529. break;
  530. case 0xDFD: // 3 4
  531. // CAUTION: I put it into removed instead of updated, because
  532. // that's what our tests expect
  533. // updated.put(name, mId);
  534. remove(name);
  535. break;
  536. case 0xF0D: // 18
  537. remove(name);
  538. break;
  539. case 0xDFF: // 5 6
  540. case 0xFDD: // 10 11
  541. // TODO: make use of tree extension as soon as available in jgit
  542. // we would like to do something like
  543. // if (!iId.equals(mId))
  544. // conflict(name, i.getDirCacheEntry(), h, m);
  545. // But since we don't know the id of a tree in the index we do
  546. // nothing here and wait that conflicts between index and merge
  547. // are found later
  548. break;
  549. case 0xD0F: // 19
  550. update(name, mId, m.getEntryFileMode());
  551. break;
  552. case 0xDF0: // conflict without a rule
  553. case 0x0FD: // 15
  554. conflict(name, (i != null) ? i.getDirCacheEntry() : null, h, m);
  555. break;
  556. case 0xFDF: // 7 8 9
  557. if (hId.equals(mId)) {
  558. if (isModified(name))
  559. conflict(name, i.getDirCacheEntry(), h, m); // 8
  560. else
  561. update(name, mId, m.getEntryFileMode()); // 7
  562. } else if (!isModified(name))
  563. update(name, mId, m.getEntryFileMode()); // 9
  564. else
  565. // To be confirmed - this case is not in the table.
  566. conflict(name, i.getDirCacheEntry(), h, m);
  567. break;
  568. case 0xFD0: // keep without a rule
  569. keep(i.getDirCacheEntry());
  570. break;
  571. case 0xFFD: // 12 13 14
  572. if (hId.equals(iId)) {
  573. dce = i.getDirCacheEntry();
  574. if (f == null || f.isModified(dce, true))
  575. conflict(name, dce, h, m);
  576. else
  577. remove(name);
  578. } else
  579. conflict(name, i.getDirCacheEntry(), h, m);
  580. break;
  581. case 0x0DF: // 16 17
  582. if (!isModified(name))
  583. update(name, mId, m.getEntryFileMode());
  584. else
  585. conflict(name, i.getDirCacheEntry(), h, m);
  586. break;
  587. default:
  588. keep(i.getDirCacheEntry());
  589. }
  590. return;
  591. }
  592. // if we have no file at all then there is nothing to do
  593. if ((ffMask & 0x222) == 0)
  594. return;
  595. if ((ffMask == 0x00F) && f != null && FileMode.TREE.equals(f.getEntryFileMode())) {
  596. // File/Directory conflict case #20
  597. conflict(name, null, h, m);
  598. }
  599. if (i == null) {
  600. // make sure not to overwrite untracked files
  601. if (f != null) {
  602. // A submodule is not a file. We should ignore it
  603. if (!FileMode.GITLINK.equals(m.getEntryFileMode())) {
  604. // a dirty worktree: the index is empty but we have a
  605. // workingtree-file
  606. if (mId == null || !mId.equals(f.getEntryObjectId())) {
  607. conflict(name, null, h, m);
  608. return;
  609. }
  610. }
  611. }
  612. /**
  613. * <pre>
  614. * I (index) H M Result
  615. * -------------------------------------------------------
  616. * 0 nothing nothing nothing (does not happen)
  617. * 1 nothing nothing exists use M
  618. * 2 nothing exists nothing remove path from index
  619. * 3 nothing exists exists use M
  620. * </pre>
  621. */
  622. if (h == null)
  623. update(name, mId, m.getEntryFileMode()); // 1
  624. else if (m == null)
  625. remove(name); // 2
  626. else
  627. update(name, mId, m.getEntryFileMode()); // 3
  628. } else {
  629. dce = i.getDirCacheEntry();
  630. if (h == null) {
  631. /**
  632. * <pre>
  633. * clean I==H I==M H M Result
  634. * -----------------------------------------------------
  635. * 4 yes N/A N/A nothing nothing keep index
  636. * 5 no N/A N/A nothing nothing keep index
  637. *
  638. * 6 yes N/A yes nothing exists keep index
  639. * 7 no N/A yes nothing exists keep index
  640. * 8 yes N/A no nothing exists fail
  641. * 9 no N/A no nothing exists fail
  642. * </pre>
  643. */
  644. if (m == null || mId.equals(iId)) {
  645. if (m==null && walk.isDirectoryFileConflict()) {
  646. if (dce != null
  647. && (f == null || f.isModified(dce, true)))
  648. conflict(name, dce, h, m);
  649. else
  650. remove(name);
  651. } else
  652. keep(dce);
  653. } else
  654. conflict(name, dce, h, m);
  655. } else if (m == null) {
  656. /**
  657. * <pre>
  658. * clean I==H I==M H M Result
  659. * -----------------------------------------------------
  660. * 10 yes yes N/A exists nothing remove path from index
  661. * 11 no yes N/A exists nothing fail
  662. * 12 yes no N/A exists nothing fail
  663. * 13 no no N/A exists nothing fail
  664. * </pre>
  665. */
  666. if (dce.getFileMode() == FileMode.GITLINK) {
  667. // Submodules that disappear from the checkout must
  668. // be removed from the index, but not deleted from disk.
  669. remove(name);
  670. } else {
  671. if (hId.equals(iId)) {
  672. if (f == null || f.isModified(dce, true))
  673. conflict(name, dce, h, m);
  674. else
  675. remove(name);
  676. } else
  677. conflict(name, dce, h, m);
  678. }
  679. } else {
  680. if (!hId.equals(mId) && !hId.equals(iId) && !mId.equals(iId))
  681. conflict(name, dce, h, m);
  682. else if (hId.equals(iId) && !mId.equals(iId)) {
  683. // For submodules just update the index with the new SHA-1
  684. if (dce != null
  685. && FileMode.GITLINK.equals(dce.getFileMode())) {
  686. update(name, mId, m.getEntryFileMode());
  687. } else if (dce != null
  688. && (f == null || f.isModified(dce, true))) {
  689. conflict(name, dce, h, m);
  690. } else {
  691. update(name, mId, m.getEntryFileMode());
  692. }
  693. } else {
  694. keep(dce);
  695. }
  696. }
  697. }
  698. }
  699. /**
  700. * A conflict is detected - add the three different stages to the index
  701. * @param path the path of the conflicting entry
  702. * @param e the previous index entry
  703. * @param h the first tree you want to merge (the HEAD)
  704. * @param m the second tree you want to merge
  705. */
  706. private void conflict(String path, DirCacheEntry e, AbstractTreeIterator h, AbstractTreeIterator m) {
  707. conflicts.add(path);
  708. DirCacheEntry entry;
  709. if (e != null) {
  710. entry = new DirCacheEntry(e.getPathString(), DirCacheEntry.STAGE_1);
  711. entry.copyMetaData(e);
  712. builder.add(entry);
  713. }
  714. if (h != null && !FileMode.TREE.equals(h.getEntryFileMode())) {
  715. entry = new DirCacheEntry(h.getEntryPathString(), DirCacheEntry.STAGE_2);
  716. entry.setFileMode(h.getEntryFileMode());
  717. entry.setObjectId(h.getEntryObjectId());
  718. builder.add(entry);
  719. }
  720. if (m != null && !FileMode.TREE.equals(m.getEntryFileMode())) {
  721. entry = new DirCacheEntry(m.getEntryPathString(), DirCacheEntry.STAGE_3);
  722. entry.setFileMode(m.getEntryFileMode());
  723. entry.setObjectId(m.getEntryObjectId());
  724. builder.add(entry);
  725. }
  726. }
  727. private void keep(DirCacheEntry e) {
  728. if (e != null && !FileMode.TREE.equals(e.getFileMode()))
  729. builder.add(e);
  730. }
  731. private void remove(String path) {
  732. removed.add(path);
  733. }
  734. private void update(String path, ObjectId mId, FileMode mode) {
  735. if (!FileMode.TREE.equals(mode)) {
  736. updated.put(path, mId);
  737. DirCacheEntry entry = new DirCacheEntry(path, DirCacheEntry.STAGE_0);
  738. entry.setObjectId(mId);
  739. entry.setFileMode(mode);
  740. builder.add(entry);
  741. }
  742. }
  743. /**
  744. * If <code>true</code>, will scan first to see if it's possible to check
  745. * out, otherwise throw {@link CheckoutConflictException}. If
  746. * <code>false</code>, it will silently deal with the problem.
  747. *
  748. * @param failOnConflict
  749. */
  750. public void setFailOnConflict(boolean failOnConflict) {
  751. this.failOnConflict = failOnConflict;
  752. }
  753. /**
  754. * This method implements how to handle conflicts when
  755. * {@link #failOnConflict} is false
  756. *
  757. * @throws CheckoutConflictException
  758. */
  759. private void cleanUpConflicts() throws CheckoutConflictException {
  760. // TODO: couldn't we delete unsaved worktree content here?
  761. for (String c : conflicts) {
  762. File conflict = new File(repo.getWorkTree(), c);
  763. if (!conflict.delete())
  764. throw new CheckoutConflictException(MessageFormat.format(
  765. JGitText.get().cannotDeleteFile, c));
  766. removeEmptyParents(conflict);
  767. }
  768. for (String r : removed) {
  769. File file = new File(repo.getWorkTree(), r);
  770. if (!file.delete())
  771. throw new CheckoutConflictException(
  772. MessageFormat.format(JGitText.get().cannotDeleteFile,
  773. file.getAbsolutePath()));
  774. removeEmptyParents(file);
  775. }
  776. }
  777. private boolean isModified(String path) throws CorruptObjectException, IOException {
  778. NameConflictTreeWalk tw = new NameConflictTreeWalk(repo);
  779. tw.addTree(new DirCacheIterator(dc));
  780. tw.addTree(new FileTreeIterator(repo));
  781. tw.setRecursive(true);
  782. tw.setFilter(PathFilter.create(path));
  783. DirCacheIterator dcIt;
  784. WorkingTreeIterator wtIt;
  785. while(tw.next()) {
  786. dcIt = tw.getTree(0, DirCacheIterator.class);
  787. wtIt = tw.getTree(1, WorkingTreeIterator.class);
  788. if (dcIt == null || wtIt == null)
  789. return true;
  790. if (wtIt.isModified(dcIt.getDirCacheEntry(), true)) {
  791. return true;
  792. }
  793. }
  794. return false;
  795. }
  796. /**
  797. * Updates the file in the working tree with content and mode from an entry
  798. * in the index. The new content is first written to a new temporary file in
  799. * the same directory as the real file. Then that new file is renamed to the
  800. * final filename. Use this method only for checkout of a single entry.
  801. * Otherwise use
  802. * {@code checkoutEntry(Repository, File f, DirCacheEntry, ObjectReader)}
  803. * instead which allows to reuse one {@code ObjectReader} for multiple
  804. * entries.
  805. *
  806. * <p>
  807. * TODO: this method works directly on File IO, we may need another
  808. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  809. * Eclipse that Files in the workspace got changed
  810. * </p>
  811. *
  812. * @param repository
  813. * @param f
  814. * the file to be modified. The parent directory for this file
  815. * has to exist already
  816. * @param entry
  817. * the entry containing new mode and content
  818. * @throws IOException
  819. */
  820. public static void checkoutEntry(final Repository repository, File f,
  821. DirCacheEntry entry) throws IOException {
  822. ObjectReader or = repository.newObjectReader();
  823. try {
  824. checkoutEntry(repository, f, entry, repository.newObjectReader());
  825. } finally {
  826. or.release();
  827. }
  828. }
  829. /**
  830. * Updates the file in the working tree with content and mode from an entry
  831. * in the index. The new content is first written to a new temporary file in
  832. * the same directory as the real file. Then that new file is renamed to the
  833. * final filename.
  834. *
  835. * <p>
  836. * TODO: this method works directly on File IO, we may need another
  837. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  838. * Eclipse that Files in the workspace got changed
  839. * </p>
  840. *
  841. * @param repo
  842. * @param f
  843. * the file to be modified. The parent directory for this file
  844. * has to exist already
  845. * @param entry
  846. * the entry containing new mode and content
  847. * @param or
  848. * object reader to use for checkout
  849. * @throws IOException
  850. */
  851. public static void checkoutEntry(final Repository repo, File f,
  852. DirCacheEntry entry, ObjectReader or) throws IOException {
  853. ObjectLoader ol = or.open(entry.getObjectId());
  854. File parentDir = f.getParentFile();
  855. File tmpFile = File.createTempFile("._" + f.getName(), null, parentDir);
  856. FileOutputStream channel = new FileOutputStream(tmpFile);
  857. try {
  858. ol.copyTo(channel);
  859. } finally {
  860. channel.close();
  861. }
  862. FS fs = repo.getFS();
  863. WorkingTreeOptions opt = repo.getConfig().get(WorkingTreeOptions.KEY);
  864. if (opt.isFileMode() && fs.supportsExecute()) {
  865. if (FileMode.EXECUTABLE_FILE.equals(entry.getRawMode())) {
  866. if (!fs.canExecute(tmpFile))
  867. fs.setExecute(tmpFile, true);
  868. } else {
  869. if (fs.canExecute(tmpFile))
  870. fs.setExecute(tmpFile, false);
  871. }
  872. }
  873. if (!tmpFile.renameTo(f)) {
  874. // tried to rename which failed. Let' delete the target file and try
  875. // again
  876. FileUtils.delete(f);
  877. if (!tmpFile.renameTo(f)) {
  878. throw new IOException(MessageFormat.format(
  879. JGitText.get().couldNotWriteFile, tmpFile.getPath(),
  880. f.getPath()));
  881. }
  882. }
  883. entry.setLastModified(f.lastModified());
  884. entry.setLength((int) ol.getSize());
  885. }
  886. }