Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

DirCacheCheckout.java 30KB

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