MergeAlgorithm.java

  1. /*
  2.  * Copyright (C) 2009, Christian Halstrick <christian.halstrick@sap.com>
  3.  * and other copyright owners as documented in the project's IP log.
  4.  *
  5.  * This program and the accompanying materials are made available
  6.  * under the terms of the Eclipse Distribution License v1.0 which
  7.  * accompanies this distribution, is reproduced below, and is
  8.  * available at http://www.eclipse.org/org/documents/edl-v10.php
  9.  *
  10.  * All rights reserved.
  11.  *
  12.  * Redistribution and use in source and binary forms, with or
  13.  * without modification, are permitted provided that the following
  14.  * conditions are met:
  15.  *
  16.  * - Redistributions of source code must retain the above copyright
  17.  *   notice, this list of conditions and the following disclaimer.
  18.  *
  19.  * - Redistributions in binary form must reproduce the above
  20.  *   copyright notice, this list of conditions and the following
  21.  *   disclaimer in the documentation and/or other materials provided
  22.  *   with the distribution.
  23.  *
  24.  * - Neither the name of the Eclipse Foundation, Inc. nor the
  25.  *   names of its contributors may be used to endorse or promote
  26.  *   products derived from this software without specific prior
  27.  *   written permission.
  28.  *
  29.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30.  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31.  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33.  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42.  */

  43. package org.eclipse.jgit.merge;

  44. import java.util.ArrayList;
  45. import java.util.Iterator;
  46. import java.util.List;

  47. import org.eclipse.jgit.diff.DiffAlgorithm;
  48. import org.eclipse.jgit.diff.Edit;
  49. import org.eclipse.jgit.diff.EditList;
  50. import org.eclipse.jgit.diff.HistogramDiff;
  51. import org.eclipse.jgit.diff.Sequence;
  52. import org.eclipse.jgit.diff.SequenceComparator;
  53. import org.eclipse.jgit.merge.MergeChunk.ConflictState;

  54. /**
  55.  * Provides the merge algorithm which does a three-way merge on content provided
  56.  * as RawText. By default {@link org.eclipse.jgit.diff.HistogramDiff} is used as
  57.  * diff algorithm.
  58.  */
  59. public final class MergeAlgorithm {
  60.     private final DiffAlgorithm diffAlg;

  61.     /**
  62.      * Creates a new MergeAlgorithm which uses
  63.      * {@link org.eclipse.jgit.diff.HistogramDiff} as diff algorithm
  64.      */
  65.     public MergeAlgorithm() {
  66.         this(new HistogramDiff());
  67.     }

  68.     /**
  69.      * Creates a new MergeAlgorithm
  70.      *
  71.      * @param diff
  72.      *            the diff algorithm used by this merge
  73.      */
  74.     public MergeAlgorithm(DiffAlgorithm diff) {
  75.         this.diffAlg = diff;
  76.     }

  77.     // An special edit which acts as a sentinel value by marking the end the
  78.     // list of edits
  79.     private final static Edit END_EDIT = new Edit(Integer.MAX_VALUE,
  80.             Integer.MAX_VALUE);

  81.     /**
  82.      * Does the three way merge between a common base and two sequences.
  83.      *
  84.      * @param cmp comparison method for this execution.
  85.      * @param base the common base sequence
  86.      * @param ours the first sequence to be merged
  87.      * @param theirs the second sequence to be merged
  88.      * @return the resulting content
  89.      */
  90.     public <S extends Sequence> MergeResult<S> merge(
  91.             SequenceComparator<S> cmp, S base, S ours, S theirs) {
  92.         List<S> sequences = new ArrayList<>(3);
  93.         sequences.add(base);
  94.         sequences.add(ours);
  95.         sequences.add(theirs);
  96.         MergeResult<S> result = new MergeResult<>(sequences);

  97.         if (ours.size() == 0) {
  98.             if (theirs.size() != 0) {
  99.                 EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
  100.                 if (!theirsEdits.isEmpty()) {
  101.                     // we deleted, they modified -> Let their complete content
  102.                     // conflict with empty text
  103.                     result.add(1, 0, 0, ConflictState.FIRST_CONFLICTING_RANGE);
  104.                     result.add(2, 0, theirs.size(),
  105.                             ConflictState.NEXT_CONFLICTING_RANGE);
  106.                 } else
  107.                     // we deleted, they didn't modify -> Let our deletion win
  108.                     result.add(1, 0, 0, ConflictState.NO_CONFLICT);
  109.             } else
  110.                 // we and they deleted -> return a single chunk of nothing
  111.                 result.add(1, 0, 0, ConflictState.NO_CONFLICT);
  112.             return result;
  113.         } else if (theirs.size() == 0) {
  114.             EditList oursEdits = diffAlg.diff(cmp, base, ours);
  115.             if (!oursEdits.isEmpty()) {
  116.                 // we modified, they deleted -> Let our complete content
  117.                 // conflict with empty text
  118.                 result.add(1, 0, ours.size(),
  119.                         ConflictState.FIRST_CONFLICTING_RANGE);
  120.                 result.add(2, 0, 0, ConflictState.NEXT_CONFLICTING_RANGE);
  121.             } else
  122.                 // they deleted, we didn't modify -> Let their deletion win
  123.                 result.add(2, 0, 0, ConflictState.NO_CONFLICT);
  124.             return result;
  125.         }

  126.         EditList oursEdits = diffAlg.diff(cmp, base, ours);
  127.         Iterator<Edit> baseToOurs = oursEdits.iterator();
  128.         EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
  129.         Iterator<Edit> baseToTheirs = theirsEdits.iterator();
  130.         int current = 0; // points to the next line (first line is 0) of base
  131.                          // which was not handled yet
  132.         Edit oursEdit = nextEdit(baseToOurs);
  133.         Edit theirsEdit = nextEdit(baseToTheirs);

  134.         // iterate over all edits from base to ours and from base to theirs
  135.         // leave the loop when there are no edits more for ours or for theirs
  136.         // (or both)
  137.         while (theirsEdit != END_EDIT || oursEdit != END_EDIT) {
  138.             if (oursEdit.getEndA() < theirsEdit.getBeginA()) {
  139.                 // something was changed in ours not overlapping with any change
  140.                 // from theirs. First add the common part in front of the edit
  141.                 // then the edit.
  142.                 if (current != oursEdit.getBeginA()) {
  143.                     result.add(0, current, oursEdit.getBeginA(),
  144.                             ConflictState.NO_CONFLICT);
  145.                 }
  146.                 result.add(1, oursEdit.getBeginB(), oursEdit.getEndB(),
  147.                         ConflictState.NO_CONFLICT);
  148.                 current = oursEdit.getEndA();
  149.                 oursEdit = nextEdit(baseToOurs);
  150.             } else if (theirsEdit.getEndA() < oursEdit.getBeginA()) {
  151.                 // something was changed in theirs not overlapping with any
  152.                 // from ours. First add the common part in front of the edit
  153.                 // then the edit.
  154.                 if (current != theirsEdit.getBeginA()) {
  155.                     result.add(0, current, theirsEdit.getBeginA(),
  156.                             ConflictState.NO_CONFLICT);
  157.                 }
  158.                 result.add(2, theirsEdit.getBeginB(), theirsEdit.getEndB(),
  159.                         ConflictState.NO_CONFLICT);
  160.                 current = theirsEdit.getEndA();
  161.                 theirsEdit = nextEdit(baseToTheirs);
  162.             } else {
  163.                 // here we found a real overlapping modification

  164.                 // if there is a common part in front of the conflict add it
  165.                 if (oursEdit.getBeginA() != current
  166.                         && theirsEdit.getBeginA() != current) {
  167.                     result.add(0, current, Math.min(oursEdit.getBeginA(),
  168.                             theirsEdit.getBeginA()), ConflictState.NO_CONFLICT);
  169.                 }

  170.                 // set some initial values for the ranges in A and B which we
  171.                 // want to handle
  172.                 int oursBeginB = oursEdit.getBeginB();
  173.                 int theirsBeginB = theirsEdit.getBeginB();
  174.                 // harmonize the start of the ranges in A and B
  175.                 if (oursEdit.getBeginA() < theirsEdit.getBeginA()) {
  176.                     theirsBeginB -= theirsEdit.getBeginA()
  177.                             - oursEdit.getBeginA();
  178.                 } else {
  179.                     oursBeginB -= oursEdit.getBeginA() - theirsEdit.getBeginA();
  180.                 }

  181.                 // combine edits:
  182.                 // Maybe an Edit on one side corresponds to multiple Edits on
  183.                 // the other side. Then we have to combine the Edits of the
  184.                 // other side - so in the end we can merge together two single
  185.                 // edits.
  186.                 //
  187.                 // It is important to notice that this combining will extend the
  188.                 // ranges of our conflict always downwards (towards the end of
  189.                 // the content). The starts of the conflicting ranges in ours
  190.                 // and theirs are not touched here.
  191.                 //
  192.                 // This combining is an iterative process: after we have
  193.                 // combined some edits we have to do the check again. The
  194.                 // combined edits could now correspond to multiple edits on the
  195.                 // other side.
  196.                 //
  197.                 // Example: when this combining algorithm works on the following
  198.                 // edits
  199.                 // oursEdits=((0-5,0-5),(6-8,6-8),(10-11,10-11)) and
  200.                 // theirsEdits=((0-1,0-1),(2-3,2-3),(5-7,5-7))
  201.                 // it will merge them into
  202.                 // oursEdits=((0-8,0-8),(10-11,10-11)) and
  203.                 // theirsEdits=((0-7,0-7))
  204.                 //
  205.                 // Since the only interesting thing to us is how in ours and
  206.                 // theirs the end of the conflicting range is changing we let
  207.                 // oursEdit and theirsEdit point to the last conflicting edit
  208.                 Edit nextOursEdit = nextEdit(baseToOurs);
  209.                 Edit nextTheirsEdit = nextEdit(baseToTheirs);
  210.                 for (;;) {
  211.                     if (oursEdit.getEndA() >= nextTheirsEdit.getBeginA()) {
  212.                         theirsEdit = nextTheirsEdit;
  213.                         nextTheirsEdit = nextEdit(baseToTheirs);
  214.                     } else if (theirsEdit.getEndA() >= nextOursEdit.getBeginA()) {
  215.                         oursEdit = nextOursEdit;
  216.                         nextOursEdit = nextEdit(baseToOurs);
  217.                     } else {
  218.                         break;
  219.                     }
  220.                 }

  221.                 // harmonize the end of the ranges in A and B
  222.                 int oursEndB = oursEdit.getEndB();
  223.                 int theirsEndB = theirsEdit.getEndB();
  224.                 if (oursEdit.getEndA() < theirsEdit.getEndA()) {
  225.                     oursEndB += theirsEdit.getEndA() - oursEdit.getEndA();
  226.                 } else {
  227.                     theirsEndB += oursEdit.getEndA() - theirsEdit.getEndA();
  228.                 }

  229.                 // A conflicting region is found. Strip off common lines in
  230.                 // in the beginning and the end of the conflicting region

  231.                 // Determine the minimum length of the conflicting areas in OURS
  232.                 // and THEIRS. Also determine how much bigger the conflicting
  233.                 // area in THEIRS is compared to OURS. All that is needed to
  234.                 // limit the search for common areas at the beginning or end
  235.                 // (the common areas cannot be bigger then the smaller
  236.                 // conflicting area. The delta is needed to know whether the
  237.                 // complete conflicting area is common in OURS and THEIRS.
  238.                 int minBSize = oursEndB - oursBeginB;
  239.                 int BSizeDelta = minBSize - (theirsEndB - theirsBeginB);
  240.                 if (BSizeDelta > 0)
  241.                     minBSize -= BSizeDelta;

  242.                 int commonPrefix = 0;
  243.                 while (commonPrefix < minBSize
  244.                         && cmp.equals(ours, oursBeginB + commonPrefix, theirs,
  245.                                 theirsBeginB + commonPrefix))
  246.                     commonPrefix++;
  247.                 minBSize -= commonPrefix;
  248.                 int commonSuffix = 0;
  249.                 while (commonSuffix < minBSize
  250.                         && cmp.equals(ours, oursEndB - commonSuffix - 1, theirs,
  251.                                 theirsEndB - commonSuffix - 1))
  252.                     commonSuffix++;
  253.                 minBSize -= commonSuffix;

  254.                 // Add the common lines at start of conflict
  255.                 if (commonPrefix > 0)
  256.                     result.add(1, oursBeginB, oursBeginB + commonPrefix,
  257.                             ConflictState.NO_CONFLICT);

  258.                 // Add the conflict (Only if there is a conflict left to report)
  259.                 if (minBSize > 0 || BSizeDelta != 0) {
  260.                     result.add(1, oursBeginB + commonPrefix, oursEndB
  261.                             - commonSuffix,
  262.                             ConflictState.FIRST_CONFLICTING_RANGE);
  263.                     result.add(2, theirsBeginB + commonPrefix, theirsEndB
  264.                             - commonSuffix,
  265.                             ConflictState.NEXT_CONFLICTING_RANGE);
  266.                 }

  267.                 // Add the common lines at end of conflict
  268.                 if (commonSuffix > 0)
  269.                     result.add(1, oursEndB - commonSuffix, oursEndB,
  270.                             ConflictState.NO_CONFLICT);

  271.                 current = Math.max(oursEdit.getEndA(), theirsEdit.getEndA());
  272.                 oursEdit = nextOursEdit;
  273.                 theirsEdit = nextTheirsEdit;
  274.             }
  275.         }
  276.         // maybe we have a common part behind the last edit: copy it to the
  277.         // result
  278.         if (current < base.size()) {
  279.             result.add(0, current, base.size(), ConflictState.NO_CONFLICT);
  280.         }
  281.         return result;
  282.     }

  283.     /**
  284.      * Helper method which returns the next Edit for an Iterator over Edits.
  285.      * When there are no more edits left this method will return the constant
  286.      * END_EDIT.
  287.      *
  288.      * @param it
  289.      *            the iterator for which the next edit should be returned
  290.      * @return the next edit from the iterator or END_EDIT if there no more
  291.      *         edits
  292.      */
  293.     private static Edit nextEdit(Iterator<Edit> it) {
  294.         return (it.hasNext() ? it.next() : END_EDIT);
  295.     }
  296. }