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

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