1
0
mirror of https://github.com/go-gitea/gitea synced 2024-12-24 03:35:55 +01:00

Move repository model into models/repo (#17933)

* Some refactors related repository model

* Move more methods out of repository

* Move repository into models/repo

* Fix test

* Fix test

* some improvements

* Remove unnecessary function
This commit is contained in:
Lunny Xiao 2021-12-10 09:27:50 +08:00 committed by GitHub
parent fb8166c6c6
commit 719bddcd76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
301 changed files with 3193 additions and 2919 deletions

@ -102,7 +102,7 @@ func migrateAvatars(dstStorage storage.ObjectStorage) error {
}
func migrateRepoAvatars(dstStorage storage.ObjectStorage) error {
return models.IterateRepository(func(repo *models.Repository) error {
return models.IterateRepository(func(repo *repo_model.Repository) error {
_, err := storage.Copy(dstStorage, repo.CustomAvatarRelativePath(), storage.RepoAvatars, repo.CustomAvatarRelativePath())
return err
})

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/convert"
@ -25,7 +26,7 @@ func TestAPIListRepoComments(t *testing.T) {
comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{},
unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)
@ -71,7 +72,7 @@ func TestAPIListIssueComments(t *testing.T) {
comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{},
unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)
@ -91,7 +92,7 @@ func TestAPICreateComment(t *testing.T) {
const commentBody = "Comment body"
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{}).(*models.Issue)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)
@ -114,7 +115,7 @@ func TestAPIGetComment(t *testing.T) {
comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment)
assert.NoError(t, comment.LoadIssue())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: comment.Issue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: comment.Issue.RepoID}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)
@ -143,7 +144,7 @@ func TestAPIEditComment(t *testing.T) {
comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{},
unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)
@ -168,7 +169,7 @@ func TestAPIDeleteComment(t *testing.T) {
comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{},
unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)

@ -13,8 +13,8 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/queue"
api "code.gitea.io/gitea/modules/structs"
@ -264,7 +264,7 @@ func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64)
owner, repo, index, ctx.Token)
req := NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{
MergeMessageField: "doAPIMergePullRequest Merge",
Do: string(models.MergeStyleMerge),
Do: string(repo_model.MergeStyleMerge),
})
resp := ctx.Session.MakeRequest(t, req, NoExpectedStatus)
@ -276,7 +276,7 @@ func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64)
queue.GetManager().FlushAll(context.Background(), 5*time.Second)
req = NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{
MergeMessageField: "doAPIMergePullRequest Merge",
Do: string(models.MergeStyleMerge),
Do: string(repo_model.MergeStyleMerge),
})
resp = ctx.Session.MakeRequest(t, req, NoExpectedStatus)
}
@ -298,7 +298,7 @@ func doAPIManuallyMergePullRequest(ctx APITestContext, owner, repo, commitID str
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s",
owner, repo, index, ctx.Token)
req := NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{
Do: string(models.MergeStyleManuallyMerged),
Do: string(repo_model.MergeStyleManuallyMerged),
MergeCommitID: commitID,
})

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -21,7 +22,7 @@ import (
func TestAPIModifyLabels(t *testing.T) {
assert.NoError(t, unittest.LoadFixtures())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -91,7 +92,7 @@ func TestAPIModifyLabels(t *testing.T) {
func TestAPIAddIssueLabels(t *testing.T) {
assert.NoError(t, unittest.LoadFixtures())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue)
_ = unittest.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID, ID: 2}).(*models.Label)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
@ -114,7 +115,7 @@ func TestAPIAddIssueLabels(t *testing.T) {
func TestAPIReplaceIssueLabels(t *testing.T) {
assert.NoError(t, unittest.LoadFixtures())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue)
label := unittest.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID}).(*models.Label)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
@ -140,7 +141,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) {
func TestAPIModifyOrgLabels(t *testing.T) {
assert.NoError(t, unittest.LoadFixtures())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
user := "user1"
session := loginUser(t, user)

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/structs"
@ -21,7 +22,7 @@ func TestAPIIssuesMilestone(t *testing.T) {
defer prepareTestEnv(t)()
milestone := unittest.AssertExistsAndLoadBean(t, &models.Milestone{ID: 1}).(*models.Milestone)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: milestone.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: milestone.RepoID}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
assert.Equal(t, int64(1), int64(milestone.NumIssues))
assert.Equal(t, structs.StateOpen, milestone.State())

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -19,7 +20,7 @@ import (
func TestAPIListStopWatches(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -33,7 +34,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
testSubscription := func(issue *models.Issue, isWatching bool) {
issueRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token)
req := NewRequest(t, "GET", urlStr)
@ -54,7 +55,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
testSubscription(issue4, false)
testSubscription(issue5, false)
issue1Repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue1.RepoID}).(*models.Repository)
issue1Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue1.RepoID}).(*repo_model.Repository)
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue1Repo.OwnerName, issue1Repo.Name, issue1.Index, owner.Name, token)
req := NewRequest(t, "DELETE", urlStr)
session.MakeRequest(t, req, http.StatusCreated)
@ -64,7 +65,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
session.MakeRequest(t, req, http.StatusOK)
testSubscription(issue1, false)
issue5Repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue5.RepoID}).(*models.Repository)
issue5Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue5.RepoID}).(*repo_model.Repository)
urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue5Repo.OwnerName, issue5Repo.Name, issue5.Index, owner.Name, token)
req = NewRequest(t, "PUT", urlStr)
session.MakeRequest(t, req, http.StatusCreated)

