/* * Copyright (C) 2021, Thomas Wolf and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; /** * How to handle content conflicts. * * @since 5.12 */ public enum ContentMergeStrategy { /** Produce a conflict. */ CONFLICT, /** Resolve the conflict hunk using the ours version. */ OURS, /** Resolve the conflict hunk using the theirs version. */ THEIRS, /** * Resolve the conflict hunk using a union of both ours and theirs versions. * * @since 6.10.1 */ UNION } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 3023 Content-Disposition: inline; filename="EolAwareOutputStream.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "8857ef8571045852e385d8744109fd2b3fc72495" /* * Copyright (C) 2014, André de Oliveira * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.jgit.merge; import java.io.IOException; import java.io.OutputStream; /** * An output stream which is aware of newlines and can be asked to begin a new * line if not already in one. */ class EolAwareOutputStream extends OutputStream { private final OutputStream out; private boolean bol = true; /** * Initialize a new EOL aware stream. * * @param out * stream to output all writes to. */ EolAwareOutputStream(OutputStream out) { this.out = out; } /** * Begin a new line if not already in one. * * @exception IOException * if an I/O error occurs. */ void beginln() throws IOException { if (!bol) write('\n'); } /** * Whether a new line has just begun * * @return true if a new line has just begun. */ boolean isBeginln() { return bol; } @Override public void write(int val) throws IOException { out.write(val); bol = (val == '\n'); } @Override public void write(byte[] buf, int pos, int cnt) throws IOException { if (cnt > 0) { out.write(buf, pos, cnt); bol = (buf[pos + (cnt - 1)] == '\n'); } } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 13435 Content-Disposition: inline; filename="MergeAlgorithm.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "d0d4d367b91ee6a19a5cd8d01ea6a5745aa9e26a" /* * Copyright (C) 2009, Christian Halstrick and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.diff.DiffAlgorithm; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.diff.EditList; import org.eclipse.jgit.diff.HistogramDiff; import org.eclipse.jgit.diff.Sequence; import org.eclipse.jgit.diff.SequenceComparator; import org.eclipse.jgit.merge.MergeChunk.ConflictState; /** * Provides the merge algorithm which does a three-way merge on content provided * as RawText. By default {@link org.eclipse.jgit.diff.HistogramDiff} is used as * diff algorithm. */ public final class MergeAlgorithm { private final DiffAlgorithm diffAlg; @NonNull private ContentMergeStrategy strategy = ContentMergeStrategy.CONFLICT; /** * Creates a new MergeAlgorithm which uses * {@link org.eclipse.jgit.diff.HistogramDiff} as diff algorithm */ public MergeAlgorithm() { this(new HistogramDiff()); } /** * Creates a new MergeAlgorithm * * @param diff * the diff algorithm used by this merge */ public MergeAlgorithm(DiffAlgorithm diff) { this.diffAlg = diff; } /** * Retrieves the {@link ContentMergeStrategy}. * * @return the {@link ContentMergeStrategy} in effect * @since 5.12 */ @NonNull public ContentMergeStrategy getContentMergeStrategy() { return strategy; } /** * Sets the {@link ContentMergeStrategy}. * * @param strategy * {@link ContentMergeStrategy} to set; if {@code null}, set * {@link ContentMergeStrategy#CONFLICT} * @since 5.12 */ public void setContentMergeStrategy(ContentMergeStrategy strategy) { this.strategy = strategy == null ? ContentMergeStrategy.CONFLICT : strategy; } // An special edit which acts as a sentinel value by marking the end the // list of edits private static final Edit END_EDIT = new Edit(Integer.MAX_VALUE, Integer.MAX_VALUE); @SuppressWarnings("ReferenceEquality") private static boolean isEndEdit(Edit edit) { return edit == END_EDIT; } /** * Does the three way merge between a common base and two sequences. * * @param * type of the sequences * @param cmp * comparison method for this execution. * @param base * the common base sequence * @param ours * the first sequence to be merged * @param theirs * the second sequence to be merged * @return the resulting content */ public MergeResult merge( SequenceComparator cmp, S base, S ours, S theirs) { List sequences = new ArrayList<>(3); sequences.add(base); sequences.add(ours); sequences.add(theirs); MergeResult result = new MergeResult<>(sequences); if (ours.size() == 0) { if (theirs.size() != 0) { EditList theirsEdits = diffAlg.diff(cmp, base, theirs); if (!theirsEdits.isEmpty()) { // we deleted, they modified switch (strategy) { case OURS: result.add(1, 0, 0, ConflictState.NO_CONFLICT); break; case THEIRS: case UNION: result.add(2, 0, theirs.size(), ConflictState.NO_CONFLICT); break; default: // Let their complete content conflict with empty text result.add(1, 0, 0, ConflictState.FIRST_CONFLICTING_RANGE); result.add(0, 0, base.size(), ConflictState.BASE_CONFLICTING_RANGE); result.add(2, 0, theirs.size(), ConflictState.NEXT_CONFLICTING_RANGE); break; } } else { // we deleted, they didn't modify -> Let our deletion win result.add(1, 0, 0, ConflictState.NO_CONFLICT); } } else { // we and they deleted -> return a single chunk of nothing result.add(1, 0, 0, ConflictState.NO_CONFLICT); } return result; } else if (theirs.size() == 0) { EditList oursEdits = diffAlg.diff(cmp, base, ours); if (!oursEdits.isEmpty()) { // we modified, they deleted switch (strategy) { case OURS: case UNION: result.add(1, 0, ours.size(), ConflictState.NO_CONFLICT); break; case THEIRS: result.add(2, 0, 0, ConflictState.NO_CONFLICT); break; default: // Let our complete content conflict with empty text result.add(1, 0, ours.size(), ConflictState.FIRST_CONFLICTING_RANGE); result.add(0, 0, base.size(), ConflictState.BASE_CONFLICTING_RANGE); result.add(2, 0, 0, ConflictState.NEXT_CONFLICTING_RANGE); break; } } else { // they deleted, we didn't modify -> Let their deletion win result.add(2, 0, 0, ConflictState.NO_CONFLICT); } return result; } EditList oursEdits = diffAlg.diff(cmp, base, ours); Iterator baseToOurs = oursEdits.iterator(); EditList theirsEdits = diffAlg.diff(cmp, base, theirs); Iterator baseToTheirs = theirsEdits.iterator(); int current = 0; // points to the next line (first line is 0) of base // which was not handled yet Edit oursEdit = nextEdit(baseToOurs); Edit theirsEdit = nextEdit(baseToTheirs); // iterate over all edits from base to ours and from base to theirs // leave the loop when there are no edits more for ours or for theirs // (or both) while (!isEndEdit(theirsEdit) || !isEndEdit(oursEdit)) { if (oursEdit.getEndA() < theirsEdit.getBeginA()) { // something was changed in ours not overlapping with any change // from theirs. First add the common part in front of the edit // then the edit. if (current != oursEdit.getBeginA()) { result.add(0, current, oursEdit.getBeginA(), ConflictState.NO_CONFLICT); } result.add(1, oursEdit.getBeginB(), oursEdit.getEndB(), ConflictState.NO_CONFLICT); current = oursEdit.getEndA(); oursEdit = nextEdit(baseToOurs); } else if (theirsEdit.getEndA() < oursEdit.getBeginA()) { // something was changed in theirs not overlapping with any // from ours. First add the common part in front of the edit // then the edit. if (current != theirsEdit.getBeginA()) { result.add(0, current, theirsEdit.getBeginA(), ConflictState.NO_CONFLICT); } result.add(2, theirsEdit.getBeginB(), theirsEdit.getEndB(), ConflictState.NO_CONFLICT); current = theirsEdit.getEndA(); theirsEdit = nextEdit(baseToTheirs); } else { // here we found a real overlapping modification // if there is a common part in front of the conflict add it if (oursEdit.getBeginA() != current && theirsEdit.getBeginA() != current) { result.add(0, current, Math.min(oursEdit.getBeginA(), theirsEdit.getBeginA()), ConflictState.NO_CONFLICT); } // set some initial values for the ranges in A and B which we // want to handle int oursBeginA = oursEdit.getBeginA(); int theirsBeginA = theirsEdit.getBeginA(); int oursBeginB = oursEdit.getBeginB(); int theirsBeginB = theirsEdit.getBeginB(); // harmonize the start of the ranges in A and B if (oursEdit.getBeginA() < theirsEdit.getBeginA()) { theirsBeginA -= theirsEdit.getBeginA() - oursEdit.getBeginA(); theirsBeginB -= theirsEdit.getBeginA() - oursEdit.getBeginA(); } else { oursBeginA -= oursEdit.getBeginA() - theirsEdit.getBeginA(); oursBeginB -= oursEdit.getBeginA() - theirsEdit.getBeginA(); } // combine edits: // Maybe an Edit on one side corresponds to multiple Edits on // the other side. Then we have to combine the Edits of the // other side - so in the end we can merge together two single // edits. // // It is important to notice that this combining will extend the // ranges of our conflict always downwards (towards the end of // the content). The starts of the conflicting ranges in ours // and theirs are not touched here. // // This combining is an iterative process: after we have // combined some edits we have to do the check again. The // combined edits could now correspond to multiple edits on the // other side. // // Example: when this combining algorithm works on the following // edits // oursEdits=((0-5,0-5),(6-8,6-8),(10-11,10-11)) and // theirsEdits=((0-1,0-1),(2-3,2-3),(5-7,5-7)) // it will merge them into // oursEdits=((0-8,0-8),(10-11,10-11)) and // theirsEdits=((0-7,0-7)) // // Since the only interesting thing to us is how in ours and // theirs the end of the conflicting range is changing we let // oursEdit and theirsEdit point to the last conflicting edit Edit nextOursEdit = nextEdit(baseToOurs); Edit nextTheirsEdit = nextEdit(baseToTheirs); for (;;) { if (oursEdit.getEndA() >= nextTheirsEdit.getBeginA()) { theirsEdit = nextTheirsEdit; nextTheirsEdit = nextEdit(baseToTheirs); } else if (theirsEdit.getEndA() >= nextOursEdit.getBeginA()) { oursEdit = nextOursEdit; nextOursEdit = nextEdit(baseToOurs); } else { break; } } // harmonize the end of the ranges in A and B int oursEndA = oursEdit.getEndA(); int theirsEndA = theirsEdit.getEndA(); int oursEndB = oursEdit.getEndB(); int theirsEndB = theirsEdit.getEndB(); if (oursEdit.getEndA() < theirsEdit.getEndA()) { oursEndA += theirsEdit.getEndA() - oursEdit.getEndA(); oursEndB += theirsEdit.getEndA() - oursEdit.getEndA(); } else { theirsEndA += oursEdit.getEndA() - theirsEdit.getEndA(); theirsEndB += oursEdit.getEndA() - theirsEdit.getEndA(); } // A conflicting region is found. Strip off common lines in // in the beginning and the end of the conflicting region // Determine the minimum length of the conflicting areas in OURS // and THEIRS. Also determine how much bigger the conflicting // area in THEIRS is compared to OURS. All that is needed to // limit the search for common areas at the beginning or end // (the common areas cannot be bigger then the smaller // conflicting area. The delta is needed to know whether the // complete conflicting area is common in OURS and THEIRS. int minBSize = oursEndB - oursBeginB; int BSizeDelta = minBSize - (theirsEndB - theirsBeginB); if (BSizeDelta > 0) minBSize -= BSizeDelta; int commonPrefix = 0; while (commonPrefix < minBSize && cmp.equals(ours, oursBeginB + commonPrefix, theirs, theirsBeginB + commonPrefix)) commonPrefix++; minBSize -= commonPrefix; int commonSuffix = 0; while (commonSuffix < minBSize && cmp.equals(ours, oursEndB - commonSuffix - 1, theirs, theirsEndB - commonSuffix - 1)) commonSuffix++; minBSize -= commonSuffix; // Add the common lines at start of conflict if (commonPrefix > 0) result.add(1, oursBeginB, oursBeginB + commonPrefix, ConflictState.NO_CONFLICT); // Add the conflict (Only if there is a conflict left to report) if (minBSize > 0 || BSizeDelta != 0) { switch (strategy) { case OURS: result.add(1, oursBeginB + commonPrefix, oursEndB - commonSuffix, ConflictState.NO_CONFLICT); break; case THEIRS: result.add(2, theirsBeginB + commonPrefix, theirsEndB - commonSuffix, ConflictState.NO_CONFLICT); break; case UNION: result.add(1, oursBeginB + commonPrefix, oursEndB - commonSuffix, ConflictState.NO_CONFLICT); result.add(2, theirsBeginB + commonPrefix, theirsEndB - commonSuffix, ConflictState.NO_CONFLICT); break; default: result.add(1, oursBeginB + commonPrefix, oursEndB - commonSuffix, ConflictState.FIRST_CONFLICTING_RANGE); int baseBegin = Math.min(oursBeginA, theirsBeginA) + commonPrefix; int baseEnd = Math.min(base.size(), Math.max(oursEndA, theirsEndA)) - commonSuffix; result.add(0, baseBegin, baseEnd, ConflictState.BASE_CONFLICTING_RANGE); result.add(2, theirsBeginB + commonPrefix, theirsEndB - commonSuffix, ConflictState.NEXT_CONFLICTING_RANGE); break; } } // Add the common lines at end of conflict if (commonSuffix > 0) result.add(1, oursEndB - commonSuffix, oursEndB, ConflictState.NO_CONFLICT); current = Math.max(oursEdit.getEndA(), theirsEdit.getEndA()); oursEdit = nextOursEdit; theirsEdit = nextTheirsEdit; } } // maybe we have a common part behind the last edit: copy it to the // result if (current < base.size()) { result.add(0, current, base.size(), ConflictState.NO_CONFLICT); } return result; } /** * Helper method which returns the next Edit for an Iterator over Edits. * When there are no more edits left this method will return the constant * END_EDIT. * * @param it * the iterator for which the next edit should be returned * @return the next edit from the iterator or END_EDIT if there no more * edits */ private static Edit nextEdit(Iterator it) { return (it.hasNext() ? it.next() : END_EDIT); } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 3766 Content-Disposition: inline; filename="MergeChunk.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "7102aa699892759faa735938c307cd56a7a8a455" /* * Copyright (C) 2009, Christian Halstrick * Copyright (C) 2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; /** * One chunk from a merge result. Each chunk contains a range from a * single sequence. In case of conflicts multiple chunks are reported for one * conflict. The conflictState tells when conflicts start and end. */ public class MergeChunk { /** * A state telling whether a MergeChunk belongs to a conflict or not. The * first chunk of a conflict is reported with a special state to be able to * distinguish the border between two consecutive conflicts */ public enum ConflictState { /** * This chunk does not belong to a conflict */ NO_CONFLICT, /** * This chunk does belong to a conflict and is the ours section of the * conflicting chunks */ FIRST_CONFLICTING_RANGE, /** * This chunk does belong to a conflict and is the base section of the * conflicting chunks * * @since 6.7 */ BASE_CONFLICTING_RANGE, /** * This chunk does belong to a conflict and is the theirs section of * the conflicting chunks. It's a subsequent one. */ NEXT_CONFLICTING_RANGE } private final int sequenceIndex; private final int begin; private final int end; private final ConflictState conflictState; /** * Creates a new empty MergeChunk * * @param sequenceIndex * determines to which sequence this chunks belongs to. Same as * in {@link org.eclipse.jgit.merge.MergeResult#add} * @param begin * the first element from the specified sequence which should be * included in the merge result. Indexes start with 0. * @param end * specifies the end of the range to be added. The element this * index points to is the first element which not added to the * merge result. All elements between begin (including begin) and * this element are added. * @param conflictState * the state of this chunk. See * {@link org.eclipse.jgit.merge.MergeChunk.ConflictState} */ protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; } /** * Get the index of the sequence to which this sequence chunks belongs to. * * @return the index of the sequence to which this sequence chunks belongs * to. Same as in {@link org.eclipse.jgit.merge.MergeResult#add} */ public int getSequenceIndex() { return sequenceIndex; } /** * Get the first element from the specified sequence which should be * included in the merge result. * * @return the first element from the specified sequence which should be * included in the merge result. Indexes start with 0. */ public int getBegin() { return begin; } /** * Get the end of the range of this chunk. * * @return the end of the range of this chunk. The element this index points * to is the first element which not added to the merge result. All * elements between begin (including begin) and this element are * added. */ public int getEnd() { return end; } /** * Get the state of this chunk. * * @return the state of this chunk. See * {@link org.eclipse.jgit.merge.MergeChunk.ConflictState} */ public ConflictState getConflictState() { return conflictState; } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 4766 Content-Disposition: inline; filename="MergeConfig.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "54b7aa4346bdfe43659873afa2c7294e9fc9d07d" /******************************************************************************* * Copyright (c) 2014 Konrad Kügler and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause *******************************************************************************/ package org.eclipse.jgit.merge; import java.io.IOException; import org.eclipse.jgit.api.MergeCommand.FastForwardMode; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.Config.SectionParser; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Repository; /** * Holds configuration for merging into a given branch * * @since 3.3 */ public class MergeConfig { /** * Get merge configuration for the current branch of the repository * * @param repo * a {@link org.eclipse.jgit.lib.Repository} object. * @return merge configuration for the current branch of the repository */ public static MergeConfig getConfigForCurrentBranch(Repository repo) { try { String branch = repo.getBranch(); if (branch != null) return repo.getConfig().get(getParser(branch)); } catch (IOException e) { // ignore } // use defaults if branch can't be determined return new MergeConfig(); } /** * Get a parser for use with * {@link org.eclipse.jgit.lib.Config#get(SectionParser)} * * @param branch * short branch name to get the configuration for, as returned * e.g. by {@link org.eclipse.jgit.lib.Repository#getBranch()} * @return a parser for use with * {@link org.eclipse.jgit.lib.Config#get(SectionParser)} */ public static final SectionParser getParser( final String branch) { return new MergeConfigSectionParser(branch); } private final FastForwardMode fastForwardMode; private final boolean squash; private final boolean commit; private MergeConfig(String branch, Config config) { String[] mergeOptions = getMergeOptions(branch, config); fastForwardMode = getFastForwardMode(config, mergeOptions); squash = isMergeConfigOptionSet("--squash", mergeOptions); //$NON-NLS-1$ commit = !isMergeConfigOptionSet("--no-commit", mergeOptions); //$NON-NLS-1$ } private MergeConfig() { fastForwardMode = FastForwardMode.FF; squash = false; commit = true; } /** * Get the fast forward mode configured for this branch * * @return the fast forward mode configured for this branch */ public FastForwardMode getFastForwardMode() { return fastForwardMode; } /** * Whether merges into this branch are configured to be squash merges, false * otherwise * * @return true if merges into this branch are configured to be squash * merges, false otherwise */ public boolean isSquash() { return squash; } /** * Whether {@code --no-commit} option is not set. * * @return {@code false} if --no-commit is configured for this branch, * {@code true} otherwise (even if --squash is configured) */ public boolean isCommit() { return commit; } private static FastForwardMode getFastForwardMode(Config config, String[] mergeOptions) { for (String option : mergeOptions) { for (FastForwardMode mode : FastForwardMode.values()) if (mode.matchConfigValue(option)) return mode; } FastForwardMode ffmode = FastForwardMode.valueOf(config.getEnum( ConfigConstants.CONFIG_KEY_MERGE, null, ConfigConstants.CONFIG_KEY_FF, FastForwardMode.Merge.TRUE)); return ffmode; } private static boolean isMergeConfigOptionSet(String optionToLookFor, String[] mergeOptions) { for (String option : mergeOptions) { if (optionToLookFor.equals(option)) return true; } return false; } private static String[] getMergeOptions(String branch, Config config) { String mergeOptions = config.getString( ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGEOPTIONS); if (mergeOptions != null) { return mergeOptions.split("\\s"); //$NON-NLS-1$ } return new String[0]; } private static class MergeConfigSectionParser implements SectionParser { private final String branch; public MergeConfigSectionParser(String branch) { this.branch = branch; } @Override public MergeConfig parse(Config cfg) { return new MergeConfig(branch, cfg); } @Override public boolean equals(Object obj) { if (obj instanceof MergeConfigSectionParser) { return branch.equals(((MergeConfigSectionParser) obj).branch); } return false; } @Override public int hashCode() { return branch.hashCode(); } } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 5805 Content-Disposition: inline; filename="MergeFormatter.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "079db4a07f1cd81141bb09b72ad3604c5c1bf6ea" /* * Copyright (C) 2009, Christian Halstrick and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.eclipse.jgit.diff.RawText; /** * A class to convert merge results into a Git conformant textual presentation */ public class MergeFormatter { /** * Formats the results of a merge of {@link org.eclipse.jgit.diff.RawText} * objects in a Git conformant way. This method also assumes that the * {@link org.eclipse.jgit.diff.RawText} objects being merged are line * oriented files which use LF as delimiter. This method will also use LF to * separate chunks and conflict metadata, therefore it fits only to texts * that are LF-separated lines. * * @param out * the output stream where to write the textual presentation * @param res * the merge result which should be presented * @param seqName * When a conflict is reported each conflicting range will get a * name. This name is following the "<<<<<<< * " or ">>>>>>> " conflict markers. The * names for the sequences are given in this list * @param charset * the character set used when writing conflict metadata * @throws java.io.IOException * if an IO error occurred * @since 5.2 */ public void formatMerge(OutputStream out, MergeResult res, List seqName, Charset charset) throws IOException { new MergeFormatterPass(out, res, seqName, charset).formatMerge(); } /** * Formats the results of a merge of {@link org.eclipse.jgit.diff.RawText} * objects in a Git conformant way using diff3 style. This method also * assumes that the {@link org.eclipse.jgit.diff.RawText} objects being * merged are line oriented files which use LF as delimiter. This method * will also use LF to separate chunks and conflict metadata, therefore it * fits only to texts that are LF-separated lines. * * @param out * the output stream where to write the textual presentation * @param res * the merge result which should be presented * @param seqName * When a conflict is reported each conflicting range will get a * name. This name is following the "<<<<<<< * ", "|||||||" or ">>>>>>> " conflict * markers. The names for the sequences are given in this list * @param charset * the character set used when writing conflict metadata * @throws java.io.IOException * if an IO error occurred * @since 6.7 */ public void formatMergeDiff3(OutputStream out, MergeResult res, List seqName, Charset charset) throws IOException { new MergeFormatterPass(out, res, seqName, charset, true).formatMerge(); } /** * Formats the results of a merge of exactly two * {@link org.eclipse.jgit.diff.RawText} objects in a Git conformant way. * This convenience method accepts the names for the three sequences (base * and the two merged sequences) as explicit parameters and doesn't require * the caller to specify a List * * @param out * the {@link java.io.OutputStream} where to write the textual * presentation * @param res * the merge result which should be presented * @param baseName * the name ranges from the base should get * @param oursName * the name ranges from ours should get * @param theirsName * the name ranges from theirs should get * @param charset * the character set used when writing conflict metadata * @throws java.io.IOException * if an IO error occurred * @since 5.2 */ @SuppressWarnings("unchecked") public void formatMerge(OutputStream out, MergeResult res, String baseName, String oursName, String theirsName, Charset charset) throws IOException { List names = new ArrayList<>(3); names.add(baseName); names.add(oursName); names.add(theirsName); formatMerge(out, res, names, charset); } /** * Formats the results of a merge of three * {@link org.eclipse.jgit.diff.RawText} objects in a Git conformant way, * using diff-3 style. This convenience method accepts the names for the * three sequences (base and the two merged sequences) as explicit * parameters and doesn't require the caller to specify a List * * @param out * the {@link java.io.OutputStream} where to write the textual * presentation * @param res * the merge result which should be presented * @param baseName * the name ranges from the base should get * @param oursName * the name ranges from ours should get * @param theirsName * the name ranges from theirs should get * @param charset * the character set used when writing conflict metadata * @throws java.io.IOException * if an IO error occurred * @since 6.7 */ @SuppressWarnings("unchecked") public void formatMergeDiff3(OutputStream out, MergeResult res, String baseName, String oursName, String theirsName, Charset charset) throws IOException { List names = new ArrayList<>(3); names.add(baseName); names.add(oursName); names.add(theirsName); formatMergeDiff3(out, res, names, charset); } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 5886 Content-Disposition: inline; filename="MergeFormatterPass.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "5e80b5fb237e9ec2deee5fde8beab6b3c430fc18" /* * Copyright (C) 2009, Christian Halstrick * Copyright (C) 2014, André de Oliveira and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.List; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.merge.MergeChunk.ConflictState; class MergeFormatterPass { private final EolAwareOutputStream out; private final MergeResult res; private final List seqName; private final Charset charset; private final boolean threeWayMerge; private final boolean writeBase; // diff3-style requested private String lastConflictingName; // is set to non-null whenever we are in // a conflict /** * @param out * the {@link java.io.OutputStream} where to write the textual * presentation * @param res * the merge result which should be presented * @param seqName * When a conflict is reported each conflicting range will get a * name. This name is following the "<<<<<<< * " or ">>>>>>> " conflict markers. The * names for the sequences are given in this list * @param charset * the character set used when writing conflict metadata */ MergeFormatterPass(OutputStream out, MergeResult res, List seqName, Charset charset) { this(out, res, seqName, charset, false); } /** * @param out * the {@link java.io.OutputStream} where to write the textual * presentation * @param res * the merge result which should be presented * @param seqName * When a conflict is reported each conflicting range will get a * name. This name is following the "<<<<<<< * ", "|||||||" or ">>>>>>> " conflict * markers. The names for the sequences are given in this list * @param charset * the character set used when writing conflict metadata * @param writeBase * base's contribution should be written in conflicts */ MergeFormatterPass(OutputStream out, MergeResult res, List seqName, Charset charset, boolean writeBase) { this.out = new EolAwareOutputStream(out); this.res = res; this.seqName = seqName; this.charset = charset; this.threeWayMerge = (res.getSequences().size() == 3); this.writeBase = writeBase; } void formatMerge() throws IOException { boolean missingNewlineAtEnd = false; for (MergeChunk chunk : res) { if (!isBase(chunk) || writeBase) { RawText seq = res.getSequences().get(chunk.getSequenceIndex()); writeConflictMetadata(chunk); // the lines with conflict-metadata are written. Now write the // chunk for (int i = chunk.getBegin(); i < chunk.getEnd(); i++) writeLine(seq, i); missingNewlineAtEnd = seq.isMissingNewlineAtEnd(); } } // one possible leftover: if the merge result ended with a conflict we // have to close the last conflict here if (lastConflictingName != null) writeConflictEnd(); if (!missingNewlineAtEnd) out.beginln(); } private void writeConflictMetadata(MergeChunk chunk) throws IOException { if (lastConflictingName != null && !isTheirs(chunk) && !isBase(chunk)) { // found the end of a conflict writeConflictEnd(); } if (isOurs(chunk)) { // found the start of a conflict writeConflictStart(chunk); } else if (isTheirs(chunk)) { // found the theirs conflicting chunk writeConflictChange(chunk); } else if (isBase(chunk)) { // found the base conflicting chunk writeConflictBase(chunk); } } private void writeConflictEnd() throws IOException { writeln(">>>>>>> " + lastConflictingName); //$NON-NLS-1$ lastConflictingName = null; } private void writeConflictStart(MergeChunk chunk) throws IOException { lastConflictingName = seqName.get(chunk.getSequenceIndex()); writeln("<<<<<<< " + lastConflictingName); //$NON-NLS-1$ } private void writeConflictChange(MergeChunk chunk) throws IOException { /* * In case of a non-three-way merge I'll add the name of the conflicting * chunk behind the equal signs. I also append the name of the last * conflicting chunk after the ending greater-than signs. If somebody * knows a better notation to present non-three-way merges - feel free * to correct here. */ lastConflictingName = seqName.get(chunk.getSequenceIndex()); writeln(threeWayMerge ? "=======" : "======= " //$NON-NLS-1$ //$NON-NLS-2$ + lastConflictingName); } private void writeConflictBase(MergeChunk chunk) throws IOException { lastConflictingName = seqName.get(chunk.getSequenceIndex()); writeln("||||||| " + lastConflictingName); //$NON-NLS-1$ } private void writeln(String s) throws IOException { out.beginln(); out.write((s + "\n").getBytes(charset)); //$NON-NLS-1$ } private void writeLine(RawText seq, int i) throws IOException { out.beginln(); seq.writeLine(out, i); // still BOL? It was a blank line. But writeLine won't lf, so we do. if (out.isBeginln()) out.write('\n'); } private boolean isBase(MergeChunk chunk) { return chunk.getConflictState() == ConflictState.BASE_CONFLICTING_RANGE; } private boolean isOurs(MergeChunk chunk) { return chunk .getConflictState() == ConflictState.FIRST_CONFLICTING_RANGE; } private boolean isTheirs(MergeChunk chunk) { return chunk.getConflictState() == ConflictState.NEXT_CONFLICTING_RANGE; } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 4878 Content-Disposition: inline; filename="MergeMessageFormatter.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "039d7d844cf370918640257a4e3563c8f38ec083" /* * Copyright (C) 2010-2012, Robin Stocker and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.util.ArrayList; import java.util.List; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.util.ChangeIdUtil; import org.eclipse.jgit.util.StringUtils; /** * Formatter for constructing the commit message for a merge commit. *

* The format should be the same as C Git does it, for compatibility. */ public class MergeMessageFormatter { /** * Construct the merge commit message. * * @param refsToMerge * the refs which will be merged * @param target * the branch ref which will be merged into * @return merge commit message */ public String format(List refsToMerge, Ref target) { StringBuilder sb = new StringBuilder(); sb.append("Merge "); //$NON-NLS-1$ List branches = new ArrayList<>(); List remoteBranches = new ArrayList<>(); List tags = new ArrayList<>(); List commits = new ArrayList<>(); List others = new ArrayList<>(); for (Ref ref : refsToMerge) { if (ref.getName().startsWith(Constants.R_HEADS)) { branches.add("'" + Repository.shortenRefName(ref.getName()) //$NON-NLS-1$ + "'"); //$NON-NLS-1$ } else if (ref.getName().startsWith(Constants.R_REMOTES)) { remoteBranches.add("'" //$NON-NLS-1$ + Repository.shortenRefName(ref.getName()) + "'"); //$NON-NLS-1$ } else if (ref.getName().startsWith(Constants.R_TAGS)) { tags.add("'" + Repository.shortenRefName(ref.getName()) + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } else { ObjectId objectId = ref.getObjectId(); if (objectId != null && ref.getName().equals(objectId.getName())) { commits.add("'" + ref.getName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } else { others.add(ref.getName()); } } } List listings = new ArrayList<>(); if (!branches.isEmpty()) listings.add(joinNames(branches, "branch", "branches")); //$NON-NLS-1$//$NON-NLS-2$ if (!remoteBranches.isEmpty()) listings.add(joinNames(remoteBranches, "remote-tracking branch", //$NON-NLS-1$ "remote-tracking branches")); //$NON-NLS-1$ if (!tags.isEmpty()) listings.add(joinNames(tags, "tag", "tags")); //$NON-NLS-1$ //$NON-NLS-2$ if (!commits.isEmpty()) listings.add(joinNames(commits, "commit", "commits")); //$NON-NLS-1$ //$NON-NLS-2$ if (!others.isEmpty()) listings.add(StringUtils.join(others, ", ", " and ")); //$NON-NLS-1$ //$NON-NLS-2$ sb.append(StringUtils.join(listings, ", ")); //$NON-NLS-1$ String targetName = target.getLeaf().getName(); if (!targetName.equals(Constants.R_HEADS + Constants.MASTER)) { String targetShortName = Repository.shortenRefName(targetName); sb.append(" into " + targetShortName); //$NON-NLS-1$ } return sb.toString(); } /** * Add section with conflicting paths to merge message. * * @param message * the original merge message * @param conflictingPaths * the paths with conflicts * @param commentChar * comment character to use for prefixing the conflict lines * @return merge message with conflicting paths added * @since 6.1 */ public String formatWithConflicts(String message, Iterable conflictingPaths, char commentChar) { StringBuilder sb = new StringBuilder(); String[] lines = message.split("\n"); //$NON-NLS-1$ int firstFooterLine = ChangeIdUtil.indexOfFirstFooterLine(lines); for (int i = 0; i < firstFooterLine; i++) { sb.append(lines[i]).append('\n'); } if (firstFooterLine == lines.length && message.length() != 0) { sb.append('\n'); } addConflictsMessage(conflictingPaths, sb, commentChar); if (firstFooterLine < lines.length) { sb.append('\n'); } for (int i = firstFooterLine; i < lines.length; i++) { sb.append(lines[i]).append('\n'); } return sb.toString(); } private static void addConflictsMessage(Iterable conflictingPaths, StringBuilder sb, char commentChar) { sb.append(commentChar).append(" Conflicts:\n"); //$NON-NLS-1$ for (String conflictingPath : conflictingPaths) { sb.append(commentChar).append('\t').append(conflictingPath) .append('\n'); } } private static String joinNames(List names, String singular, String plural) { if (names.size() == 1) { return singular + " " + names.get(0); //$NON-NLS-1$ } return plural + " " + StringUtils.join(names, ", ", " and "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 4903 Content-Disposition: inline; filename="MergeResult.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "acf955303d87e02e8ba5fba8c508085d8564cdd0" /* * Copyright (C) 2009, Christian Halstrick and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.util.Iterator; import java.util.List; import org.eclipse.jgit.diff.Sequence; import org.eclipse.jgit.merge.MergeChunk.ConflictState; import org.eclipse.jgit.util.IntList; /** * The result of merging a number of {@link org.eclipse.jgit.diff.Sequence} * objects. These sequences have one common predecessor sequence. The result of * a merge is a list of MergeChunks. Each MergeChunk contains either a range (a * subsequence) from one of the merged sequences, a range from the common * predecessor or a conflicting range from one of the merged sequences. A * conflict will be reported as multiple chunks, one for each conflicting range. * The first chunk for a conflict is marked specially to distinguish the border * between two consecutive conflicts. *

* This class does not know anything about how to present the merge result to * the end-user. MergeFormatters have to be used to construct something human * readable. * * @param * type of sequence. */ public class MergeResult implements Iterable { private final List sequences; final IntList chunks = new IntList(); private boolean containsConflicts = false; /** * Creates a new empty MergeResult * * @param sequences * contains the common predecessor sequence at position 0 * followed by the merged sequences. This list should not be * modified anymore during the lifetime of this * {@link org.eclipse.jgit.merge.MergeResult}. */ public MergeResult(List sequences) { this.sequences = sequences; } /** * Adds a new range from one of the merged sequences or from the common * predecessor. This method can add conflicting and non-conflicting ranges * controlled by the conflictState parameter * * @param srcIdx * determines from which sequence this range comes. An index of * x specifies the x+1 element in the list of sequences * specified to the constructor * @param begin * the first element from the specified sequence which should be * included in the merge result. Indexes start with 0. * @param end * specifies the end of the range to be added. The element this * index points to is the first element which not added to the * merge result. All elements between begin (including begin) and * this element are added. * @param conflictState * when set to NO_CONLICT a non-conflicting range is added. * This will end implicitly all open conflicts added before. */ public void add(int srcIdx, int begin, int end, ConflictState conflictState) { chunks.add(conflictState.ordinal()); chunks.add(srcIdx); chunks.add(begin); chunks.add(end); if (conflictState != ConflictState.NO_CONFLICT) containsConflicts = true; } /** * Returns the common predecessor sequence and the merged sequence in one * list. The common predecessor is the first element in the list * * @return the common predecessor at position 0 followed by the merged * sequences. */ public List getSequences() { return sequences; } static final ConflictState[] states = ConflictState.values(); @Override public Iterator iterator() { return new Iterator<>() { int idx; @Override public boolean hasNext() { return (idx < chunks.size()); } @Override public MergeChunk next() { ConflictState state = states[chunks.get(idx++)]; int srcIdx = chunks.get(idx++); int begin = chunks.get(idx++); int end = chunks.get(idx++); return new MergeChunk(srcIdx, begin, end, state); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Whether this merge result contains conflicts * * @return true if this merge result contains conflicts */ public boolean containsConflicts() { return containsConflicts; } /** * Sets explicitly whether this merge should be seen as containing a * conflict or not. Needed because during RecursiveMerger we want to do * content-merges and take the resulting content (even with conflict * markers!) as new conflict-free content * * @param containsConflicts * whether this merge should be seen as containing a conflict or * not. * @since 3.5 */ protected void setContainsConflicts(boolean containsConflicts) { this.containsConflicts = containsConflicts; } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 5275 Content-Disposition: inline; filename="MergeStrategy.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "ba9c5b7dccb573020a14b8306bf50b1c9fd4361e" /* * Copyright (C) 2008-2009, Google Inc. * Copyright (C) 2009, Matthias Sohn * Copyright (C) 2012, Research In Motion Limited and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.text.MessageFormat; import java.util.HashMap; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.Repository; /** * A method of combining two or more trees together to form an output tree. *

* Different strategies may employ different techniques for deciding which paths * (and ObjectIds) to carry from the input trees into the final output tree. */ public abstract class MergeStrategy { /** Simple strategy that sets the output tree to the first input tree. */ public static final MergeStrategy OURS = new StrategyOneSided("ours", 0); //$NON-NLS-1$ /** Simple strategy that sets the output tree to the second input tree. */ public static final MergeStrategy THEIRS = new StrategyOneSided("theirs", 1); //$NON-NLS-1$ /** Simple strategy to merge paths, without simultaneous edits. */ public static final ThreeWayMergeStrategy SIMPLE_TWO_WAY_IN_CORE = new StrategySimpleTwoWayInCore(); /** * Simple strategy to merge paths. It tries to merge also contents. Multiple * merge bases are not supported */ public static final ThreeWayMergeStrategy RESOLVE = new StrategyResolve(); /** * Recursive strategy to merge paths. It tries to merge also contents. * Multiple merge bases are supported * @since 3.0 */ public static final ThreeWayMergeStrategy RECURSIVE = new StrategyRecursive(); private static final HashMap STRATEGIES = new HashMap<>(); static { register(OURS); register(THEIRS); register(SIMPLE_TWO_WAY_IN_CORE); register(RESOLVE); register(RECURSIVE); } /** * Register a merge strategy so it can later be obtained by name. * * @param imp * the strategy to register. * @throws java.lang.IllegalArgumentException * a strategy by the same name has already been registered. */ public static void register(MergeStrategy imp) { register(imp.getName(), imp); } /** * Register a merge strategy so it can later be obtained by name. * * @param name * name the strategy can be looked up under. * @param imp * the strategy to register. * @throws java.lang.IllegalArgumentException * a strategy by the same name has already been registered. */ public static synchronized void register(final String name, final MergeStrategy imp) { if (STRATEGIES.containsKey(name)) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().mergeStrategyAlreadyExistsAsDefault, name)); STRATEGIES.put(name, imp); } /** * Locate a strategy by name. * * @param name * name of the strategy to locate. * @return the strategy instance; null if no strategy matches the name. */ public static synchronized MergeStrategy get(String name) { return STRATEGIES.get(name); } /** * Get all registered strategies. * * @return the registered strategy instances. No inherit order is returned; * the caller may modify (and/or sort) the returned array if * necessary to obtain a reasonable ordering. */ public static synchronized MergeStrategy[] get() { final MergeStrategy[] r = new MergeStrategy[STRATEGIES.size()]; STRATEGIES.values().toArray(r); return r; } /** * Get default name of this strategy implementation. * * @return default name of this strategy implementation. */ public abstract String getName(); /** * Create a new merge instance. * * @param db * repository database the merger will read from, and eventually * write results back to. * @return the new merge instance which implements this strategy. */ public abstract Merger newMerger(Repository db); /** * Create a new merge instance. * * @param db * repository database the merger will read from, and eventually * write results back to. * @param inCore * the merge will happen in memory, working folder will not be * modified, in case of a non-trivial merge that requires manual * resolution, the merger will fail. * @return the new merge instance which implements this strategy. */ public abstract Merger newMerger(Repository db, boolean inCore); /** * Create a new merge instance. *

* The merge will happen in memory, working folder will not be modified, in * case of a non-trivial merge that requires manual resolution, the merger * will fail. * * @param inserter * inserter to write results back to. * @param config * repo config for reading diff algorithm settings. * @return the new merge instance which implements this strategy. * @since 4.8 */ public abstract Merger newMerger(ObjectInserter inserter, Config config); } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 11125 Content-Disposition: inline; filename="Merger.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "bd762e5a983d02e92fac878ba91b96697d7def9f" /* * Copyright (C) 2008-2013, Google Inc. * Copyright (C) 2016, Laurent Delaigue and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.io.IOException; import java.text.MessageFormat; import org.eclipse.jgit.annotations.Nullable; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.NoMergeBaseException; import org.eclipse.jgit.errors.NoMergeBaseException.MergeBaseFailureReason; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; /** * Instance of a specific {@link org.eclipse.jgit.merge.MergeStrategy} for a * single {@link org.eclipse.jgit.lib.Repository}. */ public abstract class Merger { /** * The repository this merger operates on. *

* Null if and only if the merger was constructed with {@link * #Merger(ObjectInserter)}. Callers that want to assume the repo is not null * (e.g. because of a previous check that the merger is not in-core) may use * {@link #nonNullRepo()}. */ @Nullable protected final Repository db; /** Reader to support {@link #walk} and other object loading. */ protected ObjectReader reader; /** A RevWalk for computing merge bases, or listing incoming commits. */ protected RevWalk walk; private ObjectInserter inserter; /** The original objects supplied in the merge; this can be any tree-ish. */ protected RevObject[] sourceObjects; /** If {@link #sourceObjects}[i] is a commit, this is the commit. */ protected RevCommit[] sourceCommits; /** The trees matching every entry in {@link #sourceObjects}. */ protected RevTree[] sourceTrees; /** * A progress monitor. * * @since 4.2 */ protected ProgressMonitor monitor = NullProgressMonitor.INSTANCE; /** * Create a new merge instance for a repository. * * @param local * the repository this merger will read and write data on. */ protected Merger(Repository local) { if (local == null) { throw new NullPointerException(JGitText.get().repositoryIsRequired); } db = local; inserter = local.newObjectInserter(); reader = inserter.newReader(); walk = new RevWalk(reader); } /** * Create a new in-core merge instance from an inserter. * * @param oi * the inserter to write objects to. Will be closed at the * conclusion of {@code merge}, unless {@code flush} is false. * @since 4.8 */ protected Merger(ObjectInserter oi) { db = null; inserter = oi; reader = oi.newReader(); walk = new RevWalk(reader); } /** * Get the repository this merger operates on. * * @return the repository this merger operates on. */ @Nullable public Repository getRepository() { return db; } /** * Get non-null repository instance * * @return non-null repository instance * @throws java.lang.NullPointerException * if the merger was constructed without a repository. * @since 4.8 */ protected Repository nonNullRepo() { if (db == null) { throw new NullPointerException(JGitText.get().repositoryIsRequired); } return db; } /** * Get an object writer to create objects, writing objects to * {@link #getRepository()} * * @return an object writer to create objects, writing objects to * {@link #getRepository()} (if a repository was provided). */ public ObjectInserter getObjectInserter() { return inserter; } /** * Set the inserter this merger will use to create objects. *

* If an inserter was already set on this instance (such as by a prior set, * or a prior call to {@link #getObjectInserter()}), the prior inserter as * well as the in-progress walk will be released. * * @param oi * the inserter instance to use. Must be associated with the * repository instance returned by {@link #getRepository()} (if a * repository was provided). Will be closed at the conclusion of * {@code merge}, unless {@code flush} is false. */ public void setObjectInserter(ObjectInserter oi) { walk.close(); reader.close(); inserter.close(); inserter = oi; reader = oi.newReader(); walk = new RevWalk(reader); } /** * Merge together two or more tree-ish objects. *

* Any tree-ish may be supplied as inputs. Commits and/or tags pointing at * trees or commits may be passed as input objects. * * @param tips * source trees to be combined together. The merge base is not * included in this set. * @return true if the merge was completed without conflicts; false if the * merge strategy cannot handle this merge or there were conflicts * preventing it from automatically resolving all paths. * @throws IncorrectObjectTypeException * one of the input objects is not a commit, but the strategy * requires it to be a commit. * @throws java.io.IOException * one or more sources could not be read, or outputs could not * be written to the Repository. */ public boolean merge(AnyObjectId... tips) throws IOException { return merge(true, tips); } /** * Merge together two or more tree-ish objects. *

* Any tree-ish may be supplied as inputs. Commits and/or tags pointing at * trees or commits may be passed as input objects. * * @since 3.5 * @param flush * whether to flush and close the underlying object inserter when * finished to store any content-merged blobs and virtual merged * bases; if false, callers are responsible for flushing. * @param tips * source trees to be combined together. The merge base is not * included in this set. * @return true if the merge was completed without conflicts; false if the * merge strategy cannot handle this merge or there were conflicts * preventing it from automatically resolving all paths. * @throws IncorrectObjectTypeException * one of the input objects is not a commit, but the strategy * requires it to be a commit. * @throws java.io.IOException * one or more sources could not be read, or outputs could not * be written to the Repository. */ public boolean merge(boolean flush, AnyObjectId... tips) throws IOException { sourceObjects = new RevObject[tips.length]; for (int i = 0; i < tips.length; i++) sourceObjects[i] = walk.parseAny(tips[i]); sourceCommits = new RevCommit[sourceObjects.length]; for (int i = 0; i < sourceObjects.length; i++) { try { sourceCommits[i] = walk.parseCommit(sourceObjects[i]); } catch (IncorrectObjectTypeException err) { sourceCommits[i] = null; } } sourceTrees = new RevTree[sourceObjects.length]; for (int i = 0; i < sourceObjects.length; i++) sourceTrees[i] = walk.parseTree(sourceObjects[i]); try { boolean ok = mergeImpl(); if (ok && flush) inserter.flush(); return ok; } finally { if (flush) inserter.close(); reader.close(); } } /** * Get the ID of the commit that was used as merge base for merging * * @return the ID of the commit that was used as merge base for merging, or * null if no merge base was used or it was set manually * @since 3.2 */ public abstract ObjectId getBaseCommitId(); /** * Return the merge base of two commits. * * @param a * the first commit in {@link #sourceObjects}. * @param b * the second commit in {@link #sourceObjects}. * @return the merge base of two commits * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException * one of the input objects is not a commit. * @throws java.io.IOException * objects are missing or multiple merge bases were found. * @since 3.0 */ protected RevCommit getBaseCommit(RevCommit a, RevCommit b) throws IncorrectObjectTypeException, IOException { walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(a); walk.markStart(b); final RevCommit base = walk.next(); if (base == null) return null; final RevCommit base2 = walk.next(); if (base2 != null) { throw new NoMergeBaseException( MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED, MessageFormat.format( JGitText.get().multipleMergeBasesFor, a.name(), b.name(), base.name(), base2.name())); } return base; } /** * Open an iterator over a tree. * * @param treeId * the tree to scan; must be a tree (not a treeish). * @return an iterator for the tree. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException * the input object is not a tree. * @throws java.io.IOException * the tree object is not found or cannot be read. */ protected AbstractTreeIterator openTree(AnyObjectId treeId) throws IncorrectObjectTypeException, IOException { return new CanonicalTreeParser(null, reader, treeId); } /** * Execute the merge. *

* This method is called from {@link #merge(AnyObjectId[])} after the * {@link #sourceObjects}, {@link #sourceCommits} and {@link #sourceTrees} * have been populated. * * @return true if the merge was completed without conflicts; false if the * merge strategy cannot handle this merge or there were conflicts * preventing it from automatically resolving all paths. * @throws IncorrectObjectTypeException * one of the input objects is not a commit, but the strategy * requires it to be a commit. * @throws java.io.IOException * one or more sources could not be read, or outputs could not * be written to the Repository. */ protected abstract boolean mergeImpl() throws IOException; /** * Get resulting tree. * * @return resulting tree, if {@link #merge(AnyObjectId[])} returned true. */ public abstract ObjectId getResultTreeId(); /** * Set a progress monitor. * * @param monitor * Monitor to use, can be null to indicate no progress reporting * is desired. * @since 4.2 */ public void setProgressMonitor(ProgressMonitor monitor) { if (monitor == null) { this.monitor = NullProgressMonitor.INSTANCE; } else { this.monitor = monitor; } } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 8787 Content-Disposition: inline; filename="RecursiveMerger.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "f58ef4faba5ea8a0865449a72e7f89b0778523ef" /* * Copyright (C) 2012, Research In Motion Limited * Copyright (C) 2012, Christian Halstrick and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ /* * Contributors: * George Young - initial API and implementation * Christian Halstrick - initial API and implementation */ package org.eclipse.jgit.merge; import java.io.IOException; import java.text.MessageFormat; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.NoMergeBaseException; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.EmptyTreeIterator; import org.eclipse.jgit.treewalk.WorkingTreeIterator; /** * A three-way merger performing a content-merge if necessary across multiple * bases using recursion * * This merger extends the resolve merger and does several things differently: * * - allow more than one merge base, up to a maximum * * - uses "Lists" instead of Arrays for chained types * * - recursively merges the merge bases together to compute a usable base * * @since 3.0 */ public class RecursiveMerger extends ResolveMerger { /** * The maximum number of merge bases. This merge will stop when the number * of merge bases exceeds this value */ public final int MAX_BASES = 200; /** * Normal recursive merge when you want a choice of DirCache placement * inCore * * @param local * a {@link org.eclipse.jgit.lib.Repository} object. * @param inCore * a boolean. */ protected RecursiveMerger(Repository local, boolean inCore) { super(local, inCore); } /** * Normal recursive merge, implies not inCore * * @param local a {@link org.eclipse.jgit.lib.Repository} object. */ protected RecursiveMerger(Repository local) { this(local, false); } /** * Normal recursive merge, implies inCore. * * @param inserter * an {@link org.eclipse.jgit.lib.ObjectInserter} object. * @param config * the repository configuration * @since 4.8 */ protected RecursiveMerger(ObjectInserter inserter, Config config) { super(inserter, config); } /** * {@inheritDoc} *

* Get a single base commit for two given commits. If the two source commits * have more than one base commit recursively merge the base commits * together until you end up with a single base commit. */ @Override protected RevCommit getBaseCommit(RevCommit a, RevCommit b) throws IncorrectObjectTypeException, IOException { return getBaseCommit(a, b, 0); } /** * Get a single base commit for two given commits. If the two source commits * have more than one base commit recursively merge the base commits * together until a virtual common base commit has been found. * * @param a * the first commit to be merged * @param b * the second commit to be merged * @param callDepth * the callDepth when this method is called recursively * @return the merge base of two commits. If a criss-cross merge required a * synthetic merge base this commit is visible only the merger's * RevWalk and will not be in the repository. * @throws java.io.IOException * if an IO error occurred * @throws IncorrectObjectTypeException * one of the input objects is not a commit. * @throws NoMergeBaseException * too many merge bases are found or the computation of a common * merge base failed (e.g. because of a conflict). */ protected RevCommit getBaseCommit(RevCommit a, RevCommit b, int callDepth) throws IOException { ArrayList baseCommits = new ArrayList<>(); walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(a); walk.markStart(b); RevCommit c; while ((c = walk.next()) != null) baseCommits.add(c); if (baseCommits.isEmpty()) return null; if (baseCommits.size() == 1) return baseCommits.get(0); if (baseCommits.size() >= MAX_BASES) throw new NoMergeBaseException(NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES, MessageFormat.format( JGitText.get().mergeRecursiveTooManyMergeBasesFor, Integer.valueOf(MAX_BASES), a.name(), b.name(), Integer.valueOf(baseCommits.size()))); // We know we have more than one base commit. We have to do merges now // to determine a single base commit. We don't want to spoil the current // dircache and working tree with the results of this intermediate // merges. Therefore set the dircache to a new in-memory dircache and // disable that we update the working-tree. We set this back to the // original values once a single base commit is created. RevCommit currentBase = baseCommits.get(0); DirCache oldDircache = dircache; boolean oldIncore = inCore; WorkingTreeIterator oldWTreeIt = workingTreeIterator; workingTreeIterator = null; try { dircache = DirCache.read(reader, currentBase.getTree()); inCore = true; List parents = new ArrayList<>(); parents.add(currentBase); for (int commitIdx = 1; commitIdx < baseCommits.size(); commitIdx++) { RevCommit nextBase = baseCommits.get(commitIdx); if (commitIdx >= MAX_BASES) throw new NoMergeBaseException( NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES, MessageFormat.format( JGitText.get().mergeRecursiveTooManyMergeBasesFor, Integer.valueOf(MAX_BASES), a.name(), b.name(), Integer.valueOf(baseCommits.size()))); parents.add(nextBase); RevCommit bc = getBaseCommit(currentBase, nextBase, callDepth + 1); AbstractTreeIterator bcTree = (bc == null) ? new EmptyTreeIterator() : openTree(bc.getTree()); if (mergeTrees(bcTree, currentBase.getTree(), nextBase.getTree(), true)) currentBase = createCommitForTree(resultTree, parents); else { String failedPaths = failingPathsMessage(); throw new NoMergeBaseException( NoMergeBaseException.MergeBaseFailureReason.CONFLICTS_DURING_MERGE_BASE_CALCULATION, MessageFormat.format( JGitText.get().mergeRecursiveConflictsWhenMergingCommonAncestors, currentBase.getName(), nextBase.getName(), failedPaths)); } } } finally { inCore = oldIncore; dircache = oldDircache; workingTreeIterator = oldWTreeIt; unmergedPaths.clear(); mergeResults.clear(); failingPaths.clear(); } return currentBase; } /** * Create a new commit by explicitly specifying the content tree and the * parents. The commit message is not set and author/committer are set to * the current user. * * @param tree * the tree this commit should capture * @param parents * the list of parent commits * @return a new commit visible only within this merger's RevWalk. * @throws IOException * if an IO error occurred */ private RevCommit createCommitForTree(ObjectId tree, List parents) throws IOException { CommitBuilder c = new CommitBuilder(); c.setTreeId(tree); c.setParentIds(parents); c.setAuthor(mockAuthor(parents)); c.setCommitter(c.getAuthor()); return RevCommit.parse(walk, c.build()); } private static PersonIdent mockAuthor(List parents) { String name = RecursiveMerger.class.getSimpleName(); int time = 0; for (RevCommit p : parents) { time = Math.max(time, p.getCommitTime()); } return new PersonIdent(name, name + "@JGit", //$NON-NLS-1$ Instant.ofEpochSecond(time+1), ZoneOffset.UTC); } private String failingPathsMessage() { int max = 25; String failedPaths = failingPaths.entrySet().stream().limit(max) .map(entry -> entry.getKey() + ":" + entry.getValue()) //$NON-NLS-1$ .collect(Collectors.joining("\n")); //$NON-NLS-1$ if (failingPaths.size() > max) { failedPaths = String.format("%s\n... (%s failing paths omitted)", //$NON-NLS-1$ failedPaths, Integer.valueOf(failingPaths.size() - max)); } return failedPaths; } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 63812 Content-Disposition: inline; filename="ResolveMerger.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "dc96f65b87835a3d0e9f0b65fe6cc620bbc32d14" /* * Copyright (C) 2010, Christian Halstrick , * Copyright (C) 2010-2012, Matthias Sohn * Copyright (C) 2012, Research In Motion Limited * Copyright (C) 2017, Obeo (mathieu.cartaud@obeo.fr) * Copyright (C) 2018, 2023 Thomas Wolf * Copyright (C) 2023, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import static java.nio.charset.StandardCharsets.UTF_8; import static java.time.Instant.EPOCH; import static org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm.HISTOGRAM; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_DIFF_SECTION; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_ALGORITHM; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.annotations.Nullable; import org.eclipse.jgit.attributes.Attribute; import org.eclipse.jgit.attributes.Attributes; import org.eclipse.jgit.attributes.AttributesNodeProvider; import org.eclipse.jgit.diff.DiffAlgorithm; import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.diff.RawTextComparator; import org.eclipse.jgit.diff.Sequence; import org.eclipse.jgit.dircache.Checkout; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheBuildIterator; import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheCheckout; import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata; import org.eclipse.jgit.dircache.DirCacheCheckout.StreamSupplier; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.errors.BinaryBlobException; import org.eclipse.jgit.errors.IndexWriteException; import org.eclipse.jgit.errors.NoWorkTreeException; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.CoreConfig.EolStreamType; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.storage.pack.PackConfig; import org.eclipse.jgit.submodule.SubmoduleConflict; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.NameConflictTreeWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.TreeWalk.OperationType; import org.eclipse.jgit.treewalk.WorkingTreeIterator; import org.eclipse.jgit.treewalk.WorkingTreeOptions; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.jgit.util.LfsFactory; import org.eclipse.jgit.util.LfsFactory.LfsInputStream; import org.eclipse.jgit.util.TemporaryBuffer; import org.eclipse.jgit.util.io.EolStreamTypeUtil; /** * A three-way merger performing a content-merge if necessary */ public class ResolveMerger extends ThreeWayMerger { /** * Handles work tree updates on both the checkout and the index. *

* You should use a single instance for all of your file changes. In case of * an error, make sure your instance is released, and initiate a new one if * necessary. * * @since 6.3.1 */ protected static class WorkTreeUpdater implements Closeable { /** * The result of writing the index changes. */ public static class Result { private final List modifiedFiles = new ArrayList<>(); private final List failedToDelete = new ArrayList<>(); private ObjectId treeId = null; /** * Get modified tree id if any * * @return Modified tree ID if any, or null otherwise. */ public ObjectId getTreeId() { return treeId; } /** * Get path of files that couldn't be deleted * * @return Files that couldn't be deleted. */ public List getFailedToDelete() { return failedToDelete; } /** * Get path of modified files * * @return Files modified during this operation. */ public List getModifiedFiles() { return modifiedFiles; } } Result result = new Result(); /** * The repository this handler operates on. */ @Nullable private final Repository repo; /** * Set to true if this operation should work in-memory. The repo's * dircache and workingtree are not touched by this method. Eventually * needed files are created as temporary files and a new empty, * in-memory dircache will be used instead the repo's one. Often used * for bare repos where the repo doesn't even have a workingtree and * dircache. */ private final boolean inCore; private final ObjectInserter inserter; private final ObjectReader reader; private DirCache dirCache; private boolean implicitDirCache = false; /** * Builder to update the dir cache during this operation. */ private DirCacheBuilder builder; /** * The {@link WorkingTreeOptions} are needed to determine line endings * for affected files. */ private WorkingTreeOptions workingTreeOptions; /** * The size limit (bytes) which controls a file to be stored in * {@code Heap} or {@code LocalFile} during the operation. */ private int inCoreFileSizeLimit; /** * If the operation has nothing to do for a file but check it out at the * end of the operation, it can be added here. */ private final Map toBeCheckedOut = new HashMap<>(); /** * Files in this list will be deleted from the local copy at the end of * the operation. */ private final TreeMap toBeDeleted = new TreeMap<>(); /** * Keeps {@link CheckoutMetadata} for {@link #checkout()}. */ private Map checkoutMetadataByPath; /** * Keeps {@link CheckoutMetadata} for {@link #revertModifiedFiles()}. */ private Map cleanupMetadataByPath; /** * Whether the changes were successfully written. */ private boolean indexChangesWritten; /** * {@link Checkout} to use for actually checking out files if * {@link #inCore} is {@code false}. */ private Checkout checkout; /** * @param repo * the {@link Repository}. * @param dirCache * if set, use the provided dir cache. Otherwise, use the * default repository one */ private WorkTreeUpdater(Repository repo, DirCache dirCache) { this.repo = repo; this.dirCache = dirCache; this.inCore = false; this.inserter = repo.newObjectInserter(); this.reader = inserter.newReader(); Config config = repo.getConfig(); this.workingTreeOptions = config.get(WorkingTreeOptions.KEY); this.inCoreFileSizeLimit = getInCoreFileSizeLimit(config); this.checkoutMetadataByPath = new HashMap<>(); this.cleanupMetadataByPath = new HashMap<>(); this.checkout = new Checkout(nonNullRepo(), workingTreeOptions); } /** * Creates a new {@link WorkTreeUpdater} for the given repository. * * @param repo * the {@link Repository}. * @param dirCache * if set, use the provided dir cache. Otherwise, use the * default repository one * @return the {@link WorkTreeUpdater}. */ public static WorkTreeUpdater createWorkTreeUpdater(Repository repo, DirCache dirCache) { return new WorkTreeUpdater(repo, dirCache); } /** * @param repo * the {@link Repository}. * @param dirCache * if set, use the provided dir cache. Otherwise, creates a * new one * @param oi * to use for writing the modified objects with. */ private WorkTreeUpdater(Repository repo, DirCache dirCache, ObjectInserter oi) { this.repo = repo; this.dirCache = dirCache; this.inserter = oi; this.inCore = true; this.reader = oi.newReader(); if (repo != null) { this.inCoreFileSizeLimit = getInCoreFileSizeLimit( repo.getConfig()); } } /** * Creates a new {@link WorkTreeUpdater} that works in memory only. * * @param repo * the {@link Repository}. * @param dirCache * if set, use the provided dir cache. Otherwise, creates a * new one * @param oi * to use for writing the modified objects with. * @return the {@link WorkTreeUpdater} */ public static WorkTreeUpdater createInCoreWorkTreeUpdater( Repository repo, DirCache dirCache, ObjectInserter oi) { return new WorkTreeUpdater(repo, dirCache, oi); } private static int getInCoreFileSizeLimit(Config config) { return config.getInt(ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20); } /** * Gets the size limit for in-core files in this config. * * @return the size */ public int getInCoreFileSizeLimit() { return inCoreFileSizeLimit; } /** * Gets dir cache for the repo. Locked if not inCore. * * @return the result dir cache * @throws IOException * is case the dir cache cannot be read */ public DirCache getLockedDirCache() throws IOException { if (dirCache == null) { implicitDirCache = true; if (inCore) { dirCache = DirCache.newInCore(); } else { dirCache = nonNullRepo().lockDirCache(); } } if (builder == null) { builder = dirCache.builder(); } return dirCache; } /** * Creates a {@link DirCacheBuildIterator} for the builder of this * {@link WorkTreeUpdater}. * * @return the {@link DirCacheBuildIterator} */ public DirCacheBuildIterator createDirCacheBuildIterator() { return new DirCacheBuildIterator(builder); } /** * Writes the changes to the working tree (but not to the index). * * @param shouldCheckoutTheirs * before committing the changes * @throws IOException * if any of the writes fail */ public void writeWorkTreeChanges(boolean shouldCheckoutTheirs) throws IOException { handleDeletedFiles(); if (inCore) { builder.finish(); return; } if (shouldCheckoutTheirs) { // No problem found. The only thing left to be done is to // check out all files from "theirs" which have been selected to // go into the new index. checkout(); } // All content operations are successfully done. If we can now write // the new index we are on quite safe ground. Even if the checkout // of files coming from "theirs" fails the user can work around such // failures by checking out the index again. if (!builder.commit()) { revertModifiedFiles(); throw new IndexWriteException(); } } /** * Writes the changes to the index. * * @return the {@link Result} of the operation. * @throws IOException * if any of the writes fail */ public Result writeIndexChanges() throws IOException { result.treeId = getLockedDirCache().writeTree(inserter); indexChangesWritten = true; return result; } /** * Adds a {@link DirCacheEntry} for direct checkout and remembers its * {@link CheckoutMetadata}. * * @param path * of the entry * @param entry * to add * @param cleanupStreamType * to use for the cleanup metadata * @param cleanupSmudgeCommand * to use for the cleanup metadata * @param checkoutStreamType * to use for the checkout metadata * @param checkoutSmudgeCommand * to use for the checkout metadata */ public void addToCheckout(String path, DirCacheEntry entry, EolStreamType cleanupStreamType, String cleanupSmudgeCommand, EolStreamType checkoutStreamType, String checkoutSmudgeCommand) { if (entry != null) { // In some cases, we just want to add the metadata. toBeCheckedOut.put(path, entry); } addCheckoutMetadata(cleanupMetadataByPath, path, cleanupStreamType, cleanupSmudgeCommand); addCheckoutMetadata(checkoutMetadataByPath, path, checkoutStreamType, checkoutSmudgeCommand); } /** * Gets a map which maps the paths of files which have to be checked out * because the operation created new fully-merged content for this file * into the index. *

* This means: the operation wrote a new stage 0 entry for this path. *

* * @return the map */ public Map getToBeCheckedOut() { return toBeCheckedOut; } /** * Remembers the given file to be deleted. *

* Note the actual deletion is only done in * {@link #writeWorkTreeChanges}. * * @param path * of the file to be deleted * @param file * to be deleted * @param streamType * to use for cleanup metadata * @param smudgeCommand * to use for cleanup metadata */ public void deleteFile(String path, File file, EolStreamType streamType, String smudgeCommand) { toBeDeleted.put(path, file); if (file != null && file.isFile()) { addCheckoutMetadata(cleanupMetadataByPath, path, streamType, smudgeCommand); } } /** * Remembers the {@link CheckoutMetadata} for the given path; it may be * needed in {@link #checkout()} or in {@link #revertModifiedFiles()}. * * @param map * to add the metadata to * @param path * of the current node * @param streamType * to use for the metadata * @param smudgeCommand * to use for the metadata */ private void addCheckoutMetadata(Map map, String path, EolStreamType streamType, String smudgeCommand) { if (inCore || map == null) { return; } map.put(path, new CheckoutMetadata(streamType, smudgeCommand)); } /** * Detects if CRLF conversion has been configured. *

* See {@link EolStreamTypeUtil#detectStreamType} for more info. * * @param attributes * of the file for which the type is to be detected * @return the detected type */ public EolStreamType detectCheckoutStreamType(Attributes attributes) { if (inCore) { return null; } return EolStreamTypeUtil.detectStreamType(OperationType.CHECKOUT_OP, workingTreeOptions, attributes); } private void handleDeletedFiles() { // Iterate in reverse so that "folder/file" is deleted before // "folder". Otherwise, this could result in a failing path because // of a non-empty directory, for which delete() would fail. for (String path : toBeDeleted.descendingKeySet()) { File file = inCore ? null : toBeDeleted.get(path); if (file != null && !file.delete()) { if (!file.isDirectory()) { result.failedToDelete.add(path); } } } } /** * Marks the given path as modified in the operation. * * @param path * to mark as modified */ public void markAsModified(String path) { result.modifiedFiles.add(path); } /** * Gets the list of files which were modified in this operation. * * @return the list */ public List getModifiedFiles() { return result.modifiedFiles; } private void checkout() throws NoWorkTreeException, IOException { for (Map.Entry entry : toBeCheckedOut .entrySet()) { DirCacheEntry dirCacheEntry = entry.getValue(); String gitPath = entry.getKey(); if (dirCacheEntry.getFileMode() == FileMode.GITLINK) { checkout.checkoutGitlink(dirCacheEntry, gitPath); } else { checkout.checkout(dirCacheEntry, checkoutMetadataByPath.get(gitPath), reader, gitPath); result.modifiedFiles.add(gitPath); } } } /** * Reverts any uncommitted changes in the worktree. We know that for all * modified files the old content was in the old index and the index * contained only stage 0. In case of inCore operation just clear the * history of modified files. * * @throws IOException * in case the cleaning up failed */ public void revertModifiedFiles() throws IOException { if (inCore) { result.modifiedFiles.clear(); return; } if (indexChangesWritten) { return; } for (String path : result.modifiedFiles) { DirCacheEntry entry = dirCache.getEntry(path); if (entry != null) { checkout.checkout(entry, cleanupMetadataByPath.get(path), reader, path); } } } @Override public void close() throws IOException { if (implicitDirCache) { dirCache.unlock(); } } /** * Updates the file in the checkout with the given content. * * @param inputStream * the content to be updated * @param streamType * for parsing the content * @param smudgeCommand * for formatting the content * @param path * of the file to be updated * @param file * to be updated * @throws IOException * if the file cannot be updated */ public void updateFileWithContent(StreamSupplier inputStream, EolStreamType streamType, String smudgeCommand, String path, File file) throws IOException { if (inCore) { return; } checkout.safeCreateParentDirectory(path, file.getParentFile(), false); CheckoutMetadata metadata = new CheckoutMetadata(streamType, smudgeCommand); try (OutputStream outputStream = new FileOutputStream(file)) { DirCacheCheckout.getContent(repo, path, metadata, inputStream, workingTreeOptions, outputStream); } } /** * Creates a path with the given content, and adds it to the specified * stage to the index builder. * * @param input * the content to be updated * @param path * of the file to be updated * @param fileMode * of the modified file * @param entryStage * of the new entry * @param lastModified * instant of the modified file * @param len * of the content * @param lfsAttribute * for checking for LFS enablement * @return the entry which was added to the index * @throws IOException * if inserting the content fails */ public DirCacheEntry insertToIndex(InputStream input, byte[] path, FileMode fileMode, int entryStage, Instant lastModified, int len, Attribute lfsAttribute) throws IOException { return addExistingToIndex(insertResult(input, lfsAttribute, len), path, fileMode, entryStage, lastModified, len); } /** * Adds a path with the specified stage to the index builder. * * @param objectId * of the existing object to add * @param path * of the modified file * @param fileMode * of the modified file * @param entryStage * of the new entry * @param lastModified * instant of the modified file * @param len * of the modified file content * @return the entry which was added to the index */ public DirCacheEntry addExistingToIndex(ObjectId objectId, byte[] path, FileMode fileMode, int entryStage, Instant lastModified, int len) { DirCacheEntry dce = new DirCacheEntry(path, entryStage); dce.setFileMode(fileMode); if (lastModified != null) { dce.setLastModified(lastModified); } dce.setLength(inCore ? 0 : len); dce.setObjectId(objectId); builder.add(dce); return dce; } private ObjectId insertResult(InputStream input, Attribute lfsAttribute, long length) throws IOException { try (LfsInputStream is = LfsFactory.getInstance() .applyCleanFilter(repo, input, length, lfsAttribute)) { return inserter.insert(OBJ_BLOB, is.getLength(), is); } } /** * Gets the non-null repository instance of this * {@link WorkTreeUpdater}. * * @return non-null repository instance * @throws NullPointerException * if the handler was constructed without a repository. */ @NonNull private Repository nonNullRepo() throws NullPointerException { return Objects.requireNonNull(repo, () -> JGitText.get().repositoryIsRequired); } } /** * If the merge fails (means: not stopped because of unresolved conflicts) * this enum is used to explain why it failed */ public enum MergeFailureReason { /** the merge failed because of a dirty index */ DIRTY_INDEX, /** the merge failed because of a dirty workingtree */ DIRTY_WORKTREE, /** the merge failed because of a file could not be deleted */ COULD_NOT_DELETE } /** * The tree walk which we'll iterate over to merge entries. * * @since 3.4 */ protected NameConflictTreeWalk tw; /** * string versions of a list of commit SHA1s * * @since 3.0 */ protected String[] commitNames; /** * Index of the base tree within the {@link #tw tree walk}. * * @since 3.4 */ protected static final int T_BASE = 0; /** * Index of our tree in withthe {@link #tw tree walk}. * * @since 3.4 */ protected static final int T_OURS = 1; /** * Index of their tree within the {@link #tw tree walk}. * * @since 3.4 */ protected static final int T_THEIRS = 2; /** * Index of the index tree within the {@link #tw tree walk}. * * @since 3.4 */ protected static final int T_INDEX = 3; /** * Index of the working directory tree within the {@link #tw tree walk}. * * @since 3.4 */ protected static final int T_FILE = 4; /** * Handler for repository I/O actions. * * @since 6.3 */ protected WorkTreeUpdater workTreeUpdater; /** * merge result as tree * * @since 3.0 */ protected ObjectId resultTree; /** * Files modified during this operation. Note this list is only updated after a successful write. */ protected List modifiedFiles = new ArrayList<>(); /** * Paths that could not be merged by this merger because of an unsolvable * conflict. * * @since 3.4 */ protected List unmergedPaths = new ArrayList<>(); /** * Low-level textual merge results. Will be passed on to the callers in case * of conflicts. * * @since 3.4 */ protected Map> mergeResults = new HashMap<>(); /** * Paths for which the merge failed altogether. * * @since 3.4 */ protected Map failingPaths = new HashMap<>(); /** * Updated as we merge entries of the tree walk. Tells us whether we should * recurse into the entry if it is a subtree. * * @since 3.4 */ protected boolean enterSubtree; /** * Set to true if this merge should work in-memory. The repos dircache and * workingtree are not touched by this method. Eventually needed files are * created as temporary files and a new empty, in-memory dircache will be * used instead the repo's one. Often used for bare repos where the repo * doesn't even have a workingtree and dircache. * @since 3.0 */ protected boolean inCore; /** * Directory cache * @since 3.0 */ protected DirCache dircache; /** * The iterator to access the working tree. If set to null this * merger will not touch the working tree. * @since 3.0 */ protected WorkingTreeIterator workingTreeIterator; /** * our merge algorithm * @since 3.0 */ protected MergeAlgorithm mergeAlgorithm; /** * The {@link ContentMergeStrategy} to use for "resolve" and "recursive" * merges. */ @NonNull private ContentMergeStrategy contentStrategy = ContentMergeStrategy.CONFLICT; /** * The {@link AttributesNodeProvider} to use while merging trees. * * @since 6.10.1 */ protected AttributesNodeProvider attributesNodeProvider; private static MergeAlgorithm getMergeAlgorithm(Config config) { SupportedAlgorithm diffAlg = config.getEnum( CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, HISTOGRAM); return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); } private static String[] defaultCommitNames() { return new String[]{"BASE", "OURS", "THEIRS"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private static final Attributes NO_ATTRIBUTES = new Attributes(); /** * Constructor for ResolveMerger. * * @param local * the {@link org.eclipse.jgit.lib.Repository}. * @param inCore * a boolean. */ protected ResolveMerger(Repository local, boolean inCore) { super(local); Config config = local.getConfig(); mergeAlgorithm = getMergeAlgorithm(config); commitNames = defaultCommitNames(); this.inCore = inCore; } /** * Constructor for ResolveMerger. * * @param local * the {@link org.eclipse.jgit.lib.Repository}. */ protected ResolveMerger(Repository local) { this(local, false); } /** * Constructor for ResolveMerger. * * @param inserter * an {@link org.eclipse.jgit.lib.ObjectInserter} object. * @param config * the repository configuration * @since 4.8 */ protected ResolveMerger(ObjectInserter inserter, Config config) { super(inserter); mergeAlgorithm = getMergeAlgorithm(config); commitNames = defaultCommitNames(); inCore = true; } /** * Retrieves the content merge strategy for content conflicts. * * @return the {@link ContentMergeStrategy} in effect * @since 5.12 */ @NonNull public ContentMergeStrategy getContentMergeStrategy() { return contentStrategy; } /** * Sets the content merge strategy for content conflicts. * * @param strategy * {@link ContentMergeStrategy} to use * @since 5.12 */ public void setContentMergeStrategy(ContentMergeStrategy strategy) { contentStrategy = strategy == null ? ContentMergeStrategy.CONFLICT : strategy; } @Override protected boolean mergeImpl() throws IOException { return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1], false); } /** * adds a new path with the specified stage to the index builder * * @param path * the new path * @param p * canonical tree parser * @param stage * the stage * @param lastModified * lastModified attribute of the file * @param len * file length * @return the entry which was added to the index */ private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage, Instant lastModified, long len) { if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) { return workTreeUpdater.addExistingToIndex(p.getEntryObjectId(), path, p.getEntryFileMode(), stage, lastModified, (int) len); } return null; } /** * Adds the conflict stages for the current path of {@link #tw} to the index * builder and returns the "theirs" stage; if present. * * @param base * of the conflict * @param ours * of the conflict * @param theirs * of the conflict * @return the {@link DirCacheEntry} for the "theirs" stage, or {@code null} */ private DirCacheEntry addConflict(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs) { add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0); add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0); return add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0); } /** * adds a entry to the index builder which is a copy of the specified * DirCacheEntry * * @param e * the entry which should be copied * * @return the entry which was added to the index */ private DirCacheEntry keep(DirCacheEntry e) { return workTreeUpdater.addExistingToIndex(e.getObjectId(), e.getRawPath(), e.getFileMode(), e.getStage(), e.getLastModifiedInstant(), e.getLength()); } /** * Adds a {@link DirCacheEntry} for direct checkout and remembers its * {@link CheckoutMetadata}. * * @param path * of the entry * @param entry * to add * @param attributes * the {@link Attributes} of the trees * @throws IOException * if the {@link CheckoutMetadata} cannot be determined * @since 6.1 */ protected void addToCheckout(String path, DirCacheEntry entry, Attributes[] attributes) throws IOException { EolStreamType cleanupStreamType = workTreeUpdater.detectCheckoutStreamType(attributes[T_OURS]); String cleanupSmudgeCommand = tw.getSmudgeCommand(attributes[T_OURS]); EolStreamType checkoutStreamType = workTreeUpdater.detectCheckoutStreamType(attributes[T_THEIRS]); String checkoutSmudgeCommand = tw.getSmudgeCommand(attributes[T_THEIRS]); workTreeUpdater.addToCheckout(path, entry, cleanupStreamType, cleanupSmudgeCommand, checkoutStreamType, checkoutSmudgeCommand); } /** * Remember a path for deletion, and remember its {@link CheckoutMetadata} * in case it has to be restored in the cleanUp. * * @param path * of the entry * @param isFile * whether it is a file * @param attributes * to use for determining the {@link CheckoutMetadata} * @throws IOException * if the {@link CheckoutMetadata} cannot be determined * @since 5.1 */ protected void addDeletion(String path, boolean isFile, Attributes attributes) throws IOException { if (db == null || nonNullRepo().isBare() || !isFile) return; File file = new File(nonNullRepo().getWorkTree(), path); EolStreamType streamType = workTreeUpdater.detectCheckoutStreamType(attributes); String smudgeCommand = tw.getSmudgeCommand(attributes); workTreeUpdater.deleteFile(path, file, streamType, smudgeCommand); } /** * Processes one path and tries to merge taking git attributes in account. * This method will do all trivial (not content) merges and will also detect * if a merge will fail. The merge will fail when one of the following is * true *

    *
  • the index entry does not match the entry in ours. When merging one * branch into the current HEAD, ours will point to HEAD and theirs will * point to the other branch. It is assumed that the index matches the HEAD * because it will only not match HEAD if it was populated before the merge * operation. But the merge commit should not accidentally contain * modifications done before the merge. Check the git read-tree documentation for further explanations.
  • *
  • A conflict was detected and the working-tree file is dirty. When a * conflict is detected the content-merge algorithm will try to write a * merged version into the working-tree. If the file is dirty we would * override unsaved data.
  • *
* * @param base * the common base for ours and theirs * @param ours * the ours side of the merge. When merging a branch into the * HEAD ours will point to HEAD * @param theirs * the theirs side of the merge. When merging a branch into the * current HEAD theirs will point to the branch which is merged * into HEAD. * @param index * the index entry * @param work * the file in the working tree * @param ignoreConflicts * see * {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)} * @param attributes * the {@link Attributes} for the three trees * @return false if the merge will fail because the index entry * didn't match ours or the working-dir file was dirty and a * conflict occurred * @throws java.io.IOException * if an IO error occurred * @since 6.1 */ protected boolean processEntry(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs, DirCacheBuildIterator index, WorkingTreeIterator work, boolean ignoreConflicts, Attributes[] attributes) throws IOException { enterSubtree = true; final int modeO = tw.getRawMode(T_OURS); final int modeT = tw.getRawMode(T_THEIRS); final int modeB = tw.getRawMode(T_BASE); boolean gitLinkMerging = isGitLink(modeO) || isGitLink(modeT) || isGitLink(modeB); if (modeO == 0 && modeT == 0 && modeB == 0) { // File is either untracked or new, staged but uncommitted return true; } if (isIndexDirty()) { return false; } DirCacheEntry ourDce = null; if (index == null || index.getDirCacheEntry() == null) { // create a fake DCE, but only if ours is valid. ours is kept only // in case it is valid, so a null ourDce is ok in all other cases. if (nonTree(modeO)) { ourDce = new DirCacheEntry(tw.getRawPath()); ourDce.setObjectId(tw.getObjectId(T_OURS)); ourDce.setFileMode(tw.getFileMode(T_OURS)); } } else { ourDce = index.getDirCacheEntry(); } if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) { // OURS and THEIRS have equal content. Check the file mode if (modeO == modeT) { // content and mode of OURS and THEIRS are equal: it doesn't // matter which one we choose. OURS is chosen. Since the index // is clean (the index matches already OURS) we can keep the existing one keep(ourDce); // no checkout needed! return true; } // same content but different mode on OURS and THEIRS. // Try to merge the mode and report an error if this is // not possible. int newMode = mergeFileModes(modeB, modeO, modeT); if (newMode != FileMode.MISSING.getBits()) { if (newMode == modeO) { // ours version is preferred keep(ourDce); } else { // the preferred version THEIRS has a different mode // than ours. Check it out! if (isWorktreeDirty(work, ourDce)) { return false; } // we know about length and lastMod only after we have // written the new content. // This will happen later. Set these values to 0 for know. DirCacheEntry e = add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_0, EPOCH, 0); addToCheckout(tw.getPathString(), e, attributes); } return true; } if (!ignoreConflicts) { // FileModes are not mergeable. We found a conflict on modes. // For conflicting entries we don't know lastModified and // length. // This path can be skipped on ignoreConflicts, so the caller // could use virtual commit. addConflict(base, ours, theirs); unmergedPaths.add(tw.getPathString()); mergeResults.put(tw.getPathString(), new MergeResult<>(Collections.emptyList())); } return true; } if (modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) { // THEIRS was not changed compared to BASE. All changes must be in // OURS. OURS is chosen. We can keep the existing entry. if (ourDce != null) { keep(ourDce); } // no checkout needed! return true; } if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) { // OURS was not changed compared to BASE. All changes must be in // THEIRS. THEIRS is chosen. // Check worktree before checking out THEIRS if (isWorktreeDirty(work, ourDce)) { return false; } if (nonTree(modeT)) { // we know about length and lastMod only after we have written // the new content. // This will happen later. Set these values to 0 for know. DirCacheEntry e = add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_0, EPOCH, 0); if (e != null) { addToCheckout(tw.getPathString(), e, attributes); } return true; } // we want THEIRS ... but THEIRS contains a folder or the // deletion of the path. Delete what's in the working tree, // which we know to be clean. if (tw.getTreeCount() > T_FILE && tw.getRawMode(T_FILE) == 0) { // Not present in working tree, so nothing to delete return true; } if (modeT != 0 && modeT == modeB) { // Base, ours, and theirs all contain a folder: don't delete return true; } addDeletion(tw.getPathString(), nonTree(modeO), attributes[T_OURS]); return true; } if (tw.isSubtree()) { // file/folder conflicts: here I want to detect only file/folder // conflict between ours and theirs. file/folder conflicts between // base/index/workingTree and something else are not relevant or // detected later if (nonTree(modeO) != nonTree(modeT)) { if (ignoreConflicts) { // In case of merge failures, ignore this path instead of reporting unmerged, so // a caller can use virtual commit. This will not result in files with conflict // markers in the index/working tree. The actual diff on the path will be // computed directly on children. enterSubtree = false; return true; } if (nonTree(modeB)) { add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0); } if (nonTree(modeO)) { add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0); } if (nonTree(modeT)) { add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0); } unmergedPaths.add(tw.getPathString()); enterSubtree = false; return true; } // ours and theirs are both folders or both files (and treewalk // tells us we are in a subtree because of index or working-dir). // If they are both folders no content-merge is required - we can // return here. if (!nonTree(modeO)) { return true; } // ours and theirs are both files, just fall out of the if block // and do the content merge } if (nonTree(modeO) && nonTree(modeT)) { // Check worktree before modifying files boolean worktreeDirty = isWorktreeDirty(work, ourDce); if (!attributes[T_OURS].canBeContentMerged() && worktreeDirty) { return false; } if (gitLinkMerging && ignoreConflicts) { // Always select 'ours' in case of GITLINK merge failures so // a caller can use virtual commit. add(tw.getRawPath(), ours, DirCacheEntry.STAGE_0, EPOCH, 0); return true; } else if (gitLinkMerging) { addConflict(base, ours, theirs); MergeResult result = createGitLinksMergeResult( base, ours, theirs); result.setContainsConflicts(true); mergeResults.put(tw.getPathString(), result); unmergedPaths.add(tw.getPathString()); return true; } else if (!attributes[T_OURS].canBeContentMerged()) { // File marked as binary switch (getContentMergeStrategy()) { case OURS: keep(ourDce); return true; case THEIRS: DirCacheEntry theirEntry = add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_0, EPOCH, 0); addToCheckout(tw.getPathString(), theirEntry, attributes); return true; default: break; } if (ignoreConflicts) { // If the path is selected to be treated as binary via attributes, we do not perform // content merge. When ignoreConflicts = true, we simply keep OURS to allow virtual commit // to be built. keep(ourDce); return true; } // add the conflicting path to merge result String currentPath = tw.getPathString(); MergeResult result = new MergeResult<>( Collections.emptyList()); result.setContainsConflicts(true); mergeResults.put(currentPath, result); addConflict(base, ours, theirs); // attribute merge issues are conflicts but not failures unmergedPaths.add(currentPath); return true; } // Check worktree before modifying files if (worktreeDirty) { return false; } MergeResult result = null; boolean hasSymlink = FileMode.SYMLINK.equals(modeO) || FileMode.SYMLINK.equals(modeT); String currentPath = tw.getPathString(); // if the path is not a symlink in ours and theirs if (!hasSymlink) { try { result = contentMerge(base, ours, theirs, attributes, getContentMergeStrategy()); if (result.containsConflicts() && !ignoreConflicts) { result.setContainsConflicts(true); unmergedPaths.add(currentPath); } else if (ignoreConflicts) { result.setContainsConflicts(false); } updateIndex(base, ours, theirs, result, attributes[T_OURS]); workTreeUpdater.markAsModified(currentPath); // Entry is null - only add the metadata addToCheckout(currentPath, null, attributes); return true; } catch (BinaryBlobException e) { // The file is binary in either OURS, THEIRS or BASE if (ignoreConflicts) { // When ignoreConflicts = true, we simply keep OURS to allow virtual commit to be built. keep(ourDce); return true; } } } switch (getContentMergeStrategy()) { case OURS: keep(ourDce); return true; case THEIRS: DirCacheEntry e = add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_0, EPOCH, 0); if (e != null) { addToCheckout(currentPath, e, attributes); } return true; default: result = new MergeResult<>(Collections.emptyList()); result.setContainsConflicts(true); break; } if (hasSymlink) { if (ignoreConflicts) { result.setContainsConflicts(false); if (((modeT & FileMode.TYPE_MASK) == FileMode.TYPE_FILE)) { DirCacheEntry e = add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_0, EPOCH, 0); addToCheckout(currentPath, e, attributes); } else { keep(ourDce); } } else { DirCacheEntry e = addConflict(base, ours, theirs); mergeResults.put(currentPath, result); unmergedPaths.add(currentPath); // If theirs is a file, check it out. In link/file // conflicts, C git prefers the file. if (((modeT & FileMode.TYPE_MASK) == FileMode.TYPE_FILE) && e != null) { addToCheckout(currentPath, e, attributes); } } } else { // This is reachable if contentMerge() call above threw BinaryBlobException, so we don't // need to check ignoreConflicts here, since it's already handled above. result.setContainsConflicts(true); addConflict(base, ours, theirs); unmergedPaths.add(currentPath); mergeResults.put(currentPath, result); } return true; } else if (modeO != modeT) { // OURS or THEIRS has been deleted if (((modeO != 0 && !tw.idEqual(T_BASE, T_OURS)) || (modeT != 0 && !tw .idEqual(T_BASE, T_THEIRS)))) { if (gitLinkMerging && ignoreConflicts) { add(tw.getRawPath(), ours, DirCacheEntry.STAGE_0, EPOCH, 0); } else if (gitLinkMerging) { addConflict(base, ours, theirs); MergeResult result = createGitLinksMergeResult( base, ours, theirs); result.setContainsConflicts(true); mergeResults.put(tw.getPathString(), result); unmergedPaths.add(tw.getPathString()); } else { boolean isSymLink = ((modeO | modeT) & FileMode.TYPE_MASK) == FileMode.TYPE_SYMLINK; // Content merge strategy does not apply to delete-modify // conflicts! MergeResult result; if (isSymLink) { // No need to do a content merge result = new MergeResult<>(Collections.emptyList()); result.setContainsConflicts(true); } else { try { result = contentMerge(base, ours, theirs, attributes, ContentMergeStrategy.CONFLICT); } catch (BinaryBlobException e) { result = new MergeResult<>(Collections.emptyList()); result.setContainsConflicts(true); } } if (ignoreConflicts) { result.setContainsConflicts(false); if (isSymLink) { if (modeO != 0) { keep(ourDce); } else { // Check out theirs if (isWorktreeDirty(work, ourDce)) { return false; } DirCacheEntry e = add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_0, EPOCH, 0); if (e != null) { addToCheckout(tw.getPathString(), e, attributes); } } } else { // In case a conflict is detected the working tree // file is again filled with new content (containing // conflict markers). But also stage 0 of the index // is filled with that content. updateIndex(base, ours, theirs, result, attributes[T_OURS]); } } else { DirCacheEntry e = addConflict(base, ours, theirs); // OURS was deleted checkout THEIRS if (modeO == 0) { // Check worktree before checking out THEIRS if (isWorktreeDirty(work, ourDce)) { return false; } if (nonTree(modeT) && e != null) { addToCheckout(tw.getPathString(), e, attributes); } } unmergedPaths.add(tw.getPathString()); // generate a MergeResult for the deleted file mergeResults.put(tw.getPathString(), result); } } } } return true; } private static MergeResult createGitLinksMergeResult( CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs) { return new MergeResult<>(Arrays.asList( new SubmoduleConflict( base == null ? null : base.getEntryObjectId()), new SubmoduleConflict( ours == null ? null : ours.getEntryObjectId()), new SubmoduleConflict( theirs == null ? null : theirs.getEntryObjectId()))); } /** * Does the content merge. The three texts base, ours and theirs are * specified with {@link CanonicalTreeParser}. If any of the parsers is * specified as null then an empty text will be used instead. * * @param base * used to parse base tree * @param ours * used to parse ours tree * @param theirs * used to parse theirs tree * @param attributes * attributes for the different stages * @param strategy * merge strategy * * @return the result of the content merge * @throws BinaryBlobException * if any of the blobs looks like a binary blob * @throws IOException * if an IO error occurred */ private MergeResult contentMerge(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs, Attributes[] attributes, ContentMergeStrategy strategy) throws BinaryBlobException, IOException { // TW: The attributes here are used to determine the LFS smudge filter. // Is doing a content merge on LFS items really a good idea?? RawText baseText = base == null ? RawText.EMPTY_TEXT : getRawText(base.getEntryObjectId(), attributes[T_BASE]); RawText ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(ours.getEntryObjectId(), attributes[T_OURS]); RawText theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(theirs.getEntryObjectId(), attributes[T_THEIRS]); mergeAlgorithm.setContentMergeStrategy( getAttributesContentMergeStrategy(attributes[T_OURS], strategy)); return mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText, ourText, theirsText); } private ContentMergeStrategy getAttributesContentMergeStrategy( Attributes attributes, ContentMergeStrategy strategy) { Attribute attr = attributes.get(Constants.ATTR_MERGE); if (attr != null) { String attrValue = attr.getValue(); if (attrValue != null && attrValue .equals(Constants.ATTR_BUILTIN_UNION_MERGE_DRIVER)) { return ContentMergeStrategy.UNION; } } return strategy; } private boolean isIndexDirty() { if (inCore) { return false; } final int modeI = tw.getRawMode(T_INDEX); final int modeO = tw.getRawMode(T_OURS); // Index entry has to match ours to be considered clean final boolean isDirty = nonTree(modeI) && !(modeO == modeI && tw.idEqual(T_INDEX, T_OURS)); if (isDirty) { failingPaths .put(tw.getPathString(), MergeFailureReason.DIRTY_INDEX); } return isDirty; } private boolean isWorktreeDirty(WorkingTreeIterator work, DirCacheEntry ourDce) throws IOException { if (work == null) { return false; } final int modeF = tw.getRawMode(T_FILE); final int modeO = tw.getRawMode(T_OURS); // Worktree entry has to match ours to be considered clean boolean isDirty; if (ourDce != null) { isDirty = work.isModified(ourDce, true, reader); } else { isDirty = work.isModeDifferent(modeO); if (!isDirty && nonTree(modeF)) { isDirty = !tw.idEqual(T_FILE, T_OURS); } } // Ignore existing empty directories if (isDirty && modeF == FileMode.TYPE_TREE && modeO == FileMode.TYPE_MISSING) { isDirty = false; } if (isDirty) { failingPaths.put(tw.getPathString(), MergeFailureReason.DIRTY_WORKTREE); } return isDirty; } /** * Updates the index after a content merge has happened. If no conflict has * occurred this includes persisting the merged content to the object * database. In case of conflicts this method takes care to write the * correct stages to the index. * * @param base * used to parse base tree * @param ours * used to parse ours tree * @param theirs * used to parse theirs tree * @param result * merge result * @param attributes * the file's attributes * @throws IOException * if an IO error occurred */ private void updateIndex(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs, MergeResult result, Attributes attributes) throws IOException { TemporaryBuffer rawMerged = null; try { rawMerged = doMerge(result); File mergedFile = inCore ? null : writeMergedFile(rawMerged, attributes); if (result.containsConflicts()) { // A conflict occurred, the file will contain conflict markers // the index will be populated with the three stages and the // workdir (if used) contains the halfway merged content. addConflict(base, ours, theirs); mergeResults.put(tw.getPathString(), result); return; } // No conflict occurred, the file will contain fully merged content. // The index will be populated with the new merged version. Instant lastModified = mergedFile == null ? null : nonNullRepo().getFS().lastModifiedInstant(mergedFile); // Set the mode for the new content. Fall back to REGULAR_FILE if // we can't merge modes of OURS and THEIRS. int newMode = mergeFileModes(tw.getRawMode(0), tw.getRawMode(1), tw.getRawMode(2)); FileMode mode = newMode == FileMode.MISSING.getBits() ? FileMode.REGULAR_FILE : FileMode.fromBits(newMode); workTreeUpdater.insertToIndex(rawMerged.openInputStream(), tw.getPathString().getBytes(UTF_8), mode, DirCacheEntry.STAGE_0, lastModified, (int) rawMerged.length(), attributes.get(Constants.ATTR_MERGE)); } finally { if (rawMerged != null) { rawMerged.destroy(); } } } /** * Writes merged file content to the working tree. * * @param rawMerged * the raw merged content * @param attributes * the files .gitattributes entries * @return the working tree file to which the merged content was written. * @throws IOException * if an IO error occurred */ private File writeMergedFile(TemporaryBuffer rawMerged, Attributes attributes) throws IOException { File workTree = nonNullRepo().getWorkTree(); String gitPath = tw.getPathString(); File of = new File(workTree, gitPath); EolStreamType eol = workTreeUpdater.detectCheckoutStreamType(attributes); workTreeUpdater.updateFileWithContent(rawMerged::openInputStream, eol, tw.getSmudgeCommand(attributes), gitPath, of); return of; } private TemporaryBuffer doMerge(MergeResult result) throws IOException { TemporaryBuffer.LocalFile buf = new TemporaryBuffer.LocalFile( db != null ? nonNullRepo().getDirectory() : null, workTreeUpdater.getInCoreFileSizeLimit()); boolean success = false; try { new MergeFormatter().formatMerge(buf, result, Arrays.asList(commitNames), UTF_8); buf.close(); success = true; } finally { if (!success) { buf.destroy(); } } return buf; } /** * Try to merge filemodes. If only ours or theirs have changed the mode * (compared to base) we choose that one. If ours and theirs have equal * modes return that one. If also that is not the case the modes are not * mergeable. Return {@link FileMode#MISSING} int that case. * * @param modeB * filemode found in BASE * @param modeO * filemode found in OURS * @param modeT * filemode found in THEIRS * * @return the merged filemode or {@link FileMode#MISSING} in case of a * conflict */ private int mergeFileModes(int modeB, int modeO, int modeT) { if (modeO == modeT) { return modeO; } if (modeB == modeO) { // Base equal to Ours -> chooses Theirs if that is not missing return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT; } if (modeB == modeT) { // Base equal to Theirs -> chooses Ours if that is not missing return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO; } return FileMode.MISSING.getBits(); } private RawText getRawText(ObjectId id, Attributes attributes) throws IOException, BinaryBlobException { if (id.equals(ObjectId.zeroId())) { return new RawText(new byte[]{}); } ObjectLoader loader = LfsFactory.getInstance().applySmudgeFilter( getRepository(), reader.open(id, OBJ_BLOB), attributes.get(Constants.ATTR_MERGE)); int threshold = PackConfig.DEFAULT_BIG_FILE_THRESHOLD; return RawText.load(loader, threshold); } private static boolean nonTree(int mode) { return mode != 0 && !FileMode.TREE.equals(mode); } private static boolean isGitLink(int mode) { return FileMode.GITLINK.equals(mode); } @Override public ObjectId getResultTreeId() { return (resultTree == null) ? null : resultTree.toObjectId(); } /** * Set the names of the commits as they would appear in conflict markers * * @param commitNames * the names of the commits as they would appear in conflict * markers */ public void setCommitNames(String[] commitNames) { this.commitNames = commitNames; } /** * Get the names of the commits as they would appear in conflict markers. * * @return the names of the commits as they would appear in conflict * markers. */ public String[] getCommitNames() { return commitNames; } /** * Get the paths with conflicts. This is a subset of the files listed by * {@link #getModifiedFiles()} * * @return the paths with conflicts. This is a subset of the files listed by * {@link #getModifiedFiles()} */ public List getUnmergedPaths() { return unmergedPaths; } /** * Get the paths of files which have been modified by this merge. * * @return the paths of files which have been modified by this merge. A file * will be modified if a content-merge works on this path or if the * merge algorithm decides to take the theirs-version. This is a * superset of the files listed by {@link #getUnmergedPaths()}. */ public List getModifiedFiles() { return workTreeUpdater != null ? workTreeUpdater.getModifiedFiles() : modifiedFiles; } /** * Get a map which maps the paths of files which have to be checked out * because the merge created new fully-merged content for this file into the * index. * * @return a map which maps the paths of files which have to be checked out * because the merge created new fully-merged content for this file * into the index. This means: the merge wrote a new stage 0 entry * for this path. */ public Map getToBeCheckedOut() { return workTreeUpdater.getToBeCheckedOut(); } /** * Get the mergeResults * * @return the mergeResults */ public Map> getMergeResults() { return mergeResults; } /** * Get list of paths causing this merge to fail (not stopped because of a * conflict). * * @return lists paths causing this merge to fail (not stopped because of a * conflict). null is returned if this merge didn't * fail. */ public Map getFailingPaths() { return failingPaths.isEmpty() ? null : failingPaths; } /** * Returns whether this merge failed (i.e. not stopped because of a * conflict) * * @return true if a failure occurred, false * otherwise */ public boolean failed() { return !failingPaths.isEmpty(); } /** * Sets the DirCache which shall be used by this merger. If the DirCache is * not set explicitly and if this merger doesn't work in-core, this merger * will implicitly get and lock a default DirCache. If the DirCache is * explicitly set the caller is responsible to lock it in advance. Finally * the merger will call {@link org.eclipse.jgit.dircache.DirCache#commit()} * which requires that the DirCache is locked. If the {@link #mergeImpl()} * returns without throwing an exception the lock will be released. In case * of exceptions the caller is responsible to release the lock. * * @param dc * the DirCache to set */ public void setDirCache(DirCache dc) { this.dircache = dc; } /** * Sets the WorkingTreeIterator to be used by this merger. If no * WorkingTreeIterator is set this merger will ignore the working tree and * fail if a content merge is necessary. *

* TODO: enhance WorkingTreeIterator to support write operations. Then this * merger will be able to merge with a different working tree abstraction. * * @param workingTreeIterator * the workingTreeIt to set */ public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) { this.workingTreeIterator = workingTreeIterator; } /** * Sets the {@link AttributesNodeProvider} to be used by this merger. * * @param attributesNodeProvider * the attributeNodeProvider to set * @since 6.10.1 */ public void setAttributesNodeProvider( AttributesNodeProvider attributesNodeProvider) { this.attributesNodeProvider = attributesNodeProvider; } /** * The resolve conflict way of three way merging * * @param baseTree * a {@link org.eclipse.jgit.treewalk.AbstractTreeIterator} * object. * @param headTree * a {@link org.eclipse.jgit.revwalk.RevTree} object. * @param mergeTree * a {@link org.eclipse.jgit.revwalk.RevTree} object. * @param ignoreConflicts * Controls what to do in case a content-merge is done and a * conflict is detected. The default setting for this should be * false. In this case the working tree file is * filled with new content (containing conflict markers) and the * index is filled with multiple stages containing BASE, OURS and * THEIRS content. Having such non-0 stages is the sign to git * tools that there are still conflicts for that path. *

* If true is specified the behavior is different. * In case a conflict is detected the working tree file is again * filled with new content (containing conflict markers). But * also stage 0 of the index is filled with that content. No * other stages are filled. Means: there is no conflict on that * path but the new content (including conflict markers) is * stored as successful merge result. This is needed in the * context of {@link org.eclipse.jgit.merge.RecursiveMerger} * where when determining merge bases we don't want to deal with * content-merge conflicts. * @return whether the trees merged cleanly * @throws java.io.IOException * if an IO error occurred * @since 3.5 */ protected boolean mergeTrees(AbstractTreeIterator baseTree, RevTree headTree, RevTree mergeTree, boolean ignoreConflicts) throws IOException { try { workTreeUpdater = inCore ? WorkTreeUpdater.createInCoreWorkTreeUpdater(db, dircache, getObjectInserter()) : WorkTreeUpdater.createWorkTreeUpdater(db, dircache); dircache = workTreeUpdater.getLockedDirCache(); tw = new NameConflictTreeWalk(db, reader); if (attributesNodeProvider != null) { tw.setAttributesNodeProvider(attributesNodeProvider); } tw.addTree(baseTree); tw.setHead(tw.addTree(headTree)); tw.addTree(mergeTree); DirCacheBuildIterator buildIt = workTreeUpdater.createDirCacheBuildIterator(); int dciPos = tw.addTree(buildIt); if (workingTreeIterator != null) { tw.addTree(workingTreeIterator); workingTreeIterator.setDirCacheIterator(tw, dciPos); } else { tw.setFilter(TreeFilter.ANY_DIFF); } if (!mergeTreeWalk(tw, ignoreConflicts)) { return false; } workTreeUpdater.writeWorkTreeChanges(true); if (getUnmergedPaths().isEmpty() && !failed()) { WorkTreeUpdater.Result result = workTreeUpdater.writeIndexChanges(); resultTree = result.getTreeId(); modifiedFiles = result.getModifiedFiles(); for (String f : result.getFailedToDelete()) { failingPaths.put(f, MergeFailureReason.COULD_NOT_DELETE); } return result.getFailedToDelete().isEmpty(); } resultTree = null; return false; } finally { if(modifiedFiles.isEmpty()) { modifiedFiles = workTreeUpdater.getModifiedFiles(); } workTreeUpdater.close(); workTreeUpdater = null; } } /** * Process the given TreeWalk's entries. * * @param treeWalk * The walk to iterate over. * @param ignoreConflicts * see * {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)} * @return Whether the trees merged cleanly. * @throws java.io.IOException * if an IO error occurred * @since 3.5 */ protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts) throws IOException { boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE; boolean hasAttributeNodeProvider = treeWalk .getAttributesNodeProvider() != null; while (treeWalk.next()) { Attributes[] attributes = {NO_ATTRIBUTES, NO_ATTRIBUTES, NO_ATTRIBUTES}; if (hasAttributeNodeProvider) { attributes[T_BASE] = treeWalk.getAttributes(T_BASE); attributes[T_OURS] = treeWalk.getAttributes(T_OURS); attributes[T_THEIRS] = treeWalk.getAttributes(T_THEIRS); } if (!processEntry( treeWalk.getTree(T_BASE, CanonicalTreeParser.class), treeWalk.getTree(T_OURS, CanonicalTreeParser.class), treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class), treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class), hasWorkingTreeIterator ? treeWalk.getTree(T_FILE, WorkingTreeIterator.class) : null, ignoreConflicts, attributes)) { workTreeUpdater.revertModifiedFiles(); return false; } if (treeWalk.isSubtree() && enterSubtree) { treeWalk.enterSubtree(); } } return true; } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 2099 Content-Disposition: inline; filename="SquashMessageFormatter.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "4a73f8ed7ec0443c40e3f176616a28cc3c8b4e82" /* * Copyright (C) 2012, IBM Corporation and others. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.util.List; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.util.GitDateFormatter; import org.eclipse.jgit.util.GitDateFormatter.Format; /** * Formatter for constructing the commit message for a squashed commit. *

* The format should be the same as C Git does it, for compatibility. */ public class SquashMessageFormatter { private GitDateFormatter dateFormatter; /** * Create a new squash message formatter. */ public SquashMessageFormatter() { dateFormatter = new GitDateFormatter(Format.DEFAULT); } /** * Construct the squashed commit message. * * @param squashedCommits * the squashed commits * @param target * the target branch * @return squashed commit message */ public String format(List squashedCommits, Ref target) { StringBuilder sb = new StringBuilder(); sb.append("Squashed commit of the following:\n"); //$NON-NLS-1$ for (RevCommit c : squashedCommits) { sb.append("\ncommit "); //$NON-NLS-1$ sb.append(c.getName()); sb.append("\n"); //$NON-NLS-1$ sb.append(toString(c.getAuthorIdent())); sb.append("\n\t"); //$NON-NLS-1$ sb.append(c.getShortMessage()); sb.append("\n"); //$NON-NLS-1$ } return sb.toString(); } private String toString(PersonIdent author) { final StringBuilder a = new StringBuilder(); a.append("Author: "); //$NON-NLS-1$ a.append(author.getName()); a.append(" <"); //$NON-NLS-1$ a.append(author.getEmailAddress()); a.append(">\n"); //$NON-NLS-1$ a.append("Date: "); //$NON-NLS-1$ a.append(dateFormatter.formatDate(author)); a.append("\n"); //$NON-NLS-1$ return a.toString(); } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 2259 Content-Disposition: inline; filename="StrategyOneSided.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "6064ebe326dd4cbf51063789a424054a48a2fc58" /* * Copyright (C) 2008-2009, Google Inc. * Copyright (C) 2009, Robin Rosenberg and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.io.IOException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.Repository; /** * Trivial merge strategy to make the resulting tree exactly match an input. *

* This strategy can be used to cauterize an entire side branch of history, by * setting the output tree to one of the inputs, and ignoring any of the paths * of the other inputs. */ public class StrategyOneSided extends MergeStrategy { private final String strategyName; private final int treeIndex; /** * Create a new merge strategy to select a specific input tree. * * @param name * name of this strategy. * @param index * the position of the input tree to accept as the result. */ protected StrategyOneSided(String name, int index) { strategyName = name; treeIndex = index; } @Override public String getName() { return strategyName; } @Override public Merger newMerger(Repository db) { return new OneSide(db, treeIndex); } @Override public Merger newMerger(Repository db, boolean inCore) { return new OneSide(db, treeIndex); } @Override public Merger newMerger(ObjectInserter inserter, Config config) { return new OneSide(inserter, treeIndex); } static class OneSide extends Merger { private final int treeIndex; protected OneSide(Repository local, int index) { super(local); treeIndex = index; } protected OneSide(ObjectInserter inserter, int index) { super(inserter); treeIndex = index; } @Override protected boolean mergeImpl() throws IOException { return treeIndex < sourceTrees.length; } @Override public ObjectId getResultTreeId() { return sourceTrees[treeIndex]; } @Override public ObjectId getBaseCommitId() { return null; } } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 1073 Content-Disposition: inline; filename="StrategyRecursive.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "a74bfc03792457b872fb421b7e1cd0053c9c058a" /* * Copyright (C) 2012, Research In Motion Limited and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.Repository; /** * A three-way merge strategy performing a content-merge if necessary * * @since 3.0 */ public class StrategyRecursive extends StrategyResolve { @Override public ThreeWayMerger newMerger(Repository db) { return new RecursiveMerger(db, false); } @Override public ThreeWayMerger newMerger(Repository db, boolean inCore) { return new RecursiveMerger(db, inCore); } @Override public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) { return new RecursiveMerger(inserter, config); } @Override public String getName() { return "recursive"; //$NON-NLS-1$ } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 1136 Content-Disposition: inline; filename="StrategyResolve.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "a686fd0964ab52f71e624b9289869b6fbbc730d5" /* * Copyright (C) 2010, Christian Halstrick , * Copyright (C) 2010, Matthias Sohn and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.Repository; /** * A three-way merge strategy performing a content-merge if necessary */ public class StrategyResolve extends ThreeWayMergeStrategy { @Override public ThreeWayMerger newMerger(Repository db) { return new ResolveMerger(db, false); } @Override public ThreeWayMerger newMerger(Repository db, boolean inCore) { return new ResolveMerger(db, inCore); } @Override public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) { return new ResolveMerger(inserter, config); } @Override public String getName() { return "resolve"; //$NON-NLS-1$ } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 4792 Content-Disposition: inline; filename="StrategySimpleTwoWayInCore.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "c3180abd3531abd50324cee67ab9ba29636234dd" /* * Copyright (C) 2008-2009, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.io.IOException; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.errors.UnmergedPathException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.NameConflictTreeWalk; /** * Merges two commits together in-memory, ignoring any working directory. *

* The strategy chooses a path from one of the two input trees if the path is * unchanged in the other relative to their common merge base tree. This is a * trivial 3-way merge (at the file path level only). *

* Modifications of the same file path (content and/or file mode) by both input * trees will cause a merge conflict, as this strategy does not attempt to merge * file contents. */ public class StrategySimpleTwoWayInCore extends ThreeWayMergeStrategy { /** * Create a new instance of the strategy. */ protected StrategySimpleTwoWayInCore() { // } @Override public String getName() { return "simple-two-way-in-core"; //$NON-NLS-1$ } @Override public ThreeWayMerger newMerger(Repository db) { return new InCoreMerger(db); } @Override public ThreeWayMerger newMerger(Repository db, boolean inCore) { // This class is always inCore, so ignore the parameter return newMerger(db); } @Override public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) { return new InCoreMerger(inserter); } private static class InCoreMerger extends ThreeWayMerger { private static final int T_BASE = 0; private static final int T_OURS = 1; private static final int T_THEIRS = 2; private final NameConflictTreeWalk tw; private final DirCache cache; private DirCacheBuilder builder; private ObjectId resultTree; InCoreMerger(Repository local) { super(local); tw = new NameConflictTreeWalk(local, reader); cache = DirCache.newInCore(); } InCoreMerger(ObjectInserter inserter) { super(inserter); tw = new NameConflictTreeWalk(null, reader); cache = DirCache.newInCore(); } @Override protected boolean mergeImpl() throws IOException { tw.addTree(mergeBase()); tw.addTree(sourceTrees[0]); tw.addTree(sourceTrees[1]); boolean hasConflict = false; builder = cache.builder(); while (tw.next()) { final int modeO = tw.getRawMode(T_OURS); final int modeT = tw.getRawMode(T_THEIRS); if (modeO == modeT && tw.idEqual(T_OURS, T_THEIRS)) { add(T_OURS, DirCacheEntry.STAGE_0); continue; } final int modeB = tw.getRawMode(T_BASE); if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) add(T_THEIRS, DirCacheEntry.STAGE_0); else if (modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) add(T_OURS, DirCacheEntry.STAGE_0); else { if (nonTree(modeB)) { add(T_BASE, DirCacheEntry.STAGE_1); hasConflict = true; } if (nonTree(modeO)) { add(T_OURS, DirCacheEntry.STAGE_2); hasConflict = true; } if (nonTree(modeT)) { add(T_THEIRS, DirCacheEntry.STAGE_3); hasConflict = true; } if (tw.isSubtree()) tw.enterSubtree(); } } builder.finish(); builder = null; if (hasConflict) return false; try { ObjectInserter odi = getObjectInserter(); resultTree = cache.writeTree(odi); odi.flush(); return true; } catch (UnmergedPathException upe) { resultTree = null; return false; } } private static boolean nonTree(int mode) { return mode != 0 && !FileMode.TREE.equals(mode); } private void add(int tree, int stage) throws IOException { final AbstractTreeIterator i = getTree(tree); if (i != null) { if (FileMode.TREE.equals(tw.getRawMode(tree))) { builder.addTree(tw.getRawPath(), stage, reader, tw .getObjectId(tree)); } else { final DirCacheEntry e; e = new DirCacheEntry(tw.getRawPath(), stage); e.setObjectIdFromRaw(i.idBuffer(), i.idOffset()); e.setFileMode(tw.getFileMode(tree)); builder.add(e); } } } private AbstractTreeIterator getTree(int tree) { return tw.getTree(tree, AbstractTreeIterator.class); } @Override public ObjectId getResultTreeId() { return resultTree; } } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 685 Content-Disposition: inline; filename="ThreeWayMergeStrategy.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "8cefa6566e9290606b4325c22f0a3bc3b39f78e1" /* * Copyright (C) 2009, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import org.eclipse.jgit.lib.Repository; /** * A merge strategy to merge 2 trees, using a common base ancestor tree. */ public abstract class ThreeWayMergeStrategy extends MergeStrategy { @Override public abstract ThreeWayMerger newMerger(Repository db); @Override public abstract ThreeWayMerger newMerger(Repository db, boolean inCore); } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 3506 Content-Disposition: inline; filename="ThreeWayMerger.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "68a1b5e50948c07463de3bbbd3c415ed35916333" /* * Copyright (C) 2009, Google Inc. * Copyright (C) 2012, Research In Motion Limited and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.merge; import java.io.IOException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.EmptyTreeIterator; /** * A merge of 2 trees, using a common base ancestor tree. */ public abstract class ThreeWayMerger extends Merger { private RevTree baseTree; private ObjectId baseCommitId; /** * Create a new merge instance for a repository. * * @param local * the repository this merger will read and write data on. */ protected ThreeWayMerger(Repository local) { super(local); } /** * Create a new merge instance for a repository. * * @param local * the repository this merger will read and write data on. * @param inCore * perform the merge in core with no working folder involved */ protected ThreeWayMerger(Repository local, boolean inCore) { this(local); } /** * Create a new in-core merge instance from an inserter. * * @param inserter * the inserter to write objects to. * @since 4.8 */ protected ThreeWayMerger(ObjectInserter inserter) { super(inserter); } /** * Set the common ancestor tree. * * @param id * common base treeish; null to automatically compute the common * base from the input commits during * {@link #merge(AnyObjectId...)}. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException * the object is not a treeish. * @throws org.eclipse.jgit.errors.MissingObjectException * the object does not exist. * @throws java.io.IOException * the object could not be read. */ public void setBase(AnyObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException { if (id != null) { baseTree = walk.parseTree(id); } else { baseTree = null; } } @Override public boolean merge(AnyObjectId... tips) throws IOException { if (tips.length != 2) return false; return super.merge(tips); } @Override public ObjectId getBaseCommitId() { return baseCommitId; } /** * Create an iterator to walk the merge base. * * @return an iterator over the caller-specified merge base, or the natural * merge base of the two input commits. * @throws java.io.IOException * if an IO error occurred */ protected AbstractTreeIterator mergeBase() throws IOException { if (baseTree != null) { return openTree(baseTree); } RevCommit baseCommit = (baseCommitId != null) ? walk .parseCommit(baseCommitId) : getBaseCommit(sourceCommits[0], sourceCommits[1]); if (baseCommit == null) { baseCommitId = null; return new EmptyTreeIterator(); } baseCommitId = baseCommit.toObjectId(); return openTree(baseCommit.getTree()); } } X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 88 Content-Disposition: inline; filename="package-info.java" Last-Modified: Sun, 06 Jul 2025 10:01:54 GMT Expires: Sun, 06 Jul 2025 10:06:54 GMT ETag: "d61cd6a5cdd179de6cb5a5650d4b5d6c769f71e4" /** * Content and commit history merge algorithms. */ package org.eclipse.jgit.merge;