Browse Source

Basic submodule merge handling

This doesn't handle the really hard thing, which is merging spurious
conflicts inside .gitmodules files.  That's OK: git.git doesn't
either.  Users can resolve the conflict themselves and then commit
the merge.

Previously, jgit would crash when attempting to merge conflicting
submodule changes.  Even if there was no conflict, after a merge which
adds submodules, the repository would have been missing empty
directories for newly-added submodules.

This patch fixes the crash, and adds the empty directories where
necessary. It ensures that the index is in a conflicted state when
submodule changes conflict.

Reported-by: Alexey Korobkov
Bug: 494551
Change-Id: I79db6798c2bdcc1159b5b2589b02da198dc906a1
Signed-off-by: David Turner <dturner@twosigma.com>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
stable-4.11
David Turner 7 years ago committed by Matthias Sohn
parent
commit
be2a8ed63b
  1. 4
      org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java
  2. 151
      org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java
  3. 12
      org.eclipse.jgit/src/org/eclipse/jgit/dircache/DirCacheCheckout.java
  4. 43
      org.eclipse.jgit/src/org/eclipse/jgit/merge/ResolveMerger.java
  5. 77
      org.eclipse.jgit/src/org/eclipse/jgit/submodule/SubmoduleConflict.java
  6. 9
      org.eclipse.jgit/src/org/eclipse/jgit/treewalk/NameConflictTreeWalk.java
  7. 14
      org.eclipse.jgit/src/org/eclipse/jgit/treewalk/WorkingTreeIterator.java

4
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java

@ -1250,9 +1250,9 @@ public class AddCommandTest extends RepositoryTestCase {
try (Git git = new Git(db)) {
git.add().addFilepattern("nested-repo").call();
// with gitlinks ignored, we treat this as a normal directory
assertEquals(
"[nested-repo, mode:160000]",
"[nested-repo/README1.md, mode:100644][nested-repo/README2.md, mode:100644]",
indexState(0));
}
}

151
org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java

