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

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