mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
fix(git): count changed file paths with spaces in code activity stats (#40569)
Git's `--numstat` output is tab-separated, but the code activity parser split each line on whitespace. Two changed files whose names share a first word, such as `docs/release notes.md` and `docs/release plan.md`, were deduplicated into one entry and undercounted on the activity page. Parse the line by its tab separators so the full path is preserved. The contributors graph had a similar parser bug: an empty commit made it drop the following commit, and an empty tip commit was skipped. Both parsers now use NUL-prefixed separators that can't collide with commit metadata. Assisted-by: Claude Code:claude-opus-5-5 --------- Co-authored-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
4 files changed
+160
-159
No files matched your search
+89
-98
@@ -5,8 +5,8 @@ package git
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// CodeActivityStats represents git statistics data
|
||||
@@ -35,124 +36,114 @@ type CodeActivityAuthor struct {
|
||||
}
|
||||
|
||||
// GetCodeActivityStats returns code statistics for activity page
|
||||
func (repo *Repository) GetCodeActivityStats(ctx context.Context, fromTime time.Time, branch string) (*CodeActivityStats, error) {
|
||||
stats := &CodeActivityStats{}
|
||||
|
||||
since := fromTime.Format(time.RFC3339)
|
||||
|
||||
func (repo *Repository) GetCodeActivityStats(ctx context.Context, fromTime time.Time, branchName string) (*CodeActivityStats, error) {
|
||||
stdout, _, runErr := gitcmd.NewCommand("rev-list", "--count", "--no-merges", "--branches=*", "--date=iso").
|
||||
AddOptionFormat("--since=%s", since).
|
||||
AddOptionFormat("--since=%s", fromTime.Format(time.RFC3339)).
|
||||
WithRepo(repo).
|
||||
RunStdString(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
}
|
||||
|
||||
c, err := strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
|
||||
commitCountInAllBranches, err := strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stats.CommitCountInAllBranches = c
|
||||
|
||||
gitCmd := gitcmd.NewCommand("log", "--numstat", "--no-merges", "--pretty=format:---%n%h%n%aN%n%aE%n", "--date=iso").
|
||||
AddOptionFormat("--since=%s", since)
|
||||
if len(branch) == 0 {
|
||||
gitCmd.AddArguments("--branches=*")
|
||||
} else {
|
||||
gitCmd.AddArguments("--first-parent").AddDynamicArguments(branch)
|
||||
}
|
||||
if err := parseCodeActivityLog(ctx, repo, gitCmd, stats); err != nil {
|
||||
cmd := prepareCodeActivityLogCmd(fromTime, branchName).AddArguments("--numstat").WithRepo(repo)
|
||||
stats, err := parseCodeActivityLog(ctx, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
stats.CommitCountInAllBranches = commitCountInAllBranches
|
||||
return &stats, nil
|
||||
}
|
||||
|
||||
// GetCodeActivityAuthors returns the authors of non-merge commits in all branches since fromTime, sorted by commit count
|
||||
func GetCodeActivityAuthors(ctx context.Context, repo RepositoryFacade, fromTime time.Time) ([]*CodeActivityAuthor, error) {
|
||||
stats := &CodeActivityStats{}
|
||||
gitCmd := gitcmd.NewCommand("log", "--no-merges", "--pretty=format:---%n%H%n%aN%n%aE%n", "--branches=*").
|
||||
AddOptionFormat("--since=%s", fromTime.Format(time.RFC3339))
|
||||
if err := parseCodeActivityLog(ctx, repo, gitCmd, stats); err != nil {
|
||||
cmd := prepareCodeActivityLogCmd(fromTime, "").WithRepo(repo)
|
||||
stats, err := parseCodeActivityLog(ctx, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stats.Authors, nil
|
||||
}
|
||||
|
||||
func parseCodeActivityLog(ctx context.Context, repo RepositoryFacade, gitCmd *gitcmd.Command, stats *CodeActivityStats) error {
|
||||
stdoutReader, stdoutReaderClose := gitCmd.MakeStdoutPipe()
|
||||
defer stdoutReaderClose()
|
||||
err := gitCmd.
|
||||
WithRepo(repo).
|
||||
WithPipelineFunc(func(ctx gitcmd.Context) error {
|
||||
scanner := bufio.NewScanner(stdoutReader)
|
||||
scanner.Split(bufio.ScanLines)
|
||||
stats.CommitCount = 0
|
||||
stats.Additions = 0
|
||||
stats.Deletions = 0
|
||||
authors := make(map[string]*CodeActivityAuthor)
|
||||
files := make(container.Set[string])
|
||||
var author string
|
||||
p := 0
|
||||
for scanner.Scan() {
|
||||
l := strings.TrimSpace(scanner.Text())
|
||||
if l == "---" {
|
||||
p = 1
|
||||
} else if p == 0 {
|
||||
continue
|
||||
} else {
|
||||
p++
|
||||
}
|
||||
if p > 4 && len(l) == 0 {
|
||||
continue
|
||||
}
|
||||
switch p {
|
||||
case 1: // Separator
|
||||
case 2: // Commit sha-1
|
||||
stats.CommitCount++
|
||||
case 3: // Author
|
||||
author = l
|
||||
case 4: // E-mail
|
||||
email := strings.ToLower(l)
|
||||
if _, ok := authors[email]; !ok {
|
||||
authors[email] = &CodeActivityAuthor{Name: author, Email: email, Commits: 0}
|
||||
}
|
||||
authors[email].Commits++
|
||||
default: // Changed file
|
||||
if parts := strings.Fields(l); len(parts) >= 3 {
|
||||
if parts[0] != "-" {
|
||||
if c, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64); err == nil {
|
||||
stats.Additions += c
|
||||
}
|
||||
}
|
||||
if parts[1] != "-" {
|
||||
if c, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64); err == nil {
|
||||
stats.Deletions += c
|
||||
}
|
||||
}
|
||||
files.Add(parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("parseCodeActivityLog scan: %w", err)
|
||||
}
|
||||
a := make([]*CodeActivityAuthor, 0, len(authors))
|
||||
for _, v := range authors {
|
||||
a = append(a, v)
|
||||
}
|
||||
// Sort authors descending depending on commit count
|
||||
sort.Slice(a, func(i, j int) bool {
|
||||
return a[i].Commits > a[j].Commits
|
||||
})
|
||||
stats.AuthorCount = int64(len(authors))
|
||||
stats.ChangedFiles = int64(len(files))
|
||||
stats.Authors = a
|
||||
return nil
|
||||
}).
|
||||
RunWithStderr(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parseCodeActivityLog: %w", err)
|
||||
const (
|
||||
gitLogSepFormat = "%x00---" // should not conflict with any line of our git log output
|
||||
gitLogSepString = "\x00---"
|
||||
)
|
||||
|
||||
func prepareCodeActivityLogCmd(fromTime time.Time, branchName string) *gitcmd.Command {
|
||||
cmd := gitcmd.NewCommand("log", "--no-merges", "--pretty=format:"+gitLogSepFormat+"%n%H%n%aN%n%aE%n", "--date=iso").
|
||||
AddOptionFormat("--since=%s", fromTime.Format(time.RFC3339))
|
||||
if branchName == "" {
|
||||
cmd.AddArguments("--branches=*")
|
||||
} else {
|
||||
cmd.AddArguments("--first-parent").AddDynamicArguments(branchName)
|
||||
}
|
||||
return nil
|
||||
return cmd
|
||||
}
|
||||
|
||||
func parseCodeActivityLog(ctx context.Context, gitCmd *gitcmd.Command) (stats CodeActivityStats, _ error) {
|
||||
authors := make(map[string]*CodeActivityAuthor)
|
||||
files := make(container.Set[string])
|
||||
|
||||
// output format, see "man git-log" for details:
|
||||
//
|
||||
// \x00---
|
||||
// 1234567890
|
||||
// user-a
|
||||
// email-a@example.com
|
||||
//
|
||||
// 1<TAB>0<TAB>README.md
|
||||
// ...
|
||||
|
||||
author := ""
|
||||
subIdx := 0
|
||||
err := gitcmd.RunWithScannerSplit(ctx, gitCmd, bufio.ScanLines, func(ctx gitcmd.Context, line []byte) error {
|
||||
if bytes.Equal(line, []byte(gitLogSepString)) {
|
||||
subIdx = 1
|
||||
return nil
|
||||
} else if subIdx == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
subIdx++
|
||||
switch subIdx {
|
||||
case 2: // Commit ID
|
||||
stats.CommitCount++
|
||||
case 3: // Author
|
||||
author = strings.TrimSpace(string(line))
|
||||
case 4: // E-mail
|
||||
email := strings.ToLower(strings.TrimSpace(string(line)))
|
||||
if _, ok := authors[email]; !ok {
|
||||
authors[email] = &CodeActivityAuthor{Name: author, Email: email, Commits: 0}
|
||||
}
|
||||
authors[email].Commits++
|
||||
default: // Changed files
|
||||
parts := bytes.SplitN(line, []byte{'\t'}, 3)
|
||||
if len(parts) != 3 {
|
||||
return nil
|
||||
}
|
||||
if add, _ := strconv.ParseInt(string(parts[0]), 10, 64); add > 0 {
|
||||
stats.Additions += add
|
||||
}
|
||||
if del, _ := strconv.ParseInt(string(parts[1]), 10, 64); del > 0 {
|
||||
stats.Deletions += del
|
||||
}
|
||||
files.Add(string(parts[2]))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.Authors = util.ValuesOfMap(authors)
|
||||
// Sort authors descending depending on commit count
|
||||
sort.Slice(stats.Authors, func(i, j int) bool { return stats.Authors[i].Commits > stats.Authors[j].Commits })
|
||||
stats.AuthorCount = int64(len(authors))
|
||||
stats.ChangedFiles = int64(len(files))
|
||||
return stats, nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRepository_GetCodeActivityStats(t *testing.T) {
|
||||
@@ -38,3 +39,18 @@ func TestRepository_GetCodeActivityStats(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, code.Authors, authors)
|
||||
}
|
||||
|
||||
func TestRepository_GetCodeActivityStatsPathWithSpaces(t *testing.T) {
|
||||
repoFacade, err := ForceFastImportWithInit(t.Context(), t.TempDir(), []FastImportCommit{{
|
||||
Ref: "refs/heads/master",
|
||||
Files: []FastImportFile{{Path: "docs/release notes.md"}, {Path: "docs/release plan.md"}},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
repo, err := OpenRepository(t.Context(), repoFacade)
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
code, err := repo.GetCodeActivityStats(t.Context(), time.Unix(0, 0), "")
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 2, code.ChangedFiles)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ package repository
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -20,7 +21,6 @@ import (
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/log"
|
||||
api "gitea.dev/modules/structs"
|
||||
)
|
||||
|
||||
@@ -114,70 +114,42 @@ func getExtendedCommitStats(ctx context.Context, repo *git.Repository, revision
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gitCmd := gitcmd.NewCommand("log", "--shortstat", "--no-merges", "--pretty=format:---%n%aN%n%aE%n%as", "--reverse")
|
||||
// each commit is a "\x00name\x00email\x00date" line, followed by a shortstat line unless the commit is empty
|
||||
gitCmd := gitcmd.NewCommand("log", "--shortstat", "--no-merges", "--pretty=format:%x00%aN%x00%aE%x00%as", "--reverse")
|
||||
// AddOptionFormat("--max-count=%d", limit)
|
||||
gitCmd.AddDynamicArguments(baseCommit.ID.String())
|
||||
|
||||
stdoutReader, stdoutReaderClose := gitCmd.MakeStdoutPipe()
|
||||
defer stdoutReaderClose()
|
||||
gitCmd.AddDynamicArguments(baseCommit.ID.String()).WithRepo(repo)
|
||||
|
||||
var extendedCommitStats []*ExtendedCommitStats
|
||||
err = gitCmd.WithRepo(repo).
|
||||
WithPipelineFunc(func(ctx gitcmd.Context) error {
|
||||
scanner := bufio.NewScanner(stdoutReader)
|
||||
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line != "---" {
|
||||
continue
|
||||
}
|
||||
scanner.Scan()
|
||||
authorName := strings.TrimSpace(scanner.Text())
|
||||
scanner.Scan()
|
||||
authorEmail := strings.TrimSpace(scanner.Text())
|
||||
scanner.Scan()
|
||||
date := strings.TrimSpace(scanner.Text())
|
||||
scanner.Scan()
|
||||
stats := strings.TrimSpace(scanner.Text())
|
||||
if authorName == "" || authorEmail == "" || date == "" || stats == "" {
|
||||
// FIXME: find a better way to parse the output so that we will handle this properly
|
||||
log.Warn("Something is wrong with git log output, skipping...")
|
||||
log.Warn("authorName: %s, authorEmail: %s, date: %s, stats: %s", authorName, authorEmail, date, stats)
|
||||
continue
|
||||
}
|
||||
// 1 file changed, 1 insertion(+), 1 deletion(-)
|
||||
fields := strings.Split(stats, ",")
|
||||
|
||||
commitStats := api.CommitStats{}
|
||||
for _, field := range fields[1:] {
|
||||
parts := strings.Split(strings.TrimSpace(field), " ")
|
||||
value, contributionType := parts[0], parts[1]
|
||||
amount, _ := strconv.Atoi(value)
|
||||
|
||||
if strings.HasPrefix(contributionType, "insertion") {
|
||||
commitStats.Additions = amount
|
||||
} else {
|
||||
commitStats.Deletions = amount
|
||||
}
|
||||
}
|
||||
commitStats.Total = commitStats.Additions + commitStats.Deletions
|
||||
scanner.Text() // empty line at the end
|
||||
|
||||
res := &ExtendedCommitStats{
|
||||
Author: &api.CommitUser{
|
||||
Identity: api.Identity{
|
||||
Name: authorName,
|
||||
Email: authorEmail,
|
||||
},
|
||||
Date: date,
|
||||
},
|
||||
Stats: &commitStats,
|
||||
}
|
||||
extendedCommitStats = append(extendedCommitStats, res)
|
||||
}
|
||||
err = gitcmd.RunWithScannerSplit(ctx, gitCmd, bufio.ScanLines, func(_ gitcmd.Context, line []byte) error {
|
||||
if header, ok := bytes.CutPrefix(line, []byte{0}); ok {
|
||||
authorName, rest, _ := strings.Cut(string(header), "\x00")
|
||||
authorEmail, date, _ := strings.Cut(rest, "\x00")
|
||||
extendedCommitStats = append(extendedCommitStats, &ExtendedCommitStats{
|
||||
Author: &api.CommitUser{
|
||||
Identity: api.Identity{Name: strings.TrimSpace(authorName), Email: strings.TrimSpace(authorEmail)},
|
||||
Date: date,
|
||||
},
|
||||
Stats: &api.CommitStats{},
|
||||
})
|
||||
return nil
|
||||
}).
|
||||
RunWithStderr(ctx)
|
||||
}
|
||||
if len(extendedCommitStats) == 0 {
|
||||
return nil
|
||||
}
|
||||
// 1 file changed, 1 insertion(+), 1 deletion(-)
|
||||
commitStats := extendedCommitStats[len(extendedCommitStats)-1].Stats
|
||||
for _, field := range strings.Split(string(line), ",")[1:] {
|
||||
value, contributionType, _ := strings.Cut(strings.TrimSpace(field), " ")
|
||||
amount, _ := strconv.Atoi(value)
|
||||
if strings.HasPrefix(contributionType, "insertion") {
|
||||
commitStats.Additions = amount
|
||||
} else {
|
||||
commitStats.Deletions = amount
|
||||
}
|
||||
}
|
||||
commitStats.Total = commitStats.Additions + commitStats.Deletions
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ContributorsCommitStats: %w", err)
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ import (
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/cache"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/setting"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRepository_ContributorsGraph(t *testing.T) {
|
||||
@@ -82,3 +84,23 @@ func TestRepository_ContributorsGraph(t *testing.T) {
|
||||
},
|
||||
}, data["total"])
|
||||
}
|
||||
|
||||
func TestGetExtendedCommitStatsEmptyCommits(t *testing.T) {
|
||||
repoFacade, err := git.ForceFastImportWithInit(t.Context(), t.TempDir(), []git.FastImportCommit{
|
||||
{Ref: "refs/heads/master"},
|
||||
{Ref: "refs/heads/master", Parent: ":1", Files: []git.FastImportFile{{Path: "a.txt", Content: "a\n"}}},
|
||||
{Ref: "refs/heads/master", Parent: ":2"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
gitRepo, err := git.OpenRepository(t.Context(), repoFacade)
|
||||
require.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
|
||||
stats, err := getExtendedCommitStats(t.Context(), gitRepo, "master")
|
||||
require.NoError(t, err)
|
||||
var additions []int
|
||||
for _, commit := range stats {
|
||||
additions = append(additions, commit.Stats.Additions)
|
||||
}
|
||||
assert.Equal(t, []int{0, 1, 0}, additions)
|
||||
}
|
||||
Reference in new issue
Block a user