You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResolveMerger.java 43KB

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