From 7adc2de46404e32ed33f999d308ed56232cdfea5 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Mon, 9 Jan 2023 11:50:54 +0800 Subject: [PATCH] Use context parameter in models/git (#22367) After #22362, we can feel free to use transactions without `db.DefaultContext`. And there are still lots of models using `db.DefaultContext`, I think we should refactor them carefully and one by one. Co-authored-by: Lunny Xiao --- models/git/branches.go | 52 ++++++++++---------- models/git/branches_test.go | 20 ++++---- models/git/commit_status.go | 32 ++++++------ models/git/commit_status_test.go | 12 ++--- models/git/lfs.go | 34 ++++++------- models/git/lfs_lock.go | 20 ++++---- models/git/protected_tag.go | 12 ++--- models/issues/comment.go | 2 +- modules/context/repo.go | 4 +- modules/repository/repo.go | 8 +-- routers/api/v1/repo/branch.go | 4 +- routers/api/v1/repo/file.go | 2 +- routers/api/v1/repo/status.go | 2 +- routers/private/hook_pre_receive.go | 2 +- routers/web/repo/branch.go | 6 +-- routers/web/repo/commit.go | 6 +-- routers/web/repo/compare.go | 2 +- routers/web/repo/download.go | 2 +- routers/web/repo/issue.go | 4 +- routers/web/repo/lfs.go | 22 ++++----- routers/web/repo/pull.go | 2 +- routers/web/repo/setting_protected_branch.go | 6 +-- routers/web/repo/tag.go | 6 +-- routers/web/repo/view.go | 4 +- routers/web/repo/wiki.go | 2 +- services/convert/convert.go | 2 +- services/convert/status.go | 2 +- services/lfs/locks.go | 8 +-- services/lfs/server.go | 14 +++--- services/pull/lfs.go | 5 +- services/pull/update.go | 2 +- services/repository/branch.go | 6 +-- services/repository/files/commit.go | 2 +- services/repository/files/patch.go | 2 +- services/repository/files/update.go | 9 ++-- services/repository/files/upload.go | 7 +-- services/repository/lfs.go | 2 +- services/repository/push.go | 2 +- tests/integration/api_repo_lfs_test.go | 16 +++--- tests/integration/lfs_getobject_test.go | 4 +- tests/integration/repo_tag_test.go | 4 +- 41 files changed, 179 insertions(+), 176 deletions(-) diff --git a/models/git/branches.go b/models/git/branches.go index c02ab0a888..2becbc3d13 100644 --- a/models/git/branches.go +++ b/models/git/branches.go @@ -67,19 +67,19 @@ func (protectBranch *ProtectedBranch) IsProtected() bool { } // CanUserPush returns if some user could push to this protected branch -func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool { +func (protectBranch *ProtectedBranch) CanUserPush(ctx context.Context, userID int64) bool { if !protectBranch.CanPush { return false } if !protectBranch.EnableWhitelist { - if user, err := user_model.GetUserByID(db.DefaultContext, userID); err != nil { + if user, err := user_model.GetUserByID(ctx, userID); err != nil { log.Error("GetUserByID: %v", err) return false - } else if repo, err := repo_model.GetRepositoryByID(db.DefaultContext, protectBranch.RepoID); err != nil { + } else if repo, err := repo_model.GetRepositoryByID(ctx, protectBranch.RepoID); err != nil { log.Error("repo_model.GetRepositoryByID: %v", err) return false - } else if writeAccess, err := access_model.HasAccessUnit(db.DefaultContext, user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil { + } else if writeAccess, err := access_model.HasAccessUnit(ctx, user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil { log.Error("HasAccessUnit: %v", err) return false } else { @@ -95,7 +95,7 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool { return false } - in, err := organization.IsUserInTeams(db.DefaultContext, userID, protectBranch.WhitelistTeamIDs) + in, err := organization.IsUserInTeams(ctx, userID, protectBranch.WhitelistTeamIDs) if err != nil { log.Error("IsUserInTeams: %v", err) return false @@ -320,19 +320,19 @@ func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, prote } // GetProtectedBranches get all protected branches -func GetProtectedBranches(repoID int64) ([]*ProtectedBranch, error) { +func GetProtectedBranches(ctx context.Context, repoID int64) ([]*ProtectedBranch, error) { protectedBranches := make([]*ProtectedBranch, 0) - return protectedBranches, db.GetEngine(db.DefaultContext).Find(&protectedBranches, &ProtectedBranch{RepoID: repoID}) + return protectedBranches, db.GetEngine(ctx).Find(&protectedBranches, &ProtectedBranch{RepoID: repoID}) } // IsProtectedBranch checks if branch is protected -func IsProtectedBranch(repoID int64, branchName string) (bool, error) { +func IsProtectedBranch(ctx context.Context, repoID int64, branchName string) (bool, error) { protectedBranch := &ProtectedBranch{ RepoID: repoID, BranchName: branchName, } - has, err := db.GetEngine(db.DefaultContext).Exist(protectedBranch) + has, err := db.GetEngine(ctx).Exist(protectedBranch) if err != nil { return true, err } @@ -413,13 +413,13 @@ func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, curre } // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository. -func DeleteProtectedBranch(repoID, id int64) (err error) { +func DeleteProtectedBranch(ctx context.Context, repoID, id int64) (err error) { protectedBranch := &ProtectedBranch{ RepoID: repoID, ID: id, } - if affected, err := db.GetEngine(db.DefaultContext).Delete(protectedBranch); err != nil { + if affected, err := db.GetEngine(ctx).Delete(protectedBranch); err != nil { return err } else if affected != 1 { return fmt.Errorf("delete protected branch ID(%v) failed", id) @@ -440,7 +440,7 @@ type DeletedBranch struct { } // AddDeletedBranch adds a deleted branch to the database -func AddDeletedBranch(repoID int64, branchName, commit string, deletedByID int64) error { +func AddDeletedBranch(ctx context.Context, repoID int64, branchName, commit string, deletedByID int64) error { deletedBranch := &DeletedBranch{ RepoID: repoID, Name: branchName, @@ -448,20 +448,20 @@ func AddDeletedBranch(repoID int64, branchName, commit string, deletedByID int64 DeletedByID: deletedByID, } - _, err := db.GetEngine(db.DefaultContext).Insert(deletedBranch) + _, err := db.GetEngine(ctx).Insert(deletedBranch) return err } // GetDeletedBranches returns all the deleted branches -func GetDeletedBranches(repoID int64) ([]*DeletedBranch, error) { +func GetDeletedBranches(ctx context.Context, repoID int64) ([]*DeletedBranch, error) { deletedBranches := make([]*DeletedBranch, 0) - return deletedBranches, db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Desc("deleted_unix").Find(&deletedBranches) + return deletedBranches, db.GetEngine(ctx).Where("repo_id = ?", repoID).Desc("deleted_unix").Find(&deletedBranches) } // GetDeletedBranchByID get a deleted branch by its ID -func GetDeletedBranchByID(repoID, id int64) (*DeletedBranch, error) { +func GetDeletedBranchByID(ctx context.Context, repoID, id int64) (*DeletedBranch, error) { deletedBranch := &DeletedBranch{} - has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).And("id = ?", id).Get(deletedBranch) + has, err := db.GetEngine(ctx).Where("repo_id = ?", repoID).And("id = ?", id).Get(deletedBranch) if err != nil { return nil, err } @@ -472,13 +472,13 @@ func GetDeletedBranchByID(repoID, id int64) (*DeletedBranch, error) { } // RemoveDeletedBranchByID removes a deleted branch from the database -func RemoveDeletedBranchByID(repoID, id int64) (err error) { +func RemoveDeletedBranchByID(ctx context.Context, repoID, id int64) (err error) { deletedBranch := &DeletedBranch{ RepoID: repoID, ID: id, } - if affected, err := db.GetEngine(db.DefaultContext).Delete(deletedBranch); err != nil { + if affected, err := db.GetEngine(ctx).Delete(deletedBranch); err != nil { return err } else if affected != 1 { return fmt.Errorf("remove deleted branch ID(%v) failed", id) @@ -498,8 +498,8 @@ func (deletedBranch *DeletedBranch) LoadUser(ctx context.Context) { } // RemoveDeletedBranchByName removes all deleted branches -func RemoveDeletedBranchByName(repoID int64, branch string) error { - _, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch)) +func RemoveDeletedBranchByName(ctx context.Context, repoID int64, branch string) error { + _, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch)) return err } @@ -509,7 +509,7 @@ func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) { log.Trace("Doing: DeletedBranchesCleanup") deleteBefore := time.Now().Add(-olderThan) - _, err := db.GetEngine(db.DefaultContext).Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch)) + _, err := db.GetEngine(ctx).Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch)) if err != nil { log.Error("DeletedBranchesCleanup: %v", err) } @@ -526,19 +526,19 @@ type RenamedBranch struct { } // FindRenamedBranch check if a branch was renamed -func FindRenamedBranch(repoID int64, from string) (branch *RenamedBranch, exist bool, err error) { +func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *RenamedBranch, exist bool, err error) { branch = &RenamedBranch{ RepoID: repoID, From: from, } - exist, err = db.GetEngine(db.DefaultContext).Get(branch) + exist, err = db.GetEngine(ctx).Get(branch) return branch, exist, err } // RenameBranch rename a branch -func RenameBranch(repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/git/branches_test.go b/models/git/branches_test.go index 56f416622e..e26a16de03 100644 --- a/models/git/branches_test.go +++ b/models/git/branches_test.go @@ -20,15 +20,15 @@ func TestAddDeletedBranch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 1}) - assert.Error(t, git_model.AddDeletedBranch(repo.ID, firstBranch.Name, firstBranch.Commit, firstBranch.DeletedByID)) - assert.NoError(t, git_model.AddDeletedBranch(repo.ID, "test", "5655464564554545466464656", int64(1))) + assert.Error(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.Commit, firstBranch.DeletedByID)) + assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, "test", "5655464564554545466464656", int64(1))) } func TestGetDeletedBranches(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - branches, err := git_model.GetDeletedBranches(repo.ID) + branches, err := git_model.GetDeletedBranches(db.DefaultContext, repo.ID) assert.NoError(t, err) assert.Len(t, branches, 2) } @@ -65,7 +65,7 @@ func TestRemoveDeletedBranch(t *testing.T) { firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 1}) - err := git_model.RemoveDeletedBranchByID(repo.ID, 1) + err := git_model.RemoveDeletedBranchByID(db.DefaultContext, repo.ID, 1) assert.NoError(t, err) unittest.AssertNotExistsBean(t, firstBranch) unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 2}) @@ -74,7 +74,7 @@ func TestRemoveDeletedBranch(t *testing.T) { func getDeletedBranch(t *testing.T, branch *git_model.DeletedBranch) *git_model.DeletedBranch { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - deletedBranch, err := git_model.GetDeletedBranchByID(repo.ID, branch.ID) + deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo.ID, branch.ID) assert.NoError(t, err) assert.Equal(t, branch.ID, deletedBranch.ID) assert.Equal(t, branch.Name, deletedBranch.Name) @@ -86,12 +86,12 @@ func getDeletedBranch(t *testing.T, branch *git_model.DeletedBranch) *git_model. func TestFindRenamedBranch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - branch, exist, err := git_model.FindRenamedBranch(1, "dev") + branch, exist, err := git_model.FindRenamedBranch(db.DefaultContext, 1, "dev") assert.NoError(t, err) assert.Equal(t, true, exist) assert.Equal(t, "master", branch.To) - _, exist, err = git_model.FindRenamedBranch(1, "unknow") + _, exist, err = git_model.FindRenamedBranch(db.DefaultContext, 1, "unknow") assert.NoError(t, err) assert.Equal(t, false, exist) } @@ -110,7 +110,7 @@ func TestRenameBranch(t *testing.T) { }, git_model.WhitelistOptions{})) assert.NoError(t, committer.Commit()) - assert.NoError(t, git_model.RenameBranch(repo1, "master", "main", func(isDefault bool) error { + assert.NoError(t, git_model.RenameBranch(db.DefaultContext, repo1, "master", "main", func(isDefault bool) error { _isDefault = isDefault return nil })) @@ -144,7 +144,7 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { // is actually on repo with ID 1. repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - deletedBranch, err := git_model.GetDeletedBranchByID(repo2.ID, 1) + deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo2.ID, 1) // Expect no error, and the returned branch is nil. assert.NoError(t, err) @@ -154,7 +154,7 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { // This should return the deletedBranch. repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - deletedBranch, err = git_model.GetDeletedBranchByID(repo1.ID, 1) + deletedBranch, err = git_model.GetDeletedBranchByID(db.DefaultContext, repo1.ID, 1) // Expect no error, and the returned branch to be not nil. assert.NoError(t, err) diff --git a/models/git/commit_status.go b/models/git/commit_status.go index 07e0b9fb73..7c40b6d214 100644 --- a/models/git/commit_status.go +++ b/models/git/commit_status.go @@ -129,8 +129,8 @@ func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) { } // APIURL returns the absolute APIURL to this commit-status. -func (status *CommitStatus) APIURL() string { - _ = status.loadAttributes(db.DefaultContext) +func (status *CommitStatus) APIURL(ctx context.Context) string { + _ = status.loadAttributes(ctx) return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA) } @@ -162,7 +162,7 @@ type CommitStatusOptions struct { } // GetCommitStatuses returns all statuses for a given commit. -func GetCommitStatuses(repo *repo_model.Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) { +func GetCommitStatuses(ctx context.Context, repo *repo_model.Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) { if opts.Page <= 0 { opts.Page = 1 } @@ -170,7 +170,7 @@ func GetCommitStatuses(repo *repo_model.Repository, sha string, opts *CommitStat opts.Page = setting.ItemsPerPage } - countSession := listCommitStatusesStatement(repo, sha, opts) + countSession := listCommitStatusesStatement(ctx, repo, sha, opts) countSession = db.SetSessionPagination(countSession, opts) maxResults, err := countSession.Count(new(CommitStatus)) if err != nil { @@ -179,14 +179,14 @@ func GetCommitStatuses(repo *repo_model.Repository, sha string, opts *CommitStat } statuses := make([]*CommitStatus, 0, opts.PageSize) - findSession := listCommitStatusesStatement(repo, sha, opts) + findSession := listCommitStatusesStatement(ctx, repo, sha, opts) findSession = db.SetSessionPagination(findSession, opts) sortCommitStatusesSession(findSession, opts.SortType) return statuses, maxResults, findSession.Find(&statuses) } -func listCommitStatusesStatement(repo *repo_model.Repository, sha string, opts *CommitStatusOptions) *xorm.Session { - sess := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("sha = ?", sha) +func listCommitStatusesStatement(ctx context.Context, repo *repo_model.Repository, sha string, opts *CommitStatusOptions) *xorm.Session { + sess := db.GetEngine(ctx).Where("repo_id = ?", repo.ID).And("sha = ?", sha) switch opts.State { case "pending", "success", "error", "failure", "warning": sess.And("state = ?", opts.State) @@ -241,10 +241,10 @@ func GetLatestCommitStatus(ctx context.Context, repoID int64, sha string, listOp } // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts -func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) { +func FindRepoRecentCommitStatusContexts(ctx context.Context, repoID int64, before time.Duration) ([]string, error) { start := timeutil.TimeStampNow().AddDuration(-before) ids := make([]int64, 0, 10) - if err := db.GetEngine(db.DefaultContext).Table("commit_status"). + if err := db.GetEngine(ctx).Table("commit_status"). Where("repo_id = ?", repoID). And("updated_unix >= ?", start). Select("max( id ) as id"). @@ -257,7 +257,7 @@ func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]s if len(ids) == 0 { return contexts, nil } - return contexts, db.GetEngine(db.DefaultContext).Select("context").Table("commit_status").In("id", ids).Find(&contexts) + return contexts, db.GetEngine(ctx).Select("context").Table("commit_status").In("id", ids).Find(&contexts) } // NewCommitStatusOptions holds options for creating a CommitStatus @@ -269,7 +269,7 @@ type NewCommitStatusOptions struct { } // NewCommitStatus save commit statuses into database -func NewCommitStatus(opts NewCommitStatusOptions) error { +func NewCommitStatus(ctx context.Context, opts NewCommitStatusOptions) error { if opts.Repo == nil { return fmt.Errorf("NewCommitStatus[nil, %s]: no repository specified", opts.SHA) } @@ -283,7 +283,7 @@ func NewCommitStatus(opts NewCommitStatusOptions) error { return fmt.Errorf("NewCommitStatus[%s, %s]: invalid sha: %w", repoPath, opts.SHA, err) } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %w", opts.Repo.ID, opts.Creator.ID, opts.SHA, err) } @@ -322,14 +322,14 @@ type SignCommitWithStatuses struct { } // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state -func ParseCommitsWithStatus(oldCommits []*asymkey_model.SignCommit, repo *repo_model.Repository) []*SignCommitWithStatuses { +func ParseCommitsWithStatus(ctx context.Context, oldCommits []*asymkey_model.SignCommit, repo *repo_model.Repository) []*SignCommitWithStatuses { newCommits := make([]*SignCommitWithStatuses, 0, len(oldCommits)) for _, c := range oldCommits { commit := &SignCommitWithStatuses{ SignCommit: c, } - statuses, _, err := GetLatestCommitStatus(db.DefaultContext, repo.ID, commit.ID.String(), db.ListOptions{}) + statuses, _, err := GetLatestCommitStatus(ctx, repo.ID, commit.ID.String(), db.ListOptions{}) if err != nil { log.Error("GetLatestCommitStatus: %v", err) } else { @@ -348,8 +348,8 @@ func hashCommitStatusContext(context string) string { } // ConvertFromGitCommit converts git commits into SignCommitWithStatuses -func ConvertFromGitCommit(commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses { - return ParseCommitsWithStatus( +func ConvertFromGitCommit(ctx context.Context, commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses { + return ParseCommitsWithStatus(ctx, asymkey_model.ParseCommitsWithSignature( user_model.ValidateCommitsWithEmails(commits), repo.GetTrustModel(), diff --git a/models/git/commit_status_test.go b/models/git/commit_status_test.go index c829673014..2197433b3e 100644 --- a/models/git/commit_status_test.go +++ b/models/git/commit_status_test.go @@ -22,28 +22,28 @@ func TestGetCommitStatuses(t *testing.T) { sha1 := "1234123412341234123412341234123412341234" - statuses, maxResults, err := git_model.GetCommitStatuses(repo1, sha1, &git_model.CommitStatusOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 50}}) + statuses, maxResults, err := git_model.GetCommitStatuses(db.DefaultContext, repo1, sha1, &git_model.CommitStatusOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 50}}) assert.NoError(t, err) assert.Equal(t, int(maxResults), 5) assert.Len(t, statuses, 5) assert.Equal(t, "ci/awesomeness", statuses[0].Context) assert.Equal(t, structs.CommitStatusPending, statuses[0].State) - assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[0].APIURL()) + assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[0].APIURL(db.DefaultContext)) assert.Equal(t, "cov/awesomeness", statuses[1].Context) assert.Equal(t, structs.CommitStatusWarning, statuses[1].State) - assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[1].APIURL()) + assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[1].APIURL(db.DefaultContext)) assert.Equal(t, "cov/awesomeness", statuses[2].Context) assert.Equal(t, structs.CommitStatusSuccess, statuses[2].State) - assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[2].APIURL()) + assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[2].APIURL(db.DefaultContext)) assert.Equal(t, "ci/awesomeness", statuses[3].Context) assert.Equal(t, structs.CommitStatusFailure, statuses[3].State) - assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[3].APIURL()) + assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[3].APIURL(db.DefaultContext)) assert.Equal(t, "deploy/awesomeness", statuses[4].Context) assert.Equal(t, structs.CommitStatusError, statuses[4].State) - assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[4].APIURL()) + assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[4].APIURL(db.DefaultContext)) } diff --git a/models/git/lfs.go b/models/git/lfs.go index 8d418b928d..3494264688 100644 --- a/models/git/lfs.go +++ b/models/git/lfs.go @@ -135,10 +135,10 @@ var ErrLFSObjectNotExist = db.ErrNotExist{Resource: "LFS Meta object"} // NewLFSMetaObject stores a given populated LFSMetaObject structure in the database // if it is not already present. -func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) { +func NewLFSMetaObject(ctx context.Context, m *LFSMetaObject) (*LFSMetaObject, error) { var err error - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -164,13 +164,13 @@ func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) { // GetLFSMetaObjectByOid selects a LFSMetaObject entry from database by its OID. // It may return ErrLFSObjectNotExist or a database error. If the error is nil, // the returned pointer is a valid LFSMetaObject. -func GetLFSMetaObjectByOid(repoID int64, oid string) (*LFSMetaObject, error) { +func GetLFSMetaObjectByOid(ctx context.Context, repoID int64, oid string) (*LFSMetaObject, error) { if len(oid) == 0 { return nil, ErrLFSObjectNotExist } m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repoID} - has, err := db.GetEngine(db.DefaultContext).Get(m) + has, err := db.GetEngine(ctx).Get(m) if err != nil { return nil, err } else if !has { @@ -181,18 +181,18 @@ func GetLFSMetaObjectByOid(repoID int64, oid string) (*LFSMetaObject, error) { // RemoveLFSMetaObjectByOid removes a LFSMetaObject entry from database by its OID. // It may return ErrLFSObjectNotExist or a database error. -func RemoveLFSMetaObjectByOid(repoID int64, oid string) (int64, error) { - return RemoveLFSMetaObjectByOidFn(repoID, oid, nil) +func RemoveLFSMetaObjectByOid(ctx context.Context, repoID int64, oid string) (int64, error) { + return RemoveLFSMetaObjectByOidFn(ctx, repoID, oid, nil) } // RemoveLFSMetaObjectByOidFn removes a LFSMetaObject entry from database by its OID. // It may return ErrLFSObjectNotExist or a database error. It will run Fn with the current count within the transaction -func RemoveLFSMetaObjectByOidFn(repoID int64, oid string, fn func(count int64) error) (int64, error) { +func RemoveLFSMetaObjectByOidFn(ctx context.Context, repoID int64, oid string, fn func(count int64) error) (int64, error) { if len(oid) == 0 { return 0, ErrLFSObjectNotExist } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return 0, err } @@ -218,8 +218,8 @@ func RemoveLFSMetaObjectByOidFn(repoID int64, oid string, fn func(count int64) e } // GetLFSMetaObjects returns all LFSMetaObjects associated with a repository -func GetLFSMetaObjects(repoID int64, page, pageSize int) ([]*LFSMetaObject, error) { - sess := db.GetEngine(db.DefaultContext) +func GetLFSMetaObjects(ctx context.Context, repoID int64, page, pageSize int) ([]*LFSMetaObject, error) { + sess := db.GetEngine(ctx) if page >= 0 && pageSize > 0 { start := 0 @@ -233,18 +233,18 @@ func GetLFSMetaObjects(repoID int64, page, pageSize int) ([]*LFSMetaObject, erro } // CountLFSMetaObjects returns a count of all LFSMetaObjects associated with a repository -func CountLFSMetaObjects(repoID int64) (int64, error) { - return db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{RepositoryID: repoID}) +func CountLFSMetaObjects(ctx context.Context, repoID int64) (int64, error) { + return db.GetEngine(ctx).Count(&LFSMetaObject{RepositoryID: repoID}) } // LFSObjectAccessible checks if a provided Oid is accessible to the user -func LFSObjectAccessible(user *user_model.User, oid string) (bool, error) { +func LFSObjectAccessible(ctx context.Context, user *user_model.User, oid string) (bool, error) { if user.IsAdmin { - count, err := db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) + count, err := db.GetEngine(ctx).Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) return count > 0, err } cond := repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid) - count, err := db.GetEngine(db.DefaultContext).Where(cond).Join("INNER", "repository", "`lfs_meta_object`.repository_id = `repository`.id").Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) + count, err := db.GetEngine(ctx).Where(cond).Join("INNER", "repository", "`lfs_meta_object`.repository_id = `repository`.id").Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) return count > 0, err } @@ -254,8 +254,8 @@ func ExistsLFSObject(ctx context.Context, oid string) (bool, error) { } // LFSAutoAssociate auto associates accessible LFSMetaObjects -func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int64) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func LFSAutoAssociate(ctx context.Context, metas []*LFSMetaObject, user *user_model.User, repoID int64) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/git/lfs_lock.go b/models/git/lfs_lock.go index dc5b0a2ced..25480f3f96 100644 --- a/models/git/lfs_lock.go +++ b/models/git/lfs_lock.go @@ -42,8 +42,8 @@ func cleanPath(p string) string { } // CreateLFSLock creates a new lock. -func CreateLFSLock(repo *repo_model.Repository, lock *LFSLock) (*LFSLock, error) { - dbCtx, committer, err := db.TxContext(db.DefaultContext) +func CreateLFSLock(ctx context.Context, repo *repo_model.Repository, lock *LFSLock) (*LFSLock, error) { + dbCtx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -98,8 +98,8 @@ func GetLFSLockByID(ctx context.Context, id int64) (*LFSLock, error) { } // GetLFSLockByRepoID returns a list of locks of repository. -func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) { - e := db.GetEngine(db.DefaultContext) +func GetLFSLockByRepoID(ctx context.Context, repoID int64, page, pageSize int) ([]*LFSLock, error) { + e := db.GetEngine(ctx) if page >= 0 && pageSize > 0 { start := 0 if page > 0 { @@ -112,12 +112,12 @@ func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) { } // GetTreePathLock returns LSF lock for the treePath -func GetTreePathLock(repoID int64, treePath string) (*LFSLock, error) { +func GetTreePathLock(ctx context.Context, repoID int64, treePath string) (*LFSLock, error) { if !setting.LFS.StartServer { return nil, nil } - locks, err := GetLFSLockByRepoID(repoID, 0, 0) + locks, err := GetLFSLockByRepoID(ctx, repoID, 0, 0) if err != nil { return nil, err } @@ -130,13 +130,13 @@ func GetTreePathLock(repoID int64, treePath string) (*LFSLock, error) { } // CountLFSLockByRepoID returns a count of all LFSLocks associated with a repository. -func CountLFSLockByRepoID(repoID int64) (int64, error) { - return db.GetEngine(db.DefaultContext).Count(&LFSLock{RepoID: repoID}) +func CountLFSLockByRepoID(ctx context.Context, repoID int64) (int64, error) { + return db.GetEngine(ctx).Count(&LFSLock{RepoID: repoID}) } // DeleteLFSLockByID deletes a lock by given ID. -func DeleteLFSLockByID(id int64, repo *repo_model.Repository, u *user_model.User, force bool) (*LFSLock, error) { - dbCtx, committer, err := db.TxContext(db.DefaultContext) +func DeleteLFSLockByID(ctx context.Context, id int64, repo *repo_model.Repository, u *user_model.User, force bool) (*LFSLock, error) { + dbCtx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } diff --git a/models/git/protected_tag.go b/models/git/protected_tag.go index 1d32b11366..12e53a3331 100644 --- a/models/git/protected_tag.go +++ b/models/git/protected_tag.go @@ -57,14 +57,14 @@ func (pt *ProtectedTag) matchString(name string) bool { } // InsertProtectedTag inserts a protected tag to database -func InsertProtectedTag(pt *ProtectedTag) error { - _, err := db.GetEngine(db.DefaultContext).Insert(pt) +func InsertProtectedTag(ctx context.Context, pt *ProtectedTag) error { + _, err := db.GetEngine(ctx).Insert(pt) return err } // UpdateProtectedTag updates the protected tag -func UpdateProtectedTag(pt *ProtectedTag) error { - _, err := db.GetEngine(db.DefaultContext).ID(pt.ID).AllCols().Update(pt) +func UpdateProtectedTag(ctx context.Context, pt *ProtectedTag) error { + _, err := db.GetEngine(ctx).ID(pt.ID).AllCols().Update(pt) return err } @@ -98,9 +98,9 @@ func GetProtectedTags(ctx context.Context, repoID int64) ([]*ProtectedTag, error } // GetProtectedTagByID gets the protected tag with the specific id -func GetProtectedTagByID(id int64) (*ProtectedTag, error) { +func GetProtectedTagByID(ctx context.Context, id int64) (*ProtectedTag, error) { tag := new(ProtectedTag) - has, err := db.GetEngine(db.DefaultContext).ID(id).Get(tag) + has, err := db.GetEngine(ctx).ID(id).Get(tag) if err != nil { return nil, err } diff --git a/models/issues/comment.go b/models/issues/comment.go index 612f17aa5a..2dcbc7d819 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -772,7 +772,7 @@ func (c *Comment) LoadPushCommits(ctx context.Context) (err error) { } defer closer.Close() - c.Commits = git_model.ConvertFromGitCommit(gitRepo.GetCommitsFromIDs(data.CommitIDs), c.Issue.Repo) + c.Commits = git_model.ConvertFromGitCommit(ctx, gitRepo.GetCommitsFromIDs(data.CommitIDs), c.Issue.Repo) c.CommitsNum = int64(len(c.Commits)) } diff --git a/modules/context/repo.go b/modules/context/repo.go index d15d28cab7..dba20b48a0 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -126,7 +126,7 @@ func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.Use userCanPush := true requireSigned := false if protectedBranch != nil { - userCanPush = protectedBranch.CanUserPush(doer.ID) + userCanPush = protectedBranch.CanUserPush(ctx, doer.ID) requireSigned = protectedBranch.RequireSignedCommits } @@ -831,7 +831,7 @@ func getRefName(ctx *Context, pathType RepoRefType) string { if len(ref) == 0 { // maybe it's a renamed branch return getRefNameFromPath(ctx, path, func(s string) bool { - b, exist, err := git_model.FindRenamedBranch(ctx.Repo.Repository.ID, s) + b, exist, err := git_model.FindRenamedBranch(ctx, ctx.Repo.Repository.ID, s) if err != nil { log.Error("FindRenamedBranch", err) return false diff --git a/modules/repository/repo.go b/modules/repository/repo.go index a90eb8a764..d1a70e7c15 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -394,7 +394,7 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *repo_model.Re defer content.Close() - _, err := git_model.NewLFSMetaObject(&git_model.LFSMetaObject{Pointer: p, RepositoryID: repo.ID}) + _, err := git_model.NewLFSMetaObject(ctx, &git_model.LFSMetaObject{Pointer: p, RepositoryID: repo.ID}) if err != nil { log.Error("Repo[%-v]: Error creating LFS meta object %-v: %v", repo, p, err) return err @@ -402,7 +402,7 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *repo_model.Re if err := contentStore.Put(p, content); err != nil { log.Error("Repo[%-v]: Error storing content for LFS meta object %-v: %v", repo, p, err) - if _, err2 := git_model.RemoveLFSMetaObjectByOid(repo.ID, p.Oid); err2 != nil { + if _, err2 := git_model.RemoveLFSMetaObjectByOid(ctx, repo.ID, p.Oid); err2 != nil { log.Error("Repo[%-v]: Error removing LFS meta object %-v: %v", repo, p, err2) } return err @@ -421,7 +421,7 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *repo_model.Re var batch []lfs.Pointer for pointerBlob := range pointerChan { - meta, err := git_model.GetLFSMetaObjectByOid(repo.ID, pointerBlob.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(ctx, repo.ID, pointerBlob.Oid) if err != nil && err != git_model.ErrLFSObjectNotExist { log.Error("Repo[%-v]: Error querying LFS meta object %-v: %v", repo, pointerBlob.Pointer, err) return err @@ -441,7 +441,7 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *repo_model.Re if exist { log.Trace("Repo[%-v]: LFS object %-v already present; creating meta object", repo, pointerBlob.Pointer) - _, err := git_model.NewLFSMetaObject(&git_model.LFSMetaObject{Pointer: pointerBlob.Pointer, RepositoryID: repo.ID}) + _, err := git_model.NewLFSMetaObject(ctx, &git_model.LFSMetaObject{Pointer: pointerBlob.Pointer, RepositoryID: repo.ID}) if err != nil { log.Error("Repo[%-v]: Error creating LFS meta object %-v: %v", repo, pointerBlob.Pointer, err) return err diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 46fcc2fcd3..a46d2a2449 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -364,7 +364,7 @@ func ListBranchProtections(ctx *context.APIContext) { // "$ref": "#/responses/BranchProtectionList" repo := ctx.Repo.Repository - bps, err := git_model.GetProtectedBranches(repo.ID) + bps, err := git_model.GetProtectedBranches(ctx, repo.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetProtectedBranches", err) return @@ -820,7 +820,7 @@ func DeleteBranchProtection(ctx *context.APIContext) { return } - if err := git_model.DeleteProtectedBranch(ctx.Repo.Repository.ID, bp.ID); err != nil { + if err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository.ID, bp.ID); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteProtectedBranch", err) return } diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 623fe18e5d..d5e8924f5d 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -179,7 +179,7 @@ func GetRawFileOrLFS(ctx *context.APIContext) { } // Now check if there is a meta object for this pointer - meta, err := git_model.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(ctx, ctx.Repo.Repository.ID, pointer.Oid) // If there isn't one just serve the data directly if err == git_model.ErrLFSObjectNotExist { diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index 19f57b1cea..5158f38e14 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -188,7 +188,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) { listOptions := utils.GetListOptions(ctx) - statuses, maxResults, err := git_model.GetCommitStatuses(repo, sha, &git_model.CommitStatusOptions{ + statuses, maxResults, err := git_model.GetCommitStatuses(ctx, repo, sha, &git_model.CommitStatusOptions{ ListOptions: listOptions, SortType: ctx.FormTrim("sort"), State: ctx.FormTrim("state"), diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go index e49ae68a64..f58ed4ee4b 100644 --- a/routers/private/hook_pre_receive.go +++ b/routers/private/hook_pre_receive.go @@ -251,7 +251,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN if ctx.opts.DeployKeyID != 0 { canPush = !changedProtectedfiles && protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys) } else { - canPush = !changedProtectedfiles && protectBranch.CanUserPush(ctx.opts.UserID) + canPush = !changedProtectedfiles && protectBranch.CanUserPush(ctx, ctx.opts.UserID) } // 6. If we're not allowed to push directly diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index 18bb06ed1a..8b48d3fb00 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -120,7 +120,7 @@ func RestoreBranchPost(ctx *context.Context) { branchID := ctx.FormInt64("branch_id") branchName := ctx.FormString("name") - deletedBranch, err := git_model.GetDeletedBranchByID(ctx.Repo.Repository.ID, branchID) + deletedBranch, err := git_model.GetDeletedBranchByID(ctx, ctx.Repo.Repository.ID, branchID) if err != nil { log.Error("GetDeletedBranchByID: %v", err) ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName)) @@ -189,7 +189,7 @@ func loadBranches(ctx *context.Context, skip, limit int) (*Branch, []*Branch, in return nil, nil, 0 } - protectedBranches, err := git_model.GetProtectedBranches(ctx.Repo.Repository.ID) + protectedBranches, err := git_model.GetProtectedBranches(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("GetProtectedBranches", err) return nil, nil, 0 @@ -331,7 +331,7 @@ func loadOneBranch(ctx *context.Context, rawBranch, defaultBranch *git.Branch, p func getDeletedBranches(ctx *context.Context) ([]*Branch, error) { branches := []*Branch{} - deletedBranches, err := git_model.GetDeletedBranches(ctx.Repo.Repository.ID) + deletedBranches, err := git_model.GetDeletedBranches(ctx, ctx.Repo.Repository.ID) if err != nil { return branches, err } diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index 6eda3fca10..9f94159d0d 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -75,7 +75,7 @@ func Commits(ctx *context.Context) { ctx.ServerError("CommitsByRange", err) return } - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commits, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository) ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name @@ -194,7 +194,7 @@ func SearchCommits(ctx *context.Context) { return } ctx.Data["CommitCount"] = len(commits) - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commits, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository) ctx.Data["Keyword"] = query if all { @@ -235,7 +235,7 @@ func FileHistory(ctx *context.Context) { ctx.ServerError("CommitsByFileAndRange", err) return } - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commits, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository) ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index d95eeaecc9..8d45f8d674 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -636,7 +636,7 @@ func PrepareCompareDiff( return false } - commits := git_model.ConvertFromGitCommit(ci.CompareInfo.Commits, ci.HeadRepo) + commits := git_model.ConvertFromGitCommit(ctx, ci.CompareInfo.Commits, ci.HeadRepo) ctx.Data["Commits"] = commits ctx.Data["CommitCount"] = len(commits) diff --git a/routers/web/repo/download.go b/routers/web/repo/download.go index c1e9ba58b9..9e95f9dd0c 100644 --- a/routers/web/repo/download.go +++ b/routers/web/repo/download.go @@ -41,7 +41,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified time.Time pointer, _ := lfs.ReadPointer(dataRc) if pointer.IsValid() { - meta, _ := git_model.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) + meta, _ := git_model.GetLFSMetaObjectByOid(ctx, ctx.Repo.Repository.ID, pointer.Oid) if meta == nil { if err = dataRc.Close(); err != nil { log.Error("ServeBlobOrLFS: Close: %v", err) diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 100e343de4..07dd98f1a5 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -1604,7 +1604,7 @@ func ViewIssue(ctx *context.Context) { if perm.CanWrite(unit.TypeCode) { // Check if branch is not protected if pull.HeadBranch != pull.HeadRepo.DefaultBranch { - if protected, err := git_model.IsProtectedBranch(pull.HeadRepo.ID, pull.HeadBranch); err != nil { + if protected, err := git_model.IsProtectedBranch(ctx, pull.HeadRepo.ID, pull.HeadBranch); err != nil { log.Error("IsProtectedBranch: %v", err) } else if !protected { canDelete = true @@ -1688,7 +1688,7 @@ func ViewIssue(ctx *context.Context) { if pull.ProtectedBranch != nil { var showMergeInstructions bool if ctx.Doer != nil { - showMergeInstructions = pull.ProtectedBranch.CanUserPush(ctx.Doer.ID) + showMergeInstructions = pull.ProtectedBranch.CanUserPush(ctx, ctx.Doer.ID) } ctx.Data["IsBlockedByApprovals"] = !issues_model.HasEnoughApprovals(ctx, pull.ProtectedBranch, pull) ctx.Data["IsBlockedByRejection"] = issues_model.MergeBlockedByRejectedReview(ctx, pull.ProtectedBranch, pull) diff --git a/routers/web/repo/lfs.go b/routers/web/repo/lfs.go index 82e0055ab2..41d5edcdd8 100644 --- a/routers/web/repo/lfs.go +++ b/routers/web/repo/lfs.go @@ -48,7 +48,7 @@ func LFSFiles(ctx *context.Context) { if page <= 1 { page = 1 } - total, err := git_model.CountLFSMetaObjects(ctx.Repo.Repository.ID) + total, err := git_model.CountLFSMetaObjects(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("LFSFiles", err) return @@ -58,7 +58,7 @@ func LFSFiles(ctx *context.Context) { pager := context.NewPagination(int(total), setting.UI.ExplorePagingNum, page, 5) ctx.Data["Title"] = ctx.Tr("repo.settings.lfs") ctx.Data["PageIsSettingsLFS"] = true - lfsMetaObjects, err := git_model.GetLFSMetaObjects(ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) + lfsMetaObjects, err := git_model.GetLFSMetaObjects(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) if err != nil { ctx.ServerError("LFSFiles", err) return @@ -80,7 +80,7 @@ func LFSLocks(ctx *context.Context) { if page <= 1 { page = 1 } - total, err := git_model.CountLFSLockByRepoID(ctx.Repo.Repository.ID) + total, err := git_model.CountLFSLockByRepoID(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("LFSLocks", err) return @@ -90,7 +90,7 @@ func LFSLocks(ctx *context.Context) { pager := context.NewPagination(int(total), setting.UI.ExplorePagingNum, page, 5) ctx.Data["Title"] = ctx.Tr("repo.settings.lfs_locks") ctx.Data["PageIsSettingsLFS"] = true - lfsLocks, err := git_model.GetLFSLockByRepoID(ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) + lfsLocks, err := git_model.GetLFSLockByRepoID(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) if err != nil { ctx.ServerError("LFSLocks", err) return @@ -214,7 +214,7 @@ func LFSLockFile(ctx *context.Context) { return } - _, err := git_model.CreateLFSLock(ctx.Repo.Repository, &git_model.LFSLock{ + _, err := git_model.CreateLFSLock(ctx, ctx.Repo.Repository, &git_model.LFSLock{ Path: lockPath, OwnerID: ctx.Doer.ID, }) @@ -236,7 +236,7 @@ func LFSUnlock(ctx *context.Context) { ctx.NotFound("LFSUnlock", nil) return } - _, err := git_model.DeleteLFSLockByID(ctx.ParamsInt64("lid"), ctx.Repo.Repository, ctx.Doer, true) + _, err := git_model.DeleteLFSLockByID(ctx, ctx.ParamsInt64("lid"), ctx.Repo.Repository, ctx.Doer, true) if err != nil { ctx.ServerError("LFSUnlock", err) return @@ -261,7 +261,7 @@ func LFSFileGet(ctx *context.Context) { ctx.Data["Title"] = oid ctx.Data["PageIsSettingsLFS"] = true - meta, err := git_model.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, oid) + meta, err := git_model.GetLFSMetaObjectByOid(ctx, ctx.Repo.Repository.ID, oid) if err != nil { if err == git_model.ErrLFSObjectNotExist { ctx.NotFound("LFSFileGet", nil) @@ -355,7 +355,7 @@ func LFSDelete(ctx *context.Context) { return } - count, err := git_model.RemoveLFSMetaObjectByOid(ctx.Repo.Repository.ID, oid) + count, err := git_model.RemoveLFSMetaObjectByOid(ctx, ctx.Repo.Repository.ID, oid) if err != nil { ctx.ServerError("LFSDelete", err) return @@ -454,7 +454,7 @@ func LFSPointerFiles(ctx *context.Context) { Size: pointerBlob.Size, } - if _, err := git_model.GetLFSMetaObjectByOid(repo.ID, pointerBlob.Oid); err != nil { + if _, err := git_model.GetLFSMetaObjectByOid(ctx, repo.ID, pointerBlob.Oid); err != nil { if err != git_model.ErrLFSObjectNotExist { return err } @@ -472,7 +472,7 @@ func LFSPointerFiles(ctx *context.Context) { // Can we fix? // OK well that's "simple" // - we need to check whether current user has access to a repo that has access to the file - result.Associatable, err = git_model.LFSObjectAccessible(ctx.Doer, pointerBlob.Oid) + result.Associatable, err = git_model.LFSObjectAccessible(ctx, ctx.Doer, pointerBlob.Oid) if err != nil { return err } @@ -547,7 +547,7 @@ func LFSAutoAssociate(ctx *context.Context) { metas[i].Oid = oid[:idx] // metas[i].RepositoryID = ctx.Repo.Repository.ID } - if err := git_model.LFSAutoAssociate(metas, ctx.Doer, ctx.Repo.Repository.ID); err != nil { + if err := git_model.LFSAutoAssociate(ctx, metas, ctx.Doer, ctx.Repo.Repository.ID); err != nil { ctx.ServerError("LFSAutoAssociate", err) return } diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index a18f9f6a56..c0fab2cead 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -659,7 +659,7 @@ func ViewPullCommits(ctx *context.Context) { ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name - commits := git_model.ConvertFromGitCommit(prInfo.Commits, ctx.Repo.Repository) + commits := git_model.ConvertFromGitCommit(ctx, prInfo.Commits, ctx.Repo.Repository) ctx.Data["Commits"] = commits ctx.Data["CommitCount"] = len(commits) diff --git a/routers/web/repo/setting_protected_branch.go b/routers/web/repo/setting_protected_branch.go index 975873a9ef..e0467a23e6 100644 --- a/routers/web/repo/setting_protected_branch.go +++ b/routers/web/repo/setting_protected_branch.go @@ -31,7 +31,7 @@ func ProtectedBranch(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsBranches"] = true - protectedBranches, err := git_model.GetProtectedBranches(ctx.Repo.Repository.ID) + protectedBranches, err := git_model.GetProtectedBranches(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("GetProtectedBranches", err) return @@ -134,7 +134,7 @@ func SettingsProtectedBranch(c *context.Context) { c.Data["whitelist_users"] = strings.Join(base.Int64sToStrings(protectBranch.WhitelistUserIDs), ",") c.Data["merge_whitelist_users"] = strings.Join(base.Int64sToStrings(protectBranch.MergeWhitelistUserIDs), ",") c.Data["approvals_whitelist_users"] = strings.Join(base.Int64sToStrings(protectBranch.ApprovalsWhitelistUserIDs), ",") - contexts, _ := git_model.FindRepoRecentCommitStatusContexts(c.Repo.Repository.ID, 7*24*time.Hour) // Find last week status check contexts + contexts, _ := git_model.FindRepoRecentCommitStatusContexts(c, c.Repo.Repository.ID, 7*24*time.Hour) // Find last week status check contexts for _, ctx := range protectBranch.StatusCheckContexts { var found bool for i := range contexts { @@ -281,7 +281,7 @@ func SettingsProtectedBranchPost(ctx *context.Context) { ctx.Redirect(fmt.Sprintf("%s/settings/branches/%s", ctx.Repo.RepoLink, util.PathEscapeSegments(branch))) } else { if protectBranch != nil { - if err := git_model.DeleteProtectedBranch(ctx.Repo.Repository.ID, protectBranch.ID); err != nil { + if err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository.ID, protectBranch.ID); err != nil { ctx.ServerError("DeleteProtectedBranch", err) return } diff --git a/routers/web/repo/tag.go b/routers/web/repo/tag.go index 26df1dbf6c..aa9edc7375 100644 --- a/routers/web/repo/tag.go +++ b/routers/web/repo/tag.go @@ -54,7 +54,7 @@ func NewProtectedTagPost(ctx *context.Context) { pt.AllowlistTeamIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistTeams, ",")) } - if err := git_model.InsertProtectedTag(pt); err != nil { + if err := git_model.InsertProtectedTag(ctx, pt); err != nil { ctx.ServerError("InsertProtectedTag", err) return } @@ -107,7 +107,7 @@ func EditProtectedTagPost(ctx *context.Context) { pt.AllowlistUserIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistUsers, ",")) pt.AllowlistTeamIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistTeams, ",")) - if err := git_model.UpdateProtectedTag(pt); err != nil { + if err := git_model.UpdateProtectedTag(ctx, pt); err != nil { ctx.ServerError("UpdateProtectedTag", err) return } @@ -168,7 +168,7 @@ func selectProtectedTagByContext(ctx *context.Context) *git_model.ProtectedTag { id = ctx.ParamsInt64(":id") } - tag, err := git_model.GetProtectedTagByID(id) + tag, err := git_model.GetProtectedTagByID(ctx, id) if err != nil { ctx.ServerError("GetProtectedTagByID", err) return nil diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 915944e4d5..769e4e895c 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -271,7 +271,7 @@ func getFileReader(repoID int64, blob *git.Blob) ([]byte, io.ReadCloser, *fileIn return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil } - meta, err := git_model.GetLFSMetaObjectByOid(repoID, pointer.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repoID, pointer.Oid) if err != nil && err != git_model.ErrLFSObjectNotExist { // fallback to plain file return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil } @@ -412,7 +412,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st } // Check LFS Lock - lfsLock, err := git_model.GetTreePathLock(ctx.Repo.Repository.ID, ctx.Repo.TreePath) + lfsLock, err := git_model.GetTreePathLock(ctx, ctx.Repo.Repository.ID, ctx.Repo.TreePath) ctx.Data["LFSLock"] = lfsLock if err != nil { ctx.ServerError("GetTreePathLock", err) diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go index b50a4be802..fe2becb7bb 100644 --- a/routers/web/repo/wiki.go +++ b/routers/web/repo/wiki.go @@ -368,7 +368,7 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) ctx.ServerError("CommitsByFileAndRange", err) return nil, nil } - ctx.Data["Commits"] = git_model.ConvertFromGitCommit(commitsHistory, ctx.Repo.Repository) + ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commitsHistory, ctx.Repo.Repository) pager := context.NewPagination(int(commitsCount), setting.Git.CommitsRangeSize, page, 5) pager.SetDefaultParams(ctx) diff --git a/services/convert/convert.go b/services/convert/convert.go index a8329f5285..2ce51bf063 100644 --- a/services/convert/convert.go +++ b/services/convert/convert.go @@ -87,7 +87,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git if err != nil { return nil, err } - branch.UserCanPush = bp.CanUserPush(user.ID) + branch.UserCanPush = bp.CanUserPush(db.DefaultContext, user.ID) branch.UserCanMerge = git_model.IsUserMergeWhitelisted(db.DefaultContext, bp, user.ID, permission) } diff --git a/services/convert/status.go b/services/convert/status.go index 5fcf04074f..84ca1665d2 100644 --- a/services/convert/status.go +++ b/services/convert/status.go @@ -20,7 +20,7 @@ func ToCommitStatus(ctx context.Context, status *git_model.CommitStatus) *api.Co TargetURL: status.TargetURL, Description: status.Description, ID: status.Index, - URL: status.APIURL(), + URL: status.APIURL(ctx), Context: status.Context, } diff --git a/services/lfs/locks.go b/services/lfs/locks.go index d5fe3f4e31..d963d9ab57 100644 --- a/services/lfs/locks.go +++ b/services/lfs/locks.go @@ -106,7 +106,7 @@ func GetListLockHandler(ctx *context.Context) { } // If no query params path or id - lockList, err := git_model.GetLFSLockByRepoID(repository.ID, cursor, limit) + lockList, err := git_model.GetLFSLockByRepoID(ctx, repository.ID, cursor, limit) if err != nil { log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err) ctx.JSON(http.StatusInternalServerError, api.LFSLockError{ @@ -167,7 +167,7 @@ func PostLockHandler(ctx *context.Context) { return } - lock, err := git_model.CreateLFSLock(repository, &git_model.LFSLock{ + lock, err := git_model.CreateLFSLock(ctx, repository, &git_model.LFSLock{ Path: req.Path, OwnerID: ctx.Doer.ID, }) @@ -233,7 +233,7 @@ func VerifyLockHandler(ctx *context.Context) { } else if limit < 0 { limit = 0 } - lockList, err := git_model.GetLFSLockByRepoID(repository.ID, cursor, limit) + lockList, err := git_model.GetLFSLockByRepoID(ctx, repository.ID, cursor, limit) if err != nil { log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err) ctx.JSON(http.StatusInternalServerError, api.LFSLockError{ @@ -300,7 +300,7 @@ func UnLockHandler(ctx *context.Context) { return } - lock, err := git_model.DeleteLFSLockByID(ctx.ParamsInt64("lid"), repository, ctx.Doer, req.Force) + lock, err := git_model.DeleteLFSLockByID(ctx, ctx.ParamsInt64("lid"), repository, ctx.Doer, req.Force) if err != nil { if git_model.IsErrLFSUnauthorizedAction(err) { ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") diff --git a/services/lfs/server.go b/services/lfs/server.go index 8fd2759132..320c8e7281 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -197,7 +197,7 @@ func BatchHandler(ctx *context.Context) { return } - meta, err := git_model.GetLFSMetaObjectByOid(repository.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(ctx, repository.ID, p.Oid) if err != nil && err != git_model.ErrLFSObjectNotExist { log.Error("Unable to get LFS MetaObject [%s] for %s/%s. Error: %v", p.Oid, rc.User, rc.Repo, err) writeStatus(ctx, http.StatusInternalServerError) @@ -223,14 +223,14 @@ func BatchHandler(ctx *context.Context) { } if exists && meta == nil { - accessible, err := git_model.LFSObjectAccessible(ctx.Doer, p.Oid) + accessible, err := git_model.LFSObjectAccessible(ctx, ctx.Doer, p.Oid) if err != nil { log.Error("Unable to check if LFS MetaObject [%s] is accessible. Error: %v", p.Oid, err) writeStatus(ctx, http.StatusInternalServerError) return } if accessible { - _, err := git_model.NewLFSMetaObject(&git_model.LFSMetaObject{Pointer: p, RepositoryID: repository.ID}) + _, err := git_model.NewLFSMetaObject(ctx, &git_model.LFSMetaObject{Pointer: p, RepositoryID: repository.ID}) if err != nil { log.Error("Unable to create LFS MetaObject [%s] for %s/%s. Error: %v", p.Oid, rc.User, rc.Repo, err) writeStatus(ctx, http.StatusInternalServerError) @@ -297,7 +297,7 @@ func UploadHandler(ctx *context.Context) { uploadOrVerify := func() error { if exists { - accessible, err := git_model.LFSObjectAccessible(ctx.Doer, p.Oid) + accessible, err := git_model.LFSObjectAccessible(ctx, ctx.Doer, p.Oid) if err != nil { log.Error("Unable to check if LFS MetaObject [%s] is accessible. Error: %v", p.Oid, err) return err @@ -323,7 +323,7 @@ func UploadHandler(ctx *context.Context) { log.Error("Error putting LFS MetaObject [%s] into content store. Error: %v", p.Oid, err) return err } - _, err := git_model.NewLFSMetaObject(&git_model.LFSMetaObject{Pointer: p, RepositoryID: repository.ID}) + _, err := git_model.NewLFSMetaObject(ctx, &git_model.LFSMetaObject{Pointer: p, RepositoryID: repository.ID}) return err } @@ -335,7 +335,7 @@ func UploadHandler(ctx *context.Context) { } else { writeStatus(ctx, http.StatusInternalServerError) } - if _, err = git_model.RemoveLFSMetaObjectByOid(repository.ID, p.Oid); err != nil { + if _, err = git_model.RemoveLFSMetaObjectByOid(ctx, repository.ID, p.Oid); err != nil { log.Error("Error whilst removing metaobject for LFS OID[%s]: %v", p.Oid, err) } return @@ -398,7 +398,7 @@ func getAuthenticatedMeta(ctx *context.Context, rc *requestContext, p lfs_module return nil } - meta, err := git_model.GetLFSMetaObjectByOid(repository.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(ctx, repository.ID, p.Oid) if err != nil { log.Error("Unable to get LFS OID[%s] Error: %v", p.Oid, err) writeStatus(ctx, http.StatusNotFound) diff --git a/services/pull/lfs.go b/services/pull/lfs.go index 4b9826bedd..dc4ca006e4 100644 --- a/services/pull/lfs.go +++ b/services/pull/lfs.go @@ -11,6 +11,7 @@ import ( "strconv" "sync" + "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/modules/git/pipeline" @@ -115,7 +116,7 @@ func createLFSMetaObjectsFromCatFileBatch(catFileBatchReader *io.PipeReader, wg } // Then we need to check that this pointer is in the db - if _, err := git_model.GetLFSMetaObjectByOid(pr.HeadRepo.ID, pointer.Oid); err != nil { + if _, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, pr.HeadRepo.ID, pointer.Oid); err != nil { if err == git_model.ErrLFSObjectNotExist { log.Warn("During merge of: %d in %-v, there is a pointer to LFS Oid: %s which although present in the LFS store is not associated with the head repo %-v", pr.Index, pr.BaseRepo, pointer.Oid, pr.HeadRepo) continue @@ -128,7 +129,7 @@ func createLFSMetaObjectsFromCatFileBatch(catFileBatchReader *io.PipeReader, wg // Therefore it should be associated with the base repo meta := &git_model.LFSMetaObject{Pointer: pointer} meta.RepositoryID = pr.BaseRepoID - if _, err := git_model.NewLFSMetaObject(meta); err != nil { + if _, err := git_model.NewLFSMetaObject(db.DefaultContext, meta); err != nil { _ = catFileBatchReader.CloseWithError(err) break } diff --git a/services/pull/update.go b/services/pull/update.go index e09dbf6244..6f976140c5 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -115,7 +115,7 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest, } // Update function need push permission - if pr.ProtectedBranch != nil && !pr.ProtectedBranch.CanUserPush(user.ID) { + if pr.ProtectedBranch != nil && !pr.ProtectedBranch.CanUserPush(ctx, user.ID) { return false, false, nil } diff --git a/services/repository/branch.go b/services/repository/branch.go index e5ffbbeb74..8717fee23b 100644 --- a/services/repository/branch.go +++ b/services/repository/branch.go @@ -119,7 +119,7 @@ func RenameBranch(repo *repo_model.Repository, doer *user_model.User, gitRepo *g return "from_not_exist", nil } - if err := git_model.RenameBranch(repo, from, to, func(isDefault bool) error { + if err := git_model.RenameBranch(db.DefaultContext, repo, from, to, func(isDefault bool) error { err2 := gitRepo.RenameBranch(from, to) if err2 != nil { return err2 @@ -159,7 +159,7 @@ func DeleteBranch(doer *user_model.User, repo *repo_model.Repository, gitRepo *g return ErrBranchIsDefault } - isProtected, err := git_model.IsProtectedBranch(repo.ID, branchName) + isProtected, err := git_model.IsProtectedBranch(db.DefaultContext, repo.ID, branchName) if err != nil { return err } @@ -197,7 +197,7 @@ func DeleteBranch(doer *user_model.User, repo *repo_model.Repository, gitRepo *g log.Error("Update: %v", err) } - if err := git_model.AddDeletedBranch(repo.ID, branchName, commit.ID.String(), doer.ID); err != nil { + if err := git_model.AddDeletedBranch(db.DefaultContext, repo.ID, branchName, commit.ID.String(), doer.ID); err != nil { log.Warn("AddDeletedBranch: %v", err) } diff --git a/services/repository/files/commit.go b/services/repository/files/commit.go index 74f9eb868d..9d237f1e22 100644 --- a/services/repository/files/commit.go +++ b/services/repository/files/commit.go @@ -38,7 +38,7 @@ func CreateCommitStatus(ctx context.Context, repo *repo_model.Repository, creato } gitRepo.Close() - if err := git_model.NewCommitStatus(git_model.NewCommitStatusOptions{ + if err := git_model.NewCommitStatus(ctx, git_model.NewCommitStatusOptions{ Repo: repo, Creator: creator, SHA: sha, diff --git a/services/repository/files/patch.go b/services/repository/files/patch.go index b5eef8c091..33f4b6c9dc 100644 --- a/services/repository/files/patch.go +++ b/services/repository/files/patch.go @@ -70,7 +70,7 @@ func (opts *ApplyDiffPatchOptions) Validate(ctx context.Context, repo *repo_mode if err != nil { return err } - if protectedBranch != nil && !protectedBranch.CanUserPush(doer.ID) { + if protectedBranch != nil && !protectedBranch.CanUserPush(ctx, doer.ID) { return models.ErrUserCannotCommit{ UserName: doer.LowerName, } diff --git a/services/repository/files/update.go b/services/repository/files/update.go index f7a41ef24c..30cfd9e2dd 100644 --- a/services/repository/files/update.go +++ b/services/repository/files/update.go @@ -12,6 +12,7 @@ import ( "time" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -75,7 +76,7 @@ func detectEncodingAndBOM(entry *git.TreeEntry, repo *repo_model.Repository) (st if setting.LFS.StartServer { pointer, _ := lfs.ReadPointerFromBuffer(buf) if pointer.IsValid() { - meta, err := git_model.GetLFSMetaObjectByOid(repo.ID, pointer.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, pointer.Oid) if err != nil && err != git_model.ErrLFSObjectNotExist { // return default return "UTF-8", false @@ -423,7 +424,7 @@ func CreateOrUpdateRepoFile(ctx context.Context, repo *repo_model.Repository, do if lfsMetaObject != nil { // We have an LFS object - create it - lfsMetaObject, err = git_model.NewLFSMetaObject(lfsMetaObject) + lfsMetaObject, err = git_model.NewLFSMetaObject(ctx, lfsMetaObject) if err != nil { return nil, err } @@ -434,7 +435,7 @@ func CreateOrUpdateRepoFile(ctx context.Context, repo *repo_model.Repository, do } if !exist { if err := contentStore.Put(lfsMetaObject.Pointer, strings.NewReader(opts.Content)); err != nil { - if _, err2 := git_model.RemoveLFSMetaObjectByOid(repo.ID, lfsMetaObject.Oid); err2 != nil { + if _, err2 := git_model.RemoveLFSMetaObjectByOid(ctx, repo.ID, lfsMetaObject.Oid); err2 != nil { return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %w)", lfsMetaObject.Oid, err2, err) } return nil, err @@ -472,7 +473,7 @@ func VerifyBranchProtection(ctx context.Context, repo *repo_model.Repository, do if len(glob) != 0 { isUnprotectedFile = protectedBranch.IsUnprotectedFile(glob, treePath) } - if !protectedBranch.CanUserPush(doer.ID) && !isUnprotectedFile { + if !protectedBranch.CanUserPush(ctx, doer.ID) && !isUnprotectedFile { return models.ErrUserCannotCommit{ UserName: doer.LowerName, } diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index 240564d401..e7289dd60d 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -10,6 +10,7 @@ import ( "path" "strings" + "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -40,7 +41,7 @@ func cleanUpAfterFailure(infos *[]uploadInfo, t *TemporaryUploadRepository, orig continue } if !info.lfsMetaObject.Existing { - if _, err := git_model.RemoveLFSMetaObjectByOid(t.repo.ID, info.lfsMetaObject.Oid); err != nil { + if _, err := git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, t.repo.ID, info.lfsMetaObject.Oid); err != nil { original = fmt.Errorf("%w, %v", original, err) // We wrap the original error - as this is the underlying error that required the fallback } } @@ -64,7 +65,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use for i, upload := range uploads { // Check file is not lfs locked, will return nil if lock setting not enabled filepath := path.Join(opts.TreePath, upload.Name) - lfsLock, err := git_model.GetTreePathLock(repo.ID, filepath) + lfsLock, err := git_model.GetTreePathLock(ctx, repo.ID, filepath) if err != nil { return err } @@ -132,7 +133,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use if infos[i].lfsMetaObject == nil { continue } - infos[i].lfsMetaObject, err = git_model.NewLFSMetaObject(infos[i].lfsMetaObject) + infos[i].lfsMetaObject, err = git_model.NewLFSMetaObject(ctx, infos[i].lfsMetaObject) if err != nil { // OK Now we need to cleanup return cleanUpAfterFailure(&infos, t, err) diff --git a/services/repository/lfs.go b/services/repository/lfs.go index 0e88d359a8..7806e20a9f 100644 --- a/services/repository/lfs.go +++ b/services/repository/lfs.go @@ -74,7 +74,7 @@ func GarbageCollectLFSMetaObjectsForRepo(ctx context.Context, repo *repo_model.R return nil } // Non-existent pointer file - _, err = git_model.RemoveLFSMetaObjectByOidFn(repo.ID, metaObject.Oid, func(count int64) error { + _, err = git_model.RemoveLFSMetaObjectByOidFn(ctx, repo.ID, metaObject.Oid, func(count int64) error { if count > 0 { return nil } diff --git a/services/repository/push.go b/services/repository/push.go index f1eedb8e08..dc8d564cb4 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -251,7 +251,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { notification.NotifyPushCommits(db.DefaultContext, pusher, repo, opts, commits) - if err = git_model.RemoveDeletedBranchByName(repo.ID, branch); err != nil { + if err = git_model.RemoveDeletedBranchByName(ctx, repo.ID, branch); err != nil { log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, branch, err) } diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index 73599242db..c0ceaa8ba8 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -77,7 +77,7 @@ func TestAPILFSBatch(t *testing.T) { content := []byte("dummy1") oid := storeObjectInRepo(t, repo.ID, &content) - defer git_model.RemoveLFSMetaObjectByOid(repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) session := loginUser(t, "user2") @@ -261,7 +261,7 @@ func TestAPILFSBatch(t *testing.T) { content := []byte("dummy0") storeObjectInRepo(t, repo2.ID, &content) - meta, err := git_model.GetLFSMetaObjectByOid(repo.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) assert.Nil(t, meta) assert.Equal(t, git_model.ErrLFSObjectNotExist, err) @@ -276,7 +276,7 @@ func TestAPILFSBatch(t *testing.T) { assert.Nil(t, br.Objects[0].Error) assert.Empty(t, br.Objects[0].Actions) - meta, err = git_model.GetLFSMetaObjectByOid(repo.ID, p.Oid) + meta, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) assert.NoError(t, err) assert.NotNil(t, meta) @@ -337,7 +337,7 @@ func TestAPILFSUpload(t *testing.T) { content := []byte("dummy3") oid := storeObjectInRepo(t, repo.ID, &content) - defer git_model.RemoveLFSMetaObjectByOid(repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) session := loginUser(t, "user2") @@ -366,7 +366,7 @@ func TestAPILFSUpload(t *testing.T) { err = contentStore.Put(p, bytes.NewReader([]byte("dummy5"))) assert.NoError(t, err) - meta, err := git_model.GetLFSMetaObjectByOid(repo.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) assert.Nil(t, meta) assert.Equal(t, git_model.ErrLFSObjectNotExist, err) @@ -379,7 +379,7 @@ func TestAPILFSUpload(t *testing.T) { req := newRequest(t, p, "dummy5") session.MakeRequest(t, req, http.StatusOK) - meta, err = git_model.GetLFSMetaObjectByOid(repo.ID, p.Oid) + meta, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) assert.NoError(t, err) assert.NotNil(t, meta) }) @@ -427,7 +427,7 @@ func TestAPILFSUpload(t *testing.T) { assert.NoError(t, err) assert.True(t, exist) - meta, err := git_model.GetLFSMetaObjectByOid(repo.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) assert.NoError(t, err) assert.NotNil(t, meta) }) @@ -442,7 +442,7 @@ func TestAPILFSVerify(t *testing.T) { content := []byte("dummy3") oid := storeObjectInRepo(t, repo.ID, &content) - defer git_model.RemoveLFSMetaObjectByOid(repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) session := loginUser(t, "user2") diff --git a/tests/integration/lfs_getobject_test.go b/tests/integration/lfs_getobject_test.go index a191bcb61c..7b1b3e109c 100644 --- a/tests/integration/lfs_getobject_test.go +++ b/tests/integration/lfs_getobject_test.go @@ -28,7 +28,7 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string pointer, err := lfs.GeneratePointer(bytes.NewReader(*content)) assert.NoError(t, err) - _, err = git_model.NewLFSMetaObject(&git_model.LFSMetaObject{Pointer: pointer, RepositoryID: repositoryID}) + _, err = git_model.NewLFSMetaObject(db.DefaultContext, &git_model.LFSMetaObject{Pointer: pointer, RepositoryID: repositoryID}) assert.NoError(t, err) contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(pointer) @@ -44,7 +44,7 @@ func storeAndGetLfs(t *testing.T, content *[]byte, extraHeader *http.Header, exp repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") assert.NoError(t, err) oid := storeObjectInRepo(t, repo.ID, content) - defer git_model.RemoveLFSMetaObjectByOid(repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) session := loginUser(t, "user2") diff --git a/tests/integration/repo_tag_test.go b/tests/integration/repo_tag_test.go index 5ea9392a99..8667a6d6e9 100644 --- a/tests/integration/repo_tag_test.go +++ b/tests/integration/repo_tag_test.go @@ -32,12 +32,12 @@ func TestCreateNewTagProtected(t *testing.T) { err := release.CreateNewTag(git.DefaultContext, owner, repo, "master", "v-1", "first tag") assert.NoError(t, err) - err = git_model.InsertProtectedTag(&git_model.ProtectedTag{ + err = git_model.InsertProtectedTag(db.DefaultContext, &git_model.ProtectedTag{ RepoID: repo.ID, NamePattern: "v-*", }) assert.NoError(t, err) - err = git_model.InsertProtectedTag(&git_model.ProtectedTag{ + err = git_model.InsertProtectedTag(db.DefaultContext, &git_model.ProtectedTag{ RepoID: repo.ID, NamePattern: "v-1.1", AllowlistUserIDs: []int64{repo.OwnerID},