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

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