1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-26 09:09:36 -05:00
forgejo/routers/web/repo/blame.go

299 lines
8 KiB
Go
Raw Normal View History

2019-04-19 22:47:00 -04:00
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2019-04-19 22:47:00 -04:00
package repo
import (
"fmt"
gotemplate "html/template"
"net/http"
"net/url"
2019-04-19 22:47:00 -04:00
"strings"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/charset"
2019-04-19 22:47:00 -04:00
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/highlight"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/context"
files_service "code.gitea.io/gitea/services/repository/files"
2019-04-19 22:47:00 -04:00
)
type blameRow struct {
RowNumber int
Avatar gotemplate.HTML
RepoLink string
PartSha string
PreviousSha string
PreviousShaURL string
IsFirstCommit bool
CommitURL string
CommitMessage string
CommitSince gotemplate.HTML
Code gotemplate.HTML
EscapeStatus *charset.EscapeStatus
}
2019-04-19 22:47:00 -04:00
// RefBlame render blame page
func RefBlame(ctx *context.Context) {
if ctx.Repo.TreePath == "" {
ctx.NotFound("No file specified", nil)
2019-04-19 22:47:00 -04:00
return
}
paths := make([]string, 0, 5)
treeNames := strings.Split(ctx.Repo.TreePath, "/")
for i := range treeNames {
paths = append(paths, strings.Join(treeNames[:i+1], "/"))
2019-04-19 22:47:00 -04:00
}
// Get current entry user currently looking at.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
if err != nil {
HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
2019-04-19 22:47:00 -04:00
return
}
blob := entry.Blob()
ctx.Data["PageIsViewCode"] = true
ctx.Data["IsBlame"] = true
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
ctx.Data["RawFileLink"] = ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
ctx.Data["Paths"] = paths
ctx.Data["TreeNames"] = treeNames
2019-04-19 22:47:00 -04:00
ctx.Data["FileSize"] = blob.Size()
ctx.Data["FileName"] = blob.Name()
// Do not display a blame view if the size of the file is
// larger than what is configured as the maximum.
if blob.Size() >= setting.UI.MaxDisplayFileSize {
ctx.Data["IsFileTooLarge"] = true
ctx.HTML(http.StatusOK, tplRepoHome)
return
}
ctx.Data["NumLinesSet"] = true
ctx.Data["NumLines"], err = blob.GetBlobLineCount()
if err != nil {
ctx.ServerError("GetBlobLineCount", err)
return
}
result, err := performBlame(ctx, ctx.Repo.Commit, ctx.Repo.TreePath, ctx.FormBool("bypass-blame-ignore"))
2019-04-19 22:47:00 -04:00
if err != nil {
ctx.ServerError("performBlame", err)
2019-04-19 22:47:00 -04:00
return
}
ctx.Data["UsesIgnoreRevs"] = result.UsesIgnoreRevs
ctx.Data["FaultyIgnoreRevsFile"] = result.FaultyIgnoreRevsFile
2019-04-19 22:47:00 -04:00
commitNames := processBlameParts(ctx, result.Parts)
if ctx.Written() {
return
}
renderBlame(ctx, result.Parts, commitNames)
ctx.HTML(http.StatusOK, tplRepoHome)
}
type blameResult struct {
Parts []*git.BlamePart
UsesIgnoreRevs bool
FaultyIgnoreRevsFile bool
}
func performBlame(ctx *context.Context, commit *git.Commit, file string, bypassBlameIgnore bool) (*blameResult, error) {
repoPath := ctx.Repo.Repository.RepoPath()
objectFormat := ctx.Repo.GetObjectFormat()
blameReader, err := git.CreateBlameReader(ctx, objectFormat, repoPath, commit, file, bypassBlameIgnore)
if err != nil {
return nil, err
}
r := &blameResult{}
if err := fillBlameResult(blameReader, r); err != nil {
_ = blameReader.Close()
return nil, err
}
err = blameReader.Close()
if err != nil {
if len(r.Parts) == 0 && r.UsesIgnoreRevs {
// try again without ignored revs
blameReader, err = git.CreateBlameReader(ctx, objectFormat, repoPath, commit, file, true)
if err != nil {
return nil, err
}
r := &blameResult{
FaultyIgnoreRevsFile: true,
}
if err := fillBlameResult(blameReader, r); err != nil {
_ = blameReader.Close()
return nil, err
}
return r, blameReader.Close()
}
return nil, err
}
return r, nil
}
func fillBlameResult(br *git.BlameReader, r *blameResult) error {
r.UsesIgnoreRevs = br.UsesIgnoreRevs()
previousHelper := make(map[string]*git.BlamePart)
r.Parts = make([]*git.BlamePart, 0, 5)
for {
blamePart, err := br.NextPart()
if err != nil {
return fmt.Errorf("BlameReader.NextPart failed: %w", err)
}
if blamePart == nil {
break
}
if prev, ok := previousHelper[blamePart.Sha]; ok {
if blamePart.PreviousSha == "" {
blamePart.PreviousSha = prev.PreviousSha
blamePart.PreviousPath = prev.PreviousPath
}
} else {
previousHelper[blamePart.Sha] = blamePart
}
r.Parts = append(r.Parts, blamePart)
}
return nil
}
func processBlameParts(ctx *context.Context, blameParts []*git.BlamePart) map[string]*user_model.UserCommit {
// store commit data by SHA to look up avatar info etc
commitNames := make(map[string]*user_model.UserCommit)
// and as blameParts can reference the same commits multiple
// times, we cache the lookup work locally
commits := make([]*git.Commit, 0, len(blameParts))
commitCache := map[string]*git.Commit{}
commitCache[ctx.Repo.Commit.ID.String()] = ctx.Repo.Commit
2019-04-19 22:47:00 -04:00
for _, part := range blameParts {
sha := part.Sha
if _, ok := commitNames[sha]; ok {
continue
}
// find the blamePart commit, to look up parent & email address for avatars
commit, ok := commitCache[sha]
var err error
if !ok {
commit, err = ctx.Repo.GitRepo.GetCommit(sha)
if err != nil {
if git.IsErrNotExist(err) {
ctx.NotFound("Repo.GitRepo.GetCommit", err)
} else {
ctx.ServerError("Repo.GitRepo.GetCommit", err)
}
return nil
}
commitCache[sha] = commit
}
commits = append(commits, commit)
2019-04-19 22:47:00 -04:00
}
// populate commit email addresses to later look up avatars.
Add context cache as a request level cache (#22294) To avoid duplicated load of the same data in an HTTP request, we can set a context cache to do that. i.e. Some pages may load a user from a database with the same id in different areas on the same page. But the code is hidden in two different deep logic. How should we share the user? As a result of this PR, now if both entry functions accept `context.Context` as the first parameter and we just need to refactor `GetUserByID` to reuse the user from the context cache. Then it will not be loaded twice on an HTTP request. But of course, sometimes we would like to reload an object from the database, that's why `RemoveContextData` is also exposed. The core context cache is here. It defines a new context ```go type cacheContext struct { ctx context.Context data map[any]map[any]any lock sync.RWMutex } var cacheContextKey = struct{}{} func WithCacheContext(ctx context.Context) context.Context { return context.WithValue(ctx, cacheContextKey, &cacheContext{ ctx: ctx, data: make(map[any]map[any]any), }) } ``` Then you can use the below 4 methods to read/write/del the data within the same context. ```go func GetContextData(ctx context.Context, tp, key any) any func SetContextData(ctx context.Context, tp, key, value any) func RemoveContextData(ctx context.Context, tp, key any) func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) ``` Then let's take a look at how `system.GetString` implement it. ```go func GetSetting(ctx context.Context, key string) (string, error) { return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) { return cache.GetString(genSettingCacheKey(key), func() (string, error) { res, err := GetSettingNoCache(ctx, key) if err != nil { return "", err } return res.SettingValue, nil }) }) } ``` First, it will check if context data include the setting object with the key. If not, it will query from the global cache which may be memory or a Redis cache. If not, it will get the object from the database. In the end, if the object gets from the global cache or database, it will be set into the context cache. An object stored in the context cache will only be destroyed after the context disappeared.
2023-02-15 08:37:34 -05:00
for _, c := range user_model.ValidateCommitsWithEmails(ctx, commits) {
2019-04-19 22:47:00 -04:00
commitNames[c.ID.String()] = c
}
return commitNames
2019-04-19 22:47:00 -04:00
}
func renderBlame(ctx *context.Context, blameParts []*git.BlamePart, commitNames map[string]*user_model.UserCommit) {
2019-04-19 22:47:00 -04:00
repoLink := ctx.Repo.RepoLink
language, err := files_service.TryGetContentLanguage(ctx.Repo.GitRepo, ctx.Repo.CommitID, ctx.Repo.TreePath)
if err != nil {
log.Error("Unable to get file language for %-v:%s. Error: %v", ctx.Repo.Repository, ctx.Repo.TreePath, err)
}
lines := make([]string, 0)
rows := make([]*blameRow, 0)
escapeStatus := &charset.EscapeStatus{}
2019-04-19 22:47:00 -04:00
var lexerName string
avatarUtils := templates.NewAvatarUtils(ctx)
i := 0
commitCnt := 0
for _, part := range blameParts {
2019-04-19 22:47:00 -04:00
for index, line := range part.Lines {
i++
lines = append(lines, line)
br := &blameRow{
RowNumber: i,
2019-04-19 22:47:00 -04:00
}
2019-04-19 22:47:00 -04:00
commit := commitNames[part.Sha]
if index == 0 {
// Count commit number
commitCnt++
2019-04-19 22:47:00 -04:00
// User avatar image
commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Locale)
var avatar string
2019-04-19 22:47:00 -04:00
if commit.User != nil {
[Port] gitea#30014: Various code view improvements 1. Restore missing styles for message close icon 2. Move `code-line-button` so that it does not go off-screen on small viewports 3. Make `code-line-button` look and behave like other buttons 4. Make `code-line-button` work in blame 5. Make the active selection span the whole line, not just the code part 6. Tweak colors, make dark theme code bg darker, make line numbers same color in diff and file view. 7. Move code background to parent, fixing border radius and other problems 8. Enable code wrap in blame 9. Improve blame responsiveness 10. Remove `--color-code-sidebar-bg` in blame, now it uses same background as code 11. Rename `--color-active-line` to `--color-highlight-bg` 12. Add `--color-highlight-bg` 13. Fix button group borders on hover and border-right on last button. <img width="1343" alt="Screenshot 2024-03-23 at 22 34 13" src="https://github.com/go-gitea/gitea/assets/115237/fcbb919f-5dc3-43f0-97f6-870d6f412554"> <img width="1334" alt="Screenshot 2024-03-23 at 22 34 26" src="https://github.com/go-gitea/gitea/assets/115237/ca44c3b7-4328-4645-ba49-b0dc6a5ac06d"> <img width="1338" alt="Screenshot 2024-03-23 at 22 34 57" src="https://github.com/go-gitea/gitea/assets/115237/00eb0b5a-1ec7-4669-a94a-4602b9d1c1ac"> <img width="1337" alt="Screenshot 2024-03-23 at 22 34 42" src="https://github.com/go-gitea/gitea/assets/115237/752edc4a-064f-413c-9dff-c086187fcd85"> Fixes: https://github.com/go-gitea/gitea/issues/18074 --- Conflict resolution: Trivial. Ref: https://codeberg.org/forgejo/forgejo/issues/2776 (cherry picked from commit db01bf6cc88a8a7b5132b9306b3af1649566b10f)
2024-03-24 08:14:03 -04:00
avatar = string(avatarUtils.Avatar(commit.User, 18))
2019-04-19 22:47:00 -04:00
} else {
avatar = string(avatarUtils.AvatarByEmail(commit.Author.Email, commit.Author.Name, 18, "tw-mr-2"))
2019-04-19 22:47:00 -04:00
}
br.Avatar = gotemplate.HTML(avatar)
br.RepoLink = repoLink
br.PartSha = part.Sha
br.PreviousSha = part.PreviousSha
br.PreviousShaURL = fmt.Sprintf("%s/blame/commit/%s/%s", repoLink, url.PathEscape(part.PreviousSha), util.PathEscapeSegments(part.PreviousPath))
br.CommitURL = fmt.Sprintf("%s/commit/%s", repoLink, url.PathEscape(part.Sha))
br.CommitMessage = commit.CommitMessage
br.CommitSince = commitSince
2019-04-19 22:47:00 -04:00
}
if i != len(lines)-1 {
2019-04-19 22:47:00 -04:00
line += "\n"
}
fileName := fmt.Sprintf("%v", ctx.Data["FileName"])
line, lexerNameForLine := highlight.Code(fileName, language, line)
// set lexer name to the first detected lexer. this is certainly suboptimal and
// we should instead highlight the whole file at once
if lexerName == "" {
lexerName = lexerNameForLine
}
br.EscapeStatus, br.Code = charset.EscapeControlHTML(line, ctx.Locale, charset.FileviewContext)
rows = append(rows, br)
escapeStatus = escapeStatus.Or(br.EscapeStatus)
2019-04-19 22:47:00 -04:00
}
}
ctx.Data["EscapeStatus"] = escapeStatus
ctx.Data["BlameRows"] = rows
ctx.Data["CommitCnt"] = commitCnt
ctx.Data["LexerName"] = lexerName
2019-04-19 22:47:00 -04:00
}