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.

ResolveMerger.java 43KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. /*
  2. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>,
  3. * Copyright (C) 2010-2012, Matthias Sohn <matthias.sohn@sap.com>
  4. * Copyright (C) 2012, Research In Motion Limited
  5. * Copyright (C) 2017, Obeo (mathieu.cartaud@obeo.fr)
  6. * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch>
  7. * and other copyright owners as documented in the project's IP log.
  8. *
  9. * This program and the accompanying materials are made available
  10. * under the terms of the Eclipse Distribution License v1.0 which
  11. * accompanies this distribution, is reproduced below, and is
  12. * available at 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
  17. * without modification, are permitted provided that the following
  18. * conditions are met:
  19. *
  20. * - Redistributions of source code must retain the above copyright
  21. * notice, this list of conditions and the following disclaimer.
  22. *
  23. * - Redistributions in binary form must reproduce the above
  24. * copyright notice, this list of conditions and the following
  25. * disclaimer in the documentation and/or other materials provided
  26. * with the distribution.
  27. *
  28. * - Neither the name of the Eclipse Foundation, Inc. nor the
  29. * names of its contributors may be used to endorse or promote
  30. * products derived from this software without specific prior
  31. * written permission.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  34. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  35. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  36. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  37. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  38. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  39. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  40. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  41. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  42. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  43. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  44. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  45. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  46. */
  47. package org.eclipse.jgit.merge;
  48. import static java.nio.charset.StandardCharsets.UTF_8;
  49. import static java.time.Instant.EPOCH;
  50. import static org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm.HISTOGRAM;
  51. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_DIFF_SECTION;
  52. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_ALGORITHM;
  53. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  54. import java.io.BufferedOutputStream;
  55. import java.io.File;
  56. import java.io.FileNotFoundException;
  57. import java.io.FileOutputStream;
  58. import java.io.IOException;
  59. import java.io.InputStream;
  60. import java.io.OutputStream;
  61. import java.time.Instant;
  62. import java.util.ArrayList;
  63. import java.util.Arrays;
  64. import java.util.Collections;
  65. import java.util.HashMap;
  66. import java.util.Iterator;
  67. import java.util.LinkedList;
  68. import java.util.List;
  69. import java.util.Map;
  70. import org.eclipse.jgit.attributes.Attributes;
  71. import org.eclipse.jgit.diff.DiffAlgorithm;
  72. import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
  73. import org.eclipse.jgit.diff.RawText;
  74. import org.eclipse.jgit.diff.RawTextComparator;
  75. import org.eclipse.jgit.diff.Sequence;
  76. import org.eclipse.jgit.dircache.DirCache;
  77. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  78. import org.eclipse.jgit.dircache.DirCacheBuilder;
  79. import org.eclipse.jgit.dircache.DirCacheCheckout;
  80. import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata;
  81. import org.eclipse.jgit.dircache.DirCacheEntry;
  82. import org.eclipse.jgit.errors.BinaryBlobException;
  83. import org.eclipse.jgit.errors.CorruptObjectException;
  84. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  85. import org.eclipse.jgit.errors.IndexWriteException;
  86. import org.eclipse.jgit.errors.MissingObjectException;
  87. import org.eclipse.jgit.errors.NoWorkTreeException;
  88. import org.eclipse.jgit.lib.Config;
  89. import org.eclipse.jgit.lib.ConfigConstants;
  90. import org.eclipse.jgit.lib.Constants;
  91. import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
  92. import org.eclipse.jgit.lib.FileMode;
  93. import org.eclipse.jgit.lib.ObjectId;
  94. import org.eclipse.jgit.lib.ObjectInserter;
  95. import org.eclipse.jgit.lib.ObjectLoader;
  96. import org.eclipse.jgit.lib.Repository;
  97. import org.eclipse.jgit.revwalk.RevTree;
  98. import org.eclipse.jgit.storage.pack.PackConfig;
  99. import org.eclipse.jgit.submodule.SubmoduleConflict;
  100. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  101. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  102. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  103. import org.eclipse.jgit.treewalk.TreeWalk;
  104. import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
  105. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  106. import org.eclipse.jgit.treewalk.WorkingTreeOptions;
  107. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  108. import org.eclipse.jgit.util.FS;
  109. import org.eclipse.jgit.util.LfsFactory;
  110. import org.eclipse.jgit.util.LfsFactory.LfsInputStream;
  111. import org.eclipse.jgit.util.TemporaryBuffer;
  112. import org.eclipse.jgit.util.io.EolStreamTypeUtil;
  113. /**
  114. * A three-way merger performing a content-merge if necessary
  115. */
  116. public class ResolveMerger extends ThreeWayMerger {
  117. /**
  118. * If the merge fails (means: not stopped because of unresolved conflicts)
  119. * this enum is used to explain why it failed
  120. */
  121. public enum MergeFailureReason {
  122. /** the merge failed because of a dirty index */
  123. DIRTY_INDEX,
  124. /** the merge failed because of a dirty workingtree */
  125. DIRTY_WORKTREE,
  126. /** the merge failed because of a file could not be deleted */
  127. COULD_NOT_DELETE
  128. }
  129. /**
  130. * The tree walk which we'll iterate over to merge entries.
  131. *
  132. * @since 3.4
  133. */
  134. protected NameConflictTreeWalk tw;
  135. /**
  136. * string versions of a list of commit SHA1s
  137. *
  138. * @since 3.0
  139. */
  140. protected String commitNames[];
  141. /**
  142. * Index of the base tree within the {@link #tw tree walk}.
  143. *
  144. * @since 3.4
  145. */
  146. protected static final int T_BASE = 0;
  147. /**
  148. * Index of our tree in withthe {@link #tw tree walk}.
  149. *
  150. * @since 3.4
  151. */
  152. protected static final int T_OURS = 1;
  153. /**
  154. * Index of their tree within the {@link #tw tree walk}.
  155. *
  156. * @since 3.4
  157. */
  158. protected static final int T_THEIRS = 2;
  159. /**
  160. * Index of the index tree within the {@link #tw tree walk}.
  161. *
  162. * @since 3.4
  163. */
  164. protected static final int T_INDEX = 3;
  165. /**
  166. * Index of the working directory tree within the {@link #tw tree walk}.
  167. *
  168. * @since 3.4
  169. */
  170. protected static final int T_FILE = 4;
  171. /**
  172. * Builder to update the cache during this merge.
  173. *
  174. * @since 3.4
  175. */
  176. protected DirCacheBuilder builder;
  177. /**
  178. * merge result as tree
  179. *
  180. * @since 3.0
  181. */
  182. protected ObjectId resultTree;
  183. /**
  184. * Paths that could not be merged by this merger because of an unsolvable
  185. * conflict.
  186. *
  187. * @since 3.4
  188. */
  189. protected List<String> unmergedPaths = new ArrayList<>();
  190. /**
  191. * Files modified during this merge operation.
  192. *
  193. * @since 3.4
  194. */
  195. protected List<String> modifiedFiles = new LinkedList<>();
  196. /**
  197. * If the merger has nothing to do for a file but check it out at the end of
  198. * the operation, it can be added here.
  199. *
  200. * @since 3.4
  201. */
  202. protected Map<String, DirCacheEntry> toBeCheckedOut = new HashMap<>();
  203. /**
  204. * Paths in this list will be deleted from the local copy at the end of the
  205. * operation.
  206. *
  207. * @since 3.4
  208. */
  209. protected List<String> toBeDeleted = new ArrayList<>();
  210. /**
  211. * Low-level textual merge results. Will be passed on to the callers in case
  212. * of conflicts.
  213. *
  214. * @since 3.4
  215. */
  216. protected Map<String, MergeResult<? extends Sequence>> mergeResults = new HashMap<>();
  217. /**
  218. * Paths for which the merge failed altogether.
  219. *
  220. * @since 3.4
  221. */
  222. protected Map<String, MergeFailureReason> failingPaths = new HashMap<>();
  223. /**
  224. * Updated as we merge entries of the tree walk. Tells us whether we should
  225. * recurse into the entry if it is a subtree.
  226. *
  227. * @since 3.4
  228. */
  229. protected boolean enterSubtree;
  230. /**
  231. * Set to true if this merge should work in-memory. The repos dircache and
  232. * workingtree are not touched by this method. Eventually needed files are
  233. * created as temporary files and a new empty, in-memory dircache will be
  234. * used instead the repo's one. Often used for bare repos where the repo
  235. * doesn't even have a workingtree and dircache.
  236. * @since 3.0
  237. */
  238. protected boolean inCore;
  239. /**
  240. * Set to true if this merger should use the default dircache of the
  241. * repository and should handle locking and unlocking of the dircache. If
  242. * this merger should work in-core or if an explicit dircache was specified
  243. * during construction then this field is set to false.
  244. * @since 3.0
  245. */
  246. protected boolean implicitDirCache;
  247. /**
  248. * Directory cache
  249. * @since 3.0
  250. */
  251. protected DirCache dircache;
  252. /**
  253. * The iterator to access the working tree. If set to <code>null</code> this
  254. * merger will not touch the working tree.
  255. * @since 3.0
  256. */
  257. protected WorkingTreeIterator workingTreeIterator;
  258. /**
  259. * our merge algorithm
  260. * @since 3.0
  261. */
  262. protected MergeAlgorithm mergeAlgorithm;
  263. /**
  264. * The {@link WorkingTreeOptions} are needed to determine line endings for
  265. * merged files.
  266. *
  267. * @since 4.11
  268. */
  269. protected WorkingTreeOptions workingTreeOptions;
  270. /**
  271. * The size limit (bytes) which controls a file to be stored in {@code Heap}
  272. * or {@code LocalFile} during the merge.
  273. */
  274. private int inCoreLimit;
  275. /**
  276. * Keeps {@link CheckoutMetadata} for {@link #checkout()} and
  277. * {@link #cleanUp()}.
  278. */
  279. private Map<String, CheckoutMetadata> checkoutMetadata;
  280. private static MergeAlgorithm getMergeAlgorithm(Config config) {
  281. SupportedAlgorithm diffAlg = config.getEnum(
  282. CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM,
  283. HISTOGRAM);
  284. return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg));
  285. }
  286. private static int getInCoreLimit(Config config) {
  287. return config.getInt(
  288. ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20);
  289. }
  290. private static String[] defaultCommitNames() {
  291. return new String[] { "BASE", "OURS", "THEIRS" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  292. }
  293. private static final Attributes NO_ATTRIBUTES = new Attributes();
  294. /**
  295. * Constructor for ResolveMerger.
  296. *
  297. * @param local
  298. * the {@link org.eclipse.jgit.lib.Repository}.
  299. * @param inCore
  300. * a boolean.
  301. */
  302. protected ResolveMerger(Repository local, boolean inCore) {
  303. super(local);
  304. Config config = local.getConfig();
  305. mergeAlgorithm = getMergeAlgorithm(config);
  306. inCoreLimit = getInCoreLimit(config);
  307. commitNames = defaultCommitNames();
  308. this.inCore = inCore;
  309. if (inCore) {
  310. implicitDirCache = false;
  311. dircache = DirCache.newInCore();
  312. } else {
  313. implicitDirCache = true;
  314. workingTreeOptions = local.getConfig().get(WorkingTreeOptions.KEY);
  315. }
  316. }
  317. /**
  318. * Constructor for ResolveMerger.
  319. *
  320. * @param local
  321. * the {@link org.eclipse.jgit.lib.Repository}.
  322. */
  323. protected ResolveMerger(Repository local) {
  324. this(local, false);
  325. }
  326. /**
  327. * Constructor for ResolveMerger.
  328. *
  329. * @param inserter
  330. * an {@link org.eclipse.jgit.lib.ObjectInserter} object.
  331. * @param config
  332. * the repository configuration
  333. * @since 4.8
  334. */
  335. protected ResolveMerger(ObjectInserter inserter, Config config) {
  336. super(inserter);
  337. mergeAlgorithm = getMergeAlgorithm(config);
  338. commitNames = defaultCommitNames();
  339. inCore = true;
  340. implicitDirCache = false;
  341. dircache = DirCache.newInCore();
  342. }
  343. /** {@inheritDoc} */
  344. @Override
  345. protected boolean mergeImpl() throws IOException {
  346. if (implicitDirCache) {
  347. dircache = nonNullRepo().lockDirCache();
  348. }
  349. if (!inCore) {
  350. checkoutMetadata = new HashMap<>();
  351. }
  352. try {
  353. return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1],
  354. false);
  355. } finally {
  356. checkoutMetadata = null;
  357. if (implicitDirCache) {
  358. dircache.unlock();
  359. }
  360. }
  361. }
  362. private void checkout() throws NoWorkTreeException, IOException {
  363. // Iterate in reverse so that "folder/file" is deleted before
  364. // "folder". Otherwise this could result in a failing path because
  365. // of a non-empty directory, for which delete() would fail.
  366. for (int i = toBeDeleted.size() - 1; i >= 0; i--) {
  367. String fileName = toBeDeleted.get(i);
  368. File f = new File(nonNullRepo().getWorkTree(), fileName);
  369. if (!f.delete())
  370. if (!f.isDirectory())
  371. failingPaths.put(fileName,
  372. MergeFailureReason.COULD_NOT_DELETE);
  373. modifiedFiles.add(fileName);
  374. }
  375. for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
  376. .entrySet()) {
  377. DirCacheEntry cacheEntry = entry.getValue();
  378. if (cacheEntry.getFileMode() == FileMode.GITLINK) {
  379. new File(nonNullRepo().getWorkTree(), entry.getKey()).mkdirs();
  380. } else {
  381. DirCacheCheckout.checkoutEntry(db, cacheEntry, reader, false,
  382. checkoutMetadata.get(entry.getKey()));
  383. modifiedFiles.add(entry.getKey());
  384. }
  385. }
  386. }
  387. /**
  388. * Reverts the worktree after an unsuccessful merge. We know that for all
  389. * modified files the old content was in the old index and the index
  390. * contained only stage 0. In case if inCore operation just clear the
  391. * history of modified files.
  392. *
  393. * @throws java.io.IOException
  394. * @throws org.eclipse.jgit.errors.CorruptObjectException
  395. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  396. * @since 3.4
  397. */
  398. protected void cleanUp() throws NoWorkTreeException,
  399. CorruptObjectException,
  400. IOException {
  401. if (inCore) {
  402. modifiedFiles.clear();
  403. return;
  404. }
  405. DirCache dc = nonNullRepo().readDirCache();
  406. Iterator<String> mpathsIt=modifiedFiles.iterator();
  407. while(mpathsIt.hasNext()) {
  408. String mpath = mpathsIt.next();
  409. DirCacheEntry entry = dc.getEntry(mpath);
  410. if (entry != null) {
  411. DirCacheCheckout.checkoutEntry(db, entry, reader, false,
  412. checkoutMetadata.get(mpath));
  413. }
  414. mpathsIt.remove();
  415. }
  416. }
  417. /**
  418. * adds a new path with the specified stage to the index builder
  419. *
  420. * @param path
  421. * @param p
  422. * @param stage
  423. * @param lastMod
  424. * @param len
  425. * @return the entry which was added to the index
  426. */
  427. private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
  428. Instant lastMod, long len) {
  429. if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
  430. DirCacheEntry e = new DirCacheEntry(path, stage);
  431. e.setFileMode(p.getEntryFileMode());
  432. e.setObjectId(p.getEntryObjectId());
  433. e.setLastModified(lastMod);
  434. e.setLength(len);
  435. builder.add(e);
  436. return e;
  437. }
  438. return null;
  439. }
  440. /**
  441. * adds a entry to the index builder which is a copy of the specified
  442. * DirCacheEntry
  443. *
  444. * @param e
  445. * the entry which should be copied
  446. *
  447. * @return the entry which was added to the index
  448. */
  449. private DirCacheEntry keep(DirCacheEntry e) {
  450. DirCacheEntry newEntry = new DirCacheEntry(e.getRawPath(),
  451. e.getStage());
  452. newEntry.setFileMode(e.getFileMode());
  453. newEntry.setObjectId(e.getObjectId());
  454. newEntry.setLastModified(e.getLastModifiedInstant());
  455. newEntry.setLength(e.getLength());
  456. builder.add(newEntry);
  457. return newEntry;
  458. }
  459. /**
  460. * Remembers the {@link CheckoutMetadata} for the given path; it may be
  461. * needed in {@link #checkout()} or in {@link #cleanUp()}.
  462. *
  463. * @param path
  464. * of the current node
  465. * @param attributes
  466. * for the current node
  467. * @throws IOException
  468. * if the smudge filter cannot be determined
  469. * @since 5.1
  470. */
  471. protected void addCheckoutMetadata(String path, Attributes attributes)
  472. throws IOException {
  473. if (checkoutMetadata != null) {
  474. EolStreamType eol = EolStreamTypeUtil.detectStreamType(
  475. OperationType.CHECKOUT_OP, workingTreeOptions, attributes);
  476. CheckoutMetadata data = new CheckoutMetadata(eol,
  477. tw.getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE));
  478. checkoutMetadata.put(path, data);
  479. }
  480. }
  481. /**
  482. * Adds a {@link DirCacheEntry} for direct checkout and remembers its
  483. * {@link CheckoutMetadata}.
  484. *
  485. * @param path
  486. * of the entry
  487. * @param entry
  488. * to add
  489. * @param attributes
  490. * for the current entry
  491. * @throws IOException
  492. * if the {@link CheckoutMetadata} cannot be determined
  493. * @since 5.1
  494. */
  495. protected void addToCheckout(String path, DirCacheEntry entry,
  496. Attributes attributes) throws IOException {
  497. toBeCheckedOut.put(path, entry);
  498. addCheckoutMetadata(path, attributes);
  499. }
  500. /**
  501. * Remember a path for deletion, and remember its {@link CheckoutMetadata}
  502. * in case it has to be restored in {@link #cleanUp()}.
  503. *
  504. * @param path
  505. * of the entry
  506. * @param isFile
  507. * whether it is a file
  508. * @param attributes
  509. * for the entry
  510. * @throws IOException
  511. * if the {@link CheckoutMetadata} cannot be determined
  512. * @since 5.1
  513. */
  514. protected void addDeletion(String path, boolean isFile,
  515. Attributes attributes) throws IOException {
  516. toBeDeleted.add(path);
  517. if (isFile) {
  518. addCheckoutMetadata(path, attributes);
  519. }
  520. }
  521. /**
  522. * Processes one path and tries to merge taking git attributes in account.
  523. * This method will do all trivial (not content) merges and will also detect
  524. * if a merge will fail. The merge will fail when one of the following is
  525. * true
  526. * <ul>
  527. * <li>the index entry does not match the entry in ours. When merging one
  528. * branch into the current HEAD, ours will point to HEAD and theirs will
  529. * point to the other branch. It is assumed that the index matches the HEAD
  530. * because it will only not match HEAD if it was populated before the merge
  531. * operation. But the merge commit should not accidentally contain
  532. * modifications done before the merge. Check the <a href=
  533. * "http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html#_3_way_merge"
  534. * >git read-tree</a> documentation for further explanations.</li>
  535. * <li>A conflict was detected and the working-tree file is dirty. When a
  536. * conflict is detected the content-merge algorithm will try to write a
  537. * merged version into the working-tree. If the file is dirty we would
  538. * override unsaved data.</li>
  539. * </ul>
  540. *
  541. * @param base
  542. * the common base for ours and theirs
  543. * @param ours
  544. * the ours side of the merge. When merging a branch into the
  545. * HEAD ours will point to HEAD
  546. * @param theirs
  547. * the theirs side of the merge. When merging a branch into the
  548. * current HEAD theirs will point to the branch which is merged
  549. * into HEAD.
  550. * @param index
  551. * the index entry
  552. * @param work
  553. * the file in the working tree
  554. * @param ignoreConflicts
  555. * see
  556. * {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
  557. * @param attributes
  558. * the attributes defined for this entry
  559. * @return <code>false</code> if the merge will fail because the index entry
  560. * didn't match ours or the working-dir file was dirty and a
  561. * conflict occurred
  562. * @throws org.eclipse.jgit.errors.MissingObjectException
  563. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  564. * @throws org.eclipse.jgit.errors.CorruptObjectException
  565. * @throws java.io.IOException
  566. * @since 4.9
  567. */
  568. protected boolean processEntry(CanonicalTreeParser base,
  569. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  570. DirCacheBuildIterator index, WorkingTreeIterator work,
  571. boolean ignoreConflicts, Attributes attributes)
  572. throws MissingObjectException, IncorrectObjectTypeException,
  573. CorruptObjectException, IOException {
  574. enterSubtree = true;
  575. final int modeO = tw.getRawMode(T_OURS);
  576. final int modeT = tw.getRawMode(T_THEIRS);
  577. final int modeB = tw.getRawMode(T_BASE);
  578. if (modeO == 0 && modeT == 0 && modeB == 0)
  579. // File is either untracked or new, staged but uncommitted
  580. return true;
  581. if (isIndexDirty())
  582. return false;
  583. DirCacheEntry ourDce = null;
  584. if (index == null || index.getDirCacheEntry() == null) {
  585. // create a fake DCE, but only if ours is valid. ours is kept only
  586. // in case it is valid, so a null ourDce is ok in all other cases.
  587. if (nonTree(modeO)) {
  588. ourDce = new DirCacheEntry(tw.getRawPath());
  589. ourDce.setObjectId(tw.getObjectId(T_OURS));
  590. ourDce.setFileMode(tw.getFileMode(T_OURS));
  591. }
  592. } else {
  593. ourDce = index.getDirCacheEntry();
  594. }
  595. if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) {
  596. // OURS and THEIRS have equal content. Check the file mode
  597. if (modeO == modeT) {
  598. // content and mode of OURS and THEIRS are equal: it doesn't
  599. // matter which one we choose. OURS is chosen. Since the index
  600. // is clean (the index matches already OURS) we can keep the existing one
  601. keep(ourDce);
  602. // no checkout needed!
  603. return true;
  604. }
  605. // same content but different mode on OURS and THEIRS.
  606. // Try to merge the mode and report an error if this is
  607. // not possible.
  608. int newMode = mergeFileModes(modeB, modeO, modeT);
  609. if (newMode != FileMode.MISSING.getBits()) {
  610. if (newMode == modeO) {
  611. // ours version is preferred
  612. keep(ourDce);
  613. } else {
  614. // the preferred version THEIRS has a different mode
  615. // than ours. Check it out!
  616. if (isWorktreeDirty(work, ourDce)) {
  617. return false;
  618. }
  619. // we know about length and lastMod only after we have
  620. // written the new content.
  621. // This will happen later. Set these values to 0 for know.
  622. DirCacheEntry e = add(tw.getRawPath(), theirs,
  623. DirCacheEntry.STAGE_0, EPOCH, 0);
  624. addToCheckout(tw.getPathString(), e, attributes);
  625. }
  626. return true;
  627. }
  628. // FileModes are not mergeable. We found a conflict on modes.
  629. // For conflicting entries we don't know lastModified and
  630. // length.
  631. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  632. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  633. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  634. unmergedPaths.add(tw.getPathString());
  635. mergeResults.put(tw.getPathString(),
  636. new MergeResult<>(Collections.<RawText> emptyList()));
  637. return true;
  638. }
  639. if (modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) {
  640. // THEIRS was not changed compared to BASE. All changes must be in
  641. // OURS. OURS is chosen. We can keep the existing entry.
  642. if (ourDce != null)
  643. keep(ourDce);
  644. // no checkout needed!
  645. return true;
  646. }
  647. if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) {
  648. // OURS was not changed compared to BASE. All changes must be in
  649. // THEIRS. THEIRS is chosen.
  650. // Check worktree before checking out THEIRS
  651. if (isWorktreeDirty(work, ourDce))
  652. return false;
  653. if (nonTree(modeT)) {
  654. // we know about length and lastMod only after we have written
  655. // the new content.
  656. // This will happen later. Set these values to 0 for know.
  657. DirCacheEntry e = add(tw.getRawPath(), theirs,
  658. DirCacheEntry.STAGE_0, EPOCH, 0);
  659. if (e != null) {
  660. addToCheckout(tw.getPathString(), e, attributes);
  661. }
  662. return true;
  663. }
  664. // we want THEIRS ... but THEIRS contains a folder or the
  665. // deletion of the path. Delete what's in the working tree,
  666. // which we know to be clean.
  667. if (tw.getTreeCount() > T_FILE && tw.getRawMode(T_FILE) == 0) {
  668. // Not present in working tree, so nothing to delete
  669. return true;
  670. }
  671. if (modeT != 0 && modeT == modeB) {
  672. // Base, ours, and theirs all contain a folder: don't delete
  673. return true;
  674. }
  675. addDeletion(tw.getPathString(), nonTree(modeO), attributes);
  676. return true;
  677. }
  678. if (tw.isSubtree()) {
  679. // file/folder conflicts: here I want to detect only file/folder
  680. // conflict between ours and theirs. file/folder conflicts between
  681. // base/index/workingTree and something else are not relevant or
  682. // detected later
  683. if (nonTree(modeO) && !nonTree(modeT)) {
  684. if (nonTree(modeB))
  685. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  686. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  687. unmergedPaths.add(tw.getPathString());
  688. enterSubtree = false;
  689. return true;
  690. }
  691. if (nonTree(modeT) && !nonTree(modeO)) {
  692. if (nonTree(modeB))
  693. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  694. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  695. unmergedPaths.add(tw.getPathString());
  696. enterSubtree = false;
  697. return true;
  698. }
  699. // ours and theirs are both folders or both files (and treewalk
  700. // tells us we are in a subtree because of index or working-dir).
  701. // If they are both folders no content-merge is required - we can
  702. // return here.
  703. if (!nonTree(modeO))
  704. return true;
  705. // ours and theirs are both files, just fall out of the if block
  706. // and do the content merge
  707. }
  708. if (nonTree(modeO) && nonTree(modeT)) {
  709. // Check worktree before modifying files
  710. boolean worktreeDirty = isWorktreeDirty(work, ourDce);
  711. if (!attributes.canBeContentMerged() && worktreeDirty) {
  712. return false;
  713. }
  714. boolean gitlinkConflict = isGitLink(modeO) || isGitLink(modeT);
  715. // Don't attempt to resolve submodule link conflicts
  716. if (gitlinkConflict || !attributes.canBeContentMerged()) {
  717. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  718. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  719. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  720. if (gitlinkConflict) {
  721. MergeResult<SubmoduleConflict> result = new MergeResult<>(
  722. Arrays.asList(
  723. new SubmoduleConflict(base == null ? null
  724. : base.getEntryObjectId()),
  725. new SubmoduleConflict(ours == null ? null
  726. : ours.getEntryObjectId()),
  727. new SubmoduleConflict(theirs == null ? null
  728. : theirs.getEntryObjectId())));
  729. result.setContainsConflicts(true);
  730. mergeResults.put(tw.getPathString(), result);
  731. if (!ignoreConflicts) {
  732. unmergedPaths.add(tw.getPathString());
  733. }
  734. } else {
  735. // attribute merge issues are conflicts but not failures
  736. unmergedPaths.add(tw.getPathString());
  737. }
  738. return true;
  739. }
  740. // Check worktree before modifying files
  741. if (worktreeDirty) {
  742. return false;
  743. }
  744. MergeResult<RawText> result = contentMerge(base, ours, theirs,
  745. attributes);
  746. if (ignoreConflicts) {
  747. result.setContainsConflicts(false);
  748. }
  749. updateIndex(base, ours, theirs, result, attributes);
  750. String currentPath = tw.getPathString();
  751. if (result.containsConflicts() && !ignoreConflicts) {
  752. unmergedPaths.add(currentPath);
  753. }
  754. modifiedFiles.add(currentPath);
  755. addCheckoutMetadata(currentPath, attributes);
  756. } else if (modeO != modeT) {
  757. // OURS or THEIRS has been deleted
  758. if (((modeO != 0 && !tw.idEqual(T_BASE, T_OURS)) || (modeT != 0 && !tw
  759. .idEqual(T_BASE, T_THEIRS)))) {
  760. MergeResult<RawText> result = contentMerge(base, ours, theirs,
  761. attributes);
  762. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  763. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  764. DirCacheEntry e = add(tw.getRawPath(), theirs,
  765. DirCacheEntry.STAGE_3, EPOCH, 0);
  766. // OURS was deleted checkout THEIRS
  767. if (modeO == 0) {
  768. // Check worktree before checking out THEIRS
  769. if (isWorktreeDirty(work, ourDce))
  770. return false;
  771. if (nonTree(modeT)) {
  772. if (e != null) {
  773. addToCheckout(tw.getPathString(), e, attributes);
  774. }
  775. }
  776. }
  777. unmergedPaths.add(tw.getPathString());
  778. // generate a MergeResult for the deleted file
  779. mergeResults.put(tw.getPathString(), result);
  780. }
  781. }
  782. return true;
  783. }
  784. /**
  785. * Does the content merge. The three texts base, ours and theirs are
  786. * specified with {@link CanonicalTreeParser}. If any of the parsers is
  787. * specified as <code>null</code> then an empty text will be used instead.
  788. *
  789. * @param base
  790. * @param ours
  791. * @param theirs
  792. * @param attributes
  793. *
  794. * @return the result of the content merge
  795. * @throws IOException
  796. */
  797. private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
  798. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  799. Attributes attributes)
  800. throws IOException {
  801. RawText baseText;
  802. RawText ourText;
  803. RawText theirsText;
  804. try {
  805. baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
  806. base.getEntryObjectId(), attributes);
  807. ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
  808. ours.getEntryObjectId(), attributes);
  809. theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
  810. theirs.getEntryObjectId(), attributes);
  811. } catch (BinaryBlobException e) {
  812. MergeResult<RawText> r = new MergeResult<>(Collections.<RawText>emptyList());
  813. r.setContainsConflicts(true);
  814. return r;
  815. }
  816. return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
  817. ourText, theirsText));
  818. }
  819. private boolean isIndexDirty() {
  820. if (inCore)
  821. return false;
  822. final int modeI = tw.getRawMode(T_INDEX);
  823. final int modeO = tw.getRawMode(T_OURS);
  824. // Index entry has to match ours to be considered clean
  825. final boolean isDirty = nonTree(modeI)
  826. && !(modeO == modeI && tw.idEqual(T_INDEX, T_OURS));
  827. if (isDirty)
  828. failingPaths
  829. .put(tw.getPathString(), MergeFailureReason.DIRTY_INDEX);
  830. return isDirty;
  831. }
  832. private boolean isWorktreeDirty(WorkingTreeIterator work,
  833. DirCacheEntry ourDce) throws IOException {
  834. if (work == null)
  835. return false;
  836. final int modeF = tw.getRawMode(T_FILE);
  837. final int modeO = tw.getRawMode(T_OURS);
  838. // Worktree entry has to match ours to be considered clean
  839. boolean isDirty;
  840. if (ourDce != null)
  841. isDirty = work.isModified(ourDce, true, reader);
  842. else {
  843. isDirty = work.isModeDifferent(modeO);
  844. if (!isDirty && nonTree(modeF))
  845. isDirty = !tw.idEqual(T_FILE, T_OURS);
  846. }
  847. // Ignore existing empty directories
  848. if (isDirty && modeF == FileMode.TYPE_TREE
  849. && modeO == FileMode.TYPE_MISSING)
  850. isDirty = false;
  851. if (isDirty)
  852. failingPaths.put(tw.getPathString(),
  853. MergeFailureReason.DIRTY_WORKTREE);
  854. return isDirty;
  855. }
  856. /**
  857. * Updates the index after a content merge has happened. If no conflict has
  858. * occurred this includes persisting the merged content to the object
  859. * database. In case of conflicts this method takes care to write the
  860. * correct stages to the index.
  861. *
  862. * @param base
  863. * @param ours
  864. * @param theirs
  865. * @param result
  866. * @param attributes
  867. * @throws FileNotFoundException
  868. * @throws IOException
  869. */
  870. private void updateIndex(CanonicalTreeParser base,
  871. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  872. MergeResult<RawText> result, Attributes attributes)
  873. throws FileNotFoundException,
  874. IOException {
  875. TemporaryBuffer rawMerged = null;
  876. try {
  877. rawMerged = doMerge(result);
  878. File mergedFile = inCore ? null
  879. : writeMergedFile(rawMerged, attributes);
  880. if (result.containsConflicts()) {
  881. // A conflict occurred, the file will contain conflict markers
  882. // the index will be populated with the three stages and the
  883. // workdir (if used) contains the halfway merged content.
  884. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  885. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  886. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  887. mergeResults.put(tw.getPathString(), result);
  888. return;
  889. }
  890. // No conflict occurred, the file will contain fully merged content.
  891. // The index will be populated with the new merged version.
  892. DirCacheEntry dce = new DirCacheEntry(tw.getPathString());
  893. // Set the mode for the new content. Fall back to REGULAR_FILE if
  894. // we can't merge modes of OURS and THEIRS.
  895. int newMode = mergeFileModes(tw.getRawMode(0), tw.getRawMode(1),
  896. tw.getRawMode(2));
  897. dce.setFileMode(newMode == FileMode.MISSING.getBits()
  898. ? FileMode.REGULAR_FILE : FileMode.fromBits(newMode));
  899. if (mergedFile != null) {
  900. dce.setLastModified(
  901. nonNullRepo().getFS().lastModifiedInstant(mergedFile));
  902. dce.setLength((int) mergedFile.length());
  903. }
  904. dce.setObjectId(insertMergeResult(rawMerged, attributes));
  905. builder.add(dce);
  906. } finally {
  907. if (rawMerged != null) {
  908. rawMerged.destroy();
  909. }
  910. }
  911. }
  912. /**
  913. * Writes merged file content to the working tree.
  914. *
  915. * @param rawMerged
  916. * the raw merged content
  917. * @param attributes
  918. * the files .gitattributes entries
  919. * @return the working tree file to which the merged content was written.
  920. * @throws FileNotFoundException
  921. * @throws IOException
  922. */
  923. private File writeMergedFile(TemporaryBuffer rawMerged,
  924. Attributes attributes)
  925. throws FileNotFoundException, IOException {
  926. File workTree = nonNullRepo().getWorkTree();
  927. FS fs = nonNullRepo().getFS();
  928. File of = new File(workTree, tw.getPathString());
  929. File parentFolder = of.getParentFile();
  930. if (!fs.exists(parentFolder)) {
  931. parentFolder.mkdirs();
  932. }
  933. EolStreamType streamType = EolStreamTypeUtil.detectStreamType(
  934. OperationType.CHECKOUT_OP, workingTreeOptions,
  935. attributes);
  936. try (OutputStream os = EolStreamTypeUtil.wrapOutputStream(
  937. new BufferedOutputStream(new FileOutputStream(of)),
  938. streamType)) {
  939. rawMerged.writeTo(os, null);
  940. }
  941. return of;
  942. }
  943. private TemporaryBuffer doMerge(MergeResult<RawText> result)
  944. throws IOException {
  945. TemporaryBuffer.LocalFile buf = new TemporaryBuffer.LocalFile(
  946. db != null ? nonNullRepo().getDirectory() : null, inCoreLimit);
  947. boolean success = false;
  948. try {
  949. new MergeFormatter().formatMerge(buf, result,
  950. Arrays.asList(commitNames), UTF_8);
  951. buf.close();
  952. success = true;
  953. } finally {
  954. if (!success) {
  955. buf.destroy();
  956. }
  957. }
  958. return buf;
  959. }
  960. private ObjectId insertMergeResult(TemporaryBuffer buf,
  961. Attributes attributes) throws IOException {
  962. InputStream in = buf.openInputStream();
  963. try (LfsInputStream is = LfsFactory.getInstance().applyCleanFilter(
  964. getRepository(), in,
  965. buf.length(), attributes.get(Constants.ATTR_MERGE))) {
  966. return getObjectInserter().insert(OBJ_BLOB, is.getLength(), is);
  967. }
  968. }
  969. /**
  970. * Try to merge filemodes. If only ours or theirs have changed the mode
  971. * (compared to base) we choose that one. If ours and theirs have equal
  972. * modes return that one. If also that is not the case the modes are not
  973. * mergeable. Return {@link FileMode#MISSING} int that case.
  974. *
  975. * @param modeB
  976. * filemode found in BASE
  977. * @param modeO
  978. * filemode found in OURS
  979. * @param modeT
  980. * filemode found in THEIRS
  981. *
  982. * @return the merged filemode or {@link FileMode#MISSING} in case of a
  983. * conflict
  984. */
  985. private int mergeFileModes(int modeB, int modeO, int modeT) {
  986. if (modeO == modeT)
  987. return modeO;
  988. if (modeB == modeO)
  989. // Base equal to Ours -> chooses Theirs if that is not missing
  990. return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT;
  991. if (modeB == modeT)
  992. // Base equal to Theirs -> chooses Ours if that is not missing
  993. return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
  994. return FileMode.MISSING.getBits();
  995. }
  996. private RawText getRawText(ObjectId id,
  997. Attributes attributes)
  998. throws IOException, BinaryBlobException {
  999. if (id.equals(ObjectId.zeroId()))
  1000. return new RawText(new byte[] {});
  1001. ObjectLoader loader = LfsFactory.getInstance().applySmudgeFilter(
  1002. getRepository(), reader.open(id, OBJ_BLOB),
  1003. attributes.get(Constants.ATTR_MERGE));
  1004. int threshold = PackConfig.DEFAULT_BIG_FILE_THRESHOLD;
  1005. return RawText.load(loader, threshold);
  1006. }
  1007. private static boolean nonTree(int mode) {
  1008. return mode != 0 && !FileMode.TREE.equals(mode);
  1009. }
  1010. private static boolean isGitLink(int mode) {
  1011. return FileMode.GITLINK.equals(mode);
  1012. }
  1013. /** {@inheritDoc} */
  1014. @Override
  1015. public ObjectId getResultTreeId() {
  1016. return (resultTree == null) ? null : resultTree.toObjectId();
  1017. }
  1018. /**
  1019. * Set the names of the commits as they would appear in conflict markers
  1020. *
  1021. * @param commitNames
  1022. * the names of the commits as they would appear in conflict
  1023. * markers
  1024. */
  1025. public void setCommitNames(String[] commitNames) {
  1026. this.commitNames = commitNames;
  1027. }
  1028. /**
  1029. * Get the names of the commits as they would appear in conflict markers.
  1030. *
  1031. * @return the names of the commits as they would appear in conflict
  1032. * markers.
  1033. */
  1034. public String[] getCommitNames() {
  1035. return commitNames;
  1036. }
  1037. /**
  1038. * Get the paths with conflicts. This is a subset of the files listed by
  1039. * {@link #getModifiedFiles()}
  1040. *
  1041. * @return the paths with conflicts. This is a subset of the files listed by
  1042. * {@link #getModifiedFiles()}
  1043. */
  1044. public List<String> getUnmergedPaths() {
  1045. return unmergedPaths;
  1046. }
  1047. /**
  1048. * Get the paths of files which have been modified by this merge.
  1049. *
  1050. * @return the paths of files which have been modified by this merge. A file
  1051. * will be modified if a content-merge works on this path or if the
  1052. * merge algorithm decides to take the theirs-version. This is a
  1053. * superset of the files listed by {@link #getUnmergedPaths()}.
  1054. */
  1055. public List<String> getModifiedFiles() {
  1056. return modifiedFiles;
  1057. }
  1058. /**
  1059. * Get a map which maps the paths of files which have to be checked out
  1060. * because the merge created new fully-merged content for this file into the
  1061. * index.
  1062. *
  1063. * @return a map which maps the paths of files which have to be checked out
  1064. * because the merge created new fully-merged content for this file
  1065. * into the index. This means: the merge wrote a new stage 0 entry
  1066. * for this path.
  1067. */
  1068. public Map<String, DirCacheEntry> getToBeCheckedOut() {
  1069. return toBeCheckedOut;
  1070. }
  1071. /**
  1072. * Get the mergeResults
  1073. *
  1074. * @return the mergeResults
  1075. */
  1076. public Map<String, MergeResult<? extends Sequence>> getMergeResults() {
  1077. return mergeResults;
  1078. }
  1079. /**
  1080. * Get list of paths causing this merge to fail (not stopped because of a
  1081. * conflict).
  1082. *
  1083. * @return lists paths causing this merge to fail (not stopped because of a
  1084. * conflict). <code>null</code> is returned if this merge didn't
  1085. * fail.
  1086. */
  1087. public Map<String, MergeFailureReason> getFailingPaths() {
  1088. return failingPaths.isEmpty() ? null : failingPaths;
  1089. }
  1090. /**
  1091. * Returns whether this merge failed (i.e. not stopped because of a
  1092. * conflict)
  1093. *
  1094. * @return <code>true</code> if a failure occurred, <code>false</code>
  1095. * otherwise
  1096. */
  1097. public boolean failed() {
  1098. return !failingPaths.isEmpty();
  1099. }
  1100. /**
  1101. * Sets the DirCache which shall be used by this merger. If the DirCache is
  1102. * not set explicitly and if this merger doesn't work in-core, this merger
  1103. * will implicitly get and lock a default DirCache. If the DirCache is
  1104. * explicitly set the caller is responsible to lock it in advance. Finally
  1105. * the merger will call {@link org.eclipse.jgit.dircache.DirCache#commit()}
  1106. * which requires that the DirCache is locked. If the {@link #mergeImpl()}
  1107. * returns without throwing an exception the lock will be released. In case
  1108. * of exceptions the caller is responsible to release the lock.
  1109. *
  1110. * @param dc
  1111. * the DirCache to set
  1112. */
  1113. public void setDirCache(DirCache dc) {
  1114. this.dircache = dc;
  1115. implicitDirCache = false;
  1116. }
  1117. /**
  1118. * Sets the WorkingTreeIterator to be used by this merger. If no
  1119. * WorkingTreeIterator is set this merger will ignore the working tree and
  1120. * fail if a content merge is necessary.
  1121. * <p>
  1122. * TODO: enhance WorkingTreeIterator to support write operations. Then this
  1123. * merger will be able to merge with a different working tree abstraction.
  1124. *
  1125. * @param workingTreeIterator
  1126. * the workingTreeIt to set
  1127. */
  1128. public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
  1129. this.workingTreeIterator = workingTreeIterator;
  1130. }
  1131. /**
  1132. * The resolve conflict way of three way merging
  1133. *
  1134. * @param baseTree
  1135. * a {@link org.eclipse.jgit.treewalk.AbstractTreeIterator}
  1136. * object.
  1137. * @param headTree
  1138. * a {@link org.eclipse.jgit.revwalk.RevTree} object.
  1139. * @param mergeTree
  1140. * a {@link org.eclipse.jgit.revwalk.RevTree} object.
  1141. * @param ignoreConflicts
  1142. * Controls what to do in case a content-merge is done and a
  1143. * conflict is detected. The default setting for this should be
  1144. * <code>false</code>. In this case the working tree file is
  1145. * filled with new content (containing conflict markers) and the
  1146. * index is filled with multiple stages containing BASE, OURS and
  1147. * THEIRS content. Having such non-0 stages is the sign to git
  1148. * tools that there are still conflicts for that path.
  1149. * <p>
  1150. * If <code>true</code> is specified the behavior is different.
  1151. * In case a conflict is detected the working tree file is again
  1152. * filled with new content (containing conflict markers). But
  1153. * also stage 0 of the index is filled with that content. No
  1154. * other stages are filled. Means: there is no conflict on that
  1155. * path but the new content (including conflict markers) is
  1156. * stored as successful merge result. This is needed in the
  1157. * context of {@link org.eclipse.jgit.merge.RecursiveMerger}
  1158. * where when determining merge bases we don't want to deal with
  1159. * content-merge conflicts.
  1160. * @return whether the trees merged cleanly
  1161. * @throws java.io.IOException
  1162. * @since 3.5
  1163. */
  1164. protected boolean mergeTrees(AbstractTreeIterator baseTree,
  1165. RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
  1166. throws IOException {
  1167. builder = dircache.builder();
  1168. DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
  1169. tw = new NameConflictTreeWalk(db, reader);
  1170. tw.addTree(baseTree);
  1171. tw.addTree(headTree);
  1172. tw.addTree(mergeTree);
  1173. int dciPos = tw.addTree(buildIt);
  1174. if (workingTreeIterator != null) {
  1175. tw.addTree(workingTreeIterator);
  1176. workingTreeIterator.setDirCacheIterator(tw, dciPos);
  1177. } else {
  1178. tw.setFilter(TreeFilter.ANY_DIFF);
  1179. }
  1180. if (!mergeTreeWalk(tw, ignoreConflicts)) {
  1181. return false;
  1182. }
  1183. if (!inCore) {
  1184. // No problem found. The only thing left to be done is to
  1185. // checkout all files from "theirs" which have been selected to
  1186. // go into the new index.
  1187. checkout();
  1188. // All content-merges are successfully done. If we can now write the
  1189. // new index we are on quite safe ground. Even if the checkout of
  1190. // files coming from "theirs" fails the user can work around such
  1191. // failures by checking out the index again.
  1192. if (!builder.commit()) {
  1193. cleanUp();
  1194. throw new IndexWriteException();
  1195. }
  1196. builder = null;
  1197. } else {
  1198. builder.finish();
  1199. builder = null;
  1200. }
  1201. if (getUnmergedPaths().isEmpty() && !failed()) {
  1202. resultTree = dircache.writeTree(getObjectInserter());
  1203. return true;
  1204. }
  1205. resultTree = null;
  1206. return false;
  1207. }
  1208. /**
  1209. * Process the given TreeWalk's entries.
  1210. *
  1211. * @param treeWalk
  1212. * The walk to iterate over.
  1213. * @param ignoreConflicts
  1214. * see
  1215. * {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
  1216. * @return Whether the trees merged cleanly.
  1217. * @throws java.io.IOException
  1218. * @since 3.5
  1219. */
  1220. protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts)
  1221. throws IOException {
  1222. boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
  1223. boolean hasAttributeNodeProvider = treeWalk
  1224. .getAttributesNodeProvider() != null;
  1225. while (treeWalk.next()) {
  1226. if (!processEntry(
  1227. treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
  1228. treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
  1229. treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
  1230. treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
  1231. hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
  1232. WorkingTreeIterator.class) : null,
  1233. ignoreConflicts, hasAttributeNodeProvider
  1234. ? treeWalk.getAttributes()
  1235. : NO_ATTRIBUTES)) {
  1236. cleanUp();
  1237. return false;
  1238. }
  1239. if (treeWalk.isSubtree() && enterSubtree)
  1240. treeWalk.enterSubtree();
  1241. }
  1242. return true;
  1243. }
  1244. }