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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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.WorkingTreeIterator;
  87. import org.eclipse.jgit.util.FileUtils;
  88. /**
  89. * A three-way merger performing a content-merge if necessary
  90. */
  91. public class ResolveMerger extends ThreeWayMerger {
  92. /**
  93. * If the merge fails (means: not stopped because of unresolved conflicts)
  94. * this enum is used to explain why it failed
  95. */
  96. public enum MergeFailureReason {
  97. /** the merge failed because of a dirty index */
  98. DIRTY_INDEX,
  99. /** the merge failed because of a dirty workingtree */
  100. DIRTY_WORKTREE,
  101. /** the merge failed because of a file could not be deleted */
  102. COULD_NOT_DELETE
  103. }
  104. private NameConflictTreeWalk tw;
  105. /**
  106. * string versions of a list of commit SHA1s
  107. */
  108. protected String commitNames[];
  109. private static final int T_BASE = 0;
  110. private static final int T_OURS = 1;
  111. private static final int T_THEIRS = 2;
  112. private static final int T_INDEX = 3;
  113. private static final int T_FILE = 4;
  114. private DirCacheBuilder builder;
  115. /**
  116. * merge result as tree
  117. */
  118. protected ObjectId resultTree;
  119. private List<String> unmergedPaths = new ArrayList<String>();
  120. private List<String> modifiedFiles = new LinkedList<String>();
  121. private Map<String, DirCacheEntry> toBeCheckedOut = new HashMap<String, DirCacheEntry>();
  122. private List<String> toBeDeleted = new ArrayList<String>();
  123. private Map<String, MergeResult<? extends Sequence>> mergeResults = new HashMap<String, MergeResult<? extends Sequence>>();
  124. private Map<String, MergeFailureReason> failingPaths = new HashMap<String, MergeFailureReason>();
  125. private boolean enterSubtree;
  126. /**
  127. * Set to true if this merge should work in-memory. The repos dircache and
  128. * workingtree are not touched by this method. Eventually needed files are
  129. * created as temporary files and a new empty, in-memory dircache will be
  130. * used instead the repo's one. Often used for bare repos where the repo
  131. * doesn't even have a workingtree and dircache.
  132. */
  133. protected boolean inCore;
  134. /**
  135. * Set to true if this merger should use the default dircache of the
  136. * repository and should handle locking and unlocking of the dircache. If
  137. * this merger should work in-core or if an explicit dircache was specified
  138. * during construction then this field is set to false.
  139. */
  140. protected boolean implicitDirCache;
  141. /**
  142. * Directory cache
  143. */
  144. protected DirCache dircache;
  145. /**
  146. * The iterator to access the working tree. If set to <code>null</code> this
  147. * merger will not touch the working tree.
  148. */
  149. protected WorkingTreeIterator workingTreeIterator;
  150. /**
  151. * our merge algorithm
  152. */
  153. protected MergeAlgorithm mergeAlgorithm;
  154. /**
  155. * @param local
  156. * @param inCore
  157. */
  158. protected ResolveMerger(Repository local, boolean inCore) {
  159. super(local);
  160. SupportedAlgorithm diffAlg = local.getConfig().getEnum(
  161. ConfigConstants.CONFIG_DIFF_SECTION, null,
  162. ConfigConstants.CONFIG_KEY_ALGORITHM,
  163. SupportedAlgorithm.HISTOGRAM);
  164. mergeAlgorithm = new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg));
  165. commitNames = new String[] { "BASE", "OURS", "THEIRS" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  166. this.inCore = inCore;
  167. if (inCore) {
  168. implicitDirCache = false;
  169. dircache = DirCache.newInCore();
  170. } else {
  171. implicitDirCache = true;
  172. }
  173. }
  174. /**
  175. * @param local
  176. */
  177. protected ResolveMerger(Repository local) {
  178. this(local, false);
  179. }
  180. @Override
  181. protected boolean mergeImpl() throws IOException {
  182. if (implicitDirCache)
  183. dircache = getRepository().lockDirCache();
  184. try {
  185. return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1]);
  186. } finally {
  187. if (implicitDirCache)
  188. dircache.unlock();
  189. }
  190. }
  191. private void checkout() throws NoWorkTreeException, IOException {
  192. ObjectReader r = db.getObjectDatabase().newReader();
  193. try {
  194. for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
  195. .entrySet()) {
  196. File f = new File(db.getWorkTree(), entry.getKey());
  197. createDir(f.getParentFile());
  198. DirCacheCheckout.checkoutEntry(db, f, entry.getValue(), r);
  199. modifiedFiles.add(entry.getKey());
  200. }
  201. // Iterate in reverse so that "folder/file" is deleted before
  202. // "folder". Otherwise this could result in a failing path because
  203. // of a non-empty directory, for which delete() would fail.
  204. for (int i = toBeDeleted.size() - 1; i >= 0; i--) {
  205. String fileName = toBeDeleted.get(i);
  206. File f = new File(db.getWorkTree(), fileName);
  207. if (!f.delete())
  208. failingPaths.put(fileName,
  209. MergeFailureReason.COULD_NOT_DELETE);
  210. modifiedFiles.add(fileName);
  211. }
  212. } finally {
  213. r.release();
  214. }
  215. }
  216. private void createDir(File f) throws IOException {
  217. if (!f.isDirectory() && !f.mkdirs()) {
  218. File p = f;
  219. while (p != null && !p.exists())
  220. p = p.getParentFile();
  221. if (p == null || p.isDirectory())
  222. throw new IOException(JGitText.get().cannotCreateDirectory);
  223. FileUtils.delete(p);
  224. if (!f.mkdirs())
  225. throw new IOException(JGitText.get().cannotCreateDirectory);
  226. }
  227. }
  228. /**
  229. * Reverts the worktree after an unsuccessful merge. We know that for all
  230. * modified files the old content was in the old index and the index
  231. * contained only stage 0. In case if inCore operation just clear the
  232. * history of modified files.
  233. *
  234. * @throws IOException
  235. * @throws CorruptObjectException
  236. * @throws NoWorkTreeException
  237. */
  238. private void cleanUp() throws NoWorkTreeException, CorruptObjectException,
  239. IOException {
  240. if (inCore) {
  241. modifiedFiles.clear();
  242. return;
  243. }
  244. DirCache dc = db.readDirCache();
  245. ObjectReader or = db.getObjectDatabase().newReader();
  246. Iterator<String> mpathsIt=modifiedFiles.iterator();
  247. while(mpathsIt.hasNext()) {
  248. String mpath=mpathsIt.next();
  249. DirCacheEntry entry = dc.getEntry(mpath);
  250. if (entry == null)
  251. continue;
  252. FileOutputStream fos = new FileOutputStream(new File(
  253. db.getWorkTree(), mpath));
  254. try {
  255. or.open(entry.getObjectId()).copyTo(fos);
  256. } finally {
  257. fos.close();
  258. }
  259. mpathsIt.remove();
  260. }
  261. }
  262. /**
  263. * adds a new path with the specified stage to the index builder
  264. *
  265. * @param path
  266. * @param p
  267. * @param stage
  268. * @param lastMod
  269. * @param len
  270. * @return the entry which was added to the index
  271. */
  272. private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
  273. long lastMod, long len) {
  274. if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
  275. DirCacheEntry e = new DirCacheEntry(path, stage);
  276. e.setFileMode(p.getEntryFileMode());
  277. e.setObjectId(p.getEntryObjectId());
  278. e.setLastModified(lastMod);
  279. e.setLength(len);
  280. builder.add(e);
  281. return e;
  282. }
  283. return null;
  284. }
  285. /**
  286. * adds a entry to the index builder which is a copy of the specified
  287. * DirCacheEntry
  288. *
  289. * @param e
  290. * the entry which should be copied
  291. *
  292. * @return the entry which was added to the index
  293. */
  294. private DirCacheEntry keep(DirCacheEntry e) {
  295. DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(),
  296. e.getStage());
  297. newEntry.setFileMode(e.getFileMode());
  298. newEntry.setObjectId(e.getObjectId());
  299. newEntry.setLastModified(e.getLastModified());
  300. newEntry.setLength(e.getLength());
  301. builder.add(newEntry);
  302. return newEntry;
  303. }
  304. /**
  305. * Processes one path and tries to merge. This method will do all do all
  306. * trivial (not content) merges and will also detect if a merge will fail.
  307. * The merge will fail when one of the following is true
  308. * <ul>
  309. * <li>the index entry does not match the entry in ours. When merging one
  310. * branch into the current HEAD, ours will point to HEAD and theirs will
  311. * point to the other branch. It is assumed that the index matches the HEAD
  312. * because it will only not match HEAD if it was populated before the merge
  313. * operation. But the merge commit should not accidentally contain
  314. * modifications done before the merge. Check the <a href=
  315. * "http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html#_3_way_merge"
  316. * >git read-tree</a> documentation for further explanations.</li>
  317. * <li>A conflict was detected and the working-tree file is dirty. When a
  318. * conflict is detected the content-merge algorithm will try to write a
  319. * merged version into the working-tree. If the file is dirty we would
  320. * override unsaved data.</li>
  321. *
  322. * @param base
  323. * the common base for ours and theirs
  324. * @param ours
  325. * the ours side of the merge. When merging a branch into the
  326. * HEAD ours will point to HEAD
  327. * @param theirs
  328. * the theirs side of the merge. When merging a branch into the
  329. * current HEAD theirs will point to the branch which is merged
  330. * into HEAD.
  331. * @param index
  332. * the index entry
  333. * @param work
  334. * the file in the working tree
  335. * @return <code>false</code> if the merge will fail because the index entry
  336. * didn't match ours or the working-dir file was dirty and a
  337. * conflict occurred
  338. * @throws MissingObjectException
  339. * @throws IncorrectObjectTypeException
  340. * @throws CorruptObjectException
  341. * @throws IOException
  342. */
  343. private boolean processEntry(CanonicalTreeParser base,
  344. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  345. DirCacheBuildIterator index, WorkingTreeIterator work)
  346. throws MissingObjectException, IncorrectObjectTypeException,
  347. CorruptObjectException, IOException {
  348. enterSubtree = true;
  349. final int modeO = tw.getRawMode(T_OURS);
  350. final int modeT = tw.getRawMode(T_THEIRS);
  351. final int modeB = tw.getRawMode(T_BASE);
  352. if (modeO == 0 && modeT == 0 && modeB == 0)
  353. // File is either untracked or new, staged but uncommitted
  354. return true;
  355. if (isIndexDirty())
  356. return false;
  357. DirCacheEntry ourDce = null;
  358. if (index == null || index.getDirCacheEntry() == null) {
  359. // create a fake DCE, but only if ours is valid. ours is kept only
  360. // in case it is valid, so a null ourDce is ok in all other cases.
  361. if (nonTree(modeO)) {
  362. ourDce = new DirCacheEntry(tw.getRawPath());
  363. ourDce.setObjectId(tw.getObjectId(T_OURS));
  364. ourDce.setFileMode(tw.getFileMode(T_OURS));
  365. }
  366. } else {
  367. ourDce = index.getDirCacheEntry();
  368. }
  369. if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) {
  370. // OURS and THEIRS have equal content. Check the file mode
  371. if (modeO == modeT) {
  372. // content and mode of OURS and THEIRS are equal: it doesn't
  373. // matter which one we choose. OURS is chosen. Since the index
  374. // is clean (the index matches already OURS) we can keep the existing one
  375. keep(ourDce);
  376. // no checkout needed!
  377. return true;
  378. } else {
  379. // same content but different mode on OURS and THEIRS.
  380. // Try to merge the mode and report an error if this is
  381. // not possible.
  382. int newMode = mergeFileModes(modeB, modeO, modeT);
  383. if (newMode != FileMode.MISSING.getBits()) {
  384. if (newMode == modeO)
  385. // ours version is preferred
  386. keep(ourDce);
  387. else {
  388. // the preferred version THEIRS has a different mode
  389. // than ours. Check it out!
  390. if (isWorktreeDirty(work))
  391. return false;
  392. // we know about length and lastMod only after we have written the new content.
  393. // This will happen later. Set these values to 0 for know.
  394. DirCacheEntry e = add(tw.getRawPath(), theirs,
  395. DirCacheEntry.STAGE_0, 0, 0);
  396. toBeCheckedOut.put(tw.getPathString(), e);
  397. }
  398. return true;
  399. } else {
  400. // FileModes are not mergeable. We found a conflict on modes.
  401. // For conflicting entries we don't know lastModified and length.
  402. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  403. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  404. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  405. unmergedPaths.add(tw.getPathString());
  406. mergeResults.put(
  407. tw.getPathString(),
  408. new MergeResult<RawText>(Collections
  409. .<RawText> emptyList()));
  410. }
  411. return true;
  412. }
  413. }
  414. if (nonTree(modeO) && modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) {
  415. // THEIRS was not changed compared to BASE. All changes must be in
  416. // OURS. OURS is chosen. We can keep the existing entry.
  417. keep(ourDce);
  418. // no checkout needed!
  419. return true;
  420. }
  421. if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) {
  422. // OURS was not changed compared to BASE. All changes must be in
  423. // THEIRS. THEIRS is chosen.
  424. // Check worktree before checking out THEIRS
  425. if (isWorktreeDirty(work))
  426. return false;
  427. if (nonTree(modeT)) {
  428. // we know about length and lastMod only after we have written
  429. // the new content.
  430. // This will happen later. Set these values to 0 for know.
  431. DirCacheEntry e = add(tw.getRawPath(), theirs,
  432. DirCacheEntry.STAGE_0, 0, 0);
  433. if (e != null)
  434. toBeCheckedOut.put(tw.getPathString(), e);
  435. return true;
  436. } else if (modeT == 0 && modeB != 0) {
  437. // we want THEIRS ... but THEIRS contains the deletion of the
  438. // file
  439. toBeDeleted.add(tw.getPathString());
  440. return true;
  441. }
  442. }
  443. if (tw.isSubtree()) {
  444. // file/folder conflicts: here I want to detect only file/folder
  445. // conflict between ours and theirs. file/folder conflicts between
  446. // base/index/workingTree and something else are not relevant or
  447. // detected later
  448. if (nonTree(modeO) && !nonTree(modeT)) {
  449. if (nonTree(modeB))
  450. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  451. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  452. unmergedPaths.add(tw.getPathString());
  453. enterSubtree = false;
  454. return true;
  455. }
  456. if (nonTree(modeT) && !nonTree(modeO)) {
  457. if (nonTree(modeB))
  458. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  459. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  460. unmergedPaths.add(tw.getPathString());
  461. enterSubtree = false;
  462. return true;
  463. }
  464. // ours and theirs are both folders or both files (and treewalk
  465. // tells us we are in a subtree because of index or working-dir).
  466. // If they are both folders no content-merge is required - we can
  467. // return here.
  468. if (!nonTree(modeO))
  469. return true;
  470. // ours and theirs are both files, just fall out of the if block
  471. // and do the content merge
  472. }
  473. if (nonTree(modeO) && nonTree(modeT)) {
  474. // Check worktree before modifying files
  475. if (isWorktreeDirty(work))
  476. return false;
  477. // Don't attempt to resolve submodule link conflicts
  478. if (isGitLink(modeO) || isGitLink(modeT)) {
  479. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  480. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  481. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  482. unmergedPaths.add(tw.getPathString());
  483. return true;
  484. }
  485. MergeResult<RawText> result = contentMerge(base, ours, theirs);
  486. File of = writeMergedFile(result);
  487. updateIndex(base, ours, theirs, result, of);
  488. if (result.containsConflicts())
  489. unmergedPaths.add(tw.getPathString());
  490. modifiedFiles.add(tw.getPathString());
  491. } else if (modeO != modeT) {
  492. // OURS or THEIRS has been deleted
  493. if (((modeO != 0 && !tw.idEqual(T_BASE, T_OURS)) || (modeT != 0 && !tw
  494. .idEqual(T_BASE, T_THEIRS)))) {
  495. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  496. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  497. DirCacheEntry e = add(tw.getRawPath(), theirs,
  498. DirCacheEntry.STAGE_3, 0, 0);
  499. // OURS was deleted checkout THEIRS
  500. if (modeO == 0) {
  501. // Check worktree before checking out THEIRS
  502. if (isWorktreeDirty(work))
  503. return false;
  504. if (nonTree(modeT)) {
  505. if (e != null)
  506. toBeCheckedOut.put(tw.getPathString(), e);
  507. }
  508. }
  509. unmergedPaths.add(tw.getPathString());
  510. // generate a MergeResult for the deleted file
  511. mergeResults.put(tw.getPathString(),
  512. contentMerge(base, ours, theirs));
  513. }
  514. }
  515. return true;
  516. }
  517. /**
  518. * Does the content merge. The three texts base, ours and theirs are
  519. * specified with {@link CanonicalTreeParser}. If any of the parsers is
  520. * specified as <code>null</code> then an empty text will be used instead.
  521. *
  522. * @param base
  523. * @param ours
  524. * @param theirs
  525. *
  526. * @return the result of the content merge
  527. * @throws IOException
  528. */
  529. private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
  530. CanonicalTreeParser ours, CanonicalTreeParser theirs)
  531. throws IOException {
  532. RawText baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
  533. base.getEntryObjectId(), db);
  534. RawText ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
  535. ours.getEntryObjectId(), db);
  536. RawText theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
  537. theirs.getEntryObjectId(), db);
  538. return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
  539. ourText, theirsText));
  540. }
  541. private boolean isIndexDirty() {
  542. if (inCore)
  543. return false;
  544. final int modeI = tw.getRawMode(T_INDEX);
  545. final int modeO = tw.getRawMode(T_OURS);
  546. // Index entry has to match ours to be considered clean
  547. final boolean isDirty = nonTree(modeI)
  548. && !(modeO == modeI && tw.idEqual(T_INDEX, T_OURS));
  549. if (isDirty)
  550. failingPaths
  551. .put(tw.getPathString(), MergeFailureReason.DIRTY_INDEX);
  552. return isDirty;
  553. }
  554. private boolean isWorktreeDirty(WorkingTreeIterator work) {
  555. if (work == null)
  556. return false;
  557. final int modeF = tw.getRawMode(T_FILE);
  558. final int modeO = tw.getRawMode(T_OURS);
  559. // Worktree entry has to match ours to be considered clean
  560. boolean isDirty = work.isModeDifferent(modeO);
  561. if (!isDirty && nonTree(modeF))
  562. isDirty = !tw.idEqual(T_FILE, T_OURS);
  563. if (isDirty)
  564. failingPaths.put(tw.getPathString(),
  565. MergeFailureReason.DIRTY_WORKTREE);
  566. return isDirty;
  567. }
  568. /**
  569. * Updates the index after a content merge has happened. If no conflict has
  570. * occurred this includes persisting the merged content to the object
  571. * database. In case of conflicts this method takes care to write the
  572. * correct stages to the index.
  573. *
  574. * @param base
  575. * @param ours
  576. * @param theirs
  577. * @param result
  578. * @param of
  579. * @throws FileNotFoundException
  580. * @throws IOException
  581. */
  582. private void updateIndex(CanonicalTreeParser base,
  583. CanonicalTreeParser ours, CanonicalTreeParser theirs,
  584. MergeResult<RawText> result, File of) throws FileNotFoundException,
  585. IOException {
  586. if (result.containsConflicts()) {
  587. // a conflict occurred, the file will contain conflict markers
  588. // the index will be populated with the three stages and only the
  589. // workdir (if used) contains the halfways merged content
  590. add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
  591. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
  592. add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
  593. mergeResults.put(tw.getPathString(), result);
  594. } else {
  595. // no conflict occurred, the file will contain fully merged content.
  596. // the index will be populated with the new merged version
  597. DirCacheEntry dce = new DirCacheEntry(tw.getPathString());
  598. int newMode = mergeFileModes(tw.getRawMode(0), tw.getRawMode(1),
  599. tw.getRawMode(2));
  600. // set the mode for the new content. Fall back to REGULAR_FILE if
  601. // you can't merge modes of OURS and THEIRS
  602. dce.setFileMode((newMode == FileMode.MISSING.getBits()) ? FileMode.REGULAR_FILE
  603. : FileMode.fromBits(newMode));
  604. dce.setLastModified(of.lastModified());
  605. dce.setLength((int) of.length());
  606. InputStream is = new FileInputStream(of);
  607. try {
  608. dce.setObjectId(getObjectInserter().insert(
  609. Constants.OBJ_BLOB, of.length(), is));
  610. } finally {
  611. is.close();
  612. if (inCore)
  613. FileUtils.delete(of);
  614. }
  615. builder.add(dce);
  616. }
  617. }
  618. /**
  619. * Writes merged file content to the working tree. In case {@link #inCore}
  620. * is set and we don't have a working tree the content is written to a
  621. * temporary file
  622. *
  623. * @param result
  624. * the result of the content merge
  625. * @return the file to which the merged content was written
  626. * @throws FileNotFoundException
  627. * @throws IOException
  628. */
  629. private File writeMergedFile(MergeResult<RawText> result)
  630. throws FileNotFoundException, IOException {
  631. MergeFormatter fmt = new MergeFormatter();
  632. File of = null;
  633. FileOutputStream fos;
  634. if (!inCore) {
  635. File workTree = db.getWorkTree();
  636. if (workTree == null)
  637. // TODO: This should be handled by WorkingTreeIterators which
  638. // support write operations
  639. throw new UnsupportedOperationException();
  640. of = new File(workTree, tw.getPathString());
  641. File parentFolder = of.getParentFile();
  642. if (!parentFolder.exists())
  643. parentFolder.mkdirs();
  644. fos = new FileOutputStream(of);
  645. try {
  646. fmt.formatMerge(fos, result, Arrays.asList(commitNames),
  647. Constants.CHARACTER_ENCODING);
  648. } finally {
  649. fos.close();
  650. }
  651. } else if (!result.containsConflicts()) {
  652. // When working inCore, only trivial merges can be handled,
  653. // so we generate objects only in conflict free cases
  654. of = File.createTempFile("merge_", "_temp", null); //$NON-NLS-1$ //$NON-NLS-2$
  655. fos = new FileOutputStream(of);
  656. try {
  657. fmt.formatMerge(fos, result, Arrays.asList(commitNames),
  658. Constants.CHARACTER_ENCODING);
  659. } finally {
  660. fos.close();
  661. }
  662. }
  663. return of;
  664. }
  665. /**
  666. * Try to merge filemodes. If only ours or theirs have changed the mode
  667. * (compared to base) we choose that one. If ours and theirs have equal
  668. * modes return that one. If also that is not the case the modes are not
  669. * mergeable. Return {@link FileMode#MISSING} int that case.
  670. *
  671. * @param modeB
  672. * filemode found in BASE
  673. * @param modeO
  674. * filemode found in OURS
  675. * @param modeT
  676. * filemode found in THEIRS
  677. *
  678. * @return the merged filemode or {@link FileMode#MISSING} in case of a
  679. * conflict
  680. */
  681. private int mergeFileModes(int modeB, int modeO, int modeT) {
  682. if (modeO == modeT)
  683. return modeO;
  684. if (modeB == modeO)
  685. // Base equal to Ours -> chooses Theirs if that is not missing
  686. return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT;
  687. if (modeB == modeT)
  688. // Base equal to Theirs -> chooses Ours if that is not missing
  689. return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
  690. return FileMode.MISSING.getBits();
  691. }
  692. private static RawText getRawText(ObjectId id, Repository db)
  693. throws IOException {
  694. if (id.equals(ObjectId.zeroId()))
  695. return new RawText(new byte[] {});
  696. return new RawText(db.open(id, Constants.OBJ_BLOB).getCachedBytes());
  697. }
  698. private static boolean nonTree(final int mode) {
  699. return mode != 0 && !FileMode.TREE.equals(mode);
  700. }
  701. private static boolean isGitLink(final int mode) {
  702. return FileMode.GITLINK.equals(mode);
  703. }
  704. @Override
  705. public ObjectId getResultTreeId() {
  706. return (resultTree == null) ? null : resultTree.toObjectId();
  707. }
  708. /**
  709. * @param commitNames
  710. * the names of the commits as they would appear in conflict
  711. * markers
  712. */
  713. public void setCommitNames(String[] commitNames) {
  714. this.commitNames = commitNames;
  715. }
  716. /**
  717. * @return the names of the commits as they would appear in conflict
  718. * markers.
  719. */
  720. public String[] getCommitNames() {
  721. return commitNames;
  722. }
  723. /**
  724. * @return the paths with conflicts. This is a subset of the files listed
  725. * by {@link #getModifiedFiles()}
  726. */
  727. public List<String> getUnmergedPaths() {
  728. return unmergedPaths;
  729. }
  730. /**
  731. * @return the paths of files which have been modified by this merge. A
  732. * file will be modified if a content-merge works on this path or if
  733. * the merge algorithm decides to take the theirs-version. This is a
  734. * superset of the files listed by {@link #getUnmergedPaths()}.
  735. */
  736. public List<String> getModifiedFiles() {
  737. return modifiedFiles;
  738. }
  739. /**
  740. * @return a map which maps the paths of files which have to be checked out
  741. * because the merge created new fully-merged content for this file
  742. * into the index. This means: the merge wrote a new stage 0 entry
  743. * for this path.
  744. */
  745. public Map<String, DirCacheEntry> getToBeCheckedOut() {
  746. return toBeCheckedOut;
  747. }
  748. /**
  749. * @return the mergeResults
  750. */
  751. public Map<String, MergeResult<? extends Sequence>> getMergeResults() {
  752. return mergeResults;
  753. }
  754. /**
  755. * @return lists paths causing this merge to fail (not stopped because of a
  756. * conflict). <code>null</code> is returned if this merge didn't
  757. * fail.
  758. */
  759. public Map<String, MergeFailureReason> getFailingPaths() {
  760. return (failingPaths.size() == 0) ? null : failingPaths;
  761. }
  762. /**
  763. * Returns whether this merge failed (i.e. not stopped because of a
  764. * conflict)
  765. *
  766. * @return <code>true</code> if a failure occurred, <code>false</code>
  767. * otherwise
  768. */
  769. public boolean failed() {
  770. return failingPaths.size() > 0;
  771. }
  772. /**
  773. * Sets the DirCache which shall be used by this merger. If the DirCache is
  774. * not set explicitly and if this merger doesn't work in-core, this merger
  775. * will implicitly get and lock a default DirCache. If the DirCache is
  776. * explicitly set the caller is responsible to lock it in advance. Finally
  777. * the merger will call {@link DirCache#commit()} which requires that the
  778. * DirCache is locked. If the {@link #mergeImpl()} returns without throwing
  779. * an exception the lock will be released. In case of exceptions the caller
  780. * is responsible to release the lock.
  781. *
  782. * @param dc
  783. * the DirCache to set
  784. */
  785. public void setDirCache(DirCache dc) {
  786. this.dircache = dc;
  787. implicitDirCache = false;
  788. }
  789. /**
  790. * Sets the WorkingTreeIterator to be used by this merger. If no
  791. * WorkingTreeIterator is set this merger will ignore the working tree and
  792. * fail if a content merge is necessary.
  793. * <p>
  794. * TODO: enhance WorkingTreeIterator to support write operations. Then this
  795. * merger will be able to merge with a different working tree abstraction.
  796. *
  797. * @param workingTreeIterator
  798. * the workingTreeIt to set
  799. */
  800. public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
  801. this.workingTreeIterator = workingTreeIterator;
  802. }
  803. /**
  804. * The resolve conflict way of three way merging
  805. *
  806. * @param baseTree
  807. * @param headTree
  808. * @param mergeTree
  809. * @return whether the trees merged cleanly
  810. * @throws IOException
  811. */
  812. protected boolean mergeTrees(AbstractTreeIterator baseTree,
  813. RevTree headTree, RevTree mergeTree) throws IOException {
  814. builder = dircache.builder();
  815. DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
  816. tw = new NameConflictTreeWalk(db);
  817. tw.addTree(baseTree);
  818. tw.addTree(headTree);
  819. tw.addTree(mergeTree);
  820. tw.addTree(buildIt);
  821. if (workingTreeIterator != null)
  822. tw.addTree(workingTreeIterator);
  823. while (tw.next()) {
  824. if (!processEntry(
  825. tw.getTree(T_BASE, CanonicalTreeParser.class),
  826. tw.getTree(T_OURS, CanonicalTreeParser.class),
  827. tw.getTree(T_THEIRS, CanonicalTreeParser.class),
  828. tw.getTree(T_INDEX, DirCacheBuildIterator.class),
  829. (workingTreeIterator == null) ? null : tw.getTree(T_FILE,
  830. WorkingTreeIterator.class))) {
  831. cleanUp();
  832. return false;
  833. }
  834. if (tw.isSubtree() && enterSubtree)
  835. tw.enterSubtree();
  836. }
  837. if (!inCore) {
  838. // No problem found. The only thing left to be done is to
  839. // checkout all files from "theirs" which have been selected to
  840. // go into the new index.
  841. checkout();
  842. // All content-merges are successfully done. If we can now write the
  843. // new index we are on quite safe ground. Even if the checkout of
  844. // files coming from "theirs" fails the user can work around such
  845. // failures by checking out the index again.
  846. if (!builder.commit()) {
  847. cleanUp();
  848. throw new IndexWriteException();
  849. }
  850. builder = null;
  851. } else {
  852. builder.finish();
  853. builder = null;
  854. }
  855. if (getUnmergedPaths().isEmpty() && !failed()) {
  856. resultTree = dircache.writeTree(getObjectInserter());
  857. return true;
  858. } else {
  859. resultTree = null;
  860. return false;
  861. }
  862. }
  863. }