diff options
Diffstat (limited to 'services')
29 files changed, 253 insertions, 177 deletions
diff --git a/services/auth/basic.go b/services/auth/basic.go index 1869662e92..9b32ad29af 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -9,7 +9,7 @@ import ( "net/http" "strings" - "code.gitea.io/gitea/models" + auth_model "code.gitea.io/gitea/models/auth" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/log" @@ -85,7 +85,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore return u } - token, err := models.GetAccessTokenBySHA(authToken) + token, err := auth_model.GetAccessTokenBySHA(authToken) if err == nil { log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid) u, err := user_model.GetUserByID(token.UID) @@ -95,13 +95,13 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } token.UpdatedUnix = timeutil.TimeStampNow() - if err = models.UpdateAccessToken(token); err != nil { + if err = auth_model.UpdateAccessToken(token); err != nil { log.Error("UpdateAccessToken: %v", err) } store.GetData()["IsApiToken"] = true return u - } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) { + } else if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) { log.Error("GetAccessTokenBySha: %v", err) } diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index 68638a0806..8f038d6104 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -10,8 +10,7 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/auth" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" @@ -37,8 +36,8 @@ func CheckOAuthAccessToken(accessToken string) int64 { log.Trace("oauth2.ParseToken: %v", err) return 0 } - var grant *auth.OAuth2Grant - if grant, err = auth.GetOAuth2GrantByID(db.DefaultContext, token.GrantID); err != nil || grant == nil { + var grant *auth_model.OAuth2Grant + if grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, token.GrantID); err != nil || grant == nil { return 0 } if token.Type != oauth2.TypeAccessToken { @@ -91,15 +90,15 @@ func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { } return uid } - t, err := models.GetAccessTokenBySHA(tokenSHA) + t, err := auth_model.GetAccessTokenBySHA(tokenSHA) if err != nil { - if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) { + if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) { log.Error("GetAccessTokenBySHA: %v", err) } return 0 } t.UpdatedUnix = timeutil.TimeStampNow() - if err = models.UpdateAccessToken(t); err != nil { + if err = auth_model.UpdateAccessToken(t); err != nil { log.Error("UpdateAccessToken: %v", err) } store.GetData()["IsApiToken"] = true diff --git a/services/cron/tasks_extended.go b/services/cron/tasks_extended.go index 41bd5c4420..c3455ec327 100644 --- a/services/cron/tasks_extended.go +++ b/services/cron/tasks_extended.go @@ -8,7 +8,7 @@ import ( "context" "time" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/admin" asymkey_model "code.gitea.io/gitea/models/asymkey" "code.gitea.io/gitea/models/db" @@ -134,7 +134,7 @@ func registerDeleteOldActions() { OlderThan: 365 * 24 * time.Hour, }, func(ctx context.Context, _ *user_model.User, config Config) error { olderThanConfig := config.(*OlderThanConfig) - return models.DeleteOldActions(olderThanConfig.OlderThan) + return activities_model.DeleteOldActions(olderThanConfig.OlderThan) }) } diff --git a/services/issue/commit.go b/services/issue/commit.go index 1053a81162..0d04de81bc 100644 --- a/services/issue/commit.go +++ b/services/issue/commit.go @@ -13,12 +13,12 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" access_model "code.gitea.io/gitea/models/perm/access" 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" "code.gitea.io/gitea/modules/repository" ) @@ -119,8 +119,13 @@ func UpdateIssuesCommit(doer *user_model.User, repo *repo_model.Repository, comm // issue is from another repo if len(ref.Owner) > 0 && len(ref.Name) > 0 { - refRepo, err = models.GetRepositoryFromMatch(ref.Owner, ref.Name) + refRepo, err = repo_model.GetRepositoryByOwnerAndName(ref.Owner, ref.Name) if err != nil { + if repo_model.IsErrRepoNotExist(err) { + log.Warn("Repository referenced in commit but does not exist: %v", err) + } else { + log.Error("repo_model.GetRepositoryByOwnerAndName: %v", err) + } continue } } else { diff --git a/services/issue/commit_test.go b/services/issue/commit_test.go index f9ad0302ff..8469bf1ac1 100644 --- a/services/issue/commit_test.go +++ b/services/issue/commit_test.go @@ -7,7 +7,7 @@ package issue import ( "testing" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -64,7 +64,7 @@ func TestUpdateIssuesCommit(t *testing.T) { assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) // Test that push to a non-default branch closes no issue. pushCommits = []*repository.PushCommit{ @@ -91,7 +91,7 @@ func TestUpdateIssuesCommit(t *testing.T) { assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, "non-existing-branch")) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) pushCommits = []*repository.PushCommit{ { @@ -117,7 +117,7 @@ func TestUpdateIssuesCommit(t *testing.T) { assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_Colon(t *testing.T) { @@ -142,7 +142,7 @@ func TestUpdateIssuesCommit_Colon(t *testing.T) { unittest.AssertNotExistsBean(t, &issues_model.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1") assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_Issue5957(t *testing.T) { @@ -176,7 +176,7 @@ func TestUpdateIssuesCommit_Issue5957(t *testing.T) { assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, "non-existing-branch")) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { @@ -211,7 +211,7 @@ func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { @@ -246,7 +246,7 @@ func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { @@ -297,5 +297,5 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, commentBean2) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") - unittest.CheckConsistencyFor(t, &models.Action{}) + unittest.CheckConsistencyFor(t, &activities_model.Action{}) } diff --git a/services/issue/issue.go b/services/issue/issue.go index 7131829b03..bbd0278792 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -7,7 +7,7 @@ package issue import ( "fmt" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" admin_model "code.gitea.io/gitea/models/admin" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" @@ -224,7 +224,7 @@ func deleteIssue(issue *issues_model.Issue) error { return err } - if err := models.DeleteIssueActions(ctx, issue.RepoID, issue.ID); err != nil { + if err := activities_model.DeleteIssueActions(ctx, issue.RepoID, issue.ID); err != nil { return err } @@ -245,7 +245,7 @@ func deleteIssue(issue *issues_model.Issue) error { &issues_model.IssueDependency{}, &issues_model.IssueAssignees{}, &issues_model.IssueUser{}, - &models.Notification{}, + &activities_model.Notification{}, &issues_model.Reaction{}, &issues_model.IssueWatch{}, &issues_model.Stopwatch{}, diff --git a/services/mailer/mail.go b/services/mailer/mail.go index 738a207ce8..a5bfa496f9 100644 --- a/services/mailer/mail.go +++ b/services/mailer/mail.go @@ -17,7 +17,7 @@ import ( texttmpl "text/template" "time" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -302,7 +302,7 @@ func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipient // Make sure to compose independent messages to avoid leaking user emails msgID := createReference(ctx.Issue, ctx.Comment, ctx.ActionType) - reference := createReference(ctx.Issue, nil, models.ActionType(0)) + reference := createReference(ctx.Issue, nil, activities_model.ActionType(0)) msgs := make([]*Message, 0, len(recipients)) for _, recipient := range recipients { @@ -323,7 +323,7 @@ func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipient return msgs, nil } -func createReference(issue *issues_model.Issue, comment *issues_model.Comment, actionType models.ActionType) string { +func createReference(issue *issues_model.Issue, comment *issues_model.Comment, actionType activities_model.ActionType) string { var path string if issue.IsPull { path = "pulls" @@ -336,13 +336,13 @@ func createReference(issue *issues_model.Issue, comment *issues_model.Comment, a extra = fmt.Sprintf("/comment/%d", comment.ID) } else { switch actionType { - case models.ActionCloseIssue, models.ActionClosePullRequest: + case activities_model.ActionCloseIssue, activities_model.ActionClosePullRequest: extra = fmt.Sprintf("/close/%d", time.Now().UnixNano()/1e6) - case models.ActionReopenIssue, models.ActionReopenPullRequest: + case activities_model.ActionReopenIssue, activities_model.ActionReopenPullRequest: extra = fmt.Sprintf("/reopen/%d", time.Now().UnixNano()/1e6) - case models.ActionMergePullRequest: + case activities_model.ActionMergePullRequest: extra = fmt.Sprintf("/merge/%d", time.Now().UnixNano()/1e6) - case models.ActionPullRequestReadyForReview: + case activities_model.ActionPullRequestReadyForReview: extra = fmt.Sprintf("/ready/%d", time.Now().UnixNano()/1e6) } } @@ -420,7 +420,7 @@ func SendIssueAssignedMail(issue *issues_model.Issue, doer *user_model.User, con Context: context.TODO(), // TODO: use a correct context Issue: issue, Doer: doer, - ActionType: models.ActionType(0), + ActionType: activities_model.ActionType(0), Content: content, Comment: comment, }, lang, tos, false, "issue assigned") @@ -433,8 +433,8 @@ func SendIssueAssignedMail(issue *issues_model.Issue, doer *user_model.User, con } // actionToTemplate returns the type and name of the action facing the user -// (slightly different from models.ActionType) and the name of the template to use (based on availability) -func actionToTemplate(issue *issues_model.Issue, actionType models.ActionType, +// (slightly different from activities_model.ActionType) and the name of the template to use (based on availability) +func actionToTemplate(issue *issues_model.Issue, actionType activities_model.ActionType, commentType issues_model.CommentType, reviewType issues_model.ReviewType, ) (typeName, name, template string) { if issue.IsPull { @@ -443,19 +443,19 @@ func actionToTemplate(issue *issues_model.Issue, actionType models.ActionType, typeName = "issue" } switch actionType { - case models.ActionCreateIssue, models.ActionCreatePullRequest: + case activities_model.ActionCreateIssue, activities_model.ActionCreatePullRequest: name = "new" - case models.ActionCommentIssue, models.ActionCommentPull: + case activities_model.ActionCommentIssue, activities_model.ActionCommentPull: name = "comment" - case models.ActionCloseIssue, models.ActionClosePullRequest: + case activities_model.ActionCloseIssue, activities_model.ActionClosePullRequest: name = "close" - case models.ActionReopenIssue, models.ActionReopenPullRequest: + case activities_model.ActionReopenIssue, activities_model.ActionReopenPullRequest: name = "reopen" - case models.ActionMergePullRequest: + case activities_model.ActionMergePullRequest: name = "merge" - case models.ActionPullReviewDismissed: + case activities_model.ActionPullReviewDismissed: name = "review_dismissed" - case models.ActionPullRequestReadyForReview: + case activities_model.ActionPullRequestReadyForReview: name = "ready_for_review" default: switch commentType { diff --git a/services/mailer/mail_comment.go b/services/mailer/mail_comment.go index 95d11ae8a1..2dab673b4e 100644 --- a/services/mailer/mail_comment.go +++ b/services/mailer/mail_comment.go @@ -7,7 +7,7 @@ package mailer import ( "context" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" issues_model "code.gitea.io/gitea/models/issues" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" @@ -15,7 +15,7 @@ import ( ) // MailParticipantsComment sends new comment emails to repository watchers and mentioned people. -func MailParticipantsComment(ctx context.Context, c *issues_model.Comment, opType models.ActionType, issue *issues_model.Issue, mentions []*user_model.User) error { +func MailParticipantsComment(ctx context.Context, c *issues_model.Comment, opType activities_model.ActionType, issue *issues_model.Issue, mentions []*user_model.User) error { if setting.MailService == nil { // No mail service configured return nil @@ -53,7 +53,7 @@ func MailMentionsComment(ctx context.Context, pr *issues_model.PullRequest, c *i Context: ctx, Issue: pr.Issue, Doer: c.Poster, - ActionType: models.ActionCommentPull, + ActionType: activities_model.ActionCommentPull, Content: c.Content, Comment: c, }, mentions, visited, true); err != nil { diff --git a/services/mailer/mail_issue.go b/services/mailer/mail_issue.go index b4827e83a7..ec6ddcf14e 100644 --- a/services/mailer/mail_issue.go +++ b/services/mailer/mail_issue.go @@ -8,8 +8,9 @@ import ( "context" "fmt" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" issues_model "code.gitea.io/gitea/models/issues" + access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" @@ -25,7 +26,7 @@ type mailCommentContext struct { context.Context Issue *issues_model.Issue Doer *user_model.User - ActionType models.ActionType + ActionType activities_model.ActionType Content string Comment *issues_model.Comment } @@ -80,7 +81,7 @@ func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []*user_mo // =========== Repo watchers =========== // Make repo watchers last, since it's likely the list with the most users - if !(ctx.Issue.IsPull && ctx.Issue.PullRequest.IsWorkInProgress() && ctx.ActionType != models.ActionCreatePullRequest) { + if !(ctx.Issue.IsPull && ctx.Issue.PullRequest.IsWorkInProgress() && ctx.ActionType != activities_model.ActionCreatePullRequest) { ids, err = repo_model.GetRepoWatchersIDs(ctx, ctx.Issue.RepoID) if err != nil { return fmt.Errorf("GetRepoWatchersIDs(%d): %v", ctx.Issue.RepoID, err) @@ -149,7 +150,7 @@ func mailIssueCommentBatch(ctx *mailCommentContext, users []*user_model.User, vi visited[user.ID] = true // test if this user is allowed to see the issue/pull - if !models.CheckRepoUnitUser(ctx, ctx.Issue.Repo, user, checkUnit) { + if !access_model.CheckRepoUnitUser(ctx, ctx.Issue.Repo, user, checkUnit) { continue } @@ -175,16 +176,16 @@ func mailIssueCommentBatch(ctx *mailCommentContext, users []*user_model.User, vi // MailParticipants sends new issue thread created emails to repository watchers // and mentioned people. -func MailParticipants(issue *issues_model.Issue, doer *user_model.User, opType models.ActionType, mentions []*user_model.User) error { +func MailParticipants(issue *issues_model.Issue, doer *user_model.User, opType activities_model.ActionType, mentions []*user_model.User) error { if setting.MailService == nil { // No mail service configured return nil } content := issue.Content - if opType == models.ActionCloseIssue || opType == models.ActionClosePullRequest || - opType == models.ActionReopenIssue || opType == models.ActionReopenPullRequest || - opType == models.ActionMergePullRequest { + if opType == activities_model.ActionCloseIssue || opType == activities_model.ActionClosePullRequest || + opType == activities_model.ActionReopenIssue || opType == activities_model.ActionReopenPullRequest || + opType == activities_model.ActionMergePullRequest { content = "" } if err := mailIssueCommentToParticipants( diff --git a/services/mailer/mail_release.go b/services/mailer/mail_release.go index dd9f78612c..7c44f93929 100644 --- a/services/mailer/mail_release.go +++ b/services/mailer/mail_release.go @@ -8,7 +8,6 @@ import ( "bytes" "context" - "code.gitea.io/gitea/models" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" @@ -25,7 +24,7 @@ const ( ) // MailNewRelease send new release notify to all all repo watchers. -func MailNewRelease(ctx context.Context, rel *models.Release) { +func MailNewRelease(ctx context.Context, rel *repo_model.Release) { if setting.MailService == nil { // No mail service configured return @@ -55,7 +54,7 @@ func MailNewRelease(ctx context.Context, rel *models.Release) { } } -func mailNewRelease(ctx context.Context, lang string, tos []string, rel *models.Release) { +func mailNewRelease(ctx context.Context, lang string, tos []string, rel *repo_model.Release) { locale := translation.NewLocale(lang) var err error diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index 4302b2c74b..acb1f69961 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -13,7 +13,7 @@ import ( "testing" texttmpl "text/template" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -73,7 +73,7 @@ func TestComposeIssueCommentMessage(t *testing.T) { recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}} msgs, err := composeIssueCommentMessages(&mailCommentContext{ Context: context.TODO(), // TODO: use a correct context - Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, + Issue: issue, Doer: doer, ActionType: activities_model.ActionCommentIssue, Content: "test body", Comment: comment, }, "en-US", recipients, false, "issue comment") assert.NoError(t, err) @@ -102,7 +102,7 @@ func TestComposeIssueMessage(t *testing.T) { recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}} msgs, err := composeIssueCommentMessages(&mailCommentContext{ Context: context.TODO(), // TODO: use a correct context - Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, + Issue: issue, Doer: doer, ActionType: activities_model.ActionCreateIssue, Content: "test body", }, "en-US", recipients, false, "issue create") assert.NoError(t, err) @@ -147,14 +147,14 @@ func TestTemplateSelection(t *testing.T) { msg := testComposeIssueCommentMessage(t, &mailCommentContext{ Context: context.TODO(), // TODO: use a correct context - Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, + Issue: issue, Doer: doer, ActionType: activities_model.ActionCreateIssue, Content: "test body", }, recipients, false, "TestTemplateSelection") expect(t, msg, "issue/new/subject", "issue/new/body") msg = testComposeIssueCommentMessage(t, &mailCommentContext{ Context: context.TODO(), // TODO: use a correct context - Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, + Issue: issue, Doer: doer, ActionType: activities_model.ActionCommentIssue, Content: "test body", Comment: comment, }, recipients, false, "TestTemplateSelection") expect(t, msg, "issue/default/subject", "issue/default/body") @@ -163,14 +163,14 @@ func TestTemplateSelection(t *testing.T) { comment = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 4, Issue: pull}) msg = testComposeIssueCommentMessage(t, &mailCommentContext{ Context: context.TODO(), // TODO: use a correct context - Issue: pull, Doer: doer, ActionType: models.ActionCommentPull, + Issue: pull, Doer: doer, ActionType: activities_model.ActionCommentPull, Content: "test body", Comment: comment, }, recipients, false, "TestTemplateSelection") expect(t, msg, "pull/comment/subject", "pull/comment/body") msg = testComposeIssueCommentMessage(t, &mailCommentContext{ Context: context.TODO(), // TODO: use a correct context - Issue: issue, Doer: doer, ActionType: models.ActionCloseIssue, + Issue: issue, Doer: doer, ActionType: activities_model.ActionCloseIssue, Content: "test body", Comment: comment, }, recipients, false, "TestTemplateSelection") expect(t, msg, "Re: [user2/repo1] issue1 (#1)", "issue/close/body") @@ -181,7 +181,7 @@ func TestTemplateServices(t *testing.T) { assert.NoError(t, issue.LoadRepo(db.DefaultContext)) expect := func(t *testing.T, issue *issues_model.Issue, comment *issues_model.Comment, doer *user_model.User, - actionType models.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string, + actionType activities_model.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string, ) { subjectTemplates = texttmpl.Must(texttmpl.New("issue/default").Parse(tplSubject)) bodyTemplates = template.Must(template.New("issue/default").Parse(tplBody)) @@ -202,19 +202,19 @@ func TestTemplateServices(t *testing.T) { assert.Contains(t, wholemsg, "\r\n"+expBody+"\r\n") } - expect(t, issue, comment, doer, models.ActionCommentIssue, false, + expect(t, issue, comment, doer, activities_model.ActionCommentIssue, false, "{{.SubjectPrefix}}[{{.Repo}}]: @{{.Doer.Name}} commented on #{{.Issue.Index}} - {{.Issue.Title}}", "//{{.ActionType}},{{.ActionName}},{{if .IsMention}}norender{{end}}//", "Re: [user2/repo1]: @user2 commented on #1 - issue1", "//issue,comment,//") - expect(t, issue, comment, doer, models.ActionCommentIssue, true, + expect(t, issue, comment, doer, activities_model.ActionCommentIssue, true, "{{if .IsMention}}must render{{end}}", "//subject is: {{.Subject}}//", "must render", "//subject is: must render//") - expect(t, issue, comment, doer, models.ActionCommentIssue, true, + expect(t, issue, comment, doer, activities_model.ActionCommentIssue, true, "{{.FallbackSubject}}", "//{{.SubjectPrefix}}//", "Re: [user2/repo1] issue1 (#1)", @@ -266,7 +266,7 @@ func Test_createReference(t *testing.T) { type args struct { issue *issues_model.Issue comment *issues_model.Comment - actionType models.ActionType + actionType activities_model.ActionType } tests := []struct { name string @@ -278,7 +278,7 @@ func Test_createReference(t *testing.T) { name: "Open Issue", args: args{ issue: issue, - actionType: models.ActionCreateIssue, + actionType: activities_model.ActionCreateIssue, }, prefix: fmt.Sprintf("%s/issues/%d@%s", issue.Repo.FullName(), issue.Index, setting.Domain), }, @@ -286,7 +286,7 @@ func Test_createReference(t *testing.T) { name: "Open Pull", args: args{ issue: pullIssue, - actionType: models.ActionCreatePullRequest, + actionType: activities_model.ActionCreatePullRequest, }, prefix: fmt.Sprintf("%s/pulls/%d@%s", issue.Repo.FullName(), issue.Index, setting.Domain), }, @@ -295,7 +295,7 @@ func Test_createReference(t *testing.T) { args: args{ issue: issue, comment: comment, - actionType: models.ActionCommentIssue, + actionType: activities_model.ActionCommentIssue, }, prefix: fmt.Sprintf("%s/issues/%d/comment/%d@%s", issue.Repo.FullName(), issue.Index, comment.ID, setting.Domain), }, @@ -304,7 +304,7 @@ func Test_createReference(t *testing.T) { args: args{ issue: pullIssue, comment: comment, - actionType: models.ActionCommentPull, + actionType: activities_model.ActionCommentPull, }, prefix: fmt.Sprintf("%s/pulls/%d/comment/%d@%s", issue.Repo.FullName(), issue.Index, comment.ID, setting.Domain), }, @@ -312,7 +312,7 @@ func Test_createReference(t *testing.T) { name: "Close Issue", args: args{ issue: issue, - actionType: models.ActionCloseIssue, + actionType: activities_model.ActionCloseIssue, }, prefix: fmt.Sprintf("%s/issues/%d/close/", issue.Repo.FullName(), issue.Index), }, @@ -320,7 +320,7 @@ func Test_createReference(t *testing.T) { name: "Close Pull", args: args{ issue: pullIssue, - actionType: models.ActionClosePullRequest, + actionType: activities_model.ActionClosePullRequest, }, prefix: fmt.Sprintf("%s/pulls/%d/close/", issue.Repo.FullName(), issue.Index), }, @@ -328,7 +328,7 @@ func Test_createReference(t *testing.T) { name: "Reopen Issue", args: args{ issue: issue, - actionType: models.ActionReopenIssue, + actionType: activities_model.ActionReopenIssue, }, prefix: fmt.Sprintf("%s/issues/%d/reopen/", issue.Repo.FullName(), issue.Index), }, @@ -336,7 +336,7 @@ func Test_createReference(t *testing.T) { name: "Reopen Pull", args: args{ issue: pullIssue, - actionType: models.ActionReopenPullRequest, + actionType: activities_model.ActionReopenPullRequest, }, prefix: fmt.Sprintf("%s/pulls/%d/reopen/", issue.Repo.FullName(), issue.Index), }, @@ -344,7 +344,7 @@ func Test_createReference(t *testing.T) { name: "Merge Pull", args: args{ issue: pullIssue, - actionType: models.ActionMergePullRequest, + actionType: activities_model.ActionMergePullRequest, }, prefix: fmt.Sprintf("%s/pulls/%d/merge/", issue.Repo.FullName(), issue.Index), }, @@ -352,7 +352,7 @@ func Test_createReference(t *testing.T) { name: "Ready Pull", args: args{ issue: pullIssue, - actionType: models.ActionPullRequestReadyForReview, + actionType: activities_model.ActionPullRequestReadyForReview, }, prefix: fmt.Sprintf("%s/pulls/%d/ready/", issue.Repo.FullName(), issue.Index), }, diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index c7a6f9b02f..79b22bef78 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -83,7 +83,7 @@ func (g *GiteaLocalUploader) MaxBatchInsertSize(tp string) int { case "label": return db.MaxBatchInsertSize(new(issues_model.Label)) case "release": - return db.MaxBatchInsertSize(new(models.Release)) + return db.MaxBatchInsertSize(new(repo_model.Release)) case "pullrequest": return db.MaxBatchInsertSize(new(issues_model.PullRequest)) } @@ -99,7 +99,7 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate var r *repo_model.Repository if opts.MigrateToRepoID <= 0 { - r, err = repo_module.CreateRepository(g.doer, owner, models.CreateRepoOptions{ + r, err = repo_module.CreateRepository(g.doer, owner, repo_module.CreateRepoOptions{ Name: g.repoName, Description: repo.Description, OriginalURL: repo.OriginalURL, @@ -237,7 +237,7 @@ func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error { // CreateReleases creates releases func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error { - rels := make([]*models.Release, 0, len(releases)) + rels := make([]*repo_model.Release, 0, len(releases)) for _, release := range releases { if release.Created.IsZero() { if !release.Published.IsZero() { @@ -247,7 +247,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error { } } - rel := models.Release{ + rel := repo_model.Release{ RepoID: g.repo.ID, TagName: release.TagName, LowerTagName: strings.ToLower(release.TagName), diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 1f1c4bde6f..715dbf7a5c 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -15,7 +15,6 @@ import ( "testing" "time" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -85,7 +84,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, labels, 12) - releases, err := models.GetReleasesByRepoID(repo.ID, models.FindReleasesOptions{ + releases, err := repo_model.GetReleasesByRepoID(repo.ID, repo_model.FindReleasesOptions{ ListOptions: db.ListOptions{ PageSize: 10, Page: 0, @@ -95,7 +94,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, releases, 8) - releases, err = models.GetReleasesByRepoID(repo.ID, models.FindReleasesOptions{ + releases, err = repo_model.GetReleasesByRepoID(repo.ID, repo_model.FindReleasesOptions{ ListOptions: db.ListOptions{ PageSize: 10, Page: 0, @@ -146,7 +145,7 @@ func TestGiteaUploadRemapLocalUser(t *testing.T) { // The externalID does not match any existing user, everything // belongs to the doer // - target := models.Release{} + target := repo_model.Release{} uploader.userMap = make(map[int64]int64) err := uploader.remapUser(&source, &target) assert.NoError(t, err) @@ -157,7 +156,7 @@ func TestGiteaUploadRemapLocalUser(t *testing.T) { // everything belongs to the doer // source.PublisherID = user.ID - target = models.Release{} + target = repo_model.Release{} uploader.userMap = make(map[int64]int64) err = uploader.remapUser(&source, &target) assert.NoError(t, err) @@ -168,7 +167,7 @@ func TestGiteaUploadRemapLocalUser(t *testing.T) { // belongs to the existing user // source.PublisherName = user.Name - target = models.Release{} + target = repo_model.Release{} uploader.userMap = make(map[int64]int64) err = uploader.remapUser(&source, &target) assert.NoError(t, err) @@ -197,7 +196,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { // by the doer // uploader.userMap = make(map[int64]int64) - target := models.Release{} + target := repo_model.Release{} err := uploader.remapUser(&source, &target) assert.NoError(t, err) assert.EqualValues(t, doer.ID, target.GetUserID()) @@ -220,7 +219,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { // the migrated data // uploader.userMap = make(map[int64]int64) - target = models.Release{} + target = repo_model.Release{} err = uploader.remapUser(&source, &target) assert.NoError(t, err) assert.EqualValues(t, linkedUser.ID, target.GetUserID()) diff --git a/services/org/repo.go b/services/org/repo.go new file mode 100644 index 0000000000..769419d45b --- /dev/null +++ b/services/org/repo.go @@ -0,0 +1,28 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package org + +import ( + "context" + "errors" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/organization" + repo_model "code.gitea.io/gitea/models/repo" +) + +// TeamAddRepository adds new repository to team of organization. +func TeamAddRepository(t *organization.Team, repo *repo_model.Repository) (err error) { + if repo.OwnerID != t.OrgID { + return errors.New("repository does not belong to organization") + } else if models.HasRepository(t, repo.ID) { + return nil + } + + return db.WithTx(func(ctx context.Context) error { + return models.AddRepository(ctx, t, repo) + }) +} diff --git a/services/org/repo_test.go b/services/org/repo_test.go new file mode 100644 index 0000000000..21158bfa21 --- /dev/null +++ b/services/org/repo_test.go @@ -0,0 +1,34 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package org + +import ( + "testing" + + "code.gitea.io/gitea/models/organization" + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/models/unittest" + + "github.com/stretchr/testify/assert" +) + +func TestTeam_AddRepository(t *testing.T) { + assert.NoError(t, unittest.PrepareTestDatabase()) + + testSuccess := func(teamID, repoID int64) { + team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) + assert.NoError(t, TeamAddRepository(team, repo)) + unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) + unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) + } + testSuccess(2, 3) + testSuccess(2, 5) + + team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) + assert.Error(t, TeamAddRepository(team, repo)) + unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1}) +} diff --git a/services/release/release.go b/services/release/release.go index 6fa966de1f..e2e8c13699 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -23,7 +23,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" ) -func createTag(gitRepo *git.Repository, rel *models.Release, msg string) (bool, error) { +func createTag(gitRepo *git.Repository, rel *repo_model.Release, msg string) (bool, error) { var created bool // Only actual create when publish. if !rel.IsDraft { @@ -112,12 +112,12 @@ func createTag(gitRepo *git.Repository, rel *models.Release, msg string) (bool, } // CreateRelease creates a new release of repository. -func CreateRelease(gitRepo *git.Repository, rel *models.Release, attachmentUUIDs []string, msg string) error { - has, err := models.IsReleaseExist(gitRepo.Ctx, rel.RepoID, rel.TagName) +func CreateRelease(gitRepo *git.Repository, rel *repo_model.Release, attachmentUUIDs []string, msg string) error { + has, err := repo_model.IsReleaseExist(gitRepo.Ctx, rel.RepoID, rel.TagName) if err != nil { return err } else if has { - return models.ErrReleaseAlreadyExist{ + return repo_model.ErrReleaseAlreadyExist{ TagName: rel.TagName, } } @@ -131,7 +131,7 @@ func CreateRelease(gitRepo *git.Repository, rel *models.Release, attachmentUUIDs return err } - if err = models.AddReleaseAttachments(gitRepo.Ctx, rel.ID, attachmentUUIDs); err != nil { + if err = repo_model.AddReleaseAttachments(gitRepo.Ctx, rel.ID, attachmentUUIDs); err != nil { return err } @@ -144,7 +144,7 @@ func CreateRelease(gitRepo *git.Repository, rel *models.Release, attachmentUUIDs // CreateNewTag creates a new repository tag func CreateNewTag(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, commit, tagName, msg string) error { - has, err := models.IsReleaseExist(ctx, repo.ID, tagName) + has, err := repo_model.IsReleaseExist(ctx, repo.ID, tagName) if err != nil { return err } else if has { @@ -159,7 +159,7 @@ func CreateNewTag(ctx context.Context, doer *user_model.User, repo *repo_model.R } defer closer.Close() - rel := &models.Release{ + rel := &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: doer.ID, @@ -182,7 +182,7 @@ func CreateNewTag(ctx context.Context, doer *user_model.User, repo *repo_model.R // addAttachmentUUIDs accept a slice of new created attachments' uuids which will be reassigned release_id as the created release // delAttachmentUUIDs accept a slice of attachments' uuids which will be deleted from the release // editAttachments accept a map of attachment uuid to new attachment name which will be updated with attachments. -func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.Release, +func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *repo_model.Release, addAttachmentUUIDs, delAttachmentUUIDs []string, editAttachments map[string]string, ) (err error) { if rel.ID == 0 { @@ -200,11 +200,11 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.R } defer committer.Close() - if err = models.UpdateRelease(ctx, rel); err != nil { + if err = repo_model.UpdateRelease(ctx, rel); err != nil { return err } - if err = models.AddReleaseAttachments(ctx, rel.ID, addAttachmentUUIDs); err != nil { + if err = repo_model.AddReleaseAttachments(ctx, rel.ID, addAttachmentUUIDs); err != nil { return fmt.Errorf("AddReleaseAttachments: %v", err) } @@ -283,7 +283,7 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.R // DeleteReleaseByID deletes a release and corresponding Git tag by given ID. func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, delTag bool) error { - rel, err := models.GetReleaseByID(ctx, id) + rel, err := repo_model.GetReleaseByID(ctx, id) if err != nil { return fmt.Errorf("GetReleaseByID: %v", err) } @@ -324,13 +324,13 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del }, repository.NewPushCommits()) notification.NotifyDeleteRef(doer, repo, "tag", git.TagPrefix+rel.TagName) - if err := models.DeleteReleaseByID(id); err != nil { + if err := repo_model.DeleteReleaseByID(id); err != nil { return fmt.Errorf("DeleteReleaseByID: %v", err) } } else { rel.IsTag = true - if err = models.UpdateRelease(ctx, rel); err != nil { + if err = repo_model.UpdateRelease(ctx, rel); err != nil { return fmt.Errorf("Update: %v", err) } } diff --git a/services/release/release_test.go b/services/release/release_test.go index d1a9298b69..c0cafb5fcc 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -38,7 +37,7 @@ func TestRelease_Create(t *testing.T) { assert.NoError(t, err) defer gitRepo.Close() - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -52,7 +51,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, nil, "")) - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -66,7 +65,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, nil, "")) - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -80,7 +79,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, nil, "")) - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -94,7 +93,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, nil, "")) - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -115,7 +114,7 @@ func TestRelease_Create(t *testing.T) { }, strings.NewReader("testtest")) assert.NoError(t, err) - release := models.Release{ + release := repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -143,7 +142,7 @@ func TestRelease_Update(t *testing.T) { defer gitRepo.Close() // Test a changed release - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -156,18 +155,18 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: false, IsTag: false, }, nil, "")) - release, err := models.GetRelease(repo.ID, "v1.1.1") + release, err := repo_model.GetRelease(repo.ID, "v1.1.1") assert.NoError(t, err) releaseCreatedUnix := release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Note = "Changed note" assert.NoError(t, UpdateRelease(user, gitRepo, release, nil, nil, nil)) - release, err = models.GetReleaseByID(db.DefaultContext, release.ID) + release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed draft - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -180,18 +179,18 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: false, IsTag: false, }, nil, "")) - release, err = models.GetRelease(repo.ID, "v1.2.1") + release, err = repo_model.GetRelease(repo.ID, "v1.2.1") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" assert.NoError(t, UpdateRelease(user, gitRepo, release, nil, nil, nil)) - release, err = models.GetReleaseByID(db.DefaultContext, release.ID) + release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) assert.NoError(t, err) assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed pre-release - assert.NoError(t, CreateRelease(gitRepo, &models.Release{ + assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -204,19 +203,19 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: true, IsTag: false, }, nil, "")) - release, err = models.GetRelease(repo.ID, "v1.3.1") + release, err = repo_model.GetRelease(repo.ID, "v1.3.1") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" release.Note = "Changed note" assert.NoError(t, UpdateRelease(user, gitRepo, release, nil, nil, nil)) - release, err = models.GetReleaseByID(db.DefaultContext, release.ID) + release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test create release - release = &models.Release{ + release = &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -236,7 +235,7 @@ func TestRelease_Update(t *testing.T) { tagName := release.TagName assert.NoError(t, UpdateRelease(user, gitRepo, release, nil, nil, nil)) - release, err = models.GetReleaseByID(db.DefaultContext, release.ID) + release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) assert.NoError(t, err) assert.Equal(t, tagName, release.TagName) @@ -249,7 +248,7 @@ func TestRelease_Update(t *testing.T) { assert.NoError(t, err) assert.NoError(t, UpdateRelease(user, gitRepo, release, []string{attach.UUID}, nil, nil)) - assert.NoError(t, models.GetReleaseAttachments(db.DefaultContext, release)) + assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) assert.Len(t, release.Attachments, 1) assert.EqualValues(t, attach.UUID, release.Attachments[0].UUID) assert.EqualValues(t, release.ID, release.Attachments[0].ReleaseID) @@ -260,7 +259,7 @@ func TestRelease_Update(t *testing.T) { attach.UUID: "test2.txt", })) release.Attachments = nil - assert.NoError(t, models.GetReleaseAttachments(db.DefaultContext, release)) + assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) assert.Len(t, release.Attachments, 1) assert.EqualValues(t, attach.UUID, release.Attachments[0].UUID) assert.EqualValues(t, release.ID, release.Attachments[0].ReleaseID) @@ -269,7 +268,7 @@ func TestRelease_Update(t *testing.T) { // delete the attachment assert.NoError(t, UpdateRelease(user, gitRepo, release, nil, []string{attach.UUID}, nil)) release.Attachments = nil - assert.NoError(t, models.GetReleaseAttachments(db.DefaultContext, release)) + assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) assert.Empty(t, release.Attachments) } @@ -285,7 +284,7 @@ func TestRelease_createTag(t *testing.T) { defer gitRepo.Close() // Test a changed release - release := &models.Release{ + release := &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -309,7 +308,7 @@ func TestRelease_createTag(t *testing.T) { assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed draft - release = &models.Release{ + release = &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -332,7 +331,7 @@ func TestRelease_createTag(t *testing.T) { assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed pre-release - release = &models.Release{ + release = &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, diff --git a/services/repository/adopt.go b/services/repository/adopt.go index 6d6611c705..74876d8e76 100644 --- a/services/repository/adopt.go +++ b/services/repository/adopt.go @@ -11,7 +11,6 @@ import ( "path/filepath" "strings" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -26,7 +25,7 @@ import ( ) // AdoptRepository adopts pre-existing repository files for the user/organization. -func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (*repo_model.Repository, error) { +func AdoptRepository(doer, u *user_model.User, opts repo_module.CreateRepoOptions) (*repo_model.Repository, error) { if !doer.IsAdmin && !u.CanCreateRepo() { return nil, repo_model.ErrReachLimitOfRepo{ Limit: u.MaxRepoCreation, @@ -67,7 +66,7 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (* } } - if err := models.CreateRepository(ctx, doer, u, repo, true); err != nil { + if err := repo_module.CreateRepositoryByExample(ctx, doer, u, repo, true); err != nil { return err } if err := adoptRepository(ctx, repoPath, doer, repo, opts); err != nil { @@ -100,7 +99,7 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (* return repo, nil } -func adoptRepository(ctx context.Context, repoPath string, u *user_model.User, repo *repo_model.Repository, opts models.CreateRepoOptions) (err error) { +func adoptRepository(ctx context.Context, repoPath string, u *user_model.User, repo *repo_model.Repository, opts repo_module.CreateRepoOptions) (err error) { isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index ffc1f4efe9..327a2e121c 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -11,7 +11,6 @@ import ( "path" "strings" - "code.gitea.io/gitea/models" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -32,7 +31,7 @@ type UploadRepoFileOptions struct { } type uploadInfo struct { - upload *models.Upload + upload *repo_model.Upload lfsMetaObject *git_model.LFSMetaObject } @@ -56,7 +55,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return nil } - uploads, err := models.GetUploadsByUUIDs(opts.Files) + uploads, err := repo_model.GetUploadsByUUIDs(opts.Files) if err != nil { return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %v", opts.Files, err) } @@ -157,7 +156,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return err } - return models.DeleteUploads(uploads...) + return repo_model.DeleteUploads(uploads...) } func copyUploadedLFSFileIntoRepository(info *uploadInfo, filename2attribute2info map[string]map[string]string, t *TemporaryUploadRepository, treePath string) error { diff --git a/services/repository/fork.go b/services/repository/fork.go index b274585ed5..96c391e715 100644 --- a/services/repository/fork.go +++ b/services/repository/fork.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" @@ -23,6 +22,23 @@ import ( "code.gitea.io/gitea/modules/util" ) +// ErrForkAlreadyExist represents a "ForkAlreadyExist" kind of error. +type ErrForkAlreadyExist struct { + Uname string + RepoName string + ForkName string +} + +// IsErrForkAlreadyExist checks if an error is an ErrForkAlreadyExist. +func IsErrForkAlreadyExist(err error) bool { + _, ok := err.(ErrForkAlreadyExist) + return ok +} + +func (err ErrForkAlreadyExist) Error() string { + return fmt.Sprintf("repository is already forked by user [uname: %s, repo path: %s, fork path: %s]", err.Uname, err.RepoName, err.ForkName) +} + // ForkRepoOptions contains the fork repository options type ForkRepoOptions struct { BaseRepo *repo_model.Repository @@ -37,7 +53,7 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork return nil, err } if forkedRepo != nil { - return nil, models.ErrForkAlreadyExist{ + return nil, ErrForkAlreadyExist{ Uname: owner.Name, RepoName: opts.BaseRepo.FullName(), ForkName: forkedRepo.FullName(), @@ -93,7 +109,7 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork }() err = db.WithTx(func(txCtx context.Context) error { - if err = models.CreateRepository(txCtx, doer, owner, repo, false); err != nil { + if err = repo_module.CreateRepositoryByExample(txCtx, doer, owner, repo, false); err != nil { return err } diff --git a/services/repository/fork_test.go b/services/repository/fork_test.go index 376c5c06d9..d4ba507351 100644 --- a/services/repository/fork_test.go +++ b/services/repository/fork_test.go @@ -7,7 +7,6 @@ package repository 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" @@ -30,5 +29,5 @@ func TestForkRepository(t *testing.T) { }) assert.Nil(t, fork) assert.Error(t, err) - assert.True(t, models.IsErrForkAlreadyExist(err)) + assert.True(t, IsErrForkAlreadyExist(err)) } diff --git a/services/repository/push.go b/services/repository/push.go index 65ac7b660c..f3f505aa00 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -11,7 +11,6 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" @@ -292,7 +291,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { // PushUpdateAddDeleteTags updates a number of added and delete tags func PushUpdateAddDeleteTags(repo *repo_model.Repository, gitRepo *git.Repository, addTags, delTags []string) error { return db.WithTx(func(ctx context.Context) error { - if err := models.PushUpdateDeleteTagsContext(ctx, repo, delTags); err != nil { + if err := repo_model.PushUpdateDeleteTagsContext(ctx, repo, delTags); err != nil { return err } return pushUpdateAddTags(ctx, repo, gitRepo, addTags) @@ -310,16 +309,16 @@ func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitRepo lowerTags = append(lowerTags, strings.ToLower(tag)) } - releases, err := models.GetReleasesByRepoIDAndNames(ctx, repo.ID, lowerTags) + releases, err := repo_model.GetReleasesByRepoIDAndNames(ctx, repo.ID, lowerTags) if err != nil { return fmt.Errorf("GetReleasesByRepoIDAndNames: %v", err) } - relMap := make(map[string]*models.Release) + relMap := make(map[string]*repo_model.Release) for _, rel := range releases { relMap[rel.LowerTagName] = rel } - newReleases := make([]*models.Release, 0, len(lowerTags)-len(relMap)) + newReleases := make([]*repo_model.Release, 0, len(lowerTags)-len(relMap)) emailToUser := make(map[string]*user_model.User) @@ -366,7 +365,7 @@ func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitRepo rel, has := relMap[lowerTag] if !has { - rel = &models.Release{ + rel = &repo_model.Release{ RepoID: repo.ID, Title: "", TagName: tags[i], @@ -393,7 +392,7 @@ func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitRepo if rel.IsTag && author != nil { rel.PublisherID = author.ID } - if err = models.UpdateRelease(ctx, rel); err != nil { + if err = repo_model.UpdateRelease(ctx, rel); err != nil { return fmt.Errorf("Update: %v", err) } } diff --git a/services/repository/repository.go b/services/repository/repository.go index 4bde6879a6..d530358360 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -25,7 +25,7 @@ import ( ) // CreateRepository creates a repository for the user/organization. -func CreateRepository(doer, owner *user_model.User, opts models.CreateRepoOptions) (*repo_model.Repository, error) { +func CreateRepository(doer, owner *user_model.User, opts repo_module.CreateRepoOptions) (*repo_model.Repository, error) { repo, err := repo_module.CreateRepository(doer, owner, opts) if err != nil { // No need to rollback here we should do this in CreateRepository... @@ -69,7 +69,7 @@ func PushCreateRepo(authUser, owner *user_model.User, repoName string) (*repo_mo } } - repo, err := CreateRepository(authUser, owner, models.CreateRepoOptions{ + repo, err := CreateRepository(authUser, owner, repo_module.CreateRepoOptions{ Name: repoName, IsPrivate: setting.Repository.DefaultPushCreatePrivate, }) @@ -117,7 +117,7 @@ func LinkedRepository(a *repo_model.Attachment) (*repo_model.Repository, unit.Ty } return repo, unitType, err } else if a.ReleaseID != 0 { - rel, err := models.GetReleaseByID(db.DefaultContext, a.ReleaseID) + rel, err := repo_model.GetReleaseByID(db.DefaultContext, a.ReleaseID) if err != nil { return nil, unit.TypeReleases, err } diff --git a/services/repository/transfer.go b/services/repository/transfer.go index ae15383240..a0f4a7685c 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -16,6 +16,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification" + repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/sync" ) @@ -49,7 +50,7 @@ func TransferOwnership(doer, newOwner *user_model.User, repo *repo_model.Reposit } for _, team := range teams { - if err := models.AddRepository(team, newRepo); err != nil { + if err := models.AddRepository(db.DefaultContext, team, newRepo); err != nil { return err } } @@ -111,7 +112,7 @@ func StartRepositoryTransfer(doer, newOwner *user_model.User, repo *repo_model.R return err } if !hasAccess { - if err := models.AddCollaborator(repo, newOwner); err != nil { + if err := repo_module.AddCollaborator(repo, newOwner); err != nil { return err } if err := repo_model.ChangeCollaborationAccessMode(repo, newOwner.ID, perm.AccessModeRead); err != nil { diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index 3c929f2f7b..bf2a0ce0a2 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -8,7 +8,7 @@ import ( "sync" "testing" - "code.gitea.io/gitea/models" + activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" access_model "code.gitea.io/gitea/models/perm/access" @@ -49,8 +49,8 @@ func TestTransferOwnership(t *testing.T) { exist, err = util.IsExist(repo_model.RepoPath("user2", "repo3")) assert.NoError(t, err) assert.True(t, exist) - unittest.AssertExistsAndLoadBean(t, &models.Action{ - OpType: models.ActionTransferRepo, + unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ + OpType: activities_model.ActionTransferRepo, ActUserID: 2, RepoID: 3, Content: "user3/repo3", diff --git a/services/task/migrate.go b/services/task/migrate.go index 651681ef65..775cbf6128 100644 --- a/services/task/migrate.go +++ b/services/task/migrate.go @@ -10,6 +10,7 @@ import ( "strings" "code.gitea.io/gitea/models" + 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" @@ -40,7 +41,7 @@ func handleCreateError(owner *user_model.User, err error) error { } } -func runMigrateTask(t *models.Task) (err error) { +func runMigrateTask(t *admin_model.Task) (err error) { defer func() { if e := recover(); e != nil { err = fmt.Errorf("PANIC whilst trying to do migrate task: %v", e) @@ -48,7 +49,7 @@ func runMigrateTask(t *models.Task) (err error) { } if err == nil { - err = models.FinishMigrateTask(t) + err = admin_model.FinishMigrateTask(t) if err == nil { notification.NotifyMigrateRepository(t.Doer, t.Owner, t.Repo) return @@ -110,7 +111,7 @@ func runMigrateTask(t *models.Task) (err error) { } t.Repo, err = migrations.MigrateRepository(ctx, t.Doer, t.Owner.Name, *opts, func(format string, args ...interface{}) { - message := models.TranslatableMessage{ + message := admin_model.TranslatableMessage{ Format: format, Args: args, } diff --git a/services/task/task.go b/services/task/task.go index 9deb0286c5..138dc88a04 100644 --- a/services/task/task.go +++ b/services/task/task.go @@ -7,7 +7,7 @@ package task import ( "fmt" - "code.gitea.io/gitea/models" + admin_model "code.gitea.io/gitea/models/admin" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/graceful" @@ -27,7 +27,7 @@ import ( var taskQueue queue.Queue // Run a task -func Run(t *models.Task) error { +func Run(t *admin_model.Task) error { switch t.Type { case structs.TaskTypeMigrateRepo: return runMigrateTask(t) @@ -38,7 +38,7 @@ func Run(t *models.Task) error { // Init will start the service to get all unfinished tasks and run them func Init() error { - taskQueue = queue.CreateQueue("task", handle, &models.Task{}) + taskQueue = queue.CreateQueue("task", handle, &admin_model.Task{}) if taskQueue == nil { return fmt.Errorf("Unable to create Task Queue") @@ -51,7 +51,7 @@ func Init() error { func handle(data ...queue.Data) []queue.Data { for _, datum := range data { - task := datum.(*models.Task) + task := datum.(*admin_model.Task) if err := Run(task); err != nil { log.Error("Run task failed: %v", err) } @@ -70,7 +70,7 @@ func MigrateRepository(doer, u *user_model.User, opts base.MigrateOptions) error } // CreateMigrateTask creates a migrate task -func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*models.Task, error) { +func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*admin_model.Task, error) { // encrypt credentials for persistence var err error opts.CloneAddrEncrypted, err = secret.EncryptSecret(setting.SecretKey, opts.CloneAddr) @@ -93,7 +93,7 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*mod return nil, err } - task := &models.Task{ + task := &admin_model.Task{ DoerID: doer.ID, OwnerID: u.ID, Type: structs.TaskTypeMigrateRepo, @@ -101,11 +101,11 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*mod PayloadContent: string(bs), } - if err := models.CreateTask(task); err != nil { + if err := admin_model.CreateTask(task); err != nil { return nil, err } - repo, err := repo_module.CreateRepository(doer, u, models.CreateRepoOptions{ + repo, err := repo_module.CreateRepository(doer, u, repo_module.CreateRepoOptions{ Name: opts.RepoName, Description: opts.Description, OriginalURL: opts.OriginalURL, diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index 43e35eed69..ac5283bbeb 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -12,7 +12,6 @@ import ( "os" "strings" - "code.gitea.io/gitea/models" admin_model "code.gitea.io/gitea/models/admin" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" @@ -33,7 +32,7 @@ var ( func nameAllowed(name string) error { if util.IsStringInSlice(name, reservedWikiNames) { - return models.ErrWikiReservedName{ + return repo_model.ErrWikiReservedName{ Title: name, } } @@ -59,7 +58,7 @@ func NameToFilename(name string) string { // FilenameToName converts a wiki filename to its corresponding page name. func FilenameToName(filename string) (string, error) { if !strings.HasSuffix(filename, ".md") { - return "", models.ErrWikiInvalidFileName{ + return "", repo_model.ErrWikiInvalidFileName{ FileName: filename, } } @@ -178,7 +177,7 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if isNew { if isWikiExist { - return models.ErrWikiAlreadyExist{ + return repo_model.ErrWikiAlreadyExist{ Title: newWikiPath, } } diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index 1852ddbcb3..938a7d6acd 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -9,7 +9,6 @@ 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" @@ -90,11 +89,11 @@ func TestWikiFilenameToName(t *testing.T) { } { _, err := FilenameToName(badFilename) assert.Error(t, err) - assert.True(t, models.IsErrWikiInvalidFileName(err)) + assert.True(t, repo_model.IsErrWikiInvalidFileName(err)) } _, err := FilenameToName("badescaping%%.md") assert.Error(t, err) - assert.False(t, models.IsErrWikiInvalidFileName(err)) + assert.False(t, repo_model.IsErrWikiInvalidFileName(err)) } func TestWikiNameToFilenameToName(t *testing.T) { @@ -157,7 +156,7 @@ func TestRepository_AddWikiPage(t *testing.T) { // test for already-existing wiki name err := AddWikiPage(git.DefaultContext, doer, repo, "Home", wikiContent, commitMsg) assert.Error(t, err) - assert.True(t, models.IsErrWikiAlreadyExist(err)) + assert.True(t, repo_model.IsErrWikiAlreadyExist(err)) }) t.Run("check wiki reserved name", func(t *testing.T) { @@ -165,7 +164,7 @@ func TestRepository_AddWikiPage(t *testing.T) { // test for reserved wiki name err := AddWikiPage(git.DefaultContext, doer, repo, "_edit", wikiContent, commitMsg) assert.Error(t, err) - assert.True(t, models.IsErrWikiReservedName(err)) + assert.True(t, repo_model.IsErrWikiReservedName(err)) }) } |