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

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