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

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