@ -12,6 +12,7 @@ import (
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -22,7 +23,7 @@ import (
func TestAPIListIssues(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)
@ -73,7 +74,7 @@ func TestAPICreateIssue(t *testing.T) {
defer prepareTestEnv(t)()
const body, title = "apiTestBody", "apiTestTitle"
repoBefore := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)
@ -97,7 +98,7 @@ func TestAPICreateIssue(t *testing.T) {
Title: title,
})
repoAfter := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoAfter := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
assert.Equal(t, repoBefore.NumIssues+1, repoAfter.NumIssues)
assert.Equal(t, repoBefore.NumClosedIssues, repoAfter.NumClosedIssues)
}
@ -106,7 +107,7 @@ func TestAPIEditIssue(t *testing.T) {
defer prepareTestEnv(t)()
issueBefore := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue)
repoBefore := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository)
repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}).(*user_model.User)
assert.NoError(t, issueBefore.LoadAttributes())
assert.Equal(t, int64(1019307200), int64(issueBefore.DeadlineUnix))
@ -137,7 +138,7 @@ func TestAPIEditIssue(t *testing.T) {
DecodeJSON(t, resp, &apiIssue)
issueAfter := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue)
repoAfter := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository)
repoAfter := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}).(*repo_model.Repository)
// check deleted user
assert.Equal(t, int64(500), issueAfter.PosterID)

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -48,7 +49,7 @@ func TestDeleteDeployKeyNoLogin(t *testing.T) {
func TestCreateReadOnlyDeployKey(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: "repo1"}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)
@ -74,7 +75,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) {
func TestCreateReadWriteDeployKey(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: "repo1"}).(*repo_model.Repository)
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, repoOwner.Name)

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -21,7 +22,7 @@ func TestAPINotification(t *testing.T) {
defer prepareTestEnv(t)()
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
thread5 := unittest.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification)
assert.NoError(t, thread5.LoadAttributes())
session := loginUser(t, user2.Name)

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
api "code.gitea.io/gitea/modules/structs"
@ -19,7 +20,7 @@ func TestAPIPullCommits(t *testing.T) {
defer prepareTestEnv(t)()
pullIssue := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
assert.NoError(t, pullIssue.LoadIssue())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.HeadRepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.HeadRepoID}).(*repo_model.Repository)
session := loginUser(t, "user2")
req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pullIssue.Index)

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/json"
api "code.gitea.io/gitea/modules/structs"
@ -21,7 +22,7 @@ func TestAPIPullReview(t *testing.T) {
defer prepareTestEnv(t)()
pullIssue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
assert.NoError(t, pullIssue.LoadAttributes())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}).(*repo_model.Repository)
// test ListPullReviews
session := loginUser(t, "user2")
@ -198,7 +199,7 @@ func TestAPIPullReview(t *testing.T) {
// to make it simple, use same api with get review
pullIssue12 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue)
assert.NoError(t, pullIssue12.LoadAttributes())
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}).(*repo_model.Repository)
req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token)
resp = session.MakeRequest(t, req, http.StatusOK)
@ -222,7 +223,7 @@ func TestAPIPullReviewRequest(t *testing.T) {
defer prepareTestEnv(t)()
pullIssue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
assert.NoError(t, pullIssue.LoadAttributes())
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}).(*repo_model.Repository)
// Test add Review Request
session := loginUser(t, "user2")
@ -267,7 +268,7 @@ func TestAPIPullReviewRequest(t *testing.T) {
// Test team review request
pullIssue12 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue)
assert.NoError(t, pullIssue12.LoadAttributes())
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}).(*repo_model.Repository)
// Test add Team Review Request
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@ -22,7 +23,7 @@ import (
func TestAPIViewPulls(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, "user2")
@ -39,7 +40,7 @@ func TestAPIViewPulls(t *testing.T) {
// TestAPIMergePullWIP ensures that we can't merge a WIP pull request
func TestAPIMergePullWIP(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{Status: models.PullRequestStatusMergeable}, unittest.Cond("has_merged = ?", false)).(*models.PullRequest)
pr.LoadIssue()
@ -54,7 +55,7 @@ func TestAPIMergePullWIP(t *testing.T) {
token := getTokenForLoggedInUser(t, session)
req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{
MergeMessageField: pr.Issue.Title,
Do: string(models.MergeStyleMerge),
Do: string(repo_model.MergeStyleMerge),
})
session.MakeRequest(t, req, http.StatusMethodNotAllowed)
@ -62,9 +63,9 @@ func TestAPIMergePullWIP(t *testing.T) {
func TestAPICreatePullSuccess(t *testing.T) {
defer prepareTestEnv(t)()
repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
repo10 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository)
// repo10 have code, pulls units.
repo11 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
repo11 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 11}).(*repo_model.Repository)
// repo11 only have code unit but should still create pulls
owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}).(*user_model.User)
owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}).(*user_model.User)
@ -83,10 +84,10 @@ func TestAPICreatePullSuccess(t *testing.T) {
func TestAPICreatePullWithFieldsSuccess(t *testing.T) {
defer prepareTestEnv(t)()
// repo10 have code, pulls units.
repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
repo10 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository)
owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}).(*user_model.User)
// repo11 only have code unit but should still create pulls
repo11 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
repo11 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 11}).(*repo_model.Repository)
owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}).(*user_model.User)
session := loginUser(t, owner11.Name)
@ -120,10 +121,10 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) {
func TestAPICreatePullWithFieldsFailure(t *testing.T) {
defer prepareTestEnv(t)()
// repo10 have code, pulls units.
repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
repo10 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository)
owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}).(*user_model.User)
// repo11 only have code unit but should still create pulls
repo11 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
repo11 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 11}).(*repo_model.Repository)
owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}).(*user_model.User)
session := loginUser(t, owner11.Name)
@ -153,7 +154,7 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) {
func TestAPIEditPull(t *testing.T) {
defer prepareTestEnv(t)()
repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
repo10 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository)
owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}).(*user_model.User)
session := loginUser(t, owner10.Name)

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -22,7 +23,7 @@ import (
func TestAPIListReleases(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
session := loginUser(t, user2.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -71,7 +72,7 @@ func TestAPIListReleases(t *testing.T) {
testFilterByLen(true, url.Values{"draft": {"true"}, "pre-release": {"true"}}, 0, "there is no pre-release draft")
}
func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, owner *user_model.User, repo *models.Repository, name, target, title, desc string) *api.Release {
func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, owner *user_model.User, repo *repo_model.Repository, name, target, title, desc string) *api.Release {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases?token=%s",
owner.Name, repo.Name, token)
req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateReleaseOption{
@ -99,7 +100,7 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string,
func TestAPICreateAndUpdateRelease(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -150,7 +151,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -161,7 +162,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -179,7 +180,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
func TestAPIGetReleaseByTag(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.LowerName)
@ -212,7 +213,7 @@ func TestAPIGetReleaseByTag(t *testing.T) {
func TestAPIDeleteReleaseByTagName(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)

@ -11,7 +11,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -21,7 +21,7 @@ import (
func TestAPIDownloadArchive(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
session := loginUser(t, user2.LowerName)
token := getTokenForLoggedInUser(t, session)

@ -10,7 +10,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
unit_model "code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -20,7 +20,7 @@ import (
)
// getRepoEditOptionFromRepo gets the options for an existing repo exactly as is
func getRepoEditOptionFromRepo(repo *models.Repository) *api.EditRepoOption {
func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption {
name := repo.Name
description := repo.Description
website := repo.Website
@ -135,13 +135,13 @@ func TestAPIRepoEdit(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
bFalse, bTrue := false, true
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo15 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository) // empty repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo15 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15}).(*repo_model.Repository) // empty repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
// Get user2's token
session := loginUser(t, user2.Name)
@ -166,7 +166,7 @@ func TestAPIRepoEdit(t *testing.T) {
assert.Equal(t, *repoEditOption.Website, repo.Website)
assert.Equal(t, *repoEditOption.Archived, repo.Archived)
// check repo1 from database
repo1edited := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo1editedOption := getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repoEditOption.Name, *repo1editedOption.Name)
assert.Equal(t, *repoEditOption.Description, *repo1editedOption.Description)
@ -191,7 +191,7 @@ func TestAPIRepoEdit(t *testing.T) {
DecodeJSON(t, resp, &repo)
assert.NotNil(t, repo)
// check repo1 was written to database
repo1edited = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo1editedOption = getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repo1editedOption.HasIssues, true)
assert.Nil(t, repo1editedOption.ExternalTracker)
@ -213,7 +213,7 @@ func TestAPIRepoEdit(t *testing.T) {
DecodeJSON(t, resp, &repo)
assert.NotNil(t, repo)
// check repo1 was written to database
repo1edited = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo1editedOption = getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repo1editedOption.HasIssues, true)
assert.Equal(t, *repo1editedOption.ExternalTracker, *repoEditOption.ExternalTracker)
@ -244,7 +244,7 @@ func TestAPIRepoEdit(t *testing.T) {
DecodeJSON(t, resp, &repo)
assert.NotNil(t, repo)
// check repo1 was written to database
repo1edited = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo1editedOption = getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repo1editedOption.Description, *repoEditOption.Description)
assert.Equal(t, *repo1editedOption.HasIssues, true)
@ -289,7 +289,7 @@ func TestAPIRepoEdit(t *testing.T) {
_ = session.MakeRequest(t, req, http.StatusOK)
// Test making a repo public that is private
repo16 = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
repo16 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository)
assert.True(t, repo16.IsPrivate)
repoEditOption = &api.EditRepoOption{
Private: &bFalse,
@ -297,7 +297,7 @@ func TestAPIRepoEdit(t *testing.T) {
url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token2)
req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption)
_ = session.MakeRequest(t, req, http.StatusOK)
repo16 = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
repo16 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository)
assert.False(t, repo16.IsPrivate)
// Make it private again
repoEditOption.Private = &bTrue
@ -311,7 +311,7 @@ func TestAPIRepoEdit(t *testing.T) {
Archived: &bTrue,
})
_ = session.MakeRequest(t, req, http.StatusOK)
repo15 = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository)
repo15 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15}).(*repo_model.Repository)
assert.True(t, repo15.IsArchived)
req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{
Archived: &bFalse,

@ -13,7 +13,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -110,8 +110,8 @@ func getExpectedFileResponseForCreate(commitID, treePath string) *api.FileRespon
func BenchmarkAPICreateFileSmall(b *testing.B) {
onGiteaRunTB(b, func(t testing.TB, u *url.URL) {
b := t.(*testing.B)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
for n := 0; n < b.N; n++ {
treePath := fmt.Sprintf("update/file%d.txt", n)
@ -125,8 +125,8 @@ func BenchmarkAPICreateFileMedium(b *testing.B) {
onGiteaRunTB(b, func(t testing.TB, u *url.URL) {
b := t.(*testing.B)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
b.ResetTimer()
for n := 0; n < b.N; n++ {
@ -139,12 +139,12 @@ func BenchmarkAPICreateFileMedium(b *testing.B) {
func TestAPICreateFile(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
fileID := 0
// Get user2's token

@ -10,7 +10,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -39,12 +39,12 @@ func getDeleteFileOptions() *api.DeleteFileOptions {
func TestAPIDeleteFile(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
fileID := 0
// Get user2's token

@ -5,13 +5,13 @@
package integrations
import (
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
files_service "code.gitea.io/gitea/services/repository/files"
)
func createFileInBranch(user *user_model.User, repo *models.Repository, treePath, branchName, content string) (*api.FileResponse, error) {
func createFileInBranch(user *user_model.User, repo *repo_model.Repository, treePath, branchName, content string) (*api.FileResponse, error) {
opts := &files_service.UpdateRepoFileOptions{
OldBranch: branchName,
TreePath: treePath,
@ -23,6 +23,6 @@ func createFileInBranch(user *user_model.User, repo *models.Repository, treePath
return files_service.CreateOrUpdateRepoFile(repo, user, opts)
}
func createFile(user *user_model.User, repo *models.Repository, treePath string) (*api.FileResponse, error) {
func createFile(user *user_model.User, repo *repo_model.Repository, treePath string) (*api.FileResponse, error) {
return createFileInBranch(user, repo, treePath, repo.DefaultBranch, "This is a NEW file")
}

@ -12,7 +12,7 @@ import (
"path/filepath"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -105,12 +105,12 @@ func getExpectedFileResponseForUpdate(commitID, treePath string) *api.FileRespon
func TestAPIUpdateFile(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
fileID := 0
// Get user2's token

@ -10,7 +10,7 @@ import (
"path/filepath"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -54,13 +54,13 @@ func TestAPIGetContentsList(t *testing.T) {
func testAPIGetContentsList(t *testing.T, u *url.URL) {
/*** SETUP ***/
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
treePath := "" // root dir
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
treePath := "" // root dir
// Get user2's token
session := loginUser(t, user2.Name)

@ -9,7 +9,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -55,12 +55,12 @@ func TestAPIGetContents(t *testing.T) {
func testAPIGetContents(t *testing.T, u *url.URL) {
/*** SETUP ***/
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3, is an org
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
treePath := "README.md"
// Get user2's token

@ -8,7 +8,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -18,12 +18,12 @@ import (
func TestAPIReposGitBlobs(t *testing.T) {
defer prepareTestEnv(t)()
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
repo1ReadmeSHA := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
repo3ReadmeSHA := "d56a3073c1dbb7b15963110a049d50cdb5db99fc"
repo16ReadmeSHA := "f90451c72ef61a7645293d17b47be7a8e983da57"

@ -9,7 +9,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -25,7 +25,7 @@ echo Hello, World!
func TestAPIListGitHooks(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 37}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
// user1 is an admin user
@ -51,7 +51,7 @@ func TestAPIListGitHooks(t *testing.T) {
func TestAPIListGitHooksNoHooks(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
// user1 is an admin user
@ -72,7 +72,7 @@ func TestAPIListGitHooksNoHooks(t *testing.T) {
func TestAPIListGitHooksNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)
@ -85,7 +85,7 @@ func TestAPIListGitHooksNoAccess(t *testing.T) {
func TestAPIGetGitHook(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 37}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
// user1 is an admin user
@ -103,7 +103,7 @@ func TestAPIGetGitHook(t *testing.T) {
func TestAPIGetGitHookNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)
@ -116,7 +116,7 @@ func TestAPIGetGitHookNoAccess(t *testing.T) {
func TestAPIEditGitHook(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
// user1 is an admin user
@ -146,7 +146,7 @@ func TestAPIEditGitHook(t *testing.T) {
func TestAPIEditGitHookNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)
@ -162,7 +162,7 @@ func TestAPIEditGitHookNoAccess(t *testing.T) {
func TestAPIDeleteGitHook(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 37}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
// user1 is an admin user
@ -185,7 +185,7 @@ func TestAPIDeleteGitHook(t *testing.T) {
func TestAPIDeleteGitHookNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)

@ -9,7 +9,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -22,7 +22,7 @@ import (
func TestAPIGitTags(t *testing.T) {
defer prepareTestEnv(t)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -66,7 +66,7 @@ func TestAPIGitTags(t *testing.T) {
func TestAPIDeleteTagByName(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)

@ -8,19 +8,19 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
)
func TestAPIReposGitTrees(t *testing.T) {
defer prepareTestEnv(t)()
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of the repo1 & repo16
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of the repo3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // owner of neither repos
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) // public repo
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // public repo
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) // private repo
repo1TreeSHA := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
repo3TreeSHA := "2a47ca4b614a9f5a43abbd5ad851a54a616ffee6"
repo16TreeSHA := "69554a64c1e6030f051e5c3f94bfbd773cd6a324"

@ -10,7 +10,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/lfs"
@ -24,7 +24,7 @@ func TestAPILFSLocksNotStarted(t *testing.T) {
defer prepareTestEnv(t)()
setting.LFS.StartServer = false
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
req := NewRequestf(t, "GET", "/%s/%s.git/info/lfs/locks", user.Name, repo.Name)
MakeRequest(t, req, http.StatusNotFound)
@ -40,7 +40,7 @@ func TestAPILFSLocksNotLogin(t *testing.T) {
defer prepareTestEnv(t)()
setting.LFS.StartServer = true
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
req := NewRequestf(t, "GET", "/%s/%s.git/info/lfs/locks", user.Name, repo.Name)
req.Header.Set("Accept", lfs.MediaType)
@ -56,12 +56,12 @@ func TestAPILFSLocksLogged(t *testing.T) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) //in org 3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) //in org 3
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // own by org 3
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // own by org 3
tests := []struct {
user *user_model.User
repo *models.Repository
repo *repo_model.Repository
path string
httpResult int
addTime []int
@ -83,7 +83,7 @@ func TestAPILFSLocksLogged(t *testing.T) {
resultsTests := []struct {
user *user_model.User
repo *models.Repository
repo *repo_model.Repository
totalCount int
oursCount int
theirsCount int
@ -97,7 +97,7 @@ func TestAPILFSLocksLogged(t *testing.T) {
deleteTests := []struct {
user *user_model.User
repo *models.Repository
repo *repo_model.Repository
lockID string
}{}
@ -145,7 +145,7 @@ func TestAPILFSLocksLogged(t *testing.T) {
assert.EqualValues(t, test.user.DisplayName(), lock.Owner.Name)
deleteTests = append(deleteTests, struct {
user *user_model.User
repo *models.Repository
repo *repo_model.Repository
lockID string
}{test.user, test.repo, lock.ID})
}

@ -13,6 +13,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/json"
@ -28,7 +29,7 @@ func TestAPILFSNotStarted(t *testing.T) {
setting.LFS.StartServer = false
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
req := NewRequestf(t, "POST", "/%s/%s.git/info/lfs/objects/batch", user.Name, repo.Name)
MakeRequest(t, req, http.StatusNotFound)
@ -48,7 +49,7 @@ func TestAPILFSMediaType(t *testing.T) {
setting.LFS.StartServer = true
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
req := NewRequestf(t, "POST", "/%s/%s.git/info/lfs/objects/batch", user.Name, repo.Name)
MakeRequest(t, req, http.StatusUnsupportedMediaType)
@ -56,11 +57,11 @@ func TestAPILFSMediaType(t *testing.T) {
MakeRequest(t, req, http.StatusUnsupportedMediaType)
}
func createLFSTestRepository(t *testing.T, name string) *models.Repository {
func createLFSTestRepository(t *testing.T, name string) *repo_model.Repository {
ctx := NewAPITestContext(t, "user2", "lfs-"+name+"-repo")
t.Run("CreateRepo", doAPICreateRepository(ctx, false))
repo, err := models.GetRepositoryByOwnerAndName("user2", "lfs-"+name+"-repo")
repo, err := repo_model.GetRepositoryByOwnerAndName("user2", "lfs-"+name+"-repo")
assert.NoError(t, err)
return repo
@ -75,7 +76,7 @@ func TestAPILFSBatch(t *testing.T) {
content := []byte("dummy1")
oid := storeObjectInRepo(t, repo.ID, &content)
defer repo.RemoveLFSMetaObjectByOid(oid)
defer models.RemoveLFSMetaObjectByOid(repo.ID, oid)
session := loginUser(t, "user2")
@ -259,7 +260,7 @@ func TestAPILFSBatch(t *testing.T) {
content := []byte("dummy0")
storeObjectInRepo(t, repo2.ID, &content)
meta, err := repo.GetLFSMetaObjectByOid(p.Oid)
meta, err := models.GetLFSMetaObjectByOid(repo.ID, p.Oid)
assert.Nil(t, meta)
assert.Equal(t, models.ErrLFSObjectNotExist, err)
@ -274,7 +275,7 @@ func TestAPILFSBatch(t *testing.T) {
assert.Nil(t, br.Objects[0].Error)
assert.Empty(t, br.Objects[0].Actions)
meta, err = repo.GetLFSMetaObjectByOid(p.Oid)
meta, err = models.GetLFSMetaObjectByOid(repo.ID, p.Oid)
assert.NoError(t, err)
assert.NotNil(t, meta)
})
@ -331,7 +332,7 @@ func TestAPILFSUpload(t *testing.T) {
content := []byte("dummy3")
oid := storeObjectInRepo(t, repo.ID, &content)
defer repo.RemoveLFSMetaObjectByOid(oid)
defer models.RemoveLFSMetaObjectByOid(repo.ID, oid)
session := loginUser(t, "user2")
@ -360,7 +361,7 @@ func TestAPILFSUpload(t *testing.T) {
err = contentStore.Put(p, bytes.NewReader([]byte("dummy5")))
assert.NoError(t, err)
meta, err := repo.GetLFSMetaObjectByOid(p.Oid)
meta, err := models.GetLFSMetaObjectByOid(repo.ID, p.Oid)
assert.Nil(t, meta)
assert.Equal(t, models.ErrLFSObjectNotExist, err)
@ -373,7 +374,7 @@ func TestAPILFSUpload(t *testing.T) {
req := newRequest(t, p, "dummy5")
session.MakeRequest(t, req, http.StatusOK)
meta, err = repo.GetLFSMetaObjectByOid(p.Oid)
meta, err = models.GetLFSMetaObjectByOid(repo.ID, p.Oid)
assert.NoError(t, err)
assert.NotNil(t, meta)
})
@ -417,7 +418,7 @@ func TestAPILFSUpload(t *testing.T) {
assert.NoError(t, err)
assert.True(t, exist)
meta, err := repo.GetLFSMetaObjectByOid(p.Oid)
meta, err := models.GetLFSMetaObjectByOid(repo.ID, p.Oid)
assert.NoError(t, err)
assert.NotNil(t, meta)
})
@ -432,7 +433,7 @@ func TestAPILFSVerify(t *testing.T) {
content := []byte("dummy3")
oid := storeObjectInRepo(t, repo.ID, &content)
defer repo.RemoveLFSMetaObjectByOid(oid)
defer models.RemoveLFSMetaObjectByOid(repo.ID, oid)
session := loginUser(t, "user2")

@ -9,7 +9,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -21,7 +21,7 @@ func TestAPIRepoTeams(t *testing.T) {
defer prepareTestEnv(t)()
// publicOrgRepo = user3/repo21
publicOrgRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 32}).(*models.Repository)
publicOrgRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 32}).(*repo_model.Repository)
// user4
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User)
session := loginUser(t, user.Name)

@ -12,6 +12,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@ -30,7 +31,7 @@ func TestAPIUserReposNotLogin(t *testing.T) {
var apiRepos []api.Repository
DecodeJSON(t, resp, &apiRepos)
expectedLen := unittest.GetCount(t, models.Repository{OwnerID: user.ID},
expectedLen := unittest.GetCount(t, repo_model.Repository{OwnerID: user.ID},
unittest.Cond("is_private = ?", false))
assert.Len(t, apiRepos, expectedLen)
for _, repo := range apiRepos {
@ -206,11 +207,11 @@ func TestAPISearchRepo(t *testing.T) {
}
}
var repoCache = make(map[int64]*models.Repository)
var repoCache = make(map[int64]*repo_model.Repository)
func getRepo(t *testing.T, repoID int64) *models.Repository {
func getRepo(t *testing.T, repoID int64) *repo_model.Repository {
if _, ok := repoCache[repoID]; !ok {
repoCache[repoID] = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository)
repoCache[repoID] = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
}
return repoCache[repoID]
}
@ -482,7 +483,7 @@ func TestAPIRepoTransfer(t *testing.T) {
//start testing
for _, testCase := range testCases {
user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
session = loginUser(t, user.Name)
token = getTokenForLoggedInUser(t, session)
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{
@ -493,7 +494,7 @@ func TestAPIRepoTransfer(t *testing.T) {
}
//cleanup
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
_ = models.DeleteRepository(user, repo.OwnerID, repo.ID)
}
@ -504,7 +505,7 @@ func TestAPIGenerateRepo(t *testing.T) {
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
templateRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 44}).(*models.Repository)
templateRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 44}).(*repo_model.Repository)
// user
repo := new(api.Repository)
@ -539,7 +540,7 @@ func TestAPIRepoGetReviewers(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token)
resp := session.MakeRequest(t, req, http.StatusOK)
@ -553,7 +554,7 @@ func TestAPIRepoGetAssignees(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token)
resp := session.MakeRequest(t, req, http.StatusOK)

@ -10,7 +10,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -55,8 +55,8 @@ func TestAPIRepoTopic(t *testing.T) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // owner of repo2
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) // owner of repo3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // write access to repo 3
repo2 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository)
// Get user2's token
session := loginUser(t, user2.Name)

@ -10,7 +10,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
api "code.gitea.io/gitea/modules/structs"
)
@ -33,7 +33,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) {
for _, repoID := range samples {
b.StopTimer()
repo := unittest.AssertExistsAndLoadBean(b, &models.Repository{ID: repoID}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(b, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
b.StartTimer()
b.Run(repo.Name, func(b *testing.B) {
session := loginUser(b, "user2")

@ -9,14 +9,14 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
)
func TestChangeDefaultBranch(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
session := loginUser(t, owner.Name)

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
)
@ -18,7 +19,7 @@ func assertUserDeleted(t *testing.T, userID int64) {
unittest.AssertNotExistsBean(t, &user_model.User{ID: userID})
unittest.AssertNotExistsBean(t, &user_model.Follow{UserID: userID})
unittest.AssertNotExistsBean(t, &user_model.Follow{FollowID: userID})
unittest.AssertNotExistsBean(t, &models.Repository{OwnerID: userID})
unittest.AssertNotExistsBean(t, &repo_model.Repository{OwnerID: userID})
unittest.AssertNotExistsBean(t, &models.Access{UserID: userID})
unittest.AssertNotExistsBean(t, &models.OrgUser{UID: userID})
unittest.AssertNotExistsBean(t, &models.IssueUser{UID: userID})

@ -8,7 +8,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
)
@ -21,7 +21,7 @@ func TestEmptyRepo(t *testing.T) {
"commit/1ae57b34ccf7e18373",
"graph",
}
emptyRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{}, unittest.Cond("is_empty = ?", true)).(*models.Repository)
emptyRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{}, unittest.Cond("is_empty = ?", true)).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: emptyRepo.OwnerID}).(*user_model.User)
for _, subpath := range subpaths {
req := NewRequestf(t, "GET", "/%s/%s/%s", owner.Name, emptyRepo.Name, subpath)

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/eventsource"
@ -53,7 +54,7 @@ func TestEventSourceManagerRun(t *testing.T) {
}
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
thread5 := unittest.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification)
assert.NoError(t, thread5.LoadAttributes())
session := loginUser(t, user2.Name)

@ -19,6 +19,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -582,7 +583,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
t.Run("SuccessfullyPushAndCreateTestRepository", doGitPushTestRepository(tmpDir, "origin", "master"))
// Finally, fetch repo from database and ensure the correct repository has been created
repo, err := models.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
repo, err := repo_model.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
assert.NoError(t, err)
assert.False(t, repo.IsEmpty)
assert.True(t, repo.IsPrivate)
@ -628,7 +629,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
pr1, pr2 *models.PullRequest
commit string
)
repo, err := models.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
repo, err := repo_model.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
if !assert.NoError(t, err) {
return
}

@ -14,6 +14,7 @@ import (
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/indexer/issues"
@ -63,7 +64,7 @@ func TestViewIssuesSortByType(t *testing.T) {
defer prepareTestEnv(t)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
session := loginUser(t, user.Name)
req := NewRequest(t, "GET", repo.Link()+"/issues?type=created_by")
@ -90,7 +91,7 @@ func TestViewIssuesSortByType(t *testing.T) {
func TestViewIssuesKeyword(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{
RepoID: repo.ID,
Index: 1,

@ -13,6 +13,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/lfs"
@ -40,10 +41,10 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string
}
func storeAndGetLfs(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int) *httptest.ResponseRecorder {
repo, err := models.GetRepositoryByOwnerAndName("user2", "repo1")
repo, err := repo_model.GetRepositoryByOwnerAndName("user2", "repo1")
assert.NoError(t, err)
oid := storeObjectInRepo(t, repo.ID, content)
defer repo.RemoveLFSMetaObjectByOid(oid)
defer models.RemoveLFSMetaObjectByOid(repo.ID, oid)
session := loginUser(t, "user2")

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -24,8 +25,8 @@ func TestMirrorPull(t *testing.T) {
defer prepareTestEnv(t)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoPath := models.RepoPath(user.Name, repo.Name)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repoPath := repo_model.RepoPath(user.Name, repo.Name)
opts := migration.MigrateOptions{
RepoName: "test_mirror",
@ -42,7 +43,7 @@ func TestMirrorPull(t *testing.T) {
Description: opts.Description,
IsPrivate: opts.Private,
IsMirror: opts.Mirror,
Status: models.RepositoryBeingMigrated,
Status: repo_model.RepositoryBeingMigrated,
})
assert.NoError(t, err)
@ -73,7 +74,7 @@ func TestMirrorPull(t *testing.T) {
IsTag: true,
}, nil, ""))
err = mirror.GetMirror()
_, err = repo_model.GetMirrorByRepoID(mirror.ID)
assert.NoError(t, err)
ok := mirror_service.SyncPullMirror(ctx, mirror.ID)

@ -12,6 +12,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -34,7 +35,7 @@ func testMirrorPush(t *testing.T, u *url.URL) {
assert.NoError(t, migrations.Init())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
srcRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
srcRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
mirrorRepo, err := repository.CreateRepository(user, user, models.CreateRepoOptions{
Name: "test-push-mirror",
@ -45,7 +46,7 @@ func testMirrorPush(t *testing.T, u *url.URL) {
doCreatePushMirror(ctx, fmt.Sprintf("%s%s/%s", u.String(), url.PathEscape(ctx.Username), url.PathEscape(mirrorRepo.Name)), user.LowerName, userPassword)(t)
mirrors, err := models.GetPushMirrorsByRepoID(srcRepo.ID)
mirrors, err := repo_model.GetPushMirrorsByRepoID(srcRepo.ID)
assert.NoError(t, err)
assert.Len(t, mirrors, 1)

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
api "code.gitea.io/gitea/modules/structs"
@ -26,7 +27,7 @@ const privateActivityTestOtherUser = "user4"
// activity helpers
func testPrivateActivityDoSomethingForActionEntries(t *testing.T) {
repoBefore := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}).(*user_model.User)
session := loginUser(t, privateActivityTestUser)

@ -17,6 +17,7 @@ import (
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/models/webhook"
@ -29,7 +30,7 @@ import (
"github.com/unknwon/i18n"
)
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum string, mergeStyle models.MergeStyle) *httptest.ResponseRecorder {
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum string, mergeStyle repo_model.MergeStyle) *httptest.ResponseRecorder {
req := NewRequest(t, "GET", path.Join(user, repo, "pulls", pullnum))
resp := session.MakeRequest(t, req, http.StatusOK)
@ -76,7 +77,7 @@ func TestPullMerge(t *testing.T) {
elem := strings.Split(test.RedirectURL(resp), "/")
assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleMerge)
testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleMerge)
hookTasks, err = webhook.HookTasks(1, 1)
assert.NoError(t, err)
@ -98,7 +99,7 @@ func TestPullRebase(t *testing.T) {
elem := strings.Split(test.RedirectURL(resp), "/")
assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleRebase)
testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleRebase)
hookTasks, err = webhook.HookTasks(1, 1)
assert.NoError(t, err)
@ -120,7 +121,7 @@ func TestPullRebaseMerge(t *testing.T) {
elem := strings.Split(test.RedirectURL(resp), "/")
assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleRebaseMerge)
testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleRebaseMerge)
hookTasks, err = webhook.HookTasks(1, 1)
assert.NoError(t, err)
@ -143,7 +144,7 @@ func TestPullSquash(t *testing.T) {
elem := strings.Split(test.RedirectURL(resp), "/")
assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleSquash)
testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleSquash)
hookTasks, err = webhook.HookTasks(1, 1)
assert.NoError(t, err)
@ -161,7 +162,7 @@ func TestPullCleanUpAfterMerge(t *testing.T) {
elem := strings.Split(test.RedirectURL(resp), "/")
assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleMerge)
testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleMerge)
// Check PR branch deletion
resp = testPullCleanUp(t, session, elem[1], elem[2], elem[4])
@ -225,10 +226,10 @@ func TestCantMergeConflict(t *testing.T) {
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{
Name: "user1",
}).(*user_model.User)
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{
OwnerID: user1.ID,
Name: "repo1",
}).(*models.Repository)
}).(*repo_model.Repository)
pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{
HeadRepoID: repo1.ID,
@ -237,14 +238,14 @@ func TestCantMergeConflict(t *testing.T) {
BaseBranch: "base",
}).(*models.PullRequest)
gitRepo, err := git.OpenRepository(models.RepoPath(user1.Name, repo1.Name))
gitRepo, err := git.OpenRepository(repo_model.RepoPath(user1.Name, repo1.Name))
assert.NoError(t, err)
err = pull.Merge(pr, user1, gitRepo, models.MergeStyleMerge, "CONFLICT")
err = pull.Merge(pr, user1, gitRepo, repo_model.MergeStyleMerge, "CONFLICT")
assert.Error(t, err, "Merge should return an error due to conflict")
assert.True(t, models.IsErrMergeConflicts(err), "Merge error is not a conflict error")
err = pull.Merge(pr, user1, gitRepo, models.MergeStyleRebase, "CONFLICT")
err = pull.Merge(pr, user1, gitRepo, repo_model.MergeStyleRebase, "CONFLICT")
assert.Error(t, err, "Merge should return an error due to conflict")
assert.True(t, models.IsErrRebaseConflicts(err), "Merge error is not a conflict error")
gitRepo.Close()
@ -262,11 +263,11 @@ func TestCantMergeUnrelated(t *testing.T) {
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{
Name: "user1",
}).(*user_model.User)
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{
OwnerID: user1.ID,
Name: "repo1",
}).(*models.Repository)
path := models.RepoPath(user1.Name, repo1.Name)
}).(*repo_model.Repository)
path := repo_model.RepoPath(user1.Name, repo1.Name)
_, err := git.NewCommand("read-tree", "--empty").RunInDir(path)
assert.NoError(t, err)
@ -328,7 +329,7 @@ func TestCantMergeUnrelated(t *testing.T) {
BaseBranch: "base",
}).(*models.PullRequest)
err = pull.Merge(pr, user1, gitRepo, models.MergeStyleMerge, "UNRELATED")
err = pull.Merge(pr, user1, gitRepo, repo_model.MergeStyleMerge, "UNRELATED")
assert.Error(t, err, "Merge should return an error due to unrelated")
assert.True(t, models.IsErrMergeUnrelatedHistories(err), "Merge error is not a unrelated histories error")
gitRepo.Close()

@ -10,7 +10,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
@ -134,7 +134,7 @@ func TestCreateReleasePaging(t *testing.T) {
func TestViewReleaseListNoLogin(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
link := repo.Link() + "/releases"
@ -160,7 +160,7 @@ func TestViewReleaseListNoLogin(t *testing.T) {
func TestViewReleaseListLogin(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
link := repo.Link() + "/releases"
@ -191,7 +191,7 @@ func TestViewReleaseListLogin(t *testing.T) {
func TestViewTagsList(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
link := repo.Link() + "/tags"

@ -8,7 +8,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@ -40,6 +40,6 @@ func TestRenameBranch(t *testing.T) {
assert.Equal(t, "/user2/repo1/src/branch/main/README.md", location)
// check db
repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
assert.Equal(t, "main", repo1.DefaultBranch)
}

@ -10,7 +10,7 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
@ -27,7 +27,7 @@ func TestRepoActivity(t *testing.T) {
resp := testPullCreate(t, session, "user1", "repo1", "master", "This is a pull title")
elem := strings.Split(test.RedirectURL(resp), "/")
assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleMerge)
testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleMerge)
testEditFileToNewBranch(t, session, "user1", "repo1", "master", "feat/better_readme", "README.md", "Hello, World (Edited Again)\n")
testPullCreate(t, session, "user1", "repo1", "feat/better_readme", "This is a pull title")

@ -8,7 +8,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
code_indexer "code.gitea.io/gitea/modules/indexer/code"
"code.gitea.io/gitea/modules/setting"
@ -31,7 +31,7 @@ func resultFilenames(t testing.TB, doc *HTMLDoc) []string {
func TestSearchRepo(t *testing.T) {
defer prepareTestEnv(t)()
repo, err := models.GetRepositoryByOwnerAndName("user2", "repo1")
repo, err := repo_model.GetRepositoryByOwnerAndName("user2", "repo1")
assert.NoError(t, err)
executeIndexer(t, repo, code_indexer.UpdateRepoIndexer)
@ -41,7 +41,7 @@ func TestSearchRepo(t *testing.T) {
setting.Indexer.IncludePatterns = setting.IndexerGlobFromString("**.txt")
setting.Indexer.ExcludePatterns = setting.IndexerGlobFromString("**/y/**")
repo, err = models.GetRepositoryByOwnerAndName("user2", "glob")
repo, err = repo_model.GetRepositoryByOwnerAndName("user2", "glob")
assert.NoError(t, err)
executeIndexer(t, repo, code_indexer.UpdateRepoIndexer)
@ -60,6 +60,6 @@ func testSearch(t *testing.T, url string, expected []string) {
assert.EqualValues(t, expected, filenames)
}
func executeIndexer(t *testing.T, repo *models.Repository, op func(*models.Repository)) {
func executeIndexer(t *testing.T, repo *repo_model.Repository, op func(*repo_model.Repository)) {
op(repo)
}

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -22,7 +23,7 @@ import (
func TestCreateNewTagProtected(t *testing.T) {
defer prepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
t.Run("API", func(t *testing.T) {

@ -8,7 +8,7 @@ import (
"net/url"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
@ -17,7 +17,7 @@ import (
"github.com/stretchr/testify/assert"
)
func getDeleteRepoFileOptions(repo *models.Repository) *files_service.DeleteRepoFileOptions {
func getDeleteRepoFileOptions(repo *repo_model.Repository) *files_service.DeleteRepoFileOptions {
return &files_service.DeleteRepoFileOptions{
LastCommitID: "",
OldBranch: repo.DefaultBranch,

@ -10,7 +10,7 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -20,7 +20,7 @@ import (
"github.com/stretchr/testify/assert"
)
func getCreateRepoFileOptions(repo *models.Repository) *files_service.UpdateRepoFileOptions {
func getCreateRepoFileOptions(repo *repo_model.Repository) *files_service.UpdateRepoFileOptions {
return &files_service.UpdateRepoFileOptions{
OldBranch: repo.DefaultBranch,
NewBranch: repo.DefaultBranch,
@ -33,7 +33,7 @@ func getCreateRepoFileOptions(repo *models.Repository) *files_service.UpdateRepo
}
}
func getUpdateRepoFileOptions(repo *models.Repository) *files_service.UpdateRepoFileOptions {
func getUpdateRepoFileOptions(repo *repo_model.Repository) *files_service.UpdateRepoFileOptions {
return &files_service.UpdateRepoFileOptions{
OldBranch: repo.DefaultBranch,
NewBranch: repo.DefaultBranch,

@ -6,10 +6,12 @@
package models
import (
"context"
"fmt"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
)
@ -27,7 +29,7 @@ func init() {
db.RegisterModel(new(Access))
}
func accessLevel(e db.Engine, user *user_model.User, repo *Repository) (perm.AccessMode, error) {
func accessLevel(e db.Engine, user *user_model.User, repo *repo_model.Repository) (perm.AccessMode, error) {
mode := perm.AccessModeNone
var userID int64
restricted := false
@ -81,7 +83,7 @@ func updateUserAccess(accessMap map[int64]*userAccess, user *user_model.User, mo
}
// FIXME: do cross-comparison so reduce deletions and additions to the minimum?
func (repo *Repository) refreshAccesses(e db.Engine, accessMap map[int64]*userAccess) (err error) {
func refreshAccesses(e db.Engine, repo *repo_model.Repository, accessMap map[int64]*userAccess) (err error) {
minMode := perm.AccessModeRead
if !repo.IsPrivate {
minMode = perm.AccessModeWrite
@ -115,8 +117,8 @@ func (repo *Repository) refreshAccesses(e db.Engine, accessMap map[int64]*userAc
}
// refreshCollaboratorAccesses retrieves repository collaborations with their access modes.
func (repo *Repository) refreshCollaboratorAccesses(e db.Engine, accessMap map[int64]*userAccess) error {
collaborators, err := repo.getCollaborators(e, db.ListOptions{})
func refreshCollaboratorAccesses(e db.Engine, repoID int64, accessMap map[int64]*userAccess) error {
collaborators, err := getCollaborators(e, repoID, db.ListOptions{})
if err != nil {
return fmt.Errorf("getCollaborations: %v", err)
}
@ -132,16 +134,18 @@ func (repo *Repository) refreshCollaboratorAccesses(e db.Engine, accessMap map[i
// recalculateTeamAccesses recalculates new accesses for teams of an organization
// except the team whose ID is given. It is used to assign a team ID when
// remove repository from that team.
func (repo *Repository) recalculateTeamAccesses(e db.Engine, ignTeamID int64) (err error) {
func recalculateTeamAccesses(ctx context.Context, repo *repo_model.Repository, ignTeamID int64) (err error) {
accessMap := make(map[int64]*userAccess, 20)
if err = repo.getOwner(e); err != nil {
if err = repo.GetOwner(ctx); err != nil {
return err
} else if !repo.Owner.IsOrganization() {
return fmt.Errorf("owner is not an organization: %d", repo.OwnerID)
}
if err = repo.refreshCollaboratorAccesses(e, accessMap); err != nil {
e := db.GetEngine(ctx)
if err = refreshCollaboratorAccesses(e, repo.ID, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
}
@ -171,26 +175,27 @@ func (repo *Repository) recalculateTeamAccesses(e db.Engine, ignTeamID int64) (e
}
}
return repo.refreshAccesses(e, accessMap)
return refreshAccesses(e, repo, accessMap)
}
// recalculateUserAccess recalculates new access for a single user
// Usable if we know access only affected one user
func (repo *Repository) recalculateUserAccess(e db.Engine, uid int64) (err error) {
func recalculateUserAccess(ctx context.Context, repo *repo_model.Repository, uid int64) (err error) {
minMode := perm.AccessModeRead
if !repo.IsPrivate {
minMode = perm.AccessModeWrite
}
accessMode := perm.AccessModeNone
collaborator, err := repo.getCollaboration(e, uid)
e := db.GetEngine(ctx)
collaborator, err := getCollaboration(e, repo.ID, uid)
if err != nil {
return err
} else if collaborator != nil {
accessMode = collaborator.Mode
}
if err = repo.getOwner(e); err != nil {
if err = repo.GetOwner(ctx); err != nil {
return err
} else if repo.Owner.IsOrganization() {
var teams []Team
@ -223,19 +228,20 @@ func (repo *Repository) recalculateUserAccess(e db.Engine, uid int64) (err error
return nil
}
func (repo *Repository) recalculateAccesses(e db.Engine) error {
func recalculateAccesses(ctx context.Context, repo *repo_model.Repository) error {
if repo.Owner.IsOrganization() {
return repo.recalculateTeamAccesses(e, 0)
return recalculateTeamAccesses(ctx, repo, 0)
}
e := db.GetEngine(ctx)
accessMap := make(map[int64]*userAccess, 20)
if err := repo.refreshCollaboratorAccesses(e, accessMap); err != nil {
if err := refreshCollaboratorAccesses(e, repo.ID, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
}
return repo.refreshAccesses(e, accessMap)
return refreshAccesses(e, repo, accessMap)
}
// RecalculateAccesses recalculates all accesses for repository.
func (repo *Repository) RecalculateAccesses() error {
return repo.recalculateAccesses(db.GetEngine(db.DefaultContext))
func RecalculateAccesses(repo *repo_model.Repository) error {
return recalculateAccesses(db.DefaultContext, repo)
}

@ -9,6 +9,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -22,17 +23,17 @@ func TestAccessLevel(t *testing.T) {
user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User)
user29 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29}).(*user_model.User)
// A public repository owned by User 2
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
assert.False(t, repo1.IsPrivate)
// A private repository owned by Org 3
repo3 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository)
assert.True(t, repo3.IsPrivate)
// Another public repository
repo4 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
repo4 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}).(*repo_model.Repository)
assert.False(t, repo4.IsPrivate)
// org. owned private repo
repo24 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository)
repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24}).(*repo_model.Repository)
level, err := AccessLevel(user2, repo1)
assert.NoError(t, err)
@ -72,10 +73,10 @@ func TestHasAccess(t *testing.T) {
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User)
// A public repository owned by User 2
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
assert.False(t, repo1.IsPrivate)
// A private repository owned by Org 3
repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository)
assert.True(t, repo2.IsPrivate)
has, err := HasAccess(user1.ID, repo1)
@ -95,12 +96,12 @@ func TestHasAccess(t *testing.T) {
func TestRepository_RecalculateAccesses(t *testing.T) {
// test with organization repo
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
assert.NoError(t, repo1.GetOwner())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository)
assert.NoError(t, repo1.GetOwner(db.DefaultContext))
_, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 2, RepoID: 3})
assert.NoError(t, err)
assert.NoError(t, repo1.RecalculateAccesses())
assert.NoError(t, RecalculateAccesses(repo1))
access := &Access{UserID: 2, RepoID: 3}
has, err := db.GetEngine(db.DefaultContext).Get(access)
@ -112,12 +113,12 @@ func TestRepository_RecalculateAccesses(t *testing.T) {
func TestRepository_RecalculateAccesses2(t *testing.T) {
// test with non-organization repo
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
assert.NoError(t, repo1.GetOwner())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}).(*repo_model.Repository)
assert.NoError(t, repo1.GetOwner(db.DefaultContext))
_, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 4, RepoID: 4})
assert.NoError(t, err)
assert.NoError(t, repo1.RecalculateAccesses())
assert.NoError(t, RecalculateAccesses(repo1))
has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 4, RepoID: 4})
assert.NoError(t, err)

@ -6,6 +6,7 @@
package models
import (
"context"
"fmt"
"net/url"
"path"
@ -14,6 +15,7 @@ import (
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
@ -64,13 +66,13 @@ type Action struct {
ID int64 `xorm:"pk autoincr"`
UserID int64 `xorm:"INDEX"` // Receiver user id.
OpType ActionType
ActUserID int64 `xorm:"INDEX"` // Action user id.
ActUser *user_model.User `xorm:"-"`
RepoID int64 `xorm:"INDEX"`
Repo *Repository `xorm:"-"`
CommentID int64 `xorm:"INDEX"`
Comment *Comment `xorm:"-"`
IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
ActUserID int64 `xorm:"INDEX"` // Action user id.
ActUser *user_model.User `xorm:"-"`
RepoID int64 `xorm:"INDEX"`
Repo *repo_model.Repository `xorm:"-"`
CommentID int64 `xorm:"INDEX"`
Comment *Comment `xorm:"-"`
IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
RefName string
IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
Content string `xorm:"TEXT"`
@ -107,9 +109,9 @@ func (a *Action) loadRepo() {
return
}
var err error
a.Repo, err = GetRepositoryByID(a.RepoID)
a.Repo, err = repo_model.GetRepositoryByID(a.RepoID)
if err != nil {
log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
log.Error("repo_model.GetRepositoryByID(%d): %v", a.RepoID, err)
}
}
@ -191,16 +193,16 @@ func (a *Action) GetRepoLink() string {
return path.Join(setting.AppSubURL, "/", url.PathEscape(a.GetRepoUserName()), url.PathEscape(a.GetRepoName()))
}
// GetRepositoryFromMatch returns a *Repository from a username and repo strings
func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) {
// GetRepositoryFromMatch returns a *repo_model.Repository from a username and repo strings
func GetRepositoryFromMatch(ownerName, repoName string) (*repo_model.Repository, error) {
var err error
refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
refRepo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName)
if err != nil {
if IsErrRepoNotExist(err) {
if repo_model.IsErrRepoNotExist(err) {
log.Warn("Repository referenced in commit but does not exist: %v", err)
return nil, err
}
log.Error("GetRepositoryByOwnerAndName: %v", err)
log.Error("repo_model.GetRepositoryByOwnerAndName: %v", err)
return nil, err
}
return refRepo, nil
@ -208,13 +210,14 @@ func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) {
// GetCommentLink returns link to action comment.
func (a *Action) GetCommentLink() string {
return a.getCommentLink(db.GetEngine(db.DefaultContext))
return a.getCommentLink(db.DefaultContext)
}
func (a *Action) getCommentLink(e db.Engine) string {
func (a *Action) getCommentLink(ctx context.Context) string {
if a == nil {
return "#"
}
e := db.GetEngine(ctx)
if a.Comment == nil && a.CommentID != 0 {
a.Comment, _ = getCommentByID(e, a.CommentID)
}
@ -236,7 +239,7 @@ func (a *Action) getCommentLink(e db.Engine) string {
return "#"
}
if err = issue.loadRepo(e); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return "#"
}

@ -8,6 +8,7 @@ import (
"fmt"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
)
@ -59,13 +60,13 @@ func (actions ActionList) getRepoIDs() []int64 {
return keysInt64(repoIDs)
}
func (actions ActionList) loadRepositories(e db.Engine) ([]*Repository, error) {
func (actions ActionList) loadRepositories(e db.Engine) ([]*repo_model.Repository, error) {
if len(actions) == 0 {
return nil, nil
}
repoIDs := actions.getRepoIDs()
repoMaps := make(map[int64]*Repository, len(repoIDs))
repoMaps := make(map[int64]*repo_model.Repository, len(repoIDs))
err := e.
In("id", repoIDs).
Find(&repoMaps)
@ -80,7 +81,7 @@ func (actions ActionList) loadRepositories(e db.Engine) ([]*Repository, error) {
}
// LoadRepositories loads actions' all repositories
func (actions ActionList) LoadRepositories() ([]*Repository, error) {
func (actions ActionList) LoadRepositories() ([]*repo_model.Repository, error) {
return actions.loadRepositories(db.GetEngine(db.DefaultContext))
}

@ -8,6 +8,7 @@ import (
"path"
"testing"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@ -17,7 +18,7 @@ import (
func TestAction_GetRepoPath(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
action := &Action{RepoID: repo.ID}
assert.Equal(t, path.Join(owner.Name, repo.Name), action.GetRepoPath())
@ -25,7 +26,7 @@ func TestAction_GetRepoPath(t *testing.T) {
func TestAction_GetRepoLink(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
action := &Action{RepoID: repo.ID}
setting.AppSubURL = "/suburl"

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/base"
@ -74,8 +75,8 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
if user, err := user_model.GetUserByID(userID); err != nil {
log.Error("GetUserByID: %v", err)
return false
} else if repo, err := GetRepositoryByID(protectBranch.RepoID); err != nil {
log.Error("GetRepositoryByID: %v", err)
} else if repo, err := repo_model.GetRepositoryByID(protectBranch.RepoID); err != nil {
log.Error("repo_model.GetRepositoryByID: %v", err)
return false
} else if writeAccess, err := HasAccessUnit(user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil {
log.Error("HasAccessUnit: %v", err)
@ -102,7 +103,7 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
}
// IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permissionInRepo Permission) bool {
func IsUserMergeWhitelisted(protectBranch *ProtectedBranch, userID int64, permissionInRepo Permission) bool {
if !protectBranch.EnableMergeWhitelist {
// Then we need to fall back on whether the user has write permission
return permissionInRepo.CanWrite(unit.TypeCode)
@ -125,19 +126,19 @@ func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permi
}
// IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *user_model.User) (bool, error) {
return protectBranch.isUserOfficialReviewer(db.GetEngine(db.DefaultContext), user)
func IsUserOfficialReviewer(protectBranch *ProtectedBranch, user *user_model.User) (bool, error) {
return isUserOfficialReviewer(db.DefaultContext, protectBranch, user)
}
func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e db.Engine, user *user_model.User) (bool, error) {
repo, err := getRepositoryByID(e, protectBranch.RepoID)
func isUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) {
repo, err := repo_model.GetRepositoryByIDCtx(ctx, protectBranch.RepoID)
if err != nil {
return false, err
}
if !protectBranch.EnableApprovalsWhitelist {
// Anyone with write access is considered official reviewer
writeAccess, err := hasAccessUnit(e, user, repo, unit.TypeCode, perm.AccessModeWrite)
writeAccess, err := hasAccessUnit(ctx, user, repo, unit.TypeCode, perm.AccessModeWrite)
if err != nil {
return false, err
}
@ -148,7 +149,7 @@ func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e db.Engine, user *
return true, nil
}
inTeam, err := isUserInTeams(e, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
inTeam, err := isUserInTeams(db.GetEngine(ctx), user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
if err != nil {
return false, err
}
@ -335,8 +336,8 @@ type WhitelistOptions struct {
// If ID is 0, it creates a new record. Otherwise, updates existing record.
// This function also performs check if whitelist user and team's IDs have been changed
// to avoid unnecessary whitelist delete and regenerate.
func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
if err = repo.GetOwner(); err != nil {
func UpdateProtectBranch(repo *repo_model.Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
if err = repo.GetOwner(db.DefaultContext); err != nil {
return fmt.Errorf("GetOwner: %v", err)
}
@ -393,20 +394,15 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts
}
// GetProtectedBranches get all protected branches
func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
func GetProtectedBranches(repoID int64) ([]*ProtectedBranch, error) {
protectedBranches := make([]*ProtectedBranch, 0)
return protectedBranches, db.GetEngine(db.DefaultContext).Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
}
// GetBranchProtection get the branch protection of a branch
func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
return GetProtectedBranchBy(repo.ID, branchName)
return protectedBranches, db.GetEngine(db.DefaultContext).Find(&protectedBranches, &ProtectedBranch{RepoID: repoID})
}
// IsProtectedBranch checks if branch is protected
func (repo *Repository) IsProtectedBranch(branchName string) (bool, error) {
func IsProtectedBranch(repoID int64, branchName string) (bool, error) {
protectedBranch := &ProtectedBranch{
RepoID: repo.ID,
RepoID: repoID,
BranchName: branchName,
}
@ -419,7 +415,7 @@ func (repo *Repository) IsProtectedBranch(branchName string) (bool, error) {
// updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
// the users from newWhitelist which have explicit read or write access to the repo.
func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
func updateApprovalWhitelist(repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
if !hasUsersChanged {
return currentWhitelist, nil
@ -427,7 +423,7 @@ func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []
whitelist = make([]int64, 0, len(newWhitelist))
for _, userID := range newWhitelist {
if reader, err := repo.IsReader(userID); err != nil {
if reader, err := IsRepoReader(repo, userID); err != nil {
return nil, err
} else if !reader {
continue
@ -440,7 +436,7 @@ func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []
// updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
// the users from newWhitelist which have write access to the repo.
func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
func updateUserWhitelist(repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
if !hasUsersChanged {
return currentWhitelist, nil
@ -469,7 +465,7 @@ func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int6
// updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
// the teams from newWhitelist which have write access to the repo.
func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
func updateTeamWhitelist(repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
if !hasTeamsChanged {
return currentWhitelist, nil
@ -491,9 +487,9 @@ func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int6
}
// DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
func DeleteProtectedBranch(repoID, id int64) (err error) {
protectedBranch := &ProtectedBranch{
RepoID: repo.ID,
RepoID: repoID,
ID: id,
}
@ -518,28 +514,28 @@ type DeletedBranch struct {
}
// AddDeletedBranch adds a deleted branch to the database
func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
func AddDeletedBranch(repoID int64, branchName, commit string, deletedByID int64) error {
deletedBranch := &DeletedBranch{
RepoID: repo.ID,
RepoID: repoID,
Name: branchName,
Commit: commit,
DeletedByID: deletedByID,
}
_, err := db.GetEngine(db.DefaultContext).InsertOne(deletedBranch)
_, err := db.GetEngine(db.DefaultContext).Insert(deletedBranch)
return err
}
// GetDeletedBranches returns all the deleted branches
func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
func GetDeletedBranches(repoID int64) ([]*DeletedBranch, error) {
deletedBranches := make([]*DeletedBranch, 0)
return deletedBranches, db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
return deletedBranches, db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Desc("deleted_unix").Find(&deletedBranches)
}
// GetDeletedBranchByID get a deleted branch by its ID
func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
func GetDeletedBranchByID(repoID, id int64) (*DeletedBranch, error) {
deletedBranch := &DeletedBranch{}
has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("id = ?", id).Get(deletedBranch)
has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).And("id = ?", id).Get(deletedBranch)
if err != nil {
return nil, err
}
@ -549,10 +545,10 @@ func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
return deletedBranch, nil
}
// RemoveDeletedBranch removes a deleted branch from the database
func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
// RemoveDeletedBranchByID removes a deleted branch from the database
func RemoveDeletedBranchByID(repoID, id int64) (err error) {
deletedBranch := &DeletedBranch{
RepoID: repo.ID,
RepoID: repoID,
ID: id,
}
@ -575,8 +571,8 @@ func (deletedBranch *DeletedBranch) LoadUser() {
deletedBranch.DeletedBy = user
}
// RemoveDeletedBranch removes all deleted branches
func RemoveDeletedBranch(repoID int64, branch string) error {
// RemoveDeletedBranchByName removes all deleted branches
func RemoveDeletedBranchByName(repoID int64, branch string) error {
_, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
return err
}
@ -615,7 +611,7 @@ func FindRenamedBranch(repoID int64, from string) (branch *RenamedBranch, exist
}
// RenameBranch rename a branch
func (repo *Repository) RenameBranch(from, to string, gitAction func(isDefault bool) error) (err error) {
func RenameBranch(repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) {
ctx, committer, err := db.TxContext()
if err != nil {
return err

@ -7,6 +7,7 @@ package models
import (
"testing"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@ -14,18 +15,18 @@ import (
func TestAddDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
firstBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
assert.Error(t, repo.AddDeletedBranch(firstBranch.Name, firstBranch.Commit, firstBranch.DeletedByID))
assert.NoError(t, repo.AddDeletedBranch("test", "5655464564554545466464656", int64(1)))
assert.Error(t, AddDeletedBranch(repo.ID, firstBranch.Name, firstBranch.Commit, firstBranch.DeletedByID))
assert.NoError(t, AddDeletedBranch(repo.ID, "test", "5655464564554545466464656", int64(1)))
}
func TestGetDeletedBranches(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
branches, err := repo.GetDeletedBranches()
branches, err := GetDeletedBranches(repo.ID)
assert.NoError(t, err)
assert.Len(t, branches, 2)
}
@ -58,20 +59,20 @@ func TestDeletedBranchLoadUser(t *testing.T) {
func TestRemoveDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
firstBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
err := repo.RemoveDeletedBranch(1)
err := RemoveDeletedBranchByID(repo.ID, 1)
assert.NoError(t, err)
unittest.AssertNotExistsBean(t, firstBranch)
unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2})
}
func getDeletedBranch(t *testing.T, branch *DeletedBranch) *DeletedBranch {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
deletedBranch, err := repo.GetDeletedBranchByID(branch.ID)
deletedBranch, err := GetDeletedBranchByID(repo.ID, branch.ID)
assert.NoError(t, err)
assert.Equal(t, branch.ID, deletedBranch.ID)
assert.Equal(t, branch.Name, deletedBranch.Name)
@ -95,7 +96,7 @@ func TestFindRenamedBranch(t *testing.T) {
func TestRenameBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
_isDefault := false
err := UpdateProtectBranch(repo1, &ProtectedBranch{
@ -104,13 +105,13 @@ func TestRenameBranch(t *testing.T) {
}, WhitelistOptions{})
assert.NoError(t, err)
assert.NoError(t, repo1.RenameBranch("master", "main", func(isDefault bool) error {
assert.NoError(t, RenameBranch(repo1, "master", "main", func(isDefault bool) error {
_isDefault = isDefault
return nil
}))
assert.Equal(t, true, _isDefault)
repo1 = unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
assert.Equal(t, "main", repo1.DefaultBranch)
pull := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) // merged
@ -136,9 +137,9 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) {
// Get deletedBranch with ID of 1 on repo with ID 2.
// This should return a nil branch as this deleted branch
// is actually on repo with ID 1.
repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository)
deletedBranch, err := repo2.GetDeletedBranchByID(1)
deletedBranch, err := GetDeletedBranchByID(repo2.ID, 1)
// Expect no error, and the returned branch is nil.
assert.NoError(t, err)
@ -146,9 +147,9 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) {
// Now get the deletedBranch with ID of 1 on repo with ID 1.
// This should return the deletedBranch.
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
deletedBranch, err = repo1.GetDeletedBranchByID(1)
deletedBranch, err = GetDeletedBranchByID(repo1.ID, 1)
// Expect no error, and the returned branch to be not nil.
assert.NoError(t, err)

@ -5,12 +5,13 @@
package models
import (
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
)
// ConvertFromGitCommit converts git commits into SignCommitWithStatuses
func ConvertFromGitCommit(commits []*git.Commit, repo *Repository) []*SignCommitWithStatuses {
func ConvertFromGitCommit(commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses {
return ParseCommitsWithStatus(
ParseCommitsWithSignature(
user_model.ValidateCommitsWithEmails(commits),

@ -5,6 +5,7 @@
package models
import (
"context"
"crypto/sha1"
"fmt"
"net/url"
@ -12,6 +13,7 @@ import (
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -23,17 +25,17 @@ import (
// CommitStatus holds a single Status of a single Commit
type CommitStatus struct {
ID int64 `xorm:"pk autoincr"`
Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
Repo *Repository `xorm:"-"`
State api.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
TargetURL string `xorm:"TEXT"`
Description string `xorm:"TEXT"`
ContextHash string `xorm:"char(40) index"`
Context string `xorm:"TEXT"`
Creator *user_model.User `xorm:"-"`
ID int64 `xorm:"pk autoincr"`
Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
Repo *repo_model.Repository `xorm:"-"`
State api.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
TargetURL string `xorm:"TEXT"`
Description string `xorm:"TEXT"`
ContextHash string `xorm:"char(40) index"`
Context string `xorm:"TEXT"`
Creator *user_model.User `xorm:"-"`
CreatorID int64
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
@ -120,15 +122,15 @@ func getNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
return curIdx, nil
}
func (status *CommitStatus) loadAttributes(e db.Engine) (err error) {
func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
if status.Repo == nil {
status.Repo, err = getRepositoryByID(e, status.RepoID)
status.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, status.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
}
}
if status.Creator == nil && status.CreatorID > 0 {
status.Creator, err = user_model.GetUserByIDEngine(e, status.CreatorID)
status.Creator, err = user_model.GetUserByIDEngine(db.GetEngine(ctx), status.CreatorID)
if err != nil {
return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
}
@ -138,7 +140,7 @@ func (status *CommitStatus) loadAttributes(e db.Engine) (err error) {
// APIURL returns the absolute APIURL to this commit-status.
func (status *CommitStatus) APIURL() string {
_ = status.loadAttributes(db.GetEngine(db.DefaultContext))
_ = status.loadAttributes(db.DefaultContext)
return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA)
}
@ -170,7 +172,7 @@ type CommitStatusOptions struct {
}
// GetCommitStatuses returns all statuses for a given commit.
func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) {
func GetCommitStatuses(repo *repo_model.Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) {
if opts.Page <= 0 {
opts.Page = 1
}
@ -193,7 +195,7 @@ func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions)
return statuses, maxResults, findSession.Find(&statuses)
}
func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
func listCommitStatusesStatement(repo *repo_model.Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
sess := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("sha = ?", sha)
switch opts.State {
case "pending", "success", "error", "failure", "warning":
@ -274,7 +276,7 @@ func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]s
// NewCommitStatusOptions holds options for creating a CommitStatus
type NewCommitStatusOptions struct {
Repo *Repository
Repo *repo_model.Repository
Creator *user_model.User
SHA string
CommitStatus *CommitStatus
@ -330,7 +332,7 @@ type SignCommitWithStatuses struct {
}
// ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
func ParseCommitsWithStatus(oldCommits []*SignCommit, repo *Repository) []*SignCommitWithStatuses {
func ParseCommitsWithStatus(oldCommits []*SignCommit, repo *repo_model.Repository) []*SignCommitWithStatuses {
newCommits := make([]*SignCommitWithStatuses, 0, len(oldCommits))
for _, c := range oldCommits {

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/structs"
@ -17,7 +18,7 @@ import (
func TestGetCommitStatuses(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
sha1 := "1234123412341234123412341234123412341234"

@ -7,6 +7,7 @@ package models
import (
admin_model "code.gitea.io/gitea/models/admin"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"xorm.io/builder"
@ -158,12 +159,12 @@ func DeleteOrphanedObjects(subject, refobject, joinCond string) error {
// CountNullArchivedRepository counts the number of repositories with is_archived is null
func CountNullArchivedRepository() (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Count(new(Repository))
return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Count(new(repo_model.Repository))
}
// FixNullArchivedRepository sets is_archived to false where it is null
func FixNullArchivedRepository() (int64, error) {
return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{
return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&repo_model.Repository{
IsArchived: false,
})
}

@ -9,6 +9,7 @@ import (
"fmt"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/git"
)
@ -548,32 +549,6 @@ func (err ErrLFSFileLocked) Error() string {
return fmt.Sprintf("File is lfs locked [repo: %d, locked by: %s, path: %s]", err.RepoID, err.UserName, err.Path)
}
// __________ .__ __
// \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__.
// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | |
// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ |
// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____|
// \/ \/|__| \/ \/
// ErrRepoNotExist represents a "RepoNotExist" kind of error.
type ErrRepoNotExist struct {
ID int64
UID int64
OwnerName string
Name string
}
// IsErrRepoNotExist checks if an error is a ErrRepoNotExist.
func IsErrRepoNotExist(err error) bool {
_, ok := err.(ErrRepoNotExist)
return ok
}
func (err ErrRepoNotExist) Error() string {
return fmt.Sprintf("repository does not exist [id: %d, uid: %d, owner_name: %s, name: %s]",
err.ID, err.UID, err.OwnerName, err.Name)
}
// ErrNoPendingRepoTransfer is an error type for repositories without a pending
// transfer request
type ErrNoPendingRepoTransfer struct {
@ -1283,7 +1258,7 @@ func (err ErrPullRequestHeadRepoMissing) Error() string {
// ErrInvalidMergeStyle represents an error if merging with disabled merge strategy
type ErrInvalidMergeStyle struct {
ID int64
Style MergeStyle
Style repo_model.MergeStyle
}
// IsErrInvalidMergeStyle checks if an error is a ErrInvalidMergeStyle.
@ -1299,7 +1274,7 @@ func (err ErrInvalidMergeStyle) Error() string {
// ErrMergeConflicts represents an error if merging fails with a conflict
type ErrMergeConflicts struct {
Style MergeStyle
Style repo_model.MergeStyle
StdOut string
StdErr string
Err error
@ -1317,7 +1292,7 @@ func (err ErrMergeConflicts) Error() string {
// ErrMergeUnrelatedHistories represents an error if merging fails due to unrelated histories
type ErrMergeUnrelatedHistories struct {
Style MergeStyle
Style repo_model.MergeStyle
StdOut string
StdErr string
Err error
@ -1335,7 +1310,7 @@ func (err ErrMergeUnrelatedHistories) Error() string {
// ErrRebaseConflicts represents an error if rebase fails with a conflict
type ErrRebaseConflicts struct {
Style MergeStyle
Style repo_model.MergeStyle
CommitSHA string
StdOut string
StdErr string

@ -9,19 +9,20 @@ import (
"strings"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
)
// GetYamlFixturesAccess returns a string containing the contents
// for the access table, as recalculated using repo.RecalculateAccesses()
func GetYamlFixturesAccess() (string, error) {
repos := make([]*Repository, 0, 50)
repos := make([]*repo_model.Repository, 0, 50)
if err := db.GetEngine(db.DefaultContext).Find(&repos); err != nil {
return "", err
}
for _, repo := range repos {
repo.MustOwner()
if err := repo.RecalculateAccesses(); err != nil {
if err := RecalculateAccesses(repo); err != nil {
return "", err
}
}

@ -10,6 +10,7 @@ import (
"strings"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
@ -69,7 +70,7 @@ const (
)
// ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
func ParseCommitsWithSignature(oldCommits []*user_model.UserCommit, repository *Repository) []*SignCommit {
func ParseCommitsWithSignature(oldCommits []*user_model.UserCommit, repository *repo_model.Repository) []*SignCommit {
newCommits := make([]*SignCommit, 0, len(oldCommits))
keyMap := map[string]bool{}
@ -447,7 +448,7 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use
}
// CalculateTrustStatus will calculate the TrustStatus for a commit verification within a repository
func CalculateTrustStatus(verification *CommitVerification, repository *Repository, keyMap *map[string]bool) (err error) {
func CalculateTrustStatus(verification *CommitVerification, repository *repo_model.Repository, keyMap *map[string]bool) (err error) {
if !verification.Verified {
return
}
@ -458,7 +459,7 @@ func CalculateTrustStatus(verification *CommitVerification, repository *Reposito
// In the Committer trust model a signature is trusted if it matches the committer
// - it doesn't matter if they're a collaborator, the owner, Gitea or Github
// NB: This model is commit verification only
if trustModel == CommitterTrustModel {
if trustModel == repo_model.CommitterTrustModel {
// default to "unmatched"
verification.TrustStatus = "unmatched"
@ -479,9 +480,9 @@ func CalculateTrustStatus(verification *CommitVerification, repository *Reposito
if verification.SigningUser.ID == 0 {
// This commit is signed by the default key - but this key is not assigned to a user in the DB.
// However in the CollaboratorCommitterTrustModel we cannot mark this as trusted
// However in the repo_model.CollaboratorCommitterTrustModel we cannot mark this as trusted
// unless the default key matches the email of a non-user.
if trustModel == CollaboratorCommitterTrustModel && (verification.CommittingUser.ID != 0 ||
if trustModel == repo_model.CollaboratorCommitterTrustModel && (verification.CommittingUser.ID != 0 ||
verification.SigningUser.Email != verification.CommittingUser.Email) {
verification.TrustStatus = "untrusted"
}
@ -493,11 +494,11 @@ func CalculateTrustStatus(verification *CommitVerification, repository *Reposito
var has bool
isMember, has = (*keyMap)[verification.SigningKey.KeyID]
if !has {
isMember, err = repository.IsOwnerMemberCollaborator(verification.SigningUser.ID)
isMember, err = IsOwnerMemberCollaborator(repository, verification.SigningUser.ID)
(*keyMap)[verification.SigningKey.KeyID] = isMember
}
} else {
isMember, err = repository.IsOwnerMemberCollaborator(verification.SigningUser.ID)
isMember, err = IsOwnerMemberCollaborator(repository, verification.SigningUser.ID)
}
if !isMember {
@ -507,7 +508,7 @@ func CalculateTrustStatus(verification *CommitVerification, repository *Reposito
// This should be marked as questionable unless the signing user is a collaborator/team member etc.
verification.TrustStatus = "unmatched"
}
} else if trustModel == CollaboratorCommitterTrustModel && verification.CommittingUser.ID != verification.SigningUser.ID {
} else if trustModel == repo_model.CollaboratorCommitterTrustModel && verification.CommittingUser.ID != verification.SigningUser.ID {
// The committing user and the signing user are not the same and our trustmodel states that they must match
verification.TrustStatus = "unmatched"
}

@ -5,10 +5,8 @@
package models
import (
"encoding/binary"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/json"
)
func keysInt64(m map[int64]struct{}) []int64 {
@ -19,8 +17,8 @@ func keysInt64(m map[int64]struct{}) []int64 {
return keys
}
func valuesRepository(m map[int64]*Repository) []*Repository {
values := make([]*Repository, 0, len(m))
func valuesRepository(m map[int64]*repo_model.Repository) []*repo_model.Repository {
values := make([]*repo_model.Repository, 0, len(m))
for _, v := range m {
values = append(values, v)
}
@ -34,32 +32,3 @@ func valuesUser(m map[int64]*user_model.User) []*user_model.User {
}
return values
}
// JSONUnmarshalHandleDoubleEncode - due to a bug in xorm (see https://gitea.com/xorm/xorm/pulls/1957) - it's
// possible that a Blob may be double encoded or gain an unwanted prefix of 0xff 0xfe.
func JSONUnmarshalHandleDoubleEncode(bs []byte, v interface{}) error {
err := json.Unmarshal(bs, v)
if err != nil {
ok := true
rs := []byte{}
temp := make([]byte, 2)
for _, rn := range string(bs) {
if rn > 0xffff {
ok = false
break
}
binary.LittleEndian.PutUint16(temp, uint16(rn))
rs = append(rs, temp...)
}
if ok {
if len(rs) > 1 && rs[0] == 0xff && rs[1] == 0xfe {
rs = rs[2:]
}
err = json.Unmarshal(rs, v)
}
}
if err != nil && len(bs) > 2 && bs[0] == 0xff && bs[1] == 0xfe {
err = json.Unmarshal(bs[2:], v)
}
return err
}

@ -9,6 +9,7 @@ import (
"os"
"strings"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
)
@ -33,19 +34,19 @@ const (
// It is recommended to avoid using this unless you are pushing within a transaction
// or if you absolutely are sure that post-receive and pre-receive will do nothing
// We provide the full pushing-environment for other hook providers
func InternalPushingEnvironment(doer *user_model.User, repo *Repository) []string {
func InternalPushingEnvironment(doer *user_model.User, repo *repo_model.Repository) []string {
return append(PushingEnvironment(doer, repo),
EnvIsInternal+"=true",
)
}
// PushingEnvironment returns an os environment to allow hooks to work on push
func PushingEnvironment(doer *user_model.User, repo *Repository) []string {
func PushingEnvironment(doer *user_model.User, repo *repo_model.Repository) []string {
return FullPushingEnvironment(doer, doer, repo, repo.Name, 0)
}
// FullPushingEnvironment returns an os environment to allow hooks to work on push
func FullPushingEnvironment(author, committer *user_model.User, repo *Repository, repoName string, prID int64) []string {
func FullPushingEnvironment(author, committer *user_model.User, repo *repo_model.Repository, repoName string, prID int64) []string {
isWiki := "false"
if strings.HasSuffix(repoName, ".wiki") {
isWiki = "true"

@ -33,12 +33,12 @@ import (
// Issue represents an issue or pull request of repository.
type Issue struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
Repo *Repository `xorm:"-"`
Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
PosterID int64 `xorm:"INDEX"`
Poster *user_model.User `xorm:"-"`
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
Repo *repo_model.Repository `xorm:"-"`
Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
PosterID int64 `xorm:"INDEX"`
Poster *user_model.User `xorm:"-"`
OriginalAuthor string
OriginalAuthorID int64 `xorm:"index"`
Title string `xorm:"name"`
@ -118,12 +118,12 @@ func (issue *Issue) IsOverdue() bool {
// LoadRepo loads issue's repository
func (issue *Issue) LoadRepo() error {
return issue.loadRepo(db.GetEngine(db.DefaultContext))
return issue.loadRepo(db.DefaultContext)
}
func (issue *Issue) loadRepo(e db.Engine) (err error) {
func (issue *Issue) loadRepo(ctx context.Context) (err error) {
if issue.Repo == nil {
issue.Repo, err = getRepositoryByID(e, issue.RepoID)
issue.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, issue.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
}
@ -133,11 +133,11 @@ func (issue *Issue) loadRepo(e db.Engine) (err error) {
// IsTimetrackerEnabled returns true if the repo enables timetracking
func (issue *Issue) IsTimetrackerEnabled() bool {
return issue.isTimetrackerEnabled(db.GetEngine(db.DefaultContext))
return issue.isTimetrackerEnabled(db.DefaultContext)
}
func (issue *Issue) isTimetrackerEnabled(e db.Engine) bool {
if err := issue.loadRepo(e); err != nil {
func (issue *Issue) isTimetrackerEnabled(ctx context.Context) bool {
if err := issue.loadRepo(ctx); err != nil {
log.Error(fmt.Sprintf("loadRepo: %v", err))
return false
}
@ -233,17 +233,18 @@ func (issue *Issue) loadCommentsByType(e db.Engine, tp CommentType) (err error)
return err
}
func (issue *Issue) loadReactions(e db.Engine) (err error) {
func (issue *Issue) loadReactions(ctx context.Context) (err error) {
if issue.Reactions != nil {
return nil
}
e := db.GetEngine(ctx)
reactions, err := findReactions(e, FindReactionsOptions{
IssueID: issue.ID,
})
if err != nil {
return err
}
if err = issue.loadRepo(e); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return err
}
// Load reaction user data
@ -279,7 +280,7 @@ func (issue *Issue) loadMilestone(e db.Engine) (err error) {
func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if err = issue.loadRepo(e); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return
}
@ -319,16 +320,16 @@ func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
return err
}
if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
if err = CommentList(issue.Comments).loadAttributes(ctx); err != nil {
return err
}
if issue.isTimetrackerEnabled(e) {
if issue.isTimetrackerEnabled(ctx) {
if err = issue.loadTotalTimes(e); err != nil {
return err
}
}
return issue.loadReactions(e)
return issue.loadReactions(ctx)
}
// LoadAttributes loads the attribute of this issue.
@ -478,13 +479,13 @@ func (issue *Issue) ClearLabels(doer *user_model.User) (err error) {
}
defer committer.Close()
if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
} else if err = issue.loadPullRequest(db.GetEngine(ctx)); err != nil {
return err
}
perm, err := getUserRepoPermission(db.GetEngine(ctx), issue.Repo, doer)
perm, err := getUserRepoPermission(ctx, issue.Repo, doer)
if err != nil {
return err
}
@ -526,7 +527,7 @@ func (issue *Issue) ReplaceLabels(labels []*Label, doer *user_model.User) (err e
}
defer committer.Close()
if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return err
}
@ -627,7 +628,7 @@ func (issue *Issue) changeStatus(ctx context.Context, doer *user_model.User, isC
func (issue *Issue) doChangeStatus(ctx context.Context, doer *user_model.User, isMergePull bool) (*Comment, error) {
e := db.GetEngine(ctx)
// Check for open dependencies
if issue.IsClosed && issue.Repo.isDependenciesEnabled(e) {
if issue.IsClosed && issue.Repo.IsDependenciesEnabledCtx(ctx) {
// only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
noDeps, err := issueNoDependenciesLeft(e, issue)
if err != nil {
@ -694,7 +695,7 @@ func (issue *Issue) ChangeStatus(doer *user_model.User, isClosed bool) (*Comment
}
defer committer.Close()
if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return nil, err
}
if err := issue.loadPoster(db.GetEngine(ctx)); err != nil {
@ -725,7 +726,7 @@ func (issue *Issue) ChangeTitle(doer *user_model.User, oldTitle string) (err err
return fmt.Errorf("updateIssueCols: %v", err)
}
if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return fmt.Errorf("loadRepo: %v", err)
}
@ -759,7 +760,7 @@ func (issue *Issue) ChangeRef(doer *user_model.User, oldRef string) (err error)
return fmt.Errorf("updateIssueCols: %v", err)
}
if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return fmt.Errorf("loadRepo: %v", err)
}
oldRefFriendly := strings.TrimPrefix(oldRef, git.BranchPrefix)
@ -781,7 +782,7 @@ func (issue *Issue) ChangeRef(doer *user_model.User, oldRef string) (err error)
}
// AddDeletePRBranchComment adds delete branch comment for pull request issue
func AddDeletePRBranchComment(doer *user_model.User, repo *Repository, issueID int64, branchName string) error {
func AddDeletePRBranchComment(doer *user_model.User, repo *repo_model.Repository, issueID int64, branchName string) error {
issue, err := getIssueByID(db.GetEngine(db.DefaultContext), issueID)
if err != nil {
return err
@ -918,7 +919,7 @@ func (issue *Issue) GetLastEventLabelFake() string {
// NewIssueOptions represents the options of a new issue.
type NewIssueOptions struct {
Repo *Repository
Repo *repo_model.Repository
Issue *Issue
LabelIDs []int64
Attachments []string // In UUID format.
@ -1005,7 +1006,7 @@ func newIssue(ctx context.Context, doer *user_model.User, opts NewIssueOptions)
}
}
if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
if err = newIssueUsers(ctx, opts.Repo, opts.Issue); err != nil {
return err
}
@ -1055,7 +1056,7 @@ func RecalculateIssueIndexForRepo(repoID int64) error {
}
// NewIssue creates new issue with labels for repository.
func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
func NewIssue(repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
idx, err := db.GetNextResourceIndex("issue_index", repo.ID)
if err != nil {
return fmt.Errorf("generate issue index failed: %v", err)
@ -1856,7 +1857,7 @@ func UpdateIssueByAPI(issue *Issue, doer *user_model.User) (statusChangeComment
defer committer.Close()
sess := db.GetEngine(ctx)
if err := issue.loadRepo(sess); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return nil, false, fmt.Errorf("loadRepo: %v", err)
}
@ -1930,8 +1931,8 @@ func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *us
// DependencyInfo represents high level information about an issue which is a dependency of another issue.
type DependencyInfo struct {
Issue `xorm:"extends"`
Repository `xorm:"extends"`
Issue `xorm:"extends"`
repo_model.Repository `xorm:"extends"`
}
// getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
@ -2040,14 +2041,14 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx context.Context, doer *user_
if len(mentions) == 0 {
return
}
if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return
}
resolved := make(map[string]bool, 10)
var mentionTeams []string
if err := issue.Repo.getOwner(db.GetEngine(ctx)); err != nil {
if err := issue.Repo.GetOwner(ctx); err != nil {
return nil, err
}
@ -2155,7 +2156,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx context.Context, doer *user_
continue
}
// Normal users must have read access to the referencing issue
perm, err := getUserRepoPermission(db.GetEngine(ctx), issue.Repo, user)
perm, err := getUserRepoPermission(ctx, issue.Repo, user)
if err != nil {
return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
}

@ -120,7 +120,7 @@ func (issue *Issue) toggleAssignee(ctx context.Context, doer *user_model.User, a
}
// Repo infos
if err = issue.loadRepo(sess); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return false, nil, fmt.Errorf("loadRepo: %v", err)
}

@ -219,9 +219,9 @@ type Comment struct {
RefAction references.XRefAction `xorm:"SMALLINT"` // What happens if RefIssueID resolves
RefIsPull bool
RefRepo *Repository `xorm:"-"`
RefIssue *Issue `xorm:"-"`
RefComment *Comment `xorm:"-"`
RefRepo *repo_model.Repository `xorm:"-"`
RefIssue *Issue `xorm:"-"`
RefComment *Comment `xorm:"-"`
Commits []*SignCommitWithStatuses `xorm:"-"`
OldCommit string `xorm:"-"`
@ -316,7 +316,7 @@ func (c *Comment) HTMLURL() string {
log.Error("LoadIssue(%d): %v", c.IssueID, err)
return ""
}
err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
err = c.Issue.loadRepo(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return ""
@ -345,7 +345,7 @@ func (c *Comment) APIURL() string {
log.Error("LoadIssue(%d): %v", c.IssueID, err)
return ""
}
err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
err = c.Issue.loadRepo(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return ""
@ -366,7 +366,7 @@ func (c *Comment) IssueURL() string {
return ""
}
err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
err = c.Issue.loadRepo(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return ""
@ -382,7 +382,7 @@ func (c *Comment) PRURL() string {
return ""
}
err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
err = c.Issue.loadRepo(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return ""
@ -536,7 +536,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error {
return err
}
if err = c.Issue.Repo.GetOwner(); err != nil {
if err = c.Issue.Repo.GetOwner(db.DefaultContext); err != nil {
return err
}
@ -589,7 +589,7 @@ func (c *Comment) LoadTime() error {
return err
}
func (c *Comment) loadReactions(e db.Engine, repo *Repository) (err error) {
func (c *Comment) loadReactions(e db.Engine, repo *repo_model.Repository) (err error) {
if c.Reactions != nil {
return nil
}
@ -608,7 +608,7 @@ func (c *Comment) loadReactions(e db.Engine, repo *Repository) (err error) {
}
// LoadReactions loads comment reactions
func (c *Comment) LoadReactions(repo *Repository) error {
func (c *Comment) LoadReactions(repo *repo_model.Repository) error {
return c.loadReactions(db.GetEngine(db.DefaultContext), repo)
}
@ -675,7 +675,7 @@ func (c *Comment) CodeCommentURL() string {
log.Error("LoadIssue(%d): %v", c.IssueID, err)
return ""
}
err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
err = c.Issue.loadRepo(db.DefaultContext)
if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return ""
@ -764,7 +764,7 @@ func createComment(ctx context.Context, opts *CreateCommentOptions) (_ *Comment,
return nil, err
}
if err = opts.Repo.getOwner(e); err != nil {
if err = opts.Repo.GetOwner(ctx); err != nil {
return nil, err
}
@ -843,7 +843,7 @@ func createDeadlineComment(ctx context.Context, doer *user_model.User, issue *Is
content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
}
if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return nil, err
}
@ -867,7 +867,7 @@ func createIssueDependencyComment(ctx context.Context, doer *user_model.User, is
if !add {
cType = CommentTypeRemoveDependency
}
if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return
}
@ -898,7 +898,7 @@ func createIssueDependencyComment(ctx context.Context, doer *user_model.User, is
type CreateCommentOptions struct {
Type CommentType
Doer *user_model.User
Repo *Repository
Repo *repo_model.Repository
Issue *Issue
Label *Label
@ -953,7 +953,7 @@ func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
}
// CreateRefComment creates a commit reference comment to issue.
func CreateRefComment(doer *user_model.User, repo *Repository, issue *Issue, content, commitSHA string) error {
func CreateRefComment(doer *user_model.User, repo *repo_model.Repository, issue *Issue, content, commitSHA string) error {
if len(commitSHA) == 0 {
return fmt.Errorf("cannot create reference with empty commit SHA")
}
@ -1144,11 +1144,11 @@ func deleteComment(e db.Engine, comment *Comment) error {
// CodeComments represents comments on code by using this structure: FILENAME -> LINE (+ == proposed; - == previous) -> COMMENTS
type CodeComments map[string]map[int64][]*Comment
func fetchCodeComments(e db.Engine, issue *Issue, currentUser *user_model.User) (CodeComments, error) {
return fetchCodeCommentsByReview(e, issue, currentUser, nil)
func fetchCodeComments(ctx context.Context, issue *Issue, currentUser *user_model.User) (CodeComments, error) {
return fetchCodeCommentsByReview(ctx, issue, currentUser, nil)
}
func fetchCodeCommentsByReview(e db.Engine, issue *Issue, currentUser *user_model.User, review *Review) (CodeComments, error) {
func fetchCodeCommentsByReview(ctx context.Context, issue *Issue, currentUser *user_model.User, review *Review) (CodeComments, error) {
pathToLineToComment := make(CodeComments)
if review == nil {
review = &Review{ID: 0}
@ -1159,7 +1159,7 @@ func fetchCodeCommentsByReview(e db.Engine, issue *Issue, currentUser *user_mode
ReviewID: review.ID,
}
comments, err := findCodeComments(e, opts, issue, currentUser, review)
comments, err := findCodeComments(ctx, opts, issue, currentUser, review)
if err != nil {
return nil, err
}
@ -1173,7 +1173,7 @@ func fetchCodeCommentsByReview(e db.Engine, issue *Issue, currentUser *user_mode
return pathToLineToComment, nil
}
func findCodeComments(e db.Engine, opts FindCommentsOptions, issue *Issue, currentUser *user_model.User, review *Review) ([]*Comment, error) {
func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issue, currentUser *user_model.User, review *Review) ([]*Comment, error) {
var comments []*Comment
if review == nil {
review = &Review{ID: 0}
@ -1182,6 +1182,7 @@ func findCodeComments(e db.Engine, opts FindCommentsOptions, issue *Issue, curre
if review.ID == 0 {
conds = conds.And(builder.Eq{"invalidated": false})
}
e := db.GetEngine(ctx)
if err := e.Where(conds).
Asc("comment.created_unix").
Asc("comment.id").
@ -1189,7 +1190,7 @@ func findCodeComments(e db.Engine, opts FindCommentsOptions, issue *Issue, curre
return nil, err
}
if err := issue.loadRepo(e); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return nil, err
}
@ -1249,12 +1250,12 @@ func FetchCodeCommentsByLine(issue *Issue, currentUser *user_model.User, treePat
TreePath: treePath,
Line: line,
}
return findCodeComments(db.GetEngine(db.DefaultContext), opts, issue, currentUser, nil)
return findCodeComments(db.DefaultContext, opts, issue, currentUser, nil)
}
// FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
func FetchCodeComments(issue *Issue, currentUser *user_model.User) (CodeComments, error) {
return fetchCodeComments(db.GetEngine(db.DefaultContext), issue, currentUser)
return fetchCodeComments(db.DefaultContext, issue, currentUser)
}
// UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id
@ -1313,7 +1314,7 @@ func CreatePushPullComment(pusher *user_model.User, pr *PullRequest, oldCommitID
// getCommitsFromRepo get commit IDs from repo in between oldCommitID and newCommitID
// isForcePush will be true if oldCommit isn't on the branch
// Commit on baseBranch will skip
func getCommitIDsFromRepo(repo *Repository, oldCommitID, newCommitID, baseBranch string) (commitIDs []string, isForcePush bool, err error) {
func getCommitIDsFromRepo(repo *repo_model.Repository, oldCommitID, newCommitID, baseBranch string) (commitIDs []string, isForcePush bool, err error) {
repoPath := repo.RepoPath()
gitRepo, err := git.OpenRepository(repoPath)
if err != nil {

@ -5,6 +5,8 @@
package models
import (
"context"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
@ -343,11 +345,12 @@ func (comments CommentList) getDependentIssueIDs() []int64 {
return keysInt64(ids)
}
func (comments CommentList) loadDependentIssues(e db.Engine) error {
func (comments CommentList) loadDependentIssues(ctx context.Context) error {
if len(comments) == 0 {
return nil
}
e := db.GetEngine(ctx)
issueIDs := comments.getDependentIssueIDs()
issues := make(map[int64]*Issue, len(issueIDs))
left := len(issueIDs)
@ -383,7 +386,7 @@ func (comments CommentList) loadDependentIssues(e db.Engine) error {
if comment.DependentIssue == nil {
comment.DependentIssue = issues[comment.DependentIssueID]
if comment.DependentIssue != nil {
if err := comment.DependentIssue.loadRepo(e); err != nil {
if err := comment.DependentIssue.loadRepo(ctx); err != nil {
return err
}
}
@ -487,7 +490,8 @@ func (comments CommentList) loadReviews(e db.Engine) error {
}
// loadAttributes loads all attributes
func (comments CommentList) loadAttributes(e db.Engine) (err error) {
func (comments CommentList) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if err = comments.loadPosters(e); err != nil {
return
}
@ -520,7 +524,7 @@ func (comments CommentList) loadAttributes(e db.Engine) (err error) {
return
}
if err = comments.loadDependentIssues(e); err != nil {
if err = comments.loadDependentIssues(ctx); err != nil {
return
}
@ -530,7 +534,7 @@ func (comments CommentList) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads attributes of the comments, except for attachments and
// comments
func (comments CommentList) LoadAttributes() error {
return comments.loadAttributes(db.GetEngine(db.DefaultContext))
return comments.loadAttributes(db.DefaultContext)
}
// LoadAttachments loads attachments

@ -8,6 +8,7 @@ import (
"testing"
"time"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -18,7 +19,7 @@ func TestCreateComment(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &Issue{}).(*Issue)
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
now := time.Now().Unix()

@ -6,10 +6,7 @@ package models
import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
)
@ -135,18 +132,3 @@ func issueNoDependenciesLeft(e db.Engine, issue *Issue) (bool, error) {
return !exists, err
}
// IsDependenciesEnabled returns if dependencies are enabled and returns the default setting if not set.
func (repo *Repository) IsDependenciesEnabled() bool {
return repo.isDependenciesEnabled(db.GetEngine(db.DefaultContext))
}
func (repo *Repository) isDependenciesEnabled(e db.Engine) bool {
var u *RepoUnit
var err error
if u, err = repo.getUnit(e, unit.TypeIssues); err != nil {
log.Trace("%s", err)
return setting.Service.DefaultEnableDependencies
}
return u.IssuesConfig().EnableDependencies
}

@ -675,7 +675,7 @@ func newIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_m
return err
}
if err = issue.loadRepo(e); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return
}
@ -707,7 +707,7 @@ func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error
defer committer.Close()
sess := db.GetEngine(ctx)
if err = issue.loadRepo(sess); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return err
}
@ -731,7 +731,7 @@ func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error
// newIssueLabels add labels to an issue. It will check if the labels are valid for the issue
func newIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) {
e := db.GetEngine(ctx)
if err = issue.loadRepo(e); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return err
}
for _, label := range labels {
@ -780,7 +780,7 @@ func deleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *use
return nil
}
if err = issue.loadRepo(e); err != nil {
if err = issue.loadRepo(ctx); err != nil {
return
}

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -49,7 +50,7 @@ func TestNewLabels(t *testing.T) {
for _, label := range labels {
unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID))
}
unittest.CheckConsistencyFor(t, &Label{}, &Repository{})
unittest.CheckConsistencyFor(t, &Label{}, &repo_model.Repository{})
}
func TestGetLabelByID(t *testing.T) {
@ -270,7 +271,7 @@ func TestUpdateLabel(t *testing.T) {
assert.EqualValues(t, label.Color, newLabel.Color)
assert.EqualValues(t, label.Name, newLabel.Name)
assert.EqualValues(t, label.Description, newLabel.Description)
unittest.CheckConsistencyFor(t, &Label{}, &Repository{})
unittest.CheckConsistencyFor(t, &Label{}, &repo_model.Repository{})
}
func TestDeleteLabel(t *testing.T) {
@ -283,7 +284,7 @@ func TestDeleteLabel(t *testing.T) {
unittest.AssertNotExistsBean(t, &Label{ID: label.ID})
assert.NoError(t, DeleteLabel(unittest.NonexistentID, unittest.NonexistentID))
unittest.CheckConsistencyFor(t, &Label{}, &Repository{})
unittest.CheckConsistencyFor(t, &Label{}, &repo_model.Repository{})
}
func TestHasIssueLabel(t *testing.T) {

@ -32,13 +32,13 @@ func (issues IssueList) getRepoIDs() []int64 {
return keysInt64(repoIDs)
}
func (issues IssueList) loadRepositories(e db.Engine) ([]*Repository, error) {
func (issues IssueList) loadRepositories(e db.Engine) ([]*repo_model.Repository, error) {
if len(issues) == 0 {
return nil, nil
}
repoIDs := issues.getRepoIDs()
repoMaps := make(map[int64]*Repository, len(repoIDs))
repoMaps := make(map[int64]*repo_model.Repository, len(repoIDs))
left := len(repoIDs)
for left > 0 {
limit := defaultMaxInSize
@ -65,7 +65,7 @@ func (issues IssueList) loadRepositories(e db.Engine) ([]*Repository, error) {
}
// LoadRepositories loads issues' all repositories
func (issues IssueList) LoadRepositories() ([]*Repository, error) {
func (issues IssueList) LoadRepositories() ([]*repo_model.Repository, error) {
return issues.loadRepositories(db.GetEngine(db.DefaultContext))
}

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -21,9 +22,9 @@ import (
// Milestone represents a milestone of repository.
type Milestone struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"`
Repo *Repository `xorm:"-"`
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"`
Repo *repo_model.Repository `xorm:"-"`
Name string
Content string `xorm:"TEXT"`
RenderedContent string `xorm:"-"`
@ -287,7 +288,7 @@ func changeMilestoneAssign(ctx context.Context, doer *user_model.User, issue *Is
}
if oldMilestoneID > 0 || issue.MilestoneID > 0 {
if err := issue.loadRepo(e); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}
@ -335,7 +336,7 @@ func DeleteMilestoneByRepoID(repoID, id int64) error {
return err
}
repo, err := GetRepositoryByID(m.RepoID)
repo, err := repo_model.GetRepositoryByID(m.RepoID)
if err != nil {
return err
}

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@ -34,7 +35,7 @@ func TestNewMilestone(t *testing.T) {
assert.NoError(t, NewMilestone(milestone))
unittest.AssertExistsAndLoadBean(t, milestone)
unittest.CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &Milestone{})
}
func TestGetMilestoneByRepoID(t *testing.T) {
@ -52,7 +53,7 @@ func TestGetMilestoneByRepoID(t *testing.T) {
func TestGetMilestonesByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64, state api.StateType) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
milestones, _, err := GetMilestones(GetMilestonesOption{
RepoID: repo.ID,
State: state,
@ -100,7 +101,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
func TestGetMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
test := func(sortType string, sortCond func(*Milestone) int) {
for _, page := range []int{0, 1} {
milestones, _, err := GetMilestones(GetMilestonesOption{
@ -174,7 +175,7 @@ func TestUpdateMilestone(t *testing.T) {
func TestCountRepoMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), repoID)
assert.NoError(t, err)
assert.EqualValues(t, repo.NumMilestones, count)
@ -191,7 +192,7 @@ func TestCountRepoMilestones(t *testing.T) {
func TestCountRepoClosedMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
count, err := CountRepoClosedMilestones(repoID)
assert.NoError(t, err)
assert.EqualValues(t, repo.NumClosedMilestones, count)
@ -211,11 +212,11 @@ func TestChangeMilestoneStatus(t *testing.T) {
assert.NoError(t, ChangeMilestoneStatus(milestone, true))
unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}, "is_closed=1")
unittest.CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &Milestone{})
assert.NoError(t, ChangeMilestoneStatus(milestone, false))
unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}, "is_closed=0")
unittest.CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &Milestone{})
}
func TestUpdateMilestoneCounters(t *testing.T) {
@ -261,7 +262,7 @@ func TestDeleteMilestoneByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, DeleteMilestoneByRepoID(1, 1))
unittest.AssertNotExistsBean(t, &Milestone{ID: 1})
unittest.CheckConsistencyFor(t, &Repository{ID: 1})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: 1})
assert.NoError(t, DeleteMilestoneByRepoID(unittest.NonexistentID, unittest.NonexistentID))
}
@ -280,7 +281,7 @@ func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) {
func TestCountMilestonesByRepoIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
milestonesCount := func(repoID int64) (int, int) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
return repo.NumOpenMilestones, repo.NumClosedMilestones
}
repo1OpenCount, repo1ClosedCount := milestonesCount(1)
@ -299,8 +300,8 @@ func TestCountMilestonesByRepoIDs(t *testing.T) {
func TestGetMilestonesByRepoIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository)
test := func(sortType string, sortCond func(*Milestone) int) {
for _, page := range []int{0, 1} {
openMilestones, err := GetMilestonesByRepoIDs([]int64{repo1.ID, repo2.ID}, page, false, sortType)
@ -355,7 +356,7 @@ func TestGetMilestonesStats(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
stats, err := GetMilestonesStatsByRepoCond(builder.And(builder.Eq{"repo_id": repoID}))
assert.NoError(t, err)
assert.EqualValues(t, repo.NumMilestones-repo.NumClosedMilestones, stats.OpenCount)
@ -370,8 +371,8 @@ func TestGetMilestonesStats(t *testing.T) {
assert.EqualValues(t, 0, stats.OpenCount)
assert.EqualValues(t, 0, stats.ClosedCount)
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository)
milestoneStats, err := GetMilestonesStatsByRepoCond(builder.In("repo_id", []int64{repo1.ID, repo2.ID}))
assert.NoError(t, err)

@ -9,6 +9,7 @@ import (
"fmt"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
@ -286,7 +287,7 @@ func (list ReactionList) getUserIDs() []int64 {
return keysInt64(userIDs)
}
func (list ReactionList) loadUsers(e db.Engine, repo *Repository) ([]*user_model.User, error) {
func (list ReactionList) loadUsers(e db.Engine, repo *repo_model.Repository) ([]*user_model.User, error) {
if len(list) == 0 {
return nil, nil
}
@ -313,7 +314,7 @@ func (list ReactionList) loadUsers(e db.Engine, repo *Repository) ([]*user_model
}
// LoadUsers loads reactions' all users
func (list ReactionList) LoadUsers(repo *Repository) ([]*user_model.User, error) {
func (list ReactionList) LoadUsers(repo *repo_model.Repository) ([]*user_model.User, error) {
return list.loadUsers(db.GetEngine(db.DefaultContext), repo)
}

@ -7,6 +7,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@ -95,7 +96,7 @@ func TestIssueReactionCount(t *testing.T) {
addReaction(t, user4, issue, nil, "heart")
addReaction(t, ghost, issue, nil, "-1")
err := issue.loadReactions(db.GetEngine(db.DefaultContext))
err := issue.loadReactions(db.DefaultContext)
assert.NoError(t, err)
assert.Len(t, issue.Reactions, 7)
@ -135,7 +136,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) {
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User)
issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)
repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: issue1.RepoID}).(*Repository)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue1.RepoID}).(*repo_model.Repository)
comment1 := unittest.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment)

@ -156,7 +156,7 @@ func FinishIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss
return err
}
if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}
@ -177,7 +177,7 @@ func FinishIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss
// CreateIssueStopwatch creates a stopwatch if not exist, otherwise return an error
func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Issue) error {
e := db.GetEngine(ctx)
if err := issue.loadRepo(e); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}
@ -207,7 +207,7 @@ func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss
return err
}
if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}
@ -248,11 +248,7 @@ func cancelStopwatch(ctx context.Context, user *user_model.User, issue *Issue) e
return err
}
if err := issue.loadRepo(e); err != nil {
return err
}
if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}

@ -12,6 +12,7 @@ import (
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -23,7 +24,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
testSuccess := func(issueID int64, labelIDs []int64) {
issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue)
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
labels := make([]*Label, len(labelIDs))
@ -354,7 +355,7 @@ func TestGetRepoIDsForIssuesOptions(t *testing.T) {
func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *Issue {
var newIssue Issue
t.Run(title, func(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
issue := Issue{
@ -398,7 +399,7 @@ func TestIssue_ResolveMentions(t *testing.T) {
testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) {
o := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: owner}).(*user_model.User)
r := unittest.AssertExistsAndLoadBean(t, &Repository{OwnerID: o.ID, LowerName: repo}).(*Repository)
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: o.ID, LowerName: repo}).(*repo_model.Repository)
issue := &Issue{RepoID: r.ID}
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer}).(*user_model.User)
resolved, err := issue.ResolveMentionsByVisibility(db.DefaultContext, d, mentions)

@ -5,6 +5,7 @@
package models
import (
"context"
"time"
"code.gitea.io/gitea/models/db"
@ -41,16 +42,17 @@ func (t *TrackedTime) AfterLoad() {
// LoadAttributes load Issue, User
func (t *TrackedTime) LoadAttributes() (err error) {
return t.loadAttributes(db.GetEngine(db.DefaultContext))
return t.loadAttributes(db.DefaultContext)
}
func (t *TrackedTime) loadAttributes(e db.Engine) (err error) {
func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if t.Issue == nil {
t.Issue, err = getIssueByID(e, t.IssueID)
if err != nil {
return
}
err = t.Issue.loadRepo(e)
err = t.Issue.loadRepo(ctx)
if err != nil {
return
}
@ -167,7 +169,7 @@ func AddTime(user *user_model.User, issue *Issue, amount int64, created time.Tim
return nil, err
}
if err := issue.loadRepo(sess); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return nil, err
}
@ -251,7 +253,7 @@ func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error {
return ErrNotExist{}
}
if err := issue.loadRepo(sess); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}
if _, err := createComment(ctx, &CreateCommentOptions{
@ -274,13 +276,12 @@ func DeleteTime(t *TrackedTime) error {
return err
}
defer committer.Close()
sess := db.GetEngine(ctx)
if err := t.loadAttributes(sess); err != nil {
if err := t.loadAttributes(ctx); err != nil {
return err
}
if err := deleteTime(sess, t); err != nil {
if err := deleteTime(db.GetEngine(ctx), t); err != nil {
return err
}

@ -9,6 +9,7 @@ import (
"fmt"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
)
// IssueUser represents an issue-user relation.
@ -24,8 +25,8 @@ func init() {
db.RegisterModel(new(IssueUser))
}
func newIssueUsers(e db.Engine, repo *Repository, issue *Issue) error {
assignees, err := repo.getAssignees(e)
func newIssueUsers(ctx context.Context, repo *repo_model.Repository, issue *Issue) error {
assignees, err := getRepoAssignees(ctx, repo)
if err != nil {
return fmt.Errorf("getAssignees: %v", err)
}
@ -50,10 +51,7 @@ func newIssueUsers(e db.Engine, repo *Repository, issue *Issue) error {
})
}
if _, err = e.Insert(issueUsers); err != nil {
return err
}
return nil
return db.Insert(ctx, issueUsers)
}
// UpdateIssueUserByRead updates issue-user relation for reading.

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@ -16,7 +17,7 @@ import (
func Test_newIssueUsers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
newIssue := &Issue{
RepoID: repo.ID,
PosterID: 4,
@ -28,7 +29,7 @@ func Test_newIssueUsers(t *testing.T) {
// artificially insert new issue
unittest.AssertSuccessfulInsert(t, newIssue)
assert.NoError(t, newIssueUsers(db.GetEngine(db.DefaultContext), repo, newIssue))
assert.NoError(t, newIssueUsers(db.DefaultContext, repo, newIssue))
// issue_user table should now have entries for new issue
unittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})

@ -9,6 +9,7 @@ import (
"fmt"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/references"
@ -79,7 +80,7 @@ func (issue *Issue) addCrossReferences(stdCtx context.Context, doer *user_model.
func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossReferencesContext, plaincontent, mdcontent string) error {
e := db.GetEngine(stdCtx)
xreflist, err := ctx.OrigIssue.getCrossReferences(e, ctx, plaincontent, mdcontent)
xreflist, err := ctx.OrigIssue.getCrossReferences(stdCtx, ctx, plaincontent, mdcontent)
if err != nil {
return err
}
@ -136,35 +137,34 @@ func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossRefe
return nil
}
func (issue *Issue) getCrossReferences(e db.Engine, ctx *crossReferencesContext, plaincontent, mdcontent string) ([]*crossReference, error) {
func (issue *Issue) getCrossReferences(stdCtx context.Context, ctx *crossReferencesContext, plaincontent, mdcontent string) ([]*crossReference, error) {
xreflist := make([]*crossReference, 0, 5)
var (
refRepo *Repository
refRepo *repo_model.Repository
refIssue *Issue
refAction references.XRefAction
err error
)
allrefs := append(references.FindAllIssueReferences(plaincontent), references.FindAllIssueReferencesMarkdown(mdcontent)...)
for _, ref := range allrefs {
if ref.Owner == "" && ref.Name == "" {
// Issues in the same repository
if err := ctx.OrigIssue.loadRepo(e); err != nil {
if err := ctx.OrigIssue.loadRepo(stdCtx); err != nil {
return nil, err
}
refRepo = ctx.OrigIssue.Repo
} else {
// Issues in other repositories
refRepo, err = getRepositoryByOwnerAndName(e, ref.Owner, ref.Name)
refRepo, err = repo_model.GetRepositoryByOwnerAndNameCtx(stdCtx, ref.Owner, ref.Name)
if err != nil {
if IsErrRepoNotExist(err) {
if repo_model.IsErrRepoNotExist(err) {
continue
}
return nil, err
}
}
if refIssue, refAction, err = ctx.OrigIssue.verifyReferencedIssue(e, ctx, refRepo, ref); err != nil {
if refIssue, refAction, err = ctx.OrigIssue.verifyReferencedIssue(stdCtx, ctx, refRepo, ref); err != nil {
return nil, err
}
if refIssue != nil {
@ -194,15 +194,16 @@ func (issue *Issue) updateCrossReferenceList(list []*crossReference, xref *cross
}
// verifyReferencedIssue will check if the referenced issue exists, and whether the doer has permission to do what
func (issue *Issue) verifyReferencedIssue(e db.Engine, ctx *crossReferencesContext, repo *Repository,
func (issue *Issue) verifyReferencedIssue(stdCtx context.Context, ctx *crossReferencesContext, repo *repo_model.Repository,
ref references.IssueReference) (*Issue, references.XRefAction, error) {
refIssue := &Issue{RepoID: repo.ID, Index: ref.Index}
refAction := ref.Action
e := db.GetEngine(stdCtx)
if has, _ := e.Get(refIssue); !has {
return nil, references.XRefActionNone, nil
}
if err := refIssue.loadRepo(e); err != nil {
if err := refIssue.loadRepo(stdCtx); err != nil {
return nil, references.XRefActionNone, err
}
@ -213,7 +214,7 @@ func (issue *Issue) verifyReferencedIssue(e db.Engine, ctx *crossReferencesConte
// Check doer permissions; set action to None if the doer can't change the destination
if refIssue.RepoID != ctx.OrigIssue.RepoID || ref.Action != references.XRefActionNone {
perm, err := getUserRepoPermission(e, refIssue.Repo, ctx.Doer)
perm, err := getUserRepoPermission(stdCtx, refIssue.Repo, ctx.Doer)
if err != nil {
return nil, references.XRefActionNone, err
}
@ -280,7 +281,7 @@ func (comment *Comment) LoadRefIssue() (err error) {
}
comment.RefIssue, err = GetIssueByID(comment.RefIssueID)
if err == nil {
err = comment.RefIssue.loadRepo(db.GetEngine(db.DefaultContext))
err = comment.RefIssue.loadRepo(db.DefaultContext)
}
return
}

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/references"
@ -126,7 +127,7 @@ func TestXRef_ResolveCrossReferences(t *testing.T) {
}
func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispull bool) *Issue {
r := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repo}).(*Repository)
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo}).(*repo_model.Repository)
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}).(*user_model.User)
idx, err := db.GetNextResourceIndex("issue_index", r.ID)
@ -157,7 +158,7 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu
}
func testCreatePR(t *testing.T, repo, doer int64, title, content string) *PullRequest {
r := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repo}).(*Repository)
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo}).(*repo_model.Repository)
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}).(*user_model.User)
i := &Issue{RepoID: r.ID, PosterID: d.ID, Poster: d, Title: title, Content: content, IsPull: true}
pr := &PullRequest{HeadRepoID: repo, BaseRepoID: repo, HeadBranch: "head", BaseBranch: "base", Status: PullRequestStatusMergeable}

@ -5,9 +5,11 @@
package models
import (
"context"
"errors"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/timeutil"
@ -71,12 +73,12 @@ func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) {
// GetLFSMetaObjectByOid selects a LFSMetaObject entry from database by its OID.
// It may return ErrLFSObjectNotExist or a database error. If the error is nil,
// the returned pointer is a valid LFSMetaObject.
func (repo *Repository) GetLFSMetaObjectByOid(oid string) (*LFSMetaObject, error) {
func GetLFSMetaObjectByOid(repoID int64, oid string) (*LFSMetaObject, error) {
if len(oid) == 0 {
return nil, ErrLFSObjectNotExist
}
m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repo.ID}
m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repoID}
has, err := db.GetEngine(db.DefaultContext).Get(m)
if err != nil {
return nil, err
@ -88,7 +90,7 @@ func (repo *Repository) GetLFSMetaObjectByOid(oid string) (*LFSMetaObject, error
// RemoveLFSMetaObjectByOid removes a LFSMetaObject entry from database by its OID.
// It may return ErrLFSObjectNotExist or a database error.
func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) {
func RemoveLFSMetaObjectByOid(repoID int64, oid string) (int64, error) {
if len(oid) == 0 {
return 0, ErrLFSObjectNotExist
}
@ -99,7 +101,7 @@ func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) {
}
defer committer.Close()
m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repo.ID}
m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repoID}
if _, err := db.DeleteByBean(ctx, m); err != nil {
return -1, err
}
@ -113,7 +115,7 @@ func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) {
}
// GetLFSMetaObjects returns all LFSMetaObjects associated with a repository
func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject, error) {
func GetLFSMetaObjects(repoID int64, page, pageSize int) ([]*LFSMetaObject, error) {
sess := db.GetEngine(db.DefaultContext)
if page >= 0 && pageSize > 0 {
@ -124,12 +126,12 @@ func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject,
sess.Limit(pageSize, start)
}
lfsObjects := make([]*LFSMetaObject, 0, pageSize)
return lfsObjects, sess.Find(&lfsObjects, &LFSMetaObject{RepositoryID: repo.ID})
return lfsObjects, sess.Find(&lfsObjects, &LFSMetaObject{RepositoryID: repoID})
}
// CountLFSMetaObjects returns a count of all LFSMetaObjects associated with a repository
func (repo *Repository) CountLFSMetaObjects() (int64, error) {
return db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{RepositoryID: repo.ID})
func CountLFSMetaObjects(repoID int64) (int64, error) {
return db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{RepositoryID: repoID})
}
// LFSObjectAccessible checks if a provided Oid is accessible to the user
@ -202,3 +204,21 @@ func IterateLFS(f func(mo *LFSMetaObject) error) error {
}
}
}
// CopyLFS copies LFS data from one repo to another
func CopyLFS(ctx context.Context, newRepo, oldRepo *repo_model.Repository) error {
var lfsObjects []*LFSMetaObject
if err := db.GetEngine(ctx).Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
return err
}
for _, v := range lfsObjects {
v.ID = 0
v.RepositoryID = newRepo.ID
if _, err := db.GetEngine(ctx).Insert(v); err != nil {
return err
}
}
return nil
}

@ -12,21 +12,19 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"xorm.io/xorm"
"code.gitea.io/gitea/modules/setting"
)
// LFSLock represents a git lfs lock of repository.
type LFSLock struct {
ID int64 `xorm:"pk autoincr"`
Repo *Repository `xorm:"-"`
RepoID int64 `xorm:"INDEX NOT NULL"`
OwnerID int64 `xorm:"INDEX NOT NULL"`
Path string `xorm:"TEXT"`
Created time.Time `xorm:"created"`
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX NOT NULL"`
OwnerID int64 `xorm:"INDEX NOT NULL"`
Path string `xorm:"TEXT"`
Created time.Time `xorm:"created"`
}
func init() {
@ -35,33 +33,24 @@ func init() {
// BeforeInsert is invoked from XORM before inserting an object of this type.
func (l *LFSLock) BeforeInsert() {
l.RepoID = l.Repo.ID
l.Path = cleanPath(l.Path)
}
// AfterLoad is invoked from XORM after setting the values of all fields of this object.
func (l *LFSLock) AfterLoad(session *xorm.Session) {
var err error
l.Repo, err = getRepositoryByID(session, l.RepoID)
if err != nil {
log.Error("LFS lock AfterLoad failed RepoId[%d] not found: %v", l.RepoID, err)
}
}
func cleanPath(p string) string {
return path.Clean("/" + p)[1:]
}
// CreateLFSLock creates a new lock.
func CreateLFSLock(lock *LFSLock) (*LFSLock, error) {
err := CheckLFSAccessForRepo(lock.OwnerID, lock.Repo, perm.AccessModeWrite)
func CreateLFSLock(repo *repo_model.Repository, lock *LFSLock) (*LFSLock, error) {
err := CheckLFSAccessForRepo(lock.OwnerID, repo, perm.AccessModeWrite)
if err != nil {
return nil, err
}
lock.Path = cleanPath(lock.Path)
lock.RepoID = repo.ID
l, err := GetLFSLock(lock.Repo, lock.Path)
l, err := GetLFSLock(repo, lock.Path)
if err == nil {
return l, ErrLFSLockAlreadyExist{lock.RepoID, lock.Path}
}
@ -69,12 +58,12 @@ func CreateLFSLock(lock *LFSLock) (*LFSLock, error) {
return nil, err
}
_, err = db.GetEngine(db.DefaultContext).InsertOne(lock)
err = db.Insert(db.DefaultContext, lock)
return lock, err
}
// GetLFSLock returns release by given path.
func GetLFSLock(repo *Repository, path string) (*LFSLock, error) {
func GetLFSLock(repo *repo_model.Repository, path string) (*LFSLock, error) {
path = cleanPath(path)
rel := &LFSLock{RepoID: repo.ID}
has, err := db.GetEngine(db.DefaultContext).Where("lower(path) = ?", strings.ToLower(path)).Get(rel)
@ -113,19 +102,37 @@ func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) {
return lfsLocks, e.Find(&lfsLocks, &LFSLock{RepoID: repoID})
}
// GetTreePathLock returns LSF lock for the treePath
func GetTreePathLock(repoID int64, treePath string) (*LFSLock, error) {
if !setting.LFS.StartServer {
return nil, nil
}
locks, err := GetLFSLockByRepoID(repoID, 0, 0)
if err != nil {
return nil, err
}
for _, lock := range locks {
if lock.Path == treePath {
return lock, nil
}
}
return nil, nil
}
// CountLFSLockByRepoID returns a count of all LFSLocks associated with a repository.
func CountLFSLockByRepoID(repoID int64) (int64, error) {
return db.GetEngine(db.DefaultContext).Count(&LFSLock{RepoID: repoID})
}
// DeleteLFSLockByID deletes a lock by given ID.
func DeleteLFSLockByID(id int64, u *user_model.User, force bool) (*LFSLock, error) {
func DeleteLFSLockByID(id int64, repo *repo_model.Repository, u *user_model.User, force bool) (*LFSLock, error) {
lock, err := GetLFSLockByID(id)
if err != nil {
return nil, err
}
err = CheckLFSAccessForRepo(u.ID, lock.Repo, perm.AccessModeWrite)
err = CheckLFSAccessForRepo(u.ID, repo, perm.AccessModeWrite)
if err != nil {
return nil, err
}
@ -139,7 +146,7 @@ func DeleteLFSLockByID(id int64, u *user_model.User, force bool) (*LFSLock, erro
}
// CheckLFSAccessForRepo check needed access mode base on action
func CheckLFSAccessForRepo(ownerID int64, repo *Repository, mode perm.AccessMode) error {
func CheckLFSAccessForRepo(ownerID int64, repo *repo_model.Repository, mode perm.AccessMode) error {
if ownerID == 0 {
return ErrLFSUnauthorizedAction{repo.ID, "undefined", mode}
}

@ -7,6 +7,7 @@ package models
import (
"testing"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -18,7 +19,7 @@ func TestFixturesAreConsistent(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.CheckConsistencyFor(t,
&user_model.User{},
&Repository{},
&repo_model.Repository{},
&Issue{},
&PullRequest{},
&Milestone{},

@ -11,6 +11,7 @@ import (
"strconv"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
@ -63,10 +64,10 @@ type Notification struct {
UpdatedBy int64 `xorm:"INDEX NOT NULL"`
Issue *Issue `xorm:"-"`
Repository *Repository `xorm:"-"`
Comment *Comment `xorm:"-"`
User *user_model.User `xorm:"-"`
Issue *Issue `xorm:"-"`
Repository *repo_model.Repository `xorm:"-"`
Comment *Comment `xorm:"-"`
User *user_model.User `xorm:"-"`
CreatedUnix timeutil.TimeStamp `xorm:"created INDEX NOT NULL"`
UpdatedUnix timeutil.TimeStamp `xorm:"updated INDEX NOT NULL"`
@ -140,7 +141,7 @@ func CountNotifications(opts *FindNotificationOptions) (int64, error) {
}
// CreateRepoTransferNotification creates notification for the user a repository was transferred to
func CreateRepoTransferNotification(doer, newOwner *user_model.User, repo *Repository) error {
func CreateRepoTransferNotification(doer, newOwner *user_model.User, repo *repo_model.Repository) error {
ctx, committer, err := db.TxContext()
if err != nil {
return err
@ -190,14 +191,15 @@ func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID,
}
defer committer.Close()
if err := createOrUpdateIssueNotifications(db.GetEngine(ctx), issueID, commentID, notificationAuthorID, receiverID); err != nil {
if err := createOrUpdateIssueNotifications(ctx, issueID, commentID, notificationAuthorID, receiverID); err != nil {
return err
}
return committer.Commit()
}
func createOrUpdateIssueNotifications(e db.Engine, issueID, commentID, notificationAuthorID, receiverID int64) error {
func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, notificationAuthorID, receiverID int64) error {
e := db.GetEngine(ctx)
// init
var toNotify map[int64]struct{}
notifications, err := getNotificationsByIssueID(e, issueID)
@ -251,7 +253,7 @@ func createOrUpdateIssueNotifications(e db.Engine, issueID, commentID, notificat
}
}
err = issue.loadRepo(e)
err = issue.loadRepo(ctx)
if err != nil {
return err
}
@ -267,10 +269,10 @@ func createOrUpdateIssueNotifications(e db.Engine, issueID, commentID, notificat
return err
}
if issue.IsPull && !issue.Repo.checkUnitUser(e, user, unit.TypePullRequests) {
if issue.IsPull && !checkRepoUnitUser(ctx, issue.Repo, user, unit.TypePullRequests) {
continue
}
if !issue.IsPull && !issue.Repo.checkUnitUser(e, user, unit.TypeIssues) {
if !issue.IsPull && !checkRepoUnitUser(ctx, issue.Repo, user, unit.TypeIssues) {
continue
}
@ -399,7 +401,7 @@ func (n *Notification) LoadAttributes() (err error) {
func (n *Notification) loadAttributes(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
if err = n.loadRepo(e); err != nil {
if err = n.loadRepo(ctx); err != nil {
return
}
if err = n.loadIssue(ctx); err != nil {
@ -414,9 +416,9 @@ func (n *Notification) loadAttributes(ctx context.Context) (err error) {
return
}
func (n *Notification) loadRepo(e db.Engine) (err error) {
func (n *Notification) loadRepo(ctx context.Context) (err error) {
if n.Repository == nil {
n.Repository, err = getRepositoryByID(e, n.RepoID)
n.Repository, err = repo_model.GetRepositoryByIDCtx(ctx, n.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %v", n.RepoID, err)
}
@ -462,8 +464,8 @@ func (n *Notification) loadUser(e db.Engine) (err error) {
}
// GetRepo returns the repo of the notification
func (n *Notification) GetRepo() (*Repository, error) {
return n.Repository, n.loadRepo(db.GetEngine(db.DefaultContext))
func (n *Notification) GetRepo() (*repo_model.Repository, error) {
return n.Repository, n.loadRepo(db.DefaultContext)
}
// GetIssue returns the issue of the notification
@ -526,7 +528,7 @@ func (nl NotificationList) LoadRepos() (RepositoryList, []int, error) {
}
repoIDs := nl.getPendingRepoIDs()
repos := make(map[int64]*Repository, len(repoIDs))
repos := make(map[int64]*repo_model.Repository, len(repoIDs))
left := len(repoIDs)
for left > 0 {
limit := defaultMaxInSize
@ -535,13 +537,13 @@ func (nl NotificationList) LoadRepos() (RepositoryList, []int, error) {
}
rows, err := db.GetEngine(db.DefaultContext).
In("id", repoIDs[:limit]).
Rows(new(Repository))
Rows(new(repo_model.Repository))
if err != nil {
return nil, nil, err
}
for rows.Next() {
var repo Repository
var repo repo_model.Repository
err = rows.Scan(&repo)
if err != nil {
rows.Close()

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
@ -904,8 +905,8 @@ func (org *Organization) GetUserTeams(userID int64) ([]*Team, error) {
type AccessibleReposEnvironment interface {
CountRepos() (int64, error)
RepoIDs(page, pageSize int) ([]int64, error)
Repos(page, pageSize int) ([]*Repository, error)
MirrorRepos() ([]*Repository, error)
Repos(page, pageSize int) ([]*repo_model.Repository, error)
MirrorRepos() ([]*repo_model.Repository, error)
AddKeyword(keyword string)
SetSort(db.SearchOrderBy)
}
@ -987,7 +988,7 @@ func (env *accessibleReposEnv) CountRepos() (int64, error) {
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
Where(env.cond()).
Distinct("`repository`.id").
Count(&Repository{})
Count(&repo_model.Repository{})
if err != nil {
return 0, fmt.Errorf("count user repositories in organization: %v", err)
}
@ -1011,13 +1012,13 @@ func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) {
Find(&repoIDs)
}
func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*Repository, error) {
func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*repo_model.Repository, error) {
repoIDs, err := env.RepoIDs(page, pageSize)
if err != nil {
return nil, fmt.Errorf("GetUserRepositoryIDs: %v", err)
}
repos := make([]*Repository, 0, len(repoIDs))
repos := make([]*repo_model.Repository, 0, len(repoIDs))
if len(repoIDs) == 0 {
return repos, nil
}
@ -1040,13 +1041,13 @@ func (env *accessibleReposEnv) MirrorRepoIDs() ([]int64, error) {
Find(&repoIDs)
}
func (env *accessibleReposEnv) MirrorRepos() ([]*Repository, error) {
func (env *accessibleReposEnv) MirrorRepos() ([]*repo_model.Repository, error) {
repoIDs, err := env.MirrorRepoIDs()
if err != nil {
return nil, fmt.Errorf("MirrorRepoIDs: %v", err)
}
repos := make([]*Repository, 0, len(repoIDs))
repos := make([]*repo_model.Repository, 0, len(repoIDs))
if len(repoIDs) == 0 {
return repos, nil
}

@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
@ -32,8 +33,8 @@ type Team struct {
Name string
Description string
Authorize perm.AccessMode
Repos []*Repository `xorm:"-"`
Members []*user_model.User `xorm:"-"`
Repos []*repo_model.Repository `xorm:"-"`
Members []*user_model.User `xorm:"-"`
NumRepos int
NumMembers int
Units []*TeamUnit `xorm:"-"`
@ -215,7 +216,8 @@ func (t *Team) HasRepository(repoID int64) bool {
return t.hasRepository(db.GetEngine(db.DefaultContext), repoID)
}
func (t *Team) addRepository(e db.Engine, repo *Repository) (err error) {
func (t *Team) addRepository(ctx context.Context, repo *repo_model.Repository) (err error) {
e := db.GetEngine(ctx)
if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
return err
}
@ -226,7 +228,7 @@ func (t *Team) addRepository(e db.Engine, repo *Repository) (err error) {
t.NumRepos++
if err = repo.recalculateTeamAccesses(e, 0); err != nil {
if err = recalculateTeamAccesses(ctx, repo, 0); err != nil {
return fmt.Errorf("recalculateAccesses: %v", err)
}
@ -247,15 +249,16 @@ func (t *Team) addRepository(e db.Engine, repo *Repository) (err error) {
// addAllRepositories adds all repositories to the team.
// If the team already has some repositories they will be left unchanged.
func (t *Team) addAllRepositories(e db.Engine) error {
var orgRepos []Repository
func (t *Team) addAllRepositories(ctx context.Context) error {
var orgRepos []repo_model.Repository
e := db.GetEngine(ctx)
if err := e.Where("owner_id = ?", t.OrgID).Find(&orgRepos); err != nil {
return fmt.Errorf("get org repos: %v", err)
}
for _, repo := range orgRepos {
if !t.hasRepository(e, repo.ID) {
if err := t.addRepository(e, &repo); err != nil {
if err := t.addRepository(ctx, &repo); err != nil {
return fmt.Errorf("addRepository: %v", err)
}
}
@ -272,7 +275,7 @@ func (t *Team) AddAllRepositories() (err error) {
}
defer committer.Close()
if err = t.addAllRepositories(db.GetEngine(ctx)); err != nil {
if err = t.addAllRepositories(ctx); err != nil {
return err
}
@ -280,7 +283,7 @@ func (t *Team) AddAllRepositories() (err error) {
}
// AddRepository adds new repository to team of organization.
func (t *Team) AddRepository(repo *Repository) (err error) {
func (t *Team) AddRepository(repo *repo_model.Repository) (err error) {
if repo.OwnerID != t.OrgID {
return errors.New("Repository does not belong to organization")
} else if t.HasRepository(repo.ID) {
@ -293,7 +296,7 @@ func (t *Team) AddRepository(repo *Repository) (err error) {
}
defer committer.Close()
if err = t.addRepository(db.GetEngine(ctx), repo); err != nil {
if err = t.addRepository(ctx, repo); err != nil {
return err
}
@ -312,7 +315,7 @@ func (t *Team) RemoveAllRepositories() (err error) {
}
defer committer.Close()
if err = t.removeAllRepositories(db.GetEngine(ctx)); err != nil {
if err = t.removeAllRepositories(ctx); err != nil {
return err
}
@ -321,16 +324,17 @@ func (t *Team) RemoveAllRepositories() (err error) {
// removeAllRepositories removes all repositories from team and recalculates access
// Note: Shall not be called if team includes all repositories
func (t *Team) removeAllRepositories(e db.Engine) (err error) {
func (t *Team) removeAllRepositories(ctx context.Context) (err error) {
e := db.GetEngine(ctx)
// Delete all accesses.
for _, repo := range t.Repos {
if err := repo.recalculateTeamAccesses(e, t.ID); err != nil {
if err := recalculateTeamAccesses(ctx, repo, t.ID); err != nil {
return err
}
// Remove watches from all users and now unaccessible repos
for _, user := range t.Members {
has, err := hasAccess(e, user.ID, repo)
has, err := hasAccess(ctx, user.ID, repo)
if err != nil {
return err
} else if has {
@ -365,7 +369,8 @@ func (t *Team) removeAllRepositories(e db.Engine) (err error) {
// removeRepository removes a repository from a team and recalculates access
// Note: Repository shall not be removed from team if it includes all repositories (unless the repository is deleted)
func (t *Team) removeRepository(e db.Engine, repo *Repository, recalculate bool) (err error) {
func (t *Team) removeRepository(ctx context.Context, repo *repo_model.Repository, recalculate bool) (err error) {
e := db.GetEngine(ctx)
if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
return err
}
@ -377,7 +382,7 @@ func (t *Team) removeRepository(e db.Engine, repo *Repository, recalculate bool)
// Don't need to recalculate when delete a repository from organization.
if recalculate {
if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
if err = recalculateTeamAccesses(ctx, repo, t.ID); err != nil {
return err
}
}
@ -387,7 +392,7 @@ func (t *Team) removeRepository(e db.Engine, repo *Repository, recalculate bool)
return fmt.Errorf("getTeamUsersByTeamID: %v", err)
}
for _, teamUser := range teamUsers {
has, err := hasAccess(e, teamUser.UID, repo)
has, err := hasAccess(ctx, teamUser.UID, repo)
if err != nil {
return err
} else if has {
@ -418,7 +423,7 @@ func (t *Team) RemoveRepository(repoID int64) error {
return nil
}
repo, err := GetRepositoryByID(repoID)
repo, err := repo_model.GetRepositoryByID(repoID)
if err != nil {
return err
}
@ -429,7 +434,7 @@ func (t *Team) RemoveRepository(repoID int64) error {
}
defer committer.Close()
if err = t.removeRepository(db.GetEngine(ctx), repo, true); err != nil {
if err = t.removeRepository(ctx, repo, true); err != nil {
return err
}
@ -517,7 +522,7 @@ func NewTeam(t *Team) (err error) {
// Add all repositories to the team if it has access to all of them.
if t.IncludesAllRepositories {
err = t.addAllRepositories(db.GetEngine(ctx))
err = t.addAllRepositories(ctx)
if err != nil {
return fmt.Errorf("addAllRepositories: %v", err)
}
@ -660,7 +665,7 @@ func UpdateTeam(t *Team, authChanged, includeAllChanged bool) (err error) {
}
for _, repo := range t.Repos {
if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
if err = recalculateTeamAccesses(ctx, repo, 0); err != nil {
return fmt.Errorf("recalculateTeamAccesses: %v", err)
}
}
@ -668,7 +673,7 @@ func UpdateTeam(t *Team, authChanged, includeAllChanged bool) (err error) {
// Add all repositories to the team if it has access to all of them.
if includeAllChanged && t.IncludesAllRepositories {
err = t.addAllRepositories(sess)
err = t.addAllRepositories(ctx)
if err != nil {
return fmt.Errorf("addAllRepositories: %v", err)
}
@ -695,7 +700,7 @@ func DeleteTeam(t *Team) error {
return err
}
if err := t.removeAllRepositories(sess); err != nil {
if err := t.removeAllRepositories(ctx); err != nil {
return err
}
@ -848,7 +853,7 @@ func AddTeamMember(team *Team, userID int64) error {
// Give access to team repositories.
for _, repo := range team.Repos {
if err := repo.recalculateUserAccess(sess, userID); err != nil {
if err := recalculateUserAccess(ctx, repo, userID); err != nil {
return err
}
if setting.Service.AutoWatchNewRepos {
@ -894,17 +899,17 @@ func removeTeamMember(ctx context.Context, team *Team, userID int64) error {
// Delete access to team repositories.
for _, repo := range team.Repos {
if err := repo.recalculateUserAccess(e, userID); err != nil {
if err := recalculateUserAccess(ctx, repo, userID); err != nil {
return err
}
// Remove watches from now unaccessible
if err := repo.reconsiderWatches(e, userID); err != nil {
if err := reconsiderWatches(ctx, repo, userID); err != nil {
return err
}
// Remove issue assignments from now unaccessible
if err := repo.reconsiderIssueAssignees(e, userID); err != nil {
if err := reconsiderRepoIssuesAssignee(ctx, repo, userID); err != nil {
return err
}
}

@ -10,6 +10,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -124,18 +125,18 @@ func TestTeam_AddRepository(t *testing.T) {
testSuccess := func(teamID, repoID int64) {
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team)
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository)
assert.NoError(t, team.AddRepository(repo))
unittest.AssertExistsAndLoadBean(t, &TeamRepo{TeamID: teamID, RepoID: repoID})
unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &Repository{ID: repoID})
unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &repo_model.Repository{ID: repoID})
}
testSuccess(2, 3)
testSuccess(2, 5)
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team)
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
assert.Error(t, team.AddRepository(repo))
unittest.CheckConsistencyFor(t, &Team{ID: 1}, &Repository{ID: 1})
unittest.CheckConsistencyFor(t, &Team{ID: 1}, &repo_model.Repository{ID: 1})
}
func TestTeam_RemoveRepository(t *testing.T) {
@ -145,7 +146,7 @@ func TestTeam_RemoveRepository(t *testing.T) {
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team)
assert.NoError(t, team.RemoveRepository(repoID))
unittest.AssertNotExistsBean(t, &TeamRepo{TeamID: teamID, RepoID: repoID})
unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &Repository{ID: repoID})
unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &repo_model.Repository{ID: repoID})
}
testSuccess(2, 3)
testSuccess(2, 5)
@ -247,7 +248,7 @@ func TestDeleteTeam(t *testing.T) {
// check that team members don't have "leftover" access to repos
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository)
accessMode, err := AccessLevel(user, repo)
assert.NoError(t, err)
assert.True(t, accessMode < perm.AccessModeWrite)

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@ -160,13 +161,13 @@ func TestUser_RemoveMember(t *testing.T) {
func TestUser_RemoveOrgRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization)
repo := unittest.AssertExistsAndLoadBean(t, &Repository{OwnerID: org.ID}).(*Repository)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: org.ID}).(*repo_model.Repository)
// remove a repo that does belong to org
unittest.AssertExistsAndLoadBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID})
assert.NoError(t, org.RemoveOrgRepo(repo.ID))
unittest.AssertNotExistsBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID})
unittest.AssertExistsAndLoadBean(t, &Repository{ID: repo.ID}) // repo should still exist
unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) // repo should still exist
// remove a repo that does not belong to org
assert.NoError(t, org.RemoveOrgRepo(repo.ID))
@ -177,7 +178,7 @@ func TestUser_RemoveOrgRepo(t *testing.T) {
unittest.CheckConsistencyFor(t,
&user_model.User{ID: org.ID},
&Team{OrgID: org.ID},
&Repository{ID: repo.ID})
&repo_model.Repository{ID: repo.ID})
}
func TestCreateOrganization(t *testing.T) {
@ -541,10 +542,10 @@ func TestAccessibleReposEnv_Repos(t *testing.T) {
assert.NoError(t, err)
repos, err := env.Repos(1, 100)
assert.NoError(t, err)
expectedRepos := make([]*Repository, len(expectedRepoIDs))
expectedRepos := make([]*repo_model.Repository, len(expectedRepoIDs))
for i, repoID := range expectedRepoIDs {
expectedRepos[i] = unittest.AssertExistsAndLoadBean(t,
&Repository{ID: repoID}).(*Repository)
&repo_model.Repository{ID: repoID}).(*repo_model.Repository)
}
assert.Equal(t, expectedRepos, repos)
}
@ -560,10 +561,10 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) {
assert.NoError(t, err)
repos, err := env.MirrorRepos()
assert.NoError(t, err)
expectedRepos := make([]*Repository, len(expectedRepoIDs))
expectedRepos := make([]*repo_model.Repository, len(expectedRepoIDs))
for i, repoID := range expectedRepoIDs {
expectedRepos[i] = unittest.AssertExistsAndLoadBean(t,
&Repository{ID: repoID}).(*Repository)
&repo_model.Repository{ID: repoID}).(*repo_model.Repository)
}
assert.Equal(t, expectedRepos, repos)
}

@ -154,7 +154,7 @@ func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.U
return err
}
if err := issue.loadRepo(e); err != nil {
if err := issue.loadRepo(ctx); err != nil {
return err
}

@ -33,6 +33,28 @@ func init() {
db.RegisterModel(new(ProtectedTag))
}
// EnsureCompiledPattern ensures the glob pattern is compiled
func (pt *ProtectedTag) EnsureCompiledPattern() error {
if pt.RegexPattern != nil || pt.GlobPattern != nil {
return nil
}
var err error
if len(pt.NamePattern) >= 2 && strings.HasPrefix(pt.NamePattern, "/") && strings.HasSuffix(pt.NamePattern, "/") {
pt.RegexPattern, err = regexp.Compile(pt.NamePattern[1 : len(pt.NamePattern)-1])
} else {
pt.GlobPattern, err = glob.Compile(pt.NamePattern)
}
return err
}
func (pt *ProtectedTag) matchString(name string) bool {
if pt.RegexPattern != nil {
return pt.RegexPattern.MatchString(name)
}
return pt.GlobPattern.Match(name)
}
// InsertProtectedTag inserts a protected tag to database
func InsertProtectedTag(pt *ProtectedTag) error {
_, err := db.GetEngine(db.DefaultContext).Insert(pt)
@ -51,23 +73,8 @@ func DeleteProtectedTag(pt *ProtectedTag) error {
return err
}
// EnsureCompiledPattern ensures the glob pattern is compiled
func (pt *ProtectedTag) EnsureCompiledPattern() error {
if pt.RegexPattern != nil || pt.GlobPattern != nil {
return nil
}
var err error
if len(pt.NamePattern) >= 2 && strings.HasPrefix(pt.NamePattern, "/") && strings.HasSuffix(pt.NamePattern, "/") {
pt.RegexPattern, err = regexp.Compile(pt.NamePattern[1 : len(pt.NamePattern)-1])
} else {
pt.GlobPattern, err = glob.Compile(pt.NamePattern)
}
return err
}
// IsUserAllowed returns true if the user is allowed to modify the tag
func (pt *ProtectedTag) IsUserAllowed(userID int64) (bool, error) {
// IsUserAllowedModifyTag returns true if the user is allowed to modify the tag
func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) {
if base.Int64sContains(pt.AllowlistUserIDs, userID) {
return true, nil
}
@ -84,9 +91,9 @@ func (pt *ProtectedTag) IsUserAllowed(userID int64) (bool, error) {
}
// GetProtectedTags gets all protected tags of the repository
func (repo *Repository) GetProtectedTags() ([]*ProtectedTag, error) {
func GetProtectedTags(repoID int64) ([]*ProtectedTag, error) {
tags := make([]*ProtectedTag, 0)
return tags, db.GetEngine(db.DefaultContext).Find(&tags, &ProtectedTag{RepoID: repo.ID})
return tags, db.GetEngine(db.DefaultContext).Find(&tags, &ProtectedTag{RepoID: repoID})
}
// GetProtectedTagByID gets the protected tag with the specific id
@ -116,7 +123,7 @@ func IsUserAllowedToControlTag(tags []*ProtectedTag, tagName string, userID int6
continue
}
isAllowed, err = tag.IsUserAllowed(userID)
isAllowed, err = IsUserAllowedModifyTag(tag, userID)
if err != nil {
return false, err
}
@ -127,10 +134,3 @@ func IsUserAllowedToControlTag(tags []*ProtectedTag, tagName string, userID int6
return isAllowed, nil
}
func (pt *ProtectedTag) matchString(name string) bool {
if pt.RegexPattern != nil {
return pt.RegexPattern.MatchString(name)
}
return pt.GlobPattern.Match(name)
}

@ -16,29 +16,29 @@ func TestIsUserAllowed(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pt := &ProtectedTag{}
allowed, err := pt.IsUserAllowed(1)
allowed, err := IsUserAllowedModifyTag(pt, 1)
assert.NoError(t, err)
assert.False(t, allowed)
pt = &ProtectedTag{
AllowlistUserIDs: []int64{1},
}
allowed, err = pt.IsUserAllowed(1)
allowed, err = IsUserAllowedModifyTag(pt, 1)
assert.NoError(t, err)
assert.True(t, allowed)
allowed, err = pt.IsUserAllowed(2)
allowed, err = IsUserAllowedModifyTag(pt, 2)
assert.NoError(t, err)
assert.False(t, allowed)
pt = &ProtectedTag{
AllowlistTeamIDs: []int64{1},
}
allowed, err = pt.IsUserAllowed(1)
allowed, err = IsUserAllowedModifyTag(pt, 1)
assert.NoError(t, err)
assert.False(t, allowed)
allowed, err = pt.IsUserAllowed(2)
allowed, err = IsUserAllowedModifyTag(pt, 2)
assert.NoError(t, err)
assert.True(t, allowed)
@ -46,11 +46,11 @@ func TestIsUserAllowed(t *testing.T) {
AllowlistUserIDs: []int64{1},
AllowlistTeamIDs: []int64{1},
}
allowed, err = pt.IsUserAllowed(1)
allowed, err = IsUserAllowedModifyTag(pt, 1)
assert.NoError(t, err)
assert.True(t, allowed)
allowed, err = pt.IsUserAllowed(2)
allowed, err = IsUserAllowedModifyTag(pt, 2)
assert.NoError(t, err)
assert.True(t, allowed)
}

@ -6,11 +6,13 @@
package models
import (
"context"
"fmt"
"io"
"strings"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
@ -67,10 +69,10 @@ type PullRequest struct {
Issue *Issue `xorm:"-"`
Index int64
HeadRepoID int64 `xorm:"INDEX"`
HeadRepo *Repository `xorm:"-"`
BaseRepoID int64 `xorm:"INDEX"`
BaseRepo *Repository `xorm:"-"`
HeadRepoID int64 `xorm:"INDEX"`
HeadRepo *repo_model.Repository `xorm:"-"`
BaseRepoID int64 `xorm:"INDEX"`
BaseRepo *repo_model.Repository `xorm:"-"`
HeadBranch string
HeadCommitID string `xorm:"-"`
BaseBranch string
@ -95,7 +97,7 @@ func init() {
// MustHeadUserName returns the HeadRepo's username if failed return blank
func (pr *PullRequest) MustHeadUserName() string {
if err := pr.LoadHeadRepo(); err != nil {
if !IsErrRepoNotExist(err) {
if !repo_model.IsErrRepoNotExist(err) {
log.Error("LoadHeadRepo: %v", err)
} else {
log.Warn("LoadHeadRepo %d but repository does not exist: %v", pr.HeadRepoID, err)
@ -128,7 +130,7 @@ func (pr *PullRequest) LoadAttributes() error {
return pr.loadAttributes(db.GetEngine(db.DefaultContext))
}
func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) {
func (pr *PullRequest) loadHeadRepo(ctx context.Context) (err error) {
if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
if pr.HeadRepoID == pr.BaseRepoID {
if pr.BaseRepo != nil {
@ -140,8 +142,8 @@ func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) {
}
}
pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
if err != nil && !IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
pr.HeadRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.HeadRepoID)
if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
return fmt.Errorf("getRepositoryByID(head): %v", err)
}
pr.isHeadRepoLoaded = true
@ -151,15 +153,15 @@ func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) {
// LoadHeadRepo loads the head repository
func (pr *PullRequest) LoadHeadRepo() error {
return pr.loadHeadRepo(db.GetEngine(db.DefaultContext))
return pr.loadHeadRepo(db.DefaultContext)
}
// LoadBaseRepo loads the target repository
func (pr *PullRequest) LoadBaseRepo() error {
return pr.loadBaseRepo(db.GetEngine(db.DefaultContext))
return pr.loadBaseRepo(db.DefaultContext)
}
func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) {
func (pr *PullRequest) loadBaseRepo(ctx context.Context) (err error) {
if pr.BaseRepo != nil {
return nil
}
@ -174,9 +176,9 @@ func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) {
return nil
}
pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID)
if err != nil {
return fmt.Errorf("GetRepositoryByID(base): %v", err)
return fmt.Errorf("repo_model.GetRepositoryByID(base): %v", err)
}
return nil
}
@ -200,21 +202,21 @@ func (pr *PullRequest) loadIssue(e db.Engine) (err error) {
// LoadProtectedBranch loads the protected branch of the base branch
func (pr *PullRequest) LoadProtectedBranch() (err error) {
return pr.loadProtectedBranch(db.GetEngine(db.DefaultContext))
return pr.loadProtectedBranch(db.DefaultContext)
}
func (pr *PullRequest) loadProtectedBranch(e db.Engine) (err error) {
func (pr *PullRequest) loadProtectedBranch(ctx context.Context) (err error) {
if pr.ProtectedBranch == nil {
if pr.BaseRepo == nil {
if pr.BaseRepoID == 0 {
return nil
}
pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID)
if err != nil {
return
}
}
pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
pr.ProtectedBranch, err = getProtectedBranchBy(db.GetEngine(ctx), pr.BaseRepo.ID, pr.BaseBranch)
}
return
}
@ -223,7 +225,7 @@ func (pr *PullRequest) loadProtectedBranch(e db.Engine) (err error) {
func (pr *PullRequest) GetDefaultMergeMessage() string {
if pr.HeadRepo == nil {
var err error
pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
pr.HeadRepo, err = repo_model.GetRepositoryByID(pr.HeadRepoID)
if err != nil {
log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
return ""
@ -368,24 +370,6 @@ func (pr *PullRequest) IsEmpty() bool {
return pr.Status == PullRequestStatusEmpty
}
// MergeStyle represents the approach to merge commits into base branch.
type MergeStyle string
const (
// MergeStyleMerge create merge commit
MergeStyleMerge MergeStyle = "merge"
// MergeStyleRebase rebase before merging
MergeStyleRebase MergeStyle = "rebase"
// MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
MergeStyleRebaseMerge MergeStyle = "rebase-merge"
// MergeStyleSquash squash commits into single commit before merging
MergeStyleSquash MergeStyle = "squash"
// MergeStyleManuallyMerged pr has been merged manually, just mark it as merged directly
MergeStyleManuallyMerged MergeStyle = "manually-merged"
// MergeStyleRebaseUpdate not a merge style, used to update pull head by rebase
MergeStyleRebaseUpdate MergeStyle = "rebase-update-only"
)
// SetMerged sets a pull request to merged and closes the corresponding issue
func (pr *PullRequest) SetMerged() (bool, error) {
if pr.HasMerged {
@ -428,11 +412,11 @@ func (pr *PullRequest) SetMerged() (bool, error) {
return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
}
if err := pr.Issue.loadRepo(sess); err != nil {
if err := pr.Issue.loadRepo(ctx); err != nil {
return false, err
}
if err := pr.Issue.Repo.getOwner(sess); err != nil {
if err := pr.Issue.Repo.GetOwner(ctx); err != nil {
return false, err
}
@ -452,7 +436,7 @@ func (pr *PullRequest) SetMerged() (bool, error) {
}
// NewPullRequest creates new pull request with labels for repository.
func NewPullRequest(repo *Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
func NewPullRequest(repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
idx, err := db.GetNextResourceIndex("issue_index", repo.ID)
if err != nil {
return fmt.Errorf("generate pull request index failed: %v", err)

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -258,15 +259,15 @@ func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) {
func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
externalTracker := RepoUnit{
externalTracker := repo_model.RepoUnit{
Type: unit.TypeExternalTracker,
Config: &ExternalTrackerConfig{
Config: &repo_model.ExternalTrackerConfig{
ExternalTrackerFormat: "https://someurl.com/{user}/{repo}/{issue}",
},
}
baseRepo := &Repository{Name: "testRepo", ID: 1}
baseRepo := &repo_model.Repository{Name: "testRepo", ID: 1}
baseRepo.Owner = &user_model.User{Name: "testOwner"}
baseRepo.Units = []*RepoUnit{&externalTracker}
baseRepo.Units = []*repo_model.RepoUnit{&externalTracker}
pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2, BaseRepo: baseRepo}).(*PullRequest)

@ -25,12 +25,12 @@ import (
// Release represents a release of repository.
type Release struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX UNIQUE(n)"`
Repo *Repository `xorm:"-"`
PublisherID int64 `xorm:"INDEX"`
Publisher *user_model.User `xorm:"-"`
TagName string `xorm:"INDEX UNIQUE(n)"`
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX UNIQUE(n)"`
Repo *repo_model.Repository `xorm:"-"`
PublisherID int64 `xorm:"INDEX"`
Publisher *user_model.User `xorm:"-"`
TagName string `xorm:"INDEX UNIQUE(n)"`
OriginalAuthor string
OriginalAuthorID int64 `xorm:"index"`
LowerTagName string
@ -55,7 +55,7 @@ func init() {
func (r *Release) loadAttributes(e db.Engine) error {
var err error
if r.Repo == nil {
r.Repo, err = GetRepositoryByID(r.RepoID)
r.Repo, err = repo_model.GetRepositoryByID(r.RepoID)
if err != nil {
return err
}

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