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

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