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

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