Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

DirCacheCheckout.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 pathes 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 conflicts;
  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. */
  272. void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i,
  273. WorkingTreeIterator f) {
  274. if (m != null) {
  275. if (i == null || f == null || !m.idEqual(i)
  276. || (i.getDirCacheEntry() != null && (f.isModified(
  277. i.getDirCacheEntry(), true) ||
  278. i.getDirCacheEntry().getStage() != 0))) {
  279. update(m.getEntryPathString(), m.getEntryObjectId(),
  280. m.getEntryFileMode());
  281. } else
  282. keep(i.getDirCacheEntry());
  283. } else {
  284. if (f != null) {
  285. if (walk.isDirectoryFileConflict()) {
  286. conflicts.add(walk.getPathString());
  287. } else {
  288. if (i != null) {
  289. // ... and the working dir contained a file or folder ->
  290. // add it to the removed set and remove it from
  291. // conflicts set
  292. remove(i.getEntryPathString());
  293. conflicts.remove(i.getEntryPathString());
  294. }
  295. }
  296. } else if (i.getDirCacheEntry().getStage() == 0)
  297. keep(i.getDirCacheEntry());
  298. }
  299. }
  300. /**
  301. * Execute this checkout
  302. *
  303. * @return <code>false</code> if this method could not delete all the files
  304. * which should be deleted (e.g. because of of the files was
  305. * locked). In this case {@link #getToBeDeleted()} lists the files
  306. * which should be tried to be deleted outside of this method.
  307. * Although <code>false</code> is returned the checkout was
  308. * successful and the working tree was updated for all other files.
  309. * <code>true</code> is returned when no such problem occurred
  310. *
  311. * @throws IOException
  312. */
  313. public boolean checkout() throws IOException {
  314. toBeDeleted.clear();
  315. if (headCommitTree != null)
  316. preScanTwoTrees();
  317. else
  318. prescanOneTree();
  319. if (!conflicts.isEmpty()) {
  320. if (failOnConflict) {
  321. dc.unlock();
  322. throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]));
  323. } else
  324. cleanUpConflicts();
  325. }
  326. // update our index
  327. builder.finish();
  328. File file=null;
  329. String last = "";
  330. // when deleting files process them in the opposite order as they have
  331. // been reported. This ensures the files are deleted before we delete
  332. // their parent folders
  333. for (int i = removed.size() - 1; i >= 0; i--) {
  334. String r = removed.get(i);
  335. file = new File(repo.getWorkTree(), r);
  336. if (!file.delete() && file.exists())
  337. toBeDeleted.add(r);
  338. else {
  339. if (!isSamePrefix(r, last))
  340. removeEmptyParents(file);
  341. last = r;
  342. }
  343. }
  344. if (file != null)
  345. removeEmptyParents(file);
  346. for (String path : updated.keySet()) {
  347. // ... create/overwrite this file ...
  348. file = new File(repo.getWorkTree(), path);
  349. file.getParentFile().mkdirs();
  350. file.createNewFile();
  351. DirCacheEntry entry = dc.getEntry(path);
  352. checkoutEntry(repo, file, entry);
  353. }
  354. // commit the index builder - a new index is persisted
  355. if (!builder.commit()) {
  356. dc.unlock();
  357. throw new IndexWriteException();
  358. }
  359. return toBeDeleted.size() == 0;
  360. }
  361. private static boolean isSamePrefix(String a, String b) {
  362. int as = a.lastIndexOf('/');
  363. int bs = b.lastIndexOf('/');
  364. return a.substring(0, as + 1).equals(b.substring(0, bs + 1));
  365. }
  366. private void removeEmptyParents(File f) {
  367. File parentFile = f.getParentFile();
  368. while (!parentFile.equals(repo.getWorkTree())) {
  369. if (!parentFile.delete())
  370. break;
  371. parentFile = parentFile.getParentFile();
  372. }
  373. }
  374. /**
  375. * Here the main work is done. This method is called for each existing path
  376. * in head, index and merge. This method decides what to do with the
  377. * corresponding index entry: keep it, update it, remove it or mark a
  378. * conflict.
  379. *
  380. * @param h
  381. * the entry for the head
  382. * @param m
  383. * the entry for the merge
  384. * @param i
  385. * the entry for the index
  386. * @param f
  387. * the file in the working tree
  388. * @throws IOException
  389. */
  390. void processEntry(AbstractTreeIterator h, AbstractTreeIterator m,
  391. DirCacheBuildIterator i, WorkingTreeIterator f) throws IOException {
  392. DirCacheEntry dce;
  393. String name = walk.getPathString();
  394. if (i == null && m == null && h == null) {
  395. // File/Directory conflict case #20
  396. if (walk.isDirectoryFileConflict())
  397. // TODO: check whether it is always correct to report a conflict here
  398. conflict(name, null, null, null);
  399. // file only exists in working tree -> ignore it
  400. return;
  401. }
  402. ObjectId iId = (i == null ? null : i.getEntryObjectId());
  403. ObjectId mId = (m == null ? null : m.getEntryObjectId());
  404. ObjectId hId = (h == null ? null : h.getEntryObjectId());
  405. /**
  406. * <pre>
  407. * File/Directory conflicts:
  408. * the following table from ReadTreeTest tells what to do in case of directory/file
  409. * conflicts. I give comments here
  410. *
  411. * H I M Clean H==M H==I I==M Result
  412. * ------------------------------------------------------------------
  413. * 1 D D F Y N Y N Update
  414. * 2 D D F N N Y N Conflict
  415. * 3 D F D Y N N Update
  416. * 4 D F D N N N Update
  417. * 5 D F F Y N N Y Keep
  418. * 6 D F F N N N Y Keep
  419. * 7 F D F Y Y N N Update
  420. * 8 F D F N Y N N Conflict
  421. * 9 F D F Y N N N Update
  422. * 10 F D D N N Y Keep
  423. * 11 F D D N N N Conflict
  424. * 12 F F D Y N Y N Update
  425. * 13 F F D N N Y N Conflict
  426. * 14 F F D N N N Conflict
  427. * 15 0 F D N N N Conflict
  428. * 16 0 D F Y N N N Update
  429. * 17 0 D F N N N Conflict
  430. * 18 F 0 D Update
  431. * 19 D 0 F Update
  432. * 20 0 0 F N (worktree=dir) Conflict
  433. * </pre>
  434. */
  435. // The information whether head,index,merge iterators are currently
  436. // pointing to file/folder/non-existing is encoded into this variable.
  437. //
  438. // To decode write down ffMask in hexadecimal form. The last digit
  439. // represents the state for the merge iterator, the second last the
  440. // state for the index iterator and the third last represents the state
  441. // for the head iterator. The hexadecimal constant "F" stands for
  442. // "file",
  443. // an "D" stands for "directory" (tree), and a "0" stands for
  444. // non-existing
  445. //
  446. // Examples:
  447. // ffMask == 0xFFD -> Head=File, Index=File, Merge=Tree
  448. // ffMask == 0xDD0 -> Head=Tree, Index=Tree, Merge=Non-Existing
  449. int ffMask = 0;
  450. if (h != null)
  451. ffMask = FileMode.TREE.equals(h.getEntryFileMode()) ? 0xD00 : 0xF00;
  452. if (i != null)
  453. ffMask |= FileMode.TREE.equals(i.getEntryFileMode()) ? 0x0D0
  454. : 0x0F0;
  455. if (m != null)
  456. ffMask |= FileMode.TREE.equals(m.getEntryFileMode()) ? 0x00D
  457. : 0x00F;
  458. // Check whether we have a possible file/folder conflict. Therefore we
  459. // need a least one file and one folder.
  460. if (((ffMask & 0x222) != 0x000)
  461. && (((ffMask & 0x00F) == 0x00D) || ((ffMask & 0x0F0) == 0x0D0) || ((ffMask & 0xF00) == 0xD00))) {
  462. // There are 3*3*3=27 possible combinations of file/folder
  463. // conflicts. Some of them are not-relevant because
  464. // they represent no conflict, e.g. 0xFFF, 0xDDD, ... The following
  465. // switch processes all relevant cases.
  466. switch (ffMask) {
  467. case 0xDDF: // 1 2
  468. if (isModified(name)) {
  469. conflict(name, i.getDirCacheEntry(), h, m); // 1
  470. } else {
  471. update(name, m.getEntryObjectId(), m.getEntryFileMode()); // 2
  472. }
  473. break;
  474. case 0xDFD: // 3 4
  475. // CAUTION: I put it into removed instead of updated, because
  476. // that's what our tests expect
  477. // updated.put(name, mId);
  478. remove(name);
  479. break;
  480. case 0xF0D: // 18
  481. remove(name);
  482. break;
  483. case 0xDFF: // 5 6
  484. case 0xFDD: // 10 11
  485. // TODO: make use of tree extension as soon as available in jgit
  486. // we would like to do something like
  487. // if (!iId.equals(mId))
  488. // conflict(name, i.getDirCacheEntry(), h, m);
  489. // But since we don't know the id of a tree in the index we do
  490. // nothing here and wait that conflicts between index and merge
  491. // are found later
  492. break;
  493. case 0xD0F: // 19
  494. update(name, mId, m.getEntryFileMode());
  495. break;
  496. case 0xDF0: // conflict without a rule
  497. case 0x0FD: // 15
  498. conflict(name, (i != null) ? i.getDirCacheEntry() : null, h, m);
  499. break;
  500. case 0xFDF: // 7 8 9
  501. if (hId.equals(mId)) {
  502. if (isModified(name))
  503. conflict(name, i.getDirCacheEntry(), h, m); // 8
  504. else
  505. update(name, mId, m.getEntryFileMode()); // 7
  506. } else if (!isModified(name))
  507. update(name, mId, m.getEntryFileMode()); // 9
  508. else
  509. // To be confirmed - this case is not in the table.
  510. conflict(name, i.getDirCacheEntry(), h, m);
  511. break;
  512. case 0xFD0: // keep without a rule
  513. keep(i.getDirCacheEntry());
  514. break;
  515. case 0xFFD: // 12 13 14
  516. if (hId.equals(iId)) {
  517. dce = i.getDirCacheEntry();
  518. if (f == null || f.isModified(dce, true))
  519. conflict(name, i.getDirCacheEntry(), h, m);
  520. else
  521. remove(name);
  522. } else
  523. conflict(name, i.getDirCacheEntry(), h, m);
  524. break;
  525. case 0x0DF: // 16 17
  526. if (!isModified(name))
  527. update(name, mId, m.getEntryFileMode());
  528. else
  529. conflict(name, i.getDirCacheEntry(), h, m);
  530. break;
  531. default:
  532. keep(i.getDirCacheEntry());
  533. }
  534. return;
  535. }
  536. // if we have no file at all then there is nothing to do
  537. if ((ffMask & 0x222) == 0)
  538. return;
  539. if ((ffMask == 0x00F) && f != null && FileMode.TREE.equals(f.getEntryFileMode())) {
  540. // File/Directory conflict case #20
  541. conflict(name, null, h, m);
  542. }
  543. if (i == null) {
  544. /**
  545. * <pre>
  546. * I (index) H M Result
  547. * -------------------------------------------------------
  548. * 0 nothing nothing nothing (does not happen)
  549. * 1 nothing nothing exists use M
  550. * 2 nothing exists nothing remove path from index
  551. * 3 nothing exists exists use M
  552. * </pre>
  553. */
  554. if (h == null)
  555. update(name, mId, m.getEntryFileMode()); // 1
  556. else if (m == null)
  557. remove(name); // 2
  558. else
  559. update(name, mId, m.getEntryFileMode()); // 3
  560. } else {
  561. dce = i.getDirCacheEntry();
  562. if (h == null) {
  563. /**
  564. * <pre>
  565. * clean I==H I==M H M Result
  566. * -----------------------------------------------------
  567. * 4 yes N/A N/A nothing nothing keep index
  568. * 5 no N/A N/A nothing nothing keep index
  569. *
  570. * 6 yes N/A yes nothing exists keep index
  571. * 7 no N/A yes nothing exists keep index
  572. * 8 yes N/A no nothing exists fail
  573. * 9 no N/A no nothing exists fail
  574. * </pre>
  575. */
  576. if (m == null || mId.equals(iId)) {
  577. if (m==null && walk.isDirectoryFileConflict()) {
  578. if (dce != null
  579. && (f == null || f.isModified(dce, true)))
  580. conflict(name, i.getDirCacheEntry(), h, m);
  581. else
  582. remove(name);
  583. } else
  584. keep(i.getDirCacheEntry());
  585. } else
  586. conflict(name, i.getDirCacheEntry(), h, m);
  587. } else if (m == null) {
  588. /**
  589. * <pre>
  590. * clean I==H I==M H M Result
  591. * -----------------------------------------------------
  592. * 10 yes yes N/A exists nothing remove path from index
  593. * 11 no yes N/A exists nothing fail
  594. * 12 yes no N/A exists nothing fail
  595. * 13 no no N/A exists nothing fail
  596. * </pre>
  597. */
  598. if (hId.equals(iId)) {
  599. if (f == null || f.isModified(dce, true))
  600. conflict(name, i.getDirCacheEntry(), h, m);
  601. else
  602. remove(name);
  603. } else
  604. conflict(name, i.getDirCacheEntry(), h, m);
  605. } else {
  606. if (!hId.equals(mId) && !hId.equals(iId) && !mId.equals(iId))
  607. conflict(name, i.getDirCacheEntry(), h, m);
  608. else if (hId.equals(iId) && !mId.equals(iId)) {
  609. if (dce != null && (f == null || f.isModified(dce, true)))
  610. conflict(name, i.getDirCacheEntry(), h, m);
  611. else
  612. update(name, mId, m.getEntryFileMode());
  613. } else {
  614. keep(i.getDirCacheEntry());
  615. }
  616. }
  617. }
  618. }
  619. /**
  620. * A conflict is detected - add the three different stages to the index
  621. * @param path the path of the conflicting entry
  622. * @param e the previous index entry
  623. * @param h the first tree you want to merge (the HEAD)
  624. * @param m the second tree you want to merge
  625. */
  626. private void conflict(String path, DirCacheEntry e, AbstractTreeIterator h, AbstractTreeIterator m) {
  627. conflicts.add(path);
  628. DirCacheEntry entry;
  629. if (e != null) {
  630. entry = new DirCacheEntry(e.getPathString(), DirCacheEntry.STAGE_1);
  631. entry.copyMetaData(e);
  632. builder.add(entry);
  633. }
  634. if (h != null && !FileMode.TREE.equals(h.getEntryFileMode())) {
  635. entry = new DirCacheEntry(h.getEntryPathString(), DirCacheEntry.STAGE_2);
  636. entry.setFileMode(h.getEntryFileMode());
  637. entry.setObjectId(h.getEntryObjectId());
  638. builder.add(entry);
  639. }
  640. if (m != null && !FileMode.TREE.equals(m.getEntryFileMode())) {
  641. entry = new DirCacheEntry(m.getEntryPathString(), DirCacheEntry.STAGE_3);
  642. entry.setFileMode(m.getEntryFileMode());
  643. entry.setObjectId(m.getEntryObjectId());
  644. builder.add(entry);
  645. }
  646. }
  647. private void keep(DirCacheEntry e) {
  648. if (e != null && !FileMode.TREE.equals(e.getFileMode()))
  649. builder.add(e);
  650. }
  651. private void remove(String path) {
  652. removed.add(path);
  653. }
  654. private void update(String path, ObjectId mId, FileMode mode) {
  655. if (!FileMode.TREE.equals(mode)) {
  656. updated.put(path, mId);
  657. DirCacheEntry entry = new DirCacheEntry(path, DirCacheEntry.STAGE_0);
  658. entry.setObjectId(mId);
  659. entry.setFileMode(mode);
  660. builder.add(entry);
  661. }
  662. }
  663. /**
  664. * If <code>true</code>, will scan first to see if it's possible to check
  665. * out, otherwise throw {@link CheckoutConflictException}. If
  666. * <code>false</code>, it will silently deal with the problem.
  667. *
  668. * @param failOnConflict
  669. */
  670. public void setFailOnConflict(boolean failOnConflict) {
  671. this.failOnConflict = failOnConflict;
  672. }
  673. /**
  674. * This method implements how to handle conflicts when
  675. * {@link #failOnConflict} is false
  676. *
  677. * @throws CheckoutConflictException
  678. */
  679. private void cleanUpConflicts() throws CheckoutConflictException {
  680. // TODO: couldn't we delete unsaved worktree content here?
  681. for (String c : conflicts) {
  682. File conflict = new File(repo.getWorkTree(), c);
  683. if (!conflict.delete())
  684. throw new CheckoutConflictException(MessageFormat.format(
  685. JGitText.get().cannotDeleteFile, c));
  686. removeEmptyParents(conflict);
  687. }
  688. for (String r : removed) {
  689. File file = new File(repo.getWorkTree(), r);
  690. if (!file.delete())
  691. throw new CheckoutConflictException(
  692. MessageFormat.format(JGitText.get().cannotDeleteFile,
  693. file.getAbsolutePath()));
  694. removeEmptyParents(file);
  695. }
  696. }
  697. private boolean isModified(String path) throws CorruptObjectException, IOException {
  698. NameConflictTreeWalk tw = new NameConflictTreeWalk(repo);
  699. tw.addTree(new DirCacheIterator(dc));
  700. tw.addTree(new FileTreeIterator(repo));
  701. tw.setRecursive(true);
  702. tw.setFilter(PathFilter.create(path));
  703. DirCacheIterator dcIt;
  704. WorkingTreeIterator wtIt;
  705. while(tw.next()) {
  706. dcIt = tw.getTree(0, DirCacheIterator.class);
  707. wtIt = tw.getTree(1, WorkingTreeIterator.class);
  708. if (dcIt == null || wtIt == null)
  709. return true;
  710. if (wtIt.isModified(dcIt.getDirCacheEntry(), true)) {
  711. return true;
  712. }
  713. }
  714. return false;
  715. }
  716. /**
  717. * Updates the file in the working tree with content and mode from an entry
  718. * in the index. The new content is first written to a new temporary file in
  719. * the same directory as the real file. Then that new file is renamed to the
  720. * final filename.
  721. *
  722. * TODO: this method works directly on File IO, we may need another
  723. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  724. * Eclipse that Files in the workspace got changed
  725. * @param repo
  726. * @param f
  727. * the file to be modified. The parent directory for this file
  728. * has to exist already
  729. * @param entry
  730. * the entry containing new mode and content
  731. * @throws IOException
  732. */
  733. public static void checkoutEntry(final Repository repo, File f,
  734. DirCacheEntry entry) throws IOException {
  735. ObjectLoader ol = repo.open(entry.getObjectId());
  736. File parentDir = f.getParentFile();
  737. File tmpFile = File.createTempFile("._" + f.getName(), null, parentDir);
  738. FileOutputStream channel = new FileOutputStream(tmpFile);
  739. try {
  740. ol.copyTo(channel);
  741. } finally {
  742. channel.close();
  743. }
  744. FS fs = repo.getFS();
  745. WorkingTreeOptions opt = repo.getConfig().get(WorkingTreeOptions.KEY);
  746. if (opt.isFileMode() && fs.supportsExecute()) {
  747. if (FileMode.EXECUTABLE_FILE.equals(entry.getRawMode())) {
  748. if (!fs.canExecute(tmpFile))
  749. fs.setExecute(tmpFile, true);
  750. } else {
  751. if (fs.canExecute(tmpFile))
  752. fs.setExecute(tmpFile, false);
  753. }
  754. }
  755. if (!tmpFile.renameTo(f)) {
  756. // tried to rename which failed. Let' delete the target file and try
  757. // again
  758. FileUtils.delete(f);
  759. if (!tmpFile.renameTo(f)) {
  760. throw new IOException(MessageFormat.format(
  761. JGitText.get().couldNotWriteFile, tmpFile.getPath(),
  762. f.getPath()));
  763. }
  764. }
  765. entry.setLastModified(f.lastModified());
  766. entry.setLength((int) ol.getSize());
  767. }
  768. }