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

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