Another round of db.DefaultContext refactor (#27103)

Part of #27065

---------

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
This commit is contained in:
JakobDev 2023-09-25 15:17:37 +02:00 committed by GitHub
parent 93bd4351bf
commit 7047df36d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
109 changed files with 353 additions and 306 deletions

View file

@ -389,7 +389,7 @@ func runRepoSyncReleases(_ *cli.Context) error {
}
log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
if err = repo_module.SyncReleasesWithTags(repo, gitRepo); err != nil {
if err = repo_module.SyncReleasesWithTags(ctx, repo, gitRepo); err != nil {
log.Warn(" SyncReleasesWithTags: %v", err)
gitRepo.Close()
continue
@ -438,7 +438,7 @@ func runRegenerateKeys(_ *cli.Context) error {
if err := initDB(ctx); err != nil {
return err
}
return asymkey_model.RewriteAllPublicKeys()
return asymkey_model.RewriteAllPublicKeys(ctx)
}
func parseOAuth2Config(c *cli.Context) *oauth2.Source {

View file

@ -9,6 +9,7 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -30,7 +31,7 @@ func TestMigratePackages(t *testing.T) {
assert.NoError(t, err)
defer buf.Close()
v, f, err := packages_service.CreatePackageAndAddFile(&packages_service.PackageCreationInfo{
v, f, err := packages_service.CreatePackageAndAddFile(db.DefaultContext, &packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: creator,
PackageType: packages.TypeGeneric,

View file

@ -4,6 +4,8 @@
package activities
import (
"context"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
user_model "code.gitea.io/gitea/models/user"
@ -18,16 +20,16 @@ type UserHeatmapData struct {
}
// GetUserHeatmapDataByUser returns an array of UserHeatmapData
func GetUserHeatmapDataByUser(user, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(user, nil, doer)
func GetUserHeatmapDataByUser(ctx context.Context, user, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(ctx, user, nil, doer)
}
// GetUserHeatmapDataByUserTeam returns an array of UserHeatmapData
func GetUserHeatmapDataByUserTeam(user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(user, team, doer)
func GetUserHeatmapDataByUserTeam(ctx context.Context, user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
return getUserHeatmapData(ctx, user, team, doer)
}
func getUserHeatmapData(user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
func getUserHeatmapData(ctx context.Context, user *user_model.User, team *organization.Team, doer *user_model.User) ([]*UserHeatmapData, error) {
hdata := make([]*UserHeatmapData, 0)
if !ActivityReadable(user, doer) {
@ -60,7 +62,7 @@ func getUserHeatmapData(user *user_model.User, team *organization.Team, doer *us
return nil, err
}
return hdata, db.GetEngine(db.DefaultContext).
return hdata, db.GetEngine(ctx).
Select(groupBy+" AS timestamp, count(user_id) as contributions").
Table("action").
Where(cond).

View file

@ -83,7 +83,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
assert.NoError(t, err)
// Get the heatmap and compare
heatmap, err := activities_model.GetUserHeatmapDataByUser(user, doer)
heatmap, err := activities_model.GetUserHeatmapDataByUser(db.DefaultContext, user, doer)
var contributions int
for _, hm := range heatmap {
contributions += int(hm.Contributions)

View file

@ -88,14 +88,14 @@ func ListGPGKeys(ctx context.Context, uid int64, listOptions db.ListOptions) ([]
}
// CountUserGPGKeys return number of gpg keys a user own
func CountUserGPGKeys(userID int64) (int64, error) {
return db.GetEngine(db.DefaultContext).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{})
func CountUserGPGKeys(ctx context.Context, userID int64) (int64, error) {
return db.GetEngine(ctx).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{})
}
// GetGPGKeyByID returns public key by given ID.
func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
func GetGPGKeyByID(ctx context.Context, keyID int64) (*GPGKey, error) {
key := new(GPGKey)
has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key)
has, err := db.GetEngine(ctx).ID(keyID).Get(key)
if err != nil {
return nil, err
} else if !has {
@ -105,9 +105,9 @@ func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
}
// GetGPGKeysByKeyID returns public key by given ID.
func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) {
func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) {
keys := make([]*GPGKey, 0, 1)
return keys, db.GetEngine(db.DefaultContext).Where("key_id=?", keyID).Find(&keys)
return keys, db.GetEngine(ctx).Where("key_id=?", keyID).Find(&keys)
}
// GPGKeyToEntity retrieve the imported key and the traducted entity
@ -224,8 +224,8 @@ func deleteGPGKey(ctx context.Context, keyID string) (int64, error) {
}
// DeleteGPGKey deletes GPG key information in database.
func DeleteGPGKey(doer *user_model.User, id int64) (err error) {
key, err := GetGPGKeyByID(id)
func DeleteGPGKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
key, err := GetGPGKeyByID(ctx, id)
if err != nil {
if IsErrGPGKeyNotExist(err) {
return nil
@ -238,7 +238,7 @@ func DeleteGPGKey(doer *user_model.User, id int64) (err error) {
return ErrGPGKeyAccessDenied{doer.ID, key.ID}
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}

View file

@ -66,13 +66,13 @@ func addGPGSubKey(ctx context.Context, key *GPGKey) (err error) {
}
// AddGPGKey adds new public key to database.
func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, error) {
func AddGPGKey(ctx context.Context, ownerID int64, content, token, signature string) ([]*GPGKey, error) {
ekeys, err := checkArmoredGPGKeyString(content)
if err != nil {
return nil, err
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, err
}

View file

@ -392,7 +392,7 @@ func hashAndVerifyForKeyID(ctx context.Context, sig *packet.Signature, payload s
if keyID == "" {
return nil
}
keys, err := GetGPGKeysByKeyID(keyID)
keys, err := GetGPGKeysByKeyID(ctx, keyID)
if err != nil {
log.Error("GetGPGKeysByKeyID: %v", err)
return &CommitVerification{
@ -407,7 +407,7 @@ func hashAndVerifyForKeyID(ctx context.Context, sig *packet.Signature, payload s
for _, key := range keys {
var primaryKeys []*GPGKey
if key.PrimaryKeyID != "" {
primaryKeys, err = GetGPGKeysByKeyID(key.PrimaryKeyID)
primaryKeys, err = GetGPGKeysByKeyID(ctx, key.PrimaryKeyID)
if err != nil {
log.Error("GetGPGKeysByKeyID: %v", err)
return &CommitVerification{

View file

@ -7,6 +7,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/timeutil"
@ -228,7 +229,7 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL
=zHo9
-----END PGP PUBLIC KEY BLOCK-----`
keys, err := AddGPGKey(1, testEmailWithUpperCaseLetters, "", "")
keys, err := AddGPGKey(db.DefaultContext, 1, testEmailWithUpperCaseLetters, "", "")
assert.NoError(t, err)
if assert.NotEmpty(t, keys) {
key := keys[0]

View file

@ -117,7 +117,7 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
// RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
// Note: db.GetEngine(db.DefaultContext).Iterate does not get latest data after insert/delete, so we have to call this function
// outside any session scope independently.
func RewriteAllPublicKeys() error {
func RewriteAllPublicKeys(ctx context.Context) error {
// Don't rewrite key if internal server
if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
return nil
@ -165,7 +165,7 @@ func RewriteAllPublicKeys() error {
}
}
if err := RegeneratePublicKeys(db.DefaultContext, t); err != nil {
if err := RegeneratePublicKeys(ctx, t); err != nil {
return err
}

View file

@ -3,12 +3,16 @@
package issues
import "code.gitea.io/gitea/models/db"
import (
"context"
"code.gitea.io/gitea/models/db"
)
// RecalculateIssueIndexForRepo create issue_index for repo if not exist and
// update it based on highest index of existing issues assigned to a repo
func RecalculateIssueIndexForRepo(repoID int64) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func RecalculateIssueIndexForRepo(ctx context.Context, repoID int64) error {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}

View file

@ -80,9 +80,9 @@ func CountIssues(ctx context.Context, opts *IssuesOptions) (int64, error) {
}
// GetIssueStats returns issue statistic information by given conditions.
func GetIssueStats(opts *IssuesOptions) (*IssueStats, error) {
func GetIssueStats(ctx context.Context, opts *IssuesOptions) (*IssueStats, error) {
if len(opts.IssueIDs) <= MaxQueryParameters {
return getIssueStatsChunk(opts, opts.IssueIDs)
return getIssueStatsChunk(ctx, opts, opts.IssueIDs)
}
// If too long a list of IDs is provided, we get the statistics in
@ -95,7 +95,7 @@ func GetIssueStats(opts *IssuesOptions) (*IssueStats, error) {
if chunk > len(opts.IssueIDs) {
chunk = len(opts.IssueIDs)
}
stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
stats, err := getIssueStatsChunk(ctx, opts, opts.IssueIDs[i:chunk])
if err != nil {
return nil, err
}
@ -112,10 +112,10 @@ func GetIssueStats(opts *IssuesOptions) (*IssueStats, error) {
return accum, nil
}
func getIssueStatsChunk(opts *IssuesOptions, issueIDs []int64) (*IssueStats, error) {
func getIssueStatsChunk(ctx context.Context, opts *IssuesOptions, issueIDs []int64) (*IssueStats, error) {
stats := &IssueStats{}
sess := db.GetEngine(db.DefaultContext).
sess := db.GetEngine(ctx).
Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
var err error

View file

@ -369,7 +369,7 @@ func TestCorrectIssueStats(t *testing.T) {
// Now we will call the GetIssueStats with these IDs and if working,
// get the correct stats back.
issueStats, err := issues_model.GetIssueStats(&issues_model.IssuesOptions{
issueStats, err := issues_model.GetIssueStats(db.DefaultContext, &issues_model.IssuesOptions{
RepoIDs: []int64{1},
IssueIDs: ids,
})

View file

@ -311,7 +311,7 @@ func (pr *PullRequest) LoadRequestedReviewers(ctx context.Context) error {
return nil
}
reviews, err := GetReviewsByIssueID(pr.Issue.ID)
reviews, err := GetReviewsByIssueID(ctx, pr.Issue.ID)
if err != nil {
return err
}

View file

@ -71,11 +71,11 @@ type Reaction struct {
}
// LoadUser load user of reaction
func (r *Reaction) LoadUser() (*user_model.User, error) {
func (r *Reaction) LoadUser(ctx context.Context) (*user_model.User, error) {
if r.User != nil {
return r.User, nil
}
user, err := user_model.GetUserByID(db.DefaultContext, r.UserID)
user, err := user_model.GetUserByID(ctx, r.UserID)
if err != nil {
return nil, err
}
@ -141,16 +141,16 @@ func (opts *FindReactionsOptions) toConds() builder.Cond {
}
// FindCommentReactions returns a ReactionList of all reactions from an comment
func FindCommentReactions(issueID, commentID int64) (ReactionList, int64, error) {
return FindReactions(db.DefaultContext, FindReactionsOptions{
func FindCommentReactions(ctx context.Context, issueID, commentID int64) (ReactionList, int64, error) {
return FindReactions(ctx, FindReactionsOptions{
IssueID: issueID,
CommentID: commentID,
})
}
// FindIssueReactions returns a ReactionList of all reactions from an issue
func FindIssueReactions(issueID int64, listOptions db.ListOptions) (ReactionList, int64, error) {
return FindReactions(db.DefaultContext, FindReactionsOptions{
func FindIssueReactions(ctx context.Context, issueID int64, listOptions db.ListOptions) (ReactionList, int64, error) {
return FindReactions(ctx, FindReactionsOptions{
ListOptions: listOptions,
IssueID: issueID,
CommentID: -1,
@ -218,12 +218,12 @@ type ReactionOptions struct {
}
// CreateReaction creates reaction for issue or comment.
func CreateReaction(opts *ReactionOptions) (*Reaction, error) {
func CreateReaction(ctx context.Context, opts *ReactionOptions) (*Reaction, error) {
if !setting.UI.ReactionsLookup.Contains(opts.Type) {
return nil, ErrForbiddenIssueReaction{opts.Type}
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, err
}
@ -241,8 +241,8 @@ func CreateReaction(opts *ReactionOptions) (*Reaction, error) {
}
// CreateIssueReaction creates a reaction on issue.
func CreateIssueReaction(doerID, issueID int64, content string) (*Reaction, error) {
return CreateReaction(&ReactionOptions{
func CreateIssueReaction(ctx context.Context, doerID, issueID int64, content string) (*Reaction, error) {
return CreateReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,
@ -250,8 +250,8 @@ func CreateIssueReaction(doerID, issueID int64, content string) (*Reaction, erro
}
// CreateCommentReaction creates a reaction on comment.
func CreateCommentReaction(doerID, issueID, commentID int64, content string) (*Reaction, error) {
return CreateReaction(&ReactionOptions{
func CreateCommentReaction(ctx context.Context, doerID, issueID, commentID int64, content string) (*Reaction, error) {
return CreateReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,
@ -279,8 +279,8 @@ func DeleteReaction(ctx context.Context, opts *ReactionOptions) error {
}
// DeleteIssueReaction deletes a reaction on issue.
func DeleteIssueReaction(doerID, issueID int64, content string) error {
return DeleteReaction(db.DefaultContext, &ReactionOptions{
func DeleteIssueReaction(ctx context.Context, doerID, issueID int64, content string) error {
return DeleteReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,
@ -289,8 +289,8 @@ func DeleteIssueReaction(doerID, issueID int64, content string) error {
}
// DeleteCommentReaction deletes a reaction on comment.
func DeleteCommentReaction(doerID, issueID, commentID int64, content string) error {
return DeleteReaction(db.DefaultContext, &ReactionOptions{
func DeleteCommentReaction(ctx context.Context, doerID, issueID, commentID int64, content string) error {
return DeleteReaction(ctx, &ReactionOptions{
Type: content,
DoerID: doerID,
IssueID: issueID,

View file

@ -20,9 +20,9 @@ func addReaction(t *testing.T, doerID, issueID, commentID int64, content string)
var reaction *issues_model.Reaction
var err error
if commentID == 0 {
reaction, err = issues_model.CreateIssueReaction(doerID, issueID, content)
reaction, err = issues_model.CreateIssueReaction(db.DefaultContext, doerID, issueID, content)
} else {
reaction, err = issues_model.CreateCommentReaction(doerID, issueID, commentID, content)
reaction, err = issues_model.CreateCommentReaction(db.DefaultContext, doerID, issueID, commentID, content)
}
assert.NoError(t, err)
assert.NotNil(t, reaction)
@ -49,7 +49,7 @@ func TestIssueAddDuplicateReaction(t *testing.T) {
addReaction(t, user1.ID, issue1ID, 0, "heart")
reaction, err := issues_model.CreateReaction(&issues_model.ReactionOptions{
reaction, err := issues_model.CreateReaction(db.DefaultContext, &issues_model.ReactionOptions{
DoerID: user1.ID,
IssueID: issue1ID,
Type: "heart",
@ -70,7 +70,7 @@ func TestIssueDeleteReaction(t *testing.T) {
addReaction(t, user1.ID, issue1ID, 0, "heart")
err := issues_model.DeleteIssueReaction(user1.ID, issue1ID, "heart")
err := issues_model.DeleteIssueReaction(db.DefaultContext, user1.ID, issue1ID, "heart")
assert.NoError(t, err)
unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID})
@ -168,7 +168,7 @@ func TestIssueCommentReactionCount(t *testing.T) {
var comment1ID int64 = 1
addReaction(t, user1.ID, issue1ID, comment1ID, "heart")
assert.NoError(t, issues_model.DeleteCommentReaction(user1.ID, issue1ID, comment1ID, "heart"))
assert.NoError(t, issues_model.DeleteCommentReaction(db.DefaultContext, user1.ID, issue1ID, comment1ID, "heart"))
unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID, CommentID: comment1ID})
}

View file

@ -126,16 +126,16 @@ func FindLatestReviews(ctx context.Context, opts FindReviewOptions) (ReviewList,
}
// CountReviews returns count of reviews passing FindReviewOptions
func CountReviews(opts FindReviewOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Review{})
func CountReviews(ctx context.Context, opts FindReviewOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.toCond()).Count(&Review{})
}
// GetReviewersFromOriginalAuthorsByIssueID gets the latest review of each original authors for a pull request
func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) (ReviewList, error) {
func GetReviewersFromOriginalAuthorsByIssueID(ctx context.Context, issueID int64) (ReviewList, error) {
reviews := make([]*Review, 0, 10)
// Get latest review of each reviewer, sorted in order they were made
if err := db.GetEngine(db.DefaultContext).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC",
if err := db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC",
issueID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest).
Find(&reviews); err != nil {
return nil, err
@ -145,10 +145,10 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) (ReviewList, error)
}
// GetReviewsByIssueID gets the latest review of each reviewer for a pull request
func GetReviewsByIssueID(issueID int64) (ReviewList, error) {
func GetReviewsByIssueID(ctx context.Context, issueID int64) (ReviewList, error) {
reviews := make([]*Review, 0, 10)
sess := db.GetEngine(db.DefaultContext)
sess := db.GetEngine(ctx)
// Get latest review of each reviewer, sorted in order they were made
if err := sess.SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND dismissed = ? AND original_author_id = 0 GROUP BY issue_id, reviewer_id) ORDER BY review.updated_unix ASC",

View file

@ -144,7 +144,7 @@ func TestGetReviewersByIssueID(t *testing.T) {
UpdatedUnix: 946684814,
})
allReviews, err := issues_model.GetReviewsByIssueID(issue.ID)
allReviews, err := issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err)
for _, review := range allReviews {
assert.NoError(t, review.LoadReviewer(db.DefaultContext))
@ -157,7 +157,7 @@ func TestGetReviewersByIssueID(t *testing.T) {
}
}
allReviews, err = issues_model.GetReviewsByIssueID(issue.ID)
allReviews, err = issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err)
assert.NoError(t, allReviews.LoadReviewers(db.DefaultContext))
if assert.Len(t, allReviews, 3) {

View file

@ -77,8 +77,8 @@ func (opts *SearchTeamOptions) toCond() builder.Cond {
}
// SearchTeam search for teams. Caller is responsible to check permissions.
func SearchTeam(opts *SearchTeamOptions) (TeamList, int64, error) {
sess := db.GetEngine(db.DefaultContext)
func SearchTeam(ctx context.Context, opts *SearchTeamOptions) (TeamList, int64, error) {
sess := db.GetEngine(ctx)
opts.SetDefaultValues()
cond := opts.toCond()

View file

@ -142,7 +142,7 @@ func TestGetTeamMembers(t *testing.T) {
func TestGetUserTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(userID int64) {
teams, _, err := organization.SearchTeam(&organization.SearchTeamOptions{UserID: userID})
teams, _, err := organization.SearchTeam(db.DefaultContext, &organization.SearchTeamOptions{UserID: userID})
assert.NoError(t, err)
for _, team := range teams {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID})

View file

@ -181,9 +181,9 @@ func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs
}
// GetRelease returns release by given ID.
func GetRelease(repoID int64, tagName string) (*Release, error) {
func GetRelease(ctx context.Context, repoID int64, tagName string) (*Release, error) {
rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
has, err := db.GetEngine(db.DefaultContext).Get(rel)
has, err := db.GetEngine(ctx).Get(rel)
if err != nil {
return nil, err
} else if !has {
@ -284,12 +284,12 @@ func GetTagNamesByRepoID(ctx context.Context, repoID int64) ([]string, error) {
}
// CountReleasesByRepoID returns a number of releases matching FindReleaseOptions and RepoID.
func CountReleasesByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(new(Release))
func CountReleasesByRepoID(ctx context.Context, repoID int64, opts FindReleasesOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.toConds(repoID)).Count(new(Release))
}
// GetLatestReleaseByRepoID returns the latest release for a repository
func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
func GetLatestReleaseByRepoID(ctx context.Context, repoID int64) (*Release, error) {
cond := builder.NewCond().
And(builder.Eq{"repo_id": repoID}).
And(builder.Eq{"is_draft": false}).
@ -297,7 +297,7 @@ func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
And(builder.Eq{"is_tag": false})
rel := new(Release)
has, err := db.GetEngine(db.DefaultContext).
has, err := db.GetEngine(ctx).
Desc("created_unix", "id").
Where(cond).
Get(rel)
@ -442,8 +442,8 @@ func DeleteReleaseByID(ctx context.Context, id int64) error {
}
// UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID
func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.GetEngine(db.DefaultContext).Table("release").
func UpdateReleasesMigrationsByType(ctx context.Context, gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.GetEngine(ctx).Table("release").
Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
And("original_author_id = ?", originalAuthorID).
Update(map[string]any{
@ -485,8 +485,8 @@ func PushUpdateDeleteTagsContext(ctx context.Context, repo *Repository, tags []s
}
// PushUpdateDeleteTag must be called for any push actions to delete tag
func PushUpdateDeleteTag(repo *Repository, tagName string) error {
rel, err := GetRelease(repo.ID, tagName)
func PushUpdateDeleteTag(ctx context.Context, repo *Repository, tagName string) error {
rel, err := GetRelease(ctx, repo.ID, tagName)
if err != nil {
if IsErrReleaseNotExist(err) {
return nil
@ -494,14 +494,14 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error {
return fmt.Errorf("GetRelease: %w", err)
}
if rel.IsTag {
if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).Delete(new(Release)); err != nil {
if _, err = db.GetEngine(ctx).ID(rel.ID).Delete(new(Release)); err != nil {
return fmt.Errorf("Delete: %w", err)
}
} else {
rel.IsDraft = true
rel.NumCommits = 0
rel.Sha1 = ""
if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil {
if _, err = db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel); err != nil {
return fmt.Errorf("Update: %w", err)
}
}
@ -510,15 +510,15 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error {
}
// SaveOrUpdateTag must be called for any push actions to add tag
func SaveOrUpdateTag(repo *Repository, newRel *Release) error {
rel, err := GetRelease(repo.ID, newRel.TagName)
func SaveOrUpdateTag(ctx context.Context, repo *Repository, newRel *Release) error {
rel, err := GetRelease(ctx, repo.ID, newRel.TagName)
if err != nil && !IsErrReleaseNotExist(err) {
return fmt.Errorf("GetRelease: %w", err)
}
if rel == nil {
rel = newRel
if _, err = db.GetEngine(db.DefaultContext).Insert(rel); err != nil {
if _, err = db.GetEngine(ctx).Insert(rel); err != nil {
return fmt.Errorf("InsertOne: %w", err)
}
} else {
@ -529,7 +529,7 @@ func SaveOrUpdateTag(repo *Repository, newRel *Release) error {
if rel.IsTag && newRel.PublisherID > 0 {
rel.PublisherID = newRel.PublisherID
}
if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil {
if _, err = db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel); err != nil {
return fmt.Errorf("Update: %w", err)
}
}
@ -554,8 +554,8 @@ func (r *Release) GetExternalName() string { return r.OriginalAuthor }
func (r *Release) GetExternalID() int64 { return r.OriginalAuthorID }
// InsertReleases migrates release
func InsertReleases(rels ...*Release) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func InsertReleases(ctx context.Context, rels ...*Release) error {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}

View file

@ -6,6 +6,7 @@ package repo
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@ -21,6 +22,6 @@ func TestMigrate_InsertReleases(t *testing.T) {
Attachments: []*Attachment{a},
}
err := InsertReleases(r)
err := InsertReleases(db.DefaultContext, r)
assert.NoError(t, err)
}

View file

@ -94,28 +94,28 @@ func CountNotices() int64 {
}
// Notices returns notices in given page.
func Notices(page, pageSize int) ([]*Notice, error) {
func Notices(ctx context.Context, page, pageSize int) ([]*Notice, error) {
notices := make([]*Notice, 0, pageSize)
return notices, db.GetEngine(db.DefaultContext).
return notices, db.GetEngine(ctx).
Limit(pageSize, (page-1)*pageSize).
Desc("created_unix").
Find(&notices)
}
// DeleteNotice deletes a system notice by given ID.
func DeleteNotice(id int64) error {
_, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Notice))
func DeleteNotice(ctx context.Context, id int64) error {
_, err := db.GetEngine(ctx).ID(id).Delete(new(Notice))
return err
}
// DeleteNotices deletes all notices with ID from start to end (inclusive).
func DeleteNotices(start, end int64) error {
func DeleteNotices(ctx context.Context, start, end int64) error {
if start == 0 && end == 0 {
_, err := db.GetEngine(db.DefaultContext).Exec("DELETE FROM notice")
_, err := db.GetEngine(ctx).Exec("DELETE FROM notice")
return err
}
sess := db.GetEngine(db.DefaultContext).Where("id >= ?", start)
sess := db.GetEngine(ctx).Where("id >= ?", start)
if end > 0 {
sess.And("id <= ?", end)
}
@ -124,22 +124,22 @@ func DeleteNotices(start, end int64) error {
}
// DeleteNoticesByIDs deletes notices by given IDs.
func DeleteNoticesByIDs(ids []int64) error {
func DeleteNoticesByIDs(ctx context.Context, ids []int64) error {
if len(ids) == 0 {
return nil
}
_, err := db.GetEngine(db.DefaultContext).
_, err := db.GetEngine(ctx).
In("id", ids).
Delete(new(Notice))
return err
}
// DeleteOldSystemNotices deletes all old system notices from database.
func DeleteOldSystemNotices(olderThan time.Duration) (err error) {
func DeleteOldSystemNotices(ctx context.Context, olderThan time.Duration) (err error) {
if olderThan <= 0 {
return nil
}
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Notice{})
_, err = db.GetEngine(ctx).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Notice{})
return err
}

View file

@ -55,14 +55,14 @@ func TestCountNotices(t *testing.T) {
func TestNotices(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
notices, err := system.Notices(1, 2)
notices, err := system.Notices(db.DefaultContext, 1, 2)
assert.NoError(t, err)
if assert.Len(t, notices, 2) {
assert.Equal(t, int64(3), notices[0].ID)
assert.Equal(t, int64(2), notices[1].ID)
}
notices, err = system.Notices(2, 2)
notices, err = system.Notices(db.DefaultContext, 2, 2)
assert.NoError(t, err)
if assert.Len(t, notices, 1) {
assert.Equal(t, int64(1), notices[0].ID)
@ -73,7 +73,7 @@ func TestDeleteNotice(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotice(3))
assert.NoError(t, system.DeleteNotice(db.DefaultContext, 3))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 3})
}
@ -84,7 +84,7 @@ func TestDeleteNotices(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotices(1, 2))
assert.NoError(t, system.DeleteNotices(db.DefaultContext, 1, 2))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 1})
unittest.AssertNotExistsBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
@ -97,7 +97,7 @@ func TestDeleteNotices2(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotices(3, 2))
assert.NoError(t, system.DeleteNotices(db.DefaultContext, 3, 2))
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
@ -109,7 +109,7 @@ func TestDeleteNoticesByIDs(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNoticesByIDs([]int64{1, 3}))
assert.NoError(t, system.DeleteNoticesByIDs(db.DefaultContext, []int64{1, 3}))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertNotExistsBean(t, &system.Notice{ID: 3})

View file

@ -48,10 +48,10 @@ func init() {
}
// LookupUserRedirect look up userID if a user has a redirect name
func LookupUserRedirect(userName string) (int64, error) {
func LookupUserRedirect(ctx context.Context, userName string) (int64, error) {
userName = strings.ToLower(userName)
redirect := &Redirect{LowerName: userName}
if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil {
if has, err := db.GetEngine(ctx).Get(redirect); err != nil {
return 0, err
} else if !has {
return 0, ErrUserRedirectNotExist{Name: userName}

View file

@ -6,6 +6,7 @@ package user_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -15,10 +16,10 @@ import (
func TestLookupUserRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
userID, err := user_model.LookupUserRedirect("olduser1")
userID, err := user_model.LookupUserRedirect(db.DefaultContext, "olduser1")
assert.NoError(t, err)
assert.EqualValues(t, 1, userID)
_, err = user_model.LookupUserRedirect("doesnotexist")
_, err = user_model.LookupUserRedirect(db.DefaultContext, "doesnotexist")
assert.True(t, user_model.IsErrUserRedirectNotExist(err))
}

View file

@ -46,7 +46,7 @@ func GetOrganizationByParams(ctx *Context) {
ctx.Org.Organization, err = organization.GetOrgByName(ctx, orgName)
if err != nil {
if organization.IsErrOrgNotExist(err) {
redirectUserID, err := user_model.LookupUserRedirect(orgName)
redirectUserID, err := user_model.LookupUserRedirect(ctx, orgName)
if err == nil {
RedirectToUser(ctx.Base, orgName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {

View file

@ -456,7 +456,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
return nil
}
if redirectUserID, err := user_model.LookupUserRedirect(userName); err == nil {
if redirectUserID, err := user_model.LookupUserRedirect(ctx, userName); err == nil {
RedirectToUser(ctx.Base, userName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {
ctx.NotFound("GetUserByName", nil)

View file

@ -33,7 +33,7 @@ func checkAuthorizedKeys(ctx context.Context, logger log.Logger, autofix bool) e
return fmt.Errorf("Unable to open authorized_keys file. ERROR: %w", err)
}
logger.Warn("Unable to open authorized_keys. (ERROR: %v). Attempting to rewrite...", err)
if err = asymkey_model.RewriteAllPublicKeys(); err != nil {
if err = asymkey_model.RewriteAllPublicKeys(ctx); err != nil {
logger.Critical("Unable to rewrite authorized_keys file. ERROR: %v", err)
return fmt.Errorf("Unable to rewrite authorized_keys file. ERROR: %w", err)
}
@ -76,7 +76,7 @@ func checkAuthorizedKeys(ctx context.Context, logger log.Logger, autofix bool) e
return fmt.Errorf(`authorized_keys is out of date and should be regenerated with "gitea admin regenerate keys" or "gitea doctor --run authorized-keys --fix"`)
}
logger.Warn("authorized_keys is out of date. Attempting rewrite...")
err = asymkey_model.RewriteAllPublicKeys()
err = asymkey_model.RewriteAllPublicKeys(ctx)
if err != nil {
logger.Critical("Unable to rewrite authorized_keys file. ERROR: %v", err)
return fmt.Errorf("Unable to rewrite authorized_keys file. ERROR: %w", err)

View file

@ -119,7 +119,7 @@ func (graph *Graph) LoadAndProcessCommits(ctx context.Context, repository *repo_
return repo_model.IsOwnerMemberCollaborator(repository, user.ID)
}, &keyMap)
statuses, _, err := git_model.GetLatestCommitStatus(db.DefaultContext, repository.ID, c.Commit.ID.String(), db.ListOptions{})
statuses, _, err := git_model.GetLatestCommitStatus(ctx, repository.ID, c.Commit.ID.String(), db.ListOptions{})
if err != nil {
log.Error("GetLatestCommitStatus: %v", err)
} else {

View file

@ -4,19 +4,20 @@
package repository
import (
"code.gitea.io/gitea/models/db"
"context"
"code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
)
// CanUserDelete returns true if user could delete the repository
func CanUserDelete(repo *repo_model.Repository, user *user_model.User) (bool, error) {
func CanUserDelete(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (bool, error) {
if user.IsAdmin || user.ID == repo.OwnerID {
return true, nil
}
if err := repo.LoadOwner(db.DefaultContext); err != nil {
if err := repo.LoadOwner(ctx); err != nil {
return false, err
}

View file

@ -159,7 +159,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User,
// note: this will greatly improve release (tag) sync
// for pull-mirrors with many tags
repo.IsMirror = opts.Mirror
if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
if err = SyncReleasesWithTags(ctx, repo, gitRepo); err != nil {
log.Error("Failed to synchronize tags to releases for repository: %v", err)
}
}
@ -285,13 +285,13 @@ func CleanUpMigrateInfo(ctx context.Context, repo *repo_model.Repository) (*repo
}
// SyncReleasesWithTags synchronizes release table with repository tags
func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) error {
func SyncReleasesWithTags(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository) error {
log.Debug("SyncReleasesWithTags: in Repo[%d:%s/%s]", repo.ID, repo.OwnerName, repo.Name)
// optimized procedure for pull-mirrors which saves a lot of time (in
// particular for repos with many tags).
if repo.IsMirror {
return pullMirrorReleaseSync(repo, gitRepo)
return pullMirrorReleaseSync(ctx, repo, gitRepo)
}
existingRelTags := make(container.Set[string])
@ -318,7 +318,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository)
return fmt.Errorf("unable to GetTagCommitID for %q in Repo[%d:%s/%s]: %w", rel.TagName, repo.ID, repo.OwnerName, repo.Name, err)
}
if git.IsErrNotExist(err) || commitID != rel.Sha1 {
if err := repo_model.PushUpdateDeleteTag(repo, rel.TagName); err != nil {
if err := repo_model.PushUpdateDeleteTag(ctx, repo, rel.TagName); err != nil {
return fmt.Errorf("unable to PushUpdateDeleteTag: %q in Repo[%d:%s/%s]: %w", rel.TagName, repo.ID, repo.OwnerName, repo.Name, err)
}
} else {
@ -333,7 +333,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository)
return nil
}
if err := PushUpdateAddTag(db.DefaultContext, repo, gitRepo, tagName, sha1, refname); err != nil {
if err := PushUpdateAddTag(ctx, repo, gitRepo, tagName, sha1, refname); err != nil {
return fmt.Errorf("unable to PushUpdateAddTag: %q to Repo[%d:%s/%s]: %w", tagName, repo.ID, repo.OwnerName, repo.Name, err)
}
@ -390,7 +390,7 @@ func PushUpdateAddTag(ctx context.Context, repo *repo_model.Repository, gitRepo
rel.PublisherID = author.ID
}
return repo_model.SaveOrUpdateTag(repo, &rel)
return repo_model.SaveOrUpdateTag(ctx, repo, &rel)
}
// StoreMissingLfsObjectsInRepository downloads missing LFS objects
@ -497,13 +497,13 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *repo_model.Re
// upstream. Hence, after each sync we want the pull-mirror release set to be
// identical to the upstream tag set. This is much more efficient for
// repositories like https://github.com/vim/vim (with over 13000 tags).
func pullMirrorReleaseSync(repo *repo_model.Repository, gitRepo *git.Repository) error {
func pullMirrorReleaseSync(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository) error {
log.Trace("pullMirrorReleaseSync: rebuilding releases for pull-mirror Repo[%d:%s/%s]", repo.ID, repo.OwnerName, repo.Name)
tags, numTags, err := gitRepo.GetTagInfos(0, 0)
if err != nil {
return fmt.Errorf("unable to GetTagInfos in pull-mirror Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err)
}
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.WithTx(ctx, func(ctx context.Context) error {
//
// clear out existing releases
//

View file

@ -62,7 +62,7 @@ func GetRepositoryKey(ctx *context.Context) {
}
func GetRepositoryFile(ctx *context.Context) {
pv, err := alpine_service.GetOrCreateRepositoryVersion(ctx.Package.Owner.ID)
pv, err := alpine_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
@ -134,6 +134,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -227,7 +228,7 @@ func DeletePackageFile(ctx *context.Context) {
return
}
if err := packages_service.RemovePackageFileAndVersionIfUnreferenced(ctx.Doer, pfs[0]); err != nil {
if err := packages_service.RemovePackageFileAndVersionIfUnreferenced(ctx, ctx.Doer, pfs[0]); err != nil {
if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err)
} else {

View file

@ -214,6 +214,7 @@ func UploadPackage(ctx *context.Context) {
}
pv, _, err := packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -286,6 +286,7 @@ func UploadPackage(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -356,6 +357,7 @@ func DeletePackageVersion(ctx *context.Context) {
packageVersion := ctx.Params("version")
err := packages_service.RemovePackageVersionByNameAndVersion(
ctx,
ctx.Doer,
&packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -390,7 +392,7 @@ func DeletePackage(ctx *context.Context) {
}
for _, pv := range pvs {
if err := packages_service.RemovePackageVersion(ctx.Doer, pv); err != nil {
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pv); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}

View file

@ -220,6 +220,7 @@ func UploadPackage(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -408,6 +408,7 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
pci,
pfci,
)

View file

@ -229,6 +229,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -653,7 +653,7 @@ func DeleteManifest(ctx *context.Context) {
}
for _, pv := range pvs {
if err := packages_service.RemovePackageVersion(ctx.Doer, pv); err != nil {
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pv); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}

View file

@ -183,6 +183,7 @@ func uploadPackageFile(ctx *context.Context, compositeKey string, properties map
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -45,7 +45,7 @@ func GetRepositoryKey(ctx *context.Context) {
// https://wiki.debian.org/DebianRepository/Format#A.22Release.22_files
// https://wiki.debian.org/DebianRepository/Format#A.22Packages.22_Indices
func GetRepositoryFile(ctx *context.Context) {
pv, err := debian_service.GetOrCreateRepositoryVersion(ctx.Package.Owner.ID)
pv, err := debian_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
@ -81,7 +81,7 @@ func GetRepositoryFile(ctx *context.Context) {
// https://wiki.debian.org/DebianRepository/Format#indices_acquisition_via_hashsums_.28by-hash.29
func GetRepositoryFileByHash(ctx *context.Context) {
pv, err := debian_service.GetOrCreateRepositoryVersion(ctx.Package.Owner.ID)
pv, err := debian_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
@ -159,6 +159,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -89,6 +89,7 @@ func UploadPackage(ctx *context.Context) {
defer buf.Close()
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -125,6 +126,7 @@ func UploadPackage(ctx *context.Context) {
// DeletePackage deletes the specific generic package.
func DeletePackage(ctx *context.Context) {
err := packages_service.RemovePackageVersionByNameAndVersion(
ctx,
ctx.Doer,
&packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -176,7 +178,7 @@ func DeletePackageFile(ctx *context.Context) {
}
if len(pfs) == 1 {
if err := packages_service.RemovePackageVersion(ctx.Doer, pv); err != nil {
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pv); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}

View file

@ -185,6 +185,7 @@ func UploadPackage(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -174,6 +174,7 @@ func UploadPackage(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -356,6 +356,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
pvci,
pfci,
)

View file

@ -190,6 +190,7 @@ func UploadPackage(ctx *context.Context) {
defer buf.Close()
pv, _, err := packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -255,6 +256,7 @@ func DeletePackageVersion(ctx *context.Context) {
packageVersion := ctx.Params("version")
err := packages_service.RemovePackageVersionByNameAndVersion(
ctx,
ctx.Doer,
&packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -291,7 +293,7 @@ func DeletePackage(ctx *context.Context) {
}
for _, pv := range pvs {
if err := packages_service.RemovePackageVersion(ctx.Doer, pv); err != nil {
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pv); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}

View file

@ -431,6 +431,7 @@ func UploadPackage(ctx *context.Context) {
}
_, _, err := packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -503,6 +504,7 @@ func UploadSymbolPackage(ctx *context.Context) {
}
_, err = packages_service.AddFileToExistingPackage(
ctx,
pi,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
@ -529,6 +531,7 @@ func UploadSymbolPackage(ctx *context.Context) {
for _, pdb := range pdbs {
_, err := packages_service.AddFileToExistingPackage(
ctx,
pi,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
@ -647,6 +650,7 @@ func DeletePackage(ctx *context.Context) {
packageVersion := ctx.Params("version")
err := packages_service.RemovePackageVersionByNameAndVersion(
ctx,
ctx.Doer,
&packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -189,6 +189,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -145,6 +145,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -59,7 +59,7 @@ func GetRepositoryKey(ctx *context.Context) {
// Gets a pre-generated repository metadata file
func GetRepositoryFile(ctx *context.Context) {
pv, err := rpm_service.GetOrCreateRepositoryVersion(ctx.Package.Owner.ID)
pv, err := rpm_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
@ -123,6 +123,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -234,6 +234,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
@ -280,6 +281,7 @@ func DeletePackage(ctx *context.Context) {
packageVersion := ctx.FormString("version")
err := packages_service.RemovePackageVersionByNameAndVersion(
ctx,
ctx.Doer,
&packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -329,6 +329,7 @@ func UploadPackageFile(ctx *context.Context) {
}
pv, _, err := packages_service.CreatePackageAndAddFile(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -177,6 +177,7 @@ func UploadPackageFile(ctx *context.Context) {
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx,
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,

View file

@ -402,7 +402,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
if err := asymkey_service.DeletePublicKey(ctx.ContextUser, ctx.ParamsInt64(":id")); err != nil {
if err := asymkey_service.DeletePublicKey(ctx, ctx.ContextUser, ctx.ParamsInt64(":id")); err != nil {
if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound()
} else if asymkey_model.IsErrKeyAccessDenied(err) {

View file

@ -148,7 +148,7 @@ func repoAssignment() func(ctx *context.APIContext) {
owner, err = user_model.GetUserByName(ctx, userName)
if err != nil {
if user_model.IsErrUserNotExist(err) {
if redirectUserID, err := user_model.LookupUserRedirect(userName); err == nil {
if redirectUserID, err := user_model.LookupUserRedirect(ctx, userName); err == nil {
context.RedirectToUser(ctx.Base, userName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {
ctx.NotFound("GetUserByName", err)
@ -564,7 +564,7 @@ func orgAssignment(args ...bool) func(ctx *context.APIContext) {
ctx.Org.Organization, err = organization.GetOrgByName(ctx, ctx.Params(":org"))
if err != nil {
if organization.IsErrOrgNotExist(err) {
redirectUserID, err := user_model.LookupUserRedirect(ctx.Params(":org"))
redirectUserID, err := user_model.LookupUserRedirect(ctx, ctx.Params(":org"))
if err == nil {
context.RedirectToUser(ctx.Base, ctx.Params(":org"), redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {

View file

@ -53,7 +53,7 @@ func ListTeams(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
teams, count, err := organization.SearchTeam(&organization.SearchTeamOptions{
teams, count, err := organization.SearchTeam(ctx, &organization.SearchTeamOptions{
ListOptions: utils.GetListOptions(ctx),
OrgID: ctx.Org.Organization.ID,
})
@ -92,7 +92,7 @@ func ListUserTeams(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/TeamList"
teams, count, err := organization.SearchTeam(&organization.SearchTeamOptions{
teams, count, err := organization.SearchTeam(ctx, &organization.SearchTeamOptions{
ListOptions: utils.GetListOptions(ctx),
UserID: ctx.Doer.ID,
})
@ -810,7 +810,7 @@ func SearchTeam(ctx *context.APIContext) {
opts.UserID = ctx.Doer.ID
}
teams, maxResults, err := organization.SearchTeam(opts)
teams, maxResults, err := organization.SearchTeam(ctx, opts)
if err != nil {
log.Error("SearchTeam failed: %v", err)
ctx.JSON(http.StatusInternalServerError, map[string]any{

View file

@ -164,7 +164,7 @@ func DeletePackage(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
err := packages_service.RemovePackageVersion(ctx.Doer, ctx.Package.Descriptor.Version)
err := packages_service.RemovePackageVersion(ctx, ctx.Doer, ctx.Package.Descriptor.Version)
if err != nil {
ctx.Error(http.StatusInternalServerError, "RemovePackageVersion", err)
return

View file

@ -68,7 +68,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
return
}
reactions, _, err := issues_model.FindCommentReactions(comment.IssueID, comment.ID)
reactions, _, err := issues_model.FindCommentReactions(ctx, comment.IssueID, comment.ID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "FindCommentReactions", err)
return
@ -202,7 +202,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
if isCreateType {
// PostIssueCommentReaction part
reaction, err := issues_model.CreateCommentReaction(ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Reaction)
reaction, err := issues_model.CreateCommentReaction(ctx, ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Reaction)
if err != nil {
if issues_model.IsErrForbiddenIssueReaction(err) {
ctx.Error(http.StatusForbidden, err.Error(), err)
@ -225,7 +225,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
})
} else {
// DeleteIssueCommentReaction part
err = issues_model.DeleteCommentReaction(ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Reaction)
err = issues_model.DeleteCommentReaction(ctx, ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Reaction)
if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteCommentReaction", err)
return
@ -292,7 +292,7 @@ func GetIssueReactions(ctx *context.APIContext) {
return
}
reactions, count, err := issues_model.FindIssueReactions(issue.ID, utils.GetListOptions(ctx))
reactions, count, err := issues_model.FindIssueReactions(ctx, issue.ID, utils.GetListOptions(ctx))
if err != nil {
ctx.Error(http.StatusInternalServerError, "FindIssueReactions", err)
return
@ -418,7 +418,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i
if isCreateType {
// PostIssueReaction part
reaction, err := issues_model.CreateIssueReaction(ctx.Doer.ID, issue.ID, form.Reaction)
reaction, err := issues_model.CreateIssueReaction(ctx, ctx.Doer.ID, issue.ID, form.Reaction)
if err != nil {
if issues_model.IsErrForbiddenIssueReaction(err) {
ctx.Error(http.StatusForbidden, err.Error(), err)
@ -441,7 +441,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i
})
} else {
// DeleteIssueReaction part
err = issues_model.DeleteIssueReaction(ctx.Doer.ID, issue.ID, form.Reaction)
err = issues_model.DeleteIssueReaction(ctx, ctx.Doer.ID, issue.ID, form.Reaction)
if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteIssueReaction", err)
return

View file

@ -279,7 +279,7 @@ func DeleteDeploykey(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
if err := asymkey_service.DeleteDeployKey(ctx.Doer, ctx.ParamsInt64(":id")); err != nil {
if err := asymkey_service.DeleteDeployKey(ctx, ctx.Doer, ctx.ParamsInt64(":id")); err != nil {
if asymkey_model.IsErrKeyAccessDenied(err) {
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
} else {

View file

@ -92,7 +92,7 @@ func ListPullReviews(ctx *context.APIContext) {
return
}
count, err := issues_model.CountReviews(opts)
count, err := issues_model.CountReviews(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return

View file

@ -90,7 +90,7 @@ func GetLatestRelease(ctx *context.APIContext) {
// "$ref": "#/responses/Release"
// "404":
// "$ref": "#/responses/notFound"
release, err := repo_model.GetLatestReleaseByRepoID(ctx.Repo.Repository.ID)
release, err := repo_model.GetLatestReleaseByRepoID(ctx, ctx.Repo.Repository.ID)
if err != nil && !repo_model.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetLatestRelease", err)
return
@ -179,7 +179,7 @@ func ListReleases(ctx *context.APIContext) {
rels[i] = convert.ToAPIRelease(ctx, ctx.Repo.Repository, release)
}
filteredCount, err := repo_model.CountReleasesByRepoID(ctx.Repo.Repository.ID, opts)
filteredCount, err := repo_model.CountReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)
if err != nil {
ctx.InternalServerError(err)
return
@ -222,7 +222,7 @@ func CreateRelease(ctx *context.APIContext) {
// "409":
// "$ref": "#/responses/error"
form := web.GetForm(ctx).(*api.CreateReleaseOption)
rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, form.TagName)
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, form.TagName)
if err != nil {
if !repo_model.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetRelease", err)
@ -269,7 +269,7 @@ func CreateRelease(ctx *context.APIContext) {
rel.Publisher = ctx.Doer
rel.Target = form.Target
if err = release_service.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
if err = release_service.UpdateRelease(ctx, ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRelease", err)
return
}
@ -344,7 +344,7 @@ func EditRelease(ctx *context.APIContext) {
if form.IsPrerelease != nil {
rel.IsPrerelease = *form.IsPrerelease
}
if err := release_service.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
if err := release_service.UpdateRelease(ctx, ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRelease", err)
return
}

View file

@ -44,7 +44,7 @@ func GetReleaseByTag(ctx *context.APIContext) {
tag := ctx.Params(":tag")
release, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tag)
release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tag)
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound()
@ -97,7 +97,7 @@ func DeleteReleaseByTag(ctx *context.APIContext) {
tag := ctx.Params(":tag")
release, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tag)
release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tag)
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound()

View file

@ -1114,7 +1114,7 @@ func Delete(ctx *context.APIContext) {
owner := ctx.Repo.Owner
repo := ctx.Repo.Repository
canDelete, err := repo_module.CanUserDelete(repo, ctx.Doer)
canDelete, err := repo_module.CanUserDelete(ctx, repo, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "CanUserDelete", err)
return

View file

@ -257,7 +257,7 @@ func DeleteTag(ctx *context.APIContext) {
// "$ref": "#/responses/repoArchivedError"
tagName := ctx.Params("*")
tag, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
tag, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tagName)
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound()

View file

@ -29,7 +29,7 @@ func listGPGKeys(ctx *context.APIContext, uid int64, listOptions db.ListOptions)
apiKeys[i] = convert.ToGPGKey(keys[i])
}
total, err := asymkey_model.CountUserGPGKeys(uid)
total, err := asymkey_model.CountUserGPGKeys(ctx, uid)
if err != nil {
ctx.InternalServerError(err)
return
@ -112,7 +112,7 @@ func GetGPGKey(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
key, err := asymkey_model.GetGPGKeyByID(ctx.ParamsInt64(":id"))
key, err := asymkey_model.GetGPGKeyByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if asymkey_model.IsErrGPGKeyNotExist(err) {
ctx.NotFound()
@ -129,9 +129,9 @@ func CreateUserGPGKey(ctx *context.APIContext, form api.CreateGPGKeyOption, uid
token := asymkey_model.VerificationToken(ctx.Doer, 1)
lastToken := asymkey_model.VerificationToken(ctx.Doer, 0)
keys, err := asymkey_model.AddGPGKey(uid, form.ArmoredKey, token, form.Signature)
keys, err := asymkey_model.AddGPGKey(ctx, uid, form.ArmoredKey, token, form.Signature)
if err != nil && asymkey_model.IsErrGPGInvalidTokenSignature(err) {
keys, err = asymkey_model.AddGPGKey(uid, form.ArmoredKey, lastToken, form.Signature)
keys, err = asymkey_model.AddGPGKey(ctx, uid, form.ArmoredKey, lastToken, form.Signature)
}
if err != nil {
HandleAddGPGKeyError(ctx, err, token)
@ -198,7 +198,7 @@ func VerifyUserGPGKey(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "VerifyUserGPGKey", err)
}
key, err := asymkey_model.GetGPGKeysByKeyID(form.KeyID)
key, err := asymkey_model.GetGPGKeysByKeyID(ctx, form.KeyID)
if err != nil {
if asymkey_model.IsErrGPGKeyNotExist(err) {
ctx.NotFound()
@ -259,7 +259,7 @@ func DeleteGPGKey(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
if err := asymkey_model.DeleteGPGKey(ctx.Doer, ctx.ParamsInt64(":id")); err != nil {
if err := asymkey_model.DeleteGPGKey(ctx, ctx.Doer, ctx.ParamsInt64(":id")); err != nil {
if asymkey_model.IsErrGPGKeyAccessDenied(err) {
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
} else {

View file

@ -16,7 +16,7 @@ func GetUserByParamsName(ctx *context.APIContext, name string) *user_model.User
user, err := user_model.GetUserByName(ctx, username)
if err != nil {
if user_model.IsErrUserNotExist(err) {
if redirectUserID, err2 := user_model.LookupUserRedirect(username); err2 == nil {
if redirectUserID, err2 := user_model.LookupUserRedirect(ctx, username); err2 == nil {
context.RedirectToUser(ctx.Base, username, redirectUserID)
} else {
ctx.NotFound("GetUserByName", err)

View file

@ -277,7 +277,7 @@ func DeletePublicKey(ctx *context.APIContext) {
return
}
if err := asymkey_service.DeletePublicKey(ctx.Doer, id); err != nil {
if err := asymkey_service.DeletePublicKey(ctx, ctx.Doer, id); err != nil {
if asymkey_model.IsErrKeyAccessDenied(err) {
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
} else {

View file

@ -138,7 +138,7 @@ func GetUserHeatmapData(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
heatmap, err := activities_model.GetUserHeatmapDataByUser(ctx.ContextUser, ctx.Doer)
heatmap, err := activities_model.GetUserHeatmapDataByUser(ctx, ctx.ContextUser, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserHeatmapDataByUser", err)
return

View file

@ -93,7 +93,7 @@ func syncAppConfForGit(ctx context.Context) error {
mustInitCtx(ctx, repo_service.SyncRepositoryHooks)
log.Info("re-write ssh public keys ...")
mustInit(asymkey_model.RewriteAllPublicKeys)
mustInitCtx(ctx, asymkey_model.RewriteAllPublicKeys)
return system.AppState.Set(runtimeState)
}

View file

@ -30,7 +30,7 @@ func Notices(ctx *context.Context) {
page = 1
}
notices, err := system_model.Notices(page, setting.UI.Admin.NoticePagingNum)
notices, err := system_model.Notices(ctx, page, setting.UI.Admin.NoticePagingNum)
if err != nil {
ctx.ServerError("Notices", err)
return
@ -55,7 +55,7 @@ func DeleteNotices(ctx *context.Context) {
}
}
if err := system_model.DeleteNoticesByIDs(ids); err != nil {
if err := system_model.DeleteNoticesByIDs(ctx, ids); err != nil {
ctx.Flash.Error("DeleteNoticesByIDs: " + err.Error())
ctx.Status(http.StatusInternalServerError)
} else {
@ -66,7 +66,7 @@ func DeleteNotices(ctx *context.Context) {
// EmptyNotices delete all the notices
func EmptyNotices(ctx *context.Context) {
if err := system_model.DeleteNotices(0, 0); err != nil {
if err := system_model.DeleteNotices(ctx, 0, 0); err != nil {
ctx.ServerError("DeleteNotices", err)
return
}

View file

@ -93,7 +93,7 @@ func DeletePackageVersion(ctx *context.Context) {
return
}
if err := packages_service.RemovePackageVersion(ctx.Doer, pv); err != nil {
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pv); err != nil {
ctx.ServerError("RemovePackageVersion", err)
return
}

View file

@ -75,7 +75,7 @@ func TwoFactorPost(ctx *context.Context) {
}
if ctx.Session.Get("linkAccount") != nil {
err = externalaccount.LinkAccountFromStore(ctx.Session, u)
err = externalaccount.LinkAccountFromStore(ctx, ctx.Session, u)
if err != nil {
ctx.ServerError("UserSignIn", err)
return

View file

@ -164,7 +164,7 @@ func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, r
return
}
err = externalaccount.LinkAccountToUser(u, gothUser)
err = externalaccount.LinkAccountToUser(ctx, u, gothUser)
if err != nil {
ctx.ServerError("UserLinkAccount", err)
return

View file

@ -941,7 +941,7 @@ func SignInOAuthCallback(ctx *context.Context) {
if u == nil {
if ctx.Doer != nil {
// attach user to already logged in user
err = externalaccount.LinkAccountToUser(ctx.Doer, gothUser)
err = externalaccount.LinkAccountToUser(ctx, ctx.Doer, gothUser)
if err != nil {
ctx.ServerError("UserLinkAccount", err)
return

View file

@ -141,7 +141,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) {
// Now handle account linking if that's requested
if ctx.Session.Get("linkAccount") != nil {
if err := externalaccount.LinkAccountFromStore(ctx.Session, user); err != nil {
if err := externalaccount.LinkAccountFromStore(ctx, ctx.Session, user); err != nil {
ctx.ServerError("LinkAccountFromStore", err)
return
}

View file

@ -428,7 +428,7 @@ func SearchTeam(ctx *context.Context) {
ListOptions: listOptions,
}
teams, maxResults, err := org_model.SearchTeam(opts)
teams, maxResults, err := org_model.SearchTeam(ctx, opts)
if err != nil {
log.Error("SearchTeam failed: %v", err)
ctx.JSON(http.StatusInternalServerError, map[string]any{

View file

@ -231,7 +231,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
} else {
// So it did search with the keyword, and found some issues. It needs to get issueStats of these issues.
// Or the keyword is empty, so it doesn't need issueIDs as filter, just get issueStats with statsOpts.
issueStats, err = issues_model.GetIssueStats(statsOpts)
issueStats, err = issues_model.GetIssueStats(ctx, statsOpts)
if err != nil {
ctx.ServerError("GetIssueStats", err)
return
@ -611,14 +611,14 @@ type repoReviewerSelection struct {
func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, issue *issues_model.Issue, canChooseReviewer bool) {
ctx.Data["CanChooseReviewer"] = canChooseReviewer
originalAuthorReviews, err := issues_model.GetReviewersFromOriginalAuthorsByIssueID(issue.ID)
originalAuthorReviews, err := issues_model.GetReviewersFromOriginalAuthorsByIssueID(ctx, issue.ID)
if err != nil {
ctx.ServerError("GetReviewersFromOriginalAuthorsByIssueID", err)
return
}
ctx.Data["OriginalReviews"] = originalAuthorReviews
reviews, err := issues_model.GetReviewsByIssueID(issue.ID)
reviews, err := issues_model.GetReviewsByIssueID(ctx, issue.ID)
if err != nil {
ctx.ServerError("GetReviewersByIssueID", err)
return
@ -3206,7 +3206,7 @@ func ChangeIssueReaction(ctx *context.Context) {
switch ctx.Params(":action") {
case "react":
reaction, err := issues_model.CreateIssueReaction(ctx.Doer.ID, issue.ID, form.Content)
reaction, err := issues_model.CreateIssueReaction(ctx, ctx.Doer.ID, issue.ID, form.Content)
if err != nil {
if issues_model.IsErrForbiddenIssueReaction(err) {
ctx.ServerError("ChangeIssueReaction", err)
@ -3224,7 +3224,7 @@ func ChangeIssueReaction(ctx *context.Context) {
log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
case "unreact":
if err := issues_model.DeleteIssueReaction(ctx.Doer.ID, issue.ID, form.Content); err != nil {
if err := issues_model.DeleteIssueReaction(ctx, ctx.Doer.ID, issue.ID, form.Content); err != nil {
ctx.ServerError("DeleteIssueReaction", err)
return
}
@ -3308,7 +3308,7 @@ func ChangeCommentReaction(ctx *context.Context) {
switch ctx.Params(":action") {
case "react":
reaction, err := issues_model.CreateCommentReaction(ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Content)
reaction, err := issues_model.CreateCommentReaction(ctx, ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Content)
if err != nil {
if issues_model.IsErrForbiddenIssueReaction(err) {
ctx.ServerError("ChangeIssueReaction", err)
@ -3326,7 +3326,7 @@ func ChangeCommentReaction(ctx *context.Context) {
log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID, reaction.ID)
case "unreact":
if err := issues_model.DeleteCommentReaction(ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Content); err != nil {
if err := issues_model.DeleteCommentReaction(ctx, ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Content); err != nil {
ctx.ServerError("DeleteCommentReaction", err)
return
}

View file

@ -241,7 +241,7 @@ func SingleRelease(ctx *context.Context) {
writeAccess := ctx.Repo.CanWrite(unit.TypeReleases)
ctx.Data["CanCreateRelease"] = writeAccess && !ctx.Repo.Repository.IsArchived
release, err := repo_model.GetRelease(ctx.Repo.Repository.ID, ctx.Params("*"))
release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, ctx.Params("*"))
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound("GetRelease", err)
@ -297,7 +297,7 @@ func SingleRelease(ctx *context.Context) {
// LatestRelease redirects to the latest release
func LatestRelease(ctx *context.Context) {
release, err := repo_model.GetLatestReleaseByRepoID(ctx.Repo.Repository.ID)
release, err := repo_model.GetLatestReleaseByRepoID(ctx, ctx.Repo.Repository.ID)
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound("LatestRelease", err)
@ -321,7 +321,7 @@ func NewRelease(ctx *context.Context) {
ctx.Data["PageIsReleaseList"] = true
ctx.Data["tag_target"] = ctx.Repo.Repository.DefaultBranch
if tagName := ctx.FormString("tag"); len(tagName) > 0 {
rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tagName)
if err != nil && !repo_model.IsErrReleaseNotExist(err) {
ctx.ServerError("GetRelease", err)
return
@ -403,7 +403,7 @@ func NewReleasePost(ctx *context.Context) {
attachmentUUIDs = form.Files
}
rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, form.TagName)
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, form.TagName)
if err != nil {
if !repo_model.IsErrReleaseNotExist(err) {
ctx.ServerError("GetRelease", err)
@ -488,7 +488,7 @@ func NewReleasePost(ctx *context.Context) {
rel.PublisherID = ctx.Doer.ID
rel.IsTag = false
if err = releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, attachmentUUIDs, nil, nil); err != nil {
if err = releaseservice.UpdateRelease(ctx, ctx.Doer, ctx.Repo.GitRepo, rel, attachmentUUIDs, nil, nil); err != nil {
ctx.Data["Err_TagName"] = true
ctx.ServerError("UpdateRelease", err)
return
@ -508,7 +508,7 @@ func EditRelease(ctx *context.Context) {
upload.AddUploadContext(ctx, "release")
tagName := ctx.Params("*")
rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tagName)
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound("GetRelease", err)
@ -551,7 +551,7 @@ func EditReleasePost(ctx *context.Context) {
ctx.Data["PageIsEditRelease"] = true
tagName := ctx.Params("*")
rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
rel, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tagName)
if err != nil {
if repo_model.IsErrReleaseNotExist(err) {
ctx.NotFound("GetRelease", err)
@ -594,7 +594,7 @@ func EditReleasePost(ctx *context.Context) {
rel.Note = form.Content
rel.IsDraft = len(form.Draft) > 0
rel.IsPrerelease = form.Prerelease
if err = releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo,
if err = releaseservice.UpdateRelease(ctx, ctx.Doer, ctx.Repo.GitRepo,
rel, addAttachmentUUIDs, delAttachmentUUIDs, editAttachments); err != nil {
ctx.ServerError("UpdateRelease", err)
return

View file

@ -396,7 +396,7 @@ func RedirectDownload(ctx *context.Context) {
} else if len(releases) == 0 && vTag == "latest" {
// GitHub supports the alias "latest" for the latest release
// We only fetch the latest release if the tag is "latest" and no release with the tag "latest" exists
release, err := repo_model.GetLatestReleaseByRepoID(ctx.Repo.Repository.ID)
release, err := repo_model.GetLatestReleaseByRepoID(ctx, ctx.Repo.Repository.ID)
if err != nil {
ctx.Error(http.StatusNotFound)
return

View file

@ -99,7 +99,7 @@ func DeployKeysPost(ctx *context.Context) {
// DeleteDeployKey response for deleting a deploy key
func DeleteDeployKey(ctx *context.Context) {
if err := asymkey_service.DeleteDeployKey(ctx.Doer, ctx.FormInt64("id")); err != nil {
if err := asymkey_service.DeleteDeployKey(ctx, ctx.Doer, ctx.FormInt64("id")); err != nil {
ctx.Flash.Error("DeleteDeployKey: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))

View file

@ -105,7 +105,7 @@ func Dashboard(ctx *context.Context) {
}
if setting.Service.EnableUserHeatmap {
data, err := activities_model.GetUserHeatmapDataByUserTeam(ctxUser, ctx.Org.Team, ctx.Doer)
data, err := activities_model.GetUserHeatmapDataByUserTeam(ctx, ctxUser, ctx.Org.Team, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserHeatmapDataByUserTeam", err)
return

View file

@ -439,7 +439,7 @@ func PackageSettingsPost(ctx *context.Context) {
ctx.Redirect(ctx.Link)
return
case "delete":
err := packages_service.RemovePackageVersion(ctx.Doer, ctx.Package.Descriptor.Version)
err := packages_service.RemovePackageVersion(ctx, ctx.Doer, ctx.Package.Descriptor.Version)
if err != nil {
log.Error("Error deleting package: %v", err)
ctx.Flash.Error(ctx.Tr("packages.settings.delete.error"))

View file

@ -56,7 +56,7 @@ func userProfile(ctx *context.Context) {
// prepare heatmap data
if setting.Service.EnableUserHeatmap {
data, err := activities_model.GetUserHeatmapDataByUser(ctx.ContextUser, ctx.Doer)
data, err := activities_model.GetUserHeatmapDataByUser(ctx, ctx.ContextUser, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserHeatmapDataByUser", err)
return

View file

@ -80,9 +80,9 @@ func KeysPost(ctx *context.Context) {
token := asymkey_model.VerificationToken(ctx.Doer, 1)
lastToken := asymkey_model.VerificationToken(ctx.Doer, 0)
keys, err := asymkey_model.AddGPGKey(ctx.Doer.ID, form.Content, token, form.Signature)
keys, err := asymkey_model.AddGPGKey(ctx, ctx.Doer.ID, form.Content, token, form.Signature)
if err != nil && asymkey_model.IsErrGPGInvalidTokenSignature(err) {
keys, err = asymkey_model.AddGPGKey(ctx.Doer.ID, form.Content, lastToken, form.Signature)
keys, err = asymkey_model.AddGPGKey(ctx, ctx.Doer.ID, form.Content, lastToken, form.Signature)
}
if err != nil {
ctx.Data["HasGPGError"] = true
@ -224,7 +224,7 @@ func KeysPost(ctx *context.Context) {
func DeleteKey(ctx *context.Context) {
switch ctx.FormString("type") {
case "gpg":
if err := asymkey_model.DeleteGPGKey(ctx.Doer, ctx.FormInt64("id")); err != nil {
if err := asymkey_model.DeleteGPGKey(ctx, ctx.Doer, ctx.FormInt64("id")); err != nil {
ctx.Flash.Error("DeleteGPGKey: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("settings.gpg_key_deletion_success"))
@ -241,13 +241,13 @@ func DeleteKey(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
return
}
if err := asymkey_service.DeletePublicKey(ctx.Doer, keyID); err != nil {
if err := asymkey_service.DeletePublicKey(ctx, ctx.Doer, keyID); err != nil {
ctx.Flash.Error("DeletePublicKey: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("settings.ssh_key_deletion_success"))
}
case "principal":
if err := asymkey_service.DeletePublicKey(ctx.Doer, ctx.FormInt64("id")); err != nil {
if err := asymkey_service.DeletePublicKey(ctx, ctx.Doer, ctx.FormInt64("id")); err != nil {
ctx.Flash.Error("DeletePublicKey: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("settings.ssh_principal_deletion_success"))

View file

@ -4,6 +4,8 @@
package asymkey
import (
"context"
"code.gitea.io/gitea/models"
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/db"
@ -11,19 +13,19 @@ import (
)
// DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
func DeleteDeployKey(doer *user_model.User, id int64) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error {
dbCtx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
if err := models.DeleteDeployKey(ctx, doer, id); err != nil {
if err := models.DeleteDeployKey(dbCtx, doer, id); err != nil {
return err
}
if err := committer.Commit(); err != nil {
return err
}
return asymkey_model.RewriteAllPublicKeys()
return asymkey_model.RewriteAllPublicKeys(ctx)
}

View file

@ -4,13 +4,15 @@
package asymkey
import (
"context"
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
)
// DeletePublicKey deletes SSH key information both in database and authorized_keys file.
func DeletePublicKey(doer *user_model.User, id int64) (err error) {
func DeletePublicKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
key, err := asymkey_model.GetPublicKeyByID(id)
if err != nil {
return err
@ -25,13 +27,13 @@ func DeletePublicKey(doer *user_model.User, id int64) (err error) {
}
}
ctx, committer, err := db.TxContext(db.DefaultContext)
dbCtx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
if err = asymkey_model.DeletePublicKeys(ctx, id); err != nil {
if err = asymkey_model.DeletePublicKeys(dbCtx, id); err != nil {
return err
}
@ -41,8 +43,8 @@ func DeletePublicKey(doer *user_model.User, id int64) (err error) {
committer.Close()
if key.Type == asymkey_model.KeyTypePrincipal {
return asymkey_model.RewriteAllPrincipalKeys(db.DefaultContext)
return asymkey_model.RewriteAllPrincipalKeys(ctx)
}
return asymkey_model.RewriteAllPublicKeys()
return asymkey_model.RewriteAllPublicKeys(ctx)
}

View file

@ -8,6 +8,7 @@ import (
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -77,7 +78,7 @@ ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ib
assert.Contains(t, kase.keyContents, key.Content)
}
for _, key := range keys {
DeletePublicKey(user, key.ID)
DeletePublicKey(db.DefaultContext, user, key.ID)
}
}
}

View file

@ -10,7 +10,6 @@ import (
"regexp"
"strings"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/auth/webauthn"
gitea_context "code.gitea.io/gitea/modules/context"
@ -83,7 +82,7 @@ func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore
if len(user.Language) == 0 {
lc := middleware.Locale(resp, req)
user.Language = lc.Language()
if err := user_model.UpdateUserCols(db.DefaultContext, user, "language"); err != nil {
if err := user_model.UpdateUserCols(req.Context(), user, "language"); err != nil {
log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", user.ID, user.Language))
return
}

View file

@ -65,7 +65,7 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
if user != nil {
if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(user, source.authSource, sr.SSHPublicKey) {
if err := asymkey_model.RewriteAllPublicKeys(); err != nil {
if err := asymkey_model.RewriteAllPublicKeys(ctx); err != nil {
return user, err
}
}
@ -100,7 +100,7 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
}
if isAttributeSSHPublicKeySet && asymkey_model.AddPublicKeysBySource(user, source.authSource, sr.SSHPublicKey) {
if err := asymkey_model.RewriteAllPublicKeys(); err != nil {
if err := asymkey_model.RewriteAllPublicKeys(ctx); err != nil {
return user, err
}
}

View file

@ -77,7 +77,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
log.Warn("SyncExternalUsers: Cancelled at update of %s before completed update of users", source.authSource.Name)
// Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
if sshKeysNeedUpdate {
err = asymkey_model.RewriteAllPublicKeys()
err = asymkey_model.RewriteAllPublicKeys(ctx)
if err != nil {
log.Error("RewriteAllPublicKeys: %v", err)
}
@ -193,7 +193,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
// Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
if sshKeysNeedUpdate {
err = asymkey_model.RewriteAllPublicKeys()
err = asymkey_model.RewriteAllPublicKeys(ctx)
if err != nil {
log.Error("RewriteAllPublicKeys: %v", err)
}

View file

@ -69,7 +69,7 @@ func userAssignment(ctx *context.Base, doer *user_model.User, errCb func(int, st
contextUser, err = user_model.GetUserByName(ctx, username)
if err != nil {
if user_model.IsErrUserNotExist(err) {
if redirectUserID, err := user_model.LookupUserRedirect(username); err == nil {
if redirectUserID, err := user_model.LookupUserRedirect(ctx, username); err == nil {
context.RedirectToUser(ctx, username, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {
errCb(http.StatusNotFound, "GetUserByName", err)

View file

@ -13,7 +13,6 @@ import (
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/organization"
@ -334,7 +333,7 @@ func ToTeams(ctx context.Context, teams []*organization.Team, loadOrgs bool) ([]
if loadOrgs {
apiOrg, ok := cache[teams[i].OrgID]
if !ok {
org, err := organization.GetOrgByID(db.DefaultContext, teams[i].OrgID)
org, err := organization.GetOrgByID(ctx, teams[i].OrgID)
if err != nil {
return nil, err
}

View file

@ -9,7 +9,6 @@ import (
activities_model "code.gitea.io/gitea/models/activities"
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/system"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -71,8 +70,8 @@ func registerRewriteAllPublicKeys() {
Enabled: false,
RunAtStart: false,
Schedule: "@every 72h",
}, func(_ context.Context, _ *user_model.User, _ Config) error {
return asymkey_model.RewriteAllPublicKeys()
}, func(ctx context.Context, _ *user_model.User, _ Config) error {
return asymkey_model.RewriteAllPublicKeys(ctx)
})
}
@ -81,8 +80,8 @@ func registerRewriteAllPrincipalKeys() {
Enabled: false,
RunAtStart: false,
Schedule: "@every 72h",
}, func(_ context.Context, _ *user_model.User, _ Config) error {
return asymkey_model.RewriteAllPrincipalKeys(db.DefaultContext)
}, func(ctx context.Context, _ *user_model.User, _ Config) error {
return asymkey_model.RewriteAllPrincipalKeys(ctx)
})
}
@ -168,7 +167,7 @@ func registerDeleteOldSystemNotices() {
OlderThan: 365 * 24 * time.Hour,
}, func(ctx context.Context, _ *user_model.User, config Config) error {
olderThanConfig := config.(*OlderThanConfig)
return system.DeleteOldSystemNotices(olderThanConfig.OlderThan)
return system.DeleteOldSystemNotices(ctx, olderThanConfig.OlderThan)
})
}

View file

@ -4,6 +4,7 @@
package externalaccount
import (
"context"
"fmt"
user_model "code.gitea.io/gitea/models/user"
@ -19,11 +20,11 @@ type Store interface {
}
// LinkAccountFromStore links the provided user with a stored external user
func LinkAccountFromStore(store Store, user *user_model.User) error {
func LinkAccountFromStore(ctx context.Context, store Store, user *user_model.User) error {
gothUser := store.Get("linkAccountGothUser")
if gothUser == nil {
return fmt.Errorf("not in LinkAccount session")
}
return LinkAccountToUser(user, gothUser.(goth.User))
return LinkAccountToUser(ctx, user, gothUser.(goth.User))
}

View file

@ -4,6 +4,7 @@
package externalaccount
import (
"context"
"strings"
"code.gitea.io/gitea/models/auth"
@ -42,7 +43,7 @@ func toExternalLoginUser(user *user_model.User, gothUser goth.User) (*user_model
}
// LinkAccountToUser link the gothUser to the user
func LinkAccountToUser(user *user_model.User, gothUser goth.User) error {
func LinkAccountToUser(ctx context.Context, user *user_model.User, gothUser goth.User) error {
externalLoginUser, err := toExternalLoginUser(user, gothUser)
if err != nil {
return err
@ -63,7 +64,7 @@ func LinkAccountToUser(user *user_model.User, gothUser goth.User) error {
}
if tp.Name() != "" {
return UpdateMigrationsByType(tp, externalID, user.ID)
return UpdateMigrationsByType(ctx, tp, externalID, user.ID)
}
return nil
@ -80,7 +81,7 @@ func UpdateExternalUser(user *user_model.User, gothUser goth.User) error {
}
// UpdateMigrationsByType updates all migrated repositories' posterid from gitServiceType to replace originalAuthorID to posterID
func UpdateMigrationsByType(tp structs.GitServiceType, externalUserID string, userID int64) error {
func UpdateMigrationsByType(ctx context.Context, tp structs.GitServiceType, externalUserID string, userID int64) error {
if err := issues_model.UpdateIssuesMigrationsByType(tp, externalUserID, userID); err != nil {
return err
}
@ -89,7 +90,7 @@ func UpdateMigrationsByType(tp structs.GitServiceType, externalUserID string, us
return err
}
if err := repo_model.UpdateReleasesMigrationsByType(tp, externalUserID, userID); err != nil {
if err := repo_model.UpdateReleasesMigrationsByType(ctx, tp, externalUserID, userID); err != nil {
return err
}

View file

@ -350,12 +350,12 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {
rels = append(rels, &rel)
}
return repo_model.InsertReleases(rels...)
return repo_model.InsertReleases(g.ctx, rels...)
}
// SyncTags syncs releases with tags in the database
func (g *GiteaLocalUploader) SyncTags() error {
return repo_module.SyncReleasesWithTags(g.repo, g.gitRepo)
return repo_module.SyncReleasesWithTags(g.ctx, g.repo, g.gitRepo)
}
// CreateIssues creates issues
@ -937,7 +937,7 @@ func (g *GiteaLocalUploader) Finish() error {
}
// update issue_index
if err := issues_model.RecalculateIssueIndexForRepo(g.repo.ID); err != nil {
if err := issues_model.RecalculateIssueIndexForRepo(g.ctx, g.repo.ID); err != nil {
return err
}

View file

@ -62,7 +62,7 @@ func updateMigrationPosterIDByGitService(ctx context.Context, tp structs.GitServ
default:
}
externalUserID := user.ExternalID
if err := externalaccount.UpdateMigrationsByType(tp, externalUserID, user.UserID); err != nil {
if err := externalaccount.UpdateMigrationsByType(ctx, tp, externalUserID, user.UserID); err != nil {
log.Error("UpdateMigrationsByType type %s external user id %v to local user id %v failed: %v", tp.Name(), user.ExternalID, user.UserID, err)
}
}

View file

@ -313,7 +313,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
}
log.Trace("SyncMirrors [repo: %-v]: syncing releases with tags...", m.Repo)
if err = repo_module.SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
if err = repo_module.SyncReleasesWithTags(ctx, m.Repo, gitRepo); err != nil {
log.Error("SyncMirrors [repo: %-v]: failed to synchronize tags to releases: %v", m.Repo, err)
}

View file

@ -34,8 +34,8 @@ const IndexFilename = "APKINDEX.tar.gz"
// GetOrCreateRepositoryVersion gets or creates the internal repository package
// The Alpine registry needs multiple index files which are stored in this package.
func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion, error) {
return packages_service.GetOrCreateInternalPackageVersion(ownerID, packages_model.TypeAlpine, alpine_module.RepositoryPackage, alpine_module.RepositoryVersion)
func GetOrCreateRepositoryVersion(ctx context.Context, ownerID int64) (*packages_model.PackageVersion, error) {
return packages_service.GetOrCreateInternalPackageVersion(ctx, ownerID, packages_model.TypeAlpine, alpine_module.RepositoryPackage, alpine_module.RepositoryVersion)
}
// GetOrCreateKeyPair gets or creates the RSA keys used to sign repository files
@ -70,7 +70,7 @@ func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, err
// BuildAllRepositoryFiles (re)builds all repository files for every available distributions, components and architectures
func BuildAllRepositoryFiles(ctx context.Context, ownerID int64) error {
pv, err := GetOrCreateRepositoryVersion(ownerID)
pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
if err != nil {
return err
}
@ -118,7 +118,7 @@ func BuildAllRepositoryFiles(ctx context.Context, ownerID int64) error {
// BuildSpecificRepositoryFiles builds index files for the repository
func BuildSpecificRepositoryFiles(ctx context.Context, ownerID int64, branch, repository, architecture string) error {
pv, err := GetOrCreateRepositoryVersion(ownerID)
pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
if err != nil {
return err
}
@ -290,6 +290,7 @@ func buildPackagesIndex(ctx context.Context, ownerID int64, repoVersion *package
}
_, err = packages_service.AddFileToPackageVersionInternal(
ctx,
repoVersion,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{

View file

@ -32,8 +32,8 @@ import (
// GetOrCreateRepositoryVersion gets or creates the internal repository package
// The Debian registry needs multiple index files which are stored in this package.
func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion, error) {
return packages_service.GetOrCreateInternalPackageVersion(ownerID, packages_model.TypeDebian, debian_module.RepositoryPackage, debian_module.RepositoryVersion)
func GetOrCreateRepositoryVersion(ctx context.Context, ownerID int64) (*packages_model.PackageVersion, error) {
return packages_service.GetOrCreateInternalPackageVersion(ctx, ownerID, packages_model.TypeDebian, debian_module.RepositoryPackage, debian_module.RepositoryVersion)
}
// GetOrCreateKeyPair gets or creates the PGP keys used to sign repository files
@ -98,7 +98,7 @@ func generateKeypair() (string, string, error) {
// BuildAllRepositoryFiles (re)builds all repository files for every available distributions, components and architectures
func BuildAllRepositoryFiles(ctx context.Context, ownerID int64) error {
pv, err := GetOrCreateRepositoryVersion(ownerID)
pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
if err != nil {
return err
}
@ -147,7 +147,7 @@ func BuildAllRepositoryFiles(ctx context.Context, ownerID int64) error {
// BuildSpecificRepositoryFiles builds index files for the repository
func BuildSpecificRepositoryFiles(ctx context.Context, ownerID int64, distribution, component, architecture string) error {
pv, err := GetOrCreateRepositoryVersion(ownerID)
pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
if err != nil {
return err
}
@ -234,6 +234,7 @@ func buildPackagesIndices(ctx context.Context, ownerID int64, repoVersion *packa
{"Packages.xz", packagesXzContent},
} {
_, err = packages_service.AddFileToPackageVersionInternal(
ctx,
repoVersion,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
@ -381,6 +382,7 @@ func buildReleaseFiles(ctx context.Context, ownerID int64, repoVersion *packages
{"InRelease", inReleaseContent},
} {
_, err = packages_service.AddFileToPackageVersionInternal(
ctx,
repoVersion,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{

View file

@ -66,28 +66,28 @@ type PackageFileCreationInfo struct {
}
// CreatePackageAndAddFile creates a package with a file. If the same package exists already, ErrDuplicatePackageVersion is returned
func CreatePackageAndAddFile(pvci *PackageCreationInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
return createPackageAndAddFile(pvci, pfci, false)
func CreatePackageAndAddFile(ctx context.Context, pvci *PackageCreationInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
return createPackageAndAddFile(ctx, pvci, pfci, false)
}
// CreatePackageOrAddFileToExisting creates a package with a file or adds the file if the package exists already
func CreatePackageOrAddFileToExisting(pvci *PackageCreationInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
return createPackageAndAddFile(pvci, pfci, true)
func CreatePackageOrAddFileToExisting(ctx context.Context, pvci *PackageCreationInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
return createPackageAndAddFile(ctx, pvci, pfci, true)
}
func createPackageAndAddFile(pvci *PackageCreationInfo, pfci *PackageFileCreationInfo, allowDuplicate bool) (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
ctx, committer, err := db.TxContext(db.DefaultContext)
func createPackageAndAddFile(ctx context.Context, pvci *PackageCreationInfo, pfci *PackageFileCreationInfo, allowDuplicate bool) (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
dbCtx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, nil, err
}
defer committer.Close()
pv, created, err := createPackageAndVersion(ctx, pvci, allowDuplicate)
pv, created, err := createPackageAndVersion(dbCtx, pvci, allowDuplicate)
if err != nil {
return nil, nil, err
}
pf, pb, blobCreated, err := addFileToPackageVersion(ctx, pv, &pvci.PackageInfo, pfci)
pf, pb, blobCreated, err := addFileToPackageVersion(dbCtx, pv, &pvci.PackageInfo, pfci)
removeBlob := false
defer func() {
if blobCreated && removeBlob {
@ -108,12 +108,12 @@ func createPackageAndAddFile(pvci *PackageCreationInfo, pfci *PackageFileCreatio
}
if created {
pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv)
pd, err := packages_model.GetPackageDescriptor(ctx, pv)
if err != nil {
return nil, nil, err
}
notify_service.PackageCreate(db.DefaultContext, pvci.Creator, pd)
notify_service.PackageCreate(ctx, pvci.Creator, pd)
}
return pv, pf, nil
@ -189,8 +189,8 @@ func createPackageAndVersion(ctx context.Context, pvci *PackageCreationInfo, all
}
// AddFileToExistingPackage adds a file to an existing package. If the package does not exist, ErrPackageNotExist is returned
func AddFileToExistingPackage(pvi *PackageInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageFile, error) {
return addFileToPackageWrapper(func(ctx context.Context) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error) {
func AddFileToExistingPackage(ctx context.Context, pvi *PackageInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageFile, error) {
return addFileToPackageWrapper(ctx, func(ctx context.Context) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error) {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, pvi.Owner.ID, pvi.PackageType, pvi.Name, pvi.Version)
if err != nil {
return nil, nil, false, err
@ -202,14 +202,14 @@ func AddFileToExistingPackage(pvi *PackageInfo, pfci *PackageFileCreationInfo) (
// AddFileToPackageVersionInternal adds a file to the package
// This method skips quota checks and should only be used for system-managed packages.
func AddFileToPackageVersionInternal(pv *packages_model.PackageVersion, pfci *PackageFileCreationInfo) (*packages_model.PackageFile, error) {
return addFileToPackageWrapper(func(ctx context.Context) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error) {
func AddFileToPackageVersionInternal(ctx context.Context, pv *packages_model.PackageVersion, pfci *PackageFileCreationInfo) (*packages_model.PackageFile, error) {
return addFileToPackageWrapper(ctx, func(ctx context.Context) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error) {
return addFileToPackageVersionUnchecked(ctx, pv, pfci)
})
}
func addFileToPackageWrapper(fn func(ctx context.Context) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error)) (*packages_model.PackageFile, error) {
ctx, committer, err := db.TxContext(db.DefaultContext)
func addFileToPackageWrapper(ctx context.Context, fn func(ctx context.Context) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error)) (*packages_model.PackageFile, error) {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return nil, err
}
@ -418,10 +418,10 @@ func CheckSizeQuotaExceeded(ctx context.Context, doer, owner *user_model.User, p
// GetOrCreateInternalPackageVersion gets or creates an internal package
// Some package types need such internal packages for housekeeping.
func GetOrCreateInternalPackageVersion(ownerID int64, packageType packages_model.Type, name, version string) (*packages_model.PackageVersion, error) {
func GetOrCreateInternalPackageVersion(ctx context.Context, ownerID int64, packageType packages_model.Type, name, version string) (*packages_model.PackageVersion, error) {
var pv *packages_model.PackageVersion
return pv, db.WithTx(db.DefaultContext, func(ctx context.Context) error {
return pv, db.WithTx(ctx, func(ctx context.Context) error {
p := &packages_model.Package{
OwnerID: ownerID,
Type: packageType,
@ -457,31 +457,31 @@ func GetOrCreateInternalPackageVersion(ownerID int64, packageType packages_model
}
// RemovePackageVersionByNameAndVersion deletes a package version and all associated files
func RemovePackageVersionByNameAndVersion(doer *user_model.User, pvi *PackageInfo) error {
pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, pvi.Owner.ID, pvi.PackageType, pvi.Name, pvi.Version)
func RemovePackageVersionByNameAndVersion(ctx context.Context, doer *user_model.User, pvi *PackageInfo) error {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, pvi.Owner.ID, pvi.PackageType, pvi.Name, pvi.Version)
if err != nil {
return err
}
return RemovePackageVersion(doer, pv)
return RemovePackageVersion(ctx, doer, pv)
}
// RemovePackageVersion deletes the package version and all associated files
func RemovePackageVersion(doer *user_model.User, pv *packages_model.PackageVersion) error {
ctx, committer, err := db.TxContext(db.DefaultContext)
func RemovePackageVersion(ctx context.Context, doer *user_model.User, pv *packages_model.PackageVersion) error {
dbCtx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
pd, err := packages_model.GetPackageDescriptor(ctx, pv)
pd, err := packages_model.GetPackageDescriptor(dbCtx, pv)
if err != nil {
return err
}
log.Trace("Deleting package: %v", pv.ID)
if err := DeletePackageVersionAndReferences(ctx, pv); err != nil {
if err := DeletePackageVersionAndReferences(dbCtx, pv); err != nil {
return err
}
@ -489,16 +489,16 @@ func RemovePackageVersion(doer *user_model.User, pv *packages_model.PackageVersi
return err
}
notify_service.PackageDelete(db.DefaultContext, doer, pd)
notify_service.PackageDelete(ctx, doer, pd)
return nil
}
// RemovePackageFileAndVersionIfUnreferenced deletes the package file and the version if there are no referenced files afterwards
func RemovePackageFileAndVersionIfUnreferenced(doer *user_model.User, pf *packages_model.PackageFile) error {
func RemovePackageFileAndVersionIfUnreferenced(ctx context.Context, doer *user_model.User, pf *packages_model.PackageFile) error {
var pd *packages_model.PackageDescriptor
if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error {
if err := db.WithTx(ctx, func(ctx context.Context) error {
if err := DeletePackageFile(ctx, pf); err != nil {
return err
}
@ -529,7 +529,7 @@ func RemovePackageFileAndVersionIfUnreferenced(doer *user_model.User, pf *packag
}
if pd != nil {
notify_service.PackageDelete(db.DefaultContext, doer, pd)
notify_service.PackageDelete(ctx, doer, pd)
}
return nil

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