1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-21 08:31:27 -05:00

Add context.Context to more methods (#21546)

This PR adds a context parameter to a bunch of methods. Some helper
`xxxCtx()` methods got replaced with the normal name now.

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
KN4CK3R 2022-11-19 09:12:33 +01:00 committed by GitHub
parent fefdb7ffd1
commit 044c754ea5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
148 changed files with 1411 additions and 1564 deletions

View file

@ -727,7 +727,7 @@ func runRepoSyncReleases(_ *cli.Context) error {
log.Trace("Synchronizing repository releases (this may take a while)") log.Trace("Synchronizing repository releases (this may take a while)")
for page := 1; ; page++ { for page := 1; ; page++ {
repos, count, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ repos, count, err := repo_model.SearchRepositoryByName(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: repo_model.RepositoryListDefaultPageSize, PageSize: repo_model.RepositoryListDefaultPageSize,
Page: page, Page: page,

View file

@ -461,7 +461,8 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
return err return err
} }
func notifyWatchers(ctx context.Context, actions ...*Action) error { // NotifyWatchers creates batch of actions for every watcher.
func NotifyWatchers(ctx context.Context, actions ...*Action) error {
var watchers []*repo_model.Watch var watchers []*repo_model.Watch
var repo *repo_model.Repository var repo *repo_model.Repository
var err error var err error
@ -565,11 +566,6 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error {
return nil return nil
} }
// NotifyWatchers creates batch of actions for every watcher.
func NotifyWatchers(actions ...*Action) error {
return notifyWatchers(db.DefaultContext, actions...)
}
// NotifyWatchersActions creates batch of actions for every watcher. // NotifyWatchersActions creates batch of actions for every watcher.
func NotifyWatchersActions(acts []*Action) error { func NotifyWatchersActions(acts []*Action) error {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
@ -578,7 +574,7 @@ func NotifyWatchersActions(acts []*Action) error {
} }
defer committer.Close() defer committer.Close()
for _, act := range acts { for _, act := range acts {
if err := notifyWatchers(ctx, act); err != nil { if err := NotifyWatchers(ctx, act); err != nil {
return err return err
} }
} }
@ -603,17 +599,17 @@ func DeleteIssueActions(ctx context.Context, repoID, issueID int64) error {
} }
// CountActionCreatedUnixString count actions where created_unix is an empty string // CountActionCreatedUnixString count actions where created_unix is an empty string
func CountActionCreatedUnixString() (int64, error) { func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
if setting.Database.UseSQLite3 { if setting.Database.UseSQLite3 {
return db.GetEngine(db.DefaultContext).Where(`created_unix = ""`).Count(new(Action)) return db.GetEngine(ctx).Where(`created_unix = ""`).Count(new(Action))
} }
return 0, nil return 0, nil
} }
// FixActionCreatedUnixString set created_unix to zero if it is an empty string // FixActionCreatedUnixString set created_unix to zero if it is an empty string
func FixActionCreatedUnixString() (int64, error) { func FixActionCreatedUnixString(ctx context.Context) (int64, error) {
if setting.Database.UseSQLite3 { if setting.Database.UseSQLite3 {
res, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`) res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View file

@ -188,7 +188,7 @@ func TestNotifyWatchers(t *testing.T) {
RepoID: 1, RepoID: 1,
OpType: activities_model.ActionStarRepo, OpType: activities_model.ActionStarRepo,
} }
assert.NoError(t, activities_model.NotifyWatchers(action)) assert.NoError(t, activities_model.NotifyWatchers(db.DefaultContext, action))
// One watchers are inactive, thus action is only created for user 8, 1, 4, 11 // One watchers are inactive, thus action is only created for user 8, 1, 4, 11
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
@ -256,17 +256,17 @@ func TestConsistencyUpdateAction(t *testing.T) {
// //
// Get rid of incorrectly set created_unix // Get rid of incorrectly set created_unix
// //
count, err := activities_model.CountActionCreatedUnixString() count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 1, count) assert.EqualValues(t, 1, count)
count, err = activities_model.FixActionCreatedUnixString() count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 1, count) assert.EqualValues(t, 1, count)
count, err = activities_model.CountActionCreatedUnixString() count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
count, err = activities_model.FixActionCreatedUnixString() count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)

View file

@ -136,49 +136,41 @@ func GetNotifications(ctx context.Context, options *FindNotificationOptions) (nl
} }
// CountNotifications count all notifications that fit to the given options and ignore pagination. // CountNotifications count all notifications that fit to the given options and ignore pagination.
func CountNotifications(opts *FindNotificationOptions) (int64, error) { func CountNotifications(ctx context.Context, opts *FindNotificationOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.ToCond()).Count(&Notification{}) return db.GetEngine(ctx).Where(opts.ToCond()).Count(&Notification{})
} }
// CreateRepoTransferNotification creates notification for the user a repository was transferred to // CreateRepoTransferNotification creates notification for the user a repository was transferred to
func CreateRepoTransferNotification(doer, newOwner *user_model.User, repo *repo_model.Repository) error { func CreateRepoTransferNotification(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) error {
ctx, committer, err := db.TxContext(db.DefaultContext) return db.AutoTx(ctx, func(ctx context.Context) error {
if err != nil { var notify []*Notification
return err
}
defer committer.Close()
var notify []*Notification if newOwner.IsOrganization() {
users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID)
if newOwner.IsOrganization() { if err != nil || len(users) == 0 {
users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID) return err
if err != nil || len(users) == 0 { }
return err for i := range users {
} notify = append(notify, &Notification{
for i := range users { UserID: users[i].ID,
notify = append(notify, &Notification{ RepoID: repo.ID,
UserID: users[i].ID, Status: NotificationStatusUnread,
UpdatedBy: doer.ID,
Source: NotificationSourceRepository,
})
}
} else {
notify = []*Notification{{
UserID: newOwner.ID,
RepoID: repo.ID, RepoID: repo.ID,
Status: NotificationStatusUnread, Status: NotificationStatusUnread,
UpdatedBy: doer.ID, UpdatedBy: doer.ID,
Source: NotificationSourceRepository, Source: NotificationSourceRepository,
}) }}
} }
} else {
notify = []*Notification{{
UserID: newOwner.ID,
RepoID: repo.ID,
Status: NotificationStatusUnread,
UpdatedBy: doer.ID,
Source: NotificationSourceRepository,
}}
}
if err := db.Insert(ctx, notify); err != nil { return db.Insert(ctx, notify)
return err })
}
return committer.Commit()
} }
// CreateOrUpdateIssueNotifications creates an issue notification // CreateOrUpdateIssueNotifications creates an issue notification
@ -379,11 +371,7 @@ func CountUnread(ctx context.Context, userID int64) int64 {
} }
// LoadAttributes load Repo Issue User and Comment if not loaded // LoadAttributes load Repo Issue User and Comment if not loaded
func (n *Notification) LoadAttributes() (err error) { func (n *Notification) LoadAttributes(ctx context.Context) (err error) {
return n.loadAttributes(db.DefaultContext)
}
func (n *Notification) loadAttributes(ctx context.Context) (err error) {
if err = n.loadRepo(ctx); err != nil { if err = n.loadRepo(ctx); err != nil {
return return
} }
@ -481,10 +469,10 @@ func (n *Notification) APIURL() string {
type NotificationList []*Notification type NotificationList []*Notification
// LoadAttributes load Repo Issue User and Comment if not loaded // LoadAttributes load Repo Issue User and Comment if not loaded
func (nl NotificationList) LoadAttributes() error { func (nl NotificationList) LoadAttributes(ctx context.Context) error {
var err error var err error
for i := 0; i < len(nl); i++ { for i := 0; i < len(nl); i++ {
err = nl[i].LoadAttributes() err = nl[i].LoadAttributes(ctx)
if err != nil && !issues_model.IsErrCommentNotExist(err) { if err != nil && !issues_model.IsErrCommentNotExist(err) {
return err return err
} }
@ -504,7 +492,7 @@ func (nl NotificationList) getPendingRepoIDs() []int64 {
} }
// LoadRepos loads repositories from database // LoadRepos loads repositories from database
func (nl NotificationList) LoadRepos() (repo_model.RepositoryList, []int, error) { func (nl NotificationList) LoadRepos(ctx context.Context) (repo_model.RepositoryList, []int, error) {
if len(nl) == 0 { if len(nl) == 0 {
return repo_model.RepositoryList{}, []int{}, nil return repo_model.RepositoryList{}, []int{}, nil
} }
@ -517,7 +505,7 @@ func (nl NotificationList) LoadRepos() (repo_model.RepositoryList, []int, error)
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := db.GetEngine(db.DefaultContext). rows, err := db.GetEngine(ctx).
In("id", repoIDs[:limit]). In("id", repoIDs[:limit]).
Rows(new(repo_model.Repository)) Rows(new(repo_model.Repository))
if err != nil { if err != nil {
@ -578,7 +566,7 @@ func (nl NotificationList) getPendingIssueIDs() []int64 {
} }
// LoadIssues loads issues from database // LoadIssues loads issues from database
func (nl NotificationList) LoadIssues() ([]int, error) { func (nl NotificationList) LoadIssues(ctx context.Context) ([]int, error) {
if len(nl) == 0 { if len(nl) == 0 {
return []int{}, nil return []int{}, nil
} }
@ -591,7 +579,7 @@ func (nl NotificationList) LoadIssues() ([]int, error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := db.GetEngine(db.DefaultContext). rows, err := db.GetEngine(ctx).
In("id", issueIDs[:limit]). In("id", issueIDs[:limit]).
Rows(new(issues_model.Issue)) Rows(new(issues_model.Issue))
if err != nil { if err != nil {
@ -662,7 +650,7 @@ func (nl NotificationList) getPendingCommentIDs() []int64 {
} }
// LoadComments loads comments from database // LoadComments loads comments from database
func (nl NotificationList) LoadComments() ([]int, error) { func (nl NotificationList) LoadComments(ctx context.Context) ([]int, error) {
if len(nl) == 0 { if len(nl) == 0 {
return []int{}, nil return []int{}, nil
} }
@ -675,7 +663,7 @@ func (nl NotificationList) LoadComments() ([]int, error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := db.GetEngine(db.DefaultContext). rows, err := db.GetEngine(ctx).
In("id", commentIDs[:limit]). In("id", commentIDs[:limit]).
Rows(new(issues_model.Comment)) Rows(new(issues_model.Comment))
if err != nil { if err != nil {
@ -775,8 +763,8 @@ func SetRepoReadBy(ctx context.Context, userID, repoID int64) error {
} }
// SetNotificationStatus change the notification status // SetNotificationStatus change the notification status
func SetNotificationStatus(notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) { func SetNotificationStatus(ctx context.Context, notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) {
notification, err := getNotificationByID(db.DefaultContext, notificationID) notification, err := GetNotificationByID(ctx, notificationID)
if err != nil { if err != nil {
return notification, err return notification, err
} }
@ -787,16 +775,12 @@ func SetNotificationStatus(notificationID int64, user *user_model.User, status N
notification.Status = status notification.Status = status
_, err = db.GetEngine(db.DefaultContext).ID(notificationID).Update(notification) _, err = db.GetEngine(ctx).ID(notificationID).Update(notification)
return notification, err return notification, err
} }
// GetNotificationByID return notification by ID // GetNotificationByID return notification by ID
func GetNotificationByID(notificationID int64) (*Notification, error) { func GetNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) {
return getNotificationByID(db.DefaultContext, notificationID)
}
func getNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) {
notification := new(Notification) notification := new(Notification)
ok, err := db.GetEngine(ctx). ok, err := db.GetEngine(ctx).
Where("id = ?", notificationID). Where("id = ?", notificationID).
@ -813,9 +797,9 @@ func getNotificationByID(ctx context.Context, notificationID int64) (*Notificati
} }
// UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
func UpdateNotificationStatuses(user *user_model.User, currentStatus, desiredStatus NotificationStatus) error { func UpdateNotificationStatuses(ctx context.Context, user *user_model.User, currentStatus, desiredStatus NotificationStatus) error {
n := &Notification{Status: desiredStatus, UpdatedBy: user.ID} n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
_, err := db.GetEngine(db.DefaultContext). _, err := db.GetEngine(ctx).
Where("user_id = ? AND status = ?", user.ID, currentStatus). Where("user_id = ? AND status = ?", user.ID, currentStatus).
Cols("status", "updated_by", "updated_unix"). Cols("status", "updated_by", "updated_unix").
Update(n) Update(n)

View file

@ -82,14 +82,14 @@ func TestSetNotificationStatus(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notf := unittest.AssertExistsAndLoadBean(t, notf := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
_, err := activities_model.SetNotificationStatus(notf.ID, user, activities_model.NotificationStatusPinned) _, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned)
assert.NoError(t, err) assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned}) &activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned})
_, err = activities_model.SetNotificationStatus(1, user, activities_model.NotificationStatusRead) _, err = activities_model.SetNotificationStatus(db.DefaultContext, 1, user, activities_model.NotificationStatusRead)
assert.Error(t, err) assert.Error(t, err)
_, err = activities_model.SetNotificationStatus(unittest.NonexistentID, user, activities_model.NotificationStatusRead) _, err = activities_model.SetNotificationStatus(db.DefaultContext, unittest.NonexistentID, user, activities_model.NotificationStatusRead)
assert.Error(t, err) assert.Error(t, err)
} }
@ -102,7 +102,7 @@ func TestUpdateNotificationStatuses(t *testing.T) {
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
notfPinned := unittest.AssertExistsAndLoadBean(t, notfPinned := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned}) &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned})
assert.NoError(t, activities_model.UpdateNotificationStatuses(user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead)) assert.NoError(t, activities_model.UpdateNotificationStatuses(db.DefaultContext, user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead))
unittest.AssertExistsAndLoadBean(t, unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead}) &activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead})
unittest.AssertExistsAndLoadBean(t, unittest.AssertExistsAndLoadBean(t,

View file

@ -4,11 +4,16 @@
package db package db
import "xorm.io/builder" import (
"context"
"xorm.io/builder"
)
// CountOrphanedObjects count subjects with have no existing refobject anymore // CountOrphanedObjects count subjects with have no existing refobject anymore
func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) { func CountOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) (int64, error) {
return GetEngine(DefaultContext).Table("`"+subject+"`"). return GetEngine(ctx).
Table("`"+subject+"`").
Join("LEFT", "`"+refobject+"`", joinCond). Join("LEFT", "`"+refobject+"`", joinCond).
Where(builder.IsNull{"`" + refobject + "`.id"}). Where(builder.IsNull{"`" + refobject + "`.id"}).
Select("COUNT(`" + subject + "`.`id`)"). Select("COUNT(`" + subject + "`.`id`)").
@ -16,12 +21,12 @@ func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) {
} }
// DeleteOrphanedObjects delete subjects with have no existing refobject anymore // DeleteOrphanedObjects delete subjects with have no existing refobject anymore
func DeleteOrphanedObjects(subject, refobject, joinCond string) error { func DeleteOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) error {
subQuery := builder.Select("`"+subject+"`.id"). subQuery := builder.Select("`"+subject+"`.id").
From("`"+subject+"`"). From("`"+subject+"`").
Join("LEFT", "`"+refobject+"`", joinCond). Join("LEFT", "`"+refobject+"`", joinCond).
Where(builder.IsNull{"`" + refobject + "`.id"}) Where(builder.IsNull{"`" + refobject + "`.id"})
b := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`") b := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`")
_, err := GetEngine(DefaultContext).Exec(b) _, err := GetEngine(ctx).Exec(b)
return err return err
} }

View file

@ -41,11 +41,11 @@ func TestDeleteOrphanedObjects(t *testing.T) {
_, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003}) _, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
assert.NoError(t, err) assert.NoError(t, err)
orphaned, err := db.CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 3, orphaned) assert.EqualValues(t, 3, orphaned)
err = db.DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err) assert.NoError(t, err)
countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})

View file

@ -5,6 +5,7 @@
package db package db
import ( import (
"context"
"fmt" "fmt"
"regexp" "regexp"
@ -12,7 +13,7 @@ import (
) )
// CountBadSequences looks for broken sequences from recreate-table mistakes // CountBadSequences looks for broken sequences from recreate-table mistakes
func CountBadSequences() (int64, error) { func CountBadSequences(_ context.Context) (int64, error) {
if !setting.Database.UsePostgreSQL { if !setting.Database.UsePostgreSQL {
return 0, nil return 0, nil
} }
@ -33,7 +34,7 @@ func CountBadSequences() (int64, error) {
} }
// FixBadSequences fixes for broken sequences from recreate-table mistakes // FixBadSequences fixes for broken sequences from recreate-table mistakes
func FixBadSequences() error { func FixBadSequences(_ context.Context) error {
if !setting.Database.UsePostgreSQL { if !setting.Database.UsePostgreSQL {
return nil return nil
} }

View file

@ -22,7 +22,7 @@ func GetYamlFixturesAccess() (string, error) {
} }
for _, repo := range repos { for _, repo := range repos {
repo.MustOwner() repo.MustOwner(db.DefaultContext)
if err := access_model.RecalculateAccesses(db.DefaultContext, repo); err != nil { if err := access_model.RecalculateAccesses(db.DefaultContext, repo); err != nil {
return "", err return "", err
} }

View file

@ -5,6 +5,7 @@
package git package git
import ( import (
"context"
"regexp" "regexp"
"strings" "strings"
@ -69,13 +70,13 @@ func UpdateProtectedTag(pt *ProtectedTag) error {
} }
// DeleteProtectedTag deletes a protected tag by ID // DeleteProtectedTag deletes a protected tag by ID
func DeleteProtectedTag(pt *ProtectedTag) error { func DeleteProtectedTag(ctx context.Context, pt *ProtectedTag) error {
_, err := db.GetEngine(db.DefaultContext).ID(pt.ID).Delete(&ProtectedTag{}) _, err := db.GetEngine(ctx).ID(pt.ID).Delete(&ProtectedTag{})
return err return err
} }
// IsUserAllowedModifyTag returns true if the user is allowed to modify the tag // IsUserAllowedModifyTag returns true if the user is allowed to modify the tag
func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) { func IsUserAllowedModifyTag(ctx context.Context, pt *ProtectedTag, userID int64) (bool, error) {
if base.Int64sContains(pt.AllowlistUserIDs, userID) { if base.Int64sContains(pt.AllowlistUserIDs, userID) {
return true, nil return true, nil
} }
@ -84,7 +85,7 @@ func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) {
return false, nil return false, nil
} }
in, err := organization.IsUserInTeams(db.DefaultContext, userID, pt.AllowlistTeamIDs) in, err := organization.IsUserInTeams(ctx, userID, pt.AllowlistTeamIDs)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -92,9 +93,9 @@ func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) {
} }
// GetProtectedTags gets all protected tags of the repository // GetProtectedTags gets all protected tags of the repository
func GetProtectedTags(repoID int64) ([]*ProtectedTag, error) { func GetProtectedTags(ctx context.Context, repoID int64) ([]*ProtectedTag, error) {
tags := make([]*ProtectedTag, 0) tags := make([]*ProtectedTag, 0)
return tags, db.GetEngine(db.DefaultContext).Find(&tags, &ProtectedTag{RepoID: repoID}) return tags, db.GetEngine(ctx).Find(&tags, &ProtectedTag{RepoID: repoID})
} }
// GetProtectedTagByID gets the protected tag with the specific id // GetProtectedTagByID gets the protected tag with the specific id
@ -112,7 +113,7 @@ func GetProtectedTagByID(id int64) (*ProtectedTag, error) {
// IsUserAllowedToControlTag checks if a user can control the specific tag. // IsUserAllowedToControlTag checks if a user can control the specific tag.
// It returns true if the tag name is not protected or the user is allowed to control it. // It returns true if the tag name is not protected or the user is allowed to control it.
func IsUserAllowedToControlTag(tags []*ProtectedTag, tagName string, userID int64) (bool, error) { func IsUserAllowedToControlTag(ctx context.Context, tags []*ProtectedTag, tagName string, userID int64) (bool, error) {
isAllowed := true isAllowed := true
for _, tag := range tags { for _, tag := range tags {
err := tag.EnsureCompiledPattern() err := tag.EnsureCompiledPattern()
@ -124,7 +125,7 @@ func IsUserAllowedToControlTag(tags []*ProtectedTag, tagName string, userID int6
continue continue
} }
isAllowed, err = IsUserAllowedModifyTag(tag, userID) isAllowed, err = IsUserAllowedModifyTag(ctx, tag, userID)
if err != nil { if err != nil {
return false, err return false, err
} }

View file

@ -7,6 +7,7 @@ package git_test
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git" git_model "code.gitea.io/gitea/models/git"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
@ -17,29 +18,29 @@ func TestIsUserAllowed(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pt := &git_model.ProtectedTag{} pt := &git_model.ProtectedTag{}
allowed, err := git_model.IsUserAllowedModifyTag(pt, 1) allowed, err := git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, allowed) assert.False(t, allowed)
pt = &git_model.ProtectedTag{ pt = &git_model.ProtectedTag{
AllowlistUserIDs: []int64{1}, AllowlistUserIDs: []int64{1},
} }
allowed, err = git_model.IsUserAllowedModifyTag(pt, 1) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(pt, 2) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, allowed) assert.False(t, allowed)
pt = &git_model.ProtectedTag{ pt = &git_model.ProtectedTag{
AllowlistTeamIDs: []int64{1}, AllowlistTeamIDs: []int64{1},
} }
allowed, err = git_model.IsUserAllowedModifyTag(pt, 1) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, allowed) assert.False(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(pt, 2) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
@ -47,11 +48,11 @@ func TestIsUserAllowed(t *testing.T) {
AllowlistUserIDs: []int64{1}, AllowlistUserIDs: []int64{1},
AllowlistTeamIDs: []int64{1}, AllowlistTeamIDs: []int64{1},
} }
allowed, err = git_model.IsUserAllowedModifyTag(pt, 1) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(pt, 2) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
} }
@ -135,7 +136,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) {
} }
for n, c := range cases { for n, c := range cases {
isAllowed, err := git_model.IsUserAllowedToControlTag(protectedTags, c.name, c.userid) isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
} }
@ -157,7 +158,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) {
} }
for n, c := range cases { for n, c := range cases {
isAllowed, err := git_model.IsUserAllowedToControlTag(protectedTags, c.name, c.userid) isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
} }

View file

@ -48,9 +48,10 @@ func (issue *Issue) LoadAssignees(ctx context.Context) (err error) {
// GetAssigneeIDsByIssue returns the IDs of users assigned to an issue // GetAssigneeIDsByIssue returns the IDs of users assigned to an issue
// but skips joining with `user` for performance reasons. // but skips joining with `user` for performance reasons.
// User permissions must be verified elsewhere if required. // User permissions must be verified elsewhere if required.
func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) { func GetAssigneeIDsByIssue(ctx context.Context, issueID int64) ([]int64, error) {
userIDs := make([]int64, 0, 5) userIDs := make([]int64, 0, 5)
return userIDs, db.GetEngine(db.DefaultContext).Table("issue_assignees"). return userIDs, db.GetEngine(ctx).
Table("issue_assignees").
Cols("assignee_id"). Cols("assignee_id").
Where("issue_id = ?", issueID). Where("issue_id = ?", issueID).
Distinct("assignee_id"). Distinct("assignee_id").
@ -151,7 +152,7 @@ func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (re
} }
// MakeIDsFromAPIAssigneesToAdd returns an array with all assignee IDs // MakeIDsFromAPIAssigneesToAdd returns an array with all assignee IDs
func MakeIDsFromAPIAssigneesToAdd(oneAssignee string, multipleAssignees []string) (assigneeIDs []int64, err error) { func MakeIDsFromAPIAssigneesToAdd(ctx context.Context, oneAssignee string, multipleAssignees []string) (assigneeIDs []int64, err error) {
var requestAssignees []string var requestAssignees []string
// Keeping the old assigning method for compatibility reasons // Keeping the old assigning method for compatibility reasons
@ -165,7 +166,7 @@ func MakeIDsFromAPIAssigneesToAdd(oneAssignee string, multipleAssignees []string
} }
// Get the IDs of all assignees // Get the IDs of all assignees
assigneeIDs, err = user_model.GetUserIDsByNames(requestAssignees, false) assigneeIDs, err = user_model.GetUserIDsByNames(ctx, requestAssignees, false)
return assigneeIDs, err return assigneeIDs, err
} }

View file

@ -71,22 +71,22 @@ func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) {
_ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
_ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd("", []string{""}) IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{""})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []int64{}, IDs) assert.Equal(t, []int64{}, IDs)
_, err = issues_model.MakeIDsFromAPIAssigneesToAdd("", []string{"none_existing_user"}) _, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"none_existing_user"})
assert.Error(t, err) assert.Error(t, err)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd("user1", []string{"user1"}) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user1", []string{"user1"})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []int64{1}, IDs) assert.Equal(t, []int64{1}, IDs)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd("user2", []string{""}) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user2", []string{""})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []int64{2}, IDs) assert.Equal(t, []int64{2}, IDs)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd("", []string{"user1", "user2"}) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"user1", "user2"})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []int64{1, 2}, IDs) assert.Equal(t, []int64{1, 2}, IDs)
} }

View file

