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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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.nio.file.StandardCopyOption;
  48. import java.text.MessageFormat;
  49. import java.util.ArrayList;
  50. import java.util.HashMap;
  51. import java.util.List;
  52. import java.util.Map;
  53. import org.eclipse.jgit.api.errors.FilterFailedException;
  54. import org.eclipse.jgit.errors.CheckoutConflictException;
  55. import org.eclipse.jgit.errors.CorruptObjectException;
  56. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  57. import org.eclipse.jgit.errors.IndexWriteException;
  58. import org.eclipse.jgit.errors.MissingObjectException;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.CoreConfig.AutoCRLF;
  62. import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
  63. import org.eclipse.jgit.lib.CoreConfig.SymLinks;
  64. import org.eclipse.jgit.lib.FileMode;
  65. import org.eclipse.jgit.lib.NullProgressMonitor;
  66. import org.eclipse.jgit.lib.ObjectChecker;
  67. import org.eclipse.jgit.lib.ObjectId;
  68. import org.eclipse.jgit.lib.ObjectLoader;
  69. import org.eclipse.jgit.lib.ObjectReader;
  70. import org.eclipse.jgit.lib.Repository;
  71. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  72. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  73. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  74. import org.eclipse.jgit.treewalk.FileTreeIterator;
  75. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  76. import org.eclipse.jgit.treewalk.TreeWalk;
  77. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  78. import org.eclipse.jgit.treewalk.WorkingTreeOptions;
  79. import org.eclipse.jgit.treewalk.filter.PathFilter;
  80. import org.eclipse.jgit.util.FS;
  81. import org.eclipse.jgit.util.FS.ExecutionResult;
  82. import org.eclipse.jgit.util.FileUtils;
  83. import org.eclipse.jgit.util.RawParseUtils;
  84. import org.eclipse.jgit.util.SystemReader;
  85. import org.eclipse.jgit.util.io.EolStreamTypeUtil;
  86. /**
  87. * This class handles checking out one or two trees merging with the index.
  88. */
  89. public class DirCacheCheckout {
  90. private static final int MAX_EXCEPTION_TEXT_SIZE = 10 * 1024;
  91. /**
  92. * Metadata used in checkout process
  93. *
  94. * @since 4.3
  95. */
  96. public static class CheckoutMetadata {
  97. /** git attributes */
  98. public final EolStreamType eolStreamType;
  99. /** filter command to apply */
  100. public final String smudgeFilterCommand;
  101. /**
  102. * @param eolStreamType
  103. * @param smudgeFilterCommand
  104. */
  105. public CheckoutMetadata(EolStreamType eolStreamType,
  106. String smudgeFilterCommand) {
  107. this.eolStreamType = eolStreamType;
  108. this.smudgeFilterCommand = smudgeFilterCommand;
  109. }
  110. static CheckoutMetadata EMPTY = new CheckoutMetadata(
  111. EolStreamType.DIRECT, null);
  112. }
  113. private Repository repo;
  114. private HashMap<String, CheckoutMetadata> updated = new HashMap<String, CheckoutMetadata>();
  115. private ArrayList<String> conflicts = new ArrayList<String>();
  116. private ArrayList<String> removed = new ArrayList<String>();
  117. private ObjectId mergeCommitTree;
  118. private DirCache dc;
  119. private DirCacheBuilder builder;
  120. private NameConflictTreeWalk walk;
  121. private ObjectId headCommitTree;
  122. private WorkingTreeIterator workingTree;
  123. private boolean failOnConflict = true;
  124. private ArrayList<String> toBeDeleted = new ArrayList<String>();
  125. private boolean emptyDirCache;
  126. /**
  127. * @return a list of updated paths and smudgeFilterCommands
  128. */
  129. public Map<String, CheckoutMetadata> getUpdated() {
  130. return updated;
  131. }
  132. /**
  133. * @return a list of conflicts created by this checkout
  134. */
  135. public List<String> getConflicts() {
  136. return conflicts;
  137. }
  138. /**
  139. * @return a list of paths (relative to the start of the working tree) of
  140. * files which couldn't be deleted during last call to
  141. * {@link #checkout()} . {@link #checkout()} detected that these
  142. * files should be deleted but the deletion in the filesystem failed
  143. * (e.g. because a file was locked). To have a consistent state of
  144. * the working tree these files have to be deleted by the callers of
  145. * {@link DirCacheCheckout}.
  146. */
  147. public List<String> getToBeDeleted() {
  148. return toBeDeleted;
  149. }
  150. /**
  151. * @return a list of all files removed by this checkout
  152. */
  153. public List<String> getRemoved() {
  154. return removed;
  155. }
  156. /**
  157. * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
  158. * and mergeCommitTree) and the index.
  159. *
  160. * @param repo
  161. * the repository in which we do the checkout
  162. * @param headCommitTree
  163. * the id of the tree of the head commit
  164. * @param dc
  165. * the (already locked) Dircache for this repo
  166. * @param mergeCommitTree
  167. * the id of the tree we want to fast-forward to
  168. * @param workingTree
  169. * an iterator over the repositories Working Tree
  170. * @throws IOException
  171. */
  172. public DirCacheCheckout(Repository repo, ObjectId headCommitTree, DirCache dc,
  173. ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
  174. throws IOException {
  175. this.repo = repo;
  176. this.dc = dc;
  177. this.headCommitTree = headCommitTree;
  178. this.mergeCommitTree = mergeCommitTree;
  179. this.workingTree = workingTree;
  180. this.emptyDirCache = (dc == null) || (dc.getEntryCount() == 0);
  181. }
  182. /**
  183. * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
  184. * and mergeCommitTree) and the index. As iterator over the working tree
  185. * this constructor creates a standard {@link FileTreeIterator}
  186. *
  187. * @param repo
  188. * the repository in which we do the checkout
  189. * @param headCommitTree
  190. * the id of the tree of the head commit
  191. * @param dc
  192. * the (already locked) Dircache for this repo
  193. * @param mergeCommitTree
  194. * the id of the tree we want to fast-forward to
  195. * @throws IOException
  196. */
  197. public DirCacheCheckout(Repository repo, ObjectId headCommitTree,
  198. DirCache dc, ObjectId mergeCommitTree) throws IOException {
  199. this(repo, headCommitTree, dc, mergeCommitTree, new FileTreeIterator(repo));
  200. }
  201. /**
  202. * Constructs a DirCacheCeckout for checking out one tree, merging with the
  203. * index.
  204. *
  205. * @param repo
  206. * the repository in which we do the checkout
  207. * @param dc
  208. * the (already locked) Dircache for this repo
  209. * @param mergeCommitTree
  210. * the id of the tree we want to fast-forward to
  211. * @param workingTree
  212. * an iterator over the repositories Working Tree
  213. * @throws IOException
  214. */
  215. public DirCacheCheckout(Repository repo, DirCache dc,
  216. ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
  217. throws IOException {
  218. this(repo, null, dc, mergeCommitTree, workingTree);
  219. }
  220. /**
  221. * Constructs a DirCacheCeckout for checking out one tree, merging with the
  222. * index. As iterator over the working tree this constructor creates a
  223. * standard {@link FileTreeIterator}
  224. *
  225. * @param repo
  226. * the repository in which we do the checkout
  227. * @param dc
  228. * the (already locked) Dircache for this repo
  229. * @param mergeCommitTree
  230. * the id of the tree of the
  231. * @throws IOException
  232. */
  233. public DirCacheCheckout(Repository repo, DirCache dc,
  234. ObjectId mergeCommitTree) throws IOException {
  235. this(repo, null, dc, mergeCommitTree, new FileTreeIterator(repo));
  236. }
  237. /**
  238. * Scan head, index and merge tree. Used during normal checkout or merge
  239. * operations.
  240. *
  241. * @throws CorruptObjectException
  242. * @throws IOException
  243. */
  244. public void preScanTwoTrees() throws CorruptObjectException, IOException {
  245. removed.clear();
  246. updated.clear();
  247. conflicts.clear();
  248. walk = new NameConflictTreeWalk(repo);
  249. builder = dc.builder();
  250. addTree(walk, headCommitTree);
  251. addTree(walk, mergeCommitTree);
  252. int dciPos = walk.addTree(new DirCacheBuildIterator(builder));
  253. walk.addTree(workingTree);
  254. workingTree.setDirCacheIterator(walk, dciPos);
  255. while (walk.next()) {
  256. processEntry(walk.getTree(0, CanonicalTreeParser.class),
  257. walk.getTree(1, CanonicalTreeParser.class),
  258. walk.getTree(2, DirCacheBuildIterator.class),
  259. walk.getTree(3, WorkingTreeIterator.class));
  260. if (walk.isSubtree())
  261. walk.enterSubtree();
  262. }
  263. }
  264. private void addTree(TreeWalk tw, ObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException {
  265. if (id == null)
  266. tw.addTree(new EmptyTreeIterator());
  267. else
  268. tw.addTree(id);
  269. }
  270. /**
  271. * Scan index and merge tree (no HEAD). Used e.g. for initial checkout when
  272. * there is no head yet.
  273. *
  274. * @throws MissingObjectException
  275. * @throws IncorrectObjectTypeException
  276. * @throws CorruptObjectException
  277. * @throws IOException
  278. */
  279. public void prescanOneTree()
  280. throws MissingObjectException, IncorrectObjectTypeException,
  281. CorruptObjectException, IOException {
  282. removed.clear();
  283. updated.clear();
  284. conflicts.clear();
  285. builder = dc.builder();
  286. walk = new NameConflictTreeWalk(repo);
  287. addTree(walk, mergeCommitTree);
  288. int dciPos = walk.addTree(new DirCacheBuildIterator(builder));
  289. walk.addTree(workingTree);
  290. workingTree.setDirCacheIterator(walk, dciPos);
  291. while (walk.next()) {
  292. processEntry(walk.getTree(0, CanonicalTreeParser.class),
  293. walk.getTree(1, DirCacheBuildIterator.class),
  294. walk.getTree(2, WorkingTreeIterator.class));
  295. if (walk.isSubtree())
  296. walk.enterSubtree();
  297. }
  298. conflicts.removeAll(removed);
  299. }
  300. /**
  301. * Processing an entry in the context of {@link #prescanOneTree()} when only
  302. * one tree is given
  303. *
  304. * @param m the tree to merge
  305. * @param i the index
  306. * @param f the working tree
  307. * @throws IOException
  308. */
  309. void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i,
  310. WorkingTreeIterator f) throws IOException {
  311. if (m != null) {
  312. checkValidPath(m);
  313. // There is an entry in the merge commit. Means: we want to update
  314. // what's currently in the index and working-tree to that one
  315. if (i == null) {
  316. // The index entry is missing
  317. if (f != null && !FileMode.TREE.equals(f.getEntryFileMode())
  318. && !f.isEntryIgnored()) {
  319. if (failOnConflict) {
  320. // don't overwrite an untracked and not ignored file
  321. conflicts.add(walk.getPathString());
  322. } else {
  323. // failOnConflict is false. Putting something to conflicts
  324. // would mean we delete it. Instead we want the mergeCommit
  325. // content to be checked out.
  326. update(m.getEntryPathString(), m.getEntryObjectId(),
  327. m.getEntryFileMode());
  328. }
  329. } else
  330. update(m.getEntryPathString(), m.getEntryObjectId(),
  331. m.getEntryFileMode());
  332. } else if (f == null || !m.idEqual(i)) {
  333. // The working tree file is missing or the merge content differs
  334. // from index content
  335. update(m.getEntryPathString(), m.getEntryObjectId(),
  336. m.getEntryFileMode());
  337. } else if (i.getDirCacheEntry() != null) {
  338. // The index contains a file (and not a folder)
  339. if (f.isModified(i.getDirCacheEntry(), true,
  340. this.walk.getObjectReader())
  341. || i.getDirCacheEntry().getStage() != 0)
  342. // The working tree file is dirty or the index contains a
  343. // conflict
  344. update(m.getEntryPathString(), m.getEntryObjectId(),
  345. m.getEntryFileMode());
  346. else {
  347. // update the timestamp of the index with the one from the
  348. // file if not set, as we are sure to be in sync here.
  349. DirCacheEntry entry = i.getDirCacheEntry();
  350. if (entry.getLastModified() == 0)
  351. entry.setLastModified(f.getEntryLastModified());
  352. keep(entry);
  353. }
  354. } else
  355. // The index contains a folder
  356. keep(i.getDirCacheEntry());
  357. } else {
  358. // There is no entry in the merge commit. Means: we want to delete
  359. // what's currently in the index and working tree
  360. if (f != null) {
  361. // There is a file/folder for that path in the working tree
  362. if (walk.isDirectoryFileConflict()) {
  363. // We put it in conflicts. Even if failOnConflict is false
  364. // this would cause the path to be deleted. Thats exactly what
  365. // we want in this situation
  366. conflicts.add(walk.getPathString());
  367. } else {
  368. // No file/folder conflict exists. All entries are files or
  369. // all entries are folders
  370. if (i != null) {
  371. // ... and the working tree contained a file or folder
  372. // -> add it to the removed set and remove it from
  373. // conflicts set
  374. remove(i.getEntryPathString());
  375. conflicts.remove(i.getEntryPathString());
  376. } else {
  377. // untracked file, neither contained in tree to merge
  378. // nor in index
  379. }
  380. }
  381. } else {
  382. // There is no file/folder for that path in the working tree,
  383. // nor in the merge head.
  384. // The only entry we have is the index entry. Like the case
  385. // where there is a file with the same name, remove it,
  386. }
  387. }
  388. }
  389. /**
  390. * Execute this checkout
  391. *
  392. * @return <code>false</code> if this method could not delete all the files
  393. * which should be deleted (e.g. because of of the files was
  394. * locked). In this case {@link #getToBeDeleted()} lists the files
  395. * which should be tried to be deleted outside of this method.
  396. * Although <code>false</code> is returned the checkout was
  397. * successful and the working tree was updated for all other files.
  398. * <code>true</code> is returned when no such problem occurred
  399. *
  400. * @throws IOException
  401. */
  402. public boolean checkout() throws IOException {
  403. try {
  404. return doCheckout();
  405. } finally {
  406. dc.unlock();
  407. }
  408. }
  409. private boolean doCheckout() throws CorruptObjectException, IOException,
  410. MissingObjectException, IncorrectObjectTypeException,
  411. CheckoutConflictException, IndexWriteException {
  412. toBeDeleted.clear();
  413. try (ObjectReader objectReader = repo.getObjectDatabase().newReader()) {
  414. if (headCommitTree != null)
  415. preScanTwoTrees();
  416. else
  417. prescanOneTree();
  418. if (!conflicts.isEmpty()) {
  419. if (failOnConflict)
  420. throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]));
  421. else
  422. cleanUpConflicts();
  423. }
  424. // update our index
  425. builder.finish();
  426. File file = null;
  427. String last = null;
  428. // when deleting files process them in the opposite order as they have
  429. // been reported. This ensures the files are deleted before we delete
  430. // their parent folders
  431. for (int i = removed.size() - 1; i >= 0; i--) {
  432. String r = removed.get(i);
  433. file = new File(repo.getWorkTree(), r);
  434. if (!file.delete() && repo.getFS().exists(file)) {
  435. // The list of stuff to delete comes from the index
  436. // which will only contain a directory if it is
  437. // a submodule, in which case we shall not attempt
  438. // to delete it. A submodule is not empty, so it
  439. // is safe to check this after a failed delete.
  440. if (!repo.getFS().isDirectory(file))
  441. toBeDeleted.add(r);
  442. } else {
  443. if (last != null && !isSamePrefix(r, last))
  444. removeEmptyParents(new File(repo.getWorkTree(), last));
  445. last = r;
  446. }
  447. }
  448. if (file != null)
  449. removeEmptyParents(file);
  450. for (Map.Entry<String, CheckoutMetadata> e : updated.entrySet()) {
  451. String path = e.getKey();
  452. CheckoutMetadata meta = e.getValue();
  453. DirCacheEntry entry = dc.getEntry(path);
  454. if (!FileMode.GITLINK.equals(entry.getRawMode()))
  455. checkoutEntry(repo, entry, objectReader, false, meta);
  456. }
  457. // commit the index builder - a new index is persisted
  458. if (!builder.commit())
  459. throw new IndexWriteException();
  460. }
  461. return toBeDeleted.size() == 0;
  462. }
  463. private static boolean isSamePrefix(String a, String b) {
  464. int as = a.lastIndexOf('/');
  465. int bs = b.lastIndexOf('/');
  466. return a.substring(0, as + 1).equals(b.substring(0, bs + 1));
  467. }
  468. private void removeEmptyParents(File f) {
  469. File parentFile = f.getParentFile();
  470. while (parentFile != null && !parentFile.equals(repo.getWorkTree())) {
  471. if (!parentFile.delete())
  472. break;
  473. parentFile = parentFile.getParentFile();
  474. }
  475. }
  476. /**
  477. * Compares whether two pairs of ObjectId and FileMode are equal.
  478. *
  479. * @param id1
  480. * @param mode1
  481. * @param id2
  482. * @param mode2
  483. * @return <code>true</code> if FileModes and ObjectIds are equal.
  484. * <code>false</code> otherwise
  485. */
  486. private boolean equalIdAndMode(ObjectId id1, FileMode mode1, ObjectId id2,
  487. FileMode mode2) {
  488. if (!mode1.equals(mode2))
  489. return false;
  490. return id1 != null ? id1.equals(id2) : id2 == null;
  491. }
  492. /**
  493. * Here the main work is done. This method is called for each existing path
  494. * in head, index and merge. This method decides what to do with the
  495. * corresponding index entry: keep it, update it, remove it or mark a
  496. * conflict.
  497. *
  498. * @param h
  499. * the entry for the head
  500. * @param m
  501. * the entry for the merge
  502. * @param i
  503. * the entry for the index
  504. * @param f
  505. * the file in the working tree
  506. * @throws IOException
  507. */
  508. void processEntry(CanonicalTreeParser h, CanonicalTreeParser m,
  509. DirCacheBuildIterator i, WorkingTreeIterator f) throws IOException {
  510. DirCacheEntry dce = i != null ? i.getDirCacheEntry() : null;
  511. String name = walk.getPathString();
  512. if (m != null)
  513. checkValidPath(m);
  514. if (i == null && m == null && h == null) {
  515. // File/Directory conflict case #20
  516. if (walk.isDirectoryFileConflict())
  517. // TODO: check whether it is always correct to report a conflict here
  518. conflict(name, null, null, null);
  519. // file only exists in working tree -> ignore it
  520. return;
  521. }
  522. ObjectId iId = (i == null ? null : i.getEntryObjectId());
  523. ObjectId mId = (m == null ? null : m.getEntryObjectId());
  524. ObjectId hId = (h == null ? null : h.getEntryObjectId());
  525. FileMode iMode = (i == null ? null : i.getEntryFileMode());
  526. FileMode mMode = (m == null ? null : m.getEntryFileMode());
  527. FileMode hMode = (h == null ? null : h.getEntryFileMode());
  528. /**
  529. * <pre>
  530. * File/Directory conflicts:
  531. * the following table from ReadTreeTest tells what to do in case of directory/file
  532. * conflicts. I give comments here
  533. *
  534. * H I M Clean H==M H==I I==M Result
  535. * ------------------------------------------------------------------
  536. * 1 D D F Y N Y N Update
  537. * 2 D D F N N Y N Conflict
  538. * 3 D F D Y N N Keep
  539. * 4 D F D N N N Conflict
  540. * 5 D F F Y N N Y Keep
  541. * 5b D F F Y N N N Conflict
  542. * 6 D F F N N N Y Keep
  543. * 6b D F F N N N N Conflict
  544. * 7 F D F Y Y N N Update
  545. * 8 F D F N Y N N Conflict
  546. * 9 F D F N N N Conflict
  547. * 10 F D D N N Y Keep
  548. * 11 F D D N N N Conflict
  549. * 12 F F D Y N Y N Update
  550. * 13 F F D N N Y N Conflict
  551. * 14 F F D N N N Conflict
  552. * 15 0 F D N N N Conflict
  553. * 16 0 D F Y N N N Update
  554. * 17 0 D F N N N Conflict
  555. * 18 F 0 D Update
  556. * 19 D 0 F Update
  557. * 20 0 0 F N (worktree=dir) Conflict
  558. * </pre>
  559. */
  560. // The information whether head,index,merge iterators are currently
  561. // pointing to file/folder/non-existing is encoded into this variable.
  562. //
  563. // To decode write down ffMask in hexadecimal form. The last digit
  564. // represents the state for the merge iterator, the second last the
  565. // state for the index iterator and the third last represents the state
  566. // for the head iterator. The hexadecimal constant "F" stands for
  567. // "file", a "D" stands for "directory" (tree), and a "0" stands for
  568. // non-existing. Symbolic links and git links are treated as File here.
  569. //
  570. // Examples:
  571. // ffMask == 0xFFD -> Head=File, Index=File, Merge=Tree
  572. // ffMask == 0xDD0 -> Head=Tree, Index=Tree, Merge=Non-Existing
  573. int ffMask = 0;
  574. if (h != null)
  575. ffMask = FileMode.TREE.equals(hMode) ? 0xD00 : 0xF00;
  576. if (i != null)
  577. ffMask |= FileMode.TREE.equals(iMode) ? 0x0D0 : 0x0F0;
  578. if (m != null)
  579. ffMask |= FileMode.TREE.equals(mMode) ? 0x00D : 0x00F;
  580. // Check whether we have a possible file/folder conflict. Therefore we
  581. // need a least one file and one folder.
  582. if (((ffMask & 0x222) != 0x000)
  583. && (((ffMask & 0x00F) == 0x00D) || ((ffMask & 0x0F0) == 0x0D0) || ((ffMask & 0xF00) == 0xD00))) {
  584. // There are 3*3*3=27 possible combinations of file/folder
  585. // conflicts. Some of them are not-relevant because
  586. // they represent no conflict, e.g. 0xFFF, 0xDDD, ... The following
  587. // switch processes all relevant cases.
  588. switch (ffMask) {
  589. case 0xDDF: // 1 2
  590. if (f != null && isModifiedSubtree_IndexWorkingtree(name)) {
  591. conflict(name, dce, h, m); // 1
  592. } else {
  593. update(name, mId, mMode); // 2
  594. }
  595. break;
  596. case 0xDFD: // 3 4
  597. keep(dce);
  598. break;
  599. case 0xF0D: // 18
  600. remove(name);
  601. break;
  602. case 0xDFF: // 5 5b 6 6b
  603. if (equalIdAndMode(iId, iMode, mId, mMode))
  604. keep(dce); // 5 6
  605. else
  606. conflict(name, dce, h, m); // 5b 6b
  607. break;
  608. case 0xFDD: // 10 11
  609. // TODO: make use of tree extension as soon as available in jgit
  610. // we would like to do something like
  611. // if (!equalIdAndMode(iId, iMode, mId, mMode)
  612. // conflict(name, i.getDirCacheEntry(), h, m);
  613. // But since we don't know the id of a tree in the index we do
  614. // nothing here and wait that conflicts between index and merge
  615. // are found later
  616. break;
  617. case 0xD0F: // 19
  618. update(name, mId, mMode);
  619. break;
  620. case 0xDF0: // conflict without a rule
  621. case 0x0FD: // 15
  622. conflict(name, dce, h, m);
  623. break;
  624. case 0xFDF: // 7 8 9
  625. if (equalIdAndMode(hId, hMode, mId, mMode)) {
  626. if (isModifiedSubtree_IndexWorkingtree(name))
  627. conflict(name, dce, h, m); // 8
  628. else
  629. update(name, mId, mMode); // 7
  630. } else
  631. conflict(name, dce, h, m); // 9
  632. break;
  633. case 0xFD0: // keep without a rule
  634. keep(dce);
  635. break;
  636. case 0xFFD: // 12 13 14
  637. if (equalIdAndMode(hId, hMode, iId, iMode))
  638. if (f != null
  639. && f.isModified(dce, true,
  640. this.walk.getObjectReader()))
  641. conflict(name, dce, h, m); // 13
  642. else
  643. remove(name); // 12
  644. else
  645. conflict(name, dce, h, m); // 14
  646. break;
  647. case 0x0DF: // 16 17
  648. if (!isModifiedSubtree_IndexWorkingtree(name))
  649. update(name, mId, mMode);
  650. else
  651. conflict(name, dce, h, m);
  652. break;
  653. default:
  654. keep(dce);
  655. }
  656. return;
  657. }
  658. if ((ffMask & 0x222) == 0) {
  659. // HEAD, MERGE and index don't contain a file (e.g. all contain a
  660. // folder)
  661. if (f == null || FileMode.TREE.equals(f.getEntryFileMode())) {
  662. // the workingtree entry doesn't exist or also contains a folder
  663. // -> no problem
  664. return;
  665. } else {
  666. // the workingtree entry exists and is not a folder
  667. if (!idEqual(h, m)) {
  668. // Because HEAD and MERGE differ we will try to update the
  669. // workingtree with a folder -> return a conflict
  670. conflict(name, null, null, null);
  671. }
  672. return;
  673. }
  674. }
  675. if ((ffMask == 0x00F) && f != null && FileMode.TREE.equals(f.getEntryFileMode())) {
  676. // File/Directory conflict case #20
  677. conflict(name, null, h, m);
  678. return;
  679. }
  680. if (i == null) {
  681. // Nothing in Index
  682. // At least one of Head, Index, Merge is not empty
  683. // make sure not to overwrite untracked files
  684. if (f != null && !f.isEntryIgnored()) {
  685. // A submodule is not a file. We should ignore it
  686. if (!FileMode.GITLINK.equals(mMode)) {
  687. // a dirty worktree: the index is empty but we have a
  688. // workingtree-file
  689. if (mId == null
  690. || !equalIdAndMode(mId, mMode,
  691. f.getEntryObjectId(), f.getEntryFileMode())) {
  692. conflict(name, null, h, m);
  693. return;
  694. }
  695. }
  696. }
  697. /**
  698. * <pre>
  699. * I (index) H M H==M Result
  700. * -------------------------------------------
  701. * 0 nothing nothing nothing (does not happen)
  702. * 1 nothing nothing exists use M
  703. * 2 nothing exists nothing remove path from index
  704. * 3 nothing exists exists yes keep index if not in initial checkout
  705. * , otherwise use M
  706. * nothing exists exists no fail
  707. * </pre>
  708. */
  709. if (h == null)
  710. // Nothing in Head
  711. // Nothing in Index
  712. // At least one of Head, Index, Merge is not empty
  713. // -> only Merge contains something for this path. Use it!
  714. // Potentially update the file
  715. update(name, mId, mMode); // 1
  716. else if (m == null)
  717. // Nothing in Merge
  718. // Something in Head
  719. // Nothing in Index
  720. // -> only Head contains something for this path and it should
  721. // be deleted. Potentially removes the file!
  722. remove(name); // 2
  723. else { // 3
  724. // Something in Merge
  725. // Something in Head
  726. // Nothing in Index
  727. // -> Head and Merge contain something (maybe not the same) and
  728. // in the index there is nothing (e.g. 'git rm ...' was
  729. // called before). Ignore the cached deletion and use what we
  730. // find in Merge. Potentially updates the file.
  731. if (equalIdAndMode(hId, hMode, mId, mMode)) {
  732. if (emptyDirCache)
  733. update(name, mId, mMode);
  734. else
  735. keep(dce);
  736. } else
  737. conflict(name, dce, h, m);
  738. }
  739. } else {
  740. // Something in Index
  741. if (h == null) {
  742. // Nothing in Head
  743. // Something in Index
  744. /**
  745. * <pre>
  746. * clean I==H I==M H M Result
  747. * -----------------------------------------------------
  748. * 4 yes N/A N/A nothing nothing keep index
  749. * 5 no N/A N/A nothing nothing keep index
  750. *
  751. * 6 yes N/A yes nothing exists keep index
  752. * 7 no N/A yes nothing exists keep index
  753. * 8 yes N/A no nothing exists fail
  754. * 9 no N/A no nothing exists fail
  755. * </pre>
  756. */
  757. if (m == null
  758. || !isModified_IndexTree(name, iId, iMode, mId, mMode,
  759. mergeCommitTree)) {
  760. // Merge contains nothing or the same as Index
  761. // Nothing in Head
  762. // Something in Index
  763. if (m==null && walk.isDirectoryFileConflict()) {
  764. // Nothing in Merge and current path is part of
  765. // File/Folder conflict
  766. // Nothing in Head
  767. // Something in Index
  768. if (dce != null
  769. && (f == null || f.isModified(dce, true,
  770. this.walk.getObjectReader())))
  771. // No file or file is dirty
  772. // Nothing in Merge and current path is part of
  773. // File/Folder conflict
  774. // Nothing in Head
  775. // Something in Index
  776. // -> File folder conflict and Merge wants this
  777. // path to be removed. Since the file is dirty
  778. // report a conflict
  779. conflict(name, dce, h, m);
  780. else
  781. // A file is present and file is not dirty
  782. // Nothing in Merge and current path is part of
  783. // File/Folder conflict
  784. // Nothing in Head
  785. // Something in Index
  786. // -> File folder conflict and Merge wants this path
  787. // to be removed. Since the file is not dirty remove
  788. // file and index entry
  789. remove(name);
  790. } else
  791. // Something in Merge or current path is not part of
  792. // File/Folder conflict
  793. // Merge contains nothing or the same as Index
  794. // Nothing in Head
  795. // Something in Index
  796. // -> Merge contains nothing new. Keep the index.
  797. keep(dce);
  798. } else
  799. // Merge contains something and it is not the same as Index
  800. // Nothing in Head
  801. // Something in Index
  802. // -> Index contains something new (different from Head)
  803. // and Merge is different from Index. Report a conflict
  804. conflict(name, dce, h, m);
  805. } else if (m == null) {
  806. // Nothing in Merge
  807. // Something in Head
  808. // Something in Index
  809. /**
  810. * <pre>
  811. * clean I==H I==M H M Result
  812. * -----------------------------------------------------
  813. * 10 yes yes N/A exists nothing remove path from index
  814. * 11 no yes N/A exists nothing keep file
  815. * 12 yes no N/A exists nothing fail
  816. * 13 no no N/A exists nothing fail
  817. * </pre>
  818. */
  819. if (iMode == FileMode.GITLINK) {
  820. // A submodule in Index
  821. // Nothing in Merge
  822. // Something in Head
  823. // Submodules that disappear from the checkout must
  824. // be removed from the index, but not deleted from disk.
  825. remove(name);
  826. } else {
  827. // Something different from a submodule in Index
  828. // Nothing in Merge
  829. // Something in Head
  830. if (!isModified_IndexTree(name, iId, iMode, hId, hMode,
  831. headCommitTree)) {
  832. // Index contains the same as Head
  833. // Something different from a submodule in Index
  834. // Nothing in Merge
  835. // Something in Head
  836. if (f != null
  837. && f.isModified(dce, true,
  838. this.walk.getObjectReader())) {
  839. // file is dirty
  840. // Index contains the same as Head
  841. // Something different from a submodule in Index
  842. // Nothing in Merge
  843. // Something in Head
  844. if (!FileMode.TREE.equals(f.getEntryFileMode())
  845. && FileMode.TREE.equals(iMode))
  846. // The workingtree contains a file and the index semantically contains a folder.
  847. // Git considers the workingtree file as untracked. Just keep the untracked file.
  848. return;
  849. else
  850. // -> file is dirty and tracked but is should be
  851. // removed. That's a conflict
  852. conflict(name, dce, h, m);
  853. } else
  854. // file doesn't exist or is clean
  855. // Index contains the same as Head
  856. // Something different from a submodule in Index
  857. // Nothing in Merge
  858. // Something in Head
  859. // -> Remove from index and delete the file
  860. remove(name);
  861. } else
  862. // Index contains something different from Head
  863. // Something different from a submodule in Index
  864. // Nothing in Merge
  865. // Something in Head
  866. // -> Something new is in index (and maybe even on the
  867. // filesystem). But Merge wants the path to be removed.
  868. // Report a conflict
  869. conflict(name, dce, h, m);
  870. }
  871. } else {
  872. // Something in Merge
  873. // Something in Head
  874. // Something in Index
  875. if (!equalIdAndMode(hId, hMode, mId, mMode)
  876. && isModified_IndexTree(name, iId, iMode, hId, hMode,
  877. headCommitTree)
  878. && isModified_IndexTree(name, iId, iMode, mId, mMode,
  879. mergeCommitTree))
  880. // All three contents in Head, Merge, Index differ from each
  881. // other
  882. // -> All contents differ. Report a conflict.
  883. conflict(name, dce, h, m);
  884. else
  885. // At least two of the contents of Head, Index, Merge
  886. // are the same
  887. // Something in Merge
  888. // Something in Head
  889. // Something in Index
  890. if (!isModified_IndexTree(name, iId, iMode, hId, hMode,
  891. headCommitTree)
  892. && isModified_IndexTree(name, iId, iMode, mId, mMode,
  893. mergeCommitTree)) {
  894. // Head contains the same as Index. Merge differs
  895. // Something in Merge
  896. // For submodules just update the index with the new SHA-1
  897. if (dce != null
  898. && FileMode.GITLINK.equals(dce.getFileMode())) {
  899. // Index and Head contain the same submodule. Merge
  900. // differs
  901. // Something in Merge
  902. // -> Nothing new in index. Move to merge.
  903. // Potentially updates the file
  904. // TODO check that we don't overwrite some unsaved
  905. // file content
  906. update(name, mId, mMode);
  907. } else if (dce != null
  908. && (f != null && f.isModified(dce, true,
  909. this.walk.getObjectReader()))) {
  910. // File exists and is dirty
  911. // Head and Index don't contain a submodule
  912. // Head contains the same as Index. Merge differs
  913. // Something in Merge
  914. // -> Merge wants the index and file to be updated
  915. // but the file is dirty. Report a conflict
  916. conflict(name, dce, h, m);
  917. } else {
  918. // File doesn't exist or is clean
  919. // Head and Index don't contain a submodule
  920. // Head contains the same as Index. Merge differs
  921. // Something in Merge
  922. // -> Standard case when switching between branches:
  923. // Nothing new in index but something different in
  924. // Merge. Update index and file
  925. update(name, mId, mMode);
  926. }
  927. } else {
  928. // Head differs from index or merge is same as index
  929. // At least two of the contents of Head, Index, Merge
  930. // are the same
  931. // Something in Merge
  932. // Something in Head
  933. // Something in Index
  934. // Can be formulated as: Either all three states are
  935. // equal or Merge is equal to Head or Index and differs
  936. // to the other one.
  937. // -> In all three cases we don't touch index and file.
  938. keep(dce);
  939. }
  940. }
  941. }
  942. }
  943. private static boolean idEqual(AbstractTreeIterator a,
  944. AbstractTreeIterator b) {
  945. if (a == b) {
  946. return true;
  947. }
  948. if (a == null || b == null) {
  949. return false;
  950. }
  951. return a.getEntryObjectId().equals(b.getEntryObjectId());
  952. }
  953. /**
  954. * A conflict is detected - add the three different stages to the index
  955. * @param path the path of the conflicting entry
  956. * @param e the previous index entry
  957. * @param h the first tree you want to merge (the HEAD)
  958. * @param m the second tree you want to merge
  959. */
  960. private void conflict(String path, DirCacheEntry e, AbstractTreeIterator h, AbstractTreeIterator m) {
  961. conflicts.add(path);
  962. DirCacheEntry entry;
  963. if (e != null) {
  964. entry = new DirCacheEntry(e.getPathString(), DirCacheEntry.STAGE_1);
  965. entry.copyMetaData(e, true);
  966. builder.add(entry);
  967. }
  968. if (h != null && !FileMode.TREE.equals(h.getEntryFileMode())) {
  969. entry = new DirCacheEntry(h.getEntryPathString(), DirCacheEntry.STAGE_2);
  970. entry.setFileMode(h.getEntryFileMode());
  971. entry.setObjectId(h.getEntryObjectId());
  972. builder.add(entry);
  973. }
  974. if (m != null && !FileMode.TREE.equals(m.getEntryFileMode())) {
  975. entry = new DirCacheEntry(m.getEntryPathString(), DirCacheEntry.STAGE_3);
  976. entry.setFileMode(m.getEntryFileMode());
  977. entry.setObjectId(m.getEntryObjectId());
  978. builder.add(entry);
  979. }
  980. }
  981. private void keep(DirCacheEntry e) {
  982. if (e != null && !FileMode.TREE.equals(e.getFileMode()))
  983. builder.add(e);
  984. }
  985. private void remove(String path) {
  986. removed.add(path);
  987. }
  988. private void update(String path, ObjectId mId, FileMode mode)
  989. throws IOException {
  990. if (!FileMode.TREE.equals(mode)) {
  991. updated.put(path, new CheckoutMetadata(walk.getEolStreamType(),
  992. walk.getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE)));
  993. DirCacheEntry entry = new DirCacheEntry(path, DirCacheEntry.STAGE_0);
  994. entry.setObjectId(mId);
  995. entry.setFileMode(mode);
  996. builder.add(entry);
  997. }
  998. }
  999. /**
  1000. * If <code>true</code>, will scan first to see if it's possible to check
  1001. * out, otherwise throw {@link CheckoutConflictException}. If
  1002. * <code>false</code>, it will silently deal with the problem.
  1003. *
  1004. * @param failOnConflict
  1005. */
  1006. public void setFailOnConflict(boolean failOnConflict) {
  1007. this.failOnConflict = failOnConflict;
  1008. }
  1009. /**
  1010. * This method implements how to handle conflicts when
  1011. * {@link #failOnConflict} is false
  1012. *
  1013. * @throws CheckoutConflictException
  1014. */
  1015. private void cleanUpConflicts() throws CheckoutConflictException {
  1016. // TODO: couldn't we delete unsaved worktree content here?
  1017. for (String c : conflicts) {
  1018. File conflict = new File(repo.getWorkTree(), c);
  1019. if (!conflict.delete())
  1020. throw new CheckoutConflictException(MessageFormat.format(
  1021. JGitText.get().cannotDeleteFile, c));
  1022. removeEmptyParents(conflict);
  1023. }
  1024. for (String r : removed) {
  1025. File file = new File(repo.getWorkTree(), r);
  1026. if (!file.delete())
  1027. throw new CheckoutConflictException(
  1028. MessageFormat.format(JGitText.get().cannotDeleteFile,
  1029. file.getAbsolutePath()));
  1030. removeEmptyParents(file);
  1031. }
  1032. }
  1033. /**
  1034. * Checks whether the subtree starting at a given path differs between Index and
  1035. * workingtree.
  1036. *
  1037. * @param path
  1038. * @return true if the subtrees differ
  1039. * @throws CorruptObjectException
  1040. * @throws IOException
  1041. */
  1042. private boolean isModifiedSubtree_IndexWorkingtree(String path)
  1043. throws CorruptObjectException, IOException {
  1044. try (NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
  1045. int dciPos = tw.addTree(new DirCacheIterator(dc));
  1046. FileTreeIterator fti = new FileTreeIterator(repo);
  1047. tw.addTree(fti);
  1048. fti.setDirCacheIterator(tw, dciPos);
  1049. tw.setRecursive(true);
  1050. tw.setFilter(PathFilter.create(path));
  1051. DirCacheIterator dcIt;
  1052. WorkingTreeIterator wtIt;
  1053. while (tw.next()) {
  1054. dcIt = tw.getTree(0, DirCacheIterator.class);
  1055. wtIt = tw.getTree(1, WorkingTreeIterator.class);
  1056. if (dcIt == null || wtIt == null)
  1057. return true;
  1058. if (wtIt.isModified(dcIt.getDirCacheEntry(), true,
  1059. this.walk.getObjectReader())) {
  1060. return true;
  1061. }
  1062. }
  1063. return false;
  1064. }
  1065. }
  1066. private boolean isModified_IndexTree(String path, ObjectId iId,
  1067. FileMode iMode, ObjectId tId, FileMode tMode, ObjectId rootTree)
  1068. throws CorruptObjectException, IOException {
  1069. if (iMode != tMode)
  1070. return true;
  1071. if (FileMode.TREE.equals(iMode)
  1072. && (iId == null || ObjectId.zeroId().equals(iId)))
  1073. return isModifiedSubtree_IndexTree(path, rootTree);
  1074. else
  1075. return !equalIdAndMode(iId, iMode, tId, tMode);
  1076. }
  1077. /**
  1078. * Checks whether the subtree starting at a given path differs between Index and
  1079. * some tree.
  1080. *
  1081. * @param path
  1082. * @param tree
  1083. * the tree to compare
  1084. * @return true if the subtrees differ
  1085. * @throws CorruptObjectException
  1086. * @throws IOException
  1087. */
  1088. private boolean isModifiedSubtree_IndexTree(String path, ObjectId tree)
  1089. throws CorruptObjectException, IOException {
  1090. try (NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
  1091. tw.addTree(new DirCacheIterator(dc));
  1092. tw.addTree(tree);
  1093. tw.setRecursive(true);
  1094. tw.setFilter(PathFilter.create(path));
  1095. while (tw.next()) {
  1096. AbstractTreeIterator dcIt = tw.getTree(0,
  1097. DirCacheIterator.class);
  1098. AbstractTreeIterator treeIt = tw.getTree(1,
  1099. AbstractTreeIterator.class);
  1100. if (dcIt == null || treeIt == null)
  1101. return true;
  1102. if (dcIt.getEntryRawMode() != treeIt.getEntryRawMode())
  1103. return true;
  1104. if (!dcIt.getEntryObjectId().equals(treeIt.getEntryObjectId()))
  1105. return true;
  1106. }
  1107. return false;
  1108. }
  1109. }
  1110. /**
  1111. * Updates the file in the working tree with content and mode from an entry
  1112. * in the index. The new content is first written to a new temporary file in
  1113. * the same directory as the real file. Then that new file is renamed to the
  1114. * final filename.
  1115. *
  1116. * <p>
  1117. * <b>Note:</b> if the entry path on local file system exists as a non-empty
  1118. * directory, and the target entry type is a link or file, the checkout will
  1119. * fail with {@link IOException} since existing non-empty directory cannot
  1120. * be renamed to file or link without deleting it recursively.
  1121. * </p>
  1122. *
  1123. * <p>
  1124. * TODO: this method works directly on File IO, we may need another
  1125. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  1126. * Eclipse that Files in the workspace got changed
  1127. * </p>
  1128. *
  1129. * @param repo
  1130. * repository managing the destination work tree.
  1131. * @param entry
  1132. * the entry containing new mode and content
  1133. * @param or
  1134. * object reader to use for checkout
  1135. * @throws IOException
  1136. * @since 3.6
  1137. */
  1138. public static void checkoutEntry(Repository repo, DirCacheEntry entry,
  1139. ObjectReader or) throws IOException {
  1140. checkoutEntry(repo, entry, or, false, null);
  1141. }
  1142. /**
  1143. * Updates the file in the working tree with content and mode from an entry
  1144. * in the index. The new content is first written to a new temporary file in
  1145. * the same directory as the real file. Then that new file is renamed to the
  1146. * final filename.
  1147. *
  1148. * <p>
  1149. * <b>Note:</b> if the entry path on local file system exists as a file, it
  1150. * will be deleted and if it exists as a directory, it will be deleted
  1151. * recursively, independently if has any content.
  1152. * </p>
  1153. *
  1154. * <p>
  1155. * TODO: this method works directly on File IO, we may need another
  1156. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  1157. * Eclipse that Files in the workspace got changed
  1158. * </p>
  1159. *
  1160. * @param repo
  1161. * repository managing the destination work tree.
  1162. * @param entry
  1163. * the entry containing new mode and content
  1164. * @param or
  1165. * object reader to use for checkout
  1166. * @param deleteRecursive
  1167. * true to recursively delete final path if it exists on the file
  1168. * system
  1169. * @param checkoutMetadata
  1170. * containing
  1171. * <ul>
  1172. * <li>smudgeFilterCommand to be run for smudging the entry to be
  1173. * checked out</li>
  1174. * <li>eolStreamType used for stream conversion</li>
  1175. * </ul>
  1176. *
  1177. * @throws IOException
  1178. * @since 4.2
  1179. */
  1180. public static void checkoutEntry(Repository repo, DirCacheEntry entry,
  1181. ObjectReader or, boolean deleteRecursive,
  1182. CheckoutMetadata checkoutMetadata) throws IOException {
  1183. if (checkoutMetadata == null)
  1184. checkoutMetadata = CheckoutMetadata.EMPTY;
  1185. ObjectLoader ol = or.open(entry.getObjectId());
  1186. File f = new File(repo.getWorkTree(), entry.getPathString());
  1187. File parentDir = f.getParentFile();
  1188. FileUtils.mkdirs(parentDir, true);
  1189. FS fs = repo.getFS();
  1190. WorkingTreeOptions opt = repo.getConfig().get(WorkingTreeOptions.KEY);
  1191. if (entry.getFileMode() == FileMode.SYMLINK
  1192. && opt.getSymLinks() == SymLinks.TRUE) {
  1193. byte[] bytes = ol.getBytes();
  1194. String target = RawParseUtils.decode(bytes);
  1195. if (deleteRecursive && f.isDirectory()) {
  1196. FileUtils.delete(f, FileUtils.RECURSIVE);
  1197. }
  1198. fs.createSymLink(f, target);
  1199. entry.setLength(bytes.length);
  1200. entry.setLastModified(fs.lastModified(f));
  1201. return;
  1202. }
  1203. File tmpFile = File.createTempFile(
  1204. "._" + f.getName(), null, parentDir); //$NON-NLS-1$
  1205. EolStreamType nonNullEolStreamType;
  1206. if (checkoutMetadata.eolStreamType != null) {
  1207. nonNullEolStreamType = checkoutMetadata.eolStreamType;
  1208. } else if (opt.getAutoCRLF() == AutoCRLF.TRUE) {
  1209. nonNullEolStreamType = EolStreamType.AUTO_CRLF;
  1210. } else {
  1211. nonNullEolStreamType = EolStreamType.DIRECT;
  1212. }
  1213. OutputStream channel = EolStreamTypeUtil.wrapOutputStream(
  1214. new FileOutputStream(tmpFile), nonNullEolStreamType);
  1215. if (checkoutMetadata.smudgeFilterCommand != null) {
  1216. ProcessBuilder filterProcessBuilder = fs.runInShell(
  1217. checkoutMetadata.smudgeFilterCommand, new String[0]);
  1218. filterProcessBuilder.directory(repo.getWorkTree());
  1219. filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY,
  1220. repo.getDirectory().getAbsolutePath());
  1221. ExecutionResult result;
  1222. int rc;
  1223. try {
  1224. // TODO: wire correctly with AUTOCRLF
  1225. result = fs.execute(filterProcessBuilder, ol.openStream());
  1226. rc = result.getRc();
  1227. if (rc == 0) {
  1228. result.getStdout().writeTo(channel,
  1229. NullProgressMonitor.INSTANCE);
  1230. }
  1231. } catch (IOException | InterruptedException e) {
  1232. throw new IOException(new FilterFailedException(e,
  1233. checkoutMetadata.smudgeFilterCommand,
  1234. entry.getPathString()));
  1235. } finally {
  1236. channel.close();
  1237. }
  1238. if (rc != 0) {
  1239. throw new IOException(new FilterFailedException(rc,
  1240. checkoutMetadata.smudgeFilterCommand,
  1241. entry.getPathString(),
  1242. result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE),
  1243. RawParseUtils.decode(result.getStderr()
  1244. .toByteArray(MAX_EXCEPTION_TEXT_SIZE))));
  1245. }
  1246. } else {
  1247. try {
  1248. ol.copyTo(channel);
  1249. } finally {
  1250. channel.close();
  1251. }
  1252. }
  1253. // The entry needs to correspond to the on-disk filesize. If the content
  1254. // was filtered (either by autocrlf handling or smudge filters) ask the
  1255. // filesystem again for the length. Otherwise the objectloader knows the
  1256. // size
  1257. if (checkoutMetadata.eolStreamType == EolStreamType.DIRECT
  1258. && checkoutMetadata.smudgeFilterCommand == null) {
  1259. entry.setLength(ol.getSize());
  1260. } else {
  1261. entry.setLength(tmpFile.length());
  1262. }
  1263. if (opt.isFileMode() && fs.supportsExecute()) {
  1264. if (FileMode.EXECUTABLE_FILE.equals(entry.getRawMode())) {
  1265. if (!fs.canExecute(tmpFile))
  1266. fs.setExecute(tmpFile, true);
  1267. } else {
  1268. if (fs.canExecute(tmpFile))
  1269. fs.setExecute(tmpFile, false);
  1270. }
  1271. }
  1272. try {
  1273. if (deleteRecursive && f.isDirectory()) {
  1274. FileUtils.delete(f, FileUtils.RECURSIVE);
  1275. }
  1276. FileUtils.rename(tmpFile, f, StandardCopyOption.ATOMIC_MOVE);
  1277. } catch (IOException e) {
  1278. throw new IOException(
  1279. MessageFormat.format(JGitText.get().renameFileFailed,
  1280. tmpFile.getPath(), f.getPath()),
  1281. e);
  1282. } finally {
  1283. if (tmpFile.exists()) {
  1284. FileUtils.delete(tmpFile);
  1285. }
  1286. }
  1287. entry.setLastModified(fs.lastModified(f));
  1288. }
  1289. @SuppressWarnings("deprecation")
  1290. private static void checkValidPath(CanonicalTreeParser t)
  1291. throws InvalidPathException {
  1292. ObjectChecker chk = new ObjectChecker()
  1293. .setSafeForWindows(SystemReader.getInstance().isWindows())
  1294. .setSafeForMacOS(SystemReader.getInstance().isMacOS());
  1295. for (CanonicalTreeParser i = t; i != null; i = i.getParent())
  1296. checkValidPathSegment(chk, i);
  1297. }
  1298. private static void checkValidPathSegment(ObjectChecker chk,
  1299. CanonicalTreeParser t) throws InvalidPathException {
  1300. try {
  1301. int ptr = t.getNameOffset();
  1302. int end = ptr + t.getNameLength();
  1303. chk.checkPathSegment(t.getEntryPathBuffer(), ptr, end);
  1304. } catch (CorruptObjectException err) {
  1305. String path = t.getEntryPathString();
  1306. InvalidPathException i = new InvalidPathException(path);
  1307. i.initCause(err);
  1308. throw i;
  1309. }
  1310. }
  1311. }