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

refactor some functions to support ctx as first parameter (#21878)

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
Co-authored-by: Lauris BH <lauris@nix.lv>
This commit is contained in:
Lunny Xiao 2022-12-03 10:48:26 +08:00 committed by GitHub
parent 8698458f48
commit 0a7d3ff786
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
145 changed files with 360 additions and 369 deletions

View file

@ -665,7 +665,7 @@ func runDeleteUser(c *cli.Context) error {
} else if c.IsSet("username") { } else if c.IsSet("username") {
user, err = user_model.GetUserByName(ctx, c.String("username")) user, err = user_model.GetUserByName(ctx, c.String("username"))
} else { } else {
user, err = user_model.GetUserByID(c.Int64("id")) user, err = user_model.GetUserByID(ctx, c.Int64("id"))
} }
if err != nil { if err != nil {
return err return err

View file

@ -114,12 +114,12 @@ func (a *Action) GetOpType() ActionType {
} }
// LoadActUser loads a.ActUser // LoadActUser loads a.ActUser
func (a *Action) LoadActUser() { func (a *Action) LoadActUser(ctx context.Context) {
if a.ActUser != nil { if a.ActUser != nil {
return return
} }
var err error var err error
a.ActUser, err = user_model.GetUserByID(a.ActUserID) a.ActUser, err = user_model.GetUserByID(ctx, a.ActUserID)
if err == nil { if err == nil {
return return
} else if user_model.IsErrUserNotExist(err) { } else if user_model.IsErrUserNotExist(err) {
@ -129,12 +129,12 @@ func (a *Action) LoadActUser() {
} }
} }
func (a *Action) loadRepo() { func (a *Action) loadRepo(ctx context.Context) {
if a.Repo != nil { if a.Repo != nil {
return return
} }
var err error var err error
a.Repo, err = repo_model.GetRepositoryByID(a.RepoID) a.Repo, err = repo_model.GetRepositoryByID(ctx, a.RepoID)
if err != nil { if err != nil {
log.Error("repo_model.GetRepositoryByID(%d): %v", a.RepoID, err) log.Error("repo_model.GetRepositoryByID(%d): %v", a.RepoID, err)
} }
@ -142,13 +142,13 @@ func (a *Action) loadRepo() {
// GetActFullName gets the action's user full name. // GetActFullName gets the action's user full name.
func (a *Action) GetActFullName() string { func (a *Action) GetActFullName() string {
a.LoadActUser() a.LoadActUser(db.DefaultContext)
return a.ActUser.FullName return a.ActUser.FullName
} }
// GetActUserName gets the action's user name. // GetActUserName gets the action's user name.
func (a *Action) GetActUserName() string { func (a *Action) GetActUserName() string {
a.LoadActUser() a.LoadActUser(db.DefaultContext)
return a.ActUser.Name return a.ActUser.Name
} }
@ -179,7 +179,7 @@ func (a *Action) GetDisplayNameTitle() string {
// GetRepoUserName returns the name of the action repository owner. // GetRepoUserName returns the name of the action repository owner.
func (a *Action) GetRepoUserName() string { func (a *Action) GetRepoUserName() string {
a.loadRepo() a.loadRepo(db.DefaultContext)
return a.Repo.OwnerName return a.Repo.OwnerName
} }
@ -191,7 +191,7 @@ func (a *Action) ShortRepoUserName() string {
// GetRepoName returns the name of the action repository. // GetRepoName returns the name of the action repository.
func (a *Action) GetRepoName() string { func (a *Action) GetRepoName() string {
a.loadRepo() a.loadRepo(db.DefaultContext)
return a.Repo.Name return a.Repo.Name
} }
@ -379,7 +379,7 @@ func activityQueryCondition(opts GetFeedsOptions) (builder.Cond, error) {
cond := builder.NewCond() cond := builder.NewCond()
if opts.RequestedTeam != nil && opts.RequestedUser == nil { if opts.RequestedTeam != nil && opts.RequestedUser == nil {
org, err := user_model.GetUserByID(opts.RequestedTeam.OrgID) org, err := user_model.GetUserByID(db.DefaultContext, opts.RequestedTeam.OrgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -489,7 +489,7 @@ func NotifyWatchers(ctx context.Context, actions ...*Action) error {
} }
if repoChanged { if repoChanged {
act.loadRepo() act.loadRepo(ctx)
repo = act.Repo repo = act.Repo
// check repo owner exist. // check repo owner exist.
@ -514,7 +514,7 @@ func NotifyWatchers(ctx context.Context, actions ...*Action) error {
permIssue = make([]bool, len(watchers)) permIssue = make([]bool, len(watchers))
permPR = make([]bool, len(watchers)) permPR = make([]bool, len(watchers))
for i, watcher := range watchers { for i, watcher := range watchers {
user, err := user_model.GetUserByIDCtx(ctx, watcher.UserID) user, err := user_model.GetUserByID(ctx, watcher.UserID)
if err != nil { if err != nil {
permCode[i] = false permCode[i] = false
permIssue[i] = false permIssue[i] = false

View file

@ -81,7 +81,7 @@ func (actions ActionList) loadRepoOwner(ctx context.Context, userMap map[int64]*
} }
repoOwner, ok := userMap[action.Repo.OwnerID] repoOwner, ok := userMap[action.Repo.OwnerID]
if !ok { if !ok {
repoOwner, err = user_model.GetUserByIDCtx(ctx, action.Repo.OwnerID) repoOwner, err = user_model.GetUserByID(ctx, action.Repo.OwnerID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue

View file

@ -245,7 +245,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
// notify // notify
for userID := range toNotify { for userID := range toNotify {
issue.Repo.Units = nil issue.Repo.Units = nil
user, err := user_model.GetUserByIDCtx(ctx, userID) user, err := user_model.GetUserByID(ctx, userID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue
@ -388,7 +388,7 @@ func (n *Notification) LoadAttributes(ctx context.Context) (err error) {
func (n *Notification) loadRepo(ctx context.Context) (err error) { func (n *Notification) loadRepo(ctx context.Context) (err error) {
if n.Repository == nil { if n.Repository == nil {
n.Repository, err = repo_model.GetRepositoryByIDCtx(ctx, n.RepoID) n.Repository, err = repo_model.GetRepositoryByID(ctx, n.RepoID)
if err != nil { if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %w", n.RepoID, err) return fmt.Errorf("getRepositoryByID [%d]: %w", n.RepoID, err)
} }
@ -425,7 +425,7 @@ func (n *Notification) loadComment(ctx context.Context) (err error) {
func (n *Notification) loadUser(ctx context.Context) (err error) { func (n *Notification) loadUser(ctx context.Context) (err error) {
if n.User == nil { if n.User == nil {
n.User, err = user_model.GetUserByIDCtx(ctx, n.UserID) n.User, err = user_model.GetUserByID(ctx, n.UserID)
if err != nil { if err != nil {
return fmt.Errorf("getUserByID [%d]: %w", n.UserID, err) return fmt.Errorf("getUserByID [%d]: %w", n.UserID, err)
} }

View file

@ -426,7 +426,7 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use
Email: email, Email: email,
} }
if key.OwnerID != 0 { if key.OwnerID != 0 {
owner, err := user_model.GetUserByID(key.OwnerID) owner, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID)
if err == nil { if err == nil {
signer = owner signer = owner
} else if !user_model.IsErrUserNotExist(err) { } else if !user_model.IsErrUserNotExist(err) {

View file

@ -73,10 +73,10 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
} }
if !protectBranch.EnableWhitelist { if !protectBranch.EnableWhitelist {
if user, err := user_model.GetUserByID(userID); err != nil { if user, err := user_model.GetUserByID(db.DefaultContext, userID); err != nil {
log.Error("GetUserByID: %v", err) log.Error("GetUserByID: %v", err)
return false return false
} else if repo, err := repo_model.GetRepositoryByID(protectBranch.RepoID); err != nil { } else if repo, err := repo_model.GetRepositoryByID(db.DefaultContext, protectBranch.RepoID); err != nil {
log.Error("repo_model.GetRepositoryByID: %v", err) log.Error("repo_model.GetRepositoryByID: %v", err)
return false return false
} else if writeAccess, err := access_model.HasAccessUnit(db.DefaultContext, user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil { } else if writeAccess, err := access_model.HasAccessUnit(db.DefaultContext, user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil {
@ -127,13 +127,8 @@ func IsUserMergeWhitelisted(ctx context.Context, protectBranch *ProtectedBranch,
} }
// IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals) // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
func IsUserOfficialReviewer(protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { func IsUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) {
return IsUserOfficialReviewerCtx(db.DefaultContext, protectBranch, user) repo, err := repo_model.GetRepositoryByID(ctx, protectBranch.RepoID)
}
// IsUserOfficialReviewerCtx check if user is official reviewer for the branch (counts towards required approvals)
func IsUserOfficialReviewerCtx(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) {
repo, err := repo_model.GetRepositoryByIDCtx(ctx, protectBranch.RepoID)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -375,7 +370,7 @@ func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, curre
whitelist = make([]int64, 0, len(newWhitelist)) whitelist = make([]int64, 0, len(newWhitelist))
for _, userID := range newWhitelist { for _, userID := range newWhitelist {
user, err := user_model.GetUserByIDCtx(ctx, userID) user, err := user_model.GetUserByID(ctx, userID)
if err != nil { if err != nil {
return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %w", userID, repo.ID, err) return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %w", userID, repo.ID, err)
} }
@ -494,8 +489,8 @@ func RemoveDeletedBranchByID(repoID, id int64) (err error) {
// LoadUser loads the user that deleted the branch // LoadUser loads the user that deleted the branch
// When there's no user found it returns a user_model.NewGhostUser // When there's no user found it returns a user_model.NewGhostUser
func (deletedBranch *DeletedBranch) LoadUser() { func (deletedBranch *DeletedBranch) LoadUser(ctx context.Context) {
user, err := user_model.GetUserByID(deletedBranch.DeletedByID) user, err := user_model.GetUserByID(ctx, deletedBranch.DeletedByID)
if err != nil { if err != nil {
user = user_model.NewGhostUser() user = user_model.NewGhostUser()
} }

View file

@ -48,13 +48,13 @@ func TestDeletedBranchLoadUser(t *testing.T) {
branch := getDeletedBranch(t, firstBranch) branch := getDeletedBranch(t, firstBranch)
assert.Nil(t, branch.DeletedBy) assert.Nil(t, branch.DeletedBy)
branch.LoadUser() branch.LoadUser(db.DefaultContext)
assert.NotNil(t, branch.DeletedBy) assert.NotNil(t, branch.DeletedBy)
assert.Equal(t, "user1", branch.DeletedBy.Name) assert.Equal(t, "user1", branch.DeletedBy.Name)
branch = getDeletedBranch(t, secondBranch) branch = getDeletedBranch(t, secondBranch)
assert.Nil(t, branch.DeletedBy) assert.Nil(t, branch.DeletedBy)
branch.LoadUser() branch.LoadUser(db.DefaultContext)
assert.NotNil(t, branch.DeletedBy) assert.NotNil(t, branch.DeletedBy)
assert.Equal(t, "Ghost", branch.DeletedBy.Name) assert.Equal(t, "Ghost", branch.DeletedBy.Name)
} }

View file

@ -114,13 +114,13 @@ func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (in
func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) { func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
if status.Repo == nil { if status.Repo == nil {
status.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, status.RepoID) status.Repo, err = repo_model.GetRepositoryByID(ctx, status.RepoID)
if err != nil { if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err) return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err)
} }
} }
if status.Creator == nil && status.CreatorID > 0 { if status.Creator == nil && status.CreatorID > 0 {
status.Creator, err = user_model.GetUserByIDCtx(ctx, status.CreatorID) status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID)
if err != nil { if err != nil {
return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err) return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err)
} }

View file

@ -167,7 +167,7 @@ func CheckLFSAccessForRepo(ctx context.Context, ownerID int64, repo *repo_model.
if ownerID == 0 { if ownerID == 0 {
return ErrLFSUnauthorizedAction{repo.ID, "undefined", mode} return ErrLFSUnauthorizedAction{repo.ID, "undefined", mode}
} }
u, err := user_model.GetUserByIDCtx(ctx, ownerID) u, err := user_model.GetUserByID(ctx, ownerID)
if err != nil { if err != nil {
return err return err
} }

View file

@ -118,7 +118,7 @@ func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.Use
// toggles user assignee state in database // toggles user assignee state in database
func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (removed bool, err error) { func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (removed bool, err error) {
// Check if the user exists // Check if the user exists
assignee, err := user_model.GetUserByIDCtx(ctx, assigneeID) assignee, err := user_model.GetUserByID(ctx, assigneeID)
if err != nil { if err != nil {
return false, err return false, err
} }

View file

@ -22,17 +22,17 @@ func TestUpdateAssignee(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
// Assign multiple users // Assign multiple users
user2, err := user_model.GetUserByID(2) user2, err := user_model.GetUserByID(db.DefaultContext, 2)
assert.NoError(t, err) assert.NoError(t, err)
_, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user2.ID) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user2.ID)
assert.NoError(t, err) assert.NoError(t, err)
user3, err := user_model.GetUserByID(3) user3, err := user_model.GetUserByID(db.DefaultContext, 3)
assert.NoError(t, err) assert.NoError(t, err)
_, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user3.ID) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user3.ID)
assert.NoError(t, err) assert.NoError(t, err)
user1, err := user_model.GetUserByID(1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him
assert.NoError(t, err) assert.NoError(t, err)
_, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user1.ID) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user1.ID)
assert.NoError(t, err) assert.NoError(t, err)

View file

@ -350,7 +350,7 @@ func (c *Comment) LoadPoster(ctx context.Context) (err error) {
return nil return nil
} }
c.Poster, err = user_model.GetUserByIDCtx(ctx, c.PosterID) c.Poster, err = user_model.GetUserByID(ctx, c.PosterID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
c.PosterID = -1 c.PosterID = -1
@ -580,7 +580,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error {
var err error var err error
if c.AssigneeID > 0 && c.Assignee == nil { if c.AssigneeID > 0 && c.Assignee == nil {
c.Assignee, err = user_model.GetUserByIDCtx(db.DefaultContext, c.AssigneeID) c.Assignee, err = user_model.GetUserByID(db.DefaultContext, c.AssigneeID)
if err != nil { if err != nil {
if !user_model.IsErrUserNotExist(err) { if !user_model.IsErrUserNotExist(err) {
return err return err
@ -615,7 +615,7 @@ func (c *Comment) LoadResolveDoer() (err error) {
if c.ResolveDoerID == 0 || c.Type != CommentTypeCode { if c.ResolveDoerID == 0 || c.Type != CommentTypeCode {
return nil return nil
} }
c.ResolveDoer, err = user_model.GetUserByIDCtx(db.DefaultContext, c.ResolveDoerID) c.ResolveDoer, err = user_model.GetUserByID(db.DefaultContext, c.ResolveDoerID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
c.ResolveDoer = user_model.NewGhostUser() c.ResolveDoer = user_model.NewGhostUser()

View file

@ -18,7 +18,7 @@ func TestCreateIssueDependency(t *testing.T) {
// Prepare // Prepare
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user1, err := user_model.GetUserByID(1) user1, err := user_model.GetUserByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)

View file

@ -193,7 +193,7 @@ func (issue *Issue) IsOverdue() bool {
// LoadRepo loads issue's repository // LoadRepo loads issue's repository
func (issue *Issue) LoadRepo(ctx context.Context) (err error) { func (issue *Issue) LoadRepo(ctx context.Context) (err error) {
if issue.Repo == nil { if issue.Repo == nil {
issue.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, issue.RepoID) issue.Repo, err = repo_model.GetRepositoryByID(ctx, issue.RepoID)
if err != nil { if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %w", issue.RepoID, err) return fmt.Errorf("getRepositoryByID [%d]: %w", issue.RepoID, err)
} }
@ -242,7 +242,7 @@ func (issue *Issue) LoadLabels(ctx context.Context) (err error) {
// LoadPoster loads poster // LoadPoster loads poster
func (issue *Issue) LoadPoster(ctx context.Context) (err error) { 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.GetUserByID(ctx, issue.PosterID)
if err != nil { if err != nil {
issue.PosterID = -1 issue.PosterID = -1
issue.Poster = user_model.NewGhostUser() issue.Poster = user_model.NewGhostUser()

View file

@ -148,7 +148,7 @@ func (issue *Issue) getCrossReferences(stdCtx context.Context, ctx *crossReferen
refRepo = ctx.OrigIssue.Repo refRepo = ctx.OrigIssue.Repo
} else { } else {
// Issues in other repositories // Issues in other repositories
refRepo, err = repo_model.GetRepositoryByOwnerAndNameCtx(stdCtx, ref.Owner, ref.Name) refRepo, err = repo_model.GetRepositoryByOwnerAndName(stdCtx, ref.Owner, ref.Name)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
continue continue

View file

@ -284,7 +284,7 @@ func DeleteMilestoneByRepoID(repoID, id int64) error {
return err return err
} }
repo, err := repo_model.GetRepositoryByID(m.RepoID) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, m.RepoID)
if err != nil { if err != nil {
return err return err
} }

View file

@ -223,7 +223,7 @@ func (pr *PullRequest) MustHeadUserName(ctx context.Context) string {
// 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.GetUserByID(ctx, pr.MergerID)
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
pr.MergerID = -1 pr.MergerID = -1
pr.Merger = user_model.NewGhostUser() pr.Merger = user_model.NewGhostUser()
@ -248,9 +248,9 @@ func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) {
} }
} }
pr.HeadRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.HeadRepoID) pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID)
if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
return fmt.Errorf("getRepositoryByID(head): %w", err) return fmt.Errorf("GetRepositoryByID(head): %w", err)
} }
pr.isHeadRepoLoaded = true pr.isHeadRepoLoaded = true
} }
@ -273,7 +273,7 @@ func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) {
return nil return nil
} }
pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID) pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID)
if err != nil { if err != nil {
return fmt.Errorf("repo_model.GetRepositoryByID(base): %w", err) return fmt.Errorf("repo_model.GetRepositoryByID(base): %w", err)
} }
@ -294,18 +294,13 @@ func (pr *PullRequest) LoadIssue(ctx context.Context) (err error) {
} }
// LoadProtectedBranch loads the protected branch of the base branch // LoadProtectedBranch loads the protected branch of the base branch
func (pr *PullRequest) LoadProtectedBranch() (err error) { func (pr *PullRequest) LoadProtectedBranch(ctx context.Context) (err error) {
return pr.LoadProtectedBranchCtx(db.DefaultContext)
}
// LoadProtectedBranchCtx loads the protected branch of the base branch
func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (err error) {
if pr.ProtectedBranch == nil { if pr.ProtectedBranch == nil {
if pr.BaseRepo == nil { if pr.BaseRepo == nil {
if pr.BaseRepoID == 0 { if pr.BaseRepoID == 0 {
return nil return nil
} }
pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID) pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID)
if err != nil { if err != nil {
return return
} }

View file

@ -75,7 +75,7 @@ func (r *Reaction) LoadUser() (*user_model.User, error) {
if r.User != nil { if r.User != nil {
return r.User, nil return r.User, nil
} }
user, err := user_model.GetUserByIDCtx(db.DefaultContext, r.UserID) user, err := user_model.GetUserByID(db.DefaultContext, r.UserID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -158,7 +158,7 @@ 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
} }
r.Reviewer, err = user_model.GetUserByIDCtx(ctx, r.ReviewerID) r.Reviewer, err = user_model.GetUserByID(ctx, r.ReviewerID)
return err return err
} }
@ -263,7 +263,7 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo
if err != nil { if err != nil {
return false, err return false, err
} }
if err = pr.LoadProtectedBranchCtx(ctx); err != nil { if err = pr.LoadProtectedBranch(ctx); err != nil {
return false, err return false, err
} }
if pr.ProtectedBranch == nil { if pr.ProtectedBranch == nil {
@ -271,7 +271,7 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo
} }
for _, reviewer := range reviewers { for _, reviewer := range reviewers {
official, err := git_model.IsUserOfficialReviewerCtx(ctx, pr.ProtectedBranch, reviewer) official, err := git_model.IsUserOfficialReviewer(ctx, pr.ProtectedBranch, reviewer)
if official || err != nil { if official || err != nil {
return official, err return official, err
} }
@ -286,7 +286,7 @@ func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio
if err != nil { if err != nil {
return false, err return false, err
} }
if err = pr.LoadProtectedBranchCtx(ctx); err != nil { if err = pr.LoadProtectedBranch(ctx); err != nil {
return false, err return false, err
} }
if pr.ProtectedBranch == nil { if pr.ProtectedBranch == nil {

View file

@ -18,7 +18,7 @@ import (
func TestCancelStopwatch(t *testing.T) { func TestCancelStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user1, err := user_model.GetUserByID(1) user1, err := user_model.GetUserByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
@ -58,9 +58,9 @@ func TestHasUserStopwatch(t *testing.T) {
func TestCreateOrStopIssueStopwatch(t *testing.T) { func TestCreateOrStopIssueStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user2, err := user_model.GetUserByID(2) user2, err := user_model.GetUserByID(db.DefaultContext, 2)
assert.NoError(t, err) assert.NoError(t, err)
user3, err := user_model.GetUserByID(3) user3, err := user_model.GetUserByID(db.DefaultContext, 3)
assert.NoError(t, err) assert.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)

View file

@ -57,7 +57,7 @@ func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
} }
} }
if t.User == nil { if t.User == nil {
t.User, err = user_model.GetUserByIDCtx(ctx, t.UserID) t.User, err = user_model.GetUserByID(ctx, t.UserID)
if err != nil { if err != nil {
return return
} }
@ -205,7 +205,7 @@ func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string,
totalTimes := make(map[*user_model.User]string) totalTimes := make(map[*user_model.User]string)
// Fetching User and making time human readable // Fetching User and making time human readable
for userID, total := range totalTimesByUser { for userID, total := range totalTimesByUser {
user, err := user_model.GetUserByID(userID) user, err := user_model.GetUserByID(db.DefaultContext, userID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue

View file

@ -18,7 +18,7 @@ import (
func TestAddTime(t *testing.T) { func TestAddTime(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user3, err := user_model.GetUserByID(3) user3, err := user_model.GetUserByID(db.DefaultContext, 3)
assert.NoError(t, err) assert.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)

View file

@ -43,7 +43,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error {
return err return err
} }
if t.NumMembers == 1 { if t.NumMembers == 1 {
if err := t.GetMembersCtx(ctx); err != nil { if err := t.LoadMembers(ctx); err != nil {
return err return err
} }
if t.Members[0].ID == userID { if t.Members[0].ID == userID {

View file

@ -41,7 +41,7 @@ func AddRepository(ctx context.Context, t *organization.Team, repo *repo_model.R
// Make all team members watch this repo if enabled in global settings // Make all team members watch this repo if enabled in global settings
if setting.Service.AutoWatchNewRepos { if setting.Service.AutoWatchNewRepos {
if err = t.GetMembersCtx(ctx); err != nil { if err = t.LoadMembers(ctx); err != nil {
return fmt.Errorf("getMembers: %w", err) return fmt.Errorf("getMembers: %w", err)
} }
for _, u := range t.Members { for _, u := range t.Members {
@ -213,7 +213,7 @@ func RemoveRepository(t *organization.Team, repoID int64) error {
return nil return nil
} }
repo, err := repo_model.GetRepositoryByID(repoID) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, repoID)
if err != nil { if err != nil {
return err return err
} }
@ -349,8 +349,8 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err
// Update access for team members if needed. // Update access for team members if needed.
if authChanged { if authChanged {
if err = t.GetRepositoriesCtx(ctx); err != nil { if err = t.LoadRepositories(ctx); err != nil {
return fmt.Errorf("getRepositories: %w", err) return fmt.Errorf("LoadRepositories: %w", err)
} }
for _, repo := range t.Repos { for _, repo := range t.Repos {
@ -381,11 +381,11 @@ func DeleteTeam(t *organization.Team) error {
defer committer.Close() defer committer.Close()
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
if err := t.GetRepositoriesCtx(ctx); err != nil { if err := t.LoadRepositories(ctx); err != nil {
return err return err
} }
if err := t.GetMembersCtx(ctx); err != nil { if err := t.LoadMembers(ctx); err != nil {
return err return err
} }
@ -516,10 +516,16 @@ func AddTeamMember(team *organization.Team, userID int64) error {
} }
} }
// watch could be failed, so run it in a goroutine if err := committer.Commit(); err != nil {
return err
}
committer.Close()
// this behaviour may spend much time so run it in a goroutine
// FIXME: Update watch repos batchly
if setting.Service.AutoWatchNewRepos { if setting.Service.AutoWatchNewRepos {
// Get team and its repositories. // Get team and its repositories.
if err := team.GetRepositoriesCtx(db.DefaultContext); err != nil { if err := team.LoadRepositories(db.DefaultContext); err != nil {
log.Error("getRepositories failed: %v", err) log.Error("getRepositories failed: %v", err)
} }
go func(repos []*repo_model.Repository) { go func(repos []*repo_model.Repository) {
@ -531,7 +537,7 @@ func AddTeamMember(team *organization.Team, userID int64) error {
}(team.Repos) }(team.Repos)
} }
return committer.Commit() return nil
} }
func removeTeamMember(ctx context.Context, team *organization.Team, userID int64) error { func removeTeamMember(ctx context.Context, team *organization.Team, userID int64) error {
@ -548,7 +554,7 @@ func removeTeamMember(ctx context.Context, team *organization.Team, userID int64
team.NumMembers-- team.NumMembers--
if err := team.GetRepositoriesCtx(ctx); err != nil { if err := team.LoadRepositories(ctx); err != nil {
return err return err
} }

View file

@ -701,7 +701,7 @@ func AccessibleReposEnv(ctx context.Context, org *Organization, userID int64) (A
var user *user_model.User var user *user_model.User
if userID > 0 { if userID > 0 {
u, err := user_model.GetUserByIDCtx(ctx, userID) u, err := user_model.GetUserByID(ctx, userID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -37,7 +37,7 @@ func TestUserIsPublicMember(t *testing.T) {
} }
func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(uid) user, err := user_model.GetUserByID(db.DefaultContext, uid)
assert.NoError(t, err) assert.NoError(t, err)
is, err := organization.IsPublicMembership(orgID, user.ID) is, err := organization.IsPublicMembership(orgID, user.ID)
assert.NoError(t, err) assert.NoError(t, err)
@ -65,7 +65,7 @@ func TestIsUserOrgOwner(t *testing.T) {
} }
func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(uid) user, err := user_model.GetUserByID(db.DefaultContext, uid)
assert.NoError(t, err) assert.NoError(t, err)
is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID) is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID)
assert.NoError(t, err) assert.NoError(t, err)

View file

@ -222,8 +222,8 @@ func (t *Team) IsMember(userID int64) bool {
return isMember return isMember
} }
// GetRepositoriesCtx returns paginated repositories in team of organization. // LoadRepositories returns paginated repositories in team of organization.
func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) { func (t *Team) LoadRepositories(ctx context.Context) (err error) {
if t.Repos != nil { if t.Repos != nil {
return nil return nil
} }
@ -233,8 +233,8 @@ func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) {
return err return err
} }
// GetMembersCtx returns paginated members in team of organization. // LoadMembers returns paginated members in team of organization.
func (t *Team) GetMembersCtx(ctx context.Context) (err error) { func (t *Team) LoadMembers(ctx context.Context) (err error) {
t.Members, err = GetTeamMembers(ctx, &SearchMembersOptions{ t.Members, err = GetTeamMembers(ctx, &SearchMembersOptions{
TeamID: t.ID, TeamID: t.ID,
}) })
@ -248,7 +248,7 @@ func (t *Team) UnitEnabled(tp unit.Type) bool {
// UnitAccessMode returns if the team has the given unit type enabled // UnitAccessMode returns if the team has the given unit type enabled
// it is called in templates, should not be replaced by `UnitAccessModeCtx(ctx ...)` // it is called in templates, should not be replaced by `UnitAccessModeCtx(ctx ...)`
func (t *Team) UnitAccessMode(tp unit.Type) perm.AccessMode { func (t *Team) UnitAccessMode(tp unit.Type) perm.AccessMode { // Notice: It will be used in template, don't remove it directly
return t.UnitAccessModeCtx(db.DefaultContext, tp) return t.UnitAccessModeCtx(db.DefaultContext, tp)
} }

View file

@ -42,7 +42,7 @@ func TestTeam_GetRepositories(t *testing.T) {
test := func(teamID int64) { test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext)) assert.NoError(t, team.LoadRepositories(db.DefaultContext))
assert.Len(t, team.Repos, team.NumRepos) assert.Len(t, team.Repos, team.NumRepos)
for _, repo := range team.Repos { for _, repo := range team.Repos {
unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID}) unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID})
@ -57,7 +57,7 @@ func TestTeam_GetMembers(t *testing.T) {
test := func(teamID int64) { test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
assert.NoError(t, team.GetMembersCtx(db.DefaultContext)) assert.NoError(t, team.LoadMembers(db.DefaultContext))
assert.Len(t, team.Members, team.NumMembers) assert.Len(t, team.Members, team.NumMembers)
for _, member := range team.Members { for _, member := range team.Members {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID})

View file

@ -85,15 +85,15 @@ func GetPackageDescriptor(ctx context.Context, pv *PackageVersion) (*PackageDesc
if err != nil { if err != nil {
return nil, err return nil, err
} }
o, err := user_model.GetUserByIDCtx(ctx, p.OwnerID) o, err := user_model.GetUserByID(ctx, p.OwnerID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
repository, err := repo_model.GetRepositoryByIDCtx(ctx, p.RepoID) repository, err := repo_model.GetRepositoryByID(ctx, p.RepoID)
if err != nil && !repo_model.IsErrRepoNotExist(err) { if err != nil && !repo_model.IsErrRepoNotExist(err) {
return nil, err return nil, err
} }
creator, err := user_model.GetUserByIDCtx(ctx, pv.CreatorID) creator, err := user_model.GetUserByID(ctx, pv.CreatorID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -171,7 +171,7 @@ func RecalculateTeamAccesses(ctx context.Context, repo *repo_model.Repository, i
continue continue
} }
if err = t.GetMembersCtx(ctx); err != nil { if err = t.LoadMembers(ctx); err != nil {
return fmt.Errorf("getMembers '%d': %w", t.ID, err) return fmt.Errorf("getMembers '%d': %w", t.ID, err)
} }
for _, m := range t.Members { for _, m := range t.Members {

View file

@ -364,7 +364,7 @@ func HasAccess(ctx context.Context, userID int64, repo *repo_model.Repository) (
var user *user_model.User var user *user_model.User
var err error var err error
if userID > 0 { if userID > 0 {
user, err = user_model.GetUserByIDCtx(ctx, userID) user, err = user_model.GetUserByID(ctx, userID)
if err != nil { if err != nil {
return false, err return false, err
} }

View file

@ -338,7 +338,7 @@ func DeleteProjectByIDCtx(ctx context.Context, id int64) error {
return updateRepositoryProjectCount(ctx, p.RepoID) return updateRepositoryProjectCount(ctx, p.RepoID)
} }
func DeleteProjectByRepoIDCtx(ctx context.Context, repoID int64) error { func DeleteProjectByRepoID(ctx context.Context, repoID int64) error {
switch { switch {
case setting.Database.UseSQLite3: case setting.Database.UseSQLite3:
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil { if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil {

View file

@ -74,7 +74,7 @@ func GetScheduledMergeByPullID(ctx context.Context, pullID int64) (bool, *AutoMe
return false, nil, err return false, nil, err
} }
doer, err := user_model.GetUserByIDCtx(ctx, scheduledPRM.DoerID) doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID)
if err != nil { if err != nil {
return false, nil, err return false, nil, err
} }

View file

@ -52,7 +52,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
sess := db.GetEngine(ctx) sess := db.GetEngine(ctx)
// In case is a organization. // In case is a organization.
org, err := user_model.GetUserByIDCtx(ctx, uid) org, err := user_model.GetUserByID(ctx, uid)
if err != nil { if err != nil {
return err return err
} }
@ -191,7 +191,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
} }
} }
if err := project_model.DeleteProjectByRepoIDCtx(ctx, repoID); err != nil { if err := project_model.DeleteProjectByRepoID(ctx, repoID); err != nil {
return fmt.Errorf("unable to delete projects for repo[%d]: %w", repoID, err) return fmt.Errorf("unable to delete projects for repo[%d]: %w", repoID, err)
} }
@ -523,7 +523,7 @@ func CheckRepoStats(ctx context.Context) error {
} }
log.Trace("Updating repository count 'num_forks': %d", id) log.Trace("Updating repository count 'num_forks': %d", id)
repo, err := repo_model.GetRepositoryByID(id) repo, err := repo_model.GetRepositoryByID(ctx, id)
if err != nil { if err != nil {
log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err) log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err)
continue continue
@ -618,7 +618,7 @@ func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error
// Check if user has access to delete this key. // Check if user has access to delete this key.
if !doer.IsAdmin { if !doer.IsAdmin {
repo, err := repo_model.GetRepositoryByIDCtx(ctx, key.RepoID) repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID)
if err != nil { if err != nil {
return fmt.Errorf("GetRepositoryByID: %w", err) return fmt.Errorf("GetRepositoryByID: %w", err)
} }

View file

@ -44,7 +44,7 @@ func GetCollaborators(ctx context.Context, repoID int64, listOptions db.ListOpti
collaborators := make([]*Collaborator, 0, len(collaborations)) collaborators := make([]*Collaborator, 0, len(collaborations))
for _, c := range collaborations { for _, c := range collaborations {
user, err := user_model.GetUserByIDCtx(ctx, c.UserID) user, err := user_model.GetUserByID(ctx, c.UserID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repoID) log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repoID)

View file

@ -17,14 +17,14 @@ func TestGetUserFork(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// User13 has repo 11 forked from repo10 // User13 has repo 11 forked from repo10
repo, err := repo_model.GetRepositoryByID(10) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10)
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, repo) assert.NotNil(t, repo)
repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13)
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, repo) assert.NotNil(t, repo)
repo, err = repo_model.GetRepositoryByID(9) repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9)
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, repo) assert.NotNil(t, repo)
repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13)

View file

@ -26,7 +26,7 @@ func (repo *Repository) CanEnableTimetracker() bool {
} }
// IsTimetrackerEnabled returns whether or not the timetracker is enabled. It returns the default value from config if an error occurs. // IsTimetrackerEnabled returns whether or not the timetracker is enabled. It returns the default value from config if an error occurs.
func (repo *Repository) IsTimetrackerEnabled() bool { func (repo *Repository) IsTimetrackerEnabled() bool { // Notice: It will be used in template so don't remove directly
return repo.IsTimetrackerEnabledCtx(db.DefaultContext) return repo.IsTimetrackerEnabledCtx(db.DefaultContext)
} }

View file

@ -52,7 +52,7 @@ func (m *Mirror) GetRepository() *Repository {
return m.Repo return m.Repo
} }
var err error var err error
m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID) m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID)
if err != nil { if err != nil {
log.Error("getRepositoryByID[%d]: %v", m.ID, err) log.Error("getRepositoryByID[%d]: %v", m.ID, err)
} }

View file

@ -61,7 +61,7 @@ func (m *PushMirror) GetRepository() *Repository {
return m.Repo return m.Repo
} }
var err error var err error
m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID) m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID)
if err != nil { if err != nil {
log.Error("getRepositoryByID[%d]: %v", m.ID, err) log.Error("getRepositoryByID[%d]: %v", m.ID, err)
} }

View file

@ -93,13 +93,13 @@ func init() {
func (r *Release) LoadAttributes(ctx context.Context) error { 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 = GetRepositoryByID(ctx, r.RepoID)
if err != nil { if err != nil {
return err return err
} }
} }
if r.Publisher == nil { if r.Publisher == nil {
r.Publisher, err = user_model.GetUserByIDCtx(ctx, r.PublisherID) r.Publisher, err = user_model.GetUserByID(ctx, r.PublisherID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
r.Publisher = user_model.NewGhostUser() r.Publisher = user_model.NewGhostUser()

View file

@ -315,7 +315,7 @@ func (repo *Repository) LoadUnits(ctx context.Context) (err error) {
} }
// UnitEnabled if this repository has the given unit enabled // UnitEnabled if this repository has the given unit enabled
func (repo *Repository) UnitEnabled(tp unit.Type) (result bool) { func (repo *Repository) UnitEnabled(tp unit.Type) (result bool) { // Notice: Don't remove this function directly, because it has been used in go template.
return repo.UnitEnabledCtx(db.DefaultContext, tp) return repo.UnitEnabledCtx(db.DefaultContext, tp)
} }
@ -390,7 +390,7 @@ func (repo *Repository) GetOwner(ctx context.Context) (err error) {
return nil return nil
} }
repo.Owner, err = user_model.GetUserByIDCtx(ctx, repo.OwnerID) repo.Owner, err = user_model.GetUserByID(ctx, repo.OwnerID)
return err return err
} }
@ -467,16 +467,12 @@ func (repo *Repository) ComposeDocumentMetas() map[string]string {
// GetBaseRepo populates repo.BaseRepo for a fork repository and // GetBaseRepo populates repo.BaseRepo for a fork repository and
// returns an error on failure (NOTE: no error is returned for // returns an error on failure (NOTE: no error is returned for
// non-fork repositories, and BaseRepo will be left untouched) // non-fork repositories, and BaseRepo will be left untouched)
func (repo *Repository) GetBaseRepo() (err error) { func (repo *Repository) GetBaseRepo(ctx context.Context) (err error) {
return repo.getBaseRepo(db.DefaultContext)
}
func (repo *Repository) getBaseRepo(ctx context.Context) (err error) {
if !repo.IsFork { if !repo.IsFork {
return nil return nil
} }
repo.BaseRepo, err = GetRepositoryByIDCtx(ctx, repo.ForkID) repo.BaseRepo, err = GetRepositoryByID(ctx, repo.ForkID)
return err return err
} }
@ -611,11 +607,6 @@ func (repo *Repository) GetTrustModel() TrustModelType {
return trustModel return trustModel
} }
// GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
return GetRepositoryByOwnerAndNameCtx(db.DefaultContext, ownerName, repoName)
}
// __________ .__ __ // __________ .__ __
// \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. // \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__.
// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | // | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | |
@ -647,8 +638,8 @@ func (err ErrRepoNotExist) Unwrap() error {
return util.ErrNotExist return util.ErrNotExist
} }
// GetRepositoryByOwnerAndNameCtx returns the repository by given owner name and repo name // GetRepositoryByOwnerAndName returns the repository by given owner name and repo name
func GetRepositoryByOwnerAndNameCtx(ctx context.Context, ownerName, repoName string) (*Repository, error) { func GetRepositoryByOwnerAndName(ctx context.Context, ownerName, repoName string) (*Repository, error) {
var repo Repository var repo Repository
has, err := db.GetEngine(ctx).Table("repository").Select("repository.*"). has, err := db.GetEngine(ctx).Table("repository").Select("repository.*").
Join("INNER", "`user`", "`user`.id = repository.owner_id"). Join("INNER", "`user`", "`user`.id = repository.owner_id").
@ -678,8 +669,8 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
return repo, err return repo, err
} }
// GetRepositoryByIDCtx returns the repository by given id if exists. // GetRepositoryByID returns the repository by given id if exists.
func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { func GetRepositoryByID(ctx context.Context, id int64) (*Repository, error) {
repo := new(Repository) repo := new(Repository)
has, err := db.GetEngine(ctx).ID(id).Get(repo) has, err := db.GetEngine(ctx).ID(id).Get(repo)
if err != nil { if err != nil {
@ -690,11 +681,6 @@ func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) {
return repo, nil return repo, nil
} }
// GetRepositoryByID returns the repository by given id if exists.
func GetRepositoryByID(id int64) (*Repository, error) {
return GetRepositoryByIDCtx(db.DefaultContext, id)
}
// GetRepositoriesMapByIDs returns the repositories by given id slice. // GetRepositoriesMapByIDs returns the repositories by given id slice.
func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
repos := make(map[int64]*Repository, len(ids)) repos := make(map[int64]*Repository, len(ids))
@ -722,7 +708,7 @@ func GetTemplateRepo(ctx context.Context, repo *Repository) (*Repository, error)
return nil, nil return nil, nil
} }
return GetRepositoryByIDCtx(ctx, repo.TemplateID) return GetRepositoryByID(ctx, repo.TemplateID)
} }
// TemplateRepo returns the repository, which is template of this repository // TemplateRepo returns the repository, which is template of this repository

View file

@ -115,7 +115,7 @@ func TestMetas(t *testing.T) {
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp
testSuccess(markup.IssueNameStyleRegexp) testSuccess(markup.IssueNameStyleRegexp)
repo, err := repo_model.GetRepositoryByID(3) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3)
assert.NoError(t, err) assert.NoError(t, err)
metas = repo.ComposeMetas() metas = repo.ComposeMetas()

View file

@ -53,7 +53,7 @@ func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) {
} }
func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error { func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error {
user, err := user_model.GetUserByIDCtx(ctx, uid) user, err := user_model.GetUserByID(ctx, uid)
if err != nil { if err != nil {
return err return err
} }

View file

@ -41,7 +41,7 @@ func init() {
// LoadAttributes fetches the transfer recipient from the database // LoadAttributes fetches the transfer recipient from the database
func (r *RepoTransfer) LoadAttributes() error { func (r *RepoTransfer) LoadAttributes() error {
if r.Recipient == nil { if r.Recipient == nil {
u, err := user_model.GetUserByID(r.RecipientID) u, err := user_model.GetUserByID(db.DefaultContext, r.RecipientID)
if err != nil { if err != nil {
return err return err
} }
@ -65,7 +65,7 @@ func (r *RepoTransfer) LoadAttributes() error {
} }
if r.Doer == nil { if r.Doer == nil {
u, err := user_model.GetUserByID(r.DoerID) u, err := user_model.GetUserByID(db.DefaultContext, r.DoerID)
if err != nil { if err != nil {
return err return err
} }
@ -161,7 +161,7 @@ func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int
} }
defer committer.Close() defer committer.Close()
repo, err := repo_model.GetRepositoryByIDCtx(ctx, repoID) repo, err := repo_model.GetRepositoryByID(ctx, repoID)
if err != nil { if err != nil {
return err return err
} }

View file

@ -332,7 +332,7 @@ func ActivateEmail(email *EmailAddress) error {
} }
func updateActivation(ctx context.Context, email *EmailAddress, activate bool) error { func updateActivation(ctx context.Context, email *EmailAddress, activate bool) error {
user, err := GetUserByIDCtx(ctx, email.UID) user, err := GetUserByID(ctx, email.UID)
if err != nil { if err != nil {
return err return err
} }

View file

@ -162,7 +162,7 @@ func TestMakeEmailPrimary(t *testing.T) {
err = user_model.MakeEmailPrimary(email) err = user_model.MakeEmailPrimary(email)
assert.NoError(t, err) assert.NoError(t, err)
user, _ := user_model.GetUserByID(int64(10)) user, _ := user_model.GetUserByID(db.DefaultContext, int64(10))
assert.Equal(t, "user101@example.com", user.Email) assert.Equal(t, "user101@example.com", user.Email)
} }

View file

@ -993,12 +993,7 @@ func UserPath(userName string) string { //revive:disable-line:exported
} }
// GetUserByID returns the user object by given ID if exists. // GetUserByID returns the user object by given ID if exists.
func GetUserByID(id int64) (*User, error) { func GetUserByID(ctx context.Context, id int64) (*User, error) {
return GetUserByIDCtx(db.DefaultContext, id)
}
// GetUserByIDCtx returns the user object by given ID if exists.
func GetUserByIDCtx(ctx context.Context, id int64) (*User, error) {
u := new(User) u := new(User)
has, err := db.GetEngine(ctx).ID(id).Get(u) has, err := db.GetEngine(ctx).ID(id).Get(u)
if err != nil { if err != nil {
@ -1176,7 +1171,7 @@ func GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
return nil, err return nil, err
} }
if has { if has {
return GetUserByIDCtx(ctx, emailAddress.UID) return GetUserByID(ctx, emailAddress.UID)
} }
// Finally, if email address is the protected email address: // Finally, if email address is the protected email address:
@ -1220,7 +1215,7 @@ func GetUserByOpenID(uri string) (*User, error) {
return nil, err return nil, err
} }
if has { if has {
return GetUserByID(oid.UID) return GetUserByID(db.DefaultContext, oid.UID)
} }
return nil, ErrUserNotExist{0, uri, 0} return nil, ErrUserNotExist{0, uri, 0}

View file

@ -22,7 +22,7 @@ import (
func TestOAuth2Application_LoadUser(t *testing.T) { func TestOAuth2Application_LoadUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1}) app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1})
user, err := user_model.GetUserByID(app.UID) user, err := user_model.GetUserByID(db.DefaultContext, app.UID)
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, user) assert.NotNil(t, user)
} }

View file

@ -139,7 +139,7 @@ func (ctx *Context) IsUserRepoReaderAny() bool {
// RedirectToUser redirect to a differently-named user // RedirectToUser redirect to a differently-named user
func RedirectToUser(ctx *Context, userName string, redirectUserID int64) { func RedirectToUser(ctx *Context, userName string, redirectUserID int64) {
user, err := user_model.GetUserByID(redirectUserID) user, err := user_model.GetUserByID(ctx, redirectUserID)
if err != nil { if err != nil {
ctx.ServerError("GetUserByID", err) ctx.ServerError("GetUserByID", err)
return return

View file

@ -264,7 +264,7 @@ func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (*editorconfig.Ed
// RetrieveBaseRepo retrieves base repository // RetrieveBaseRepo retrieves base repository
func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository) { func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository) {
// Non-fork repository will not return error in this method. // Non-fork repository will not return error in this method.
if err := repo.GetBaseRepo(); err != nil { if err := repo.GetBaseRepo(ctx); err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
repo.IsFork = false repo.IsFork = false
repo.ForkID = 0 repo.ForkID = 0
@ -335,7 +335,7 @@ func RedirectToRepo(ctx *Context, redirectRepoID int64) {
ownerName := ctx.Params(":username") ownerName := ctx.Params(":username")
previousRepoName := ctx.Params(":reponame") previousRepoName := ctx.Params(":reponame")
repo, err := repo_model.GetRepositoryByID(redirectRepoID) repo, err := repo_model.GetRepositoryByID(ctx, redirectRepoID)
if err != nil { if err != nil {
ctx.ServerError("GetRepositoryByID", err) ctx.ServerError("GetRepositoryByID", err)
return return
@ -410,7 +410,7 @@ func RepoIDAssignment() func(ctx *Context) {
repoID := ctx.ParamsInt64(":repoid") repoID := ctx.ParamsInt64(":repoid")
// Get repository. // Get repository.
repo, err := repo_model.GetRepositoryByID(repoID) repo, err := repo_model.GetRepositoryByID(ctx, repoID)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
ctx.NotFound("GetRepositoryByID", nil) ctx.NotFound("GetRepositoryByID", nil)

View file

@ -5,6 +5,7 @@
package convert package convert
import ( import (
"context"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -408,8 +409,8 @@ func ToOAuth2Application(app *auth.OAuth2Application) *api.OAuth2Application {
} }
// ToLFSLock convert a LFSLock to api.LFSLock // ToLFSLock convert a LFSLock to api.LFSLock
func ToLFSLock(l *git_model.LFSLock) *api.LFSLock { func ToLFSLock(ctx context.Context, l *git_model.LFSLock) *api.LFSLock {
u, err := user_model.GetUserByID(l.OwnerID) u, err := user_model.GetUserByID(ctx, l.OwnerID)
if err != nil { if err != nil {
return nil return nil
} }

View file

@ -149,7 +149,7 @@ func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) {
} }
repo, ok = repoCache[issue.RepoID] repo, ok = repoCache[issue.RepoID]
if !ok { if !ok {
repo, err = repo_model.GetRepositoryByID(issue.RepoID) repo, err = repo_model.GetRepositoryByID(db.DefaultContext, issue.RepoID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -138,15 +138,15 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_
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.GetUserByIDCtx(ctx, c.Label.OrgID) org, err = user_model.GetUserByID(ctx, c.Label.OrgID)
if err != nil { if err != nil {
log.Error("GetUserByIDCtx(%d): %v", c.Label.OrgID, err) log.Error("GetUserByID(%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.GetRepositoryByIDCtx(ctx, c.Label.RepoID) repo, err = repo_model.GetRepositoryByID(ctx, c.Label.RepoID)
if err != nil { if err != nil {
log.Error("GetRepositoryByIDCtx(%d): %v", c.Label.RepoID, err) log.Error("GetRepositoryByIDCtx(%d): %v", c.Label.RepoID, err)
return nil return nil

View file

@ -7,6 +7,7 @@ import (
"net/url" "net/url"
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/perm" "code.gitea.io/gitea/models/perm"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
) )
@ -23,7 +24,7 @@ func ToNotificationThread(n *activities_model.Notification) *api.NotificationThr
// since user only get notifications when he has access to use minimal access mode // since user only get notifications when he has access to use minimal access mode
if n.Repository != nil { if n.Repository != nil {
result.Repository = ToRepo(n.Repository, perm.AccessModeRead) result.Repository = ToRepo(db.DefaultContext, n.Repository, perm.AccessModeRead)
// This permission is not correct and we should not be reporting it // This permission is not correct and we should not be reporting it
for repository := result.Repository; repository != nil; repository = repository.Parent { for repository := result.Repository; repository != nil; repository = repository.Parent {

View file

@ -22,7 +22,7 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m
} }
if permission.HasAccess() { if permission.HasAccess() {
repo = ToRepo(pd.Repository, permission.AccessMode) repo = ToRepo(ctx, pd.Repository, permission.AccessMode)
} }
} }

View file

@ -79,7 +79,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
Name: pr.BaseBranch, Name: pr.BaseBranch,
Ref: pr.BaseBranch, Ref: pr.BaseBranch,
RepoID: pr.BaseRepoID, RepoID: pr.BaseRepoID,
Repository: ToRepo(pr.BaseRepo, p.AccessMode), Repository: ToRepo(ctx, pr.BaseRepo, p.AccessMode),
}, },
Head: &api.PRBranchInfo{ Head: &api.PRBranchInfo{
Name: pr.HeadBranch, Name: pr.HeadBranch,
@ -139,7 +139,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
} }
apiPullRequest.Head.RepoID = pr.HeadRepo.ID apiPullRequest.Head.RepoID = pr.HeadRepo.ID
apiPullRequest.Head.Repository = ToRepo(pr.HeadRepo, p.AccessMode) apiPullRequest.Head.Repository = ToRepo(ctx, pr.HeadRepo, p.AccessMode)
headGitRepo, err := git.OpenRepository(ctx, pr.HeadRepo.RepoPath()) headGitRepo, err := git.OpenRepository(ctx, pr.HeadRepo.RepoPath())
if err != nil { if err != nil {

View file

@ -31,7 +31,7 @@ func TestPullRequest_APIFormat(t *testing.T) {
Ref: "refs/pull/2/head", Ref: "refs/pull/2/head",
Sha: "4a357436d925b5c974181ff12a994538ddc5a269", Sha: "4a357436d925b5c974181ff12a994538ddc5a269",
RepoID: 1, RepoID: 1,
Repository: ToRepo(headRepo, perm.AccessModeRead), Repository: ToRepo(db.DefaultContext, headRepo, perm.AccessModeRead),
}, apiPullRequest.Head) }, apiPullRequest.Head)
// withOut HeadRepo // withOut HeadRepo

View file

@ -4,6 +4,7 @@
package convert package convert
import ( import (
"context"
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -16,11 +17,11 @@ import (
) )
// ToRepo converts a Repository to api.Repository // ToRepo converts a Repository to api.Repository
func ToRepo(repo *repo_model.Repository, mode perm.AccessMode) *api.Repository { func ToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode) *api.Repository {
return innerToRepo(repo, mode, false) return innerToRepo(ctx, repo, mode, false)
} }
func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository { func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository {
var parent *api.Repository var parent *api.Repository
cloneLink := repo.CloneLink() cloneLink := repo.CloneLink()
@ -30,12 +31,12 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo
Pull: mode >= perm.AccessModeRead, Pull: mode >= perm.AccessModeRead,
} }
if !isParent { if !isParent {
err := repo.GetBaseRepo() err := repo.GetBaseRepo(ctx)
if err != nil { if err != nil {
return nil return nil
} }
if repo.BaseRepo != nil { if repo.BaseRepo != nil {
parent = innerToRepo(repo.BaseRepo, mode, true) parent = innerToRepo(ctx, repo.BaseRepo, mode, true)
} }
} }

View file

@ -4,13 +4,15 @@
package convert package convert
import ( import (
"context"
git_model "code.gitea.io/gitea/models/git" git_model "code.gitea.io/gitea/models/git"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
) )
// ToCommitStatus converts git_model.CommitStatus to api.CommitStatus // ToCommitStatus converts git_model.CommitStatus to api.CommitStatus
func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { func ToCommitStatus(ctx context.Context, status *git_model.CommitStatus) *api.CommitStatus {
apiStatus := &api.CommitStatus{ apiStatus := &api.CommitStatus{
Created: status.CreatedUnix.AsTime(), Created: status.CreatedUnix.AsTime(),
Updated: status.CreatedUnix.AsTime(), Updated: status.CreatedUnix.AsTime(),
@ -23,7 +25,7 @@ func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus {
} }
if status.CreatorID != 0 { if status.CreatorID != 0 {
creator, _ := user_model.GetUserByID(status.CreatorID) creator, _ := user_model.GetUserByID(ctx, status.CreatorID)
apiStatus.Creator = ToUser(creator, nil) apiStatus.Creator = ToUser(creator, nil)
} }
@ -31,7 +33,7 @@ func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus {
} }
// ToCombinedStatus converts List of CommitStatus to a CombinedStatus // ToCombinedStatus converts List of CommitStatus to a CombinedStatus
func ToCombinedStatus(statuses []*git_model.CommitStatus, repo *api.Repository) *api.CombinedStatus { func ToCombinedStatus(ctx context.Context, statuses []*git_model.CommitStatus, repo *api.Repository) *api.CombinedStatus {
if len(statuses) == 0 { if len(statuses) == 0 {
return nil return nil
} }
@ -45,7 +47,7 @@ func ToCombinedStatus(statuses []*git_model.CommitStatus, repo *api.Repository)
retStatus.Statuses = make([]*api.CommitStatus, 0, len(statuses)) retStatus.Statuses = make([]*api.CommitStatus, 0, len(statuses))
for _, status := range statuses { for _, status := range statuses {
retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(status)) retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(ctx, status))
if status.State.NoBetterThan(retStatus.State) { if status.State.NoBetterThan(retStatus.State) {
retStatus.State = status.State retStatus.State = status.State
} }

View file

@ -84,7 +84,7 @@ type IndexerData struct {
var indexerQueue queue.UniqueQueue var indexerQueue queue.UniqueQueue
func index(ctx context.Context, indexer Indexer, repoID int64) error { func index(ctx context.Context, indexer Indexer, repoID int64) error {
repo, err := repo_model.GetRepositoryByID(repoID) repo, err := repo_model.GetRepositoryByID(ctx, repoID)
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
return indexer.Delete(repoID) return indexer.Delete(repoID)
} }

View file

@ -21,7 +21,7 @@ func (db *DBIndexer) Index(id int64) error {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("Stats.DB Index Repo[%d]", id)) ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("Stats.DB Index Repo[%d]", id))
defer finished() defer finished()
repo, err := repo_model.GetRepositoryByID(id) repo, err := repo_model.GetRepositoryByID(ctx, id)
if err != nil { if err != nil {
return err return err
} }

View file

@ -36,7 +36,7 @@ func TestRepoStatsIndex(t *testing.T) {
err := Init() err := Init()
assert.NoError(t, err) assert.NoError(t, err)
repo, err := repo_model.GetRepositoryByID(1) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
err = UpdateRepoIndexer(repo) err = UpdateRepoIndexer(repo)

View file

@ -58,7 +58,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user
Action: api.HookIssueLabelCleared, Action: api.HookIssueLabelCleared,
Index: issue.Index, Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} else { } else {
@ -66,7 +66,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user
Action: api.HookIssueLabelCleared, Action: api.HookIssueLabelCleared,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} }
@ -81,8 +81,8 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m
// forked webhook // forked webhook
if err := webhook_services.PrepareWebhooks(ctx, 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(ctx, oldRepo, oldMode),
Repo: convert.ToRepo(repo, mode), Repo: convert.ToRepo(ctx, repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err) log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err)
@ -94,7 +94,7 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m
if u.IsOrganization() { if u.IsOrganization() {
if err := webhook_services.PrepareWebhooks(ctx, 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(ctx, repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(u, nil),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
@ -107,7 +107,7 @@ func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u
// 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(ctx, 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(ctx, repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(u, nil),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
@ -118,7 +118,7 @@ func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u
func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) {
if err := webhook_services.PrepareWebhooks(ctx, 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.HookRepoDeleted, Action: api.HookRepoDeleted,
Repository: convert.ToRepo(repo, perm.AccessModeOwner), Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner),
Organization: convert.ToUser(repo.MustOwner(ctx), nil), Organization: convert.ToUser(repo.MustOwner(ctx), nil),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
@ -130,7 +130,7 @@ func (m *webhookNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *
// 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(ctx, 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(ctx, repo, perm.AccessModeOwner),
Organization: convert.ToUser(u, nil), Organization: convert.ToUser(u, nil),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
@ -150,7 +150,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u
apiPullRequest := &api.PullRequestPayload{ apiPullRequest := &api.PullRequestPayload{
Index: issue.Index, Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
} }
if removed { if removed {
@ -168,7 +168,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u
apiIssue := &api.IssuePayload{ apiIssue := &api.IssuePayload{
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
} }
if removed { if removed {
@ -202,7 +202,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user
}, },
}, },
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} else { } else {
@ -215,7 +215,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user
}, },
}, },
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} }
@ -237,7 +237,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use
apiPullRequest := &api.PullRequestPayload{ apiPullRequest := &api.PullRequestPayload{
Index: issue.Index, Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
} }
if isClosed { if isClosed {
@ -250,7 +250,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use
apiIssue := &api.IssuePayload{ apiIssue := &api.IssuePayload{
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
} }
if isClosed { if isClosed {
@ -280,7 +280,7 @@ func (m *webhookNotifier) NotifyNewIssue(ctx context.Context, issue *issues_mode
Action: api.HookIssueOpened, Action: api.HookIssueOpened,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(issue.Poster, nil), Sender: convert.ToUser(issue.Poster, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks: %v", err) log.Error("PrepareWebhooks: %v", err)
@ -306,7 +306,7 @@ func (m *webhookNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues
Action: api.HookIssueOpened, Action: api.HookIssueOpened,
Index: pull.Issue.Index, Index: pull.Issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, pull, nil), PullRequest: convert.ToAPIPullRequest(ctx, pull, nil),
Repository: convert.ToRepo(pull.Issue.Repo, mode), Repository: convert.ToRepo(ctx, pull.Issue.Repo, mode),
Sender: convert.ToUser(pull.Issue.Poster, nil), Sender: convert.ToUser(pull.Issue.Poster, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks: %v", err) log.Error("PrepareWebhooks: %v", err)
@ -327,7 +327,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us
}, },
}, },
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} else { } else {
@ -340,7 +340,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us
}, },
}, },
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} }
@ -381,7 +381,7 @@ func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_mo
From: oldContent, From: oldContent,
}, },
}, },
Repository: convert.ToRepo(c.Issue.Repo, mode), Repository: convert.ToRepo(ctx, c.Issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
IsPull: c.Issue.IsPull, IsPull: c.Issue.IsPull,
}); err != nil { }); err != nil {
@ -404,7 +404,7 @@ func (m *webhookNotifier) NotifyCreateIssueComment(ctx context.Context, doer *us
Action: api.HookIssueCommentCreated, Action: api.HookIssueCommentCreated,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Comment: convert.ToComment(comment), Comment: convert.ToComment(comment),
Repository: convert.ToRepo(repo, mode), Repository: convert.ToRepo(ctx, repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
IsPull: issue.IsPull, IsPull: issue.IsPull,
}); err != nil { }); err != nil {
@ -441,7 +441,7 @@ func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_mo
Action: api.HookIssueCommentDeleted, Action: api.HookIssueCommentDeleted,
Issue: convert.ToAPIIssue(ctx, 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(ctx, comment.Issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
IsPull: comment.Issue.IsPull, IsPull: comment.Issue.IsPull,
}); err != nil { }); err != nil {
@ -453,7 +453,7 @@ func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_mode
// Add to hook queue for created wiki page. // Add to hook queue for created wiki page.
if err := webhook_services.PrepareWebhooks(ctx, 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(ctx, repo, perm.AccessModeOwner),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
Page: page, Page: page,
Comment: comment, Comment: comment,
@ -466,7 +466,7 @@ func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_mod
// Add to hook queue for edit wiki page. // Add to hook queue for edit wiki page.
if err := webhook_services.PrepareWebhooks(ctx, 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(ctx, repo, perm.AccessModeOwner),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
Page: page, Page: page,
Comment: comment, Comment: comment,
@ -479,7 +479,7 @@ func (m *webhookNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_m
// Add to hook queue for edit wiki page. // Add to hook queue for edit wiki page.
if err := webhook_services.PrepareWebhooks(ctx, 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(ctx, repo, perm.AccessModeOwner),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
Page: page, Page: page,
}); err != nil { }); err != nil {
@ -516,7 +516,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use
Action: api.HookIssueLabelUpdated, Action: api.HookIssueLabelUpdated,
Index: issue.Index, Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, perm.AccessModeNone), Repository: convert.ToRepo(ctx, issue.Repo, perm.AccessModeNone),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} else { } else {
@ -524,7 +524,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use
Action: api.HookIssueLabelUpdated, Action: api.HookIssueLabelUpdated,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} }
@ -558,7 +558,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer *
Action: hookAction, Action: hookAction,
Index: issue.Index, Index: issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} else { } else {
@ -566,7 +566,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer *
Action: hookAction, Action: hookAction,
Index: issue.Index, Index: issue.Index,
Issue: convert.ToAPIIssue(ctx, issue), Issue: convert.ToAPIIssue(ctx, issue),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}) })
} }
@ -591,7 +591,7 @@ func (m *webhookNotifier) NotifyPushCommits(ctx context.Context, pusher *user_mo
Commits: apiCommits, Commits: apiCommits,
TotalCommits: commits.Len, TotalCommits: commits.Len,
HeadCommit: apiHeadCommit, HeadCommit: apiHeadCommit,
Repo: convert.ToRepo(repo, perm.AccessModeOwner), Repo: convert.ToRepo(ctx, repo, perm.AccessModeOwner),
Pusher: apiPusher, Pusher: apiPusher,
Sender: apiPusher, Sender: apiPusher,
}); err != nil { }); err != nil {
@ -631,7 +631,7 @@ func (*webhookNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_m
apiPullRequest := &api.PullRequestPayload{ apiPullRequest := &api.PullRequestPayload{
Index: pr.Issue.Index, Index: pr.Issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(pr.Issue.Repo, mode), Repository: convert.ToRepo(ctx, pr.Issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
Action: api.HookIssueClosed, Action: api.HookIssueClosed,
} }
@ -659,7 +659,7 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Contex
}, },
}, },
PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(issue.Repo, mode), Repository: convert.ToRepo(ctx, issue.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks [pr: %d]: %v", pr.ID, err) log.Error("PrepareWebhooks [pr: %d]: %v", pr.ID, err)
@ -696,7 +696,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue
Action: api.HookIssueReviewed, Action: api.HookIssueReviewed,
Index: review.Issue.Index, Index: review.Issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(review.Issue.Repo, mode), Repository: convert.ToRepo(ctx, review.Issue.Repo, mode),
Sender: convert.ToUser(review.Reviewer, nil), Sender: convert.ToUser(review.Reviewer, nil),
Review: &api.ReviewPayload{ Review: &api.ReviewPayload{
Type: string(reviewHookType), Type: string(reviewHookType),
@ -709,7 +709,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue
func (m *webhookNotifier) NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { 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(ctx, repo, perm.AccessModeNone)
refName := git.RefEndName(refFullName) refName := git.RefEndName(refFullName)
if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{
@ -737,7 +737,7 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe
Action: api.HookIssueSynchronized, Action: api.HookIssueSynchronized,
Index: pr.Issue.Index, Index: pr.Issue.Index,
PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), PullRequest: convert.ToAPIPullRequest(ctx, pr, nil),
Repository: convert.ToRepo(pr.Issue.Repo, perm.AccessModeNone), Repository: convert.ToRepo(ctx, pr.Issue.Repo, perm.AccessModeNone),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err) log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
@ -746,7 +746,7 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe
func (m *webhookNotifier) NotifyDeleteRef(ctx context.Context, 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(ctx, repo, perm.AccessModeNone)
refName := git.RefEndName(refFullName) refName := git.RefEndName(refFullName)
if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{ if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{
@ -770,7 +770,7 @@ func sendReleaseHook(ctx context.Context, doer *user_model.User, rel *repo_model
if err := webhook_services.PrepareWebhooks(ctx, 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(ctx, rel.Repo, mode),
Sender: convert.ToUser(doer, nil), Sender: convert.ToUser(doer, nil),
}); err != nil { }); err != nil {
log.Error("PrepareWebhooks: %v", err) log.Error("PrepareWebhooks: %v", err)
@ -805,7 +805,7 @@ func (m *webhookNotifier) NotifySyncPushCommits(ctx context.Context, pusher *use
Commits: apiCommits, Commits: apiCommits,
TotalCommits: commits.Len, TotalCommits: commits.Len,
HeadCommit: apiHeadCommit, HeadCommit: apiHeadCommit,
Repo: convert.ToRepo(repo, perm.AccessModeOwner), Repo: convert.ToRepo(ctx, repo, perm.AccessModeOwner),
Pusher: apiPusher, Pusher: apiPusher,
Sender: apiPusher, Sender: apiPusher,
}); err != nil { }); err != nil {

View file

@ -25,7 +25,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) {
testTeamRepositories := func(teamID int64, repoIds []int64) { testTeamRepositories := func(teamID int64, repoIds []int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext), "%s: GetRepositories", team.Name) assert.NoError(t, team.LoadRepositories(db.DefaultContext), "%s: GetRepositories", team.Name)
assert.Len(t, team.Repos, team.NumRepos, "%s: len repo", team.Name) assert.Len(t, team.Repos, team.NumRepos, "%s: len repo", team.Name)
assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name)
for i, rid := range repoIds { for i, rid := range repoIds {
@ -36,7 +36,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) {
} }
// Get an admin user. // Get an admin user.
user, err := user_model.GetUserByID(1) user, err := user_model.GetUserByID(db.DefaultContext, 1)
assert.NoError(t, err, "GetUserByID") assert.NoError(t, err, "GetUserByID")
// Create org. // Create org.
@ -153,7 +153,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// Get sample repo and change visibility // Get sample repo and change visibility
repo, err := repo_model.GetRepositoryByID(9) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 9)
assert.NoError(t, err) assert.NoError(t, err)
repo.IsPrivate = true repo.IsPrivate = true

View file

@ -243,7 +243,7 @@ func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *r
} }
// re-fetch repo // re-fetch repo
if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil {
return fmt.Errorf("getRepositoryByID: %w", err) return fmt.Errorf("getRepositoryByID: %w", err)
} }

View file

@ -414,7 +414,7 @@ func initRepository(ctx context.Context, repoPath string, u *user_model.User, re
// Re-fetch the repository from database before updating it (else it would // Re-fetch the repository from database before updating it (else it would
// override changes that were done earlier with sql) // override changes that were done earlier with sql)
if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil {
return fmt.Errorf("getRepositoryByID: %w", err) return fmt.Errorf("getRepositoryByID: %w", err)
} }

View file

@ -25,6 +25,7 @@ import (
activities_model "code.gitea.io/gitea/models/activities" activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/avatars" "code.gitea.io/gitea/models/avatars"
"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/organization" "code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -631,7 +632,7 @@ func Avatar(item interface{}, others ...interface{}) template.HTML {
// AvatarByAction renders user avatars from action. args: action, size (int), class (string) // AvatarByAction renders user avatars from action. args: action, size (int), class (string)
func AvatarByAction(action *activities_model.Action, others ...interface{}) template.HTML { func AvatarByAction(action *activities_model.Action, others ...interface{}) template.HTML {
action.LoadActUser() action.LoadActUser(db.DefaultContext)
return Avatar(action.ActUser, others...) return Avatar(action.ActUser, others...)
} }

View file

@ -57,7 +57,7 @@ func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) {
ctx.Repo = &context.Repository{} ctx.Repo = &context.Repository{}
ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
var err error var err error
ctx.Repo.Owner, err = user_model.GetUserByID(ctx.Repo.Repository.OwnerID) ctx.Repo.Owner, err = user_model.GetUserByID(ctx, ctx.Repo.Repository.OwnerID)
assert.NoError(t, err) assert.NoError(t, err)
ctx.Repo.RepoLink = ctx.Repo.Repository.Link() ctx.Repo.RepoLink = ctx.Repo.Repository.Link()
ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, ctx.Doer) ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, ctx.Doer)

View file

@ -30,7 +30,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS
return nil return nil
} }
u, err := user_model.GetUserByID(uid) u, err := user_model.GetUserByID(req.Context(), uid)
if err != nil { if err != nil {
log.Error("GetUserByID: %v", err) log.Error("GetUserByID: %v", err)
return nil return nil

View file

@ -34,7 +34,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS
return user_model.NewGhostUser() return user_model.NewGhostUser()
} }
u, err := user_model.GetUserByID(uid) u, err := user_model.GetUserByID(req.Context(), uid)
if err != nil { if err != nil {
log.Error("GetUserByID: %v", err) log.Error("GetUserByID: %v", err)
return nil return nil

View file

@ -29,7 +29,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS
return nil return nil
} }
u, err := user_model.GetUserByID(token.UID) u, err := user_model.GetUserByID(req.Context(), token.UID)
if err != nil { if err != nil {
log.Error("GetUserByID: %v", err) log.Error("GetUserByID: %v", err)
return nil return nil

View file

@ -546,7 +546,7 @@ func GetTeamRepos(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
return return
} }
repos[i] = convert.ToRepo(repo, access) repos[i] = convert.ToRepo(ctx, repo, access)
} }
ctx.SetTotalCountHeader(int64(team.NumRepos)) ctx.SetTotalCountHeader(int64(team.NumRepos))
ctx.JSON(http.StatusOK, repos) ctx.JSON(http.StatusOK, repos)
@ -598,7 +598,7 @@ func GetTeamRepo(ctx *context.APIContext) {
return return
} }
ctx.JSON(http.StatusOK, convert.ToRepo(repo, access)) ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, access))
} }
// getRepositoryByParams get repository by a team's organization ID and repo name // getRepositoryByParams get repository by a team's organization ID and repo name

View file

@ -63,7 +63,7 @@ func ListForks(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return return
} }
apiForks[i] = convert.ToRepo(fork, access) apiForks[i] = convert.ToRepo(ctx, fork, access)
} }
ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumForks)) ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumForks))
@ -150,5 +150,5 @@ func CreateFork(ctx *context.APIContext) {
} }
// TODO change back to 201 // TODO change back to 201
ctx.JSON(http.StatusAccepted, convert.ToRepo(fork, perm.AccessModeOwner)) ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, fork, perm.AccessModeOwner))
} }

View file

@ -184,7 +184,7 @@ func TestHook(ctx *context.APIContext) {
Commits: []*api.PayloadCommit{commit}, Commits: []*api.PayloadCommit{commit},
TotalCommits: 1, TotalCommits: 1,
HeadCommit: commit, HeadCommit: commit,
Repo: convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone), Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone),
Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone),
Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone),
}); err != nil { }); err != nil {

View file

@ -623,7 +623,7 @@ func CreateIssue(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.GetUserByID(ctx, aID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserByID", err) ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
return return

View file

@ -199,7 +199,7 @@ func isXRefCommentAccessible(ctx stdCtx.Context, user *user_model.User, c *issue
if issues_model.CommentTypeIsRef(c.Type) && c.RefRepoID != issueRepoID && c.RefRepoID != 0 { if issues_model.CommentTypeIsRef(c.Type) && c.RefRepoID != issueRepoID && c.RefRepoID != 0 {
var err error var err error
// Set RefRepo for description in template // Set RefRepo for description in template
c.RefRepo, err = repo_model.GetRepositoryByIDCtx(ctx, c.RefRepoID) c.RefRepo, err = repo_model.GetRepositoryByID(ctx, c.RefRepoID)
if err != nil { if err != nil {
return false return false
} }

View file

@ -5,6 +5,7 @@
package repo package repo
import ( import (
stdCtx "context"
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -23,16 +24,16 @@ import (
) )
// appendPrivateInformation appends the owner and key type information to api.PublicKey // appendPrivateInformation appends the owner and key type information to api.PublicKey
func appendPrivateInformation(apiKey *api.DeployKey, key *asymkey_model.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) { func appendPrivateInformation(ctx stdCtx.Context, apiKey *api.DeployKey, key *asymkey_model.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) {
apiKey.ReadOnly = key.Mode == perm.AccessModeRead apiKey.ReadOnly = key.Mode == perm.AccessModeRead
if repository.ID == key.RepoID { if repository.ID == key.RepoID {
apiKey.Repository = convert.ToRepo(repository, key.Mode) apiKey.Repository = convert.ToRepo(ctx, repository, key.Mode)
} else { } else {
repo, err := repo_model.GetRepositoryByID(key.RepoID) repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID)
if err != nil { if err != nil {
return apiKey, err return apiKey, err
} }
apiKey.Repository = convert.ToRepo(repo, key.Mode) apiKey.Repository = convert.ToRepo(ctx, repo, key.Mode)
} }
return apiKey, nil return apiKey, nil
} }
@ -107,7 +108,7 @@ func ListDeployKeys(ctx *context.APIContext) {
} }
apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) apiKeys[i] = convert.ToDeployKey(apiLink, keys[i])
if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) { if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], ctx.Repo.Repository) apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], ctx.Repo.Repository)
} }
} }
@ -161,7 +162,7 @@ func GetDeployKey(ctx *context.APIContext) {
apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
apiKey := convert.ToDeployKey(apiLink, key) apiKey := convert.ToDeployKey(apiLink, key)
if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) { if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Repo.Repository) apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Repo.Repository)
} }
ctx.JSON(http.StatusOK, apiKey) ctx.JSON(http.StatusOK, apiKey)
} }

View file

@ -66,7 +66,7 @@ func Migrate(ctx *context.APIContext) {
if len(form.RepoOwner) != 0 { if len(form.RepoOwner) != 0 {
repoOwner, err = user_model.GetUserByName(ctx, form.RepoOwner) repoOwner, err = user_model.GetUserByName(ctx, form.RepoOwner)
} else if form.RepoOwnerID != 0 { } else if form.RepoOwnerID != 0 {
repoOwner, err = user_model.GetUserByID(form.RepoOwnerID) repoOwner, err = user_model.GetUserByID(ctx, form.RepoOwnerID)
} else { } else {
repoOwner = ctx.Doer repoOwner = ctx.Doer
} }
@ -211,7 +211,7 @@ func Migrate(ctx *context.APIContext) {
} }
log.Trace("Repository migrated: %s/%s", repoOwner.Name, form.RepoName) log.Trace("Repository migrated: %s/%s", repoOwner.Name, form.RepoName)
ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeAdmin)) ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeAdmin))
} }
func handleMigrateError(ctx *context.APIContext, repoOwner *user_model.User, remoteAddr string, err error) { func handleMigrateError(ctx *context.APIContext, repoOwner *user_model.User, remoteAddr string, err error) {

View file

@ -399,7 +399,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.GetUserByIDCtx(ctx, aID) assignee, err := user_model.GetUserByID(ctx, aID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserByID", err) ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
return return

View file

@ -215,7 +215,7 @@ func Search(ctx *context.APIContext) {
Error: err.Error(), Error: err.Error(),
}) })
} }
results[i] = convert.ToRepo(repo, accessMode) results[i] = convert.ToRepo(ctx, repo, accessMode)
} }
ctx.SetLinkHeader(int(count), opts.PageSize) ctx.SetLinkHeader(int(count), opts.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
@ -257,12 +257,12 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre
} }
// reload repo from db to get a real state after creation // reload repo from db to get a real state after creation
repo, err = repo_model.GetRepositoryByID(repo.ID) repo, err = repo_model.GetRepositoryByID(ctx, repo.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err) ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err)
} }
ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeOwner)) ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeOwner))
} }
// Create one repository of mine // Create one repository of mine
@ -407,7 +407,7 @@ func Generate(ctx *context.APIContext) {
} }
log.Trace("Repository generated [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) log.Trace("Repository generated [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeOwner)) ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeOwner))
} }
// CreateOrgRepoDeprecated create one repository of the organization // CreateOrgRepoDeprecated create one repository of the organization
@ -523,7 +523,7 @@ func Get(ctx *context.APIContext) {
return return
} }
ctx.JSON(http.StatusOK, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) ctx.JSON(http.StatusOK, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode))
} }
// GetByID returns a single Repository // GetByID returns a single Repository
@ -544,7 +544,7 @@ func GetByID(ctx *context.APIContext) {
// "200": // "200":
// "$ref": "#/responses/Repository" // "$ref": "#/responses/Repository"
repo, err := repo_model.GetRepositoryByID(ctx.ParamsInt64(":id")) repo, err := repo_model.GetRepositoryByID(ctx, ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -562,7 +562,7 @@ func GetByID(ctx *context.APIContext) {
ctx.NotFound() ctx.NotFound()
return return
} }
ctx.JSON(http.StatusOK, convert.ToRepo(repo, perm.AccessMode)) ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, perm.AccessMode))
} }
// Edit edit repository properties // Edit edit repository properties
@ -618,13 +618,13 @@ func Edit(ctx *context.APIContext) {
} }
} }
repo, err := repo_model.GetRepositoryByID(ctx.Repo.Repository.ID) repo, err := repo_model.GetRepositoryByID(ctx, ctx.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
ctx.JSON(http.StatusOK, convert.ToRepo(repo, ctx.Repo.AccessMode)) ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, ctx.Repo.AccessMode))
} }
// updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility // updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility
@ -669,7 +669,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
if opts.Private != nil { if opts.Private != nil {
// Visibility of forked repository is forced sync with base repository. // Visibility of forked repository is forced sync with base repository.
if repo.IsFork { if repo.IsFork {
if err := repo.GetBaseRepo(); err != nil { if err := repo.GetBaseRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "Unable to load base repository", err) ctx.Error(http.StatusInternalServerError, "Unable to load base repository", err)
return err return err
} }

View file

@ -66,7 +66,7 @@ func NewCommitStatus(ctx *context.APIContext) {
return return
} }
ctx.JSON(http.StatusCreated, convert.ToCommitStatus(status)) ctx.JSON(http.StatusCreated, convert.ToCommitStatus(ctx, status))
} }
// GetCommitStatuses returns all statuses for any given commit hash // GetCommitStatuses returns all statuses for any given commit hash
@ -199,7 +199,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) {
apiStatuses := make([]*api.CommitStatus, 0, len(statuses)) apiStatuses := make([]*api.CommitStatus, 0, len(statuses))
for _, status := range statuses { for _, status := range statuses {
apiStatuses = append(apiStatuses, convert.ToCommitStatus(status)) apiStatuses = append(apiStatuses, convert.ToCommitStatus(ctx, status))
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
@ -263,7 +263,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
return return
} }
combiStatus := convert.ToCombinedStatus(statuses, convert.ToRepo(repo, ctx.Repo.AccessMode)) combiStatus := convert.ToCombinedStatus(ctx, statuses, convert.ToRepo(ctx, repo, ctx.Repo.AccessMode))
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, combiStatus) ctx.JSON(http.StatusOK, combiStatus)