@ -46,6 +46,8 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
@ -53,6 +55,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeResult;
@ -61,21 +64,29 @@ import org.eclipse.jgit.api.errors.CheckoutConflictException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.NoMergeBaseException;
import org.eclipse.jgit.errors.NoMergeBaseException.MergeBaseFailureReason;
import org.eclipse.jgit.junit.RepositoryTestCase;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
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.ObjectStream;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.merge.ResolveMerger.MergeFailureReason;
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.storage.file.FileBasedConfig;
import org.eclipse.jgit.treewalk.FileTreeIterator;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FileUtils;
@ -1130,6 +1141,146 @@ public class ResolveMergerTest extends RepositoryTestCase {
indexState(CONTENT));
}
/**
* Merging two conflicting submodules when the index does not contain any
* entry for that submodule.
*
* @param strategy
* @throws Exception
*/
@Theory
public void checkMergeConflictingSubmodulesWithoutIndex(
MergeStrategy strategy) throws Exception {
Git git = Git.wrap(db);
writeTrashFile("initial", "initial");
git.add().addFilepattern("initial").call();
RevCommit initial = git.commit().setMessage("initial").call();
writeSubmodule("one", ObjectId
.fromString("1000000000000000000000000000000000000000"));
git.add().addFilepattern(Constants.DOT_GIT_MODULES).call();
RevCommit right = git.commit().setMessage("added one").call();
// a second commit in the submodule
git.checkout().setStartPoint(initial).setName("left")
.setCreateBranch(true).call();
writeSubmodule("one", ObjectId
.fromString("2000000000000000000000000000000000000000"));
git.add().addFilepattern(Constants.DOT_GIT_MODULES).call();
git.commit().setMessage("a different one").call();
MergeResult result = git.merge().setStrategy(strategy).include(right)
.call();
assertEquals(MergeStatus.CONFLICTING, result.getMergeStatus());
Map<String, int[][]> conflicts = result.getConflicts();
assertEquals(1, conflicts.size());
assertNotNull(conflicts.get("one"));
}
/**
* Merging two non-conflicting submodules when the index does not contain
* any entry for either submodule.
*
* @param strategy
* @throws Exception
*/
@Theory
public void checkMergeNonConflictingSubmodulesWithoutIndex(
MergeStrategy strategy) throws Exception {
Git git = Git.wrap(db);
writeTrashFile("initial", "initial");
git.add().addFilepattern("initial").call();
writeSubmodule("one", ObjectId
.fromString("1000000000000000000000000000000000000000"));
// Our initial commit should include a .gitmodules with a bunch of
// comment lines, so that
// we don't have a content merge issue when we add a new submodule at
// the top and a different
// one at the bottom. This is sort of a hack, but it should allow
// add/add submodule merges
String existing = read(Constants.DOT_GIT_MODULES);
String context = "\n# context\n# more context\n# yet more context\n";
write(new File(db.getWorkTree(), Constants.DOT_GIT_MODULES),
existing + context + context + context);
git.add().addFilepattern(Constants.DOT_GIT_MODULES).call();
RevCommit initial = git.commit().setMessage("initial").call();
writeSubmodule("two", ObjectId
.fromString("1000000000000000000000000000000000000000"));
git.add().addFilepattern(Constants.DOT_GIT_MODULES).call();
RevCommit right = git.commit().setMessage("added two").call();
git.checkout().setStartPoint(initial).setName("left")
.setCreateBranch(true).call();
// we need to manually create the submodule for three for the
// .gitmodules hackery
addSubmoduleToIndex("three", ObjectId
.fromString("1000000000000000000000000000000000000000"));
new File(db.getWorkTree(), "three").mkdir();
existing = read(Constants.DOT_GIT_MODULES);
String three = "[submodule \"three\"]\n\tpath = three\n\turl = "
+ db.getDirectory().toURI() + "\n";
write(new File(db.getWorkTree(), Constants.DOT_GIT_MODULES),
three + existing);
git.add().addFilepattern(Constants.DOT_GIT_MODULES).call();
git.commit().setMessage("a different one").call();
MergeResult result = git.merge().setStrategy(strategy).include(right)
.call();
assertNull(result.getCheckoutConflicts());
assertNull(result.getFailingPaths());
for (String dir : Arrays.asList("one", "two", "three")) {
assertTrue(new File(db.getWorkTree(), dir).isDirectory());
}
}
private void writeSubmodule(String path, ObjectId commit)
throws IOException, ConfigInvalidException {
addSubmoduleToIndex(path, commit);
new File(db.getWorkTree(), path).mkdir();
StoredConfig config = db.getConfig();
config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
ConfigConstants.CONFIG_KEY_URL,
db.getDirectory().toURI().toString());
config.save();
FileBasedConfig modulesConfig = new FileBasedConfig(
new File(db.getWorkTree(), Constants.DOT_GIT_MODULES),
db.getFS());
modulesConfig.load();
modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
ConfigConstants.CONFIG_KEY_PATH, path);
modulesConfig.save();
}
private void addSubmoduleToIndex(String path, ObjectId commit)
throws IOException {
DirCache cache = db.lockDirCache();
DirCacheEditor editor = cache.editor();
editor.add(new DirCacheEditor.PathEdit(path) {
@Override
public void apply(DirCacheEntry ent) {
ent.setFileMode(FileMode.GITLINK);
ent.setObjectId(commit);
}
});
editor.commit();
}
// Assert that every specified index entry has the same last modification
// timestamp as the associated file
private void checkConsistentLastModified(String... pathes)

12
org.eclipse.jgit/src/org/eclipse/jgit/dircache/DirCacheCheckout.java vendored

