Skip to content

The Unified and Autonomous Development Platform

Update to jgit 5.13.0

Shen YuJiang2c0148003bae
diff --git a/pom.xml b/pom.xml
index df5391b4a3..2784206930 100644
--- a/pom.xml
+++ b/pom.xml
@@ -499,6 +499,11 @@
<artifactId>org.eclipse.jgit.http.server</artifactId>
<version>${jgit.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.eclipse.jgit</groupId>
+ <artifactId>org.eclipse.jgit.gpg.bc</artifactId>
+ <version>${jgit.version}</version>
+ </dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.archive</artifactId>
@@ -585,7 +590,7 @@
<wicketbootstrap.version>0.10.18</wicketbootstrap.version>
<lucene.version>7.1.0</lucene.version>
<shiro.version>1.7.1</shiro.version>
- <jgit.version>5.7.0.202003110725-r</jgit.version>
+ <jgit.version>5.13.0.202109080827-r</jgit.version>
<flexmark.version>0.62.2</flexmark.version>
<groovy.version>3.0.7</groovy.version>
<servlet.version>3.1.0</servlet.version>
diff --git a/server-core/pom.xml b/server-core/pom.xml
index 55db3d3a6c..b87402a326 100644
--- a/server-core/pom.xml
+++ b/server-core/pom.xml
@@ -188,6 +188,10 @@
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.http.server</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.eclipse.jgit</groupId>
+ <artifactId>org.eclipse.jgit.gpg.bc</artifactId>
+ </dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.archive</artifactId>
diff --git a/server-core/src/main/java/io/onedev/server/git/GitUtils.java b/server-core/src/main/java/io/onedev/server/git/GitUtils.java
index e144cae264..8c6a649847 100644
--- a/server-core/src/main/java/io/onedev/server/git/GitUtils.java
+++ b/server-core/src/main/java/io/onedev/server/git/GitUtils.java
@@ -58,54 +58,53 @@ import io.onedev.server.git.exception.ObsoleteCommitException;
import io.onedev.server.git.exception.RefUpdateException;
public class GitUtils {
-
- public static final int SHORT_SHA_LENGTH = 8;
-
- public static boolean isEmptyPath(String path) {
- return Strings.isNullOrEmpty(path) || Objects.equal(path, DiffEntry.DEV_NULL);
- }
-
- public static String abbreviateSHA(String sha, int length) {
- Preconditions.checkArgument(ObjectId.isId(sha));
- return sha.substring(0, length);
- }
+
+ public static final int SHORT_SHA_LENGTH = 8;
+
+ public static boolean isEmptyPath(String path) {
+ return Strings.isNullOrEmpty(path) || Objects.equal(path, DiffEntry.DEV_NULL);
+ }
+
+ public static String abbreviateSHA(String sha, int length) {
+ Preconditions.checkArgument(ObjectId.isId(sha));
+ return sha.substring(0, length);
+ }
public static String abbreviateSHA(String sha) {
return abbreviateSHA(sha, SHORT_SHA_LENGTH);
}
-
+
public static List<DiffEntry> diff(Repository repository, AnyObjectId oldRevId, AnyObjectId newRevId) {
List<DiffEntry> diffs = new ArrayList<>();
- try ( DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);
+ try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);
RevWalk revWalk = new RevWalk(repository);
ObjectReader reader = repository.newObjectReader();) {
- diffFormatter.setRepository(repository);
- diffFormatter.setDetectRenames(true);
- diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
-
- CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
- if (!oldRevId.equals(ObjectId.zeroId()))
- oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree());
-
- CanonicalTreeParser newTreeParser = new CanonicalTreeParser();
- if (!newRevId.equals(ObjectId.zeroId()))
- newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree());
-
- for (DiffEntry entry: diffFormatter.scan(oldTreeParser, newTreeParser)) {
- if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
- || !Objects.equal(entry.getOldMode(), entry.getNewMode())
- || entry.getOldId()==null || !entry.getOldId().isComplete()
- || entry.getNewId()== null || !entry.getNewId().isComplete()
- || !entry.getOldId().equals(entry.getNewId())) {
- diffs.add(entry);
- }
- }
+ diffFormatter.setRepository(repository);
+ diffFormatter.setDetectRenames(true);
+ diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
+
+ CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
+ if (!oldRevId.equals(ObjectId.zeroId()))
+ oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree());
+
+ CanonicalTreeParser newTreeParser = new CanonicalTreeParser();
+ if (!newRevId.equals(ObjectId.zeroId()))
+ newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree());
+
+ for (DiffEntry entry : diffFormatter.scan(oldTreeParser, newTreeParser)) {
+ if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
+ || !Objects.equal(entry.getOldMode(), entry.getNewMode()) || entry.getOldId() == null
+ || !entry.getOldId().isComplete() || entry.getNewId() == null || !entry.getNewId().isComplete()
+ || !entry.getOldId().equals(entry.getNewId())) {
+ diffs.add(entry);
+ }
+ }
} catch (IOException e) {
throw new RuntimeException(e);
- }
+ }
return diffs;
}
-
+
@Nullable
public static String getDetailMessage(RevCommit commit) {
int start = 0;
@@ -114,14 +113,14 @@ public class GitUtils {
int index = fullMessage.indexOf('\n', start);
if (index == -1)
return null;
- start = index+1;
+ start = index + 1;
int nextIndex = fullMessage.indexOf('\n', start);
if (nextIndex == -1)
return null;
- start = nextIndex+1;
+ start = nextIndex + 1;
if (fullMessage.substring(index, nextIndex).trim().length() == 0) {
String detailMessage = fullMessage.substring(start).trim();
- return detailMessage.length()!=0?detailMessage:null;
+ return detailMessage.length() != 0 ? detailMessage : null;
}
}
}
@@ -133,19 +132,17 @@ public class GitUtils {
return "Sub module";
else if (blobType == FileMode.TYPE_SYMLINK)
return "Symbol link";
- else
+ else
return "Folder";
}
public static PersonIdent newPersonIdent(String name, String email, Date when) {
- return new PersonIdent(name, email, when.getTime(),
- SystemReader.getInstance().getTimezone(when.getTime()));
+ return new PersonIdent(name, email, when.getTime(), SystemReader.getInstance().getTimezone(when.getTime()));
}
-
+
/**
- * Parse the original git raw date to Java date. The raw git date is in
- * unix timestamp with timezone like:
- * 1392312299 -0800
+ * Parse the original git raw date to Java date. The raw git date is in unix
+ * timestamp with timezone like: 1392312299 -0800
*
* @param input the input raw date string
* @return Java date
@@ -157,7 +154,7 @@ public class GitUtils {
/**
* Parse the raw user information into PersonIdent object, the raw information
- * should be in format <code>[name] [<email>] [epoch timezone]</code>, for
+ * should be in format <code>[name] [<email>] [epoch timezone]</code>, for
* example:
*
* Jacob Thornton <[email protected]> 1328060294 -0800
@@ -168,32 +165,32 @@ public class GitUtils {
public static @Nullable PersonIdent parsePersonIdent(String raw) {
if (Strings.isNullOrEmpty(raw))
return null;
-
+
int pos1 = raw.indexOf('<');
if (pos1 <= 0)
throw new IllegalArgumentException("Raw " + raw);
-
+
String name = raw.substring(0, pos1 - 1);
-
+
int pos2 = raw.indexOf('>');
if (pos2 <= 0)
throw new IllegalArgumentException("Raw " + raw);
-
+
String time = raw.substring(pos2 + 1).trim();
Date when = parseRawDate(time);
-
+
String email = raw.substring(pos1 + 1, pos2 - 1);
-
+
return newPersonIdent(name, email, when);
}
-
+
public static int comparePath(@Nullable String path1, @Nullable String path2) {
List<String> segments1 = splitPath(path1);
List<String> segments2 = splitPath(path2);
-
+
int index = 0;
- for (String segment1: segments1) {
- if (index<segments2.size()) {
+ for (String segment1 : segments1) {
+ if (index < segments2.size()) {
int result = segment1.compareTo(segments2.get(index));
if (result != 0)
return result;
@@ -202,7 +199,7 @@ public class GitUtils {
}
index++;
}
- if (index<segments2.size())
+ if (index < segments2.size())
return -1;
else
return 0;
@@ -219,145 +216,137 @@ public class GitUtils {
public static @Nullable String normalizePath(@Nullable String path) {
List<String> pathSegments = splitPath(PathUtils.normalizeDots(path));
- if (!pathSegments.isEmpty())
+ if (!pathSegments.isEmpty())
return Joiner.on("/").join(pathSegments);
- else
+ else
return null;
}
/**
- * Convert a git reference name to branch name.
- *
- * @param refName
- * name of the git reference
- * @return
- * name of the branch, or <tt>null</tt> if specified ref
- * does not represent a branch
- */
- public static @Nullable String ref2branch(String refName) {
- if (refName.startsWith(Constants.R_HEADS))
+ * Convert a git reference name to branch name.
+ *
+ * @param refName name of the git reference
+ * @return name of the branch, or <tt>null</tt> if specified ref does not
+ * represent a branch
+ */
+ public static @Nullable String ref2branch(String refName) {
+ if (refName.startsWith(Constants.R_HEADS))
return refName.substring(Constants.R_HEADS.length());
else
return null;
- }
-
- public static String branch2ref(String branch) {
- return Constants.R_HEADS + branch;
- }
+ }
+
+ public static String branch2ref(String branch) {
+ return Constants.R_HEADS + branch;
+ }
/**
- * Convert a git reference name to tag name.
- *
- * @param refName
- * name of the git reference
- * @return
- * name of the tag, or <tt>null</tt> if specified ref
- * does not represent a tag
- */
- public static @Nullable String ref2tag(String refName) {
- if (refName.startsWith(Constants.R_TAGS))
+ * Convert a git reference name to tag name.
+ *
+ * @param refName name of the git reference
+ * @return name of the tag, or <tt>null</tt> if specified ref does not represent
+ * a tag
+ */
+ public static @Nullable String ref2tag(String refName) {
+ if (refName.startsWith(Constants.R_TAGS))
return refName.substring(Constants.R_TAGS.length());
else
return null;
- }
-
- public static String tag2ref(String tag) {
- return Constants.R_TAGS + tag;
- }
-
- public static BlobIdent getOldBlobIdent(DiffEntry diffEntry, String oldRev) {
- BlobIdent blobIdent;
+ }
+
+ public static String tag2ref(String tag) {
+ return Constants.R_TAGS + tag;
+ }
+
+ public static BlobIdent getOldBlobIdent(DiffEntry diffEntry, String oldRev) {
+ BlobIdent blobIdent;
if (diffEntry.getChangeType() != ChangeType.ADD) {
blobIdent = new BlobIdent(oldRev, diffEntry.getOldPath(), diffEntry.getOldMode().getBits());
} else {
blobIdent = new BlobIdent(oldRev, null, null);
}
return blobIdent;
- }
-
- public static BlobIdent getNewBlobIdent(DiffEntry diffEntry, String newRev) {
- BlobIdent blobIdent;
+ }
+
+ public static BlobIdent getNewBlobIdent(DiffEntry diffEntry, String newRev) {
+ BlobIdent blobIdent;
if (diffEntry.getChangeType() != ChangeType.DELETE) {
blobIdent = new BlobIdent(newRev, diffEntry.getNewPath(), diffEntry.getNewMode().getBits());
} else {
blobIdent = new BlobIdent(newRev, null, null);
}
return blobIdent;
- }
-
- /**
- * @return
- * merge base of specified commits, or <tt>null</tt> if two commits do not have related history. In this
- * case, these two commits can not be merged
- */
- @Nullable
- public static ObjectId getMergeBase(Repository repository, ObjectId commitId1, ObjectId commitId2) {
+ }
+
+ /**
+ * @return merge base of specified commits, or <tt>null</tt> if two commits do
+ * not have related history. In this case, these two commits can not be
+ * merged
+ */
+ @Nullable
+ public static ObjectId getMergeBase(Repository repository, ObjectId commitId1, ObjectId commitId2) {
try (RevWalk revWalk = new RevWalk(repository)) {
revWalk.setRevFilter(RevFilter.MERGE_BASE);
-
+
revWalk.markStart(revWalk.parseCommit(commitId1));
revWalk.markStart(revWalk.parseCommit(commitId2));
RevCommit mergeBase = revWalk.next();
- return mergeBase!=null?mergeBase.copy():null;
+ return mergeBase != null ? mergeBase.copy() : null;
} catch (IOException e) {
throw new RuntimeException(e);
- }
- }
-
- /**
- * @return
- * merge base of specified commits, or <tt>null</tt> if two commits do not have related history. In this
- * case, these two commits can not be merged
- */
- @Nullable
- public static ObjectId getMergeBase(Repository repository1, ObjectId commit1,
- Repository repository2, ObjectId commit2) {
- if (repository1.getDirectory() == null
- || !repository1.getDirectory().equals(repository2.getDirectory())) {
+ }
+ }
+
+ /**
+ * @return merge base of specified commits, or <tt>null</tt> if two commits do
+ * not have related history. In this case, these two commits can not be
+ * merged
+ */
+ @Nullable
+ public static ObjectId getMergeBase(Repository repository1, ObjectId commit1, Repository repository2,
+ ObjectId commit2) {
+ if (repository1.getDirectory() == null || !repository1.getDirectory().equals(repository2.getDirectory())) {
fetch(repository2, commit2, repository1);
}
return GitUtils.getMergeBase(repository1, commit1, commit2);
}
-
+
public static void fetch(Repository fromRepository, ObjectId fromCommit, Repository toRepository) {
- new FetchCommand(toRepository.getDirectory(), null)
- .from(fromRepository.getDirectory().getAbsolutePath())
- .refspec(fromCommit.name())
- .call();
- }
-
- public static boolean isMergedInto(Repository repository, @Nullable Map<String, String> gitEnvs,
- ObjectId base, ObjectId tip) {
- if (gitEnvs != null && !gitEnvs.isEmpty()) {
- IsAncestorCommand cmd = new IsAncestorCommand(repository.getDirectory(), gitEnvs);
- cmd.ancestor(base.name()).descendant(tip.name());
- return cmd.call();
- } else {
- try (RevWalk revWalk = new RevWalk(repository)) {
- RevCommit baseCommit;
- try {
- baseCommit = revWalk.parseCommit(base);
- } catch (MissingObjectException e) {
- return false;
- }
- return revWalk.isMergedInto(baseCommit, revWalk.parseCommit(tip));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- /**
- * Get commit of specified revision id.
- *
- * @param revWalk
- * @param revId
- * @return
- * <tt>null</tt> if specified id does not exist or does not
- * represent a commit
- */
- @Nullable
- public static RevCommit parseCommit(RevWalk revWalk, ObjectId revId) {
+ new FetchCommand(toRepository.getDirectory(), null).from(fromRepository.getDirectory().getAbsolutePath())
+ .refspec(fromCommit.name()).call();
+ }
+
+ public static boolean isMergedInto(Repository repository, @Nullable Map<String, String> gitEnvs, ObjectId base,
+ ObjectId tip) {
+ if (gitEnvs != null && !gitEnvs.isEmpty()) {
+ IsAncestorCommand cmd = new IsAncestorCommand(repository.getDirectory(), gitEnvs);
+ cmd.ancestor(base.name()).descendant(tip.name());
+ return cmd.call();
+ } else {
+ try (RevWalk revWalk = new RevWalk(repository)) {
+ RevCommit baseCommit;
+ try {
+ baseCommit = revWalk.parseCommit(base);
+ } catch (MissingObjectException e) {
+ return false;
+ }
+ return revWalk.isMergedInto(baseCommit, revWalk.parseCommit(tip));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ /**
+ * Get commit of specified revision id.
+ *
+ * @param revWalk
+ * @param revId
+ * @return <tt>null</tt> if specified id does not exist or does not represent a
+ * commit
+ */
+ @Nullable
+ public static RevCommit parseCommit(RevWalk revWalk, ObjectId revId) {
RevObject peeled;
try {
peeled = revWalk.peel(revWalk.parseAny(revId));
@@ -370,10 +359,10 @@ public class GitUtils {
} catch (IOException e) {
throw new RuntimeException(e);
}
- }
+ }
- @Nullable
- public static ObjectId resolve(Repository repository, String revision) {
+ @Nullable
+ public static ObjectId resolve(Repository repository, String revision) {
try {
return repository.resolve(revision);
} catch (RevisionSyntaxException | AmbiguousObjectException | IncorrectObjectTypeException e) {
@@ -381,85 +370,83 @@ public class GitUtils {
} catch (IOException e) {
throw new RuntimeException(e);
}
- }
-
- @Nullable
- public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
- try ( RevWalk revWalk = new RevWalk(repository);
- ObjectInserter inserter = repository.newObjectInserter();) {
- RevCommit sourceCommit = revWalk.parseCommit(source);
- RevCommit targetCommit = revWalk.parseCommit(target);
- revWalk.setRevFilter(RevFilter.NO_MERGES);
- List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
- Collections.reverse(commits);
- RevCommit headCommit = targetCommit;
- for (RevCommit commit: commits) {
- ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
- merger.setBase(commit.getParent(0));
- if (merger.merge(headCommit, commit)) {
+ }
+
+ @Nullable
+ public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
+ try (RevWalk revWalk = new RevWalk(repository); ObjectInserter inserter = repository.newObjectInserter();) {
+ RevCommit sourceCommit = revWalk.parseCommit(source);
+ RevCommit targetCommit = revWalk.parseCommit(target);
+ revWalk.setRevFilter(RevFilter.NO_MERGES);
+ List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
+ Collections.reverse(commits);
+ RevCommit headCommit = targetCommit;
+ for (RevCommit commit : commits) {
+ ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
+ merger.setBase(commit.getParent(0));
+ if (merger.merge(headCommit, commit)) {
if (!headCommit.getTree().getId().equals(merger.getResultTreeId())) {
- if (!commit.getTree().getId().equals(merger.getResultTreeId())
+ if (!commit.getTree().getId().equals(merger.getResultTreeId())
|| !commit.getParent(0).equals(headCommit)) {
- CommitBuilder commitBuilder = new CommitBuilder();
- commitBuilder.setAuthor(commit.getAuthorIdent());
- commitBuilder.setCommitter(committer);
- commitBuilder.setParentId(headCommit);
- commitBuilder.setMessage(commit.getFullMessage());
- commitBuilder.setTreeId(merger.getResultTreeId());
- headCommit = revWalk.parseCommit(inserter.insert(commitBuilder));
+ CommitBuilder commitBuilder = new CommitBuilder();
+ commitBuilder.setAuthor(commit.getAuthorIdent());
+ commitBuilder.setCommitter(committer);
+ commitBuilder.setParentId(headCommit);
+ commitBuilder.setMessage(commit.getFullMessage());
+ commitBuilder.setTreeId(merger.getResultTreeId());
+ headCommit = revWalk.parseCommit(inserter.insert(commitBuilder));
} else {
headCommit = commit;
}
}
- } else {
- return null;
- }
- }
- inserter.flush();
- return headCommit.copy();
- } catch (IOException e) {
- throw new RuntimeException(e);
+ } else {
+ return null;
+ }
+ }
+ inserter.flush();
+ return headCommit.copy();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
}
- }
-
- @Nullable
- public static ObjectId merge(Repository repository, ObjectId targetCommitId, ObjectId sourceCommitId,
- boolean squash, PersonIdent committer, PersonIdent author, String commitMessage,
- boolean useOursOnConflict) {
- boolean prevUseOursOnConflict = UseOursOnConflict.get();
- UseOursOnConflict.set(useOursOnConflict);
- try ( RevWalk revWalk = new RevWalk(repository);
- ObjectInserter inserter = repository.newObjectInserter();) {
- RevCommit sourceCommit = revWalk.parseCommit(sourceCommitId);
- RevCommit targetCommit = revWalk.parseCommit(targetCommitId);
- Merger merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
- if (merger.merge(targetCommit, sourceCommit)) {
- CommitBuilder mergedCommit = new CommitBuilder();
- mergedCommit.setAuthor(author);
- mergedCommit.setCommitter(committer);
- if (squash)
- mergedCommit.setParentId(targetCommit);
- else
- mergedCommit.setParentIds(targetCommit, sourceCommit);
- mergedCommit.setMessage(commitMessage);
- mergedCommit.setTreeId(merger.getResultTreeId());
- ObjectId mergedCommitId = inserter.insert(mergedCommit);
- inserter.flush();
- return mergedCommitId;
- } else {
- return null;
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- UseOursOnConflict.set(prevUseOursOnConflict);
+ }
+
+ @Nullable
+ public static ObjectId merge(Repository repository, ObjectId targetCommitId, ObjectId sourceCommitId,
+ boolean squash, PersonIdent committer, PersonIdent author, String commitMessage,
+ boolean useOursOnConflict) {
+ try (RevWalk revWalk = new RevWalk(repository); ObjectInserter inserter = repository.newObjectInserter();) {
+ RevCommit sourceCommit = revWalk.parseCommit(sourceCommitId);
+ RevCommit targetCommit = revWalk.parseCommit(targetCommitId);
+ Merger merger;
+ if (useOursOnConflict)
+ merger = MergeStrategy.OURS.newMerger(repository, true);
+ else
+ merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
+ if (merger.merge(targetCommit, sourceCommit)) {
+ CommitBuilder mergedCommit = new CommitBuilder();
+ mergedCommit.setAuthor(author);
+ mergedCommit.setCommitter(committer);
+ if (squash)
+ mergedCommit.setParentId(targetCommit);
+ else
+ mergedCommit.setParentIds(targetCommit, sourceCommit);
+ mergedCommit.setMessage(commitMessage);
+ mergedCommit.setTreeId(merger.getResultTreeId());
+ ObjectId mergedCommitId = inserter.insert(mergedCommit);
+ inserter.flush();
+ return mergedCommitId;
+ } else {
+ return null;
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
}
- }
-
- public static Collection<String> getChangedFiles(Repository repository, ObjectId oldCommitId, ObjectId newCommitId) {
+ }
+
+ public static Collection<String> getChangedFiles(Repository repository, ObjectId oldCommitId,
+ ObjectId newCommitId) {
Collection<String> changedFiles = new HashSet<>();
- try ( RevWalk revWalk = new RevWalk(repository);
- TreeWalk treeWalk = new TreeWalk(repository)) {
+ try (RevWalk revWalk = new RevWalk(repository); TreeWalk treeWalk = new TreeWalk(repository)) {
treeWalk.setFilter(TreeFilter.ANY_DIFF);
treeWalk.setRecursive(true);
RevCommit oldCommit = revWalk.parseCommit(oldCommitId);
@@ -473,12 +460,12 @@ public class GitUtils {
throw new RuntimeException(e);
}
return changedFiles;
- }
+ }
+
+ public static boolean isValid(File gitDir) {
+ return new File(gitDir, "objects").exists();
+ }
- public static boolean isValid(File gitDir) {
- return new File(gitDir, "objects").exists();
- }
-
public static RefUpdate getRefUpdate(Repository repository, String refName) {
try {
return repository.updateRef(refName);
@@ -486,44 +473,43 @@ public class GitUtils {
throw new RuntimeException(e);
}
}
-
+
public static void updateRef(RefUpdate refUpdate) {
try {
RefUpdate.Result result = refUpdate.forceUpdate();
- if (result == RefUpdate.Result.LOCK_FAILURE
- && refUpdate.getExpectedOldObjectId() != null
- && !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
- throw new ObsoleteCommitException(refUpdate.getOldObjectId());
- } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
- && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
- throw new RefUpdateException(result);
- }
+ if (result == RefUpdate.Result.LOCK_FAILURE && refUpdate.getExpectedOldObjectId() != null
+ && !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
+ throw new ObsoleteCommitException(refUpdate.getOldObjectId());
+ } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
+ && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
+ throw new RefUpdateException(result);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
}
-
+
public static void deleteRef(RefUpdate refUpdate) {
try {
refUpdate.setForceUpdate(true);
RefUpdate.Result result = refUpdate.delete();
- if (result == RefUpdate.Result.LOCK_FAILURE
- && refUpdate.getExpectedOldObjectId() != null
- && !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
- throw new ObsoleteCommitException(refUpdate.getOldObjectId());
- } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
- && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
- throw new RefUpdateException(result);
- }
+ if (result == RefUpdate.Result.LOCK_FAILURE && refUpdate.getExpectedOldObjectId() != null
+ && !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
+ throw new ObsoleteCommitException(refUpdate.getOldObjectId());
+ } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
+ && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
+ throw new RefUpdateException(result);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
}
-
+
public static void linkRef(RefUpdate refUpdate, String target) {
try {
RefUpdate.Result result = refUpdate.link(target);
- if (result != RefUpdate.Result.FORCED && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE)
+ if (result != RefUpdate.Result.FORCED && result != RefUpdate.Result.NEW
+ && result != RefUpdate.Result.NO_CHANGE)
throw new RefUpdateException(result);
} catch (IOException e) {
throw new RuntimeException(e);
diff --git a/server-core/src/main/java/io/onedev/server/git/UseOursOnConflict.java b/server-core/src/main/java/io/onedev/server/git/UseOursOnConflict.java
deleted file mode 100644
index 82a7f35194..0000000000
--- a/server-core/src/main/java/io/onedev/server/git/UseOursOnConflict.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package io.onedev.server.git;
-
-public class UseOursOnConflict {
-
- private static ThreadLocal<Boolean> holder = new ThreadLocal<Boolean>() {
-
- @Override
- protected Boolean initialValue() {
- return false;
- }
-
- };
-
- public static boolean get() {
- return holder.get();
- }
-
- public static void set(boolean useOursOnConflict) {
- holder.set(useOursOnConflict);
- }
-
-}
-
diff --git a/server-core/src/main/java/io/onedev/server/model/Project.java b/server-core/src/main/java/io/onedev/server/model/Project.java
index e8b4041614..6fc47bccee 100644
--- a/server-core/src/main/java/io/onedev/server/model/Project.java
+++ b/server-core/src/main/java/io/onedev/server/model/Project.java
@@ -61,10 +61,10 @@ import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/EolAwareOutputStream.java b/server-core/src/main/java/org/eclipse/jgit/merge/EolAwareOutputStream.java
deleted file mode 100644
index e44970abff..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/EolAwareOutputStream.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2014, André de Oliveira <[email protected]>
- *
- * 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');
- }
-
- /** @return true if a new line has just begun. */
- boolean isBeginln() {
- return bol;
- }
-
- /** {@inheritDoc} */
- @Override
- public void write(int val) throws IOException {
- out.write(val);
- bol = (val == '\n');
- }
-
- /** {@inheritDoc} */
- @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');
- }
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeAlgorithm.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeAlgorithm.java
deleted file mode 100644
index 5978b8af33..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeAlgorithm.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * Copyright (C) 2009, Christian Halstrick <[email protected]> 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.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;
-
-import io.onedev.server.git.UseOursOnConflict;
-
-/**
- * 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;
-
- /**
- * 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;
- }
-
- // 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);
-
- private static boolean isEndEdit(Edit edit) {
- return edit == END_EDIT;
- }
-
- /**
- * Does the three way merge between a common base and two 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 <S extends Sequence> MergeResult<S> merge(
- SequenceComparator<S> cmp, S base, S ours, S theirs) {
- List<S> sequences = new ArrayList<>(3);
- sequences.add(base);
- sequences.add(ours);
- sequences.add(theirs);
- MergeResult<S> result = new MergeResult<>(sequences);
-
- boolean useOursOnConflict = UseOursOnConflict.get();
-
- if (ours.size() == 0) {
- if (theirs.size() != 0) {
- EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
- if (!theirsEdits.isEmpty()) {
- // we deleted, they modified -> Let their complete content
- // conflict with empty text
- if (useOursOnConflict) {
- result.add(1, 0, 0, ConflictState.NO_CONFLICT);
- } else {
- result.add(1, 0, 0, ConflictState.FIRST_CONFLICTING_RANGE);
- result.add(2, 0, theirs.size(),
- ConflictState.NEXT_CONFLICTING_RANGE);
- }
- } 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 -> Let our complete content
- // conflict with empty text
- if (useOursOnConflict) {
- result.add(1, 0, ours.size(), ConflictState.NO_CONFLICT);
- } else {
- result.add(1, 0, ours.size(),
- ConflictState.FIRST_CONFLICTING_RANGE);
- result.add(2, 0, 0, ConflictState.NEXT_CONFLICTING_RANGE);
- }
- } 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<Edit> baseToOurs = oursEdits.iterator();
- EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
- Iterator<Edit> 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 oursBeginB = oursEdit.getBeginB();
- int theirsBeginB = theirsEdit.getBeginB();
- // harmonize the start of the ranges in A and B
- if (oursEdit.getBeginA() < theirsEdit.getBeginA()) {
- theirsBeginB -= theirsEdit.getBeginA()
- - oursEdit.getBeginA();
- } else {
- 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 oursEndB = oursEdit.getEndB();
- int theirsEndB = theirsEdit.getEndB();
- if (oursEdit.getEndA() < theirsEdit.getEndA()) {
- oursEndB += theirsEdit.getEndA() - oursEdit.getEndA();
- } else {
- 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) {
- if (useOursOnConflict) {
- result.add(1, oursBeginB + commonPrefix, oursEndB
- - commonSuffix,
- ConflictState.NO_CONFLICT);
- } else {
- result.add(1, oursBeginB + commonPrefix, oursEndB
- - commonSuffix,
- ConflictState.FIRST_CONFLICTING_RANGE);
- result.add(2, theirsBeginB + commonPrefix, theirsEndB
- - commonSuffix,
- ConflictState.NEXT_CONFLICTING_RANGE);
- }
- }
-
- // 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<Edit> it) {
- return (it.hasNext() ? it.next() : END_EDIT);
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeChunk.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeChunk.java
deleted file mode 100644
index ca998e30bc..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeChunk.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2009, Christian Halstrick <[email protected]>
- * 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 first one of the
- * conflicting chunks
- */
- FIRST_CONFLICTING_RANGE,
-
- /**
- * This chunk does belong to a conflict but is not the first one 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;
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeConfig.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeConfig.java
deleted file mode 100644
index 54b7aa4346..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeConfig.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * 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<MergeConfig> 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<MergeConfig> {
-
- 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();
- }
-
- }
-
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatter.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatter.java
deleted file mode 100644
index 36adf92e21..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatter.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2009, Christian Halstrick <[email protected]> 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 "&lt;&lt;&lt;&lt;&lt;&lt;&lt;
- * " or "&gt;&gt;&gt;&gt;&gt;&gt;&gt; " conflict markers. The
- * names for the sequences are given in this list
- * @param charsetName
- * the name of the character set used when writing conflict
- * metadata
- * @throws java.io.IOException
- * @deprecated Use
- * {@link #formatMerge(OutputStream, MergeResult, List, Charset)}
- * instead.
- */
- @Deprecated
- public void formatMerge(OutputStream out, MergeResult<RawText> res,
- List<String> seqName, String charsetName) throws IOException {
- formatMerge(out, res, seqName, Charset.forName(charsetName));
- }
-
- /**
- * 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 "&lt;&lt;&lt;&lt;&lt;&lt;&lt;
- * " or "&gt;&gt;&gt;&gt;&gt;&gt;&gt; " 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
- * @since 5.2
- */
- public void formatMerge(OutputStream out, MergeResult<RawText> res,
- List<String> seqName, Charset charset) throws IOException {
- new MergeFormatterPass(out, res, seqName, charset).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 charsetName
- * the name of the character set used when writing conflict
- * metadata
- * @throws java.io.IOException
- * @deprecated use
- * {@link #formatMerge(OutputStream, MergeResult, String, String, String, Charset)}
- * instead.
- */
- @SuppressWarnings("rawtypes")
- @Deprecated
- public void formatMerge(OutputStream out, MergeResult res, String baseName,
- String oursName, String theirsName, String charsetName) throws IOException {
- formatMerge(out, res, baseName, oursName, theirsName,
- Charset.forName(charsetName));
- }
-
- /**
- * 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
- * @since 5.2
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public void formatMerge(OutputStream out, MergeResult res, String baseName,
- String oursName, String theirsName, Charset charset)
- throws IOException {
- List<String> names = new ArrayList<>(3);
- names.add(baseName);
- names.add(oursName);
- names.add(theirsName);
- formatMerge(out, res, names, charset);
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatterPass.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatterPass.java
deleted file mode 100644
index f09b343007..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatterPass.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2009, Christian Halstrick <[email protected]>
- * Copyright (C) 2014, André de Oliveira <[email protected]> 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<RawText> res;
-
- private final List<String> seqName;
-
- private final Charset charset;
-
- private final boolean threeWayMerge;
-
- 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 "&lt;&lt;&lt;&lt;&lt;&lt;&lt;
- * " or "&gt;&gt;&gt;&gt;&gt;&gt;&gt; " 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<RawText> res,
- List<String> seqName, Charset charset) {
- this.out = new EolAwareOutputStream(out);
- this.res = res;
- this.seqName = seqName;
- this.charset = charset;
- this.threeWayMerge = (res.getSequences().size() == 3);
- }
-
- void formatMerge() throws IOException {
- boolean missingNewlineAtEnd = false;
- for (MergeChunk chunk : res) {
- 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
- && chunk.getConflictState() != ConflictState.NEXT_CONFLICTING_RANGE) {
- // found the end of an conflict
- writeConflictEnd();
- }
- if (chunk.getConflictState() == ConflictState.FIRST_CONFLICTING_RANGE) {
- // found the start of an conflict
- writeConflictStart(chunk);
- } else if (chunk.getConflictState() == ConflictState.NEXT_CONFLICTING_RANGE) {
- // found another conflicting chunk
- writeConflictChange(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 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');
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeMessageFormatter.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeMessageFormatter.java
deleted file mode 100644
index f7966a267f..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeMessageFormatter.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2010-2012, Robin Stocker <[email protected]> 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.
- * <p>
- * 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<Ref> refsToMerge, Ref target) {
- StringBuilder sb = new StringBuilder();
- sb.append("Merge "); //$NON-NLS-1$
-
- List<String> branches = new ArrayList<>();
- List<String> remoteBranches = new ArrayList<>();
- List<String> tags = new ArrayList<>();
- List<String> commits = new ArrayList<>();
- List<String> 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<String> 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
- * @return merge message with conflicting paths added
- */
- public String formatWithConflicts(String message,
- List<String> conflictingPaths) {
- 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);
- 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(List<String> conflictingPaths,
- StringBuilder sb) {
- sb.append("Conflicts:\n"); //$NON-NLS-1$
- for (String conflictingPath : conflictingPaths) {
- sb.append('\t').append(conflictingPath).append('\n');
- }
- }
-
- private static String joinNames(List<String> 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$
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeResult.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeResult.java
deleted file mode 100644
index 062a5a84e0..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeResult.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2009, Christian Halstrick <[email protected]> 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.
- * <p>
- * 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 <S>
- * type of sequence.
- */
-public class MergeResult<S extends Sequence> implements Iterable<MergeChunk> {
- private final List<S> 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<S> 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<S> getSequences() {
- return sequences;
- }
-
- static final ConflictState[] states = ConflictState.values();
-
- /** {@inheritDoc} */
- @Override
- public Iterator<MergeChunk> iterator() {
- return new Iterator<MergeChunk>() {
- 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;
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/MergeStrategy.java b/server-core/src/main/java/org/eclipse/jgit/merge/MergeStrategy.java
deleted file mode 100644
index ba9c5b7dcc..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/MergeStrategy.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2008-2009, Google Inc.
- * Copyright (C) 2009, Matthias Sohn <[email protected]>
- * 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.
- * <p>
- * 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<String, MergeStrategy> 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.
- * <p>
- * 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);
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/Merger.java b/server-core/src/main/java/org/eclipse/jgit/merge/Merger.java
deleted file mode 100644
index bd762e5a98..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/Merger.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * Copyright (C) 2008-2013, Google Inc.
- * Copyright (C) 2016, Laurent Delaigue <[email protected]> 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.
- * <p>
- * 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.
- * <p>
- * 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.
- * <p>
- * 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.
- * <p>
- * 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.
- * <p>
- * 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;
- }
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/RecursiveMerger.java b/server-core/src/main/java/org/eclipse/jgit/merge/RecursiveMerger.java
deleted file mode 100644
index bf2a78f6b3..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/RecursiveMerger.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2012, Research In Motion Limited
- * Copyright (C) 2012, Christian Halstrick <[email protected]> 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.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.TimeZone;
-
-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}
- * <p>
- * 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
- * @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<RevCommit> 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<RevCommit> 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
- throw new NoMergeBaseException(
- NoMergeBaseException.MergeBaseFailureReason.CONFLICTS_DURING_MERGE_BASE_CALCULATION,
- MessageFormat.format(
- JGitText.get().mergeRecursiveConflictsWhenMergingCommonAncestors,
- currentBase.getName(), nextBase.getName()));
- }
- } finally {
- inCore = oldIncore;
- dircache = oldDircache;
- workingTreeIterator = oldWTreeIt;
- toBeCheckedOut.clear();
- toBeDeleted.clear();
- modifiedFiles.clear();
- 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
- */
- private RevCommit createCommitForTree(ObjectId tree, List<RevCommit> 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<RevCommit> 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$
- new Date((time + 1) * 1000L),
- TimeZone.getTimeZone("GMT+0000")); //$NON-NLS-1$
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/ResolveMerger.java b/server-core/src/main/java/org/eclipse/jgit/merge/ResolveMerger.java
deleted file mode 100644
index cb14b1398d..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/ResolveMerger.java
+++ /dev/null
@@ -1,1345 +0,0 @@
-/*
- * Copyright (C) 2010, Christian Halstrick <[email protected]>,
- * Copyright (C) 2010-2012, Matthias Sohn <[email protected]>
- * Copyright (C) 2012, Research In Motion Limited
- * Copyright (C) 2017, Obeo ([email protected])
- * Copyright (C) 2018, Thomas Wolf <[email protected]> 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.BufferedOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-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.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jgit.attributes.Attributes;
-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.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.DirCacheEntry;
-import org.eclipse.jgit.errors.BinaryBlobException;
-import org.eclipse.jgit.errors.CorruptObjectException;
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.IndexWriteException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.errors.NoWorkTreeException;
-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.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.FS;
-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;
-
-import io.onedev.server.git.UseOursOnConflict;
-
-/**
- * A three-way merger performing a content-merge if necessary
- */
-public class ResolveMerger extends ThreeWayMerger {
- /**
- * 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;
-
- /**
- * Builder to update the cache during this merge.
- *
- * @since 3.4
- */
- protected DirCacheBuilder builder;
-
- /**
- * merge result as tree
- *
- * @since 3.0
- */
- protected ObjectId resultTree;
-
- /**
- * Paths that could not be merged by this merger because of an unsolvable
- * conflict.
- *
- * @since 3.4
- */
- protected List<String> unmergedPaths = new ArrayList<>();
-
- /**
- * Files modified during this merge operation.
- *
- * @since 3.4
- */
- protected List<String> modifiedFiles = new LinkedList<>();
-
- /**
- * If the merger has nothing to do for a file but check it out at the end of
- * the operation, it can be added here.
- *
- * @since 3.4
- */
- protected Map<String, DirCacheEntry> toBeCheckedOut = new HashMap<>();
-
- /**
- * Paths in this list will be deleted from the local copy at the end of the
- * operation.
- *
- * @since 3.4
- */
- protected List<String> toBeDeleted = new ArrayList<>();
-
- /**
- * Low-level textual merge results. Will be passed on to the callers in case
- * of conflicts.
- *
- * @since 3.4
- */
- protected Map<String, MergeResult<? extends Sequence>> mergeResults = new HashMap<>();
-
- /**
- * Paths for which the merge failed altogether.
- *
- * @since 3.4
- */
- protected Map<String, MergeFailureReason> 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;
-
- /**
- * Set to true if this merger should use the default dircache of the
- * repository and should handle locking and unlocking of the dircache. If
- * this merger should work in-core or if an explicit dircache was specified
- * during construction then this field is set to false.
- * @since 3.0
- */
- protected boolean implicitDirCache;
-
- /**
- * Directory cache
- * @since 3.0
- */
- protected DirCache dircache;
-
- /**
- * The iterator to access the working tree. If set to <code>null</code> 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 WorkingTreeOptions} are needed to determine line endings for
- * merged files.
- *
- * @since 4.11
- */
- protected WorkingTreeOptions workingTreeOptions;
-
- /**
- * The size limit (bytes) which controls a file to be stored in {@code Heap}
- * or {@code LocalFile} during the merge.
- */
- private int inCoreLimit;
-
- /**
- * Keeps {@link CheckoutMetadata} for {@link #checkout()} and
- * {@link #cleanUp()}.
- */
- private Map<String, CheckoutMetadata> checkoutMetadata;
-
- 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 int getInCoreLimit(Config config) {
- return config.getInt(
- ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20);
- }
-
- 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);
- inCoreLimit = getInCoreLimit(config);
- commitNames = defaultCommitNames();
- this.inCore = inCore;
-
- if (inCore) {
- implicitDirCache = false;
- dircache = DirCache.newInCore();
- } else {
- implicitDirCache = true;
- workingTreeOptions = local.getConfig().get(WorkingTreeOptions.KEY);
- }
- }
-
- /**
- * 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;
- implicitDirCache = false;
- dircache = DirCache.newInCore();
- }
-
- /** {@inheritDoc} */
- @Override
- protected boolean mergeImpl() throws IOException {
- if (implicitDirCache) {
- dircache = nonNullRepo().lockDirCache();
- }
- if (!inCore) {
- checkoutMetadata = new HashMap<>();
- }
- try {
- return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1],
- false);
- } finally {
- checkoutMetadata = null;
- if (implicitDirCache) {
- dircache.unlock();
- }
- }
- }
-
- private void checkout() throws NoWorkTreeException, IOException {
- // 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 (int i = toBeDeleted.size() - 1; i >= 0; i--) {
- String fileName = toBeDeleted.get(i);
- File f = new File(nonNullRepo().getWorkTree(), fileName);
- if (!f.delete())
- if (!f.isDirectory())
- failingPaths.put(fileName,
- MergeFailureReason.COULD_NOT_DELETE);
- modifiedFiles.add(fileName);
- }
- for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
- .entrySet()) {
- DirCacheEntry cacheEntry = entry.getValue();
- if (cacheEntry.getFileMode() == FileMode.GITLINK) {
- new File(nonNullRepo().getWorkTree(), entry.getKey()).mkdirs();
- } else {
- DirCacheCheckout.checkoutEntry(db, cacheEntry, reader, false,
- checkoutMetadata.get(entry.getKey()));
- modifiedFiles.add(entry.getKey());
- }
- }
- }
-
- /**
- * Reverts the worktree after an unsuccessful merge. We know that for all
- * modified files the old content was in the old index and the index
- * contained only stage 0. In case if inCore operation just clear the
- * history of modified files.
- *
- * @throws java.io.IOException
- * @throws org.eclipse.jgit.errors.CorruptObjectException
- * @throws org.eclipse.jgit.errors.NoWorkTreeException
- * @since 3.4
- */
- protected void cleanUp() throws NoWorkTreeException,
- CorruptObjectException,
- IOException {
- if (inCore) {
- modifiedFiles.clear();
- return;
- }
-
- DirCache dc = nonNullRepo().readDirCache();
- Iterator<String> mpathsIt=modifiedFiles.iterator();
- while(mpathsIt.hasNext()) {
- String mpath = mpathsIt.next();
- DirCacheEntry entry = dc.getEntry(mpath);
- if (entry != null) {
- DirCacheCheckout.checkoutEntry(db, entry, reader, false,
- checkoutMetadata.get(mpath));
- }
- mpathsIt.remove();
- }
- }
-
- /**
- * adds a new path with the specified stage to the index builder
- *
- * @param path
- * @param p
- * @param stage
- * @param lastMod
- * @param len
- * @return the entry which was added to the index
- */
- private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
- Instant lastMod, long len) {
- if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
- DirCacheEntry e = new DirCacheEntry(path, stage);
- e.setFileMode(p.getEntryFileMode());
- e.setObjectId(p.getEntryObjectId());
- e.setLastModified(lastMod);
- e.setLength(len);
- builder.add(e);
- return e;
- }
- return null;
- }
-
- /**
- * 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) {
- DirCacheEntry newEntry = new DirCacheEntry(e.getRawPath(),
- e.getStage());
- newEntry.setFileMode(e.getFileMode());
- newEntry.setObjectId(e.getObjectId());
- newEntry.setLastModified(e.getLastModifiedInstant());
- newEntry.setLength(e.getLength());
- builder.add(newEntry);
- return newEntry;
- }
-
- /**
- * Remembers the {@link CheckoutMetadata} for the given path; it may be
- * needed in {@link #checkout()} or in {@link #cleanUp()}.
- *
- * @param path
- * of the current node
- * @param attributes
- * for the current node
- * @throws IOException
- * if the smudge filter cannot be determined
- * @since 5.1
- */
- protected void addCheckoutMetadata(String path, Attributes attributes)
- throws IOException {
- if (checkoutMetadata != null) {
- EolStreamType eol = EolStreamTypeUtil.detectStreamType(
- OperationType.CHECKOUT_OP, workingTreeOptions, attributes);
- CheckoutMetadata data = new CheckoutMetadata(eol,
- tw.getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE));
- checkoutMetadata.put(path, data);
- }
- }
-
- /**
- * Adds a {@link DirCacheEntry} for direct checkout and remembers its
- * {@link CheckoutMetadata}.
- *
- * @param path
- * of the entry
- * @param entry
- * to add
- * @param attributes
- * for the current entry
- * @throws IOException
- * if the {@link CheckoutMetadata} cannot be determined
- * @since 5.1
- */
- protected void addToCheckout(String path, DirCacheEntry entry,
- Attributes attributes) throws IOException {
- toBeCheckedOut.put(path, entry);
- addCheckoutMetadata(path, attributes);
- }
-
- /**
- * Remember a path for deletion, and remember its {@link CheckoutMetadata}
- * in case it has to be restored in {@link #cleanUp()}.
- *
- * @param path
- * of the entry
- * @param isFile
- * whether it is a file
- * @param attributes
- * for the entry
- * @throws IOException
- * if the {@link CheckoutMetadata} cannot be determined
- * @since 5.1
- */
- protected void addDeletion(String path, boolean isFile,
- Attributes attributes) throws IOException {
- toBeDeleted.add(path);
- if (isFile) {
- addCheckoutMetadata(path, attributes);
- }
- }
-
- /**
- * 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
- * <ul>
- * <li>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 <a href=
- * "http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html#_3_way_merge"
- * >git read-tree</a> documentation for further explanations.</li>
- * <li>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.</li>
- * </ul>
- *
- * @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 attributes defined for this entry
- * @return <code>false</code> 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 org.eclipse.jgit.errors.MissingObjectException
- * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
- * @throws org.eclipse.jgit.errors.CorruptObjectException
- * @throws java.io.IOException
- * @since 4.9
- */
- protected boolean processEntry(CanonicalTreeParser base,
- CanonicalTreeParser ours, CanonicalTreeParser theirs,
- DirCacheBuildIterator index, WorkingTreeIterator work,
- boolean ignoreConflicts, Attributes attributes)
- throws MissingObjectException, IncorrectObjectTypeException,
- CorruptObjectException, IOException {
- boolean useOursOnConflict = UseOursOnConflict.get();
- enterSubtree = true;
- final int modeO = tw.getRawMode(T_OURS);
- final int modeT = tw.getRawMode(T_THEIRS);
- final int modeB = tw.getRawMode(T_BASE);
-
- 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;
- }
- // FileModes are not mergeable. We found a conflict on modes.
- // For conflicting entries we don't know lastModified and
- // length.
- add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
- add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
- add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
- unmergedPaths.add(tw.getPathString());
- mergeResults.put(tw.getPathString(),
- new MergeResult<>(Collections.<RawText> 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);
- 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 (useOursOnConflict) {
- if (ourDce != null)
- keep(ourDce);
- } else {
- if (nonTree(modeB))
- add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
- add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
- unmergedPaths.add(tw.getPathString());
- }
- enterSubtree = false;
- return true;
- }
- if (nonTree(modeT) && !nonTree(modeO)) {
- if (useOursOnConflict) {
- if (ourDce != null)
- keep(ourDce);
- } else {
- if (nonTree(modeB))
- add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
- 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.canBeContentMerged() && worktreeDirty) {
- return false;
- }
-
- boolean gitlinkConflict = isGitLink(modeO) || isGitLink(modeT);
- // Don't attempt to resolve submodule link conflicts
- if (gitlinkConflict || !attributes.canBeContentMerged()) {
- if (useOursOnConflict) {
- if (ourDce != null)
- keep(ourDce);
- } else {
- add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
- add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
- add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
-
- 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,
- attributes);
- if (ignoreConflicts) {
- result.setContainsConflicts(false);
- }
- updateIndex(base, ours, theirs, result, attributes);
- String currentPath = tw.getPathString();
- if (result.containsConflicts() && !ignoreConflicts) {
- unmergedPaths.add(currentPath);
- }
- modifiedFiles.add(currentPath);
- addCheckoutMetadata(currentPath, attributes);
- } 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 (useOursOnConflict) {
- if (ourDce != null)
- keep(ourDce);
- } else {
- MergeResult<RawText> result = contentMerge(base, ours, theirs,
- attributes);
-
- add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
- add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
- DirCacheEntry e = add(tw.getRawPath(), theirs,
- DirCacheEntry.STAGE_3, EPOCH, 0);
-
- // OURS was deleted checkout THEIRS
- if (modeO == 0) {
- // Check worktree before checking out THEIRS
- if (isWorktreeDirty(work, ourDce))
- return false;
- if (nonTree(modeT)) {
- if (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;
- }
-
- /**
- * Does the content merge. The three texts base, ours and theirs are
- * specified with {@link CanonicalTreeParser}. If any of the parsers is
- * specified as <code>null</code> then an empty text will be used instead.
- *
- * @param base
- * @param ours
- * @param theirs
- * @param attributes
- *
- * @return the result of the content merge
- * @throws IOException
- */
- private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
- CanonicalTreeParser ours, CanonicalTreeParser theirs,
- Attributes attributes)
- throws IOException {
- RawText baseText;
- RawText ourText;
- RawText theirsText;
-
- try {
- baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
- base.getEntryObjectId(), attributes);
- ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
- ours.getEntryObjectId(), attributes);
- theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
- theirs.getEntryObjectId(), attributes);
- } catch (BinaryBlobException e) {
- MergeResult<RawText> r = new MergeResult<>(Collections.<RawText>emptyList());
- r.setContainsConflicts(true);
- return r;
- }
- return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
- ourText, theirsText));
- }
-
- 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
- * @param ours
- * @param theirs
- * @param result
- * @param attributes
- * @throws FileNotFoundException
- * @throws IOException
- */
- private void updateIndex(CanonicalTreeParser base,
- CanonicalTreeParser ours, CanonicalTreeParser theirs,
- MergeResult<RawText> result, Attributes attributes)
- throws FileNotFoundException,
- 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.
- add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
- add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
- add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
- 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.
- DirCacheEntry dce = new DirCacheEntry(tw.getPathString());
-
- // 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));
- dce.setFileMode(newMode == FileMode.MISSING.getBits()
- ? FileMode.REGULAR_FILE : FileMode.fromBits(newMode));
- if (mergedFile != null) {
- dce.setLastModified(
- nonNullRepo().getFS().lastModifiedInstant(mergedFile));
- dce.setLength((int) mergedFile.length());
- }
- dce.setObjectId(insertMergeResult(rawMerged, attributes));
- builder.add(dce);
- } 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 FileNotFoundException
- * @throws IOException
- */
- private File writeMergedFile(TemporaryBuffer rawMerged,
- Attributes attributes)
- throws FileNotFoundException, IOException {
- File workTree = nonNullRepo().getWorkTree();
- FS fs = nonNullRepo().getFS();
- File of = new File(workTree, tw.getPathString());
- File parentFolder = of.getParentFile();
- if (!fs.exists(parentFolder)) {
- parentFolder.mkdirs();
- }
- EolStreamType streamType = EolStreamTypeUtil.detectStreamType(
- OperationType.CHECKOUT_OP, workingTreeOptions,
- attributes);
- try (OutputStream os = EolStreamTypeUtil.wrapOutputStream(
- new BufferedOutputStream(new FileOutputStream(of)),
- streamType)) {
- rawMerged.writeTo(os, null);
- }
- return of;
- }
-
- private TemporaryBuffer doMerge(MergeResult<RawText> result)
- throws IOException {
- TemporaryBuffer.LocalFile buf = new TemporaryBuffer.LocalFile(
- db != null ? nonNullRepo().getDirectory() : null, inCoreLimit);
- 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;
- }
-
- private ObjectId insertMergeResult(TemporaryBuffer buf,
- Attributes attributes) throws IOException {
- InputStream in = buf.openInputStream();
- try (LfsInputStream is = LfsFactory.getInstance().applyCleanFilter(
- getRepository(), in,
- buf.length(), attributes.get(Constants.ATTR_MERGE))) {
- return getObjectInserter().insert(OBJ_BLOB, is.getLength(), is);
- }
- }
-
- /**
- * 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;
-
- if (UseOursOnConflict.get())
- return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
- else
- 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);
- }
-
- /** {@inheritDoc} */
- @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<String> 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<String> getModifiedFiles() {
- return 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<String, DirCacheEntry> getToBeCheckedOut() {
- return toBeCheckedOut;
- }
-
- /**
- * Get the mergeResults
- *
- * @return the mergeResults
- */
- public Map<String, MergeResult<? extends Sequence>> 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). <code>null</code> is returned if this merge didn't
- * fail.
- */
- public Map<String, MergeFailureReason> getFailingPaths() {
- return failingPaths.isEmpty() ? null : failingPaths;
- }
-
- /**
- * Returns whether this merge failed (i.e. not stopped because of a
- * conflict)
- *
- * @return <code>true</code> if a failure occurred, <code>false</code>
- * 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;
- implicitDirCache = false;
- }
-
- /**
- * 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.
- * <p>
- * 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;
- }
-
-
- /**
- * 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
- * <code>false</code>. 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.
- * <p>
- * If <code>true</code> 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
- * @since 3.5
- */
- protected boolean mergeTrees(AbstractTreeIterator baseTree,
- RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
- throws IOException {
-
- builder = dircache.builder();
- DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
-
- tw = new NameConflictTreeWalk(db, reader);
- tw.addTree(baseTree);
- tw.addTree(headTree);
- tw.addTree(mergeTree);
- 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;
- }
-
- if (!inCore) {
- // No problem found. The only thing left to be done is to
- // checkout all files from "theirs" which have been selected to
- // go into the new index.
- checkout();
-
- // All content-merges 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()) {
- cleanUp();
- throw new IndexWriteException();
- }
- builder = null;
-
- } else {
- builder.finish();
- builder = null;
- }
-
- if (getUnmergedPaths().isEmpty() && !failed()) {
- resultTree = dircache.writeTree(getObjectInserter());
- return true;
- }
- resultTree = null;
- return false;
- }
-
- /**
- * 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
- * @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()) {
- 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, hasAttributeNodeProvider
- ? treeWalk.getAttributes()
- : NO_ATTRIBUTES)) {
- cleanUp();
- return false;
- }
- if (treeWalk.isSubtree() && enterSubtree)
- treeWalk.enterSubtree();
- }
- return true;
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/SquashMessageFormatter.java b/server-core/src/main/java/org/eclipse/jgit/merge/SquashMessageFormatter.java
deleted file mode 100644
index 4a73f8ed7e..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/SquashMessageFormatter.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.
- * <p>
- * 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<RevCommit> 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();
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/StrategyOneSided.java b/server-core/src/main/java/org/eclipse/jgit/merge/StrategyOneSided.java
deleted file mode 100644
index 7055ccd127..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/StrategyOneSided.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2008-2009, Google Inc.
- * Copyright (C) 2009, Robin Rosenberg <[email protected]> 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.
- * <p>
- * 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;
- }
-
- /** {@inheritDoc} */
- @Override
- public String getName() {
- return strategyName;
- }
-
- /** {@inheritDoc} */
- @Override
- public Merger newMerger(Repository db) {
- return new OneSide(db, treeIndex);
- }
-
- /** {@inheritDoc} */
- @Override
- public Merger newMerger(Repository db, boolean inCore) {
- return new OneSide(db, treeIndex);
- }
-
- /** {@inheritDoc} */
- @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;
- }
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/StrategyRecursive.java b/server-core/src/main/java/org/eclipse/jgit/merge/StrategyRecursive.java
deleted file mode 100644
index c9512edf63..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/StrategyRecursive.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 {
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(Repository db) {
- return new RecursiveMerger(db, false);
- }
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(Repository db, boolean inCore) {
- return new RecursiveMerger(db, inCore);
- }
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
- return new RecursiveMerger(inserter, config);
- }
-
- /** {@inheritDoc} */
- @Override
- public String getName() {
- return "recursive"; //$NON-NLS-1$
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/StrategyResolve.java b/server-core/src/main/java/org/eclipse/jgit/merge/StrategyResolve.java
deleted file mode 100644
index 5991ef68a3..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/StrategyResolve.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2010, Christian Halstrick <[email protected]>,
- * Copyright (C) 2010, Matthias Sohn <[email protected]> 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 {
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(Repository db) {
- return new ResolveMerger(db, false);
- }
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(Repository db, boolean inCore) {
- return new ResolveMerger(db, inCore);
- }
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
- return new ResolveMerger(inserter, config);
- }
-
- /** {@inheritDoc} */
- @Override
- public String getName() {
- return "resolve"; //$NON-NLS-1$
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/StrategySimpleTwoWayInCore.java b/server-core/src/main/java/org/eclipse/jgit/merge/StrategySimpleTwoWayInCore.java
deleted file mode 100644
index ff40fc1d68..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/StrategySimpleTwoWayInCore.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * 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.
- * <p>
- * 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).
- * <p>
- * 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() {
- //
- }
-
- /** {@inheritDoc} */
- @Override
- public String getName() {
- return "simple-two-way-in-core"; //$NON-NLS-1$
- }
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(Repository db) {
- return new InCoreMerger(db);
- }
-
- /** {@inheritDoc} */
- @Override
- public ThreeWayMerger newMerger(Repository db, boolean inCore) {
- // This class is always inCore, so ignore the parameter
- return newMerger(db);
- }
-
- /** {@inheritDoc} */
- @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;
- }
- }
-
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMergeStrategy.java b/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMergeStrategy.java
deleted file mode 100644
index 411789fd95..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMergeStrategy.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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 {
- /** {@inheritDoc} */
- @Override
- public abstract ThreeWayMerger newMerger(Repository db);
-
- /** {@inheritDoc} */
- @Override
- public abstract ThreeWayMerger newMerger(Repository db, boolean inCore);
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMerger.java b/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMerger.java
deleted file mode 100644
index f283edee01..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMerger.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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;
- }
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean merge(AnyObjectId... tips) throws IOException {
- if (tips.length != 2)
- return false;
- return super.merge(tips);
- }
-
- /** {@inheritDoc} */
- @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
- */
- 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());
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/merge/package-info.java b/server-core/src/main/java/org/eclipse/jgit/merge/package-info.java
deleted file mode 100644
index d61cd6a5cd..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/merge/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Content and commit history merge algorithms.
- */
-package org.eclipse.jgit.merge;
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmapWalker.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmapWalker.java
index 023962e251..8cd5eb2238 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmapWalker.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmapWalker.java
@@ -16,6 +16,7 @@ import java.util.Arrays;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.internal.revwalk.AddToBitmapFilter;
+import org.eclipse.jgit.internal.revwalk.AddToBitmapWithCacheFilter;
import org.eclipse.jgit.internal.revwalk.AddUnseenToBitmapFilter;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.BitmapIndex;
@@ -41,6 +42,11 @@ public final class BitmapWalker {
private long countOfBitmapIndexMisses;
+ // Cached bitmap and commit to save walk time.
+ private AnyObjectId prevCommit;
+
+ private Bitmap prevBitmap;
+
/**
* Create a BitmapWalker.
*
@@ -55,6 +61,28 @@ public final class BitmapWalker {
this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
}
+ /**
+ * Set the cached commit for the walker.
+ *
+ * @param prevCommit
+ * the cached commit.
+ * @since 5.8
+ */
+ public void setPrevCommit(AnyObjectId prevCommit) {
+ this.prevCommit = prevCommit;
+ }
+
+ /**
+ * Set the bitmap associated with the cached commit for the walker.
+ *
+ * @param prevBitmap
+ * the bitmap associated with the cached commit.
+ * @since 5.8
+ */
+ public void setPrevBitmap(Bitmap prevBitmap) {
+ this.prevBitmap = prevBitmap;
+ }
+
/**
* Return the number of objects that had to be walked because they were not covered by a
* bitmap.
@@ -169,7 +197,10 @@ public final class BitmapWalker {
}
if (marked) {
- if (seen == null) {
+ if (prevCommit != null) {
+ walker.setRevFilter(new AddToBitmapWithCacheFilter(prevCommit,
+ prevBitmap, bitmapResult));
+ } else if (seen == null) {
walker.setRevFilter(new AddToBitmapFilter(bitmapResult));
} else {
walker.setRevFilter(
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmappedReachabilityChecker.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmappedReachabilityChecker.java
deleted file mode 100644
index 02514526d0..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmappedReachabilityChecker.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2019, Google LLC 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.revwalk;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Stream;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.lib.BitmapIndex;
-import org.eclipse.jgit.lib.BitmapIndex.Bitmap;
-import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.revwalk.filter.RevFilter;
-
-/**
- * Checks the reachability using bitmaps.
- */
-class BitmappedReachabilityChecker implements ReachabilityChecker {
-
- private final RevWalk walk;
-
- /**
- * @param walk
- * walk on the repository to get or create the bitmaps for the
- * commits. It must have bitmaps.
- * @throws AssertionError
- * runtime exception if walk is over a repository without
- * bitmaps
- * @throws IOException
- * if the index or the object reader cannot be opened.
- */
- public BitmappedReachabilityChecker(RevWalk walk)
- throws IOException {
- this.walk = walk;
- if (walk.getObjectReader().getBitmapIndex() == null) {
- throw new AssertionError(
- "Trying to use bitmapped reachability check " //$NON-NLS-1$
- + "on a repository without bitmaps"); //$NON-NLS-1$
- }
- }
-
- /**
- * Check all targets are reachable from the starters.
- * <p>
- * In this implementation, it is recommended to put the most popular
- * starters (e.g. refs/heads tips) at the beginning.
- */
- @Override
- public Optional<RevCommit> areAllReachable(Collection<RevCommit> targets,
- Stream<RevCommit> starters) throws MissingObjectException,
- IncorrectObjectTypeException, IOException {
-
- List<RevCommit> remainingTargets = new ArrayList<>(targets);
-
- walk.reset();
- walk.sort(RevSort.TOPO);
-
- // Filter emits only commits that are unreachable from previously
- // visited commits. Internally it keeps a bitmap of everything
- // reachable so far, which we use to discard reachable targets.
- BitmapIndex repoBitmaps = walk.getObjectReader().getBitmapIndex();
- ReachedFilter reachedFilter = new ReachedFilter(repoBitmaps);
- walk.setRevFilter(reachedFilter);
-
- Iterator<RevCommit> startersIter = starters.iterator();
- while (startersIter.hasNext()) {
- walk.markStart(startersIter.next());
- while (walk.next() != null) {
- remainingTargets.removeIf(reachedFilter::isReachable);
-
- if (remainingTargets.isEmpty()) {
- return Optional.empty();
- }
- }
- walk.reset();
- }
-
- return Optional.of(remainingTargets.get(0));
- }
-
- /**
- * This filter emits commits that were not bitmap-reachable from anything
- * visited before. Or in other words, commits that add something (themselves
- * or their bitmap) to the "reached" bitmap.
- *
- * Current progress can be queried via {@link #isReachable(RevCommit)}.
- */
- private static class ReachedFilter extends RevFilter {
-
- private final BitmapIndex repoBitmaps;
- private final BitmapBuilder reached;
-
- /**
- * Create a filter that emits only previously unreachable commits.
- *
- * @param repoBitmaps
- * bitmap index of the repo
- */
- public ReachedFilter(BitmapIndex repoBitmaps) {
- this.repoBitmaps = repoBitmaps;
- this.reached = repoBitmaps.newBitmapBuilder();
- }
-
- /** {@inheritDoc} */
- @Override
- public final boolean include(RevWalk walker, RevCommit cmit) {
- Bitmap commitBitmap;
-
- if (reached.contains(cmit)) {
- // already seen or included
- dontFollow(cmit);
- return false;
- }
-
- if ((commitBitmap = repoBitmaps.getBitmap(cmit)) != null) {
- reached.or(commitBitmap);
- // Emit the commit because there are new contents in the bitmap
- // but don't follow parents (they are already in the bitmap)
- dontFollow(cmit);
- return true;
- }
-
- // No bitmaps, keep going
- reached.addObject(cmit, Constants.OBJ_COMMIT);
- return true;
- }
-
- private static final void dontFollow(RevCommit cmit) {
- for (RevCommit p : cmit.getParents()) {
- p.add(RevFlag.SEEN);
- }
- }
-
- /** {@inheritDoc} */
- @Override
- public final RevFilter clone() {
- throw new UnsupportedOperationException();
- }
-
- /** {@inheritDoc} */
- @Override
- public final boolean requiresCommitBody() {
- return false;
- }
-
- boolean isReachable(RevCommit commit) {
- return reached.contains(commit);
- }
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/DateRevQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/DateRevQueue.java
index b875be9270..0cabf07057 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/DateRevQueue.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/DateRevQueue.java
@@ -93,7 +93,7 @@ public class DateRevQueue extends AbstractRevQueue {
head = n;
} else {
Entry p = q.next;
- while (p != null && p.commit.commitTime > when) {
+ while (p != null && p.commit.commitTime >= when) {
q = p;
p = q.next;
}
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectReachabilityChecker.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectReachabilityChecker.java
new file mode 100644
index 0000000000..48e908e884
--- /dev/null
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectReachabilityChecker.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2020, Google LLC 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.revwalk;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+/**
+ * Checks if all objects are reachable from certain starting points.
+ *
+ * This is an expensive check that browses commits, trees, blobs and tags. For
+ * reachability just between commits see {@link ReachabilityChecker}
+ * implementations.
+ *
+ * @since 5.8
+ */
+public interface ObjectReachabilityChecker {
+
+ /**
+ * Checks that all targets are reachable from the starters.
+ *
+ * @implSpec Missing or invalid objects are reported as illegal state.
+ * Caller should have found them while translating ObjectIds into
+ * RevObjects. They can only happen here if the caller is mixing
+ * revwalks.
+ *
+ * @param targets
+ * objects to check for reachability from the starters
+ * @param starters
+ * objects known to be reachable to the caller
+ * @return Optional a single unreachable target if there are any (there
+ * could be more). Empty optional means all targets are reachable.
+ * @throws IOException
+ * Cannot access underlying storage
+ */
+ Optional<RevObject> areAllReachable(Collection<RevObject> targets,
+ Stream<RevObject> starters) throws IOException;
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectWalk.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectWalk.java
index 04a4b4c631..e6f9580bf7 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectWalk.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/ObjectWalk.java
@@ -159,6 +159,29 @@ public class ObjectWalk extends RevWalk {
pathBuf = new byte[256];
}
+ /**
+ * Create an object reachability checker that will use bitmaps if possible.
+ *
+ * This reachability checker accepts any object as target. For checks
+ * exclusively between commits, see
+ * {@link RevWalk#createReachabilityChecker()}.
+ *
+ * @return an object reachability checker, using bitmaps if possible.
+ *
+ * @throws IOException
+ * when the index fails to load.
+ *
+ * @since 5.8
+ * @deprecated use
+ * {@code ObjectReader#createObjectReachabilityChecker(ObjectWalk)}
+ * instead.
+ */
+ @Deprecated
+ public final ObjectReachabilityChecker createObjectReachabilityChecker()
+ throws IOException {
+ return reader.createObjectReachabilityChecker(this);
+ }
+
/**
* Mark an object or commit to start graph traversal from.
* <p>
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/PedestrianReachabilityChecker.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/PedestrianReachabilityChecker.java
deleted file mode 100644
index 5dc03776c2..0000000000
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/PedestrianReachabilityChecker.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2019, Google LLC. 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.revwalk;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Optional;
-import java.util.stream.Stream;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-
-/**
- * Checks the reachability walking the graph from the starters towards the
- * target.
- */
-class PedestrianReachabilityChecker implements ReachabilityChecker {
-
- private final boolean topoSort;
-
- private final RevWalk walk;
-
- /**
- * New instance of the reachability checker using a existing walk.
- *
- * @param topoSort
- * walk commits in topological order
- * @param walk
- * RevWalk instance to reuse. Caller retains ownership.
- */
- public PedestrianReachabilityChecker(boolean topoSort,
- RevWalk walk) {
- this.topoSort = topoSort;
- this.walk = walk;
- }
-
- @Override
- public Optional<RevCommit> areAllReachable(Collection<RevCommit> targets,
- Stream<RevCommit> starters)
- throws MissingObjectException, IncorrectObjectTypeException,
- IOException {
- walk.reset();
- if (topoSort) {
- walk.sort(RevSort.TOPO);
- }
-
- for (RevCommit target: targets) {
- walk.markStart(target);
- }
-
- Iterator<RevCommit> iterator = starters.iterator();
- while (iterator.hasNext()) {
- walk.markUninteresting(iterator.next());
- }
-
- return Optional.ofNullable(walk.next());
- }
-}
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObject.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObject.java
index 5ce4bc33b5..4d2684a0f0 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObject.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObject.java
@@ -152,6 +152,7 @@ public abstract class RevObject extends ObjectIdOwnerMap.Entry {
*/
protected void appendCoreFlags(StringBuilder s) {
s.append((flags & RevWalk.TOPO_DELAY) != 0 ? 'o' : '-');
+ s.append((flags & RevWalk.TOPO_QUEUED) != 0 ? 'q' : '-');
s.append((flags & RevWalk.TEMP_MARK) != 0 ? 't' : '-');
s.append((flags & RevWalk.REWRITE) != 0 ? 'r' : '-');
s.append((flags & RevWalk.UNINTERESTING) != 0 ? 'u' : '-');
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevSort.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevSort.java
index fc6ae28dc9..08396a8061 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevSort.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevSort.java
@@ -39,6 +39,18 @@ public enum RevSort {
*/
TOPO,
+ /**
+ * Topological sorting (all children before parents) without intermixing
+ * lines of history.
+ * <p>
+ * This behavior more closely resembles C Git's git-log --topo-order than
+ * {@link #TOPO}. See C Git's topo-order <a href=
+ * "https://git-scm.com/docs/git-log#Documentation/git-log.txt---topo-order">description</a>.
+ *
+ * @since 5.8
+ */
+ TOPO_KEEP_BRANCH_TOGETHER,
+
/**
* Flip the output into the reverse ordering.
* <p>
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTag.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTag.java
index cac257199f..b9d145008b 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTag.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTag.java
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2008-2009, Google Inc.
+ * Copyright (C) 2008, 2009, Google Inc.
* Copyright (C) 2008, Marek Zawirski <[email protected]>
- * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others
+ * Copyright (C) 2008, 2021, Shawn O. Pearce <[email protected]> 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
@@ -18,7 +18,9 @@ import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
+import java.util.Arrays;
+import org.eclipse.jgit.annotations.Nullable;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
@@ -35,6 +37,10 @@ import org.eclipse.jgit.util.StringUtils;
* An annotated tag.
*/
public class RevTag extends RevObject {
+
+ private static final byte[] hSignature = Constants
+ .encodeASCII("-----BEGIN PGP SIGNATURE-----"); //$NON-NLS-1$
+
/**
* Parse an annotated tag from its canonical format.
*
@@ -171,6 +177,71 @@ public class RevTag extends RevObject {
return RawParseUtils.parsePersonIdent(raw, nameB);
}
+ private static int nextStart(byte[] prefix, byte[] buffer, int from) {
+ int stop = buffer.length - prefix.length + 1;
+ int ptr = from;
+ if (ptr > 0) {
+ ptr = RawParseUtils.nextLF(buffer, ptr - 1);
+ }
+ while (ptr < stop) {
+ int lineStart = ptr;
+ boolean found = true;
+ for (byte element : prefix) {
+ if (element != buffer[ptr++]) {
+ found = false;
+ break;
+ }
+ }
+ if (found) {
+ return lineStart;
+ }
+ do {
+ ptr = RawParseUtils.nextLF(buffer, ptr);
+ } while (ptr < stop && buffer[ptr] == '\n');
+ }
+ return -1;
+ }
+
+ private int getSignatureStart() {
+ byte[] raw = buffer;
+ int msgB = RawParseUtils.tagMessage(raw, 0);
+ if (msgB < 0) {
+ return msgB;
+ }
+ // Find the last signature start and return the rest
+ int start = nextStart(hSignature, raw, msgB);
+ if (start < 0) {
+ return start;
+ }
+ int next = RawParseUtils.nextLF(raw, start);
+ while (next < raw.length) {
+ int newStart = nextStart(hSignature, raw, next);
+ if (newStart < 0) {
+ break;
+ }
+ start = newStart;
+ next = RawParseUtils.nextLF(raw, start);
+ }
+ return start;
+ }
+
+ /**
+ * Parse the GPG signature from the raw buffer.
+ *
+ * @return contents of the GPG signature; {@code null} if the tag was not
+ * signed.
+ * @since 5.11
+ */
+ @Nullable
+ public final byte[] getRawGpgSignature() {
+ byte[] raw = buffer;
+ int start = getSignatureStart();
+ if (start < 0) {
+ return null;
+ }
+ return Arrays.copyOfRange(raw, start, raw.length);
+ }
+
/**
* Parse the complete tag message and decode it to a string.
* <p>
@@ -187,7 +258,12 @@ public class RevTag extends RevObject {
if (msgB < 0) {
return ""; //$NON-NLS-1$
}
- return RawParseUtils.decode(guessEncoding(), raw, msgB, raw.length);
+ int signatureStart = getSignatureStart();
+ int end = signatureStart < 0 ? raw.length : signatureStart;
+ if (end == msgB) {
+ return ""; //$NON-NLS-1$
+ }
+ return RawParseUtils.decode(guessEncoding(), raw, msgB, end);
}
/**
@@ -213,6 +289,16 @@ public class RevTag extends RevObject {
}
int msgE = RawParseUtils.endOfParagraph(raw, msgB);
+ int signatureStart = getSignatureStart();
+ if (signatureStart >= msgB && msgE > signatureStart) {
+ msgE = signatureStart;
+ if (msgE > msgB) {
+ msgE--;
+ }
+ if (msgB == msgE) {
+ return ""; //$NON-NLS-1$
+ }
+ }
String str = RawParseUtils.decode(guessEncoding(), raw, msgB, msgE);
if (RevCommit.hasLF(raw, msgB, msgE)) {
str = StringUtils.replaceLineBreaksWithSpace(str);
@@ -257,6 +343,22 @@ public class RevTag extends RevObject {
return tagName;
}
+ /**
+ * Obtain the raw unparsed tag body (<b>NOTE - THIS IS NOT A COPY</b>).
+ * <p>
+ * This method is exposed only to provide very fast, efficient access to
+ * this tag's message buffer. Applications relying on this buffer should be
+ * very careful to ensure they do not modify its contents during their use
+ * of it.
+ *
+ * @return the raw unparsed tag body. This is <b>NOT A COPY</b>. Do not
+ * alter the returned array.
+ * @since 5.11
+ */
+ public final byte[] getRawBuffer() {
+ return buffer;
+ }
+
/**
* Discard the message buffer to reduce memory usage.
* <p>
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java
index f425e87618..a297d5776d 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalk.java
@@ -32,10 +32,13 @@ import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.AsyncObjectLoaderQueue;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.MutableObjectId;
+import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectIdOwnerMap;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
+import org.eclipse.jgit.lib.ProgressMonitor;
+import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
@@ -131,8 +134,17 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {
*/
static final int TOPO_DELAY = 1 << 5;
+ /**
+ * Temporary mark for use within {@link TopoNonIntermixSortGenerator}.
+ * <p>
+ * This mark indicates the commit has been queued for emission in
+ * {@link TopoSortGenerator} and can be produced. This mark is removed when
+ * the commit has been produced.
+ */
+ static final int TOPO_QUEUED = 1 << 6;
+
/** Number of flag bits we keep internal for our own use. See above flags. */
- static final int RESERVED_FLAGS = 6;
+ static final int RESERVED_FLAGS = 7;
private static final int APP_FLAGS = -1 & ~((1 << RESERVED_FLAGS) - 1);
@@ -172,6 +184,12 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {
boolean shallowCommitsInitialized;
+ private enum GetMergedIntoStrategy {
+ RETURN_ON_FIRST_FOUND,
+ RETURN_ON_FIRST_NOT_FOUND,
+ EVALUATE_ALL
+ }
+
/**
* Create a new revision walker for a given repository.
*
@@ -227,13 +245,13 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {
* if it cannot open any of the underlying indices.
*
* @since 5.4
+ * @deprecated use {@code ObjectReader#createReachabilityChecker(RevWalk)}
+ * instead.
*/
- public ReachabilityChecker createReachabilityChecker() throws IOException {
- if (reader.getBitmapIndex() != null) {
- return new BitmappedReachabilityChecker(this);
- }
-
- return new PedestrianReachabilityChecker(true, this);
+ @Deprecated
+ public final ReachabilityChecker createReachabilityChecker()
+ throws IOException {
+ return reader.createReachabilityChecker(this);
}
/**
@@ -415,6 +433,149 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {
}
}
+ /**
+ * Determine the Refs into which a commit is merged.
+ * <p>
+ * A commit is merged into a ref if we can find a path of commits that leads
+ * from that specific ref and ends at <code>commit</code>.
+ * <p>
+ *
+ * @param commit
+ * commit the caller thinks is reachable from <code>refs</code>.
+ * @param refs
+ * refs to start iteration from, and which is most likely a
+ * descendant (child) of <code>commit</code>.
+ * @return list of refs that are reachable from <code>commit</code>.
+ * @throws java.io.IOException
+ * a pack file or loose object could not be read.
+ * @since 5.12
+ */
+ public List<Ref> getMergedInto(RevCommit commit, Collection<Ref> refs)
+ throws IOException{
+ return getMergedInto(commit, refs, NullProgressMonitor.INSTANCE);
+ }
+
+ /**
+ * Determine the Refs into which a commit is merged.
+ * <p>
+ * A commit is merged into a ref if we can find a path of commits that leads
+ * from that specific ref and ends at <code>commit</code>.
+ * <p>
+ *
+ * @param commit
+ * commit the caller thinks is reachable from <code>refs</code>.
+ * @param refs
+ * refs to start iteration from, and which is most likely a
+ * descendant (child) of <code>commit</code>.
+ * @param monitor
+ * the callback for progress and cancellation
+ * @return list of refs that are reachable from <code>commit</code>.
+ * @throws java.io.IOException
+ * a pack file or loose object could not be read.
+ * @since 5.12
+ */
+ public List<Ref> getMergedInto(RevCommit commit, Collection<Ref> refs,
+ ProgressMonitor monitor) throws IOException{
+ return getMergedInto(commit, refs,
+ GetMergedIntoStrategy.EVALUATE_ALL,
+ monitor);
+ }
+
+ /**
+ * Determine if a <code>commit</code> is merged into any of the given
+ * <code>refs</code>.
+ *
+ * @param commit
+ * commit the caller thinks is reachable from <code>refs</code>.
+ * @param refs
+ * refs to start iteration from, and which is most likely a
+ * descendant (child) of <code>commit</code>.
+ * @return true if commit is merged into any of the refs; false otherwise.
+ * @throws java.io.IOException
+ * a pack file or loose object could not be read.
+ * @since 5.12
+ */
+ public boolean isMergedIntoAny(RevCommit commit, Collection<Ref> refs)
+ throws IOException {
+ return getMergedInto(commit, refs,
+ GetMergedIntoStrategy.RETURN_ON_FIRST_FOUND,
+ NullProgressMonitor.INSTANCE).size() > 0;
+ }
+
+ /**
+ * Determine if a <code>commit</code> is merged into all of the given
+ * <code>refs</code>.
+ *
+ * @param commit
+ * commit the caller thinks is reachable from <code>refs</code>.
+ * @param refs
+ * refs to start iteration from, and which is most likely a
+ * descendant (child) of <code>commit</code>.
+ * @return true if commit is merged into all of the refs; false otherwise.
+ * @throws java.io.IOException
+ * a pack file or loose object could not be read.
+ * @since 5.12
+ */
+ public boolean isMergedIntoAll(RevCommit commit, Collection<Ref> refs)
+ throws IOException {
+ return getMergedInto(commit, refs,
+ GetMergedIntoStrategy.RETURN_ON_FIRST_NOT_FOUND,
+ NullProgressMonitor.INSTANCE).size()
+ == refs.size();
+ }
+
+ @SuppressWarnings("rawtypes")
+ private List<Ref> getMergedInto(RevCommit needle, Collection<Ref> haystacks,
+ Enum returnStrategy, ProgressMonitor monitor) throws IOException {
+ List<Ref> result = new ArrayList<>();
+ List<RevCommit> uninteresting = new ArrayList<>();
+ RevFilter oldRF = filter;
+ TreeFilter oldTF = treeFilter;
+ try {
+ finishDelayedFreeFlags();
+ reset(~freeFlags & APP_FLAGS);
+ filter = RevFilter.ALL;
+ treeFilter = TreeFilter.ALL;
+ for (Ref r: haystacks) {
+ if (monitor.isCancelled()) {
+ return result;
+ }
+ monitor.update(1);
+ RevObject o = parseAny(r.getObjectId());
+ if (!(o instanceof RevCommit)) {
+ continue;
+ }
+ RevCommit c = (RevCommit) o;
+ resetRetain(RevFlag.UNINTERESTING);
+ markStart(c);
+ boolean commitFound = false;
+ RevCommit next;
+ while ((next = next()) != null) {
+ if (References.isSameObject(next, needle)) {
+ result.add(r);
+ if (returnStrategy == GetMergedIntoStrategy.RETURN_ON_FIRST_FOUND) {
+ return result;
+ }
+ commitFound = true;
+ break;
+ }
+ }
+ if(!commitFound){
+ markUninteresting(c);
+ uninteresting.add(c);
+ if (returnStrategy == GetMergedIntoStrategy.RETURN_ON_FIRST_NOT_FOUND) {
+ return result;
+ }
+ }
+ }
+ } finally {
+ roots.addAll(uninteresting);
+ filter = oldRF;
+ treeFilter = oldTF;
+ }
+ return result;
+ }
+
/**
* Pop the next most recent commit.
*
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalkUtils.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalkUtils.java
index 3feb9c5a45..e52e916318 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalkUtils.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevWalkUtils.java
@@ -159,15 +159,12 @@ public final class RevWalkUtils {
// Make sure commit is from the same RevWalk
commit = revWalk.parseCommit(commit.getId());
revWalk.reset();
- List<Ref> result = new ArrayList<>();
+ List<Ref> filteredRefs = new ArrayList<>();
monitor.beginTask(JGitText.get().searchForReachableBranches,
refs.size());
final int SKEW = 24*3600; // one day clock skew
for (Ref ref : refs) {
- if (monitor.isCancelled())
- return result;
- monitor.update(1);
RevObject maybehead = revWalk.parseAny(ref.getObjectId());
if (!(maybehead instanceof RevCommit))
continue;
@@ -179,9 +176,9 @@ public final class RevWalkUtils {
if (headCommit.getCommitTime() + SKEW < commit.getCommitTime())
continue;
- if (revWalk.isMergedInto(commit, headCommit))
- result.add(ref);
+ filteredRefs.add(ref);
}
+ List<Ref> result = revWalk.getMergedInto(commit, filteredRefs, monitor);
monitor.endTask();
return result;
}
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/StartGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/StartGenerator.java
index 2c1b0a59ee..bfcea6ea8f 100644
--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/StartGenerator.java
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/StartGenerator.java
@@ -135,8 +135,18 @@ class StartGenerator extends Generator {
}
if (walker.hasRevSort(RevSort.TOPO)
- && (g.outputType() & SORT_TOPO) == 0)
+ && walker.hasRevSort(RevSort.TOPO_KEEP_BRANCH_TOGETHER)) {
+ throw new IllegalStateException(JGitText
+ .get().cannotCombineTopoSortWithTopoKeepBranchTogetherSort);
+ }
+
+ if (walker.hasRevSort(RevSort.TOPO)
+ && (g.outputType() & SORT_TOPO) == 0) {
g = new TopoSortGenerator(g);
+ } else if (walker.hasRevSort(RevSort.TOPO_KEEP_BRANCH_TOGETHER)
+ && (g.outputType() & SORT_TOPO) == 0) {
+ g = new TopoNonIntermixSortGenerator(g);
+ }
if (walker.hasRevSort(RevSort.REVERSE))
g = new LIFORevQueue(g);
if (boundary)
diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoNonIntermixSortGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoNonIntermixSortGenerator.java
new file mode 100644
index 0000000000..4f6d417ed1
--- /dev/null
+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoNonIntermixSortGenerator.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2020, Google LLC. 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.revwalk;
+
+import java.io.IOException;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+
+/** Sorts commits in topological order without intermixing lines of history. */
+class TopoNonIntermixSortGenerator extends Generator {
+ private static final int TOPO_QUEUED = RevWalk.TOPO_QUEUED;
+
+ private final FIFORevQueue pending;
+
+ private final int outputType;
+
+ /**
+ * Create a new sorter and completely spin the generator.
+ * <p>
+ * When the constructor completes the supplied generator will have no
+ * commits remaining, as all of the commits will be held inside of this
+ * generator's internal buffer.
+ *
+ * @param s
+ * generator to pull all commits out of, and into this buffer.
+ * @throws MissingObjectException
+ * @throws IncorrectObjectTypeException
+ * @throws IOException
+ */
+ TopoNonIntermixSortGenerator(Generator s) throws MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ super(s.firstParent);
+ pending = new FIFORevQueue(firstParent);
+ outputType = s.outputType() | SORT_TOPO;
+ s.shareFreeList(pending);
+ for (;;) {
+ final RevCommit c = s.next();
+ if (c == null) {
+ break;
+ }
+ if ((c.flags & TOPO_QUEUED) == 0) {
+ for (RevCommit p : c.parents) {
+ p.inDegree++;
+
+ if (firstParent) {
+ break;
+ }
+ }
+ }
+ c.flags |= TOPO_QUEUED;
+ pending.add(c);
+ }
+ }
+
+ @Override
+ int outputType() {
+ return outputType;
+ }
+
+ @Override
+ void shareFreeList(BlockRevQueue q) {
+ q.shareFreeList(pending);
+ }
+
+ @Override
+ RevCommit next() throws MissingObjectException,
+ IncorrectObjectTypeException, IOException {
+ for (;;) {
+ final RevCommit c = pending.next();
+ if (c == null) {
+ return null;
+ }
+
+ if (c.inDegree > 0) {
+ // At least one of our children is missing. We delay
+ // production until all of our children are output.
+ //
+ continue;
+ }
+
+ if ((c.flags & TOPO_QUEUED) == 0) {
+ // c is a parent that already produced or a parent that
+ // was never in the priority queue and should never produce.
+ //
+ continue;
+ }
+
+ for (RevCommit p : c.parents) {
+ if (--p.inDegree == 0 && (p.flags & TOPO_QUEUED) != 0) {
+ // The parent has no unproduced interesting children. unpop
+ // the parent so it goes right behind this child. This means
+ // that this parent commit may appear in "pending" more than
+ // once, but this is safe since upon the second and
+ // subsequent iterations with this commit, it will no longer
+ // have TOPO_QUEUED set, and thus will be skipped.
+ //
+ pending.unpop(p);
+ }
+ if (firstParent) {
+ break;
+ }
+ }
+
+ c.flags &= ~TOPO_QUEUED;
+ return c;
+ }
+ }
+}