Template
1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo synced 2024-11-22 18:04:24 +01:00

Even more db.DefaultContext refactor (#27352)

Part of #27065

---------

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: delvh <dev.lh@web.de>
This commit is contained in:
JakobDev 2023-10-03 12:30:41 +02:00 committed by GitHub
parent 08507e2760
commit cc5df26680
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
97 changed files with 298 additions and 294 deletions

View file

@ -524,7 +524,7 @@ func activityQueryCondition(ctx context.Context, opts GetFeedsOptions) (builder.
} }
if opts.RequestedTeam != nil { if opts.RequestedTeam != nil {
env := organization.OrgFromUser(opts.RequestedUser).AccessibleTeamReposEnv(opts.RequestedTeam) env := organization.OrgFromUser(opts.RequestedUser).AccessibleTeamReposEnv(ctx, opts.RequestedTeam)
teamRepoIDs, err := env.RepoIDs(1, opts.RequestedUser.NumRepos) teamRepoIDs, err := env.RepoIDs(1, opts.RequestedUser.NumRepos)
if err != nil { if err != nil {
return nil, fmt.Errorf("GetTeamRepositories: %w", err) return nil, fmt.Errorf("GetTeamRepositories: %w", err)

View file

@ -52,7 +52,7 @@ type IssueByRepositoryCount struct {
func GetStatistic(ctx context.Context) (stats Statistic) { func GetStatistic(ctx context.Context) (stats Statistic) {
e := db.GetEngine(ctx) e := db.GetEngine(ctx)
stats.Counter.User = user_model.CountUsers(ctx, nil) stats.Counter.User = user_model.CountUsers(ctx, nil)
stats.Counter.Org, _ = organization.CountOrgs(organization.FindOrgOptions{IncludePrivate: true}) stats.Counter.Org, _ = organization.CountOrgs(ctx, organization.FindOrgOptions{IncludePrivate: true})
stats.Counter.PublicKey, _ = e.Count(new(asymkey_model.PublicKey)) stats.Counter.PublicKey, _ = e.Count(new(asymkey_model.PublicKey))
stats.Counter.Repo, _ = repo_model.CountRepositories(ctx, repo_model.CountRepositoryOptions{}) stats.Counter.Repo, _ = repo_model.CountRepositories(ctx, repo_model.CountRepositoryOptions{})
stats.Counter.Watch, _ = e.Count(new(repo_model.Watch)) stats.Counter.Watch, _ = e.Count(new(repo_model.Watch))

View file

@ -18,7 +18,7 @@ func TestUpdateAssignee(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// Fake issue with assignees // Fake issue with assignees
issue, err := issues_model.GetIssueWithAttrsByID(1) issue, err := issues_model.GetIssueWithAttrsByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
// Assign multiple users // Assign multiple users

View file

@ -655,12 +655,12 @@ func (c *Comment) LoadDepIssueDetails(ctx context.Context) (err error) {
} }
// LoadTime loads the associated time for a CommentTypeAddTimeManual // LoadTime loads the associated time for a CommentTypeAddTimeManual
func (c *Comment) LoadTime() error { func (c *Comment) LoadTime(ctx context.Context) error {
if c.Time != nil || c.TimeID == 0 { if c.Time != nil || c.TimeID == 0 {
return nil return nil
} }
var err error var err error
c.Time, err = GetTrackedTimeByID(c.TimeID) c.Time, err = GetTrackedTimeByID(ctx, c.TimeID)
return err return err
} }

View file

@ -201,12 +201,12 @@ func (issue *Issue) IsTimetrackerEnabled(ctx context.Context) bool {
} }
// GetPullRequest returns the issue pull request // GetPullRequest returns the issue pull request
func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) { func (issue *Issue) GetPullRequest(ctx context.Context) (pr *PullRequest, err error) {
if !issue.IsPull { if !issue.IsPull {
return nil, fmt.Errorf("Issue is not a pull request") return nil, fmt.Errorf("Issue is not a pull request")
} }
pr, err = GetPullRequestByIssueID(db.DefaultContext, issue.ID) pr, err = GetPullRequestByIssueID(ctx, issue.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -369,9 +369,9 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) {
} }
// GetIsRead load the `IsRead` field of the issue // GetIsRead load the `IsRead` field of the issue
func (issue *Issue) GetIsRead(userID int64) error { func (issue *Issue) GetIsRead(ctx context.Context, userID int64) error {
issueUser := &IssueUser{IssueID: issue.ID, UID: userID} issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
if has, err := db.GetEngine(db.DefaultContext).Get(issueUser); err != nil { if has, err := db.GetEngine(ctx).Get(issueUser); err != nil {
return err return err
} else if !has { } else if !has {
issue.IsRead = false issue.IsRead = false
@ -382,9 +382,9 @@ func (issue *Issue) GetIsRead(userID int64) error {
} }
// APIURL returns the absolute APIURL to this issue. // APIURL returns the absolute APIURL to this issue.
func (issue *Issue) APIURL() string { func (issue *Issue) APIURL(ctx context.Context) string {
if issue.Repo == nil { if issue.Repo == nil {
err := issue.LoadRepo(db.DefaultContext) err := issue.LoadRepo(ctx)
if err != nil { if err != nil {
log.Error("Issue[%d].APIURL(): %v", issue.ID, err) log.Error("Issue[%d].APIURL(): %v", issue.ID, err)
return "" return ""
@ -479,9 +479,9 @@ func (issue *Issue) GetLastEventLabel() string {
} }
// GetLastComment return last comment for the current issue. // GetLastComment return last comment for the current issue.
func (issue *Issue) GetLastComment() (*Comment, error) { func (issue *Issue) GetLastComment(ctx context.Context) (*Comment, error) {
var c Comment var c Comment
exist, err := db.GetEngine(db.DefaultContext).Where("type = ?", CommentTypeComment). exist, err := db.GetEngine(ctx).Where("type = ?", CommentTypeComment).
And("issue_id = ?", issue.ID).Desc("created_unix").Get(&c) And("issue_id = ?", issue.ID).Desc("created_unix").Get(&c)
if err != nil { if err != nil {
return nil, err return nil, err
@ -543,12 +543,12 @@ func GetIssueByID(ctx context.Context, id int64) (*Issue, error) {
} }
// GetIssueWithAttrsByID returns an issue with attributes by given ID. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
func GetIssueWithAttrsByID(id int64) (*Issue, error) { func GetIssueWithAttrsByID(ctx context.Context, id int64) (*Issue, error) {
issue, err := GetIssueByID(db.DefaultContext, id) issue, err := GetIssueByID(ctx, id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return issue, issue.LoadAttributes(db.DefaultContext) return issue, issue.LoadAttributes(ctx)
} }
// GetIssuesByIDs return issues with the given IDs. // GetIssuesByIDs return issues with the given IDs.
@ -600,8 +600,8 @@ func GetParticipantsIDsByIssueID(ctx context.Context, issueID int64) ([]int64, e
} }
// IsUserParticipantsOfIssue return true if user is participants of an issue // IsUserParticipantsOfIssue return true if user is participants of an issue
func IsUserParticipantsOfIssue(user *user_model.User, issue *Issue) bool { func IsUserParticipantsOfIssue(ctx context.Context, user *user_model.User, issue *Issue) bool {
userIDs, err := issue.GetParticipantIDsByIssue(db.DefaultContext) userIDs, err := issue.GetParticipantIDsByIssue(ctx)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return false return false
@ -894,8 +894,8 @@ func IsErrIssueMaxPinReached(err error) bool {
} }
// InsertIssues insert issues to database // InsertIssues insert issues to database
func InsertIssues(issues ...*Issue) error { func InsertIssues(ctx context.Context, issues ...*Issue) error {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }

View file

@ -65,7 +65,7 @@ func TestIssueAPIURL(t *testing.T) {
err := issue.LoadAttributes(db.DefaultContext) err := issue.LoadAttributes(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL()) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(db.DefaultContext))
} }
func TestGetIssuesByIDs(t *testing.T) { func TestGetIssuesByIDs(t *testing.T) {
@ -477,7 +477,7 @@ func assertCreateIssues(t *testing.T, isPull bool) {
Labels: []*issues_model.Label{label}, Labels: []*issues_model.Label{label},
Reactions: []*issues_model.Reaction{reaction}, Reactions: []*issues_model.Reaction{reaction},
} }
err := issues_model.InsertIssues(is) err := issues_model.InsertIssues(db.DefaultContext, is)
assert.NoError(t, err) assert.NoError(t, err)
i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: title}) i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: title})

View file

@ -81,7 +81,7 @@ func CheckIssueWatch(ctx context.Context, user *user_model.User, issue *Issue) (
if err != nil { if err != nil {
return false, err return false, err
} }
return repo_model.IsWatchMode(w.Mode) || IsUserParticipantsOfIssue(user, issue), nil return repo_model.IsWatchMode(w.Mode) || IsUserParticipantsOfIssue(ctx, user, issue), nil
} }
// GetIssueWatchersIDs returns IDs of subscribers or explicit unsubscribers to a given issue id // GetIssueWatchersIDs returns IDs of subscribers or explicit unsubscribers to a given issue id

View file

@ -1040,7 +1040,7 @@ func ParseCodeOwnersLine(ctx context.Context, tokens []string) (*CodeOwnerRule,
warnings = append(warnings, fmt.Sprintf("incorrect codeowner organization: %s", user)) warnings = append(warnings, fmt.Sprintf("incorrect codeowner organization: %s", user))
continue continue
} }
teams, err := org.LoadTeams() teams, err := org.LoadTeams(ctx)
if err != nil { if err != nil {
warnings = append(warnings, fmt.Sprintf("incorrect codeowner team: %s", user)) warnings = append(warnings, fmt.Sprintf("incorrect codeowner team: %s", user))
continue continue

View file

@ -199,8 +199,8 @@ func addTime(ctx context.Context, user *user_model.User, issue *Issue, amount in
} }
// TotalTimesForEachUser returns the spent time in seconds for each user by an issue // TotalTimesForEachUser returns the spent time in seconds for each user by an issue
func TotalTimesForEachUser(options *FindTrackedTimesOptions) (map[*user_model.User]int64, error) { func TotalTimesForEachUser(ctx context.Context, options *FindTrackedTimesOptions) (map[*user_model.User]int64, error) {
trackedTimes, err := GetTrackedTimes(db.DefaultContext, options) trackedTimes, err := GetTrackedTimes(ctx, options)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -213,7 +213,7 @@ func TotalTimesForEachUser(options *FindTrackedTimesOptions) (map[*user_model.Us
totalTimes := make(map[*user_model.User]int64) totalTimes := make(map[*user_model.User]int64)
// Fetching User and making time human readable // Fetching User and making time human readable
for userID, total := range totalTimesByUser { for userID, total := range totalTimesByUser {
user, err := user_model.GetUserByID(db.DefaultContext, userID) user, err := user_model.GetUserByID(ctx, userID)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
continue continue
@ -226,8 +226,8 @@ func TotalTimesForEachUser(options *FindTrackedTimesOptions) (map[*user_model.Us
} }
// DeleteIssueUserTimes deletes times for issue // DeleteIssueUserTimes deletes times for issue
func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error { func DeleteIssueUserTimes(ctx context.Context, issue *Issue, user *user_model.User) error {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -265,8 +265,8 @@ func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error {
} }
// DeleteTime delete a specific Time // DeleteTime delete a specific Time
func DeleteTime(t *TrackedTime) error { func DeleteTime(ctx context.Context, t *TrackedTime) error {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -315,9 +315,9 @@ func deleteTime(ctx context.Context, t *TrackedTime) error {
} }
// GetTrackedTimeByID returns raw TrackedTime without loading attributes by id // GetTrackedTimeByID returns raw TrackedTime without loading attributes by id
func GetTrackedTimeByID(id int64) (*TrackedTime, error) { func GetTrackedTimeByID(ctx context.Context, id int64) (*TrackedTime, error) {
time := new(TrackedTime) time := new(TrackedTime)
has, err := db.GetEngine(db.DefaultContext).ID(id).Get(time) has, err := db.GetEngine(ctx).ID(id).Get(time)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {

View file

@ -82,7 +82,7 @@ func TestGetTrackedTimes(t *testing.T) {
func TestTotalTimesForEachUser(t *testing.T) { func TestTotalTimesForEachUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
total, err := issues_model.TotalTimesForEachUser(&issues_model.FindTrackedTimesOptions{IssueID: 1}) total, err := issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, total, 1) assert.Len(t, total, 1)
for user, time := range total { for user, time := range total {
@ -90,7 +90,7 @@ func TestTotalTimesForEachUser(t *testing.T) {
assert.EqualValues(t, 400, time) assert.EqualValues(t, 400, time)
} }
total, err = issues_model.TotalTimesForEachUser(&issues_model.FindTrackedTimesOptions{IssueID: 2}) total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 2})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, total, 2) assert.Len(t, total, 2)
for user, time := range total { for user, time := range total {
@ -103,7 +103,7 @@ func TestTotalTimesForEachUser(t *testing.T) {
} }
} }
total, err = issues_model.TotalTimesForEachUser(&issues_model.FindTrackedTimesOptions{IssueID: 5}) total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 5})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, total, 1) assert.Len(t, total, 1)
for user, time := range total { for user, time := range total {
@ -111,7 +111,7 @@ func TestTotalTimesForEachUser(t *testing.T) {
assert.EqualValues(t, 1, time) assert.EqualValues(t, 1, time)
} }
total, err = issues_model.TotalTimesForEachUser(&issues_model.FindTrackedTimesOptions{IssueID: 4}) total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 4})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, total, 2) assert.Len(t, total, 2)
} }

View file

@ -362,7 +362,7 @@ func AddTeamMember(ctx context.Context, team *organization.Team, userID int64) e
return err return err
} }
if err := organization.AddOrgUser(team.OrgID, userID); err != nil { if err := organization.AddOrgUser(ctx, team.OrgID, userID); err != nil {
return err return err
} }

View file

@ -96,23 +96,23 @@ func (Organization) TableName() string {
} }
// IsOwnedBy returns true if given user is in the owner team. // IsOwnedBy returns true if given user is in the owner team.
func (org *Organization) IsOwnedBy(uid int64) (bool, error) { func (org *Organization) IsOwnedBy(ctx context.Context, uid int64) (bool, error) {
return IsOrganizationOwner(db.DefaultContext, org.ID, uid) return IsOrganizationOwner(ctx, org.ID, uid)
} }
// IsOrgAdmin returns true if given user is in the owner team or an admin team. // IsOrgAdmin returns true if given user is in the owner team or an admin team.
func (org *Organization) IsOrgAdmin(uid int64) (bool, error) { func (org *Organization) IsOrgAdmin(ctx context.Context, uid int64) (bool, error) {
return IsOrganizationAdmin(db.DefaultContext, org.ID, uid) return IsOrganizationAdmin(ctx, org.ID, uid)
} }
// IsOrgMember returns true if given user is member of organization. // IsOrgMember returns true if given user is member of organization.
func (org *Organization) IsOrgMember(uid int64) (bool, error) { func (org *Organization) IsOrgMember(ctx context.Context, uid int64) (bool, error) {
return IsOrganizationMember(db.DefaultContext, org.ID, uid) return IsOrganizationMember(ctx, org.ID, uid)
} }
// CanCreateOrgRepo returns true if given user can create repo in organization // CanCreateOrgRepo returns true if given user can create repo in organization
func (org *Organization) CanCreateOrgRepo(uid int64) (bool, error) { func (org *Organization) CanCreateOrgRepo(ctx context.Context, uid int64) (bool, error) {
return CanCreateOrgRepo(db.DefaultContext, org.ID, uid) return CanCreateOrgRepo(ctx, org.ID, uid)
} }
// GetTeam returns named team of organization. // GetTeam returns named team of organization.
@ -135,8 +135,8 @@ func FindOrgTeams(ctx context.Context, orgID int64) ([]*Team, error) {
} }
// LoadTeams load teams if not loaded. // LoadTeams load teams if not loaded.
func (org *Organization) LoadTeams() ([]*Team, error) { func (org *Organization) LoadTeams(ctx context.Context) ([]*Team, error) {
return FindOrgTeams(db.DefaultContext, org.ID) return FindOrgTeams(ctx, org.ID)
} }
// GetMembers returns all members of organization. // GetMembers returns all members of organization.
@ -147,8 +147,8 @@ func (org *Organization) GetMembers(ctx context.Context) (user_model.UserList, m
} }
// HasMemberWithUserID returns true if user with userID is part of the u organisation. // HasMemberWithUserID returns true if user with userID is part of the u organisation.
func (org *Organization) HasMemberWithUserID(userID int64) bool { func (org *Organization) HasMemberWithUserID(ctx context.Context, userID int64) bool {
return org.hasMemberWithUserID(db.DefaultContext, userID) return org.hasMemberWithUserID(ctx, userID)
} }
func (org *Organization) hasMemberWithUserID(ctx context.Context, userID int64) bool { func (org *Organization) hasMemberWithUserID(ctx context.Context, userID int64) bool {
@ -199,8 +199,8 @@ type FindOrgMembersOpts struct {
} }
// CountOrgMembers counts the organization's members // CountOrgMembers counts the organization's members
func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) { func CountOrgMembers(ctx context.Context, opts *FindOrgMembersOpts) (int64, error) {
sess := db.GetEngine(db.DefaultContext).Where("org_id=?", opts.OrgID) sess := db.GetEngine(ctx).Where("org_id=?", opts.OrgID)
if opts.PublicOnly { if opts.PublicOnly {
sess.And("is_public = ?", true) sess.And("is_public = ?", true)
} }
@ -271,7 +271,7 @@ func (org *Organization) UnitPermission(ctx context.Context, doer *user_model.Us
} }
// CreateOrganization creates record of a new organization. // CreateOrganization creates record of a new organization.
func CreateOrganization(org *Organization, owner *user_model.User) (err error) { func CreateOrganization(ctx context.Context, org *Organization, owner *user_model.User) (err error) {
if !owner.CanCreateOrganization() { if !owner.CanCreateOrganization() {
return ErrUserNotAllowedCreateOrg{} return ErrUserNotAllowedCreateOrg{}
} }
@ -280,7 +280,7 @@ func CreateOrganization(org *Organization, owner *user_model.User) (err error) {
return err return err
} }
isExist, err := user_model.IsUserExist(db.DefaultContext, 0, org.Name) isExist, err := user_model.IsUserExist(ctx, 0, org.Name)
if err != nil { if err != nil {
return err return err
} else if isExist { } else if isExist {
@ -300,7 +300,7 @@ func CreateOrganization(org *Organization, owner *user_model.User) (err error) {
org.NumMembers = 1 org.NumMembers = 1
org.Type = user_model.UserTypeOrganization org.Type = user_model.UserTypeOrganization
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -412,9 +412,9 @@ func DeleteOrganization(ctx context.Context, org *Organization) error {
} }
// GetOrgUserMaxAuthorizeLevel returns highest authorize level of user in an organization // GetOrgUserMaxAuthorizeLevel returns highest authorize level of user in an organization
func (org *Organization) GetOrgUserMaxAuthorizeLevel(uid int64) (perm.AccessMode, error) { func (org *Organization) GetOrgUserMaxAuthorizeLevel(ctx context.Context, uid int64) (perm.AccessMode, error) {
var authorize perm.AccessMode var authorize perm.AccessMode
_, err := db.GetEngine(db.DefaultContext). _, err := db.GetEngine(ctx).
Select("max(team.authorize)"). Select("max(team.authorize)").
Table("team"). Table("team").
Join("INNER", "team_user", "team_user.team_id = team.id"). Join("INNER", "team_user", "team_user.team_id = team.id").
@ -468,9 +468,9 @@ func (opts FindOrgOptions) toConds() builder.Cond {
} }
// FindOrgs returns a list of organizations according given conditions // FindOrgs returns a list of organizations according given conditions
func FindOrgs(opts FindOrgOptions) ([]*Organization, error) { func FindOrgs(ctx context.Context, opts FindOrgOptions) ([]*Organization, error) {
orgs := make([]*Organization, 0, 10) orgs := make([]*Organization, 0, 10)
sess := db.GetEngine(db.DefaultContext). sess := db.GetEngine(ctx).
Where(opts.toConds()). Where(opts.toConds()).
Asc("`user`.name") Asc("`user`.name")
if opts.Page > 0 && opts.PageSize > 0 { if opts.Page > 0 && opts.PageSize > 0 {
@ -480,8 +480,8 @@ func FindOrgs(opts FindOrgOptions) ([]*Organization, error) {
} }
// CountOrgs returns total count organizations according options // CountOrgs returns total count organizations according options
func CountOrgs(opts FindOrgOptions) (int64, error) { func CountOrgs(ctx context.Context, opts FindOrgOptions) (int64, error) {
return db.GetEngine(db.DefaultContext). return db.GetEngine(ctx).
Where(opts.toConds()). Where(opts.toConds()).
Count(new(Organization)) Count(new(Organization))
} }
@ -505,13 +505,13 @@ func HasOrgOrUserVisible(ctx context.Context, orgOrUser, user *user_model.User)
} }
// HasOrgsVisible tells if the given user can see at least one of the orgs provided // HasOrgsVisible tells if the given user can see at least one of the orgs provided
func HasOrgsVisible(orgs []*Organization, user *user_model.User) bool { func HasOrgsVisible(ctx context.Context, orgs []*Organization, user *user_model.User) bool {
if len(orgs) == 0 { if len(orgs) == 0 {
return false return false
} }
for _, org := range orgs { for _, org := range orgs {
if HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user) { if HasOrgOrUserVisible(ctx, org.AsUser(), user) {
return true return true
} }
} }
@ -550,9 +550,9 @@ func GetOrgUsersByOrgID(ctx context.Context, opts *FindOrgMembersOpts) ([]*OrgUs
} }
// ChangeOrgUserStatus changes public or private membership status. // ChangeOrgUserStatus changes public or private membership status.
func ChangeOrgUserStatus(orgID, uid int64, public bool) error { func ChangeOrgUserStatus(ctx context.Context, orgID, uid int64, public bool) error {
ou := new(OrgUser) ou := new(OrgUser)
has, err := db.GetEngine(db.DefaultContext). has, err := db.GetEngine(ctx).
Where("uid=?", uid). Where("uid=?", uid).
And("org_id=?", orgID). And("org_id=?", orgID).
Get(ou) Get(ou)
@ -563,18 +563,18 @@ func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
} }
ou.IsPublic = public ou.IsPublic = public
_, err = db.GetEngine(db.DefaultContext).ID(ou.ID).Cols("is_public").Update(ou) _, err = db.GetEngine(ctx).ID(ou.ID).Cols("is_public").Update(ou)
return err return err
} }
// AddOrgUser adds new user to given organization. // AddOrgUser adds new user to given organization.
func AddOrgUser(orgID, uid int64) error { func AddOrgUser(ctx context.Context, orgID, uid int64) error {
isAlreadyMember, err := IsOrganizationMember(db.DefaultContext, orgID, uid) isAlreadyMember, err := IsOrganizationMember(ctx, orgID, uid)
if err != nil || isAlreadyMember { if err != nil || isAlreadyMember {
return err return err
} }
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -669,19 +669,19 @@ func (org *Organization) getUserTeamIDs(ctx context.Context, userID int64) ([]in
} }
// TeamsWithAccessToRepo returns all teams that have given access level to the repository. // TeamsWithAccessToRepo returns all teams that have given access level to the repository.
func (org *Organization) TeamsWithAccessToRepo(repoID int64, mode perm.AccessMode) ([]*Team, error) { func (org *Organization) TeamsWithAccessToRepo(ctx context.Context, repoID int64, mode perm.AccessMode) ([]*Team, error) {
return GetTeamsWithAccessToRepo(db.DefaultContext, org.ID, repoID, mode) return GetTeamsWithAccessToRepo(ctx, org.ID, repoID, mode)
} }
// GetUserTeamIDs returns of all team IDs of the organization that user is member of. // GetUserTeamIDs returns of all team IDs of the organization that user is member of.
func (org *Organization) GetUserTeamIDs(userID int64) ([]int64, error) { func (org *Organization) GetUserTeamIDs(ctx context.Context, userID int64) ([]int64, error) {
return org.getUserTeamIDs(db.DefaultContext, userID) return org.getUserTeamIDs(ctx, userID)
} }
// GetUserTeams returns all teams that belong to user, // GetUserTeams returns all teams that belong to user,
// and that the user has joined. // and that the user has joined.
func (org *Organization) GetUserTeams(userID int64) ([]*Team, error) { func (org *Organization) GetUserTeams(ctx context.Context, userID int64) ([]*Team, error) {
return org.getUserTeams(db.DefaultContext, userID) return org.getUserTeams(ctx, userID)
} }
// AccessibleReposEnvironment operations involving the repositories that are // AccessibleReposEnvironment operations involving the repositories that are
@ -733,11 +733,11 @@ func AccessibleReposEnv(ctx context.Context, org *Organization, userID int64) (A
// AccessibleTeamReposEnv an AccessibleReposEnvironment for the repositories in `org` // AccessibleTeamReposEnv an AccessibleReposEnvironment for the repositories in `org`
// that are accessible to the specified team. // that are accessible to the specified team.
func (org *Organization) AccessibleTeamReposEnv(team *Team) AccessibleReposEnvironment { func (org *Organization) AccessibleTeamReposEnv(ctx context.Context, team *Team) AccessibleReposEnvironment {
return &accessibleReposEnv{ return &accessibleReposEnv{
org: org, org: org,
team: team, team: team,
ctx: db.DefaultContext, ctx: ctx,
orderBy: db.SearchOrderByRecentUpdated, orderBy: db.SearchOrderByRecentUpdated,
} }
} }

View file

@ -31,7 +31,7 @@ func TestUser_IsOwnedBy(t *testing.T) {
{2, 3, false}, {2, 3, false},
} { } {
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID})
isOwner, err := org.IsOwnedBy(testCase.UserID) isOwner, err := org.IsOwnedBy(db.DefaultContext, testCase.UserID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, testCase.ExpectedOwner, isOwner) assert.Equal(t, testCase.ExpectedOwner, isOwner)
} }
@ -52,7 +52,7 @@ func TestUser_IsOrgMember(t *testing.T) {
{2, 3, false}, {2, 3, false},
} { } {
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID})
isMember, err := org.IsOrgMember(testCase.UserID) isMember, err := org.IsOrgMember(db.DefaultContext, testCase.UserID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, testCase.ExpectedMember, isMember) assert.Equal(t, testCase.ExpectedMember, isMember)
} }
@ -89,7 +89,7 @@ func TestUser_GetOwnerTeam(t *testing.T) {
func TestUser_GetTeams(t *testing.T) { func TestUser_GetTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
teams, err := org.LoadTeams() teams, err := org.LoadTeams(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, teams, 5) { if assert.Len(t, teams, 5) {
assert.Equal(t, int64(1), teams[0].ID) assert.Equal(t, int64(1), teams[0].ID)
@ -131,7 +131,7 @@ func TestCountOrganizations(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{}) expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{})
assert.NoError(t, err) assert.NoError(t, err)
cnt, err := organization.CountOrgs(organization.FindOrgOptions{IncludePrivate: true}) cnt, err := organization.CountOrgs(db.DefaultContext, organization.FindOrgOptions{IncludePrivate: true})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, cnt) assert.Equal(t, expected, cnt)
} }
@ -168,7 +168,7 @@ func TestIsOrganizationMember(t *testing.T) {
func TestIsPublicMembership(t *testing.T) { func TestIsPublicMembership(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64, expected bool) { test := func(orgID, userID int64, expected bool) {
isMember, err := organization.IsPublicMembership(orgID, userID) isMember, err := organization.IsPublicMembership(db.DefaultContext, orgID, userID)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, expected, isMember) assert.EqualValues(t, expected, isMember)
} }
@ -183,7 +183,7 @@ func TestIsPublicMembership(t *testing.T) {
func TestFindOrgs(t *testing.T) { func TestFindOrgs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
orgs, err := organization.FindOrgs(organization.FindOrgOptions{ orgs, err := organization.FindOrgs(db.DefaultContext, organization.FindOrgOptions{
UserID: 4, UserID: 4,
IncludePrivate: true, IncludePrivate: true,
}) })
@ -192,14 +192,14 @@ func TestFindOrgs(t *testing.T) {
assert.EqualValues(t, 3, orgs[0].ID) assert.EqualValues(t, 3, orgs[0].ID)
} }
orgs, err = organization.FindOrgs(organization.FindOrgOptions{ orgs, err = organization.FindOrgs(db.DefaultContext, organization.FindOrgOptions{
UserID: 4, UserID: 4,
IncludePrivate: false, IncludePrivate: false,
}) })
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, orgs, 0) assert.Len(t, orgs, 0)
total, err := organization.CountOrgs(organization.FindOrgOptions{ total, err := organization.CountOrgs(db.DefaultContext, organization.FindOrgOptions{
UserID: 4, UserID: 4,
IncludePrivate: true, IncludePrivate: true,
}) })
@ -250,7 +250,7 @@ func TestChangeOrgUserStatus(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID, userID int64, public bool) { testSuccess := func(orgID, userID int64, public bool) {
assert.NoError(t, organization.ChangeOrgUserStatus(orgID, userID, public)) assert.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, orgID, userID, public))
orgUser := unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: orgID, UID: userID}) orgUser := unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: orgID, UID: userID})
assert.Equal(t, public, orgUser.IsPublic) assert.Equal(t, public, orgUser.IsPublic)
} }
@ -258,14 +258,14 @@ func TestChangeOrgUserStatus(t *testing.T) {
testSuccess(3, 2, false) testSuccess(3, 2, false)
testSuccess(3, 2, false) testSuccess(3, 2, false)
testSuccess(3, 4, true) testSuccess(3, 4, true)
assert.NoError(t, organization.ChangeOrgUserStatus(unittest.NonexistentID, unittest.NonexistentID, true)) assert.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID, true))
} }
func TestUser_GetUserTeamIDs(t *testing.T) { func TestUser_GetUserTeamIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expected []int64) { testSuccess := func(userID int64, expected []int64) {
teamIDs, err := org.GetUserTeamIDs(userID) teamIDs, err := org.GetUserTeamIDs(db.DefaultContext, userID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, teamIDs) assert.Equal(t, expected, teamIDs)
} }
@ -352,7 +352,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(org, owner)) assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
org = unittest.AssertExistsAndLoadBean(t, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
@ -375,7 +375,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(org, owner)) assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
org = unittest.AssertExistsAndLoadBean(t, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
@ -398,7 +398,7 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(org, owner)) assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
org = unittest.AssertExistsAndLoadBean(t, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
@ -461,7 +461,7 @@ func TestCreateOrganization(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(org, owner)) assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
org = unittest.AssertExistsAndLoadBean(t, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
ownerTeam := unittest.AssertExistsAndLoadBean(t, ownerTeam := unittest.AssertExistsAndLoadBean(t,
@ -481,7 +481,7 @@ func TestCreateOrganization2(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
err := organization.CreateOrganization(org, owner) err := organization.CreateOrganization(db.DefaultContext, org, owner)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err)) assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err))
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
@ -495,7 +495,7 @@ func TestCreateOrganization3(t *testing.T) {
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
org := &organization.Organization{Name: "org3"} // should already exist org := &organization.Organization{Name: "org3"} // should already exist
unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check
err := organization.CreateOrganization(org, owner) err := organization.CreateOrganization(db.DefaultContext, org, owner)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, user_model.IsErrUserAlreadyExist(err)) assert.True(t, user_model.IsErrUserAlreadyExist(err))
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
@ -506,7 +506,7 @@ func TestCreateOrganization4(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
err := organization.CreateOrganization(&organization.Organization{Name: "assets"}, owner) err := organization.CreateOrganization(db.DefaultContext, &organization.Organization{Name: "assets"}, owner)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, db.IsErrNameReserved(err)) assert.True(t, db.IsErrNameReserved(err))
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{}) unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})

