The Unified and Autonomous Development Platform
chore: Remove source line stats by time and contrib lines for performance reason
Robin Shenbc4a3df12de8
diff --git a/doc/images/line-stats.png b/doc/images/line-stats.pngdeleted file mode 100644index 5a1a8f1172..0000000000Binary files a/doc/images/line-stats.png and /dev/null differdiff --git a/readme.md b/readme.mdindex 4d9b088677..cca0380fc4 100644--- a/readme.md+++ b/readme.md@@ -203,14 +203,6 @@ Search anything and jump to it without digging through menus.-## 📈 SLOC trend by language--Inspects git history of main branch to calculate trend of-source lines of code by language efficiently.-[**See It In Action**](https://code.onedev.io/onedev/server/~stats/lines)---## 🕊️ Fast, lightweight, and reliableCrafted with resource usage and performance in mind. Get all features above with a 1 core 2G mem boxdiff --git a/server-core/src/main/java/io/onedev/server/git/GitContribution.java b/server-core/src/main/java/io/onedev/server/git/GitContribution.javadeleted file mode 100644index cca5f2a26c..0000000000--- a/server-core/src/main/java/io/onedev/server/git/GitContribution.java+++ /dev/null@@ -1,35 +0,0 @@-package io.onedev.server.git;--import java.io.Serializable;--public class GitContribution implements Serializable {-- private static final long serialVersionUID = 1L;-- public enum Type {COMMITS, ADDITIONS, DELETIONS};-- private final int commits;-- private final int additions;-- private final int deletions;-- public GitContribution(int commits, int additions, int deletions) {- this.commits = commits;- this.additions = additions;- this.deletions = deletions;- }-- public int getCommits() {- return commits;- }-- public int getAdditions() {- return additions;- }-- public int getDeletions() {- return deletions;- }--}diff --git a/server-core/src/main/java/io/onedev/server/git/GitContributor.java b/server-core/src/main/java/io/onedev/server/git/GitContributor.javaindex 4ed9906404..54818875f0 100644--- a/server-core/src/main/java/io/onedev/server/git/GitContributor.java+++ b/server-core/src/main/java/io/onedev/server/git/GitContributor.java@@ -11,13 +11,13 @@ public class GitContributor implements Serializable {private final PersonIdent author;- private final GitContribution totalContribution;+ private final int totalCommits;private final Map<Integer, Integer> dailyContributions;- public GitContributor(PersonIdent author, GitContribution totalContribution, Map<Integer, Integer> dailyContributions) {+ public GitContributor(PersonIdent author, int totalCommits, Map<Integer, Integer> dailyContributions) {this.author = author;- this.totalContribution = totalContribution;+ this.totalCommits = totalCommits;this.dailyContributions = dailyContributions;}@@ -25,8 +25,8 @@ public class GitContributor implements Serializable {return author;}- public GitContribution getTotalContribution() {- return totalContribution;+ public int getTotalCommits() {+ return totalCommits;}public Map<Integer, Integer> getDailyContributions() {diff --git a/server-core/src/main/java/io/onedev/server/git/command/ListNumStatsCommand.java b/server-core/src/main/java/io/onedev/server/git/command/ListNumStatsCommand.javaindex db94cee4fd..6d35adf1f5 100644--- a/server-core/src/main/java/io/onedev/server/git/command/ListNumStatsCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/ListNumStatsCommand.java@@ -42,8 +42,7 @@ public class ListNumStatsCommand {if (noRenames) {git.addArgs("diff", "--numstat", "--no-renames", fromRev + ".." + toRev);} else {- git.addArgs("-c", "diff.renameLimit=1000", "diff", "--numstat",- "--find-renames=100%", fromRev + ".." + toRev);+ git.addArgs("diff", "--numstat", "--find-renames=100%", fromRev + ".." + toRev);}git.execute(new LineConsumer() {diff --git a/server-core/src/main/java/io/onedev/server/git/command/LogCommand.java b/server-core/src/main/java/io/onedev/server/git/command/LogCommand.javaindex 3f56090c26..2ca7cc08cd 100644--- a/server-core/src/main/java/io/onedev/server/git/command/LogCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/LogCommand.java@@ -23,7 +23,7 @@ public abstract class LogCommand {private static final Logger logger = LoggerFactory.getLogger(LogCommand.class);- public enum Field {PARENTS, AUTHOR, COMMITTER, COMMIT_DATE, SUBJECT, BODY, FILE_CHANGES, LINE_CHANGES};+ public enum Field {PARENTS, AUTHOR, COMMITTER, COMMIT_DATE, SUBJECT, BODY, FILE_CHANGES};private static final String BODY_END = "$<#BodyEnd#>$";@@ -110,23 +110,19 @@ public abstract class LogCommand {format += "body:%b" + BODY_END + "%n";if (noRenames) {- if (fields.contains(Field.LINE_CHANGES))- git.addArgs("log", "--numstat", "--no-renames");- else if (fields.contains(Field.FILE_CHANGES))+ if (fields.contains(Field.FILE_CHANGES))git.addArgs("log", "--name-status", "--no-renames");elsegit.addArgs("log");} else {- if (fields.contains(Field.LINE_CHANGES))- git.addArgs("-c", "diff.renameLimit=1000", "log", "--numstat", "--find-renames=100%");- else if (fields.contains(Field.FILE_CHANGES))- git.addArgs("-c", "diff.renameLimit=1000", "log", "--name-status", "--find-renames=100%");+ if (fields.contains(Field.FILE_CHANGES))+ git.addArgs("log", "--name-status", "--find-renames=100%");elsegit.addArgs("log");}git.addArgs("--format=" + format, "--date=raw");- if (options.firstParent() && (fields.contains(Field.LINE_CHANGES) || fields.contains(Field.FILE_CHANGES)))+ if (options.firstParent() && fields.contains(Field.FILE_CHANGES))git.addArgs("-m");options.configure(git);@@ -159,7 +155,7 @@ public abstract class LogCommand {commitBuilderRef.set(new LogCommit.Builder());if (fields.contains(Field.PARENTS))commitBuilderRef.get().parentHashes = new ArrayList<>();- if (fields.contains(Field.FILE_CHANGES) || fields.contains(Field.LINE_CHANGES))+ if (fields.contains(Field.FILE_CHANGES))commitBuilderRef.get().fileChanges = new ArrayList<>();commitBuilderRef.get().hash = line.substring("hash:".length()).trim();} else if (line.startsWith("parents:")) {@@ -187,28 +183,24 @@ public abstract class LogCommand {commitBuilderRef.get().subject = line.substring("subject:".length()).trim();} else if (line.trim().length() != 0 && line.contains("\t")) {FileChange change;- if (fields.contains(Field.LINE_CHANGES)) {- change = GitUtils.parseNumStats(line);- } else {- StringTokenizer tokenizer = new StringTokenizer(line, "\t");- String statusCode = tokenizer.nextToken();- if (statusCode.startsWith("R")) {- String oldPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));- String newPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));- change = new FileChange(oldPath, newPath, -1, -1);- } else if (statusCode.equals("M") || statusCode.equals("T")) {- String path = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));- change = new FileChange(path, path, -1, -1);- } else if (statusCode.equals("D")) {- String oldPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));- change = new FileChange(oldPath, null, -1, -1);- } else if (statusCode.equals("A")) {- String newPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));- change = new FileChange(null, newPath, -1, -1);- } else {- change = null;- }- }+ StringTokenizer tokenizer = new StringTokenizer(line, "\t");+ String statusCode = tokenizer.nextToken();+ if (statusCode.startsWith("R")) {+ String oldPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));+ String newPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));+ change = new FileChange(oldPath, newPath, -1, -1);+ } else if (statusCode.equals("M") || statusCode.equals("T")) {+ String path = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));+ change = new FileChange(path, path, -1, -1);+ } else if (statusCode.equals("D")) {+ String oldPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));+ change = new FileChange(oldPath, null, -1, -1);+ } else if (statusCode.equals("A")) {+ String newPath = QuotedString.GIT_PATH.dequote(tokenizer.nextToken("\t"));+ change = new FileChange(null, newPath, -1, -1);+ } else {+ change = null;+ }if (change != null)commitBuilderRef.get().fileChanges.add(change);}@@ -218,12 +210,7 @@ public abstract class LogCommand {@Overridepublic void consume(String line) {- if (line.contains("inexact rename detection was skipped")- || line.contains("you may want to set your diff.renameLimit variable")) {- logger.trace(line);- } else {- logger.error(line);- }+ logger.error(line);}}).checkReturnCode();diff --git a/server-core/src/main/java/io/onedev/server/git/command/LogCommit.java b/server-core/src/main/java/io/onedev/server/git/command/LogCommit.javaindex 84f58b9924..c6b7f6d48d 100644--- a/server-core/src/main/java/io/onedev/server/git/command/LogCommit.java+++ b/server-core/src/main/java/io/onedev/server/git/command/LogCommit.java@@ -12,7 +12,6 @@ import org.apache.commons.lang3.StringUtils;import org.eclipse.jgit.lib.PersonIdent;import io.onedev.server.git.GitUtils;-import io.onedev.server.util.patternset.PatternSet;public class LogCommit implements Serializable {@@ -97,24 +96,6 @@ public class LogCommit implements Serializable {return commitDate;}- public int getAdditions(@Nullable PatternSet patterns) {- int additions = 0;- for (FileChange change: fileChanges) {- if (change.getAdditions() > 0 && change.matches(patterns))- additions += change.getAdditions();- }- return additions;- }-- public int getDeletions(@Nullable PatternSet patterns) {- int deletions = 0;- for (FileChange change: fileChanges) {- if (change.getDeletions() > 0 && change.matches(patterns))- deletions += change.getDeletions();- }- return deletions;- }-public static class Builder {public String hash;diff --git a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchCreatedSpec.java b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchCreatedSpec.javaindex e7e60d79e3..042a42afaa 100644--- a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchCreatedSpec.java+++ b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchCreatedSpec.java@@ -48,7 +48,7 @@ public class BranchCreatedSpec extends AutoSpec {}@Editable(order=9900, name="Applicable Issues", placeholder="All", description="Optionally specify issues applicable "- + "for this transition. Leave empty for all issues")+ + "for this transition in same project as the branch. Leave empty for all issues")@IssueQuery(withOrder = false, withCurrentBranchCriteria = true)@Overridepublic String getIssueQuery() {diff --git a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchUpdatedSpec.java b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchUpdatedSpec.javaindex 3e6dafa737..a896b6223c 100644--- a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchUpdatedSpec.java+++ b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BranchUpdatedSpec.java@@ -61,7 +61,7 @@ public class BranchUpdatedSpec extends AutoSpec {}@Editable(order=9900, name="Applicable Issues", placeholder="All", description="Optionally specify issues applicable "- + "for this transition. Leave empty for all issues")+ + "for this transition in same project as the branch. Leave empty for all issues")@IssueQuery(withOrder = false, withCurrentCommitCriteria = true)@Overridepublic String getIssueQuery() {diff --git a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BuildSuccessfulSpec.java b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BuildSuccessfulSpec.javaindex aa09bef54f..2f4e247536 100644--- a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BuildSuccessfulSpec.java+++ b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/BuildSuccessfulSpec.java@@ -73,7 +73,7 @@ public class BuildSuccessfulSpec extends AutoSpec {}@Editable(order=9900, name="Applicable Issues", placeholder="All", description="Optionally specify issues "- + "applicable for this transition. Leave empty for all issues")+ + "applicable for this transition in same project as the build. Leave empty for all issues")@IssueQuery(withOrder = false, withCurrentBuildCriteria = true)@Overridepublic String getIssueQuery() {diff --git a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/PullRequestSpec.java b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/PullRequestSpec.javaindex 23102a4a55..2667f98c91 100644--- a/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/PullRequestSpec.java+++ b/server-core/src/main/java/io/onedev/server/model/support/issue/transitionspec/PullRequestSpec.java@@ -38,7 +38,7 @@ public abstract class PullRequestSpec extends AutoSpec {}@Editable(order=9900, name="Applicable Issues", placeholder="All", description="Optionally specify issues "- + "applicable for this transition. Leave empty for all issues")+ + "applicable for this transition in same project as the pull request. Leave empty for all issues")@IssueQuery(withOrder = false, withCurrentPullRequestCriteria = true)@Overridepublic String getIssueQuery() {diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.javaindex 7e91aa6fdb..36fe9e3e95 100644--- a/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java+++ b/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java@@ -43,7 +43,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;import io.onedev.commons.utils.ExplicitException;import io.onedev.server.data.migration.VersionedXmlDoc;-import io.onedev.server.git.GitContribution;import io.onedev.server.git.GitContributor;import io.onedev.server.model.BaseAuthorization;import io.onedev.server.model.GroupAuthorization;@@ -262,7 +261,6 @@ public class ProjectResource {@Path("/{projectId}/top-contributors")@GETpublic List<GitContributor> getTopContributors(@PathParam("projectId") Long projectId,- @QueryParam("type") @NotNull GitContribution.Type type,@QueryParam("sinceDate") @NotEmpty @Api(description="Since date of format <i>yyyy-MM-dd</i>") String since,@QueryParam("untilDate") @NotEmpty @Api(description="Until date of format <i>yyyy-MM-dd</i>") String until,@QueryParam("count") int count) {@@ -276,7 +274,7 @@ public class ProjectResource {int sinceDay = (int) LocalDate.parse(since).toEpochDay();int untilDay = (int) LocalDate.parse(until).toEpochDay();- return commitInfoService.getTopContributors(project.getId(), count, type, sinceDay, untilDay);+ return commitInfoService.getTopContributors(project.getId(), count, sinceDay, untilDay);}@SuppressWarnings("unused")diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultCodeCommentService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultCodeCommentService.javaindex 36307d46bb..ecc23fa6d1 100644--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultCodeCommentService.java+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultCodeCommentService.java@@ -14,7 +14,6 @@ import java.util.List;import java.util.Map;import java.util.stream.Collectors;-import org.jspecify.annotations.Nullable;import javax.inject.Inject;import javax.inject.Singleton;import javax.persistence.criteria.CriteriaBuilder;@@ -33,10 +32,10 @@ import org.hibernate.criterion.Criterion;import org.hibernate.criterion.Restrictions;import org.hibernate.query.Query;import org.hibernate.query.criteria.internal.path.SingularAttributePath;+import org.jspecify.annotations.Nullable;import com.google.common.base.Preconditions;import com.google.common.collect.Lists;-import com.google.common.collect.Sets;import io.onedev.commons.utils.PlanarRange;import io.onedev.server.OneDev;@@ -70,7 +69,6 @@ import io.onedev.server.util.ProjectScope;import io.onedev.server.util.criteria.Criteria;import io.onedev.server.util.diff.DiffUtils;import io.onedev.server.util.diff.WhitespaceOption;-import io.onedev.server.xodus.CommitInfoService;@Singletonpublic class DefaultCodeCommentService extends BaseEntityService<CodeComment> implements CodeCommentService {@@ -82,9 +80,6 @@ public class DefaultCodeCommentService extends BaseEntityService<CodeComment> im@Injectprivate ListenerRegistry listenerRegistry;- @Inject- private CommitInfoService commitInfoService;-@Transactional@Overridepublic void create(CodeComment comment) {@@ -154,12 +149,10 @@ public class DefaultCodeCommentService extends BaseEntityService<CodeComment> imMap<CodeComment, PlanarRange> comments = new HashMap<>();Map<String, Map<String, List<CodeComment>>> possibleComments = new HashMap<>();- Collection<String> possiblePaths = Sets.newHashSet(path);- possiblePaths.addAll(commitInfoService.getHistoryPaths(project.getId(), path));EntityCriteria<CodeComment> criteria = EntityCriteria.of(CodeComment.class);criteria.add(Restrictions.eq(CodeComment.PROP_PROJECT, project));- criteria.add(Restrictions.in(CodeComment.PROP_MARK + "." + Mark.PROP_PATH, possiblePaths));+ criteria.add(Restrictions.eq(CodeComment.PROP_MARK + "." + Mark.PROP_PATH, path));for (CodeComment comment: query(criteria)) {String possiblePath = comment.getMark().getPath();diff --git a/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java b/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.javaindex 02a922df83..56e6bf5f73 100644--- a/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java+++ b/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java@@ -161,7 +161,6 @@ import io.onedev.server.web.page.project.setting.servicedesk.ServiceDeskSettingPimport io.onedev.server.web.page.project.setting.webhook.WebHooksPage;import io.onedev.server.web.page.project.setting.workspacespec.WorkspaceSpecsPage;import io.onedev.server.web.page.project.stats.code.CodeContribsPage;-import io.onedev.server.web.page.project.stats.code.SourceLinesPage;import io.onedev.server.web.page.project.tags.ProjectTagsPage;import io.onedev.server.web.page.project.workspaces.ProjectWorkspacesPage;import io.onedev.server.web.page.project.workspaces.detail.changes.WorkspaceChangesPage;@@ -435,7 +434,6 @@ public class BaseUrlMapper extends CompoundRequestMapper {add(new ProjectPageMapper("${project}/~commits/${commit}", CommitDetailPage.class));add(new ProjectPageMapper("${project}/~compare", RevisionComparePage.class));add(new ProjectPageMapper("${project}/~stats/code/contribs", CodeContribsPage.class));- add(new ProjectPageMapper("${project}/~stats/code/lines", SourceLinesPage.class));add(new ProjectPageMapper("${project}/~branches", ProjectBranchesPage.class));add(new ProjectPageMapper("${project}/~tags", ProjectTagsPage.class));diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.javaindex f86937687e..60b3b84736 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java@@ -111,7 +111,6 @@ import io.onedev.server.web.page.project.setting.servicedesk.ServiceDeskSettingPimport io.onedev.server.web.page.project.setting.webhook.WebHooksPage;import io.onedev.server.web.page.project.setting.workspacespec.WorkspaceSpecsPage;import io.onedev.server.web.page.project.stats.code.CodeContribsPage;-import io.onedev.server.web.page.project.stats.code.SourceLinesPage;import io.onedev.server.web.page.project.tags.ProjectTagsPage;import io.onedev.server.web.page.project.workspaces.ProjectWorkspacesPage;import io.onedev.server.web.page.project.workspaces.detail.WorkspaceDetailPage;@@ -267,9 +266,8 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware {List<SidebarMenuItem> statsMenuItems = new ArrayList<>();if (getProject().isCodeManagement() && SecurityUtils.canReadCode(getProject())) {- statsMenuItems.add(new SidebarMenuItem.Page(null, _T("Code"),- CodeContribsPage.class, CodeContribsPage.paramsOf(getProject()),- Lists.newArrayList(SourceLinesPage.class)));+ statsMenuItems.add(new SidebarMenuItem.Page(null, _T("Code Contributions"),+ CodeContribsPage.class, CodeContribsPage.paramsOf(getProject())));}// Add the sub menu even if it is empty as we need to place stats menu in the right place.diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.htmlindex b2d9a73fb0..8cc254bef7 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.html+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.html@@ -1,20 +1,19 @@<wicket:extend>- <div class="code-contribs">- <wicket:enclosure child="note">- <div class="alert alert-light alert-notice mb-5">- <wicket:svg href="bulb" class="icon mr-2"/><span wicket:id="note"></span>+ <div class="code-contribs p-2 p-sm-5 d-flex flex-column flex-grow-1">+ <div class="card d-flex flex-column flex-grow-1">+ <div class="card-body d-flex flex-column flex-grow-1">+ <div class="alert alert-light alert-notice mb-4 d-flex align-items-center flex-wrap">+ <div class="mr-auto d-flex align-items-center">+ <wicket:enclosure child="note">+ <wicket:svg href="bulb" class="icon mr-2"/><span wicket:id="note"></span>+ </wicket:enclosure>+ </div>+ <select wicket:id="period" class="form-control form-control-sm period"></select>+ </div>+ <div class="overall chart border p-4 rounded mb-4"></div>+ <div class="top-contributors"></div>+ </div></div>- </wicket:enclosure>- <div class="d-flex align-items-center mb-4">- <span class="date-range mr-3 font-size-h5"></span>- <select class="contrib-type custom-select form-control ml-auto">- <option value="Commits"><wicket:t>Commits</wicket:t></option>- <option value="Additions"><wicket:t>Additions</wicket:t></option>- <option value="Deletions"><wicket:t>Deletions</wicket:t></option>- </select>- </div>- <div class="overall chart border p-4 rounded mb-4"></div>- <div class="top-contributors"></div></div><div wicket:id="userCard" class="user-card-content"></div>-</wicket:extend>\ No newline at end of file+</wicket:extend>diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.javaindex 8be59f6db8..869dc2865d 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsPage.java@@ -3,17 +3,27 @@ package io.onedev.server.web.page.project.stats.code;import static io.onedev.server.web.translation.Translation._T;import java.text.MessageFormat;+import java.time.LocalDate;+import java.util.Arrays;import java.util.HashMap;+import java.util.List;import java.util.Map;+import java.util.stream.Collectors;import org.apache.wicket.Component;import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;import org.apache.wicket.ajax.AjaxRequestTarget;import org.apache.wicket.ajax.attributes.CallbackParameter;+import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.head.JavaScriptHeaderItem;import org.apache.wicket.markup.head.OnDomReadyHeaderItem;import org.apache.wicket.markup.html.WebMarkupContainer;import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.form.DropDownChoice;+import org.apache.wicket.markup.html.form.IChoiceRenderer;+import org.apache.wicket.markup.html.link.BookmarkablePageLink;+import org.apache.wicket.model.IModel;import org.apache.wicket.request.cycle.RequestCycle;import org.apache.wicket.request.mapper.parameter.PageParameters;import org.eclipse.jgit.lib.PersonIdent;@@ -22,20 +32,40 @@ import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import io.onedev.server.OneDev;-import io.onedev.server.git.GitContribution;+import io.onedev.server.model.Project;import io.onedev.server.security.SecurityUtils;import io.onedev.server.web.behavior.AbstractPostAjaxBehavior;+import io.onedev.server.web.component.link.ViewStateAwarePageLink;import io.onedev.server.web.component.user.card.PersonCardPanel;+import io.onedev.server.web.page.project.ProjectPage;+import io.onedev.server.web.page.project.dashboard.ProjectDashboardPage;import io.onedev.server.xodus.CommitInfoService;-public class CodeContribsPage extends CodeStatsPage {+public class CodeContribsPage extends ProjectPage {private static final String USER_CARD_ID = "userCard";+ private static final String PARAM_PERIOD = "period";++ private static final ContributionPeriod DEFAULT_PERIOD = ContributionPeriod.SIX_MONTHS;+private AbstractDefaultAjaxBehavior userCardBehavior;+ private ContributionPeriod period;+public CodeContribsPage(PageParameters params) {super(params);++ var periodValue = params.get(PARAM_PERIOD).toOptionalString();+ if (periodValue != null) {+ try {+ period = ContributionPeriod.valueOf(periodValue.toUpperCase());+ } catch (IllegalArgumentException e) {+ period = DEFAULT_PERIOD;+ }+ } else {+ period = DEFAULT_PERIOD;+ }}@Override@@ -50,6 +80,52 @@ public class CodeContribsPage extends CodeStatsPage {add(new Label("note", MessageFormat.format(_T("Contributions to {0} branch, excluding merge commits"), getProject().getDefaultBranch())));elseadd(new WebMarkupContainer("note").setVisible(false));++ var periods = Arrays.asList(ContributionPeriod.values());+ var periodChoice = new DropDownChoice<>("period", new IModel<ContributionPeriod>() {++ @Override+ public void detach() {+ }++ @Override+ public ContributionPeriod getObject() {+ return period;+ }++ @Override+ public void setObject(ContributionPeriod object) {+ period = object;+ }++ }, periods, new IChoiceRenderer<ContributionPeriod>() {++ @Override+ public Object getDisplayValue(ContributionPeriod object) {+ return object.getDisplayName();+ }++ @Override+ public String getIdValue(ContributionPeriod object, int index) {+ return object.name();+ }++ @Override+ public ContributionPeriod getObject(String id, IModel<? extends List<? extends ContributionPeriod>> choices) {+ return ContributionPeriod.valueOf(id);+ }++ });+ periodChoice.add(new OnChangeAjaxBehavior() {++ @Override+ protected void onUpdate(AjaxRequestTarget target) {+ setResponsePage(CodeContribsPage.class, paramsOf(getProject(), period));+ }++ });+ add(periodChoice);+add(new WebMarkupContainer(USER_CARD_ID).setOutputMarkupId(true));add(userCardBehavior = new AbstractPostAjaxBehavior() {@@ -64,7 +140,7 @@ public class CodeContribsPage extends CodeStatsPage {userCard.setOutputMarkupId(true);replace(userCard);target.add(userCard);- target.appendJavaScript("onedev.server.codeStats.contribs.onUserCardAvailable();");+ target.appendJavaScript("onedev.server.codeContribs.onUserCardAvailable();");}});@@ -74,29 +150,35 @@ public class CodeContribsPage extends CodeStatsPage {public void renderHead(IHeaderResponse response) {super.renderHead(response);+ response.render(JavaScriptHeaderItem.forReference(new CodeContribsResourceReference()));+CommitInfoService commitInfoService = OneDev.getInstance(CommitInfoService.class);- Map<Integer, Integer[]> data = new HashMap<>();- Map<Integer, GitContribution> overallContributions =+ Map<Integer, Integer> overallContributions =commitInfoService.getOverallContributions(getProject().getId());- for (Map.Entry<Integer, GitContribution> entry: overallContributions.entrySet()) {- GitContribution contribution = entry.getValue();- Integer[] dataValue = new Integer[] {contribution.getCommits(), contribution.getAdditions(), contribution.getDeletions()};- data.put(entry.getKey(), dataValue);++ Integer fromDay = period.getFromDay();+ if (fromDay != null) {+ var fromDayValue = fromDay;+ overallContributions = overallContributions.entrySet().stream()+ .filter(it -> it.getKey() >= fromDayValue)+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));}PageParameters params = TopContributorsResource.paramsOf(getProject());String topContributorsUrl = urlFor(new TopContributorsResourceReference(), params).toString();var mapper = OneDev.getInstance(ObjectMapper.class);try {- var jsonOfData = mapper.writeValueAsString(data);+ var jsonOfData = mapper.writeValueAsString(overallContributions);var translations = new HashMap<String, String>();translations.put("commits", _T("commits"));translations.put("noData", _T("No data"));var jsonOfTranslations = mapper.writeValueAsString(translations);CharSequence callback = userCardBehavior.getCallbackFunction(CallbackParameter.explicit("name"), CallbackParameter.explicit("emailAddress"));- String script = String.format("onedev.server.codeStats.contribs.onDomReady(%s, '%s', %s, %b, %s);",- jsonOfData, topContributorsUrl, callback, isDarkMode(), jsonOfTranslations);+ String toDay = fromDay != null ? String.valueOf((int) LocalDate.now().toEpochDay()) : "null";+ String script = String.format("onedev.server.codeContribs.onDomReady(%s, '%s', %s, %b, %s, %s, %s);",+ jsonOfData, topContributorsUrl, callback, isDarkMode(), jsonOfTranslations,+ fromDay != null ? fromDay : "null", toDay);response.render(OnDomReadyHeaderItem.forScript(script));} catch (JsonProcessingException e) {throw new RuntimeException(e);@@ -105,7 +187,22 @@ public class CodeContribsPage extends CodeStatsPage {@Overrideprotected Component newProjectTitle(String componentId) {- return new Label(componentId, _T("Code Contribution Statistics"));+ return new Label(componentId, _T("Code Contributions"));+ }++ @Override+ protected BookmarkablePageLink<Void> navToProject(String componentId, Project project) {+ if (project.isCodeManagement() && SecurityUtils.canReadCode(project))+ return new ViewStateAwarePageLink<>(componentId, getPageClass(), paramsOf(project));+ else+ return new ViewStateAwarePageLink<>(componentId, ProjectDashboardPage.class, ProjectDashboardPage.paramsOf(project.getId()));+ }++ public static PageParameters paramsOf(Project project, ContributionPeriod period) {+ PageParameters params = paramsOf(project);+ if (period != DEFAULT_PERIOD)+ params.add(PARAM_PERIOD, period.name().toLowerCase());+ return params;}}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsResourceReference.java b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsResourceReference.javasimilarity index 81%rename from server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsResourceReference.javarename to server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsResourceReference.javaindex a609ae2f2e..0fd126af43 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsResourceReference.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeContribsResourceReference.java@@ -1,23 +1,24 @@package io.onedev.server.web.page.project.stats.code;-import io.onedev.server.web.asset.doneevents.DoneEventsResourceReference;-import io.onedev.server.web.asset.echarts.EChartsResourceReference;-import io.onedev.server.web.asset.hover.HoverResourceReference;-import io.onedev.server.web.asset.jsjoda.JsJodaResourceReference;-import io.onedev.server.web.page.base.BaseDependentResourceReference;+import java.util.List;+import org.apache.wicket.markup.head.CssHeaderItem;import org.apache.wicket.markup.head.HeaderItem;import org.apache.wicket.markup.head.JavaScriptHeaderItem;import org.apache.wicket.request.resource.CssResourceReference;-import java.util.List;+import io.onedev.server.web.asset.doneevents.DoneEventsResourceReference;+import io.onedev.server.web.asset.echarts.EChartsResourceReference;+import io.onedev.server.web.asset.hover.HoverResourceReference;+import io.onedev.server.web.asset.jsjoda.JsJodaResourceReference;+import io.onedev.server.web.page.base.BaseDependentResourceReference;-public class CodeStatsResourceReference extends BaseDependentResourceReference {+public class CodeContribsResourceReference extends BaseDependentResourceReference {private static final long serialVersionUID = 1L;- public CodeStatsResourceReference() {- super(CodeStatsResourceReference.class, "code-stats.js");+ public CodeContribsResourceReference() {+ super(CodeContribsResourceReference.class, "code-contribs.js");}@Override@@ -28,7 +29,7 @@ public class CodeStatsResourceReference extends BaseDependentResourceReference {dependencies.add(JavaScriptHeaderItem.forReference(new HoverResourceReference()));dependencies.add(JavaScriptHeaderItem.forReference(new JsJodaResourceReference()));dependencies.add(CssHeaderItem.forReference(- new CssResourceReference(CodeStatsResourceReference.class, "code-stats.css")));+ new CssResourceReference(CodeContribsResourceReference.class, "code-contribs.css")));return dependencies;}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsPage.htmldeleted file mode 100644index ef9d74d9ea..0000000000--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsPage.html+++ /dev/null@@ -1,11 +0,0 @@-<wicket:extend>- <div class="code-stats p-2 p-sm-5 d-flex flex-column flex-grow-1">- <div class="card d-flex flex-column flex-grow-1">- <div class="card-body d-flex flex-column flex-grow-1">- <ul wicket:id="tabs" class="tabs nav nav-tabs nav-tabs-line mb-5"></ul>- <wicket:child></wicket:child>- </div>- </div>- </div>-</wicket:extend>-diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsPage.javadeleted file mode 100644index a03f44a59d..0000000000--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/CodeStatsPage.java+++ /dev/null@@ -1,62 +0,0 @@-package io.onedev.server.web.page.project.stats.code;--import static io.onedev.server.web.translation.Translation._T;--import java.util.ArrayList;--import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.JavaScriptHeaderItem;-import org.apache.wicket.markup.html.link.BookmarkablePageLink;-import org.apache.wicket.model.Model;-import org.apache.wicket.request.mapper.parameter.PageParameters;--import io.onedev.server.model.Project;-import io.onedev.server.security.SecurityUtils;-import io.onedev.server.web.component.link.ViewStateAwarePageLink;-import io.onedev.server.web.component.tabbable.PageTab;-import io.onedev.server.web.component.tabbable.Tabbable;-import io.onedev.server.web.page.project.ProjectPage;-import io.onedev.server.web.page.project.dashboard.ProjectDashboardPage;--public abstract class CodeStatsPage extends ProjectPage {-- public CodeStatsPage(PageParameters params) {- super(params);- }-- @Override- protected void onInitialize() {- super.onInitialize();-- var tabs = new ArrayList<PageTab>();- var params = paramsOf(getProject());- tabs.add(new PageTab(Model.of(_T("Contributions")), CodeContribsPage.class, params));- tabs.add(new PageTab(Model.of(_T("Source Lines")), SourceLinesPage.class, params));- add(new Tabbable("tabs", tabs));- }-- @Override- protected boolean isPermitted() {- return SecurityUtils.canReadCode(getProject());- }-- @Override- public void renderHead(IHeaderResponse response) {- super.renderHead(response);- response.render(JavaScriptHeaderItem.forReference(new CodeStatsResourceReference()));- }-- @Override- protected String getPageTitle() {- return _T("Code Statistics") + " - " + getProject().getPath();- }-- @Override- protected BookmarkablePageLink<Void> navToProject(String componentId, Project project) {- if (project.isCodeManagement() && SecurityUtils.canReadCode(project))- return new ViewStateAwarePageLink<>(componentId, getPageClass(), paramsOf(project.getId()));- else- return new ViewStateAwarePageLink<>(componentId, ProjectDashboardPage.class, ProjectDashboardPage.paramsOf(project.getId()));- }--}\ No newline at end of filediff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/ContributionPeriod.java b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/ContributionPeriod.javanew file mode 100644index 0000000000..3396e392b0--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/ContributionPeriod.java@@ -0,0 +1,45 @@+package io.onedev.server.web.page.project.stats.code;++import static io.onedev.server.web.translation.Translation._T;++import java.time.LocalDate;++import org.jspecify.annotations.Nullable;++enum ContributionPeriod {++ SIX_MONTHS, ONE_YEAR, FIVE_YEARS, ALL;++ String getDisplayName() {+ switch (this) {+ case SIX_MONTHS:+ return _T("6 Months");+ case ONE_YEAR:+ return _T("1 Year");+ case FIVE_YEARS:+ return _T("5 Years");+ case ALL:+ return _T("All");+ default:+ throw new RuntimeException("Unexpected period: " + this);+ }+ }++ @Nullable+ Integer getFromDay() {+ var today = LocalDate.now();+ switch (this) {+ case SIX_MONTHS:+ return (int) today.minusMonths(6).toEpochDay();+ case ONE_YEAR:+ return (int) today.minusYears(1).toEpochDay();+ case FIVE_YEARS:+ return (int) today.minusYears(5).toEpochDay();+ case ALL:+ return null;+ default:+ throw new RuntimeException("Unexpected period: " + this);+ }+ }++}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/SourceLinesPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/SourceLinesPage.htmldeleted file mode 100644index 46a45039cc..0000000000--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/SourceLinesPage.html+++ /dev/null@@ -1,5 +0,0 @@-<wicket:extend>- <div class="source-lines d-flex flex-column flex-grow-1 overflow-auto">- <div class="chart resize-aware flex-grow-1"></div>- </div>-</wicket:extend>diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/SourceLinesPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/SourceLinesPage.javadeleted file mode 100644index 5d74cb0b40..0000000000--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/SourceLinesPage.java+++ /dev/null@@ -1,59 +0,0 @@-package io.onedev.server.web.page.project.stats.code;--import static io.onedev.server.web.translation.Translation._T;--import java.util.HashMap;-import java.util.LinkedHashMap;-import java.util.Map;-import java.util.TreeSet;--import org.apache.wicket.Component;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.request.mapper.parameter.PageParameters;--import com.fasterxml.jackson.core.JsonProcessingException;-import com.fasterxml.jackson.databind.ObjectMapper;--import io.onedev.server.OneDev;-import io.onedev.server.xodus.CommitInfoService;--public class SourceLinesPage extends CodeStatsPage {-- public SourceLinesPage(PageParameters params) {- super(params);- }-- @Override- public void renderHead(IHeaderResponse response) {- super.renderHead(response);-- Map<Integer, Map<String, Integer>> lineIncrements = OneDev.getInstance(CommitInfoService.class)- .getLineIncrements(getProject().getId());- Map<Integer, Map<String, Integer>> data = new LinkedHashMap<>();- for (var key: new TreeSet<>(lineIncrements.keySet()))- data.put(key, lineIncrements.get(key));- var translations = new HashMap<String, String>();- translations.put("noData", _T("No data"));- translations.put("noDefaultBranch", _T("No default branch"));- translations.put("sloc", _T("SLOC on {0}"));- try {- ObjectMapper mapper = OneDev.getInstance(ObjectMapper.class);- String jsonOfData = mapper.writeValueAsString(data);- String jsonOfDefaultBranch = mapper.writeValueAsString(getProject().getDefaultBranch());- String jsonOfTranslations = mapper.writeValueAsString(translations);- String script = String.format("onedev.server.codeStats.sourceLines.onDomReady(%s, %s, %b, %s);",- jsonOfData, jsonOfDefaultBranch, isDarkMode(), jsonOfTranslations);- response.render(OnDomReadyHeaderItem.forScript(script));- } catch (JsonProcessingException e) {- throw new RuntimeException(e);- }- }-- @Override- protected Component newProjectTitle(String componentId) {- return new Label(componentId, _T("Code Line Statistics"));- }--}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/TopContributorsResource.java b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/TopContributorsResource.javaindex eabb011e63..0d70183b4b 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/TopContributorsResource.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/TopContributorsResource.java@@ -21,7 +21,6 @@ import com.google.common.collect.Lists;import io.onedev.server.OneDev;import io.onedev.server.service.EmailAddressService;-import io.onedev.server.git.GitContribution;import io.onedev.server.git.GitContributor;import io.onedev.server.model.EmailAddress;import io.onedev.server.model.Project;@@ -46,8 +45,6 @@ class TopContributorsResource extends AbstractResource {private static final String PARAM_TO = "to";- private static final String PARAM_TYPE = "type";-private static final int TOP_CONTRIBUTORS = 100;@Override@@ -56,7 +53,6 @@ class TopContributorsResource extends AbstractResource {Long projectId = params.get(PARAM_PROJECT).toLong();int fromDay = params.get(PARAM_FROM).toInteger();int toDay = params.get(PARAM_TO).toInteger();- GitContribution.Type type = GitContribution.Type.valueOf(params.get(PARAM_TYPE).toString());ResourceResponse response = new ResourceResponse();response.setContentType("application/json");@@ -73,7 +69,7 @@ class TopContributorsResource extends AbstractResource {String toDate = formatISO8601Date(toDate(ofEpochDay(toDay).plusDays(1).atStartOfDay()));List<GitContributor> topContributors = OneDev.getInstance(CommitInfoService.class)- .getTopContributors(project.getId(), TOP_CONTRIBUTORS, type, fromDay, toDay);+ .getTopContributors(project.getId(), TOP_CONTRIBUTORS, fromDay, toDay);AvatarService avatarService = OneDev.getInstance(AvatarService.class);EmailAddressService emailAddressService = OneDev.getInstance(EmailAddressService.class);@@ -85,9 +81,7 @@ class TopContributorsResource extends AbstractResource {contributorData.put("authorName", author.getName());contributorData.put("authorEmailAddress", author.getEmailAddress());contributorData.put("authorAvatarUrl", avatarService.getPersonAvatarUrl(author));- contributorData.put("totalCommits", contributor.getTotalContribution().getCommits());- contributorData.put("totalAdditions", contributor.getTotalContribution().getAdditions());- contributorData.put("totalDeletions", contributor.getTotalContribution().getDeletions());+ contributorData.put("totalCommits", contributor.getTotalCommits());AuthorCriteria authorCriteria;EmailAddress emailAddress = emailAddressService.findByValue(author.getEmailAddress());diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-stats.css b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-contribs.csssimilarity index 67%rename from server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-stats.cssrename to server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-contribs.cssindex 3e687b9acd..896ff8e818 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-stats.css+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-contribs.css@@ -1,5 +1,5 @@-.code-contribs select {- width: 120px;+.code-contribs .alert .period {+ width: 10rem;}.code-contribs .overall {height: 360px;@@ -20,13 +20,6 @@background: url(/~img/dark-ajax-indicator-big.png) no-repeat scroll center center;}-.code-contribs .top-contributors .head .total-contribution span.additions {- color: green;-}-.code-contribs .top-contributors .head .total-contribution span.deletions {- color: red;-}-.code-contribs .top-contributors .avatar {width: 36px;height: 36px;@@ -40,12 +33,3 @@.code-contribs .top-contributors .col-xl-6.right {padding-left: 1rem;}--.source-lines .chart {- min-height: 400px;-}-.source-lines .no-data {- text-align: center;- font-size: 3rem;- font-style: italic;-}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-contribs.js b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-contribs.jsnew file mode 100644index 0000000000..fe739d9e1d--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-contribs.js@@ -0,0 +1,333 @@+onedev.server.codeContribs = {+ formatYAxisLabel: function(value, index, useKilo) {+ if (index == 0)+ useKilo = false;+ else if (index == 1 && value >= 1000)+ useKilo = true;+ return {+ useKilo: useKilo,+ value: useKilo? (value/1000).toFixed(1) + " k": value+ }+ },+ formatDay: function(day) {+ var localDate = JSJoda.LocalDate.ofEpochDay(day);+ return localDate.year()%100 + "-" + localDate.monthValue() + "-" + localDate.dayOfMonth();+ },+ onDomReady : function(overallContributions, topContributorsDataUrl, userCardCallback, darkMode, translations, fromDay, toDay) {+ var $contribs = $(".code-contribs");+ var $overall = $contribs.find(".overall");+ if (Object.keys(overallContributions).length === 0) {+ $overall.html("<div class='no-data'>" + translations.noData + "</div>");+ return;+ }++ var contribDays = [];++ for (var day in overallContributions)+ contribDays.push(Number(day));++ contribDays.sort(function(day1, day2) {+ return day1 - day2;+ });++ var days = [];++ var lastDay = toDay != null ? toDay : contribDays[contribDays.length-1];+ var currentDay = fromDay != null ? fromDay : contribDays[0];+ while (currentDay <= lastDay) {+ days.push(currentDay);+ currentDay++;+ }++ var fromDay = days[0];+ var toDay = days[days.length-1];++ var $topContributors = $contribs.find(".top-contributors");++ var overallChart = echarts.init($overall[0]);+ $overall.data("chart", overallChart);++ var overallXAxisData = [];+ for (var i=0; i<days.length; i++) {+ overallXAxisData.push(onedev.server.codeContribs.formatDay(days[i]));+ }++ function getOverallSeriesData() {+ var data = [];+ for (var i=0; i<days.length; i++) {+ var contribution = overallContributions[days[i]];+ if (contribution)+ data.push(contribution);+ else+ data.push(0);+ }+ return data;+ }++ var grid = {+ left: '80px',+ right: '40px',+ top: '40px',+ bottom: '40px'+ };++ var useKiloForOverallChart;++ var overallChartOption = {+ grid: grid,+ xAxis: {+ type: 'category',+ data: overallXAxisData,+ boundaryGap: false,+ axisLabel: {+ color: darkMode?'#cdcdde':'#3F4254'+ }+ },+ yAxis: {+ minInterval: 1,+ splitLine: {+ lineStyle: {+ color: darkMode?'#535370':'#E4E6EF'+ }+ },+ axisLine: {+ show: false+ },+ axisLabel: {+ formatter: function(value, index) {+ var result = onedev.server.codeContribs.formatYAxisLabel(value, index, useKiloForOverallChart);+ useKiloForOverallChart = result.useKilo;+ return result.value;+ },+ color: darkMode?'#cdcdde':'#3F4254'+ },+ },+ toolbox: {+ show: false+ },+ brush: {+ xAxisIndex: 'all',+ brushLink: 'all',+ outOfBrush: {+ colorAlpha: 0.1+ },+ brushStyle: {+ color: darkMode?'rgba(55, 60, 63, 0.5)':'rgba(225, 240, 255, 0.5)',+ borderColor: darkMode?'rgba(54, 153, 255, 0.8)':'rgba(54, 153, 255, 0.8)'+ }+ },+ series: [ {+ type: 'line',+ symbol: 'none',+ smooth: true,+ color: "#1BC5BD",+ animation: false,+ data: getOverallSeriesData(),+ areaStyle: {+ color: "#1BC5BD"+ }+ } ]+ };+ overallChart.setOption(overallChartOption);+ overallChart.dispatchAction({+ type: 'takeGlobalCursor',+ key: 'brush',+ brushOption: {+ brushType: 'lineX',+ brushMode: 'single'+ }+ });+ overallChart.on("brush", function(params) {+ if (params.areas[0]) {+ var selection = params.areas[0].coordRange;+ function normalizeIndex(index) {+ if (index < 0)+ return 0;+ else if (index > days.length -1)+ return days.length-1;+ else+ return index;+ }+ fromDay = days[normalizeIndex(selection[0])];+ toDay = days[normalizeIndex(selection[1])];+ } else {+ fromDay = days[0];+ toDay = days[days.length-1];+ }+ $topContributors.trigger("update");+ });++ function updateTopContributors() {+ $topContributors.empty().append("<div class='loading'></div>");+ setTimeout(function() {+ $.ajax({+ url: topContributorsDataUrl + "&from=" + fromDay + "&to=" + toDay,+ cache: false,+ beforeSend: function(xhr) {+ xhr.setRequestHeader('Wicket-Ajax', 'true');+ xhr.setRequestHeader('Wicket-Ajax-BaseURL', Wicket.Ajax.baseUrl || '.');+ },+ success: function(topContributors) {+ var xAxisData = [];+ for (var i=0; i<days.length; i++) {+ if (days[i] >= fromDay && days[i] <= toDay)+ xAxisData.push(onedev.server.codeContribs.formatDay(days[i]));+ }++ var maxValue = 0;+ for (var i=0; i<topContributors.length; i++) {+ for (var day in topContributors[i].dailyContributions) {+ var value = topContributors[i].dailyContributions[day];+ if (maxValue < value)+ maxValue = value;+ }+ }++ function renderContributor($container, contributor, index) {+ function createAuthorLink() {+ var $link = $("<a class='user'></a>");+ if (contributor.authorProfileUrl)+ $link.attr("href", contributor.authorProfileUrl);+ else+ $link.css("cursor", "default");+ return $link;+ }+ var $contrib = $("<div class='contrib border rounded p-3 mb-5'></div>");+ $container.append($contrib);+ var $head = $("<div class='head d-flex align-items-center'></div>");+ $contrib.append($head);+ var $left = $("<div class='mr-3 d-flex align-items-center'></div>");+ $head.append($left);+ var $avatarLink = createAuthorLink();+ $avatarLink.addClass("mr-3");+ $avatarLink.append("<img class='avatar' src='" + contributor.authorAvatarUrl + "'></img>");+ $left.append($avatarLink);++ var $userInfo = $("<div></div>");+ $left.append($userInfo);+ var $nameDiv = $("<div class='font-weight-bold'></div>");+ $nameLink = createAuthorLink();+ $nameLink.append(contributor.authorName);+ $nameDiv.append($nameLink);+ $userInfo.append($nameDiv);++ var alignment = {targetX: 0, targetY: 0, x: 0, y: 100, offset: 8};+ $left.find("a.user").hover(function() {+ var $card = $("<div id='user-card' class='floating'></div>");+ $card.hide();+ $card.data("trigger", this);+ $card.data("alignment", alignment);+ $("body").append($card);+ userCardCallback(contributor.authorName, contributor.authorEmailAddress);+ return $card;+ }, alignment);++ var $totalContribution = $("<div class='total-contribution font-size-sm'></div>");+ $userInfo.append($totalContribution);+ $totalContribution.append("<a href='" + contributor.commitsUrl + "' class='commits'>" + contributor.totalCommits + " " + translations.commits + "</a>");+ $head.append("<div class='ml-auto font-size-h6 font-weight-bold'>#" + (index + 1) + "</div>");++ var $body = $("<div class='body chart'></div>");+ $contrib.append($body);++ var chart = echarts.init($body[0]);+ $body.data("chart", chart);++ var seriesData = [];+ var maxValueOfContributor = 0;+ for (var i=0; i<days.length; i++) {+ if (days[i] >= fromDay && days[i] <= toDay) {+ var contribution = contributor.dailyContributions[days[i]];+ if (contribution) {+ seriesData.push(contribution);+ if (maxValueOfContributor < contribution)+ maxValueOfContributor = contribution;+ } else {+ seriesData.push(0);+ }+ }+ }++ var useKilo;+ var option = {+ grid: grid,+ xAxis: {+ type: 'category',+ data: xAxisData,+ boundaryGap: false,+ axisLabel: {+ color: darkMode?'#cdcdde':'#3F4254'+ }+ },+ yAxis: {+ minInterval: 1,+ axisLine: {+ show: false+ },+ splitLine: {+ lineStyle: {+ color: darkMode?'#535370':'#E4E6EF'+ }+ },+ boundaryGap: [0, (maxValue-maxValueOfContributor)/maxValueOfContributor],+ axisLabel: {+ formatter: function(value, index) {+ var result = onedev.server.codeContribs.formatYAxisLabel(value, index, useKilo);+ useKilo = result.useKilo;+ return result.value;+ },+ color: darkMode?'#cdcdde':'#3F4254'+ },+ },+ series: [ {+ type: 'line',+ color: "#FFA800",+ symbol: 'none',+ smooth: true,+ sampling: 'average',+ animation: false,+ areaStyle: {+ color: "#FFA800"+ },+ data: seriesData,+ } ]+ };+ chart.setOption(option);+ }++ $topContributors.empty();+ var rows = Math.trunc(topContributors.length/2);+ for (var i=0; i<rows; i++) {+ var $row = $("<div class='row'><div class='col-xl-6 left'></div><div class='col-xl-6 right'></div>");+ $topContributors.append($row);+ renderContributor($row.children(".left"), topContributors[i*2], i*2);+ renderContributor($row.children(".right"), topContributors[i*2+1], i*2+1);+ }+ if (rows*2 < topContributors.length) {+ var $row = $("<div class='row'><div class='col-md-6 left'></div></div");+ $topContributors.append($row);+ renderContributor($row.children(".left"), topContributors[rows*2], rows*2);+ }+ },+ });+ }, 10);+ }++ $topContributors.doneEvents("update", function() {+ updateTopContributors();+ });++ updateTopContributors();++ $(window).resize(function() {+ $contribs.find(".chart").each(function() {+ $(this).data("chart").resize();+ });+ });+ },+ onUserCardAvailable: function() {+ var $userCard = $("#user-card");+ $userCard.empty().append($(".user-card-content").children()).show();+ $userCard.align({placement: $userCard.data("alignment"), target: {element: $userCard.data("trigger")}});+ }+}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-stats.js b/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-stats.jsdeleted file mode 100644index d810cd29d4..0000000000--- a/server-core/src/main/java/io/onedev/server/web/page/project/stats/code/code-stats.js+++ /dev/null@@ -1,513 +0,0 @@-onedev.server.codeStats = {- formatYAxisLabel: function(value, index, useKilo) {- if (index == 0)- useKilo = false;- else if (index == 1 && value >= 1000)- useKilo = true;- return {- useKilo: useKilo,- value: useKilo? (value/1000).toFixed(1) + " k": value- }- },- formatDay: function(day) {- var localDate = JSJoda.LocalDate.ofEpochDay(day);- return localDate.year()%100 + "-" + localDate.monthValue() + "-" + localDate.dayOfMonth();- },- contribs: {- onDomReady : function(overallContributions, topContributorsDataUrl, userCardCallback, darkMode, translations) {- var $contribs = $(".code-contribs");- var $overall = $contribs.find(".overall");- if (Object.keys(overallContributions).length === 0) {- $overall.html("<div class='no-data'>" + translations.noData + "</div>");- return;- }-- var contribDays = [];-- for (var day in overallContributions)- contribDays.push(Number(day));-- contribDays.sort(function(day1, day2) {- return day1 - day2;- });-- var days = [];-- var lastDay = contribDays[contribDays.length-1];- var currentDay = contribDays[0];- while (currentDay <= lastDay) {- days.push(currentDay);- currentDay++;- }-- var fromDay = days[0];- var toDay = days[days.length-1];-- function updateDateRange() {- $contribs.find(".date-range").text(- onedev.server.codeStats.formatDay(fromDay)- + " ~ "- + onedev.server.codeStats.formatDay(toDay));- }-- var $contribType = $contribs.find(".contrib-type");- var $topContributors = $contribs.find(".top-contributors");-- var overallChart = echarts.init($overall[0]);- $overall.data("chart", overallChart);-- var overallXAxisData = [];- for (var i=0; i<days.length; i++) {- overallXAxisData.push(onedev.server.codeStats.formatDay(days[i]));- }-- function getOverallSeriesData() {- var data = [];- for (var i=0; i<days.length; i++) {- var contribution = overallContributions[days[i]];- if (contribution)- data.push(contribution[$contribType[0].selectedIndex]);- else- data.push(0);- }- return data;- }-- var grid = {- left: '80px',- right: '40px',- top: '40px',- bottom: '40px'- };-- var useKiloForOverallChart;-- var overallChartOption = {- grid: grid,- xAxis: {- type: 'category',- data: overallXAxisData,- boundaryGap: false,- axisLabel: {- color: darkMode?'#cdcdde':'#3F4254'- }- },- yAxis: {- minInterval: 1,- splitLine: {- lineStyle: {- color: darkMode?'#535370':'#E4E6EF'- }- },- axisLine: {- show: false- },- axisLabel: {- formatter: function(value, index) {- var result = onedev.server.codeStats.formatYAxisLabel(value, index, useKiloForOverallChart);- useKiloForOverallChart = result.useKilo;- return result.value;- },- color: darkMode?'#cdcdde':'#3F4254'- },- },- toolbox: {- show: false- },- brush: {- xAxisIndex: 'all',- brushLink: 'all',- outOfBrush: {- colorAlpha: 0.1- },- brushStyle: {- color: darkMode?'rgba(55, 60, 63, 0.5)':'rgba(225, 240, 255, 0.5)',- borderColor: darkMode?'rgba(54, 153, 255, 0.8)':'rgba(54, 153, 255, 0.8)'- }- },- series: [ {- type: 'line',- symbol: 'none',- smooth: true,- color: "#1BC5BD",- animation: false,- data: getOverallSeriesData(),- areaStyle: {- color: "#1BC5BD"- }- } ]- };- overallChart.setOption(overallChartOption);- overallChart.dispatchAction({- type: 'takeGlobalCursor',- key: 'brush',- brushOption: {- brushType: 'lineX',- brushMode: 'single'- }- });- overallChart.on("brush", function(params) {- if (params.areas[0]) {- var selection = params.areas[0].coordRange;- function normalizeIndex(index) {- if (index < 0)- return 0;- else if (index > days.length -1)- return days.length-1;- else- return index;- }- fromDay = days[normalizeIndex(selection[0])];- toDay = days[normalizeIndex(selection[1])];- } else {- fromDay = days[0];- toDay = days[days.length-1];- }- updateDateRange();- $topContributors.trigger("update");- });-- function updateTopContributors() {- $topContributors.empty().append("<div class='loading'></div>");- setTimeout(function() {- $.ajax({- url: topContributorsDataUrl + "&type=" + $contribType.val().toUpperCase() + "&from=" + fromDay + "&to=" + toDay,- cache: false,- beforeSend: function(xhr) {- xhr.setRequestHeader('Wicket-Ajax', 'true');- xhr.setRequestHeader('Wicket-Ajax-BaseURL', Wicket.Ajax.baseUrl || '.');- },- success: function(topContributors) {- var xAxisData = [];- for (var i=0; i<days.length; i++) {- if (days[i] >= fromDay && days[i] <= toDay)- xAxisData.push(onedev.server.codeStats.formatDay(days[i]));- }-- var maxValue = 0;- for (var i=0; i<topContributors.length; i++) {- for (var day in topContributors[i].dailyContributions) {- var value = topContributors[i].dailyContributions[day];- if (maxValue < value)- maxValue = value;- }- }-- function renderContributor($container, contributor, index) {- function createAuthorLink() {- var $link = $("<a class='user'></a>");- if (contributor.authorProfileUrl)- $link.attr("href", contributor.authorProfileUrl);- else- $link.css("cursor", "default");- return $link;- }- var $contrib = $("<div class='contrib border rounded p-3 mb-5'></div>");- $container.append($contrib);- var $head = $("<div class='head d-flex align-items-center'></div>");- $contrib.append($head);- var $left = $("<div class='mr-3 d-flex align-items-center'></div>");- $head.append($left);- var $avatarLink = createAuthorLink();- $avatarLink.addClass("mr-3");- $avatarLink.append("<img class='avatar' src='" + contributor.authorAvatarUrl + "'></img>");- $left.append($avatarLink);-- var $userInfo = $("<div></div>");- $left.append($userInfo);- var $nameDiv = $("<div class='font-weight-bold'></div>");- $nameLink = createAuthorLink();- $nameLink.append(contributor.authorName);- $nameDiv.append($nameLink);- $userInfo.append($nameDiv);-- var alignment = {targetX: 0, targetY: 0, x: 0, y: 100, offset: 8};- $left.find("a.user").hover(function() {- var $card = $("<div id='user-card' class='floating'></div>");- $card.hide();- $card.data("trigger", this);- $card.data("alignment", alignment);- $("body").append($card);- userCardCallback(contributor.authorName, contributor.authorEmailAddress);- return $card;- }, alignment);-- var $totalContribution = $("<div class='total-contribution font-size-sm'></div>");- $userInfo.append($totalContribution);- $totalContribution.append("<a href='" + contributor.commitsUrl + "' class='commits mr-2'>" + contributor.totalCommits + " " + translations.commits + "</a>");- $totalContribution.append("<span class='additions mr-2'>" + contributor.totalAdditions + " ++</span>");- $totalContribution.append("<span class='deletions'>" + contributor.totalDeletions + " --</span>");- $head.append("<div class='ml-auto font-size-h6 font-weight-bold'>#" + (index + 1) + "</div>");-- var $body = $("<div class='body chart'></div>");- $contrib.append($body);-- var chart = echarts.init($body[0]);- $body.data("chart", chart);-- var seriesData = [];- var maxValueOfContributor = 0;- for (var i=0; i<days.length; i++) {- if (days[i] >= fromDay && days[i] <= toDay) {- var contribution = contributor.dailyContributions[days[i]];- if (contribution) {- seriesData.push(contribution);- if (maxValueOfContributor < contribution)- maxValueOfContributor = contribution;- } else {- seriesData.push(0);- }- }- }-- var useKilo;- var option = {- grid: grid,- xAxis: {- type: 'category',- data: xAxisData,- boundaryGap: false,- axisLabel: {- color: darkMode?'#cdcdde':'#3F4254'- }- },- yAxis: {- minInterval: 1,- axisLine: {- show: false- },- splitLine: {- lineStyle: {- color: darkMode?'#535370':'#E4E6EF'- }- },- boundaryGap: [0, (maxValue-maxValueOfContributor)/maxValueOfContributor],- axisLabel: {- formatter: function(value, index) {- var result = onedev.server.codeStats.formatYAxisLabel(value, index, useKilo);- useKilo = result.useKilo;- return result.value;- },- color: darkMode?'#cdcdde':'#3F4254'- },- },- series: [ {- type: 'line',- color: "#FFA800",- symbol: 'none',- smooth: true,- sampling: 'average',- animation: false,- areaStyle: {- color: "#FFA800"- },- data: seriesData,- } ]- };- chart.setOption(option);- }-- $topContributors.empty();- var rows = Math.trunc(topContributors.length/2);- for (var i=0; i<rows; i++) {- var $row = $("<div class='row'><div class='col-xl-6 left'></div><div class='col-xl-6 right'></div>");- $topContributors.append($row);- renderContributor($row.children(".left"), topContributors[i*2], i*2);- renderContributor($row.children(".right"), topContributors[i*2+1], i*2+1);- }- if (rows*2 < topContributors.length) {- var $row = $("<div class='row'><div class='col-md-6 left'></div></div");- $topContributors.append($row);- renderContributor($row.children(".left"), topContributors[rows*2], rows*2);- }- },- });- }, 10);- }-- $contribType.change(function() {- overallChartOption.series[0].data = getOverallSeriesData();- overallChart.setOption(overallChartOption);- updateTopContributors();- });-- $topContributors.doneEvents("update", function() {- updateTopContributors();- });-- updateDateRange();- updateTopContributors();-- $(window).resize(function() {- $contribs.find(".chart").each(function() {- $(this).data("chart").resize();- });- });- },- onUserCardAvailable: function() {- var $userCard = $("#user-card");- $userCard.empty().append($(".user-card-content").children()).show();- $userCard.align({placement: $userCard.data("alignment"), target: {element: $userCard.data("trigger")}});- }- },-- sourceLines: {- onDomReady: function(lineIncrements, defaultBranch, darkMode, translations) {- var numOfTopLanguages = 10;-- var $chart = $(".source-lines>.chart");- if (lineIncrements.length == 0) {- $chart.append("<div class='no-data'>" + translations.noData + "</div>");- return;- }-- var languageLines = {};- var incrementDays = [];- for (var day in lineIncrements) {- delete lineIncrements[day]["@class"];- incrementDays.push(Number(day));- var incrementsOnDay = lineIncrements[day];- for (var language in incrementsOnDay) {- var increment = incrementsOnDay[language];- var dailyLinesByLanguages = languageLines[language];- if (dailyLinesByLanguages != undefined)- dailyLinesByLanguages += increment;- else- dailyLinesByLanguages = increment;- languageLines[language] = dailyLinesByLanguages;- }- }-- var languages = Object.keys(languageLines);- languages.sort(function(a, b) {- return languageLines[b] - languageLines[a];- });-- var topLanguages = languages.slice(0, numOfTopLanguages);-- var lastDay = incrementDays[incrementDays.length-1];- var currentDay = incrementDays[0];- var dailyLinesByLanguages = {};- for (var i in topLanguages)- dailyLinesByLanguages[topLanguages[i]] = [];- var xAxisData = [];- while (currentDay <= lastDay) {- var incrementsOnCurrentDay = lineIncrements[currentDay];- for (var language in dailyLinesByLanguages) {- var dailyLines = dailyLinesByLanguages[language];- var increments;- if (incrementsOnCurrentDay) {- increments = incrementsOnCurrentDay[language];- if (increments == undefined)- increments = 0;- } else {- increments = 0;- }-- if (dailyLines.length != 0)- dailyLines.push(dailyLines[dailyLines.length-1] + increments);- else- dailyLines.push(increments);- }- xAxisData.push(onedev.server.codeStats.formatDay(currentDay));- currentDay++;- }-- var chart = echarts.init($chart[0]);-- var useKilo;- var title;- if (defaultBranch != null)- title = translations.sloc.replace("{0}", defaultBranch);- else- title = translations.noDefaultBranch;- var option = {- title: {- text: title,- left: 'center',- top: 10,- textStyle: {- color: darkMode?'#cdcdde':'#3F4254'- }- },- grid: {- left: '60px',- right: '40px',- top: '120px',- bottom: '40px'- },- xAxis: {- type: 'category',- data: xAxisData,- boundaryGap: false,- axisLabel: {- color: darkMode?'#cdcdde':'#3F4254'- }- },- yAxis: {- minInterval: 1,- min: 0,- axisLine: {- show: false- },- splitLine: {- lineStyle: {- color: darkMode?'#535370':'#E4E6EF'- }- },- boundaryGap: [0, 0],- axisLabel: {- formatter: function(value, index) {- var result = onedev.server.codeStats.formatYAxisLabel(value, index, useKilo);- useKilo = result.useKilo;- return result.value;- },- color: darkMode?'#cdcdde':'#3F4254'- },- },- tooltip: {- trigger: 'axis',- textStyle: {- color: darkMode? 'white': '#535370'- },- borderColor: darkMode? '#36364F': 'white',- backgroundColor: darkMode? '#36364F': 'white'- },- legend: {- top: 40,- data: [],- textStyle: {- color: darkMode?'#cdcdde':'#3F4254'- }- },- series: []- };-- var colors = ["#53a8fd", "#19A519", "#EEAD08", "#09c112", "#ff4242", "#b00000", "#af29f8", "#ee6c1e", "#ef56cd", "#630596", "#8e4509", "#9b0f7b"];- var colorIndex = 0;- for (language in dailyLinesByLanguages) {- option.series.push({- name: language,- type: 'line',- color: colors[colorIndex],- symbol: 'none',- sampling: 'average',- smooth: true,- animation: false,- data: dailyLinesByLanguages[language],- });- option.legend.data.push({- name: language,- });-- if (++colorIndex == colors.length)- colorIndex = 0;- }- chart.setOption(option);-- $chart.on("resized", function() {- chart.resize();- });- }- }-}\ No newline at end of filediff --git a/server-core/src/main/java/io/onedev/server/xodus/CommitInfoService.java b/server-core/src/main/java/io/onedev/server/xodus/CommitInfoService.javaindex 3bbe906a0f..b3148f8af2 100644--- a/server-core/src/main/java/io/onedev/server/xodus/CommitInfoService.java+++ b/server-core/src/main/java/io/onedev/server/xodus/CommitInfoService.java@@ -8,7 +8,6 @@ import java.util.Map;import org.eclipse.jgit.lib.ObjectId;-import io.onedev.server.git.GitContribution;import io.onedev.server.git.GitContributor;import io.onedev.server.model.User;import io.onedev.server.util.NameAndEmail;@@ -40,18 +39,16 @@ public interface CommitInfoService {Collection<ObjectId> getDescendants(Long projectId, Collection<ObjectId> ancestors);void cloneInfo(Long sourceProjectId, Long targetProjectId);-- Collection<String> getHistoryPaths(Long projectId, String path);-+/*** Get overall contributions** @param projectId* project to get daily commits for* @return- * map of day to contribution+ * map of day to commit count*/- Map<Integer, GitContribution> getOverallContributions(Long projectId);+ Map<Integer, Integer> getOverallContributions(Long projectId);/*** Get list of top contributors@@ -60,33 +57,30 @@ public interface CommitInfoService {* project to get top contributors for* @param top* number of top contributors to get- * @param type- * type of contribution to order by* @param fromDay* from day* @param toDay* to day* @return- * list of top user contributors, reversely ordered by number of contributions+ * list of top user contributors, reversely ordered by number of commits*/- List<GitContributor> getTopContributors(Long projectId, int top,- GitContribution.Type type, int fromDay, int toDay);+ List<GitContributor> getTopContributors(Long projectId, int top, int fromDay, int toDay);Map<Long, Map<ObjectId, Long>> getUserCommits(User user, Date fromDate, Date toDate);/**- * Get source code line statistics over time+ * Get source code line statistics of default branch head** @param projectId* project to get line stats for* @return- * line statistics data+ * map of programming language to line count*/- Map<Integer, Map<String, Integer>> getLineIncrements(Long projectId);+ Map<String, Integer> getLineStats(Long projectId);Collection<ObjectId> getFixCommits(Long projectId, Long issueId, boolean headOnly);List<Long> sortUsersByContribution(Map<Long, Collection<EmailAddressFacade>> userEmails,Long projectId, Collection<String> files);-}\ No newline at end of file+}diff --git a/server-core/src/main/java/io/onedev/server/xodus/DefaultCommitInfoService.java b/server-core/src/main/java/io/onedev/server/xodus/DefaultCommitInfoService.javaindex cd94be7df9..e5eed876e9 100644--- a/server-core/src/main/java/io/onedev/server/xodus/DefaultCommitInfoService.java+++ b/server-core/src/main/java/io/onedev/server/xodus/DefaultCommitInfoService.java@@ -3,13 +3,13 @@ package io.onedev.server.xodus;import static io.onedev.server.util.DateUtils.toLocalDate;import static java.util.stream.Collectors.toSet;+import java.io.BufferedInputStream;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.time.ZoneId;import java.util.ArrayList;import java.util.Collection;@@ -75,7 +75,6 @@ import io.onedev.server.event.project.ActiveServerChanged;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;@@ -96,6 +95,7 @@ import io.onedev.server.service.IssueService;import io.onedev.server.service.ProjectService;import io.onedev.server.service.UserService;import io.onedev.server.util.ElementPumper;+import io.onedev.server.util.FileExtension;import io.onedev.server.util.NameAndEmail;import io.onedev.server.util.Pair;import io.onedev.server.util.ProgrammingLanguageDetector;@@ -120,14 +120,12 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceprivate static final Logger logger = LoggerFactory.getLogger(DefaultCommitInfoService.class);- private static final int INFO_VERSION = 19;+ private static final int INFO_VERSION = 22;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";@@ -140,8 +138,6 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceprivate 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";@@ -241,7 +237,6 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceStore defaultStore = getStore(env, DEFAULT_STORE);Store commitsStore = getStore(env, COMMITS_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);Store userToIndexStore = getStore(env, USER_TO_INDEX_STORE);@@ -311,7 +306,6 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServicevar options = new RevListOptions().revisions(revisions);EnumSet<LogCommand.Field> fields = EnumSet.allOf(LogCommand.Field.class);- fields.remove(LogCommand.Field.LINE_CHANGES);new LogCommand(projectService.getGitDir(project.getId())) {@Override@@ -430,43 +424,6 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService}}}-- for (FileChange change : currentCommit.getFileChanges()) {- if (change.getOldPath() != null && change.getNewPath() != null- && !change.getOldPath().equals(change.getNewPath())) {- int pathIndex = getPathIndex(pathToIndexStore, indexToPathStore, txn,- nextIndex, change.getNewPath());- ByteIterable pathKey = new IntByteIterable(pathIndex);- Set<Integer> historyPathIndexes = new HashSet<>();- byte[] bytesOfHistoryPaths = readBytes(historyPathsStore, txn, pathKey);- if (bytesOfHistoryPaths == null) {- bytesOfHistoryPaths = new byte[0];- int pos = 0;- for (int i = 0; i < bytesOfHistoryPaths.length / Integer.SIZE; i++) {- historyPathIndexes.add(ByteBuffer.wrap(bytesOfHistoryPaths, pos, Integer.SIZE).getInt());- pos += Integer.SIZE;- }- } else {- historyPathIndexes = new HashSet<>();- }- if (historyPathIndexes.size() < MAX_HISTORY_PATHS) {- 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,- newBytesOfHistoryPaths, 0, bytesOfHistoryPaths.length);- ByteBuffer buffer = ByteBuffer.wrap(newBytesOfHistoryPaths,- bytesOfHistoryPaths.length, Integer.BYTES);- buffer.putInt(oldPathIndex);- historyPathsStore.put(txn, pathKey,- new ArrayByteIterable(newBytesOfHistoryPaths));- }- }- }- }}}@@ -493,9 +450,9 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServicevar defaultBranch = project.getDefaultBranch();if (defaultBranch != null && GitUtils.branch2ref(defaultBranch).equals(refName)) {- collectLineStats(project, commitId);- collectContributions(project, commitId);collectFiles(project, commitId);+ collectLineStats(project, commitId);+ collectContributions(project, commitId);}logger.debug("Collected commit information (project: {}, ref: {})", project.getPath(), refName);@@ -509,7 +466,6 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceStore userCommitsStore = getStore(env, USER_COMMITS_STORE);Repository repository = projectService.getRepository(project.getId());- PatternSet filePatterns = PatternSet.parse(project.findCodeAnalysisFiles());ObjectId lastCommitId = env.computeInTransaction(txn -> {ObjectId innerLastCommitId;@@ -529,10 +485,10 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService});processCommitRange(project, commitId, lastCommitId, (untilCommitId, sinceCommitId) -> env.executeInTransaction(txn -> {- Map<Integer, GitContribution> overallContributions =+ Map<Integer, Integer> overallContributions =deserializeDailyContributions(readBytes(defaultStore, txn, OVERALL_CONTRIBUTIONS_KEY));- Map<Integer, Map<Integer, GitContribution>> dailyContributionsCache = new HashMap<>();+ Map<Integer, Map<Integer, Integer>> dailyContributionsCache = new HashMap<>();Map<String, Map<ObjectId, Long>> userCommitsCache = new HashMap<>();@@ -551,8 +507,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceEnumSet<LogCommand.Field> fields = EnumSet.of(LogCommand.Field.AUTHOR,LogCommand.Field.COMMIT_DATE,- LogCommand.Field.PARENTS,- LogCommand.Field.LINE_CHANGES);+ LogCommand.Field.PARENTS);new LogCommand(projectService.getGitDir(project.getId())) {@@ -568,7 +523,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServicepublic void process(LogCommit currentCommit) {if (currentCommit.getCommitDate() != null && currentCommit.getParentHashes().size() <= 1) {int day = (int) toLocalDate(currentCommit.getCommitDate(), ZoneId.systemDefault()).toEpochDay();- updateContrib(overallContributions, day, currentCommit, filePatterns);+ updateContrib(overallContributions, day);if (currentCommit.getAuthor() != null) {NameAndEmail author = new NameAndEmail(currentCommit.getAuthor());@@ -576,13 +531,13 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceint userIndex = readInt(userToIndexStore, txn, authorKey, -1);Preconditions.checkState(userIndex != -1);- Map<Integer, GitContribution> contribsOnDay = dailyContributionsCache.get(day);+ Map<Integer, Integer> contribsOnDay = dailyContributionsCache.get(day);if (contribsOnDay == null) {contribsOnDay = deserializeDailyContributions(readBytes(dailyContributionsStore, txn, new IntByteIterable(day)));dailyContributionsCache.put(day, contribsOnDay);}- updateContrib(contribsOnDay, userIndex, currentCommit, filePatterns);+ updateContrib(contribsOnDay, userIndex);var userCommits = userCommitsCache.get(author.getEmailAddress());if (userCommits == null) {@@ -596,7 +551,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService}.pump();- for (Map.Entry<Integer, Map<Integer, GitContribution>> entry : dailyContributionsCache.entrySet()) {+ for (Map.Entry<Integer, Map<Integer, Integer>> entry : dailyContributionsCache.entrySet()) {byte[] bytesOfContributionsOnDay = serializeDailyContributions(entry.getValue());dailyContributionsStore.put(txn, new IntByteIterable(entry.getKey()),new ArrayByteIterable(bytesOfContributionsOnDay));@@ -692,7 +647,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceObjectId lastCommitId = env.computeInTransaction(txn -> {byte[] lastCommitBytes = readBytes(defaultStore, txn, LAST_COMMIT_OF_LINE_STATS_KEY);- if (lastCommitBytes != null) {+ if (lastCommitBytes != null && readBytes(defaultStore, txn, LINE_STATS_KEY) != null) {try {ObjectId innerLastCommitId = ObjectId.fromRaw(lastCommitBytes);if (repository.getObjectDatabase().has(innerLastCommitId)@@ -708,38 +663,21 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServicePatternSet filePatterns = PatternSet.parse(project.findCodeAnalysisFiles());if (lastCommitId == null) {- env.executeInTransaction(txn -> {- Map<Integer, Map<String, Integer>> lineStats = new HashMap<>();-- new ElementPumper<LogCommit>() {-- @Override- public void generate(Consumer<LogCommit> consumer) {- List<String> revisions = new ArrayList<>();- revisions.add(commitId.name());-- EnumSet<LogCommand.Field> fields = EnumSet.of(- LogCommand.Field.COMMIT_DATE,- LogCommand.Field.LINE_CHANGES);-- var options = new RevListOptions().revisions(revisions).firstParent(true);- new LogCommand(projectService.getGitDir(project.getId())) {-- @Override- protected void consume(LogCommit commit) {- consumer.accept(commit);- }-- }.options(options).noRenames(true).fields(fields).run();- }-- @Override- public void process(LogCommit currentCommit) {- updateLineStats(txn, currentCommit, lineStats, filePatterns);+ Map<String, Integer> lineStats = new HashMap<>();+ for (String path : GitUtils.getBlobPaths(repository, commitId)) {+ String language = getLanguage(path, filePatterns);+ if (language != null) {+ try (InputStream input = GitUtils.getInputStream(repository, commitId, path)) {+ int lines = countLines(input);+ if (lines > 0)+ lineStats.merge(language, lines, Integer::sum);+ } catch (IOException e) {+ throw new RuntimeException(e);}+ }+ }- }.pump();-+ env.executeInTransaction(txn -> {byte[] bytesOfLineStats = SerializationUtils.serialize((Serializable) lineStats);defaultStore.put(txn, LINE_STATS_KEY, new ArrayByteIterable(bytesOfLineStats));@@ -747,7 +685,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService});} else {env.executeInTransaction(txn -> {- Map<Integer, Map<String, Integer>> lineStats;+ Map<String, Integer> lineStats;byte[] bytesOfLineStats = readBytes(defaultStore, txn, LINE_STATS_KEY);if (bytesOfLineStats != null)lineStats = SerializationUtils.deserialize(bytesOfLineStats);@@ -757,12 +695,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceListNumStatsCommand command = new ListNumStatsCommand(projectService.getGitDir(project.getId()),lastCommitId.name(), commitId.name(), true);- List<FileChange> fileChanges = command.run();- RevCommit revCommit = project.getRevCommit(commitId, true);- LogCommit gitCommit = new LogCommit(revCommit.name(), null, null, revCommit.getAuthorIdent(),- revCommit.getCommitterIdent().getWhen(), null, null, fileChanges);-- updateLineStats(txn, gitCommit, lineStats, filePatterns);+ updateLineStats(lineStats, command.run(), filePatterns);bytesOfLineStats = SerializationUtils.serialize((Serializable) lineStats);defaultStore.put(txn, LINE_STATS_KEY, new ArrayByteIterable(bytesOfLineStats));@@ -827,40 +760,54 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService}}- private void updateLineStats(Transaction txn, LogCommit currentCommit, Map<Integer, Map<String, Integer>> lineStats,+ static void updateLineStats(Map<String, Integer> lineStats, Collection<FileChange> fileChanges,PatternSet filePatterns) {- int day = (int) toLocalDate(currentCommit.getCommitDate(), ZoneId.systemDefault()).toEpochDay();-- Map<String, Integer> lineStatsOnDay = lineStats.get(day);- if (lineStatsOnDay == null) {- lineStatsOnDay = new HashMap<>();- lineStats.put(day, lineStatsOnDay);- }-- Map<String, Integer> languageLines = new HashMap<>();- for (FileChange change : currentCommit.getFileChanges()) {+ for (FileChange change : fileChanges) {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)- lines += accumulatedLines;- languageLines.put(language, lines);+ int updatedLines = lineStats.getOrDefault(language, 0) + lines;+ if (updatedLines != 0)+ lineStats.put(language, updatedLines);+ else+ lineStats.remove(language);}}}}+ }- for (Map.Entry<String, Integer> entry : languageLines.entrySet()) {- String language = entry.getKey();- Integer lines = entry.getValue();- Integer accumulatedLines = lineStatsOnDay.get(language);- if (accumulatedLines != null)- lines += accumulatedLines;- lineStatsOnDay.put(language, lines);+ @Nullable+ private String getLanguage(String path, PatternSet filePatterns) {+ if (new FileChange(null, path, 0, 0).matches(filePatterns)) {+ String extension = FileExtension.getExtension(path);+ if (StringUtils.isNotBlank(extension))+ return ProgrammingLanguageDetector.getLanguageForExtension(extension);}+ return null;+ }++ static int countLines(InputStream input) throws IOException {+ int lines = 0;+ int lastByte = -1;+ try (var bufferedInput = new BufferedInputStream(input)) {+ byte[] buffer = new byte[8192];+ int bytesRead;+ while ((bytesRead = bufferedInput.read(buffer)) != -1) {+ for (int i = 0; i < bytesRead; i++) {+ if (buffer[i] == 0)+ return -1;+ if (buffer[i] == '\n')+ lines++;+ }+ lastByte = buffer[bytesRead - 1];+ }+ }+ if (lastByte != -1 && lastByte != '\n')+ lines++;+ return lines;}private int getPathIndex(Store pathToIndexStore, Store indexToPathStore, Transaction txn,@@ -946,26 +893,22 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService}@Override- public Map<Integer, Map<String, Integer>> getLineIncrements(Long projectId) {+ public Map<String, Integer> getLineStats(Long projectId) {return projectService.runOnActiveServer(projectId, new ClusterTask<>() {private static final long serialVersionUID = 1L;@Override- public Map<Integer, Map<String, Integer>> call() throws Exception {+ public Map<String, Integer> call() throws Exception {Environment env = getEnv(projectId.toString());Store store = getStore(env, DEFAULT_STORE);return env.computeInReadonlyTransaction(txn -> {- Map<Integer, Map<String, Integer>> lineIncrements = new HashMap<>();+ Map<String, Integer> lineStats = new HashMap<>();byte[] bytes = readBytes(store, txn, LINE_STATS_KEY);- if (bytes != null) {- @SuppressWarnings("unchecked")- var storedMap = (Map<Integer, Map<String, Integer>>) SerializationUtils.deserialize(bytes);- for (var entry : storedMap.entrySet())- lineIncrements.put(entry.getKey(), entry.getValue());- }- return lineIncrements;+ if (bytes != null)+ lineStats.putAll(SerializationUtils.deserialize(bytes));+ return lineStats;});}@@ -973,19 +916,8 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService}- private void updateContrib(Map<Integer, GitContribution> contributions, int key, LogCommit 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));- } else {- contribution = new GitContribution(- 1, commit.getAdditions(filePatterns), commit.getDeletions(filePatterns));- }- contributions.put(key, contribution);+ private void updateContrib(Map<Integer, Integer> contributions, int key) {+ contributions.put(key, contributions.getOrDefault(key, 0) + 1);}private int getCommitCount(Long projectId, Collection<EmailAddressFacade> emailAddresses,@@ -1299,87 +1231,19 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService@Sessional@Override- public Collection<String> getHistoryPaths(Long projectId, String path) {+ public Map<Integer, Integer> getOverallContributions(Long projectId) {return projectService.runOnActiveServer(projectId, new ClusterTask<>() {private static final long serialVersionUID = 1L;@Override- public Collection<String> call() {- Environment env = getEnv(projectId.toString());- Store 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<>() {-- private Collection<String> getPaths(Transaction txn, Set<Integer> pathIndexes) {- Set<String> paths = new HashSet<>();- 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;- }-- @Override- public Collection<String> compute(Transaction txn) {- int pathIndex = readInt(pathToIndexStore, txn, new StringByteIterable(path), -1);- if (pathIndex != -1) {- Set<Integer> pathIndexes = new HashSet<>();- pathIndexes.add(pathIndex);- while (true) {- Set<Integer> newPathIndexes = new HashSet<>(pathIndexes);- 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++) {- newPathIndexes.add(ByteBuffer.wrap(bytesOfHistoryPaths, pos, Integer.BYTES).getInt());- if (newPathIndexes.size() == MAX_HISTORY_PATHS)- return getPaths(txn, newPathIndexes);- pos += Integer.BYTES;- }- }- }- if (pathIndexes.equals(newPathIndexes))- break;- else- pathIndexes = newPathIndexes;- }- return getPaths(txn, pathIndexes);- } else {- return new HashSet<>();- }- }- });- }-- });-- }-- @Sessional- @Override- public Map<Integer, GitContribution> getOverallContributions(Long projectId) {- return projectService.runOnActiveServer(projectId, new ClusterTask<>() {-- private static final long serialVersionUID = 1L;-- @Override- public Map<Integer, GitContribution> call() {+ public Map<Integer, Integer> call() {Environment env = getEnv(projectId.toString());Store store = getStore(env, DEFAULT_STORE);return env.computeInReadonlyTransaction(txn -> {- Map<Integer, GitContribution> overallContributions = new HashMap<>();- for (Map.Entry<Integer, GitContribution> entry :- deserializeDailyContributions(readBytes(store, txn, OVERALL_CONTRIBUTIONS_KEY)).entrySet()) {- overallContributions.put(entry.getKey(), entry.getValue());- }- return overallContributions;+ return new HashMap<>(deserializeDailyContributions(+ readBytes(store, txn, OVERALL_CONTRIBUTIONS_KEY)));});}@@ -1389,8 +1253,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService@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, int fromDay, int toDay) {return projectService.runOnActiveServer(projectId, new ClusterTask<>() {private static final long serialVersionUID = 1L;@@ -1437,45 +1300,30 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService@Overridepublic List<GitContributor> compute(Transaction txn) {- Map<Integer, GitContribution> overallContributions =+ Map<Integer, Integer> overallContributions =deserializeDailyContributions(readBytes(defaultStore, txn, OVERALL_CONTRIBUTIONS_KEY));- Map<NameAndEmail, GitContribution> totalContributions = new HashMap<>();+ Map<NameAndEmail, Integer> totalContributions = new HashMap<>();Map<Integer, Optional<NameAndEmail>> users = new HashMap<>();- Map<Integer, Map<Integer, GitContribution>> contribsByDay = new LinkedHashMap<>();+ Map<Integer, Map<Integer, Integer>> contribsByDay = new LinkedHashMap<>();for (int dayValue : overallContributions.keySet()) {if (dayValue >= fromDay && dayValue <= toDay) {ByteIterable dayKey = new IntByteIterable(dayValue);- Map<Integer, GitContribution> contribsOnDay =+ Map<Integer, Integer> contribsOnDay =deserializeDailyContributions(readBytes(dailyContributionsStore, txn, dayKey));contribsByDay.put(dayValue, contribsOnDay);- for (Map.Entry<Integer, GitContribution> entry : contribsOnDay.entrySet()) {+ for (Map.Entry<Integer, Integer> entry : contribsOnDay.entrySet()) {NameAndEmail user = getUser(txn, users, entry.getKey());if (user != null) {- GitContribution totalContrib = totalContributions.get(user);- if (totalContrib == null) {- totalContrib = entry.getValue();- } else {- totalContrib = new GitContribution(- totalContrib.getCommits() + entry.getValue().getCommits(),- totalContrib.getAdditions() + entry.getValue().getAdditions(),- totalContrib.getDeletions() + entry.getValue().getDeletions());- }- totalContributions.put(user, totalContrib);+ totalContributions.put(user,+ totalContributions.getOrDefault(user, 0) + entry.getValue());}}}}List<NameAndEmail> topUsers = new ArrayList<>(totalContributions.keySet());- topUsers.sort((o1, o2) -> {- if (type == GitContribution.Type.COMMITS)- return totalContributions.get(o2).getCommits() - totalContributions.get(o1).getCommits();- else if (type == GitContribution.Type.ADDITIONS)- return totalContributions.get(o2).getAdditions() - totalContributions.get(o1).getAdditions();- else- return totalContributions.get(o2).getDeletions() - totalContributions.get(o1).getDeletions();- });+ topUsers.sort((o1, o2) -> totalContributions.get(o2) - totalContributions.get(o1));if (top < topUsers.size())topUsers = topUsers.subList(0, top);@@ -1484,8 +1332,8 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServiceMap<NameAndEmail, Map<Integer, Integer>> userContributions = new HashMap<>();- for (Map.Entry<Integer, Map<Integer, GitContribution>> dayEntry : contribsByDay.entrySet()) {- for (Map.Entry<Integer, GitContribution> userEntry : dayEntry.getValue().entrySet()) {+ for (Map.Entry<Integer, Map<Integer, Integer>> dayEntry : contribsByDay.entrySet()) {+ for (Map.Entry<Integer, Integer> userEntry : dayEntry.getValue().entrySet()) {NameAndEmail user = getUser(txn, users, userEntry.getKey());if (user != null && topUserSet.contains(user)) {Map<Integer, Integer> contribsOfUser = userContributions.get(user);@@ -1493,12 +1341,7 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServicecontribsOfUser = new HashMap<>();userContributions.put(user, contribsOfUser);}- if (type == GitContribution.Type.COMMITS)- contribsOfUser.put(dayEntry.getKey(), userEntry.getValue().getCommits());- else if (type == GitContribution.Type.ADDITIONS)- contribsOfUser.put(dayEntry.getKey(), userEntry.getValue().getAdditions());- else- contribsOfUser.put(dayEntry.getKey(), userEntry.getValue().getDeletions());+ contribsOfUser.put(dayEntry.getKey(), userEntry.getValue());}}}@@ -1574,20 +1417,16 @@ public class DefaultCommitInfoService extends AbstractEnvironmentServicereturn userCommits;}- private Map<Integer, GitContribution> deserializeDailyContributions(byte[] bytes) {+ private Map<Integer, Integer> deserializeDailyContributions(byte[] bytes) {if (bytes != null) {- Map<Integer, GitContribution> contributions = new HashMap<>();+ Map<Integer, Integer> contributions = new HashMap<>();int pos = 0;- for (int i = 0; i < bytes.length / 4 / Integer.BYTES; i++) {+ for (int i = 0; i < bytes.length / 2 / Integer.BYTES; i++) {int key = ByteBuffer.wrap(bytes, pos, Integer.BYTES).getInt();pos += Integer.BYTES;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();- pos += Integer.BYTES;- contributions.put(key, new GitContribution(commits, additions, deletions));+ contributions.put(key, commits);}return contributions;} else {@@ -1612,22 +1451,16 @@ public class DefaultCommitInfoService extends AbstractEnvironmentService}}- private byte[] serializeDailyContributions(Map<Integer, GitContribution> dailyContributions) {- byte[] bytes = new byte[dailyContributions.size() * Integer.BYTES * 4];+ private byte[] serializeDailyContributions(Map<Integer, Integer> dailyContributions) {+ byte[] bytes = new byte[dailyContributions.size() * Integer.BYTES * 2];int pos = 0;- for (Map.Entry<Integer, GitContribution> entry : dailyContributions.entrySet()) {+ for (Map.Entry<Integer, Integer> entry : dailyContributions.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();+ byte[] commitsBytes = ByteBuffer.allocate(Integer.BYTES).putInt(entry.getValue()).array();System.arraycopy(commitsBytes, 0, bytes, pos, Integer.BYTES);pos += Integer.BYTES;- byte[] additionsBytes = ByteBuffer.allocate(Integer.BYTES).putInt(entry.getValue().getAdditions()).array();- System.arraycopy(additionsBytes, 0, bytes, pos, Integer.BYTES);- pos += Integer.BYTES;- byte[] deletionsBytes = ByteBuffer.allocate(Integer.BYTES).putInt(entry.getValue().getDeletions()).array();- System.arraycopy(deletionsBytes, 0, bytes, pos, Integer.BYTES);- pos += Integer.BYTES;}return bytes;}diff --git a/server-core/src/test/java/io/onedev/server/git/command/LogCommandTest.java b/server-core/src/test/java/io/onedev/server/git/command/LogCommandTest.javaindex ca2ec358c7..4efb4339fd 100644--- a/server-core/src/test/java/io/onedev/server/git/command/LogCommandTest.java+++ b/server-core/src/test/java/io/onedev/server/git/command/LogCommandTest.java@@ -71,7 +71,6 @@ public class LogCommandTest extends AbstractGitTest {var options = new RevListOptions().revisions(newArrayList("main"));EnumSet<LogCommand.Field> fields = EnumSet.allOf(LogCommand.Field.class);- fields.remove(LogCommand.Field.LINE_CHANGES);new LogCommand(git.getRepository().getDirectory()) {@Overridediff --git a/server-core/src/test/java/io/onedev/server/xodus/DefaultCommitInfoServiceTest.java b/server-core/src/test/java/io/onedev/server/xodus/DefaultCommitInfoServiceTest.javanew file mode 100644index 0000000000..903076f06b--- /dev/null+++ b/server-core/src/test/java/io/onedev/server/xodus/DefaultCommitInfoServiceTest.java@@ -0,0 +1,49 @@+package io.onedev.server.xodus;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertFalse;++import java.io.ByteArrayInputStream;+import java.nio.charset.StandardCharsets;+import java.util.HashMap;+import java.util.List;++import org.junit.Test;++import io.onedev.server.git.command.FileChange;+import io.onedev.server.util.patternset.PatternSet;++public class DefaultCommitInfoServiceTest {++ @Test+ public void shouldCountTextLinesAndIgnoreBinaryContent() throws Exception {+ assertEquals(0, countLines(""));+ assertEquals(1, countLines("first"));+ assertEquals(1, countLines("first\n"));+ assertEquals(2, countLines("first\nsecond"));+ assertEquals(-1, DefaultCommitInfoService.countLines(+ new ByteArrayInputStream(new byte[] {'a', 0, 'b'})));+ }++ @Test+ public void shouldApplyLineChangesToLatestStats() {+ var lineStats = new HashMap<String, Integer>();+ lineStats.put("Java", 10);+ lineStats.put("Python", 3);++ DefaultCommitInfoService.updateLineStats(lineStats, List.of(+ new FileChange(null, "src/Main.java", 5, 2),+ new FileChange(null, "src/old.py", 0, 3),+ new FileChange(null, "README.txt", 20, 0)), PatternSet.parse("**"));++ assertEquals(13, lineStats.get("Java").intValue());+ assertFalse(lineStats.containsKey("Python"));+ assertEquals(1, lineStats.size());+ }++ private int countLines(String content) throws Exception {+ return DefaultCommitInfoService.countLines(+ new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));+ }++}