The Unified and Autonomous Development Platform
Fix issue #1076 - Partial issue refresh after closing via commit
Robin Shen3ca6e75ba680
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.javaindex 18136b456c..fee24ea45f 100644--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java@@ -17,6 +17,7 @@ import io.onedev.server.entityreference.ReferencedFromAware;import io.onedev.server.event.Listen;import io.onedev.server.event.ListenerRegistry;import io.onedev.server.event.entity.EntityRemoved;+import io.onedev.server.event.project.issue.IssueCommitsAttached;import io.onedev.server.event.project.issue.IssueChanged;import io.onedev.server.event.project.issue.IssueEvent;import io.onedev.server.event.project.issue.IssueOpened;@@ -321,7 +322,9 @@ public class DefaultIssueManager extends BaseEntityManager<Issue> implements Iss@Listenpublic void on(IssueEvent event) {boolean minorChange = false;- if (event instanceof IssueChanged) {+ if (event instanceof IssueCommitsAttached) {+ minorChange = true;+ } else if (event instanceof IssueChanged) {IssueChangeData changeData = ((IssueChanged)event).getChange().getData();if (changeData instanceof ReferencedFromAware)minorChange = true;diff --git a/server-core/src/main/java/io/onedev/server/event/project/issue/IssueCommitsAttached.java b/server-core/src/main/java/io/onedev/server/event/project/issue/IssueCommitsAttached.javanew file mode 100644index 0000000000..33f97a5cb9--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/event/project/issue/IssueCommitsAttached.java@@ -0,0 +1,25 @@+package io.onedev.server.event.project.issue;++import io.onedev.server.model.Issue;++import java.util.Date;++public class IssueCommitsAttached extends IssueEvent {++ private static final long serialVersionUID = 1L;++ public IssueCommitsAttached(Issue issue) {+ super(null, new Date(), issue);+ }++ @Override+ public boolean affectsListing() {+ return false;+ }++ @Override+ public String getActivity() {+ return "commits attached";+ }++}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 d81890f05b..2437e8801c 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@@ -1,55 +1,7 @@package io.onedev.server.infomanager;-import java.io.File;-import java.io.IOException;-import java.io.InputStream;-import java.io.ObjectStreamException;-import java.io.Serializable;-import java.nio.ByteBuffer;-import java.nio.charset.StandardCharsets;-import java.util.ArrayList;-import java.util.Collection;-import java.util.Collections;-import java.util.Comparator;-import java.util.EnumSet;-import java.util.HashMap;-import java.util.HashSet;-import java.util.Iterator;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-import java.util.Optional;-import java.util.Set;-import java.util.Stack;-import java.util.UUID;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.atomic.AtomicInteger;-import java.util.function.Consumer;--import javax.annotation.Nullable;-import javax.inject.Inject;-import javax.inject.Singleton;-import javax.ws.rs.client.Client;-import javax.ws.rs.client.ClientBuilder;-import javax.ws.rs.client.Invocation;-import javax.ws.rs.client.WebTarget;-import javax.ws.rs.core.HttpHeaders;-import javax.ws.rs.core.Response;--import org.apache.commons.lang3.SerializationUtils;-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.revwalk.RevCommit;-import org.eclipse.jgit.revwalk.RevObject;-import org.eclipse.jgit.revwalk.RevWalk;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;-import com.google.common.base.Preconditions;import com.google.common.base.Splitter;-import io.onedev.commons.loader.ManagedSerializedForm;import io.onedev.commons.utils.FileUtils;import io.onedev.commons.utils.PathUtils;@@ -58,32 +10,25 @@ import io.onedev.k8shelper.KubernetesHelper;import io.onedev.server.cluster.ClusterManager;import io.onedev.server.cluster.ClusterTask;import io.onedev.server.entitymanager.EmailAddressManager;+import io.onedev.server.entitymanager.IssueManager;import io.onedev.server.entitymanager.ProjectManager;import io.onedev.server.entitymanager.UserManager;import io.onedev.server.event.Listen;+import io.onedev.server.event.ListenerRegistry;import io.onedev.server.event.entity.EntityRemoved;import io.onedev.server.event.project.RefUpdated;+import io.onedev.server.event.project.issue.IssueCommitsAttached;import io.onedev.server.event.system.SystemStarted;import io.onedev.server.git.GitContribution;import io.onedev.server.git.GitContributor;import io.onedev.server.git.GitUtils;-import io.onedev.server.git.command.FileChange;-import io.onedev.server.git.command.GitCommit;-import io.onedev.server.git.command.ListFileChangesCommand;-import io.onedev.server.git.command.ListFilesCommand;-import io.onedev.server.git.command.ListNumStatsCommand;-import io.onedev.server.git.command.LogCommand;-import io.onedev.server.git.command.RevListCommand;+import io.onedev.server.git.command.*;import io.onedev.server.git.command.RevListCommand.Order;import io.onedev.server.model.Project;import io.onedev.server.persistence.SessionManager;import io.onedev.server.persistence.annotation.Sessional;import io.onedev.server.storage.StorageManager;-import io.onedev.server.util.Day;-import io.onedev.server.util.ElementPumper;-import io.onedev.server.util.NameAndEmail;-import io.onedev.server.util.Pair;-import io.onedev.server.util.ProgrammingLanguageDetector;+import io.onedev.server.util.*;import io.onedev.server.util.concurrent.BatchWorkManager;import io.onedev.server.util.concurrent.BatchWorker;import io.onedev.server.util.concurrent.Prioritized;@@ -95,109 +40,137 @@ import jetbrains.exodus.ByteIterable;import jetbrains.exodus.backup.BackupStrategy;import jetbrains.exodus.backup.BackupStrategy.FileDescriptor;import jetbrains.exodus.backup.VirtualFileDescriptor;-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;+import jetbrains.exodus.env.*;+import org.apache.commons.lang3.SerializationUtils;+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.revwalk.RevCommit;+import org.eclipse.jgit.revwalk.RevObject;+import org.eclipse.jgit.revwalk.RevWalk;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import javax.annotation.Nullable;+import javax.inject.Inject;+import javax.inject.Singleton;+import javax.ws.rs.client.Client;+import javax.ws.rs.client.ClientBuilder;+import javax.ws.rs.client.Invocation;+import javax.ws.rs.client.WebTarget;+import javax.ws.rs.core.HttpHeaders;+import javax.ws.rs.core.Response;+import java.io.*;+import java.nio.ByteBuffer;+import java.nio.charset.StandardCharsets;+import java.util.*;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Consumer;@Singleton-public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager+public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerimplements CommitInfoManager, Serializable {private static final long serialVersionUID = 1L;private static final Logger logger = LoggerFactory.getLogger(DefaultCommitInfoManager.class);-+private static final int INFO_VERSION = 15;-- private static final long LOG_FILE_SIZE = 256*1024;-++ private static final long LOG_FILE_SIZE = 256 * 1024;+private static final int COLLECT_BATCH_SIZE = 10000;-+private static final int MAX_HISTORY_PATHS = 100;-+private static final int MAX_COMMIT_FILES = 100;-+private static final String INFO_DIR = "commit";-+private static final String DEFAULT_STORE = "default";-+private static final String COMMITS_STORE = "commits";-+private static final String FIX_COMMITS_STORE = "fixCommits";-+private static final String COMMIT_COUNTS_STORE = "commitCounts";private static final String HISTORY_PATHS_STORE = "historyPaths";-+private static final String PATH_TO_INDEX_STORE = "pathToIndex";-+private static final String INDEX_TO_PATH_STORE = "indexToPath";-+private static final String USER_TO_INDEX_STORE = "userToIndex";-+private static final String INDEX_TO_USER_STORE = "indexToUser";-+private static final String EMAIL_TO_INDEX_STORE = "emailToIndex";-+private static final String DAILY_CONTRIBUTIONS_STORE = "dailyContributions";-+private static final ByteIterable NEXT_PATH_INDEX_KEY = new StringByteIterable("nextPathIndex");-+private static final ByteIterable NEXT_USER_INDEX_KEY = new StringByteIterable("nextUserIndex");-+private static final ByteIterable NEXT_EMAIL_INDEX_KEY = new StringByteIterable("nextEmailIndex");-+private static final ByteIterable LAST_COMMIT_KEY = new StringByteIterable("lastCommit");-+private static final ByteIterable LAST_COMMIT_OF_LINE_STATS_KEY = new StringByteIterable("lastCommitOfLineStats");-+private static final ByteIterable LAST_COMMIT_OF_CONTRIBS_KEY = new StringByteIterable("lastCommitOfContribs");-+private static final ByteIterable LAST_COMMIT_OF_FILES_KEY = new StringByteIterable("lastCommitOfFiles");-+private static final ByteIterable LINE_STATS_KEY = new StringByteIterable("lineStats");-+private static final ByteIterable USERS_KEY = new StringByteIterable("users");-+private static final ByteIterable FILES_KEY = new StringByteIterable("files");-+private static final ByteIterable FILE_COUNT_KEY = new StringByteIterable("fileCount");-+private static final ByteIterable OVERALL_CONTRIBUTIONS_KEY = new StringByteIterable("overallContributions");-+private static final ByteIterable COMMIT_COUNT_KEY = new StringByteIterable("commitCount");-+private static final int PRIORITY = 100;-+private final StorageManager storageManager;-+private final BatchWorkManager batchWorkManager;-+private final ProjectManager projectManager;-+private final SessionManager sessionManager;-+private final ClusterManager clusterManager;-+private final UserManager userManager;-+private final EmailAddressManager emailAddressManager;-++ private final IssueManager issueManager;++ private final ListenerRegistry listenerRegistry;+private final Map<Long, List<String>> filesCache = new ConcurrentHashMap<>();-+private final Map<Long, Integer> fileCountCache = new ConcurrentHashMap<>();-+private final Map<Long, Integer> totalCommitCountCache = new ConcurrentHashMap<>();-+private final Map<Long, List<NameAndEmail>> usersCache = new ConcurrentHashMap<>();-+@Inject- public DefaultCommitInfoManager(ProjectManager projectManager, StorageManager storageManager,- BatchWorkManager batchWorkManager, SessionManager sessionManager,- EmailAddressManager emailAddressManager, UserManager userManager,- ClusterManager clusterManager) {+ public DefaultCommitInfoManager(ProjectManager projectManager, StorageManager storageManager,+ BatchWorkManager batchWorkManager, SessionManager sessionManager,+ EmailAddressManager emailAddressManager, UserManager userManager,+ ClusterManager clusterManager, ListenerRegistry listenerRegistry,+ IssueManager issueManager) {this.projectManager = projectManager;this.storageManager = storageManager;this.batchWorkManager = batchWorkManager;@@ -205,23 +178,25 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerthis.emailAddressManager = emailAddressManager;this.userManager = userManager;this.clusterManager = clusterManager;+ this.listenerRegistry = listenerRegistry;+ this.issueManager = issueManager;}-+private boolean isCommitCollected(byte[] commitBytes) {/*- * Collected commits stores an additional byte to differentiate from those not collected but with parent- * information stored+ * Collected commits stores an additional byte to differentiate from those not collected but with parent+ * information stored*/return commitBytes != null && commitBytes.length % 20 != 0;}-+private void doCollect(Project project, ObjectId commitId, String refName) {logger.debug("Collecting commit information (project: {}, ref: {})...", project.getPath(), refName);-+Environment env = getEnv(project.getId().toString());Store defaultStore = getStore(env, DEFAULT_STORE);Store commitsStore = getStore(env, COMMITS_STORE);- Store commitCountsStore = getStore(env, COMMIT_COUNTS_STORE);+ Store commitCountsStore = getStore(env, COMMIT_COUNTS_STORE);Store historyPathsStore = getStore(env, HISTORY_PATHS_STORE);Store pathToIndexStore = getStore(env, PATH_TO_INDEX_STORE);Store indexToPathStore = getStore(env, INDEX_TO_PATH_STORE);@@ -229,16 +204,16 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerStore emailToIndexStore = getStore(env, EMAIL_TO_INDEX_STORE);Store indexToUserStore = getStore(env, INDEX_TO_USER_STORE);Store fixCommitsStore = getStore(env, FIX_COMMITS_STORE);-+Repository repository = projectManager.getRepository(project.getId());Pair<byte[], ObjectId> result = env.computeInTransaction(new TransactionalComputable<Pair<byte[], ObjectId>>() {-+@Overridepublic Pair<byte[], ObjectId> compute(Transaction txn) {ByteIterable commitKey = new CommitByteIterable(commitId);byte[] commitBytes = readBytes(commitsStore, txn, commitKey);-+ObjectId lastCommitId;byte[] lastCommitBytes = readBytes(defaultStore, txn, LAST_COMMIT_KEY);if (lastCommitBytes != null) {@@ -252,30 +227,30 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager} else {lastCommitId = null;}-+return new Pair<>(commitBytes, lastCommitId);}});-+if (!isCommitCollected(result.getFirst())) {processCommitRange(project, commitId, result.getSecond(), new CommitRangeProcessor() {@Overridepublic void process(ObjectId untilCommitId, ObjectId sinceCommitId) {env.executeInTransaction(new TransactionalExecutable() {-+@SuppressWarnings("unchecked")@Overridepublic void execute(Transaction txn) {AtomicInteger totalCommitCount = new AtomicInteger(readInt(defaultStore, txn, COMMIT_COUNT_KEY, 0));-+NextIndex nextIndex = new NextIndex();nextIndex.user = readInt(defaultStore, txn, NEXT_USER_INDEX_KEY, 0);nextIndex.email = readInt(defaultStore, txn, NEXT_EMAIL_INDEX_KEY, 0);nextIndex.path = readInt(defaultStore, txn, NEXT_PATH_INDEX_KEY, 0);-+Map<Long, Integer> commitCountCache = new HashMap<>();-+Set<NameAndEmail> users;byte[] userBytes = readBytes(defaultStore, txn, USERS_KEY);if (userBytes != null)@@ -301,7 +276,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerprotected void consume(GitCommit commit) {consumer.accept(commit);}-+}.fields(fields).run();}@@ -310,47 +285,47 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerObjectId currentCommitId = ObjectId.fromString(currentCommit.getHash());ByteIterable currentCommitKey = new CommitByteIterable(currentCommitId);byte[] currentCommitBytes = readBytes(commitsStore, txn, currentCommitKey);-+if (!isCommitCollected(currentCommitBytes)) {totalCommitCount.incrementAndGet();-+byte[] newCurrentCommitBytes;if (currentCommitBytes == null) {newCurrentCommitBytes = new byte[1];} else {- newCurrentCommitBytes = new byte[1+currentCommitBytes.length];+ newCurrentCommitBytes = new byte[1 + currentCommitBytes.length];System.arraycopy(currentCommitBytes, 0, newCurrentCommitBytes, 1, currentCommitBytes.length);}-+commitsStore.put(txn, currentCommitKey, new ArrayByteIterable(newCurrentCommitBytes));-- for (String parentCommitHash: currentCommit.getParentHashes()) {++ for (String parentCommitHash : currentCommit.getParentHashes()) {ByteIterable parentCommitKey = new CommitByteIterable(ObjectId.fromString(parentCommitHash));byte[] parentCommitBytes = readBytes(commitsStore, txn, parentCommitKey);byte[] newParentCommitBytes;if (parentCommitBytes != null) {- newParentCommitBytes = new byte[parentCommitBytes.length+20];+ newParentCommitBytes = new byte[parentCommitBytes.length + 20];System.arraycopy(parentCommitBytes, 0, newParentCommitBytes, 0, parentCommitBytes.length);} else {newParentCommitBytes = new byte[20];}- currentCommitId.copyRawTo(newParentCommitBytes, newParentCommitBytes.length-20);+ currentCommitId.copyRawTo(newParentCommitBytes, newParentCommitBytes.length - 20);commitsStore.put(txn, parentCommitKey, new ArrayByteIterable(newParentCommitBytes));}-+String commitMessage = currentCommit.getSubject();if (currentCommit.getBody() != null)commitMessage += "\n\n" + currentCommit.getBody();-+Repository repository = projectManager.getRepository(project.getId());- for (Long issueId: project.parseFixedIssueIds(commitMessage)) {+ for (Long issueId : project.parseFixedIssueIds(commitMessage)) {ByteIterable issueKey = new LongByteIterable(issueId);Collection<ObjectId> fixingCommits = readCommits(fixCommitsStore, txn, issueKey);-+boolean addNextCommit = true;- for (Iterator<ObjectId> it = fixingCommits.iterator(); it.hasNext();) {+ for (Iterator<ObjectId> it = fixingCommits.iterator(); it.hasNext(); ) {ObjectId fixCommit = it.next();- if (GitUtils.isMergedInto(repository, null, fixCommit, currentCommitId)) {+ if (GitUtils.isMergedInto(repository, null, fixCommit, currentCommitId)) {it.remove();} else if (GitUtils.isMergedInto(repository, null, currentCommitId, fixCommit)) {addNextCommit = false;@@ -360,52 +335,53 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerif (addNextCommit)fixingCommits.add(currentCommitId);writeCommits(fixCommitsStore, txn, issueKey, fixingCommits);+ listenerRegistry.post(new IssueCommitsAttached(issueManager.load(issueId)));}-+if (currentCommit.getCommitter() != null)users.add(new NameAndEmail(currentCommit.getCommitter()));if (currentCommit.getAuthor() != null) {NameAndEmail nameAndEmail = new NameAndEmail(currentCommit.getAuthor());users.add(nameAndEmail);-- ByteIterable authorKey = new ArrayByteIterable(SerializationUtils.serialize(nameAndEmail));++ ByteIterable authorKey = new ArrayByteIterable(SerializationUtils.serialize(nameAndEmail));int userIndex = readInt(userToIndexStore, txn, authorKey, -1);if (userIndex == -1) {userIndex = nextIndex.user++;writeInt(userToIndexStore, txn, authorKey, userIndex);indexToUserStore.put(txn, new IntByteIterable(userIndex), authorKey);}-- ByteIterable emailKey = new StringByteIterable(nameAndEmail.getEmailAddress());++ ByteIterable emailKey = new StringByteIterable(nameAndEmail.getEmailAddress());int emailIndex = readInt(emailToIndexStore, txn, emailKey, -1);if (emailIndex == -1) {emailIndex = nextIndex.email++;writeInt(emailToIndexStore, txn, emailKey, emailIndex);}-- for (FileChange change: currentCommit.getFileChanges()) {- for (String path: change.getPaths()) {- int pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,++ for (FileChange change : currentCommit.getFileChanges()) {+ for (String path : change.getPaths()) {+ int pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,nextIndex, path);updateCommitCount(commitCountsStore, txn, commitCountCache, emailIndex, pathIndex);while (path.contains("/")) {path = StringUtils.substringBeforeLast(path, "/");- pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,+ pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,nextIndex, path);updateCommitCount(commitCountsStore, txn, commitCountCache, emailIndex, pathIndex);}- pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,+ pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,nextIndex, "");updateCommitCount(commitCountsStore, txn, commitCountCache, emailIndex, pathIndex);}}}-- for (FileChange change: currentCommit.getFileChanges()) {- if (change.getOldPath() != null && change.getNewPath() != null++ for (FileChange change : currentCommit.getFileChanges()) {+ if (change.getOldPath() != null && change.getNewPath() != null&& !change.getOldPath().equals(change.getNewPath())) {- int pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,+ int pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,nextIndex, change.getNewPath());ByteIterable pathKey = new IntByteIterable(pathIndex);Set<Integer> historyPathIndexes = new HashSet<>();@@ -413,7 +389,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerif (bytesOfHistoryPaths == null) {bytesOfHistoryPaths = new byte[0];int pos = 0;- for (int i=0; i<bytesOfHistoryPaths.length/Integer.SIZE; i++) {+ for (int i = 0; i < bytesOfHistoryPaths.length / Integer.SIZE; i++) {historyPathIndexes.add(ByteBuffer.wrap(bytesOfHistoryPaths, pos, Integer.SIZE).getInt());pos += Integer.SIZE;}@@ -421,23 +397,23 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerhistoryPathIndexes = new HashSet<>();}if (historyPathIndexes.size() < MAX_HISTORY_PATHS) {- int oldPathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,+ int oldPathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,nextIndex, change.getOldPath());if (!historyPathIndexes.contains(oldPathIndex)) {historyPathIndexes.add(oldPathIndex);- byte[] newBytesOfHistoryPaths =- new byte[bytesOfHistoryPaths.length+Integer.SIZE];- System.arraycopy(bytesOfHistoryPaths, 0,+ byte[] newBytesOfHistoryPaths =+ new byte[bytesOfHistoryPaths.length + Integer.SIZE];+ System.arraycopy(bytesOfHistoryPaths, 0,newBytesOfHistoryPaths, 0, bytesOfHistoryPaths.length);- ByteBuffer buffer = ByteBuffer.wrap(newBytesOfHistoryPaths,+ ByteBuffer buffer = ByteBuffer.wrap(newBytesOfHistoryPaths,bytesOfHistoryPaths.length, Integer.BYTES);buffer.putInt(oldPathIndex);- historyPathsStore.put(txn, pathKey,+ historyPathsStore.put(txn, pathKey,new ArrayByteIterable(newBytesOfHistoryPaths));}}}- }+ }}}@@ -445,32 +421,32 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerwriteInt(defaultStore, txn, COMMIT_COUNT_KEY, totalCommitCount.get());totalCommitCountCache.remove(project.getId());-+writeInt(defaultStore, txn, NEXT_USER_INDEX_KEY, nextIndex.user);writeInt(defaultStore, txn, NEXT_EMAIL_INDEX_KEY, nextIndex.email);writeInt(defaultStore, txn, NEXT_PATH_INDEX_KEY, nextIndex.path);-+userBytes = SerializationUtils.serialize((Serializable) users);defaultStore.put(txn, USERS_KEY, new ArrayByteIterable(userBytes));usersCache.remove(project.getId());-- for (Map.Entry<Long, Integer> entry: commitCountCache.entrySet())++ for (Map.Entry<Long, Integer> entry : commitCountCache.entrySet())writeInt(commitCountsStore, txn, new LongByteIterable(entry.getKey()), entry.getValue());-+defaultStore.put(txn, LAST_COMMIT_KEY, new CommitByteIterable(untilCommitId));}});}-+});}-+if (GitUtils.branch2ref(project.getDefaultBranch()).equals(refName)) {collectLineStats(project, commitId);collectContribs(project, commitId);collectFiles(project, commitId);- }-+ }+logger.debug("Collected commit information (project: {}, ref: {})", project.getPath(), refName);}@@ -478,13 +454,13 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerEnvironment env = getEnv(project.getId().toString());Store defaultStore = getStore(env, DEFAULT_STORE);Store userToIndexStore = getStore(env, USER_TO_INDEX_STORE);- Store dailyContributionsStore = getStore(env, DAILY_CONTRIBUTIONS_STORE);-+ Store dailyContributionsStore = getStore(env, DAILY_CONTRIBUTIONS_STORE);+Repository repository = projectManager.getRepository(project.getId());PatternSet filePatterns = project.findCodeAnalysisPatterns();-+ObjectId lastCommitId = env.computeInTransaction(new TransactionalComputable<ObjectId>() {-+@Overridepublic ObjectId compute(Transaction txn) {ObjectId lastCommitId;@@ -503,20 +479,20 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerreturn lastCommitId;}});-+processCommitRange(project, commitId, lastCommitId, new CommitRangeProcessor() {@Overridepublic void process(ObjectId untilCommitId, ObjectId sinceCommitId) {env.executeInTransaction(new TransactionalExecutable() {-+@Overridepublic void execute(Transaction txn) {- Map<Integer, GitContribution> overallContributions =+ Map<Integer, GitContribution> overallContributions =deserializeContributions(readBytes(defaultStore, txn, OVERALL_CONTRIBUTIONS_KEY));-+Map<Integer, Map<Integer, GitContribution>> dailyContributionsCache = new HashMap<>();-+new ElementPumper<GitCommit>() {@Override@@ -528,18 +504,18 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerrevisions.add("^" + sinceCommitId.name());EnumSet<LogCommand.Field> fields = EnumSet.of(- LogCommand.Field.AUTHOR,+ LogCommand.Field.AUTHOR,LogCommand.Field.COMMIT_DATE,LogCommand.Field.PARENTS,LogCommand.Field.LINE_CHANGES);-+new LogCommand(storageManager.getProjectGitDir(project.getId()), revisions) {@Overrideprotected void consume(GitCommit commit) {consumer.accept(commit);}-+}.fields(fields).run();}@@ -551,7 +527,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerif (currentCommit.getAuthor() != null) {NameAndEmail author = new NameAndEmail(currentCommit.getAuthor());- ByteIterable authorKey = new ArrayByteIterable(SerializationUtils.serialize(author));+ ByteIterable authorKey = new ArrayByteIterable(SerializationUtils.serialize(author));int userIndex = readInt(userToIndexStore, txn, authorKey, -1);Preconditions.checkState(userIndex != -1);@@ -567,32 +543,32 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}}.pump();-- for (Map.Entry<Integer, Map<Integer, GitContribution>> entry: dailyContributionsCache.entrySet()) {++ for (Map.Entry<Integer, Map<Integer, GitContribution>> entry : dailyContributionsCache.entrySet()) {byte[] bytesOfContributionsOnDay = serializeContributions(entry.getValue());- dailyContributionsStore.put(txn, new IntByteIterable(entry.getKey()),+ dailyContributionsStore.put(txn, new IntByteIterable(entry.getKey()),new ArrayByteIterable(bytesOfContributionsOnDay));}- defaultStore.put(txn, OVERALL_CONTRIBUTIONS_KEY,+ defaultStore.put(txn, OVERALL_CONTRIBUTIONS_KEY,new ArrayByteIterable(serializeContributions(overallContributions)));-+defaultStore.put(txn, LAST_COMMIT_OF_CONTRIBS_KEY, new CommitByteIterable(untilCommitId));}-+});}-+});}-+private void collectFiles(Project project, ObjectId commitId) {Environment env = getEnv(project.getId().toString());Store defaultStore = getStore(env, DEFAULT_STORE);-+Repository repository = projectManager.getRepository(project.getId());-+ObjectId lastCommitId = env.computeInTransaction(new TransactionalComputable<ObjectId>() {-+@Overridepublic ObjectId compute(Transaction txn) {ObjectId lastCommitId;@@ -614,12 +590,12 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerif (lastCommitId == null) {env.executeInTransaction(new TransactionalExecutable() {-+@Overridepublic void execute(Transaction txn) {File gitDir = storageManager.getProjectGitDir(project.getId());Collection<String> files = new ListFilesCommand(gitDir, commitId.name()).run();-+byte[] bytesOfFiles = SerializationUtils.serialize((Serializable) files);defaultStore.put(txn, FILES_KEY, new ArrayByteIterable(bytesOfFiles));writeInt(defaultStore, txn, FILE_COUNT_KEY, files.size());@@ -627,26 +603,26 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerfilesCache.remove(project.getId());fileCountCache.remove(project.getId());}-+});} else {env.executeInTransaction(new TransactionalExecutable() {-+@SuppressWarnings("unchecked")@Overridepublic void execute(Transaction txn) {Collection<String> files;byte[] bytesOfFiles = readBytes(defaultStore, txn, FILES_KEY);- if (bytesOfFiles != null)+ if (bytesOfFiles != null)files = (Set<String>) SerializationUtils.deserialize(bytesOfFiles);- else+ elsefiles = new HashSet<>();-+boolean filesChanged = false;ListFileChangesCommand command = new ListFileChangesCommand(- storageManager.getProjectGitDir(project.getId()),+ storageManager.getProjectGitDir(project.getId()),lastCommitId.name(), commitId.name());- for (FileChange change: command.run()) {+ for (FileChange change : command.run()) {if (change.getOldPath() == null && change.getNewPath() != null) {files.add(change.getNewPath());filesChanged = true;@@ -665,46 +641,46 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerfileCountCache.remove(project.getId());}}-+});- }- }-+ }+ }+private void collectLineStats(Project project, ObjectId commitId) {Environment env = getEnv(project.getId().toString());Store defaultStore = getStore(env, DEFAULT_STORE);-+Repository repository = projectManager.getRepository(project.getId());-+ObjectId lastCommitId = env.computeInTransaction(new TransactionalComputable<ObjectId>() {-+@Overridepublic ObjectId compute(Transaction txn) {byte[] lastCommitBytes = readBytes(defaultStore, txn, LAST_COMMIT_OF_LINE_STATS_KEY);if (lastCommitBytes != null) {try {ObjectId lastCommitId = ObjectId.fromRaw(lastCommitBytes);- if (repository.getObjectDatabase().has(lastCommitId)+ if (repository.getObjectDatabase().has(lastCommitId)&& GitUtils.isMergedInto(repository, null, lastCommitId, commitId)) {return lastCommitId;}} catch (IOException e) {throw new RuntimeException(e);- }- }+ }+ }return null;}-+});PatternSet filePatterns = project.findCodeAnalysisPatterns();if (lastCommitId == null) {env.executeInTransaction(new TransactionalExecutable() {-+@Overridepublic void execute(Transaction txn) {Map<Integer, Map<String, Integer>> lineStats = new HashMap<>();-+new ElementPumper<GitCommit>() {@Override@@ -713,16 +689,16 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerrevisions.add(commitId.name());EnumSet<LogCommand.Field> fields = EnumSet.of(- LogCommand.Field.COMMIT_DATE,+ LogCommand.Field.COMMIT_DATE,LogCommand.Field.LINE_CHANGES);-+new LogCommand(storageManager.getProjectGitDir(project.getId()), revisions) {@Overrideprotected void consume(GitCommit commit) {consumer.accept(commit);}-+}.firstParent(true).noRenames(true).fields(fields).run();}@@ -730,19 +706,19 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic void process(GitCommit currentCommit) {updateLineStats(txn, currentCommit, lineStats, filePatterns);}-+}.pump();-+byte[] bytesOfLineStats = SerializationUtils.serialize((Serializable) lineStats);defaultStore.put(txn, LINE_STATS_KEY, new ArrayByteIterable(bytesOfLineStats));-+defaultStore.put(txn, LAST_COMMIT_OF_LINE_STATS_KEY, new CommitByteIterable(commitId));}-+});} else {env.executeInTransaction(new TransactionalExecutable() {-+@SuppressWarnings("unchecked")@Overridepublic void execute(Transaction txn) {@@ -754,63 +730,63 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager} else {lineStats = new HashMap<>();}-+ListNumStatsCommand command = new ListNumStatsCommand(- storageManager.getProjectGitDir(project.getId()),+ storageManager.getProjectGitDir(project.getId()),lastCommitId.name(), commitId.name(), true);List<FileChange> fileChanges = command.run();RevCommit revCommit = project.getRevCommit(commitId, true);- GitCommit gitCommit = new GitCommit(revCommit.name(), null, null, revCommit.getAuthorIdent(),+ GitCommit gitCommit = new GitCommit(revCommit.name(), null, null, revCommit.getAuthorIdent(),revCommit.getCommitterIdent().getWhen(), null, null, fileChanges);-+updateLineStats(txn, gitCommit, lineStats, filePatterns);bytesOfLineStats = SerializationUtils.serialize((Serializable) lineStats);defaultStore.put(txn, LINE_STATS_KEY, new ArrayByteIterable(bytesOfLineStats));-+defaultStore.put(txn, LAST_COMMIT_OF_LINE_STATS_KEY, new CommitByteIterable(commitId));}-+});- }+ }}-- private void processCommitRange(Project project, ObjectId untilCommitId,- @Nullable ObjectId sinceCommitId, CommitRangeProcessor commitRangeProcessor) {++ private void processCommitRange(Project project, ObjectId untilCommitId,+ @Nullable ObjectId sinceCommitId, CommitRangeProcessor commitRangeProcessor) {RevListCommand revList = new RevListCommand(storageManager.getProjectGitDir(project.getId()));List<String> revisions = new ArrayList<>();revisions.add(untilCommitId.name());- if (sinceCommitId != null)+ if (sinceCommitId != null)revisions.add("^" + sinceCommitId.name());revList.options().revisions(revisions).order(Order.TOPO);-+List<ObjectId> historyIds = new ArrayList<>();- for (String commitHash: revList.run())+ for (String commitHash : revList.run())historyIds.add(ObjectId.fromString(commitHash));-+revList = new RevListCommand(storageManager.getProjectGitDir(project.getId()));revList.options().revisions(revisions).firstParent(true);-+Set<ObjectId> firstParentIds = new HashSet<>();- for (String commitHash: revList.run())+ for (String commitHash : revList.run())firstParentIds.add(ObjectId.fromString(commitHash));/*- * Instead of collecting information of master branch all at once, we identify some- * intermediate commits and collect the information using these intermediate commits+ * Instead of collecting information of master branch all at once, we identify some+ * intermediate commits and collect the information using these intermediate commits* multiple times for two reasons:* 1. Use less memory- * 2. Commit Exodus transaction sooner so user can use auto-completion when search+ * 2. Commit Exodus transaction sooner so user can use auto-completion when search* commits even if collection is not done yet*/List<ObjectId> intermediateCommitIds = new ArrayList<>();int count = 0;- for (ObjectId historyId: historyIds) {+ for (ObjectId historyId : historyIds) {count++;/*- * Only use intermediate commits that are part of first parent chain. This- * makes sure that subsequent intermediate commits are always ancestor of- * current intermediate commit (after reverse done below), to avoid+ * Only use intermediate commits that are part of first parent chain. This+ * makes sure that subsequent intermediate commits are always ancestor of+ * current intermediate commit (after reverse done below), to avoid* collecting some commits multiple times*/if (count > COLLECT_BATCH_SIZE && firstParentIds.contains(historyId)) {@@ -821,40 +797,40 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerCollections.reverse(intermediateCommitIds);intermediateCommitIds.add(untilCommitId);-- for(ObjectId intermediateCommitId: intermediateCommitIds) {++ for (ObjectId intermediateCommitId : intermediateCommitIds) {commitRangeProcessor.process(intermediateCommitId, sinceCommitId);sinceCommitId = intermediateCommitId;- }+ }}-- private void updateLineStats(Transaction txn, GitCommit currentCommit, Map<Integer, Map<String, Integer>> lineStats,- PatternSet filePatterns) {++ private void updateLineStats(Transaction txn, GitCommit currentCommit, Map<Integer, Map<String, Integer>> lineStats,+ PatternSet filePatterns) {int dayValue = new Day(currentCommit.getCommitDate()).getValue();-+Map<String, Integer> lineStatsOnDay = lineStats.get(dayValue);if (lineStatsOnDay == null) {lineStatsOnDay = new HashMap<>();lineStats.put(dayValue, lineStatsOnDay);}-+Map<String, Integer> languageLines = new HashMap<>();- for (FileChange change: currentCommit.getFileChanges()) {+ for (FileChange change : currentCommit.getFileChanges()) {if (change.matches(filePatterns)) {int lines = change.getAdditions() - change.getDeletions();if (lines != 0 && StringUtils.isNotBlank(change.getNewExtension())) {String language = ProgrammingLanguageDetector.getLanguageForExtension(change.getNewExtension());if (language != null) {Integer accumulatedLines = languageLines.get(language);- if (accumulatedLines != null)+ if (accumulatedLines != null)lines += accumulatedLines;languageLines.put(language, lines);}}}}-- for (Map.Entry<String, Integer> entry: languageLines.entrySet()) {++ for (Map.Entry<String, Integer> entry : languageLines.entrySet()) {String language = entry.getKey();Integer lines = entry.getValue();Integer accumulatedLines = lineStatsOnDay.get(language);@@ -863,9 +839,9 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerlineStatsOnDay.put(language, lines);}}-- private int getPathIndex(Store pathToIndexStore, Store indexToPathStore, Transaction txn,- NextIndex nextIndex, String path) {++ private int getPathIndex(Store pathToIndexStore, Store indexToPathStore, Transaction txn,+ NextIndex nextIndex, String path) {StringByteIterable pathKey = new StringByteIterable(path);int pathIndex = readInt(pathToIndexStore, txn, pathKey, -1);if (pathIndex == -1) {@@ -875,18 +851,18 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}return pathIndex;}-- private void updateCommitCount(Store store, Transaction txn,- Map<Long, Integer> commitCountCache, int emailIndex, int pathIndex) {- long commitCountKey = ((long)emailIndex<<32)|pathIndex;-++ private void updateCommitCount(Store store, Transaction txn,+ Map<Long, Integer> commitCountCache, int emailIndex, int pathIndex) {+ long commitCountKey = ((long) emailIndex << 32) | pathIndex;+Integer commitCountOfPathByEmail = commitCountCache.get(commitCountKey);if (commitCountOfPathByEmail == null)commitCountOfPathByEmail = readInt(store, txn, new LongByteIterable(commitCountKey), 0);- commitCountOfPathByEmail ++;+ commitCountOfPathByEmail++;commitCountCache.put(commitCountKey, commitCountOfPathByEmail);}-+@Overridepublic List<NameAndEmail> getUsers(Long projectId) {return projectManager.runOnProjectServer(projectId, new ClusterTask<List<NameAndEmail>>() {@@ -906,24 +882,24 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager@Overridepublic List<NameAndEmail> compute(Transaction txn) {byte[] bytes = readBytes(store, txn, USERS_KEY);- if (bytes != null) {- List<NameAndEmail> users =+ if (bytes != null) {+ List<NameAndEmail> users =new ArrayList<>((Set<NameAndEmail>) SerializationUtils.deserialize(bytes));Collections.sort(users);return users;- } else {+ } else {return new ArrayList<>();}}-+});usersCache.put(projectId, users);}- return users;+ return users;}-+});-+}@Override@@ -946,10 +922,10 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic List<String> compute(Transaction txn) {byte[] bytes = readBytes(store, txn, FILES_KEY);if (bytes != null) {- List<String> files = new ArrayList<>((Collection<String>)SerializationUtils.deserialize(bytes));+ List<String> files = new ArrayList<>((Collection<String>) SerializationUtils.deserialize(bytes));Map<String, List<String>> segmentsMap = new HashMap<>();Splitter splitter = Splitter.on("/");- for (String file: files)+ for (String file : files)segmentsMap.put(file, splitter.splitToList(file));files.sort(new Comparator<String>() {@@ -957,7 +933,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic int compare(String o1, String o2) {return PathUtils.compare(segmentsMap.get(o1), segmentsMap.get(o2));}-+});return files;} else {@@ -969,9 +945,9 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}return files;}-+});-+}@Override@@ -994,36 +970,36 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerif (bytes != null) {@SuppressWarnings("unchecked")var storedMap = (Map<Integer, Map<String, Integer>>) SerializationUtils.deserialize(bytes);- for (var entry: storedMap.entrySet())+ for (var entry : storedMap.entrySet())lineIncrements.put(new Day(entry.getKey()), entry.getValue());- }+ }return lineIncrements;}-+});}-+});-+}-- private void updateContribution(Map<Integer, GitContribution> contributions, int key, GitCommit commit,- PatternSet filePatterns) {++ private void updateContribution(Map<Integer, GitContribution> contributions, int key, GitCommit commit,+ PatternSet filePatterns) {GitContribution contribution = contributions.get(key);if (contribution != null) {contribution = new GitContribution(- contribution.getCommits()+1,- contribution.getAdditions()+commit.getAdditions(filePatterns),- contribution.getDeletions()+commit.getDeletions(filePatterns));+ contribution.getCommits() + 1,+ contribution.getAdditions() + commit.getAdditions(filePatterns),+ contribution.getDeletions() + commit.getDeletions(filePatterns));} else {contribution = new GitContribution(1, commit.getAdditions(filePatterns), commit.getDeletions(filePatterns));}contributions.put(key, contribution);}-- private int getCommitCount(Long projectId, Collection<EmailAddressFacade> emailAddresses,- String path) {++ private int getCommitCount(Long projectId, Collection<EmailAddressFacade> emailAddresses,+ String path) {Environment env = getEnv(projectId.toString());Store emailToIndexStore = getStore(env, EMAIL_TO_INDEX_STORE);Store pathToIndexStore = getStore(env, PATH_TO_INDEX_STORE);@@ -1034,21 +1010,21 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager@Overridepublic Integer compute(Transaction txn) {AtomicInteger count = new AtomicInteger(0);- emailAddresses.stream().filter(it->it.isVerified()).forEach(it-> {+ emailAddresses.stream().filter(it -> it.isVerified()).forEach(it -> {int emailIndex = readInt(emailToIndexStore, txn, new StringByteIterable(it.getValue()), -1);if (emailIndex != -1) {int pathIndex = readInt(pathToIndexStore, txn, new StringByteIterable(path), -1);if (pathIndex != -1) {- long commitCountKey = ((long)emailIndex<<32)|pathIndex;+ long commitCountKey = ((long) emailIndex << 32) | pathIndex;count.addAndGet(readInt(commitCountStore, txn, new LongByteIterable(commitCountKey), 0));- }- }+ }+ }});return count.get();}});}-+@Overridepublic Collection<ObjectId> getDescendants(Long projectId, Collection<ObjectId> ancestors) {return projectManager.runOnProjectServer(projectId, new ClusterTask<Collection<ObjectId>>() {@@ -1065,7 +1041,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager@Overridepublic Set<ObjectId> compute(Transaction txn) {Set<ObjectId> descendants = new HashSet<>();-+// Use stack instead of recursion to avoid StackOverflowExceptionStack<ObjectId> stack = new Stack<>();descendants.addAll(ancestors);@@ -1075,16 +1051,16 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerbyte[] valueBytes = readBytes(store, txn, new CommitByteIterable(current));if (valueBytes != null) {if (valueBytes.length % 20 == 0) {- for (int i=0; i<valueBytes.length/20; i++) {- ObjectId child = ObjectId.fromRaw(valueBytes, i*20);+ for (int i = 0; i < valueBytes.length / 20; i++) {+ ObjectId child = ObjectId.fromRaw(valueBytes, i * 20);if (!descendants.contains(child)) {descendants.add(child);stack.push(child);}}- } else {- for (int i=0; i<(valueBytes.length-1)/20; i++) {- ObjectId child = ObjectId.fromRaw(valueBytes, i*20+1);+ } else {+ for (int i = 0; i < (valueBytes.length - 1) / 20; i++) {+ ObjectId child = ObjectId.fromRaw(valueBytes, i * 20 + 1);if (!descendants.contains(child)) {descendants.add(child);stack.push(child);@@ -1093,13 +1069,13 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}}}-+return descendants;}-+});}-+});}@@ -1120,15 +1096,15 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagertotalCommitCountCache.remove(projectId);fileCountCache.remove(projectId);usersCache.remove(projectId);-+return null;}-+});}}}-+private BatchWorker getBatchWorker(Long projectId) {return new BatchWorker("project-" + projectId + "-collectCommitInfo") {@@ -1140,20 +1116,20 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic void run() {Project project = projectManager.load(projectId);List<CollectingWork> collectingWorks = new ArrayList<>();- for (Object work: works)- collectingWorks.add((CollectingWork)work);+ for (Object work : works)+ collectingWorks.add((CollectingWork) work);Collections.sort(collectingWorks, new CommitTimeComparator());-- for (CollectingWork work: collectingWorks)++ for (CollectingWork work : collectingWorks)doCollect(project, work.getCommit().copy(), work.getRefName());}-+});}-- };++ };}-+private void collect(Long projectId) {List<CollectingWork> works = new ArrayList<>();try (RevWalk revWalk = new RevWalk(projectManager.getRepository(projectId))) {@@ -1161,7 +1137,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerrefs.addAll(projectManager.getRepository(projectId).getRefDatabase().getRefsByPrefix(Constants.R_HEADS));refs.addAll(projectManager.getRepository(projectId).getRefDatabase().getRefsByPrefix(Constants.R_TAGS));- for (Ref ref: refs) {+ for (Ref ref : refs) {RevObject revObj = revWalk.peel(revWalk.parseAny(ref.getObjectId()));if (revObj instanceof RevCommit)works.add(new CollectingWork(PRIORITY, (RevCommit) revObj, ref.getName()));@@ -1171,8 +1147,8 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}Collections.sort(works, new CommitTimeComparator());-- for (CollectingWork work: works)++ for (CollectingWork work : works)batchWorkManager.submit(getBatchWorker(projectId), work);}@@ -1180,7 +1156,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager@Listenpublic void on(SystemStarted event) {Collection<Long> projectIds = projectManager.getIds();- for (File file: storageManager.getProjectsDir().listFiles()) {+ for (File file : storageManager.getProjectsDir().listFiles()) {Long projectId = Long.valueOf(file.getName());if (projectIds.contains(projectId)) {checkVersion(getEnvDir(projectId.toString()));@@ -1188,13 +1164,13 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}}}-+@Sessional@Listenpublic void on(RefUpdated event) {- if (!event.getNewCommitId().equals(ObjectId.zeroId())- && (event.getRefName().startsWith(Constants.R_HEADS)- || event.getRefName().startsWith(Constants.R_TAGS))) {+ if (!event.getNewCommitId().equals(ObjectId.zeroId())+ && (event.getRefName().startsWith(Constants.R_HEADS)+ || event.getRefName().startsWith(Constants.R_TAGS))) {Repository repository = projectManager.getRepository(event.getProject().getId());try (RevWalk revWalk = new RevWalk(repository)) {RevCommit commit = GitUtils.parseCommit(revWalk, event.getNewCommitId());@@ -1231,7 +1207,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}return commitCount;}-+});}@@ -1254,22 +1230,22 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic Integer compute(Transaction txn) {return readInt(store, txn, FILE_COUNT_KEY, 0);}-+});fileCountCache.put(projectId, fileCount);}return fileCount;}-+});}-+static class CollectingWork extends Prioritized {-+private final String refName;-+private final RevCommit commit;-+public CollectingWork(int priority, RevCommit commit, String refName) {super(priority);this.commit = commit;@@ -1285,14 +1261,14 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}}-+static class CommitTimeComparator implements Comparator<CollectingWork> {@Overridepublic int compare(CollectingWork o1, CollectingWork o2) {return o1.getCommit().getCommitTime() - o2.getCommit().getCommitTime();}-+}@Sessional@@ -1308,13 +1284,13 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerWebTarget target = client.target(serverUrl).path("~api/cluster/commit-info").queryParam("projectId", sourceProjectId);- Invocation.Builder builder = target.request();- builder.header(HttpHeaders.AUTHORIZATION,+ Invocation.Builder builder = target.request();+ builder.header(HttpHeaders.AUTHORIZATION,KubernetesHelper.BEARER + " " + clusterManager.getCredentialValue());- try (Response response = builder.get()){+ try (Response response = builder.get()) {KubernetesHelper.checkStatus(response);FileUtils.untar(- response.readEntity(InputStream.class),+ response.readEntity(InputStream.class),getEnvDir(targetProjectId.toString()), false);}} finally {@@ -1329,8 +1305,8 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagertry {backupStrategy.beforeBackup();try {- for (VirtualFileDescriptor descriptor: backupStrategy.getContents()) {- FileUtils.copyFileToDirectory(((FileDescriptor)descriptor).getFile(), targetDir);+ for (VirtualFileDescriptor descriptor : backupStrategy.getContents()) {+ FileUtils.copyFileToDirectory(((FileDescriptor) descriptor).getFile(), targetDir);}} finally {backupStrategy.afterBackup();@@ -1340,14 +1316,14 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerthrow new RuntimeException(e);}}-+@Overrideprotected File getEnvDir(String envKey) {File infoDir = new File(storageManager.getProjectInfoDir(Long.valueOf(envKey)), INFO_DIR);FileUtils.createDir(infoDir);return infoDir;}-+@Sessional@Overridepublic Collection<String> getHistoryPaths(Long projectId, String path) {@@ -1361,19 +1337,19 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerStore historyPathsStore = getStore(env, HISTORY_PATHS_STORE);Store pathToIndexStore = getStore(env, PATH_TO_INDEX_STORE);Store indexToPathStore = getStore(env, INDEX_TO_PATH_STORE);-+return env.computeInReadonlyTransaction(new TransactionalComputable<Collection<String>>() {private Collection<String> getPaths(Transaction txn, Set<Integer> pathIndexes) {Set<String> paths = new HashSet<>();- for (int pathIndex: pathIndexes) {+ for (int pathIndex : pathIndexes) {byte[] pathBytes = readBytes(indexToPathStore, txn, new IntByteIterable(pathIndex));if (pathBytes != null)paths.add(new String(pathBytes, StandardCharsets.UTF_8));}return paths;}-+@Overridepublic Collection<String> compute(Transaction txn) {int pathIndex = readInt(pathToIndexStore, txn, new StringByteIterable(path), -1);@@ -1382,12 +1358,12 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpathIndexes.add(pathIndex);while (true) {Set<Integer> newPathIndexes = new HashSet<>(pathIndexes);- for (int eachPathIndex: pathIndexes) {- byte[] bytesOfHistoryPaths =+ for (int eachPathIndex : pathIndexes) {+ byte[] bytesOfHistoryPaths =readBytes(historyPathsStore, txn, new IntByteIterable(eachPathIndex));if (bytesOfHistoryPaths != null) {int pos = 0;- for (int i=0; i<bytesOfHistoryPaths.length/Integer.BYTES; i++) {+ for (int i = 0; i < bytesOfHistoryPaths.length / Integer.BYTES; i++) {newPathIndexes.add(ByteBuffer.wrap(bytesOfHistoryPaths, pos, Integer.BYTES).getInt());if (newPathIndexes.size() == MAX_HISTORY_PATHS)return getPaths(txn, newPathIndexes);@@ -1405,13 +1381,13 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerreturn new HashSet<>();}}- });+ });}-+});}-+@Sessional@Overridepublic Map<Day, GitContribution> getOverallContributions(Long projectId) {@@ -1429,24 +1405,24 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager@Overridepublic Map<Day, GitContribution> compute(Transaction txn) {Map<Day, GitContribution> overallContributions = new HashMap<>();- for (Map.Entry<Integer, GitContribution> entry:- deserializeContributions(readBytes(store, txn, OVERALL_CONTRIBUTIONS_KEY)).entrySet()) {+ for (Map.Entry<Integer, GitContribution> entry :+ deserializeContributions(readBytes(store, txn, OVERALL_CONTRIBUTIONS_KEY)).entrySet()) {overallContributions.put(new Day(entry.getKey()), entry.getValue());}return overallContributions;}-+});}-+});-+}-+@Sessional@Override- public List<GitContributor> getTopContributors(Long projectId, int top,- GitContribution.Type type, int fromDay, int toDay) {+ public List<GitContributor> getTopContributors(Long projectId, int top,+ GitContribution.Type type, int fromDay, int toDay) {return projectManager.runOnProjectServer(projectId, new ClusterTask<List<GitContributor>>() {private static final long serialVersionUID = 1L;@@ -1457,16 +1433,16 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerStore defaultStore = getStore(env, DEFAULT_STORE);Store indexToUserStore = getStore(env, INDEX_TO_USER_STORE);Store dailyContributionsStore = getStore(env, DAILY_CONTRIBUTIONS_STORE);-+return env.computeInReadonlyTransaction(new TransactionalComputable<List<GitContributor>>() {@Nullable- private NameAndEmail getUser(Transaction txn, Map<Integer, Optional<NameAndEmail>> users,- Integer userIndex) {+ private NameAndEmail getUser(Transaction txn, Map<Integer, Optional<NameAndEmail>> users,+ Integer userIndex) {Optional<NameAndEmail> userOpt = users.get(userIndex);if (userOpt == null) {byte[] userBytes = readBytes(indexToUserStore, txn, new IntByteIterable(userIndex));- if (userBytes != null) {+ if (userBytes != null) {NameAndEmail user = (NameAndEmail) SerializationUtils.deserialize(userBytes);EmailAddressFacade emailAddress = emailAddressManager.findFacadeByValue(user.getEmailAddress());if (emailAddress != null && emailAddress.isVerified()) {@@ -1483,29 +1459,29 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}}userOpt = Optional.of(user);- } else {+ } else {userOpt = Optional.empty();}users.put(userIndex, userOpt);}return userOpt.orElse(null);}-+@Overridepublic List<GitContributor> compute(Transaction txn) {- Map<Integer, GitContribution> overallContributions =+ Map<Integer, GitContribution> overallContributions =deserializeContributions(readBytes(defaultStore, txn, OVERALL_CONTRIBUTIONS_KEY));Map<NameAndEmail, GitContribution> totalContributions = new HashMap<>();Map<Integer, Optional<NameAndEmail>> users = new HashMap<>();Map<Integer, Map<Integer, GitContribution>> contributionsByDay = new LinkedHashMap<>();-- for (int dayValue: overallContributions.keySet()) {++ for (int dayValue : overallContributions.keySet()) {if (dayValue >= fromDay && dayValue <= toDay) {ByteIterable dayKey = new IntByteIterable(dayValue);- Map<Integer, GitContribution> contributionsOnDay =+ Map<Integer, GitContribution> contributionsOnDay =deserializeContributions(readBytes(dailyContributionsStore, txn, dayKey));contributionsByDay.put(dayValue, contributionsOnDay);- for (Map.Entry<Integer, GitContribution> entry: contributionsOnDay.entrySet()) {+ for (Map.Entry<Integer, GitContribution> entry : contributionsOnDay.entrySet()) {NameAndEmail user = getUser(txn, users, entry.getKey());if (user != null) {GitContribution totalContribution = totalContributions.get(user);@@ -1513,8 +1489,8 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagertotalContribution = entry.getValue();} else {totalContribution = new GitContribution(- totalContribution.getCommits() + entry.getValue().getCommits(),- totalContribution.getAdditions() + entry.getValue().getAdditions(),+ totalContribution.getCommits() + entry.getValue().getCommits(),+ totalContribution.getAdditions() + entry.getValue().getAdditions(),totalContribution.getDeletions() + entry.getValue().getDeletions());}totalContributions.put(user, totalContribution);@@ -1522,7 +1498,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}}}-+List<NameAndEmail> topUsers = new ArrayList<>(totalContributions.keySet());Collections.sort(topUsers, new Comparator<NameAndEmail>() {@@ -1535,18 +1511,18 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerelsereturn totalContributions.get(o2).getDeletions() - totalContributions.get(o1).getDeletions();}-+});if (top < topUsers.size())topUsers = topUsers.subList(0, top);-+Set<NameAndEmail> topUserSet = new HashSet<>(topUsers);-+Map<NameAndEmail, Map<Day, Integer>> userContributions = new HashMap<>();-- for (Map.Entry<Integer, Map<Integer, GitContribution>> dayEntry: contributionsByDay.entrySet()) {- for (Map.Entry<Integer, GitContribution> userEntry: dayEntry.getValue().entrySet()) {++ for (Map.Entry<Integer, Map<Integer, GitContribution>> dayEntry : contributionsByDay.entrySet()) {+ for (Map.Entry<Integer, GitContribution> userEntry : dayEntry.getValue().entrySet()) {NameAndEmail user = getUser(txn, users, userEntry.getKey());if (user != null && topUserSet.contains(user)) {Map<Day, Integer> contributionsOfUser = userContributions.get(user);@@ -1566,34 +1542,34 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}List<GitContributor> topContributors = new ArrayList<>();-- for (NameAndEmail user: topUsers) {- topContributors.add(new GitContributor(user.asPersonIdent(),++ for (NameAndEmail user : topUsers) {+ topContributors.add(new GitContributor(user.asPersonIdent(),totalContributions.get(user), userContributions.get(user)));}-+return topContributors;}-+});}-+});-+}private Map<Integer, GitContribution> deserializeContributions(byte[] bytes) {if (bytes != null) {Map<Integer, GitContribution> contributions = new HashMap<>();int pos = 0;- for (int i=0; i<bytes.length/4/Integer.BYTES; i++) {+ for (int i = 0; i < bytes.length / 4 / Integer.BYTES; i++) {int key = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();pos += Integer.BYTES;- int commits = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();+ int commits = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();pos += Integer.BYTES;int additions = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();pos += Integer.BYTES;- int deletions = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();+ int deletions = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();pos += Integer.BYTES;contributions.put(key, new GitContribution(commits, additions, deletions));}@@ -1602,12 +1578,12 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerreturn new HashMap<>();}}-+private byte[] serializeContributions(Map<Integer, GitContribution> contributions) {- byte[] bytes = new byte[contributions.size()*Integer.BYTES*4];+ byte[] bytes = new byte[contributions.size() * Integer.BYTES * 4];int pos = 0;- for (Map.Entry<Integer, GitContribution> entry: contributions.entrySet()) {- byte[] keyBytes = ByteBuffer.allocate(Integer.BYTES).putInt(entry.getKey()).array();+ for (Map.Entry<Integer, GitContribution> entry : contributions.entrySet()) {+ byte[] keyBytes = ByteBuffer.allocate(Integer.BYTES).putInt(entry.getKey()).array();System.arraycopy(keyBytes, 0, bytes, pos, Integer.BYTES);pos += Integer.BYTES;byte[] commitsBytes = ByteBuffer.allocate(Integer.BYTES).putInt(entry.getValue().getCommits()).array();@@ -1622,7 +1598,7 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManager}return bytes;}-+@Overrideprotected long getLogFileSize() {return LOG_FILE_SIZE;@@ -1643,24 +1619,24 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic Collection<ObjectId> call() throws Exception {Environment env = getEnv(projectId.toString());Store store = getStore(env, FIX_COMMITS_STORE);-+return env.computeInTransaction(new TransactionalComputable<Collection<ObjectId>>() {-+@Overridepublic Collection<ObjectId> compute(Transaction txn) {return readCommits(store, txn, new LongByteIterable(issueId));}-+});}-+});-+}-+@Override- public List<Long> sortUsersByContribution(Map<Long, Collection<EmailAddressFacade>> userEmails,- Long projectId, Collection<String> files) {+ public List<Long> sortUsersByContribution(Map<Long, Collection<EmailAddressFacade>> userEmails,+ Long projectId, Collection<String> files) {return projectManager.runOnProjectServer(projectId, new ClusterTask<List<Long>>() {private static final long serialVersionUID = 1L;@@ -1669,13 +1645,13 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerpublic List<Long> call() throws Exception {if (userEmails.size() <= 1)return new ArrayList<>(userEmails.keySet());-+Map<Long, Long> commitCounts = new HashMap<>();- for (var userId: userEmails.keySet())+ for (var userId : userEmails.keySet())commitCounts.put(userId, 0L);int count = 0;- for (String path: files) {+ for (String path : files) {int addedCommitCount = addCommitCounts(projectId, commitCounts, userEmails, path);while (addedCommitCount == 0) {if (path.contains("/")) {@@ -1700,19 +1676,19 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerelsereturn -1;}-+});return userIds;}-+});-+}-- private int addCommitCounts(Long projectId, Map<Long, Long> commitCounts,- Map<Long, Collection<EmailAddressFacade>> userEmails, String path) {++ private int addCommitCounts(Long projectId, Map<Long, Long> commitCounts,+ Map<Long, Collection<EmailAddressFacade>> userEmails, String path) {int addedCommitCount = 0;- for (var entry: commitCounts.entrySet()) {+ for (var entry : commitCounts.entrySet()) {var userId = entry.getKey();int commitCount = getCommitCount(projectId, userEmails.get(userId), path);entry.setValue(entry.getValue() + commitCount);@@ -1723,20 +1699,20 @@ public class DefaultCommitInfoManager extends AbstractMultiEnvironmentManagerprivate static class NextIndex {int user;-+int email;-+int path;}private static interface CommitRangeProcessor {-+void process(ObjectId untilCommitId, @Nullable ObjectId sinceCommitId);-+}-+public Object writeReplace() throws ObjectStreamException {return new ManagedSerializedForm(CommitInfoManager.class);}-+}diff --git a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.javaindex 007d5bdc02..0c348156a3 100644--- a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java+++ b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java@@ -11,6 +11,7 @@ import javax.inject.Inject;import javax.inject.Singleton;import io.onedev.server.entitymanager.*;+import io.onedev.server.event.project.issue.*;import org.apache.commons.lang3.StringUtils;import com.google.common.collect.Lists;@@ -18,10 +19,6 @@ import com.google.common.collect.Sets;import io.onedev.server.entityreference.ReferencedFromAware;import io.onedev.server.event.Listen;-import io.onedev.server.event.project.issue.IssueChanged;-import io.onedev.server.event.project.issue.IssueCommented;-import io.onedev.server.event.project.issue.IssueEvent;-import io.onedev.server.event.project.issue.IssueOpened;import io.onedev.server.infomanager.VisitInfoManager;import io.onedev.server.mail.MailManager;import io.onedev.server.markdown.MarkdownManager;@@ -75,6 +72,9 @@ public class IssueNotificationManager extends AbstractNotificationManager {@Transactional@Listenpublic void on(IssueEvent event) {+ if (event instanceof IssueCommitsAttached)+ return;+Issue issue = event.getIssue();User user = event.getUser();diff --git a/server-core/src/main/java/io/onedev/server/util/channelnotification/ChannelNotificationManager.java b/server-core/src/main/java/io/onedev/server/util/channelnotification/ChannelNotificationManager.javaindex 0936a0c256..ab881f6f3f 100644--- a/server-core/src/main/java/io/onedev/server/util/channelnotification/ChannelNotificationManager.java+++ b/server-core/src/main/java/io/onedev/server/util/channelnotification/ChannelNotificationManager.java@@ -7,6 +7,7 @@ import java.util.Map;import javax.inject.Inject;+import io.onedev.server.event.project.issue.IssueCommitsAttached;import org.apache.commons.lang3.StringUtils;import org.apache.http.HttpEntity;import org.apache.http.HttpStatus;@@ -60,170 +61,147 @@ import io.onedev.server.util.ReflectionUtils;public abstract class ChannelNotificationManager<T extends ChannelNotificationSetting> {private static final Logger logger = LoggerFactory.getLogger(ChannelNotificationManager.class);-+private final ObjectMapper objectMapper;-+private final Class<T> settingClass;-+@SuppressWarnings("unchecked")@Injectpublic ChannelNotificationManager(ObjectMapper objectMapper) {this.objectMapper = objectMapper;-+List<Class<?>> typeArguments = ReflectionUtils.getTypeArguments(ChannelNotificationManager.class, getClass());if (typeArguments.size() == 1 && ChannelNotificationSetting.class.isAssignableFrom(typeArguments.get(0))) {settingClass = (Class<T>) typeArguments.get(0);} else {- throw new RuntimeException("Super class of channel notification manager implementation must "- + "be ChannelNotificationManager and must realize the type argument <T>");+ throw new RuntimeException("Super class of channel notification manager implementation must " + "be ChannelNotificationManager and must realize the type argument <T>");}- }-+ }+@Sessional@Listenpublic void on(IssueEvent event) {- if (!(event instanceof IssueChanged)- || !(((IssueChanged) event).getChange().getData() instanceof ReferencedFromAware)) {+ if (!(event instanceof IssueCommitsAttached) && (!(event instanceof IssueChanged) || !(((IssueChanged) event).getChange().getData() instanceof ReferencedFromAware))) {Issue issue = event.getIssue();User user = event.getUser();-- String issueInfo = String.format("[Issue] (%s - %s)", issue.getFQN(), issue.getTitle());-- String eventDescription;- if (user != null)- eventDescription = user.getDisplayName() + " " + event.getActivity();- else- eventDescription = StringUtils.capitalize(event.getActivity());-++ String issueInfo = String.format("[Issue] (%s - %s)", issue.getFQN(), issue.getTitle());++ String eventDescription;+ if (user != null) eventDescription = user.getDisplayName() + " " + event.getActivity();+ else eventDescription = StringUtils.capitalize(event.getActivity());+postIfApplicable(issueInfo + " " + eventDescription, event);}-+}-+@Sessional@Listenpublic void on(PullRequestEvent event) {boolean significantChange = false;if (event instanceof PullRequestChanged) {PullRequestChangeData changeData = ((PullRequestChanged) event).getChange().getData();- if (changeData instanceof PullRequestApproveData- || changeData instanceof PullRequestRequestedForChangesData- || changeData instanceof PullRequestMergeData- || changeData instanceof PullRequestDiscardData- || changeData instanceof PullRequestReopenData) {+ if (changeData instanceof PullRequestApproveData || changeData instanceof PullRequestRequestedForChangesData || changeData instanceof PullRequestMergeData || changeData instanceof PullRequestDiscardData || changeData instanceof PullRequestReopenData) {significantChange = true;}- } else if (!(event instanceof PullRequestMergePreviewCalculated- || event instanceof PullRequestBuildEvent- || event instanceof PullRequestReviewRequested- || event instanceof PullRequestReviewerRemoved- || event instanceof PullRequestAssigned- || event instanceof PullRequestUnassigned)) {+ } else if (!(event instanceof PullRequestMergePreviewCalculated || event instanceof PullRequestBuildEvent || event instanceof PullRequestReviewRequested || event instanceof PullRequestReviewerRemoved || event instanceof PullRequestAssigned || event instanceof PullRequestUnassigned)) {significantChange = true;}-+if (significantChange) {PullRequest request = event.getRequest();User user = event.getUser();-- String pullRequestInfo = String.format("[Pull Request] (%s - %s)", request.getFQN(), request.getTitle());-- String eventDescription;- if (user != null)- eventDescription = user.getDisplayName() + " " + event.getActivity();- else- eventDescription = StringUtils.capitalize(event.getActivity());++ String pullRequestInfo = String.format("[Pull Request] (%s - %s)", request.getFQN(), request.getTitle());++ String eventDescription;+ if (user != null) eventDescription = user.getDisplayName() + " " + event.getActivity();+ else eventDescription = StringUtils.capitalize(event.getActivity());postIfApplicable(pullRequestInfo + " " + eventDescription, event);}-+}-+@Sessional@Listenpublic void on(BuildEvent event) {Build build = event.getBuild();String eventDescription = build.getStatus().toString();- if (build.getVersion() != null)- eventDescription = build.getVersion() + " " + eventDescription;-+ if (build.getVersion() != null) eventDescription = build.getVersion() + " " + eventDescription;+String buildInfo = String.format("[Build] (%s - %s)", build.getFQN(), build.getJobName());postIfApplicable(buildInfo + " " + eventDescription, event);}-+@Sessional@Listenpublic void on(RefUpdated event) {- if (!event.getNewCommitId().equals(ObjectId.zeroId())) {+ if (!event.getNewCommitId().equals(ObjectId.zeroId())) {Project project = event.getProject();RevCommit commit = project.getRevCommit(event.getNewCommitId(), false);if (commit != null) {String target = GitUtils.ref2branch(event.getRefName());if (target == null) {target = GitUtils.ref2tag(event.getRefName());- if (target == null)- target = event.getRefName();+ if (target == null) target = event.getRefName();}-- String commitInfo = String.format("[Commit] (%s:%s - %s)",- project.getPath(), GitUtils.abbreviateSHA(commit.name()), target);++ String commitInfo = String.format("[Commit] (%s:%s - %s)", project.getPath(), GitUtils.abbreviateSHA(commit.name()), target);postIfApplicable(commitInfo + " " + commit.getShortMessage(), event);}}}-+@Sessional@Listenpublic void on(CodeCommentEvent event) {if (!(event instanceof CodeCommentUpdated)) {CodeComment comment = event.getComment();- String commentInfo = String.format("[Code Comment] (%s:%s)",- event.getProject().getPath(), comment.getMark().getPath());-- String eventDescription = String.format("%s %s",- event.getUser().getDisplayName(), event.getActivity());-+ String commentInfo = String.format("[Code Comment] (%s:%s)", event.getProject().getPath(), comment.getMark().getPath());++ String eventDescription = String.format("%s %s", event.getUser().getDisplayName(), event.getActivity());+postIfApplicable(commentInfo + " " + eventDescription, event);}- }-+ }+private Collection<ChannelNotification> getNotifications(Project project) {Map<String, ChannelNotification> notifications = new HashMap<>();do {T setting = project.getContributedSetting(settingClass);- for (ChannelNotificationWrapper wrapper: setting.getNotifications())+ for (ChannelNotificationWrapper wrapper : setting.getNotifications())notifications.putIfAbsent(wrapper.getChannelNotification().getWebhookUrl(), wrapper.getChannelNotification());project = project.getParent();} while (project != null);-+return notifications.values();}-+private void postIfApplicable(String title, ProjectEvent event) {Object data = toJsonObject(title, event);-- for (ChannelNotification notification: getNotifications(event.getProject())) {++ for (ChannelNotification notification : getNotifications(event.getProject())) {if (notification.matches(event)) {try (CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties().build()) {HttpPost post = new HttpPost(notification.getWebhookUrl());-- StringEntity requestEntity = new StringEntity(objectMapper.writeValueAsString(data), ContentType.APPLICATION_JSON);++ StringEntity requestEntity = new StringEntity(objectMapper.writeValueAsString(data), ContentType.APPLICATION_JSON);post.setEntity(requestEntity);-+try (CloseableHttpResponse response = client.execute(post)) {- if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK- && response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {HttpEntity responseEntity = response.getEntity();String errorMessage;if (responseEntity != null) {String content = IOUtils.readInputStreamToString(responseEntity.getContent());- errorMessage = String.format("Error sending channel notification (status code: %d, response: %s)",- response.getStatusLine().getStatusCode(), content);+ errorMessage = String.format("Error sending channel notification (status code: %d, response: %s)", response.getStatusLine().getStatusCode(), content);} else {- errorMessage = String.format("Error sending channel notification (status code: %d)",- response.getStatusLine().getStatusCode());+ errorMessage = String.format("Error sending channel notification (status code: %d)", response.getStatusLine().getStatusCode());}logger.error(errorMessage);}@@ -234,7 +212,7 @@ public abstract class ChannelNotificationManager<T extends ChannelNotificationSe}}}-+protected abstract Object toJsonObject(String title, ProjectEvent event);-+}diff --git a/server-core/src/main/java/io/onedev/server/web/component/beaneditmodal/BeanEditContentPanel.html b/server-core/src/main/java/io/onedev/server/web/component/beaneditmodal/BeanEditContentPanel.htmlindex 54bc984d9a..631defd7c0 100644--- a/server-core/src/main/java/io/onedev/server/web/component/beaneditmodal/BeanEditContentPanel.html+++ b/server-core/src/main/java/io/onedev/server/web/component/beaneditmodal/BeanEditContentPanel.html@@ -1,17 +1,17 @@-<wicket:panel>- <form wicket:id="form" class="bean-edit leave-confirm">- <div class="modal-header">- <h5 wicket:id="title" class="modal-title"></h5>- <button wicket:id="close" type="button" class="close"><wicket:svg href="times" class="icon"/></button>- </div>- <div class="modal-body">- <div wicket:id="description" class="alert alert-light alert-notice"></div>- <div wicket:id="feedback"></div>- <div wicket:id="editor"></div>- </div>- <div class="modal-footer">- <button wicket:id="ok" class="btn btn-primary">Ok</button>- <button wicket:id="cancel" class="btn btn-secondary">Cancel</button>- </div>- </form>+<wicket:panel>+ <form wicket:id="form" class="bean-edit leave-confirm">+ <div class="modal-header">+ <h5 wicket:id="title" class="modal-title"></h5>+ <button wicket:id="close" type="button" class="close"><wicket:svg href="times" class="icon"/></button>+ </div>+ <div class="modal-body">+ <div wicket:id="description" class="alert alert-light alert-notice"></div>+ <div wicket:id="feedback"></div>+ <div wicket:id="editor"></div>+ </div>+ <div class="modal-footer">+ <button wicket:id="ok" class="btn btn-primary">Ok</button>+ <button wicket:id="cancel" class="btn btn-secondary">Cancel</button>+ </div>+ </form></wicket:panel>\ No newline at end of filediff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/fieldvalues/FieldValuesPanel.java b/server-core/src/main/java/io/onedev/server/web/component/issue/fieldvalues/FieldValuesPanel.javaindex 5224d56f7c..1953afc1c2 100644--- a/server-core/src/main/java/io/onedev/server/web/component/issue/fieldvalues/FieldValuesPanel.java+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/fieldvalues/FieldValuesPanel.java@@ -152,6 +152,11 @@ public abstract class FieldValuesPanel extends Panel implements EditContext, Proreturn getIssueSetting().getFieldSpec(inputName);}+ @Override+ protected boolean isDirtyAware() {+ return false;+ }+@Overrideprotected void onSave(AjaxRequestTarget target, Serializable bean) {fieldValues.putAll(FieldUtils.getFieldValues(