View file

@ -78,8 +78,8 @@ func IsOrganizationMember(ctx context.Context, orgID, uid int64) (bool, error) {
} }
// IsPublicMembership returns true if the given user's membership of given org is public. // IsPublicMembership returns true if the given user's membership of given org is public.
func IsPublicMembership(orgID, uid int64) (bool, error) { func IsPublicMembership(ctx context.Context, orgID, uid int64) (bool, error) {
return db.GetEngine(db.DefaultContext). return db.GetEngine(ctx).
Where("uid=?", uid). Where("uid=?", uid).
And("org_id=?", orgID). And("org_id=?", orgID).
And("is_public=?", true). And("is_public=?", true).
@ -98,12 +98,12 @@ func CanCreateOrgRepo(ctx context.Context, orgID, uid int64) (bool, error) {
} }
// IsUserOrgOwner returns true if user is in the owner team of given organization. // IsUserOrgOwner returns true if user is in the owner team of given organization.
func IsUserOrgOwner(users user_model.UserList, orgID int64) map[int64]bool { func IsUserOrgOwner(ctx context.Context, users user_model.UserList, orgID int64) map[int64]bool {
results := make(map[int64]bool, len(users)) results := make(map[int64]bool, len(users))
for _, user := range users { for _, user := range users {
results[user.ID] = false // Set default to false results[user.ID] = false // Set default to false
} }
ownerMaps, err := loadOrganizationOwners(db.DefaultContext, users, orgID) ownerMaps, err := loadOrganizationOwners(ctx, users, orgID)
if err == nil { if err == nil {
for _, owner := range ownerMaps { for _, owner := range ownerMaps {
results[owner.UID] = true results[owner.UID] = true

View file

@ -39,7 +39,7 @@ func TestUserIsPublicMember(t *testing.T) {
func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(db.DefaultContext, uid) user, err := user_model.GetUserByID(db.DefaultContext, uid)
assert.NoError(t, err) assert.NoError(t, err)
is, err := organization.IsPublicMembership(orgID, user.ID) is, err := organization.IsPublicMembership(db.DefaultContext, orgID, user.ID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, is) assert.Equal(t, expected, is)
} }
@ -123,7 +123,7 @@ func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bo
assert.NoError(t, err) assert.NoError(t, err)
members, _, err := org.GetMembers(db.DefaultContext) members, _, err := org.GetMembers(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, organization.IsUserOrgOwner(members, orgID)) assert.Equal(t, expected, organization.IsUserOrgOwner(db.DefaultContext, members, orgID))
} }
func TestAddOrgUser(t *testing.T) { func TestAddOrgUser(t *testing.T) {
@ -134,7 +134,7 @@ func TestAddOrgUser(t *testing.T) {
if !unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) { if !unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) {
expectedNumMembers++ expectedNumMembers++
} }
assert.NoError(t, organization.AddOrgUser(orgID, userID)) assert.NoError(t, organization.AddOrgUser(db.DefaultContext, orgID, userID))
ou := &organization.OrgUser{OrgID: orgID, UID: userID} ou := &organization.OrgUser{OrgID: orgID, UID: userID}
unittest.AssertExistsAndLoadBean(t, ou) unittest.AssertExistsAndLoadBean(t, ou)
assert.Equal(t, isPublic, ou.IsPublic) assert.Equal(t, isPublic, ou.IsPublic)

View file

@ -144,8 +144,8 @@ func (t *Team) IsOwnerTeam() bool {
} }
// IsMember returns true if given user is a member of team. // IsMember returns true if given user is a member of team.
func (t *Team) IsMember(userID int64) bool { func (t *Team) IsMember(ctx context.Context, userID int64) bool {
isMember, err := IsTeamMember(db.DefaultContext, t.OrgID, t.ID, userID) isMember, err := IsTeamMember(ctx, t.OrgID, t.ID, userID)
if err != nil { if err != nil {
log.Error("IsMember: %v", err) log.Error("IsMember: %v", err)
return false return false
@ -217,10 +217,10 @@ func GetTeam(ctx context.Context, orgID int64, name string) (*Team, error) {
} }
// GetTeamIDsByNames returns a slice of team ids corresponds to names. // GetTeamIDsByNames returns a slice of team ids corresponds to names.
func GetTeamIDsByNames(orgID int64, names []string, ignoreNonExistent bool) ([]int64, error) { func GetTeamIDsByNames(ctx context.Context, orgID int64, names []string, ignoreNonExistent bool) ([]int64, error) {
ids := make([]int64, 0, len(names)) ids := make([]int64, 0, len(names))
for _, name := range names { for _, name := range names {
u, err := GetTeam(db.DefaultContext, orgID, name) u, err := GetTeam(ctx, orgID, name)
if err != nil { if err != nil {
if ignoreNonExistent { if ignoreNonExistent {
continue continue
@ -251,13 +251,13 @@ func GetTeamByID(ctx context.Context, teamID int64) (*Team, error) {
} }
// GetTeamNamesByID returns team's lower name from a list of team ids. // GetTeamNamesByID returns team's lower name from a list of team ids.
func GetTeamNamesByID(teamIDs []int64) ([]string, error) { func GetTeamNamesByID(ctx context.Context, teamIDs []int64) ([]string, error) {
if len(teamIDs) == 0 { if len(teamIDs) == 0 {
return []string{}, nil return []string{}, nil
} }
var teamNames []string var teamNames []string
err := db.GetEngine(db.DefaultContext).Table("team"). err := db.GetEngine(ctx).Table("team").
Select("lower_name"). Select("lower_name").
In("id", teamIDs). In("id", teamIDs).
Asc("name"). Asc("name").

View file

@ -27,14 +27,14 @@ func TestTeam_IsMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1})
assert.True(t, team.IsMember(2)) assert.True(t, team.IsMember(db.DefaultContext, 2))
assert.False(t, team.IsMember(4)) assert.False(t, team.IsMember(db.DefaultContext, 4))
assert.False(t, team.IsMember(unittest.NonexistentID)) assert.False(t, team.IsMember(db.DefaultContext, unittest.NonexistentID))
team = unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) team = unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})
assert.True(t, team.IsMember(2)) assert.True(t, team.IsMember(db.DefaultContext, 2))
assert.True(t, team.IsMember(4)) assert.True(t, team.IsMember(db.DefaultContext, 4))
assert.False(t, team.IsMember(unittest.NonexistentID)) assert.False(t, team.IsMember(db.DefaultContext, unittest.NonexistentID))
} }
func TestTeam_GetRepositories(t *testing.T) { func TestTeam_GetRepositories(t *testing.T) {
@ -188,7 +188,7 @@ func TestUsersInTeamsCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
test := func(teamIDs, userIDs []int64, expected int64) { test := func(teamIDs, userIDs []int64, expected int64) {
count, err := organization.UsersInTeamsCount(teamIDs, userIDs) count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, count) assert.Equal(t, expected, count)
} }

View file

@ -30,8 +30,8 @@ func getUnitsByTeamID(ctx context.Context, teamID int64) (units []*TeamUnit, err
} }
// UpdateTeamUnits updates a teams's units // UpdateTeamUnits updates a teams's units
func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) { func UpdateTeamUnits(ctx context.Context, team *Team, units []TeamUnit) (err error) {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }

View file

@ -78,9 +78,9 @@ func IsUserInTeams(ctx context.Context, userID int64, teamIDs []int64) (bool, er
} }
// UsersInTeamsCount counts the number of users which are in userIDs and teamIDs // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
func UsersInTeamsCount(userIDs, teamIDs []int64) (int64, error) { func UsersInTeamsCount(ctx context.Context, userIDs, teamIDs []int64) (int64, error) {
var ids []int64 var ids []int64
if err := db.GetEngine(db.DefaultContext).In("uid", userIDs).In("team_id", teamIDs). if err := db.GetEngine(ctx).In("uid", userIDs).In("team_id", teamIDs).
Table("team_user"). Table("team_user").
Cols("uid").GroupBy("uid").Find(&ids); err != nil { Cols("uid").GroupBy("uid").Find(&ids); err != nil {
return 0, err return 0, err

View file

@ -261,16 +261,16 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use
} }
// IsUserRealRepoAdmin check if this user is real repo admin // IsUserRealRepoAdmin check if this user is real repo admin
func IsUserRealRepoAdmin(repo *repo_model.Repository, user *user_model.User) (bool, error) { func IsUserRealRepoAdmin(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (bool, error) {
if repo.OwnerID == user.ID { if repo.OwnerID == user.ID {
return true, nil return true, nil
} }
if err := repo.LoadOwner(db.DefaultContext); err != nil { if err := repo.LoadOwner(ctx); err != nil {
return false, err return false, err
} }
accessMode, err := accessLevel(db.DefaultContext, user, repo) accessMode, err := accessLevel(ctx, user, repo)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -394,13 +394,13 @@ func getUsersWithAccessMode(ctx context.Context, repo *repo_model.Repository, mo
} }
// GetRepoReaders returns all users that have explicit read access or higher to the repository. // GetRepoReaders returns all users that have explicit read access or higher to the repository.
func GetRepoReaders(repo *repo_model.Repository) (_ []*user_model.User, err error) { func GetRepoReaders(ctx context.Context, repo *repo_model.Repository) (_ []*user_model.User, err error) {
return getUsersWithAccessMode(db.DefaultContext, repo, perm_model.AccessModeRead) return getUsersWithAccessMode(ctx, repo, perm_model.AccessModeRead)
} }
// GetRepoWriters returns all users that have write access to the repository. // GetRepoWriters returns all users that have write access to the repository.
func GetRepoWriters(repo *repo_model.Repository) (_ []*user_model.User, err error) { func GetRepoWriters(ctx context.Context, repo *repo_model.Repository) (_ []*user_model.User, err error) {
return getUsersWithAccessMode(db.DefaultContext, repo, perm_model.AccessModeWrite) return getUsersWithAccessMode(ctx, repo, perm_model.AccessModeWrite)
} }
// IsRepoReader returns true if user has explicit read access or higher to the repository. // IsRepoReader returns true if user has explicit read access or higher to the repository.

View file

@ -58,12 +58,12 @@ func init() {
} }
// GetRepository returns the path of the repository. // GetRepository returns the path of the repository.
func (m *PushMirror) GetRepository() *Repository { func (m *PushMirror) GetRepository(ctx context.Context) *Repository {
if m.Repo != nil { if m.Repo != nil {
return m.Repo return m.Repo
} }
var err error var err error
m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID) m.Repo, err = GetRepositoryByID(ctx, m.RepoID)
if err != nil { if err != nil {
log.Error("getRepositoryByID[%d]: %v", m.ID, err) log.Error("getRepositoryByID[%d]: %v", m.ID, err)
} }

View file

@ -279,14 +279,14 @@ func getUnitsByRepoID(ctx context.Context, repoID int64) (units []*RepoUnit, err
} }
// UpdateRepoUnit updates the provided repo unit // UpdateRepoUnit updates the provided repo unit
func UpdateRepoUnit(unit *RepoUnit) error { func UpdateRepoUnit(ctx context.Context, unit *RepoUnit) error {
_, err := db.GetEngine(db.DefaultContext).ID(unit.ID).Update(unit) _, err := db.GetEngine(ctx).ID(unit.ID).Update(unit)
return err return err
} }
// UpdateRepositoryUnits updates a repository's units // UpdateRepositoryUnits updates a repository's units
func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []unit.Type) (err error) { func UpdateRepositoryUnits(ctx context.Context, repo *Repository, units []RepoUnit, deleteUnitTypes []unit.Type) (err error) {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }

View file

@ -88,8 +88,8 @@ func RemoveStorageWithNotice(ctx context.Context, bucket storage.ObjectStorage,
} }
// CountNotices returns number of notices. // CountNotices returns number of notices.
func CountNotices() int64 { func CountNotices(ctx context.Context) int64 {
count, _ := db.GetEngine(db.DefaultContext).Count(new(Notice)) count, _ := db.GetEngine(ctx).Count(new(Notice))
return count return count
} }

View file

@ -49,7 +49,7 @@ func TestCreateRepositoryNotice(t *testing.T) {
func TestCountNotices(t *testing.T) { func TestCountNotices(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.Equal(t, int64(3), system.CountNotices()) assert.Equal(t, int64(3), system.CountNotices(db.DefaultContext))
} }
func TestNotices(t *testing.T) { func TestNotices(t *testing.T) {

View file

@ -128,7 +128,7 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
ctx.Org.IsTeamAdmin = true ctx.Org.IsTeamAdmin = true
ctx.Org.CanCreateOrgRepo = true ctx.Org.CanCreateOrgRepo = true
} else if ctx.IsSigned { } else if ctx.IsSigned {
ctx.Org.IsOwner, err = org.IsOwnedBy(ctx.Doer.ID) ctx.Org.IsOwner, err = org.IsOwnedBy(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("IsOwnedBy", err) ctx.ServerError("IsOwnedBy", err)
return return
@ -140,12 +140,12 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
ctx.Org.IsTeamAdmin = true ctx.Org.IsTeamAdmin = true
ctx.Org.CanCreateOrgRepo = true ctx.Org.CanCreateOrgRepo = true
} else { } else {
ctx.Org.IsMember, err = org.IsOrgMember(ctx.Doer.ID) ctx.Org.IsMember, err = org.IsOrgMember(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("IsOrgMember", err) ctx.ServerError("IsOrgMember", err)
return return
} }
ctx.Org.CanCreateOrgRepo, err = org.CanCreateOrgRepo(ctx.Doer.ID) ctx.Org.CanCreateOrgRepo, err = org.CanCreateOrgRepo(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("CanCreateOrgRepo", err) ctx.ServerError("CanCreateOrgRepo", err)
return return
@ -165,7 +165,7 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
ctx.Data["IsPackageEnabled"] = setting.Packages.Enabled ctx.Data["IsPackageEnabled"] = setting.Packages.Enabled
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
ctx.Data["IsPublicMember"] = func(uid int64) bool { ctx.Data["IsPublicMember"] = func(uid int64) bool {
is, _ := organization.IsPublicMembership(ctx.Org.Organization.ID, uid) is, _ := organization.IsPublicMembership(ctx, ctx.Org.Organization.ID, uid)
return is return is
} }
ctx.Data["CanCreateOrgRepo"] = ctx.Org.CanCreateOrgRepo ctx.Data["CanCreateOrgRepo"] = ctx.Org.CanCreateOrgRepo
@ -179,7 +179,7 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
OrgID: org.ID, OrgID: org.ID,
PublicOnly: ctx.Org.PublicMemberOnly, PublicOnly: ctx.Org.PublicMemberOnly,
} }
ctx.Data["NumMembers"], err = organization.CountOrgMembers(opts) ctx.Data["NumMembers"], err = organization.CountOrgMembers(ctx, opts)
if err != nil { if err != nil {
ctx.ServerError("CountOrgMembers", err) ctx.ServerError("CountOrgMembers", err)
return return
@ -191,7 +191,7 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
if ctx.Org.IsOwner { if ctx.Org.IsOwner {
shouldSeeAllTeams = true shouldSeeAllTeams = true
} else { } else {
teams, err := org.GetUserTeams(ctx.Doer.ID) teams, err := org.GetUserTeams(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("GetUserTeams", err) ctx.ServerError("GetUserTeams", err)
return return
@ -204,13 +204,13 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
} }
} }
if shouldSeeAllTeams { if shouldSeeAllTeams {
ctx.Org.Teams, err = org.LoadTeams() ctx.Org.Teams, err = org.LoadTeams(ctx)
if err != nil { if err != nil {
ctx.ServerError("LoadTeams", err) ctx.ServerError("LoadTeams", err)
return return
} }
} else { } else {
ctx.Org.Teams, err = org.GetUserTeams(ctx.Doer.ID) ctx.Org.Teams, err = org.GetUserTeams(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("GetUserTeams", err) ctx.ServerError("GetUserTeams", err)
return return

View file

@ -109,7 +109,7 @@ func determineAccessMode(ctx *Base, pkg *Package, doer *user_model.User) (perm.A
if doer != nil && !doer.IsGhost() { if doer != nil && !doer.IsGhost() {
// 1. If user is logged in, check all team packages permissions // 1. If user is logged in, check all team packages permissions
var err error var err error
accessMode, err = org.GetOrgUserMaxAuthorizeLevel(doer.ID) accessMode, err = org.GetOrgUserMaxAuthorizeLevel(ctx, doer.ID)
if err != nil { if err != nil {
return accessMode, err return accessMode, err
} }

View file

@ -290,7 +290,7 @@ func fixBrokenRepoUnits16961(ctx context.Context, logger log.Logger, autofix boo
return nil return nil
} }
return repo_model.UpdateRepoUnit(repoUnit) return repo_model.UpdateRepoUnit(ctx, repoUnit)
}, },
) )
if err != nil { if err != nil {

View file

@ -244,7 +244,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) {
// update team information and then check permission // update team information and then check permission
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5})
err = organization.UpdateTeamUnits(team, nil) err = organization.UpdateTeamUnits(db.DefaultContext, team, nil)
assert.NoError(t, err) assert.NoError(t, err)
perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner)
assert.NoError(t, err) assert.NoError(t, err)

View file

@ -22,7 +22,7 @@ func CanUserDelete(ctx context.Context, repo *repo_model.Repository, user *user_
} }
if repo.Owner.IsOrganization() { if repo.Owner.IsOrganization() {
isAdmin, err := organization.OrgFromUser(repo.Owner).IsOrgAdmin(user.ID) isAdmin, err := organization.OrgFromUser(repo.Owner).IsOrgAdmin(ctx, user.ID)
if err != nil { if err != nil {
return false, err return false, err
} }

View file

@ -62,7 +62,7 @@ func CreateOrg(ctx *context.APIContext) {
Visibility: visibility, Visibility: visibility,
} }
if err := organization.CreateOrganization(org, ctx.ContextUser); err != nil { if err := organization.CreateOrganization(ctx, org, ctx.ContextUser); err != nil {
if user_model.IsErrUserAlreadyExist(err) || if user_model.IsErrUserAlreadyExist(err) ||
db.IsErrNameReserved(err) || db.IsErrNameReserved(err) ||
db.IsErrNameCharsNotAllowed(err) || db.IsErrNameCharsNotAllowed(err) ||

View file

@ -25,7 +25,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) {
ListOptions: utils.GetListOptions(ctx), ListOptions: utils.GetListOptions(ctx),
} }
count, err := organization.CountOrgMembers(opts) count, err := organization.CountOrgMembers(ctx, opts)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -75,7 +75,7 @@ func ListMembers(ctx *context.APIContext) {
publicOnly := true publicOnly := true
if ctx.Doer != nil { if ctx.Doer != nil {
isMember, err := ctx.Org.Organization.IsOrgMember(ctx.Doer.ID) isMember, err := ctx.Org.Organization.IsOrgMember(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
return return
@ -144,12 +144,12 @@ func IsMember(ctx *context.APIContext) {
return return
} }
if ctx.Doer != nil { if ctx.Doer != nil {
userIsMember, err := ctx.Org.Organization.IsOrgMember(ctx.Doer.ID) userIsMember, err := ctx.Org.Organization.IsOrgMember(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
return return
} else if userIsMember || ctx.Doer.IsAdmin { } else if userIsMember || ctx.Doer.IsAdmin {
userToCheckIsMember, err := ctx.Org.Organization.IsOrgMember(userToCheck.ID) userToCheckIsMember, err := ctx.Org.Organization.IsOrgMember(ctx, userToCheck.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
} else if userToCheckIsMember { } else if userToCheckIsMember {
@ -194,7 +194,7 @@ func IsPublicMember(ctx *context.APIContext) {
if ctx.Written() { if ctx.Written() {
return return
} }
is, err := organization.IsPublicMembership(ctx.Org.Organization.ID, userToCheck.ID) is, err := organization.IsPublicMembership(ctx, ctx.Org.Organization.ID, userToCheck.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsPublicMembership", err) ctx.Error(http.StatusInternalServerError, "IsPublicMembership", err)
return return
@ -240,7 +240,7 @@ func PublicizeMember(ctx *context.APIContext) {
ctx.Error(http.StatusForbidden, "", "Cannot publicize another member") ctx.Error(http.StatusForbidden, "", "Cannot publicize another member")
return return
} }
err := organization.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToPublicize.ID, true) err := organization.ChangeOrgUserStatus(ctx, ctx.Org.Organization.ID, userToPublicize.ID, true)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err) ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err)
return return
@ -282,7 +282,7 @@ func ConcealMember(ctx *context.APIContext) {
ctx.Error(http.StatusForbidden, "", "Cannot conceal another member") ctx.Error(http.StatusForbidden, "", "Cannot conceal another member")
return return
} }
err := organization.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToConceal.ID, false) err := organization.ChangeOrgUserStatus(ctx, ctx.Org.Organization.ID, userToConceal.ID, false)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err) ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err)
return return

View file

@ -30,12 +30,12 @@ func listUserOrgs(ctx *context.APIContext, u *user_model.User) {
UserID: u.ID, UserID: u.ID,
IncludePrivate: showPrivate, IncludePrivate: showPrivate,
} }
orgs, err := organization.FindOrgs(opts) orgs, err := organization.FindOrgs(ctx, opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "FindOrgs", err) ctx.Error(http.StatusInternalServerError, "FindOrgs", err)
return return
} }
maxResults, err := organization.CountOrgs(opts) maxResults, err := organization.CountOrgs(ctx, opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CountOrgs", err) ctx.Error(http.StatusInternalServerError, "CountOrgs", err)
return return
@ -145,7 +145,7 @@ func GetUserOrgsPermissions(ctx *context.APIContext) {
} }
org := organization.OrgFromUser(o) org := organization.OrgFromUser(o)
authorizeLevel, err := org.GetOrgUserMaxAuthorizeLevel(ctx.ContextUser.ID) authorizeLevel, err := org.GetOrgUserMaxAuthorizeLevel(ctx, ctx.ContextUser.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetOrgUserAuthorizeLevel", err) ctx.Error(http.StatusInternalServerError, "GetOrgUserAuthorizeLevel", err)
return return
@ -164,7 +164,7 @@ func GetUserOrgsPermissions(ctx *context.APIContext) {
op.IsOwner = true op.IsOwner = true
} }
op.CanCreateRepository, err = org.CanCreateOrgRepo(ctx.ContextUser.ID) op.CanCreateRepository, err = org.CanCreateOrgRepo(ctx, ctx.ContextUser.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err) ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err)
return return
@ -268,7 +268,7 @@ func Create(ctx *context.APIContext) {
Visibility: visibility, Visibility: visibility,
RepoAdminChangeTeamAccess: form.RepoAdminChangeTeamAccess, RepoAdminChangeTeamAccess: form.RepoAdminChangeTeamAccess,
} }
if err := organization.CreateOrganization(org, ctx.Doer); err != nil { if err := organization.CreateOrganization(ctx, org, ctx.Doer); err != nil {
if user_model.IsErrUserAlreadyExist(err) || if user_model.IsErrUserAlreadyExist(err) ||
db.IsErrNameReserved(err) || db.IsErrNameReserved(err) ||
db.IsErrNameCharsNotAllowed(err) || db.IsErrNameCharsNotAllowed(err) ||
@ -429,7 +429,7 @@ func ListOrgActivityFeeds(ctx *context.APIContext) {
includePrivate = true includePrivate = true
} else { } else {
org := organization.OrgFromUser(ctx.ContextUser) org := organization.OrgFromUser(ctx.ContextUser)
isMember, err := org.IsOrgMember(ctx.Doer.ID) isMember, err := org.IsOrgMember(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
return return

View file

@ -572,7 +572,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
} }
var whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64 var whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64
if repo.Owner.IsOrganization() { if repo.Owner.IsOrganization() {
whitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false) whitelistTeams, err = organization.GetTeamIDsByNames(ctx, repo.OwnerID, form.PushWhitelistTeams, false)
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
@ -581,7 +581,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetTeamIDsByNames", err) ctx.Error(http.StatusInternalServerError, "GetTeamIDsByNames", err)
return return
} }
mergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false) mergeWhitelistTeams, err = organization.GetTeamIDsByNames(ctx, repo.OwnerID, form.MergeWhitelistTeams, false)
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
@ -590,7 +590,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetTeamIDsByNames", err) ctx.Error(http.StatusInternalServerError, "GetTeamIDsByNames", err)
return return
} }
approvalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false) approvalsWhitelistTeams, err = organization.GetTeamIDsByNames(ctx, repo.OwnerID, form.ApprovalsWhitelistTeams, false)
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
@ -848,7 +848,7 @@ func EditBranchProtection(ctx *context.APIContext) {
var whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64 var whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64
if repo.Owner.IsOrganization() { if repo.Owner.IsOrganization() {
if form.PushWhitelistTeams != nil { if form.PushWhitelistTeams != nil {
whitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false) whitelistTeams, err = organization.GetTeamIDsByNames(ctx, repo.OwnerID, form.PushWhitelistTeams, false)
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
@ -861,7 +861,7 @@ func EditBranchProtection(ctx *context.APIContext) {
whitelistTeams = protectBranch.WhitelistTeamIDs whitelistTeams = protectBranch.WhitelistTeamIDs
} }
if form.MergeWhitelistTeams != nil { if form.MergeWhitelistTeams != nil {
mergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false) mergeWhitelistTeams, err = organization.GetTeamIDsByNames(ctx, repo.OwnerID, form.MergeWhitelistTeams, false)
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
@ -874,7 +874,7 @@ func EditBranchProtection(ctx *context.APIContext) {
mergeWhitelistTeams = protectBranch.MergeWhitelistTeamIDs mergeWhitelistTeams = protectBranch.MergeWhitelistTeamIDs
} }
if form.ApprovalsWhitelistTeams != nil { if form.ApprovalsWhitelistTeams != nil {
approvalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false) approvalsWhitelistTeams, err = organization.GetTeamIDsByNames(ctx, repo.OwnerID, form.ApprovalsWhitelistTeams, false)
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err) ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)

View file

@ -123,7 +123,7 @@ func CreateFork(ctx *context.APIContext) {
} }
return return
} }
isMember, err := org.IsOrgMember(ctx.Doer.ID) isMember, err := org.IsOrgMember(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
return return

View file

@ -844,7 +844,7 @@ func EditIssue(ctx *context.APIContext) {
} }
if form.State != nil { if form.State != nil {
if issue.IsPull { if issue.IsPull {
if pr, err := issue.GetPullRequest(); err != nil { if pr, err := issue.GetPullRequest(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "GetPullRequest", err) ctx.Error(http.StatusInternalServerError, "GetPullRequest", err)
return return
} else if pr.HasMerged { } else if pr.HasMerged {

View file

@ -178,7 +178,7 @@ func CreateIssueAttachment(ctx *context.APIContext) {
filename = query filename = query
} }
attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, header.Size, &repo_model.Attachment{ attachment, err := attachment.UploadAttachment(ctx, file, setting.Attachment.AllowedTypes, header.Size, &repo_model.Attachment{
Name: filename, Name: filename,
UploaderID: ctx.Doer.ID, UploaderID: ctx.Doer.ID,
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,

View file

@ -182,7 +182,7 @@ func CreateIssueCommentAttachment(ctx *context.APIContext) {
filename = query filename = query
} }
attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, header.Size, &repo_model.Attachment{ attachment, err := attachment.UploadAttachment(ctx, file, setting.Attachment.AllowedTypes, header.Size, &repo_model.Attachment{
Name: filename, Name: filename,
UploaderID: ctx.Doer.ID, UploaderID: ctx.Doer.ID,
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,

View file

@ -241,7 +241,7 @@ func ListPinnedPullRequests(ctx *context.APIContext) {
apiPrs := make([]*api.PullRequest, len(issues)) apiPrs := make([]*api.PullRequest, len(issues))
for i, currentIssue := range issues { for i, currentIssue := range issues {
pr, err := currentIssue.GetPullRequest() pr, err := currentIssue.GetPullRequest(ctx)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetPullRequest", err) ctx.Error(http.StatusInternalServerError, "GetPullRequest", err)
return return

View file

@ -206,7 +206,7 @@ func CheckIssueSubscription(ctx *context.APIContext) {
Ignored: !watching, Ignored: !watching,
Reason: nil, Reason: nil,
CreatedAt: issue.CreatedUnix.AsTime(), CreatedAt: issue.CreatedUnix.AsTime(),
URL: issue.APIURL() + "/subscriptions", URL: issue.APIURL(ctx) + "/subscriptions",
RepositoryURL: ctx.Repo.Repository.APIURL(), RepositoryURL: ctx.Repo.Repository.APIURL(),
}) })
} }

View file

@ -283,7 +283,7 @@ func ResetIssueTime(ctx *context.APIContext) {
return return
} }
err = issues_model.DeleteIssueUserTimes(issue, ctx.Doer) err = issues_model.DeleteIssueUserTimes(ctx, issue, ctx.Doer)
if err != nil { if err != nil {
if db.IsErrNotExist(err) { if db.IsErrNotExist(err) {
ctx.Error(http.StatusNotFound, "DeleteIssueUserTimes", err) ctx.Error(http.StatusNotFound, "DeleteIssueUserTimes", err)
@ -356,7 +356,7 @@ func DeleteTime(ctx *context.APIContext) {
return return
} }
time, err := issues_model.GetTrackedTimeByID(ctx.ParamsInt64(":id")) time, err := issues_model.GetTrackedTimeByID(ctx, ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if db.IsErrNotExist(err) { if db.IsErrNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -376,7 +376,7 @@ func DeleteTime(ctx *context.APIContext) {
return return
} }
err = issues_model.DeleteTime(time) err = issues_model.DeleteTime(ctx, time)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteTime", err) ctx.Error(http.StatusInternalServerError, "DeleteTime", err)
return return

View file

@ -93,7 +93,7 @@ func Migrate(ctx *context.APIContext) {
if repoOwner.IsOrganization() { if repoOwner.IsOrganization() {
// Check ownership of organization. // Check ownership of organization.
isOwner, err := organization.OrgFromUser(repoOwner).IsOwnedBy(ctx.Doer.ID) isOwner, err := organization.OrgFromUser(repoOwner).IsOwnedBy(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOwnedBy", err) ctx.Error(http.StatusInternalServerError, "IsOwnedBy", err)
return return

View file

@ -176,7 +176,7 @@ func ListPushMirrors(ctx *context.APIContext) {
responsePushMirrors := make([]*api.PushMirror, 0, len(pushMirrors)) responsePushMirrors := make([]*api.PushMirror, 0, len(pushMirrors))
for _, mirror := range pushMirrors { for _, mirror := range pushMirrors {
m, err := convert.ToPushMirror(mirror) m, err := convert.ToPushMirror(ctx, mirror)
if err == nil { if err == nil {
responsePushMirrors = append(responsePushMirrors, m) responsePushMirrors = append(responsePushMirrors, m)
} }
@ -232,7 +232,7 @@ func GetPushMirrorByName(ctx *context.APIContext) {
ctx.Error(http.StatusNotFound, "GetPushMirrors", err) ctx.Error(http.StatusNotFound, "GetPushMirrors", err)
return return
} }
m, err := convert.ToPushMirror(pushMirror) m, err := convert.ToPushMirror(ctx, pushMirror)
if err != nil { if err != nil {
ctx.ServerError("GetPushMirrorByRemoteName", err) ctx.ServerError("GetPushMirrorByRemoteName", err)
return return
@ -381,7 +381,7 @@ func CreatePushMirror(ctx *context.APIContext, mirrorOption *api.CreatePushMirro
ctx.ServerError("AddPushMirrorRemote", err) ctx.ServerError("AddPushMirrorRemote", err)
return return
} }
m, err := convert.ToPushMirror(pushMirror) m, err := convert.ToPushMirror(ctx, pushMirror)
if err != nil { if err != nil {
ctx.ServerError("ToPushMirror", err) ctx.ServerError("ToPushMirror", err)
return return

View file

@ -1442,7 +1442,7 @@ func GetPullRequestFiles(ctx *context.APIContext) {
maxLines := setting.Git.MaxGitDiffLines maxLines := setting.Git.MaxGitDiffLines
// FIXME: If there are too many files in the repo, may cause some unpredictable issues. // FIXME: If there are too many files in the repo, may cause some unpredictable issues.
diff, err := gitdiff.GetDiff(baseGitRepo, diff, err := gitdiff.GetDiff(ctx, baseGitRepo,
&gitdiff.DiffOptions{ &gitdiff.DiffOptions{
BeforeCommitID: startCommitID, BeforeCommitID: startCommitID,
AfterCommitID: endCommitID, AfterCommitID: endCommitID,

View file

@ -200,7 +200,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
} }
// Create a new attachment and save the file // Create a new attachment and save the file
attach, err := attachment.UploadAttachment(file, setting.Repository.Release.AllowedTypes, header.Size, &repo_model.Attachment{ attach, err := attachment.UploadAttachment(ctx, file, setting.Repository.Release.AllowedTypes, header.Size, &repo_model.Attachment{
Name: filename, Name: filename,
UploaderID: ctx.Doer.ID, UploaderID: ctx.Doer.ID,
RepoID: release.RepoID, RepoID: release.RepoID,

View file

@ -396,7 +396,7 @@ func Generate(ctx *context.APIContext) {
} }
if !ctx.Doer.IsAdmin { if !ctx.Doer.IsAdmin {
canCreate, err := organization.OrgFromUser(ctxUser).CanCreateOrgRepo(ctx.Doer.ID) canCreate, err := organization.OrgFromUser(ctxUser).CanCreateOrgRepo(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("CanCreateOrgRepo", err) ctx.ServerError("CanCreateOrgRepo", err)
return return
@ -502,7 +502,7 @@ func CreateOrgRepo(ctx *context.APIContext) {
} }
if !ctx.Doer.IsAdmin { if !ctx.Doer.IsAdmin {
canCreate, err := org.CanCreateOrgRepo(ctx.Doer.ID) canCreate, err := org.CanCreateOrgRepo(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err) ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err)
return return
@ -982,7 +982,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error {
} }
if len(units)+len(deleteUnitTypes) > 0 { if len(units)+len(deleteUnitTypes) > 0 {
if err := repo_model.UpdateRepositoryUnits(repo, units, deleteUnitTypes); err != nil { if err := repo_model.UpdateRepositoryUnits(ctx, repo, units, deleteUnitTypes); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRepositoryUnits", err) ctx.Error(http.StatusInternalServerError, "UpdateRepositoryUnits", err)
return err return err
} }

View file

@ -68,7 +68,7 @@ func Transfer(ctx *context.APIContext) {
} }
if newOwner.Type == user_model.UserTypeOrganization { if newOwner.Type == user_model.UserTypeOrganization {
if !ctx.Doer.IsAdmin && newOwner.Visibility == api.VisibleTypePrivate && !organization.OrgFromUser(newOwner).HasMemberWithUserID(ctx.Doer.ID) { if !ctx.Doer.IsAdmin && newOwner.Visibility == api.VisibleTypePrivate && !organization.OrgFromUser(newOwner).HasMemberWithUserID(ctx, ctx.Doer.ID) {
// The user shouldn't know about this organization // The user shouldn't know about this organization
ctx.Error(http.StatusNotFound, "", "The new owner does not exist or cannot be found") ctx.Error(http.StatusNotFound, "", "The new owner does not exist or cannot be found")
return return

View file

@ -24,7 +24,7 @@ func Notices(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.notices") ctx.Data["Title"] = ctx.Tr("admin.notices")
ctx.Data["PageIsAdminNotices"] = true ctx.Data["PageIsAdminNotices"] = true
total := system_model.CountNotices() total := system_model.CountNotices(ctx)
page := ctx.FormInt("page") page := ctx.FormInt("page")
if page <= 1 { if page <= 1 {
page = 1 page = 1

View file

@ -290,7 +290,7 @@ func ViewUser(ctx *context.Context) {
ctx.Data["Emails"] = emails ctx.Data["Emails"] = emails
ctx.Data["EmailsTotal"] = len(emails) ctx.Data["EmailsTotal"] = len(emails)
orgs, err := org_model.FindOrgs(org_model.FindOrgOptions{ orgs, err := org_model.FindOrgs(ctx, org_model.FindOrgOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
ListAll: true, ListAll: true,
}, },

View file

@ -312,12 +312,12 @@ func getOAuthGroupsForUser(ctx go_context.Context, user *user_model.User) ([]str
var groups []string var groups []string
for _, org := range orgs { for _, org := range orgs {
groups = append(groups, org.Name) groups = append(groups, org.Name)
teams, err := org.LoadTeams() teams, err := org.LoadTeams(ctx)
if err != nil { if err != nil {
return nil, fmt.Errorf("LoadTeams: %w", err) return nil, fmt.Errorf("LoadTeams: %w", err)
} }
for _, team := range teams { for _, team := range teams {
if team.IsMember(user.ID) { if team.IsMember(ctx, user.ID) {
groups = append(groups, org.Name+":"+team.LowerName) groups = append(groups, org.Name+":"+team.LowerName)
} }
} }

View file

@ -38,7 +38,7 @@ func Members(ctx *context.Context) {
} }
if ctx.Doer != nil { if ctx.Doer != nil {
isMember, err := ctx.Org.Organization.IsOrgMember(ctx.Doer.ID) isMember, err := ctx.Org.Organization.IsOrgMember(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsOrgMember") ctx.Error(http.StatusInternalServerError, "IsOrgMember")
return return
@ -47,7 +47,7 @@ func Members(ctx *context.Context) {
} }
ctx.Data["PublicOnly"] = opts.PublicOnly ctx.Data["PublicOnly"] = opts.PublicOnly
total, err := organization.CountOrgMembers(opts) total, err := organization.CountOrgMembers(ctx, opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CountOrgMembers") ctx.Error(http.StatusInternalServerError, "CountOrgMembers")
return return
@ -70,7 +70,7 @@ func Members(ctx *context.Context) {
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.Data["Members"] = members ctx.Data["Members"] = members
ctx.Data["MembersIsPublicMember"] = membersIsPublic ctx.Data["MembersIsPublicMember"] = membersIsPublic
ctx.Data["MembersIsUserOrgOwner"] = organization.IsUserOrgOwner(members, org.ID) ctx.Data["MembersIsUserOrgOwner"] = organization.IsUserOrgOwner(ctx, members, org.ID)
ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus(ctx) ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus(ctx)
ctx.HTML(http.StatusOK, tplMembers) ctx.HTML(http.StatusOK, tplMembers)
@ -92,13 +92,13 @@ func MembersAction(ctx *context.Context) {
ctx.Error(http.StatusNotFound) ctx.Error(http.StatusNotFound)
return return
} }
err = organization.ChangeOrgUserStatus(org.ID, uid, false) err = organization.ChangeOrgUserStatus(ctx, org.ID, uid, false)
case "public": case "public":
if ctx.Doer.ID != uid && !ctx.Org.IsOwner { if ctx.Doer.ID != uid && !ctx.Org.IsOwner {
ctx.Error(http.StatusNotFound) ctx.Error(http.StatusNotFound)
return return
} }
err = organization.ChangeOrgUserStatus(org.ID, uid, true) err = organization.ChangeOrgUserStatus(ctx, org.ID, uid, true)
case "remove": case "remove":
if !ctx.Org.IsOwner { if !ctx.Org.IsOwner {
ctx.Error(http.StatusNotFound) ctx.Error(http.StatusNotFound)

View file

@ -58,7 +58,7 @@ func CreatePost(ctx *context.Context) {
RepoAdminChangeTeamAccess: form.RepoAdminChangeTeamAccess, RepoAdminChangeTeamAccess: form.RepoAdminChangeTeamAccess,
} }
if err := organization.CreateOrganization(org, ctx.Doer); err != nil { if err := organization.CreateOrganization(ctx, org, ctx.Doer); err != nil {
ctx.Data["Err_OrgName"] = true ctx.Data["Err_OrgName"] = true
switch { switch {
case user_model.IsErrUserAlreadyExist(err): case user_model.IsErrUserAlreadyExist(err):

View file

@ -159,7 +159,7 @@ func TeamsAction(ctx *context.Context) {
return return
} }
if ctx.Org.Team.IsMember(u.ID) { if ctx.Org.Team.IsMember(ctx, u.ID) {
ctx.Flash.Error(ctx.Tr("org.teams.add_duplicate_users")) ctx.Flash.Error(ctx.Tr("org.teams.add_duplicate_users"))
} else { } else {
err = models.AddTeamMember(ctx, ctx.Org.Team, u.ID) err = models.AddTeamMember(ctx, ctx.Org.Team, u.ID)

View file

@ -608,7 +608,7 @@ func disableOrEnableWorkflowFile(ctx *context_module.Context, isEnable bool) {
cfg.DisableWorkflow(workflow) cfg.DisableWorkflow(workflow)
} }
if err := repo_model.UpdateRepoUnit(cfgUnit); err != nil { if err := repo_model.UpdateRepoUnit(ctx, cfgUnit); err != nil {
ctx.ServerError("UpdateRepoUnit", err) ctx.ServerError("UpdateRepoUnit", err)
return return
} }

View file

@ -45,7 +45,7 @@ func uploadAttachment(ctx *context.Context, repoID int64, allowedTypes string) {
} }
defer file.Close() defer file.Close()
attach, err := attachment.UploadAttachment(file, allowedTypes, header.Size, &repo_model.Attachment{ attach, err := attachment.UploadAttachment(ctx, file, allowedTypes, header.Size, &repo_model.Attachment{
Name: header.Filename, Name: header.Filename,
UploaderID: ctx.Doer.ID, UploaderID: ctx.Doer.ID,
RepoID: repoID, RepoID: repoID,

View file

@ -305,7 +305,7 @@ func Diff(ctx *context.Context) {
maxLines, maxFiles = -1, -1 maxLines, maxFiles = -1, -1
} }
diff, err := gitdiff.GetDiff(gitRepo, &gitdiff.DiffOptions{ diff, err := gitdiff.GetDiff(ctx, gitRepo, &gitdiff.DiffOptions{
AfterCommitID: commitID, AfterCommitID: commitID,
SkipTo: ctx.FormString("skip-to"), SkipTo: ctx.FormString("skip-to"),
MaxLines: maxLines, MaxLines: maxLines,

View file

@ -609,7 +609,7 @@ func PrepareCompareDiff(
maxLines, maxFiles = -1, -1 maxLines, maxFiles = -1, -1
} }
diff, err := gitdiff.GetDiff(ci.HeadGitRepo, diff, err := gitdiff.GetDiff(ctx, ci.HeadGitRepo,
&gitdiff.DiffOptions{ &gitdiff.DiffOptions{
BeforeCommitID: beforeCommitID, BeforeCommitID: beforeCommitID,
AfterCommitID: headCommitID, AfterCommitID: headCommitID,

View file

@ -305,7 +305,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
// Check read status // Check read status
if !ctx.IsSigned { if !ctx.IsSigned {
issues[i].IsRead = true issues[i].IsRead = true
} else if err = issues[i].GetIsRead(ctx.Doer.ID); err != nil { } else if err = issues[i].GetIsRead(ctx, ctx.Doer.ID); err != nil {
ctx.ServerError("GetIsRead", err) ctx.ServerError("GetIsRead", err)
return return
} }
@ -1270,7 +1270,7 @@ func roleDescriptor(ctx stdCtx.Context, repo *repo_model.Repository, poster *use
} }
// Otherwise check if poster is the real repo admin. // Otherwise check if poster is the real repo admin.
ok, err := access_model.IsUserRealRepoAdmin(repo, poster) ok, err := access_model.IsUserRealRepoAdmin(ctx, repo, poster)
if err != nil { if err != nil {
return roleDescriptor, err return roleDescriptor, err
} }
@ -1554,7 +1554,7 @@ func ViewIssue(ctx *context.Context) {
} else { } else {
ctx.Data["CanUseTimetracker"] = false ctx.Data["CanUseTimetracker"] = false
} }
if ctx.Data["WorkingUsers"], err = issues_model.TotalTimesForEachUser(&issues_model.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil { if ctx.Data["WorkingUsers"], err = issues_model.TotalTimesForEachUser(ctx, &issues_model.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
ctx.ServerError("TotalTimesForEachUser", err) ctx.ServerError("TotalTimesForEachUser", err)
return return
} }
@ -1728,7 +1728,7 @@ func ViewIssue(ctx *context.Context) {
comment.Type == issues_model.CommentTypeStopTracking || comment.Type == issues_model.CommentTypeStopTracking ||
comment.Type == issues_model.CommentTypeDeleteTimeManual { comment.Type == issues_model.CommentTypeDeleteTimeManual {
// drop error since times could be pruned from DB.. // drop error since times could be pruned from DB..
_ = comment.LoadTime() _ = comment.LoadTime(ctx)
if comment.Content != "" { if comment.Content != "" {
// Content before v1.21 did store the formated string instead of seconds, // Content before v1.21 did store the formated string instead of seconds,
// so "|" is used as delimeter to mark the new format // so "|" is used as delimeter to mark the new format
@ -3579,7 +3579,7 @@ func handleTeamMentions(ctx *context.Context) {
if ctx.Doer.IsAdmin { if ctx.Doer.IsAdmin {
isAdmin = true isAdmin = true
} else { } else {
isAdmin, err = org.IsOwnedBy(ctx.Doer.ID) isAdmin, err = org.IsOwnedBy(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("IsOwnedBy", err) ctx.ServerError("IsOwnedBy", err)
return return
@ -3587,13 +3587,13 @@ func handleTeamMentions(ctx *context.Context) {
} }
if isAdmin { if isAdmin {
teams, err = org.LoadTeams() teams, err = org.LoadTeams(ctx)
if err != nil { if err != nil {
ctx.ServerError("LoadTeams", err) ctx.ServerError("LoadTeams", err)
return return
} }
} else { } else {
teams, err = org.GetUserTeams(ctx.Doer.ID) teams, err = org.GetUserTeams(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("GetUserTeams", err) ctx.ServerError("GetUserTeams", err)
return return

View file

@ -85,7 +85,7 @@ func RetrieveLabels(ctx *context.Context) {
return return
} }
if ctx.Doer != nil { if ctx.Doer != nil {
ctx.Org.IsOwner, err = org.IsOwnedBy(ctx.Doer.ID) ctx.Org.IsOwner, err = org.IsOwnedBy(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("org.IsOwnedBy", err) ctx.ServerError("org.IsOwnedBy", err)
return return

View file

@ -61,7 +61,7 @@ func DeleteTime(c *context.Context) {
return return
} }
t, err := issues_model.GetTrackedTimeByID(c.ParamsInt64(":timeid")) t, err := issues_model.GetTrackedTimeByID(c, c.ParamsInt64(":timeid"))
if err != nil { if err != nil {
if db.IsErrNotExist(err) { if db.IsErrNotExist(err) {
c.NotFound("time not found", err) c.NotFound("time not found", err)
@ -77,7 +77,7 @@ func DeleteTime(c *context.Context) {
return return
} }
if err = issues_model.DeleteTime(t); err != nil { if err = issues_model.DeleteTime(c, t); err != nil {
c.ServerError("DeleteTime", err) c.ServerError("DeleteTime", err)
return return
} }

View file

@ -265,7 +265,7 @@ func ForkPost(ctx *context.Context) {
// Check if user is allowed to create repo's on the organization. // Check if user is allowed to create repo's on the organization.
if ctxUser.IsOrganization() { if ctxUser.IsOrganization() {
isAllowedToFork, err := organization.OrgFromUser(ctxUser).CanCreateOrgRepo(ctx.Doer.ID) isAllowedToFork, err := organization.OrgFromUser(ctxUser).CanCreateOrgRepo(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("CanCreateOrgRepo", err) ctx.ServerError("CanCreateOrgRepo", err)
return return
@ -908,7 +908,7 @@ func viewPullFiles(ctx *context.Context, specifiedStartCommit, specifiedEndCommi
// as the viewed information is designed to be loaded only on latest PR // as the viewed information is designed to be loaded only on latest PR
// diff and if you're signed in. // diff and if you're signed in.
if !ctx.IsSigned || willShowSpecifiedCommit || willShowSpecifiedCommitRange { if !ctx.IsSigned || willShowSpecifiedCommit || willShowSpecifiedCommitRange {
diff, err = gitdiff.GetDiff(gitRepo, diffOptions, files...) diff, err = gitdiff.GetDiff(ctx, gitRepo, diffOptions, files...)
methodWithError = "GetDiff" methodWithError = "GetDiff"
} else { } else {
diff, err = gitdiff.SyncAndGetUserSpecificDiff(ctx, ctx.Doer.ID, pull, gitRepo, diffOptions, files...) diff, err = gitdiff.SyncAndGetUserSpecificDiff(ctx, ctx.Doer.ID, pull, gitRepo, diffOptions, files...)

View file

@ -119,7 +119,7 @@ func checkContextUser(ctx *context.Context, uid int64) *user_model.User {
return nil return nil
} }
if !ctx.Doer.IsAdmin { if !ctx.Doer.IsAdmin {
canCreate, err := organization.OrgFromUser(org).CanCreateOrgRepo(ctx.Doer.ID) canCreate, err := organization.OrgFromUser(org).CanCreateOrgRepo(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("CanCreateOrgRepo", err) ctx.ServerError("CanCreateOrgRepo", err)
return nil return nil

View file

@ -70,7 +70,7 @@ func SettingsProtectedBranch(c *context.Context) {
c.Data["PageIsSettingsBranches"] = true c.Data["PageIsSettingsBranches"] = true
c.Data["Title"] = c.Tr("repo.settings.protected_branch") + " - " + rule.RuleName c.Data["Title"] = c.Tr("repo.settings.protected_branch") + " - " + rule.RuleName
users, err := access_model.GetRepoReaders(c.Repo.Repository) users, err := access_model.GetRepoReaders(c, c.Repo.Repository)
if err != nil { if err != nil {
c.ServerError("Repo.Repository.GetReaders", err) c.ServerError("Repo.Repository.GetReaders", err)
return return
@ -84,7 +84,7 @@ func SettingsProtectedBranch(c *context.Context) {
c.Data["recent_status_checks"] = contexts c.Data["recent_status_checks"] = contexts
if c.Repo.Owner.IsOrganization() { if c.Repo.Owner.IsOrganization() {
teams, err := organization.OrgFromUser(c.Repo.Owner).TeamsWithAccessToRepo(c.Repo.Repository.ID, perm.AccessModeRead) teams, err := organization.OrgFromUser(c.Repo.Owner).TeamsWithAccessToRepo(c, c.Repo.Repository.ID, perm.AccessModeRead)
if err != nil { if err != nil {
c.ServerError("Repo.Owner.TeamsWithAccessToRepo", err) c.ServerError("Repo.Owner.TeamsWithAccessToRepo", err)
return return

View file

@ -147,7 +147,7 @@ func setTagsContext(ctx *context.Context) error {
} }
ctx.Data["ProtectedTags"] = protectedTags ctx.Data["ProtectedTags"] = protectedTags
users, err := access_model.GetRepoReaders(ctx.Repo.Repository) users, err := access_model.GetRepoReaders(ctx, ctx.Repo.Repository)
if err != nil { if err != nil {
ctx.ServerError("Repo.Repository.GetReaders", err) ctx.ServerError("Repo.Repository.GetReaders", err)
return err return err
@ -155,7 +155,7 @@ func setTagsContext(ctx *context.Context) error {
ctx.Data["Users"] = users ctx.Data["Users"] = users
if ctx.Repo.Owner.IsOrganization() { if ctx.Repo.Owner.IsOrganization() {
teams, err := organization.OrgFromUser(ctx.Repo.Owner).TeamsWithAccessToRepo(ctx.Repo.Repository.ID, perm.AccessModeRead) teams, err := organization.OrgFromUser(ctx.Repo.Owner).TeamsWithAccessToRepo(ctx, ctx.Repo.Repository.ID, perm.AccessModeRead)
if err != nil { if err != nil {
ctx.ServerError("Repo.Owner.TeamsWithAccessToRepo", err) ctx.ServerError("Repo.Owner.TeamsWithAccessToRepo", err)
return err return err

View file

@ -594,7 +594,7 @@ func SettingsPost(ctx *context.Context) {
return return
} }
if err := repo_model.UpdateRepositoryUnits(repo, units, deleteUnitTypes); err != nil { if err := repo_model.UpdateRepositoryUnits(ctx, repo, units, deleteUnitTypes); err != nil {
ctx.ServerError("UpdateRepositoryUnits", err) ctx.ServerError("UpdateRepositoryUnits", err)
return return
} }
@ -761,7 +761,7 @@ func SettingsPost(ctx *context.Context) {
} }
if newOwner.Type == user_model.UserTypeOrganization { if newOwner.Type == user_model.UserTypeOrganization {
if !ctx.Doer.IsAdmin && newOwner.Visibility == structs.VisibleTypePrivate && !organization.OrgFromUser(newOwner).HasMemberWithUserID(ctx.Doer.ID) { if !ctx.Doer.IsAdmin && newOwner.Visibility == structs.VisibleTypePrivate && !organization.OrgFromUser(newOwner).HasMemberWithUserID(ctx, ctx.Doer.ID) {
// The user shouldn't know about this organization // The user shouldn't know about this organization
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil) ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
return return

View file

@ -57,7 +57,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) {
} }
showPrivate := ctx.IsSigned && (ctx.Doer.IsAdmin || ctx.Doer.ID == ctx.ContextUser.ID) showPrivate := ctx.IsSigned && (ctx.Doer.IsAdmin || ctx.Doer.ID == ctx.ContextUser.ID)
orgs, err := organization.FindOrgs(organization.FindOrgOptions{ orgs, err := organization.FindOrgs(ctx, organization.FindOrgOptions{
UserID: ctx.ContextUser.ID, UserID: ctx.ContextUser.ID,
IncludePrivate: showPrivate, IncludePrivate: showPrivate,
}) })
@ -66,7 +66,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) {
return return
} }
ctx.Data["Orgs"] = orgs ctx.Data["Orgs"] = orgs
ctx.Data["HasOrgsVisible"] = organization.HasOrgsVisible(orgs, ctx.Doer) ctx.Data["HasOrgsVisible"] = organization.HasOrgsVisible(ctx, orgs, ctx.Doer)
badges, _, err := user_model.GetUserBadges(ctx, ctx.ContextUser) badges, _, err := user_model.GetUserBadges(ctx, ctx.ContextUser)
if err != nil { if err != nil {

View file

@ -219,12 +219,12 @@ func Organization(ctx *context.Context) {
opts.Page = 1 opts.Page = 1
} }
orgs, err := organization.FindOrgs(opts) orgs, err := organization.FindOrgs(ctx, opts)
if err != nil { if err != nil {
ctx.ServerError("FindOrgs", err) ctx.ServerError("FindOrgs", err)
return return
} }
total, err := organization.CountOrgs(opts) total, err := organization.CountOrgs(ctx, opts)
if err != nil { if err != nil {
ctx.ServerError("CountOrgs", err) ctx.ServerError("CountOrgs", err)
return return

View file

@ -19,12 +19,12 @@ import (
) )
// NewAttachment creates a new attachment object, but do not verify. // NewAttachment creates a new attachment object, but do not verify.
func NewAttachment(attach *repo_model.Attachment, file io.Reader, size int64) (*repo_model.Attachment, error) { func NewAttachment(ctx context.Context, attach *repo_model.Attachment, file io.Reader, size int64) (*repo_model.Attachment, error) {
if attach.RepoID == 0 { if attach.RepoID == 0 {
return nil, fmt.Errorf("attachment %s should belong to a repository", attach.Name) return nil, fmt.Errorf("attachment %s should belong to a repository", attach.Name)
} }
err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { err := db.WithTx(ctx, func(ctx context.Context) error {
attach.UUID = uuid.New().String() attach.UUID = uuid.New().String()
size, err := storage.Attachments.Save(attach.RelativePath(), file, size) size, err := storage.Attachments.Save(attach.RelativePath(), file, size)
if err != nil { if err != nil {
@ -39,7 +39,7 @@ func NewAttachment(attach *repo_model.Attachment, file io.Reader, size int64) (*
} }
// UploadAttachment upload new attachment into storage and update database // UploadAttachment upload new attachment into storage and update database
func UploadAttachment(file io.Reader, allowedTypes string, fileSize int64, opts *repo_model.Attachment) (*repo_model.Attachment, error) { func UploadAttachment(ctx context.Context, file io.Reader, allowedTypes string, fileSize int64, opts *repo_model.Attachment) (*repo_model.Attachment, error) {
buf := make([]byte, 1024) buf := make([]byte, 1024)
n, _ := util.ReadAtMost(file, buf) n, _ := util.ReadAtMost(file, buf)
buf = buf[:n] buf = buf[:n]
@ -48,5 +48,5 @@ func UploadAttachment(file io.Reader, allowedTypes string, fileSize int64, opts
return nil, err return nil, err
} }
return NewAttachment(opts, io.MultiReader(bytes.NewReader(buf), file), fileSize) return NewAttachment(ctx, opts, io.MultiReader(bytes.NewReader(buf), file), fileSize)
} }

View file

@ -32,7 +32,7 @@ func TestUploadAttachment(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
defer f.Close() defer f.Close()
attach, err := NewAttachment(&repo_model.Attachment{ attach, err := NewAttachment(db.DefaultContext, &repo_model.Attachment{
RepoID: 1, RepoID: 1,
UploaderID: user.ID, UploaderID: user.ID,
Name: filepath.Base(fPath), Name: filepath.Base(fPath),

View file

@ -119,15 +119,15 @@ func ToBranchProtection(ctx context.Context, bp *git_model.ProtectedBranch) *api
if err != nil { if err != nil {
log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err) log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err)
} }
pushWhitelistTeams, err := organization.GetTeamNamesByID(bp.WhitelistTeamIDs) pushWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.WhitelistTeamIDs)
if err != nil { if err != nil {
log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err) log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
} }
mergeWhitelistTeams, err := organization.GetTeamNamesByID(bp.MergeWhitelistTeamIDs) mergeWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.MergeWhitelistTeamIDs)
if err != nil { if err != nil {
log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err) log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
} }
approvalsWhitelistTeams, err := organization.GetTeamNamesByID(bp.ApprovalsWhitelistTeamIDs) approvalsWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.ApprovalsWhitelistTeamIDs)
if err != nil { if err != nil {
log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err) log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err)
} }

View file

@ -210,7 +210,7 @@ func ToCommit(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Rep
// Get diff stats for commit // Get diff stats for commit
if opts.Stat { if opts.Stat {
diff, err := gitdiff.GetDiff(gitRepo, &gitdiff.DiffOptions{ diff, err := gitdiff.GetDiff(ctx, gitRepo, &gitdiff.DiffOptions{
AfterCommitID: commit.ID.String(), AfterCommitID: commit.ID.String(),
}) })
if err != nil { if err != nil {

View file

@ -62,7 +62,7 @@ func toIssue(ctx context.Context, issue *issues_model.Issue, getDownloadURL func
if err := issue.Repo.LoadOwner(ctx); err != nil { if err := issue.Repo.LoadOwner(ctx); err != nil {
return &api.Issue{} return &api.Issue{}
} }
apiIssue.URL = issue.APIURL() apiIssue.URL = issue.APIURL(ctx)
apiIssue.HTMLURL = issue.HTMLURL() apiIssue.HTMLURL = issue.HTMLURL()
apiIssue.Labels = ToLabelList(issue.Labels, issue.Repo, issue.Repo.Owner) apiIssue.Labels = ToLabelList(issue.Labels, issue.Repo, issue.Repo.Owner)
apiIssue.Repo = &api.RepositoryMeta{ apiIssue.Repo = &api.RepositoryMeta{

View file

@ -55,7 +55,7 @@ func ToTimelineComment(ctx context.Context, repo *repo_model.Repository, c *issu
return nil return nil
} }
err = c.LoadTime() err = c.LoadTime(ctx)
if err != nil { if err != nil {
log.Error("LoadTime: %v", err) log.Error("LoadTime: %v", err)
return nil return nil

View file

@ -4,13 +4,15 @@
package convert package convert
import ( import (
"context"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
) )
// ToPushMirror convert from repo_model.PushMirror and remoteAddress to api.TopicResponse // ToPushMirror convert from repo_model.PushMirror and remoteAddress to api.TopicResponse
func ToPushMirror(pm *repo_model.PushMirror) (*api.PushMirror, error) { func ToPushMirror(ctx context.Context, pm *repo_model.PushMirror) (*api.PushMirror, error) {
repo := pm.GetRepository() repo := pm.GetRepository(ctx)
return &api.PushMirror{ return &api.PushMirror{
RepoName: repo.Name, RepoName: repo.Name,
RemoteName: pm.RemoteName, RemoteName: pm.RemoteName,

View file

@ -39,10 +39,10 @@ func ToNotificationThread(ctx context.Context, n *activities_model.Notification)
result.Subject = &api.NotificationSubject{Type: api.NotifySubjectIssue} result.Subject = &api.NotificationSubject{Type: api.NotifySubjectIssue}
if n.Issue != nil { if n.Issue != nil {
result.Subject.Title = n.Issue.Title result.Subject.Title = n.Issue.Title
result.Subject.URL = n.Issue.APIURL() result.Subject.URL = n.Issue.APIURL(ctx)
result.Subject.HTMLURL = n.Issue.HTMLURL() result.Subject.HTMLURL = n.Issue.HTMLURL()
result.Subject.State = n.Issue.State() result.Subject.State = n.Issue.State()
comment, err := n.Issue.GetLastComment() comment, err := n.Issue.GetLastComment(ctx)
if err == nil && comment != nil { if err == nil && comment != nil {
result.Subject.LatestCommentURL = comment.APIURL(ctx) result.Subject.LatestCommentURL = comment.APIURL(ctx)
result.Subject.LatestCommentHTMLURL = comment.HTMLURL(ctx) result.Subject.LatestCommentHTMLURL = comment.HTMLURL(ctx)
@ -52,16 +52,16 @@ func ToNotificationThread(ctx context.Context, n *activities_model.Notification)
result.Subject = &api.NotificationSubject{Type: api.NotifySubjectPull} result.Subject = &api.NotificationSubject{Type: api.NotifySubjectPull}
if n.Issue != nil { if n.Issue != nil {
result.Subject.Title = n.Issue.Title result.Subject.Title = n.Issue.Title
result.Subject.URL = n.Issue.APIURL() result.Subject.URL = n.Issue.APIURL(ctx)
result.Subject.HTMLURL = n.Issue.HTMLURL() result.Subject.HTMLURL = n.Issue.HTMLURL()
result.Subject.State = n.Issue.State() result.Subject.State = n.Issue.State()
comment, err := n.Issue.GetLastComment() comment, err := n.Issue.GetLastComment(ctx)
if err == nil && comment != nil { if err == nil && comment != nil {
result.Subject.LatestCommentURL = comment.APIURL(ctx) result.Subject.LatestCommentURL = comment.APIURL(ctx)
result.Subject.LatestCommentHTMLURL = comment.HTMLURL(ctx) result.Subject.LatestCommentHTMLURL = comment.HTMLURL(ctx)
} }
pr, _ := n.Issue.GetPullRequest() pr, _ := n.Issue.GetPullRequest(ctx)
if pr != nil && pr.HasMerged { if pr != nil && pr.HasMerged {
result.Subject.State = "merged" result.Subject.State = "merged"
} }

View file

@ -8,6 +8,7 @@ import (
"strings" "strings"
"testing" "testing"
"code.gitea.io/gitea/models/db"
csv_module "code.gitea.io/gitea/modules/csv" csv_module "code.gitea.io/gitea/modules/csv"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -190,7 +191,7 @@ c,d,e`,
} }
for n, c := range cases { for n, c := range cases {
diff, err := ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.diff), "") diff, err := ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.diff), "")
if err != nil { if err != nil {
t.Errorf("ParsePatch failed: %s", err) t.Errorf("ParsePatch failed: %s", err)
} }

View file

@ -494,7 +494,7 @@ func (diff *Diff) LoadComments(ctx context.Context, issue *issues_model.Issue, c
const cmdDiffHead = "diff --git " const cmdDiffHead = "diff --git "
// ParsePatch builds a Diff object from a io.Reader and some parameters. // ParsePatch builds a Diff object from a io.Reader and some parameters.
func ParsePatch(maxLines, maxLineCharacters, maxFiles int, reader io.Reader, skipToFile string) (*Diff, error) { func ParsePatch(ctx context.Context, maxLines, maxLineCharacters, maxFiles int, reader io.Reader, skipToFile string) (*Diff, error) {
log.Debug("ParsePatch(%d, %d, %d, ..., %s)", maxLines, maxLineCharacters, maxFiles, skipToFile) log.Debug("ParsePatch(%d, %d, %d, ..., %s)", maxLines, maxLineCharacters, maxFiles, skipToFile)
var curFile *DiffFile var curFile *DiffFile
@ -709,7 +709,7 @@ parsingLoop:
curFile.IsAmbiguous = false curFile.IsAmbiguous = false
} }
// Otherwise do nothing with this line, but now switch to parsing hunks // Otherwise do nothing with this line, but now switch to parsing hunks
lineBytes, isFragment, err := parseHunks(curFile, maxLines, maxLineCharacters, input) lineBytes, isFragment, err := parseHunks(ctx, curFile, maxLines, maxLineCharacters, input)
diff.TotalAddition += curFile.Addition diff.TotalAddition += curFile.Addition
diff.TotalDeletion += curFile.Deletion diff.TotalDeletion += curFile.Deletion
if err != nil { if err != nil {
@ -818,7 +818,7 @@ func skipToNextDiffHead(input *bufio.Reader) (line string, err error) {
return line, err return line, err
} }
func parseHunks(curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio.Reader) (lineBytes []byte, isFragment bool, err error) { func parseHunks(ctx context.Context, curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio.Reader) (lineBytes []byte, isFragment bool, err error) {
sb := strings.Builder{} sb := strings.Builder{}
var ( var (
@ -995,7 +995,7 @@ func parseHunks(curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio
oid := strings.TrimPrefix(line[1:], lfs.MetaFileOidPrefix) oid := strings.TrimPrefix(line[1:], lfs.MetaFileOidPrefix)
if len(oid) == 64 { if len(oid) == 64 {
m := &git_model.LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}} m := &git_model.LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}
count, err := db.CountByBean(db.DefaultContext, m) count, err := db.CountByBean(ctx, m)
if err == nil && count > 0 { if err == nil && count > 0 {
curFile.IsBin = true curFile.IsBin = true
@ -1106,7 +1106,7 @@ type DiffOptions struct {
// GetDiff builds a Diff between two commits of a repository. // GetDiff builds a Diff between two commits of a repository.
// Passing the empty string as beforeCommitID returns a diff from the parent commit. // Passing the empty string as beforeCommitID returns a diff from the parent commit.
// The whitespaceBehavior is either an empty string or a git flag // The whitespaceBehavior is either an empty string or a git flag
func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff, error) { func GetDiff(ctx context.Context, gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff, error) {
repoPath := gitRepo.Path repoPath := gitRepo.Path
commit, err := gitRepo.GetCommit(opts.AfterCommitID) commit, err := gitRepo.GetCommit(opts.AfterCommitID)
@ -1165,7 +1165,7 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
_ = writer.Close() _ = writer.Close()
}() }()
diff, err := ParsePatch(opts.MaxLines, opts.MaxLineCharacters, opts.MaxFiles, reader, parsePatchSkipToFile) diff, err := ParsePatch(ctx, opts.MaxLines, opts.MaxLineCharacters, opts.MaxFiles, reader, parsePatchSkipToFile)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to ParsePatch: %w", err) return nil, fmt.Errorf("unable to ParsePatch: %w", err)
} }
@ -1280,7 +1280,7 @@ func GetPullDiffStats(gitRepo *git.Repository, opts *DiffOptions) (*PullDiffStat
// SyncAndGetUserSpecificDiff is like GetDiff, except that user specific data such as which files the given user has already viewed on the given PR will also be set // SyncAndGetUserSpecificDiff is like GetDiff, except that user specific data such as which files the given user has already viewed on the given PR will also be set
// Additionally, the database asynchronously is updated if files have changed since the last review // Additionally, the database asynchronously is updated if files have changed since the last review
func SyncAndGetUserSpecificDiff(ctx context.Context, userID int64, pull *issues_model.PullRequest, gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff, error) { func SyncAndGetUserSpecificDiff(ctx context.Context, userID int64, pull *issues_model.PullRequest, gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff, error) {
diff, err := GetDiff(gitRepo, opts, files...) diff, err := GetDiff(ctx, gitRepo, opts, files...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1347,8 +1347,8 @@ outer:
} }
// CommentAsDiff returns c.Patch as *Diff // CommentAsDiff returns c.Patch as *Diff
func CommentAsDiff(c *issues_model.Comment) (*Diff, error) { func CommentAsDiff(ctx context.Context, c *issues_model.Comment) (*Diff, error) {
diff, err := ParsePatch(setting.Git.MaxGitDiffLines, diff, err := ParsePatch(ctx, setting.Git.MaxGitDiffLines,
setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.Patch), "") setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.Patch), "")
if err != nil { if err != nil {
log.Error("Unable to parse patch: %v", err) log.Error("Unable to parse patch: %v", err)
@ -1365,7 +1365,7 @@ func CommentAsDiff(c *issues_model.Comment) (*Diff, error) {
} }
// CommentMustAsDiff executes AsDiff and logs the error instead of returning // CommentMustAsDiff executes AsDiff and logs the error instead of returning
func CommentMustAsDiff(c *issues_model.Comment) *Diff { func CommentMustAsDiff(ctx context.Context, c *issues_model.Comment) *Diff {
if c == nil { if c == nil {
return nil return nil
} }
@ -1374,7 +1374,7 @@ func CommentMustAsDiff(c *issues_model.Comment) *Diff {
log.Error("PANIC whilst retrieving diff for comment[%d] Error: %v\nStack: %s", c.ID, err, log.Stack(2)) log.Error("PANIC whilst retrieving diff for comment[%d] Error: %v\nStack: %s", c.ID, err, log.Stack(2))
} }
}() }()
diff, err := CommentAsDiff(c) diff, err := CommentAsDiff(ctx, c)
if err != nil { if err != nil {
log.Warn("CommentMustAsDiff: %v", err) log.Warn("CommentMustAsDiff: %v", err)
} }

View file

@ -175,7 +175,7 @@ diff --git "\\a/README.md" "\\b/README.md"
} }
for _, testcase := range tests { for _, testcase := range tests {
t.Run(testcase.name, func(t *testing.T) { t.Run(testcase.name, func(t *testing.T) {
got, err := ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff), testcase.skipTo) got, err := ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff), testcase.skipTo)
if (err != nil) != testcase.wantErr { if (err != nil) != testcase.wantErr {
t.Errorf("ParsePatch(%q) error = %v, wantErr %v", testcase.name, err, testcase.wantErr) t.Errorf("ParsePatch(%q) error = %v, wantErr %v", testcase.name, err, testcase.wantErr)
return return
@ -400,7 +400,7 @@ index 6961180..9ba1a00 100644
for _, testcase := range tests { for _, testcase := range tests {
t.Run(testcase.name, func(t *testing.T) { t.Run(testcase.name, func(t *testing.T) {
got, err := ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff), "") got, err := ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff), "")
if (err != nil) != testcase.wantErr { if (err != nil) != testcase.wantErr {
t.Errorf("ParsePatch(%q) error = %v, wantErr %v", testcase.name, err, testcase.wantErr) t.Errorf("ParsePatch(%q) error = %v, wantErr %v", testcase.name, err, testcase.wantErr)
return return
@ -449,21 +449,21 @@ index 0000000..6bb8f39
diffBuilder.WriteString("+line" + strconv.Itoa(i) + "\n") diffBuilder.WriteString("+line" + strconv.Itoa(i) + "\n")
} }
diff = diffBuilder.String() diff = diffBuilder.String()
result, err := ParsePatch(20, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "") result, err := ParsePatch(db.DefaultContext, 20, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "")
if err != nil { if err != nil {
t.Errorf("There should not be an error: %v", err) t.Errorf("There should not be an error: %v", err)
} }
if !result.Files[0].IsIncomplete { if !result.Files[0].IsIncomplete {
t.Errorf("Files should be incomplete! %v", result.Files[0]) t.Errorf("Files should be incomplete! %v", result.Files[0])
} }
result, err = ParsePatch(40, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "") result, err = ParsePatch(db.DefaultContext, 40, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "")
if err != nil { if err != nil {
t.Errorf("There should not be an error: %v", err) t.Errorf("There should not be an error: %v", err)
} }
if result.Files[0].IsIncomplete { if result.Files[0].IsIncomplete {
t.Errorf("Files should not be incomplete! %v", result.Files[0]) t.Errorf("Files should not be incomplete! %v", result.Files[0])
} }
result, err = ParsePatch(40, 5, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "") result, err = ParsePatch(db.DefaultContext, 40, 5, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "")
if err != nil { if err != nil {
t.Errorf("There should not be an error: %v", err) t.Errorf("There should not be an error: %v", err)
} }
@ -494,14 +494,14 @@ index 0000000..6bb8f39
diffBuilder.WriteString("+line" + strconv.Itoa(35) + "\n") diffBuilder.WriteString("+line" + strconv.Itoa(35) + "\n")
diff = diffBuilder.String() diff = diffBuilder.String()
result, err = ParsePatch(20, 4096, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "") result, err = ParsePatch(db.DefaultContext, 20, 4096, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "")
if err != nil { if err != nil {
t.Errorf("There should not be an error: %v", err) t.Errorf("There should not be an error: %v", err)
} }
if !result.Files[0].IsIncomplete { if !result.Files[0].IsIncomplete {
t.Errorf("Files should be incomplete! %v", result.Files[0]) t.Errorf("Files should be incomplete! %v", result.Files[0])
} }
result, err = ParsePatch(40, 4096, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "") result, err = ParsePatch(db.DefaultContext, 40, 4096, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "")
if err != nil { if err != nil {
t.Errorf("There should not be an error: %v", err) t.Errorf("There should not be an error: %v", err)
} }
@ -520,7 +520,7 @@ index 0000000..6bb8f39
Docker Pulls Docker Pulls
+ cut off + cut off
+ cut off` + cut off`
_, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "") _, err = ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff), "")
if err != nil { if err != nil {
t.Errorf("ParsePatch failed: %s", err) t.Errorf("ParsePatch failed: %s", err)
} }
@ -536,7 +536,7 @@ index 0000000..6bb8f39
Docker Pulls Docker Pulls
+ cut off + cut off
+ cut off` + cut off`
_, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff2), "") _, err = ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff2), "")
if err != nil { if err != nil {
t.Errorf("ParsePatch failed: %s", err) t.Errorf("ParsePatch failed: %s", err)
} }
@ -552,7 +552,7 @@ index 0000000..6bb8f39
Docker Pulls Docker Pulls
+ cut off + cut off
+ cut off` + cut off`
_, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff2a), "") _, err = ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff2a), "")
if err != nil { if err != nil {
t.Errorf("ParsePatch failed: %s", err) t.Errorf("ParsePatch failed: %s", err)
} }
@ -568,7 +568,7 @@ index 0000000..6bb8f39
Docker Pulls Docker Pulls
+ cut off + cut off
+ cut off` + cut off`
_, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff3), "") _, err = ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff3), "")
if err != nil { if err != nil {
t.Errorf("ParsePatch failed: %s", err) t.Errorf("ParsePatch failed: %s", err)
} }
@ -634,7 +634,7 @@ func TestGetDiffRangeWithWhitespaceBehavior(t *testing.T) {
} }
defer gitRepo.Close() defer gitRepo.Close()
for _, behavior := range []git.TrustedCmdArgs{{"-w"}, {"--ignore-space-at-eol"}, {"-b"}, nil} { for _, behavior := range []git.TrustedCmdArgs{{"-w"}, {"--ignore-space-at-eol"}, {"-b"}, nil} {
diffs, err := GetDiff(gitRepo, diffs, err := GetDiff(db.DefaultContext, gitRepo,
&DiffOptions{ &DiffOptions{
AfterCommitID: "bd7063cc7c04689c4d082183d32a604ed27a24f9", AfterCommitID: "bd7063cc7c04689c4d082183d32a604ed27a24f9",
BeforeCommitID: "559c156f8e0178b71cb44355428f24001b08fc68", BeforeCommitID: "559c156f8e0178b71cb44355428f24001b08fc68",
@ -665,6 +665,6 @@ func TestNoCrashes(t *testing.T) {
} }
for _, testcase := range tests { for _, testcase := range tests {
// It shouldn't crash, so don't care about the output. // It shouldn't crash, so don't care about the output.
ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff), "") ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff), "")
} }
} }

View file

@ -18,7 +18,7 @@ func TestDeleteNotPassedAssignee(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
// Fake issue with assignees // Fake issue with assignees
issue, err := issues_model.GetIssueWithAttrsByID(1) issue, err := issues_model.GetIssueWithAttrsByID(db.DefaultContext, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, issue.Assignees, 1) assert.Len(t, issue.Assignees, 1)

View file

@ -87,7 +87,7 @@ func (h *ReplyHandler) Handle(ctx context.Context, content *MailContent, doer *u
attachmentIDs := make([]string, 0, len(content.Attachments)) attachmentIDs := make([]string, 0, len(content.Attachments))
if setting.Attachment.Enabled { if setting.Attachment.Enabled {
for _, attachment := range content.Attachments { for _, attachment := range content.Attachments {
a, err := attachment_service.UploadAttachment(bytes.NewReader(attachment.Content), setting.Attachment.AllowedTypes, int64(len(attachment.Content)), &repo_model.Attachment{ a, err := attachment_service.UploadAttachment(ctx, bytes.NewReader(attachment.Content), setting.Attachment.AllowedTypes, int64(len(attachment.Content)), &repo_model.Attachment{
Name: attachment.Name, Name: attachment.Name,
UploaderID: doer.ID, UploaderID: doer.ID,
RepoID: issue.Repo.ID, RepoID: issue.Repo.ID,

View file

@ -430,7 +430,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error {
} }
if len(iss) > 0 { if len(iss) > 0 {
if err := issues_model.InsertIssues(iss...); err != nil { if err := issues_model.InsertIssues(g.ctx, iss...); err != nil {
return err return err
} }

View file

@ -54,7 +54,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error {
mirrorType = PullMirrorType mirrorType = PullMirrorType
referenceID = m.RepoID referenceID = m.RepoID
} else if m, ok := bean.(*repo_model.PushMirror); ok { } else if m, ok := bean.(*repo_model.PushMirror); ok {
if m.GetRepository() == nil { if m.GetRepository(ctx) == nil {
log.Error("Disconnected push-mirror found: %d", m.ID) log.Error("Disconnected push-mirror found: %d", m.ID)
return nil return nil
} }

View file

@ -9,7 +9,6 @@ import (
"strings" "strings"
"time" "time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
system_model "code.gitea.io/gitea/models/system" system_model "code.gitea.io/gitea/models/system"
"code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/cache"
@ -461,7 +460,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool {
} }
defer gitRepo.Close() defer gitRepo.Close()
if ok := checkAndUpdateEmptyRepository(m, gitRepo, results); !ok { if ok := checkAndUpdateEmptyRepository(ctx, m, gitRepo, results); !ok {
return false return false
} }
} }
@ -550,7 +549,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool {
return true return true
} }
func checkAndUpdateEmptyRepository(m *repo_model.Mirror, gitRepo *git.Repository, results []*mirrorSyncResult) bool { func checkAndUpdateEmptyRepository(ctx context.Context, m *repo_model.Mirror, gitRepo *git.Repository, results []*mirrorSyncResult) bool {
if !m.Repo.IsEmpty { if !m.Repo.IsEmpty {
return true return true
} }
@ -601,7 +600,7 @@ func checkAndUpdateEmptyRepository(m *repo_model.Mirror, gitRepo *git.Repository
} }
m.Repo.IsEmpty = false m.Repo.IsEmpty = false
// Update the is empty and default_branch columns // Update the is empty and default_branch columns
if err := repo_model.UpdateRepositoryCols(db.DefaultContext, m.Repo, "default_branch", "is_empty"); err != nil { if err := repo_model.UpdateRepositoryCols(ctx, m.Repo, "default_branch", "is_empty"); err != nil {
log.Error("Failed to update default branch of repository %-v. Error: %v", m.Repo, err) log.Error("Failed to update default branch of repository %-v. Error: %v", m.Repo, err)
desc := fmt.Sprintf("Failed to update default branch of repository '%s': %v", m.Repo.RepoPath(), err) desc := fmt.Sprintf("Failed to update default branch of repository '%s': %v", m.Repo.RepoPath(), err)
if err = system_model.CreateRepositoryNotice(desc); err != nil { if err = system_model.CreateRepositoryNotice(desc); err != nil {

View file

@ -65,7 +65,7 @@ func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr str
// RemovePushMirrorRemote removes the push mirror remote. // RemovePushMirrorRemote removes the push mirror remote.
func RemovePushMirrorRemote(ctx context.Context, m *repo_model.PushMirror) error { func RemovePushMirrorRemote(ctx context.Context, m *repo_model.PushMirror) error {
cmd := git.NewCommand(ctx, "remote", "rm").AddDynamicArguments(m.RemoteName) cmd := git.NewCommand(ctx, "remote", "rm").AddDynamicArguments(m.RemoteName)
_ = m.GetRepository() _ = m.GetRepository(ctx)
if _, _, err := cmd.RunStdString(&git.RunOpts{Dir: m.Repo.RepoPath()}); err != nil { if _, _, err := cmd.RunStdString(&git.RunOpts{Dir: m.Repo.RepoPath()}); err != nil {
return err return err
@ -99,7 +99,7 @@ func SyncPushMirror(ctx context.Context, mirrorID int64) bool {
return false return false
} }
_ = m.GetRepository() _ = m.GetRepository(ctx)
m.LastError = "" m.LastError = ""

View file

@ -264,7 +264,7 @@ func createCodeComment(ctx context.Context, doer *user_model.User, repo *repo_mo
// SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist
func SubmitReview(ctx context.Context, doer *user_model.User, gitRepo *git.Repository, issue *issues_model.Issue, reviewType issues_model.ReviewType, content, commitID string, attachmentUUIDs []string) (*issues_model.Review, *issues_model.Comment, error) { func SubmitReview(ctx context.Context, doer *user_model.User, gitRepo *git.Repository, issue *issues_model.Issue, reviewType issues_model.ReviewType, content, commitID string, attachmentUUIDs []string) (*issues_model.Review, *issues_model.Comment, error) {
pr, err := issue.GetPullRequest() pr, err := issue.GetPullRequest(ctx)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View file

@ -107,7 +107,7 @@ func TestRelease_Create(t *testing.T) {
testPlayload := "testtest" testPlayload := "testtest"
attach, err := attachment.NewAttachment(&repo_model.Attachment{ attach, err := attachment.NewAttachment(db.DefaultContext, &repo_model.Attachment{
RepoID: repo.ID, RepoID: repo.ID,
UploaderID: user.ID, UploaderID: user.ID,
Name: "test.txt", Name: "test.txt",
@ -241,7 +241,7 @@ func TestRelease_Update(t *testing.T) {
// Add new attachments // Add new attachments
samplePayload := "testtest" samplePayload := "testtest"
attach, err := attachment.NewAttachment(&repo_model.Attachment{ attach, err := attachment.NewAttachment(db.DefaultContext, &repo_model.Attachment{
RepoID: repo.ID, RepoID: repo.ID,
UploaderID: user.ID, UploaderID: user.ID,
Name: "test.txt", Name: "test.txt",

View file

@ -44,7 +44,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) {
Type: user_model.UserTypeOrganization, Type: user_model.UserTypeOrganization,
Visibility: structs.VisibleTypePublic, Visibility: structs.VisibleTypePublic,
} }
assert.NoError(t, organization.CreateOrganization(org, user), "CreateOrganization") assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, user), "CreateOrganization")
// Check Owner team. // Check Owner team.
ownerTeam, err := org.GetOwnerTeam(db.DefaultContext) ownerTeam, err := org.GetOwnerTeam(db.DefaultContext)

View file

@ -343,7 +343,7 @@ func (t *TemporaryUploadRepository) DiffIndex() (*gitdiff.Diff, error) {
Stderr: stderr, Stderr: stderr,
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error { PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
_ = stdoutWriter.Close() _ = stdoutWriter.Close()
diff, finalErr = gitdiff.ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "") diff, finalErr = gitdiff.ParsePatch(t.ctx, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "")
if finalErr != nil { if finalErr != nil {
log.Error("ParsePatch: %v", finalErr) log.Error("ParsePatch: %v", finalErr)
cancel() cancel()

View file

@ -189,7 +189,7 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) error {
// An alternative option here would be write a function which would delete all organizations but it seems // An alternative option here would be write a function which would delete all organizations but it seems
// but such a function would likely get out of date // but such a function would likely get out of date
for { for {
orgs, err := organization.FindOrgs(organization.FindOrgOptions{ orgs, err := organization.FindOrgs(ctx, organization.FindOrgOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: repo_model.RepositoryListDefaultPageSize, PageSize: repo_model.RepositoryListDefaultPageSize,
Page: 1, Page: 1,

View file

@ -350,7 +350,7 @@ func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model
// DeleteWiki removes the actual and local copy of repository wiki. // DeleteWiki removes the actual and local copy of repository wiki.
func DeleteWiki(ctx context.Context, repo *repo_model.Repository) error { func DeleteWiki(ctx context.Context, repo *repo_model.Repository) error {
if err := repo_model.UpdateRepositoryUnits(repo, nil, []unit.Type{unit.TypeWiki}); err != nil { if err := repo_model.UpdateRepositoryUnits(ctx, repo, nil, []unit.Type{unit.TypeWiki}); err != nil {
return err return err
} }

View file

@ -2,7 +2,7 @@
<h4 class="ui top attached header"> <h4 class="ui top attached header">
<strong>{{.Team.Name}}</strong> <strong>{{.Team.Name}}</strong>
<div class="ui right"> <div class="ui right">
{{if .Team.IsMember $.SignedUser.ID}} {{if .Team.IsMember ctx $.SignedUser.ID}}
<form> <form>
<button class="ui red tiny button delete-button" data-modal-id="leave-team-sidebar" <button class="ui red tiny button delete-button" data-modal-id="leave-team-sidebar"
data-url="{{.OrgLink}}/teams/{{.Team.LowerName | PathEscape}}/action/leave" data-datauid="{{$.SignedUser.ID}}" data-url="{{.OrgLink}}/teams/{{.Team.LowerName | PathEscape}}/action/leave" data-datauid="{{$.SignedUser.ID}}"

View file

@ -16,7 +16,7 @@
<div class="ui top attached header"> <div class="ui top attached header">
<a class="text black" href="{{$.OrgLink}}/teams/{{.LowerName | PathEscape}}"><strong>{{.Name}}</strong></a> <a class="text black" href="{{$.OrgLink}}/teams/{{.LowerName | PathEscape}}"><strong>{{.Name}}</strong></a>
<div class="ui right"> <div class="ui right">
{{if .IsMember $.SignedUser.ID}} {{if .IsMember ctx $.SignedUser.ID}}
<form> <form>
<button class="ui red tiny button delete-button" data-modal-id="leave-team" <button class="ui red tiny button delete-button" data-modal-id="leave-team"
data-url="{{$.OrgLink}}/teams/{{.LowerName | PathEscape}}/action/leave" data-datauid="{{$.SignedUser.ID}}" data-url="{{$.OrgLink}}/teams/{{.LowerName | PathEscape}}/action/leave" data-datauid="{{$.SignedUser.ID}}"

View file

@ -1,7 +1,7 @@
{{if .IsPull}} {{if .IsPull}}
{{if and .PullRequest .PullRequest.HasMerged}} {{if and .PullRequest .PullRequest.HasMerged}}
{{svg "octicon-git-merge" 16 "text purple"}} {{svg "octicon-git-merge" 16 "text purple"}}
{{else if and .GetPullRequest .GetPullRequest.HasMerged}} {{else if and (.GetPullRequest ctx) (.GetPullRequest ctx).HasMerged}}
{{svg "octicon-git-merge" 16 "text purple"}} {{svg "octicon-git-merge" 16 "text purple"}}
{{else}} {{else}}
{{if .IsClosed}} {{if .IsClosed}}
@ -9,7 +9,7 @@
{{else}} {{else}}
{{if and .PullRequest .PullRequest.IsWorkInProgress}} {{if and .PullRequest .PullRequest.IsWorkInProgress}}
{{svg "octicon-git-pull-request-draft" 16 "text grey"}} {{svg "octicon-git-pull-request-draft" 16 "text grey"}}
{{else if and .GetPullRequest .GetPullRequest.IsWorkInProgress}} {{else if and (.GetPullRequest ctx) (.GetPullRequest ctx).IsWorkInProgress}}
{{svg "octicon-git-pull-request-draft" 16 "text grey"}} {{svg "octicon-git-pull-request-draft" 16 "text grey"}}
{{else}} {{else}}
{{svg "octicon-git-pull-request" 16 "text green"}} {{svg "octicon-git-pull-request" 16 "text green"}}

View file

@ -45,7 +45,7 @@ func TestPullRequestTargetEvent(t *testing.T) {
assert.NotEmpty(t, baseRepo) assert.NotEmpty(t, baseRepo)
// enable actions // enable actions
err = repo_model.UpdateRepositoryUnits(baseRepo, []repo_model.RepoUnit{{ err = repo_model.UpdateRepositoryUnits(db.DefaultContext, baseRepo, []repo_model.RepoUnit{{
RepoID: baseRepo.ID, RepoID: baseRepo.ID,
Type: unit_model.TypeActions, Type: unit_model.TypeActions,
}}, nil) }}, nil)

View file

@ -9,6 +9,7 @@ import (
"testing" "testing"
auth_model "code.gitea.io/gitea/models/auth" auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
@ -44,7 +45,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
assert.EqualValues(t, isWatching, wi.Subscribed) assert.EqualValues(t, isWatching, wi.Subscribed)
assert.EqualValues(t, !isWatching, wi.Ignored) assert.EqualValues(t, !isWatching, wi.Ignored)
assert.EqualValues(t, issue.APIURL()+"/subscriptions", wi.URL) assert.EqualValues(t, issue.APIURL(db.DefaultContext)+"/subscriptions", wi.URL)
assert.EqualValues(t, issue.CreatedUnix, wi.CreatedAt.Unix()) assert.EqualValues(t, issue.CreatedUnix, wi.CreatedAt.Unix())
assert.EqualValues(t, issueRepo.APIURL(), wi.RepositoryURL) assert.EqualValues(t, issueRepo.APIURL(), wi.RepositoryURL)
} }

View file

@ -100,7 +100,7 @@ func TestAPINotification(t *testing.T) {
assert.True(t, apiN.Unread) assert.True(t, apiN.Unread)
assert.EqualValues(t, "issue4", apiN.Subject.Title) assert.EqualValues(t, "issue4", apiN.Subject.Title)
assert.EqualValues(t, "Issue", apiN.Subject.Type) assert.EqualValues(t, "Issue", apiN.Subject.Type)
assert.EqualValues(t, thread5.Issue.APIURL(), apiN.Subject.URL) assert.EqualValues(t, thread5.Issue.APIURL(db.DefaultContext), apiN.Subject.URL)
assert.EqualValues(t, thread5.Repository.HTMLURL(), apiN.Repository.HTMLURL) assert.EqualValues(t, thread5.Repository.HTMLURL(), apiN.Repository.HTMLURL)
MakeRequest(t, NewRequest(t, "GET", "/api/v1/notifications/new"), http.StatusUnauthorized) MakeRequest(t, NewRequest(t, "GET", "/api/v1/notifications/new"), http.StatusUnauthorized)

View file

@ -414,7 +414,7 @@ func TestLDAPGroupTeamSyncAddMember(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ user := unittest.AssertExistsAndLoadBean(t, &user_model.User{
Name: gitLDAPUser.UserName, Name: gitLDAPUser.UserName,
}) })
usersOrgs, err := organization.FindOrgs(organization.FindOrgOptions{ usersOrgs, err := organization.FindOrgs(db.DefaultContext, organization.FindOrgOptions{
UserID: user.ID, UserID: user.ID,
IncludePrivate: true, IncludePrivate: true,
}) })
@ -458,7 +458,7 @@ func TestLDAPGroupTeamSyncRemoveMember(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ user := unittest.AssertExistsAndLoadBean(t, &user_model.User{
Name: gitLDAPUsers[0].UserName, Name: gitLDAPUsers[0].UserName,
}) })
err = organization.AddOrgUser(org.ID, user.ID) err = organization.AddOrgUser(db.DefaultContext, org.ID, user.ID)
assert.NoError(t, err) assert.NoError(t, err)
err = models.AddTeamMember(db.DefaultContext, team, user.ID) err = models.AddTeamMember(db.DefaultContext, team, user.ID)
assert.NoError(t, err) assert.NoError(t, err)

View file

@ -9,6 +9,7 @@ import (
"testing" "testing"
auth_model "code.gitea.io/gitea/models/auth" auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -117,7 +118,7 @@ func doCheckOrgCounts(username string, orgCounts map[string]int, strict bool, ca
Name: username, Name: username,
}) })
orgs, err := organization.FindOrgs(organization.FindOrgOptions{ orgs, err := organization.FindOrgs(db.DefaultContext, organization.FindOrgOptions{
UserID: user.ID, UserID: user.ID,
IncludePrivate: true, IncludePrivate: true,
}) })