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

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