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

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