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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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 java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.FileNotFoundException;
  49. import java.io.FileOutputStream;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.util.ArrayList;
  53. import java.util.Arrays;
  54. import java.util.Collections;
  55. import java.util.HashMap;
  56. import java.util.Iterator;
  57. import java.util.LinkedList;
  58. import java.util.List;
  59. import java.util.Map;
  60. import org.eclipse.jgit.diff.DiffAlgorithm;
  61. import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
  62. import org.eclipse.jgit.diff.RawText;
  63. import org.eclipse.jgit.diff.RawTextComparator;
  64. import org.eclipse.jgit.diff.Sequence;
  65. import org.eclipse.jgit.dircache.DirCache;
  66. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  67. import org.eclipse.jgit.dircache.DirCacheBuilder;
  68. import org.eclipse.jgit.dircache.DirCacheCheckout;
  69. import org.eclipse.jgit.dircache.DirCacheEntry;
  70. import org.eclipse.jgit.errors.CorruptObjectException;
  71. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  72. import org.eclipse.jgit.errors.IndexWriteException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.errors.NoWorkTreeException;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.lib.ConfigConstants;
  77. import org.eclipse.jgit.lib.Constants;
  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.FileUtils;
  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. ObjectReader r = db.getObjectDatabase().newReader();
  280. try {
  281. for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
  282. .entrySet()) {
  283. File f = new File(db.getWorkTree(), entry.getKey());
  284. createDir(f.getParentFile());
  285. DirCacheCheckout.checkoutEntry(db, f, entry.getValue(), r);
  286. modifiedFiles.add(entry.getKey());
  287. }
  288. // Iterate in reverse so that "folder/file" is deleted before
  289. // "folder". Otherwise this could result in a failing path because
  290. // of a non-empty directory, for which delete() would fail.
  291. for (int i = toBeDeleted.size() - 1; i >= 0; i--) {
  292. String fileName = toBeDeleted.get(i);
  293. File f = new File(db.getWorkTree(), fileName);
  294. if (!f.delete())
  295. if (!f.isDirectory())
  296. failingPaths.put(fileName,
  297. MergeFailureReason.COULD_NOT_DELETE);
  298. modifiedFiles.add(fileName);
  299. }
  300. } finally {
  301. r.release();
  302. }
  303. }
  304. private void createDir(File f) throws IOException {
  305. if (!db.getFS().isDirectory(f) && !f.mkdirs()) {
  306. File p = f;
  307. while (p != null && !db.getFS().exists(p))
  308. p = p.getParentFile();
  309. if (p == null || db.getFS().isDirectory(p))
  310. throw new IOException(JGitText.get().cannotCreateDirectory);
  311. FileUtils.delete(p);
  312. if (!f.mkdirs())
  313. throw new IOException(JGitText.get().cannotCreateDirectory);
  314. }
  315. }
  316. /**
  317. * Reverts the worktree after an unsuccessful merge. We know that for all
  318. * modified files the old content was in the old index and the index
  319. * contained only stage 0. In case if inCore operation just clear the
  320. * history of modified files.
  321. *
  322. * @throws IOException
  323. * @throws CorruptObjectException
  324. * @throws NoWorkTreeException
  325. * @since 3.4
  326. */
  327. protected void cleanUp() throws NoWorkTreeException,
  328. CorruptObjectException,
  329. IOException {
  330. if (inCore) {
  331. modifiedFiles.clear();
  332. return;
  333. }
  334. DirCache dc = db.readDirCache();
  335. ObjectReader or = db.getObjectDatabase().newReader();
  336. Iterator<String> mpathsIt=modifiedFiles.iterator();
  337. while(mpathsIt.hasNext()) {
  338. String mpath=mpathsIt.next();
  339. DirCacheEntry entry = dc.getEntry(mpath);
  340. if (entry == null)
  341. continue;
  342. FileOutputStream fos = new FileOutputStream(new File(
  343. db.getWorkTree(), mpath));
  344. try {
  345. or.open(entry.getObjectId()).copyTo(fos);
  346. } finally {
  347. fos.close();
  348. }
  349. mpathsIt.remove();
  350. }
  351. }
  352. /**
  353. * adds a new path with the specified stage to the index builder
  354. *
  355. * @param path
  356. * @param p
  357. * @param stage
  358. * @param lastMod
  359. * @param len
  360. * @return the entry which was added to the index
  361. */
  362. private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
  363. long lastMod, long len) {
  364. if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
  365. DirCacheEntry e = new DirCacheEntry(path, stage);
  366. e.setFileMode(p.getEntryFileMode());
  367. e.setObjectId(p.getEntryObjectId());
  368. e.setLastModified(lastMod);
  369. e.setLength(len);
  370. builder.add(e);
  371. return e;
  372. }
  373. return null;
  374. }
  375. /**
  376. * adds a entry to the index builder which is a copy of the specified
  377. * DirCacheEntry
  378. *
  379. * @param e
  380. * the entry which should be copied
  381. *
  382. * @return the entry which was added to the index
  383. */
  384. private DirCacheEntry keep(DirCacheEntry e) {
  385. DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(),
  386. e.getStage());
  387. newEntry.setFileMode(e.getFileMode());
  388. newEntry.setObjectId(e.getObjectId());
  389. newEntry.setLastModified(e.getLastModified());
  390. newEntry.setLength(e.getLength());
  391. builder.add(newEntry);
  392. return newEntry;
  393. }
  394. /**
  395. * Processes one path and tries to merge. This method will do all do all
  396. * trivial (not content) merges and will also detect if a merge will fail.
  397. * The merge will fail when one of the following is true
  398. * <ul>
  399. * <li>the index entry does not match the entry in ours. When merging one
  400. * branch into the current HEAD, ours will point to HEAD and theirs will
  401. * point to the other branch. It is assumed that the index matches the HEAD
  402. * because it will only not match HEAD if it was populated before the merge
  403. * operation. But the merge commit should not accidentally contain
  404. * modifications done before the merge. Check the <a href=
  405. * "http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html#_3_way_merge"
  406. * >git read-tree</a> documentation for further explanations.</li>
  407. * <li>A conflict was detected and the working-tree file is dirty. When a
  408. * conflict is detected the content-merge algorithm will try to write a
  409. * merged version into the working-tree. If the file is dirty we would
  410. * override unsaved data.</li>
  411. *
  412. * @param base
  413. * the common base for ours and theirs
  414. * @param ours
  415. * the ours side of the merge. When merging a branch into the
  416. * HEAD ours will point to HEAD
  417. * @param theirs
  418. * the theirs side of the merge. When merging a branch into the
  419. * current HEAD theirs will point to the branch which is merged
  420. * into HEAD.
  421. * @param index
  422. * the index entry
  423. * @param work
  424. * the file in the working tree
  425. * @param ignoreConflicts
  426. * see
  427. * {@link ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
  428. * @return <code>false</code> if the merge will fail because the index entry
  429. * didn't match ours or the working-dir file was dirty and a
  430. * conflict occurred
  431. * @throws MissingObjectException
  432. * @throws IncorrectObjectTypeException
  433. * @throws CorruptObjectException
  434. * @throws IOException
  435. * @since 3.4
  436. */
  437. protected boolean processEntry(CanonicalTreeParser base,
  438. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  439. DirCacheBuildIterator index, WorkingTreeIterator work,
  440. boolean ignoreConflicts)
  441. throws MissingObjectException, IncorrectObjectTypeException,
  442. CorruptObjectException, IOException {
  443. enterSubtree = true;
  444. final int modeO = tw.getRawMode(T_OURS);
  445. final int modeT = tw.getRawMode(T_THEIRS);
  446. final int modeB = tw.getRawMode(T_BASE);
  447. if (modeO == 0 && modeT == 0 && modeB == 0)
  448. // File is either untracked or new, staged but uncommitted
  449. return true;
  450. if (isIndexDirty())
  451. return false;
  452. DirCacheEntry ourDce = null;
  453. if (index == null || index.getDirCacheEntry() == null) {
  454. // create a fake DCE, but only if ours is valid. ours is kept only
  455. // in case it is valid, so a null ourDce is ok in all other cases.
  456. if (nonTree(modeO)) {
  457. ourDce = new DirCacheEntry(tw.getRawPath());
  458. ourDce.setObjectId(tw.getObjectId(T_OURS));
  459. ourDce.setFileMode(tw.getFileMode(T_OURS));
  460. }
  461. } else {
  462. ourDce = index.getDirCacheEntry();
  463. }
  464. if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) {
  465. // OURS and THEIRS have equal content. Check the file mode
  466. if (modeO == modeT) {
  467. // content and mode of OURS and THEIRS are equal: it doesn't
  468. // matter which one we choose. OURS is chosen. Since the index
  469. // is clean (the index matches already OURS) we can keep the existing one
  470. keep(ourDce);
  471. // no checkout needed!
  472. return true;
  473. } else {
  474. // same content but different mode on OURS and THEIRS.
  475. // Try to merge the mode and report an error if this is
  476. // not possible.
  477. int newMode = mergeFileModes(modeB, modeO, modeT);
  478. if (newMode != FileMode.MISSING.getBits()) {
  479. if (newMode == modeO)
  480. // ours version is preferred
  481. keep(ourDce);
  482. else {
  483. // the preferred version THEIRS has a different mode
  484. // than ours. Check it out!
  485. if (isWorktreeDirty(work, ourDce))
  486. return false;
  487. // we know about length and lastMod only after we have written the new content.
  488. // This will happen later. Set these values to 0 for know.
  489. DirCacheEntry e = add(tw.getRawPath(), theirs,
  490. DirCacheEntry.STAGE_0, 0, 0);
  491. toBeCheckedOut.put(tw.getPathString(), e);
  492. }
  493. return true;
  494. } else {
  495. // FileModes are not mergeable. We found a conflict on modes.
  496. // For conflicting entries we don't know lastModified and length.
  497. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  498. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  499. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  500. unmergedPaths.add(tw.getPathString());
  501. mergeResults.put(
  502. tw.getPathString(),
  503. new MergeResult<RawText>(Collections
  504. .<RawText> emptyList()));
  505. }
  506. return true;
  507. }
  508. }
  509. if (nonTree(modeO) && modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) {
  510. // THEIRS was not changed compared to BASE. All changes must be in
  511. // OURS. OURS is chosen. We can keep the existing entry.
  512. keep(ourDce);
  513. // no checkout needed!
  514. return true;
  515. }
  516. if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) {
  517. // OURS was not changed compared to BASE. All changes must be in
  518. // THEIRS. THEIRS is chosen.
  519. // Check worktree before checking out THEIRS
  520. if (isWorktreeDirty(work, ourDce))
  521. return false;
  522. if (nonTree(modeT)) {
  523. // we know about length and lastMod only after we have written
  524. // the new content.
  525. // This will happen later. Set these values to 0 for know.
  526. DirCacheEntry e = add(tw.getRawPath(), theirs,
  527. DirCacheEntry.STAGE_0, 0, 0);
  528. if (e != null)
  529. toBeCheckedOut.put(tw.getPathString(), e);
  530. return true;
  531. } else if (modeT == 0 && modeB != 0) {
  532. // we want THEIRS ... but THEIRS contains the deletion of the
  533. // file. Also, do not complain if the file is already deleted
  534. // locally. This complements the test in isWorktreeDirty() for
  535. // the same case.
  536. if (tw.getTreeCount() > T_FILE && tw.getRawMode(T_FILE) == 0)
  537. return true;
  538. toBeDeleted.add(tw.getPathString());
  539. return true;
  540. }
  541. }
  542. if (tw.isSubtree()) {
  543. // file/folder conflicts: here I want to detect only file/folder
  544. // conflict between ours and theirs. file/folder conflicts between
  545. // base/index/workingTree and something else are not relevant or
  546. // detected later
  547. if (nonTree(modeO) && !nonTree(modeT)) {
  548. if (nonTree(modeB))
  549. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  550. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  551. unmergedPaths.add(tw.getPathString());
  552. enterSubtree = false;
  553. return true;
  554. }
  555. if (nonTree(modeT) && !nonTree(modeO)) {
  556. if (nonTree(modeB))
  557. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  558. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  559. unmergedPaths.add(tw.getPathString());
  560. enterSubtree = false;
  561. return true;
  562. }
  563. // ours and theirs are both folders or both files (and treewalk
  564. // tells us we are in a subtree because of index or working-dir).
  565. // If they are both folders no content-merge is required - we can
  566. // return here.
  567. if (!nonTree(modeO))
  568. return true;
  569. // ours and theirs are both files, just fall out of the if block
  570. // and do the content merge
  571. }
  572. if (nonTree(modeO) && nonTree(modeT)) {
  573. // Check worktree before modifying files
  574. if (isWorktreeDirty(work, ourDce))
  575. return false;
  576. // Don't attempt to resolve submodule link conflicts
  577. if (isGitLink(modeO) || isGitLink(modeT)) {
  578. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  579. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  580. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  581. unmergedPaths.add(tw.getPathString());
  582. return true;
  583. }
  584. MergeResult<RawText> result = contentMerge(base, ours, theirs);
  585. if (ignoreConflicts)
  586. result.setContainsConflicts(false);
  587. File of = writeMergedFile(result);
  588. updateIndex(base, ours, theirs, result, of);
  589. if (result.containsConflicts() && !ignoreConflicts)
  590. unmergedPaths.add(tw.getPathString());
  591. modifiedFiles.add(tw.getPathString());
  592. } else if (modeO != modeT) {
  593. // OURS or THEIRS has been deleted
  594. if (((modeO != 0 && !tw.idEqual(T_BASE, T_OURS)) || (modeT != 0 && !tw
  595. .idEqual(T_BASE, T_THEIRS)))) {
  596. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  597. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  598. DirCacheEntry e = add(tw.getRawPath(), theirs,
  599. DirCacheEntry.STAGE_3, 0, 0);
  600. // OURS was deleted checkout THEIRS
  601. if (modeO == 0) {
  602. // Check worktree before checking out THEIRS
  603. if (isWorktreeDirty(work, ourDce))
  604. return false;
  605. if (nonTree(modeT)) {
  606. if (e != null)
  607. toBeCheckedOut.put(tw.getPathString(), e);
  608. }
  609. }
  610. unmergedPaths.add(tw.getPathString());
  611. // generate a MergeResult for the deleted file
  612. mergeResults.put(tw.getPathString(),
  613. contentMerge(base, ours, theirs));
  614. }
  615. }
  616. return true;
  617. }
  618. /**
  619. * Does the content merge. The three texts base, ours and theirs are
  620. * specified with {@link CanonicalTreeParser}. If any of the parsers is
  621. * specified as <code>null</code> then an empty text will be used instead.
  622. *
  623. * @param base
  624. * @param ours
  625. * @param theirs
  626. *
  627. * @return the result of the content merge
  628. * @throws IOException
  629. */
  630. private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
  631. CanonicalTreeParser ours, CanonicalTreeParser theirs)
  632. throws IOException {
  633. RawText baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
  634. base.getEntryObjectId(), db);
  635. RawText ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
  636. ours.getEntryObjectId(), db);
  637. RawText theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
  638. theirs.getEntryObjectId(), db);
  639. return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
  640. ourText, theirsText));
  641. }
  642. private boolean isIndexDirty() {
  643. if (inCore)
  644. return false;
  645. final int modeI = tw.getRawMode(T_INDEX);
  646. final int modeO = tw.getRawMode(T_OURS);
  647. // Index entry has to match ours to be considered clean
  648. final boolean isDirty = nonTree(modeI)
  649. && !(modeO == modeI && tw.idEqual(T_INDEX, T_OURS));
  650. if (isDirty)
  651. failingPaths
  652. .put(tw.getPathString(), MergeFailureReason.DIRTY_INDEX);
  653. return isDirty;
  654. }
  655. private boolean isWorktreeDirty(WorkingTreeIterator work,
  656. DirCacheEntry ourDce) throws IOException {
  657. if (work == null)
  658. return false;
  659. final int modeF = tw.getRawMode(T_FILE);
  660. final int modeO = tw.getRawMode(T_OURS);
  661. // Worktree entry has to match ours to be considered clean
  662. boolean isDirty;
  663. if (ourDce != null)
  664. isDirty = work.isModified(ourDce, true, reader);
  665. else {
  666. isDirty = work.isModeDifferent(modeO);
  667. if (!isDirty && nonTree(modeF))
  668. isDirty = !tw.idEqual(T_FILE, T_OURS);
  669. }
  670. // Ignore existing empty directories
  671. if (isDirty && modeF == FileMode.TYPE_TREE
  672. && modeO == FileMode.TYPE_MISSING)
  673. isDirty = false;
  674. if (isDirty)
  675. failingPaths.put(tw.getPathString(),
  676. MergeFailureReason.DIRTY_WORKTREE);
  677. return isDirty;
  678. }
  679. /**
  680. * Updates the index after a content merge has happened. If no conflict has
  681. * occurred this includes persisting the merged content to the object
  682. * database. In case of conflicts this method takes care to write the
  683. * correct stages to the index.
  684. *
  685. * @param base
  686. * @param ours
  687. * @param theirs
  688. * @param result
  689. * @param of
  690. * @throws FileNotFoundException
  691. * @throws IOException
  692. */
  693. private void updateIndex(CanonicalTreeParser base,
  694. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  695. MergeResult<RawText> result, File of) throws FileNotFoundException,
  696. IOException {
  697. if (result.containsConflicts()) {
  698. // a conflict occurred, the file will contain conflict markers
  699. // the index will be populated with the three stages and only the
  700. // workdir (if used) contains the halfways merged content
  701. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  702. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  703. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  704. mergeResults.put(tw.getPathString(), result);
  705. } else {
  706. // no conflict occurred, the file will contain fully merged content.
  707. // the index will be populated with the new merged version
  708. DirCacheEntry dce = new DirCacheEntry(tw.getPathString());
  709. int newMode = mergeFileModes(tw.getRawMode(0), tw.getRawMode(1),
  710. tw.getRawMode(2));
  711. // set the mode for the new content. Fall back to REGULAR_FILE if
  712. // you can't merge modes of OURS and THEIRS
  713. dce.setFileMode((newMode == FileMode.MISSING.getBits()) ? FileMode.REGULAR_FILE
  714. : FileMode.fromBits(newMode));
  715. dce.setLastModified(of.lastModified());
  716. dce.setLength((int) of.length());
  717. InputStream is = new FileInputStream(of);
  718. try {
  719. dce.setObjectId(getObjectInserter().insert(
  720. Constants.OBJ_BLOB, of.length(), is));
  721. } finally {
  722. is.close();
  723. if (inCore)
  724. FileUtils.delete(of);
  725. }
  726. builder.add(dce);
  727. }
  728. }
  729. /**
  730. * Writes merged file content to the working tree. In case {@link #inCore}
  731. * is set and we don't have a working tree the content is written to a
  732. * temporary file
  733. *
  734. * @param result
  735. * the result of the content merge
  736. * @return the file to which the merged content was written
  737. * @throws FileNotFoundException
  738. * @throws IOException
  739. */
  740. private File writeMergedFile(MergeResult<RawText> result)
  741. throws FileNotFoundException, IOException {
  742. MergeFormatter fmt = new MergeFormatter();
  743. File of = null;
  744. FileOutputStream fos;
  745. if (!inCore) {
  746. File workTree = db.getWorkTree();
  747. if (workTree == null)
  748. // TODO: This should be handled by WorkingTreeIterators which
  749. // support write operations
  750. throw new UnsupportedOperationException();
  751. FS fs = db.getFS();
  752. of = new File(workTree, tw.getPathString());
  753. File parentFolder = of.getParentFile();
  754. if (!fs.exists(parentFolder))
  755. parentFolder.mkdirs();
  756. fos = new FileOutputStream(of);
  757. try {
  758. fmt.formatMerge(fos, result, Arrays.asList(commitNames),
  759. Constants.CHARACTER_ENCODING);
  760. } finally {
  761. fos.close();
  762. }
  763. } else if (!result.containsConflicts()) {
  764. // When working inCore, only trivial merges can be handled,
  765. // so we generate objects only in conflict free cases
  766. of = File.createTempFile("merge_", "_temp", null); //$NON-NLS-1$ //$NON-NLS-2$
  767. fos = new FileOutputStream(of);
  768. try {
  769. fmt.formatMerge(fos, result, Arrays.asList(commitNames),
  770. Constants.CHARACTER_ENCODING);
  771. } finally {
  772. fos.close();
  773. }
  774. }
  775. return of;
  776. }
  777. /**
  778. * Try to merge filemodes. If only ours or theirs have changed the mode
  779. * (compared to base) we choose that one. If ours and theirs have equal
  780. * modes return that one. If also that is not the case the modes are not
  781. * mergeable. Return {@link FileMode#MISSING} int that case.
  782. *
  783. * @param modeB
  784. * filemode found in BASE
  785. * @param modeO
  786. * filemode found in OURS
  787. * @param modeT
  788. * filemode found in THEIRS
  789. *
  790. * @return the merged filemode or {@link FileMode#MISSING} in case of a
  791. * conflict
  792. */
  793. private int mergeFileModes(int modeB, int modeO, int modeT) {
  794. if (modeO == modeT)
  795. return modeO;
  796. if (modeB == modeO)
  797. // Base equal to Ours -> chooses Theirs if that is not missing
  798. return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT;
  799. if (modeB == modeT)
  800. // Base equal to Theirs -> chooses Ours if that is not missing
  801. return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
  802. return FileMode.MISSING.getBits();
  803. }
  804. private static RawText getRawText(ObjectId id, Repository db)
  805. throws IOException {
  806. if (id.equals(ObjectId.zeroId()))
  807. return new RawText(new byte[] {});
  808. return new RawText(db.open(id, Constants.OBJ_BLOB).getCachedBytes());
  809. }
  810. private static boolean nonTree(final int mode) {
  811. return mode != 0 && !FileMode.TREE.equals(mode);
  812. }
  813. private static boolean isGitLink(final int mode) {
  814. return FileMode.GITLINK.equals(mode);
  815. }
  816. @Override
  817. public ObjectId getResultTreeId() {
  818. return (resultTree == null) ? null : resultTree.toObjectId();
  819. }
  820. /**
  821. * @param commitNames
  822. * the names of the commits as they would appear in conflict
  823. * markers
  824. */
  825. public void setCommitNames(String[] commitNames) {
  826. this.commitNames = commitNames;
  827. }
  828. /**
  829. * @return the names of the commits as they would appear in conflict
  830. * markers.
  831. */
  832. public String[] getCommitNames() {
  833. return commitNames;
  834. }
  835. /**
  836. * @return the paths with conflicts. This is a subset of the files listed
  837. * by {@link #getModifiedFiles()}
  838. */
  839. public List<String> getUnmergedPaths() {
  840. return unmergedPaths;
  841. }
  842. /**
  843. * @return the paths of files which have been modified by this merge. A
  844. * file will be modified if a content-merge works on this path or if
  845. * the merge algorithm decides to take the theirs-version. This is a
  846. * superset of the files listed by {@link #getUnmergedPaths()}.
  847. */
  848. public List<String> getModifiedFiles() {
  849. return modifiedFiles;
  850. }
  851. /**
  852. * @return a map which maps the paths of files which have to be checked out
  853. * because the merge created new fully-merged content for this file
  854. * into the index. This means: the merge wrote a new stage 0 entry
  855. * for this path.
  856. */
  857. public Map<String, DirCacheEntry> getToBeCheckedOut() {
  858. return toBeCheckedOut;
  859. }
  860. /**
  861. * @return the mergeResults
  862. */
  863. public Map<String, MergeResult<? extends Sequence>> getMergeResults() {
  864. return mergeResults;
  865. }
  866. /**
  867. * @return lists paths causing this merge to fail (not stopped because of a
  868. * conflict). <code>null</code> is returned if this merge didn't
  869. * fail.
  870. */
  871. public Map<String, MergeFailureReason> getFailingPaths() {
  872. return (failingPaths.size() == 0) ? null : failingPaths;
  873. }
  874. /**
  875. * Returns whether this merge failed (i.e. not stopped because of a
  876. * conflict)
  877. *
  878. * @return <code>true</code> if a failure occurred, <code>false</code>
  879. * otherwise
  880. */
  881. public boolean failed() {
  882. return failingPaths.size() > 0;
  883. }
  884. /**
  885. * Sets the DirCache which shall be used by this merger. If the DirCache is
  886. * not set explicitly and if this merger doesn't work in-core, this merger
  887. * will implicitly get and lock a default DirCache. If the DirCache is
  888. * explicitly set the caller is responsible to lock it in advance. Finally
  889. * the merger will call {@link DirCache#commit()} which requires that the
  890. * DirCache is locked. If the {@link #mergeImpl()} returns without throwing
  891. * an exception the lock will be released. In case of exceptions the caller
  892. * is responsible to release the lock.
  893. *
  894. * @param dc
  895. * the DirCache to set
  896. */
  897. public void setDirCache(DirCache dc) {
  898. this.dircache = dc;
  899. implicitDirCache = false;
  900. }
  901. /**
  902. * Sets the WorkingTreeIterator to be used by this merger. If no
  903. * WorkingTreeIterator is set this merger will ignore the working tree and
  904. * fail if a content merge is necessary.
  905. * <p>
  906. * TODO: enhance WorkingTreeIterator to support write operations. Then this
  907. * merger will be able to merge with a different working tree abstraction.
  908. *
  909. * @param workingTreeIterator
  910. * the workingTreeIt to set
  911. */
  912. public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
  913. this.workingTreeIterator = workingTreeIterator;
  914. }
  915. /**
  916. * The resolve conflict way of three way merging
  917. *
  918. * @param baseTree
  919. * @param headTree
  920. * @param mergeTree
  921. * @param ignoreConflicts
  922. * Controls what to do in case a content-merge is done and a
  923. * conflict is detected. The default setting for this should be
  924. * <code>false</code>. In this case the working tree file is
  925. * filled with new content (containing conflict markers) and the
  926. * index is filled with multiple stages containing BASE, OURS and
  927. * THEIRS content. Having such non-0 stages is the sign to git
  928. * tools that there are still conflicts for that path.
  929. * <p>
  930. * If <code>true</code> is specified the behavior is different.
  931. * In case a conflict is detected the working tree file is again
  932. * filled with new content (containing conflict markers). But
  933. * also stage 0 of the index is filled with that content. No
  934. * other stages are filled. Means: there is no conflict on that
  935. * path but the new content (including conflict markers) is
  936. * stored as successful merge result. This is needed in the
  937. * context of {@link RecursiveMerger} where when determining
  938. * merge bases we don't want to deal with content-merge
  939. * conflicts.
  940. * @return whether the trees merged cleanly
  941. * @throws IOException
  942. * @since 3.0
  943. */
  944. protected boolean mergeTrees(AbstractTreeIterator baseTree,
  945. RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
  946. throws IOException {
  947. builder = dircache.builder();
  948. DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
  949. tw = new NameConflictTreeWalk(db);
  950. tw.addTree(baseTree);
  951. tw.addTree(headTree);
  952. tw.addTree(mergeTree);
  953. tw.addTree(buildIt);
  954. if (workingTreeIterator != null)
  955. tw.addTree(workingTreeIterator);
  956. if (!mergeTreeWalk(tw, ignoreConflicts)) {
  957. return false;
  958. }
  959. if (!inCore) {
  960. // No problem found. The only thing left to be done is to
  961. // checkout all files from "theirs" which have been selected to
  962. // go into the new index.
  963. checkout();
  964. // All content-merges are successfully done. If we can now write the
  965. // new index we are on quite safe ground. Even if the checkout of
  966. // files coming from "theirs" fails the user can work around such
  967. // failures by checking out the index again.
  968. if (!builder.commit()) {
  969. cleanUp();
  970. throw new IndexWriteException();
  971. }
  972. builder = null;
  973. } else {
  974. builder.finish();
  975. builder = null;
  976. }
  977. if (getUnmergedPaths().isEmpty() && !failed()) {
  978. resultTree = dircache.writeTree(getObjectInserter());
  979. return true;
  980. } else {
  981. resultTree = null;
  982. return false;
  983. }
  984. }
  985. /**
  986. * Process the given TreeWalk's entries.
  987. *
  988. * @param treeWalk
  989. * The walk to iterate over.
  990. * @param ignoreConflicts
  991. * see
  992. * {@link ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
  993. * @return Whether the trees merged cleanly.
  994. * @throws IOException
  995. * @since 3.4
  996. */
  997. protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts)
  998. throws IOException {
  999. boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
  1000. while (treeWalk.next()) {
  1001. if (!processEntry(
  1002. treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
  1003. treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
  1004. treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
  1005. treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
  1006. hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
  1007. WorkingTreeIterator.class) : null, ignoreConflicts)) {
  1008. cleanUp();
  1009. return false;
  1010. }
  1011. if (treeWalk.isSubtree() && enterSubtree)
  1012. treeWalk.enterSubtree();
  1013. }
  1014. return true;
  1015. }
  1016. }