From 901cdb24b926d796c8cc333e83a924449bf723f5 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 31 Dec 2022 14:55:56 +0800 Subject: [PATCH 01/14] Add context cache support --- cmd/admin.go | 2 +- models/activities/repo_activity.go | 6 +- models/asymkey/gpg_key_commit_verification.go | 11 +-- models/avatars/avatar.go | 14 +-- models/git/commit_status.go | 5 +- models/issues/comment.go | 2 +- models/organization/org.go | 4 +- models/system/setting.go | 47 ++++++---- models/user/avatar.go | 12 +-- models/user/user.go | 15 ++-- modules/auth/webauthn/webauthn.go | 3 +- modules/cache/context.go | 56 ++++++++++++ modules/gitgraph/graph_models.go | 8 +- modules/notification/webhook/webhook.go | 90 +++++++++---------- modules/repository/commits.go | 12 +-- modules/repository/repo.go | 6 +- modules/templates/helper.go | 23 +++-- routers/api/v1/activitypub/person.go | 2 +- routers/api/v1/admin/org.go | 4 +- routers/api/v1/admin/user.go | 6 +- routers/api/v1/org/member.go | 2 +- routers/api/v1/org/org.go | 10 +-- routers/api/v1/org/team.go | 16 ++-- routers/api/v1/repo/branch.go | 6 +- routers/api/v1/repo/collaborators.go | 8 +- routers/api/v1/repo/commits.go | 4 +- routers/api/v1/repo/hook.go | 6 +- routers/api/v1/repo/issue_comment.go | 10 +-- routers/api/v1/repo/issue_reaction.go | 12 +-- routers/api/v1/repo/issue_subscription.go | 2 +- routers/api/v1/repo/notes.go | 2 +- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/repo/pull_review.go | 2 +- routers/api/v1/repo/release.go | 8 +- routers/api/v1/repo/release_attachment.go | 2 +- routers/api/v1/repo/release_tags.go | 2 +- routers/api/v1/repo/star.go | 2 +- routers/api/v1/repo/subscriber.go | 2 +- routers/api/v1/repo/tag.go | 2 +- routers/api/v1/repo/teams.go | 4 +- routers/api/v1/repo/transfer.go | 2 +- routers/api/v1/user/follower.go | 2 +- routers/api/v1/user/key.go | 13 +-- routers/api/v1/user/user.go | 6 +- routers/install/install.go | 2 +- routers/private/hook_verification.go | 2 +- routers/web/admin/config.go | 2 +- routers/web/auth/linkaccount.go | 2 +- routers/web/auth/oauth.go | 4 +- routers/web/auth/openid.go | 2 +- routers/web/auth/password.go | 2 +- routers/web/org/teams.go | 2 +- routers/web/repo/blame.go | 6 +- routers/web/repo/commit.go | 14 +-- routers/web/repo/compare.go | 2 +- routers/web/repo/issue.go | 2 +- routers/web/repo/pull.go | 2 +- routers/web/repo/view.go | 4 +- routers/web/repo/webhook.go | 2 +- routers/web/repo/wiki.go | 2 +- routers/web/user/avatar.go | 4 +- routers/web/user/search.go | 2 +- routers/web/webfinger.go | 4 +- services/asymkey/sign.go | 12 +-- services/auth/reverseproxy.go | 2 +- services/convert/convert.go | 26 +++--- services/convert/git_commit.go | 25 +++--- services/convert/issue.go | 6 +- services/convert/issue_comment.go | 14 +-- services/convert/package.go | 4 +- services/convert/pull.go | 2 +- services/convert/pull_review.go | 8 +- services/convert/release.go | 6 +- services/convert/repository.go | 12 +-- services/convert/status.go | 2 +- services/convert/user.go | 22 ++--- services/pull/check.go | 2 +- services/release/release.go | 2 +- services/repository/files/cherry_pick.go | 2 +- services/repository/files/commit.go | 4 +- services/repository/files/file.go | 2 +- services/repository/files/patch.go | 2 +- services/repository/push.go | 2 +- 83 files changed, 373 insertions(+), 301 deletions(-) create mode 100644 modules/cache/context.go diff --git a/cmd/admin.go b/cmd/admin.go index 7463b21d81ab6..67976db8b89ee 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -661,7 +661,7 @@ func runDeleteUser(c *cli.Context) error { var err error var user *user_model.User if c.IsSet("email") { - user, err = user_model.GetUserByEmail(c.String("email")) + user, err = user_model.GetUserByEmail(ctx, c.String("email")) } else if c.IsSet("username") { user, err = user_model.GetUserByName(ctx, c.String("username")) } else { diff --git a/models/activities/repo_activity.go b/models/activities/repo_activity.go index 9018276c3aeb8..72b6be3122601 100644 --- a/models/activities/repo_activity.go +++ b/models/activities/repo_activity.go @@ -97,12 +97,12 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository } users := make(map[int64]*ActivityAuthorData) var unknownUserID int64 - unknownUserAvatarLink := user_model.NewGhostUser().AvatarLink() + unknownUserAvatarLink := user_model.NewGhostUser().AvatarLink(ctx) for _, v := range code.Authors { if len(v.Email) == 0 { continue } - u, err := user_model.GetUserByEmail(v.Email) + u, err := user_model.GetUserByEmail(ctx, v.Email) if u == nil || user_model.IsErrUserNotExist(err) { unknownUserID-- users[unknownUserID] = &ActivityAuthorData{ @@ -119,7 +119,7 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository users[u.ID] = &ActivityAuthorData{ Name: u.DisplayName(), Login: u.LowerName, - AvatarLink: u.AvatarLink(), + AvatarLink: u.AvatarLink(ctx), HomeLink: u.HomeLink(), Commits: v.Commits, } diff --git a/models/asymkey/gpg_key_commit_verification.go b/models/asymkey/gpg_key_commit_verification.go index 1b88fb8b13872..db6e78cad522c 100644 --- a/models/asymkey/gpg_key_commit_verification.go +++ b/models/asymkey/gpg_key_commit_verification.go @@ -4,6 +4,7 @@ package asymkey import ( + "context" "fmt" "hash" "strings" @@ -70,14 +71,14 @@ const ( ) // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys. -func ParseCommitsWithSignature(oldCommits []*user_model.UserCommit, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error)) []*SignCommit { +func ParseCommitsWithSignature(ctx context.Context, oldCommits []*user_model.UserCommit, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error)) []*SignCommit { newCommits := make([]*SignCommit, 0, len(oldCommits)) keyMap := map[string]bool{} for _, c := range oldCommits { signCommit := &SignCommit{ UserCommit: c, - Verification: ParseCommitWithSignature(c.Commit), + Verification: ParseCommitWithSignature(ctx, c.Commit), } _ = CalculateTrustStatus(signCommit.Verification, repoTrustModel, isOwnerMemberCollaborator, &keyMap) @@ -88,13 +89,13 @@ func ParseCommitsWithSignature(oldCommits []*user_model.UserCommit, repoTrustMod } // ParseCommitWithSignature check if signature is good against keystore. -func ParseCommitWithSignature(c *git.Commit) *CommitVerification { +func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerification { var committer *user_model.User if c.Committer != nil { var err error // Find Committer account - committer, err = user_model.GetUserByEmail(c.Committer.Email) // This finds the user by primary email or activated email so commit will not be valid if email is not - if err != nil { // Skipping not user for committer + committer, err = user_model.GetUserByEmail(ctx, c.Committer.Email) // This finds the user by primary email or activated email so commit will not be valid if email is not + if err != nil { // Skipping not user for committer committer = &user_model.User{ Name: c.Committer.Name, Email: c.Committer.Email, diff --git a/models/avatars/avatar.go b/models/avatars/avatar.go index 7ccb782fa62f1..cfc24dc5a0a0f 100644 --- a/models/avatars/avatar.go +++ b/models/avatars/avatar.go @@ -147,13 +147,13 @@ func generateRecognizedAvatarURL(u url.URL, size int) string { // generateEmailAvatarLink returns a email avatar link. // if final is true, it may use a slow path (eg: query DNS). // if final is false, it always uses a fast path. -func generateEmailAvatarLink(email string, size int, final bool) string { +func generateEmailAvatarLink(ctx context.Context, email string, size int, final bool) string { email = strings.TrimSpace(email) if email == "" { return DefaultAvatarLink() } - enableFederatedAvatarSetting, _ := system_model.GetSetting(system_model.KeyPictureEnableFederatedAvatar) + enableFederatedAvatarSetting, _ := system_model.GetSetting(ctx, system_model.KeyPictureEnableFederatedAvatar) enableFederatedAvatar := enableFederatedAvatarSetting.GetValueBool() var err error @@ -175,7 +175,7 @@ func generateEmailAvatarLink(email string, size int, final bool) string { return urlStr } - disableGravatarSetting, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar) + disableGravatarSetting, _ := system_model.GetSetting(ctx, system_model.KeyPictureDisableGravatar) disableGravatar := disableGravatarSetting.GetValueBool() if !disableGravatar { @@ -189,11 +189,11 @@ func generateEmailAvatarLink(email string, size int, final bool) string { } // GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}") -func GenerateEmailAvatarFastLink(email string, size int) string { - return generateEmailAvatarLink(email, size, false) +func GenerateEmailAvatarFastLink(ctx context.Context, email string, size int) string { + return generateEmailAvatarLink(ctx, email, size, false) } // GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow) -func GenerateEmailAvatarFinalLink(email string, size int) string { - return generateEmailAvatarLink(email, size, true) +func GenerateEmailAvatarFinalLink(ctx context.Context, email string, size int) string { + return generateEmailAvatarLink(ctx, email, size, true) } diff --git a/models/git/commit_status.go b/models/git/commit_status.go index 07e0b9fb73b4c..343a150e70f3b 100644 --- a/models/git/commit_status.go +++ b/models/git/commit_status.go @@ -348,10 +348,11 @@ func hashCommitStatusContext(context string) string { } // ConvertFromGitCommit converts git commits into SignCommitWithStatuses -func ConvertFromGitCommit(commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses { +func ConvertFromGitCommit(ctx context.Context, commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses { return ParseCommitsWithStatus( asymkey_model.ParseCommitsWithSignature( - user_model.ValidateCommitsWithEmails(commits), + ctx, + user_model.ValidateCommitsWithEmails(ctx, commits), repo.GetTrustModel(), func(user *user_model.User) (bool, error) { return repo_model.IsOwnerMemberCollaborator(repo, user.ID) diff --git a/models/issues/comment.go b/models/issues/comment.go index 612f17aa5af68..2dcbc7d8198c3 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -772,7 +772,7 @@ func (c *Comment) LoadPushCommits(ctx context.Context) (err error) { } defer closer.Close() - c.Commits = git_model.ConvertFromGitCommit(gitRepo.GetCommitsFromIDs(data.CommitIDs), c.Issue.Repo) + c.Commits = git_model.ConvertFromGitCommit(ctx, gitRepo.GetCommitsFromIDs(data.CommitIDs), c.Issue.Repo) c.CommitsNum = int64(len(c.Commits)) } diff --git a/models/organization/org.go b/models/organization/org.go index 9d9e9cda46a48..c7d2154eda742 100644 --- a/models/organization/org.go +++ b/models/organization/org.go @@ -164,8 +164,8 @@ func (org *Organization) hasMemberWithUserID(ctx context.Context, userID int64) } // AvatarLink returns the full avatar link with http host -func (org *Organization) AvatarLink() string { - return org.AsUser().AvatarLink() +func (org *Organization) AvatarLink(ctx context.Context) string { + return org.AsUser().AvatarLink(ctx) } // HTMLURL returns the organization's full link. diff --git a/models/system/setting.go b/models/system/setting.go index dc6145b417e49..3142ff76dd99d 100644 --- a/models/system/setting.go +++ b/models/system/setting.go @@ -80,8 +80,8 @@ func IsErrDataExpired(err error) bool { } // GetSettingNoCache returns specific setting without using the cache -func GetSettingNoCache(key string) (*Setting, error) { - v, err := GetSettings([]string{key}) +func GetSettingNoCache(ctx context.Context, key string) (*Setting, error) { + v, err := GetSettings(ctx, []string{key}) if err != nil { return nil, err } @@ -92,9 +92,9 @@ func GetSettingNoCache(key string) (*Setting, error) { } // GetSetting returns the setting value via the key -func GetSetting(key string) (*Setting, error) { +func GetSetting(ctx context.Context, key string) (*Setting, error) { return cache.Get(genSettingCacheKey(key), func() (*Setting, error) { - res, err := GetSettingNoCache(key) + res, err := GetSettingNoCache(ctx, key) if err != nil { return nil, err } @@ -104,15 +104,25 @@ func GetSetting(key string) (*Setting, error) { // GetSettingBool return bool value of setting, // none existing keys and errors are ignored and result in false -func GetSettingBool(key string) bool { - s, _ := GetSetting(key) +func GetSettingBool(ctx context.Context, key string) bool { + s, _ := GetSetting(ctx, key) return s.GetValueBool() } +const contextCacheKey = "system_setting" + // GetSettings returns specific settings -func GetSettings(keys []string) (map[string]*Setting, error) { +func GetSettings(ctx context.Context, keys []string) (map[string]*Setting, error) { + newKeys := make([]string, 0, len(keys)) + settingsMap := make(map[string]*Setting) for i := 0; i < len(keys); i++ { - keys[i] = strings.ToLower(keys[i]) + key := strings.ToLower(keys[i]) + v := cache.GetContextData(ctx, contextCacheKey, key) + if v != nil { + settingsMap[key] = v.(*Setting) + } else { + newKeys = append(newKeys, key) + } } settings := make([]*Setting, 0, len(keys)) if err := db.GetEngine(db.DefaultContext). @@ -120,9 +130,10 @@ func GetSettings(keys []string) (map[string]*Setting, error) { Find(&settings); err != nil { return nil, err } - settingsMap := make(map[string]*Setting) + for _, s := range settings { settingsMap[s.SettingKey] = s + cache.SetContextData(ctx, contextCacheKey, s.SettingKey, s) } return settingsMap, nil } @@ -160,16 +171,17 @@ func GetAllSettings() (AllSettings, error) { } // DeleteSetting deletes a specific setting for a user -func DeleteSetting(setting *Setting) error { +func DeleteSetting(ctx context.Context, setting *Setting) error { + cache.RemoveContextData(ctx, contextCacheKey, setting.SettingKey) cache.Remove(genSettingCacheKey(setting.SettingKey)) _, err := db.GetEngine(db.DefaultContext).Delete(setting) return err } -func SetSettingNoVersion(key, value string) error { - s, err := GetSettingNoCache(key) +func SetSettingNoVersion(ctx context.Context, key, value string) error { + s, err := GetSettingNoCache(ctx, key) if IsErrSettingIsNotExist(err) { - return SetSetting(&Setting{ + return SetSetting(ctx, &Setting{ SettingKey: key, SettingValue: value, }) @@ -178,11 +190,12 @@ func SetSettingNoVersion(key, value string) error { return err } s.SettingValue = value - return SetSetting(s) + return SetSetting(ctx, s) } // SetSetting updates a users' setting for a specific key -func SetSetting(setting *Setting) error { +func SetSetting(ctx context.Context, setting *Setting) error { + cache.SetContextData(ctx, contextCacheKey, setting.SettingKey, setting) _, err := cache.Set(genSettingCacheKey(setting.SettingKey), func() (*Setting, error) { return setting, upsertSettingValue(strings.ToLower(setting.SettingKey), setting.SettingValue, setting.Version) }) @@ -240,7 +253,7 @@ var ( func Init() error { var disableGravatar bool - disableGravatarSetting, err := GetSettingNoCache(KeyPictureDisableGravatar) + disableGravatarSetting, err := GetSettingNoCache(db.DefaultContext, KeyPictureDisableGravatar) if IsErrSettingIsNotExist(err) { disableGravatar = setting.GetDefaultDisableGravatar() disableGravatarSetting = &Setting{SettingValue: strconv.FormatBool(disableGravatar)} @@ -251,7 +264,7 @@ func Init() error { } var enableFederatedAvatar bool - enableFederatedAvatarSetting, err := GetSettingNoCache(KeyPictureEnableFederatedAvatar) + enableFederatedAvatarSetting, err := GetSettingNoCache(db.DefaultContext, KeyPictureEnableFederatedAvatar) if IsErrSettingIsNotExist(err) { enableFederatedAvatar = setting.GetDefaultEnableFederatedAvatar(disableGravatar) enableFederatedAvatarSetting = &Setting{SettingValue: strconv.FormatBool(enableFederatedAvatar)} diff --git a/models/user/avatar.go b/models/user/avatar.go index ce25139b5f743..4f8c8fdbba421 100644 --- a/models/user/avatar.go +++ b/models/user/avatar.go @@ -58,7 +58,7 @@ func GenerateRandomAvatar(ctx context.Context, u *User) error { } // AvatarLinkWithSize returns a link to the user's avatar with size. size <= 0 means default size -func (u *User) AvatarLinkWithSize(size int) string { +func (u *User) AvatarLinkWithSize(ctx context.Context, size int) string { if u.ID == -1 { // ghost user return avatars.DefaultAvatarLink() @@ -67,7 +67,7 @@ func (u *User) AvatarLinkWithSize(size int) string { useLocalAvatar := false autoGenerateAvatar := false - disableGravatarSetting, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar) + disableGravatarSetting, _ := system_model.GetSetting(ctx, system_model.KeyPictureDisableGravatar) disableGravatar := disableGravatarSetting.GetValueBool() @@ -81,7 +81,7 @@ func (u *User) AvatarLinkWithSize(size int) string { if useLocalAvatar { if u.Avatar == "" && autoGenerateAvatar { - if err := GenerateRandomAvatar(db.DefaultContext, u); err != nil { + if err := GenerateRandomAvatar(ctx, u); err != nil { log.Error("GenerateRandomAvatar: %v", err) } } @@ -90,12 +90,12 @@ func (u *User) AvatarLinkWithSize(size int) string { } return avatars.GenerateUserAvatarImageLink(u.Avatar, size) } - return avatars.GenerateEmailAvatarFastLink(u.AvatarEmail, size) + return avatars.GenerateEmailAvatarFastLink(ctx, u.AvatarEmail, size) } // AvatarLink returns the full avatar link with http host -func (u *User) AvatarLink() string { - link := u.AvatarLinkWithSize(0) +func (u *User) AvatarLink(ctx context.Context) string { + link := u.AvatarLinkWithSize(ctx, 0) if !strings.HasPrefix(link, "//") && !strings.Contains(link, "://") { return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL+"/") } diff --git a/models/user/user.go b/models/user/user.go index 825223201b679..60b18119c24e5 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -1125,11 +1125,11 @@ type UserCommit struct { //revive:disable-line:exported } // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user. -func ValidateCommitWithEmail(c *git.Commit) *User { +func ValidateCommitWithEmail(ctx context.Context, c *git.Commit) *User { if c.Author == nil { return nil } - u, err := GetUserByEmail(c.Author.Email) + u, err := GetUserByEmail(ctx, c.Author.Email) if err != nil { return nil } @@ -1137,7 +1137,7 @@ func ValidateCommitWithEmail(c *git.Commit) *User { } // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users. -func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit { +func ValidateCommitsWithEmails(ctx context.Context, oldCommits []*git.Commit) []*UserCommit { var ( emails = make(map[string]*User) newCommits = make([]*UserCommit, 0, len(oldCommits)) @@ -1146,7 +1146,7 @@ func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit { var u *User if c.Author != nil { if v, ok := emails[c.Author.Email]; !ok { - u, _ = GetUserByEmail(c.Author.Email) + u, _ = GetUserByEmail(ctx, c.Author.Email) emails[c.Author.Email] = u } else { u = v @@ -1162,12 +1162,7 @@ func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit { } // GetUserByEmail returns the user object by given e-mail if exists. -func GetUserByEmail(email string) (*User, error) { - return GetUserByEmailContext(db.DefaultContext, email) -} - -// GetUserByEmailContext returns the user object by given e-mail if exists with db context -func GetUserByEmailContext(ctx context.Context, email string) (*User, error) { +func GetUserByEmail(ctx context.Context, email string) (*User, error) { if len(email) == 0 { return nil, ErrUserNotExist{0, email, 0} } diff --git a/modules/auth/webauthn/webauthn.go b/modules/auth/webauthn/webauthn.go index ec60a86100db6..5f8f529805aed 100644 --- a/modules/auth/webauthn/webauthn.go +++ b/modules/auth/webauthn/webauthn.go @@ -9,6 +9,7 @@ import ( "net/url" "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" @@ -63,7 +64,7 @@ func (u *User) WebAuthnDisplayName() string { // WebAuthnIcon implements the webauthn.User interface func (u *User) WebAuthnIcon() string { - return (*user_model.User)(u).AvatarLink() + return (*user_model.User)(u).AvatarLink(db.DefaultContext) } // WebAuthnCredentials implementns the webauthn.User interface diff --git a/modules/cache/context.go b/modules/cache/context.go new file mode 100644 index 0000000000000..47de4a9ce5f6f --- /dev/null +++ b/modules/cache/context.go @@ -0,0 +1,56 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package cache + +import "context" + +type CacheContext struct { + ctx context.Context + Data map[any]map[any]any +} + +type CacheContextKey struct{} + +func WithCacheContext(ctx context.Context) context.Context { + return context.WithValue(ctx, &CacheContextKey{}, &CacheContext{ + ctx: ctx, + Data: make(map[any]map[any]any), + }) +} + +func GetContextData(ctx context.Context, tp, key any) any { + if ctx == nil { + return nil + } + if c, ok := ctx.Value(&CacheContextKey{}).(*CacheContext); ok { + if c.Data[tp] != nil { + return c.Data[tp][key] + } + } + return nil +} + +func SetContextData(ctx context.Context, tp, key, value any) { + if ctx == nil { + return + } + if c, ok := ctx.Value(&CacheContextKey{}).(*CacheContext); ok { + if c.Data[tp] == nil { + c.Data[tp] = make(map[any]any) + } + c.Data[tp][key] = value + } +} + +func RemoveContextData(ctx context.Context, tp, key any) { + if ctx == nil { + return + } + if c, ok := ctx.Value(&CacheContextKey{}).(*CacheContext); ok { + if c.Data[tp] == nil { + c.Data[tp] = make(map[any]any) + } + delete(c.Data[tp], key) + } +} diff --git a/modules/gitgraph/graph_models.go b/modules/gitgraph/graph_models.go index 0e0fc1cd012da..748f7f307574e 100644 --- a/modules/gitgraph/graph_models.go +++ b/modules/gitgraph/graph_models.go @@ -5,6 +5,7 @@ package gitgraph import ( "bytes" + "context" "fmt" "strings" @@ -88,9 +89,8 @@ func (graph *Graph) AddCommit(row, column int, flowID int64, data []byte) error // LoadAndProcessCommits will load the git.Commits for each commit in the graph, // the associate the commit with the user author, and check the commit verification // before finally retrieving the latest status -func (graph *Graph) LoadAndProcessCommits(repository *repo_model.Repository, gitRepo *git.Repository) error { +func (graph *Graph) LoadAndProcessCommits(ctx context.Context, repository *repo_model.Repository, gitRepo *git.Repository) error { var err error - var ok bool emails := map[string]*user_model.User{} @@ -108,12 +108,12 @@ func (graph *Graph) LoadAndProcessCommits(repository *repo_model.Repository, git if c.Commit.Author != nil { email := c.Commit.Author.Email if c.User, ok = emails[email]; !ok { - c.User, _ = user_model.GetUserByEmail(email) + c.User, _ = user_model.GetUserByEmail(ctx, email) emails[email] = c.User } } - c.Verification = asymkey_model.ParseCommitWithSignature(c.Commit) + c.Verification = asymkey_model.ParseCommitWithSignature(ctx, c.Commit) _ = asymkey_model.CalculateTrustStatus(c.Verification, repository.GetTrustModel(), func(user *user_model.User) (bool, error) { return repo_model.IsOwnerMemberCollaborator(repository, user.ID) diff --git a/modules/notification/webhook/webhook.go b/modules/notification/webhook/webhook.go index 97d5e04340d93..4cbd4034d7cf9 100644 --- a/modules/notification/webhook/webhook.go +++ b/modules/notification/webhook/webhook.go @@ -59,7 +59,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ @@ -67,7 +67,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } if err != nil { @@ -83,7 +83,7 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{ Forkee: convert.ToRepo(ctx, oldRepo, oldMode), Repo: convert.ToRepo(ctx, repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err) } @@ -95,8 +95,8 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Organization: convert.ToUser(u, nil), - Sender: convert.ToUser(doer, nil), + Organization: convert.ToUser(ctx, u, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) } @@ -108,8 +108,8 @@ func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Organization: convert.ToUser(u, nil), - Sender: convert.ToUser(doer, nil), + Organization: convert.ToUser(ctx, u, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) } @@ -119,8 +119,8 @@ func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoDeleted, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Organization: convert.ToUser(repo.MustOwner(ctx), nil), - Sender: convert.ToUser(doer, nil), + Organization: convert.ToUser(ctx, repo.MustOwner(ctx), nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) } @@ -131,8 +131,8 @@ func (m *webhookNotifier) NotifyMigrateRepository(ctx context.Context, doer, u * if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Organization: convert.ToUser(u, nil), - Sender: convert.ToUser(doer, nil), + Organization: convert.ToUser(ctx, u, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) } @@ -151,7 +151,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), } if removed { apiPullRequest.Action = api.HookIssueUnassigned @@ -169,7 +169,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), } if removed { apiIssue.Action = api.HookIssueUnassigned @@ -203,7 +203,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user }, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ @@ -216,7 +216,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user }, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } @@ -238,7 +238,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), } if isClosed { apiPullRequest.Action = api.HookIssueClosed @@ -251,7 +251,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), } if isClosed { apiIssue.Action = api.HookIssueClosed @@ -281,7 +281,7 @@ func (m *webhookNotifier) NotifyNewIssue(ctx context.Context, issue *issues_mode Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(issue.Poster, nil), + Sender: convert.ToUser(ctx, issue.Poster, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } @@ -307,7 +307,7 @@ func (m *webhookNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues Index: pull.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pull, nil), Repository: convert.ToRepo(ctx, pull.Issue.Repo, mode), - Sender: convert.ToUser(pull.Issue.Poster, nil), + Sender: convert.ToUser(ctx, pull.Issue.Poster, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } @@ -333,7 +333,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us }, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ @@ -346,7 +346,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us }, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } if err != nil { @@ -380,14 +380,14 @@ func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_mo if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentEdited, Issue: convert.ToAPIIssue(ctx, c.Issue), - Comment: convert.ToComment(c), + Comment: convert.ToComment(ctx, c), Changes: &api.ChangesPayload{ Body: &api.ChangesFromPayload{ From: oldContent, }, }, Repository: convert.ToRepo(ctx, c.Issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), IsPull: c.Issue.IsPull, }); err != nil { log.Error("PrepareWebhooks [comment_id: %d]: %v", c.ID, err) @@ -408,9 +408,9 @@ func (m *webhookNotifier) NotifyCreateIssueComment(ctx context.Context, doer *us if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentCreated, Issue: convert.ToAPIIssue(ctx, issue), - Comment: convert.ToComment(comment), + Comment: convert.ToComment(ctx, comment), Repository: convert.ToRepo(ctx, repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), IsPull: issue.IsPull, }); err != nil { log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err) @@ -445,9 +445,9 @@ func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_mo if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentDeleted, Issue: convert.ToAPIIssue(ctx, comment.Issue), - Comment: convert.ToComment(comment), + Comment: convert.ToComment(ctx, comment), Repository: convert.ToRepo(ctx, comment.Issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), IsPull: comment.Issue.IsPull, }); err != nil { log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err) @@ -459,7 +459,7 @@ func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_mode if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiCreated, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), Page: page, Comment: comment, }); err != nil { @@ -472,7 +472,7 @@ func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_mod if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiEdited, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), Page: page, Comment: comment, }); err != nil { @@ -485,7 +485,7 @@ func (m *webhookNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_m if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiDeleted, Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), Page: page, }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) @@ -522,7 +522,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, perm.AccessModeNone), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ @@ -530,7 +530,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } if err != nil { @@ -564,7 +564,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueMilestone, &api.IssuePayload{ @@ -572,7 +572,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }) } if err != nil { @@ -581,7 +581,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * } func (m *webhookNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { - apiPusher := convert.ToUser(pusher, nil) + apiPusher := convert.ToUser(ctx, pusher, nil) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) if err != nil { log.Error("commits.ToAPIPayloadCommits failed: %v", err) @@ -637,7 +637,7 @@ func (*webhookNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_m Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), Repository: convert.ToRepo(ctx, pr.Issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), Action: api.HookIssueClosed, } @@ -665,7 +665,7 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Contex }, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), Repository: convert.ToRepo(ctx, issue.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [pr: %d]: %v", pr.ID, err) } @@ -702,7 +702,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue Index: review.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), Repository: convert.ToRepo(ctx, review.Issue.Repo, mode), - Sender: convert.ToUser(review.Reviewer, nil), + Sender: convert.ToUser(ctx, review.Reviewer, nil), Review: &api.ReviewPayload{ Type: string(reviewHookType), Content: review.Content, @@ -713,7 +713,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue } func (m *webhookNotifier) NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { - apiPusher := convert.ToUser(pusher, nil) + apiPusher := convert.ToUser(ctx, pusher, nil) apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) @@ -743,14 +743,14 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), Repository: convert.ToRepo(ctx, pr.Issue.Repo, perm.AccessModeNone), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err) } } func (m *webhookNotifier) NotifyDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { - apiPusher := convert.ToUser(pusher, nil) + apiPusher := convert.ToUser(ctx, pusher, nil) apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) @@ -774,9 +774,9 @@ func sendReleaseHook(ctx context.Context, doer *user_model.User, rel *repo_model mode, _ := access_model.AccessLevel(ctx, doer, rel.Repo) if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{ Action: action, - Release: convert.ToRelease(rel), + Release: convert.ToRelease(ctx, rel), Repository: convert.ToRepo(ctx, rel.Repo, mode), - Sender: convert.ToUser(doer, nil), + Sender: convert.ToUser(ctx, doer, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } @@ -795,7 +795,7 @@ func (m *webhookNotifier) NotifyDeleteRelease(ctx context.Context, doer *user_mo } func (m *webhookNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { - apiPusher := convert.ToUser(pusher, nil) + apiPusher := convert.ToUser(ctx, pusher, nil) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) if err != nil { log.Error("commits.ToAPIPayloadCommits failed: %v", err) @@ -849,7 +849,7 @@ func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_mo if err := webhook_services.PrepareWebhooks(ctx, source, webhook.HookEventPackage, &api.PackagePayload{ Action: action, Package: apiPackage, - Sender: convert.ToUser(sender, nil), + Sender: convert.ToUser(ctx, sender, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } diff --git a/modules/repository/commits.go b/modules/repository/commits.go index a47f9b2dc83d6..96844d5b1da04 100644 --- a/modules/repository/commits.go +++ b/modules/repository/commits.go @@ -53,7 +53,7 @@ func (pc *PushCommits) toAPIPayloadCommit(ctx context.Context, repoPath, repoLin authorUsername := "" author, ok := pc.emailUsers[commit.AuthorEmail] if !ok { - author, err = user_model.GetUserByEmail(commit.AuthorEmail) + author, err = user_model.GetUserByEmail(ctx, commit.AuthorEmail) if err == nil { authorUsername = author.Name pc.emailUsers[commit.AuthorEmail] = author @@ -65,7 +65,7 @@ func (pc *PushCommits) toAPIPayloadCommit(ctx context.Context, repoPath, repoLin committerUsername := "" committer, ok := pc.emailUsers[commit.CommitterEmail] if !ok { - committer, err = user_model.GetUserByEmail(commit.CommitterEmail) + committer, err = user_model.GetUserByEmail(ctx, commit.CommitterEmail) if err == nil { // TODO: check errors other than email not found. committerUsername = committer.Name @@ -133,7 +133,7 @@ func (pc *PushCommits) ToAPIPayloadCommits(ctx context.Context, repoPath, repoLi // AvatarLink tries to match user in database with e-mail // in order to show custom avatar, and falls back to general avatar link. -func (pc *PushCommits) AvatarLink(email string) string { +func (pc *PushCommits) AvatarLink(ctx context.Context, email string) string { if pc.avatars == nil { pc.avatars = make(map[string]string) } @@ -147,9 +147,9 @@ func (pc *PushCommits) AvatarLink(email string) string { u, ok := pc.emailUsers[email] if !ok { var err error - u, err = user_model.GetUserByEmail(email) + u, err = user_model.GetUserByEmail(ctx, email) if err != nil { - pc.avatars[email] = avatars.GenerateEmailAvatarFastLink(email, size) + pc.avatars[email] = avatars.GenerateEmailAvatarFastLink(ctx, email, size) if !user_model.IsErrUserNotExist(err) { log.Error("GetUserByEmail: %v", err) return "" @@ -159,7 +159,7 @@ func (pc *PushCommits) AvatarLink(email string) string { } } if u != nil { - pc.avatars[email] = u.AvatarLinkWithSize(size) + pc.avatars[email] = u.AvatarLinkWithSize(ctx, size) } return pc.avatars[email] diff --git a/modules/repository/repo.go b/modules/repository/repo.go index a90eb8a764ac9..62e9cc8dcadcd 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -318,7 +318,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) return nil } - if err := PushUpdateAddTag(repo, gitRepo, tagName, sha1, refname); err != nil { + if err := PushUpdateAddTag(db.DefaultContext, repo, gitRepo, tagName, sha1, refname); err != nil { return fmt.Errorf("unable to PushUpdateAddTag: %q to Repo[%d:%s/%s]: %w", tagName, repo.ID, repo.OwnerName, repo.Name, err) } @@ -328,7 +328,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) } // PushUpdateAddTag must be called for any push actions to add tag -func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagName, sha1, refname string) error { +func PushUpdateAddTag(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, tagName, sha1, refname string) error { tag, err := gitRepo.GetTagWithID(sha1, tagName) if err != nil { return fmt.Errorf("unable to GetTag: %w", err) @@ -350,7 +350,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN createdAt := time.Unix(1, 0) if sig != nil { - author, err = user_model.GetUserByEmail(sig.Email) + author, err = user_model.GetUserByEmail(ctx, sig.Email) if err != nil && !user_model.IsErrUserNotExist(err) { return fmt.Errorf("unable to GetUserByEmail for %q: %w", sig.Email, err) } diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 7b997b49d9e7d..c9ebf6502081c 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -25,7 +25,6 @@ import ( activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/avatars" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" @@ -86,8 +85,8 @@ func NewFuncMap() []template.FuncMap { "AssetVersion": func() string { return setting.AssetVersion }, - "DisableGravatar": func() bool { - return system_model.GetSettingBool(system_model.KeyPictureDisableGravatar) + "DisableGravatar": func(ctx context.Context) bool { + return system_model.GetSettingBool(ctx, system_model.KeyPictureDisableGravatar) }, "DefaultShowFullName": func() bool { return setting.UI.DefaultShowFullName @@ -606,22 +605,22 @@ func AvatarHTML(src string, size int, class, name string) template.HTML { } // Avatar renders user avatars. args: user, size (int), class (string) -func Avatar(item interface{}, others ...interface{}) template.HTML { +func Avatar(ctx context.Context, item interface{}, others ...interface{}) template.HTML { size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) switch t := item.(type) { case *user_model.User: - src := t.AvatarLinkWithSize(size * setting.Avatar.RenderedSizeFactor) + src := t.AvatarLinkWithSize(ctx, size*setting.Avatar.RenderedSizeFactor) if src != "" { return AvatarHTML(src, size, class, t.DisplayName()) } case *repo_model.Collaborator: - src := t.AvatarLinkWithSize(size * setting.Avatar.RenderedSizeFactor) + src := t.AvatarLinkWithSize(ctx, size*setting.Avatar.RenderedSizeFactor) if src != "" { return AvatarHTML(src, size, class, t.DisplayName()) } case *organization.Organization: - src := t.AsUser().AvatarLinkWithSize(size * setting.Avatar.RenderedSizeFactor) + src := t.AsUser().AvatarLinkWithSize(ctx, size*setting.Avatar.RenderedSizeFactor) if src != "" { return AvatarHTML(src, size, class, t.AsUser().DisplayName()) } @@ -631,9 +630,9 @@ func Avatar(item interface{}, others ...interface{}) template.HTML { } // AvatarByAction renders user avatars from action. args: action, size (int), class (string) -func AvatarByAction(action *activities_model.Action, others ...interface{}) template.HTML { - action.LoadActUser(db.DefaultContext) - return Avatar(action.ActUser, others...) +func AvatarByAction(ctx context.Context, action *activities_model.Action, others ...interface{}) template.HTML { + action.LoadActUser(ctx) + return Avatar(ctx, action.ActUser, others...) } // RepoAvatar renders repo avatars. args: repo, size(int), class (string) @@ -648,9 +647,9 @@ func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTM } // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string) -func AvatarByEmail(email, name string, others ...interface{}) template.HTML { +func AvatarByEmail(ctx context.Context, email, name string, others ...interface{}) template.HTML { size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) - src := avatars.GenerateEmailAvatarFastLink(email, size*setting.Avatar.RenderedSizeFactor) + src := avatars.GenerateEmailAvatarFastLink(ctx, email, size*setting.Avatar.RenderedSizeFactor) if src != "" { return AvatarHTML(src, size, class, name) diff --git a/routers/api/v1/activitypub/person.go b/routers/api/v1/activitypub/person.go index 80855809856c2..492930b84929b 100644 --- a/routers/api/v1/activitypub/person.go +++ b/routers/api/v1/activitypub/person.go @@ -55,7 +55,7 @@ func Person(ctx *context.APIContext) { person.Icon = ap.Image{ Type: ap.ImageType, MediaType: "image/png", - URL: ap.IRI(ctx.ContextUser.AvatarLink()), + URL: ap.IRI(ctx.ContextUser.AvatarLink(ctx)), } person.Inbox = ap.IRI(link + "/inbox") diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index ff66244184421..6d50a12674a33 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -74,7 +74,7 @@ func CreateOrg(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToOrganization(org)) + ctx.JSON(http.StatusCreated, convert.ToOrganization(ctx, org)) } // GetAllOrgs API for getting information of all the organizations @@ -114,7 +114,7 @@ func GetAllOrgs(ctx *context.APIContext) { } orgs := make([]*api.Organization, len(users)) for i := range users { - orgs[i] = convert.ToOrganization(organization.OrgFromUser(users[i])) + orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(users[i])) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 6b48ce4a9d4d3..4ee1a320ccb16 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -140,7 +140,7 @@ func CreateUser(ctx *context.APIContext) { if form.SendNotify { mailer.SendRegisterNotifyMail(u) } - ctx.JSON(http.StatusCreated, convert.ToUser(u, ctx.Doer)) + ctx.JSON(http.StatusCreated, convert.ToUser(ctx, u, ctx.Doer)) } // EditUser api for modifying a user's information @@ -280,7 +280,7 @@ func EditUser(ctx *context.APIContext) { } log.Trace("Account profile updated by admin (%s): %s", ctx.Doer.Name, ctx.ContextUser.Name) - ctx.JSON(http.StatusOK, convert.ToUser(ctx.ContextUser, ctx.Doer)) + ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.ContextUser, ctx.Doer)) } // DeleteUser api for deleting a user @@ -441,7 +441,7 @@ func GetAllUsers(ctx *context.APIContext) { results := make([]*api.User, len(users)) for i := range users { - results[i] = convert.ToUser(users[i], ctx.Doer) + results[i] = convert.ToUser(ctx, users[i], ctx.Doer) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) diff --git a/routers/api/v1/org/member.go b/routers/api/v1/org/member.go index 33c9944978038..e4afd7f3c67f4 100644 --- a/routers/api/v1/org/member.go +++ b/routers/api/v1/org/member.go @@ -39,7 +39,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) { apiMembers := make([]*api.User, len(members)) for i, member := range members { - apiMembers[i] = convert.ToUser(member, ctx.Doer) + apiMembers[i] = convert.ToUser(ctx, member, ctx.Doer) } ctx.SetTotalCountHeader(count) diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index a1b071d4887a2..75420dcc43a8f 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -42,7 +42,7 @@ func listUserOrgs(ctx *context.APIContext, u *user_model.User) { apiOrgs := make([]*api.Organization, len(orgs)) for i := range orgs { - apiOrgs[i] = convert.ToOrganization(orgs[i]) + apiOrgs[i] = convert.ToOrganization(ctx, orgs[i]) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) @@ -211,7 +211,7 @@ func GetAll(ctx *context.APIContext) { } orgs := make([]*api.Organization, len(publicOrgs)) for i := range publicOrgs { - orgs[i] = convert.ToOrganization(organization.OrgFromUser(publicOrgs[i])) + orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(publicOrgs[i])) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) @@ -274,7 +274,7 @@ func Create(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToOrganization(org)) + ctx.JSON(http.StatusCreated, convert.ToOrganization(ctx, org)) } // Get get an organization @@ -298,7 +298,7 @@ func Get(ctx *context.APIContext) { ctx.NotFound("HasOrgOrUserVisible", nil) return } - ctx.JSON(http.StatusOK, convert.ToOrganization(ctx.Org.Organization)) + ctx.JSON(http.StatusOK, convert.ToOrganization(ctx, ctx.Org.Organization)) } // Edit change an organization's information @@ -344,7 +344,7 @@ func Edit(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToOrganization(org)) + ctx.JSON(http.StatusOK, convert.ToOrganization(ctx, org)) } // Delete an organization diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index 8f87e82764857..686e48ece3d64 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -58,7 +58,7 @@ func ListTeams(ctx *context.APIContext) { return } - apiTeams, err := convert.ToTeams(teams, false) + apiTeams, err := convert.ToTeams(ctx, teams, false) if err != nil { ctx.Error(http.StatusInternalServerError, "ConvertToTeams", err) return @@ -97,7 +97,7 @@ func ListUserTeams(ctx *context.APIContext) { return } - apiTeams, err := convert.ToTeams(teams, true) + apiTeams, err := convert.ToTeams(ctx, teams, true) if err != nil { ctx.Error(http.StatusInternalServerError, "ConvertToTeams", err) return @@ -125,7 +125,7 @@ func GetTeam(ctx *context.APIContext) { // "200": // "$ref": "#/responses/Team" - apiTeam, err := convert.ToTeam(ctx.Org.Team) + apiTeam, err := convert.ToTeam(ctx, ctx.Org.Team) if err != nil { ctx.InternalServerError(err) return @@ -223,7 +223,7 @@ func CreateTeam(ctx *context.APIContext) { return } - apiTeam, err := convert.ToTeam(team) + apiTeam, err := convert.ToTeam(ctx, team) if err != nil { ctx.InternalServerError(err) return @@ -306,7 +306,7 @@ func EditTeam(ctx *context.APIContext) { return } - apiTeam, err := convert.ToTeam(team) + apiTeam, err := convert.ToTeam(ctx, team) if err != nil { ctx.InternalServerError(err) return @@ -383,7 +383,7 @@ func GetTeamMembers(ctx *context.APIContext) { members := make([]*api.User, len(teamMembers)) for i, member := range teamMembers { - members[i] = convert.ToUser(member, ctx.Doer) + members[i] = convert.ToUser(ctx, member, ctx.Doer) } ctx.SetTotalCountHeader(int64(ctx.Org.Team.NumMembers)) @@ -428,7 +428,7 @@ func GetTeamMember(ctx *context.APIContext) { ctx.NotFound() return } - ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.Doer)) + ctx.JSON(http.StatusOK, convert.ToUser(ctx, u, ctx.Doer)) } // AddTeamMember api for add a member to a team @@ -779,7 +779,7 @@ func SearchTeam(ctx *context.APIContext) { return } - apiTeams, err := convert.ToTeams(teams, false) + apiTeams, err := convert.ToTeams(ctx, teams, false) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 46fcc2fcd3668..83836f7fe6e76 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -76,7 +76,7 @@ func GetBranch(ctx *context.APIContext) { return } - br, err := convert.ToBranch(ctx.Repo.Repository, branch, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) + br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) if err != nil { ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) return @@ -212,7 +212,7 @@ func CreateBranch(ctx *context.APIContext) { return } - br, err := convert.ToBranch(ctx.Repo.Repository, branch, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) + br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) if err != nil { ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) return @@ -281,7 +281,7 @@ func ListBranches(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetProtectedBranchBy", err) return } - apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) + apiBranch, err := convert.ToBranch(ctx, ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) if err != nil { ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) return diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 293778420bc2b..942d4c799fbd3 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -65,7 +65,7 @@ func ListCollaborators(ctx *context.APIContext) { users := make([]*api.User, len(collaborators)) for i, collaborator := range collaborators { - users[i] = convert.ToUser(collaborator.User, ctx.Doer) + users[i] = convert.ToUser(ctx, collaborator.User, ctx.Doer) } ctx.SetTotalCountHeader(count) @@ -287,7 +287,7 @@ func GetRepoPermissions(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToUserAndPermission(collaborator, ctx.ContextUser, permission.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToUserAndPermission(ctx, collaborator, ctx.ContextUser, permission.AccessMode)) } // GetReviewers return all users that can be requested to review in this repo @@ -317,7 +317,7 @@ func GetReviewers(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "ListCollaborators", err) return } - ctx.JSON(http.StatusOK, convert.ToUsers(ctx.Doer, reviewers)) + ctx.JSON(http.StatusOK, convert.ToUsers(ctx, ctx.Doer, reviewers)) } // GetAssignees return all users that have write access and can be assigned to issues @@ -347,5 +347,5 @@ func GetAssignees(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "ListCollaborators", err) return } - ctx.JSON(http.StatusOK, convert.ToUsers(ctx.Doer, assignees)) + ctx.JSON(http.StatusOK, convert.ToUsers(ctx, ctx.Doer, assignees)) } diff --git a/routers/api/v1/repo/commits.go b/routers/api/v1/repo/commits.go index 68a92ca2a840b..22b013e7dc3b8 100644 --- a/routers/api/v1/repo/commits.go +++ b/routers/api/v1/repo/commits.go @@ -69,7 +69,7 @@ func getCommit(ctx *context.APIContext, identifier string) { return } - json, err := convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, commit, nil, true) + json, err := convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, commit, nil, true) if err != nil { ctx.Error(http.StatusInternalServerError, "toCommit", err) return @@ -217,7 +217,7 @@ func GetAllCommits(ctx *context.APIContext) { for i, commit := range commits { // Create json struct - apiCommits[i], err = convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, commit, userCache, stat) + apiCommits[i], err = convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, commit, userCache, stat) if err != nil { ctx.Error(http.StatusInternalServerError, "toCommit", err) return diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 757ae7247bf71..c55a237c5f6bb 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -173,7 +173,7 @@ func TestHook(ctx *context.APIContext) { return } - commit := convert.ToPayloadCommit(ctx.Repo.Repository, ctx.Repo.Commit) + commit := convert.ToPayloadCommit(ctx, ctx.Repo.Repository, ctx.Repo.Commit) commitID := ctx.Repo.Commit.ID.String() if err := webhook_service.PrepareWebhook(ctx, hook, webhook.HookEventPush, &api.PushPayload{ @@ -185,8 +185,8 @@ func TestHook(ctx *context.APIContext) { TotalCommits: 1, HeadCommit: commit, Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone), - Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), - Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), + Pusher: convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone), + Sender: convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone), }); err != nil { ctx.Error(http.StatusInternalServerError, "PrepareWebhook: ", err) return diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index 40c92998d19c4..3d14343d476ac 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -103,7 +103,7 @@ func ListIssueComments(ctx *context.APIContext) { apiComments := make([]*api.Comment, len(comments)) for i, comment := range comments { comment.Issue = issue - apiComments[i] = convert.ToComment(comments[i]) + apiComments[i] = convert.ToComment(ctx, comments[i]) } ctx.SetTotalCountHeader(totalCount) @@ -308,7 +308,7 @@ func ListRepoIssueComments(ctx *context.APIContext) { return } for i := range comments { - apiComments[i] = convert.ToComment(comments[i]) + apiComments[i] = convert.ToComment(ctx, comments[i]) } ctx.SetTotalCountHeader(totalCount) @@ -368,7 +368,7 @@ func CreateIssueComment(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToComment(comment)) + ctx.JSON(http.StatusCreated, convert.ToComment(ctx, comment)) } // GetIssueComment Get a comment by ID @@ -436,7 +436,7 @@ func GetIssueComment(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToComment(comment)) + ctx.JSON(http.StatusOK, convert.ToComment(ctx, comment)) } // EditIssueComment modify a comment of an issue @@ -561,7 +561,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) return } - ctx.JSON(http.StatusOK, convert.ToComment(comment)) + ctx.JSON(http.StatusOK, convert.ToComment(ctx, comment)) } // DeleteIssueComment delete a comment from an issue diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go index 1b998a5354241..921f6e53f9c00 100644 --- a/routers/api/v1/repo/issue_reaction.go +++ b/routers/api/v1/repo/issue_reaction.go @@ -80,7 +80,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) { var result []api.Reaction for _, r := range reactions { result = append(result, api.Reaction{ - User: convert.ToUser(r.User, ctx.Doer), + User: convert.ToUser(ctx, r.User, ctx.Doer), Reaction: r.Type, Created: r.CreatedUnix.AsTime(), }) @@ -202,7 +202,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp ctx.Error(http.StatusForbidden, err.Error(), err) } else if issues_model.IsErrReactionAlreadyExist(err) { ctx.JSON(http.StatusOK, api.Reaction{ - User: convert.ToUser(ctx.Doer, ctx.Doer), + User: convert.ToUser(ctx, ctx.Doer, ctx.Doer), Reaction: reaction.Type, Created: reaction.CreatedUnix.AsTime(), }) @@ -213,7 +213,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp } ctx.JSON(http.StatusCreated, api.Reaction{ - User: convert.ToUser(ctx.Doer, ctx.Doer), + User: convert.ToUser(ctx, ctx.Doer, ctx.Doer), Reaction: reaction.Type, Created: reaction.CreatedUnix.AsTime(), }) @@ -298,7 +298,7 @@ func GetIssueReactions(ctx *context.APIContext) { var result []api.Reaction for _, r := range reactions { result = append(result, api.Reaction{ - User: convert.ToUser(r.User, ctx.Doer), + User: convert.ToUser(ctx, r.User, ctx.Doer), Reaction: r.Type, Created: r.CreatedUnix.AsTime(), }) @@ -412,7 +412,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i ctx.Error(http.StatusForbidden, err.Error(), err) } else if issues_model.IsErrReactionAlreadyExist(err) { ctx.JSON(http.StatusOK, api.Reaction{ - User: convert.ToUser(ctx.Doer, ctx.Doer), + User: convert.ToUser(ctx, ctx.Doer, ctx.Doer), Reaction: reaction.Type, Created: reaction.CreatedUnix.AsTime(), }) @@ -423,7 +423,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i } ctx.JSON(http.StatusCreated, api.Reaction{ - User: convert.ToUser(ctx.Doer, ctx.Doer), + User: convert.ToUser(ctx, ctx.Doer, ctx.Doer), Reaction: reaction.Type, Created: reaction.CreatedUnix.AsTime(), }) diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 6d22c82652ef0..107119eb08f51 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -280,7 +280,7 @@ func GetIssueSubscribers(ctx *context.APIContext) { } apiUsers := make([]*api.User, 0, len(users)) for _, v := range users { - apiUsers = append(apiUsers, convert.ToUser(v, ctx.Doer)) + apiUsers = append(apiUsers, convert.ToUser(ctx, v, ctx.Doer)) } count, err := issues_model.CountIssueWatchers(ctx, issue.ID) diff --git a/routers/api/v1/repo/notes.go b/routers/api/v1/repo/notes.go index 8eaa503ff7cc5..2d1f3291f8b9c 100644 --- a/routers/api/v1/repo/notes.go +++ b/routers/api/v1/repo/notes.go @@ -68,7 +68,7 @@ func getNote(ctx *context.APIContext, identifier string) { return } - cmt, err := convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, note.Commit, nil, true) + cmt, err := convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, note.Commit, nil, true) if err != nil { ctx.Error(http.StatusInternalServerError, "ToCommit", err) return diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 1b1aba17d9299..975ccae1b1776 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -1310,7 +1310,7 @@ func GetPullRequestCommits(ctx *context.APIContext) { apiCommits := make([]*api.Commit, 0, end-start) for i := start; i < end; i++ { - apiCommit, err := convert.ToCommit(ctx.Repo.Repository, baseGitRepo, commits[i], userCache, true) + apiCommit, err := convert.ToCommit(ctx, ctx.Repo.Repository, baseGitRepo, commits[i], userCache, true) if err != nil { ctx.ServerError("toCommit", err) return diff --git a/routers/api/v1/repo/pull_review.go b/routers/api/v1/repo/pull_review.go index 96dc1fc2dee1d..f6acaa780a02e 100644 --- a/routers/api/v1/repo/pull_review.go +++ b/routers/api/v1/repo/pull_review.go @@ -673,7 +673,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions for _, r := range opts.Reviewers { var reviewer *user_model.User if strings.Contains(r, "@") { - reviewer, err = user_model.GetUserByEmail(r) + reviewer, err = user_model.GetUserByEmail(ctx, r) } else { reviewer, err = user_model.GetUserByName(ctx, r) } diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index d0b20102f7a4f..671721ba65e47 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -64,7 +64,7 @@ func GetRelease(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(http.StatusOK, convert.ToRelease(release)) + ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release)) } // ListReleases list a repository's releases @@ -133,7 +133,7 @@ func ListReleases(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - rels[i] = convert.ToRelease(release) + rels[i] = convert.ToRelease(ctx, release) } filteredCount, err := repo_model.CountReleasesByRepoID(ctx.Repo.Repository.ID, opts) @@ -231,7 +231,7 @@ func CreateRelease(ctx *context.APIContext) { return } } - ctx.JSON(http.StatusCreated, convert.ToRelease(rel)) + ctx.JSON(http.StatusCreated, convert.ToRelease(ctx, rel)) } // EditRelease edit a release @@ -316,7 +316,7 @@ func EditRelease(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(http.StatusOK, convert.ToRelease(rel)) + ctx.JSON(http.StatusOK, convert.ToRelease(ctx, rel)) } // DeleteRelease delete a release from a repository diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index 5aaea693c03b3..597578aac578b 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -117,7 +117,7 @@ func ListReleaseAttachments(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(http.StatusOK, convert.ToRelease(release).Attachments) + ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release).Attachments) } // CreateReleaseAttachment creates an attachment and saves the given file diff --git a/routers/api/v1/repo/release_tags.go b/routers/api/v1/repo/release_tags.go index 7cc846fdc4437..051ee8f22ec0a 100644 --- a/routers/api/v1/repo/release_tags.go +++ b/routers/api/v1/repo/release_tags.go @@ -63,7 +63,7 @@ func GetReleaseByTag(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(http.StatusOK, convert.ToRelease(release)) + ctx.JSON(http.StatusOK, convert.ToRelease(ctx, release)) } // DeleteReleaseByTag delete a release from a repository by tag name diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go index c7b2eb01ff65f..e4cf0ffab67d3 100644 --- a/routers/api/v1/repo/star.go +++ b/routers/api/v1/repo/star.go @@ -50,7 +50,7 @@ func ListStargazers(ctx *context.APIContext) { } users := make([]*api.User, len(stargazers)) for i, stargazer := range stargazers { - users[i] = convert.ToUser(stargazer, ctx.Doer) + users[i] = convert.ToUser(ctx, stargazer, ctx.Doer) } ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumStars)) diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index 6cd369898eba0..613fbee409298 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -50,7 +50,7 @@ func ListSubscribers(ctx *context.APIContext) { } users := make([]*api.User, len(subscribers)) for i, subscriber := range subscribers { - users[i] = convert.ToUser(subscriber, ctx.Doer) + users[i] = convert.ToUser(ctx, subscriber, ctx.Doer) } ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumWatches)) diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index cb65e2b651b0e..b28b6b0b91d73 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -107,7 +107,7 @@ func GetAnnotatedTag(ctx *context.APIContext) { if err != nil { ctx.Error(http.StatusBadRequest, "GetAnnotatedTag", err) } - ctx.JSON(http.StatusOK, convert.ToAnnotatedTag(ctx.Repo.Repository, tag, commit)) + ctx.JSON(http.StatusOK, convert.ToAnnotatedTag(ctx, ctx.Repo.Repository, tag, commit)) } } diff --git a/routers/api/v1/repo/teams.go b/routers/api/v1/repo/teams.go index eafe4236ec3ac..01292f18d8aed 100644 --- a/routers/api/v1/repo/teams.go +++ b/routers/api/v1/repo/teams.go @@ -47,7 +47,7 @@ func ListTeams(ctx *context.APIContext) { return } - apiTeams, err := convert.ToTeams(teams, false) + apiTeams, err := convert.ToTeams(ctx, teams, false) if err != nil { ctx.InternalServerError(err) return @@ -98,7 +98,7 @@ func IsTeam(ctx *context.APIContext) { } if models.HasRepository(team, ctx.Repo.Repository.ID) { - apiTeam, err := convert.ToTeam(team) + apiTeam, err := convert.ToTeam(ctx, team) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/repo/transfer.go b/routers/api/v1/repo/transfer.go index aec398da7a416..ded8edd41c067 100644 --- a/routers/api/v1/repo/transfer.go +++ b/routers/api/v1/repo/transfer.go @@ -81,7 +81,7 @@ func Transfer(ctx *context.APIContext) { return } - org := convert.ToOrganization(organization.OrgFromUser(newOwner)) + org := convert.ToOrganization(ctx, organization.OrgFromUser(newOwner)) for _, tID := range *opts.TeamIDs { team, err := organization.GetTeamByID(ctx, tID) if err != nil { diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index e9d4ae478b3d2..bc03b22ea78ef 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -17,7 +17,7 @@ import ( func responseAPIUsers(ctx *context.APIContext, users []*user_model.User) { apiUsers := make([]*api.User, len(users)) for i := range users { - apiUsers[i] = convert.ToUser(users[i], ctx.Doer) + apiUsers[i] = convert.ToUser(ctx, users[i], ctx.Doer) } ctx.JSON(http.StatusOK, &apiUsers) } diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index 8aad69884fd8b..f90c65817d28d 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -4,6 +4,7 @@ package user import ( + std_ctx "context" "net/http" asymkey_model "code.gitea.io/gitea/models/asymkey" @@ -21,20 +22,20 @@ import ( ) // appendPrivateInformation appends the owner and key type information to api.PublicKey -func appendPrivateInformation(apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) { +func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) { if key.Type == asymkey_model.KeyTypeDeploy { apiKey.KeyType = "deploy" } else if key.Type == asymkey_model.KeyTypeUser { apiKey.KeyType = "user" if defaultUser.ID == key.OwnerID { - apiKey.Owner = convert.ToUser(defaultUser, defaultUser) + apiKey.Owner = convert.ToUser(ctx, defaultUser, defaultUser) } else { user, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) if err != nil { return apiKey, err } - apiKey.Owner = convert.ToUser(user, user) + apiKey.Owner = convert.ToUser(ctx, user, user) } } else { apiKey.KeyType = "unknown" @@ -87,7 +88,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) { for i := range keys { apiKeys[i] = convert.ToPublicKey(apiLink, keys[i]) if ctx.Doer.IsAdmin || ctx.Doer.ID == keys[i].OwnerID { - apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], user) + apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], user) } } @@ -187,7 +188,7 @@ func GetPublicKey(ctx *context.APIContext) { apiLink := composePublicKeysAPILink() apiKey := convert.ToPublicKey(apiLink, key) if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID { - apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Doer) + apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer) } ctx.JSON(http.StatusOK, apiKey) } @@ -208,7 +209,7 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid apiLink := composePublicKeysAPILink() apiKey := convert.ToPublicKey(apiLink, key) if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID { - apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Doer) + apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer) } ctx.JSON(http.StatusCreated, apiKey) } diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 55f3df40b9cca..6fd4b3a95cf08 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -74,7 +74,7 @@ func Search(ctx *context.APIContext) { ctx.JSON(http.StatusOK, map[string]interface{}{ "ok": true, - "data": convert.ToUsers(ctx.Doer, users), + "data": convert.ToUsers(ctx, ctx.Doer, users), }) } @@ -102,7 +102,7 @@ func GetInfo(ctx *context.APIContext) { ctx.NotFound("GetUserByName", user_model.ErrUserNotExist{Name: ctx.Params(":username")}) return } - ctx.JSON(http.StatusOK, convert.ToUser(ctx.ContextUser, ctx.Doer)) + ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.ContextUser, ctx.Doer)) } // GetAuthenticatedUser get current user's information @@ -116,7 +116,7 @@ func GetAuthenticatedUser(ctx *context.APIContext) { // "200": // "$ref": "#/responses/User" - ctx.JSON(http.StatusOK, convert.ToUser(ctx.Doer, ctx.Doer)) + ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.Doer, ctx.Doer)) } // GetUserHeatmapData is the handler to get a users heatmap diff --git a/routers/install/install.go b/routers/install/install.go index ab37f9ba35fed..1ec407c59facd 100644 --- a/routers/install/install.go +++ b/routers/install/install.go @@ -441,7 +441,7 @@ func SubmitInstall(ctx *context.Context) { cfg.Section("server").Key("OFFLINE_MODE").SetValue(fmt.Sprint(form.OfflineMode)) // if you are reinstalling, this maybe not right because of missing version - if err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, strconv.FormatBool(form.DisableGravatar)); err != nil { + if err := system_model.SetSettingNoVersion(ctx, system_model.KeyPictureDisableGravatar, strconv.FormatBool(form.DisableGravatar)); err != nil { ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form) return } diff --git a/routers/private/hook_verification.go b/routers/private/hook_verification.go index 7b9550dfddddf..8ccde4f3d7549 100644 --- a/routers/private/hook_verification.go +++ b/routers/private/hook_verification.go @@ -101,7 +101,7 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error { if err != nil { return err } - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { cancel() return &errUnverifiedCommit{ diff --git a/routers/web/admin/config.go b/routers/web/admin/config.go index eaa02588ca5c9..a0288380c7b0e 100644 --- a/routers/web/admin/config.go +++ b/routers/web/admin/config.go @@ -201,7 +201,7 @@ func ChangeConfig(ctx *context.Context) { value := ctx.FormString("value") version := ctx.FormInt("version") - if err := system_model.SetSetting(&system_model.Setting{ + if err := system_model.SetSetting(ctx, &system_model.Setting{ SettingKey: key, SettingValue: value, Version: version, diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index 6c409c6b9df8b..ef300547a11d9 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -58,7 +58,7 @@ func LinkAccount(ctx *context.Context) { ctx.Data["email"] = email if len(email) != 0 { - u, err := user_model.GetUserByEmail(email) + u, err := user_model.GetUserByEmail(ctx, email) if err != nil && !user_model.IsErrUserNotExist(err) { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 3d70ca9a50677..9ede271e1b16a 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -222,7 +222,7 @@ func newAccessTokenResponse(ctx stdContext.Context, grant *auth.OAuth2Grant, ser idToken.Name = user.GetDisplayName() idToken.PreferredUsername = user.Name idToken.Profile = user.HTMLURL() - idToken.Picture = user.AvatarLink() + idToken.Picture = user.AvatarLink(ctx) idToken.Website = user.Website idToken.Locale = user.Language idToken.UpdatedAt = user.UpdatedUnix @@ -283,7 +283,7 @@ func InfoOAuth(ctx *context.Context) { Name: ctx.Doer.FullName, Username: ctx.Doer.Name, Email: ctx.Doer.Email, - Picture: ctx.Doer.AvatarLink(), + Picture: ctx.Doer.AvatarLink(ctx), } groups, err := getOAuthGroupsForUser(ctx.Doer) diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go index f544b6535687d..aff2e5f780857 100644 --- a/routers/web/auth/openid.go +++ b/routers/web/auth/openid.go @@ -197,7 +197,7 @@ func signInOpenIDVerify(ctx *context.Context) { log.Trace("User has email=%s and nickname=%s", email, nickname) if email != "" { - u, err = user_model.GetUserByEmail(email) + u, err = user_model.GetUserByEmail(ctx, email) if err != nil { if !user_model.IsErrUserNotExist(err) { ctx.RenderWithErr(err.Error(), tplSignInOpenID, &forms.SignInOpenIDForm{ diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index e546c77bc91e9..16628645d7288 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -59,7 +59,7 @@ func ForgotPasswdPost(ctx *context.Context) { email := ctx.FormString("email") ctx.Data["Email"] = email - u, err := user_model.GetUserByEmail(email) + u, err := user_model.GetUserByEmail(ctx, email) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale) diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index d9754633bfd97..1ed7980145491 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -401,7 +401,7 @@ func SearchTeam(ctx *context.Context) { return } - apiTeams, err := convert.ToTeams(teams, false) + apiTeams, err := convert.ToTeams(ctx, teams, false) if err != nil { log.Error("convert ToTeams failed: %v", err) ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index 50bfa9d3bd289..88e135812b20b 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -199,7 +199,7 @@ func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) (map[st } // populate commit email addresses to later look up avatars. - for _, c := range user_model.ValidateCommitsWithEmails(commits) { + for _, c := range user_model.ValidateCommitsWithEmails(ctx, commits) { commitNames[c.ID.String()] = c } @@ -262,9 +262,9 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m var avatar string if commit.User != nil { - avatar = string(templates.Avatar(commit.User, 18, "mr-3")) + avatar = string(templates.Avatar(ctx, commit.User, 18, "mr-3")) } else { - avatar = string(templates.AvatarByEmail(commit.Author.Email, commit.Author.Name, 18, "mr-3")) + avatar = string(templates.AvatarByEmail(ctx, commit.Author.Email, commit.Author.Name, 18, "mr-3")) } br.Avatar = gotemplate.HTML(avatar) diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index 6eda3fca10b32..843b1d8dfd01d 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -75,7 +75,7 @@ func Commits(ctx *context.Context) { ctx.ServerError("CommitsByRange", err) return } - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commits, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository) ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name @@ -138,7 +138,7 @@ func Graph(ctx *context.Context) { return } - if err := graph.LoadAndProcessCommits(ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil { + if err := graph.LoadAndProcessCommits(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil { ctx.ServerError("LoadAndProcessCommits", err) return } @@ -194,7 +194,7 @@ func SearchCommits(ctx *context.Context) { return } ctx.Data["CommitCount"] = len(commits) - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commits, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository) ctx.Data["Keyword"] = query if all { @@ -235,7 +235,7 @@ func FileHistory(ctx *context.Context) { ctx.ServerError("CommitsByFileAndRange", err) return } - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commits, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository) ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name @@ -343,9 +343,9 @@ func Diff(ctx *context.Context) { ctx.Data["CommitStatus"] = git_model.CalcCommitStatus(statuses) ctx.Data["CommitStatuses"] = statuses - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) ctx.Data["Verification"] = verification - ctx.Data["Author"] = user_model.ValidateCommitWithEmail(commit) + ctx.Data["Author"] = user_model.ValidateCommitWithEmail(ctx, commit) ctx.Data["Parents"] = parents ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0 @@ -361,7 +361,7 @@ func Diff(ctx *context.Context) { if err == nil { ctx.Data["Note"] = string(charset.ToUTF8WithFallback(note.Message)) ctx.Data["NoteCommit"] = note.Commit - ctx.Data["NoteAuthor"] = user_model.ValidateCommitWithEmail(note.Commit) + ctx.Data["NoteAuthor"] = user_model.ValidateCommitWithEmail(ctx, note.Commit) } ctx.Data["BranchName"], err = commit.GetBranchName() diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index d95eeaecc9774..8d45f8d674444 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -636,7 +636,7 @@ func PrepareCompareDiff( return false } - commits := git_model.ConvertFromGitCommit(ci.CompareInfo.Commits, ci.HeadRepo) + commits := git_model.ConvertFromGitCommit(ctx, ci.CompareInfo.Commits, ci.HeadRepo) ctx.Data["Commits"] = commits ctx.Data["CommitCount"] = len(commits) diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 100e343de49b0..3a68d69d56614 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -3236,5 +3236,5 @@ func handleTeamMentions(ctx *context.Context) { ctx.Data["MentionableTeams"] = teams ctx.Data["MentionableTeamsOrg"] = ctx.Repo.Owner.Name - ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.AvatarLink() + ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.AvatarLink(ctx) } diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index a18f9f6a56a53..c0fab2cead625 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -659,7 +659,7 @@ func ViewPullCommits(ctx *context.Context) { ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name - commits := git_model.ConvertFromGitCommit(prInfo.Commits, ctx.Repo.Repository) + commits := git_model.ConvertFromGitCommit(ctx, prInfo.Commits, ctx.Repo.Repository) ctx.Data["Commits"] = commits ctx.Data["CommitCount"] = len(commits) diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 915944e4d5db9..ebb4b9e8fd343 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -840,7 +840,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri ctx.Data["LatestCommit"] = latestCommit if latestCommit != nil { - verification := asymkey_model.ParseCommitWithSignature(latestCommit) + verification := asymkey_model.ParseCommitWithSignature(ctx, latestCommit) if err := asymkey_model.CalculateTrustStatus(verification, ctx.Repo.Repository.GetTrustModel(), func(user *user_model.User) (bool, error) { return repo_model.IsOwnerMemberCollaborator(ctx.Repo.Repository, user.ID) @@ -849,7 +849,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri return nil } ctx.Data["LatestCommitVerification"] = verification - ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(latestCommit) + ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(ctx, latestCommit) statuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, latestCommit.ID.String(), db.ListOptions{}) if err != nil { diff --git a/routers/web/repo/webhook.go b/routers/web/repo/webhook.go index 2b6f107fafd11..3d8684fa2fc65 100644 --- a/routers/web/repo/webhook.go +++ b/routers/web/repo/webhook.go @@ -659,7 +659,7 @@ func TestWebhook(ctx *context.Context) { } } - apiUser := convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone) + apiUser := convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone) apiCommit := &api.PayloadCommit{ ID: commit.ID.String(), diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go index b50a4be802043..fe2becb7bb473 100644 --- a/routers/web/repo/wiki.go +++ b/routers/web/repo/wiki.go @@ -368,7 +368,7 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) ctx.ServerError("CommitsByFileAndRange", err) return nil, nil } - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commitsHistory, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commitsHistory, ctx.Repo.Repository) pager := context.NewPagination(int(commitsCount), setting.Git.CommitsRangeSize, page, 5) pager.SetDefaultParams(ctx) diff --git a/routers/web/user/avatar.go b/routers/web/user/avatar.go index 20c2ef3e47bfd..2dba74822e531 100644 --- a/routers/web/user/avatar.go +++ b/routers/web/user/avatar.go @@ -41,7 +41,7 @@ func AvatarByUserName(ctx *context.Context) { user = user_model.NewGhostUser() } - cacheableRedirect(ctx, user.AvatarLinkWithSize(size)) + cacheableRedirect(ctx, user.AvatarLinkWithSize(ctx, size)) } // AvatarByEmailHash redirects the browser to the email avatar link @@ -53,5 +53,5 @@ func AvatarByEmailHash(ctx *context.Context) { return } size := ctx.FormInt("size") - cacheableRedirect(ctx, avatars.GenerateEmailAvatarFinalLink(email, size)) + cacheableRedirect(ctx, avatars.GenerateEmailAvatarFinalLink(ctx, email, size)) } diff --git a/routers/web/user/search.go b/routers/web/user/search.go index f9b0e07358645..c5c3aa75f084e 100644 --- a/routers/web/user/search.go +++ b/routers/web/user/search.go @@ -38,6 +38,6 @@ func Search(ctx *context.Context) { ctx.JSON(http.StatusOK, map[string]interface{}{ "ok": true, - "data": convert.ToUsers(ctx.Doer, users), + "data": convert.ToUsers(ctx, ctx.Doer, users), }) } diff --git a/routers/web/webfinger.go b/routers/web/webfinger.go index 935832aa1f205..a8e816d7b7ab4 100644 --- a/routers/web/webfinger.go +++ b/routers/web/webfinger.go @@ -60,7 +60,7 @@ func WebfingerQuery(ctx *context.Context) { u, err = user_model.GetUserByName(ctx, parts[0]) case "mailto": - u, err = user_model.GetUserByEmailContext(ctx, resource.Opaque) + u, err = user_model.GetUserByEmail(ctx, resource.Opaque) if u != nil && u.KeepEmailPrivate { err = user_model.ErrUserNotExist{} } @@ -99,7 +99,7 @@ func WebfingerQuery(ctx *context.Context) { }, { Rel: "http://webfinger.net/rel/avatar", - Href: u.AvatarLink(), + Href: u.AvatarLink(ctx), }, { Rel: "self", diff --git a/services/asymkey/sign.go b/services/asymkey/sign.go index 227e0bbf33880..3ebd871ed625e 100644 --- a/services/asymkey/sign.go +++ b/services/asymkey/sign.go @@ -207,7 +207,7 @@ Loop: if commit.Signature == nil { return false, "", nil, &ErrWontSign{parentSigned} } - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { return false, "", nil, &ErrWontSign{parentSigned} } @@ -260,7 +260,7 @@ Loop: if commit.Signature == nil { return false, "", nil, &ErrWontSign{parentSigned} } - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { return false, "", nil, &ErrWontSign{parentSigned} } @@ -332,7 +332,7 @@ Loop: if err != nil { return false, "", nil, err } - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { return false, "", nil, &ErrWontSign{baseSigned} } @@ -348,7 +348,7 @@ Loop: if err != nil { return false, "", nil, err } - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { return false, "", nil, &ErrWontSign{headSigned} } @@ -364,7 +364,7 @@ Loop: if err != nil { return false, "", nil, err } - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { return false, "", nil, &ErrWontSign{commitsSigned} } @@ -378,7 +378,7 @@ Loop: return false, "", nil, err } for _, commit := range commitList { - verification := asymkey_model.ParseCommitWithSignature(commit) + verification := asymkey_model.ParseCommitWithSignature(ctx, commit) if !verification.Verified { return false, "", nil, &ErrWontSign{commitsSigned} } diff --git a/services/auth/reverseproxy.go b/services/auth/reverseproxy.go index 0206ccdf667df..91acff90cc6c8 100644 --- a/services/auth/reverseproxy.go +++ b/services/auth/reverseproxy.go @@ -91,7 +91,7 @@ func (r *ReverseProxy) getUserFromAuthEmail(req *http.Request) *user_model.User } log.Trace("ReverseProxy Authorization: Found email: %s", email) - user, err := user_model.GetUserByEmail(email) + user, err := user_model.GetUserByEmail(req.Context(), email) if err != nil { // Do not allow auto-registration, we don't have a username here if !user_model.IsErrUserNotExist(err) { diff --git a/services/convert/convert.go b/services/convert/convert.go index 756a1f95d9054..93b5a04ad9ece 100644 --- a/services/convert/convert.go +++ b/services/convert/convert.go @@ -41,7 +41,7 @@ func ToEmail(email *user_model.EmailAddress) *api.Email { } // ToBranch convert a git.Commit and git.Branch to an api.Branch -func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) { +func ToBranch(ctx context.Context, repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) { if bp == nil { var hasPerm bool var canPush bool @@ -61,7 +61,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git return &api.Branch{ Name: b.Name, - Commit: ToPayloadCommit(repo, c), + Commit: ToPayloadCommit(ctx, repo, c), Protected: false, RequiredApprovals: 0, EnableStatusCheck: false, @@ -73,7 +73,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git branch := &api.Branch{ Name: b.Name, - Commit: ToPayloadCommit(repo, c), + Commit: ToPayloadCommit(ctx, repo, c), Protected: true, RequiredApprovals: bp.RequiredApprovals, EnableStatusCheck: bp.EnableStatusCheck, @@ -164,8 +164,8 @@ func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag { } // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification -func ToVerification(c *git.Commit) *api.PayloadCommitVerification { - verif := asymkey_model.ParseCommitWithSignature(c) +func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerification { + verif := asymkey_model.ParseCommitWithSignature(ctx, c) commitVerification := &api.PayloadCommitVerification{ Verified: verif.Verified, Reason: verif.Reason, @@ -298,10 +298,10 @@ func ToDeployKey(apiLink string, key *asymkey_model.DeployKey) *api.DeployKey { } // ToOrganization convert user_model.User to api.Organization -func ToOrganization(org *organization.Organization) *api.Organization { +func ToOrganization(ctx context.Context, org *organization.Organization) *api.Organization { return &api.Organization{ ID: org.ID, - AvatarURL: org.AsUser().AvatarLink(), + AvatarURL: org.AsUser().AvatarLink(ctx), Name: org.Name, UserName: org.Name, FullName: org.FullName, @@ -314,8 +314,8 @@ func ToOrganization(org *organization.Organization) *api.Organization { } // ToTeam convert models.Team to api.Team -func ToTeam(team *organization.Team, loadOrg ...bool) (*api.Team, error) { - teams, err := ToTeams([]*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0]) +func ToTeam(ctx context.Context, team *organization.Team, loadOrg ...bool) (*api.Team, error) { + teams, err := ToTeams(ctx, []*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0]) if err != nil || len(teams) == 0 { return nil, err } @@ -323,7 +323,7 @@ func ToTeam(team *organization.Team, loadOrg ...bool) (*api.Team, error) { } // ToTeams convert models.Team list to api.Team list -func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) { +func ToTeams(ctx context.Context, teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) { if len(teams) == 0 || teams[0] == nil { return nil, nil } @@ -353,7 +353,7 @@ func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) { if err != nil { return nil, err } - apiOrg = ToOrganization(org) + apiOrg = ToOrganization(ctx, org) cache[teams[i].OrgID] = apiOrg } apiTeams[i].Organization = apiOrg @@ -363,7 +363,7 @@ func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) { } // ToAnnotatedTag convert git.Tag to api.AnnotatedTag -func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag { +func ToAnnotatedTag(ctx context.Context, repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag { return &api.AnnotatedTag{ Tag: t.Name, SHA: t.ID.String(), @@ -371,7 +371,7 @@ func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api Message: t.Message, URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()), Tagger: ToCommitUser(t.Tagger), - Verification: ToVerification(c), + Verification: ToVerification(ctx, c), } } diff --git a/services/convert/git_commit.go b/services/convert/git_commit.go index 59842e40209b1..20fb8c2565398 100644 --- a/services/convert/git_commit.go +++ b/services/convert/git_commit.go @@ -4,6 +4,7 @@ package convert import ( + "context" "net/url" "time" @@ -37,16 +38,16 @@ func ToCommitMeta(repo *repo_model.Repository, tag *git.Tag) *api.CommitMeta { } // ToPayloadCommit convert a git.Commit to api.PayloadCommit -func ToPayloadCommit(repo *repo_model.Repository, c *git.Commit) *api.PayloadCommit { +func ToPayloadCommit(ctx context.Context, repo *repo_model.Repository, c *git.Commit) *api.PayloadCommit { authorUsername := "" - if author, err := user_model.GetUserByEmail(c.Author.Email); err == nil { + if author, err := user_model.GetUserByEmail(ctx, c.Author.Email); err == nil { authorUsername = author.Name } else if !user_model.IsErrUserNotExist(err) { log.Error("GetUserByEmail: %v", err) } committerUsername := "" - if committer, err := user_model.GetUserByEmail(c.Committer.Email); err == nil { + if committer, err := user_model.GetUserByEmail(ctx, c.Committer.Email); err == nil { committerUsername = committer.Name } else if !user_model.IsErrUserNotExist(err) { log.Error("GetUserByEmail: %v", err) @@ -67,12 +68,12 @@ func ToPayloadCommit(repo *repo_model.Repository, c *git.Commit) *api.PayloadCom UserName: committerUsername, }, Timestamp: c.Author.When, - Verification: ToVerification(c), + Verification: ToVerification(ctx, c), } } // ToCommit convert a git.Commit to api.Commit -func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, userCache map[string]*user_model.User, stat bool) (*api.Commit, error) { +func ToCommit(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, userCache map[string]*user_model.User, stat bool) (*api.Commit, error) { var apiAuthor, apiCommitter *api.User // Retrieve author and committer information @@ -87,13 +88,13 @@ func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git. } if ok { - apiAuthor = ToUser(cacheAuthor, nil) + apiAuthor = ToUser(ctx, cacheAuthor, nil) } else { - author, err := user_model.GetUserByEmail(commit.Author.Email) + author, err := user_model.GetUserByEmail(ctx, commit.Author.Email) if err != nil && !user_model.IsErrUserNotExist(err) { return nil, err } else if err == nil { - apiAuthor = ToUser(author, nil) + apiAuthor = ToUser(ctx, author, nil) if userCache != nil { userCache[commit.Author.Email] = author } @@ -109,13 +110,13 @@ func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git. } if ok { - apiCommitter = ToUser(cacheCommitter, nil) + apiCommitter = ToUser(ctx, cacheCommitter, nil) } else { - committer, err := user_model.GetUserByEmail(commit.Committer.Email) + committer, err := user_model.GetUserByEmail(ctx, commit.Committer.Email) if err != nil && !user_model.IsErrUserNotExist(err) { return nil, err } else if err == nil { - apiCommitter = ToUser(committer, nil) + apiCommitter = ToUser(ctx, committer, nil) if userCache != nil { userCache[commit.Committer.Email] = committer } @@ -161,7 +162,7 @@ func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git. SHA: commit.ID.String(), Created: commit.Committer.When, }, - Verification: ToVerification(commit), + Verification: ToVerification(ctx, commit), }, Author: apiAuthor, Committer: apiCommitter, diff --git a/services/convert/issue.go b/services/convert/issue.go index f3af03ed949ff..02f25e6e0e6a7 100644 --- a/services/convert/issue.go +++ b/services/convert/issue.go @@ -41,7 +41,7 @@ func ToAPIIssue(ctx context.Context, issue *issues_model.Issue) *api.Issue { URL: issue.APIURL(), HTMLURL: issue.HTMLURL(), Index: issue.Index, - Poster: ToUser(issue.Poster, nil), + Poster: ToUser(ctx, issue.Poster, nil), Title: issue.Title, Body: issue.Content, Attachments: ToAttachments(issue.Attachments), @@ -77,9 +77,9 @@ func ToAPIIssue(ctx context.Context, issue *issues_model.Issue) *api.Issue { } if len(issue.Assignees) > 0 { for _, assignee := range issue.Assignees { - apiIssue.Assignees = append(apiIssue.Assignees, ToUser(assignee, nil)) + apiIssue.Assignees = append(apiIssue.Assignees, ToUser(ctx, assignee, nil)) } - apiIssue.Assignee = ToUser(issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee` + apiIssue.Assignee = ToUser(ctx, issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee` } if issue.IsPull { if err := issue.LoadPullRequest(ctx); err != nil { diff --git a/services/convert/issue_comment.go b/services/convert/issue_comment.go index 6044cbcf61343..2810c6c9bc91b 100644 --- a/services/convert/issue_comment.go +++ b/services/convert/issue_comment.go @@ -14,10 +14,10 @@ import ( ) // ToComment converts a issues_model.Comment to the api.Comment format -func ToComment(c *issues_model.Comment) *api.Comment { +func ToComment(ctx context.Context, c *issues_model.Comment) *api.Comment { return &api.Comment{ ID: c.ID, - Poster: ToUser(c.Poster, nil), + Poster: ToUser(ctx, c.Poster, nil), HTMLURL: c.HTMLURL(), IssueURL: c.IssueURL(), PRURL: c.PRURL(), @@ -69,7 +69,7 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_ comment := &api.TimelineComment{ ID: c.ID, Type: c.Type.String(), - Poster: ToUser(c.Poster, nil), + Poster: ToUser(ctx, c.Poster, nil), HTMLURL: c.HTMLURL(), IssueURL: c.IssueURL(), PRURL: c.PRURL(), @@ -131,7 +131,7 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_ log.Error("LoadPoster: %v", err) return nil } - comment.RefComment = ToComment(com) + comment.RefComment = ToComment(ctx, com) } if c.Label != nil { @@ -157,14 +157,14 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_ } if c.Assignee != nil { - comment.Assignee = ToUser(c.Assignee, nil) + comment.Assignee = ToUser(ctx, c.Assignee, nil) } if c.AssigneeTeam != nil { - comment.AssigneeTeam, _ = ToTeam(c.AssigneeTeam) + comment.AssigneeTeam, _ = ToTeam(ctx, c.AssigneeTeam) } if c.ResolveDoer != nil { - comment.ResolveDoer = ToUser(c.ResolveDoer, nil) + comment.ResolveDoer = ToUser(ctx, c.ResolveDoer, nil) } if c.DependentIssue != nil { diff --git a/services/convert/package.go b/services/convert/package.go index 68ae6f4e62dbf..7d170ccc253d5 100644 --- a/services/convert/package.go +++ b/services/convert/package.go @@ -28,9 +28,9 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m return &api.Package{ ID: pd.Version.ID, - Owner: ToUser(pd.Owner, doer), + Owner: ToUser(ctx, pd.Owner, doer), Repository: repo, - Creator: ToUser(pd.Creator, doer), + Creator: ToUser(ctx, pd.Creator, doer), Type: string(pd.Package.Type), Name: pd.Package.Name, Version: pd.Version.Version, diff --git a/services/convert/pull.go b/services/convert/pull.go index db0add6cdee7b..0e55d5a214de2 100644 --- a/services/convert/pull.go +++ b/services/convert/pull.go @@ -197,7 +197,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u if pr.HasMerged { apiPullRequest.Merged = pr.MergedUnix.AsTimePtr() apiPullRequest.MergedCommitID = &pr.MergedCommitID - apiPullRequest.MergedBy = ToUser(pr.Merger, nil) + apiPullRequest.MergedBy = ToUser(ctx, pr.Merger, nil) } return apiPullRequest diff --git a/services/convert/pull_review.go b/services/convert/pull_review.go index 66c5018ee2a9c..5d5d5d883c997 100644 --- a/services/convert/pull_review.go +++ b/services/convert/pull_review.go @@ -21,14 +21,14 @@ func ToPullReview(ctx context.Context, r *issues_model.Review, doer *user_model. r.Reviewer = user_model.NewGhostUser() } - apiTeam, err := ToTeam(r.ReviewerTeam) + apiTeam, err := ToTeam(ctx, r.ReviewerTeam) if err != nil { return nil, err } result := &api.PullReview{ ID: r.ID, - Reviewer: ToUser(r.Reviewer, doer), + Reviewer: ToUser(ctx, r.Reviewer, doer), ReviewerTeam: apiTeam, State: api.ReviewStateUnknown, Body: r.Content, @@ -93,8 +93,8 @@ func ToPullReviewCommentList(ctx context.Context, review *issues_model.Review, d apiComment := &api.PullReviewComment{ ID: comment.ID, Body: comment.Content, - Poster: ToUser(comment.Poster, doer), - Resolver: ToUser(comment.ResolveDoer, doer), + Poster: ToUser(ctx, comment.Poster, doer), + Resolver: ToUser(ctx, comment.ResolveDoer, doer), ReviewID: review.ID, Created: comment.CreatedUnix.AsTime(), Updated: comment.UpdatedUnix.AsTime(), diff --git a/services/convert/release.go b/services/convert/release.go index 3afa53c03f5fa..ca28aa0d6b07c 100644 --- a/services/convert/release.go +++ b/services/convert/release.go @@ -4,12 +4,14 @@ package convert import ( + "context" + repo_model "code.gitea.io/gitea/models/repo" api "code.gitea.io/gitea/modules/structs" ) // ToRelease convert a repo_model.Release to api.Release -func ToRelease(r *repo_model.Release) *api.Release { +func ToRelease(ctx context.Context, r *repo_model.Release) *api.Release { return &api.Release{ ID: r.ID, TagName: r.TagName, @@ -24,7 +26,7 @@ func ToRelease(r *repo_model.Release) *api.Release { IsPrerelease: r.IsPrerelease, CreatedAt: r.CreatedUnix.AsTime(), PublishedAt: r.CreatedUnix.AsTime(), - Publisher: ToUser(r.Publisher, nil), + Publisher: ToUser(ctx, r.Publisher, nil), Attachments: ToAttachments(r.Attachments), } } diff --git a/services/convert/repository.go b/services/convert/repository.go index ce53a6669237c..d8143b235ec5a 100644 --- a/services/convert/repository.go +++ b/services/convert/repository.go @@ -124,7 +124,7 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc if err := t.LoadAttributes(ctx); err != nil { log.Warn("LoadAttributes of RepoTransfer: %v", err) } else { - transfer = ToRepoTransfer(t) + transfer = ToRepoTransfer(ctx, t) } } } @@ -138,7 +138,7 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc return &api.Repository{ ID: repo.ID, - Owner: ToUserWithAccessMode(repo.Owner, mode), + Owner: ToUserWithAccessMode(ctx, repo.Owner, mode), Name: repo.Name, FullName: repo.FullName(), Description: repo.Description, @@ -191,12 +191,12 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.Acc } // ToRepoTransfer convert a models.RepoTransfer to a structs.RepeTransfer -func ToRepoTransfer(t *models.RepoTransfer) *api.RepoTransfer { - teams, _ := ToTeams(t.Teams, false) +func ToRepoTransfer(ctx context.Context, t *models.RepoTransfer) *api.RepoTransfer { + teams, _ := ToTeams(ctx, t.Teams, false) return &api.RepoTransfer{ - Doer: ToUser(t.Doer, nil), - Recipient: ToUser(t.Recipient, nil), + Doer: ToUser(ctx, t.Doer, nil), + Recipient: ToUser(ctx, t.Recipient, nil), Teams: teams, } } diff --git a/services/convert/status.go b/services/convert/status.go index 5fcf04074f889..301521b51a523 100644 --- a/services/convert/status.go +++ b/services/convert/status.go @@ -26,7 +26,7 @@ func ToCommitStatus(ctx context.Context, status *git_model.CommitStatus) *api.Co if status.CreatorID != 0 { creator, _ := user_model.GetUserByID(ctx, status.CreatorID) - apiStatus.Creator = ToUser(creator, nil) + apiStatus.Creator = ToUser(ctx, creator, nil) } return apiStatus diff --git a/services/convert/user.go b/services/convert/user.go index 6b90539fd9814..79fcba0176f9a 100644 --- a/services/convert/user.go +++ b/services/convert/user.go @@ -4,6 +4,8 @@ package convert import ( + "context" + "code.gitea.io/gitea/models/perm" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -11,7 +13,7 @@ import ( // ToUser convert user_model.User to api.User // if doer is set, private information is added if the doer has the permission to see it -func ToUser(user, doer *user_model.User) *api.User { +func ToUser(ctx context.Context, user, doer *user_model.User) *api.User { if user == nil { return nil } @@ -21,36 +23,36 @@ func ToUser(user, doer *user_model.User) *api.User { signed = true authed = doer.ID == user.ID || doer.IsAdmin } - return toUser(user, signed, authed) + return toUser(ctx, user, signed, authed) } // ToUsers convert list of user_model.User to list of api.User -func ToUsers(doer *user_model.User, users []*user_model.User) []*api.User { +func ToUsers(ctx context.Context, doer *user_model.User, users []*user_model.User) []*api.User { result := make([]*api.User, len(users)) for i := range users { - result[i] = ToUser(users[i], doer) + result[i] = ToUser(ctx, users[i], doer) } return result } // ToUserWithAccessMode convert user_model.User to api.User // AccessMode is not none show add some more information -func ToUserWithAccessMode(user *user_model.User, accessMode perm.AccessMode) *api.User { +func ToUserWithAccessMode(ctx context.Context, user *user_model.User, accessMode perm.AccessMode) *api.User { if user == nil { return nil } - return toUser(user, accessMode != perm.AccessModeNone, false) + return toUser(ctx, user, accessMode != perm.AccessModeNone, false) } // toUser convert user_model.User to api.User // signed shall only be set if requester is logged in. authed shall only be set if user is site admin or user himself -func toUser(user *user_model.User, signed, authed bool) *api.User { +func toUser(ctx context.Context, user *user_model.User, signed, authed bool) *api.User { result := &api.User{ ID: user.ID, UserName: user.Name, FullName: user.FullName, Email: user.GetEmail(), - AvatarURL: user.AvatarLink(), + AvatarURL: user.AvatarLink(ctx), Created: user.CreatedUnix.AsTime(), Restricted: user.IsRestricted, Location: user.Location, @@ -97,9 +99,9 @@ func User2UserSettings(user *user_model.User) api.UserSettings { } // ToUserAndPermission return User and its collaboration permission for a repository -func ToUserAndPermission(user, doer *user_model.User, accessMode perm.AccessMode) api.RepoCollaboratorPermission { +func ToUserAndPermission(ctx context.Context, user, doer *user_model.User, accessMode perm.AccessMode) api.RepoCollaboratorPermission { return api.RepoCollaboratorPermission{ - User: ToUser(user, doer), + User: ToUser(ctx, user, doer), Permission: accessMode.String(), RoleName: accessMode.String(), } diff --git a/services/pull/check.go b/services/pull/check.go index 86460cd49cad0..f39119b24ddb5 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -255,7 +255,7 @@ func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool { pr.MergedCommitID = commit.ID.String() pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix()) pr.Status = issues_model.PullRequestStatusManuallyMerged - merger, _ := user_model.GetUserByEmail(commit.Author.Email) + merger, _ := user_model.GetUserByEmail(ctx, commit.Author.Email) // When the commit author is unknown set the BaseRepo owner as merger if merger == nil { diff --git a/services/release/release.go b/services/release/release.go index 13042cd3ac2e8..eec03b46883e5 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -102,7 +102,7 @@ func createTag(ctx context.Context, gitRepo *git.Repository, rel *repo_model.Rel } if rel.PublisherID <= 0 { - u, err := user_model.GetUserByEmailContext(ctx, commit.Author.Email) + u, err := user_model.GetUserByEmail(ctx, commit.Author.Email) if err == nil { rel.PublisherID = u.ID } diff --git a/services/repository/files/cherry_pick.go b/services/repository/files/cherry_pick.go index 6bc67e2636992..c1c5bfb617689 100644 --- a/services/repository/files/cherry_pick.go +++ b/services/repository/files/cherry_pick.go @@ -115,7 +115,7 @@ func CherryPick(ctx context.Context, repo *repo_model.Repository, doer *user_mod } fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil - verification := GetPayloadCommitVerification(commit) + verification := GetPayloadCommitVerification(ctx, commit) fileResponse := &structs.FileResponse{ Commit: fileCommitResponse, Verification: verification, diff --git a/services/repository/files/commit.go b/services/repository/files/commit.go index 74f9eb868d005..5f7d6ec8a24d4 100644 --- a/services/repository/files/commit.go +++ b/services/repository/files/commit.go @@ -66,9 +66,9 @@ func CountDivergingCommits(ctx context.Context, repo *repo_model.Repository, bra } // GetPayloadCommitVerification returns the verification information of a commit -func GetPayloadCommitVerification(commit *git.Commit) *structs.PayloadCommitVerification { +func GetPayloadCommitVerification(ctx context.Context, commit *git.Commit) *structs.PayloadCommitVerification { verification := &structs.PayloadCommitVerification{} - commitVerification := asymkey_model.ParseCommitWithSignature(commit) + commitVerification := asymkey_model.ParseCommitWithSignature(ctx, commit) if commit.Signature != nil { verification.Signature = commit.Signature.Signature verification.Payload = commit.Signature.Payload diff --git a/services/repository/files/file.go b/services/repository/files/file.go index ddd64a5399d71..2bac4372d378c 100644 --- a/services/repository/files/file.go +++ b/services/repository/files/file.go @@ -21,7 +21,7 @@ import ( func GetFileResponseFromCommit(ctx context.Context, repo *repo_model.Repository, commit *git.Commit, branch, treeName string) (*api.FileResponse, error) { fileContents, _ := GetContents(ctx, repo, treeName, branch, false) // ok if fails, then will be nil fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil - verification := GetPayloadCommitVerification(commit) + verification := GetPayloadCommitVerification(ctx, commit) fileResponse := &api.FileResponse{ Content: fileContents, Commit: fileCommitResponse, diff --git a/services/repository/files/patch.go b/services/repository/files/patch.go index b5eef8c09139b..137b7e5c2bc86 100644 --- a/services/repository/files/patch.go +++ b/services/repository/files/patch.go @@ -182,7 +182,7 @@ func ApplyDiffPatch(ctx context.Context, repo *repo_model.Repository, doer *user } fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil - verification := GetPayloadCommitVerification(commit) + verification := GetPayloadCommitVerification(ctx, commit) fileResponse := &structs.FileResponse{ Commit: fileCommitResponse, Verification: verification, diff --git a/services/repository/push.go b/services/repository/push.go index f1eedb8e08398..4afcdd3ac9e08 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -345,7 +345,7 @@ func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitRepo var ok bool author, ok = emailToUser[sig.Email] if !ok { - author, err = user_model.GetUserByEmailContext(ctx, sig.Email) + author, err = user_model.GetUserByEmail(ctx, sig.Email) if err != nil && !user_model.IsErrUserNotExist(err) { return fmt.Errorf("GetUserByEmail: %w", err) } From 94a7ddf747aad6acefe706664dbc0a90255e4eca Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 31 Dec 2022 20:44:12 +0800 Subject: [PATCH 02/14] Fix test --- models/avatars/avatar_test.go | 11 ++++++----- models/system/setting.go | 8 ++++++-- models/system/setting_test.go | 11 ++++++----- modules/cache/context.go | 12 ++++++------ modules/repository/commits_test.go | 7 ++++--- routers/common/middleware.go | 3 ++- routers/web/auth/oauth_test.go | 4 ++-- services/convert/user_test.go | 9 +++++---- services/user/user_test.go | 2 +- tests/integration/api_comment_test.go | 2 +- tests/integration/api_issue_reaction_test.go | 6 +++--- tests/integration/api_team_test.go | 3 ++- tests/integration/api_team_user_test.go | 3 ++- tests/integration/api_user_orgs_test.go | 9 +++++---- tests/integration/user_avatar_test.go | 3 ++- 15 files changed, 53 insertions(+), 40 deletions(-) diff --git a/models/avatars/avatar_test.go b/models/avatars/avatar_test.go index 29be2ea346c3c..a3cb36d0e1320 100644 --- a/models/avatars/avatar_test.go +++ b/models/avatars/avatar_test.go @@ -7,6 +7,7 @@ import ( "testing" avatars_model "code.gitea.io/gitea/models/avatars" + "code.gitea.io/gitea/models/db" system_model "code.gitea.io/gitea/models/system" "code.gitea.io/gitea/modules/setting" @@ -16,15 +17,15 @@ import ( const gravatarSource = "https://secure.gravatar.com/avatar/" func disableGravatar(t *testing.T) { - err := system_model.SetSettingNoVersion(system_model.KeyPictureEnableFederatedAvatar, "false") + err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureEnableFederatedAvatar, "false") assert.NoError(t, err) - err = system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "true") + err = system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "true") assert.NoError(t, err) system_model.LibravatarService = nil } func enableGravatar(t *testing.T) { - err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "false") + err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "false") assert.NoError(t, err) setting.GravatarSource = gravatarSource err = system_model.Init() @@ -47,11 +48,11 @@ func TestSizedAvatarLink(t *testing.T) { disableGravatar(t) assert.Equal(t, "/testsuburl/assets/img/avatar_default.png", - avatars_model.GenerateEmailAvatarFastLink("gitea@example.com", 100)) + avatars_model.GenerateEmailAvatarFastLink(db.DefaultContext, "gitea@example.com", 100)) enableGravatar(t) assert.Equal(t, "https://secure.gravatar.com/avatar/353cbad9b58e69c96154ad99f92bedc7?d=identicon&s=100", - avatars_model.GenerateEmailAvatarFastLink("gitea@example.com", 100), + avatars_model.GenerateEmailAvatarFastLink(db.DefaultContext, "gitea@example.com", 100), ) } diff --git a/models/system/setting.go b/models/system/setting.go index 3142ff76dd99d..e0c2a1cf6c083 100644 --- a/models/system/setting.go +++ b/models/system/setting.go @@ -124,9 +124,13 @@ func GetSettings(ctx context.Context, keys []string) (map[string]*Setting, error newKeys = append(newKeys, key) } } - settings := make([]*Setting, 0, len(keys)) + if len(newKeys) == 0 { + return settingsMap, nil + } + + settings := make([]*Setting, 0, len(newKeys)) if err := db.GetEngine(db.DefaultContext). - Where(builder.In("setting_key", keys)). + Where(builder.In("setting_key", newKeys)). Find(&settings); err != nil { return nil, err } diff --git a/models/system/setting_test.go b/models/system/setting_test.go index 3ff5ba2520890..f00354ee48b7e 100644 --- a/models/system/setting_test.go +++ b/models/system/setting_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/system" "code.gitea.io/gitea/models/unittest" @@ -20,21 +21,21 @@ func TestSettings(t *testing.T) { newSetting := &system.Setting{SettingKey: keyName, SettingValue: "50"} // create setting - err := system.SetSetting(newSetting) + err := system.SetSetting(db.DefaultContext, newSetting) assert.NoError(t, err) // test about saving unchanged values - err = system.SetSetting(newSetting) + err = system.SetSetting(db.DefaultContext, newSetting) assert.NoError(t, err) // get specific setting - settings, err := system.GetSettings([]string{keyName}) + settings, err := system.GetSettings(db.DefaultContext, []string{keyName}) assert.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, newSetting.SettingValue, settings[strings.ToLower(keyName)].SettingValue) // updated setting updatedSetting := &system.Setting{SettingKey: keyName, SettingValue: "100", Version: newSetting.Version} - err = system.SetSetting(updatedSetting) + err = system.SetSetting(db.DefaultContext, updatedSetting) assert.NoError(t, err) // get all settings @@ -44,7 +45,7 @@ func TestSettings(t *testing.T) { assert.EqualValues(t, updatedSetting.SettingValue, settings[strings.ToLower(updatedSetting.SettingKey)].SettingValue) // delete setting - err = system.DeleteSetting(&system.Setting{SettingKey: strings.ToLower(keyName)}) + err = system.DeleteSetting(db.DefaultContext, &system.Setting{SettingKey: strings.ToLower(keyName)}) assert.NoError(t, err) settings, err = system.GetAllSettings() assert.NoError(t, err) diff --git a/modules/cache/context.go b/modules/cache/context.go index 47de4a9ce5f6f..e268712c34e80 100644 --- a/modules/cache/context.go +++ b/modules/cache/context.go @@ -5,15 +5,15 @@ package cache import "context" -type CacheContext struct { +type cacheContext struct { ctx context.Context Data map[any]map[any]any } -type CacheContextKey struct{} +type cacheContextKey struct{} func WithCacheContext(ctx context.Context) context.Context { - return context.WithValue(ctx, &CacheContextKey{}, &CacheContext{ + return context.WithValue(ctx, &cacheContextKey{}, &cacheContext{ ctx: ctx, Data: make(map[any]map[any]any), }) @@ -23,7 +23,7 @@ func GetContextData(ctx context.Context, tp, key any) any { if ctx == nil { return nil } - if c, ok := ctx.Value(&CacheContextKey{}).(*CacheContext); ok { + if c, ok := ctx.Value(&cacheContextKey{}).(*cacheContext); ok { if c.Data[tp] != nil { return c.Data[tp][key] } @@ -35,7 +35,7 @@ func SetContextData(ctx context.Context, tp, key, value any) { if ctx == nil { return } - if c, ok := ctx.Value(&CacheContextKey{}).(*CacheContext); ok { + if c, ok := ctx.Value(&cacheContextKey{}).(*cacheContext); ok { if c.Data[tp] == nil { c.Data[tp] = make(map[any]any) } @@ -47,7 +47,7 @@ func RemoveContextData(ctx context.Context, tp, key any) { if ctx == nil { return } - if c, ok := ctx.Value(&CacheContextKey{}).(*CacheContext); ok { + if c, ok := ctx.Value(&cacheContextKey{}).(*cacheContext); ok { if c.Data[tp] == nil { c.Data[tp] = make(map[any]any) } diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index 2ae4bc73d2eca..2bd8de38aa1ea 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" system_model "code.gitea.io/gitea/models/system" "code.gitea.io/gitea/models/unittest" @@ -102,7 +103,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { } func enableGravatar(t *testing.T) { - err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "false") + err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "false") assert.NoError(t, err) setting.GravatarSource = "https://secure.gravatar.com/avatar" err = system_model.Init() @@ -136,13 +137,13 @@ func TestPushCommits_AvatarLink(t *testing.T) { assert.Equal(t, "https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?d=identicon&s=84", - pushCommits.AvatarLink("user2@example.com")) + pushCommits.AvatarLink(db.DefaultContext, "user2@example.com")) assert.Equal(t, "https://secure.gravatar.com/avatar/"+ fmt.Sprintf("%x", md5.Sum([]byte("nonexistent@example.com")))+ "?d=identicon&s=84", - pushCommits.AvatarLink("nonexistent@example.com")) + pushCommits.AvatarLink(db.DefaultContext, "nonexistent@example.com")) } func TestCommitToPushCommit(t *testing.T) { diff --git a/routers/common/middleware.go b/routers/common/middleware.go index 0c7838b0ef5be..d664bfccfac9f 100644 --- a/routers/common/middleware.go +++ b/routers/common/middleware.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" + "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" @@ -28,7 +29,7 @@ func Middlewares() []func(http.Handler) http.Handler { ctx, _, finished := process.GetManager().AddTypedContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI), process.RequestProcessType, true) defer finished() - next.ServeHTTP(context.NewResponse(resp), req.WithContext(ctx)) + next.ServeHTTP(context.NewResponse(resp), req.WithContext(cache.WithCacheContext(ctx))) }) }, } diff --git a/routers/web/auth/oauth_test.go b/routers/web/auth/oauth_test.go index 5116b4fc713d2..62f723600d3b1 100644 --- a/routers/web/auth/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -69,7 +69,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.Equal(t, user.Name, oidcToken.Name) assert.Equal(t, user.Name, oidcToken.PreferredUsername) assert.Equal(t, user.HTMLURL(), oidcToken.Profile) - assert.Equal(t, user.AvatarLink(), oidcToken.Picture) + assert.Equal(t, user.AvatarLink(db.DefaultContext), oidcToken.Picture) assert.Equal(t, user.Website, oidcToken.Website) assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt) assert.Equal(t, user.Email, oidcToken.Email) @@ -87,7 +87,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.Equal(t, user.FullName, oidcToken.Name) assert.Equal(t, user.Name, oidcToken.PreferredUsername) assert.Equal(t, user.HTMLURL(), oidcToken.Profile) - assert.Equal(t, user.AvatarLink(), oidcToken.Picture) + assert.Equal(t, user.AvatarLink(db.DefaultContext), oidcToken.Picture) assert.Equal(t, user.Website, oidcToken.Website) assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt) assert.Equal(t, user.Email, oidcToken.Email) diff --git a/services/convert/user_test.go b/services/convert/user_test.go index c3ab4187b724b..4b1effc7aa5fc 100644 --- a/services/convert/user_test.go +++ b/services/convert/user_test.go @@ -6,6 +6,7 @@ package convert import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -18,22 +19,22 @@ func TestUser_ToUser(t *testing.T) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1, IsAdmin: true}) - apiUser := toUser(user1, true, true) + apiUser := toUser(db.DefaultContext, user1, true, true) assert.True(t, apiUser.IsAdmin) assert.Contains(t, apiUser.AvatarURL, "://") user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2, IsAdmin: false}) - apiUser = toUser(user2, true, true) + apiUser = toUser(db.DefaultContext, user2, true, true) assert.False(t, apiUser.IsAdmin) - apiUser = toUser(user1, false, false) + apiUser = toUser(db.DefaultContext, user1, false, false) assert.False(t, apiUser.IsAdmin) assert.EqualValues(t, api.VisibleTypePublic.String(), apiUser.Visibility) user31 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 31, IsAdmin: false, Visibility: api.VisibleTypePrivate}) - apiUser = toUser(user31, true, true) + apiUser = toUser(db.DefaultContext, user31, true, true) assert.False(t, apiUser.IsAdmin) assert.EqualValues(t, api.VisibleTypePrivate.String(), apiUser.Visibility) } diff --git a/services/user/user_test.go b/services/user/user_test.go index 5e052a9df26fb..a25804fcebffd 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -115,7 +115,7 @@ func TestCreateUser_Issue5882(t *testing.T) { assert.NoError(t, user_model.CreateUser(v.user)) - u, err := user_model.GetUserByEmail(v.user.Email) + u, err := user_model.GetUserByEmail(db.DefaultContext, v.user.Email) assert.NoError(t, err) assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index fb2d41223e7e8..e9dd227364bc1 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -126,7 +126,7 @@ func TestAPIGetComment(t *testing.T) { DecodeJSON(t, resp, &apiComment) assert.NoError(t, comment.LoadPoster(db.DefaultContext)) - expect := convert.ToComment(comment) + expect := convert.ToComment(db.DefaultContext, comment) assert.Equal(t, expect.ID, apiComment.ID) assert.Equal(t, expect.Poster.FullName, apiComment.Poster.FullName) diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index 4e2ae3d57dc78..9ef3eacba3b3e 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -64,7 +64,7 @@ func TestAPIIssuesReactions(t *testing.T) { DecodeJSON(t, resp, &apiReactions) expectResponse := make(map[int]api.Reaction) expectResponse[0] = api.Reaction{ - User: convert.ToUser(user2, user2), + User: convert.ToUser(db.DefaultContext, user2, user2), Reaction: "eyes", Created: time.Unix(1573248003, 0), } @@ -124,12 +124,12 @@ func TestAPICommentReactions(t *testing.T) { DecodeJSON(t, resp, &apiReactions) expectResponse := make(map[int]api.Reaction) expectResponse[0] = api.Reaction{ - User: convert.ToUser(user2, user2), + User: convert.ToUser(db.DefaultContext, user2, user2), Reaction: "laugh", Created: time.Unix(1573248004, 0), } expectResponse[1] = api.Reaction{ - User: convert.ToUser(user1, user1), + User: convert.ToUser(db.DefaultContext, user1, user1), Reaction: "laugh", Created: time.Unix(1573248005, 0), } diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index 06d47bf70b056..e6505f343af4a 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -9,6 +9,7 @@ import ( "sort" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" @@ -209,7 +210,7 @@ func checkTeamResponse(t *testing.T, testName string, apiTeam *api.Team, name, d func checkTeamBean(t *testing.T, id int64, name, description string, includesAllRepositories bool, permission string, units []string, unitsMap map[string]string) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: id}) assert.NoError(t, team.GetUnits(), "GetUnits") - apiTeam, err := convert.ToTeam(team) + apiTeam, err := convert.ToTeam(db.DefaultContext, team) assert.NoError(t, err) checkTeamResponse(t, fmt.Sprintf("checkTeamBean/%s_%s", name, description), apiTeam, name, description, includesAllRepositories, permission, units, unitsMap) } diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index a5078aedccb83..a02d83cf0c82f 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -33,7 +34,7 @@ func TestAPITeamUser(t *testing.T) { user2.Created = user2.Created.In(time.Local) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) - expectedUser := convert.ToUser(user, user) + expectedUser := convert.ToUser(db.DefaultContext, user, user) // test time via unix timestamp assert.EqualValues(t, expectedUser.LastLogin.Unix(), user2.LastLogin.Unix()) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 1f9ee2ea6eef6..b9c3d9fe0cf32 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -8,6 +8,7 @@ import ( "net/http" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -34,7 +35,7 @@ func TestUserOrgs(t *testing.T) { Name: user17.Name, UserName: user17.Name, FullName: user17.FullName, - AvatarURL: user17.AvatarLink(), + AvatarURL: user17.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", @@ -45,7 +46,7 @@ func TestUserOrgs(t *testing.T) { Name: user3.Name, UserName: user3.Name, FullName: user3.FullName, - AvatarURL: user3.AvatarLink(), + AvatarURL: user3.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", @@ -99,7 +100,7 @@ func TestMyOrgs(t *testing.T) { Name: user17.Name, UserName: user17.Name, FullName: user17.FullName, - AvatarURL: user17.AvatarLink(), + AvatarURL: user17.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", @@ -110,7 +111,7 @@ func TestMyOrgs(t *testing.T) { Name: user3.Name, UserName: user3.Name, FullName: user3.FullName, - AvatarURL: user3.AvatarLink(), + AvatarURL: user3.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", diff --git a/tests/integration/user_avatar_test.go b/tests/integration/user_avatar_test.go index 08ecb8b74964b..7aeba6a334cf7 100644 --- a/tests/integration/user_avatar_test.go +++ b/tests/integration/user_avatar_test.go @@ -12,6 +12,7 @@ import ( "net/url" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/avatar" @@ -73,7 +74,7 @@ func TestUserAvatar(t *testing.T) { user2 = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo3, is an org - req = NewRequest(t, "GET", user2.AvatarLinkWithSize(0)) + req = NewRequest(t, "GET", user2.AvatarLinkWithSize(db.DefaultContext, 0)) _ = session.MakeRequest(t, req, http.StatusOK) // Can't test if the response matches because the image is re-generated on upload but checking that this at least doesn't give a 404 should be enough. From 109979d1ffe5449011a0bc53da5a3087d47880a2 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 1 Jan 2023 12:37:35 +0800 Subject: [PATCH 03/14] replace template function --- templates/base/head_navbar.tmpl | 4 ++-- templates/explore/organizations.tmpl | 2 +- templates/explore/users.tmpl | 2 +- templates/org/header.tmpl | 2 +- templates/org/home.tmpl | 4 ++-- templates/org/member/members.tmpl | 2 +- templates/org/team/invite.tmpl | 2 +- templates/org/team/members.tmpl | 2 +- templates/repo/commit_page.tmpl | 6 +++--- templates/repo/commits_list.tmpl | 2 +- templates/repo/commits_list_small.tmpl | 2 +- templates/repo/create.tmpl | 6 +++--- templates/repo/editor/commit_form.tmpl | 2 +- templates/repo/forks.tmpl | 2 +- templates/repo/graph/commits.tmpl | 2 +- templates/repo/issue/list.tmpl | 6 +++--- templates/repo/issue/milestone_issues.tmpl | 6 +++--- templates/repo/issue/new_form.tmpl | 4 ++-- templates/repo/issue/view_content.tmpl | 8 ++++---- templates/repo/issue/view_content/comments.tmpl | 8 ++++---- templates/repo/issue/view_content/pull.tmpl | 2 +- templates/repo/issue/view_content/sidebar.tmpl | 12 ++++++------ templates/repo/migrate/codebase.tmpl | 6 +++--- templates/repo/migrate/git.tmpl | 6 +++--- templates/repo/migrate/gitbucket.tmpl | 6 +++--- templates/repo/migrate/gitea.tmpl | 6 +++--- templates/repo/migrate/github.tmpl | 6 +++--- templates/repo/migrate/gitlab.tmpl | 6 +++--- templates/repo/migrate/gogs.tmpl | 6 +++--- templates/repo/migrate/onedev.tmpl | 6 +++--- templates/repo/projects/view.tmpl | 2 +- templates/repo/pulls/fork.tmpl | 6 +++--- templates/repo/release/list.tmpl | 4 ++-- templates/repo/settings/collaboration.tmpl | 2 +- templates/repo/settings/lfs_locks.tmpl | 2 +- templates/repo/settings/protected_branch.tmpl | 6 +++--- templates/repo/settings/tags.tmpl | 4 ++-- templates/repo/shabox_badge.tmpl | 2 +- templates/repo/user_cards.tmpl | 2 +- templates/repo/view_list.tmpl | 2 +- templates/shared/issuelist.tmpl | 2 +- templates/shared/user/avatarlink.tmpl | 2 +- templates/user/dashboard/navbar.tmpl | 6 +++--- templates/user/overview/header.tmpl | 2 +- templates/user/profile.tmpl | 6 +++--- templates/user/project.tmpl | 6 +++--- templates/user/settings/organization.tmpl | 2 +- 47 files changed, 97 insertions(+), 97 deletions(-) diff --git a/templates/base/head_navbar.tmpl b/templates/base/head_navbar.tmpl index 4fc61cf36909b..aadaa83aa5c98 100644 --- a/templates/base/head_navbar.tmpl +++ b/templates/base/head_navbar.tmpl @@ -57,7 +57,7 @@