View file

@ -122,12 +122,12 @@ func Transfer(ctx *context.APIContext) {
if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer { if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer {
log.Trace("Repository transfer initiated: %s -> %s", oldFullname, ctx.Repo.Repository.FullName()) log.Trace("Repository transfer initiated: %s -> %s", oldFullname, ctx.Repo.Repository.FullName())
ctx.JSON(http.StatusCreated, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeAdmin))
return return
} }
log.Trace("Repository transferred: %s -> %s", oldFullname, ctx.Repo.Repository.FullName()) log.Trace("Repository transferred: %s -> %s", oldFullname, ctx.Repo.Repository.FullName())
ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeAdmin))
} }
// AcceptTransfer accept a repo transfer // AcceptTransfer accept a repo transfer
@ -165,7 +165,7 @@ func AcceptTransfer(ctx *context.APIContext) {
return return
} }
ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode))
} }
// RejectTransfer reject a repo transfer // RejectTransfer reject a repo transfer
@ -203,7 +203,7 @@ func RejectTransfer(ctx *context.APIContext) {
return return
} }
ctx.JSON(http.StatusOK, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) ctx.JSON(http.StatusOK, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode))
} }
func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error {

View file

@ -7,6 +7,7 @@ import (
"net/http" "net/http"
asymkey_model "code.gitea.io/gitea/models/asymkey" asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
@ -29,7 +30,7 @@ func appendPrivateInformation(apiKey *api.PublicKey, key *asymkey_model.PublicKe
if defaultUser.ID == key.OwnerID { if defaultUser.ID == key.OwnerID {
apiKey.Owner = convert.ToUser(defaultUser, defaultUser) apiKey.Owner = convert.ToUser(defaultUser, defaultUser)
} else { } else {
user, err := user_model.GetUserByID(key.OwnerID) user, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID)
if err != nil { if err != nil {
return apiKey, err return apiKey, err
} }

View file

@ -44,7 +44,7 @@ func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) {
return return
} }
if ctx.IsSigned && ctx.Doer.IsAdmin || access >= perm.AccessModeRead { if ctx.IsSigned && ctx.Doer.IsAdmin || access >= perm.AccessModeRead {
apiRepos = append(apiRepos, convert.ToRepo(repos[i], access)) apiRepos = append(apiRepos, convert.ToRepo(ctx, repos[i], access))
} }
} }
@ -127,7 +127,7 @@ func ListMyRepos(ctx *context.APIContext) {
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err) ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
} }
results[i] = convert.ToRepo(repo, accessMode) results[i] = convert.ToRepo(ctx, repo, accessMode)
} }
ctx.SetLinkHeader(int(count), opts.ListOptions.PageSize) ctx.SetLinkHeader(int(count), opts.ListOptions.PageSize)