@ -570,7 +570,9 @@ public class DirCacheCheckout {
String path = e.getKey();
CheckoutMetadata meta = e.getValue();
DirCacheEntry entry = dc.getEntry(path);
if (!FileMode.GITLINK.equals(entry.getRawMode())) {
if (FileMode.GITLINK.equals(entry.getRawMode())) {
checkoutGitlink(path, entry);
} else {
checkoutEntry(repo, entry, objectReader, false, meta);
}
e = null;
@ -603,6 +605,14 @@ public class DirCacheCheckout {
return toBeDeleted.size() == 0;
}
private void checkoutGitlink(String path, DirCacheEntry entry)
throws IOException {
File gitlinkDir = new File(repo.getWorkTree(), path);
FileUtils.mkdirs(gitlinkDir, true);
FS fs = repo.getFS();
entry.setLastModified(fs.lastModified(gitlinkDir));
}
private static ArrayList<String> filterOut(ArrayList<String> strings,
IntList indicesToRemove) {
int n = indicesToRemove.size();

43
org.eclipse.jgit/src/org/eclipse/jgit/merge/ResolveMerger.java

@ -96,6 +96,7 @@ 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;
@ -393,8 +394,13 @@ public class ResolveMerger extends ThreeWayMerger {
}
for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
.entrySet()) {
DirCacheCheckout.checkoutEntry(db, entry.getValue(), reader);
modifiedFiles.add(entry.getKey());
DirCacheEntry cacheEntry = entry.getValue();
if (cacheEntry.getFileMode() == FileMode.GITLINK) {
new File(nonNullRepo().getWorkTree(), entry.getKey()).mkdirs();
} else {
DirCacheCheckout.checkoutEntry(db, cacheEntry, reader);
modifiedFiles.add(entry.getKey());
}
}
}
@ -725,19 +731,44 @@ public class ResolveMerger extends ThreeWayMerger {
if (nonTree(modeO) && nonTree(modeT)) {
// Check worktree before modifying files
if (isWorktreeDirty(work, ourDce))
boolean worktreeDirty = isWorktreeDirty(work, ourDce);
if (!attributes.canBeContentMerged() && worktreeDirty) {
return false;
}
boolean gitlinkConflict = isGitLink(modeO) || isGitLink(modeT);
// Don't attempt to resolve submodule link conflicts
if (isGitLink(modeO) || isGitLink(modeT)
|| !attributes.canBeContentMerged()) {
if (gitlinkConflict || !attributes.canBeContentMerged()) {
add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
unmergedPaths.add(tw.getPathString());
if (gitlinkConflict) {
MergeResult<SubmoduleConflict> result = 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())));
result.setContainsConflicts(true);
mergeResults.put(tw.getPathString(), result);
if (!ignoreConflicts) {
unmergedPaths.add(tw.getPathString());
}
} else {
// attribute merge issues are conflicts but not failures
unmergedPaths.add(tw.getPathString());
}
return true;
}
// Check worktree before modifying files
if (worktreeDirty) {
return false;
}
MergeResult<RawText> result = contentMerge(base, ours, theirs);
if (ignoreConflicts) {
result.setContainsConflicts(false);

77
org.eclipse.jgit/src/org/eclipse/jgit/submodule/SubmoduleConflict.java

@ -0,0 +1,77 @@
/*
* Copyright (C) 2017, Two Sigma Open Source
* and other copyright owners as documented in the project's IP log.
*
* 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.submodule;
import org.eclipse.jgit.diff.Sequence;
import org.eclipse.jgit.lib.ObjectId;
/**
* Merges expect that conflicts will consist of Sequences, but that doesn't
* really make sense for submodules. So this represents a submodule conflict.
*
* @since 4.11
*/
public class SubmoduleConflict extends Sequence {
private final ObjectId objectId;
/**
* Create a SubmoduleConflict for the given submodule object id
* @param objectId
*/
public SubmoduleConflict(ObjectId objectId) {
super();
this.objectId = objectId;
}
@Override
public int size() {
return 1;
}
/**
* @return the object id for the conflicting submodule
*/
public ObjectId getObjectId() {
return objectId;
}
}

9
org.eclipse.jgit/src/org/eclipse/jgit/treewalk/NameConflictTreeWalk.java

@ -187,7 +187,7 @@ public class NameConflictTreeWalk extends TreeWalk {
//
t.matches = minRef;
} else if (fastMinHasMatch && isTree(t) && !isTree(minRef)
&& nameEqual(t, minRef)) {
&& !isGitlink(minRef) && nameEqual(t, minRef)) {
// The minimum is a file (non-tree) but the next entry
// of this iterator is a tree whose name matches our file.
// This is a classic D/F conflict and commonly occurs like
@ -218,6 +218,10 @@ public class NameConflictTreeWalk extends TreeWalk {
return a.pathCompare(b, TREE_MODE) == 0;
}
private boolean isGitlink(AbstractTreeIterator p) {
return FileMode.GITLINK.equals(p.mode);
}
private static boolean isTree(final AbstractTreeIterator p) {
return FileMode.TREE.equals(p.mode);
}
@ -306,8 +310,9 @@ public class NameConflictTreeWalk extends TreeWalk {
if (t.matches == minRef)
t.matches = treeMatch;
if (dfConflict == null)
if (dfConflict == null && !isGitlink(minRef)) {
dfConflict = treeMatch;
}
return treeMatch;
}

14
org.eclipse.jgit/src/org/eclipse/jgit/treewalk/WorkingTreeIterator.java

@ -952,7 +952,19 @@ public abstract class WorkingTreeIterator extends AbstractTreeIterator {
}
return false;
case DIFFER_BY_METADATA:
if (mode == FileMode.SYMLINK.getBits())
if (mode == FileMode.TREE.getBits()
&& entry.getFileMode().equals(FileMode.GITLINK)) {
byte[] idBuffer = idBuffer();
int idOffset = idOffset();
if (entry.getObjectId().compareTo(idBuffer, idOffset) == 0) {
return true;
} else if (ObjectId.zeroId().compareTo(idBuffer,
idOffset) == 0) {
return new File(repository.getWorkTree(),
entry.getPathString()).list().length > 0;
}
return false;
} else if (mode == FileMode.SYMLINK.getBits())
return contentCheck(entry, reader);
return true;
default:

Loading…
Cancel
Save