@ -309,13 +309,8 @@ type PushActionContent struct {
CommitIDs []string `json:"commit_ids"` CommitIDs []string `json:"commit_ids"`
} }
// LoadIssue loads issue from database // LoadIssue loads the issue reference for the comment
func (c *Comment) LoadIssue() (err error) { func (c *Comment) LoadIssue(ctx context.Context) (err error) {
return c.LoadIssueCtx(db.DefaultContext)
}
// LoadIssueCtx loads issue from database
func (c *Comment) LoadIssueCtx(ctx context.Context) (err error) {
if c.Issue != nil { if c.Issue != nil {
return nil return nil
} }
@ -350,7 +345,8 @@ func (c *Comment) AfterLoad(session *xorm.Session) {
} }
} }
func (c *Comment) loadPoster(ctx context.Context) (err error) { // LoadPoster loads comment poster
func (c *Comment) LoadPoster(ctx context.Context) (err error) {
if c.PosterID <= 0 || c.Poster != nil { if c.PosterID <= 0 || c.Poster != nil {
return nil return nil
} }
@ -381,7 +377,7 @@ func (c *Comment) AfterDelete() {
// HTMLURL formats a URL-string to the issue-comment // HTMLURL formats a URL-string to the issue-comment
func (c *Comment) HTMLURL() string { func (c *Comment) HTMLURL() string {
err := c.LoadIssue() err := c.LoadIssue(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
@ -410,7 +406,7 @@ func (c *Comment) HTMLURL() string {
// APIURL formats a API-string to the issue-comment // APIURL formats a API-string to the issue-comment
func (c *Comment) APIURL() string { func (c *Comment) APIURL() string {
err := c.LoadIssue() err := c.LoadIssue(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
@ -426,7 +422,7 @@ func (c *Comment) APIURL() string {
// IssueURL formats a URL-string to the issue // IssueURL formats a URL-string to the issue
func (c *Comment) IssueURL() string { func (c *Comment) IssueURL() string {
err := c.LoadIssue() err := c.LoadIssue(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
@ -446,7 +442,7 @@ func (c *Comment) IssueURL() string {
// PRURL formats a URL-string to the pull-request // PRURL formats a URL-string to the pull-request
func (c *Comment) PRURL() string { func (c *Comment) PRURL() string {
err := c.LoadIssue() err := c.LoadIssue(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
@ -521,10 +517,10 @@ func (c *Comment) LoadProject() error {
} }
// LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
func (c *Comment) LoadMilestone() error { func (c *Comment) LoadMilestone(ctx context.Context) error {
if c.OldMilestoneID > 0 { if c.OldMilestoneID > 0 {
var oldMilestone Milestone var oldMilestone Milestone
has, err := db.GetEngine(db.DefaultContext).ID(c.OldMilestoneID).Get(&oldMilestone) has, err := db.GetEngine(ctx).ID(c.OldMilestoneID).Get(&oldMilestone)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -534,7 +530,7 @@ func (c *Comment) LoadMilestone() error {
if c.MilestoneID > 0 { if c.MilestoneID > 0 {
var milestone Milestone var milestone Milestone
has, err := db.GetEngine(db.DefaultContext).ID(c.MilestoneID).Get(&milestone) has, err := db.GetEngine(ctx).ID(c.MilestoneID).Get(&milestone)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -544,19 +540,14 @@ func (c *Comment) LoadMilestone() error {
return nil return nil
} }
// LoadPoster loads comment poster
func (c *Comment) LoadPoster() error {
return c.loadPoster(db.DefaultContext)
}
// LoadAttachments loads attachments (it never returns error, the error during `GetAttachmentsByCommentIDCtx` is ignored) // LoadAttachments loads attachments (it never returns error, the error during `GetAttachmentsByCommentIDCtx` is ignored)
func (c *Comment) LoadAttachments() error { func (c *Comment) LoadAttachments(ctx context.Context) error {
if len(c.Attachments) > 0 { if len(c.Attachments) > 0 {
return nil return nil
} }
var err error var err error
c.Attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, c.ID) c.Attachments, err = repo_model.GetAttachmentsByCommentID(ctx, c.ID)
if err != nil { if err != nil {
log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err) log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err)
} }
@ -598,7 +589,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error {
c.Assignee = user_model.NewGhostUser() c.Assignee = user_model.NewGhostUser()
} }
} else if c.AssigneeTeamID > 0 && c.AssigneeTeam == nil { } else if c.AssigneeTeamID > 0 && c.AssigneeTeam == nil {
if err = c.LoadIssue(); err != nil { if err = c.LoadIssue(db.DefaultContext); err != nil {
return err return err
} }
@ -740,7 +731,7 @@ func (c *Comment) UnsignedLine() uint64 {
// CodeCommentURL returns the url to a comment in code // CodeCommentURL returns the url to a comment in code
func (c *Comment) CodeCommentURL() string { func (c *Comment) CodeCommentURL() string {
err := c.LoadIssue() err := c.LoadIssue(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
@ -1145,7 +1136,7 @@ func UpdateComment(c *Comment, doer *user_model.User) error {
if _, err := sess.ID(c.ID).AllCols().Update(c); err != nil { if _, err := sess.ID(c.ID).AllCols().Update(c); err != nil {
return err return err
} }
if err := c.LoadIssueCtx(ctx); err != nil { if err := c.LoadIssue(ctx); err != nil {
return err return err
} }
if err := c.AddCrossReferences(ctx, doer, true); err != nil { if err := c.AddCrossReferences(ctx, doer, true); err != nil {
@ -1245,7 +1236,7 @@ func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issu
return nil, err return nil, err
} }
if err := CommentList(comments).loadPosters(ctx); err != nil { if err := CommentList(comments).LoadPosters(ctx); err != nil {
return nil, err return nil, err
} }
@ -1363,11 +1354,11 @@ func CreateAutoMergeComment(ctx context.Context, typ CommentType, pr *PullReques
if typ != CommentTypePRScheduledToAutoMerge && typ != CommentTypePRUnScheduledToAutoMerge { if typ != CommentTypePRScheduledToAutoMerge && typ != CommentTypePRUnScheduledToAutoMerge {
return nil, fmt.Errorf("comment type %d cannot be used to create an auto merge comment", typ) return nil, fmt.Errorf("comment type %d cannot be used to create an auto merge comment", typ)
} }
if err = pr.LoadIssueCtx(ctx); err != nil { if err = pr.LoadIssue(ctx); err != nil {
return return
} }
if err = pr.LoadBaseRepoCtx(ctx); err != nil { if err = pr.LoadBaseRepo(ctx); err != nil {
return return
} }
@ -1512,18 +1503,18 @@ func (c *Comment) GetExternalName() string { return c.OriginalAuthor }
func (c *Comment) GetExternalID() int64 { return c.OriginalAuthorID } func (c *Comment) GetExternalID() int64 { return c.OriginalAuthorID }
// CountCommentTypeLabelWithEmptyLabel count label comments with empty label // CountCommentTypeLabelWithEmptyLabel count label comments with empty label
func CountCommentTypeLabelWithEmptyLabel() (int64, error) { func CountCommentTypeLabelWithEmptyLabel(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment)) return db.GetEngine(ctx).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment))
} }
// FixCommentTypeLabelWithEmptyLabel count label comments with empty label // FixCommentTypeLabelWithEmptyLabel count label comments with empty label
func FixCommentTypeLabelWithEmptyLabel() (int64, error) { func FixCommentTypeLabelWithEmptyLabel(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment)) return db.GetEngine(ctx).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment))
} }
// CountCommentTypeLabelWithOutsideLabels count label comments with outside label // CountCommentTypeLabelWithOutsideLabels count label comments with outside label
func CountCommentTypeLabelWithOutsideLabels() (int64, error) { func CountCommentTypeLabelWithOutsideLabels(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel). return db.GetEngine(ctx).Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel).
Table("comment"). Table("comment").
Join("inner", "label", "label.id = comment.label_id"). Join("inner", "label", "label.id = comment.label_id").
Join("inner", "issue", "issue.id = comment.issue_id "). Join("inner", "issue", "issue.id = comment.issue_id ").
@ -1532,8 +1523,8 @@ func CountCommentTypeLabelWithOutsideLabels() (int64, error) {
} }
// FixCommentTypeLabelWithOutsideLabels count label comments with outside label // FixCommentTypeLabelWithOutsideLabels count label comments with outside label
func FixCommentTypeLabelWithOutsideLabels() (int64, error) { func FixCommentTypeLabelWithOutsideLabels(ctx context.Context) (int64, error) {
res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM comment WHERE comment.id IN ( res, err := db.GetEngine(ctx).Exec(`DELETE FROM comment WHERE comment.id IN (
SELECT il_too.id FROM ( SELECT il_too.id FROM (
SELECT com.id SELECT com.id
FROM comment AS com FROM comment AS com

View file

@ -24,7 +24,8 @@ func (comments CommentList) getPosterIDs() []int64 {
return posterIDs.Values() return posterIDs.Values()
} }
func (comments CommentList) loadPosters(ctx context.Context) error { // LoadPosters loads posters
func (comments CommentList) LoadPosters(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -277,7 +278,8 @@ func (comments CommentList) Issues() IssueList {
return issueList return issueList
} }
func (comments CommentList) loadIssues(ctx context.Context) error { // LoadIssues loads issues of comments
func (comments CommentList) LoadIssues(ctx context.Context) error {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -382,7 +384,8 @@ func (comments CommentList) loadDependentIssues(ctx context.Context) error {
return nil return nil
} }
func (comments CommentList) loadAttachments(ctx context.Context) (err error) { // LoadAttachments loads attachments
func (comments CommentList) LoadAttachments(ctx context.Context) (err error) {
if len(comments) == 0 { if len(comments) == 0 {
return nil return nil
} }
@ -476,7 +479,7 @@ func (comments CommentList) loadReviews(ctx context.Context) error { //nolint
// loadAttributes loads all attributes // loadAttributes loads all attributes
func (comments CommentList) loadAttributes(ctx context.Context) (err error) { func (comments CommentList) loadAttributes(ctx context.Context) (err error) {
if err = comments.loadPosters(ctx); err != nil { if err = comments.LoadPosters(ctx); err != nil {
return return
} }
@ -496,7 +499,7 @@ func (comments CommentList) loadAttributes(ctx context.Context) (err error) {
return return
} }
if err = comments.loadAttachments(ctx); err != nil { if err = comments.LoadAttachments(ctx); err != nil {
return return
} }
@ -504,7 +507,7 @@ func (comments CommentList) loadAttributes(ctx context.Context) (err error) {
return return
} }
if err = comments.loadIssues(ctx); err != nil { if err = comments.LoadIssues(ctx); err != nil {
return return
} }
@ -520,18 +523,3 @@ func (comments CommentList) loadAttributes(ctx context.Context) (err error) {
func (comments CommentList) LoadAttributes() error { func (comments CommentList) LoadAttributes() error {
return comments.loadAttributes(db.DefaultContext) return comments.loadAttributes(db.DefaultContext)
} }
// LoadAttachments loads attachments
func (comments CommentList) LoadAttachments() error {
return comments.loadAttachments(db.DefaultContext)
}
// LoadPosters loads posters
func (comments CommentList) LoadPosters() error {
return comments.loadPosters(db.DefaultContext)
}
// LoadIssues loads issues of comments
func (comments CommentList) LoadIssues() error {
return comments.loadIssues(db.DefaultContext)
}

View file

@ -241,11 +241,7 @@ func (issue *Issue) LoadLabels(ctx context.Context) (err error) {
} }
// LoadPoster loads poster // LoadPoster loads poster
func (issue *Issue) LoadPoster() error { func (issue *Issue) LoadPoster(ctx context.Context) (err error) {
return issue.loadPoster(db.DefaultContext)
}
func (issue *Issue) loadPoster(ctx context.Context) (err error) {
if issue.Poster == nil { if issue.Poster == nil {
issue.Poster, err = user_model.GetUserByIDCtx(ctx, issue.PosterID) issue.Poster, err = user_model.GetUserByIDCtx(ctx, issue.PosterID)
if err != nil { if err != nil {
@ -261,7 +257,8 @@ func (issue *Issue) loadPoster(ctx context.Context) (err error) {
return err return err
} }
func (issue *Issue) loadPullRequest(ctx context.Context) (err error) { // LoadPullRequest loads pull request info
func (issue *Issue) LoadPullRequest(ctx context.Context) (err error) {
if issue.IsPull && issue.PullRequest == nil { if issue.IsPull && issue.PullRequest == nil {
issue.PullRequest, err = GetPullRequestByIssueID(ctx, issue.ID) issue.PullRequest, err = GetPullRequestByIssueID(ctx, issue.ID)
if err != nil { if err != nil {
@ -275,18 +272,13 @@ func (issue *Issue) loadPullRequest(ctx context.Context) (err error) {
return nil return nil
} }
// LoadPullRequest loads pull request info
func (issue *Issue) LoadPullRequest() error {
return issue.loadPullRequest(db.DefaultContext)
}
func (issue *Issue) loadComments(ctx context.Context) (err error) { func (issue *Issue) loadComments(ctx context.Context) (err error) {
return issue.loadCommentsByType(ctx, CommentTypeUnknown) return issue.loadCommentsByType(ctx, CommentTypeUnknown)
} }
// LoadDiscussComments loads discuss comments // LoadDiscussComments loads discuss comments
func (issue *Issue) LoadDiscussComments() error { func (issue *Issue) LoadDiscussComments(ctx context.Context) error {
return issue.loadCommentsByType(db.DefaultContext, CommentTypeComment) return issue.loadCommentsByType(ctx, CommentTypeComment)
} }
func (issue *Issue) loadCommentsByType(ctx context.Context, tp CommentType) (err error) { func (issue *Issue) loadCommentsByType(ctx context.Context, tp CommentType) (err error) {
@ -357,7 +349,8 @@ func (issue *Issue) loadForeignReference(ctx context.Context) (err error) {
return nil return nil
} }
func (issue *Issue) loadMilestone(ctx context.Context) (err error) { // LoadMilestone load milestone of this issue.
func (issue *Issue) LoadMilestone(ctx context.Context) (err error) {
if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 { if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 {
issue.Milestone, err = GetMilestoneByRepoID(ctx, issue.RepoID, issue.MilestoneID) issue.Milestone, err = GetMilestoneByRepoID(ctx, issue.RepoID, issue.MilestoneID)
if err != nil && !IsErrMilestoneNotExist(err) { if err != nil && !IsErrMilestoneNotExist(err) {
@ -373,7 +366,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) {
return return
} }
if err = issue.loadPoster(ctx); err != nil { if err = issue.LoadPoster(ctx); err != nil {
return return
} }
@ -381,7 +374,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) {
return return
} }
if err = issue.loadMilestone(ctx); err != nil { if err = issue.LoadMilestone(ctx); err != nil {
return return
} }
@ -393,7 +386,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) {
return return
} }
if err = issue.loadPullRequest(ctx); err != nil && !IsErrPullRequestNotExist(err) { if err = issue.LoadPullRequest(ctx); err != nil && !IsErrPullRequestNotExist(err) {
// It is possible pull request is not yet created. // It is possible pull request is not yet created.
return err return err
} }
@ -425,11 +418,6 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) {
return issue.loadReactions(ctx) return issue.loadReactions(ctx)
} }
// LoadMilestone load milestone of this issue.
func (issue *Issue) LoadMilestone() error {
return issue.loadMilestone(db.DefaultContext)
}
// GetIsRead load the `IsRead` field of the issue // GetIsRead load the `IsRead` field of the issue
func (issue *Issue) GetIsRead(userID int64) error { func (issue *Issue) GetIsRead(userID int64) error {
issueUser := &IssueUser{IssueID: issue.ID, UID: userID} issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
@ -548,7 +536,7 @@ func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) {
if err := issue.LoadRepo(ctx); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return err return err
} else if err = issue.loadPullRequest(ctx); err != nil { } else if err = issue.LoadPullRequest(ctx); err != nil {
return err return err
} }
@ -751,7 +739,7 @@ func ChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User,
if err := issue.LoadRepo(ctx); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return nil, err return nil, err
} }
if err := issue.loadPoster(ctx); err != nil { if err := issue.LoadPoster(ctx); err != nil {
return nil, err return nil, err
} }
@ -1027,7 +1015,7 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue
return fmt.Errorf("find all labels [label_ids: %v]: %w", opts.LabelIDs, err) return fmt.Errorf("find all labels [label_ids: %v]: %w", opts.LabelIDs, err)
} }
if err = opts.Issue.loadPoster(ctx); err != nil { if err = opts.Issue.LoadPoster(ctx); err != nil {
return err return err
} }
@ -1505,10 +1493,9 @@ func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Sess
} }
// CountIssuesByRepo map from repoID to number of issues matching the options // CountIssuesByRepo map from repoID to number of issues matching the options
func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { func CountIssuesByRepo(ctx context.Context, opts *IssuesOptions) (map[int64]int64, error) {
e := db.GetEngine(db.DefaultContext) sess := db.GetEngine(ctx).
Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
opts.setupSessionNoLimit(sess) opts.setupSessionNoLimit(sess)
@ -1551,10 +1538,9 @@ func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]i
} }
// Issues returns a list of issues by given conditions. // Issues returns a list of issues by given conditions.
func Issues(opts *IssuesOptions) ([]*Issue, error) { func Issues(ctx context.Context, opts *IssuesOptions) ([]*Issue, error) {
e := db.GetEngine(db.DefaultContext) sess := db.GetEngine(ctx).
Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
opts.setupSessionWithLimit(sess) opts.setupSessionWithLimit(sess)
sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID) sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
@ -1572,11 +1558,11 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) {
} }
// CountIssues number return of issues by given conditions. // CountIssues number return of issues by given conditions.
func CountIssues(opts *IssuesOptions) (int64, error) { func CountIssues(ctx context.Context, opts *IssuesOptions) (int64, error) {
e := db.GetEngine(db.DefaultContext) sess := db.GetEngine(ctx).
Select("COUNT(issue.id) AS count").
sess := e.Select("COUNT(issue.id) AS count").Table("issue") Table("issue").
sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
opts.setupSessionNoLimit(sess) opts.setupSessionNoLimit(sess)
return sess.Count() return sess.Count()
@ -1585,9 +1571,10 @@ func CountIssues(opts *IssuesOptions) (int64, error) {
// GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue, // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
// but skips joining with `user` for performance reasons. // but skips joining with `user` for performance reasons.
// User permissions must be verified elsewhere if required. // User permissions must be verified elsewhere if required.
func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) { func GetParticipantsIDsByIssueID(ctx context.Context, issueID int64) ([]int64, error) {
userIDs := make([]int64, 0, 5) userIDs := make([]int64, 0, 5)
return userIDs, db.GetEngine(db.DefaultContext).Table("comment"). return userIDs, db.GetEngine(ctx).
Table("comment").
Cols("poster_id"). Cols("poster_id").
Where("issue_id = ?", issueID). Where("issue_id = ?", issueID).
And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
@ -2426,8 +2413,9 @@ func (issue *Issue) GetExternalName() string { return issue.OriginalAuthor }
func (issue *Issue) GetExternalID() int64 { return issue.OriginalAuthorID } func (issue *Issue) GetExternalID() int64 { return issue.OriginalAuthorID }
// CountOrphanedIssues count issues without a repo // CountOrphanedIssues count issues without a repo
func CountOrphanedIssues() (int64, error) { func CountOrphanedIssues(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Table("issue"). return db.GetEngine(ctx).
Table("issue").
Join("LEFT", "repository", "issue.repo_id=repository.id"). Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}). Where(builder.IsNull{"repository.id"}).
Select("COUNT(`issue`.`id`)"). Select("COUNT(`issue`.`id`)").
@ -2435,35 +2423,31 @@ func CountOrphanedIssues() (int64, error) {
} }
// DeleteOrphanedIssues delete issues without a repo // DeleteOrphanedIssues delete issues without a repo
func DeleteOrphanedIssues() error { func DeleteOrphanedIssues(ctx context.Context) error {
ctx, committer, err := db.TxContext(db.DefaultContext) var attachmentPaths []string
err := db.AutoTx(ctx, func(ctx context.Context) error {
var ids []int64
if err := db.GetEngine(ctx).Table("issue").Distinct("issue.repo_id").
Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id").
Find(&ids); err != nil {
return err
}
for i := range ids {
paths, err := DeleteIssuesByRepoID(ctx, ids[i])
if err != nil {
return err
}
attachmentPaths = append(attachmentPaths, paths...)
}
return nil
})
if err != nil { if err != nil {
return err return err
} }
defer committer.Close()
var ids []int64
if err := db.GetEngine(ctx).Table("issue").Distinct("issue.repo_id").
Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id").
Find(&ids); err != nil {
return err
}
var attachmentPaths []string
for i := range ids {
paths, err := DeleteIssuesByRepoID(ctx, ids[i])
if err != nil {
return err
}
attachmentPaths = append(attachmentPaths, paths...)
}
if err := committer.Commit(); err != nil {
return err
}
committer.Close()
// Remove issue attachment files. // Remove issue attachment files.
for i := range attachmentPaths { for i := range attachmentPaths {

View file

@ -34,7 +34,8 @@ func (issues IssueList) getRepoIDs() []int64 {
return repoIDs.Values() return repoIDs.Values()
} }
func (issues IssueList) loadRepositories(ctx context.Context) ([]*repo_model.Repository, error) { // LoadRepositories loads issues' all repositories
func (issues IssueList) LoadRepositories(ctx context.Context) ([]*repo_model.Repository, error) {
if len(issues) == 0 { if len(issues) == 0 {
return nil, nil return nil, nil
} }
@ -73,11 +74,6 @@ func (issues IssueList) loadRepositories(ctx context.Context) ([]*repo_model.Rep
return repo_model.ValuesRepository(repoMaps), nil return repo_model.ValuesRepository(repoMaps), nil
} }
// LoadRepositories loads issues' all repositories
func (issues IssueList) LoadRepositories() ([]*repo_model.Repository, error) {
return issues.loadRepositories(db.DefaultContext)
}
func (issues IssueList) getPosterIDs() []int64 { func (issues IssueList) getPosterIDs() []int64 {
posterIDs := make(container.Set[int64], len(issues)) posterIDs := make(container.Set[int64], len(issues))
for _, issue := range issues { for _, issue := range issues {
@ -317,7 +313,8 @@ func (issues IssueList) getPullIssueIDs() []int64 {
return ids return ids
} }
func (issues IssueList) loadPullRequests(ctx context.Context) error { // LoadPullRequests loads pull requests
func (issues IssueList) LoadPullRequests(ctx context.Context) error {
issuesIDs := issues.getPullIssueIDs() issuesIDs := issues.getPullIssueIDs()
if len(issuesIDs) == 0 { if len(issuesIDs) == 0 {
return nil return nil
@ -361,7 +358,8 @@ func (issues IssueList) loadPullRequests(ctx context.Context) error {
return nil return nil
} }
func (issues IssueList) loadAttachments(ctx context.Context) (err error) { // LoadAttachments loads attachments
func (issues IssueList) LoadAttachments(ctx context.Context) (err error) {
if len(issues) == 0 { if len(issues) == 0 {
return nil return nil
} }
@ -513,8 +511,8 @@ func (issues IssueList) loadTotalTrackedTimes(ctx context.Context) (err error) {
// loadAttributes loads all attributes, expect for attachments and comments // loadAttributes loads all attributes, expect for attachments and comments
func (issues IssueList) loadAttributes(ctx context.Context) error { func (issues IssueList) loadAttributes(ctx context.Context) error {
if _, err := issues.loadRepositories(ctx); err != nil { if _, err := issues.LoadRepositories(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadRepositories: %w", err) return fmt.Errorf("issue.loadAttributes: LoadRepositories: %w", err)
} }
if err := issues.loadPosters(ctx); err != nil { if err := issues.loadPosters(ctx); err != nil {
@ -537,7 +535,7 @@ func (issues IssueList) loadAttributes(ctx context.Context) error {
return fmt.Errorf("issue.loadAttributes: loadAssignees: %w", err) return fmt.Errorf("issue.loadAttributes: loadAssignees: %w", err)
} }
if err := issues.loadPullRequests(ctx); err != nil { if err := issues.LoadPullRequests(ctx); err != nil {
return fmt.Errorf("issue.loadAttributes: loadPullRequests: %w", err) return fmt.Errorf("issue.loadAttributes: loadPullRequests: %w", err)
} }
@ -554,24 +552,14 @@ func (issues IssueList) LoadAttributes() error {
return issues.loadAttributes(db.DefaultContext) return issues.loadAttributes(db.DefaultContext)
} }
// LoadAttachments loads attachments
func (issues IssueList) LoadAttachments() error {
return issues.loadAttachments(db.DefaultContext)
}
// LoadComments loads comments // LoadComments loads comments
func (issues IssueList) LoadComments() error { func (issues IssueList) LoadComments(ctx context.Context) error {
return issues.loadComments(db.DefaultContext, builder.NewCond()) return issues.loadComments(ctx, builder.NewCond())
} }
// LoadDiscussComments loads discuss comments // LoadDiscussComments loads discuss comments
func (issues IssueList) LoadDiscussComments() error { func (issues IssueList) LoadDiscussComments(ctx context.Context) error {
return issues.loadComments(db.DefaultContext, builder.Eq{"comment.type": CommentTypeComment}) return issues.loadComments(ctx, builder.Eq{"comment.type": CommentTypeComment})
}
// LoadPullRequests loads pull requests
func (issues IssueList) LoadPullRequests() error {
return issues.loadPullRequests(db.DefaultContext)
} }
// GetApprovalCounts returns a map of issue ID to slice of approval counts // GetApprovalCounts returns a map of issue ID to slice of approval counts

View file

@ -7,6 +7,7 @@ package issues_test
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -23,7 +24,7 @@ func TestIssueList_LoadRepositories(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}), unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
} }
repos, err := issueList.LoadRepositories() repos, err := issueList.LoadRepositories(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, repos, 2) assert.Len(t, repos, 2)
for _, issue := range issueList { for _, issue := range issueList {

View file

@ -61,11 +61,11 @@ func (issue *Issue) projectBoardID(ctx context.Context) int64 {
} }
// LoadIssuesFromBoard load issues assigned to this board // LoadIssuesFromBoard load issues assigned to this board
func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) { func LoadIssuesFromBoard(ctx context.Context, b *project_model.Board) (IssueList, error) {
issueList := make([]*Issue, 0, 10) issueList := make([]*Issue, 0, 10)
if b.ID != 0 { if b.ID != 0 {
issues, err := Issues(&IssuesOptions{ issues, err := Issues(ctx, &IssuesOptions{
ProjectBoardID: b.ID, ProjectBoardID: b.ID,
ProjectID: b.ProjectID, ProjectID: b.ProjectID,
SortType: "project-column-sorting", SortType: "project-column-sorting",
@ -77,7 +77,7 @@ func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) {
} }
if b.Default { if b.Default {
issues, err := Issues(&IssuesOptions{ issues, err := Issues(ctx, &IssuesOptions{
ProjectBoardID: -1, // Issues without ProjectBoardID ProjectBoardID: -1, // Issues without ProjectBoardID
ProjectID: b.ProjectID, ProjectID: b.ProjectID,
SortType: "project-column-sorting", SortType: "project-column-sorting",
@ -88,7 +88,7 @@ func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) {
issueList = append(issueList, issues...) issueList = append(issueList, issues...)
} }
if err := IssueList(issueList).LoadComments(); err != nil { if err := IssueList(issueList).LoadComments(ctx); err != nil {
return nil, err return nil, err
} }
@ -96,10 +96,10 @@ func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) {
} }
// LoadIssuesFromBoardList load issues assigned to the boards // LoadIssuesFromBoardList load issues assigned to the boards
func LoadIssuesFromBoardList(bs project_model.BoardList) (map[int64]IssueList, error) { func LoadIssuesFromBoardList(ctx context.Context, bs project_model.BoardList) (map[int64]IssueList, error) {
issuesMap := make(map[int64]IssueList, len(bs)) issuesMap := make(map[int64]IssueList, len(bs))
for i := range bs { for i := range bs {
il, err := LoadIssuesFromBoard(bs[i]) il, err := LoadIssuesFromBoard(ctx, bs[i])
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -189,7 +189,7 @@ func TestIssues(t *testing.T) {
[]int64{}, // issues with **both** label 1 and 2, none of these issues matches, TODO: add more tests []int64{}, // issues with **both** label 1 and 2, none of these issues matches, TODO: add more tests
}, },
} { } {
issues, err := issues_model.Issues(&test.Opts) issues, err := issues_model.Issues(db.DefaultContext, &test.Opts)
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, issues, len(test.ExpectedIssueIDs)) { if assert.Len(t, issues, len(test.ExpectedIssueIDs)) {
for i, issue := range issues { for i, issue := range issues {
@ -556,7 +556,7 @@ func TestLoadTotalTrackedTime(t *testing.T) {
func TestCountIssues(t *testing.T) { func TestCountIssues(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
count, err := issues_model.CountIssues(&issues_model.IssuesOptions{}) count, err := issues_model.CountIssues(db.DefaultContext, &issues_model.IssuesOptions{})
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 17, count) assert.EqualValues(t, 17, count)
} }

View file

@ -235,7 +235,7 @@ func (c *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.Us
if c.Type != CommentTypeCode && c.Type != CommentTypeComment { if c.Type != CommentTypeCode && c.Type != CommentTypeComment {
return nil return nil
} }
if err := c.LoadIssueCtx(stdCtx); err != nil { if err := c.LoadIssue(stdCtx); err != nil {
return err return err
} }
ctx := &crossReferencesContext{ ctx := &crossReferencesContext{

View file

@ -116,8 +116,8 @@ func (label *Label) CalOpenIssues() {
} }
// CalOpenOrgIssues calculates the open issues of a label for a specific repo // CalOpenOrgIssues calculates the open issues of a label for a specific repo
func (label *Label) CalOpenOrgIssues(repoID, labelID int64) { func (label *Label) CalOpenOrgIssues(ctx context.Context, repoID, labelID int64) {
counts, _ := CountIssuesByRepo(&IssuesOptions{ counts, _ := CountIssuesByRepo(ctx, &IssuesOptions{
RepoID: repoID, RepoID: repoID,
LabelIDs: []int64{labelID}, LabelIDs: []int64{labelID},
IsClosed: util.OptionalBoolFalse, IsClosed: util.OptionalBoolFalse,
@ -395,9 +395,9 @@ func BuildLabelNamesIssueIDsCondition(labelNames []string) *builder.Builder {
// GetLabelsInRepoByIDs returns a list of labels by IDs in given repository, // GetLabelsInRepoByIDs returns a list of labels by IDs in given repository,
// it silently ignores label IDs that do not belong to the repository. // it silently ignores label IDs that do not belong to the repository.
func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) { func GetLabelsInRepoByIDs(ctx context.Context, repoID int64, labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs)) labels := make([]*Label, 0, len(labelIDs))
return labels, db.GetEngine(db.DefaultContext). return labels, db.GetEngine(ctx).
Where("repo_id = ?", repoID). Where("repo_id = ?", repoID).
In("id", labelIDs). In("id", labelIDs).
Asc("name"). Asc("name").
@ -498,9 +498,9 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error)
// GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization,
// it silently ignores label IDs that do not belong to the organization. // it silently ignores label IDs that do not belong to the organization.
func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) { func GetLabelsInOrgByIDs(ctx context.Context, orgID int64, labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs)) labels := make([]*Label, 0, len(labelIDs))
return labels, db.GetEngine(db.DefaultContext). return labels, db.GetEngine(ctx).
Where("org_id = ?", orgID). Where("org_id = ?", orgID).
In("id", labelIDs). In("id", labelIDs).
Asc("name"). Asc("name").
@ -746,13 +746,13 @@ func DeleteLabelsByRepoID(ctx context.Context, repoID int64) error {
} }
// CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore // CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore
func CountOrphanedLabels() (int64, error) { func CountOrphanedLabels(ctx context.Context) (int64, error) {
noref, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count() noref, err := db.GetEngine(ctx).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count()
if err != nil { if err != nil {
return 0, err return 0, err
} }
norepo, err := db.GetEngine(db.DefaultContext).Table("label"). norepo, err := db.GetEngine(ctx).Table("label").
Where(builder.And( Where(builder.And(
builder.Gt{"repo_id": 0}, builder.Gt{"repo_id": 0},
builder.NotIn("repo_id", builder.Select("id").From("repository")), builder.NotIn("repo_id", builder.Select("id").From("repository")),
@ -762,7 +762,7 @@ func CountOrphanedLabels() (int64, error) {
return 0, err return 0, err
} }
noorg, err := db.GetEngine(db.DefaultContext).Table("label"). noorg, err := db.GetEngine(ctx).Table("label").
Where(builder.And( Where(builder.And(
builder.Gt{"org_id": 0}, builder.Gt{"org_id": 0},
builder.NotIn("org_id", builder.Select("id").From("user")), builder.NotIn("org_id", builder.Select("id").From("user")),
@ -776,14 +776,14 @@ func CountOrphanedLabels() (int64, error) {
} }
// DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore // DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore
func DeleteOrphanedLabels() error { func DeleteOrphanedLabels(ctx context.Context) error {
// delete labels with no reference // delete labels with no reference
if _, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil { if _, err := db.GetEngine(ctx).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil {
return err return err
} }
// delete labels with none existing repos // delete labels with none existing repos
if _, err := db.GetEngine(db.DefaultContext). if _, err := db.GetEngine(ctx).
Where(builder.And( Where(builder.And(
builder.Gt{"repo_id": 0}, builder.Gt{"repo_id": 0},
builder.NotIn("repo_id", builder.Select("id").From("repository")), builder.NotIn("repo_id", builder.Select("id").From("repository")),
@ -793,7 +793,7 @@ func DeleteOrphanedLabels() error {
} }
// delete labels with none existing orgs // delete labels with none existing orgs
if _, err := db.GetEngine(db.DefaultContext). if _, err := db.GetEngine(ctx).
Where(builder.And( Where(builder.And(
builder.Gt{"org_id": 0}, builder.Gt{"org_id": 0},
builder.NotIn("org_id", builder.Select("id").From("user")), builder.NotIn("org_id", builder.Select("id").From("user")),
@ -806,23 +806,23 @@ func DeleteOrphanedLabels() error {
} }
// CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore // CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore
func CountOrphanedIssueLabels() (int64, error) { func CountOrphanedIssueLabels(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Table("issue_label"). return db.GetEngine(ctx).Table("issue_label").
NotIn("label_id", builder.Select("id").From("label")). NotIn("label_id", builder.Select("id").From("label")).
Count() Count()
} }
// DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore // DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore
func DeleteOrphanedIssueLabels() error { func DeleteOrphanedIssueLabels(ctx context.Context) error {
_, err := db.GetEngine(db.DefaultContext). _, err := db.GetEngine(ctx).
NotIn("label_id", builder.Select("id").From("label")). NotIn("label_id", builder.Select("id").From("label")).
Delete(IssueLabel{}) Delete(IssueLabel{})
return err return err
} }
// CountIssueLabelWithOutsideLabels count label comments with outside label // CountIssueLabelWithOutsideLabels count label comments with outside label
func CountIssueLabelWithOutsideLabels() (int64, error) { func CountIssueLabelWithOutsideLabels(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")). return db.GetEngine(ctx).Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")).
Table("issue_label"). Table("issue_label").
Join("inner", "label", "issue_label.label_id = label.id "). Join("inner", "label", "issue_label.label_id = label.id ").
Join("inner", "issue", "issue.id = issue_label.issue_id "). Join("inner", "issue", "issue.id = issue_label.issue_id ").
@ -831,8 +831,8 @@ func CountIssueLabelWithOutsideLabels() (int64, error) {
} }
// FixIssueLabelWithOutsideLabels fix label comments with outside label // FixIssueLabelWithOutsideLabels fix label comments with outside label
func FixIssueLabelWithOutsideLabels() (int64, error) { func FixIssueLabelWithOutsideLabels(ctx context.Context) (int64, error) {
res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM issue_label WHERE issue_label.id IN ( res, err := db.GetEngine(ctx).Exec(`DELETE FROM issue_label WHERE issue_label.id IN (
SELECT il_too.id FROM ( SELECT il_too.id FROM (
SELECT il_too_too.id SELECT il_too_too.id
FROM issue_label AS il_too_too FROM issue_label AS il_too_too

View file

@ -121,7 +121,7 @@ func TestGetLabelInRepoByID(t *testing.T) {
func TestGetLabelsInRepoByIDs(t *testing.T) { func TestGetLabelsInRepoByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
labels, err := issues_model.GetLabelsInRepoByIDs(1, []int64{1, 2, unittest.NonexistentID}) labels, err := issues_model.GetLabelsInRepoByIDs(db.DefaultContext, 1, []int64{1, 2, unittest.NonexistentID})
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, labels, 2) { if assert.Len(t, labels, 2) {
assert.EqualValues(t, 1, labels[0].ID) assert.EqualValues(t, 1, labels[0].ID)
@ -212,7 +212,7 @@ func TestGetLabelInOrgByID(t *testing.T) {
func TestGetLabelsInOrgByIDs(t *testing.T) { func TestGetLabelsInOrgByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
labels, err := issues_model.GetLabelsInOrgByIDs(3, []int64{3, 4, unittest.NonexistentID}) labels, err := issues_model.GetLabelsInOrgByIDs(db.DefaultContext, 3, []int64{3, 4, unittest.NonexistentID})
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, labels, 2) { if assert.Len(t, labels, 2) {
assert.EqualValues(t, 3, labels[0].ID) assert.EqualValues(t, 3, labels[0].ID)

View file

@ -205,8 +205,8 @@ func DeletePullsByBaseRepoID(ctx context.Context, repoID int64) error {
} }
// MustHeadUserName returns the HeadRepo's username if failed return blank // MustHeadUserName returns the HeadRepo's username if failed return blank
func (pr *PullRequest) MustHeadUserName() string { func (pr *PullRequest) MustHeadUserName(ctx context.Context) string {
if err := pr.LoadHeadRepo(); err != nil { if err := pr.LoadHeadRepo(ctx); err != nil {
if !repo_model.IsErrRepoNotExist(err) { if !repo_model.IsErrRepoNotExist(err) {
log.Error("LoadHeadRepo: %v", err) log.Error("LoadHeadRepo: %v", err)
} else { } else {
@ -220,8 +220,9 @@ func (pr *PullRequest) MustHeadUserName() string {
return pr.HeadRepo.OwnerName return pr.HeadRepo.OwnerName
} }
// LoadAttributes loads pull request attributes from database
// Note: don't try to get Issue because will end up recursive querying. // Note: don't try to get Issue because will end up recursive querying.
func (pr *PullRequest) loadAttributes(ctx context.Context) (err error) { func (pr *PullRequest) LoadAttributes(ctx context.Context) (err error) {
if pr.HasMerged && pr.Merger == nil { if pr.HasMerged && pr.Merger == nil {
pr.Merger, err = user_model.GetUserByIDCtx(ctx, pr.MergerID) pr.Merger, err = user_model.GetUserByIDCtx(ctx, pr.MergerID)
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
@ -235,13 +236,8 @@ func (pr *PullRequest) loadAttributes(ctx context.Context) (err error) {
return nil return nil
} }
// LoadAttributes loads pull request attributes from database // LoadHeadRepo loads the head repository
func (pr *PullRequest) LoadAttributes() error { func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) {
return pr.loadAttributes(db.DefaultContext)
}
// LoadHeadRepoCtx loads the head repository
func (pr *PullRequest) LoadHeadRepoCtx(ctx context.Context) (err error) {
if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 { if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
if pr.HeadRepoID == pr.BaseRepoID { if pr.HeadRepoID == pr.BaseRepoID {
if pr.BaseRepo != nil { if pr.BaseRepo != nil {
@ -262,18 +258,8 @@ func (pr *PullRequest) LoadHeadRepoCtx(ctx context.Context) (err error) {
return nil return nil
} }
// LoadHeadRepo loads the head repository
func (pr *PullRequest) LoadHeadRepo() error {
return pr.LoadHeadRepoCtx(db.DefaultContext)
}
// LoadBaseRepo loads the target repository // LoadBaseRepo loads the target repository
func (pr *PullRequest) LoadBaseRepo() error { func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) {
return pr.LoadBaseRepoCtx(db.DefaultContext)
}
// LoadBaseRepoCtx loads the target repository
func (pr *PullRequest) LoadBaseRepoCtx(ctx context.Context) (err error) {
if pr.BaseRepo != nil { if pr.BaseRepo != nil {
return nil return nil
} }
@ -296,12 +282,7 @@ func (pr *PullRequest) LoadBaseRepoCtx(ctx context.Context) (err error) {
} }
// LoadIssue loads issue information from database // LoadIssue loads issue information from database
func (pr *PullRequest) LoadIssue() (err error) { func (pr *PullRequest) LoadIssue(ctx context.Context) (err error) {
return pr.LoadIssueCtx(db.DefaultContext)
}
// LoadIssueCtx loads issue information from database
func (pr *PullRequest) LoadIssueCtx(ctx context.Context) (err error) {
if pr.Issue != nil { if pr.Issue != nil {
return nil return nil
} }
@ -392,7 +373,7 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
break break
} }
if err := review.loadReviewer(ctx); err != nil && !user_model.IsErrUserNotExist(err) { if err := review.LoadReviewer(ctx); err != nil && !user_model.IsErrUserNotExist(err) {
log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err) log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
return err return err
} else if review.Reviewer == nil { } else if review.Reviewer == nil {
@ -458,7 +439,7 @@ func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) {
} }
pr.Issue = nil pr.Issue = nil
if err := pr.LoadIssueCtx(ctx); err != nil { if err := pr.LoadIssue(ctx); err != nil {
return false, err return false, err
} }
@ -541,9 +522,9 @@ func NewPullRequest(outerCtx context.Context, repo *repo_model.Repository, issue
// GetUnmergedPullRequest returns a pull request that is open and has not been merged // GetUnmergedPullRequest returns a pull request that is open and has not been merged
// by given head/base and repo/branch. // by given head/base and repo/branch.
func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) { func GetUnmergedPullRequest(ctx context.Context, headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) {
pr := new(PullRequest) pr := new(PullRequest)
has, err := db.GetEngine(db.DefaultContext). has, err := db.GetEngine(ctx).
Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?", Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?",
headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false). headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false).
Join("INNER", "issue", "issue.id=pull_request.issue_id"). Join("INNER", "issue", "issue.id=pull_request.issue_id").
@ -588,10 +569,10 @@ func GetPullRequestByIndex(ctx context.Context, repoID, index int64) (*PullReque
return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""} return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
} }
if err = pr.loadAttributes(ctx); err != nil { if err = pr.LoadAttributes(ctx); err != nil {
return nil, err return nil, err
} }
if err = pr.LoadIssueCtx(ctx); err != nil { if err = pr.LoadIssue(ctx); err != nil {
return nil, err return nil, err
} }
@ -607,7 +588,7 @@ func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
} else if !has { } else if !has {
return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""} return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
} }
return pr, pr.loadAttributes(ctx) return pr, pr.LoadAttributes(ctx)
} }
// GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
@ -634,7 +615,7 @@ func GetPullRequestByIssueID(ctx context.Context, issueID int64) (*PullRequest,
} else if !has { } else if !has {
return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""} return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
} }
return pr, pr.loadAttributes(ctx) return pr, pr.LoadAttributes(ctx)
} }
// GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request // GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request
@ -664,14 +645,15 @@ func (pr *PullRequest) UpdateCols(cols ...string) error {
} }
// UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error { func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string) error {
_, err := db.GetEngine(db.DefaultContext).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr) _, err := db.GetEngine(ctx).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
return err return err
} }
// IsWorkInProgress determine if the Pull Request is a Work In Progress by its title // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
// Issue must be set before this method can be called.
func (pr *PullRequest) IsWorkInProgress() bool { func (pr *PullRequest) IsWorkInProgress() bool {
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(db.DefaultContext); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return false return false
} }
@ -695,8 +677,8 @@ func (pr *PullRequest) IsFilesConflicted() bool {
// GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
// It returns an empty string when none were found // It returns an empty string when none were found
func (pr *PullRequest) GetWorkInProgressPrefix() string { func (pr *PullRequest) GetWorkInProgressPrefix(ctx context.Context) string {
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return "" return ""
} }
@ -739,7 +721,7 @@ func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRep
// GetBaseBranchHTMLURL returns the HTML URL of the base branch // GetBaseBranchHTMLURL returns the HTML URL of the base branch
func (pr *PullRequest) GetBaseBranchHTMLURL() string { func (pr *PullRequest) GetBaseBranchHTMLURL() string {
if err := pr.LoadBaseRepo(); err != nil { if err := pr.LoadBaseRepo(db.DefaultContext); err != nil {
log.Error("LoadBaseRepo: %v", err) log.Error("LoadBaseRepo: %v", err)
return "" return ""
} }
@ -755,7 +737,7 @@ func (pr *PullRequest) GetHeadBranchHTMLURL() string {
return "" return ""
} }
if err := pr.LoadHeadRepo(); err != nil { if err := pr.LoadHeadRepo(db.DefaultContext); err != nil {
log.Error("LoadHeadRepo: %v", err) log.Error("LoadHeadRepo: %v", err)
return "" return ""
} }

View file

@ -79,7 +79,7 @@ func CanMaintainerWriteToBranch(p access_model.Permission, branch string, user *
for _, pr := range prs { for _, pr := range prs {
if pr.AllowMaintainerEdit { if pr.AllowMaintainerEdit {
err = pr.LoadBaseRepo() err = pr.LoadBaseRepo(db.DefaultContext)
if err != nil { if err != nil {
continue continue
} }

View file

@ -17,7 +17,7 @@ import (
func TestPullRequest_LoadAttributes(t *testing.T) { func TestPullRequest_LoadAttributes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadAttributes()) assert.NoError(t, pr.LoadAttributes(db.DefaultContext))
assert.NotNil(t, pr.Merger) assert.NotNil(t, pr.Merger)
assert.Equal(t, pr.MergerID, pr.Merger.ID) assert.Equal(t, pr.MergerID, pr.Merger.ID)
} }
@ -25,10 +25,10 @@ func TestPullRequest_LoadAttributes(t *testing.T) {
func TestPullRequest_LoadIssue(t *testing.T) { func TestPullRequest_LoadIssue(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadIssue(db.DefaultContext))
assert.NotNil(t, pr.Issue) assert.NotNil(t, pr.Issue)
assert.Equal(t, int64(2), pr.Issue.ID) assert.Equal(t, int64(2), pr.Issue.ID)
assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadIssue(db.DefaultContext))
assert.NotNil(t, pr.Issue) assert.NotNil(t, pr.Issue)
assert.Equal(t, int64(2), pr.Issue.ID) assert.Equal(t, int64(2), pr.Issue.ID)
} }
@ -36,10 +36,10 @@ func TestPullRequest_LoadIssue(t *testing.T) {
func TestPullRequest_LoadBaseRepo(t *testing.T) { func TestPullRequest_LoadBaseRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadBaseRepo()) assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext))
assert.NotNil(t, pr.BaseRepo) assert.NotNil(t, pr.BaseRepo)
assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID)
assert.NoError(t, pr.LoadBaseRepo()) assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext))
assert.NotNil(t, pr.BaseRepo) assert.NotNil(t, pr.BaseRepo)
assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID)
} }
@ -47,7 +47,7 @@ func TestPullRequest_LoadBaseRepo(t *testing.T) {
func TestPullRequest_LoadHeadRepo(t *testing.T) { func TestPullRequest_LoadHeadRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadHeadRepo()) assert.NoError(t, pr.LoadHeadRepo(db.DefaultContext))
assert.NotNil(t, pr.HeadRepo) assert.NotNil(t, pr.HeadRepo)
assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID) assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID)
} }
@ -96,11 +96,11 @@ func TestPullRequestsOldest(t *testing.T) {
func TestGetUnmergedPullRequest(t *testing.T) { func TestGetUnmergedPullRequest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetUnmergedPullRequest(1, 1, "branch2", "master", issues_model.PullRequestFlowGithub) pr, err := issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 1, "branch2", "master", issues_model.PullRequestFlowGithub)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(2), pr.ID) assert.Equal(t, int64(2), pr.ID)
_, err = issues_model.GetUnmergedPullRequest(1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub) _, err = issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err)) assert.True(t, issues_model.IsErrPullRequestNotExist(err))
} }
@ -228,7 +228,7 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue() pr.LoadIssue(db.DefaultContext)
assert.False(t, pr.IsWorkInProgress()) assert.False(t, pr.IsWorkInProgress())
@ -243,16 +243,16 @@ func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue() pr.LoadIssue(db.DefaultContext)
assert.Empty(t, pr.GetWorkInProgressPrefix()) assert.Empty(t, pr.GetWorkInProgressPrefix(db.DefaultContext))
original := pr.Issue.Title original := pr.Issue.Title
pr.Issue.Title = "WIP: " + original pr.Issue.Title = "WIP: " + original
assert.Equal(t, "WIP:", pr.GetWorkInProgressPrefix()) assert.Equal(t, "WIP:", pr.GetWorkInProgressPrefix(db.DefaultContext))
pr.Issue.Title = "[wip] " + original pr.Issue.Title = "[wip] " + original
assert.Equal(t, "[wip]", pr.GetWorkInProgressPrefix()) assert.Equal(t, "[wip]", pr.GetWorkInProgressPrefix(db.DefaultContext))
} }
func TestDeleteOrphanedObjects(t *testing.T) { func TestDeleteOrphanedObjects(t *testing.T) {
@ -264,11 +264,11 @@ func TestDeleteOrphanedObjects(t *testing.T) {
_, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003}) _, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
assert.NoError(t, err) assert.NoError(t, err)
orphaned, err := db.CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 3, orphaned) assert.EqualValues(t, 3, orphaned)
err = db.DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err) assert.NoError(t, err)
countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})

View file

@ -154,7 +154,8 @@ func (r *Review) loadIssue(ctx context.Context) (err error) {
return err return err
} }
func (r *Review) loadReviewer(ctx context.Context) (err error) { // LoadReviewer loads reviewer
func (r *Review) LoadReviewer(ctx context.Context) (err error) {
if r.ReviewerID == 0 || r.Reviewer != nil { if r.ReviewerID == 0 || r.Reviewer != nil {
return return
} }
@ -162,7 +163,8 @@ func (r *Review) loadReviewer(ctx context.Context) (err error) {
return err return err
} }
func (r *Review) loadReviewerTeam(ctx context.Context) (err error) { // LoadReviewerTeam loads reviewer team
func (r *Review) LoadReviewerTeam(ctx context.Context) (err error) {
if r.ReviewerTeamID == 0 || r.ReviewerTeam != nil { if r.ReviewerTeamID == 0 || r.ReviewerTeam != nil {
return return
} }
@ -171,16 +173,6 @@ func (r *Review) loadReviewerTeam(ctx context.Context) (err error) {
return err return err
} }
// LoadReviewer loads reviewer
func (r *Review) LoadReviewer() error {
return r.loadReviewer(db.DefaultContext)
}
// LoadReviewerTeam loads reviewer team
func (r *Review) LoadReviewerTeam() error {
return r.loadReviewerTeam(db.DefaultContext)
}
// LoadAttributes loads all attributes except CodeComments // LoadAttributes loads all attributes except CodeComments
func (r *Review) LoadAttributes(ctx context.Context) (err error) { func (r *Review) LoadAttributes(ctx context.Context) (err error) {
if err = r.loadIssue(ctx); err != nil { if err = r.loadIssue(ctx); err != nil {
@ -189,10 +181,10 @@ func (r *Review) LoadAttributes(ctx context.Context) (err error) {
if err = r.LoadCodeComments(ctx); err != nil { if err = r.LoadCodeComments(ctx); err != nil {
return return
} }
if err = r.loadReviewer(ctx); err != nil { if err = r.LoadReviewer(ctx); err != nil {
return return
} }
if err = r.loadReviewerTeam(ctx); err != nil { if err = r.LoadReviewerTeam(ctx); err != nil {
return return
} }
return err return err

View file

@ -135,7 +135,7 @@ func TestGetReviewersByIssueID(t *testing.T) {
allReviews, err := issues_model.GetReviewersByIssueID(issue.ID) allReviews, err := issues_model.GetReviewersByIssueID(issue.ID)
for _, reviewer := range allReviews { for _, reviewer := range allReviews {
assert.NoError(t, reviewer.LoadReviewer()) assert.NoError(t, reviewer.LoadReviewer(db.DefaultContext))
} }
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, allReviews, 3) { if assert.Len(t, allReviews, 3) {

View file

@ -143,7 +143,7 @@ func TestDeleteTeam(t *testing.T) {
// check that team members don't have "leftover" access to repos // check that team members don't have "leftover" access to repos
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
accessMode, err := access_model.AccessLevel(user, repo) accessMode, err := access_model.AccessLevel(db.DefaultContext, user, repo)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, accessMode < perm.AccessModeWrite) assert.True(t, accessMode < perm.AccessModeWrite)
} }

View file

@ -36,34 +36,34 @@ func TestAccessLevel(t *testing.T) {
// org. owned private repo // org. owned private repo
repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24}) repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24})
level, err := access_model.AccessLevel(user2, repo1) level, err := access_model.AccessLevel(db.DefaultContext, user2, repo1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeOwner, level) assert.Equal(t, perm_model.AccessModeOwner, level)
level, err = access_model.AccessLevel(user2, repo3) level, err = access_model.AccessLevel(db.DefaultContext, user2, repo3)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeOwner, level) assert.Equal(t, perm_model.AccessModeOwner, level)
level, err = access_model.AccessLevel(user5, repo1) level, err = access_model.AccessLevel(db.DefaultContext, user5, repo1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeRead, level) assert.Equal(t, perm_model.AccessModeRead, level)
level, err = access_model.AccessLevel(user5, repo3) level, err = access_model.AccessLevel(db.DefaultContext, user5, repo3)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeNone, level) assert.Equal(t, perm_model.AccessModeNone, level)
// restricted user has no access to a public repo // restricted user has no access to a public repo
level, err = access_model.AccessLevel(user29, repo1) level, err = access_model.AccessLevel(db.DefaultContext, user29, repo1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeNone, level) assert.Equal(t, perm_model.AccessModeNone, level)
// ... unless he's a collaborator // ... unless he's a collaborator
level, err = access_model.AccessLevel(user29, repo4) level, err = access_model.AccessLevel(db.DefaultContext, user29, repo4)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeWrite, level) assert.Equal(t, perm_model.AccessModeWrite, level)
// ... or a team member // ... or a team member
level, err = access_model.AccessLevel(user29, repo24) level, err = access_model.AccessLevel(db.DefaultContext, user29, repo24)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeRead, level) assert.Equal(t, perm_model.AccessModeRead, level)
} }

View file

@ -326,17 +326,13 @@ func IsUserRepoAdmin(ctx context.Context, repo *repo_model.Repository, user *use
// AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the
// user does not have access. // user does not have access.
func AccessLevel(user *user_model.User, repo *repo_model.Repository) (perm_model.AccessMode, error) { //nolint func AccessLevel(ctx context.Context, user *user_model.User, repo *repo_model.Repository) (perm_model.AccessMode, error) { //nolint
return AccessLevelUnit(user, repo, unit.TypeCode) return AccessLevelUnit(ctx, user, repo, unit.TypeCode)
} }
// AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the // AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the
// user does not have access. // user does not have access.
func AccessLevelUnit(user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { //nolint func AccessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { //nolint
return accessLevelUnit(db.DefaultContext, user, repo, unitType)
}
func accessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) {
perm, err := GetUserRepoPermission(ctx, repo, user) perm, err := GetUserRepoPermission(ctx, repo, user)
if err != nil { if err != nil {
return perm_model.AccessModeNone, err return perm_model.AccessModeNone, err
@ -346,7 +342,7 @@ func accessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_mode
// HasAccessUnit returns true if user has testMode to the unit of the repository // HasAccessUnit returns true if user has testMode to the unit of the repository
func HasAccessUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) { func HasAccessUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) {
mode, err := accessLevelUnit(ctx, user, repo, unitType) mode, err := AccessLevelUnit(ctx, user, repo, unitType)
return testMode <= mode, err return testMode <= mode, err
} }

View file

@ -226,20 +226,20 @@ func UpdateAttachment(ctx context.Context, atta *Attachment) error {
} }
// DeleteAttachmentsByRelease deletes all attachments associated with the given release. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
func DeleteAttachmentsByRelease(releaseID int64) error { func DeleteAttachmentsByRelease(ctx context.Context, releaseID int64) error {
_, err := db.GetEngine(db.DefaultContext).Where("release_id = ?", releaseID).Delete(&Attachment{}) _, err := db.GetEngine(ctx).Where("release_id = ?", releaseID).Delete(&Attachment{})
return err return err
} }
// CountOrphanedAttachments returns the number of bad attachments // CountOrphanedAttachments returns the number of bad attachments
func CountOrphanedAttachments() (int64, error) { func CountOrphanedAttachments(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). return db.GetEngine(ctx).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
Count(new(Attachment)) Count(new(Attachment))
} }
// DeleteOrphanedAttachments delete all bad attachments // DeleteOrphanedAttachments delete all bad attachments
func DeleteOrphanedAttachments() error { func DeleteOrphanedAttachments(ctx context.Context) error {
_, err := db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). _, err := db.GetEngine(ctx).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
Delete(new(Attachment)) Delete(new(Attachment))
return err return err
} }

View file

@ -120,9 +120,9 @@ func GetPushMirrorsByRepoID(ctx context.Context, repoID int64, listOptions db.Li
} }
// GetPushMirrorsSyncedOnCommit returns push-mirrors for this repo that should be updated by new commits // GetPushMirrorsSyncedOnCommit returns push-mirrors for this repo that should be updated by new commits
func GetPushMirrorsSyncedOnCommit(repoID int64) ([]*PushMirror, error) { func GetPushMirrorsSyncedOnCommit(ctx context.Context, repoID int64) ([]*PushMirror, error) {
mirrors := make([]*PushMirror, 0, 10) mirrors := make([]*PushMirror, 0, 10)
return mirrors, db.GetEngine(db.DefaultContext). return mirrors, db.GetEngine(ctx).
Where("repo_id=? AND sync_on_commit=?", repoID, true). Where("repo_id=? AND sync_on_commit=?", repoID, true).
Find(&mirrors) Find(&mirrors)
} }

View file

@ -90,7 +90,8 @@ func init() {
db.RegisterModel(new(Release)) db.RegisterModel(new(Release))
} }
func (r *Release) loadAttributes(ctx context.Context) error { // LoadAttributes load repo and publisher attributes for a release
func (r *Release) LoadAttributes(ctx context.Context) error {
var err error var err error
if r.Repo == nil { if r.Repo == nil {
r.Repo, err = GetRepositoryByIDCtx(ctx, r.RepoID) r.Repo, err = GetRepositoryByIDCtx(ctx, r.RepoID)
@ -111,11 +112,6 @@ func (r *Release) loadAttributes(ctx context.Context) error {
return GetReleaseAttachments(ctx, r) return GetReleaseAttachments(ctx, r)
} }
// LoadAttributes load repo and publisher attributes for a release
func (r *Release) LoadAttributes() error {
return r.loadAttributes(db.DefaultContext)
}
// APIURL the api url for a release. release must have attributes loaded // APIURL the api url for a release. release must have attributes loaded
func (r *Release) APIURL() string { func (r *Release) APIURL() string {
return r.Repo.APIURL() + "/releases/" + strconv.FormatInt(r.ID, 10) return r.Repo.APIURL() + "/releases/" + strconv.FormatInt(r.ID, 10)
@ -241,8 +237,8 @@ func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond {
} }
// GetReleasesByRepoID returns a list of releases of repository. // GetReleasesByRepoID returns a list of releases of repository.
func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) { func GetReleasesByRepoID(ctx context.Context, repoID int64, opts FindReleasesOptions) ([]*Release, error) {
sess := db.GetEngine(db.DefaultContext). sess := db.GetEngine(ctx).
Desc("created_unix", "id"). Desc("created_unix", "id").
Where(opts.toConds(repoID)) Where(opts.toConds(repoID))
@ -381,8 +377,8 @@ func SortReleases(rels []*Release) {
} }
// DeleteReleaseByID deletes a release from database by given ID. // DeleteReleaseByID deletes a release from database by given ID.
func DeleteReleaseByID(id int64) error { func DeleteReleaseByID(ctx context.Context, id int64) error {
_, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Release)) _, err := db.GetEngine(ctx).ID(id).Delete(new(Release))
return err return err
} }

View file

@ -236,14 +236,6 @@ func (repo *Repository) AfterLoad() {
repo.NumOpenProjects = repo.NumProjects - repo.NumClosedProjects repo.NumOpenProjects = repo.NumProjects - repo.NumClosedProjects
} }
// MustOwner always returns a valid *user_model.User object to avoid
// conceptually impossible error handling.
// It creates a fake object that contains error details
// when error occurs.
func (repo *Repository) MustOwner() *user_model.User {
return repo.mustOwner(db.DefaultContext)
}
// LoadAttributes loads attributes of the repository. // LoadAttributes loads attributes of the repository.
func (repo *Repository) LoadAttributes(ctx context.Context) error { func (repo *Repository) LoadAttributes(ctx context.Context) error {
// Load owner // Load owner
@ -403,7 +395,11 @@ func (repo *Repository) GetOwner(ctx context.Context) (err error) {
return err return err
} }
func (repo *Repository) mustOwner(ctx context.Context) *user_model.User { // MustOwner always returns a valid *user_model.User object to avoid
// conceptually impossible error handling.
// It creates a fake object that contains error details
// when error occurs.
func (repo *Repository) MustOwner(ctx context.Context) *user_model.User {
if err := repo.GetOwner(ctx); err != nil { if err := repo.GetOwner(ctx); err != nil {
return &user_model.User{ return &user_model.User{
Name: "error", Name: "error",
@ -438,7 +434,7 @@ func (repo *Repository) ComposeMetas() map[string]string {
} }
} }
repo.MustOwner() repo.MustOwner(db.DefaultContext)
if repo.Owner.IsOrganization() { if repo.Owner.IsOrganization() {
teams := make([]string, 0, 5) teams := make([]string, 0, 5)
_ = db.GetEngine(db.DefaultContext).Table("team_repo"). _ = db.GetEngine(db.DefaultContext).Table("team_repo").
@ -792,13 +788,13 @@ func UpdateRepoIssueNumbers(ctx context.Context, repoID int64, isPull, isClosed
} }
// CountNullArchivedRepository counts the number of repositories with is_archived is null // CountNullArchivedRepository counts the number of repositories with is_archived is null
func CountNullArchivedRepository() (int64, error) { func CountNullArchivedRepository(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Count(new(Repository)) return db.GetEngine(ctx).Where(builder.IsNull{"is_archived"}).Count(new(Repository))
} }
// FixNullArchivedRepository sets is_archived to false where it is null // FixNullArchivedRepository sets is_archived to false where it is null
func FixNullArchivedRepository() (int64, error) { func FixNullArchivedRepository(ctx context.Context) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{ return db.GetEngine(ctx).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{
IsArchived: false, IsArchived: false,
}) })
} }

View file

@ -518,14 +518,13 @@ func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond {
// SearchRepository returns repositories based on search options, // SearchRepository returns repositories based on search options,
// it returns results in given range and number of total results. // it returns results in given range and number of total results.
func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) { func SearchRepository(ctx context.Context, opts *SearchRepoOptions) (RepositoryList, int64, error) {
cond := SearchRepositoryCondition(opts) cond := SearchRepositoryCondition(opts)
return SearchRepositoryByCondition(opts, cond, true) return SearchRepositoryByCondition(ctx, opts, cond, true)
} }
// SearchRepositoryByCondition search repositories by condition // SearchRepositoryByCondition search repositories by condition
func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) { func SearchRepositoryByCondition(ctx context.Context, opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) {
ctx := db.DefaultContext
sess, count, err := searchRepositoryByCondition(ctx, opts, cond) sess, count, err := searchRepositoryByCondition(ctx, opts, cond)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
@ -652,9 +651,9 @@ func AccessibleRepositoryCondition(user *user_model.User, unitType unit.Type) bu
// SearchRepositoryByName takes keyword and part of repository name to search, // SearchRepositoryByName takes keyword and part of repository name to search,
// it returns results in given range and number of total results. // it returns results in given range and number of total results.
func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, error) { func SearchRepositoryByName(ctx context.Context, opts *SearchRepoOptions) (RepositoryList, int64, error) {
opts.IncludeDescription = false opts.IncludeDescription = false
return SearchRepository(opts) return SearchRepository(ctx, opts)
} }
// SearchRepositoryIDs takes keyword and part of repository name to search, // SearchRepositoryIDs takes keyword and part of repository name to search,

View file

@ -20,7 +20,7 @@ func TestSearchRepository(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// test search public repository on explore page // test search public repository on explore page
repos, count, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
@ -35,7 +35,7 @@ func TestSearchRepository(t *testing.T) {
} }
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
@ -49,7 +49,7 @@ func TestSearchRepository(t *testing.T) {
assert.Len(t, repos, 2) assert.Len(t, repos, 2)
// test search private repository on explore page // test search private repository on explore page
repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
@ -65,7 +65,7 @@ func TestSearchRepository(t *testing.T) {
} }
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
@ -80,14 +80,14 @@ func TestSearchRepository(t *testing.T) {
assert.Len(t, repos, 3) assert.Len(t, repos, 3)
// Test non existing owner // Test non existing owner
repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID}) repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID})
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, repos) assert.Empty(t, repos)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
// Test search within description // Test search within description
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(db.DefaultContext, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
@ -104,7 +104,7 @@ func TestSearchRepository(t *testing.T) {
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
// Test NOT search within description // Test NOT search within description
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(db.DefaultContext, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
@ -277,7 +277,7 @@ func TestSearchRepository(t *testing.T) {
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
repos, count, err := repo_model.SearchRepositoryByName(testCase.opts) repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(testCase.count), count) assert.Equal(t, int64(testCase.count), count)
@ -377,7 +377,7 @@ func TestSearchRepositoryByTopicName(t *testing.T) {
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
_, count, err := repo_model.SearchRepositoryByName(testCase.opts) _, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(testCase.count), count) assert.Equal(t, int64(testCase.count), count)
}) })

View file

@ -17,8 +17,9 @@ import (
) )
// GetStarredRepos returns the repos starred by a particular user // GetStarredRepos returns the repos starred by a particular user
func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) { func GetStarredRepos(ctx context.Context, userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) {
sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID). sess := db.GetEngine(ctx).
Where("star.uid=?", userID).
Join("LEFT", "star", "`repository`.id=`star`.repo_id") Join("LEFT", "star", "`repository`.id=`star`.repo_id")
if !private { if !private {
sess = sess.And("is_private=?", false) sess = sess.And("is_private=?", false)
@ -36,8 +37,9 @@ func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]
} }
// GetWatchedRepos returns the repos watched by a particular user // GetWatchedRepos returns the repos watched by a particular user
func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) { func GetWatchedRepos(ctx context.Context, userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) {
sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID). sess := db.GetEngine(ctx).
Where("watch.user_id=?", userID).
And("`watch`.mode<>?", WatchModeDont). And("`watch`.mode<>?", WatchModeDont).
Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
if !private { if !private {

View file

@ -1042,14 +1042,15 @@ func GetUserEmailsByNames(ctx context.Context, names []string) []string {
} }
// GetMaileableUsersByIDs gets users from ids, but only if they can receive mails // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) { func GetMaileableUsersByIDs(ctx context.Context, ids []int64, isMention bool) ([]*User, error) {
if len(ids) == 0 { if len(ids) == 0 {
return nil, nil return nil, nil
} }
ous := make([]*User, 0, len(ids)) ous := make([]*User, 0, len(ids))
if isMention { if isMention {
return ous, db.GetEngine(db.DefaultContext).In("id", ids). return ous, db.GetEngine(ctx).
In("id", ids).
Where("`type` = ?", UserTypeIndividual). Where("`type` = ?", UserTypeIndividual).
And("`prohibit_login` = ?", false). And("`prohibit_login` = ?", false).
And("`is_active` = ?", true). And("`is_active` = ?", true).
@ -1057,7 +1058,8 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
Find(&ous) Find(&ous)
} }
return ous, db.GetEngine(db.DefaultContext).In("id", ids). return ous, db.GetEngine(ctx).
In("id", ids).
Where("`type` = ?", UserTypeIndividual). Where("`type` = ?", UserTypeIndividual).
And("`prohibit_login` = ?", false). And("`prohibit_login` = ?", false).
And("`is_active` = ?", true). And("`is_active` = ?", true).
@ -1090,10 +1092,10 @@ func GetUserNameByID(ctx context.Context, id int64) (string, error) {
} }
// GetUserIDsByNames returns a slice of ids corresponds to names. // GetUserIDsByNames returns a slice of ids corresponds to names.
func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) { func GetUserIDsByNames(ctx context.Context, names []string, ignoreNonExistent bool) ([]int64, error) {
ids := make([]int64, 0, len(names)) ids := make([]int64, 0, len(names))
for _, name := range names { for _, name := range names {
u, err := GetUserByName(db.DefaultContext, name) u, err := GetUserByName(ctx, name)
if err != nil { if err != nil {
if ignoreNonExistent { if ignoreNonExistent {
continue continue

View file

@ -257,12 +257,12 @@ func TestGetUserIDsByNames(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// ignore non existing // ignore non existing
IDs, err := user_model.GetUserIDsByNames([]string{"user1", "user2", "none_existing_user"}, true) IDs, err := user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "user2", "none_existing_user"}, true)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []int64{1, 2}, IDs) assert.Equal(t, []int64{1, 2}, IDs)
// ignore non existing // ignore non existing
IDs, err = user_model.GetUserIDsByNames([]string{"user1", "do_not_exist"}, false) IDs, err = user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "do_not_exist"}, false)
assert.Error(t, err) assert.Error(t, err)
assert.Equal(t, []int64(nil), IDs) assert.Equal(t, []int64(nil), IDs)
} }
@ -270,14 +270,14 @@ func TestGetUserIDsByNames(t *testing.T) {
func TestGetMaileableUsersByIDs(t *testing.T) { func TestGetMaileableUsersByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
results, err := user_model.GetMaileableUsersByIDs([]int64{1, 4}, false) results, err := user_model.GetMaileableUsersByIDs(db.DefaultContext, []int64{1, 4}, false)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, results, 1) assert.Len(t, results, 1)
if len(results) > 1 { if len(results) > 1 {
assert.Equal(t, results[0].ID, 1) assert.Equal(t, results[0].ID, 1)
} }
results, err = user_model.GetMaileableUsersByIDs([]int64{1, 4}, true) results, err = user_model.GetMaileableUsersByIDs(db.DefaultContext, []int64{1, 4}, true)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, results, 2) assert.Len(t, results, 2)
if len(results) > 2 { if len(results) > 2 {

View file

@ -5,6 +5,7 @@
package convert package convert
import ( import (
"context"
"fmt" "fmt"
"net/url" "net/url"
"strings" "strings"
@ -22,17 +23,17 @@ import (
// it assumes some fields assigned with values: // it assumes some fields assigned with values:
// Required - Poster, Labels, // Required - Poster, Labels,
// Optional - Milestone, Assignee, PullRequest // Optional - Milestone, Assignee, PullRequest
func ToAPIIssue(issue *issues_model.Issue) *api.Issue { func ToAPIIssue(ctx context.Context, issue *issues_model.Issue) *api.Issue {
if err := issue.LoadLabels(db.DefaultContext); err != nil { if err := issue.LoadLabels(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
if err := issue.LoadPoster(); err != nil { if err := issue.LoadPoster(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
if err := issue.LoadRepo(db.DefaultContext); err != nil { if err := issue.LoadRepo(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
if err := issue.Repo.GetOwner(db.DefaultContext); err != nil { if err := issue.Repo.GetOwner(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
@ -64,14 +65,14 @@ func ToAPIIssue(issue *issues_model.Issue) *api.Issue {
apiIssue.Closed = issue.ClosedUnix.AsTimePtr() apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
} }
if err := issue.LoadMilestone(); err != nil { if err := issue.LoadMilestone(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
if issue.Milestone != nil { if issue.Milestone != nil {
apiIssue.Milestone = ToAPIMilestone(issue.Milestone) apiIssue.Milestone = ToAPIMilestone(issue.Milestone)
} }
if err := issue.LoadAssignees(db.DefaultContext); err != nil { if err := issue.LoadAssignees(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
if len(issue.Assignees) > 0 { if len(issue.Assignees) > 0 {
@ -81,7 +82,7 @@ func ToAPIIssue(issue *issues_model.Issue) *api.Issue {
apiIssue.Assignee = ToUser(issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee` apiIssue.Assignee = ToUser(issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
} }
if issue.IsPull { if issue.IsPull {
if err := issue.LoadPullRequest(); err != nil { if err := issue.LoadPullRequest(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
apiIssue.PullRequest = &api.PullRequestMeta{ apiIssue.PullRequest = &api.PullRequestMeta{
@ -99,16 +100,16 @@ func ToAPIIssue(issue *issues_model.Issue) *api.Issue {
} }
// ToAPIIssueList converts an IssueList to API format // ToAPIIssueList converts an IssueList to API format
func ToAPIIssueList(il issues_model.IssueList) []*api.Issue { func ToAPIIssueList(ctx context.Context, il issues_model.IssueList) []*api.Issue {
result := make([]*api.Issue, len(il)) result := make([]*api.Issue, len(il))
for i := range il { for i := range il {
result[i] = ToAPIIssue(il[i]) result[i] = ToAPIIssue(ctx, il[i])
} }
return result return result
} }
// ToTrackedTime converts TrackedTime to API format // ToTrackedTime converts TrackedTime to API format
func ToTrackedTime(t *issues_model.TrackedTime) (apiT *api.TrackedTime) { func ToTrackedTime(ctx context.Context, t *issues_model.TrackedTime) (apiT *api.TrackedTime) {
apiT = &api.TrackedTime{ apiT = &api.TrackedTime{
ID: t.ID, ID: t.ID,
IssueID: t.IssueID, IssueID: t.IssueID,
@ -118,7 +119,7 @@ func ToTrackedTime(t *issues_model.TrackedTime) (apiT *api.TrackedTime) {
Created: t.Created, Created: t.Created,
} }
if t.Issue != nil { if t.Issue != nil {
apiT.Issue = ToAPIIssue(t.Issue) apiT.Issue = ToAPIIssue(ctx, t.Issue)
} }
if t.User != nil { if t.User != nil {
apiT.UserName = t.User.Name apiT.UserName = t.User.Name
@ -169,10 +170,10 @@ func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) {
} }
// ToTrackedTimeList converts TrackedTimeList to API format // ToTrackedTimeList converts TrackedTimeList to API format
func ToTrackedTimeList(tl issues_model.TrackedTimeList) api.TrackedTimeList { func ToTrackedTimeList(ctx context.Context, tl issues_model.TrackedTimeList) api.TrackedTimeList {
result := make([]*api.TrackedTime, 0, len(tl)) result := make([]*api.TrackedTime, 0, len(tl))
for _, t := range tl { for _, t := range tl {
result = append(result, ToTrackedTime(t)) result = append(result, ToTrackedTime(ctx, t))
} }
return result return result
} }

View file

@ -5,7 +5,8 @@
package convert package convert
import ( import (
"code.gitea.io/gitea/models/db" "context"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -28,8 +29,8 @@ func ToComment(c *issues_model.Comment) *api.Comment {
} }
// ToTimelineComment converts a issues_model.Comment to the api.TimelineComment format // ToTimelineComment converts a issues_model.Comment to the api.TimelineComment format
func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.TimelineComment { func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_model.User) *api.TimelineComment {
err := c.LoadMilestone() err := c.LoadMilestone(ctx)
if err != nil { if err != nil {
log.Error("LoadMilestone: %v", err) log.Error("LoadMilestone: %v", err)
return nil return nil
@ -107,25 +108,25 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time
return nil return nil
} }
comment.TrackedTime = ToTrackedTime(c.Time) comment.TrackedTime = ToTrackedTime(ctx, c.Time)
} }
if c.RefIssueID != 0 { if c.RefIssueID != 0 {
issue, err := issues_model.GetIssueByID(db.DefaultContext, c.RefIssueID) issue, err := issues_model.GetIssueByID(ctx, c.RefIssueID)
if err != nil { if err != nil {
log.Error("GetIssueByID(%d): %v", c.RefIssueID, err) log.Error("GetIssueByID(%d): %v", c.RefIssueID, err)
return nil return nil
} }
comment.RefIssue = ToAPIIssue(issue) comment.RefIssue = ToAPIIssue(ctx, issue)
} }
if c.RefCommentID != 0 { if c.RefCommentID != 0 {
com, err := issues_model.GetCommentByID(db.DefaultContext, c.RefCommentID) com, err := issues_model.GetCommentByID(ctx, c.RefCommentID)
if err != nil { if err != nil {
log.Error("GetCommentByID(%d): %v", c.RefCommentID, err) log.Error("GetCommentByID(%d): %v", c.RefCommentID, err)
return nil return nil
} }
err = com.LoadPoster() err = com.LoadPoster(ctx)
if err != nil { if err != nil {
log.Error("LoadPoster: %v", err) log.Error("LoadPoster: %v", err)
return nil return nil
@ -138,17 +139,17 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time
var repo *repo_model.Repository var repo *repo_model.Repository
if c.Label.BelongsToOrg() { if c.Label.BelongsToOrg() {
var err error var err error
org, err = user_model.GetUserByID(c.Label.OrgID) org, err = user_model.GetUserByIDCtx(ctx, c.Label.OrgID)
if err != nil { if err != nil {
log.Error("GetUserByID(%d): %v", c.Label.OrgID, err) log.Error("GetUserByIDCtx(%d): %v", c.Label.OrgID, err)
return nil return nil
} }
} }
if c.Label.BelongsToRepo() { if c.Label.BelongsToRepo() {
var err error var err error
repo, err = repo_model.GetRepositoryByID(c.Label.RepoID) repo, err = repo_model.GetRepositoryByIDCtx(ctx, c.Label.RepoID)
if err != nil { if err != nil {
log.Error("GetRepositoryByID(%d): %v", c.Label.RepoID, err) log.Error("GetRepositoryByIDCtx(%d): %v", c.Label.RepoID, err)
return nil return nil
} }
} }
@ -167,7 +168,7 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time
} }
if c.DependentIssue != nil { if c.DependentIssue != nil {
comment.DependentIssue = ToAPIIssue(c.DependentIssue) comment.DependentIssue = ToAPIIssue(ctx, c.DependentIssue)
} }
return comment return comment

View file

@ -33,13 +33,13 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
return nil return nil
} }
apiIssue := ToAPIIssue(pr.Issue) apiIssue := ToAPIIssue(ctx, pr.Issue)
if err := pr.LoadBaseRepoCtx(ctx); err != nil { if err := pr.LoadBaseRepo(ctx); err != nil {
log.Error("GetRepositoryById[%d]: %v", pr.ID, err) log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
return nil return nil
} }
if err := pr.LoadHeadRepoCtx(ctx); err != nil { if err := pr.LoadHeadRepo(ctx); err != nil {
log.Error("GetRepositoryById[%d]: %v", pr.ID, err) log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
return nil return nil
} }

View file

@ -7,6 +7,7 @@ package convert
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -22,8 +23,8 @@ func TestPullRequest_APIFormat(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadAttributes()) assert.NoError(t, pr.LoadAttributes(db.DefaultContext))
assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadIssue(db.DefaultContext))
apiPullRequest := ToAPIPullRequest(git.DefaultContext, pr, nil) apiPullRequest := ToAPIPullRequest(git.DefaultContext, pr, nil)
assert.NotNil(t, apiPullRequest) assert.NotNil(t, apiPullRequest)
assert.EqualValues(t, &structs.PRBranchInfo{ assert.EqualValues(t, &structs.PRBranchInfo{
@ -36,8 +37,8 @@ func TestPullRequest_APIFormat(t *testing.T) {
// withOut HeadRepo // withOut HeadRepo
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadIssue(db.DefaultContext))
assert.NoError(t, pr.LoadAttributes()) assert.NoError(t, pr.LoadAttributes(db.DefaultContext))
// simulate fork deletion // simulate fork deletion
pr.HeadRepo = nil pr.HeadRepo = nil
pr.HeadRepoID = 100000 pr.HeadRepoID = 100000

View file

@ -18,13 +18,13 @@ import (
type consistencyCheck struct { type consistencyCheck struct {
Name string Name string
Counter func() (int64, error) Counter func(context.Context) (int64, error)
Fixer func() (int64, error) Fixer func(context.Context) (int64, error)
FixedMessage string FixedMessage string
} }
func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix bool) error { func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix bool) error {
count, err := c.Counter() count, err := c.Counter(ctx)
if err != nil { if err != nil {
logger.Critical("Error: %v whilst counting %s", err, c.Name) logger.Critical("Error: %v whilst counting %s", err, c.Name)
return err return err
@ -32,7 +32,7 @@ func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix b
if count > 0 { if count > 0 {
if autofix { if autofix {
var fixed int64 var fixed int64
if fixed, err = c.Fixer(); err != nil { if fixed, err = c.Fixer(ctx); err != nil {
logger.Critical("Error: %v whilst fixing %s", err, c.Name) logger.Critical("Error: %v whilst fixing %s", err, c.Name)
return err return err
} }
@ -54,9 +54,9 @@ func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix b
return nil return nil
} }
func asFixer(fn func() error) func() (int64, error) { func asFixer(fn func(ctx context.Context) error) func(ctx context.Context) (int64, error) {
return func() (int64, error) { return func(ctx context.Context) (int64, error) {
err := fn() err := fn(ctx)
return -1, err return -1, err
} }
} }
@ -64,11 +64,11 @@ func asFixer(fn func() error) func() (int64, error) {
func genericOrphanCheck(name, subject, refobject, joincond string) consistencyCheck { func genericOrphanCheck(name, subject, refobject, joincond string) consistencyCheck {
return consistencyCheck{ return consistencyCheck{
Name: name, Name: name,
Counter: func() (int64, error) { Counter: func(ctx context.Context) (int64, error) {
return db.CountOrphanedObjects(subject, refobject, joincond) return db.CountOrphanedObjects(ctx, subject, refobject, joincond)
}, },
Fixer: func() (int64, error) { Fixer: func(ctx context.Context) (int64, error) {
err := db.DeleteOrphanedObjects(subject, refobject, joincond) err := db.DeleteOrphanedObjects(ctx, subject, refobject, joincond)
return -1, err return -1, err
}, },
} }

View file

@ -291,7 +291,7 @@ func populateIssueIndexer(ctx context.Context) {
return return
default: default:
} }
repos, _, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ repos, _, err := repo_model.SearchRepositoryByName(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{Page: page, PageSize: repo_model.RepositoryListDefaultPageSize}, ListOptions: db.ListOptions{Page: page, PageSize: repo_model.RepositoryListDefaultPageSize},
OrderBy: db.SearchOrderByID, OrderBy: db.SearchOrderByID,
Private: true, Private: true,
@ -313,14 +313,14 @@ func populateIssueIndexer(ctx context.Context) {
return return
default: default:
} }
UpdateRepoIndexer(repo) UpdateRepoIndexer(ctx, repo)
} }
} }
} }
// UpdateRepoIndexer add/update all issues of the repositories // UpdateRepoIndexer add/update all issues of the repositories
func UpdateRepoIndexer(repo *repo_model.Repository) { func UpdateRepoIndexer(ctx context.Context, repo *repo_model.Repository) {
is, err := issues_model.Issues(&issues_model.IssuesOptions{ is, err := issues_model.Issues(ctx, &issues_model.IssuesOptions{
RepoID: repo.ID, RepoID: repo.ID,
IsClosed: util.OptionalBoolNone, IsClosed: util.OptionalBoolNone,
IsPull: util.OptionalBoolNone, IsPull: util.OptionalBoolNone,
@ -329,8 +329,8 @@ func UpdateRepoIndexer(repo *repo_model.Repository) {
log.Error("Issues: %v", err) log.Error("Issues: %v", err)
return return
} }
if err = issues_model.IssueList(is).LoadDiscussComments(); err != nil { if err = issues_model.IssueList(is).LoadDiscussComments(ctx); err != nil {
log.Error("LoadComments: %v", err) log.Error("LoadDiscussComments: %v", err)
return return
} }
for _, issue := range is { for _, issue := range is {
@ -360,11 +360,11 @@ func UpdateIssueIndexer(issue *issues_model.Issue) {
} }
// DeleteRepoIssueIndexer deletes repo's all issues indexes // DeleteRepoIssueIndexer deletes repo's all issues indexes
func DeleteRepoIssueIndexer(repo *repo_model.Repository) { func DeleteRepoIssueIndexer(ctx context.Context, repo *repo_model.Repository) {
var ids []int64 var ids []int64
ids, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, repo.ID) ids, err := issues_model.GetIssueIDsByRepoID(ctx, repo.ID)
if err != nil { if err != nil {
log.Error("getIssueIDsByRepoID failed: %v", err) log.Error("GetIssueIDsByRepoID failed: %v", err)
return return
} }

View file

@ -5,20 +5,18 @@
package action package action
import ( import (
"context"
"fmt" "fmt"
"path" "path"
"strings" "strings"
activities_model "code.gitea.io/gitea/models/activities" activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/notification/base" "code.gitea.io/gitea/modules/notification/base"
"code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
) )
@ -34,18 +32,18 @@ func NewNotifier() base.Notifier {
return &actionNotifier{} return &actionNotifier{}
} }
func (a *actionNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func (a *actionNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
if err := issue.LoadPoster(); err != nil { if err := issue.LoadPoster(ctx); err != nil {
log.Error("issue.LoadPoster: %v", err) log.Error("issue.LoadPoster: %v", err)
return return
} }
if err := issue.LoadRepo(db.DefaultContext); err != nil { if err := issue.LoadRepo(ctx); err != nil {
log.Error("issue.LoadRepo: %v", err) log.Error("issue.LoadRepo: %v", err)
return return
} }
repo := issue.Repo repo := issue.Repo
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: issue.Poster.ID, ActUserID: issue.Poster.ID,
ActUser: issue.Poster, ActUser: issue.Poster,
OpType: activities_model.ActionCreateIssue, OpType: activities_model.ActionCreateIssue,
@ -59,7 +57,7 @@ func (a *actionNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*u
} }
// NotifyIssueChangeStatus notifies close or reopen issue to notifiers // NotifyIssueChangeStatus notifies close or reopen issue to notifiers
func (a *actionNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) { func (a *actionNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) {
// Compose comment action, could be plain comment, close or reopen issue/pull request. // Compose comment action, could be plain comment, close or reopen issue/pull request.
// This object will be used to notify watchers in the end of function. // This object will be used to notify watchers in the end of function.
act := &activities_model.Action{ act := &activities_model.Action{
@ -86,13 +84,13 @@ func (a *actionNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *i
} }
// Notify watchers for whatever action comes in, ignore if no action type. // Notify watchers for whatever action comes in, ignore if no action type.
if err := activities_model.NotifyWatchers(act); err != nil { if err := activities_model.NotifyWatchers(ctx, act); err != nil {
log.Error("NotifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
// NotifyCreateIssueComment notifies comment on an issue to notifiers // NotifyCreateIssueComment notifies comment on an issue to notifiers
func (a *actionNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func (a *actionNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
act := &activities_model.Action{ act := &activities_model.Action{
@ -122,26 +120,26 @@ func (a *actionNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *r
} }
// Notify watchers for whatever action comes in, ignore if no action type. // Notify watchers for whatever action comes in, ignore if no action type.
if err := activities_model.NotifyWatchers(act); err != nil { if err := activities_model.NotifyWatchers(ctx, act); err != nil {
log.Error("NotifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, mentions []*user_model.User) { func (a *actionNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues_model.PullRequest, mentions []*user_model.User) {
if err := pull.LoadIssue(); err != nil { if err := pull.LoadIssue(ctx); err != nil {
log.Error("pull.LoadIssue: %v", err) log.Error("pull.LoadIssue: %v", err)
return return
} }
if err := pull.Issue.LoadRepo(db.DefaultContext); err != nil { if err := pull.Issue.LoadRepo(ctx); err != nil {
log.Error("pull.Issue.LoadRepo: %v", err) log.Error("pull.Issue.LoadRepo: %v", err)
return return
} }
if err := pull.Issue.LoadPoster(); err != nil { if err := pull.Issue.LoadPoster(ctx); err != nil {
log.Error("pull.Issue.LoadPoster: %v", err) log.Error("pull.Issue.LoadPoster: %v", err)
return return
} }
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: pull.Issue.Poster.ID, ActUserID: pull.Issue.Poster.ID,
ActUser: pull.Issue.Poster, ActUser: pull.Issue.Poster,
OpType: activities_model.ActionCreatePullRequest, OpType: activities_model.ActionCreatePullRequest,
@ -154,8 +152,8 @@ func (a *actionNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, me
} }
} }
func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { func (a *actionNotifier) NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldRepoName string) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionRenameRepo, OpType: activities_model.ActionRenameRepo,
@ -168,8 +166,8 @@ func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *rep
} }
} }
func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { func (a *actionNotifier) NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionTransferRepo, OpType: activities_model.ActionTransferRepo,
@ -182,8 +180,8 @@ func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *r
} }
} }
func (a *actionNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func (a *actionNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionCreateRepo, OpType: activities_model.ActionCreateRepo,
@ -195,8 +193,8 @@ func (a *actionNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *
} }
} }
func (a *actionNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { func (a *actionNotifier) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionCreateRepo, OpType: activities_model.ActionCreateRepo,
@ -208,11 +206,8 @@ func (a *actionNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, re
} }
} }
func (a *actionNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { func (a *actionNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("actionNotifier.NotifyPullRequestReview Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) if err := review.LoadReviewer(ctx); err != nil {
defer finished()
if err := review.LoadReviewer(); err != nil {
log.Error("LoadReviewer '%d/%d': %v", review.ID, review.ReviewerID, err) log.Error("LoadReviewer '%d/%d': %v", review.ID, review.ReviewerID, err)
return return
} }
@ -269,8 +264,8 @@ func (a *actionNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r
} }
} }
func (*actionNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (*actionNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionMergePullRequest, OpType: activities_model.ActionMergePullRequest,
@ -283,8 +278,8 @@ func (*actionNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer
} }
} }
func (*actionNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (*actionNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionAutoMergePullRequest, OpType: activities_model.ActionAutoMergePullRequest,
@ -297,12 +292,12 @@ func (*actionNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest,
} }
} }
func (*actionNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { func (*actionNotifier) NotifyPullRevieweDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) {
reviewerName := review.Reviewer.Name reviewerName := review.Reviewer.Name
if len(review.OriginalAuthor) > 0 { if len(review.OriginalAuthor) > 0 {
reviewerName = review.OriginalAuthor reviewerName = review.OriginalAuthor
} }
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: activities_model.ActionPullReviewDismissed, OpType: activities_model.ActionPullReviewDismissed,
@ -317,7 +312,7 @@ func (*actionNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *i
} }
} }
func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (a *actionNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
data, err := json.Marshal(commits) data, err := json.Marshal(commits)
if err != nil { if err != nil {
log.Error("Marshal: %v", err) log.Error("Marshal: %v", err)
@ -336,7 +331,7 @@ func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_m
opType = activities_model.ActionDeleteBranch opType = activities_model.ActionDeleteBranch
} }
if err = activities_model.NotifyWatchers(&activities_model.Action{ if err = activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: pusher.ID, ActUserID: pusher.ID,
ActUser: pusher, ActUser: pusher,
OpType: opType, OpType: opType,
@ -346,17 +341,17 @@ func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_m
RefName: opts.RefFullName, RefName: opts.RefFullName,
IsPrivate: repo.IsPrivate, IsPrivate: repo.IsPrivate,
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func (a *actionNotifier) NotifyCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
opType := activities_model.ActionCommitRepo opType := activities_model.ActionCommitRepo
if refType == "tag" { if refType == "tag" {
// has sent same action in `NotifyPushCommits`, so skip it. // has sent same action in `NotifyPushCommits`, so skip it.
return return
} }
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: opType, OpType: opType,
@ -365,17 +360,17 @@ func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model
IsPrivate: repo.IsPrivate, IsPrivate: repo.IsPrivate,
RefName: refFullName, RefName: refFullName,
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func (a *actionNotifier) NotifyDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
opType := activities_model.ActionDeleteBranch opType := activities_model.ActionDeleteBranch
if refType == "tag" { if refType == "tag" {
// has sent same action in `NotifyPushCommits`, so skip it. // has sent same action in `NotifyPushCommits`, so skip it.
return return
} }
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,
OpType: opType, OpType: opType,
@ -384,20 +379,20 @@ func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model
IsPrivate: repo.IsPrivate, IsPrivate: repo.IsPrivate,
RefName: refFullName, RefName: refFullName,
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (a *actionNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
data, err := json.Marshal(commits) data, err := json.Marshal(commits)
if err != nil { if err != nil {
log.Error("json.Marshal: %v", err) log.Error("json.Marshal: %v", err)
return return
} }
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: repo.OwnerID, ActUserID: repo.OwnerID,
ActUser: repo.MustOwner(), ActUser: repo.MustOwner(ctx),
OpType: activities_model.ActionMirrorSyncPush, OpType: activities_model.ActionMirrorSyncPush,
RepoID: repo.ID, RepoID: repo.ID,
Repo: repo, Repo: repo,
@ -405,44 +400,44 @@ func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *re
RefName: opts.RefFullName, RefName: opts.RefFullName,
Content: string(data), Content: string(data),
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func (a *actionNotifier) NotifySyncCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: repo.OwnerID, ActUserID: repo.OwnerID,
ActUser: repo.MustOwner(), ActUser: repo.MustOwner(ctx),
OpType: activities_model.ActionMirrorSyncCreate, OpType: activities_model.ActionMirrorSyncCreate,
RepoID: repo.ID, RepoID: repo.ID,
Repo: repo, Repo: repo,
IsPrivate: repo.IsPrivate, IsPrivate: repo.IsPrivate,
RefName: refFullName, RefName: refFullName,
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func (a *actionNotifier) NotifySyncDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: repo.OwnerID, ActUserID: repo.OwnerID,
ActUser: repo.MustOwner(), ActUser: repo.MustOwner(ctx),
OpType: activities_model.ActionMirrorSyncDelete, OpType: activities_model.ActionMirrorSyncDelete,
RepoID: repo.ID, RepoID: repo.ID,
Repo: repo, Repo: repo,
IsPrivate: repo.IsPrivate, IsPrivate: repo.IsPrivate,
RefName: refFullName, RefName: refFullName,
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }
func (a *actionNotifier) NotifyNewRelease(rel *repo_model.Release) { func (a *actionNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) {
if err := rel.LoadAttributes(); err != nil { if err := rel.LoadAttributes(ctx); err != nil {
log.Error("NotifyNewRelease: %v", err) log.Error("LoadAttributes: %v", err)
return return
} }
if err := activities_model.NotifyWatchers(&activities_model.Action{ if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{
ActUserID: rel.PublisherID, ActUserID: rel.PublisherID,
ActUser: rel.Publisher, ActUser: rel.Publisher,
OpType: activities_model.ActionPublishRelease, OpType: activities_model.ActionPublishRelease,
@ -452,6 +447,6 @@ func (a *actionNotifier) NotifyNewRelease(rel *repo_model.Release) {
Content: rel.Title, Content: rel.Title,
RefName: rel.TagName, RefName: rel.TagName,
}); err != nil { }); err != nil {
log.Error("notifyWatchers: %v", err) log.Error("NotifyWatchers: %v", err)
} }
} }

View file

@ -10,6 +10,7 @@ import (
"testing" "testing"
activities_model "code.gitea.io/gitea/models/activities" activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -46,7 +47,7 @@ func TestRenameRepoAction(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, actionBean) unittest.AssertNotExistsBean(t, actionBean)
NewNotifier().NotifyRenameRepository(user, repo, oldRepoName) NewNotifier().NotifyRenameRepository(db.DefaultContext, user, repo, oldRepoName)
unittest.AssertExistsAndLoadBean(t, actionBean) unittest.AssertExistsAndLoadBean(t, actionBean)
unittest.CheckConsistencyFor(t, &activities_model.Action{}) unittest.CheckConsistencyFor(t, &activities_model.Action{})

View file

@ -5,6 +5,8 @@
package base package base
import ( import (
"context"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
packages_model "code.gitea.io/gitea/models/packages" packages_model "code.gitea.io/gitea/models/packages"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -15,50 +17,50 @@ import (
// Notifier defines an interface to notify receiver // Notifier defines an interface to notify receiver
type Notifier interface { type Notifier interface {
Run() Run()
NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository)
NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository)
NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository)
NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository)
NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldRepoName string)
NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldOwnerName string)
NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User)
NotifyIssueChangeStatus(*user_model.User, *issues_model.Issue, *issues_model.Comment, bool) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool)
NotifyDeleteIssue(*user_model.User, *issues_model.Issue) NotifyDeleteIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Issue)
NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64)
NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment)
NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment)
NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string)
NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue)
NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string)
NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldRef string) NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldRef string)
NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue,
addedLabels, removedLabels []*issues_model.Label) addedLabels, removedLabels []*issues_model.Label)
NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User)
NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest)
NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest)
NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest)
NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User)
NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User)
NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string)
NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment)
NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment)
NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User) issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User)
NotifyUpdateComment(*user_model.User, *issues_model.Comment, string) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string)
NotifyDeleteComment(*user_model.User, *issues_model.Comment) NotifyDeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment)
NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string)
NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string)
NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string)
NotifyNewRelease(rel *repo_model.Release) NotifyNewRelease(ctx context.Context, rel *repo_model.Release)
NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release)
NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release)
NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits)
NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) NotifyCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string)
NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) NotifyDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string)
NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits)
NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) NotifySyncCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string)
NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) NotifySyncDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string)
NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository)
NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor)
NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor)
} }

View file

@ -5,6 +5,8 @@
package base package base
import ( import (
"context"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
packages_model "code.gitea.io/gitea/models/packages" packages_model "code.gitea.io/gitea/models/packages"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -22,179 +24,179 @@ func (*NullNotifier) Run() {
} }
// NotifyCreateIssueComment places a place holder function // NotifyCreateIssueComment places a place holder function
func (*NullNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func (*NullNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User) { issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User) {
} }
// NotifyNewIssue places a place holder function // NotifyNewIssue places a place holder function
func (*NullNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func (*NullNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
} }
// NotifyIssueChangeStatus places a place holder function // NotifyIssueChangeStatus places a place holder function
func (*NullNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { func (*NullNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) {
} }
// NotifyDeleteIssue notify when some issue deleted // NotifyDeleteIssue notify when some issue deleted
func (*NullNotifier) NotifyDeleteIssue(doer *user_model.User, issue *issues_model.Issue) { func (*NullNotifier) NotifyDeleteIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) {
} }
// NotifyNewPullRequest places a place holder function // NotifyNewPullRequest places a place holder function
func (*NullNotifier) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { func (*NullNotifier) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) {
} }
// NotifyPullRequestReview places a place holder function // NotifyPullRequestReview places a place holder function
func (*NullNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { func (*NullNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) {
} }
// NotifyPullRequestCodeComment places a place holder function // NotifyPullRequestCodeComment places a place holder function
func (*NullNotifier) NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { func (*NullNotifier) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) {
} }
// NotifyMergePullRequest places a place holder function // NotifyMergePullRequest places a place holder function
func (*NullNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (*NullNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
} }
// NotifyAutoMergePullRequest places a place holder function // NotifyAutoMergePullRequest places a place holder function
func (*NullNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (*NullNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
} }
// NotifyPullRequestSynchronized places a place holder function // NotifyPullRequestSynchronized places a place holder function
func (*NullNotifier) NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) { func (*NullNotifier) NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
} }
// NotifyPullRequestChangeTargetBranch places a place holder function // NotifyPullRequestChangeTargetBranch places a place holder function
func (*NullNotifier) NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { func (*NullNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) {
} }
// NotifyPullRequestPushCommits notifies when push commits to pull request's head branch // NotifyPullRequestPushCommits notifies when push commits to pull request's head branch
func (*NullNotifier) NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { func (*NullNotifier) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) {
} }
// NotifyPullRevieweDismiss notifies when a review was dismissed by repo admin // NotifyPullReviewDismiss notifies when a review was dismissed by repo admin
func (*NullNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { func (*NullNotifier) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) {
} }
// NotifyUpdateComment places a place holder function // NotifyUpdateComment places a place holder function
func (*NullNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { func (*NullNotifier) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) {
} }
// NotifyDeleteComment places a place holder function // NotifyDeleteComment places a place holder function
func (*NullNotifier) NotifyDeleteComment(doer *user_model.User, c *issues_model.Comment) { func (*NullNotifier) NotifyDeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment) {
} }
// NotifyNewWikiPage places a place holder function // NotifyNewWikiPage places a place holder function
func (*NullNotifier) NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { func (*NullNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) {
} }
// NotifyEditWikiPage places a place holder function // NotifyEditWikiPage places a place holder function
func (*NullNotifier) NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { func (*NullNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) {
} }
// NotifyDeleteWikiPage places a place holder function // NotifyDeleteWikiPage places a place holder function
func (*NullNotifier) NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) { func (*NullNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) {
} }
// NotifyNewRelease places a place holder function // NotifyNewRelease places a place holder function
func (*NullNotifier) NotifyNewRelease(rel *repo_model.Release) { func (*NullNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) {
} }
// NotifyUpdateRelease places a place holder function // NotifyUpdateRelease places a place holder function
func (*NullNotifier) NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) { func (*NullNotifier) NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) {
} }
// NotifyDeleteRelease places a place holder function // NotifyDeleteRelease places a place holder function
func (*NullNotifier) NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) { func (*NullNotifier) NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) {
} }
// NotifyIssueChangeMilestone places a place holder function // NotifyIssueChangeMilestone places a place holder function
func (*NullNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { func (*NullNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) {
} }
// NotifyIssueChangeContent places a place holder function // NotifyIssueChangeContent places a place holder function
func (*NullNotifier) NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { func (*NullNotifier) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) {
} }
// NotifyIssueChangeAssignee places a place holder function // NotifyIssueChangeAssignee places a place holder function
func (*NullNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { func (*NullNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) {
} }
// NotifyPullReviewRequest places a place holder function // NotifyPullReviewRequest places a place holder function
func (*NullNotifier) NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { func (*NullNotifier) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) {
} }
// NotifyIssueClearLabels places a place holder function // NotifyIssueClearLabels places a place holder function
func (*NullNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) { func (*NullNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) {
} }
// NotifyIssueChangeTitle places a place holder function // NotifyIssueChangeTitle places a place holder function
func (*NullNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func (*NullNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
} }
// NotifyIssueChangeRef places a place holder function // NotifyIssueChangeRef places a place holder function
func (*NullNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func (*NullNotifier) NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
} }
// NotifyIssueChangeLabels places a place holder function // NotifyIssueChangeLabels places a place holder function
func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, func (*NullNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue,
addedLabels, removedLabels []*issues_model.Label) { addedLabels, removedLabels []*issues_model.Label) {
} }
// NotifyCreateRepository places a place holder function // NotifyCreateRepository places a place holder function
func (*NullNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func (*NullNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
} }
// NotifyDeleteRepository places a place holder function // NotifyDeleteRepository places a place holder function
func (*NullNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { func (*NullNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) {
} }
// NotifyForkRepository places a place holder function // NotifyForkRepository places a place holder function
func (*NullNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { func (*NullNotifier) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) {
} }
// NotifyMigrateRepository places a place holder function // NotifyMigrateRepository places a place holder function
func (*NullNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func (*NullNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
} }
// NotifyPushCommits notifies commits pushed to notifiers // NotifyPushCommits notifies commits pushed to notifiers
func (*NullNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (*NullNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
} }
// NotifyCreateRef notifies branch or tag creation to notifiers // NotifyCreateRef notifies branch or tag creation to notifiers
func (*NullNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func (*NullNotifier) NotifyCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
} }
// NotifyDeleteRef notifies branch or tag deletion to notifiers // NotifyDeleteRef notifies branch or tag deletion to notifiers
func (*NullNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func (*NullNotifier) NotifyDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
} }
// NotifyRenameRepository places a place holder function // NotifyRenameRepository places a place holder function
func (*NullNotifier) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { func (*NullNotifier) NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldRepoName string) {
} }
// NotifyTransferRepository places a place holder function // NotifyTransferRepository places a place holder function
func (*NullNotifier) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { func (*NullNotifier) NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) {
} }
// NotifySyncPushCommits places a place holder function // NotifySyncPushCommits places a place holder function
func (*NullNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (*NullNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
} }
// NotifySyncCreateRef places a place holder function // NotifySyncCreateRef places a place holder function
func (*NullNotifier) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func (*NullNotifier) NotifySyncCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
} }
// NotifySyncDeleteRef places a place holder function // NotifySyncDeleteRef places a place holder function
func (*NullNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func (*NullNotifier) NotifySyncDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
} }
// NotifyRepoPendingTransfer places a place holder function // NotifyRepoPendingTransfer places a place holder function
func (*NullNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { func (*NullNotifier) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) {
} }
// NotifyPackageCreate places a place holder function // NotifyPackageCreate places a place holder function
func (*NullNotifier) NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) { func (*NullNotifier) NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
} }
// NotifyPackageDelete places a place holder function // NotifyPackageDelete places a place holder function
func (*NullNotifier) NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) { func (*NullNotifier) NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
} }

View file

@ -5,6 +5,8 @@
package indexer package indexer
import ( import (
"context"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -29,13 +31,13 @@ func NewNotifier() base.Notifier {
return &indexerNotifier{} return &indexerNotifier{}
} }
func (r *indexerNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func (r *indexerNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
if comment.Type == issues_model.CommentTypeComment { if comment.Type == issues_model.CommentTypeComment {
if issue.Comments == nil { if issue.Comments == nil {
if err := issue.LoadDiscussComments(); err != nil { if err := issue.LoadDiscussComments(ctx); err != nil {
log.Error("LoadComments failed: %v", err) log.Error("LoadDiscussComments failed: %v", err)
return return
} }
} else { } else {
@ -46,15 +48,15 @@ func (r *indexerNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *
} }
} }
func (r *indexerNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func (r *indexerNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
issue_indexer.UpdateIssueIndexer(issue) issue_indexer.UpdateIssueIndexer(issue)
} }
func (r *indexerNotifier) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { func (r *indexerNotifier) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) {
issue_indexer.UpdateIssueIndexer(pr.Issue) issue_indexer.UpdateIssueIndexer(pr.Issue)
} }
func (r *indexerNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { func (r *indexerNotifier) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) {
if c.Type == issues_model.CommentTypeComment { if c.Type == issues_model.CommentTypeComment {
var found bool var found bool
if c.Issue.Comments != nil { if c.Issue.Comments != nil {
@ -68,8 +70,8 @@ func (r *indexerNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m
} }
if !found { if !found {
if err := c.Issue.LoadDiscussComments(); err != nil { if err := c.Issue.LoadDiscussComments(ctx); err != nil {
log.Error("LoadComments failed: %v", err) log.Error("LoadDiscussComments failed: %v", err)
return return
} }
} }
@ -78,9 +80,9 @@ func (r *indexerNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m
} }
} }
func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *issues_model.Comment) { func (r *indexerNotifier) NotifyDeleteComment(ctx context.Context, doer *user_model.User, comment *issues_model.Comment) {
if comment.Type == issues_model.CommentTypeComment { if comment.Type == issues_model.CommentTypeComment {
if err := comment.LoadIssue(); err != nil { if err := comment.LoadIssue(ctx); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
@ -97,8 +99,8 @@ func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *is
} }
if !found { if !found {
if err := comment.Issue.LoadDiscussComments(); err != nil { if err := comment.Issue.LoadDiscussComments(ctx); err != nil {
log.Error("LoadComments failed: %v", err) log.Error("LoadDiscussComments failed: %v", err)
return return
} }
} }
@ -107,15 +109,15 @@ func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *is
} }
} }
func (r *indexerNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { func (r *indexerNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) {
issue_indexer.DeleteRepoIssueIndexer(repo) issue_indexer.DeleteRepoIssueIndexer(ctx, repo)
if setting.Indexer.RepoIndexerEnabled { if setting.Indexer.RepoIndexerEnabled {
code_indexer.UpdateRepoIndexer(repo) code_indexer.UpdateRepoIndexer(repo)
} }
} }
func (r *indexerNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func (r *indexerNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
issue_indexer.UpdateRepoIndexer(repo) issue_indexer.UpdateRepoIndexer(ctx, repo)
if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty { if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty {
code_indexer.UpdateRepoIndexer(repo) code_indexer.UpdateRepoIndexer(repo)
} }
@ -124,7 +126,7 @@ func (r *indexerNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo
} }
} }
func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (r *indexerNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch { if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch {
code_indexer.UpdateRepoIndexer(repo) code_indexer.UpdateRepoIndexer(repo)
} }
@ -133,7 +135,7 @@ func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_
} }
} }
func (r *indexerNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (r *indexerNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch { if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch {
code_indexer.UpdateRepoIndexer(repo) code_indexer.UpdateRepoIndexer(repo)
} }
@ -142,14 +144,14 @@ func (r *indexerNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *r
} }
} }
func (r *indexerNotifier) NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { func (r *indexerNotifier) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) {
issue_indexer.UpdateIssueIndexer(issue) issue_indexer.UpdateIssueIndexer(issue)
} }
func (r *indexerNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func (r *indexerNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
issue_indexer.UpdateIssueIndexer(issue) issue_indexer.UpdateIssueIndexer(issue)
} }
func (r *indexerNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldRef string) { func (r *indexerNotifier) NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldRef string) {
issue_indexer.UpdateIssueIndexer(issue) issue_indexer.UpdateIssueIndexer(issue)
} }

View file

@ -5,16 +5,15 @@
package mail package mail
import ( import (
"context"
"fmt" "fmt"
activities_model "code.gitea.io/gitea/models/activities" activities_model "code.gitea.io/gitea/models/activities"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/notification/base" "code.gitea.io/gitea/modules/notification/base"
"code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/services/mailer" "code.gitea.io/gitea/services/mailer"
) )
@ -29,12 +28,9 @@ func NewNotifier() base.Notifier {
return &mailNotifier{} return &mailNotifier{}
} }
func (m *mailNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func (m *mailNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyCreateIssueComment Issue[%d] #%d in [%d]", issue.ID, issue.Index, issue.RepoID))
defer finished()
var act activities_model.ActionType var act activities_model.ActionType
if comment.Type == issues_model.CommentTypeClose { if comment.Type == issues_model.CommentTypeClose {
act = activities_model.ActionCloseIssue act = activities_model.ActionCloseIssue
@ -53,13 +49,13 @@ func (m *mailNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *rep
} }
} }
func (m *mailNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func (m *mailNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
if err := mailer.MailParticipants(issue, issue.Poster, activities_model.ActionCreateIssue, mentions); err != nil { if err := mailer.MailParticipants(ctx, issue, issue.Poster, activities_model.ActionCreateIssue, mentions); err != nil {
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
} }
func (m *mailNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { func (m *mailNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) {
var actionType activities_model.ActionType var actionType activities_model.ActionType
if issue.IsPull { if issue.IsPull {
if isClosed { if isClosed {
@ -75,33 +71,30 @@ func (m *mailNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *iss
} }
} }
if err := mailer.MailParticipants(issue, doer, actionType, nil); err != nil { if err := mailer.MailParticipants(ctx, issue, doer, actionType, nil); err != nil {
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
} }
func (m *mailNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func (m *mailNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
if err := issue.LoadPullRequest(); err != nil { if err := issue.LoadPullRequest(ctx); err != nil {
log.Error("issue.LoadPullRequest: %v", err) log.Error("issue.LoadPullRequest: %v", err)
return return
} }
if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress() { if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress() {
if err := mailer.MailParticipants(issue, doer, activities_model.ActionPullRequestReadyForReview, nil); err != nil { if err := mailer.MailParticipants(ctx, issue, doer, activities_model.ActionPullRequestReadyForReview, nil); err != nil {
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
} }
} }
func (m *mailNotifier) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { func (m *mailNotifier) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) {
if err := mailer.MailParticipants(pr.Issue, pr.Issue.Poster, activities_model.ActionCreatePullRequest, mentions); err != nil { if err := mailer.MailParticipants(ctx, pr.Issue, pr.Issue.Poster, activities_model.ActionCreatePullRequest, mentions); err != nil {
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
} }
func (m *mailNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { func (m *mailNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRequestReview Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID))
defer finished()
var act activities_model.ActionType var act activities_model.ActionType
if comment.Type == issues_model.CommentTypeClose { if comment.Type == issues_model.CommentTypeClose {
act = activities_model.ActionCloseIssue act = activities_model.ActionCloseIssue
@ -115,60 +108,54 @@ func (m *mailNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r *
} }
} }
func (m *mailNotifier) NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { func (m *mailNotifier) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRequestCodeComment Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID))
defer finished()
if err := mailer.MailMentionsComment(ctx, pr, comment, mentions); err != nil { if err := mailer.MailMentionsComment(ctx, pr, comment, mentions); err != nil {
log.Error("MailMentionsComment: %v", err) log.Error("MailMentionsComment: %v", err)
} }
} }
func (m *mailNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { func (m *mailNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) {
// mail only sent to added assignees and not self-assignee // mail only sent to added assignees and not self-assignee
if !removed && doer.ID != assignee.ID && assignee.EmailNotifications() != user_model.EmailNotificationsDisabled { if !removed && doer.ID != assignee.ID && assignee.EmailNotifications() != user_model.EmailNotificationsDisabled {
ct := fmt.Sprintf("Assigned #%d.", issue.Index) ct := fmt.Sprintf("Assigned #%d.", issue.Index)
if err := mailer.SendIssueAssignedMail(issue, doer, ct, comment, []*user_model.User{assignee}); err != nil { if err := mailer.SendIssueAssignedMail(ctx, issue, doer, ct, comment, []*user_model.User{assignee}); err != nil {
log.Error("Error in SendIssueAssignedMail for issue[%d] to assignee[%d]: %v", issue.ID, assignee.ID, err) log.Error("Error in SendIssueAssignedMail for issue[%d] to assignee[%d]: %v", issue.ID, assignee.ID, err)
} }
} }
} }
func (m *mailNotifier) NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { func (m *mailNotifier) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) {
if isRequest && doer.ID != reviewer.ID && reviewer.EmailNotifications() != user_model.EmailNotificationsDisabled { if isRequest && doer.ID != reviewer.ID && reviewer.EmailNotifications() != user_model.EmailNotificationsDisabled {
ct := fmt.Sprintf("Requested to review %s.", issue.HTMLURL()) ct := fmt.Sprintf("Requested to review %s.", issue.HTMLURL())
if err := mailer.SendIssueAssignedMail(issue, doer, ct, comment, []*user_model.User{reviewer}); err != nil { if err := mailer.SendIssueAssignedMail(ctx, issue, doer, ct, comment, []*user_model.User{reviewer}); err != nil {
log.Error("Error in SendIssueAssignedMail for issue[%d] to reviewer[%d]: %v", issue.ID, reviewer.ID, err) log.Error("Error in SendIssueAssignedMail for issue[%d] to reviewer[%d]: %v", issue.ID, reviewer.ID, err)
} }
} }
} }
func (m *mailNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (m *mailNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
log.Error("pr.LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
if err := mailer.MailParticipants(pr.Issue, doer, activities_model.ActionMergePullRequest, nil); err != nil { if err := mailer.MailParticipants(ctx, pr.Issue, doer, activities_model.ActionMergePullRequest, nil); err != nil {
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
} }
func (m *mailNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (m *mailNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
log.Error("pr.LoadIssue: %v", err) log.Error("pr.LoadIssue: %v", err)
return return
} }
if err := mailer.MailParticipants(pr.Issue, doer, activities_model.ActionAutoMergePullRequest, nil); err != nil { if err := mailer.MailParticipants(ctx, pr.Issue, doer, activities_model.ActionAutoMergePullRequest, nil); err != nil {
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
} }
func (m *mailNotifier) NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { func (m *mailNotifier) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRequestPushCommits Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID))
defer finished()
var err error var err error
if err = comment.LoadIssue(); err != nil { if err = comment.LoadIssue(ctx); err != nil {
log.Error("comment.LoadIssue: %v", err) log.Error("comment.LoadIssue: %v", err)
return return
} }
@ -176,35 +163,29 @@ func (m *mailNotifier) NotifyPullRequestPushCommits(doer *user_model.User, pr *i
log.Error("comment.Issue.LoadRepo: %v", err) log.Error("comment.Issue.LoadRepo: %v", err)
return return
} }
if err = comment.Issue.LoadPullRequest(); err != nil { if err = comment.Issue.LoadPullRequest(ctx); err != nil {
log.Error("comment.Issue.LoadPullRequest: %v", err) log.Error("comment.Issue.LoadPullRequest: %v", err)
return return
} }
if err = comment.Issue.PullRequest.LoadBaseRepoCtx(ctx); err != nil { if err = comment.Issue.PullRequest.LoadBaseRepo(ctx); err != nil {
log.Error("comment.Issue.PullRequest.LoadBaseRepo: %v", err) log.Error("comment.Issue.PullRequest.LoadBaseRepo: %v", err)
return return
} }
if err := comment.LoadPushCommits(ctx); err != nil { if err := comment.LoadPushCommits(ctx); err != nil {
log.Error("comment.LoadPushCommits: %v", err) log.Error("comment.LoadPushCommits: %v", err)
} }
m.NotifyCreateIssueComment(doer, comment.Issue.Repo, comment.Issue, comment, nil) m.NotifyCreateIssueComment(ctx, doer, comment.Issue.Repo, comment.Issue, comment, nil)
} }
func (m *mailNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { func (m *mailNotifier) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRevieweDismiss Review[%d] in Issue[%d]", review.ID, review.IssueID))
defer finished()
if err := mailer.MailParticipantsComment(ctx, comment, activities_model.ActionPullReviewDismissed, review.Issue, nil); err != nil { if err := mailer.MailParticipantsComment(ctx, comment, activities_model.ActionPullReviewDismissed, review.Issue, nil); err != nil {
log.Error("MailParticipantsComment: %v", err) log.Error("MailParticipantsComment: %v", err)
} }
} }
func (m *mailNotifier) NotifyNewRelease(rel *repo_model.Release) { func (m *mailNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyNewRelease rel[%d]%s in [%d]", rel.ID, rel.Title, rel.RepoID)) if err := rel.LoadAttributes(ctx); err != nil {
defer finished() log.Error("LoadAttributes: %v", err)
if err := rel.LoadAttributes(); err != nil {
log.Error("NotifyNewRelease: %v", err)
return return
} }
@ -215,8 +196,8 @@ func (m *mailNotifier) NotifyNewRelease(rel *repo_model.Release) {
mailer.MailNewRelease(ctx, rel) mailer.MailNewRelease(ctx, rel)
} }
func (m *mailNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { func (m *mailNotifier) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) {
if err := mailer.SendRepoTransferNotifyMail(doer, newOwner, repo); err != nil { if err := mailer.SendRepoTransferNotifyMail(ctx, doer, newOwner, repo); err != nil {
log.Error("NotifyRepoPendingTransfer: %v", err) log.Error("SendRepoTransferNotifyMail: %v", err)
} }
} }

View file

@ -5,6 +5,8 @@
package mirror package mirror
import ( import (
"context"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -24,16 +26,16 @@ func NewNotifier() base.Notifier {
return &mirrorNotifier{} return &mirrorNotifier{}
} }
func (m *mirrorNotifier) NotifyPushCommits(_ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) { func (m *mirrorNotifier) NotifyPushCommits(ctx context.Context, _ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) {
syncPushMirrorWithSyncOnCommit(repo.ID) syncPushMirrorWithSyncOnCommit(ctx, repo.ID)
} }
func (m *mirrorNotifier) NotifySyncPushCommits(_ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) { func (m *mirrorNotifier) NotifySyncPushCommits(ctx context.Context, _ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) {
syncPushMirrorWithSyncOnCommit(repo.ID) syncPushMirrorWithSyncOnCommit(ctx, repo.ID)
} }
func syncPushMirrorWithSyncOnCommit(repoID int64) { func syncPushMirrorWithSyncOnCommit(ctx context.Context, repoID int64) {
pushMirrors, err := repo_model.GetPushMirrorsSyncedOnCommit(repoID) pushMirrors, err := repo_model.GetPushMirrorsSyncedOnCommit(ctx, repoID)
if err != nil { if err != nil {
log.Error("repo_model.GetPushMirrorsSyncedOnCommit failed: %v", err) log.Error("repo_model.GetPushMirrorsSyncedOnCommit failed: %v", err)
return return

View file

@ -5,6 +5,8 @@
package notification package notification
import ( import (
"context"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
packages_model "code.gitea.io/gitea/models/packages" packages_model "code.gitea.io/gitea/models/packages"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -41,313 +43,313 @@ func NewContext() {
} }
// NotifyNewWikiPage notifies creating new wiki pages to notifiers // NotifyNewWikiPage notifies creating new wiki pages to notifiers
func NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { func NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyNewWikiPage(doer, repo, page, comment) notifier.NotifyNewWikiPage(ctx, doer, repo, page, comment)
} }
} }
// NotifyEditWikiPage notifies editing or renaming wiki pages to notifiers // NotifyEditWikiPage notifies editing or renaming wiki pages to notifiers
func NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { func NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyEditWikiPage(doer, repo, page, comment) notifier.NotifyEditWikiPage(ctx, doer, repo, page, comment)
} }
} }
// NotifyDeleteWikiPage notifies deleting wiki pages to notifiers // NotifyDeleteWikiPage notifies deleting wiki pages to notifiers
func NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) { func NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyDeleteWikiPage(doer, repo, page) notifier.NotifyDeleteWikiPage(ctx, doer, repo, page)
} }
} }
// NotifyCreateIssueComment notifies issue comment related message to notifiers // NotifyCreateIssueComment notifies issue comment related message to notifiers
func NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyCreateIssueComment(doer, repo, issue, comment, mentions) notifier.NotifyCreateIssueComment(ctx, doer, repo, issue, comment, mentions)
} }
} }
// NotifyNewIssue notifies new issue to notifiers // NotifyNewIssue notifies new issue to notifiers
func NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyNewIssue(issue, mentions) notifier.NotifyNewIssue(ctx, issue, mentions)
} }
} }
// NotifyIssueChangeStatus notifies close or reopen issue to notifiers // NotifyIssueChangeStatus notifies close or reopen issue to notifiers
func NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) { func NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeStatus(doer, issue, actionComment, closeOrReopen) notifier.NotifyIssueChangeStatus(ctx, doer, issue, actionComment, closeOrReopen)
} }
} }
// NotifyDeleteIssue notify when some issue deleted // NotifyDeleteIssue notify when some issue deleted
func NotifyDeleteIssue(doer *user_model.User, issue *issues_model.Issue) { func NotifyDeleteIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyDeleteIssue(doer, issue) notifier.NotifyDeleteIssue(ctx, doer, issue)
} }
} }
// NotifyMergePullRequest notifies merge pull request to notifiers // NotifyMergePullRequest notifies merge pull request to notifiers
func NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyMergePullRequest(pr, doer) notifier.NotifyMergePullRequest(ctx, doer, pr)
} }
} }
// NotifyAutoMergePullRequest notifies merge pull request to notifiers // NotifyAutoMergePullRequest notifies merge pull request to notifiers
func NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyAutoMergePullRequest(pr, doer) notifier.NotifyAutoMergePullRequest(ctx, doer, pr)
} }
} }
// NotifyNewPullRequest notifies new pull request to notifiers // NotifyNewPullRequest notifies new pull request to notifiers
func NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { func NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyNewPullRequest(pr, mentions) notifier.NotifyNewPullRequest(ctx, pr, mentions)
} }
} }
// NotifyPullRequestSynchronized notifies Synchronized pull request // NotifyPullRequestSynchronized notifies Synchronized pull request
func NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) { func NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullRequestSynchronized(doer, pr) notifier.NotifyPullRequestSynchronized(ctx, doer, pr)
} }
} }
// NotifyPullRequestReview notifies new pull request review // NotifyPullRequestReview notifies new pull request review
func NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { func NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullRequestReview(pr, review, comment, mentions) notifier.NotifyPullRequestReview(ctx, pr, review, comment, mentions)
} }
} }
// NotifyPullRequestCodeComment notifies new pull request code comment // NotifyPullRequestCodeComment notifies new pull request code comment
func NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { func NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullRequestCodeComment(pr, comment, mentions) notifier.NotifyPullRequestCodeComment(ctx, pr, comment, mentions)
} }
} }
// NotifyPullRequestChangeTargetBranch notifies when a pull request's target branch was changed // NotifyPullRequestChangeTargetBranch notifies when a pull request's target branch was changed
func NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { func NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullRequestChangeTargetBranch(doer, pr, oldBranch) notifier.NotifyPullRequestChangeTargetBranch(ctx, doer, pr, oldBranch)
} }
} }
// NotifyPullRequestPushCommits notifies when push commits to pull request's head branch // NotifyPullRequestPushCommits notifies when push commits to pull request's head branch
func NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { func NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullRequestPushCommits(doer, pr, comment) notifier.NotifyPullRequestPushCommits(ctx, doer, pr, comment)
} }
} }
// NotifyPullRevieweDismiss notifies when a review was dismissed by repo admin // NotifyPullReviewDismiss notifies when a review was dismissed by repo admin
func NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { func NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullRevieweDismiss(doer, review, comment) notifier.NotifyPullReviewDismiss(ctx, doer, review, comment)
} }
} }
// NotifyUpdateComment notifies update comment to notifiers // NotifyUpdateComment notifies update comment to notifiers
func NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { func NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyUpdateComment(doer, c, oldContent) notifier.NotifyUpdateComment(ctx, doer, c, oldContent)
} }
} }
// NotifyDeleteComment notifies delete comment to notifiers // NotifyDeleteComment notifies delete comment to notifiers
func NotifyDeleteComment(doer *user_model.User, c *issues_model.Comment) { func NotifyDeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyDeleteComment(doer, c) notifier.NotifyDeleteComment(ctx, doer, c)
} }
} }
// NotifyNewRelease notifies new release to notifiers // NotifyNewRelease notifies new release to notifiers
func NotifyNewRelease(rel *repo_model.Release) { func NotifyNewRelease(ctx context.Context, rel *repo_model.Release) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyNewRelease(rel) notifier.NotifyNewRelease(ctx, rel)
} }
} }
// NotifyUpdateRelease notifies update release to notifiers // NotifyUpdateRelease notifies update release to notifiers
func NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) { func NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyUpdateRelease(doer, rel) notifier.NotifyUpdateRelease(ctx, doer, rel)
} }
} }
// NotifyDeleteRelease notifies delete release to notifiers // NotifyDeleteRelease notifies delete release to notifiers
func NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) { func NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyDeleteRelease(doer, rel) notifier.NotifyDeleteRelease(ctx, doer, rel)
} }
} }
// NotifyIssueChangeMilestone notifies change milestone to notifiers // NotifyIssueChangeMilestone notifies change milestone to notifiers
func NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { func NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeMilestone(doer, issue, oldMilestoneID) notifier.NotifyIssueChangeMilestone(ctx, doer, issue, oldMilestoneID)
} }
} }
// NotifyIssueChangeContent notifies change content to notifiers // NotifyIssueChangeContent notifies change content to notifiers
func NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { func NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeContent(doer, issue, oldContent) notifier.NotifyIssueChangeContent(ctx, doer, issue, oldContent)
} }
} }
// NotifyIssueChangeAssignee notifies change content to notifiers // NotifyIssueChangeAssignee notifies change content to notifiers
func NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { func NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeAssignee(doer, issue, assignee, removed, comment) notifier.NotifyIssueChangeAssignee(ctx, doer, issue, assignee, removed, comment)
} }
} }
// NotifyPullReviewRequest notifies Request Review change // NotifyPullReviewRequest notifies Request Review change
func NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { func NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPullReviewRequest(doer, issue, reviewer, isRequest, comment) notifier.NotifyPullReviewRequest(ctx, doer, issue, reviewer, isRequest, comment)
} }
} }
// NotifyIssueClearLabels notifies clear labels to notifiers // NotifyIssueClearLabels notifies clear labels to notifiers
func NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) { func NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueClearLabels(doer, issue) notifier.NotifyIssueClearLabels(ctx, doer, issue)
} }
} }
// NotifyIssueChangeTitle notifies change title to notifiers // NotifyIssueChangeTitle notifies change title to notifiers
func NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeTitle(doer, issue, oldTitle) notifier.NotifyIssueChangeTitle(ctx, doer, issue, oldTitle)
} }
} }
// NotifyIssueChangeRef notifies change reference to notifiers // NotifyIssueChangeRef notifies change reference to notifiers
func NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldRef string) { func NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldRef string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeRef(doer, issue, oldRef) notifier.NotifyIssueChangeRef(ctx, doer, issue, oldRef)
} }
} }
// NotifyIssueChangeLabels notifies change labels to notifiers // NotifyIssueChangeLabels notifies change labels to notifiers
func NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, func NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue,
addedLabels, removedLabels []*issues_model.Label, addedLabels, removedLabels []*issues_model.Label,
) { ) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyIssueChangeLabels(doer, issue, addedLabels, removedLabels) notifier.NotifyIssueChangeLabels(ctx, doer, issue, addedLabels, removedLabels)
} }
} }
// NotifyCreateRepository notifies create repository to notifiers // NotifyCreateRepository notifies create repository to notifiers
func NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyCreateRepository(doer, u, repo) notifier.NotifyCreateRepository(ctx, doer, u, repo)
} }
} }
// NotifyMigrateRepository notifies create repository to notifiers // NotifyMigrateRepository notifies create repository to notifiers
func NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyMigrateRepository(doer, u, repo) notifier.NotifyMigrateRepository(ctx, doer, u, repo)
} }
} }
// NotifyTransferRepository notifies create repository to notifiers // NotifyTransferRepository notifies create repository to notifiers
func NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, newOwnerName string) { func NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, newOwnerName string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyTransferRepository(doer, repo, newOwnerName) notifier.NotifyTransferRepository(ctx, doer, repo, newOwnerName)
} }
} }
// NotifyDeleteRepository notifies delete repository to notifiers // NotifyDeleteRepository notifies delete repository to notifiers
func NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { func NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyDeleteRepository(doer, repo) notifier.NotifyDeleteRepository(ctx, doer, repo)
} }
} }
// NotifyForkRepository notifies fork repository to notifiers // NotifyForkRepository notifies fork repository to notifiers
func NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { func NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyForkRepository(doer, oldRepo, repo) notifier.NotifyForkRepository(ctx, doer, oldRepo, repo)
} }
} }
// NotifyRenameRepository notifies repository renamed // NotifyRenameRepository notifies repository renamed
func NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldName string) { func NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldName string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyRenameRepository(doer, repo, oldName) notifier.NotifyRenameRepository(ctx, doer, repo, oldName)
} }
} }
// NotifyPushCommits notifies commits pushed to notifiers // NotifyPushCommits notifies commits pushed to notifiers
func NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPushCommits(pusher, repo, opts, commits) notifier.NotifyPushCommits(ctx, pusher, repo, opts, commits)
} }
} }
// NotifyCreateRef notifies branch or tag creation to notifiers // NotifyCreateRef notifies branch or tag creation to notifiers
func NotifyCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyCreateRef(pusher, repo, refType, refFullName, refID) notifier.NotifyCreateRef(ctx, pusher, repo, refType, refFullName, refID)
} }
} }
// NotifyDeleteRef notifies branch or tag deletion to notifiers // NotifyDeleteRef notifies branch or tag deletion to notifiers
func NotifyDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func NotifyDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyDeleteRef(pusher, repo, refType, refFullName) notifier.NotifyDeleteRef(ctx, pusher, repo, refType, refFullName)
} }
} }
// NotifySyncPushCommits notifies commits pushed to notifiers // NotifySyncPushCommits notifies commits pushed to notifiers
func NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifySyncPushCommits(pusher, repo, opts, commits) notifier.NotifySyncPushCommits(ctx, pusher, repo, opts, commits)
} }
} }
// NotifySyncCreateRef notifies branch or tag creation to notifiers // NotifySyncCreateRef notifies branch or tag creation to notifiers
func NotifySyncCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func NotifySyncCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifySyncCreateRef(pusher, repo, refType, refFullName, refID) notifier.NotifySyncCreateRef(ctx, pusher, repo, refType, refFullName, refID)
} }
} }
// NotifySyncDeleteRef notifies branch or tag deletion to notifiers // NotifySyncDeleteRef notifies branch or tag deletion to notifiers
func NotifySyncDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func NotifySyncDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifySyncDeleteRef(pusher, repo, refType, refFullName) notifier.NotifySyncDeleteRef(ctx, pusher, repo, refType, refFullName)
} }
} }
// NotifyRepoPendingTransfer notifies creation of pending transfer to notifiers // NotifyRepoPendingTransfer notifies creation of pending transfer to notifiers
func NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { func NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyRepoPendingTransfer(doer, newOwner, repo) notifier.NotifyRepoPendingTransfer(ctx, doer, newOwner, repo)
} }
} }
// NotifyPackageCreate notifies creation of a package to notifiers // NotifyPackageCreate notifies creation of a package to notifiers
func NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) { func NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPackageCreate(doer, pd) notifier.NotifyPackageCreate(ctx, doer, pd)
} }
} }
// NotifyPackageDelete notifies deletion of a package to notifiers // NotifyPackageDelete notifies deletion of a package to notifiers
func NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) { func NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyPackageDelete(doer, pd) notifier.NotifyPackageDelete(ctx, doer, pd)
} }
} }

View file

@ -5,6 +5,8 @@
package ui package ui
import ( import (
"context"
activities_model "code.gitea.io/gitea/models/activities" activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
@ -54,7 +56,7 @@ func (ns *notificationService) Run() {
graceful.GetManager().RunWithShutdownFns(ns.issueQueue.Run) graceful.GetManager().RunWithShutdownFns(ns.issueQueue.Run)
} }
func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func (ns *notificationService) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
opts := issueNotificationOpts{ opts := issueNotificationOpts{
@ -78,7 +80,7 @@ func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, r
} }
} }
func (ns *notificationService) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func (ns *notificationService) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
_ = ns.issueQueue.Push(issueNotificationOpts{ _ = ns.issueQueue.Push(issueNotificationOpts{
IssueID: issue.ID, IssueID: issue.ID,
NotificationAuthorID: issue.Poster.ID, NotificationAuthorID: issue.Poster.ID,
@ -92,15 +94,15 @@ func (ns *notificationService) NotifyNewIssue(issue *issues_model.Issue, mention
} }
} }
func (ns *notificationService) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { func (ns *notificationService) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) {
_ = ns.issueQueue.Push(issueNotificationOpts{ _ = ns.issueQueue.Push(issueNotificationOpts{
IssueID: issue.ID, IssueID: issue.ID,
NotificationAuthorID: doer.ID, NotificationAuthorID: doer.ID,
}) })
} }
func (ns *notificationService) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func (ns *notificationService) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
if err := issue.LoadPullRequest(); err != nil { if err := issue.LoadPullRequest(ctx); err != nil {
log.Error("issue.LoadPullRequest: %v", err) log.Error("issue.LoadPullRequest: %v", err)
return return
} }
@ -112,24 +114,24 @@ func (ns *notificationService) NotifyIssueChangeTitle(doer *user_model.User, iss
} }
} }
func (ns *notificationService) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (ns *notificationService) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
_ = ns.issueQueue.Push(issueNotificationOpts{ _ = ns.issueQueue.Push(issueNotificationOpts{
IssueID: pr.Issue.ID, IssueID: pr.Issue.ID,
NotificationAuthorID: doer.ID, NotificationAuthorID: doer.ID,
}) })
} }
func (ns *notificationService) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (ns *notificationService) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
ns.NotifyMergePullRequest(pr, doer) ns.NotifyMergePullRequest(ctx, doer, pr)
} }
func (ns *notificationService) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { func (ns *notificationService) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) {
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
log.Error("Unable to load issue: %d for pr: %d: Error: %v", pr.IssueID, pr.ID, err) log.Error("Unable to load issue: %d for pr: %d: Error: %v", pr.IssueID, pr.ID, err)
return return
} }
toNotify := make(container.Set[int64], 32) toNotify := make(container.Set[int64], 32)
repoWatchers, err := repo_model.GetRepoWatchersIDs(db.DefaultContext, pr.Issue.RepoID) repoWatchers, err := repo_model.GetRepoWatchersIDs(ctx, pr.Issue.RepoID)
if err != nil { if err != nil {
log.Error("GetRepoWatchersIDs: %v", err) log.Error("GetRepoWatchersIDs: %v", err)
return return
@ -137,7 +139,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *issues_model.PullRequest
for _, id := range repoWatchers { for _, id := range repoWatchers {
toNotify.Add(id) toNotify.Add(id)
} }
issueParticipants, err := issues_model.GetParticipantsIDsByIssueID(pr.IssueID) issueParticipants, err := issues_model.GetParticipantsIDsByIssueID(ctx, pr.IssueID)
if err != nil { if err != nil {
log.Error("GetParticipantsIDsByIssueID: %v", err) log.Error("GetParticipantsIDsByIssueID: %v", err)
return return
@ -158,7 +160,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *issues_model.PullRequest
} }
} }
func (ns *notificationService) NotifyPullRequestReview(pr *issues_model.PullRequest, r *issues_model.Review, c *issues_model.Comment, mentions []*user_model.User) { func (ns *notificationService) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, c *issues_model.Comment, mentions []*user_model.User) {
opts := issueNotificationOpts{ opts := issueNotificationOpts{
IssueID: pr.Issue.ID, IssueID: pr.Issue.ID,
NotificationAuthorID: r.Reviewer.ID, NotificationAuthorID: r.Reviewer.ID,
@ -180,7 +182,7 @@ func (ns *notificationService) NotifyPullRequestReview(pr *issues_model.PullRequ
} }
} }
func (ns *notificationService) NotifyPullRequestCodeComment(pr *issues_model.PullRequest, c *issues_model.Comment, mentions []*user_model.User) { func (ns *notificationService) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, c *issues_model.Comment, mentions []*user_model.User) {
for _, mention := range mentions { for _, mention := range mentions {
_ = ns.issueQueue.Push(issueNotificationOpts{ _ = ns.issueQueue.Push(issueNotificationOpts{
IssueID: pr.Issue.ID, IssueID: pr.Issue.ID,
@ -191,7 +193,7 @@ func (ns *notificationService) NotifyPullRequestCodeComment(pr *issues_model.Pul
} }
} }
func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { func (ns *notificationService) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) {
opts := issueNotificationOpts{ opts := issueNotificationOpts{
IssueID: pr.IssueID, IssueID: pr.IssueID,
NotificationAuthorID: doer.ID, NotificationAuthorID: doer.ID,
@ -200,7 +202,7 @@ func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.Use
_ = ns.issueQueue.Push(opts) _ = ns.issueQueue.Push(opts)
} }
func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { func (ns *notificationService) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) {
opts := issueNotificationOpts{ opts := issueNotificationOpts{
IssueID: review.IssueID, IssueID: review.IssueID,
NotificationAuthorID: doer.ID, NotificationAuthorID: doer.ID,
@ -209,7 +211,7 @@ func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, r
_ = ns.issueQueue.Push(opts) _ = ns.issueQueue.Push(opts)
} }
func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { func (ns *notificationService) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) {
if !removed && doer.ID != assignee.ID { if !removed && doer.ID != assignee.ID {
opts := issueNotificationOpts{ opts := issueNotificationOpts{
IssueID: issue.ID, IssueID: issue.ID,
@ -225,7 +227,7 @@ func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User,
} }
} }
func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { func (ns *notificationService) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) {
if isRequest { if isRequest {
opts := issueNotificationOpts{ opts := issueNotificationOpts{
IssueID: issue.ID, IssueID: issue.ID,
@ -241,8 +243,11 @@ func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, is
} }
} }
func (ns *notificationService) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { func (ns *notificationService) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) {
if err := activities_model.CreateRepoTransferNotification(doer, newOwner, repo); err != nil { err := db.AutoTx(ctx, func(ctx context.Context) error {
log.Error("NotifyRepoPendingTransfer: %v", err) return activities_model.CreateRepoTransferNotification(ctx, doer, newOwner, repo)
})
if err != nil {
log.Error("CreateRepoTransferNotification: %v", err)
} }
} }

View file

@ -5,9 +5,8 @@
package webhook package webhook
import ( import (
"fmt" "context"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
packages_model "code.gitea.io/gitea/models/packages" packages_model "code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
@ -18,10 +17,8 @@ import (
"code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/convert"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/notification/base" "code.gitea.io/gitea/modules/notification/base"
"code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
@ -39,12 +36,9 @@ func NewNotifier() base.Notifier {
return &webhookNotifier{} return &webhookNotifier{}
} }
func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) { func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueClearLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) if err := issue.LoadPoster(ctx); err != nil {
defer finished() log.Error("LoadPoster: %v", err)
if err := issue.LoadPoster(); err != nil {
log.Error("loadPoster: %v", err)
return return
} }
@ -53,10 +47,10 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *i
return return
} }
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
var err error var err error
if issue.IsPull { if issue.IsPull {
if err = issue.LoadPullRequest(); err != nil { if err = issue.LoadPullRequest(ctx); err != nil {
log.Error("LoadPullRequest: %v", err) log.Error("LoadPullRequest: %v", err)
return return
} }
@ -72,7 +66,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *i
err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{
Action: api.HookIssueLabelCleared, Action: api.HookIssueLabelCleared,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
@ -82,12 +76,12 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *i
} }
} }
func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) {
oldMode, _ := access_model.AccessLevel(doer, oldRepo) oldMode, _ := access_model.AccessLevel(ctx, doer, oldRepo)
mode, _ := access_model.AccessLevel(doer, repo) mode, _ := access_model.AccessLevel(ctx, doer, repo)
// forked webhook // forked webhook
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{
Forkee: convert.ToRepo(oldRepo, oldMode), Forkee: convert.ToRepo(oldRepo, oldMode),
Repo: convert.ToRepo(repo, mode), Repo: convert.ToRepo(repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
@ -95,11 +89,11 @@ func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, r
log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err) log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err)
} }
u := repo.MustOwner() u := repo.MustOwner(ctx)
// Add to hook queue for created repo after session commit. // Add to hook queue for created repo after session commit.
if u.IsOrganization() { if u.IsOrganization() {
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{
Action: api.HookRepoCreated, Action: api.HookRepoCreated,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(u, nil),
@ -110,9 +104,9 @@ func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, r
} }
} }
func (m *webhookNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
// Add to hook queue for created repo after session commit. // Add to hook queue for created repo after session commit.
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{
Action: api.HookRepoCreated, Action: api.HookRepoCreated,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(u, nil),
@ -122,22 +116,20 @@ func (m *webhookNotifier) NotifyCreateRepository(doer, u *user_model.User, repo
} }
} }
func (m *webhookNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) {
u := repo.MustOwner() if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{
Action: api.HookRepoDeleted, Action: api.HookRepoDeleted,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(repo.MustOwner(ctx), nil),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err)
} }
} }
func (m *webhookNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) {
// Add to hook queue for created repo after session commit. // Add to hook queue for created repo after session commit.
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{
Action: api.HookRepoCreated, Action: api.HookRepoCreated,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(u, nil),
@ -147,14 +139,11 @@ func (m *webhookNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo
} }
} }
func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeAssignee User: %s[%d] Issue[%d] #%d in [%d] Assignee %s[%d] removed: %t", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID, assignee.Name, assignee.ID, removed))
defer finished()
if issue.IsPull { if issue.IsPull {
mode, _ := access_model.AccessLevelUnit(doer, issue.Repo, unit.TypePullRequests) mode, _ := access_model.AccessLevelUnit(ctx, doer, issue.Repo, unit.TypePullRequests)
if err := issue.LoadPullRequest(); err != nil { if err := issue.LoadPullRequest(ctx); err != nil {
log.Error("LoadPullRequest failed: %v", err) log.Error("LoadPullRequest failed: %v", err)
return return
} }
@ -176,10 +165,10 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue
return return
} }
} else { } else {
mode, _ := access_model.AccessLevelUnit(doer, issue.Repo, unit.TypeIssues) mode, _ := access_model.AccessLevelUnit(ctx, doer, issue.Repo, unit.TypeIssues)
apiIssue := &api.IssuePayload{ apiIssue := &api.IssuePayload{
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
} }
@ -196,14 +185,11 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue
} }
} }
func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeTitle User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
defer finished()
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo)
var err error var err error
if issue.IsPull { if issue.IsPull {
if err = issue.LoadPullRequest(); err != nil { if err = issue.LoadPullRequest(ctx); err != nil {
log.Error("LoadPullRequest failed: %v", err) log.Error("LoadPullRequest failed: %v", err)
return return
} }
@ -229,7 +215,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *i
From: oldTitle, From: oldTitle,
}, },
}, },
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
@ -240,14 +226,11 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *i
} }
} }
func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeStatus User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
defer finished()
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo)
var err error var err error
if issue.IsPull { if issue.IsPull {
if err = issue.LoadPullRequest(); err != nil { if err = issue.LoadPullRequest(ctx); err != nil {
log.Error("LoadPullRequest: %v", err) log.Error("LoadPullRequest: %v", err)
return return
} }
@ -267,7 +250,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *
} else { } else {
apiIssue := &api.IssuePayload{ apiIssue := &api.IssuePayload{
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
} }
@ -283,21 +266,21 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *
} }
} }
func (m *webhookNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { func (m *webhookNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) {
if err := issue.LoadRepo(db.DefaultContext); err != nil { if err := issue.LoadRepo(ctx); err != nil {
log.Error("issue.LoadRepo: %v", err) log.Error("issue.LoadRepo: %v", err)
return return
} }
if err := issue.LoadPoster(); err != nil { if err := issue.LoadPoster(ctx); err != nil {
log.Error("issue.LoadPoster: %v", err) log.Error("issue.LoadPoster: %v", err)
return return
} }
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{
Action: api.HookIssueOpened, Action: api.HookIssueOpened,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(issue.Poster, nil), Sender: convert.ToUser(issue.Poster, nil),
}); err != nil { }); err != nil {
@ -305,11 +288,8 @@ func (m *webhookNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*
} }
} }
func (m *webhookNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, mentions []*user_model.User) { func (m *webhookNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues_model.PullRequest, mentions []*user_model.User) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyNewPullRequest Pull[%d] #%d in [%d]", pull.ID, pull.Index, pull.BaseRepoID)) if err := pull.LoadIssue(ctx); err != nil {
defer finished()
if err := pull.LoadIssue(); err != nil {
log.Error("pull.LoadIssue: %v", err) log.Error("pull.LoadIssue: %v", err)
return return
} }
@ -317,12 +297,12 @@ func (m *webhookNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, m
log.Error("pull.Issue.LoadRepo: %v", err) log.Error("pull.Issue.LoadRepo: %v", err)
return return
} }
if err := pull.Issue.LoadPoster(); err != nil { if err := pull.Issue.LoadPoster(ctx); err != nil {
log.Error("pull.Issue.LoadPoster: %v", err) log.Error("pull.Issue.LoadPoster: %v", err)
return return
} }
mode, _ := access_model.AccessLevel(pull.Issue.Poster, pull.Issue.Repo) mode, _ := access_model.AccessLevel(ctx, pull.Issue.Poster, pull.Issue.Repo)
if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pull.Issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pull.Issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{
Action: api.HookIssueOpened, Action: api.HookIssueOpened,
Index: pull.Issue.Index, Index: pull.Issue.Index,
@ -334,11 +314,8 @@ func (m *webhookNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, m
} }
} }
func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeContent User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
defer finished()
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo)
var err error var err error
if issue.IsPull { if issue.IsPull {
issue.PullRequest.Issue = issue issue.PullRequest.Issue = issue
@ -363,7 +340,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue
From: oldContent, From: oldContent,
}, },
}, },
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
@ -373,17 +350,17 @@ func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue
} }
} }
func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) {
if err := c.LoadPoster(); err != nil { if err := c.LoadPoster(ctx); err != nil {
log.Error("LoadPoster: %v", err) log.Error("LoadPoster: %v", err)
return return
} }
if err := c.LoadIssue(); err != nil { if err := c.LoadIssue(ctx); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
if err := c.Issue.LoadAttributes(db.DefaultContext); err != nil { if err := c.Issue.LoadAttributes(ctx); err != nil {
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
return return
} }
@ -395,10 +372,10 @@ func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m
eventType = webhook.HookEventIssueComment eventType = webhook.HookEventIssueComment
} }
mode, _ := access_model.AccessLevel(doer, c.Issue.Repo) mode, _ := access_model.AccessLevel(ctx, doer, c.Issue.Repo)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{
Action: api.HookIssueCommentEdited, Action: api.HookIssueCommentEdited,
Issue: convert.ToAPIIssue(c.Issue), Issue: convert.ToAPIIssue(ctx, c.Issue),
Comment: convert.ToComment(c), Comment: convert.ToComment(c),
Changes: &api.ChangesPayload{ Changes: &api.ChangesPayload{
Body: &api.ChangesFromPayload{ Body: &api.ChangesFromPayload{
@ -413,7 +390,7 @@ func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m
} }
} }
func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, func (m *webhookNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
var eventType webhook.HookEventType var eventType webhook.HookEventType
@ -423,10 +400,10 @@ func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *
eventType = webhook.HookEventIssueComment eventType = webhook.HookEventIssueComment
} }
mode, _ := access_model.AccessLevel(doer, repo) mode, _ := access_model.AccessLevel(ctx, doer, repo)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{
Action: api.HookIssueCommentCreated, Action: api.HookIssueCommentCreated,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Comment: convert.ToComment(comment), Comment: convert.ToComment(comment),
Repository: convert.ToRepo(repo, mode), Repository: convert.ToRepo(repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
@ -436,19 +413,19 @@ func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *
} }
} }
func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *issues_model.Comment) { func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_model.User, comment *issues_model.Comment) {
var err error var err error
if err = comment.LoadPoster(); err != nil { if err = comment.LoadPoster(ctx); err != nil {
log.Error("LoadPoster: %v", err) log.Error("LoadPoster: %v", err)
return return
} }
if err = comment.LoadIssue(); err != nil { if err = comment.LoadIssue(ctx); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
if err = comment.Issue.LoadAttributes(db.DefaultContext); err != nil { if err = comment.Issue.LoadAttributes(ctx); err != nil {
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
return return
} }
@ -460,10 +437,10 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *is
eventType = webhook.HookEventIssueComment eventType = webhook.HookEventIssueComment
} }
mode, _ := access_model.AccessLevel(doer, comment.Issue.Repo) mode, _ := access_model.AccessLevel(ctx, doer, comment.Issue.Repo)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{
Action: api.HookIssueCommentDeleted, Action: api.HookIssueCommentDeleted,
Issue: convert.ToAPIIssue(comment.Issue), Issue: convert.ToAPIIssue(ctx, comment.Issue),
Comment: convert.ToComment(comment), Comment: convert.ToComment(comment),
Repository: convert.ToRepo(comment.Issue.Repo, mode), Repository: convert.ToRepo(comment.Issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
@ -473,9 +450,9 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *is
} }
} }
func (m *webhookNotifier) NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) {
// Add to hook queue for created wiki page. // Add to hook queue for created wiki page.
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{
Action: api.HookWikiCreated, Action: api.HookWikiCreated,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
@ -486,9 +463,9 @@ func (m *webhookNotifier) NotifyNewWikiPage(doer *user_model.User, repo *repo_mo
} }
} }
func (m *webhookNotifier) NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) {
// Add to hook queue for edit wiki page. // Add to hook queue for edit wiki page.
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{
Action: api.HookWikiEdited, Action: api.HookWikiEdited,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
@ -499,9 +476,9 @@ func (m *webhookNotifier) NotifyEditWikiPage(doer *user_model.User, repo *repo_m
} }
} }
func (m *webhookNotifier) NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) { func (m *webhookNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) {
// Add to hook queue for edit wiki page. // Add to hook queue for edit wiki page.
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{
Action: api.HookWikiDeleted, Action: api.HookWikiDeleted,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(repo, perm.AccessModeOwner),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
@ -511,12 +488,9 @@ func (m *webhookNotifier) NotifyDeleteWikiPage(doer *user_model.User, repo *repo
} }
} }
func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue,
addedLabels, removedLabels []*issues_model.Label, addedLabels, removedLabels []*issues_model.Label,
) { ) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID))
defer finished()
var err error var err error
if err = issue.LoadRepo(ctx); err != nil { if err = issue.LoadRepo(ctx); err != nil {
@ -524,18 +498,18 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *
return return
} }
if err = issue.LoadPoster(); err != nil { if err = issue.LoadPoster(ctx); err != nil {
log.Error("LoadPoster: %v", err) log.Error("LoadPoster: %v", err)
return return
} }
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
if issue.IsPull { if issue.IsPull {
if err = issue.LoadPullRequest(); err != nil { if err = issue.LoadPullRequest(ctx); err != nil {
log.Error("loadPullRequest: %v", err) log.Error("loadPullRequest: %v", err)
return return
} }
if err = issue.PullRequest.LoadIssue(); err != nil { if err = issue.PullRequest.LoadIssue(ctx); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
@ -550,7 +524,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *
err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{
Action: api.HookIssueLabelUpdated, Action: api.HookIssueLabelUpdated,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
@ -560,10 +534,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *
} }
} }
func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeMilestone User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID))
defer finished()
var hookAction api.HookIssueAction var hookAction api.HookIssueAction
var err error var err error
if issue.MilestoneID > 0 { if issue.MilestoneID > 0 {
@ -572,14 +543,14 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu
hookAction = api.HookIssueDemilestoned hookAction = api.HookIssueDemilestoned
} }
if err = issue.LoadAttributes(db.DefaultContext); err != nil { if err = issue.LoadAttributes(ctx); err != nil {
log.Error("issue.LoadAttributes failed: %v", err) log.Error("issue.LoadAttributes failed: %v", err)
return return
} }
mode, _ := access_model.AccessLevel(doer, issue.Repo) mode, _ := access_model.AccessLevel(ctx, doer, issue.Repo)
if issue.IsPull { if issue.IsPull {
err = issue.PullRequest.LoadIssue() err = issue.PullRequest.LoadIssue(ctx)
if err != nil { if err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
@ -595,7 +566,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu
err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueMilestone, &api.IssuePayload{ err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueMilestone, &api.IssuePayload{
Action: hookAction, Action: hookAction,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
@ -605,10 +576,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu
} }
} }
func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (m *webhookNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPushCommits User: %s[%d] in %s[%d]", pusher.Name, pusher.ID, repo.FullName(), repo.ID))
defer finished()
apiPusher := convert.ToUser(pusher, nil) apiPusher := convert.ToUser(pusher, nil)
apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL())
if err != nil { if err != nil {
@ -632,23 +600,20 @@ func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_
} }
} }
func (m *webhookNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (m *webhookNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
// just redirect to the NotifyMergePullRequest // just redirect to the NotifyMergePullRequest
m.NotifyMergePullRequest(pr, doer) m.NotifyMergePullRequest(ctx, doer, pr)
} }
func (*webhookNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { func (*webhookNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyMergePullRequest Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID))
defer finished()
// Reload pull request information. // Reload pull request information.
if err := pr.LoadAttributes(); err != nil { if err := pr.LoadAttributes(ctx); err != nil {
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
return return
} }
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
log.Error("LoadAttributes: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
@ -657,7 +622,7 @@ func (*webhookNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doe
return return
} }
mode, err := access_model.AccessLevel(doer, pr.Issue.Repo) mode, err := access_model.AccessLevel(ctx, doer, pr.Issue.Repo)
if err != nil { if err != nil {
log.Error("models.AccessLevel: %v", err) log.Error("models.AccessLevel: %v", err)
return return
@ -672,29 +637,21 @@ func (*webhookNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doe
Action: api.HookIssueClosed, Action: api.HookIssueClosed,
} }
err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pr.Issue.Repo}, webhook.HookEventPullRequest, apiPullRequest) if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pr.Issue.Repo}, webhook.HookEventPullRequest, apiPullRequest); err != nil {
if err != nil {
log.Error("PrepareWebhooks: %v", err) log.Error("PrepareWebhooks: %v", err)
} }
} }
func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPullRequestChangeTargetBranch Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) if err := pr.LoadIssue(ctx); err != nil {
defer finished() log.Error("LoadIssue: %v", err)
return
}
issue := pr.Issue issue := pr.Issue
if !issue.IsPull {
return
}
var err error
if err = issue.LoadPullRequest(); err != nil { mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo)
log.Error("LoadPullRequest failed: %v", err) if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{
return
}
issue.PullRequest.Issue = issue
mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo)
err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{
Action: api.HookIssueEdited, Action: api.HookIssueEdited,
Index: issue.Index, Index: issue.Index,
Changes: &api.ChangesPayload{ Changes: &api.ChangesPayload{
@ -702,20 +659,15 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(doer *user_model.U
From: oldBranch, From: oldBranch,
}, },
}, },
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) }); err != nil {
log.Error("PrepareWebhooks [pr: %d]: %v", pr.ID, err)
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
} }
} }
func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPullRequestReview Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID))
defer finished()
var reviewHookType webhook.HookEventType var reviewHookType webhook.HookEventType
switch review.Type { switch review.Type {
@ -731,12 +683,12 @@ func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest,
return return
} }
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
log.Error("pr.LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
mode, err := access_model.AccessLevel(review.Issue.Poster, review.Issue.Repo) mode, err := access_model.AccessLevel(ctx, review.Issue.Poster, review.Issue.Repo)
if err != nil { if err != nil {
log.Error("models.AccessLevel: %v", err) log.Error("models.AccessLevel: %v", err)
return return
@ -756,12 +708,12 @@ func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest,
} }
} }
func (m *webhookNotifier) NotifyCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { 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(pusher, nil)
apiRepo := convert.ToRepo(repo, perm.AccessModeNone) apiRepo := convert.ToRepo(repo, perm.AccessModeNone)
refName := git.RefEndName(refFullName) refName := git.RefEndName(refFullName)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{
Ref: refName, Ref: refName,
Sha: refID, Sha: refID,
RefType: refType, RefType: refType,
@ -772,15 +724,12 @@ func (m *webhookNotifier) NotifyCreateRef(pusher *user_model.User, repo *repo_mo
} }
} }
func (m *webhookNotifier) NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) { func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPullRequestSynchronized Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) if err := pr.LoadIssue(ctx); err != nil {
defer finished() log.Error("LoadIssue: %v", err)
if err := pr.LoadIssue(); err != nil {
log.Error("pr.LoadIssue: %v", err)
return return
} }
if err := pr.Issue.LoadAttributes(db.DefaultContext); err != nil { if err := pr.Issue.LoadAttributes(ctx); err != nil {
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
return return
} }
@ -796,12 +745,12 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(doer *user_model.User, p
} }
} }
func (m *webhookNotifier) NotifyDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { 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(pusher, nil)
apiRepo := convert.ToRepo(repo, perm.AccessModeNone) apiRepo := convert.ToRepo(repo, perm.AccessModeNone)
refName := git.RefEndName(refFullName) refName := git.RefEndName(refFullName)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{
Ref: refName, Ref: refName,
RefType: refType, RefType: refType,
PusherType: api.PusherTypeUser, PusherType: api.PusherTypeUser,
@ -812,14 +761,14 @@ func (m *webhookNotifier) NotifyDeleteRef(pusher *user_model.User, repo *repo_mo
} }
} }
func sendReleaseHook(doer *user_model.User, rel *repo_model.Release, action api.HookReleaseAction) { func sendReleaseHook(ctx context.Context, doer *user_model.User, rel *repo_model.Release, action api.HookReleaseAction) {
if err := rel.LoadAttributes(); err != nil { if err := rel.LoadAttributes(ctx); err != nil {
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
return return
} }
mode, _ := access_model.AccessLevel(doer, rel.Repo) mode, _ := access_model.AccessLevel(ctx, doer, rel.Repo)
if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{
Action: action, Action: action,
Release: convert.ToRelease(rel), Release: convert.ToRelease(rel),
Repository: convert.ToRepo(rel.Repo, mode), Repository: convert.ToRepo(rel.Repo, mode),
@ -829,22 +778,19 @@ func sendReleaseHook(doer *user_model.User, rel *repo_model.Release, action api.
} }
} }
func (m *webhookNotifier) NotifyNewRelease(rel *repo_model.Release) { func (m *webhookNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) {
sendReleaseHook(rel.Publisher, rel, api.HookReleasePublished) sendReleaseHook(ctx, rel.Publisher, rel, api.HookReleasePublished)
} }
func (m *webhookNotifier) NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) { func (m *webhookNotifier) NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) {
sendReleaseHook(doer, rel, api.HookReleaseUpdated) sendReleaseHook(ctx, doer, rel, api.HookReleaseUpdated)
} }
func (m *webhookNotifier) NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) { func (m *webhookNotifier) NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) {
sendReleaseHook(doer, rel, api.HookReleaseDeleted) sendReleaseHook(ctx, doer, rel, api.HookReleaseDeleted)
} }
func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { func (m *webhookNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifySyncPushCommits User: %s[%d] in %s[%d]", pusher.Name, pusher.ID, repo.FullName(), repo.ID))
defer finished()
apiPusher := convert.ToUser(pusher, nil) apiPusher := convert.ToUser(pusher, nil)
apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL())
if err != nil { if err != nil {
@ -868,31 +814,28 @@ func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *r
} }
} }
func (m *webhookNotifier) NotifySyncCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { func (m *webhookNotifier) NotifySyncCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) {
m.NotifyCreateRef(pusher, repo, refType, refFullName, refID) m.NotifyCreateRef(ctx, pusher, repo, refType, refFullName, refID)
} }
func (m *webhookNotifier) NotifySyncDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { func (m *webhookNotifier) NotifySyncDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) {
m.NotifyDeleteRef(pusher, repo, refType, refFullName) m.NotifyDeleteRef(ctx, pusher, repo, refType, refFullName)
} }
func (m *webhookNotifier) NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) { func (m *webhookNotifier) NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
notifyPackage(doer, pd, api.HookPackageCreated) notifyPackage(ctx, doer, pd, api.HookPackageCreated)
} }
func (m *webhookNotifier) NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) { func (m *webhookNotifier) NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
notifyPackage(doer, pd, api.HookPackageDeleted) notifyPackage(ctx, doer, pd, api.HookPackageDeleted)
} }
func notifyPackage(sender *user_model.User, pd *packages_model.PackageDescriptor, action api.HookPackageAction) { func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_model.PackageDescriptor, action api.HookPackageAction) {
source := webhook_services.EventSource{ source := webhook_services.EventSource{
Repository: pd.Repository, Repository: pd.Repository,
Owner: pd.Owner, Owner: pd.Owner,
} }
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.notifyPackage Package: %s[%d]", pd.Package.Name, pd.Package.ID))
defer finished()
apiPackage, err := convert.ToPackage(ctx, pd, sender) apiPackage, err := convert.ToPackage(ctx, pd, sender)
if err != nil { if err != nil {
log.Error("Error converting package: %v", err) log.Error("Error converting package: %v", err)

View file

@ -288,7 +288,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository)
} }
for page := 1; ; page++ { for page := 1; ; page++ {
opts.Page = page opts.Page = page
rels, err := repo_model.GetReleasesByRepoID(repo.ID, opts) rels, err := repo_model.GetReleasesByRepoID(gitRepo.Ctx, repo.ID, opts)
if err != nil { if err != nil {
return fmt.Errorf("unable to GetReleasesByRepoID in Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err) return fmt.Errorf("unable to GetReleasesByRepoID in Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err)
} }

View file

@ -676,7 +676,7 @@ func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeRef
} }
if versionDeleted { if versionDeleted {
notification.NotifyPackageDelete(apictx.Doer, pd) notification.NotifyPackageDelete(apictx, apictx.Doer, pd)
} }
return nil return nil

View file

@ -42,7 +42,7 @@ func NodeInfo(ctx *context.APIContext) {
usersActiveMonth := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeOneMonthAgo})) usersActiveMonth := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeOneMonthAgo}))
usersActiveHalfyear := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeHaveYearAgo})) usersActiveHalfyear := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeHaveYearAgo}))
allIssues, _ := issues_model.CountIssues(&issues_model.IssuesOptions{}) allIssues, _ := issues_model.CountIssues(ctx, &issues_model.IssuesOptions{})
allComments, _ := issues_model.CountComments(&issues_model.FindCommentsOptions{}) allComments, _ := issues_model.CountComments(&issues_model.FindCommentsOptions{})
nodeInfoUsage = structs.NodeInfoUsage{ nodeInfoUsage = structs.NodeInfoUsage{

View file

@ -109,7 +109,7 @@ func ListRepoNotifications(ctx *context.APIContext) {
} }
opts.RepoID = ctx.Repo.Repository.ID opts.RepoID = ctx.Repo.Repository.ID
totalCount, err := activities_model.CountNotifications(opts) totalCount, err := activities_model.CountNotifications(ctx, opts)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -120,7 +120,7 @@ func ListRepoNotifications(ctx *context.APIContext) {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
err = nl.LoadAttributes() err = nl.LoadAttributes(ctx)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -217,12 +217,12 @@ func ReadRepoNotifications(ctx *context.APIContext) {
changed := make([]*structs.NotificationThread, 0, len(nl)) changed := make([]*structs.NotificationThread, 0, len(nl))
for _, n := range nl { for _, n := range nl {
notif, err := activities_model.SetNotificationStatus(n.ID, ctx.Doer, targetStatus) notif, err := activities_model.SetNotificationStatus(ctx, n.ID, ctx.Doer, targetStatus)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
_ = notif.LoadAttributes() _ = notif.LoadAttributes(ctx)
changed = append(changed, convert.ToNotificationThread(notif)) changed = append(changed, convert.ToNotificationThread(notif))
} }
ctx.JSON(http.StatusResetContent, changed) ctx.JSON(http.StatusResetContent, changed)

View file

@ -42,7 +42,7 @@ func GetThread(ctx *context.APIContext) {
if n == nil { if n == nil {
return return
} }
if err := n.LoadAttributes(); err != nil && !issues_model.IsErrCommentNotExist(err) { if err := n.LoadAttributes(ctx); err != nil && !issues_model.IsErrCommentNotExist(err) {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
@ -89,12 +89,12 @@ func ReadThread(ctx *context.APIContext) {
targetStatus = activities_model.NotificationStatusRead targetStatus = activities_model.NotificationStatusRead
} }
notif, err := activities_model.SetNotificationStatus(n.ID, ctx.Doer, targetStatus) notif, err := activities_model.SetNotificationStatus(ctx, n.ID, ctx.Doer, targetStatus)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
if err = notif.LoadAttributes(); err != nil && !issues_model.IsErrCommentNotExist(err) { if err = notif.LoadAttributes(ctx); err != nil && !issues_model.IsErrCommentNotExist(err) {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
@ -102,7 +102,7 @@ func ReadThread(ctx *context.APIContext) {
} }
func getThread(ctx *context.APIContext) *activities_model.Notification { func getThread(ctx *context.APIContext) *activities_model.Notification {
n, err := activities_model.GetNotificationByID(ctx.ParamsInt64(":id")) n, err := activities_model.GetNotificationByID(ctx, ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if db.IsErrNotExist(err) { if db.IsErrNotExist(err) {
ctx.Error(http.StatusNotFound, "GetNotificationByID", err) ctx.Error(http.StatusNotFound, "GetNotificationByID", err)

View file

@ -69,7 +69,7 @@ func ListNotifications(ctx *context.APIContext) {
return return
} }
totalCount, err := activities_model.CountNotifications(opts) totalCount, err := activities_model.CountNotifications(ctx, opts)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -80,7 +80,7 @@ func ListNotifications(ctx *context.APIContext) {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
err = nl.LoadAttributes() err = nl.LoadAttributes(ctx)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -162,12 +162,12 @@ func ReadNotifications(ctx *context.APIContext) {
changed := make([]*structs.NotificationThread, 0, len(nl)) changed := make([]*structs.NotificationThread, 0, len(nl))
for _, n := range nl { for _, n := range nl {
notif, err := activities_model.SetNotificationStatus(n.ID, ctx.Doer, targetStatus) notif, err := activities_model.SetNotificationStatus(ctx, n.ID, ctx.Doer, targetStatus)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
_ = notif.LoadAttributes() _ = notif.LoadAttributes(ctx)
changed = append(changed, convert.ToNotificationThread(notif)) changed = append(changed, convert.ToNotificationThread(notif))
} }

View file

@ -542,7 +542,7 @@ func GetTeamRepos(ctx *context.APIContext) {
} }
repos := make([]*api.Repository, len(teamRepos)) repos := make([]*api.Repository, len(teamRepos))
for i, repo := range teamRepos { for i, repo := range teamRepos {
access, err := access_model.AccessLevel(ctx.Doer, repo) access, err := access_model.AccessLevel(ctx, ctx.Doer, repo)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
return return
@ -593,7 +593,7 @@ func GetTeamRepo(ctx *context.APIContext) {
return return
} }
access, err := access_model.AccessLevel(ctx.Doer, repo) access, err := access_model.AccessLevel(ctx, ctx.Doer, repo)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
return return
@ -650,7 +650,7 @@ func AddTeamRepository(ctx *context.APIContext) {
if ctx.Written() { if ctx.Written() {
return return
} }
if access, err := access_model.AccessLevel(ctx.Doer, repo); err != nil { if access, err := access_model.AccessLevel(ctx, ctx.Doer, repo); err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return return
} else if access < perm.AccessModeAdmin { } else if access < perm.AccessModeAdmin {
@ -700,7 +700,7 @@ func RemoveTeamRepository(ctx *context.APIContext) {
if ctx.Written() { if ctx.Written() {
return return
} }
if access, err := access_model.AccessLevel(ctx.Doer, repo); err != nil { if access, err := access_model.AccessLevel(ctx, ctx.Doer, repo); err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return return
} else if access < perm.AccessModeAdmin { } else if access < perm.AccessModeAdmin {

View file

@ -427,7 +427,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
requiredApprovals = form.RequiredApprovals requiredApprovals = form.RequiredApprovals
} }
whitelistUsers, err := user_model.GetUserIDsByNames(form.PushWhitelistUsernames, false) whitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err)
@ -436,7 +436,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetUserIDsByNames", err) ctx.Error(http.StatusInternalServerError, "GetUserIDsByNames", err)
return return
} }
mergeWhitelistUsers, err := user_model.GetUserIDsByNames(form.MergeWhitelistUsernames, false) mergeWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err)
@ -445,7 +445,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetUserIDsByNames", err) ctx.Error(http.StatusInternalServerError, "GetUserIDsByNames", err)
return return
} }
approvalsWhitelistUsers, err := user_model.GetUserIDsByNames(form.ApprovalsWhitelistUsernames, false) approvalsWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err)
@ -656,7 +656,7 @@ func EditBranchProtection(ctx *context.APIContext) {
var whitelistUsers []int64 var whitelistUsers []int64
if form.PushWhitelistUsernames != nil { if form.PushWhitelistUsernames != nil {
whitelistUsers, err = user_model.GetUserIDsByNames(form.PushWhitelistUsernames, false) whitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err)
@ -670,7 +670,7 @@ func EditBranchProtection(ctx *context.APIContext) {
} }
var mergeWhitelistUsers []int64 var mergeWhitelistUsers []int64
if form.MergeWhitelistUsernames != nil { if form.MergeWhitelistUsernames != nil {
mergeWhitelistUsers, err = user_model.GetUserIDsByNames(form.MergeWhitelistUsernames, false) mergeWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err)
@ -684,7 +684,7 @@ func EditBranchProtection(ctx *context.APIContext) {
} }
var approvalsWhitelistUsers []int64 var approvalsWhitelistUsers []int64
if form.ApprovalsWhitelistUsernames != nil { if form.ApprovalsWhitelistUsernames != nil {
approvalsWhitelistUsers, err = user_model.GetUserIDsByNames(form.ApprovalsWhitelistUsernames, false) approvalsWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err)

View file

@ -59,7 +59,7 @@ func ListForks(ctx *context.APIContext) {
} }
apiForks := make([]*api.Repository, len(forks)) apiForks := make([]*api.Repository, len(forks))
for i, fork := range forks { for i, fork := range forks {
access, err := access_model.AccessLevel(ctx.Doer, fork) access, err := access_model.AccessLevel(ctx, ctx.Doer, fork)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return return

View file

@ -179,7 +179,7 @@ func SearchIssues(ctx *context.APIContext) {
repoCond := repo_model.SearchRepositoryCondition(opts) repoCond := repo_model.SearchRepositoryCondition(opts)
repoIDs, _, err := repo_model.SearchRepositoryIDs(opts) repoIDs, _, err := repo_model.SearchRepositoryIDs(opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err) ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err)
return return
} }
@ -268,7 +268,7 @@ func SearchIssues(ctx *context.APIContext) {
issuesOpt.ReviewRequestedID = ctxUserID issuesOpt.ReviewRequestedID = ctxUserID
} }
if issues, err = issues_model.Issues(issuesOpt); err != nil { if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, "Issues", err) ctx.Error(http.StatusInternalServerError, "Issues", err)
return return
} }
@ -276,7 +276,7 @@ func SearchIssues(ctx *context.APIContext) {
issuesOpt.ListOptions = db.ListOptions{ issuesOpt.ListOptions = db.ListOptions{
Page: -1, Page: -1,
} }
if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, "CountIssues", err) ctx.Error(http.StatusInternalServerError, "CountIssues", err)
return return
} }
@ -284,7 +284,7 @@ func SearchIssues(ctx *context.APIContext) {
ctx.SetLinkHeader(int(filteredCount), limit) ctx.SetLinkHeader(int(filteredCount), limit)
ctx.SetTotalCountHeader(filteredCount) ctx.SetTotalCountHeader(filteredCount)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues))
} }
// ListIssues list the issues of a repository // ListIssues list the issues of a repository
@ -477,7 +477,7 @@ func ListIssues(ctx *context.APIContext) {
MentionedID: mentionedByID, MentionedID: mentionedByID,
} }
if issues, err = issues_model.Issues(issuesOpt); err != nil { if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, "Issues", err) ctx.Error(http.StatusInternalServerError, "Issues", err)
return return
} }
@ -485,7 +485,7 @@ func ListIssues(ctx *context.APIContext) {
issuesOpt.ListOptions = db.ListOptions{ issuesOpt.ListOptions = db.ListOptions{
Page: -1, Page: -1,
} }
if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, "CountIssues", err) ctx.Error(http.StatusInternalServerError, "CountIssues", err)
return return
} }
@ -493,7 +493,7 @@ func ListIssues(ctx *context.APIContext) {
ctx.SetLinkHeader(int(filteredCount), listOptions.PageSize) ctx.SetLinkHeader(int(filteredCount), listOptions.PageSize)
ctx.SetTotalCountHeader(filteredCount) ctx.SetTotalCountHeader(filteredCount)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues))
} }
func getUserIDForFilter(ctx *context.APIContext, queryName string) int64 { func getUserIDForFilter(ctx *context.APIContext, queryName string) int64 {
@ -555,7 +555,7 @@ func GetIssue(ctx *context.APIContext) {
} }
return return
} }
ctx.JSON(http.StatusOK, convert.ToAPIIssue(issue)) ctx.JSON(http.StatusOK, convert.ToAPIIssue(ctx, issue))
} }
// CreateIssue create an issue of a repository // CreateIssue create an issue of a repository
@ -612,7 +612,7 @@ func CreateIssue(ctx *context.APIContext) {
var err error var err error
if ctx.Repo.CanWrite(unit.TypeIssues) { if ctx.Repo.CanWrite(unit.TypeIssues) {
issue.MilestoneID = form.Milestone issue.MilestoneID = form.Milestone
assigneeIDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees) assigneeIDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(ctx, form.Assignee, form.Assignees)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
@ -671,7 +671,7 @@ func CreateIssue(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetIssueByID", err) ctx.Error(http.StatusInternalServerError, "GetIssueByID", err)
return return
} }
ctx.JSON(http.StatusCreated, convert.ToAPIIssue(issue)) ctx.JSON(http.StatusCreated, convert.ToAPIIssue(ctx, issue))
} }
// EditIssue modify an issue of a repository // EditIssue modify an issue of a repository
@ -823,11 +823,11 @@ func EditIssue(ctx *context.APIContext) {
} }
if titleChanged { if titleChanged {
notification.NotifyIssueChangeTitle(ctx.Doer, issue, oldTitle) notification.NotifyIssueChangeTitle(ctx, ctx.Doer, issue, oldTitle)
} }
if statusChangeComment != nil { if statusChangeComment != nil {
notification.NotifyIssueChangeStatus(ctx.Doer, issue, statusChangeComment, issue.IsClosed) notification.NotifyIssueChangeStatus(ctx, ctx.Doer, issue, statusChangeComment, issue.IsClosed)
} }
// Refetch from database to assign some automatic values // Refetch from database to assign some automatic values
@ -836,11 +836,11 @@ func EditIssue(ctx *context.APIContext) {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
if err = issue.LoadMilestone(); err != nil { if err = issue.LoadMilestone(ctx); err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
ctx.JSON(http.StatusCreated, convert.ToAPIIssue(issue)) ctx.JSON(http.StatusCreated, convert.ToAPIIssue(ctx, issue))
} }
func DeleteIssue(ctx *context.APIContext) { func DeleteIssue(ctx *context.APIContext) {

View file

@ -91,7 +91,7 @@ func ListIssueComments(ctx *context.APIContext) {
return return
} }
if err := issues_model.CommentList(comments).LoadPosters(); err != nil { if err := issues_model.CommentList(comments).LoadPosters(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadPosters", err) ctx.Error(http.StatusInternalServerError, "LoadPosters", err)
return return
} }
@ -178,7 +178,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
return return
} }
if err := issues_model.CommentList(comments).LoadPosters(); err != nil { if err := issues_model.CommentList(comments).LoadPosters(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadPosters", err) ctx.Error(http.StatusInternalServerError, "LoadPosters", err)
return return
} }
@ -187,7 +187,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
for _, comment := range comments { for _, comment := range comments {
if comment.Type != issues_model.CommentTypeCode && isXRefCommentAccessible(ctx, ctx.Doer, comment, issue.RepoID) { if comment.Type != issues_model.CommentTypeCode && isXRefCommentAccessible(ctx, ctx.Doer, comment, issue.RepoID) {
comment.Issue = issue comment.Issue = issue
apiComments = append(apiComments, convert.ToTimelineComment(comment, ctx.Doer)) apiComments = append(apiComments, convert.ToTimelineComment(ctx, comment, ctx.Doer))
} }
} }
@ -281,21 +281,21 @@ func ListRepoIssueComments(ctx *context.APIContext) {
return return
} }
if err = issues_model.CommentList(comments).LoadPosters(); err != nil { if err = issues_model.CommentList(comments).LoadPosters(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadPosters", err) ctx.Error(http.StatusInternalServerError, "LoadPosters", err)
return return
} }
apiComments := make([]*api.Comment, len(comments)) apiComments := make([]*api.Comment, len(comments))
if err := issues_model.CommentList(comments).LoadIssues(); err != nil { if err := issues_model.CommentList(comments).LoadIssues(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssues", err) ctx.Error(http.StatusInternalServerError, "LoadIssues", err)
return return
} }
if err := issues_model.CommentList(comments).LoadPosters(); err != nil { if err := issues_model.CommentList(comments).LoadPosters(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadPosters", err) ctx.Error(http.StatusInternalServerError, "LoadPosters", err)
return return
} }
if _, err := issues_model.CommentList(comments).Issues().LoadRepositories(); err != nil { if _, err := issues_model.CommentList(comments).Issues().LoadRepositories(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadRepositories", err) ctx.Error(http.StatusInternalServerError, "LoadRepositories", err)
return return
} }
@ -354,7 +354,7 @@ func CreateIssueComment(ctx *context.APIContext) {
return return
} }
comment, err := comment_service.CreateIssueComment(ctx.Doer, ctx.Repo.Repository, issue, form.Body, nil) comment, err := comment_service.CreateIssueComment(ctx, ctx.Doer, ctx.Repo.Repository, issue, form.Body, nil)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CreateIssueComment", err) ctx.Error(http.StatusInternalServerError, "CreateIssueComment", err)
return return
@ -409,7 +409,7 @@ func GetIssueComment(ctx *context.APIContext) {
return return
} }
if err = comment.LoadIssue(); err != nil { if err = comment.LoadIssue(ctx); err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
@ -423,7 +423,7 @@ func GetIssueComment(ctx *context.APIContext) {
return return
} }
if err := comment.LoadPoster(); err != nil { if err := comment.LoadPoster(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "comment.LoadPoster", err) ctx.Error(http.StatusInternalServerError, "comment.LoadPoster", err)
return return
} }
@ -548,7 +548,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption)
oldContent := comment.Content oldContent := comment.Content
comment.Content = form.Body comment.Content = form.Body
if err := comment_service.UpdateComment(comment, ctx.Doer, oldContent); err != nil { if err := comment_service.UpdateComment(ctx, comment, ctx.Doer, oldContent); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateComment", err) ctx.Error(http.StatusInternalServerError, "UpdateComment", err)
return return
} }
@ -647,7 +647,7 @@ func deleteIssueComment(ctx *context.APIContext) {
return return
} }
if err = comment_service.DeleteComment(ctx.Doer, comment); err != nil { if err = comment_service.DeleteComment(ctx, ctx.Doer, comment); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteCommentByID", err) ctx.Error(http.StatusInternalServerError, "DeleteCommentByID", err)
return return
} }

View file

@ -58,7 +58,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
return return
} }
if err := comment.LoadIssue(); err != nil { if err := comment.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "comment.LoadIssue", err) ctx.Error(http.StatusInternalServerError, "comment.LoadIssue", err)
} }
@ -185,7 +185,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
return return
} }
err = comment.LoadIssue() err = comment.LoadIssue(ctx)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "comment.LoadIssue() failed", err) ctx.Error(http.StatusInternalServerError, "comment.LoadIssue() failed", err)
} }

View file

@ -139,7 +139,7 @@ func ListTrackedTimes(ctx *context.APIContext) {
} }
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes))
} }
// AddTime add time manual to the given issue // AddTime add time manual to the given issue
@ -224,7 +224,7 @@ func AddTime(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }
ctx.JSON(http.StatusOK, convert.ToTrackedTime(trackedTime)) ctx.JSON(http.StatusOK, convert.ToTrackedTime(ctx, trackedTime))
} }
// ResetIssueTime reset time manual to the given issue // ResetIssueTime reset time manual to the given issue
@ -448,7 +448,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }
ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes))
} }
// ListTrackedTimesByRepository lists all tracked times of the repository // ListTrackedTimesByRepository lists all tracked times of the repository
@ -558,7 +558,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) {
} }
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes))
} }
// ListMyTrackedTimes lists all tracked times of the current user // ListMyTrackedTimes lists all tracked times of the current user
@ -620,5 +620,5 @@ func ListMyTrackedTimes(ctx *context.APIContext) {
} }
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes))
} }

View file

@ -195,7 +195,7 @@ func Migrate(ctx *context.APIContext) {
} }
if err == nil { if err == nil {
notification.NotifyMigrateRepository(ctx.Doer, repoOwner, repo) notification.NotifyMigrateRepository(ctx, ctx.Doer, repoOwner, repo)
return return
} }

View file

@ -109,19 +109,19 @@ func ListPullRequests(ctx *context.APIContext) {
apiPrs := make([]*api.PullRequest, len(prs)) apiPrs := make([]*api.PullRequest, len(prs))
for i := range prs { for i := range prs {
if err = prs[i].LoadIssue(); err != nil { if err = prs[i].LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err) ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return return
} }
if err = prs[i].LoadAttributes(); err != nil { if err = prs[i].LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }
if err = prs[i].LoadBaseRepoCtx(ctx); err != nil { if err = prs[i].LoadBaseRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err) ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
return return
} }
if err = prs[i].LoadHeadRepoCtx(ctx); err != nil { if err = prs[i].LoadHeadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
return return
} }
@ -173,11 +173,11 @@ func GetPullRequest(ctx *context.APIContext) {
return return
} }
if err = pr.LoadBaseRepoCtx(ctx); err != nil { if err = pr.LoadBaseRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err) ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
return return
} }
if err = pr.LoadHeadRepoCtx(ctx); err != nil { if err = pr.LoadHeadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
return return
} }
@ -300,7 +300,7 @@ func CreatePullRequest(ctx *context.APIContext) {
defer headGitRepo.Close() defer headGitRepo.Close()
// Check if another PR exists with the same targets // Check if another PR exists with the same targets
existingPr, err := issues_model.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch, issues_model.PullRequestFlowGithub) existingPr, err := issues_model.GetUnmergedPullRequest(ctx, headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch, issues_model.PullRequestFlowGithub)
if err != nil { if err != nil {
if !issues_model.IsErrPullRequestNotExist(err) { if !issues_model.IsErrPullRequestNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetUnmergedPullRequest", err) ctx.Error(http.StatusInternalServerError, "GetUnmergedPullRequest", err)
@ -320,7 +320,7 @@ func CreatePullRequest(ctx *context.APIContext) {
} }
if len(form.Labels) > 0 { if len(form.Labels) > 0 {
labels, err := issues_model.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) labels, err := issues_model.GetLabelsInRepoByIDs(ctx, ctx.Repo.Repository.ID, form.Labels)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err) ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err)
return return
@ -334,7 +334,7 @@ func CreatePullRequest(ctx *context.APIContext) {
} }
if ctx.Repo.Owner.IsOrganization() { if ctx.Repo.Owner.IsOrganization() {
orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx.Repo.Owner.ID, form.Labels) orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx, ctx.Repo.Owner.ID, form.Labels)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err) ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err)
return return
@ -389,7 +389,7 @@ func CreatePullRequest(ctx *context.APIContext) {
} }
// Get all assignee IDs // Get all assignee IDs
assigneeIDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees) assigneeIDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(ctx, form.Assignee, form.Assignees)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
@ -400,7 +400,7 @@ func CreatePullRequest(ctx *context.APIContext) {
} }
// Check if the passed assignees is assignable // Check if the passed assignees is assignable
for _, aID := range assigneeIDs { for _, aID := range assigneeIDs {
assignee, err := user_model.GetUserByID(aID) assignee, err := user_model.GetUserByIDCtx(ctx, aID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserByID", err) ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
return return
@ -483,7 +483,7 @@ func EditPullRequest(ctx *context.APIContext) {
return return
} }
err = pr.LoadIssue() err = pr.LoadIssue(ctx)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err) ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return return
@ -551,14 +551,14 @@ func EditPullRequest(ctx *context.APIContext) {
} }
if ctx.Repo.CanWrite(unit.TypePullRequests) && form.Labels != nil { if ctx.Repo.CanWrite(unit.TypePullRequests) && form.Labels != nil {
labels, err := issues_model.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) labels, err := issues_model.GetLabelsInRepoByIDs(ctx, ctx.Repo.Repository.ID, form.Labels)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDsError", err) ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDsError", err)
return return
} }
if ctx.Repo.Owner.IsOrganization() { if ctx.Repo.Owner.IsOrganization() {
orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx.Repo.Owner.ID, form.Labels) orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx, ctx.Repo.Owner.ID, form.Labels)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err) ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err)
return return
@ -591,11 +591,11 @@ func EditPullRequest(ctx *context.APIContext) {
} }
if titleChanged { if titleChanged {
notification.NotifyIssueChangeTitle(ctx.Doer, issue, oldTitle) notification.NotifyIssueChangeTitle(ctx, ctx.Doer, issue, oldTitle)
} }
if statusChangeComment != nil { if statusChangeComment != nil {
notification.NotifyIssueChangeStatus(ctx.Doer, issue, statusChangeComment, issue.IsClosed) notification.NotifyIssueChangeStatus(ctx, ctx.Doer, issue, statusChangeComment, issue.IsClosed)
} }
// change pull target branch // change pull target branch
@ -619,7 +619,7 @@ func EditPullRequest(ctx *context.APIContext) {
} }
return return
} }
notification.NotifyPullRequestChangeTargetBranch(ctx.Doer, pr, form.Base) notification.NotifyPullRequestChangeTargetBranch(ctx, ctx.Doer, pr, form.Base)
} }
// update allow edits // update allow edits
@ -743,12 +743,12 @@ func MergePullRequest(ctx *context.APIContext) {
return return
} }
if err := pr.LoadHeadRepoCtx(ctx); err != nil { if err := pr.LoadHeadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
return return
} }
if err := pr.LoadIssueCtx(ctx); err != nil { if err := pr.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err) ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return return
} }
@ -811,7 +811,7 @@ func MergePullRequest(ctx *context.APIContext) {
message := strings.TrimSpace(form.MergeTitleField) message := strings.TrimSpace(form.MergeTitleField)
if len(message) == 0 { if len(message) == 0 {
message, err = pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do)) message, err = pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetDefaultMergeMessage", err) ctx.Error(http.StatusInternalServerError, "GetDefaultMergeMessage", err)
return return
@ -1097,7 +1097,7 @@ func UpdatePullRequest(ctx *context.APIContext) {
return return
} }
if err = pr.LoadIssue(); err != nil { if err = pr.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err) ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return return
} }
@ -1107,11 +1107,11 @@ func UpdatePullRequest(ctx *context.APIContext) {
return return
} }
if err = pr.LoadBaseRepoCtx(ctx); err != nil { if err = pr.LoadBaseRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err) ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
return return
} }
if err = pr.LoadHeadRepoCtx(ctx); err != nil { if err = pr.LoadHeadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
return return
} }
@ -1267,7 +1267,7 @@ func GetPullRequestCommits(ctx *context.APIContext) {
return return
} }
if err := pr.LoadBaseRepoCtx(ctx); err != nil { if err := pr.LoadBaseRepo(ctx); err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
@ -1383,12 +1383,12 @@ func GetPullRequestFiles(ctx *context.APIContext) {
return return
} }
if err := pr.LoadBaseRepo(); err != nil { if err := pr.LoadBaseRepo(ctx); err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
if err := pr.LoadHeadRepo(); err != nil { if err := pr.LoadHeadRepo(ctx); err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }

View file

@ -71,7 +71,7 @@ func ListPullReviews(ctx *context.APIContext) {
return return
} }
if err = pr.LoadIssue(); err != nil { if err = pr.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err) ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return return
} }
@ -476,7 +476,7 @@ func SubmitPullReview(ctx *context.APIContext) {
// preparePullReviewType return ReviewType and false or nil and true if an error happen // preparePullReviewType return ReviewType and false or nil and true if an error happen
func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest, event api.ReviewStateType, body string, hasComments bool) (issues_model.ReviewType, bool) { func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest, event api.ReviewStateType, body string, hasComments bool) (issues_model.ReviewType, bool) {
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err) ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return -1, true return -1, true
} }

View file

@ -61,7 +61,7 @@ func GetRelease(ctx *context.APIContext) {
return return
} }
if err := release.LoadAttributes(); err != nil { if err := release.LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }
@ -123,14 +123,14 @@ func ListReleases(ctx *context.APIContext) {
IsPreRelease: ctx.FormOptionalBool("pre-release"), IsPreRelease: ctx.FormOptionalBool("pre-release"),
} }
releases, err := repo_model.GetReleasesByRepoID(ctx.Repo.Repository.ID, opts) releases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetReleasesByRepoID", err) ctx.Error(http.StatusInternalServerError, "GetReleasesByRepoID", err)
return return
} }
rels := make([]*api.Release, len(releases)) rels := make([]*api.Release, len(releases))
for i, release := range releases { for i, release := range releases {
if err := release.LoadAttributes(); err != nil { if err := release.LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }
@ -313,7 +313,7 @@ func EditRelease(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return return
} }
if err := rel.LoadAttributes(); err != nil { if err := rel.LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }

View file

@ -114,7 +114,7 @@ func ListReleaseAttachments(ctx *context.APIContext) {
ctx.NotFound() ctx.NotFound()
return return
} }
if err := release.LoadAttributes(); err != nil { if err := release.LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }

View file

@ -60,7 +60,7 @@ func GetReleaseByTag(ctx *context.APIContext) {
return return
} }
if err = release.LoadAttributes(); err != nil { if err = release.LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return return
} }

View file

@ -191,7 +191,7 @@ func Search(ctx *context.APIContext) {
} }
var err error var err error
repos, count, err := repo_model.SearchRepository(opts) repos, count, err := repo_model.SearchRepository(ctx, opts)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, api.SearchError{ ctx.JSON(http.StatusInternalServerError, api.SearchError{
OK: false, OK: false,
@ -209,7 +209,7 @@ func Search(ctx *context.APIContext) {
}) })
return return
} }
accessMode, err := access_model.AccessLevel(ctx.Doer, repo) accessMode, err := access_model.AccessLevel(ctx, ctx.Doer, repo)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, api.SearchError{ ctx.JSON(http.StatusInternalServerError, api.SearchError{
OK: false, OK: false,

View file

@ -86,7 +86,7 @@ func NewWikiPage(ctx *context.APIContext) {
wikiPage := getWikiPage(ctx, wikiName) wikiPage := getWikiPage(ctx, wikiName)
if !ctx.Written() { if !ctx.Written() {
notification.NotifyNewWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName, form.Message) notification.NotifyNewWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName, form.Message)
ctx.JSON(http.StatusCreated, wikiPage) ctx.JSON(http.StatusCreated, wikiPage)
} }
} }
@ -154,7 +154,7 @@ func EditWikiPage(ctx *context.APIContext) {
wikiPage := getWikiPage(ctx, newWikiName) wikiPage := getWikiPage(ctx, newWikiName)
if !ctx.Written() { if !ctx.Written() {
notification.NotifyEditWikiPage(ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message) notification.NotifyEditWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message)
ctx.JSON(http.StatusOK, wikiPage) ctx.JSON(http.StatusOK, wikiPage)
} }
} }
@ -245,7 +245,7 @@ func DeleteWikiPage(ctx *context.APIContext) {
return return
} }
notification.NotifyDeleteWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName) notification.NotifyDeleteWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName)
ctx.Status(http.StatusNoContent) ctx.Status(http.StatusNoContent)
} }

View file

@ -39,7 +39,7 @@ func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) {
apiRepos := make([]*api.Repository, 0, len(repos)) apiRepos := make([]*api.Repository, 0, len(repos))
for i := range repos { for i := range repos {
access, err := access_model.AccessLevel(ctx.Doer, repos[i]) access, err := access_model.AccessLevel(ctx, ctx.Doer, repos[i])
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return return
@ -112,7 +112,7 @@ func ListMyRepos(ctx *context.APIContext) {
} }
var err error var err error
repos, count, err := repo_model.SearchRepository(opts) repos, count, err := repo_model.SearchRepository(ctx, opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepository", err) ctx.Error(http.StatusInternalServerError, "SearchRepository", err)
return return
@ -124,7 +124,7 @@ func ListMyRepos(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetOwner", err) ctx.Error(http.StatusInternalServerError, "GetOwner", err)
return return
} }
accessMode, err := access_model.AccessLevel(ctx.Doer, repo) accessMode, err := access_model.AccessLevel(ctx, ctx.Doer, repo)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
} }

View file

@ -6,6 +6,7 @@
package user package user
import ( import (
std_context "context"
"net/http" "net/http"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -20,15 +21,15 @@ import (
// getStarredRepos returns the repos that the user with the specified userID has // getStarredRepos returns the repos that the user with the specified userID has
// starred // starred
func getStarredRepos(user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, error) { func getStarredRepos(ctx std_context.Context, user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, error) {
starredRepos, err := repo_model.GetStarredRepos(user.ID, private, listOptions) starredRepos, err := repo_model.GetStarredRepos(ctx, user.ID, private, listOptions)
if err != nil { if err != nil {
return nil, err return nil, err
} }
repos := make([]*api.Repository, len(starredRepos)) repos := make([]*api.Repository, len(starredRepos))
for i, starred := range starredRepos { for i, starred := range starredRepos {
access, err := access_model.AccessLevel(user, starred) access, err := access_model.AccessLevel(ctx, user, starred)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -63,7 +64,7 @@ func GetStarredRepos(ctx *context.APIContext) {
// "$ref": "#/responses/RepositoryList" // "$ref": "#/responses/RepositoryList"
private := ctx.ContextUser.ID == ctx.Doer.ID private := ctx.ContextUser.ID == ctx.Doer.ID
repos, err := getStarredRepos(ctx.ContextUser, private, utils.GetListOptions(ctx)) repos, err := getStarredRepos(ctx, ctx.ContextUser, private, utils.GetListOptions(ctx))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "getStarredRepos", err) ctx.Error(http.StatusInternalServerError, "getStarredRepos", err)
return return
@ -93,7 +94,7 @@ func GetMyStarredRepos(ctx *context.APIContext) {
// "200": // "200":
// "$ref": "#/responses/RepositoryList" // "$ref": "#/responses/RepositoryList"
repos, err := getStarredRepos(ctx.Doer, true, utils.GetListOptions(ctx)) repos, err := getStarredRepos(ctx, ctx.Doer, true, utils.GetListOptions(ctx))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "getStarredRepos", err) ctx.Error(http.StatusInternalServerError, "getStarredRepos", err)
} }

View file

@ -5,6 +5,7 @@
package user package user
import ( import (
std_context "context"
"net/http" "net/http"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -18,15 +19,15 @@ import (
) )
// getWatchedRepos returns the repos that the user with the specified userID is watching // getWatchedRepos returns the repos that the user with the specified userID is watching
func getWatchedRepos(user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, int64, error) { func getWatchedRepos(ctx std_context.Context, user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, int64, error) {
watchedRepos, total, err := repo_model.GetWatchedRepos(user.ID, private, listOptions) watchedRepos, total, err := repo_model.GetWatchedRepos(ctx, user.ID, private, listOptions)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
repos := make([]*api.Repository, len(watchedRepos)) repos := make([]*api.Repository, len(watchedRepos))
for i, watched := range watchedRepos { for i, watched := range watchedRepos {
access, err := access_model.AccessLevel(user, watched) access, err := access_model.AccessLevel(ctx, user, watched)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
@ -61,7 +62,7 @@ func GetWatchedRepos(ctx *context.APIContext) {
// "$ref": "#/responses/RepositoryList" // "$ref": "#/responses/RepositoryList"
private := ctx.ContextUser.ID == ctx.Doer.ID private := ctx.ContextUser.ID == ctx.Doer.ID
repos, total, err := getWatchedRepos(ctx.ContextUser, private, utils.GetListOptions(ctx)) repos, total, err := getWatchedRepos(ctx, ctx.ContextUser, private, utils.GetListOptions(ctx))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err) ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err)
} }
@ -90,7 +91,7 @@ func GetMyWatchedRepos(ctx *context.APIContext) {
// "200": // "200":
// "$ref": "#/responses/RepositoryList" // "$ref": "#/responses/RepositoryList"
repos, total, err := getWatchedRepos(ctx.Doer, true, utils.GetListOptions(ctx)) repos, total, err := getWatchedRepos(ctx, ctx.Doer, true, utils.GetListOptions(ctx))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err) ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err)
} }

View file

@ -202,7 +202,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
continue continue
} }
pr, err := issues_model.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch, issues_model.PullRequestFlowGithub) pr, err := issues_model.GetUnmergedPullRequest(ctx, repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch, issues_model.PullRequestFlowGithub)
if err != nil && !issues_model.IsErrPullRequestNotExist(err) { if err != nil && !issues_model.IsErrPullRequestNotExist(err) {
log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err) log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{ ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{

View file

@ -372,7 +372,7 @@ func preReceiveTag(ctx *preReceiveContext, oldCommitID, newCommitID, refFullName
if !ctx.gotProtectedTags { if !ctx.gotProtectedTags {
var err error var err error
ctx.protectedTags, err = git_model.GetProtectedTags(ctx.Repo.Repository.ID) ctx.protectedTags, err = git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID)
if err != nil { if err != nil {
log.Error("Unable to get protected tags for %-v Error: %v", ctx.Repo.Repository, err) log.Error("Unable to get protected tags for %-v Error: %v", ctx.Repo.Repository, err)
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{
@ -383,7 +383,7 @@ func preReceiveTag(ctx *preReceiveContext, oldCommitID, newCommitID, refFullName
ctx.gotProtectedTags = true ctx.gotProtectedTags = true
} }
isAllowed, err := git_model.IsUserAllowedToControlTag(ctx.protectedTags, tagName, ctx.opts.UserID) isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, ctx.protectedTags, tagName, ctx.opts.UserID)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{
Err: err.Error(), Err: err.Error(),

View file

@ -98,7 +98,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) {
language := ctx.FormTrim("language") language := ctx.FormTrim("language")
ctx.Data["Language"] = language ctx.Data["Language"] = language
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: page, Page: page,
PageSize: opts.PageSize, PageSize: opts.PageSize,

View file

@ -88,7 +88,7 @@ func HomeSitemap(ctx *context.Context) {
} }
} }
_, cnt, err := repo_model.SearchRepository(&repo_model.SearchRepoOptions{ _, cnt, err := repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: 1, PageSize: 1,
}, },

View file

@ -99,7 +99,7 @@ func Home(ctx *context.Context) {
count int64 count int64
err error err error
) )
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
Page: page, Page: page,

View file

@ -275,14 +275,14 @@ func loadOneBranch(ctx *context.Context, rawBranch, defaultBranch *git.Branch, p
mergeMovedOn := false mergeMovedOn := false
if pr != nil { if pr != nil {
pr.HeadRepo = ctx.Repo.Repository pr.HeadRepo = ctx.Repo.Repository
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
ctx.ServerError("pr.LoadIssue", err) ctx.ServerError("LoadIssue", err)
return nil return nil
} }
if repo, ok := repoIDToRepo[pr.BaseRepoID]; ok { if repo, ok := repoIDToRepo[pr.BaseRepoID]; ok {
pr.BaseRepo = repo pr.BaseRepo = repo
} else if err := pr.LoadBaseRepoCtx(ctx); err != nil { } else if err := pr.LoadBaseRepo(ctx); err != nil {
ctx.ServerError("pr.LoadBaseRepo", err) ctx.ServerError("LoadBaseRepo", err)
return nil return nil
} else { } else {
repoIDToRepo[pr.BaseRepoID] = pr.BaseRepo repoIDToRepo[pr.BaseRepoID] = pr.BaseRepo

View file

@ -747,7 +747,7 @@ func CompareDiff(ctx *context.Context) {
ctx.Data["HeadTags"] = headTags ctx.Data["HeadTags"] = headTags
if ctx.Data["PageIsComparePull"] == true { if ctx.Data["PageIsComparePull"] == true {
pr, err := issues_model.GetUnmergedPullRequest(ci.HeadRepo.ID, ctx.Repo.Repository.ID, ci.HeadBranch, ci.BaseBranch, issues_model.PullRequestFlowGithub) pr, err := issues_model.GetUnmergedPullRequest(ctx, ci.HeadRepo.ID, ctx.Repo.Repository.ID, ci.HeadBranch, ci.BaseBranch, issues_model.PullRequestFlowGithub)
if err != nil { if err != nil {
if !issues_model.IsErrPullRequestNotExist(err) { if !issues_model.IsErrPullRequestNotExist(err) {
ctx.ServerError("GetUnmergedPullRequest", err) ctx.ServerError("GetUnmergedPullRequest", err)
@ -755,7 +755,7 @@ func CompareDiff(ctx *context.Context) {
} }
} else { } else {
ctx.Data["HasPullRequest"] = true ctx.Data["HasPullRequest"] = true
if err := pr.LoadIssue(); err != nil { if err := pr.LoadIssue(ctx); err != nil {
ctx.ServerError("LoadIssue", err) ctx.ServerError("LoadIssue", err)
return return
} }

View file

@ -246,7 +246,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
if forceEmpty { if forceEmpty {
issues = []*issues_model.Issue{} issues = []*issues_model.Issue{}
} else { } else {
issues, err = issues_model.Issues(&issues_model.IssuesOptions{ issues, err = issues_model.Issues(ctx, &issues_model.IssuesOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: pager.Paginater.Current(), Page: pager.Paginater.Current(),
PageSize: setting.UI.IssuePagingNum, PageSize: setting.UI.IssuePagingNum,
@ -608,7 +608,7 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, is
currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews)) currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews))
for _, item := range pullReviews { for _, item := range pullReviews {
if item.Review.ReviewerID > 0 { if item.Review.ReviewerID > 0 {
if err = item.Review.LoadReviewer(); err != nil { if err = item.Review.LoadReviewer(ctx); err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue
} }
@ -617,7 +617,7 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, is
} }
item.User = item.Review.Reviewer item.User = item.Review.Reviewer
} else if item.Review.ReviewerTeamID > 0 { } else if item.Review.ReviewerTeamID > 0 {
if err = item.Review.LoadReviewerTeam(); err != nil { if err = item.Review.LoadReviewerTeam(ctx); err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
continue continue
} }
@ -1163,7 +1163,7 @@ func getBranchData(ctx *context.Context, issue *issues_model.Issue) {
pull := issue.PullRequest pull := issue.PullRequest
ctx.Data["BaseBranch"] = pull.BaseBranch ctx.Data["BaseBranch"] = pull.BaseBranch
ctx.Data["HeadBranch"] = pull.HeadBranch ctx.Data["HeadBranch"] = pull.HeadBranch
ctx.Data["HeadUserName"] = pull.MustHeadUserName() ctx.Data["HeadUserName"] = pull.MustHeadUserName(ctx)
} }
} }
@ -1426,13 +1426,13 @@ func ViewIssue(ctx *context.Context) {
for _, comment = range issue.Comments { for _, comment = range issue.Comments {
comment.Issue = issue comment.Issue = issue
if err := comment.LoadPoster(); err != nil { if err := comment.LoadPoster(ctx); err != nil {
ctx.ServerError("LoadPoster", err) ctx.ServerError("LoadPoster", err)
return return
} }
if comment.Type == issues_model.CommentTypeComment || comment.Type == issues_model.CommentTypeReview { if comment.Type == issues_model.CommentTypeComment || comment.Type == issues_model.CommentTypeReview {
if err := comment.LoadAttachments(); err != nil { if err := comment.LoadAttachments(ctx); err != nil {
ctx.ServerError("LoadAttachments", err) ctx.ServerError("LoadAttachments", err)
return return
} }
@ -1467,7 +1467,7 @@ func ViewIssue(ctx *context.Context) {
return return
} }
} else if comment.Type == issues_model.CommentTypeMilestone { } else if comment.Type == issues_model.CommentTypeMilestone {
if err = comment.LoadMilestone(); err != nil { if err = comment.LoadMilestone(ctx); err != nil {
ctx.ServerError("LoadMilestone", err) ctx.ServerError("LoadMilestone", err)
return return
} }
@ -1591,7 +1591,7 @@ func ViewIssue(ctx *context.Context) {
ctx.Data["AllowMerge"] = false ctx.Data["AllowMerge"] = false
if ctx.IsSigned { if ctx.IsSigned {
if err := pull.LoadHeadRepoCtx(ctx); err != nil { if err := pull.LoadHeadRepo(ctx); err != nil {
log.Error("LoadHeadRepo: %v", err) log.Error("LoadHeadRepo: %v", err)
} else if pull.HeadRepo != nil { } else if pull.HeadRepo != nil {
perm, err := access_model.GetUserRepoPermission(ctx, pull.HeadRepo, ctx.Doer) perm, err := access_model.GetUserRepoPermission(ctx, pull.HeadRepo, ctx.Doer)
@ -1613,7 +1613,7 @@ func ViewIssue(ctx *context.Context) {
} }
} }
if err := pull.LoadBaseRepoCtx(ctx); err != nil { if err := pull.LoadBaseRepo(ctx); err != nil {
log.Error("LoadBaseRepo: %v", err) log.Error("LoadBaseRepo: %v", err)
} }
perm, err := access_model.GetUserRepoPermission(ctx, pull.BaseRepo, ctx.Doer) perm, err := access_model.GetUserRepoPermission(ctx, pull.BaseRepo, ctx.Doer)
@ -1662,14 +1662,14 @@ func ViewIssue(ctx *context.Context) {
ctx.Data["MergeStyle"] = mergeStyle ctx.Data["MergeStyle"] = mergeStyle
defaultMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pull, mergeStyle) defaultMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pull, mergeStyle)
if err != nil { if err != nil {
ctx.ServerError("GetDefaultMergeMessage", err) ctx.ServerError("GetDefaultMergeMessage", err)
return return
} }
ctx.Data["DefaultMergeMessage"] = defaultMergeMessage ctx.Data["DefaultMergeMessage"] = defaultMergeMessage
defaultSquashMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pull, repo_model.MergeStyleSquash) defaultSquashMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pull, repo_model.MergeStyleSquash)
if err != nil { if err != nil {
ctx.ServerError("GetDefaultSquashMergeMessage", err) ctx.ServerError("GetDefaultSquashMergeMessage", err)
return return
@ -1885,7 +1885,7 @@ func GetIssueInfo(ctx *context.Context) {
} }
} }
ctx.JSON(http.StatusOK, convert.ToAPIIssue(issue)) ctx.JSON(http.StatusOK, convert.ToAPIIssue(ctx, issue))
} }
// UpdateIssueTitle change issue's title // UpdateIssueTitle change issue's title
@ -2280,7 +2280,7 @@ func SearchIssues(ctx *context.Context) {
repoCond := repo_model.SearchRepositoryCondition(opts) repoCond := repo_model.SearchRepositoryCondition(opts)
repoIDs, _, err := repo_model.SearchRepositoryIDs(opts) repoIDs, _, err := repo_model.SearchRepositoryIDs(opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err.Error()) ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err.Error())
return return
} }
@ -2369,7 +2369,7 @@ func SearchIssues(ctx *context.Context) {
issuesOpt.ReviewRequestedID = ctxUserID issuesOpt.ReviewRequestedID = ctxUserID
} }
if issues, err = issues_model.Issues(issuesOpt); err != nil { if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, "Issues", err.Error()) ctx.Error(http.StatusInternalServerError, "Issues", err.Error())
return return
} }
@ -2377,14 +2377,14 @@ func SearchIssues(ctx *context.Context) {
issuesOpt.ListOptions = db.ListOptions{ issuesOpt.ListOptions = db.ListOptions{
Page: -1, Page: -1,
} }
if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, "CountIssues", err.Error()) ctx.Error(http.StatusInternalServerError, "CountIssues", err.Error())
return return
} }
} }
ctx.SetTotalCountHeader(filteredCount) ctx.SetTotalCountHeader(filteredCount)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues))
} }
func getUserIDForFilter(ctx *context.Context, queryName string) int64 { func getUserIDForFilter(ctx *context.Context, queryName string) int64 {
@ -2527,7 +2527,7 @@ func ListIssues(ctx *context.Context) {
MentionedID: mentionedByID, MentionedID: mentionedByID,
} }
if issues, err = issues_model.Issues(issuesOpt); err != nil { if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, err.Error()) ctx.Error(http.StatusInternalServerError, err.Error())
return return
} }
@ -2535,14 +2535,14 @@ func ListIssues(ctx *context.Context) {
issuesOpt.ListOptions = db.ListOptions{ issuesOpt.ListOptions = db.ListOptions{
Page: -1, Page: -1,
} }
if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil {
ctx.Error(http.StatusInternalServerError, err.Error()) ctx.Error(http.StatusInternalServerError, err.Error())
return return
} }
} }
ctx.SetTotalCountHeader(filteredCount) ctx.SetTotalCountHeader(filteredCount)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues))
} }
// UpdateIssueStatus change issue's status // UpdateIssueStatus change issue's status
@ -2562,7 +2562,7 @@ func UpdateIssueStatus(ctx *context.Context) {
log.Warn("Unrecognized action: %s", action) log.Warn("Unrecognized action: %s", action)
} }
if _, err := issues_model.IssueList(issues).LoadRepositories(); err != nil { if _, err := issues_model.IssueList(issues).LoadRepositories(ctx); err != nil {
ctx.ServerError("LoadRepositories", err) ctx.ServerError("LoadRepositories", err)
return return
} }
@ -2646,7 +2646,7 @@ func NewComment(ctx *context.Context) {
if form.Status == "reopen" && issue.IsPull { if form.Status == "reopen" && issue.IsPull {
pull := issue.PullRequest pull := issue.PullRequest
var err error var err error
pr, err = issues_model.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch, pull.Flow) pr, err = issues_model.GetUnmergedPullRequest(ctx, pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch, pull.Flow)
if err != nil { if err != nil {
if !issues_model.IsErrPullRequestNotExist(err) { if !issues_model.IsErrPullRequestNotExist(err) {
ctx.ServerError("GetUnmergedPullRequest", err) ctx.ServerError("GetUnmergedPullRequest", err)
@ -2706,7 +2706,7 @@ func NewComment(ctx *context.Context) {
return return
} }
comment, err := comment_service.CreateIssueComment(ctx.Doer, ctx.Repo.Repository, issue, form.Content, attachments) comment, err := comment_service.CreateIssueComment(ctx, ctx.Doer, ctx.Repo.Repository, issue, form.Content, attachments)
if err != nil { if err != nil {
ctx.ServerError("CreateIssueComment", err) ctx.ServerError("CreateIssueComment", err)
return return
@ -2723,7 +2723,7 @@ func UpdateCommentContent(ctx *context.Context) {
return return
} }
if err := comment.LoadIssue(); err != nil { if err := comment.LoadIssue(ctx); err != nil {
ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err) ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err)
return return
} }
@ -2746,12 +2746,12 @@ func UpdateCommentContent(ctx *context.Context) {
}) })
return return
} }
if err = comment_service.UpdateComment(comment, ctx.Doer, oldContent); err != nil { if err = comment_service.UpdateComment(ctx, comment, ctx.Doer, oldContent); err != nil {
ctx.ServerError("UpdateComment", err) ctx.ServerError("UpdateComment", err)
return return
} }
if err := comment.LoadAttachments(); err != nil { if err := comment.LoadAttachments(ctx); err != nil {
ctx.ServerError("LoadAttachments", err) ctx.ServerError("LoadAttachments", err)
return return
} }
@ -2789,7 +2789,7 @@ func DeleteComment(ctx *context.Context) {
return return
} }
if err := comment.LoadIssue(); err != nil { if err := comment.LoadIssue(ctx); err != nil {
ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err) ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err)
return return
} }
@ -2802,8 +2802,8 @@ func DeleteComment(ctx *context.Context) {
return return
} }
if err = comment_service.DeleteComment(ctx.Doer, comment); err != nil { if err = comment_service.DeleteComment(ctx, ctx.Doer, comment); err != nil {
ctx.ServerError("DeleteCommentByID", err) ctx.ServerError("DeleteComment", err)
return return
} }
@ -2915,7 +2915,7 @@ func ChangeCommentReaction(ctx *context.Context) {
return return
} }
if err := comment.LoadIssue(); err != nil { if err := comment.LoadIssue(ctx); err != nil {
ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err) ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err)
return return
} }
@ -3061,7 +3061,7 @@ func GetCommentAttachments(ctx *context.Context) {
} }
attachments := make([]*api.Attachment, 0) attachments := make([]*api.Attachment, 0)
if comment.Type == issues_model.CommentTypeComment { if comment.Type == issues_model.CommentTypeComment {
if err := comment.LoadAttachments(); err != nil { if err := comment.LoadAttachments(ctx); err != nil {
ctx.ServerError("LoadAttachments", err) ctx.ServerError("LoadAttachments", err)
return return
} }

View file

@ -75,7 +75,7 @@ func RetrieveLabels(ctx *context.Context) {
return return
} }
for _, l := range orgLabels { for _, l := range orgLabels {
l.CalOpenOrgIssues(ctx.Repo.Repository.ID, l.ID) l.CalOpenOrgIssues(ctx, ctx.Repo.Repository.ID, l.ID)
} }
ctx.Data["OrgLabels"] = orgLabels ctx.Data["OrgLabels"] = orgLabels

View file

@ -297,7 +297,7 @@ func ViewProject(ctx *context.Context) {
boards[0].Title = ctx.Tr("repo.projects.type.uncategorized") boards[0].Title = ctx.Tr("repo.projects.type.uncategorized")
} }
issuesMap, err := issues_model.LoadIssuesFromBoardList(boards) issuesMap, err := issues_model.LoadIssuesFromBoardList(ctx, boards)
if err != nil { if err != nil {
ctx.ServerError("LoadIssuesOfBoards", err) ctx.ServerError("LoadIssuesOfBoards", err)
return return
@ -314,7 +314,7 @@ func ViewProject(ctx *context.Context) {
} }
if len(referencedIds) > 0 { if len(referencedIds) > 0 {
if linkedPrs, err := issues_model.Issues(&issues_model.IssuesOptions{ if linkedPrs, err := issues_model.Issues(ctx, &issues_model.IssuesOptions{
IssueIDs: referencedIds, IssueIDs: referencedIds,
IsPull: util.OptionalBoolTrue, IsPull: util.OptionalBoolTrue,
}); err == nil { }); err == nil {

View file

@ -281,7 +281,7 @@ func checkPullInfo(ctx *context.Context) *issues_model.Issue {
} }
return nil return nil
} }
if err = issue.LoadPoster(); err != nil { if err = issue.LoadPoster(ctx); err != nil {
ctx.ServerError("LoadPoster", err) ctx.ServerError("LoadPoster", err)
return nil return nil
} }
@ -297,12 +297,12 @@ func checkPullInfo(ctx *context.Context) *issues_model.Issue {
return nil return nil
} }
if err = issue.LoadPullRequest(); err != nil { if err = issue.LoadPullRequest(ctx); err != nil {
ctx.ServerError("LoadPullRequest", err) ctx.ServerError("LoadPullRequest", err)
return nil return nil
} }
if err = issue.PullRequest.LoadHeadRepoCtx(ctx); err != nil { if err = issue.PullRequest.LoadHeadRepo(ctx); err != nil {
ctx.ServerError("LoadHeadRepo", err) ctx.ServerError("LoadHeadRepo", err)
return nil return nil
} }
@ -319,12 +319,12 @@ func checkPullInfo(ctx *context.Context) *issues_model.Issue {
} }
func setMergeTarget(ctx *context.Context, pull *issues_model.PullRequest) { func setMergeTarget(ctx *context.Context, pull *issues_model.PullRequest) {
if ctx.Repo.Owner.Name == pull.MustHeadUserName() { if ctx.Repo.Owner.Name == pull.MustHeadUserName(ctx) {
ctx.Data["HeadTarget"] = pull.HeadBranch ctx.Data["HeadTarget"] = pull.HeadBranch
} else if pull.HeadRepo == nil { } else if pull.HeadRepo == nil {
ctx.Data["HeadTarget"] = pull.MustHeadUserName() + ":" + pull.HeadBranch ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + ":" + pull.HeadBranch
} else { } else {
ctx.Data["HeadTarget"] = pull.MustHeadUserName() + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch
} }
ctx.Data["BaseTarget"] = pull.BaseBranch ctx.Data["BaseTarget"] = pull.BaseBranch
ctx.Data["HeadBranchHTMLURL"] = pull.GetHeadBranchHTMLURL() ctx.Data["HeadBranchHTMLURL"] = pull.GetHeadBranchHTMLURL()
@ -416,12 +416,12 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
pull := issue.PullRequest pull := issue.PullRequest
if err := pull.LoadHeadRepoCtx(ctx); err != nil { if err := pull.LoadHeadRepo(ctx); err != nil {
ctx.ServerError("LoadHeadRepo", err) ctx.ServerError("LoadHeadRepo", err)
return nil return nil
} }
if err := pull.LoadBaseRepoCtx(ctx); err != nil { if err := pull.LoadBaseRepo(ctx); err != nil {
ctx.ServerError("LoadBaseRepo", err) ctx.ServerError("LoadBaseRepo", err)
return nil return nil
} }
@ -606,7 +606,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C
if pull.IsWorkInProgress() { if pull.IsWorkInProgress() {
ctx.Data["IsPullWorkInProgress"] = true ctx.Data["IsPullWorkInProgress"] = true
ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix() ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix(ctx)
} }
if pull.IsFilesConflicted() { if pull.IsFilesConflicted() {
@ -834,11 +834,11 @@ func UpdatePullRequest(ctx *context.Context) {
rebase := ctx.FormString("style") == "rebase" rebase := ctx.FormString("style") == "rebase"
if err := issue.PullRequest.LoadBaseRepoCtx(ctx); err != nil { if err := issue.PullRequest.LoadBaseRepo(ctx); err != nil {
ctx.ServerError("LoadBaseRepo", err) ctx.ServerError("LoadBaseRepo", err)
return return
} }
if err := issue.PullRequest.LoadHeadRepoCtx(ctx); err != nil { if err := issue.PullRequest.LoadHeadRepo(ctx); err != nil {
ctx.ServerError("LoadHeadRepo", err) ctx.ServerError("LoadHeadRepo", err)
return return
} }
@ -974,7 +974,7 @@ func MergePullRequest(ctx *context.Context) {
message := strings.TrimSpace(form.MergeTitleField) message := strings.TrimSpace(form.MergeTitleField)
if len(message) == 0 { if len(message) == 0 {
var err error var err error
message, err = pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do)) message, err = pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do))
if err != nil { if err != nil {
ctx.ServerError("GetDefaultMergeMessage", err) ctx.ServerError("GetDefaultMergeMessage", err)
return return
@ -1296,14 +1296,14 @@ func CleanUpPullRequest(ctx *context.Context) {
return return
} }
if err := pr.LoadHeadRepoCtx(ctx); err != nil { if err := pr.LoadHeadRepo(ctx); err != nil {
ctx.ServerError("LoadHeadRepo", err) ctx.ServerError("LoadHeadRepo", err)
return return
} else if pr.HeadRepo == nil { } else if pr.HeadRepo == nil {
// Forked repository has already been deleted // Forked repository has already been deleted
ctx.NotFound("CleanUpPullRequest", nil) ctx.NotFound("CleanUpPullRequest", nil)
return return
} else if err = pr.LoadBaseRepoCtx(ctx); err != nil { } else if err = pr.LoadBaseRepo(ctx); err != nil {
ctx.ServerError("LoadBaseRepo", err) ctx.ServerError("LoadBaseRepo", err)
return return
} else if err = pr.HeadRepo.GetOwner(ctx); err != nil { } else if err = pr.HeadRepo.GetOwner(ctx); err != nil {
@ -1499,7 +1499,7 @@ func UpdatePullRequestTarget(ctx *context.Context) {
} }
return return
} }
notification.NotifyPullRequestChangeTargetBranch(ctx.Doer, pr, targetBranch) notification.NotifyPullRequestChangeTargetBranch(ctx, ctx.Doer, pr, targetBranch)
ctx.JSON(http.StatusOK, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"base_branch": pr.BaseBranch, "base_branch": pr.BaseBranch,

View file

@ -114,7 +114,7 @@ func UpdateResolveConversation(ctx *context.Context) {
return return
} }
if err = comment.LoadIssue(); err != nil { if err = comment.LoadIssue(ctx); err != nil {
ctx.ServerError("comment.LoadIssue", err) ctx.ServerError("comment.LoadIssue", err)
return return
} }
@ -169,7 +169,7 @@ func renderConversation(ctx *context.Context, comment *issues_model.Comment) {
ctx.Data["comments"] = comments ctx.Data["comments"] = comments
ctx.Data["CanMarkConversation"] = true ctx.Data["CanMarkConversation"] = true
ctx.Data["Issue"] = comment.Issue ctx.Data["Issue"] = comment.Issue
if err = comment.Issue.LoadPullRequest(); err != nil { if err = comment.Issue.LoadPullRequest(ctx); err != nil {
ctx.ServerError("comment.Issue.LoadPullRequest", err) ctx.ServerError("comment.Issue.LoadPullRequest", err)
return return
} }

View file

@ -130,7 +130,7 @@ func releasesOrTags(ctx *context.Context, isTagList bool) {
opts.IncludeDrafts = writeAccess opts.IncludeDrafts = writeAccess
} }
releases, err := repo_model.GetReleasesByRepoID(ctx.Repo.Repository.ID, opts) releases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)
if err != nil { if err != nil {
ctx.ServerError("GetReleasesByRepoID", err) ctx.ServerError("GetReleasesByRepoID", err)
return return
@ -266,7 +266,7 @@ func LatestRelease(ctx *context.Context) {
return return
} }
if err := release.LoadAttributes(); err != nil { if err := release.LoadAttributes(ctx); err != nil {
ctx.ServerError("LoadAttributes", err) ctx.ServerError("LoadAttributes", err)
return return
} }
@ -289,7 +289,7 @@ func NewRelease(ctx *context.Context) {
if rel != nil { if rel != nil {
rel.Repo = ctx.Repo.Repository rel.Repo = ctx.Repo.Repository
if err := rel.LoadAttributes(); err != nil { if err := rel.LoadAttributes(ctx); err != nil {
ctx.ServerError("LoadAttributes", err) ctx.ServerError("LoadAttributes", err)
return return
} }
@ -454,7 +454,7 @@ func EditRelease(ctx *context.Context) {
ctx.Data["IsDraft"] = rel.IsDraft ctx.Data["IsDraft"] = rel.IsDraft
rel.Repo = ctx.Repo.Repository rel.Repo = ctx.Repo.Repository
if err := rel.LoadAttributes(); err != nil { if err := rel.LoadAttributes(ctx); err != nil {
ctx.ServerError("LoadAttributes", err) ctx.ServerError("LoadAttributes", err)
return return
} }

View file

@ -540,7 +540,7 @@ func SearchRepo(ctx *context.Context) {
} }
var err error var err error
repos, count, err := repo_model.SearchRepository(opts) repos, count, err := repo_model.SearchRepository(ctx, opts)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, api.SearchError{ ctx.JSON(http.StatusInternalServerError, api.SearchError{
OK: false, OK: false,

View file

@ -124,7 +124,7 @@ func DeleteProtectedTagPost(ctx *context.Context) {
return return
} }
if err := git_model.DeleteProtectedTag(pt); err != nil { if err := git_model.DeleteProtectedTag(ctx, pt); err != nil {
ctx.ServerError("DeleteProtectedTag", err) ctx.ServerError("DeleteProtectedTag", err)
return return
} }
@ -137,7 +137,7 @@ func setTagsContext(ctx *context.Context) error {
ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsTags"] = true ctx.Data["PageIsSettingsTags"] = true
protectedTags, err := git_model.GetProtectedTags(ctx.Repo.Repository.ID) protectedTags, err := git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.ServerError("GetProtectedTags", err) ctx.ServerError("GetProtectedTags", err)
return err return err

View file

@ -706,7 +706,7 @@ func NewWikiPost(ctx *context.Context) {
return return
} }
notification.NotifyNewWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName, form.Message) notification.NotifyNewWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName, form.Message)
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wiki_service.NameToSubURL(wikiName)) ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wiki_service.NameToSubURL(wikiName))
} }
@ -750,7 +750,7 @@ func EditWikiPost(ctx *context.Context) {
return return
} }
notification.NotifyEditWikiPage(ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message) notification.NotifyEditWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message)
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wiki_service.NameToSubURL(newWikiName)) ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wiki_service.NameToSubURL(newWikiName))
} }
@ -767,7 +767,7 @@ func DeleteWikiPagePost(ctx *context.Context) {
return return
} }
notification.NotifyDeleteWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName) notification.NotifyDeleteWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName)
ctx.JSON(http.StatusOK, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/wiki/", "redirect": ctx.Repo.RepoLink + "/wiki/",

View file

@ -202,7 +202,7 @@ func Milestones(ctx *context.Context) {
return return
} }
showRepos, _, err := repo_model.SearchRepositoryByCondition(&repoOpts, userRepoCond, false) showRepos, _, err := repo_model.SearchRepositoryByCondition(ctx, &repoOpts, userRepoCond, false)
if err != nil { if err != nil {
ctx.ServerError("SearchRepositoryByCondition", err) ctx.ServerError("SearchRepositoryByCondition", err)
return return
@ -461,7 +461,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
// USING NON-FINAL STATE OF opts FOR A QUERY. // USING NON-FINAL STATE OF opts FOR A QUERY.
var issueCountByRepo map[int64]int64 var issueCountByRepo map[int64]int64
if !forceEmpty { if !forceEmpty {
issueCountByRepo, err = issues_model.CountIssuesByRepo(opts) issueCountByRepo, err = issues_model.CountIssuesByRepo(ctx, opts)
if err != nil { if err != nil {
ctx.ServerError("CountIssuesByRepo", err) ctx.ServerError("CountIssuesByRepo", err)
return return
@ -504,7 +504,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
// USING FINAL STATE OF opts FOR A QUERY. // USING FINAL STATE OF opts FOR A QUERY.
var issues []*issues_model.Issue var issues []*issues_model.Issue
if !forceEmpty { if !forceEmpty {
issues, err = issues_model.Issues(opts) issues, err = issues_model.Issues(ctx, opts)
if err != nil { if err != nil {
ctx.ServerError("Issues", err) ctx.ServerError("Issues", err)
return return

View file

@ -33,20 +33,20 @@ const (
) )
// GetNotificationCount is the middleware that sets the notification count in the context // GetNotificationCount is the middleware that sets the notification count in the context
func GetNotificationCount(c *context.Context) { func GetNotificationCount(ctx *context.Context) {
if strings.HasPrefix(c.Req.URL.Path, "/api") { if strings.HasPrefix(ctx.Req.URL.Path, "/api") {
return return
} }
if !c.IsSigned { if !ctx.IsSigned {
return return
} }
c.Data["NotificationUnreadCount"] = func() int64 { ctx.Data["NotificationUnreadCount"] = func() int64 {
count, err := activities_model.GetNotificationCount(c, c.Doer, activities_model.NotificationStatusUnread) count, err := activities_model.GetNotificationCount(ctx, ctx.Doer, activities_model.NotificationStatusUnread)
if err != nil { if err != nil {
if err != goctx.Canceled { if err != goctx.Canceled {
log.Error("Unable to GetNotificationCount for user:%-v: %v", c.Doer, err) log.Error("Unable to GetNotificationCount for user:%-v: %v", ctx.Doer, err)
} }
return -1 return -1
} }
@ -56,25 +56,25 @@ func GetNotificationCount(c *context.Context) {
} }
// Notifications is the notifications page // Notifications is the notifications page
func Notifications(c *context.Context) { func Notifications(ctx *context.Context) {
getNotifications(c) getNotifications(ctx)
if c.Written() { if ctx.Written() {
return return
} }
if c.FormBool("div-only") { if ctx.FormBool("div-only") {
c.Data["SequenceNumber"] = c.FormString("sequence-number") ctx.Data["SequenceNumber"] = ctx.FormString("sequence-number")
c.HTML(http.StatusOK, tplNotificationDiv) ctx.HTML(http.StatusOK, tplNotificationDiv)
return return
} }
c.HTML(http.StatusOK, tplNotification) ctx.HTML(http.StatusOK, tplNotification)
} }
func getNotifications(c *context.Context) { func getNotifications(ctx *context.Context) {
var ( var (
keyword = c.FormTrim("q") keyword = ctx.FormTrim("q")
status activities_model.NotificationStatus status activities_model.NotificationStatus
page = c.FormInt("page") page = ctx.FormInt("page")
perPage = c.FormInt("perPage") perPage = ctx.FormInt("perPage")
) )
if page < 1 { if page < 1 {
page = 1 page = 1
@ -90,74 +90,74 @@ func getNotifications(c *context.Context) {
status = activities_model.NotificationStatusUnread status = activities_model.NotificationStatusUnread
} }
total, err := activities_model.GetNotificationCount(c, c.Doer, status) total, err := activities_model.GetNotificationCount(ctx, ctx.Doer, status)
if err != nil { if err != nil {
c.ServerError("ErrGetNotificationCount", err) ctx.ServerError("ErrGetNotificationCount", err)
return return
} }
// redirect to last page if request page is more than total pages // redirect to last page if request page is more than total pages
pager := context.NewPagination(int(total), perPage, page, 5) pager := context.NewPagination(int(total), perPage, page, 5)
if pager.Paginater.Current() < page { if pager.Paginater.Current() < page {
c.Redirect(fmt.Sprintf("%s/notifications?q=%s&page=%d", setting.AppSubURL, url.QueryEscape(c.FormString("q")), pager.Paginater.Current())) ctx.Redirect(fmt.Sprintf("%s/notifications?q=%s&page=%d", setting.AppSubURL, url.QueryEscape(ctx.FormString("q")), pager.Paginater.Current()))
return return
} }
statuses := []activities_model.NotificationStatus{status, activities_model.NotificationStatusPinned} statuses := []activities_model.NotificationStatus{status, activities_model.NotificationStatusPinned}
notifications, err := activities_model.NotificationsForUser(c, c.Doer, statuses, page, perPage) notifications, err := activities_model.NotificationsForUser(ctx, ctx.Doer, statuses, page, perPage)
if err != nil { if err != nil {
c.ServerError("ErrNotificationsForUser", err) ctx.ServerError("ErrNotificationsForUser", err)
return return
} }
failCount := 0 failCount := 0
repos, failures, err := notifications.LoadRepos() repos, failures, err := notifications.LoadRepos(ctx)
if err != nil { if err != nil {
c.ServerError("LoadRepos", err) ctx.ServerError("LoadRepos", err)
return return
} }
notifications = notifications.Without(failures) notifications = notifications.Without(failures)
if err := repos.LoadAttributes(); err != nil { if err := repos.LoadAttributes(); err != nil { // TODO
c.ServerError("LoadAttributes", err) ctx.ServerError("LoadAttributes", err)
return return
} }
failCount += len(failures) failCount += len(failures)
failures, err = notifications.LoadIssues() failures, err = notifications.LoadIssues(ctx)
if err != nil { if err != nil {
c.ServerError("LoadIssues", err) ctx.ServerError("LoadIssues", err)
return return
} }
notifications = notifications.Without(failures) notifications = notifications.Without(failures)
failCount += len(failures) failCount += len(failures)
failures, err = notifications.LoadComments() failures, err = notifications.LoadComments(ctx)
if err != nil { if err != nil {
c.ServerError("LoadComments", err) ctx.ServerError("LoadComments", err)
return return
} }
notifications = notifications.Without(failures) notifications = notifications.Without(failures)
failCount += len(failures) failCount += len(failures)
if failCount > 0 { if failCount > 0 {
c.Flash.Error(fmt.Sprintf("ERROR: %d notifications were removed due to missing parts - check the logs", failCount)) ctx.Flash.Error(fmt.Sprintf("ERROR: %d notifications were removed due to missing parts - check the logs", failCount))
} }
c.Data["Title"] = c.Tr("notifications") ctx.Data["Title"] = ctx.Tr("notifications")
c.Data["Keyword"] = keyword ctx.Data["Keyword"] = keyword
c.Data["Status"] = status ctx.Data["Status"] = status
c.Data["Notifications"] = notifications ctx.Data["Notifications"] = notifications
pager.SetDefaultParams(c) pager.SetDefaultParams(ctx)
c.Data["Page"] = pager ctx.Data["Page"] = pager
} }
// NotificationStatusPost is a route for changing the status of a notification // NotificationStatusPost is a route for changing the status of a notification
func NotificationStatusPost(c *context.Context) { func NotificationStatusPost(ctx *context.Context) {
var ( var (
notificationID = c.FormInt64("notification_id") notificationID = ctx.FormInt64("notification_id")
statusStr = c.FormString("status") statusStr = ctx.FormString("status")
status activities_model.NotificationStatus status activities_model.NotificationStatus
) )
@ -169,56 +169,56 @@ func NotificationStatusPost(c *context.Context) {
case "pinned": case "pinned":
status = activities_model.NotificationStatusPinned status = activities_model.NotificationStatusPinned
default: default:
c.ServerError("InvalidNotificationStatus", errors.New("Invalid notification status")) ctx.ServerError("InvalidNotificationStatus", errors.New("Invalid notification status"))
return return
} }
if _, err := activities_model.SetNotificationStatus(notificationID, c.Doer, status); err != nil { if _, err := activities_model.SetNotificationStatus(ctx, notificationID, ctx.Doer, status); err != nil {
c.ServerError("SetNotificationStatus", err) ctx.ServerError("SetNotificationStatus", err)
return return
} }
if !c.FormBool("noredirect") { if !ctx.FormBool("noredirect") {
url := fmt.Sprintf("%s/notifications?page=%s", setting.AppSubURL, url.QueryEscape(c.FormString("page"))) url := fmt.Sprintf("%s/notifications?page=%s", setting.AppSubURL, url.QueryEscape(ctx.FormString("page")))
c.Redirect(url, http.StatusSeeOther) ctx.Redirect(url, http.StatusSeeOther)
} }
getNotifications(c) getNotifications(ctx)
if c.Written() { if ctx.Written() {
return return
} }
c.Data["Link"] = setting.AppURL + "notifications" ctx.Data["Link"] = setting.AppURL + "notifications"
c.Data["SequenceNumber"] = c.Req.PostFormValue("sequence-number") ctx.Data["SequenceNumber"] = ctx.Req.PostFormValue("sequence-number")
c.HTML(http.StatusOK, tplNotificationDiv) ctx.HTML(http.StatusOK, tplNotificationDiv)
} }
// NotificationPurgePost is a route for 'purging' the list of notifications - marking all unread as read // NotificationPurgePost is a route for 'purging' the list of notifications - marking all unread as read
func NotificationPurgePost(c *context.Context) { func NotificationPurgePost(ctx *context.Context) {
err := activities_model.UpdateNotificationStatuses(c.Doer, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead) err := activities_model.UpdateNotificationStatuses(ctx, ctx.Doer, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead)
if err != nil { if err != nil {
c.ServerError("ErrUpdateNotificationStatuses", err) ctx.ServerError("UpdateNotificationStatuses", err)
return return
} }
c.Redirect(setting.AppSubURL+"/notifications", http.StatusSeeOther) ctx.Redirect(setting.AppSubURL+"/notifications", http.StatusSeeOther)
} }
// NotificationSubscriptions returns the list of subscribed issues // NotificationSubscriptions returns the list of subscribed issues
func NotificationSubscriptions(c *context.Context) { func NotificationSubscriptions(ctx *context.Context) {
page := c.FormInt("page") page := ctx.FormInt("page")
if page < 1 { if page < 1 {
page = 1 page = 1
} }
sortType := c.FormString("sort") sortType := ctx.FormString("sort")
c.Data["SortType"] = sortType ctx.Data["SortType"] = sortType
state := c.FormString("state") state := ctx.FormString("state")
if !util.IsStringInSlice(state, []string{"all", "open", "closed"}, true) { if !util.IsStringInSlice(state, []string{"all", "open", "closed"}, true) {
state = "all" state = "all"
} }
c.Data["State"] = state ctx.Data["State"] = state
var showClosed util.OptionalBool var showClosed util.OptionalBool
switch state { switch state {
case "all": case "all":
@ -230,7 +230,7 @@ func NotificationSubscriptions(c *context.Context) {
} }
var issueTypeBool util.OptionalBool var issueTypeBool util.OptionalBool
issueType := c.FormString("issueType") issueType := ctx.FormString("issueType")
switch issueType { switch issueType {
case "issues": case "issues":
issueTypeBool = util.OptionalBoolFalse issueTypeBool = util.OptionalBoolFalse
@ -239,71 +239,71 @@ func NotificationSubscriptions(c *context.Context) {
default: default:
issueTypeBool = util.OptionalBoolNone issueTypeBool = util.OptionalBoolNone
} }
c.Data["IssueType"] = issueType ctx.Data["IssueType"] = issueType
var labelIDs []int64 var labelIDs []int64
selectedLabels := c.FormString("labels") selectedLabels := ctx.FormString("labels")
c.Data["Labels"] = selectedLabels ctx.Data["Labels"] = selectedLabels
if len(selectedLabels) > 0 && selectedLabels != "0" { if len(selectedLabels) > 0 && selectedLabels != "0" {
var err error var err error
labelIDs, err = base.StringsToInt64s(strings.Split(selectedLabels, ",")) labelIDs, err = base.StringsToInt64s(strings.Split(selectedLabels, ","))
if err != nil { if err != nil {
c.ServerError("StringsToInt64s", err) ctx.ServerError("StringsToInt64s", err)
return return
} }
} }
count, err := issues_model.CountIssues(&issues_model.IssuesOptions{ count, err := issues_model.CountIssues(ctx, &issues_model.IssuesOptions{
SubscriberID: c.Doer.ID, SubscriberID: ctx.Doer.ID,
IsClosed: showClosed, IsClosed: showClosed,
IsPull: issueTypeBool, IsPull: issueTypeBool,
LabelIDs: labelIDs, LabelIDs: labelIDs,
}) })
if err != nil { if err != nil {
c.ServerError("CountIssues", err) ctx.ServerError("CountIssues", err)
return return
} }
issues, err := issues_model.Issues(&issues_model.IssuesOptions{ issues, err := issues_model.Issues(ctx, &issues_model.IssuesOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.IssuePagingNum, PageSize: setting.UI.IssuePagingNum,
Page: page, Page: page,
}, },
SubscriberID: c.Doer.ID, SubscriberID: ctx.Doer.ID,
SortType: sortType, SortType: sortType,
IsClosed: showClosed, IsClosed: showClosed,
IsPull: issueTypeBool, IsPull: issueTypeBool,
LabelIDs: labelIDs, LabelIDs: labelIDs,
}) })
if err != nil { if err != nil {
c.ServerError("Issues", err) ctx.ServerError("Issues", err)
return return
} }
commitStatuses, lastStatus, err := pull_service.GetIssuesAllCommitStatus(c, issues) commitStatuses, lastStatus, err := pull_service.GetIssuesAllCommitStatus(ctx, issues)
if err != nil { if err != nil {
c.ServerError("GetIssuesAllCommitStatus", err) ctx.ServerError("GetIssuesAllCommitStatus", err)
return return
} }
c.Data["CommitLastStatus"] = lastStatus ctx.Data["CommitLastStatus"] = lastStatus
c.Data["CommitStatuses"] = commitStatuses ctx.Data["CommitStatuses"] = commitStatuses
c.Data["Issues"] = issues ctx.Data["Issues"] = issues
c.Data["IssueRefEndNames"], c.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, "") ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, "")
commitStatus, err := pull_service.GetIssuesLastCommitStatus(c, issues) commitStatus, err := pull_service.GetIssuesLastCommitStatus(ctx, issues)
if err != nil { if err != nil {
c.ServerError("GetIssuesLastCommitStatus", err) ctx.ServerError("GetIssuesLastCommitStatus", err)
return return
} }
c.Data["CommitStatus"] = commitStatus ctx.Data["CommitStatus"] = commitStatus
issueList := issues_model.IssueList(issues) issueList := issues_model.IssueList(issues)
approvalCounts, err := issueList.GetApprovalCounts(c) approvalCounts, err := issueList.GetApprovalCounts(ctx)
if err != nil { if err != nil {
c.ServerError("ApprovalCounts", err) ctx.ServerError("ApprovalCounts", err)
return return
} }
c.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 { ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
counts, ok := approvalCounts[issueID] counts, ok := approvalCounts[issueID]
if !ok || len(counts) == 0 { if !ok || len(counts) == 0 {
return 0 return 0
@ -322,32 +322,32 @@ func NotificationSubscriptions(c *context.Context) {
return 0 return 0
} }
c.Data["Status"] = 1 ctx.Data["Status"] = 1
c.Data["Title"] = c.Tr("notification.subscriptions") ctx.Data["Title"] = ctx.Tr("notification.subscriptions")
// redirect to last page if request page is more than total pages // redirect to last page if request page is more than total pages
pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5) pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
if pager.Paginater.Current() < page { if pager.Paginater.Current() < page {
c.Redirect(fmt.Sprintf("/notifications/subscriptions?page=%d", pager.Paginater.Current())) ctx.Redirect(fmt.Sprintf("/notifications/subscriptions?page=%d", pager.Paginater.Current()))
return return
} }
pager.AddParam(c, "sort", "SortType") pager.AddParam(ctx, "sort", "SortType")
pager.AddParam(c, "state", "State") pager.AddParam(ctx, "state", "State")
c.Data["Page"] = pager ctx.Data["Page"] = pager
c.HTML(http.StatusOK, tplNotificationSubscriptions) ctx.HTML(http.StatusOK, tplNotificationSubscriptions)
} }
// NotificationWatching returns the list of watching repos // NotificationWatching returns the list of watching repos
func NotificationWatching(c *context.Context) { func NotificationWatching(ctx *context.Context) {
page := c.FormInt("page") page := ctx.FormInt("page")
if page < 1 { if page < 1 {
page = 1 page = 1
} }
var orderBy db.SearchOrderBy var orderBy db.SearchOrderBy
c.Data["SortType"] = c.FormString("sort") ctx.Data["SortType"] = ctx.FormString("sort")
switch c.FormString("sort") { switch ctx.FormString("sort") {
case "newest": case "newest":
orderBy = db.SearchOrderByNewest orderBy = db.SearchOrderByNewest
case "oldest": case "oldest":
@ -369,41 +369,41 @@ func NotificationWatching(c *context.Context) {
case "fewestforks": case "fewestforks":
orderBy = db.SearchOrderByForks orderBy = db.SearchOrderByForks
default: default:
c.Data["SortType"] = "recentupdate" ctx.Data["SortType"] = "recentupdate"
orderBy = db.SearchOrderByRecentUpdated orderBy = db.SearchOrderByRecentUpdated
} }
repos, count, err := repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err := repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
Page: page, Page: page,
}, },
Actor: c.Doer, Actor: ctx.Doer,
Keyword: c.FormTrim("q"), Keyword: ctx.FormTrim("q"),
OrderBy: orderBy, OrderBy: orderBy,
Private: c.IsSigned, Private: ctx.IsSigned,
WatchedByID: c.Doer.ID, WatchedByID: ctx.Doer.ID,
Collaborate: util.OptionalBoolFalse, Collaborate: util.OptionalBoolFalse,
TopicOnly: c.FormBool("topic"), TopicOnly: ctx.FormBool("topic"),
IncludeDescription: setting.UI.SearchRepoDescription, IncludeDescription: setting.UI.SearchRepoDescription,
}) })
if err != nil { if err != nil {
c.ServerError("ErrSearchRepository", err) ctx.ServerError("SearchRepository", err)
return return
} }
total := int(count) total := int(count)
c.Data["Total"] = total ctx.Data["Total"] = total
c.Data["Repos"] = repos ctx.Data["Repos"] = repos
// redirect to last page if request page is more than total pages // redirect to last page if request page is more than total pages
pager := context.NewPagination(total, setting.UI.User.RepoPagingNum, page, 5) pager := context.NewPagination(total, setting.UI.User.RepoPagingNum, page, 5)
pager.SetDefaultParams(c) pager.SetDefaultParams(ctx)
c.Data["Page"] = pager ctx.Data["Page"] = pager
c.Data["Status"] = 2 ctx.Data["Status"] = 2
c.Data["Title"] = c.Tr("notification.watching") ctx.Data["Title"] = ctx.Tr("notification.watching")
c.HTML(http.StatusOK, tplNotificationSubscriptions) ctx.HTML(http.StatusOK, tplNotificationSubscriptions)
} }
// NewAvailable returns the notification counts // NewAvailable returns the notification counts

View file

@ -203,7 +203,7 @@ func Profile(ctx *context.Context) {
} }
case "stars": case "stars":
ctx.Data["PageIsProfileStarList"] = true ctx.Data["PageIsProfileStarList"] = true
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
Page: page, Page: page,
@ -235,7 +235,7 @@ func Profile(ctx *context.Context) {
return return
} }
case "watching": case "watching":
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
Page: page, Page: page,
@ -257,7 +257,7 @@ func Profile(ctx *context.Context) {
total = int(count) total = int(count)
default: default:
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
Page: page, Page: page,

View file

@ -96,7 +96,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git.
headBranch = curentTopicBranch headBranch = curentTopicBranch
} }
pr, err := issues_model.GetUnmergedPullRequest(repo.ID, repo.ID, headBranch, baseBranchName, issues_model.PullRequestFlowAGit) pr, err := issues_model.GetUnmergedPullRequest(ctx, repo.ID, repo.ID, headBranch, baseBranchName, issues_model.PullRequestFlowAGit)
if err != nil { if err != nil {
if !issues_model.IsErrPullRequestNotExist(err) { if !issues_model.IsErrPullRequestNotExist(err) {
return nil, fmt.Errorf("Failed to get unmerged agit flow pull request in repository: %s/%s Error: %w", ownerName, repoName, err) return nil, fmt.Errorf("Failed to get unmerged agit flow pull request in repository: %s/%s Error: %w", ownerName, repoName, err)
@ -159,7 +159,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git.
} }
// update exist pull request // update exist pull request
if err := pr.LoadBaseRepoCtx(ctx); err != nil { if err := pr.LoadBaseRepo(ctx); err != nil {
return nil, fmt.Errorf("Unable to load base repository for PR[%d] Error: %w", pr.ID, err) return nil, fmt.Errorf("Unable to load base repository for PR[%d] Error: %w", pr.ID, err)
} }
@ -203,15 +203,15 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git.
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to get user. Error: %w", err) return nil, fmt.Errorf("Failed to get user. Error: %w", err)
} }
err = pr.LoadIssue() err = pr.LoadIssue(ctx)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to load pull issue. Error: %w", err) return nil, fmt.Errorf("Failed to load pull issue. Error: %w", err)
} }
comment, err := issues_model.CreatePushPullComment(ctx, pusher, pr, oldCommitID, opts.NewCommitIDs[i]) comment, err := issues_model.CreatePushPullComment(ctx, pusher, pr, oldCommitID, opts.NewCommitIDs[i])
if err == nil && comment != nil { if err == nil && comment != nil {
notification.NotifyPullRequestPushCommits(pusher, pr, comment) notification.NotifyPullRequestPushCommits(ctx, pusher, pr, comment)
} }
notification.NotifyPullRequestSynchronized(pusher, pr) notification.NotifyPullRequestSynchronized(ctx, pusher, pr)
isForcePush := comment != nil && comment.IsForcePush isForcePush := comment != nil && comment.IsForcePush
results = append(results, private.HookProcReceiveRefResult{ results = append(results, private.HookProcReceiveRefResult{

Some files were not shown because too many files have changed in this diff Show more