View file

@ -32,7 +32,7 @@ func getStarredRepos(ctx std_context.Context, user *user_model.User, private boo
if err != nil { if err != nil {
return nil, err return nil, err
} }
repos[i] = convert.ToRepo(starred, access) repos[i] = convert.ToRepo(ctx, starred, access)
} }
return repos, nil return repos, nil
} }

View file

@ -30,7 +30,7 @@ func getWatchedRepos(ctx std_context.Context, user *user_model.User, private boo
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
repos[i] = convert.ToRepo(watched, access) repos[i] = convert.ToRepo(ctx, watched, access)
} }
return repos, total, nil return repos, total, nil
} }

View file

@ -183,7 +183,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
baseRepo = repo baseRepo = repo
if repo.IsFork { if repo.IsFork {
if err := repo.GetBaseRepo(); err != nil { if err := repo.GetBaseRepo(ctx); err != nil {
log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err) log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{ ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err), Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),

View file

@ -464,7 +464,7 @@ func (ctx *preReceiveContext) loadPusherAndPermission() bool {
return true return true
} }
user, err := user_model.GetUserByID(ctx.opts.UserID) user, err := user_model.GetUserByID(ctx, ctx.opts.UserID)
if err != nil { if err != nil {
log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err) log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err)
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{

View file

@ -68,7 +68,7 @@ func RepoAssignment(ctx *gitea_context.PrivateContext) context.CancelFunc {
} }
func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *repo_model.Repository { func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *repo_model.Repository {
repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, ownerName, repoName)
if err != nil { if err != nil {
log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err) log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ ctx.JSON(http.StatusInternalServerError, map[string]interface{}{

View file

@ -51,7 +51,7 @@ func ServNoCommand(ctx *context.PrivateContext) {
results.Key = key results.Key = key
if key.Type == asymkey_model.KeyTypeUser || key.Type == asymkey_model.KeyTypePrincipal { if key.Type == asymkey_model.KeyTypeUser || key.Type == asymkey_model.KeyTypePrincipal {
user, err := user_model.GetUserByID(key.OwnerID) user, err := user_model.GetUserByID(ctx, key.OwnerID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.JSON(http.StatusUnauthorized, private.Response{ ctx.JSON(http.StatusUnauthorized, private.Response{
@ -259,7 +259,7 @@ func ServCommand(ctx *context.PrivateContext) {
} else { } else {
// Get the user represented by the Key // Get the user represented by the Key
var err error var err error
user, err = user_model.GetUserByID(key.OwnerID) user, err = user_model.GetUserByID(ctx, key.OwnerID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.JSON(http.StatusUnauthorized, private.ErrServCommand{ ctx.JSON(http.StatusUnauthorized, private.ErrServCommand{

View file

@ -41,7 +41,7 @@ func Repos(ctx *context.Context) {
// DeleteRepo delete one repository // DeleteRepo delete one repository
func DeleteRepo(ctx *context.Context) { func DeleteRepo(ctx *context.Context) {
repo, err := repo_model.GetRepositoryByID(ctx.FormInt64("id")) repo, err := repo_model.GetRepositoryByID(ctx, ctx.FormInt64("id"))
if err != nil { if err != nil {
ctx.ServerError("GetRepositoryByID", err) ctx.ServerError("GetRepositoryByID", err)
return return

View file

@ -206,7 +206,7 @@ func NewUserPost(ctx *context.Context) {
} }
func prepareUserInfo(ctx *context.Context) *user_model.User { func prepareUserInfo(ctx *context.Context) *user_model.User {
u, err := user_model.GetUserByID(ctx.ParamsInt64(":userid")) u, err := user_model.GetUserByID(ctx, ctx.ParamsInt64(":userid"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Redirect(setting.AppSubURL + "/admin/users") ctx.Redirect(setting.AppSubURL + "/admin/users")
@ -413,7 +413,7 @@ func EditUserPost(ctx *context.Context) {
// DeleteUser response for deleting a user // DeleteUser response for deleting a user
func DeleteUser(ctx *context.Context) { func DeleteUser(ctx *context.Context) {
u, err := user_model.GetUserByID(ctx.ParamsInt64(":userid")) u, err := user_model.GetUserByID(ctx, ctx.ParamsInt64(":userid"))
if err != nil { if err != nil {
ctx.ServerError("GetUserByID", err) ctx.ServerError("GetUserByID", err)
return return

View file

@ -68,7 +68,7 @@ func TwoFactorPost(ctx *context.Context) {
if ok && twofa.LastUsedPasscode != form.Passcode { if ok && twofa.LastUsedPasscode != form.Passcode {
remember := ctx.Session.Get("twofaRemember").(bool) remember := ctx.Session.Get("twofaRemember").(bool)
u, err := user_model.GetUserByID(id) u, err := user_model.GetUserByID(ctx, id)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
@ -146,7 +146,7 @@ func TwoFactorScratchPost(ctx *context.Context) {
} }
remember := ctx.Session.Get("twofaRemember").(bool) remember := ctx.Session.Get("twofaRemember").(bool)
u, err := user_model.GetUserByID(id) u, err := user_model.GetUserByID(ctx, id)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return

View file

@ -747,7 +747,7 @@ func ActivateEmail(ctx *context.Context) {
log.Trace("Email activated: %s", email.Email) log.Trace("Email activated: %s", email.Email)
ctx.Flash.Success(ctx.Tr("settings.add_email_success")) ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
if u, err := user_model.GetUserByID(email.UID); err != nil { if u, err := user_model.GetUserByID(ctx, email.UID); err != nil {
log.Warn("GetUserByID: %d", email.UID) log.Warn("GetUserByID: %d", email.UID)
} else if setting.CacheService.Enabled { } else if setting.CacheService.Enabled {
// Allow user to validate more emails // Allow user to validate more emails

View file

@ -194,7 +194,7 @@ func newAccessTokenResponse(ctx stdContext.Context, grant *auth.OAuth2Grant, ser
ErrorDescription: "cannot find application", ErrorDescription: "cannot find application",
} }
} }
user, err := user_model.GetUserByID(grant.UserID) user, err := user_model.GetUserByID(ctx, grant.UserID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
return nil, &AccessTokenError{ return nil, &AccessTokenError{
@ -385,7 +385,7 @@ func AuthorizeOAuth(ctx *context.Context) {
var user *user_model.User var user *user_model.User
if app.UID != 0 { if app.UID != 0 {
user, err = user_model.GetUserByID(app.UID) user, err = user_model.GetUserByID(ctx, app.UID)
if err != nil { if err != nil {
ctx.ServerError("GetUserByID", err) ctx.ServerError("GetUserByID", err)
return return
@ -1222,7 +1222,7 @@ func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, res
return nil, goth.User{}, err return nil, goth.User{}, err
} }
if hasUser { if hasUser {
user, err = user_model.GetUserByID(externalLoginUser.UserID) user, err = user_model.GetUserByID(request.Context(), externalLoginUser.UserID)
return user, gothUser, err return user, gothUser, err
} }

View file

@ -49,7 +49,7 @@ func WebAuthnLoginAssertion(ctx *context.Context) {
return return
} }
user, err := user_model.GetUserByID(idSess) user, err := user_model.GetUserByID(ctx, idSess)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
@ -91,7 +91,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) {
}() }()
// Load the user from the db // Load the user from the db
user, err := user_model.GetUserByID(idSess) user, err := user_model.GetUserByID(ctx, idSess)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return

View file

@ -68,7 +68,7 @@ func renderMarkdown(ctx *context.Context, act *activities_model.Action, content
// feedActionsToFeedItems convert gitea's Action feed to feeds Item // feedActionsToFeedItems convert gitea's Action feed to feeds Item
func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) { func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) {
for _, act := range actions { for _, act := range actions {
act.LoadActUser() act.LoadActUser(ctx)
var content, desc, title string var content, desc, title string

View file

@ -52,7 +52,7 @@ func goGet(ctx *context.Context) {
} }
branchName := setting.Repository.DefaultBranch branchName := setting.Repository.DefaultBranch
repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, ownerName, repoName)
if err == nil && len(repo.DefaultBranch) > 0 { if err == nil && len(repo.DefaultBranch) > 0 {
branchName = repo.DefaultBranch branchName = repo.DefaultBranch
} }

View file

@ -49,7 +49,7 @@ func Teams(ctx *context.Context) {
ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeams"] = true
for _, t := range ctx.Org.Teams { for _, t := range ctx.Org.Teams {
if err := t.GetMembersCtx(ctx); err != nil { if err := t.LoadMembers(ctx); err != nil {
ctx.ServerError("GetMembers", err) ctx.ServerError("GetMembers", err)
return return
} }
@ -346,7 +346,7 @@ func TeamMembers(ctx *context.Context) {
ctx.Data["Title"] = ctx.Org.Team.Name ctx.Data["Title"] = ctx.Org.Team.Name
ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeams"] = true
ctx.Data["PageIsOrgTeamMembers"] = true ctx.Data["PageIsOrgTeamMembers"] = true
if err := ctx.Org.Team.GetMembersCtx(ctx); err != nil { if err := ctx.Org.Team.LoadMembers(ctx); err != nil {
ctx.ServerError("GetMembers", err) ctx.ServerError("GetMembers", err)
return return
} }
@ -368,7 +368,7 @@ func TeamRepositories(ctx *context.Context) {
ctx.Data["Title"] = ctx.Org.Team.Name ctx.Data["Title"] = ctx.Org.Team.Name
ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeams"] = true
ctx.Data["PageIsOrgTeamRepos"] = true ctx.Data["PageIsOrgTeamRepos"] = true
if err := ctx.Org.Team.GetRepositoriesCtx(ctx); err != nil { if err := ctx.Org.Team.LoadRepositories(ctx); err != nil {
ctx.ServerError("GetRepositories", err) ctx.ServerError("GetRepositories", err)
return return
} }
@ -570,7 +570,7 @@ func getTeamInviteFromContext(ctx *context.Context) (*org_model.TeamInvite, *org
return nil, nil, nil, nil, err return nil, nil, nil, nil, err
} }
inviter, err := user_model.GetUserByIDCtx(ctx, invite.InviterID) inviter, err := user_model.GetUserByID(ctx, invite.InviterID)
if err != nil { if err != nil {
return nil, nil, nil, nil, err return nil, nil, nil, nil, err
} }
@ -580,7 +580,7 @@ func getTeamInviteFromContext(ctx *context.Context) (*org_model.TeamInvite, *org
return nil, nil, nil, nil, err return nil, nil, nil, nil, err
} }
org, err := user_model.GetUserByIDCtx(ctx, team.OrgID) org, err := user_model.GetUserByID(ctx, team.OrgID)
if err != nil { if err != nil {
return nil, nil, nil, nil, err return nil, nil, nil, nil, err
} }

View file

@ -94,7 +94,7 @@ func GetAttachment(ctx *context.Context) {
return return
} }
repository, unitType, err := repo_service.LinkedRepository(attach) repository, unitType, err := repo_service.LinkedRepository(ctx, attach)
if err != nil { if err != nil {
ctx.ServerError("LinkedRepository", err) ctx.ServerError("LinkedRepository", err)
return return

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