The Unified and Autonomous Development Platform
Modify jgit to be able to use our content upon merge conflict
Robin Shenb5de2da9a792
diff --git a/pom.xml b/pom.xmlindex c5e7b3ea5d..f22626b643 100644--- a/pom.xml+++ b/pom.xml@@ -581,7 +581,7 @@<wicketbootstrap.version>0.10.18</wicketbootstrap.version><lucene.version>7.1.0</lucene.version><shiro.version>1.4.2</shiro.version>- <jgit.version>5.2.0.201812061821-r</jgit.version>+ <jgit.version>5.7.0.202003110725-r</jgit.version><flexmark.version>0.18.3</flexmark.version><groovy.version>2.4.14</groovy.version><servlet.version>3.1.0</servlet.version>diff --git a/server-core/src/main/java/io/onedev/server/CoreModule.java b/server-core/src/main/java/io/onedev/server/CoreModule.javaindex 66e484e6c0..084ba8d048 100644--- a/server-core/src/main/java/io/onedev/server/CoreModule.java+++ b/server-core/src/main/java/io/onedev/server/CoreModule.java@@ -164,9 +164,9 @@ import io.onedev.server.git.GitSshCommandCreator;import io.onedev.server.git.config.GitConfig;import io.onedev.server.git.hookcallback.GitPostReceiveCallback;import io.onedev.server.git.hookcallback.GitPreReceiveCallback;-import io.onedev.server.infomanager.CodeCommentRelationInfoManager;+import io.onedev.server.infomanager.PullRequestInfoManager;import io.onedev.server.infomanager.CommitInfoManager;-import io.onedev.server.infomanager.DefaultCodeCommentRelationInfoManager;+import io.onedev.server.infomanager.DefaultPullRequestInfoManager;import io.onedev.server.infomanager.DefaultCommitInfoManager;import io.onedev.server.infomanager.DefaultUserInfoManager;import io.onedev.server.infomanager.UserInfoManager;@@ -375,7 +375,7 @@ public class CoreModule extends AbstractPluginModule {bind(PullRequestChangeManager.class).to(DefaultPullRequestChangeManager.class);bind(CodeCommentReplyManager.class).to(DefaultCodeCommentReplyManager.class);bind(AttachmentStorageManager.class).to(DefaultAttachmentStorageManager.class);- bind(CodeCommentRelationInfoManager.class).to(DefaultCodeCommentRelationInfoManager.class);+ bind(PullRequestInfoManager.class).to(DefaultPullRequestInfoManager.class);bind(CodeCommentRelationManager.class).to(DefaultCodeCommentRelationManager.class);bind(WorkExecutor.class).to(DefaultWorkExecutor.class);bind(PullRequestNotificationManager.class);diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/PullRequestManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/PullRequestManager.javaindex 8c3f6141be..d5db7d2405 100644--- a/server-core/src/main/java/io/onedev/server/entitymanager/PullRequestManager.java+++ b/server-core/src/main/java/io/onedev/server/entitymanager/PullRequestManager.java@@ -80,5 +80,5 @@ public interface PullRequestManager extends EntityManager<PullRequest> {int count(@Nullable Project targetProject, EntityCriteria<PullRequest> requestCriteria);List<PullRequest> query(Project targetProject, String term, int count);-+}diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.javaindex 2201cb226b..27612d31eb 100644--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java@@ -1094,7 +1094,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequestPullRequestUpdate update = new PullRequestUpdate();request.addUpdate(update);update.setRequest(request);- update.setHeadCommitHash(request.getHeadCommitHash());+ update.setRequestHead(request.getHeadCommitHash());update.setMergeBaseCommitHash(request.getBaseCommitHash());request.setMergeStrategy(mergeStrategy);open(request);diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestUpdateManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestUpdateManager.javaindex fb6dd43a34..c8948bc11f 100644--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestUpdateManager.java+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestUpdateManager.java@@ -57,7 +57,7 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullRPullRequestUpdate update = new PullRequestUpdate();update.setRequest(request);- update.setHeadCommitHash(request.getHeadCommitHash());+ update.setRequestHead(request.getHeadCommitHash());update.setMergeBaseCommitHash(mergeBase.name());request.addUpdate(update);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.javaindex 7b55b82997..99dc5c47b1 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@@ -292,12 +292,12 @@ public class GitUtils {* case, these two commits can not be merged*/@Nullable- public static ObjectId getMergeBase(Repository repository, ObjectId commit1, ObjectId commit2) {+ 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(commit1));- revWalk.markStart(revWalk.parseCommit(commit2));+ revWalk.markStart(revWalk.parseCommit(commitId1));+ revWalk.markStart(revWalk.parseCommit(commitId2));RevCommit mergeBase = revWalk.next();return mergeBase!=null?mergeBase.copy():null;} catch (IOException e) {@@ -419,12 +419,15 @@ public class GitUtils {}@Nullable- public static ObjectId merge(Repository repository, ObjectId source, ObjectId target,- boolean squash, PersonIdent committer, PersonIdent author, String commitMessage) {+ 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(source);- RevCommit targetCommit = revWalk.parseCommit(target);+ 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();@@ -444,6 +447,8 @@ public class GitUtils {}} catch (IOException e) {throw new RuntimeException(e);+ } finally {+ UseOursOnConflict.set(prevUseOursOnConflict);}}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.javanew file mode 100644index 0000000000..82a7f35194--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/git/UseOursOnConflict.java@@ -0,0 +1,23 @@+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/git/command/CheckoutCommand.java b/server-core/src/main/java/io/onedev/server/git/command/CheckoutCommand.javadeleted file mode 100644index c6d715eb2e..0000000000--- a/server-core/src/main/java/io/onedev/server/git/command/CheckoutCommand.java+++ /dev/null@@ -1,56 +0,0 @@-package io.onedev.server.git.command;--import java.io.File;-import java.util.Map;--import javax.annotation.Nullable;--import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.common.base.Preconditions;--import io.onedev.commons.utils.command.Commandline;-import io.onedev.commons.utils.command.LineConsumer;--public class CheckoutCommand extends GitCommand<Void> {-- private static final Logger logger = LoggerFactory.getLogger(CheckoutCommand.class);-- private String refspec;-- public CheckoutCommand(File gitDir, @Nullable Map<String, String> environments) {- super(gitDir, environments);- }-- public CheckoutCommand refspec(String refspec) {- this.refspec = refspec;- return this;- }-- @Override- public Void call() {- Preconditions.checkNotNull(refspec, "refspec param has to be specified.");-- Commandline cmd = cmd().addArgs("checkout", "--quiet", refspec);-- cmd.execute(new LineConsumer() {-- @Override- public void consume(String line) {- logger.trace(line);- }-- }, new LineConsumer() {-- @Override- public void consume(String line) {- logger.error(line);- }-- }).checkReturnCode();-- return null;- }--}diff --git a/server-core/src/main/java/io/onedev/server/git/command/CleanCommand.java b/server-core/src/main/java/io/onedev/server/git/command/CleanCommand.javadeleted file mode 100644index 845fe17a8b..0000000000--- a/server-core/src/main/java/io/onedev/server/git/command/CleanCommand.java+++ /dev/null@@ -1,52 +0,0 @@-package io.onedev.server.git.command;--import java.io.File;--import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import io.onedev.commons.utils.command.Commandline;-import io.onedev.commons.utils.command.LineConsumer;--public class CleanCommand extends GitCommand<Void> {-- private static final Logger logger = LoggerFactory.getLogger(CleanCommand.class);-- private String[] options;-- public CleanCommand(final File gitDir) {- super(gitDir);- }-- public CleanCommand options(String...options) {- this.options = options;- return this;- }-- @Override- public Void call() {- Commandline cmd = cmd().addArgs("clean");-- if (options != null)- cmd.addArgs(options);-- cmd.execute(new LineConsumer() {-- @Override- public void consume(String line) {- logger.trace(line);- }-- }, new LineConsumer() {-- @Override- public void consume(String line) {- logger.error(line);- }-- }).checkReturnCode();-- return null;- }--}diff --git a/server-core/src/main/java/io/onedev/server/git/command/InitCommand.java b/server-core/src/main/java/io/onedev/server/git/command/InitCommand.javadeleted file mode 100644index 777cfadb14..0000000000--- a/server-core/src/main/java/io/onedev/server/git/command/InitCommand.java+++ /dev/null@@ -1,72 +0,0 @@-package io.onedev.server.git.command;--import java.io.File;--import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.common.base.Preconditions;--import io.onedev.commons.utils.command.Commandline;-import io.onedev.commons.utils.command.LineConsumer;--public class InitCommand extends GitCommand<Void> {-- private static final Logger logger = LoggerFactory.getLogger(InitCommand.class);-- private String from;-- private String[] refspec = new String[0];-- public InitCommand(final File gitDir) {- super(gitDir);- }-- public InitCommand from(String from) {- this.from = from;- return this;- }-- public InitCommand refspec(String... refspec) {- this.refspec = refspec;- return this;- }-- @Override- public Void call() {- Preconditions.checkNotNull(from, "from param has to be specified.");-- Commandline cmd = cmd().addArgs("fetch");- cmd.addArgs(from);- cmd.addArgs("--force");-- for (String each: refspec)- cmd.addArgs(each);-- cmd.execute(new LineConsumer() {-- @Override- public void consume(String line) {- logger.trace(line);- }-- }, new LineConsumer() {-- @Override- public void consume(String line) {- if (line.startsWith("From ")- || line.startsWith(" * branch")- || line.startsWith(" * [new ref]")- || line.contains("..") && line.contains("->")) {- logger.info(line);- } else {- logger.error(line);- }- }-- }).checkReturnCode();-- return null;- }--}diff --git a/server-core/src/main/java/io/onedev/server/infomanager/CodeCommentRelationInfoManager.java b/server-core/src/main/java/io/onedev/server/infomanager/CodeCommentRelationInfoManager.javadeleted file mode 100644index 703935251f..0000000000--- a/server-core/src/main/java/io/onedev/server/infomanager/CodeCommentRelationInfoManager.java+++ /dev/null@@ -1,13 +0,0 @@-package io.onedev.server.infomanager;--import java.util.Collection;--import org.eclipse.jgit.lib.ObjectId;--import io.onedev.server.model.Project;--public interface CodeCommentRelationInfoManager {-- public Collection<Long> getPullRequestIds(Project project, ObjectId commitId);--}diff --git a/server-core/src/main/java/io/onedev/server/infomanager/DefaultCodeCommentRelationInfoManager.java b/server-core/src/main/java/io/onedev/server/infomanager/DefaultCodeCommentRelationInfoManager.javadeleted file mode 100644index 6238eb81bc..0000000000--- a/server-core/src/main/java/io/onedev/server/infomanager/DefaultCodeCommentRelationInfoManager.java+++ /dev/null@@ -1,348 +0,0 @@-package io.onedev.server.infomanager;--import java.io.File;-import java.io.Serializable;-import java.util.Collection;-import java.util.HashMap;-import java.util.HashSet;-import java.util.List;-import java.util.Map;-import java.util.Set;-import java.util.concurrent.Callable;--import javax.inject.Inject;-import javax.inject.Singleton;--import org.apache.commons.lang3.SerializationUtils;-import org.eclipse.jgit.lib.ObjectId;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import io.onedev.commons.launcher.loader.Listen;-import io.onedev.commons.utils.FileUtils;-import io.onedev.server.entitymanager.CodeCommentManager;-import io.onedev.server.entitymanager.CodeCommentRelationManager;-import io.onedev.server.entitymanager.ProjectManager;-import io.onedev.server.entitymanager.PullRequestManager;-import io.onedev.server.entitymanager.PullRequestUpdateManager;-import io.onedev.server.event.entity.EntityPersisted;-import io.onedev.server.event.entity.EntityRemoved;-import io.onedev.server.event.system.SystemStarted;-import io.onedev.server.model.CodeComment;-import io.onedev.server.model.CodeComment.ComparingInfo;-import io.onedev.server.model.CodeCommentRelation;-import io.onedev.server.model.Project;-import io.onedev.server.model.PullRequest;-import io.onedev.server.model.PullRequestUpdate;-import io.onedev.server.persistence.SessionManager;-import io.onedev.server.persistence.TransactionManager;-import io.onedev.server.persistence.annotation.Sessional;-import io.onedev.server.persistence.annotation.Transactional;-import io.onedev.server.storage.StorageManager;-import io.onedev.server.util.concurrent.Prioritized;-import io.onedev.server.util.work.BatchWorkManager;-import io.onedev.server.util.work.BatchWorker;-import jetbrains.exodus.ArrayByteIterable;-import jetbrains.exodus.ByteIterable;-import jetbrains.exodus.env.Environment;-import jetbrains.exodus.env.Store;-import jetbrains.exodus.env.Transaction;-import jetbrains.exodus.env.TransactionalComputable;-import jetbrains.exodus.env.TransactionalExecutable;--@Singleton-public class DefaultCodeCommentRelationInfoManager extends AbstractEnvironmentManager- implements CodeCommentRelationInfoManager {-- private static final int INFO_VERSION = 6;-- private static final int BATCH_SIZE = 5000;-- private static final Logger logger = LoggerFactory.getLogger(DefaultCodeCommentRelationInfoManager.class);-- private static final String INFO_DIR = "codeCommentRelation";-- private static final String DEFAULT_STORE = "default";-- private static final String CODE_COMMENT_STORE = "codeComment";-- private static final String PULL_REQUEST_STORE = "pullRequest";-- private static final ByteIterable LAST_PULL_REQUEST_UPDATE_KEY = new StringByteIterable("lastPullRequestUpdate");-- private static final ByteIterable LAST_CODE_COMMENT_KEY = new StringByteIterable("lastCodeComment");-- private static final int PRIORITY = 100;-- private final StorageManager storageManager;-- private final BatchWorkManager batchWorkManager;-- private final ProjectManager projectManager;-- private final PullRequestUpdateManager pullRequestUpdateManager;-- private final PullRequestManager pullRequestManager;-- private final CodeCommentRelationManager codeCommentRelationManager;-- private final SessionManager sessionManager;-- private final CodeCommentManager codeCommentManager;-- private final TransactionManager transactionManager;-- @Inject- public DefaultCodeCommentRelationInfoManager(TransactionManager transactionManager, ProjectManager projectManager,- StorageManager storageManager, PullRequestUpdateManager pullRequestUpdateManager,- CodeCommentManager codeCommentManager, BatchWorkManager batchWorkManager, SessionManager sessionManager,- PullRequestManager pullRequestManager, CodeCommentRelationManager codeCommentRelationManager) {- this.projectManager = projectManager;- this.storageManager = storageManager;- this.pullRequestUpdateManager = pullRequestUpdateManager;- this.codeCommentManager = codeCommentManager;- this.batchWorkManager = batchWorkManager;- this.sessionManager = sessionManager;- this.pullRequestManager = pullRequestManager;- this.codeCommentRelationManager = codeCommentRelationManager;- this.transactionManager = transactionManager;- }-- private BatchWorker getBatchWorker(Long projectId) {- return new BatchWorker("project-" + projectId + "-collectCodeCommentRelationInfo") {-- @Override- public void doWorks(Collection<Prioritized> works) {- boolean hasMore;- do {- // do the work batch by batch to avoid consuming too much memory- hasMore = sessionManager.call(new Callable<Boolean>() {-- @Override- public Boolean call() throws Exception {- return collect(projectManager.load(projectId));- }-- });- } while (hasMore);- }-- };- }-- @Transactional- @Listen- public void on(EntityRemoved event) {- if (event.getEntity() instanceof Project) {- Long projectId = event.getEntity().getId();- removeEnv(projectId.toString());- }- }-- private boolean collect(Project project) {- logger.debug("Collecting code comment relation info (project: {})...", project);-- Environment env = getEnv(project.getId().toString());- Store defaultStore = getStore(env, DEFAULT_STORE);- Store codeCommentStore = getStore(env, CODE_COMMENT_STORE);- Store pullRequestStore = getStore(env, PULL_REQUEST_STORE);-- Long lastPullRequestUpdateId = env.computeInTransaction(new TransactionalComputable<Long>() {-- @Override- public Long compute(Transaction txn) {- return readLong(defaultStore, txn, LAST_PULL_REQUEST_UPDATE_KEY, 0);- }-- });-- List<PullRequestUpdate> unprocessedPullRequestUpdates = pullRequestUpdateManager.queryAfter(- project, lastPullRequestUpdateId, BATCH_SIZE);- for (PullRequestUpdate update: unprocessedPullRequestUpdates) {- env.executeInTransaction(new TransactionalExecutable() {-- @Override- public void execute(Transaction txn) {- PullRequest request = update.getRequest();- if (request.isValid()) {- for (ObjectId commit: update.getCommits()) {- ByteIterable commitKey = new CommitByteIterable(commit);-- Collection<Long> pullRequestIds = readLongs(pullRequestStore, txn, commitKey);- pullRequestIds.add(update.getRequest().getId());-- writeLongs(pullRequestStore, txn, commitKey, pullRequestIds);-- Map<Long, ComparingInfo> comments = getCodeCommentComparingInfos(codeCommentStore, txn, commitKey);- Set<Long> commentIdsToRemove = new HashSet<>();- for (Map.Entry<Long, ComparingInfo> entry: comments.entrySet()) {- if (request.getRequestComparingInfo(entry.getValue()) != null) {- Long commentId = entry.getKey();- CodeComment comment = codeCommentManager.get(commentId);- if (comment != null) {- if (codeCommentRelationManager.find(request, comment) == null) {- CodeCommentRelation relation = new CodeCommentRelation();- relation.setComment(comment);- relation.setRequest(request);- codeCommentRelationManager.save(relation);- }- } else {- commentIdsToRemove.add(commentId);- }- }- }- if (!commentIdsToRemove.isEmpty()) {- comments.keySet().removeAll(commentIdsToRemove);- codeCommentStore.put(txn, commitKey,- new ArrayByteIterable(SerializationUtils.serialize((Serializable) comments)));- }- }- }- defaultStore.put(txn, LAST_PULL_REQUEST_UPDATE_KEY, new LongByteIterable(update.getId()));- }-- });- }-- Long lastCodeCommentId = env.computeInTransaction(new TransactionalComputable<Long>() {-- @Override- public Long compute(final Transaction txn) {- return readLong(defaultStore, txn, LAST_CODE_COMMENT_KEY, 0);- }-- });-- List<CodeComment> unprocessedCodeComments = codeCommentManager.queryAfter(project,- lastCodeCommentId, BATCH_SIZE);- for (CodeComment comment: unprocessedCodeComments) {- if (comment.isValid()) {- env.executeInTransaction(new TransactionalExecutable() {-- private void associateCommentWithCommit(Transaction txn, String commit) {- ObjectId commitId = ObjectId.fromString(commit);- ByteIterable commitKey = new CommitByteIterable(commitId);-- Map<Long, ComparingInfo> comments = getCodeCommentComparingInfos(codeCommentStore, txn, commitKey);- comments.put(comment.getId(), comment.getComparingInfo());- codeCommentStore.put(txn, commitKey,- new ArrayByteIterable(SerializationUtils.serialize((Serializable) comments)));-- Collection<Long> pullRequestIds = readLongs(pullRequestStore, txn, commitKey);-- Set<Long> pullRequestIdsToRemove = new HashSet<>();- for (Long pullRequestId: pullRequestIds) {- PullRequest request = pullRequestManager.get(pullRequestId);- if (request != null && request.isValid()) {- if (request.getRequestComparingInfo(comment.getComparingInfo()) != null- && codeCommentRelationManager.find(request, comment) == null) {- CodeCommentRelation relation = new CodeCommentRelation();- relation.setComment(comment);- relation.setRequest(request);- codeCommentRelationManager.save(relation);- }- } else {- pullRequestIdsToRemove.add(pullRequestId);- }- }- if (!pullRequestIdsToRemove.isEmpty()) {- pullRequestIds.removeAll(pullRequestIdsToRemove);- writeLongs(pullRequestStore, txn, commitKey, pullRequestIds);- }- }-- @Override- public void execute(Transaction txn) {- associateCommentWithCommit(txn, comment.getMarkPos().getCommit());- String compareCommit = comment.getCompareContext().getCompareCommit();- if (!comment.getMarkPos().getCommit().equals(compareCommit)- && project.getRepository().hasObject(ObjectId.fromString(compareCommit)))- associateCommentWithCommit(txn, comment.getCompareContext().getCompareCommit());- defaultStore.put(txn, LAST_CODE_COMMENT_KEY, new LongByteIterable(comment.getId()));- }-- });- }- }- logger.debug("Collected code comment relation info (project: {})", project);-- return unprocessedPullRequestUpdates.size() == BATCH_SIZE || unprocessedCodeComments.size() == BATCH_SIZE;- }-- @Override- public Collection<Long> getPullRequestIds(Project project, ObjectId commitId) {- Environment env = getEnv(project.getId().toString());- Store store = getStore(env, PULL_REQUEST_STORE);-- return env.computeInTransaction(new TransactionalComputable<Collection<Long>>() {-- @Override- public Collection<Long> compute(Transaction txn) {- return readLongs(store, txn, new CommitByteIterable(commitId));- }-- });-- }-- @SuppressWarnings("unchecked")- private Map<Long, ComparingInfo> getCodeCommentComparingInfos(Store store, Transaction txn, ByteIterable commitKey) {- byte[] valueBytes = readBytes(store, txn, commitKey);- if (valueBytes != null) {- return (Map<Long, ComparingInfo>) SerializationUtils.deserialize(valueBytes);- } else {- return new HashMap<>();- }- }-- @Transactional- @Listen- public void on(EntityPersisted event) {- if (event.isNew()) {- if (event.getEntity() instanceof PullRequestUpdate) {- Long projectId = ((PullRequestUpdate) event.getEntity()).getRequest().getTargetProject().getId();- transactionManager.runAfterCommit(new Runnable() {-- @Override- public void run() {- batchWorkManager.submit(getBatchWorker(projectId), new Prioritized(PRIORITY));- }-- });- } else if (event.getEntity() instanceof CodeComment) {- Long projectId = ((CodeComment)event.getEntity()).getProject().getId();- transactionManager.runAfterCommit(new Runnable() {-- @Override- public void run() {- batchWorkManager.submit(getBatchWorker(projectId), new Prioritized(PRIORITY));- }-- });- }- }- }-- @Sessional- @Listen- public void on(SystemStarted event) {- for (Project project: projectManager.query()) {- checkVersion(project.getId().toString());- batchWorkManager.submit(getBatchWorker(project.getId()), new Prioritized(PRIORITY));- }- }-- @Override- protected File getEnvDir(String envKey) {- File infoDir = new File(storageManager.getProjectInfoDir(Long.valueOf(envKey)), INFO_DIR);- if (!infoDir.exists())- FileUtils.createDir(infoDir);- return infoDir;- }-- @Override- protected int getEnvVersion() {- return INFO_VERSION;- }--}diff --git a/server-core/src/main/java/io/onedev/server/infomanager/DefaultCommitInfoManager.java b/server-core/src/main/java/io/onedev/server/infomanager/DefaultCommitInfoManager.javaindex 4c5cd01ba0..e747e01cc5 100644--- a/server-core/src/main/java/io/onedev/server/infomanager/DefaultCommitInfoManager.java+++ b/server-core/src/main/java/io/onedev/server/infomanager/DefaultCommitInfoManager.java@@ -330,8 +330,12 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemebyte[] lastCommitBytes = readBytes(defaultStore, txn, LAST_COMMIT_KEY);if (lastCommitBytes != null) {lastCommitId = ObjectId.fromRaw(lastCommitBytes);- if (!repository.hasObject(lastCommitId))- lastCommitId = null;+ try {+ if (!repository.getObjectDatabase().has(lastCommitId))+ lastCommitId = null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }} else {lastCommitId = null;}@@ -584,8 +588,12 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemebyte[] lastCommitBytes = readBytes(defaultStore, txn, LAST_COMMIT_OF_CONTRIBS_KEY);if (lastCommitBytes != null) {lastCommitId = ObjectId.fromRaw(lastCommitBytes);- if (!repository.hasObject(lastCommitId))- lastCommitId = null;+ try {+ if (!repository.getObjectDatabase().has(lastCommitId))+ lastCommitId = null;+ } catch (IOException e) {+ throw new RuntimeException(e);+ }} else {lastCommitId = null;}@@ -686,10 +694,14 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemepublic ObjectId compute(Transaction txn) {byte[] lastCommitBytes = readBytes(defaultStore, txn, LAST_COMMIT_OF_LINE_STATS_KEY);if (lastCommitBytes != null) {- ObjectId lastCommitId = ObjectId.fromRaw(lastCommitBytes);- if (repository.hasObject(lastCommitId)- && GitUtils.isMergedInto(repository, null, lastCommitId, commitId)) {- return lastCommitId;+ try {+ ObjectId lastCommitId = ObjectId.fromRaw(lastCommitBytes);+ if (repository.getObjectDatabase().has(lastCommitId)+ && GitUtils.isMergedInto(repository, null, lastCommitId, commitId)) {+ return lastCommitId;+ }+ } catch (IOException e) {+ throw new RuntimeException(e);}}return null;diff --git a/server-core/src/main/java/io/onedev/server/infomanager/DefaultPullRequestInfoManager.java b/server-core/src/main/java/io/onedev/server/infomanager/DefaultPullRequestInfoManager.javanew file mode 100644index 0000000000..3cc4a42006--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/infomanager/DefaultPullRequestInfoManager.java@@ -0,0 +1,269 @@+package io.onedev.server.infomanager;++import java.io.File;+import java.util.Collection;+import java.util.List;+import java.util.concurrent.Callable;++import javax.inject.Inject;+import javax.inject.Singleton;++import org.eclipse.jgit.lib.ObjectId;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import io.onedev.commons.launcher.loader.Listen;+import io.onedev.commons.utils.FileUtils;+import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.entitymanager.PullRequestUpdateManager;+import io.onedev.server.event.entity.EntityPersisted;+import io.onedev.server.event.entity.EntityRemoved;+import io.onedev.server.event.system.SystemStarted;+import io.onedev.server.model.CodeComment;+import io.onedev.server.model.Project;+import io.onedev.server.model.PullRequest;+import io.onedev.server.model.PullRequestUpdate;+import io.onedev.server.persistence.SessionManager;+import io.onedev.server.persistence.TransactionManager;+import io.onedev.server.persistence.annotation.Sessional;+import io.onedev.server.persistence.annotation.Transactional;+import io.onedev.server.storage.StorageManager;+import io.onedev.server.util.concurrent.Prioritized;+import io.onedev.server.util.work.BatchWorkManager;+import io.onedev.server.util.work.BatchWorker;+import jetbrains.exodus.ArrayByteIterable;+import jetbrains.exodus.ByteIterable;+import jetbrains.exodus.env.Environment;+import jetbrains.exodus.env.Store;+import jetbrains.exodus.env.Transaction;+import jetbrains.exodus.env.TransactionalComputable;+import jetbrains.exodus.env.TransactionalExecutable;++@Singleton+public class DefaultPullRequestInfoManager extends AbstractEnvironmentManager+ implements PullRequestInfoManager {++ private static final int INFO_VERSION = 6;++ private static final int BATCH_SIZE = 5000;++ private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestInfoManager.class);++ private static final String INFO_DIR = "pullRequest";++ private static final String DEFAULT_STORE = "default";++ private static final String COMMIT_TO_IDS_STORE = "commitToIds";++ private static final String MERGE_COMMITS_STORE = "mergeCommits";++ private static final ByteIterable LAST_PULL_REQUEST_UPDATE_KEY = new StringByteIterable("lastPullRequestUpdate");++ private static final int PRIORITY = 100;++ private final StorageManager storageManager;++ private final BatchWorkManager batchWorkManager;++ private final ProjectManager projectManager;++ private final PullRequestUpdateManager pullRequestUpdateManager;++ private final SessionManager sessionManager;++ private final TransactionManager transactionManager;++ @Inject+ public DefaultPullRequestInfoManager(TransactionManager transactionManager, ProjectManager projectManager,+ StorageManager storageManager, PullRequestUpdateManager pullRequestUpdateManager,+ BatchWorkManager batchWorkManager, SessionManager sessionManager) {+ this.projectManager = projectManager;+ this.storageManager = storageManager;+ this.pullRequestUpdateManager = pullRequestUpdateManager;+ this.batchWorkManager = batchWorkManager;+ this.sessionManager = sessionManager;+ this.transactionManager = transactionManager;+ }++ private BatchWorker getBatchWorker(Long projectId) {+ return new BatchWorker("project-" + projectId + "-collectPullRequestInfo") {++ @Override+ public void doWorks(Collection<Prioritized> works) {+ boolean hasMore;+ do {+ // do the work batch by batch to avoid consuming too much memory+ hasMore = sessionManager.call(new Callable<Boolean>() {++ @Override+ public Boolean call() throws Exception {+ return collect(projectManager.load(projectId));+ }++ });+ } while (hasMore);+ }++ };+ }++ @Transactional+ @Listen+ public void on(EntityRemoved event) {+ if (event.getEntity() instanceof Project) {+ Long projectId = event.getEntity().getId();+ removeEnv(projectId.toString());+ }+ }++ private boolean collect(Project project) {+ logger.debug("Collecting pull request info (project: {})...", project);++ Environment env = getEnv(project.getId().toString());+ Store defaultStore = getStore(env, DEFAULT_STORE);+ Store commitToIdsStore = getStore(env, COMMIT_TO_IDS_STORE);++ Long lastPullRequestUpdateId = env.computeInTransaction(new TransactionalComputable<Long>() {++ @Override+ public Long compute(Transaction txn) {+ return readLong(defaultStore, txn, LAST_PULL_REQUEST_UPDATE_KEY, 0);+ }++ });++ List<PullRequestUpdate> unprocessedPullRequestUpdates = pullRequestUpdateManager.queryAfter(+ project, lastPullRequestUpdateId, BATCH_SIZE);+ env.executeInTransaction(new TransactionalExecutable() {++ @Override+ public void execute(Transaction txn) {+ PullRequestUpdate lastUpdate = null;+ for (PullRequestUpdate update: unprocessedPullRequestUpdates) {+ PullRequest request = update.getRequest();+ if (request.isValid()) {+ for (ObjectId commit: update.getCommits()) {+ ByteIterable commitKey = new CommitByteIterable(commit);+ Collection<Long> pullRequestIds = readLongs(commitToIdsStore, txn, commitKey);+ pullRequestIds.add(update.getRequest().getId());+ writeLongs(commitToIdsStore, txn, commitKey, pullRequestIds);+ }+ }+ lastUpdate = update;+ }+ if (lastUpdate != null)+ defaultStore.put(txn, LAST_PULL_REQUEST_UPDATE_KEY, new LongByteIterable(lastUpdate.getId()));+ }++ });+ logger.debug("Collected pull request info (project: {})", project);++ return unprocessedPullRequestUpdates.size() == BATCH_SIZE;+ }++ @Override+ public Collection<Long> getPullRequestIds(Project project, ObjectId commitId) {+ Environment env = getEnv(project.getId().toString());+ Store store = getStore(env, COMMIT_TO_IDS_STORE);++ return env.computeInTransaction(new TransactionalComputable<Collection<Long>>() {++ @Override+ public Collection<Long> compute(Transaction txn) {+ return readLongs(store, txn, new CommitByteIterable(commitId));+ }++ });+ }++ @Transactional+ @Listen+ public void on(EntityPersisted event) {+ if (event.isNew()) {+ if (event.getEntity() instanceof PullRequestUpdate) {+ Long projectId = ((PullRequestUpdate) event.getEntity()).getRequest().getTargetProject().getId();+ transactionManager.runAfterCommit(new Runnable() {++ @Override+ public void run() {+ batchWorkManager.submit(getBatchWorker(projectId), new Prioritized(PRIORITY));+ }++ });+ } else if (event.getEntity() instanceof CodeComment) {+ Long projectId = ((CodeComment)event.getEntity()).getProject().getId();+ transactionManager.runAfterCommit(new Runnable() {++ @Override+ public void run() {+ batchWorkManager.submit(getBatchWorker(projectId), new Prioritized(PRIORITY));+ }++ });+ }+ }+ }++ @Sessional+ @Listen+ public void on(SystemStarted event) {+ for (Project project: projectManager.query()) {+ checkVersion(project.getId().toString());+ batchWorkManager.submit(getBatchWorker(project.getId()), new Prioritized(PRIORITY));+ }+ }++ @Override+ protected File getEnvDir(String envKey) {+ File infoDir = new File(storageManager.getProjectInfoDir(Long.valueOf(envKey)), INFO_DIR);+ if (!infoDir.exists())+ FileUtils.createDir(infoDir);+ return infoDir;+ }++ @Override+ protected int getEnvVersion() {+ return INFO_VERSION;+ }++ @Override+ public ObjectId readMergeCommitId(Project project, ObjectId commitId1, ObjectId commitId2) {+ Environment env = getEnv(project.getId().toString());+ Store store = getStore(env, MERGE_COMMITS_STORE);++ return env.computeInTransaction(new TransactionalComputable<ObjectId>() {++ @Override+ public ObjectId compute(Transaction txn) {+ byte[] keyBytes = new byte[40];+ commitId1.copyRawTo(keyBytes, 0);+ commitId2.copyRawTo(keyBytes, 20);+ byte[] valueBytes = readBytes(store, txn, new ArrayByteIterable(keyBytes));+ if (valueBytes != null)+ return ObjectId.fromRaw(valueBytes);+ else+ return null;+ }++ });+ }++ @Override+ public void writeMergeCommitId(Project project, ObjectId commitId1, ObjectId commitId2, ObjectId mergeCommitId) {+ Environment env = getEnv(project.getId().toString());+ Store store = getStore(env, MERGE_COMMITS_STORE);++ env.executeInTransaction(new TransactionalExecutable() {++ @Override+ public void execute(Transaction txn) {+ byte[] keyBytes = new byte[40];+ commitId1.copyRawTo(keyBytes, 0);+ commitId2.copyRawTo(keyBytes, 20);+ store.put(txn, new ArrayByteIterable(keyBytes), new CommitByteIterable(mergeCommitId));+ }++ });+ }++}diff --git a/server-core/src/main/java/io/onedev/server/infomanager/PullRequestInfoManager.java b/server-core/src/main/java/io/onedev/server/infomanager/PullRequestInfoManager.javanew file mode 100644index 0000000000..64a3e6fabf--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/infomanager/PullRequestInfoManager.java@@ -0,0 +1,20 @@+package io.onedev.server.infomanager;++import java.util.Collection;++import javax.annotation.Nullable;++import org.eclipse.jgit.lib.ObjectId;++import io.onedev.server.model.Project;++public interface PullRequestInfoManager {++ Collection<Long> getPullRequestIds(Project project, ObjectId commitId);++ @Nullable+ ObjectId readMergeCommitId(Project project, ObjectId commitId1, ObjectId commitId2);++ void writeMergeCommitId(Project project, ObjectId commitId1, ObjectId commitId2, ObjectId mergeCommit);++}diff --git a/server-core/src/main/java/io/onedev/server/model/Build.java b/server-core/src/main/java/io/onedev/server/model/Build.javaindex 802bc2bb52..194f586f9c 100644--- a/server-core/src/main/java/io/onedev/server/model/Build.java+++ b/server-core/src/main/java/io/onedev/server/model/Build.java@@ -913,7 +913,11 @@ public class Build extends AbstractEntity implements Referenceable {}public boolean isValid() {- return getProject().getRepository().hasObject(ObjectId.fromString(getCommitHash()));+ try {+ return getProject().getRepository().getObjectDatabase().has(ObjectId.fromString(getCommitHash()));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }}@Nullablediff --git a/server-core/src/main/java/io/onedev/server/model/CodeComment.java b/server-core/src/main/java/io/onedev/server/model/CodeComment.javaindex 085168fa96..045aca7a7d 100644--- a/server-core/src/main/java/io/onedev/server/model/CodeComment.java+++ b/server-core/src/main/java/io/onedev/server/model/CodeComment.java@@ -122,6 +122,10 @@ public class CodeComment extends AbstractEntity implements AttachmentStorageSupp@Embeddedprivate CompareContext compareContext;++ @ManyToOne(fetch=FetchType.LAZY)+ @JoinColumn(nullable=false)+ private PullRequest request;@OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)private Collection<CodeCommentReply> replies = new ArrayList<>();@@ -144,6 +148,15 @@ public class CodeComment extends AbstractEntity implements AttachmentStorageSuppthis.project = project;}+ @Nullable+ public PullRequest getRequest() {+ return request;+ }++ public void setRequest(PullRequest request) {+ this.request = request;+ }+@Nullablepublic User getUser() {return user;@@ -249,7 +262,11 @@ public class CodeComment extends AbstractEntity implements AttachmentStorageSupp}public boolean isValid() {- return project.getRepository().hasObject(ObjectId.fromString(markPos.getCommit()));+ try {+ return project.getRepository().getObjectDatabase().has(ObjectId.fromString(markPos.getCommit()));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }}@Nullablediff --git a/server-core/src/main/java/io/onedev/server/model/Issue.java b/server-core/src/main/java/io/onedev/server/model/Issue.javaindex 2b31a67449..d36d67ac17 100644--- a/server-core/src/main/java/io/onedev/server/model/Issue.java+++ b/server-core/src/main/java/io/onedev/server/model/Issue.java@@ -54,7 +54,7 @@ import io.onedev.server.entitymanager.GroupManager;import io.onedev.server.entitymanager.PullRequestManager;import io.onedev.server.entitymanager.SettingManager;import io.onedev.server.entitymanager.UserManager;-import io.onedev.server.infomanager.CodeCommentRelationInfoManager;+import io.onedev.server.infomanager.PullRequestInfoManager;import io.onedev.server.infomanager.CommitInfoManager;import io.onedev.server.infomanager.UserInfoManager;import io.onedev.server.model.support.EntityWatch;@@ -621,7 +621,7 @@ public class Issue extends AbstractEntity implements Referenceable, AttachmentStif (pullRequests == null) {pullRequests = new ArrayList<>();- CodeCommentRelationInfoManager codeCommentRelationInfoManager = OneDev.getInstance(CodeCommentRelationInfoManager.class);+ PullRequestInfoManager codeCommentRelationInfoManager = OneDev.getInstance(PullRequestInfoManager.class);Collection<Long> pullRequestIds = new HashSet<>();for (ObjectId commit: getCommits())pullRequestIds.addAll(codeCommentRelationInfoManager.getPullRequestIds(getProject(), commit));diff --git a/server-core/src/main/java/io/onedev/server/model/PullRequest.java b/server-core/src/main/java/io/onedev/server/model/PullRequest.javaindex 34da276a44..36d2b310e4 100644--- a/server-core/src/main/java/io/onedev/server/model/PullRequest.java+++ b/server-core/src/main/java/io/onedev/server/model/PullRequest.java@@ -36,6 +36,7 @@ import javax.persistence.Table;import javax.persistence.UniqueConstraint;import org.apache.commons.lang3.StringUtils;+import org.eclipse.jgit.lib.ObjectDatabase;import org.eclipse.jgit.lib.ObjectId;import org.eclipse.jgit.lib.RefUpdate;import org.eclipse.jgit.lib.Repository;@@ -289,6 +290,9 @@ public class PullRequest extends AbstractEntity implements Referenceable, Attach@OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)private Collection<PullRequestWatch> watches = new ArrayList<>();+ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<CodeComment> codeComments = new ArrayList<>();+@OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)private Collection<CodeCommentRelation> codeCommentRelations = new ArrayList<>();@@ -527,6 +531,14 @@ public class PullRequest extends AbstractEntity implements Referenceable, Attach}}+ public Collection<CodeComment> getCodeComments() {+ return codeComments;+ }++ public void setCodeComments(Collection<CodeComment> codeComments) {+ this.codeComments = codeComments;+ }+public Collection<CodeCommentRelation> getCodeCommentRelations() {return codeCommentRelations;}@@ -941,19 +953,24 @@ public class PullRequest extends AbstractEntity implements Referenceable, Attachpublic boolean isValid() {if (valid == null) {Repository repository = targetProject.getRepository();- if (!repository.hasObject(ObjectId.fromString(baseCommitHash))- || !repository.hasObject(ObjectId.fromString(headCommitHash))) {- valid = false;- } else {- for (PullRequestUpdate update: updates) {- if (!repository.hasObject(ObjectId.fromString(update.getMergeBaseCommitHash()))- || !repository.hasObject(ObjectId.fromString(update.getHeadCommitHash()))) {- valid = false;- break;+ ObjectDatabase objDb = repository.getObjectDatabase();+ try {+ if (!objDb.has(ObjectId.fromString(baseCommitHash))+ || !objDb.has(ObjectId.fromString(headCommitHash))) {+ valid = false;+ } else {+ for (PullRequestUpdate update: updates) {+ if (!objDb.has(ObjectId.fromString(update.getMergeBaseCommitHash()))+ || !objDb.has(ObjectId.fromString(update.getRequestHead()))) {+ valid = false;+ break;+ }}+ if (valid == null)+ valid = true;}- if (valid == null)- valid = true;+ } catch (IOException e) {+ throw new RuntimeException(e);}}return valid;@@ -1026,11 +1043,26 @@ public class PullRequest extends AbstractEntity implements Referenceable, Attach}}-+@Overridepublic String getAttachmentStorageUUID() {return uuid;}++ public ObjectId getComparisonBase(ObjectId oldCommitId, ObjectId newCommitId) {+ for (PullRequestUpdate update: getSortedUpdates()) {+ if (update.getCommits().contains(newCommitId)) {+ ObjectId targetHeadId = ObjectId.fromString(update.getTargetHead());+ ObjectId mergeBaseId = GitUtils.getMergeBase(getTargetProject().getRepository(), targetHeadId, newCommitId);+ if (mergeBaseId != null) {++ } else {+ return oldCommitId;+ }+ }+ }+ throw new IllegalStateException();+ }@Overridepublic Project getAttachmentProject() {diff --git a/server-core/src/main/java/io/onedev/server/model/PullRequestReview.java b/server-core/src/main/java/io/onedev/server/model/PullRequestReview.javaindex d92c9f7d23..efdd592851 100644--- a/server-core/src/main/java/io/onedev/server/model/PullRequestReview.java+++ b/server-core/src/main/java/io/onedev/server/model/PullRequestReview.java@@ -90,7 +90,7 @@ public class PullRequestReview extends AbstractEntity {update = request.getLatestUpdate();} else {for (PullRequestUpdate each: request.getUpdates()) {- if (each.getHeadCommitHash().equals(result.getCommit())) {+ if (each.getRequestHead().equals(result.getCommit())) {update = each;break;}diff --git a/server-core/src/main/java/io/onedev/server/model/PullRequestUpdate.java b/server-core/src/main/java/io/onedev/server/model/PullRequestUpdate.javaindex 416c1124a2..7747befda9 100644--- a/server-core/src/main/java/io/onedev/server/model/PullRequestUpdate.java+++ b/server-core/src/main/java/io/onedev/server/model/PullRequestUpdate.java@@ -51,7 +51,10 @@ public class PullRequestUpdate extends AbstractEntity {private PullRequest request;@Column(nullable=false)- private String headCommitHash;+ private String requestHead;++ @Column(nullable=false)+ private String targetHead;@Column(nullable=false)private String mergeBaseCommitHash;@@ -71,14 +74,22 @@ public class PullRequestUpdate extends AbstractEntity {this.request = request;}- public String getHeadCommitHash() {- return headCommitHash;+ public String getRequestHead() {+ return requestHead;}- public void setHeadCommitHash(String headCommitHash) {- this.headCommitHash = headCommitHash;+ public void setRequestHead(String requestHead) {+ this.requestHead = requestHead;}+ public String getTargetHead() {+ return targetHead;+ }++ public void setTargetHead(String targetHead) {+ this.targetHead = targetHead;+ }+public String getMergeBaseCommitHash() {return mergeBaseCommitHash;}@@ -119,7 +130,7 @@ public class PullRequestUpdate extends AbstractEntity {TreeWalk treeWalk = new TreeWalk(repository)) {RevCommit mergeBaseCommit = revWalk.parseCommit(ObjectId.fromString(getMergeBaseCommitHash()));RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getRequestHead()));revWalk.markStart(mergeBaseCommit);revWalk.markStart(baseCommit);revWalk.setRevFilter(RevFilter.MERGE_BASE);@@ -182,7 +193,7 @@ public class PullRequestUpdate extends AbstractEntity {int index = request.getSortedUpdates().indexOf(this);if (index > 0)- return request.getSortedUpdates().get(index-1).getHeadCommitHash();+ return request.getSortedUpdates().get(index-1).getRequestHead();elsereturn request.getBaseCommitHash();}@@ -219,7 +230,7 @@ public class PullRequestUpdate extends AbstractEntity {commits = new ArrayList<>();try (RevWalk revWalk = new RevWalk(getRequest().getWorkProject().getRepository())) {- revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash())));+ revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getRequestHead())));revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));/*@@ -241,11 +252,11 @@ public class PullRequestUpdate extends AbstractEntity {}public RevCommit getHeadCommit() {- return request.getWorkProject().getRevCommit(ObjectId.fromString(getHeadCommitHash()), true);+ return request.getWorkProject().getRevCommit(ObjectId.fromString(getRequestHead()), true);}public void writeRef() {- ObjectId updateHeadId = ObjectId.fromString(getHeadCommitHash());+ ObjectId updateHeadId = ObjectId.fromString(getRequestHead());if (!request.getTargetProject().equals(request.getSourceProject())) {try {request.getTargetProject().git().fetch()diff --git a/server-core/src/main/java/io/onedev/server/model/support/pullrequest/MergeStrategy.java b/server-core/src/main/java/io/onedev/server/model/support/pullrequest/MergeStrategy.javaindex 7be2680db4..d5da7911d5 100644--- a/server-core/src/main/java/io/onedev/server/model/support/pullrequest/MergeStrategy.java+++ b/server-core/src/main/java/io/onedev/server/model/support/pullrequest/MergeStrategy.java@@ -20,8 +20,8 @@ public enum MergeStrategy {Repository repository = request.getTargetProject().getRepository();ObjectId requestHead = request.getHeadCommit();ObjectId targetHead = request.getTarget().getObjectId();- return GitUtils.merge(repository, requestHead, targetHead, false, user, user,- request.getCommitMessage());+ return GitUtils.merge(repository, targetHead, requestHead, false, user, user,+ request.getCommitMessage(), false);}},@@ -36,8 +36,8 @@ public enum MergeStrategy {return requestHead;} else {PersonIdent user = new PersonIdent(OneDev.NAME, "");- return GitUtils.merge(repository, requestHead, targetHead, false, user, user,- request.getCommitMessage());+ return GitUtils.merge(repository, targetHead, requestHead, false, user, user,+ request.getCommitMessage(), false);}}@@ -50,8 +50,8 @@ public enum MergeStrategy {ObjectId requestHead = request.getHeadCommit();ObjectId targetHead = request.getTarget().getObjectId();PersonIdent user = new PersonIdent(OneDev.NAME, "");- return GitUtils.merge(repository, requestHead, targetHead, true, user, user,- request.getCommitMessage());+ return GitUtils.merge(repository, targetHead, requestHead, true, user, user,+ request.getCommitMessage(), false);}},diff --git a/server-core/src/main/java/io/onedev/server/search/code/DefaultIndexManager.java b/server-core/src/main/java/io/onedev/server/search/code/DefaultIndexManager.javaindex 8c7d4acf06..f8e8800e5b 100644--- a/server-core/src/main/java/io/onedev/server/search/code/DefaultIndexManager.java+++ b/server-core/src/main/java/io/onedev/server/search/code/DefaultIndexManager.java@@ -159,7 +159,7 @@ public class DefaultIndexManager implements IndexManager {if (lastCommitIndexVersion.equals(getIndexVersion())) {String lastCommitHash = doc.get(LAST_COMMIT_HASH.name());ObjectId lastCommitId = ObjectId.fromString(lastCommitHash);- if (repository.hasObject(lastCommitId)) {+ if (repository.getObjectDatabase().has(lastCommitId)) {treeWalk.addTree(revWalk.parseCommit(lastCommitId).getTree());treeWalk.setFilter(TreeFilter.ANY_DIFF);}diff --git a/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesCommitCriteria.java b/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesCommitCriteria.javaindex 4ef3cc1159..b88d00fe57 100644--- a/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesCommitCriteria.java+++ b/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesCommitCriteria.java@@ -10,7 +10,7 @@ import javax.persistence.criteria.Root;import org.eclipse.jgit.lib.ObjectId;import io.onedev.server.OneDev;-import io.onedev.server.infomanager.CodeCommentRelationInfoManager;+import io.onedev.server.infomanager.PullRequestInfoManager;import io.onedev.server.model.Project;import io.onedev.server.model.PullRequest;import io.onedev.server.search.entity.EntityCriteria;@@ -47,7 +47,7 @@ public class IncludesCommitCriteria extends EntityCriteria<PullRequest> {}private Collection<Long> getPullRequestIds() {- return OneDev.getInstance(CodeCommentRelationInfoManager.class).getPullRequestIds(project, commitId);+ return OneDev.getInstance(PullRequestInfoManager.class).getPullRequestIds(project, commitId);}@Overridediff --git a/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesIssueCriteria.java b/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesIssueCriteria.javaindex a03c660b01..3bfe9921bb 100644--- a/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesIssueCriteria.java+++ b/server-core/src/main/java/io/onedev/server/search/entity/pullrequest/IncludesIssueCriteria.java@@ -11,7 +11,7 @@ import javax.persistence.criteria.Root;import org.eclipse.jgit.lib.ObjectId;import io.onedev.server.OneDev;-import io.onedev.server.infomanager.CodeCommentRelationInfoManager;+import io.onedev.server.infomanager.PullRequestInfoManager;import io.onedev.server.infomanager.CommitInfoManager;import io.onedev.server.model.Issue;import io.onedev.server.model.Project;@@ -47,7 +47,7 @@ public class IncludesIssueCriteria extends EntityCriteria<PullRequest> {private Collection<Long> getPullRequestIds(Project project) {Collection<Long> pullRequestIds = new HashSet<>();for (ObjectId commit: OneDev.getInstance(CommitInfoManager.class).getFixCommits(project, issue.getNumber()))- pullRequestIds.addAll(OneDev.getInstance(CodeCommentRelationInfoManager.class).getPullRequestIds(project, commit));+ pullRequestIds.addAll(OneDev.getInstance(PullRequestInfoManager.class).getPullRequestIds(project, commit));return pullRequestIds;}diff --git a/server-core/src/main/java/io/onedev/server/ssh/DefaultKeyPairProvider.java b/server-core/src/main/java/io/onedev/server/ssh/DefaultKeyPairProvider.javaindex 88342d6d63..c9c953b4cf 100644--- a/server-core/src/main/java/io/onedev/server/ssh/DefaultKeyPairProvider.java+++ b/server-core/src/main/java/io/onedev/server/ssh/DefaultKeyPairProvider.java@@ -9,6 +9,7 @@ import javax.inject.Singleton;import org.apache.sshd.common.config.keys.KeyUtils;import org.apache.sshd.common.keyprovider.KeyPairProvider;+import org.apache.sshd.common.session.SessionContext;import com.google.common.collect.Lists;@@ -26,7 +27,7 @@ public class DefaultKeyPairProvider implements KeyPairProvider {}@Override- public Iterable<KeyPair> loadKeys() {+ public Iterable<KeyPair> loadKeys(SessionContext session) {SshSetting sshSetting = settingManager.getSshSetting();try {@@ -37,4 +38,5 @@ public class DefaultKeyPairProvider implements KeyPairProvider {throw new RuntimeException(e);}}+}diff --git a/server-core/src/main/java/io/onedev/server/ssh/DefaultSshAuthenticator.java b/server-core/src/main/java/io/onedev/server/ssh/DefaultSshAuthenticator.javaindex 13c2b50532..0a1218e8e3 100644--- a/server-core/src/main/java/io/onedev/server/ssh/DefaultSshAuthenticator.java+++ b/server-core/src/main/java/io/onedev/server/ssh/DefaultSshAuthenticator.java@@ -5,7 +5,7 @@ import java.security.PublicKey;import javax.inject.Inject;import javax.inject.Singleton;-import org.apache.sshd.common.AttributeStore.AttributeKey;+import org.apache.sshd.common.AttributeRepository.AttributeKey;import org.apache.sshd.common.config.keys.KeyUtils;import org.apache.sshd.server.auth.AsyncAuthException;import org.apache.sshd.server.session.ServerSession;diff --git a/server-core/src/main/java/io/onedev/server/ssh/SshKeyUtils.java b/server-core/src/main/java/io/onedev/server/ssh/SshKeyUtils.javaindex 4087a50e1e..e9310e4090 100644--- a/server-core/src/main/java/io/onedev/server/ssh/SshKeyUtils.java+++ b/server-core/src/main/java/io/onedev/server/ssh/SshKeyUtils.java@@ -27,8 +27,7 @@ public class SshKeyUtils {List<AuthorizedKeyEntry> entries = AuthorizedKeyEntry.readAuthorizedKeys(stringReader, true);AuthorizedKeyEntry entry = entries.get(0);- PublicKey pubEntry = entry.resolvePublicKey(PublicKeyEntryResolver.FAILING);- return pubEntry;+ return entry.resolvePublicKey(null, PublicKeyEntryResolver.FAILING);}public static PublicKey decodePEMPublicKey(String publicKey) throws IOException, GeneralSecurityException {diff --git a/server-core/src/main/java/io/onedev/server/web/component/codecomment/CodeCommentListPanel.java b/server-core/src/main/java/io/onedev/server/web/component/codecomment/CodeCommentListPanel.javaindex 23f716e809..aa3f392c3c 100644--- a/server-core/src/main/java/io/onedev/server/web/component/codecomment/CodeCommentListPanel.java+++ b/server-core/src/main/java/io/onedev/server/web/component/codecomment/CodeCommentListPanel.java@@ -1,5 +1,6 @@package io.onedev.server.web.component.codecomment;+import java.io.IOException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;@@ -272,14 +273,18 @@ public abstract class CodeCommentListPanel extends Panel {link = new BookmarkablePageLink<Void>("link", PullRequestChangesPage.class,PullRequestChangesPage.paramsOf(request, comment));} else {- String compareCommit = comment.getCompareContext().getCompareCommit();- if (!compareCommit.equals(comment.getMarkPos().getCommit())- && getProject().getRepository().hasObject(ObjectId.fromString(compareCommit))) {- link = new BookmarkablePageLink<Void>("link", RevisionComparePage.class,- RevisionComparePage.paramsOf(comment));- } else {- link = new BookmarkablePageLink<Void>("link", ProjectBlobPage.class,- ProjectBlobPage.paramsOf(comment));+ try {+ String compareCommit = comment.getCompareContext().getCompareCommit();+ if (!compareCommit.equals(comment.getMarkPos().getCommit())+ && getProject().getRepository().getObjectDatabase().has(ObjectId.fromString(compareCommit))) {+ link = new BookmarkablePageLink<Void>("link", RevisionComparePage.class,+ RevisionComparePage.paramsOf(comment));+ } else {+ link = new BookmarkablePageLink<Void>("link", ProjectBlobPage.class,+ ProjectBlobPage.paramsOf(comment));+ }+ } catch (IOException e) {+ throw new RuntimeException(e);}}}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.javaindex a5dfcc5379..158902e55e 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java@@ -208,7 +208,7 @@ public class NewPullRequestPage extends ProjectPage implements CommentSupport {update.setDate(new DateTime(request.getSubmitDate()).plusSeconds(1).toDate());request.addUpdate(update);update.setRequest(request);- update.setHeadCommitHash(request.getHeadCommitHash());+ update.setRequestHead(request.getHeadCommitHash());update.setMergeBaseCommitHash(request.getBaseCommitHash());OneDev.getInstance(PullRequestManager.class).checkQuality(request);diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UnreviewedChangesPanel.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UnreviewedChangesPanel.javaindex b5b02fc8b6..fd010e9917 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UnreviewedChangesPanel.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UnreviewedChangesPanel.java@@ -21,7 +21,7 @@ public class UnreviewedChangesPanel extends GenericPanel<PullRequestUpdate> {PullRequestUpdate update = getModelObject();PullRequestChangesPage.State state = new PullRequestChangesPage.State();- state.oldCommit = update.getHeadCommitHash();+ state.oldCommit = update.getRequestHead();state.newCommit = update.getRequest().getHeadCommitHash();add(new ViewStateAwarePageLink<Void>("link", PullRequestChangesPage.class,diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UpdateChangesLink.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UpdateChangesLink.javaindex 863375f918..ae854d55b5 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UpdateChangesLink.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/UpdateChangesLink.java@@ -19,7 +19,7 @@ public class UpdateChangesLink extends ViewStateAwarePageLink<Void> {private static PageParameters paramsOf(PullRequestUpdate update) {return PullRequestChangesPage.paramsOf(update.getRequest(),- update.getBaseCommitHash(), update.getHeadCommitHash());+ update.getBaseCommitHash(), update.getRequestHead());}public IModel<?> getBody() {diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/activities/SinceChangesLink.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/activities/SinceChangesLink.javaindex d0a32ab7a1..3f912696de 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/activities/SinceChangesLink.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/activities/SinceChangesLink.java@@ -31,7 +31,7 @@ public class SinceChangesLink extends ViewStateAwarePageLink<Void> {String commit = request.getBaseCommitHash();for (PullRequestUpdate update: request.getSortedUpdates()) {if (update.getDate().before(sinceDate))- commit = update.getHeadCommitHash();+ commit = update.getRequestHead();}return commit;}diff --git a/server-core/src/main/java/io/onedev/server/web/page/test/TestPage.java b/server-core/src/main/java/io/onedev/server/web/page/test/TestPage.javaindex b19152c540..2dbbd9b89d 100644--- a/server-core/src/main/java/io/onedev/server/web/page/test/TestPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/test/TestPage.java@@ -28,7 +28,7 @@ public class TestPage extends BasePage {});}-+@Overridepublic void renderHead(IHeaderResponse response) {super.renderHead(response);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.javanew file mode 100644index 0000000000..e44970abff--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/EolAwareOutputStream.java@@ -0,0 +1,97 @@+/*+ * 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.javanew file mode 100644index 0000000000..5978b8af33--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeAlgorithm.java@@ -0,0 +1,308 @@+/*+ * 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.javanew file mode 100644index 0000000000..ca998e30bc--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeChunk.java@@ -0,0 +1,120 @@+/*+ * 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.javanew file mode 100644index 0000000000..54b7aa4346--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeConfig.java@@ -0,0 +1,171 @@+/*******************************************************************************+ * 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.javanew file mode 100644index 0000000000..36adf92e21--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatter.java@@ -0,0 +1,150 @@+/*+ * 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 "<<<<<<<+ * " or ">>>>>>> " 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 "<<<<<<<+ * " or ">>>>>>> " conflict markers. The+ * names for the sequences are given in this list+ * @param charset+ * the character set used when writing conflict metadata+ * @throws java.io.IOException+ * @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.javanew file mode 100644index 0000000000..f09b343007--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeFormatterPass.java@@ -0,0 +1,128 @@+/*+ * 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 "<<<<<<<+ * " or ">>>>>>> " conflict markers. The+ * names for the sequences are given in this list+ * @param charset+ * the character set used when writing conflict metadata+ */+ MergeFormatterPass(OutputStream out, MergeResult<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.javanew file mode 100644index 0000000000..f7966a267f--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeMessageFormatter.java@@ -0,0 +1,135 @@+/*+ * 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.javanew file mode 100644index 0000000000..062a5a84e0--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeResult.java@@ -0,0 +1,150 @@+/*+ * 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.javanew file mode 100644index 0000000000..ba9c5b7dcc--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/MergeStrategy.java@@ -0,0 +1,162 @@+/*+ * 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.javanew file mode 100644index 0000000000..bd762e5a98--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/Merger.java@@ -0,0 +1,344 @@+/*+ * 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.javanew file mode 100644index 0000000000..bf2a78f6b3--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/RecursiveMerger.java@@ -0,0 +1,240 @@+/*+ * 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.javanew file mode 100644index 0000000000..cb14b1398d--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/ResolveMerger.java@@ -0,0 +1,1345 @@+/*+ * 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.javanew file mode 100644index 0000000000..4a73f8ed7e--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/SquashMessageFormatter.java@@ -0,0 +1,73 @@+/*+ * 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.javanew file mode 100644index 0000000000..7055ccd127--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/StrategyOneSided.java@@ -0,0 +1,98 @@+/*+ * 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.javanew file mode 100644index 0000000000..c9512edf63--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/StrategyRecursive.java@@ -0,0 +1,47 @@+/*+ * 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.javanew file mode 100644index 0000000000..5991ef68a3--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/StrategyResolve.java@@ -0,0 +1,45 @@+/*+ * 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.javanew file mode 100644index 0000000000..ff40fc1d68--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/StrategySimpleTwoWayInCore.java@@ -0,0 +1,183 @@+/*+ * 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.javanew file mode 100644index 0000000000..411789fd95--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMergeStrategy.java@@ -0,0 +1,26 @@+/*+ * 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.javanew file mode 100644index 0000000000..f283edee01--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/ThreeWayMerger.java@@ -0,0 +1,126 @@+/*+ * 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.javanew file mode 100644index 0000000000..d61cd6a5cd--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/merge/package-info.java@@ -0,0 +1,4 @@+/**+ * Content and commit history merge algorithms.+ */+package org.eclipse.jgit.merge;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/AbstractRevQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/AbstractRevQueue.javaindex 247a3bdb28..e0c7bdd396 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/AbstractRevQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/AbstractRevQueue.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -49,6 +16,10 @@ abstract class AbstractRevQueue extends Generator {/** Current output flags set for this generator instance. */int outputType;+ AbstractRevQueue(boolean firstParent) {+ super(firstParent);+ }+/*** Add a commit to the queue.* <p>@@ -96,10 +67,15 @@ abstract class AbstractRevQueue extends Generator {*/public final void addParents(RevCommit c, RevFlag queueControl) {final RevCommit[] pList = c.parents;- if (pList == null)+ if (pList == null) {return;- for (RevCommit p : pList)- add(p, queueControl);+ }+ for (int i = 0; i < pList.length; i++) {+ if (firstParent && i > 0) {+ break;+ }+ add(pList[i], queueControl);+ }}/**@@ -138,6 +114,10 @@ abstract class AbstractRevQueue extends Generator {}private static class AlwaysEmptyQueue extends AbstractRevQueue {+ private AlwaysEmptyQueue() {+ super(false);+ }+@Overridepublic void add(RevCommit c) {throw new UnsupportedOperationException();diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/AsyncRevObjectQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/AsyncRevObjectQueue.javaindex 98654f14c2..279697b6eb 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/AsyncRevObjectQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/AsyncRevObjectQueue.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2010, Google Inc.- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2010, Google Inc. and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;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.javaindex b07de5f1f6..023962e251 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@@ -1,44 +1,11 @@/*- * Copyright (C) 2012, Google Inc.- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2012, Google Inc. and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;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.javanew file mode 100644index 0000000000..02514526d0--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/BitmappedReachabilityChecker.java@@ -0,0 +1,163 @@+/*+ * 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/BlockObjQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockObjQueue.javaindex fcdf79520a..294ff4de79 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockObjQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockObjQueue.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockRevQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockRevQueue.javaindex 79307b5b7c..cdd8073d6e 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockRevQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/BlockRevQueue.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -53,13 +20,19 @@ abstract class BlockRevQueue extends AbstractRevQueue {/*** Create an empty revision queue.+ *+ * @param firstParent+ * whether only first-parent links should be followed when+ * walking*/- protected BlockRevQueue() {+ protected BlockRevQueue(boolean firstParent) {+ super(firstParent);free = new BlockFreeList();}BlockRevQueue(Generator s) throws MissingObjectException,IncorrectObjectTypeException, IOException {+ super(s.firstParent);free = new BlockFreeList();outputType = s.outputType();s.shareFreeList(this);diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/BoundaryGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/BoundaryGenerator.javaindex 0fd6621e62..8b78d062b5 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/BoundaryGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/BoundaryGenerator.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -55,6 +22,7 @@ class BoundaryGenerator extends Generator {Generator g;BoundaryGenerator(RevWalk w, Generator s) {+ super(s.firstParent);g = new InitialGenerator(w, s);}@@ -86,8 +54,9 @@ class BoundaryGenerator extends Generator {private final Generator source;InitialGenerator(RevWalk w, Generator s) {+ super(s.firstParent);walk = w;- held = new FIFORevQueue();+ held = new FIFORevQueue(firstParent);source = s;source.shareFreeList(held);}@@ -107,13 +76,19 @@ class BoundaryGenerator extends Generator {IncorrectObjectTypeException, IOException {RevCommit c = source.next();if (c != null) {- for (RevCommit p : c.parents)- if ((p.flags & UNINTERESTING) != 0)+ for (int i = 0; i < c.parents.length; i++) {+ if (firstParent && i > 0) {+ break;+ }+ RevCommit p = c.parents[i];+ if ((p.flags & UNINTERESTING) != 0) {held.add(p);+ }+ }return c;}- final FIFORevQueue boundary = new FIFORevQueue();+ final FIFORevQueue boundary = new FIFORevQueue(firstParent);boundary.shareFreeList(held);for (;;) {c = held.next();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.javaindex b86e876201..b875be9270 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@@ -1,45 +1,12 @@/** Copyright (C) 2008, Shawn O. Pearce <[email protected]>,- * Copyright (C) 2013, Gustaf Lundh <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2013, Gustaf Lundh <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -69,15 +36,18 @@ public class DateRevQueue extends AbstractRevQueue {private int last = -1;- /**- * Create an empty date queue.- */+ /** Create an empty date queue. */public DateRevQueue() {- super();+ super(false);+ }++ DateRevQueue(boolean firstParent) {+ super(firstParent);}DateRevQueue(Generator s) throws MissingObjectException,IncorrectObjectTypeException, IOException {+ super(s.firstParent);for (;;) {final RevCommit c = s.next();if (c == null)diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/DelayRevQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/DelayRevQueue.javaindex c397a01317..234c74b07f 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/DelayRevQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/DelayRevQueue.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -70,6 +37,7 @@ final class DelayRevQueue extends Generator {private int size;DelayRevQueue(Generator g) {+ super(g.firstParent);pending = g;delay = new FIFORevQueue();}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthGenerator.javaindex 5154920393..3a2cb8b0f9 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthGenerator.java@@ -1,45 +1,12 @@/** Copyright (C) 2010, Garmin International- * Copyright (C) 2010, Matt Fischer <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2010, Matt Fischer <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -95,7 +62,8 @@ class DepthGenerator extends Generator {*/DepthGenerator(DepthWalk w, Generator s) throws MissingObjectException,IncorrectObjectTypeException, IOException {- pending = new FIFORevQueue();+ super(s.firstParent);+ pending = new FIFORevQueue(firstParent);walk = (RevWalk)w;this.depth = w.getDepth();@@ -108,12 +76,25 @@ class DepthGenerator extends Generator {// Begin by sucking out all of the source's commits, and// adding them to the pending queue+ FIFORevQueue unshallowCommits = new FIFORevQueue();for (;;) {RevCommit c = s.next();if (c == null)break;- if (((DepthWalk.Commit) c).getDepth() == 0)+ if (c.has(UNSHALLOW)) {+ unshallowCommits.add(c);+ } else if (((DepthWalk.Commit) c).getDepth() == 0) {pending.add(c);+ }+ }+ // Move unshallow commits to the front so that the REINTERESTING flag+ // carry over code is executed first.+ for (;;) {+ RevCommit c = unshallowCommits.next();+ if (c == null) {+ break;+ }+ pending.unpop(c);}// Mark DEEPEN_NOT on all deepen-not commits and their ancestors.@@ -183,7 +164,11 @@ class DepthGenerator extends Generator {int newDepth = c.depth + 1;- for (RevCommit p : c.parents) {+ for (int i = 0; i < c.parents.length; i++) {+ if (firstParent && i > 0) {+ break;+ }+ RevCommit p = c.parents[i];DepthWalk.Commit dp = (DepthWalk.Commit) p;// If no depth has been assigned to this commit, assigndiff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthWalk.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthWalk.javaindex 0201f0b602..5277563ac4 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthWalk.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/DepthWalk.java@@ -1,45 +1,12 @@/** Copyright (C) 2010, Garmin International- * Copyright (C) 2010, Matt Fischer <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2010, Matt Fischer <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/EndGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/EndGenerator.javaindex 627e1c7a51..4c93c574bd 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/EndGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/EndGenerator.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -47,7 +14,7 @@ class EndGenerator extends Generator {static final EndGenerator INSTANCE = new EndGenerator();private EndGenerator() {- // We have nothing to initialize.+ super(false);}@Overridediff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/FIFORevQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/FIFORevQueue.javaindex cdb084c15e..0f8eddd6d4 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/FIFORevQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/FIFORevQueue.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -56,11 +23,13 @@ public class FIFORevQueue extends BlockRevQueue {private Block tail;- /**- * Create an empty FIFO queue.- */+ /** Create an empty FIFO queue. */public FIFORevQueue() {- super();+ super(false);+ }++ FIFORevQueue(boolean firstParent) {+ super(firstParent);}FIFORevQueue(Generator s) throws MissingObjectException,diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/FixUninterestingGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/FixUninterestingGenerator.javaindex 4e6d7e681d..ec7db112c8 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/FixUninterestingGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/FixUninterestingGenerator.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -62,6 +29,7 @@ final class FixUninterestingGenerator extends Generator {private final Generator pending;FixUninterestingGenerator(Generator g) {+ super(g.firstParent);pending = g;}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/FollowFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/FollowFilter.javaindex dae3aacb83..3b54123f0b 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/FollowFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/FollowFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2010, Google Inc.- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2010, Google Inc. and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterKey.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterKey.javaindex 45d5f809bb..74e4c1edb7 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterKey.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterKey.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2009, Google Inc.- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2009, Google Inc. and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterLine.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterLine.javaindex d6fed66702..3d128a6bd3 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterLine.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/FooterLine.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2009, Google Inc.- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2009, Google Inc. and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -95,7 +62,7 @@ public final class FooterLine {for (int kPtr = 0; kPtr < len;) {byte b = buffer[bPtr++];if ('A' <= b && b <= 'Z')- b += 'a' - 'A';+ b += (byte) ('a' - 'A');if (b != kRaw[kPtr++])return false;}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/Generator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/Generator.javaindex b2c92ea249..3493dcfb47 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/Generator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/Generator.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -75,6 +42,12 @@ abstract class Generator {/** Output may have {@link RevWalk#UNINTERESTING} marked on it. */static final int HAS_UNINTERESTING = 1 << 4;+ protected final boolean firstParent;++ protected Generator(boolean firstParent) {+ this.firstParent = firstParent;+ }+/*** Connect the supplied queue to this generator's own free list (if any).*diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/LIFORevQueue.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/LIFORevQueue.javaindex 846b8d92fa..4773ca8427 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/LIFORevQueue.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/LIFORevQueue.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -59,7 +26,7 @@ public class LIFORevQueue extends BlockRevQueue {* Create an empty LIFO queue.*/public LIFORevQueue() {- super();+ super(false);}LIFORevQueue(Generator s) throws MissingObjectException,diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/MergeBaseGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/MergeBaseGenerator.javaindex 2fe95318b2..c0fea75777 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/MergeBaseGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/MergeBaseGenerator.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -85,8 +52,9 @@ class MergeBaseGenerator extends Generator {private CarryStack stack;MergeBaseGenerator(RevWalk w) {+ super(w.isFirstParent());walker = w;- pending = new DateRevQueue();+ pending = new DateRevQueue(firstParent);}void init(AbstractRevQueue p) throws IOException {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.javaindex e5903c9117..04a4b4c631 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@@ -1,48 +1,16 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;+import static java.util.Objects.requireNonNull;import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;import static org.eclipse.jgit.lib.Constants.OBJ_COMMIT;import static org.eclipse.jgit.lib.Constants.OBJ_TREE;@@ -97,6 +65,55 @@ public class ObjectWalk extends RevWalk {*/private static final int IN_PENDING = RevWalk.REWRITE;+ /**+ * When walking over a tree and blob graph, objects are usually marked as+ * seen as they are visited and this "seen" status is checked upon the next+ * visit. If they are already "seen" then they are not processed (returned+ * by {@link ObjectWalk#nextObject()}) again. However, this behavior can be+ * overridden by supplying a different implementation of this class.+ *+ * @since 5.4+ */+ public interface VisitationPolicy {+ /**+ * Whenever the rev or object walk reaches a Git object, if that object+ * already exists as a RevObject, this method is called to determine if+ * that object should be visited.+ *+ * @param o+ * the object to check if it should be visited+ * @return true if the object should be visited+ */+ boolean shouldVisit(RevObject o);++ /**+ * Called when an object is visited.+ *+ * @param o+ * the object that was visited+ */+ void visited(RevObject o);+ }++ /**+ * The default visitation policy: causes all objects to be visited exactly+ * once.+ *+ * @since 5.4+ */+ public static final VisitationPolicy SIMPLE_VISITATION_POLICY =+ new VisitationPolicy() {+ @Override+ public boolean shouldVisit(RevObject o) {+ return (o.flags & SEEN) == 0;+ }++ @Override+ public void visited(RevObject o) {+ o.flags |= SEEN;+ }+ };+private List<RevObject> rootObjects;private BlockObjQueue pendingObjects;@@ -113,6 +130,8 @@ public class ObjectWalk extends RevWalk {private boolean boundary;+ private VisitationPolicy visitationPolicy = SIMPLE_VISITATION_POLICY;+/*** Create a new revision and object walker for a given repository.*@@ -299,6 +318,18 @@ public class ObjectWalk extends RevWalk {objectFilter = newFilter != null ? newFilter : ObjectFilter.ALL;}+ /**+ * Sets the visitation policy to use during this walk.+ *+ * @param policy+ * the {@code VisitationPolicy} to use+ * @since 5.4+ */+ public void setVisitationPolicy(VisitationPolicy policy) {+ assertNotStarted();+ visitationPolicy = requireNonNull(policy);+ }+/** {@inheritDoc} */@Overridepublic RevCommit next() throws MissingObjectException,@@ -325,16 +356,29 @@ public class ObjectWalk extends RevWalk {}}+ /**+ * Skips the current tree such that {@link #nextObject()} does not return+ * any objects inside it. This should be called right after+ * {@link #nextObject()} returns the tree.+ *+ * @since 5.4+ */+ public void skipTree() {+ if (currVisit != null) {+ currVisit.ptr = currVisit.buf.length;+ }+ }+/*** Pop the next most recent object.** @return next most recent object; null if traversal is over.* @throws org.eclipse.jgit.errors.MissingObjectException- * one or or more of the next objects are not available from the+ * one or more of the next objects are not available from the* object database, but were thought to be candidates for* traversal. This usually indicates a broken link.* @throws org.eclipse.jgit.errors.IncorrectObjectTypeException- * one or or more of the objects in a tree do not match the type+ * one or more of the objects in a tree do not match the type* indicated.* @throws java.io.IOException* a pack file or loose object could not be read.@@ -357,24 +401,23 @@ public class ObjectWalk extends RevWalk {}RevObject obj = objects.get(idBuffer);- if (obj != null && (obj.flags & SEEN) != 0)+ if (obj != null && !visitationPolicy.shouldVisit(obj))continue;int mode = parseMode(buf, startPtr, ptr, tv);- int flags;switch (mode >>> TYPE_SHIFT) {case TYPE_FILE:case TYPE_SYMLINK:if (obj == null) {obj = new RevBlob(idBuffer);- obj.flags = SEEN;+ visitationPolicy.visited(obj);objects.add(obj);return obj;}if (!(obj instanceof RevBlob))throw new IncorrectObjectTypeException(obj, OBJ_BLOB);- obj.flags = flags = obj.flags | SEEN;- if ((flags & UNINTERESTING) == 0)+ visitationPolicy.visited(obj);+ if ((obj.flags & UNINTERESTING) == 0)return obj;if (boundary)return obj;@@ -383,17 +426,17 @@ public class ObjectWalk extends RevWalk {case TYPE_TREE:if (obj == null) {obj = new RevTree(idBuffer);- obj.flags = SEEN;+ visitationPolicy.visited(obj);objects.add(obj);- return enterTree(obj);+ return pushTree(obj);}if (!(obj instanceof RevTree))throw new IncorrectObjectTypeException(obj, OBJ_TREE);- obj.flags = flags = obj.flags | SEEN;- if ((flags & UNINTERESTING) == 0)- return enterTree(obj);+ visitationPolicy.visited(obj);+ if ((obj.flags & UNINTERESTING) == 0)+ return pushTree(obj);if (boundary)- return enterTree(obj);+ return pushTree(obj);continue;case TYPE_GITLINK:@@ -419,30 +462,23 @@ public class ObjectWalk extends RevWalk {if (o == null) {return null;}- int flags = o.flags;- if ((flags & SEEN) != 0)+ if (!visitationPolicy.shouldVisit(o)) {continue;- flags |= SEEN;- o.flags = flags;- if ((flags & UNINTERESTING) == 0 | boundary) {+ }+ visitationPolicy.visited(o);+ if ((o.flags & UNINTERESTING) == 0 || boundary) {if (o instanceof RevTree) {- tv = newTreeVisit(o);- tv.parent = null;- currVisit = tv;+ // The previous while loop should have exhausted the stack+ // of trees.+ assert currVisit == null;++ pushTree(o);}return o;}}}- private RevObject enterTree(RevObject obj) throws MissingObjectException,- IncorrectObjectTypeException, IOException {- TreeVisit tv = newTreeVisit(obj);- tv.parent = currVisit;- currVisit = tv;- return obj;- }-private static int findObjectId(byte[] buf, int ptr) {// Skip over the mode and name until the NUL before the ObjectId// can be located. Skip the NUL as the function returns.@@ -534,11 +570,11 @@ public class ObjectWalk extends RevWalk {* provides some detail about the connectivity failure.** @throws org.eclipse.jgit.errors.MissingObjectException- * one or or more of the next objects are not available from the+ * one or more of the next objects are not available from the* object database, but were thought to be candidates for* traversal. This usually indicates a broken link.* @throws org.eclipse.jgit.errors.IncorrectObjectTypeException- * one or or more of the objects in a tree do not match the type+ * one or more of the objects in a tree do not match the type* indicated.* @throws java.io.IOException* a pack file or loose object could not be read.@@ -581,6 +617,17 @@ public class ObjectWalk extends RevWalk {return RawParseUtils.decode(pathBuf, 0, pathLen);}+ /**+ * @return the current traversal depth from the root tree object+ * @since 5.4+ */+ public int getTreeDepth() {+ if (currVisit == null) {+ return 0;+ }+ return currVisit.depth;+ }+/*** Get the current object's path hash code.* <p>@@ -768,7 +815,7 @@ public class ObjectWalk extends RevWalk {}}- private TreeVisit newTreeVisit(RevObject obj) throws LargeObjectException,+ private RevObject pushTree(RevObject obj) throws LargeObjectException,MissingObjectException, IncorrectObjectTypeException, IOException {TreeVisit tv = freeVisit;if (tv != null) {@@ -782,7 +829,15 @@ public class ObjectWalk extends RevWalk {}tv.obj = obj;tv.buf = reader.open(obj, OBJ_TREE).getCachedBytes();- return tv;+ tv.parent = currVisit;+ currVisit = tv;+ if (tv.parent == null) {+ tv.depth = 1;+ } else {+ tv.depth = tv.parent.depth + 1;+ }++ return obj;}private void releaseTreeVisit(TreeVisit tv) {@@ -812,5 +867,8 @@ public class ObjectWalk extends RevWalk {/** Number of bytes in the path leading up to this tree. */int pathLen;++ /** Number of levels deep from the root tree. 0 for root tree. */+ int depth;}}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.javanew file mode 100644index 0000000000..5dc03776c2--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/PedestrianReachabilityChecker.java@@ -0,0 +1,66 @@+/*+ * 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/PendingGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/PendingGenerator.javaindex e607b7daa0..add387de03 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/PendingGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/PendingGenerator.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -109,6 +76,7 @@ class PendingGenerator extends Generator {PendingGenerator(final RevWalk w, final DateRevQueue p,final RevFilter f, final int out) {+ super(w.isFirstParent());walker = w;pending = p;filter = f;@@ -140,7 +108,13 @@ class PendingGenerator extends Generator {produce = filter.include(walker, c);}- for (RevCommit p : c.parents) {+ for (int i = 0; i < c.parents.length; i++) {+ RevCommit p = c.parents[i];+ // If the commit is uninteresting, don't try to prune+ // parents because we want the maximal uninteresting set.+ if (firstParent && i > 0 && (c.flags & UNINTERESTING) == 0) {+ continue;+ }if ((p.flags & SEEN) != 0)continue;if ((p.flags & PARSED) == 0)diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/ReachabilityChecker.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/ReachabilityChecker.javanew file mode 100644index 0000000000..d499084b42--- /dev/null+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/ReachabilityChecker.java@@ -0,0 +1,92 @@+/*+ * 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.Optional;+import java.util.stream.Stream;++import org.eclipse.jgit.errors.IncorrectObjectTypeException;+import org.eclipse.jgit.errors.MissingObjectException;++/**+ * Check if a commit is reachable from a collection of starting commits.+ * <p>+ * Note that this checks the reachability of commits (and tags). Trees, blobs or+ * any other object will cause IncorrectObjectTypeException exceptions.+ *+ * @since 5.4+ */+public interface ReachabilityChecker {++ /**+ * Check if all targets are reachable from the {@code starter} commits.+ * <p>+ * Caller should parse the objectIds (preferably with+ * {@code walk.parseCommit()} and handle missing/incorrect type objects+ * before calling this method.+ *+ * @param targets+ * commits to reach.+ * @param starters+ * known starting points.+ * @return An unreachable target if at least one of the targets is+ * unreachable. An empty optional if all targets are reachable from+ * the starters.+ *+ * @throws MissingObjectException+ * if any of the incoming objects doesn't exist in the+ * repository.+ * @throws IncorrectObjectTypeException+ * if any of the incoming objects is not a commit or a tag.+ * @throws IOException+ * if any of the underlying indexes or readers can not be+ * opened.+ *+ * @deprecated see {{@link #areAllReachable(Collection, Stream)}+ */+ @Deprecated+ default Optional<RevCommit> areAllReachable(Collection<RevCommit> targets,+ Collection<RevCommit> starters) throws MissingObjectException,+ IncorrectObjectTypeException, IOException {+ return areAllReachable(targets, starters.stream());+ }++ /**+ * Check if all targets are reachable from the {@code starter} commits.+ * <p>+ * Caller should parse the objectIds (preferably with+ * {@code walk.parseCommit()} and handle missing/incorrect type objects+ * before calling this method.+ *+ * @param targets+ * commits to reach.+ * @param starters+ * known starting points.+ * @return An unreachable target if at least one of the targets is+ * unreachable. An empty optional if all targets are reachable from+ * the starters.+ *+ * @throws MissingObjectException+ * if any of the incoming objects doesn't exist in the+ * repository.+ * @throws IncorrectObjectTypeException+ * if any of the incoming objects is not a commit or a tag.+ * @throws IOException+ * if any of the underlying indexes or readers can not be+ * opened.+ * @since 5.6+ */+ Optional<RevCommit> areAllReachable(Collection<RevCommit> targets,+ Stream<RevCommit> starters)+ throws MissingObjectException, IncorrectObjectTypeException,+ IOException;+}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RenameCallback.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RenameCallback.javaindex 7754f18e9a..ba3399ce9f 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RenameCallback.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RenameCallback.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2011, GEBIT Solutions- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2011, GEBIT Solutions and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevBlob.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevBlob.javaindex cc5e3e40db..f5abbb870a 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevBlob.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevBlob.java@@ -1,46 +1,13 @@/** Copyright (C) 2009, Google Inc.* Copyright (C) 2008, Marek Zawirski <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommit.javaindex af4ec1f00b..82725f3db9 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommit.java@@ -1,45 +1,12 @@/** Copyright (C) 2008-2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -188,18 +155,22 @@ public class RevCommit extends RevObject {}idBuffer.fromString(raw, ptr + 7);final RevCommit p = walk.lookupCommit(idBuffer);- if (nParents == 0) {+ switch (nParents) {+ case 0:pList[nParents++] = p;- } else if (nParents == 1) {+ break;+ case 1:pList = new RevCommit[] { pList[0], p };nParents = 2;- } else {+ break;+ default:if (pList.length <= nParents) {RevCommit[] old = pList;pList = new RevCommit[pList.length + 32];System.arraycopy(old, 0, pList, 0, nParents);}pList[nParents++] = p;+ break;}ptr += 48;}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommitList.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommitList.javaindex d2fda2f91e..59213a8e60 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommitList.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevCommitList.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlag.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlag.javaindex 413a552962..a0160ddbef 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlag.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlag.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlagSet.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlagSet.javaindex 45a730cfd2..71cc9a4850 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlagSet.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevFlagSet.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;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.javaindex eef9bf33e0..5ce4bc33b5 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@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObjectList.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObjectList.javaindex 2f21e17455..0393f55957 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObjectList.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevObjectList.java@@ -1,46 +1,13 @@/** Copyright (C) 2009, Google Inc.* Copyright (C) 2009, Jonas Fonseca <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;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.javaindex a3b31a1922..fc6ae28dc9 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@@ -1,45 +1,12 @@/** Copyright (C) 2008, Marek Zawirski <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;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.javaindex 32e7adfb0c..cac257199f 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,46 +1,13 @@/** Copyright (C) 2008-2009, Google Inc.* Copyright (C) 2008, Marek Zawirski <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTree.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTree.javaindex e7de270f65..8119af468a 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTree.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RevTree.java@@ -1,46 +1,13 @@/** Copyright (C) 2009, Google Inc.* Copyright (C) 2008, Marek Zawirski <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;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.javaindex 400ea33c21..f425e87618 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@@ -1,46 +1,13 @@/** Copyright (C) 2007, Robin Rosenberg <[email protected]>* Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * Copyright (C) 2014, Gustaf Lundh <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2014, Gustaf Lundh <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -72,6 +39,7 @@ import org.eclipse.jgit.lib.ObjectReader;import org.eclipse.jgit.lib.Repository;import org.eclipse.jgit.revwalk.filter.RevFilter;import org.eclipse.jgit.treewalk.filter.TreeFilter;+import org.eclipse.jgit.util.References;/*** Walks a commit graph and produces the matching commits in order.@@ -200,6 +168,8 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {private boolean rewriteParents = true;+ private boolean firstParent;+boolean shallowCommitsInitialized;/**@@ -232,7 +202,7 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {idBuffer = new MutableObjectId();objects = new ObjectIdOwnerMap<>();roots = new ArrayList<>();- queue = new DateRevQueue();+ queue = new DateRevQueue(false);pending = new StartGenerator(this);sorting = EnumSet.of(RevSort.NONE);filter = RevFilter.ALL;@@ -249,6 +219,23 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {return reader;}+ /**+ * Get a reachability checker for commits over this revwalk.+ *+ * @return the most efficient reachability checker for this repository.+ * @throws IOException+ * if it cannot open any of the underlying indices.+ *+ * @since 5.4+ */+ public ReachabilityChecker createReachabilityChecker() throws IOException {+ if (reader.getBitmapIndex() != null) {+ return new BitmappedReachabilityChecker(this);+ }++ return new PedestrianReachabilityChecker(true, this);+ }+/*** {@inheritDoc}* <p>@@ -394,11 +381,11 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {* <code>base</code> (and thus <code>base</code> is fully merged* into <code>tip</code>); false otherwise.* @throws org.eclipse.jgit.errors.MissingObjectException- * one or or more of the next commit's parents are not available+ * one or more of the next commit's parents are not available* from the object database, but were thought to be candidates* for traversal. This usually indicates a broken link.* @throws org.eclipse.jgit.errors.IncorrectObjectTypeException- * one or or more of the next commit's parents are not actually+ * one or more of the next commit's parents are not actually* commit objects.* @throws java.io.IOException* a pack file or loose object could not be read.@@ -416,9 +403,11 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {markStart(tip);markStart(base);RevCommit mergeBase;- while ((mergeBase = next()) != null)- if (mergeBase == base)+ while ((mergeBase = next()) != null) {+ if (References.isSameObject(mergeBase, base)) {return true;+ }+ }return false;} finally {filter = oldRF;@@ -431,11 +420,11 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {** @return next most recent commit; null if traversal is over.* @throws org.eclipse.jgit.errors.MissingObjectException- * one or or more of the next commit's parents are not available+ * one or more of the next commit's parents are not available* from the object database, but were thought to be candidates* for traversal. This usually indicates a broken link.* @throws org.eclipse.jgit.errors.IncorrectObjectTypeException- * one or or more of the next commit's parents are not actually+ * one or more of the next commit's parents are not actually* commit objects.* @throws java.io.IOException* a pack file or loose object could not be read.@@ -506,7 +495,7 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {if (sorting.size() > 1)sorting.remove(RevSort.NONE);- else if (sorting.size() == 0)+ else if (sorting.isEmpty())sorting.add(RevSort.NONE);}@@ -643,6 +632,35 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {retainBody = retain;}+ /**+ * @return whether only first-parent links should be followed when walking.+ *+ * @since 5.5+ */+ public boolean isFirstParent() {+ return firstParent;+ }++ /**+ * Set whether or not only first parent links should be followed.+ * <p>+ * If set, second- and higher-parent links are not traversed at all.+ * <p>+ * This must be called prior to {@link #markStart(RevCommit)}.+ *+ * @param enable+ * true to walk only first-parent links.+ *+ * @since 5.5+ */+ public void setFirstParent(boolean enable) {+ assertNotStarted();+ assertNoCommitsMarkedStart();+ firstParent = enable;+ queue = new DateRevQueue(firstParent);+ pending = new StartGenerator(this);+ }+/*** Locate a reference to a blob without loading it.* <p>@@ -1275,7 +1293,8 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {* <p>* Unlike {@link #dispose()} previously acquired RevObject (and RevCommit)* instances are not invalidated. RevFlag instances are not invalidated, but- * are removed from all RevObjects.+ * are removed from all RevObjects. The value of {@code firstParent} is+ * retained.** @param retainFlags* application flags that should <b>not</b> be cleared from@@ -1311,7 +1330,7 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {}roots.clear();- queue = new DateRevQueue();+ queue = new DateRevQueue(firstParent);pending = new StartGenerator(this);}@@ -1329,9 +1348,10 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {delayFreeFlags = 0;retainOnReset = 0;carryFlags = UNINTERESTING;+ firstParent = false;objects.clear();roots.clear();- queue = new DateRevQueue();+ queue = new DateRevQueue(firstParent);pending = new StartGenerator(this);shallowCommitsInitialized = false;}@@ -1403,6 +1423,21 @@ public class RevWalk implements Iterable<RevCommit>, AutoCloseable {throw new IllegalStateException(JGitText.get().outputHasAlreadyBeenStarted);}+ /**+ * Throws an exception if any commits have been marked as start.+ * <p>+ * If {@link #markStart(RevCommit)} has already been called,+ * {@link #reset()} can be called to satisfy this condition.+ *+ * @since 5.5+ */+ protected void assertNoCommitsMarkedStart() {+ if (roots.isEmpty())+ return;+ throw new IllegalStateException(+ JGitText.get().commitsHaveAlreadyBeenMarkedAsStart);+ }+private boolean isNotStarted() {return pending instanceof StartGenerator;}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.javaindex f1252a4c4b..3feb9c5a45 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@@ -1,44 +1,11 @@/*- * Copyright (C) 2011-2012, Robin Stocker <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2011-2012, Robin Stocker <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -50,6 +17,9 @@ import java.util.List;import org.eclipse.jgit.errors.IncorrectObjectTypeException;import org.eclipse.jgit.errors.MissingObjectException;+import org.eclipse.jgit.internal.JGitText;+import org.eclipse.jgit.lib.NullProgressMonitor;+import org.eclipse.jgit.lib.ProgressMonitor;import org.eclipse.jgit.lib.Ref;/**@@ -130,7 +100,7 @@ public final class RevWalkUtils {/*** Find the list of branches a given commit is reachable from when following- * parent.s+ * parents.* <p>* Note that this method calls* {@link org.eclipse.jgit.revwalk.RevWalk#reset()} at the beginning.@@ -153,15 +123,51 @@ public final class RevWalkUtils {RevWalk revWalk, Collection<Ref> refs)throws MissingObjectException, IncorrectObjectTypeException,IOException {+ return findBranchesReachableFrom(commit, revWalk, refs,+ NullProgressMonitor.INSTANCE);+ }++ /**+ * Find the list of branches a given commit is reachable from when following+ * parents.+ * <p>+ * Note that this method calls+ * {@link org.eclipse.jgit.revwalk.RevWalk#reset()} at the beginning.+ * <p>+ * In order to improve performance this method assumes clock skew among+ * committers is never larger than 24 hours.+ *+ * @param commit+ * the commit we are looking at+ * @param revWalk+ * The RevWalk to be used.+ * @param refs+ * the set of branches we want to see reachability from+ * @param monitor+ * the callback for progress and cancellation+ * @return the list of branches a given commit is reachable from+ * @throws org.eclipse.jgit.errors.MissingObjectException+ * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException+ * @throws java.io.IOException+ * @since 5.4+ */+ public static List<Ref> findBranchesReachableFrom(RevCommit commit,+ RevWalk revWalk, Collection<Ref> refs, ProgressMonitor monitor)+ throws MissingObjectException, IncorrectObjectTypeException,+ IOException {// Make sure commit is from the same RevWalkcommit = revWalk.parseCommit(commit.getId());revWalk.reset();List<Ref> result = new ArrayList<>();-+ monitor.beginTask(JGitText.get().searchForReachableBranches,+ refs.size());final int SKEW = 24*3600; // one day clock skewfor (Ref ref : refs) {+ if (monitor.isCancelled())+ return result;+ monitor.update(1);RevObject maybehead = revWalk.parseAny(ref.getObjectId());if (!(maybehead instanceof RevCommit))continue;@@ -176,6 +182,7 @@ public final class RevWalkUtils {if (revWalk.isMergedInto(commit, headCommit))result.add(ref);}+ monitor.endTask();return result;}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/RewriteGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/RewriteGenerator.javaindex 1c868ffe08..a928c2e79b 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/RewriteGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/RewriteGenerator.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -77,6 +44,7 @@ class RewriteGenerator extends Generator {private final Generator source;RewriteGenerator(Generator s) {+ super(s.firstParent);source = s;}@@ -103,6 +71,14 @@ class RewriteGenerator extends Generator {for (int i = 0; i < nParents; i++) {final RevCommit oldp = pList[i];final RevCommit newp = rewrite(oldp);+ if (firstParent) {+ if (newp == null) {+ c.parents = RevCommit.NO_PARENTS;+ } else {+ c.parents = new RevCommit[] { newp };+ }+ return c;+ }if (oldp != newp) {pList[i] = newp;rewrote = true;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.javaindex eb129a2631..2c1b0a59ee 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@@ -1,46 +1,13 @@/** Copyright (C) 2008-2009, Google Inc.* Copyright (C) 2008, Marek Zawirski <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -67,6 +34,7 @@ class StartGenerator extends Generator {private final RevWalk walker;StartGenerator(RevWalk w) {+ super(w.isFirstParent());walker = w;}@@ -89,9 +57,14 @@ class StartGenerator extends Generator {// Computing for merge bases is a special case and does not// use the bulk of the generator pipeline.//- if (tf != TreeFilter.ALL)+ if (tf != TreeFilter.ALL) {throw new IllegalStateException(MessageFormat.format(JGitText.get().cannotCombineTreeFilterWithRevFilter, tf, rf));+ }+ if (w.isFirstParent()) {+ throw new IllegalStateException(+ JGitText.get().cannotFindMergeBaseUsingFirstParent);+ }final MergeBaseGenerator mbg = new MergeBaseGenerator(w);walker.pending = mbg;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoSortGenerator.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoSortGenerator.javaindex 645034351f..7a5db43a7a 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoSortGenerator.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/TopoSortGenerator.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -71,15 +38,21 @@ class TopoSortGenerator extends Generator {*/TopoSortGenerator(Generator s) throws MissingObjectException,IncorrectObjectTypeException, IOException {- pending = new FIFORevQueue();+ super(s.firstParent);+ pending = new FIFORevQueue(firstParent);outputType = s.outputType() | SORT_TOPO;s.shareFreeList(pending);for (;;) {final RevCommit c = s.next();- if (c == null)+ if (c == null) {break;- for (RevCommit p : c.parents)+ }+ for (RevCommit p : c.parents) {p.inDegree++;+ if (firstParent) {+ break;+ }+ }pending.add(c);}}@@ -122,6 +95,9 @@ class TopoSortGenerator extends Generator {p.flags &= ~TOPO_DELAY;pending.unpop(p);}+ if (firstParent) {+ break;+ }}return c;}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/TreeRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/TreeRevFilter.javaindex 16835536fa..33259388ff 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/TreeRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/TreeRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk;@@ -116,8 +83,7 @@ public class TreeRevFilter extends RevFilter {* @param rewriteFlag* flag to color commits to be removed from the simplified DAT.*/- TreeRevFilter(final RevWalk walker, final TreeFilter t,- final int rewriteFlag) {+ TreeRevFilter(RevWalk walker, TreeFilter t, int rewriteFlag) {pathFilter = new TreeWalk(walker.reader);pathFilter.setFilter(t);pathFilter.setRecursive(t.shouldBeRecursive());@@ -137,14 +103,15 @@ public class TreeRevFilter extends RevFilter {IncorrectObjectTypeException, IOException {// Reset the tree filter to scan this commit and parents.//- final RevCommit[] pList = c.parents;- final int nParents = pList.length;- final TreeWalk tw = pathFilter;- final ObjectId[] trees = new ObjectId[nParents + 1];+ RevCommit[] pList = c.parents;+ int nParents = pList.length;+ TreeWalk tw = pathFilter;+ ObjectId[] trees = new ObjectId[nParents + 1];for (int i = 0; i < nParents; i++) {- final RevCommit p = c.parents[i];- if ((p.flags & PARSED) == 0)+ RevCommit p = c.parents[i];+ if ((p.flags & PARSED) == 0) {p.parseHeaders(walker);+ }trees[i] = p.getTree();}trees[nParents] = c.getTree();@@ -156,10 +123,11 @@ public class TreeRevFilter extends RevFilter {int chgs = 0, adds = 0;while (tw.next()) {chgs++;- if (tw.getRawMode(0) == 0 && tw.getRawMode(1) != 0)+ if (tw.getRawMode(0) == 0 && tw.getRawMode(1) != 0) {adds++;- else+ } else {break; // no point in looking at this further.+ }}if (chgs == 0) {@@ -168,25 +136,26 @@ public class TreeRevFilter extends RevFilter {//c.flags |= rewriteFlag;return false;- } else {- // We have interesting items, but neither of the special- // cases denoted above.+ }++ // We have interesting items, but neither of the special+ // cases denoted above.+ //+ if (adds > 0 && tw.getFilter() instanceof FollowFilter) {+ // One of the paths we care about was added in this+ // commit. We need to update our filter to its older+ // name, if we can discover it. Find out what that is.//- if (adds > 0 && tw.getFilter() instanceof FollowFilter) {- // One of the paths we care about was added in this- // commit. We need to update our filter to its older- // name, if we can discover it. Find out what that is.- //- updateFollowFilter(trees, ((FollowFilter) tw.getFilter()).cfg);- }- return true;+ updateFollowFilter(trees, ((FollowFilter) tw.getFilter()).cfg);}+ return true;} else if (nParents == 0) {// We have no parents to compare against. Consider us to be// REWRITE only if we have no paths matching our filter.//- if (tw.next())+ if (tw.next()) {return true;+ }c.flags |= rewriteFlag;return false;}@@ -196,18 +165,19 @@ public class TreeRevFilter extends RevFilter {// it does not contribute changes to us. Such a parent may be an// uninteresting side branch.//- final int[] chgs = new int[nParents];- final int[] adds = new int[nParents];+ int[] chgs = new int[nParents];+ int[] adds = new int[nParents];while (tw.next()) {- final int myMode = tw.getRawMode(nParents);+ int myMode = tw.getRawMode(nParents);for (int i = 0; i < nParents; i++) {- final int pMode = tw.getRawMode(i);- if (myMode == pMode && tw.idEqual(i, nParents))+ int pMode = tw.getRawMode(i);+ if (myMode == pMode && tw.idEqual(i, nParents)) {continue;-+ }chgs[i]++;- if (pMode == 0 && myMode != 0)+ if (pMode == 0 && myMode != 0) {adds[i]++;+ }}}@@ -220,7 +190,7 @@ public class TreeRevFilter extends RevFilter {// parent commit.//- final RevCommit p = pList[i];+ RevCommit p = pList[i];if ((p.flags & UNINTERESTING) != 0) {// This parent was marked as not interesting by the// application. We should look for another parent@@ -246,7 +216,7 @@ public class TreeRevFilter extends RevFilter {pList[i].parents = RevCommit.NO_PARENTS;}*/-+// We have an interesting difference relative to this parent.//diff = true;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.javaindex dfb83b491a..f48bc017e5 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AndRevFilter.java@@ -1,45 +1,12 @@/** Copyright (C) 2007, Robin Rosenberg <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.javaindex 334d4f0144..4fc83ce20e 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/AuthorRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.javaindex 38805153ef..6ac490a345 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitTimeRevFilter.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Mark Struberg <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.javaindex 37c840e379..69155d040b 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/CommitterRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.javaindex 02c6670758..0e3a803b64 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MaxCountRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2011, Tomasz Zarna <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2011, Tomasz Zarna <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.javaindex 480aaa38eb..91f9a07dec 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/MessageRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.javaindex 69dec567b8..1482c51291 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/NotRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.javaindex 777e4e01c5..519b9fb1d7 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/ObjectFilter.java@@ -1,44 +1,11 @@/**- * Copyright (C) 2015, Google Inc.- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2015, Google Inc. and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.javaindex 1cef12f79c..11f35e075e 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/OrRevFilter.java@@ -1,45 +1,12 @@/** Copyright (C) 2007, Robin Rosenberg <[email protected]>- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.javaindex 4f41edf54d..efb5ee5e4d 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/PatternMatchRevFilter.java@@ -1,45 +1,12 @@/** Copyright (C) 2009, Google Inc.- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;@@ -75,8 +42,8 @@ public abstract class PatternMatchRevFilter extends RevFilter {protected static final String forceToRaw(String patternText) {final byte[] b = Constants.encode(patternText);final StringBuilder needle = new StringBuilder(b.length);- for (int i = 0; i < b.length; i++)- needle.append((char) (b[i] & 0xff));+ for (byte element : b)+ needle.append((char) (element & 0xff));return needle.toString();}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.javaindex 39f0d60166..256e4794cd 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.javaindex c67c44b216..16d9f76143 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/RevFlagFilter.java@@ -1,49 +1,17 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;import java.io.IOException;+import java.util.Arrays;import org.eclipse.jgit.errors.IncorrectObjectTypeException;import org.eclipse.jgit.errors.MissingObjectException;@@ -78,8 +46,7 @@ public abstract class RevFlagFilter extends RevFilter {*/public static RevFilter hasAll(RevFlag... a) {final RevFlagSet set = new RevFlagSet();- for (RevFlag flag : a)- set.add(flag);+ set.addAll(Arrays.asList(a));return new HasAll(set);}@@ -103,8 +70,7 @@ public abstract class RevFlagFilter extends RevFilter {*/public static RevFilter hasAny(RevFlag... a) {final RevFlagSet set = new RevFlagSet();- for (RevFlag flag : a)- set.add(flag);+ set.addAll(Arrays.asList(a));return new HasAny(set);}diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.javaindex 79af5a3d4b..84df36a2d2 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SkipRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2011, Tomasz Zarna <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2011, Tomasz Zarna <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.java b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.javaindex 54650da0e0..7f00dfd504 100644--- a/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.java+++ b/server-core/src/main/java/org/eclipse/jgit/revwalk/filter/SubStringRevFilter.java@@ -1,44 +1,11 @@/*- * Copyright (C) 2008, Shawn O. Pearce <[email protected]>- * and other copyright owners as documented in the project's IP log.+ * Copyright (C) 2008, Shawn O. Pearce <[email protected]> and others*- * 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+ * 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.*- * 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.+ * SPDX-License-Identifier: BSD-3-Clause*/package org.eclipse.jgit.revwalk.filter;diff --git a/server-core/src/test/java/io/onedev/server/git/AbstractGitTest.java b/server-core/src/test/java/io/onedev/server/git/AbstractGitTest.javaindex 9d4db1bf3a..f26d29117f 100644--- a/server-core/src/test/java/io/onedev/server/git/AbstractGitTest.java+++ b/server-core/src/test/java/io/onedev/server/git/AbstractGitTest.java@@ -7,6 +7,7 @@ import javax.annotation.Nullable;import org.eclipse.jgit.api.AddCommand;import org.eclipse.jgit.api.CommitCommand;+import org.eclipse.jgit.api.Git;import org.eclipse.jgit.api.RmCommand;import org.eclipse.jgit.api.errors.GitAPIException;import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;@@ -30,7 +31,7 @@ public abstract class AbstractGitTest extends AppLoaderMocker {protected File gitDir;- protected org.eclipse.jgit.api.Git git;+ protected Git git;protected PersonIdent user = new PersonIdent("foo", "[email protected]");@@ -39,7 +40,7 @@ public abstract class AbstractGitTest extends AppLoaderMocker {gitDir = FileUtils.createTempDir();try {- git = org.eclipse.jgit.api.Git.init().setBare(false).setDirectory(gitDir).call();+ git = Git.init().setBare(false).setDirectory(gitDir).call();} catch (IllegalStateException | GitAPIException e) {throw new RuntimeException(e);}@@ -62,29 +63,40 @@ public abstract class AbstractGitTest extends AppLoaderMocker {Assert.assertTrue(gitError, gitError == null);}- @Override- protected void teardown() {- git.close();-- while (gitDir.exists()) {+ protected void deleteDir(File dir, int retries) {+ int retried = 0;+ while (dir.exists()) {try {- FileUtils.deleteDir(gitDir);+ FileUtils.deleteDir(dir);break;} catch (Exception e) {- // git gc might be running, so we'll retry deletion- logger.error("Error deleting directory '" + gitDir.getAbsolutePath() + "', will retry later...", e);- try {- Thread.sleep(5000);- } catch (InterruptedException e2) {+ if (retried++ < retries) {+ logger.error("Error deleting directory '" + dir.getAbsolutePath() + "', will retry later...", e);+ try {+ Thread.sleep(5000);+ } catch (InterruptedException e2) {+ }+ } else {+ throw e;}}}}++ @Override+ protected void teardown() {+ git.close();+ deleteDir(gitDir, 3);+ }protected void createDir(String path) {FileUtils.createDir(new File(gitDir, path));}+ protected void deleteDir(String path) {+ FileUtils.deleteDir(new File(gitDir, path));+ }+protected void writeFile(String path, String content) {File file = new File(gitDir, path);FileUtils.writeFile(file, content);diff --git a/server-core/src/test/java/io/onedev/server/git/GitUtilsTest.java b/server-core/src/test/java/io/onedev/server/git/GitUtilsTest.javaindex 9286f6bcac..97f75fee4f 100644--- a/server-core/src/test/java/io/onedev/server/git/GitUtilsTest.java+++ b/server-core/src/test/java/io/onedev/server/git/GitUtilsTest.java@@ -1,11 +1,17 @@package io.onedev.server.git;import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertNotNull;import static org.junit.Assert.assertNull;+import static org.junit.Assert.assertTrue;+import java.io.File;+import java.io.InputStream;import java.util.HashSet;import java.util.Set;+import org.eclipse.jgit.api.Git;+import org.eclipse.jgit.lib.FileMode;import org.eclipse.jgit.lib.ObjectId;import org.eclipse.jgit.revwalk.RevCommit;import org.eclipse.jgit.revwalk.RevWalk;@@ -13,6 +19,10 @@ import org.eclipse.jgit.treewalk.TreeWalk;import org.junit.Test;import com.google.common.collect.Sets;+import com.google.common.io.Resources;++import io.onedev.commons.utils.FileUtils;+import io.onedev.commons.utils.ZipUtils;public class GitUtilsTest extends AbstractGitTest {@@ -117,7 +127,8 @@ public class GitUtilsTest extends AbstractGitTest {addFileAndCommit("master2", "", "master2");ObjectId masterId = git.getRepository().resolve("master");ObjectId devId = git.getRepository().resolve("dev");- ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), devId, masterId, false, user, user, "merge commit");+ ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), masterId, devId, false,+ user, user, "merge commit", false);try ( RevWalk revWalk = new RevWalk(git.getRepository());TreeWalk treeWalk = new TreeWalk(git.getRepository())) {RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);@@ -134,7 +145,7 @@ public class GitUtilsTest extends AbstractGitTest {}@Test- public void testMergeWithConflicts() throws Exception {+ public void testMergeWithContentConflict() throws Exception {addFileAndCommit("initial", "", "initial");git.checkout().setCreateBranch(true).setName("dev").call();addFileAndCommit("dev1", "", "dev1");@@ -142,8 +153,290 @@ public class GitUtilsTest extends AbstractGitTest {git.checkout().setName("master").call();addFileAndCommit("master1", "", "master1");addFileAndCommit("conflict", "2", "master2");- assertNull(GitUtils.merge(git.getRepository(), git.getRepository().resolve("dev"),- git.getRepository().resolve("master"), false, user, user, "merge commit"));+ assertNull(GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false));++ ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);+ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "conflict", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "conflict", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("2", blob.getText().getContent());+ }++ }++ @Test+ public void testMergeWithDeletionAndModificationConflict() throws Exception {+ addFileAndCommit("file", "", "initial commit");+ git.checkout().setCreateBranch(true).setName("dev").call();+ removeFileAndCommit("file", "remove file");+ git.checkout().setName("master").call();+ addFileAndCommit("file", "1", "master");++ assertNull(GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false));++ ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);+ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "file", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "file", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("1", blob.getText().getContent());+ }+ }++ @Test+ public void testMergeWithBindaryConflict() throws Exception {+ addFileAndCommit("file", "", "initial commit");+ git.checkout().setCreateBranch(true).setName("dev").call();++ createDir("dir1");+ File file = new File(gitDir, "dir1/file");+ byte[] content = new byte[1000];+ for (int i=0; i<content.length; i++)+ content[i] = 1;+ FileUtils.writeByteArrayToFile(file, content);+ add("dir1/file");+ commit("add dir1/file");++ addFileAndCommit("dir2/file", "111\n222\n333\n444\n555\n", "add dir2/file");++ git.checkout().setName("master").call();++ createDir("dir1");+ file = new File(gitDir, "dir1/file");+ content = new byte[2000];+ for (int i=0; i<content.length; i++)+ content[i] = 2;+ FileUtils.writeByteArrayToFile(file, content);+ add("dir1/file");+ commit("add dir1/file");++ addFileAndCommit("dir2/file", "111\n222\n333\n444\n555\naaa\n", "add dir2/file");++ assertNull(GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false));++ ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);+ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "dir1/file", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "dir1/file", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals(2000, blob.getBytes().length);++ treeWalk = TreeWalk.forPath(git.getRepository(), "dir2/file", mergeCommit.getTree());+ blobIdent = new BlobIdent(mergeCommit.name(), "dir2/file", FileMode.REGULAR_FILE.getBits());+ blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("111\n222\n333\n444\n555\naaa\n", blob.getText().getContent());+ }++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("dev"),+ git.getRepository().resolve("master"), false, user, user, "merge commit", true);+ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "dir1/file", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "dir1/file", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals(1000, blob.getBytes().length);++ treeWalk = TreeWalk.forPath(git.getRepository(), "dir2/file", mergeCommit.getTree());+ blobIdent = new BlobIdent(mergeCommit.name(), "dir2/file", FileMode.REGULAR_FILE.getBits());+ blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("111\n222\n333\n444\n555\n", blob.getText().getContent());+ }}+ @Test+ public void testMergeWithFileAndFolderConflict() throws Exception {+ addFileAndCommit("file", "", "initial commit");+ git.checkout().setCreateBranch(true).setName("dev").call();++ git.checkout().setName("master").call();+ createDir("newpath");+ addFileAndCommit("newpath/file", "1", "new path");++ git.checkout().setName("dev").call();+ addFileAndCommit("newpath", "2", "new path");++ ObjectId mergeCommitId;++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false);++ assertNull(mergeCommitId);++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);+ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "newpath", mergeCommit.getTree());+ assertEquals(FileMode.TREE, treeWalk.getFileMode());++ treeWalk = TreeWalk.forPath(git.getRepository(), "newpath/file", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "newpath/file", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("1", blob.getText().getContent());+ }++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("dev"),+ git.getRepository().resolve("master"), false, user, user, "merge commit", true);+ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "newpath", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "newpath", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("2", blob.getText().getContent());+ }+ }++ @Test+ public void testMergeWithLinkAndLinkConflict() throws Exception {+ File tempDir;++ tempDir = FileUtils.createTempDir();+ try (InputStream is = Resources.getResource(GitUtilsTest.class, "git-conflict-link-link.zip").openStream()) {+ ZipUtils.unzip(is, tempDir);+ try (Git git = Git.open(tempDir)) {+ ObjectId mergeCommitId;++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false);++ assertNull(mergeCommitId);++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);++ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "lib", mergeCommit.getTree());+ assertTrue(treeWalk != null && treeWalk.getFileMode(0) == FileMode.GITLINK);+ treeWalk = TreeWalk.forPath(git.getRepository(), ".gitmodules", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), ".gitmodules", FileMode.GITLINK.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertTrue(blob.getText().getContent().trim().endsWith("/home/robin/temp/lib"));+ }+ }+ } finally {+ deleteDir(tempDir, 3);+ }+ }++ @Test+ public void testMergeWithLinkAndFileConflict() throws Exception {+ File tempDir;++ tempDir = FileUtils.createTempDir();+ try (InputStream is = Resources.getResource(GitUtilsTest.class, "git-conflict-link-file.zip").openStream()) {+ ZipUtils.unzip(is, tempDir);+ try (Git git = Git.open(tempDir)) {+ ObjectId mergeCommitId;++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false);++ assertNull(mergeCommitId);++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);++ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "lib", mergeCommit.getTree());+ assertTrue(treeWalk != null && treeWalk.getFileMode(0) == FileMode.GITLINK);+ treeWalk = TreeWalk.forPath(git.getRepository(), ".gitmodules", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), ".gitmodules", FileMode.GITLINK.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertTrue(blob.getText().getContent().trim().endsWith("/home/robin/temp/lib"));+ }++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("dev"),+ git.getRepository().resolve("master"), false, user, user, "merge commit", true);++ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "lib", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "lib", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertEquals("lib", blob.getText().getContent().trim());+ }+ }+ } finally {+ deleteDir(tempDir, 3);+ }++ }++ @Test+ public void testMergeWithLinkAndDirConflict() throws Exception {+ File tempDir;++ tempDir = FileUtils.createTempDir();+ try (InputStream is = Resources.getResource(GitUtilsTest.class, "git-conflict-link-dir.zip").openStream()) {+ ZipUtils.unzip(is, tempDir);+ try (Git git = Git.open(tempDir)) {+ ObjectId mergeCommitId;++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", false);++ assertNull(mergeCommitId);++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"),+ git.getRepository().resolve("dev"), false, user, user, "merge commit", true);++ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "lib", mergeCommit.getTree());+ assertTrue(treeWalk != null && treeWalk.getFileMode(0) == FileMode.GITLINK);+ treeWalk = TreeWalk.forPath(git.getRepository(), ".gitmodules", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), ".gitmodules", FileMode.GITLINK.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertTrue(blob.getText().getContent().trim().endsWith("/home/robin/temp/lib/"));+ }++ mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("dev"),+ git.getRepository().resolve("master"), false, user, user, "merge commit", true);++ assertNotNull(mergeCommitId);++ try ( RevWalk revWalk = new RevWalk(git.getRepository())) {+ RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);+ TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "lib/file", mergeCommit.getTree());+ BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "lib/file", FileMode.REGULAR_FILE.getBits());+ Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());+ assertTrue(blob.getText().getContent().length() == 0);+ }+ }+ } finally {+ deleteDir(tempDir, 3);+ }+ }}diff --git a/server-core/src/test/java/io/onedev/server/git/git-conflict-link-dir.zip b/server-core/src/test/java/io/onedev/server/git/git-conflict-link-dir.zipnew file mode 100644index 0000000000..d3d1915621Binary files /dev/null and b/server-core/src/test/java/io/onedev/server/git/git-conflict-link-dir.zip differdiff --git a/server-core/src/test/java/io/onedev/server/git/git-conflict-link-file.zip b/server-core/src/test/java/io/onedev/server/git/git-conflict-link-file.zipnew file mode 100644index 0000000000..5e0ed5655eBinary files /dev/null and b/server-core/src/test/java/io/onedev/server/git/git-conflict-link-file.zip differdiff --git a/server-core/src/test/java/io/onedev/server/git/git-conflict-link-link.zip b/server-core/src/test/java/io/onedev/server/git/git-conflict-link-link.zipnew file mode 100644index 0000000000..8bad652114Binary files /dev/null and b/server-core/src/test/java/io/onedev/server/git/git-conflict-link-link.zip differ