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

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