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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. if (modeO == 0 && modeT == 0 && modeB == 0)
  546. // File is either untracked or new, staged but uncommitted
  547. return true;
  548. if (isIndexDirty())
  549. return false;
  550. DirCacheEntry ourDce = null;
  551. if (index == null || index.getDirCacheEntry() == null) {
  552. // create a fake DCE, but only if ours is valid. ours is kept only
  553. // in case it is valid, so a null ourDce is ok in all other cases.
  554. if (nonTree(modeO)) {
  555. ourDce = new DirCacheEntry(tw.getRawPath());
  556. ourDce.setObjectId(tw.getObjectId(T_OURS));
  557. ourDce.setFileMode(tw.getFileMode(T_OURS));
  558. }
  559. } else {
  560. ourDce = index.getDirCacheEntry();
  561. }
  562. if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) {
  563. // OURS and THEIRS have equal content. Check the file mode
  564. if (modeO == modeT) {
  565. // content and mode of OURS and THEIRS are equal: it doesn't
  566. // matter which one we choose. OURS is chosen. Since the index
  567. // is clean (the index matches already OURS) we can keep the existing one
  568. keep(ourDce);
  569. // no checkout needed!
  570. return true;
  571. }
  572. // same content but different mode on OURS and THEIRS.
  573. // Try to merge the mode and report an error if this is
  574. // not possible.
  575. int newMode = mergeFileModes(modeB, modeO, modeT);
  576. if (newMode != FileMode.MISSING.getBits()) {
  577. if (newMode == modeO) {
  578. // ours version is preferred
  579. keep(ourDce);
  580. } else {
  581. // the preferred version THEIRS has a different mode
  582. // than ours. Check it out!
  583. if (isWorktreeDirty(work, ourDce)) {
  584. return false;
  585. }
  586. // we know about length and lastMod only after we have
  587. // written the new content.
  588. // This will happen later. Set these values to 0 for know.
  589. DirCacheEntry e = add(tw.getRawPath(), theirs,
  590. DirCacheEntry.STAGE_0, EPOCH, 0);
  591. addToCheckout(tw.getPathString(), e, attributes);
  592. }
  593. return true;
  594. }
  595. // FileModes are not mergeable. We found a conflict on modes.
  596. // For conflicting entries we don't know lastModified and
  597. // length.
  598. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  599. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  600. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  601. unmergedPaths.add(tw.getPathString());
  602. mergeResults.put(tw.getPathString(),
  603. new MergeResult<>(Collections.<RawText> emptyList()));
  604. return true;
  605. }
  606. if (modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) {
  607. // THEIRS was not changed compared to BASE. All changes must be in
  608. // OURS. OURS is chosen. We can keep the existing entry.
  609. if (ourDce != null)
  610. keep(ourDce);
  611. // no checkout needed!
  612. return true;
  613. }
  614. if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) {
  615. // OURS was not changed compared to BASE. All changes must be in
  616. // THEIRS. THEIRS is chosen.
  617. // Check worktree before checking out THEIRS
  618. if (isWorktreeDirty(work, ourDce))
  619. return false;
  620. if (nonTree(modeT)) {
  621. // we know about length and lastMod only after we have written
  622. // the new content.
  623. // This will happen later. Set these values to 0 for know.
  624. DirCacheEntry e = add(tw.getRawPath(), theirs,
  625. DirCacheEntry.STAGE_0, EPOCH, 0);
  626. if (e != null) {
  627. addToCheckout(tw.getPathString(), e, attributes);
  628. }
  629. return true;
  630. }
  631. // we want THEIRS ... but THEIRS contains a folder or the
  632. // deletion of the path. Delete what's in the working tree,
  633. // which we know to be clean.
  634. if (tw.getTreeCount() > T_FILE && tw.getRawMode(T_FILE) == 0) {
  635. // Not present in working tree, so nothing to delete
  636. return true;
  637. }
  638. if (modeT != 0 && modeT == modeB) {
  639. // Base, ours, and theirs all contain a folder: don't delete
  640. return true;
  641. }
  642. addDeletion(tw.getPathString(), nonTree(modeO), attributes);
  643. return true;
  644. }
  645. if (tw.isSubtree()) {
  646. // file/folder conflicts: here I want to detect only file/folder
  647. // conflict between ours and theirs. file/folder conflicts between
  648. // base/index/workingTree and something else are not relevant or
  649. // detected later
  650. if (nonTree(modeO) && !nonTree(modeT)) {
  651. if (nonTree(modeB))
  652. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  653. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  654. unmergedPaths.add(tw.getPathString());
  655. enterSubtree = false;
  656. return true;
  657. }
  658. if (nonTree(modeT) && !nonTree(modeO)) {
  659. if (nonTree(modeB))
  660. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  661. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  662. unmergedPaths.add(tw.getPathString());
  663. enterSubtree = false;
  664. return true;
  665. }
  666. // ours and theirs are both folders or both files (and treewalk
  667. // tells us we are in a subtree because of index or working-dir).
  668. // If they are both folders no content-merge is required - we can
  669. // return here.
  670. if (!nonTree(modeO))
  671. return true;
  672. // ours and theirs are both files, just fall out of the if block
  673. // and do the content merge
  674. }
  675. if (nonTree(modeO) && nonTree(modeT)) {
  676. // Check worktree before modifying files
  677. boolean worktreeDirty = isWorktreeDirty(work, ourDce);
  678. if (!attributes.canBeContentMerged() && worktreeDirty) {
  679. return false;
  680. }
  681. boolean gitlinkConflict = isGitLink(modeO) || isGitLink(modeT);
  682. // Don't attempt to resolve submodule link conflicts
  683. if (gitlinkConflict || !attributes.canBeContentMerged()) {
  684. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  685. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  686. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  687. if (gitlinkConflict) {
  688. MergeResult<SubmoduleConflict> result = new MergeResult<>(
  689. Arrays.asList(
  690. new SubmoduleConflict(base == null ? null
  691. : base.getEntryObjectId()),
  692. new SubmoduleConflict(ours == null ? null
  693. : ours.getEntryObjectId()),
  694. new SubmoduleConflict(theirs == null ? null
  695. : theirs.getEntryObjectId())));
  696. result.setContainsConflicts(true);
  697. mergeResults.put(tw.getPathString(), result);
  698. if (!ignoreConflicts) {
  699. unmergedPaths.add(tw.getPathString());
  700. }
  701. } else {
  702. // attribute merge issues are conflicts but not failures
  703. unmergedPaths.add(tw.getPathString());
  704. }
  705. return true;
  706. }
  707. // Check worktree before modifying files
  708. if (worktreeDirty) {
  709. return false;
  710. }
  711. MergeResult<RawText> result = contentMerge(base, ours, theirs,
  712. attributes);
  713. if (ignoreConflicts) {
  714. result.setContainsConflicts(false);
  715. }
  716. updateIndex(base, ours, theirs, result, attributes);
  717. String currentPath = tw.getPathString();
  718. if (result.containsConflicts() && !ignoreConflicts) {
  719. unmergedPaths.add(currentPath);
  720. }
  721. modifiedFiles.add(currentPath);
  722. addCheckoutMetadata(currentPath, attributes);
  723. } else if (modeO != modeT) {
  724. // OURS or THEIRS has been deleted
  725. if (((modeO != 0 && !tw.idEqual(T_BASE, T_OURS)) || (modeT != 0 && !tw
  726. .idEqual(T_BASE, T_THEIRS)))) {
  727. MergeResult<RawText> result = contentMerge(base, ours, theirs,
  728. attributes);
  729. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  730. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  731. DirCacheEntry e = add(tw.getRawPath(), theirs,
  732. DirCacheEntry.STAGE_3, EPOCH, 0);
  733. // OURS was deleted checkout THEIRS
  734. if (modeO == 0) {
  735. // Check worktree before checking out THEIRS
  736. if (isWorktreeDirty(work, ourDce))
  737. return false;
  738. if (nonTree(modeT)) {
  739. if (e != null) {
  740. addToCheckout(tw.getPathString(), e, attributes);
  741. }
  742. }
  743. }
  744. unmergedPaths.add(tw.getPathString());
  745. // generate a MergeResult for the deleted file
  746. mergeResults.put(tw.getPathString(), result);
  747. }
  748. }
  749. return true;
  750. }
  751. /**
  752. * Does the content merge. The three texts base, ours and theirs are
  753. * specified with {@link CanonicalTreeParser}. If any of the parsers is
  754. * specified as <code>null</code> then an empty text will be used instead.
  755. *
  756. * @param base
  757. * @param ours
  758. * @param theirs
  759. * @param attributes
  760. *
  761. * @return the result of the content merge
  762. * @throws IOException
  763. */
  764. private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
  765. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  766. Attributes attributes)
  767. throws IOException {
  768. RawText baseText;
  769. RawText ourText;
  770. RawText theirsText;
  771. try {
  772. baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
  773. base.getEntryObjectId(), attributes);
  774. ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
  775. ours.getEntryObjectId(), attributes);
  776. theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
  777. theirs.getEntryObjectId(), attributes);
  778. } catch (BinaryBlobException e) {
  779. MergeResult<RawText> r = new MergeResult<>(Collections.<RawText>emptyList());
  780. r.setContainsConflicts(true);
  781. return r;
  782. }
  783. return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
  784. ourText, theirsText));
  785. }
  786. private boolean isIndexDirty() {
  787. if (inCore)
  788. return false;
  789. final int modeI = tw.getRawMode(T_INDEX);
  790. final int modeO = tw.getRawMode(T_OURS);
  791. // Index entry has to match ours to be considered clean
  792. final boolean isDirty = nonTree(modeI)
  793. && !(modeO == modeI && tw.idEqual(T_INDEX, T_OURS));
  794. if (isDirty)
  795. failingPaths
  796. .put(tw.getPathString(), MergeFailureReason.DIRTY_INDEX);
  797. return isDirty;
  798. }
  799. private boolean isWorktreeDirty(WorkingTreeIterator work,
  800. DirCacheEntry ourDce) throws IOException {
  801. if (work == null)
  802. return false;
  803. final int modeF = tw.getRawMode(T_FILE);
  804. final int modeO = tw.getRawMode(T_OURS);
  805. // Worktree entry has to match ours to be considered clean
  806. boolean isDirty;
  807. if (ourDce != null)
  808. isDirty = work.isModified(ourDce, true, reader);
  809. else {
  810. isDirty = work.isModeDifferent(modeO);
  811. if (!isDirty && nonTree(modeF))
  812. isDirty = !tw.idEqual(T_FILE, T_OURS);
  813. }
  814. // Ignore existing empty directories
  815. if (isDirty && modeF == FileMode.TYPE_TREE
  816. && modeO == FileMode.TYPE_MISSING)
  817. isDirty = false;
  818. if (isDirty)
  819. failingPaths.put(tw.getPathString(),
  820. MergeFailureReason.DIRTY_WORKTREE);
  821. return isDirty;
  822. }
  823. /**
  824. * Updates the index after a content merge has happened. If no conflict has
  825. * occurred this includes persisting the merged content to the object
  826. * database. In case of conflicts this method takes care to write the
  827. * correct stages to the index.
  828. *
  829. * @param base
  830. * @param ours
  831. * @param theirs
  832. * @param result
  833. * @param attributes
  834. * @throws FileNotFoundException
  835. * @throws IOException
  836. */
  837. private void updateIndex(CanonicalTreeParser base,
  838. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  839. MergeResult<RawText> result, Attributes attributes)
  840. throws FileNotFoundException,
  841. IOException {
  842. TemporaryBuffer rawMerged = null;
  843. try {
  844. rawMerged = doMerge(result);
  845. File mergedFile = inCore ? null
  846. : writeMergedFile(rawMerged, attributes);
  847. if (result.containsConflicts()) {
  848. // A conflict occurred, the file will contain conflict markers
  849. // the index will be populated with the three stages and the
  850. // workdir (if used) contains the halfway merged content.
  851. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
  852. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
  853. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
  854. mergeResults.put(tw.getPathString(), result);
  855. return;
  856. }
  857. // No conflict occurred, the file will contain fully merged content.
  858. // The index will be populated with the new merged version.
  859. DirCacheEntry dce = new DirCacheEntry(tw.getPathString());
  860. // Set the mode for the new content. Fall back to REGULAR_FILE if
  861. // we can't merge modes of OURS and THEIRS.
  862. int newMode = mergeFileModes(tw.getRawMode(0), tw.getRawMode(1),
  863. tw.getRawMode(2));
  864. dce.setFileMode(newMode == FileMode.MISSING.getBits()
  865. ? FileMode.REGULAR_FILE : FileMode.fromBits(newMode));
  866. if (mergedFile != null) {
  867. dce.setLastModified(
  868. nonNullRepo().getFS().lastModifiedInstant(mergedFile));
  869. dce.setLength((int) mergedFile.length());
  870. }
  871. dce.setObjectId(insertMergeResult(rawMerged, attributes));
  872. builder.add(dce);
  873. } finally {
  874. if (rawMerged != null) {
  875. rawMerged.destroy();
  876. }
  877. }
  878. }
  879. /**
  880. * Writes merged file content to the working tree.
  881. *
  882. * @param rawMerged
  883. * the raw merged content
  884. * @param attributes
  885. * the files .gitattributes entries
  886. * @return the working tree file to which the merged content was written.
  887. * @throws FileNotFoundException
  888. * @throws IOException
  889. */
  890. private File writeMergedFile(TemporaryBuffer rawMerged,
  891. Attributes attributes)
  892. throws FileNotFoundException, IOException {
  893. File workTree = nonNullRepo().getWorkTree();
  894. FS fs = nonNullRepo().getFS();
  895. File of = new File(workTree, tw.getPathString());
  896. File parentFolder = of.getParentFile();
  897. if (!fs.exists(parentFolder)) {
  898. parentFolder.mkdirs();
  899. }
  900. EolStreamType streamType = EolStreamTypeUtil.detectStreamType(
  901. OperationType.CHECKOUT_OP, workingTreeOptions,
  902. attributes);
  903. try (OutputStream os = EolStreamTypeUtil.wrapOutputStream(
  904. new BufferedOutputStream(new FileOutputStream(of)),
  905. streamType)) {
  906. rawMerged.writeTo(os, null);
  907. }
  908. return of;
  909. }
  910. private TemporaryBuffer doMerge(MergeResult<RawText> result)
  911. throws IOException {
  912. TemporaryBuffer.LocalFile buf = new TemporaryBuffer.LocalFile(
  913. db != null ? nonNullRepo().getDirectory() : null, inCoreLimit);
  914. boolean success = false;
  915. try {
  916. new MergeFormatter().formatMerge(buf, result,
  917. Arrays.asList(commitNames), UTF_8);
  918. buf.close();
  919. success = true;
  920. } finally {
  921. if (!success) {
  922. buf.destroy();
  923. }
  924. }
  925. return buf;
  926. }
  927. private ObjectId insertMergeResult(TemporaryBuffer buf,
  928. Attributes attributes) throws IOException {
  929. InputStream in = buf.openInputStream();
  930. try (LfsInputStream is = LfsFactory.getInstance().applyCleanFilter(
  931. getRepository(), in,
  932. buf.length(), attributes.get(Constants.ATTR_MERGE))) {
  933. return getObjectInserter().insert(OBJ_BLOB, is.getLength(), is);
  934. }
  935. }
  936. /**
  937. * Try to merge filemodes. If only ours or theirs have changed the mode
  938. * (compared to base) we choose that one. If ours and theirs have equal
  939. * modes return that one. If also that is not the case the modes are not
  940. * mergeable. Return {@link FileMode#MISSING} int that case.
  941. *
  942. * @param modeB
  943. * filemode found in BASE
  944. * @param modeO
  945. * filemode found in OURS
  946. * @param modeT
  947. * filemode found in THEIRS
  948. *
  949. * @return the merged filemode or {@link FileMode#MISSING} in case of a
  950. * conflict
  951. */
  952. private int mergeFileModes(int modeB, int modeO, int modeT) {
  953. if (modeO == modeT)
  954. return modeO;
  955. if (modeB == modeO)
  956. // Base equal to Ours -> chooses Theirs if that is not missing
  957. return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT;
  958. if (modeB == modeT)
  959. // Base equal to Theirs -> chooses Ours if that is not missing
  960. return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
  961. return FileMode.MISSING.getBits();
  962. }
  963. private RawText getRawText(ObjectId id,
  964. Attributes attributes)
  965. throws IOException, BinaryBlobException {
  966. if (id.equals(ObjectId.zeroId()))
  967. return new RawText(new byte[] {});
  968. ObjectLoader loader = LfsFactory.getInstance().applySmudgeFilter(
  969. getRepository(), reader.open(id, OBJ_BLOB),
  970. attributes.get(Constants.ATTR_MERGE));
  971. int threshold = PackConfig.DEFAULT_BIG_FILE_THRESHOLD;
  972. return RawText.load(loader, threshold);
  973. }
  974. private static boolean nonTree(int mode) {
  975. return mode != 0 && !FileMode.TREE.equals(mode);
  976. }
  977. private static boolean isGitLink(int mode) {
  978. return FileMode.GITLINK.equals(mode);
  979. }
  980. /** {@inheritDoc} */
  981. @Override
  982. public ObjectId getResultTreeId() {
  983. return (resultTree == null) ? null : resultTree.toObjectId();
  984. }
  985. /**
  986. * Set the names of the commits as they would appear in conflict markers
  987. *
  988. * @param commitNames
  989. * the names of the commits as they would appear in conflict
  990. * markers
  991. */
  992. public void setCommitNames(String[] commitNames) {
  993. this.commitNames = commitNames;
  994. }
  995. /**
  996. * Get the names of the commits as they would appear in conflict markers.
  997. *
  998. * @return the names of the commits as they would appear in conflict
  999. * markers.
  1000. */
  1001. public String[] getCommitNames() {
  1002. return commitNames;
  1003. }
  1004. /**
  1005. * Get the paths with conflicts. This is a subset of the files listed by
  1006. * {@link #getModifiedFiles()}
  1007. *
  1008. * @return the paths with conflicts. This is a subset of the files listed by
  1009. * {@link #getModifiedFiles()}
  1010. */
  1011. public List<String> getUnmergedPaths() {
  1012. return unmergedPaths;
  1013. }
  1014. /**
  1015. * Get the paths of files which have been modified by this merge.
  1016. *
  1017. * @return the paths of files which have been modified by this merge. A file
  1018. * will be modified if a content-merge works on this path or if the
  1019. * merge algorithm decides to take the theirs-version. This is a
  1020. * superset of the files listed by {@link #getUnmergedPaths()}.
  1021. */
  1022. public List<String> getModifiedFiles() {
  1023. return modifiedFiles;
  1024. }
  1025. /**
  1026. * Get a map which maps the paths of files which have to be checked out
  1027. * because the merge created new fully-merged content for this file into the
  1028. * index.
  1029. *
  1030. * @return a map which maps the paths of files which have to be checked out
  1031. * because the merge created new fully-merged content for this file
  1032. * into the index. This means: the merge wrote a new stage 0 entry
  1033. * for this path.
  1034. */
  1035. public Map<String, DirCacheEntry> getToBeCheckedOut() {
  1036. return toBeCheckedOut;
  1037. }
  1038. /**
  1039. * Get the mergeResults
  1040. *
  1041. * @return the mergeResults
  1042. */
  1043. public Map<String, MergeResult<? extends Sequence>> getMergeResults() {
  1044. return mergeResults;
  1045. }
  1046. /**
  1047. * Get list of paths causing this merge to fail (not stopped because of a
  1048. * conflict).
  1049. *
  1050. * @return lists paths causing this merge to fail (not stopped because of a
  1051. * conflict). <code>null</code> is returned if this merge didn't
  1052. * fail.
  1053. */
  1054. public Map<String, MergeFailureReason> getFailingPaths() {
  1055. return failingPaths.isEmpty() ? null : failingPaths;
  1056. }
  1057. /**
  1058. * Returns whether this merge failed (i.e. not stopped because of a
  1059. * conflict)
  1060. *
  1061. * @return <code>true</code> if a failure occurred, <code>false</code>
  1062. * otherwise
  1063. */
  1064. public boolean failed() {
  1065. return !failingPaths.isEmpty();
  1066. }
  1067. /**
  1068. * Sets the DirCache which shall be used by this merger. If the DirCache is
  1069. * not set explicitly and if this merger doesn't work in-core, this merger
  1070. * will implicitly get and lock a default DirCache. If the DirCache is
  1071. * explicitly set the caller is responsible to lock it in advance. Finally
  1072. * the merger will call {@link org.eclipse.jgit.dircache.DirCache#commit()}
  1073. * which requires that the DirCache is locked. If the {@link #mergeImpl()}
  1074. * returns without throwing an exception the lock will be released. In case
  1075. * of exceptions the caller is responsible to release the lock.
  1076. *
  1077. * @param dc
  1078. * the DirCache to set
  1079. */
  1080. public void setDirCache(DirCache dc) {
  1081. this.dircache = dc;
  1082. implicitDirCache = false;
  1083. }
  1084. /**
  1085. * Sets the WorkingTreeIterator to be used by this merger. If no
  1086. * WorkingTreeIterator is set this merger will ignore the working tree and
  1087. * fail if a content merge is necessary.
  1088. * <p>
  1089. * TODO: enhance WorkingTreeIterator to support write operations. Then this
  1090. * merger will be able to merge with a different working tree abstraction.
  1091. *
  1092. * @param workingTreeIterator
  1093. * the workingTreeIt to set
  1094. */
  1095. public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
  1096. this.workingTreeIterator = workingTreeIterator;
  1097. }
  1098. /**
  1099. * The resolve conflict way of three way merging
  1100. *
  1101. * @param baseTree
  1102. * a {@link org.eclipse.jgit.treewalk.AbstractTreeIterator}
  1103. * object.
  1104. * @param headTree
  1105. * a {@link org.eclipse.jgit.revwalk.RevTree} object.
  1106. * @param mergeTree
  1107. * a {@link org.eclipse.jgit.revwalk.RevTree} object.
  1108. * @param ignoreConflicts
  1109. * Controls what to do in case a content-merge is done and a
  1110. * conflict is detected. The default setting for this should be
  1111. * <code>false</code>. In this case the working tree file is
  1112. * filled with new content (containing conflict markers) and the
  1113. * index is filled with multiple stages containing BASE, OURS and
  1114. * THEIRS content. Having such non-0 stages is the sign to git
  1115. * tools that there are still conflicts for that path.
  1116. * <p>
  1117. * If <code>true</code> is specified the behavior is different.
  1118. * In case a conflict is detected the working tree file is again
  1119. * filled with new content (containing conflict markers). But
  1120. * also stage 0 of the index is filled with that content. No
  1121. * other stages are filled. Means: there is no conflict on that
  1122. * path but the new content (including conflict markers) is
  1123. * stored as successful merge result. This is needed in the
  1124. * context of {@link org.eclipse.jgit.merge.RecursiveMerger}
  1125. * where when determining merge bases we don't want to deal with
  1126. * content-merge conflicts.
  1127. * @return whether the trees merged cleanly
  1128. * @throws java.io.IOException
  1129. * @since 3.5
  1130. */
  1131. protected boolean mergeTrees(AbstractTreeIterator baseTree,
  1132. RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
  1133. throws IOException {
  1134. builder = dircache.builder();
  1135. DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
  1136. tw = new NameConflictTreeWalk(db, reader);
  1137. tw.addTree(baseTree);
  1138. tw.addTree(headTree);
  1139. tw.addTree(mergeTree);
  1140. int dciPos = tw.addTree(buildIt);
  1141. if (workingTreeIterator != null) {
  1142. tw.addTree(workingTreeIterator);
  1143. workingTreeIterator.setDirCacheIterator(tw, dciPos);
  1144. } else {
  1145. tw.setFilter(TreeFilter.ANY_DIFF);
  1146. }
  1147. if (!mergeTreeWalk(tw, ignoreConflicts)) {
  1148. return false;
  1149. }
  1150. if (!inCore) {
  1151. // No problem found. The only thing left to be done is to
  1152. // checkout all files from "theirs" which have been selected to
  1153. // go into the new index.
  1154. checkout();
  1155. // All content-merges are successfully done. If we can now write the
  1156. // new index we are on quite safe ground. Even if the checkout of
  1157. // files coming from "theirs" fails the user can work around such
  1158. // failures by checking out the index again.
  1159. if (!builder.commit()) {
  1160. cleanUp();
  1161. throw new IndexWriteException();
  1162. }
  1163. builder = null;
  1164. } else {
  1165. builder.finish();
  1166. builder = null;
  1167. }
  1168. if (getUnmergedPaths().isEmpty() && !failed()) {
  1169. resultTree = dircache.writeTree(getObjectInserter());
  1170. return true;
  1171. }
  1172. resultTree = null;
  1173. return false;
  1174. }
  1175. /**
  1176. * Process the given TreeWalk's entries.
  1177. *
  1178. * @param treeWalk
  1179. * The walk to iterate over.
  1180. * @param ignoreConflicts
  1181. * see
  1182. * {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
  1183. * @return Whether the trees merged cleanly.
  1184. * @throws java.io.IOException
  1185. * @since 3.5
  1186. */
  1187. protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts)
  1188. throws IOException {
  1189. boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
  1190. boolean hasAttributeNodeProvider = treeWalk
  1191. .getAttributesNodeProvider() != null;
  1192. while (treeWalk.next()) {
  1193. if (!processEntry(
  1194. treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
  1195. treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
  1196. treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
  1197. treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
  1198. hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
  1199. WorkingTreeIterator.class) : null,
  1200. ignoreConflicts, hasAttributeNodeProvider
  1201. ? treeWalk.getAttributes()
  1202. : NO_ATTRIBUTES)) {
  1203. cleanUp();
  1204. return false;
  1205. }
  1206. if (treeWalk.isSubtree() && enterSubtree)
  1207. treeWalk.enterSubtree();
  1208. }
  1209. return true;
  1210. }
  1211. }