From 719bddcd76610a63dadc8555760072957a11cf30 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 10 Dec 2021 09:27:50 +0800 Subject: [PATCH] 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 --- cmd/migrate_storage.go | 2 +- integrations/api_comment_test.go | 13 +- .../api_helper_for_declarative_test.go | 8 +- integrations/api_issue_label_test.go | 9 +- integrations/api_issue_milestone_test.go | 3 +- integrations/api_issue_stopwatch_test.go | 3 +- integrations/api_issue_subscription_test.go | 7 +- integrations/api_issue_test.go | 11 +- integrations/api_keys_test.go | 5 +- integrations/api_notification_test.go | 3 +- integrations/api_pull_commits_test.go | 3 +- integrations/api_pull_review_test.go | 9 +- integrations/api_pull_test.go | 21 +- integrations/api_releases_test.go | 15 +- integrations/api_repo_archive_test.go | 4 +- integrations/api_repo_edit_test.go | 32 +- integrations/api_repo_file_create_test.go | 22 +- integrations/api_repo_file_delete_test.go | 14 +- integrations/api_repo_file_helpers.go | 6 +- integrations/api_repo_file_update_test.go | 14 +- .../api_repo_get_contents_list_test.go | 16 +- integrations/api_repo_get_contents_test.go | 14 +- integrations/api_repo_git_blobs_test.go | 14 +- integrations/api_repo_git_hook_test.go | 20 +- integrations/api_repo_git_tags_test.go | 6 +- integrations/api_repo_git_trees_test.go | 14 +- integrations/api_repo_lfs_locks_test.go | 18 +- integrations/api_repo_lfs_test.go | 25 +- integrations/api_repo_teams_test.go | 4 +- integrations/api_repo_test.go | 19 +- integrations/api_repo_topic_test.go | 6 +- integrations/benchmarks_test.go | 4 +- integrations/change_default_branch_test.go | 4 +- integrations/delete_user_test.go | 3 +- integrations/empty_repo_test.go | 4 +- integrations/eventsource_test.go | 3 +- integrations/git_test.go | 5 +- integrations/issue_test.go | 5 +- integrations/lfs_getobject_test.go | 5 +- integrations/mirror_pull_test.go | 9 +- integrations/mirror_push_test.go | 5 +- integrations/privateactivity_test.go | 3 +- integrations/pull_merge_test.go | 31 +- integrations/release_test.go | 8 +- integrations/rename_branch_test.go | 4 +- integrations/repo_activity_test.go | 4 +- integrations/repo_search_test.go | 8 +- integrations/repo_tag_test.go | 3 +- integrations/repofiles_delete_test.go | 4 +- integrations/repofiles_update_test.go | 6 +- models/access.go | 40 +- models/access_test.go | 25 +- models/action.go | 37 +- models/action_list.go | 7 +- models/action_test.go | 5 +- models/branches.go | 74 +- models/branches_test.go | 33 +- models/commit.go | 3 +- models/commit_status.go | 40 +- models/commit_status_test.go | 3 +- models/consistency.go | 5 +- models/error.go | 35 +- models/fixture_generation.go | 5 +- models/gpg_key_commit_verification.go | 17 +- models/helper.go | 37 +- models/helper_environment.go | 7 +- models/issue.go | 71 +- models/issue_assignees.go | 2 +- models/issue_comment.go | 51 +- models/issue_comment_list.go | 14 +- models/issue_comment_test.go | 3 +- models/issue_dependency.go | 18 - models/issue_label.go | 8 +- models/issue_label_test.go | 7 +- models/issue_list.go | 6 +- models/issue_milestone.go | 11 +- models/issue_milestone_test.go | 29 +- models/issue_reaction.go | 5 +- models/issue_reaction_test.go | 5 +- models/issue_stopwatch.go | 12 +- models/issue_test.go | 7 +- models/issue_tracked_time.go | 17 +- models/issue_user.go | 10 +- models/issue_user_test.go | 5 +- models/issue_xref.go | 25 +- models/issue_xref_test.go | 5 +- models/lfs.go | 36 +- models/lfs_lock.go | 61 +- models/main_test.go | 3 +- models/notification.go | 38 +- models/org.go | 15 +- models/org_team.go | 59 +- models/org_team_test.go | 13 +- models/org_test.go | 15 +- models/project_issue.go | 2 +- models/protected_tag.go | 54 +- models/protected_tag_test.go | 14 +- models/pull.go | 62 +- models/pull_test.go | 9 +- models/release.go | 14 +- models/repo.go | 1038 ++--------------- models/repo/avatar.go | 94 ++ models/repo/git.go | 31 + models/{repo_issue.go => repo/issue.go} | 22 +- .../language_stats.go} | 25 +- models/repo/main_test.go | 3 + models/{repo_mirror.go => repo/mirror.go} | 49 +- .../pushmirror.go} | 2 +- .../pushmirror_test.go} | 2 +- models/repo/repo.go | 736 ++++++++++++ models/{ => repo}/repo_indexer.go | 20 +- models/repo/repo_test.go | 44 + models/{ => repo}/repo_unit.go | 29 +- models/{ => repo}/wiki.go | 2 +- models/{ => repo}/wiki_test.go | 2 +- models/repo_activity.go | 5 +- models/repo_archiver.go | 6 +- models/repo_avatar.go | 92 +- models/repo_branch.go | 11 - models/repo_collaboration.go | 79 +- models/repo_collaboration_test.go | 37 +- models/repo_generate.go | 11 +- models/repo_list.go | 79 +- models/repo_permission.go | 80 +- models/repo_permission_test.go | 31 +- models/repo_redirect_test.go | 7 +- models/repo_sign.go | 5 +- models/repo_test.go | 89 +- models/repo_transfer.go | 47 +- models/repo_transfer_test.go | 3 +- models/repo_watch.go | 22 +- models/repo_watch_test.go | 33 +- models/review.go | 50 +- models/ssh_key_deploy.go | 11 +- models/star.go | 3 +- models/star_test.go | 5 +- models/statistic.go | 4 +- models/task.go | 17 +- models/topic.go | 5 +- models/update.go | 9 +- models/user.go | 17 +- modules/context/api.go | 6 +- modules/context/repo.go | 72 +- modules/convert/convert.go | 11 +- modules/convert/git_commit.go | 8 +- modules/convert/git_commit_test.go | 4 +- modules/convert/issue.go | 14 +- modules/convert/issue_test.go | 3 +- modules/convert/pull_test.go | 3 +- modules/convert/repository.go | 14 +- modules/convert/wiki.go | 4 +- modules/doctor/checkOldArchives.go | 4 +- modules/doctor/fix16961.go | 41 +- modules/doctor/fix16961_test.go | 32 +- modules/doctor/mergebase.go | 7 +- modules/doctor/misc.go | 15 +- modules/gitgraph/graph_models.go | 3 +- modules/indexer/code/bleve.go | 8 +- modules/indexer/code/elastic_search.go | 8 +- modules/indexer/code/git.go | 12 +- modules/indexer/code/indexer.go | 14 +- modules/indexer/code/indexer_test.go | 1 + modules/indexer/code/wrapped.go | 4 +- modules/indexer/issues/indexer.go | 5 +- modules/indexer/issues/indexer_test.go | 1 + modules/indexer/stats/db.go | 8 +- modules/indexer/stats/indexer.go | 4 +- modules/indexer/stats/indexer_test.go | 9 +- modules/indexer/stats/queue.go | 4 +- modules/json/json.go | 30 + modules/notification/action/action.go | 23 +- modules/notification/action/action_test.go | 3 +- modules/notification/base/notifier.go | 29 +- modules/notification/base/null.go | 29 +- modules/notification/indexer/indexer.go | 11 +- modules/notification/mail/mail.go | 5 +- modules/notification/notification.go | 29 +- modules/notification/ui/ui.go | 5 +- modules/notification/webhook/webhook.go | 23 +- modules/repofiles/commit_status.go | 3 +- modules/repository/commits_test.go | 4 +- modules/repository/create.go | 11 +- modules/repository/generate.go | 19 +- modules/repository/init.go | 13 +- modules/repository/push.go | 4 +- modules/repository/repo.go | 29 +- modules/templates/helper.go | 5 +- modules/test/context_tests.go | 6 +- routers/api/v1/admin/adopt.go | 9 +- routers/api/v1/api.go | 5 +- routers/api/v1/org/team.go | 7 +- routers/api/v1/repo/branch.go | 10 +- routers/api/v1/repo/collaborators.go | 17 +- routers/api/v1/repo/commits.go | 4 +- routers/api/v1/repo/file.go | 3 +- routers/api/v1/repo/fork.go | 2 +- routers/api/v1/repo/key.go | 5 +- routers/api/v1/repo/language.go | 6 +- routers/api/v1/repo/migrate.go | 3 +- routers/api/v1/repo/pull.go | 21 +- routers/api/v1/repo/repo.go | 61 +- routers/api/v1/repo/repo_test.go | 6 +- routers/api/v1/repo/subscriber.go | 3 +- routers/api/v1/repo/teams.go | 2 +- routers/api/v1/repo/transfer.go | 3 +- routers/api/v1/user/repo.go | 3 +- routers/api/v1/user/watch.go | 3 +- routers/private/default_branch.go | 6 +- routers/private/hook_post_receive.go | 5 +- routers/private/hook_pre_receive.go | 2 +- routers/private/internal_repo.go | 6 +- routers/private/serv.go | 7 +- routers/web/admin/repos.go | 7 +- routers/web/explore/code.go | 9 +- routers/web/explore/repo.go | 3 +- routers/web/goget.go | 6 +- routers/web/org/home.go | 3 +- routers/web/org/teams.go | 7 +- routers/web/repo/blame.go | 4 +- routers/web/repo/branch.go | 11 +- routers/web/repo/commit.go | 3 +- routers/web/repo/compare.go | 22 +- routers/web/repo/download.go | 3 +- routers/web/repo/http.go | 14 +- routers/web/repo/issue.go | 45 +- routers/web/repo/lfs.go | 15 +- routers/web/repo/pull.go | 29 +- routers/web/repo/repo.go | 8 +- routers/web/repo/setting.go | 85 +- routers/web/repo/setting_protected_branch.go | 9 +- routers/web/repo/settings_test.go | 19 +- routers/web/repo/tag.go | 4 +- routers/web/repo/view.go | 19 +- routers/web/repo/wiki_test.go | 10 +- routers/web/user/home.go | 17 +- routers/web/user/profile.go | 3 +- routers/web/user/setting/adopt.go | 3 +- routers/web/user/setting/profile.go | 3 +- services/auth/source/ldap/source.go | 3 +- services/auth/source/oauth2/source.go | 3 +- services/auth/source/pam/source.go | 3 +- services/auth/source/smtp/source.go | 3 +- services/auth/source/sspi/source.go | 3 +- services/comments/comments.go | 3 +- services/issue/commit.go | 7 +- services/issue/commit_test.go | 17 +- services/issue/issue.go | 3 +- services/lfs/locks.go | 16 +- services/lfs/server.go | 17 +- services/mailer/mail.go | 3 +- services/mailer/mail_issue.go | 2 +- services/mailer/mail_repo.go | 5 +- services/mailer/mail_test.go | 5 +- services/migrations/gitea_uploader.go | 10 +- services/migrations/gitea_uploader_test.go | 5 +- services/migrations/migrate.go | 3 +- services/mirror/mirror.go | 10 +- services/mirror/mirror_pull.go | 15 +- services/mirror/mirror_push.go | 12 +- services/org/org.go | 3 +- services/pull/check.go | 8 +- services/pull/lfs.go | 2 +- services/pull/merge.go | 38 +- services/pull/pull.go | 9 +- services/pull/review.go | 3 +- services/pull/temp_repo.go | 10 +- services/pull/update.go | 7 +- services/release/release.go | 6 +- services/release/release_test.go | 14 +- services/repository/adopt.go | 21 +- services/repository/branch.go | 21 +- services/repository/cache.go | 4 +- services/repository/check.go | 19 +- services/repository/files/commit.go | 5 +- services/repository/files/content.go | 7 +- services/repository/files/delete.go | 3 +- services/repository/files/diff.go | 4 +- services/repository/files/diff_test.go | 4 +- services/repository/files/file.go | 6 +- services/repository/files/temp_repo.go | 11 +- services/repository/files/tree.go | 3 +- services/repository/files/update.go | 15 +- services/repository/files/upload.go | 7 +- services/repository/fork.go | 22 +- services/repository/fork_test.go | 3 +- services/repository/generate.go | 5 +- services/repository/hooks.go | 6 +- services/repository/push.go | 11 +- services/repository/repository.go | 7 +- services/repository/transfer.go | 18 +- services/repository/transfer_test.go | 15 +- services/task/migrate.go | 3 +- services/task/task.go | 3 +- services/user/user.go | 3 +- services/user/user_test.go | 7 +- services/webhook/main_test.go | 1 + services/webhook/webhook.go | 10 +- services/webhook/webhook_test.go | 8 +- services/wiki/wiki.go | 21 +- services/wiki/wiki_test.go | 13 +- templates/repo/settings/options.tmpl | 4 +- 301 files changed, 3193 insertions(+), 2919 deletions(-) create mode 100644 models/repo/avatar.go create mode 100644 models/repo/git.go rename models/{repo_issue.go => repo/issue.go} (70%) rename models/{repo_language_stats.go => repo/language_stats.go} (85%) rename models/{repo_mirror.go => repo/mirror.go} (75%) rename models/{repo_pushmirror.go => repo/pushmirror.go} (99%) rename models/{repo_pushmirror_test.go => repo/pushmirror_test.go} (98%) create mode 100644 models/repo/repo.go rename models/{ => repo}/repo_indexer.go (81%) create mode 100644 models/repo/repo_test.go rename models/{ => repo}/repo_unit.go (89%) rename models/{ => repo}/wiki.go (98%) rename models/{ => repo}/wiki_test.go (99%) delete mode 100644 models/repo_branch.go diff --git a/cmd/migrate_storage.go b/cmd/migrate_storage.go index f8e2378ca..fb4b8dcd9 100644 --- a/cmd/migrate_storage.go +++ b/cmd/migrate_storage.go @@ -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 }) diff --git a/integrations/api_comment_test.go b/integrations/api_comment_test.go index 9ab97c0f4..0c3ac2ae5 100644 --- a/integrations/api_comment_test.go +++ b/integrations/api_comment_test.go @@ -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) diff --git a/integrations/api_helper_for_declarative_test.go b/integrations/api_helper_for_declarative_test.go index a8aba3199..9c6adaf08 100644 --- a/integrations/api_helper_for_declarative_test.go +++ b/integrations/api_helper_for_declarative_test.go @@ -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, }) diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go index 9ee8b75b5..42bfedf32 100644 --- a/integrations/api_issue_label_test.go +++ b/integrations/api_issue_label_test.go @@ -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) diff --git a/integrations/api_issue_milestone_test.go b/integrations/api_issue_milestone_test.go index 6a94321d3..60a632942 100644 --- a/integrations/api_issue_milestone_test.go +++ b/integrations/api_issue_milestone_test.go @@ -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()) diff --git a/integrations/api_issue_stopwatch_test.go b/integrations/api_issue_stopwatch_test.go index 8b9af3f0c..3f62e042c 100644 --- a/integrations/api_issue_stopwatch_test.go +++ b/integrations/api_issue_stopwatch_test.go @@ -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) diff --git a/integrations/api_issue_subscription_test.go b/integrations/api_issue_subscription_test.go index 18ff4159b..dfc3edee8 100644 --- a/integrations/api_issue_subscription_test.go +++ b/integrations/api_issue_subscription_test.go @@ -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) diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go index 87bec7a8f..0912d1d82 100644 --- a/integrations/api_issue_test.go +++ b/integrations/api_issue_test.go @@ -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) diff --git a/integrations/api_keys_test.go b/integrations/api_keys_test.go index 9bcfa7046..5fbd51318 100644 --- a/integrations/api_keys_test.go +++ b/integrations/api_keys_test.go @@ -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) diff --git a/integrations/api_notification_test.go b/integrations/api_notification_test.go index e3f39b363..12b3bac42 100644 --- a/integrations/api_notification_test.go +++ b/integrations/api_notification_test.go @@ -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) diff --git a/integrations/api_pull_commits_test.go b/integrations/api_pull_commits_test.go index a3d1bee58..5e057b05a 100644 --- a/integrations/api_pull_commits_test.go +++ b/integrations/api_pull_commits_test.go @@ -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) diff --git a/integrations/api_pull_review_test.go b/integrations/api_pull_review_test.go index 50b945408..df6dc75d5 100644 --- a/integrations/api_pull_review_test.go +++ b/integrations/api_pull_review_test.go @@ -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{ diff --git a/integrations/api_pull_test.go b/integrations/api_pull_test.go index db53d4159..b6b8ad873 100644 --- a/integrations/api_pull_test.go +++ b/integrations/api_pull_test.go @@ -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) diff --git a/integrations/api_releases_test.go b/integrations/api_releases_test.go index 5a16e60d7..b3d9c898e 100644 --- a/integrations/api_releases_test.go +++ b/integrations/api_releases_test.go @@ -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) diff --git a/integrations/api_repo_archive_test.go b/integrations/api_repo_archive_test.go index 6de61eea9..7778b7ff6 100644 --- a/integrations/api_repo_archive_test.go +++ b/integrations/api_repo_archive_test.go @@ -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) diff --git a/integrations/api_repo_edit_test.go b/integrations/api_repo_edit_test.go index defa86fca..91ec4c699 100644 --- a/integrations/api_repo_edit_test.go +++ b/integrations/api_repo_edit_test.go @@ -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, diff --git a/integrations/api_repo_file_create_test.go b/integrations/api_repo_file_create_test.go index 5092b8095..ba6c1a56a 100644 --- a/integrations/api_repo_file_create_test.go +++ b/integrations/api_repo_file_create_test.go @@ -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 diff --git a/integrations/api_repo_file_delete_test.go b/integrations/api_repo_file_delete_test.go index 0a87c0924..42df869d6 100644 --- a/integrations/api_repo_file_delete_test.go +++ b/integrations/api_repo_file_delete_test.go @@ -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 diff --git a/integrations/api_repo_file_helpers.go b/integrations/api_repo_file_helpers.go index 8477d65a3..53f74df24 100644 --- a/integrations/api_repo_file_helpers.go +++ b/integrations/api_repo_file_helpers.go @@ -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") } diff --git a/integrations/api_repo_file_update_test.go b/integrations/api_repo_file_update_test.go index 1fc84d5de..63bee1145 100644 --- a/integrations/api_repo_file_update_test.go +++ b/integrations/api_repo_file_update_test.go @@ -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 diff --git a/integrations/api_repo_get_contents_list_test.go b/integrations/api_repo_get_contents_list_test.go index 63ac9cfb5..449798a32 100644 --- a/integrations/api_repo_get_contents_list_test.go +++ b/integrations/api_repo_get_contents_list_test.go @@ -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) diff --git a/integrations/api_repo_get_contents_test.go b/integrations/api_repo_get_contents_test.go index 9843239ec..ddb988422 100644 --- a/integrations/api_repo_get_contents_test.go +++ b/integrations/api_repo_get_contents_test.go @@ -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 diff --git a/integrations/api_repo_git_blobs_test.go b/integrations/api_repo_git_blobs_test.go index 0311b6120..0a3cf632c 100644 --- a/integrations/api_repo_git_blobs_test.go +++ b/integrations/api_repo_git_blobs_test.go @@ -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" diff --git a/integrations/api_repo_git_hook_test.go b/integrations/api_repo_git_hook_test.go index ee5932176..a31b27c45 100644 --- a/integrations/api_repo_git_hook_test.go +++ b/integrations/api_repo_git_hook_test.go @@ -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) diff --git a/integrations/api_repo_git_tags_test.go b/integrations/api_repo_git_tags_test.go index 73c04531f..e2ee73872 100644 --- a/integrations/api_repo_git_tags_test.go +++ b/integrations/api_repo_git_tags_test.go @@ -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) diff --git a/integrations/api_repo_git_trees_test.go b/integrations/api_repo_git_trees_test.go index c54d3e324..03e065645 100644 --- a/integrations/api_repo_git_trees_test.go +++ b/integrations/api_repo_git_trees_test.go @@ -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" diff --git a/integrations/api_repo_lfs_locks_test.go b/integrations/api_repo_lfs_locks_test.go index f4d1ad124..3e0b40f51 100644 --- a/integrations/api_repo_lfs_locks_test.go +++ b/integrations/api_repo_lfs_locks_test.go @@ -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}) } diff --git a/integrations/api_repo_lfs_test.go b/integrations/api_repo_lfs_test.go index 6f3becf17..26f7e50f5 100644 --- a/integrations/api_repo_lfs_test.go +++ b/integrations/api_repo_lfs_test.go @@ -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") diff --git a/integrations/api_repo_teams_test.go b/integrations/api_repo_teams_test.go index ca1e33eab..07a8b9418 100644 --- a/integrations/api_repo_teams_test.go +++ b/integrations/api_repo_teams_test.go @@ -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) diff --git a/integrations/api_repo_test.go b/integrations/api_repo_test.go index b07416a5b..1e443362f 100644 --- a/integrations/api_repo_test.go +++ b/integrations/api_repo_test.go @@ -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) diff --git a/integrations/api_repo_topic_test.go b/integrations/api_repo_topic_test.go index 572099b7d..c417b3a9d 100644 --- a/integrations/api_repo_topic_test.go +++ b/integrations/api_repo_topic_test.go @@ -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) diff --git a/integrations/benchmarks_test.go b/integrations/benchmarks_test.go index 627825083..517e7f005 100644 --- a/integrations/benchmarks_test.go +++ b/integrations/benchmarks_test.go @@ -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") diff --git a/integrations/change_default_branch_test.go b/integrations/change_default_branch_test.go index 3b79e5032..af5542e0b 100644 --- a/integrations/change_default_branch_test.go +++ b/integrations/change_default_branch_test.go @@ -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) diff --git a/integrations/delete_user_test.go b/integrations/delete_user_test.go index 385b1822b..8eb4f45fa 100644 --- a/integrations/delete_user_test.go +++ b/integrations/delete_user_test.go @@ -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}) diff --git a/integrations/empty_repo_test.go b/integrations/empty_repo_test.go index 70e7aff9a..abc28b74c 100644 --- a/integrations/empty_repo_test.go +++ b/integrations/empty_repo_test.go @@ -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) diff --git a/integrations/eventsource_test.go b/integrations/eventsource_test.go index 277f5695a..8984c1fcb 100644 --- a/integrations/eventsource_test.go +++ b/integrations/eventsource_test.go @@ -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) diff --git a/integrations/git_test.go b/integrations/git_test.go index 642c1f122..baabae9e7 100644 --- a/integrations/git_test.go +++ b/integrations/git_test.go @@ -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 } diff --git a/integrations/issue_test.go b/integrations/issue_test.go index 69998b6f4..c7c000b01 100644 --- a/integrations/issue_test.go +++ b/integrations/issue_test.go @@ -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, diff --git a/integrations/lfs_getobject_test.go b/integrations/lfs_getobject_test.go index d179428c6..e9f0c5802 100644 --- a/integrations/lfs_getobject_test.go +++ b/integrations/lfs_getobject_test.go @@ -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") diff --git a/integrations/mirror_pull_test.go b/integrations/mirror_pull_test.go index fb70fd017..2bc50b614 100644 --- a/integrations/mirror_pull_test.go +++ b/integrations/mirror_pull_test.go @@ -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) diff --git a/integrations/mirror_push_test.go b/integrations/mirror_push_test.go index d9fa54376..c8b73880e 100644 --- a/integrations/mirror_push_test.go +++ b/integrations/mirror_push_test.go @@ -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) diff --git a/integrations/privateactivity_test.go b/integrations/privateactivity_test.go index 72890f611..796933964 100644 --- a/integrations/privateactivity_test.go +++ b/integrations/privateactivity_test.go @@ -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) diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index 2e219dcc9..812b5dd17 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -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() diff --git a/integrations/release_test.go b/integrations/release_test.go index 1f15aba09..28e034779 100644 --- a/integrations/release_test.go +++ b/integrations/release_test.go @@ -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" diff --git a/integrations/rename_branch_test.go b/integrations/rename_branch_test.go index 1fe198305..e856214f3 100644 --- a/integrations/rename_branch_test.go +++ b/integrations/rename_branch_test.go @@ -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) } diff --git a/integrations/repo_activity_test.go b/integrations/repo_activity_test.go index 56b70c959..66cc8dcfe 100644 --- a/integrations/repo_activity_test.go +++ b/integrations/repo_activity_test.go @@ -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") diff --git a/integrations/repo_search_test.go b/integrations/repo_search_test.go index 56d89fee3..078298836 100644 --- a/integrations/repo_search_test.go +++ b/integrations/repo_search_test.go @@ -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) } diff --git a/integrations/repo_tag_test.go b/integrations/repo_tag_test.go index 823e7e658..b90dcf058 100644 --- a/integrations/repo_tag_test.go +++ b/integrations/repo_tag_test.go @@ -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) { diff --git a/integrations/repofiles_delete_test.go b/integrations/repofiles_delete_test.go index 8490f8d3a..d2bfe31d9 100644 --- a/integrations/repofiles_delete_test.go +++ b/integrations/repofiles_delete_test.go @@ -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, diff --git a/integrations/repofiles_update_test.go b/integrations/repofiles_update_test.go index fe0e2c21c..7099cbdde 100644 --- a/integrations/repofiles_update_test.go +++ b/integrations/repofiles_update_test.go @@ -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, diff --git a/models/access.go b/models/access.go index f7252019a..6a97bcffc 100644 --- a/models/access.go +++ b/models/access.go @@ -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) } diff --git a/models/access_test.go b/models/access_test.go index 05bd1656e..43e61e812 100644 --- a/models/access_test.go +++ b/models/access_test.go @@ -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) diff --git a/models/action.go b/models/action.go index 66fa78f26..16d6c42aa 100644 --- a/models/action.go +++ b/models/action.go @@ -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 "#" } diff --git a/models/action_list.go b/models/action_list.go index 4f2024cfc..3f52d3cd5 100644 --- a/models/action_list.go +++ b/models/action_list.go @@ -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)) } diff --git a/models/action_test.go b/models/action_test.go index 8ab88bb97..02edae2df 100644 --- a/models/action_test.go +++ b/models/action_test.go @@ -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" diff --git a/models/branches.go b/models/branches.go index 3d377cf0f..e6d8b7441 100644 --- a/models/branches.go +++ b/models/branches.go @@ -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 diff --git a/models/branches_test.go b/models/branches_test.go index 187f23d41..e1a71853f 100644 --- a/models/branches_test.go +++ b/models/branches_test.go @@ -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) diff --git a/models/commit.go b/models/commit.go index 12aecdae8..8de71da1b 100644 --- a/models/commit.go +++ b/models/commit.go @@ -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), diff --git a/models/commit_status.go b/models/commit_status.go index bba39fde8..e0942d202 100644 --- a/models/commit_status.go +++ b/models/commit_status.go @@ -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 { diff --git a/models/commit_status_test.go b/models/commit_status_test.go index 02e384935..bb9e37507 100644 --- a/models/commit_status_test.go +++ b/models/commit_status_test.go @@ -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" diff --git a/models/consistency.go b/models/consistency.go index d16e7f5e9..0b9d9fd2c 100644 --- a/models/consistency.go +++ b/models/consistency.go @@ -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, }) } diff --git a/models/error.go b/models/error.go index 36c70e49a..20ed7f90e 100644 --- a/models/error.go +++ b/models/error.go @@ -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 diff --git a/models/fixture_generation.go b/models/fixture_generation.go index c87909d01..56baa1c34 100644 --- a/models/fixture_generation.go +++ b/models/fixture_generation.go @@ -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 } } diff --git a/models/gpg_key_commit_verification.go b/models/gpg_key_commit_verification.go index 5eeeb69ef..48f58c07b 100644 --- a/models/gpg_key_commit_verification.go +++ b/models/gpg_key_commit_verification.go @@ -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" } diff --git a/models/helper.go b/models/helper.go index 41dd1ccd5..15df42453 100644 --- a/models/helper.go +++ b/models/helper.go @@ -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 -} diff --git a/models/helper_environment.go b/models/helper_environment.go index 3e98f60ff..57ec3ea1e 100644 --- a/models/helper_environment.go +++ b/models/helper_environment.go @@ -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" diff --git a/models/issue.go b/models/issue.go index 58649c754..595f0c942 100644 --- a/models/issue.go +++ b/models/issue.go @@ -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) } diff --git a/models/issue_assignees.go b/models/issue_assignees.go index 527549171..b3511f8b5 100644 --- a/models/issue_assignees.go +++ b/models/issue_assignees.go @@ -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) } diff --git a/models/issue_comment.go b/models/issue_comment.go index 417caccfa..754fa3439 100644 --- a/models/issue_comment.go +++ b/models/issue_comment.go @@ -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 { diff --git a/models/issue_comment_list.go b/models/issue_comment_list.go index ef6aff9cb..23a2756dc 100644 --- a/models/issue_comment_list.go +++ b/models/issue_comment_list.go @@ -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 diff --git a/models/issue_comment_test.go b/models/issue_comment_test.go index 5ab4892bc..ec318688e 100644 --- a/models/issue_comment_test.go +++ b/models/issue_comment_test.go @@ -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() diff --git a/models/issue_dependency.go b/models/issue_dependency.go index 9fef652b4..d2c5785b9 100644 --- a/models/issue_dependency.go +++ b/models/issue_dependency.go @@ -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 -} diff --git a/models/issue_label.go b/models/issue_label.go index 9b36d8dfd..53d28c059 100644 --- a/models/issue_label.go +++ b/models/issue_label.go @@ -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 } diff --git a/models/issue_label_test.go b/models/issue_label_test.go index aa3c92b28..887f7f142 100644 --- a/models/issue_label_test.go +++ b/models/issue_label_test.go @@ -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) { diff --git a/models/issue_list.go b/models/issue_list.go index 7c98f60b3..5d8a9f692 100644 --- a/models/issue_list.go +++ b/models/issue_list.go @@ -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)) } diff --git a/models/issue_milestone.go b/models/issue_milestone.go index a85c86546..f0949e8b1 100644 --- a/models/issue_milestone.go +++ b/models/issue_milestone.go @@ -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 } diff --git a/models/issue_milestone_test.go b/models/issue_milestone_test.go index 21d90a611..9b40144e6 100644 --- a/models/issue_milestone_test.go +++ b/models/issue_milestone_test.go @@ -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) diff --git a/models/issue_reaction.go b/models/issue_reaction.go index fb34db4ed..4072733a1 100644 --- a/models/issue_reaction.go +++ b/models/issue_reaction.go @@ -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) } diff --git a/models/issue_reaction_test.go b/models/issue_reaction_test.go index 458250ac5..886d19e55 100644 --- a/models/issue_reaction_test.go +++ b/models/issue_reaction_test.go @@ -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) diff --git a/models/issue_stopwatch.go b/models/issue_stopwatch.go index 7754e90a8..530a52421 100644 --- a/models/issue_stopwatch.go +++ b/models/issue_stopwatch.go @@ -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 } diff --git a/models/issue_test.go b/models/issue_test.go index a9e19438d..eadeb66ab 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -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) diff --git a/models/issue_tracked_time.go b/models/issue_tracked_time.go index 392bf91e1..c887baae1 100644 --- a/models/issue_tracked_time.go +++ b/models/issue_tracked_time.go @@ -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 } diff --git a/models/issue_user.go b/models/issue_user.go index b112441e5..0b1f8204b 100644 --- a/models/issue_user.go +++ b/models/issue_user.go @@ -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. diff --git a/models/issue_user_test.go b/models/issue_user_test.go index daa68d731..946da6e18 100644 --- a/models/issue_user_test.go +++ b/models/issue_user_test.go @@ -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}) diff --git a/models/issue_xref.go b/models/issue_xref.go index ceaff62be..fdabedf29 100644 --- a/models/issue_xref.go +++ b/models/issue_xref.go @@ -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 } diff --git a/models/issue_xref_test.go b/models/issue_xref_test.go index 06f937c80..9b1cb5e2d 100644 --- a/models/issue_xref_test.go +++ b/models/issue_xref_test.go @@ -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} diff --git a/models/lfs.go b/models/lfs.go index da5e61ed0..56924ffcf 100644 --- a/models/lfs.go +++ b/models/lfs.go @@ -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 +} diff --git a/models/lfs_lock.go b/models/lfs_lock.go index 7cd8e1279..a77dd24e9 100644 --- a/models/lfs_lock.go +++ b/models/lfs_lock.go @@ -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} } diff --git a/models/main_test.go b/models/main_test.go index 87e59f5b1..20107eab1 100644 --- a/models/main_test.go +++ b/models/main_test.go @@ -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{}, diff --git a/models/notification.go b/models/notification.go index ef8a1e83b..b71973823 100644 --- a/models/notification.go +++ b/models/notification.go @@ -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() diff --git a/models/org.go b/models/org.go index becfa4cb0..e5cd80ab7 100644 --- a/models/org.go +++ b/models/org.go @@ -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 } diff --git a/models/org_team.go b/models/org_team.go index dc16fa503..c42312323 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -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 } } diff --git a/models/org_team_test.go b/models/org_team_test.go index 084e376cc..59b7b6d5a 100644 --- a/models/org_team_test.go +++ b/models/org_team_test.go @@ -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) diff --git a/models/org_test.go b/models/org_test.go index c24064c5b..ec324cb71 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -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) } diff --git a/models/project_issue.go b/models/project_issue.go index c1421485b..c7735addc 100644 --- a/models/project_issue.go +++ b/models/project_issue.go @@ -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 } diff --git a/models/protected_tag.go b/models/protected_tag.go index 93318300e..c9cc0fa1b 100644 --- a/models/protected_tag.go +++ b/models/protected_tag.go @@ -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) -} diff --git a/models/protected_tag_test.go b/models/protected_tag_test.go index ed838483d..bbd508609 100644 --- a/models/protected_tag_test.go +++ b/models/protected_tag_test.go @@ -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) } diff --git a/models/pull.go b/models/pull.go index aa58322bc..243d40b1f 100644 --- a/models/pull.go +++ b/models/pull.go @@ -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) diff --git a/models/pull_test.go b/models/pull_test.go index 2281dbffd..f5e9d486f 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -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) diff --git a/models/release.go b/models/release.go index f60024c71..a19d4f937 100644 --- a/models/release.go +++ b/models/release.go @@ -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 } diff --git a/models/repo.go b/models/repo.go index 4f6b1c346..6bdc4c20d 100644 --- a/models/repo.go +++ b/models/repo.go @@ -7,11 +7,7 @@ package models import ( "context" - "errors" "fmt" - "html/template" - "net" - "net/url" "os" "path" "path/filepath" @@ -32,22 +28,15 @@ import ( "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/options" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/storage" api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" "xorm.io/builder" ) -var ( - // ErrMirrorNotExist mirror does not exist error - ErrMirrorNotExist = errors.New("Mirror does not exist") -) - var ( // Gitignores contains the gitiginore files Gitignores []string @@ -137,241 +126,16 @@ func NewRepoContext() { admin_model.RemoveAllWithNotice(db.DefaultContext, "Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp")) } -// RepositoryStatus defines the status of repository -type RepositoryStatus int - -// all kinds of RepositoryStatus -const ( - RepositoryReady RepositoryStatus = iota // a normal repository - RepositoryBeingMigrated // repository is migrating - RepositoryPendingTransfer // repository pending in ownership transfer state - RepositoryBroken // repository is in a permanently broken state -) - -// TrustModelType defines the types of trust model for this repository -type TrustModelType int - -// kinds of TrustModel -const ( - DefaultTrustModel TrustModelType = iota // default trust model - CommitterTrustModel - CollaboratorTrustModel - CollaboratorCommitterTrustModel -) - -// String converts a TrustModelType to a string -func (t TrustModelType) String() string { - switch t { - case DefaultTrustModel: - return "default" - case CommitterTrustModel: - return "committer" - case CollaboratorTrustModel: - return "collaborator" - case CollaboratorCommitterTrustModel: - return "collaboratorcommitter" - } - return "default" +// CheckRepoUnitUser check whether user could visit the unit of this repository +func CheckRepoUnitUser(repo *repo_model.Repository, user *user_model.User, unitType unit.Type) bool { + return checkRepoUnitUser(db.DefaultContext, repo, user, unitType) } -// ToTrustModel converts a string to a TrustModelType -func ToTrustModel(model string) TrustModelType { - switch strings.ToLower(strings.TrimSpace(model)) { - case "default": - return DefaultTrustModel - case "collaborator": - return CollaboratorTrustModel - case "committer": - return CommitterTrustModel - case "collaboratorcommitter": - return CollaboratorCommitterTrustModel - } - return DefaultTrustModel -} - -// Repository represents a git repository. -type Repository struct { - ID int64 `xorm:"pk autoincr"` - OwnerID int64 `xorm:"UNIQUE(s) index"` - OwnerName string - Owner *user_model.User `xorm:"-"` - LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"` - Name string `xorm:"INDEX NOT NULL"` - Description string `xorm:"TEXT"` - Website string `xorm:"VARCHAR(2048)"` - OriginalServiceType api.GitServiceType `xorm:"index"` - OriginalURL string `xorm:"VARCHAR(2048)"` - DefaultBranch string - - NumWatches int - NumStars int - NumForks int - NumIssues int - NumClosedIssues int - NumOpenIssues int `xorm:"-"` - NumPulls int - NumClosedPulls int - NumOpenPulls int `xorm:"-"` - NumMilestones int `xorm:"NOT NULL DEFAULT 0"` - NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"` - NumOpenMilestones int `xorm:"-"` - NumProjects int `xorm:"NOT NULL DEFAULT 0"` - NumClosedProjects int `xorm:"NOT NULL DEFAULT 0"` - NumOpenProjects int `xorm:"-"` - - IsPrivate bool `xorm:"INDEX"` - IsEmpty bool `xorm:"INDEX"` - IsArchived bool `xorm:"INDEX"` - IsMirror bool `xorm:"INDEX"` - *Mirror `xorm:"-"` - PushMirrors []*PushMirror `xorm:"-"` - Status RepositoryStatus `xorm:"NOT NULL DEFAULT 0"` - - RenderingMetas map[string]string `xorm:"-"` - DocumentRenderingMetas map[string]string `xorm:"-"` - Units []*RepoUnit `xorm:"-"` - PrimaryLanguage *LanguageStat `xorm:"-"` - - IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"` - ForkID int64 `xorm:"INDEX"` - BaseRepo *Repository `xorm:"-"` - IsTemplate bool `xorm:"INDEX NOT NULL DEFAULT false"` - TemplateID int64 `xorm:"INDEX"` - TemplateRepo *Repository `xorm:"-"` - Size int64 `xorm:"NOT NULL DEFAULT 0"` - CodeIndexerStatus *RepoIndexerStatus `xorm:"-"` - StatsIndexerStatus *RepoIndexerStatus `xorm:"-"` - IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"` - CloseIssuesViaCommitInAnyBranch bool `xorm:"NOT NULL DEFAULT false"` - Topics []string `xorm:"TEXT JSON"` - - TrustModel TrustModelType - - // Avatar: ID(10-20)-md5(32) - must fit into 64 symbols - Avatar string `xorm:"VARCHAR(64)"` - - CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` - UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` -} - -func init() { - db.RegisterModel(new(Repository)) -} - -// SanitizedOriginalURL returns a sanitized OriginalURL -func (repo *Repository) SanitizedOriginalURL() string { - if repo.OriginalURL == "" { - return "" - } - u, err := url.Parse(repo.OriginalURL) - if err != nil { - return "" - } - u.User = nil - return u.String() -} - -// ColorFormat returns a colored string to represent this repo -func (repo *Repository) ColorFormat(s fmt.State) { - log.ColorFprintf(s, "%d:%s/%s", - log.NewColoredIDValue(repo.ID), - repo.OwnerName, - repo.Name) -} - -// IsBeingMigrated indicates that repository is being migrated -func (repo *Repository) IsBeingMigrated() bool { - return repo.Status == RepositoryBeingMigrated -} - -// IsBeingCreated indicates that repository is being migrated or forked -func (repo *Repository) IsBeingCreated() bool { - return repo.IsBeingMigrated() -} - -// IsBroken indicates that repository is broken -func (repo *Repository) IsBroken() bool { - return repo.Status == RepositoryBroken -} - -// AfterLoad is invoked from XORM after setting the values of all fields of this object. -func (repo *Repository) AfterLoad() { - // FIXME: use models migration to solve all at once. - if len(repo.DefaultBranch) == 0 { - repo.DefaultBranch = setting.Repository.DefaultBranch - } - - repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues - repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls - repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones - repo.NumOpenProjects = repo.NumProjects - repo.NumClosedProjects -} - -// MustOwner always returns a valid *user_model.User object to avoid -// conceptually impossible error handling. -// It creates a fake object that contains error details -// when error occurs. -func (repo *Repository) MustOwner() *user_model.User { - return repo.mustOwner(db.GetEngine(db.DefaultContext)) -} - -// FullName returns the repository full name -func (repo *Repository) FullName() string { - return repo.OwnerName + "/" + repo.Name -} - -// HTMLURL returns the repository HTML URL -func (repo *Repository) HTMLURL() string { - return setting.AppURL + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) -} - -// CommitLink make link to by commit full ID -// note: won't check whether it's an right id -func (repo *Repository) CommitLink(commitID string) (result string) { - if commitID == "" || commitID == "0000000000000000000000000000000000000000" { - result = "" - } else { - result = repo.HTMLURL() + "/commit/" + url.PathEscape(commitID) - } - return -} - -// APIURL returns the repository API URL -func (repo *Repository) APIURL() string { - return setting.AppURL + "api/v1/repos/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) -} - -// GetCommitsCountCacheKey returns cache key used for commits count caching. -func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) string { - var prefix string - if isRef { - prefix = "ref" - } else { - prefix = "commit" - } - return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName) -} - -func (repo *Repository) getUnits(e db.Engine) (err error) { - if repo.Units != nil { - return nil - } - - repo.Units, err = getUnitsByRepoID(e, repo.ID) - log.Trace("repo.Units: %-+v", repo.Units) - return err -} - -// CheckUnitUser check whether user could visit the unit of this repository -func (repo *Repository) CheckUnitUser(user *user_model.User, unitType unit.Type) bool { - return repo.checkUnitUser(db.GetEngine(db.DefaultContext), user, unitType) -} - -func (repo *Repository) checkUnitUser(e db.Engine, user *user_model.User, unitType unit.Type) bool { +func checkRepoUnitUser(ctx context.Context, repo *repo_model.Repository, user *user_model.User, unitType unit.Type) bool { if user.IsAdmin { return true } - perm, err := getUserRepoPermission(e, repo, user) + perm, err := getUserRepoPermission(ctx, repo, user) if err != nil { log.Error("getUserRepoPermission(): %v", err) return false @@ -380,167 +144,12 @@ func (repo *Repository) checkUnitUser(e db.Engine, user *user_model.User, unitTy return perm.CanRead(unitType) } -// UnitEnabled if this repository has the given unit enabled -func (repo *Repository) UnitEnabled(tp unit.Type) bool { - if err := repo.getUnits(db.GetEngine(db.DefaultContext)); err != nil { - log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error()) - } - for _, unit := range repo.Units { - if unit.Type == tp { - return true - } - } - return false -} - -// ErrUnitTypeNotExist represents a "UnitTypeNotExist" kind of error. -type ErrUnitTypeNotExist struct { - UT unit.Type -} - -// IsErrUnitTypeNotExist checks if an error is a ErrUnitNotExist. -func IsErrUnitTypeNotExist(err error) bool { - _, ok := err.(ErrUnitTypeNotExist) - return ok -} - -func (err ErrUnitTypeNotExist) Error() string { - return fmt.Sprintf("Unit type does not exist: %s", err.UT.String()) -} - -// MustGetUnit always returns a RepoUnit object -func (repo *Repository) MustGetUnit(tp unit.Type) *RepoUnit { - ru, err := repo.GetUnit(tp) - if err == nil { - return ru - } - - if tp == unit.TypeExternalWiki { - return &RepoUnit{ - Type: tp, - Config: new(ExternalWikiConfig), - } - } else if tp == unit.TypeExternalTracker { - return &RepoUnit{ - Type: tp, - Config: new(ExternalTrackerConfig), - } - } else if tp == unit.TypePullRequests { - return &RepoUnit{ - Type: tp, - Config: new(PullRequestsConfig), - } - } else if tp == unit.TypeIssues { - return &RepoUnit{ - Type: tp, - Config: new(IssuesConfig), - } - } - return &RepoUnit{ - Type: tp, - Config: new(UnitConfig), - } -} - -// GetUnit returns a RepoUnit object -func (repo *Repository) GetUnit(tp unit.Type) (*RepoUnit, error) { - return repo.getUnit(db.GetEngine(db.DefaultContext), tp) -} - -func (repo *Repository) getUnit(e db.Engine, tp unit.Type) (*RepoUnit, error) { - if err := repo.getUnits(e); err != nil { - return nil, err - } - for _, unit := range repo.Units { - if unit.Type == tp { - return unit, nil - } - } - return nil, ErrUnitTypeNotExist{tp} -} - -func (repo *Repository) getOwner(e db.Engine) (err error) { - if repo.Owner != nil { - return nil - } - - repo.Owner, err = user_model.GetUserByIDEngine(e, repo.OwnerID) - return err -} - -// GetOwner returns the repository owner -func (repo *Repository) GetOwner() error { - return repo.getOwner(db.GetEngine(db.DefaultContext)) -} - -func (repo *Repository) mustOwner(e db.Engine) *user_model.User { - if err := repo.getOwner(e); err != nil { - return &user_model.User{ - Name: "error", - FullName: err.Error(), - } - } - - return repo.Owner -} - -// ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers. -func (repo *Repository) ComposeMetas() map[string]string { - if len(repo.RenderingMetas) == 0 { - metas := map[string]string{ - "user": repo.OwnerName, - "repo": repo.Name, - "repoPath": repo.RepoPath(), - "mode": "comment", - } - - unit, err := repo.GetUnit(unit.TypeExternalTracker) - if err == nil { - metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat - switch unit.ExternalTrackerConfig().ExternalTrackerStyle { - case markup.IssueNameStyleAlphanumeric: - metas["style"] = markup.IssueNameStyleAlphanumeric - default: - metas["style"] = markup.IssueNameStyleNumeric - } - } - - repo.MustOwner() - if repo.Owner.IsOrganization() { - teams := make([]string, 0, 5) - _ = db.GetEngine(db.DefaultContext).Table("team_repo"). - Join("INNER", "team", "team.id = team_repo.team_id"). - Where("team_repo.repo_id = ?", repo.ID). - Select("team.lower_name"). - OrderBy("team.lower_name"). - Find(&teams) - metas["teams"] = "," + strings.Join(teams, ",") + "," - metas["org"] = strings.ToLower(repo.OwnerName) - } - - repo.RenderingMetas = metas - } - return repo.RenderingMetas -} - -// ComposeDocumentMetas composes a map of metas for properly rendering documents -func (repo *Repository) ComposeDocumentMetas() map[string]string { - if len(repo.DocumentRenderingMetas) == 0 { - metas := map[string]string{} - for k, v := range repo.ComposeMetas() { - metas[k] = v - } - metas["mode"] = "document" - repo.DocumentRenderingMetas = metas - } - return repo.DocumentRenderingMetas -} - -func (repo *Repository) getAssignees(e db.Engine) (_ []*user_model.User, err error) { - if err = repo.getOwner(e); err != nil { +func getRepoAssignees(ctx context.Context, repo *repo_model.Repository) (_ []*user_model.User, err error) { + if err = repo.GetOwner(ctx); err != nil { return nil, err } + e := db.GetEngine(ctx) accesses := make([]*Access, 0, 10) if err = e. Where("repo_id = ? AND mode >= ?", repo.ID, perm.AccessModeWrite). @@ -568,19 +177,20 @@ func (repo *Repository) getAssignees(e db.Engine) (_ []*user_model.User, err err return users, nil } -// GetAssignees returns all users that have write access and can be assigned to issues +// GetRepoAssignees returns all users that have write access and can be assigned to issues // of the repository, -func (repo *Repository) GetAssignees() (_ []*user_model.User, err error) { - return repo.getAssignees(db.GetEngine(db.DefaultContext)) +func GetRepoAssignees(repo *repo_model.Repository) (_ []*user_model.User, err error) { + return getRepoAssignees(db.DefaultContext, repo) } -func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*user_model.User, error) { +func getReviewers(ctx context.Context, repo *repo_model.Repository, doerID, posterID int64) ([]*user_model.User, error) { // Get the owner of the repository - this often already pre-cached and if so saves complexity for the following queries - if err := repo.getOwner(e); err != nil { + if err := repo.GetOwner(ctx); err != nil { return nil, err } var users []*user_model.User + e := db.GetEngine(ctx) if repo.IsPrivate || repo.Owner.Visibility == api.VisibleTypePrivate { // This a private repository: @@ -622,13 +232,13 @@ func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*us // * for public repositories this returns all users that have read access or higher to the repository, // all repo watchers and all organization members. // TODO: may be we should have a busy choice for users to block review request to them. -func (repo *Repository) GetReviewers(doerID, posterID int64) ([]*user_model.User, error) { - return repo.getReviewers(db.GetEngine(db.DefaultContext), doerID, posterID) +func GetReviewers(repo *repo_model.Repository, doerID, posterID int64) ([]*user_model.User, error) { + return getReviewers(db.DefaultContext, repo, doerID, posterID) } // GetReviewerTeams get all teams can be requested to review -func (repo *Repository) GetReviewerTeams() ([]*Team, error) { - if err := repo.GetOwner(); err != nil { +func GetReviewerTeams(repo *repo_model.Repository) ([]*Team, error) { + if err := repo.GetOwner(db.DefaultContext); err != nil { return nil, err } if !repo.Owner.IsOrganization() { @@ -643,102 +253,7 @@ func (repo *Repository) GetReviewerTeams() ([]*Team, error) { return teams, err } -// GetMilestoneByID returns the milestone belongs to repository by given ID. -func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) { - return GetMilestoneByRepoID(repo.ID, milestoneID) -} - -// IssueStats returns number of open and closed repository issues by given filter mode. -func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) { - return GetRepoIssueStats(repo.ID, uid, filterMode, isPull) -} - -// GetMirror sets the repository mirror, returns an error upon failure -func (repo *Repository) GetMirror() (err error) { - repo.Mirror, err = GetMirrorByRepoID(repo.ID) - return err -} - -// LoadPushMirrors populates the repository push mirrors. -func (repo *Repository) LoadPushMirrors() (err error) { - repo.PushMirrors, err = GetPushMirrorsByRepoID(repo.ID) - return err -} - -// GetBaseRepo populates repo.BaseRepo for a fork repository and -// returns an error on failure (NOTE: no error is returned for -// non-fork repositories, and BaseRepo will be left untouched) -func (repo *Repository) GetBaseRepo() (err error) { - return repo.getBaseRepo(db.GetEngine(db.DefaultContext)) -} - -func (repo *Repository) getBaseRepo(e db.Engine) (err error) { - if !repo.IsFork { - return nil - } - - repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID) - return err -} - -// IsGenerated returns whether _this_ repository was generated from a template -func (repo *Repository) IsGenerated() bool { - return repo.TemplateID != 0 -} - -// GetTemplateRepo populates repo.TemplateRepo for a generated repository and -// returns an error on failure (NOTE: no error is returned for -// non-generated repositories, and TemplateRepo will be left untouched) -func (repo *Repository) GetTemplateRepo() (err error) { - return repo.getTemplateRepo(db.GetEngine(db.DefaultContext)) -} - -func (repo *Repository) getTemplateRepo(e db.Engine) (err error) { - if !repo.IsGenerated() { - return nil - } - - repo.TemplateRepo, err = getRepositoryByID(e, repo.TemplateID) - return err -} - -// RepoPath returns the repository path -func (repo *Repository) RepoPath() string { - return RepoPath(repo.OwnerName, repo.Name) -} - -// GitConfigPath returns the path to a repository's git config/ directory -func GitConfigPath(repoPath string) string { - return filepath.Join(repoPath, "config") -} - -// GitConfigPath returns the repository git config path -func (repo *Repository) GitConfigPath() string { - return GitConfigPath(repo.RepoPath()) -} - -// Link returns the repository link -func (repo *Repository) Link() string { - return setting.AppSubURL + "/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) -} - -// ComposeCompareURL returns the repository comparison URL -func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { - return fmt.Sprintf("%s/%s/compare/%s...%s", url.PathEscape(repo.OwnerName), url.PathEscape(repo.Name), util.PathEscapeSegments(oldCommitID), util.PathEscapeSegments(newCommitID)) -} - -// UpdateDefaultBranch updates the default branch -func (repo *Repository) UpdateDefaultBranch() error { - _, err := db.GetEngine(db.DefaultContext).ID(repo.ID).Cols("default_branch").Update(repo) - return err -} - -// IsOwnedBy returns true when user owns this repository -func (repo *Repository) IsOwnedBy(userID int64) bool { - return repo.OwnerID == userID -} - -func (repo *Repository) updateSize(e db.Engine) error { +func updateRepoSize(e db.Engine, repo *repo_model.Repository) error { size, err := util.GetDirectorySize(repo.RepoPath()) if err != nil { return fmt.Errorf("updateSize: %v", err) @@ -754,13 +269,13 @@ func (repo *Repository) updateSize(e db.Engine) error { return err } -// UpdateSize updates the repository size, calculating it using util.GetDirectorySize -func (repo *Repository) UpdateSize(ctx context.Context) error { - return repo.updateSize(db.GetEngine(ctx)) +// UpdateRepoSize updates the repository size, calculating it using util.GetDirectorySize +func UpdateRepoSize(ctx context.Context, repo *repo_model.Repository) error { + return updateRepoSize(db.GetEngine(ctx), repo) } // CanUserForkRepo returns true if specified user can fork repository. -func CanUserForkRepo(user *user_model.User, repo *Repository) (bool, error) { +func CanUserForkRepo(user *user_model.User, repo *repo_model.Repository) (bool, error) { if user == nil { return false, nil } @@ -780,12 +295,12 @@ func CanUserForkRepo(user *user_model.User, repo *Repository) (bool, error) { } // CanUserDelete returns true if user could delete the repository -func (repo *Repository) CanUserDelete(user *user_model.User) (bool, error) { +func CanUserDelete(repo *repo_model.Repository, user *user_model.User) (bool, error) { if user.IsAdmin || user.ID == repo.OwnerID { return true, nil } - if err := repo.GetOwner(); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { return false, err } @@ -801,33 +316,18 @@ func (repo *Repository) CanUserDelete(user *user_model.User) (bool, error) { return false, nil } -// CanEnablePulls returns true if repository meets the requirements of accepting pulls. -func (repo *Repository) CanEnablePulls() bool { - return !repo.IsMirror && !repo.IsEmpty +// GetRepoReaders returns all users that have explicit read access or higher to the repository. +func GetRepoReaders(repo *repo_model.Repository) (_ []*user_model.User, err error) { + return getUsersWithAccessMode(db.DefaultContext, repo, perm.AccessModeRead) } -// AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled. -func (repo *Repository) AllowsPulls() bool { - return repo.CanEnablePulls() && repo.UnitEnabled(unit.TypePullRequests) +// GetRepoWriters returns all users that have write access to the repository. +func GetRepoWriters(repo *repo_model.Repository) (_ []*user_model.User, err error) { + return getUsersWithAccessMode(db.DefaultContext, repo, perm.AccessModeWrite) } -// CanEnableEditor returns true if repository meets the requirements of web editor. -func (repo *Repository) CanEnableEditor() bool { - return !repo.IsMirror -} - -// GetReaders returns all users that have explicit read access or higher to the repository. -func (repo *Repository) GetReaders() (_ []*user_model.User, err error) { - return repo.getUsersWithAccessMode(db.GetEngine(db.DefaultContext), perm.AccessModeRead) -} - -// GetWriters returns all users that have write access to the repository. -func (repo *Repository) GetWriters() (_ []*user_model.User, err error) { - return repo.getUsersWithAccessMode(db.GetEngine(db.DefaultContext), perm.AccessModeWrite) -} - -// IsReader returns true if user has explicit read access or higher to the repository. -func (repo *Repository) IsReader(userID int64) (bool, error) { +// IsRepoReader returns true if user has explicit read access or higher to the repository. +func IsRepoReader(repo *repo_model.Repository, userID int64) (bool, error) { if repo.OwnerID == userID { return true, nil } @@ -835,11 +335,12 @@ func (repo *Repository) IsReader(userID int64) (bool, error) { } // getUsersWithAccessMode returns users that have at least given access mode to the repository. -func (repo *Repository) getUsersWithAccessMode(e db.Engine, mode perm.AccessMode) (_ []*user_model.User, err error) { - if err = repo.getOwner(e); err != nil { +func getUsersWithAccessMode(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode) (_ []*user_model.User, err error) { + if err = repo.GetOwner(ctx); err != nil { return nil, err } + e := db.GetEngine(ctx) accesses := make([]*Access, 0, 10) if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil { return nil, err @@ -865,88 +366,9 @@ func (repo *Repository) getUsersWithAccessMode(e db.Engine, mode perm.AccessMode return users, nil } -// DescriptionHTML does special handles to description and return HTML string. -func (repo *Repository) DescriptionHTML() template.HTML { - desc, err := markup.RenderDescriptionHTML(&markup.RenderContext{ - URLPrefix: repo.HTMLURL(), - Metas: repo.ComposeMetas(), - }, repo.Description) - if err != nil { - log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err) - return template.HTML(markup.Sanitize(repo.Description)) - } - return template.HTML(markup.Sanitize(string(desc))) -} - -// ReadBy sets repo to be visited by given user. -func (repo *Repository) ReadBy(userID int64) error { - return setRepoNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, repo.ID) -} - -func isRepositoryExist(e db.Engine, u *user_model.User, repoName string) (bool, error) { - has, err := e.Get(&Repository{ - OwnerID: u.ID, - LowerName: strings.ToLower(repoName), - }) - if err != nil { - return false, err - } - isDir, err := util.IsDir(RepoPath(u.Name, repoName)) - return has && isDir, err -} - -// IsRepositoryExist returns true if the repository with given name under user has already existed. -func IsRepositoryExist(u *user_model.User, repoName string) (bool, error) { - return isRepositoryExist(db.GetEngine(db.DefaultContext), u, repoName) -} - -// CloneLink represents different types of clone URLs of repository. -type CloneLink struct { - SSH string - HTTPS string - Git string -} - -// ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name. -func ComposeHTTPSCloneURL(owner, repo string) string { - return fmt.Sprintf("%s%s/%s.git", setting.AppURL, url.PathEscape(owner), url.PathEscape(repo)) -} - -func (repo *Repository) cloneLink(isWiki bool) *CloneLink { - repoName := repo.Name - if isWiki { - repoName += ".wiki" - } - - sshUser := setting.RunUser - if setting.SSH.StartBuiltinServer { - sshUser = setting.SSH.BuiltinServerUser - } - - cl := new(CloneLink) - - // if we have a ipv6 literal we need to put brackets around it - // for the git cloning to work. - sshDomain := setting.SSH.Domain - ip := net.ParseIP(setting.SSH.Domain) - if ip != nil && ip.To4() == nil { - sshDomain = "[" + setting.SSH.Domain + "]" - } - - if setting.SSH.Port != 22 { - cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, net.JoinHostPort(setting.SSH.Domain, strconv.Itoa(setting.SSH.Port)), url.PathEscape(repo.OwnerName), url.PathEscape(repoName)) - } else if setting.Repository.UseCompatSSHURI { - cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, sshDomain, url.PathEscape(repo.OwnerName), url.PathEscape(repoName)) - } else { - cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, sshDomain, url.PathEscape(repo.OwnerName), url.PathEscape(repoName)) - } - cl.HTTPS = ComposeHTTPSCloneURL(repo.OwnerName, repoName) - return cl -} - -// CloneLink returns clone URLs of repository. -func (repo *Repository) CloneLink() (cl *CloneLink) { - return repo.cloneLink(false) +// SetRepoReadBy sets repo to be visited by given user. +func SetRepoReadBy(repoID, userID int64) error { + return setRepoNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, repoID) } // CheckCreateRepository check if could created a repository @@ -959,16 +381,17 @@ func CheckCreateRepository(doer, u *user_model.User, name string, overwriteOrAdo return err } - has, err := isRepositoryExist(db.GetEngine(db.DefaultContext), u, name) + has, err := repo_model.IsRepositoryExist(u, name) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { return ErrRepoAlreadyExist{u.Name, name} } - isExist, err := util.IsExist(RepoPath(u.Name, name)) + repoPath := repo_model.RepoPath(u.Name, name) + isExist, err := util.IsExist(repoPath) if err != nil { - log.Error("Unable to check if %s exists. Error: %v", RepoPath(u.Name, name), err) + log.Error("Unable to check if %s exists. Error: %v", repoPath, err) return err } if !overwriteOrAdopt && isExist { @@ -992,14 +415,14 @@ type CreateRepoOptions struct { IsMirror bool IsTemplate bool AutoInit bool - Status RepositoryStatus - TrustModel TrustModelType + Status repo_model.RepositoryStatus + TrustModel repo_model.TrustModelType MirrorInterval string } // ForkRepoOptions contains the fork repository options type ForkRepoOptions struct { - BaseRepo *Repository + BaseRepo *repo_model.Repository Name string Description string } @@ -1048,19 +471,19 @@ func IsUsableRepoName(name string) error { } // CreateRepository creates a repository for the user/organization. -func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *Repository, overwriteOrAdopt bool) (err error) { +func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository, overwriteOrAdopt bool) (err error) { if err = IsUsableRepoName(repo.Name); err != nil { return err } - has, err := isRepositoryExist(db.GetEngine(ctx), u, repo.Name) + has, err := repo_model.IsRepositoryExistCtx(ctx, u, repo.Name) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { return ErrRepoAlreadyExist{u.Name, repo.Name} } - repoPath := RepoPath(u.Name, repo.Name) + repoPath := repo_model.RepoPath(u.Name, repo.Name) isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) @@ -1074,7 +497,7 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *Repos } } - if _, err = db.GetEngine(ctx).Insert(repo); err != nil { + if err = db.Insert(ctx, repo); err != nil { return err } if err = deleteRepoRedirect(db.GetEngine(ctx), u.ID, repo.Name); err != nil { @@ -1082,33 +505,33 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *Repos } // insert units for repo - units := make([]RepoUnit, 0, len(unit.DefaultRepoUnits)) + units := make([]repo_model.RepoUnit, 0, len(unit.DefaultRepoUnits)) for _, tp := range unit.DefaultRepoUnits { if tp == unit.TypeIssues { - units = append(units, RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: tp, - Config: &IssuesConfig{ + Config: &repo_model.IssuesConfig{ EnableTimetracker: setting.Service.DefaultEnableTimetracking, AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime, EnableDependencies: setting.Service.DefaultEnableDependencies, }, }) } else if tp == unit.TypePullRequests { - units = append(units, RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: tp, - Config: &PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true, DefaultMergeStyle: MergeStyleMerge}, + Config: &repo_model.PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true, DefaultMergeStyle: repo_model.MergeStyleMerge}, }) } else { - units = append(units, RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: tp, }) } } - if _, err = db.GetEngine(ctx).Insert(&units); err != nil { + if err = db.Insert(ctx, units); err != nil { return err } @@ -1131,7 +554,7 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *Repos } for _, t := range teams { if t.IncludesAllRepositories { - if err := t.addRepository(db.GetEngine(ctx), repo); err != nil { + if err := t.addRepository(ctx, repo); err != nil { return fmt.Errorf("addRepository: %v", err) } } @@ -1141,14 +564,14 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *Repos return fmt.Errorf("isUserRepoAdmin: %v", err) } else if !isAdmin { // Make creator repo admin if it wan't assigned automatically - if err = repo.addCollaborator(db.GetEngine(ctx), doer); err != nil { + if err = addCollaborator(ctx, repo, doer); err != nil { return fmt.Errorf("AddCollaborator: %v", err) } - if err = repo.changeCollaborationAccessMode(db.GetEngine(ctx), doer.ID, perm.AccessModeAdmin); err != nil { + if err = changeCollaborationAccessMode(db.GetEngine(ctx), repo, doer.ID, perm.AccessModeAdmin); err != nil { return fmt.Errorf("ChangeCollaborationAccessMode: %v", err) } } - } else if err = repo.recalculateAccesses(db.GetEngine(ctx)); err != nil { + } else if err = recalculateAccesses(ctx, repo); err != nil { // Organization automatically called this in addRepository method. return fmt.Errorf("recalculateAccesses: %v", err) } @@ -1167,9 +590,8 @@ func CreateRepository(ctx context.Context, doer, u *user_model.User, repo *Repos } // CheckDaemonExportOK creates/removes git-daemon-export-ok for git-daemon... -func (repo *Repository) CheckDaemonExportOK(ctx context.Context) error { - e := db.GetEngine(ctx) - if err := repo.getOwner(e); err != nil { +func CheckDaemonExportOK(ctx context.Context, repo *repo_model.Repository) error { + if err := repo.GetOwner(ctx); err != nil { return err } @@ -1198,42 +620,6 @@ func (repo *Repository) CheckDaemonExportOK(ctx context.Context) error { return nil } -func countRepositories(userID int64, private bool) int64 { - sess := db.GetEngine(db.DefaultContext).Where("id > 0") - - if userID > 0 { - sess.And("owner_id = ?", userID) - } - if !private { - sess.And("is_private=?", false) - } - - count, err := sess.Count(new(Repository)) - if err != nil { - log.Error("countRepositories: %v", err) - } - return count -} - -// CountRepositories returns number of repositories. -// Argument private only takes effect when it is false, -// set it true to count all repositories. -func CountRepositories(private bool) int64 { - return countRepositories(-1, private) -} - -// CountUserRepositories returns number of repositories user owns. -// Argument private only takes effect when it is false, -// set it true to count all repositories. -func CountUserRepositories(userID int64, private bool) int64 { - return countRepositories(userID, private) -} - -// RepoPath returns repository path by given user and repository name. -func RepoPath(userName, repoName string) string { - return filepath.Join(user_model.UserPath(userName), strings.ToLower(repoName)+".git") -} - // IncrementRepoForkNum increment repository fork number func IncrementRepoForkNum(ctx context.Context, repoID int64) error { _, err := db.GetEngine(ctx).Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID) @@ -1247,25 +633,25 @@ func DecrementRepoForkNum(ctx context.Context, repoID int64) error { } // ChangeRepositoryName changes all corresponding setting from old repository name to new one. -func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName string) (err error) { +func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, newRepoName string) (err error) { oldRepoName := repo.Name newRepoName = strings.ToLower(newRepoName) if err = IsUsableRepoName(newRepoName); err != nil { return err } - if err := repo.GetOwner(); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { return err } - has, err := IsRepositoryExist(repo.Owner, newRepoName) + has, err := repo_model.IsRepositoryExist(repo.Owner, newRepoName) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { return ErrRepoAlreadyExist{repo.Owner.Name, newRepoName} } - newRepoPath := RepoPath(repo.Owner.Name, newRepoName) + newRepoPath := repo_model.RepoPath(repo.Owner.Name, newRepoName) if err = util.Rename(repo.RepoPath(), newRepoPath); err != nil { return fmt.Errorf("rename repository directory: %v", err) } @@ -1277,7 +663,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName s return err } if isExist { - if err = util.Rename(wikiPath, WikiPath(repo.Owner.Name, newRepoName)); err != nil { + if err = util.Rename(wikiPath, repo_model.WikiPath(repo.Owner.Name, newRepoName)); err != nil { return fmt.Errorf("rename repository wiki: %v", err) } } @@ -1295,19 +681,19 @@ func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName s return committer.Commit() } -func getRepositoriesByForkID(e db.Engine, forkID int64) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) +func getRepositoriesByForkID(e db.Engine, forkID int64) ([]*repo_model.Repository, error) { + repos := make([]*repo_model.Repository, 0, 10) return repos, e. Where("fork_id=?", forkID). Find(&repos) } // GetRepositoriesByForkID returns all repositories with given fork ID. -func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) { +func GetRepositoriesByForkID(forkID int64) ([]*repo_model.Repository, error) { return getRepositoriesByForkID(db.GetEngine(db.DefaultContext), forkID) } -func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (err error) { +func updateRepository(ctx context.Context, repo *repo_model.Repository, visibilityChanged bool) (err error) { repo.LowerName = strings.ToLower(repo.Name) if utf8.RuneCountInString(repo.Description) > 255 { @@ -1317,21 +703,23 @@ func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (er repo.Website = string([]rune(repo.Website)[:255]) } + e := db.GetEngine(ctx) + if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil { return fmt.Errorf("update: %v", err) } - if err = repo.updateSize(e); err != nil { + if err = updateRepoSize(e, repo); err != nil { log.Error("Failed to update size for repository: %v", err) } if visibilityChanged { - if err = repo.getOwner(e); err != nil { + if err = repo.GetOwner(ctx); err != nil { return fmt.Errorf("getOwner: %v", err) } if repo.Owner.IsOrganization() { // Organization repository need to recalculate access table when visibility is changed. - if err = repo.recalculateTeamAccesses(e, 0); err != nil { + if err = recalculateTeamAccesses(ctx, repo, 0); err != nil { return fmt.Errorf("recalculateTeamAccesses: %v", err) } } @@ -1347,7 +735,7 @@ func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (er } // Create/Remove git-daemon-export-ok for git-daemon... - if err := repo.CheckDaemonExportOK(db.WithEngine(db.DefaultContext, e)); err != nil { + if err := CheckDaemonExportOK(db.WithEngine(ctx, e), repo); err != nil { return err } @@ -1357,7 +745,7 @@ func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (er } for i := range forkRepos { forkRepos[i].IsPrivate = repo.IsPrivate || repo.Owner.Visibility == api.VisibleTypePrivate - if err = updateRepository(e, forkRepos[i], true); err != nil { + if err = updateRepository(ctx, forkRepos[i], true); err != nil { return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err) } } @@ -1367,19 +755,19 @@ func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (er } // UpdateRepositoryCtx updates a repository with db context -func UpdateRepositoryCtx(ctx context.Context, repo *Repository, visibilityChanged bool) error { - return updateRepository(db.GetEngine(ctx), repo, visibilityChanged) +func UpdateRepositoryCtx(ctx context.Context, repo *repo_model.Repository, visibilityChanged bool) error { + return updateRepository(ctx, repo, visibilityChanged) } // UpdateRepository updates a repository -func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) { +func UpdateRepository(repo *repo_model.Repository, visibilityChanged bool) (err error) { ctx, committer, err := db.TxContext() if err != nil { return err } defer committer.Close() - if err = updateRepository(db.GetEngine(ctx), repo, visibilityChanged); err != nil { + if err = updateRepository(ctx, repo, visibilityChanged); err != nil { return fmt.Errorf("updateRepository: %v", err) } @@ -1397,7 +785,7 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { } defer committer.Close() - if _, err := db.GetEngine(ctx).Where("owner_id = ?", ownerID).Cols("owner_name").Update(&Repository{ + if _, err := db.GetEngine(ctx).Where("owner_id = ?", ownerID).Cols("owner_name").Update(&repo_model.Repository{ OwnerName: ownerName, }); err != nil { return err @@ -1413,7 +801,7 @@ func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error { } // UpdateRepositoryUnits updates a repository's units -func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []unit.Type) (err error) { +func UpdateRepositoryUnits(repo *repo_model.Repository, units []repo_model.RepoUnit, deleteUnitTypes []unit.Type) (err error) { ctx, committer, err := db.TxContext() if err != nil { return err @@ -1425,7 +813,7 @@ func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes [ deleteUnitTypes = append(deleteUnitTypes, u.Type) } - if _, err = db.GetEngine(ctx).Where("repo_id = ?", repo.ID).In("type", deleteUnitTypes).Delete(new(RepoUnit)); err != nil { + if _, err = db.GetEngine(ctx).Where("repo_id = ?", repo.ID).In("type", deleteUnitTypes).Delete(new(repo_model.RepoUnit)); err != nil { return err } @@ -1454,12 +842,17 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { return err } - repo := &Repository{OwnerID: uid} + repo := &repo_model.Repository{OwnerID: uid} has, err := sess.ID(repoID).Get(repo) if err != nil { return err } else if !has { - return ErrRepoNotExist{repoID, uid, "", ""} + return repo_model.ErrRepoNotExist{ + ID: repoID, + UID: uid, + OwnerName: "", + Name: "", + } } // Delete Deploy Keys @@ -1468,15 +861,20 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { return fmt.Errorf("listDeployKeys: %v", err) } for _, dKey := range deployKeys { - if err := deleteDeployKey(sess, doer, dKey.ID); err != nil { + if err := deleteDeployKey(ctx, doer, dKey.ID); err != nil { return fmt.Errorf("deleteDeployKeys: %v", err) } } - if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil { + if cnt, err := sess.ID(repoID).Delete(&repo_model.Repository{}); err != nil { return err } else if cnt != 1 { - return ErrRepoNotExist{repoID, uid, "", ""} + return repo_model.ErrRepoNotExist{ + ID: repoID, + UID: uid, + OwnerName: "", + Name: "", + } } if org.IsOrganization() { @@ -1487,7 +885,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { for _, t := range teams { if !t.hasRepository(sess, repoID) { continue - } else if err = t.removeRepository(sess, repo, false); err != nil { + } else if err = t.removeRepository(ctx, repo, false); err != nil { return err } } @@ -1517,18 +915,18 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { &DeletedBranch{RepoID: repoID}, &webhook.HookTask{RepoID: repoID}, &LFSLock{RepoID: repoID}, - &LanguageStat{RepoID: repoID}, + &repo_model.LanguageStat{RepoID: repoID}, &Milestone{RepoID: repoID}, - &Mirror{RepoID: repoID}, + &repo_model.Mirror{RepoID: repoID}, &Notification{RepoID: repoID}, &ProtectedBranch{RepoID: repoID}, &ProtectedTag{RepoID: repoID}, &PullRequest{BaseRepoID: repoID}, - &PushMirror{RepoID: repoID}, + &repo_model.PushMirror{RepoID: repoID}, &Release{RepoID: repoID}, - &RepoIndexerStatus{RepoID: repoID}, + &repo_model.RepoIndexerStatus{RepoID: repoID}, &RepoRedirect{RedirectRepoID: repoID}, - &RepoUnit{RepoID: repoID}, + &repo_model.RepoUnit{RepoID: repoID}, &Star{RepoID: repoID}, &Task{RepoID: repoID}, &Watch{RepoID: repoID}, @@ -1697,132 +1095,6 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { return nil } -// GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. -func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { - return getRepositoryByOwnerAndName(db.GetEngine(db.DefaultContext), ownerName, repoName) -} - -func getRepositoryByOwnerAndName(e db.Engine, ownerName, repoName string) (*Repository, error) { - var repo Repository - has, err := e.Table("repository").Select("repository.*"). - Join("INNER", "`user`", "`user`.id = repository.owner_id"). - Where("repository.lower_name = ?", strings.ToLower(repoName)). - And("`user`.lower_name = ?", strings.ToLower(ownerName)). - Get(&repo) - if err != nil { - return nil, err - } else if !has { - return nil, ErrRepoNotExist{0, 0, ownerName, repoName} - } - return &repo, nil -} - -// GetRepositoryByName returns the repository by given name under user if exists. -func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { - repo := &Repository{ - OwnerID: ownerID, - LowerName: strings.ToLower(name), - } - has, err := db.GetEngine(db.DefaultContext).Get(repo) - if err != nil { - return nil, err - } else if !has { - return nil, ErrRepoNotExist{0, ownerID, "", name} - } - return repo, err -} - -func getRepositoryByID(e db.Engine, id int64) (*Repository, error) { - repo := new(Repository) - has, err := e.ID(id).Get(repo) - if err != nil { - return nil, err - } else if !has { - return nil, ErrRepoNotExist{id, 0, "", ""} - } - return repo, nil -} - -// GetRepositoryByID returns the repository by given id if exists. -func GetRepositoryByID(id int64) (*Repository, error) { - return getRepositoryByID(db.GetEngine(db.DefaultContext), id) -} - -// GetRepositoryByIDCtx returns the repository by given id if exists. -func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { - return getRepositoryByID(db.GetEngine(ctx), id) -} - -// GetRepositoriesMapByIDs returns the repositories by given id slice. -func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { - repos := make(map[int64]*Repository, len(ids)) - return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos) -} - -// GetUserRepositories returns a list of repositories of given user. -func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error) { - if len(opts.OrderBy) == 0 { - opts.OrderBy = "updated_unix DESC" - } - - cond := builder.NewCond() - cond = cond.And(builder.Eq{"owner_id": opts.Actor.ID}) - if !opts.Private { - cond = cond.And(builder.Eq{"is_private": false}) - } - - if opts.LowerNames != nil && len(opts.LowerNames) > 0 { - cond = cond.And(builder.In("lower_name", opts.LowerNames)) - } - - sess := db.GetEngine(db.DefaultContext) - - count, err := sess.Where(cond).Count(new(Repository)) - if err != nil { - return nil, 0, fmt.Errorf("Count: %v", err) - } - - sess = sess.Where(cond).OrderBy(opts.OrderBy.String()) - repos := make([]*Repository, 0, opts.PageSize) - return repos, count, db.SetSessionPagination(sess, opts).Find(&repos) -} - -// GetUserMirrorRepositories returns a list of mirror repositories of given user. -func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, db.GetEngine(db.DefaultContext). - Where("owner_id = ?", userID). - And("is_mirror = ?", true). - Find(&repos) -} - -func getRepositoryCount(e db.Engine, ownerID int64) (int64, error) { - return e.Count(&Repository{OwnerID: ownerID}) -} - -func getPublicRepositoryCount(e db.Engine, u *user_model.User) (int64, error) { - return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID}) -} - -func getPrivateRepositoryCount(e db.Engine, u *user_model.User) (int64, error) { - return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID}) -} - -// GetRepositoryCount returns the total number of repositories of user. -func GetRepositoryCount(ctx context.Context, ownerID int64) (int64, error) { - return getRepositoryCount(db.GetEngine(ctx), ownerID) -} - -// GetPublicRepositoryCount returns the total number of public repositories of user. -func GetPublicRepositoryCount(u *user_model.User) (int64, error) { - return getPublicRepositoryCount(db.GetEngine(db.DefaultContext), u) -} - -// GetPrivateRepositoryCount returns the total number of private repositories of user. -func GetPrivateRepositoryCount(u *user_model.User) (int64, error) { - return getPrivateRepositoryCount(db.GetEngine(db.DefaultContext), u) -} - type repoChecker struct { querySQL, correctSQL string desc string @@ -1958,9 +1230,9 @@ func CheckRepoStats(ctx context.Context) error { } log.Trace("Updating repository count 'num_forks': %d", id) - repo, err := GetRepositoryByID(id) + repo, err := repo_model.GetRepositoryByID(id) if err != nil { - log.Error("GetRepositoryByID[%d]: %v", id, err) + log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err) continue } @@ -1982,7 +1254,7 @@ func CheckRepoStats(ctx context.Context) error { } // SetArchiveRepoState sets if a repo is archived -func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { +func SetArchiveRepoState(repo *repo_model.Repository, isArchived bool) (err error) { repo.IsArchived = isArchived _, err = db.GetEngine(db.DefaultContext).Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo) return @@ -1996,8 +1268,8 @@ func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { // \/ \/ // GetForkedRepo checks if given user has already forked a repository with given ID. -func GetForkedRepo(ownerID, repoID int64) *Repository { - repo := new(Repository) +func GetForkedRepo(ownerID, repoID int64) *repo_model.Repository { + repo := new(repo_model.Repository) has, _ := db.GetEngine(db.DefaultContext). Where("owner_id=? AND fork_id=?", ownerID, repoID). Get(repo) @@ -2016,40 +1288,22 @@ func HasForkedRepo(ownerID, repoID int64) bool { return has } -// CopyLFS copies LFS data from one repo to another -func CopyLFS(ctx context.Context, newRepo, oldRepo *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 -} - // GetForks returns all the forks of the repository -func (repo *Repository) GetForks(listOptions db.ListOptions) ([]*Repository, error) { +func GetForks(repo *repo_model.Repository, listOptions db.ListOptions) ([]*repo_model.Repository, error) { if listOptions.Page == 0 { - forks := make([]*Repository, 0, repo.NumForks) - return forks, db.GetEngine(db.DefaultContext).Find(&forks, &Repository{ForkID: repo.ID}) + forks := make([]*repo_model.Repository, 0, repo.NumForks) + return forks, db.GetEngine(db.DefaultContext).Find(&forks, &repo_model.Repository{ForkID: repo.ID}) } sess := db.GetPaginatedSession(&listOptions) - forks := make([]*Repository, 0, listOptions.PageSize) - return forks, sess.Find(&forks, &Repository{ForkID: repo.ID}) + forks := make([]*repo_model.Repository, 0, listOptions.PageSize) + return forks, sess.Find(&forks, &repo_model.Repository{ForkID: repo.ID}) } // GetUserFork return user forked repository from this repository, if not forked return nil -func (repo *Repository) GetUserFork(userID int64) (*Repository, error) { - var forkedRepo Repository - has, err := db.GetEngine(db.DefaultContext).Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo) +func GetUserFork(repoID, userID int64) (*repo_model.Repository, error) { + var forkedRepo repo_model.Repository + has, err := db.GetEngine(db.DefaultContext).Where("fork_id = ?", repoID).And("owner_id = ?", userID).Get(&forkedRepo) if err != nil { return nil, err } @@ -2059,54 +1313,16 @@ func (repo *Repository) GetUserFork(userID int64) (*Repository, error) { return &forkedRepo, nil } -// GetOriginalURLHostname returns the hostname of a URL or the URL -func (repo *Repository) GetOriginalURLHostname() string { - u, err := url.Parse(repo.OriginalURL) - if err != nil { - return repo.OriginalURL - } - - return u.Host -} - -// GetTreePathLock returns LSF lock for the treePath -func (repo *Repository) GetTreePathLock(treePath string) (*LFSLock, error) { - if setting.LFS.StartServer { - locks, err := GetLFSLockByRepoID(repo.ID, 0, 0) - if err != nil { - return nil, err - } - for _, lock := range locks { - if lock.Path == treePath { - return lock, nil - } - } - } - return nil, nil -} - -func updateRepositoryCols(e db.Engine, repo *Repository, cols ...string) error { +func updateRepositoryCols(e db.Engine, repo *repo_model.Repository, cols ...string) error { _, err := e.ID(repo.ID).Cols(cols...).Update(repo) return err } // UpdateRepositoryCols updates repository's columns -func UpdateRepositoryCols(repo *Repository, cols ...string) error { +func UpdateRepositoryCols(repo *repo_model.Repository, cols ...string) error { return updateRepositoryCols(db.GetEngine(db.DefaultContext), repo, cols...) } -// GetTrustModel will get the TrustModel for the repo or the default trust model -func (repo *Repository) GetTrustModel() TrustModelType { - trustModel := repo.TrustModel - if trustModel == DefaultTrustModel { - trustModel = ToTrustModel(setting.Repository.Signing.DefaultTrustModel) - if trustModel == DefaultTrustModel { - return CollaboratorTrustModel - } - } - return trustModel -} - func updateUserStarNumbers(users []user_model.User) error { ctx, committer, err := db.TxContext() if err != nil { @@ -2147,11 +1363,11 @@ func DoctorUserStarNum() (err error) { } // IterateRepository iterate repositories -func IterateRepository(f func(repo *Repository) error) error { +func IterateRepository(f func(repo *repo_model.Repository) error) error { var start int batchSize := setting.Database.IterateBufferSize for { - repos := make([]*Repository, 0, batchSize) + repos := make([]*repo_model.Repository, 0, batchSize) if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&repos); err != nil { return err } @@ -2169,13 +1385,13 @@ func IterateRepository(f func(repo *Repository) error) error { } // LinkedRepository returns the linked repo if any -func LinkedRepository(a *repo_model.Attachment) (*Repository, unit.Type, error) { +func LinkedRepository(a *repo_model.Attachment) (*repo_model.Repository, unit.Type, error) { if a.IssueID != 0 { iss, err := GetIssueByID(a.IssueID) if err != nil { return nil, unit.TypeIssues, err } - repo, err := GetRepositoryByID(iss.RepoID) + repo, err := repo_model.GetRepositoryByID(iss.RepoID) unitType := unit.TypeIssues if iss.IsPull { unitType = unit.TypePullRequests @@ -2186,7 +1402,7 @@ func LinkedRepository(a *repo_model.Attachment) (*Repository, unit.Type, error) if err != nil { return nil, unit.TypeReleases, err } - repo, err := GetRepositoryByID(rel.RepoID) + repo, err := repo_model.GetRepositoryByID(rel.RepoID) return repo, unit.TypeReleases, err } return nil, -1, nil diff --git a/models/repo/avatar.go b/models/repo/avatar.go new file mode 100644 index 000000000..f11f868d6 --- /dev/null +++ b/models/repo/avatar.go @@ -0,0 +1,94 @@ +// 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 repo + +import ( + "fmt" + "image/png" + "io" + "net/url" + "strings" + + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/avatar" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/storage" +) + +// CustomAvatarRelativePath returns repository custom avatar file path. +func (repo *Repository) CustomAvatarRelativePath() string { + return repo.Avatar +} + +// RelAvatarLink returns a relative link to the repository's avatar. +func (repo *Repository) RelAvatarLink() string { + return repo.relAvatarLink(db.GetEngine(db.DefaultContext)) +} + +// generateRandomAvatar generates a random avatar for repository. +func generateRandomAvatar(e db.Engine, repo *Repository) error { + idToString := fmt.Sprintf("%d", repo.ID) + + seed := idToString + img, err := avatar.RandomImage([]byte(seed)) + if err != nil { + return fmt.Errorf("RandomImage: %v", err) + } + + repo.Avatar = idToString + + if err := storage.SaveFrom(storage.RepoAvatars, repo.CustomAvatarRelativePath(), func(w io.Writer) error { + if err := png.Encode(w, img); err != nil { + log.Error("Encode: %v", err) + } + return err + }); err != nil { + return fmt.Errorf("Failed to create dir %s: %v", repo.CustomAvatarRelativePath(), err) + } + + log.Info("New random avatar created for repository: %d", repo.ID) + + if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil { + return err + } + + return nil +} + +func (repo *Repository) relAvatarLink(e db.Engine) string { + // If no avatar - path is empty + avatarPath := repo.CustomAvatarRelativePath() + if len(avatarPath) == 0 { + switch mode := setting.RepoAvatar.Fallback; mode { + case "image": + return setting.RepoAvatar.FallbackImage + case "random": + if err := generateRandomAvatar(e, repo); err != nil { + log.Error("generateRandomAvatar: %v", err) + } + default: + // default behaviour: do not display avatar + return "" + } + } + return setting.AppSubURL + "/repo-avatars/" + url.PathEscape(repo.Avatar) +} + +// AvatarLink returns a link to the repository's avatar. +func (repo *Repository) AvatarLink() string { + return repo.avatarLink(db.GetEngine(db.DefaultContext)) +} + +// avatarLink returns user avatar absolute link. +func (repo *Repository) avatarLink(e db.Engine) string { + link := repo.relAvatarLink(e) + // we only prepend our AppURL to our known (relative, internal) avatar link to get an absolute URL + if strings.HasPrefix(link, "/") && !strings.HasPrefix(link, "//") { + return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:] + } + // otherwise, return the link as it is + return link +} diff --git a/models/repo/git.go b/models/repo/git.go new file mode 100644 index 000000000..509020565 --- /dev/null +++ b/models/repo/git.go @@ -0,0 +1,31 @@ +// 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 repo + +import "code.gitea.io/gitea/models/db" + +// 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" +) + +// UpdateDefaultBranch updates the default branch +func UpdateDefaultBranch(repo *Repository) error { + _, err := db.GetEngine(db.DefaultContext).ID(repo.ID).Cols("default_branch").Update(repo) + return err +} diff --git a/models/repo_issue.go b/models/repo/issue.go similarity index 70% rename from models/repo_issue.go rename to models/repo/issue.go index 32bfdc15b..3edcc7b5a 100644 --- a/models/repo_issue.go +++ b/models/repo/issue.go @@ -2,10 +2,14 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( + "context" + + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" ) @@ -45,3 +49,19 @@ func (repo *Repository) AllowOnlyContributorsToTrackTime() bool { } return u.IssuesConfig().AllowOnlyContributorsToTrackTime } + +// IsDependenciesEnabled returns if dependencies are enabled and returns the default setting if not set. +func (repo *Repository) IsDependenciesEnabled() bool { + return repo.IsDependenciesEnabledCtx(db.DefaultContext) +} + +// IsDependenciesEnabledCtx returns if dependencies are enabled and returns the default setting if not set. +func (repo *Repository) IsDependenciesEnabledCtx(ctx context.Context) bool { + var u *RepoUnit + var err error + if u, err = repo.getUnit(ctx, unit.TypeIssues); err != nil { + log.Trace("%s", err) + return setting.Service.DefaultEnableDependencies + } + return u.IssuesConfig().EnableDependencies +} diff --git a/models/repo_language_stats.go b/models/repo/language_stats.go similarity index 85% rename from models/repo_language_stats.go rename to models/repo/language_stats.go index 79de42ce0..3b0888b6b 100644 --- a/models/repo_language_stats.go +++ b/models/repo/language_stats.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "math" @@ -34,7 +34,8 @@ func init() { // LanguageStatList defines a list of language statistics type LanguageStatList []*LanguageStat -func (stats LanguageStatList) loadAttributes() { +// LoadAttributes loads attributes +func (stats LanguageStatList) LoadAttributes() { for i := range stats { stats[i].Color = enry.GetColor(stats[i].Language) } @@ -65,7 +66,7 @@ func (stats LanguageStatList) getLanguagePercentages() map[string]float32 { return langPerc } -func (repo *Repository) getLanguageStats(e db.Engine) (LanguageStatList, error) { +func getLanguageStats(e db.Engine, repo *Repository) (LanguageStatList, error) { stats := make(LanguageStatList, 0, 6) if err := e.Where("`repo_id` = ?", repo.ID).Desc("`size`").Find(&stats); err != nil { return nil, err @@ -74,13 +75,13 @@ func (repo *Repository) getLanguageStats(e db.Engine) (LanguageStatList, error) } // GetLanguageStats returns the language statistics for a repository -func (repo *Repository) GetLanguageStats() (LanguageStatList, error) { - return repo.getLanguageStats(db.GetEngine(db.DefaultContext)) +func GetLanguageStats(repo *Repository) (LanguageStatList, error) { + return getLanguageStats(db.GetEngine(db.DefaultContext), repo) } // GetTopLanguageStats returns the top language statistics for a repository -func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error) { - stats, err := repo.getLanguageStats(db.GetEngine(db.DefaultContext)) +func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error) { + stats, err := getLanguageStats(db.GetEngine(db.DefaultContext), repo) if err != nil { return nil, err } @@ -106,12 +107,12 @@ func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error) Percentage: float32(math.Round(float64(other)*10) / 10), }) } - topstats.loadAttributes() + topstats.LoadAttributes() return topstats, nil } // UpdateLanguageStats updates the language statistics for repository -func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]int64) error { +func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int64) error { ctx, committer, err := db.TxContext() if err != nil { return err @@ -119,7 +120,7 @@ func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]in defer committer.Close() sess := db.GetEngine(ctx) - oldstats, err := repo.getLanguageStats(sess) + oldstats, err := getLanguageStats(sess, repo) if err != nil { return err } @@ -175,7 +176,7 @@ func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]in } // Update indexer status - if err = repo.updateIndexerStatus(sess, RepoIndexerTypeStats, commitID); err != nil { + if err = updateIndexerStatus(sess, repo, RepoIndexerTypeStats, commitID); err != nil { return err } @@ -203,7 +204,7 @@ func CopyLanguageStat(originalRepo, destRepo *Repository) error { } // update destRepo's indexer status tmpCommitID := RepoLang[0].CommitID - if err := destRepo.updateIndexerStatus(sess, RepoIndexerTypeStats, tmpCommitID); err != nil { + if err := updateIndexerStatus(sess, destRepo, RepoIndexerTypeStats, tmpCommitID); err != nil { return err } if _, err := sess.Insert(&RepoLang); err != nil { diff --git a/models/repo/main_test.go b/models/repo/main_test.go index aa960bf13..f40a97628 100644 --- a/models/repo/main_test.go +++ b/models/repo/main_test.go @@ -15,5 +15,8 @@ func TestMain(m *testing.M) { unittest.MainTest(m, filepath.Join("..", ".."), "attachment.yml", "repo_archiver.yml", + "repository.yml", + "repo_unit.yml", + "repo_indexer_status.yml", ) } diff --git a/models/repo_mirror.go b/models/repo/mirror.go similarity index 75% rename from models/repo_mirror.go rename to models/repo/mirror.go index e28d0d251..bdb449af3 100644 --- a/models/repo_mirror.go +++ b/models/repo/mirror.go @@ -3,9 +3,11 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( + "errors" + "fmt" "time" "code.gitea.io/gitea/models/db" @@ -15,6 +17,11 @@ import ( "xorm.io/xorm" ) +var ( + // ErrMirrorNotExist mirror does not exist error + ErrMirrorNotExist = errors.New("Mirror does not exist") +) + // RemoteMirrorer defines base methods for pull/push mirrors. type RemoteMirrorer interface { GetRepository() *Repository @@ -128,3 +135,43 @@ func InsertMirror(mirror *Mirror) error { _, err := db.GetEngine(db.DefaultContext).Insert(mirror) return err } + +// MirrorRepositoryList contains the mirror repositories +type MirrorRepositoryList []*Repository + +func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error { + if len(repos) == 0 { + return nil + } + + // Load mirrors. + repoIDs := make([]int64, 0, len(repos)) + for i := range repos { + if !repos[i].IsMirror { + continue + } + + repoIDs = append(repoIDs, repos[i].ID) + } + mirrors := make([]*Mirror, 0, len(repoIDs)) + if err := e. + Where("id > 0"). + In("repo_id", repoIDs). + Find(&mirrors); err != nil { + return fmt.Errorf("find mirrors: %v", err) + } + + set := make(map[int64]*Mirror) + for i := range mirrors { + set[mirrors[i].RepoID] = mirrors[i] + } + for i := range repos { + repos[i].Mirror = set[repos[i].ID] + } + return nil +} + +// LoadAttributes loads the attributes for the given MirrorRepositoryList +func (repos MirrorRepositoryList) LoadAttributes() error { + return repos.loadAttributes(db.GetEngine(db.DefaultContext)) +} diff --git a/models/repo_pushmirror.go b/models/repo/pushmirror.go similarity index 99% rename from models/repo_pushmirror.go rename to models/repo/pushmirror.go index 38a1a6694..0b6216164 100644 --- a/models/repo_pushmirror.go +++ b/models/repo/pushmirror.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "errors" diff --git a/models/repo_pushmirror_test.go b/models/repo/pushmirror_test.go similarity index 98% rename from models/repo_pushmirror_test.go rename to models/repo/pushmirror_test.go index aa4465082..eff31fbac 100644 --- a/models/repo_pushmirror_test.go +++ b/models/repo/pushmirror_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "testing" diff --git a/models/repo/repo.go b/models/repo/repo.go new file mode 100644 index 000000000..9353e813b --- /dev/null +++ b/models/repo/repo.go @@ -0,0 +1,736 @@ +// 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 repo + +import ( + "context" + "fmt" + "html/template" + "net" + "net/url" + "path/filepath" + "strconv" + "strings" + + "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/markup" + "code.gitea.io/gitea/modules/setting" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/util" +) + +// TrustModelType defines the types of trust model for this repository +type TrustModelType int + +// kinds of TrustModel +const ( + DefaultTrustModel TrustModelType = iota // default trust model + CommitterTrustModel + CollaboratorTrustModel + CollaboratorCommitterTrustModel +) + +// String converts a TrustModelType to a string +func (t TrustModelType) String() string { + switch t { + case DefaultTrustModel: + return "default" + case CommitterTrustModel: + return "committer" + case CollaboratorTrustModel: + return "collaborator" + case CollaboratorCommitterTrustModel: + return "collaboratorcommitter" + } + return "default" +} + +// ToTrustModel converts a string to a TrustModelType +func ToTrustModel(model string) TrustModelType { + switch strings.ToLower(strings.TrimSpace(model)) { + case "default": + return DefaultTrustModel + case "collaborator": + return CollaboratorTrustModel + case "committer": + return CommitterTrustModel + case "collaboratorcommitter": + return CollaboratorCommitterTrustModel + } + return DefaultTrustModel +} + +// RepositoryStatus defines the status of repository +type RepositoryStatus int + +// all kinds of RepositoryStatus +const ( + RepositoryReady RepositoryStatus = iota // a normal repository + RepositoryBeingMigrated // repository is migrating + RepositoryPendingTransfer // repository pending in ownership transfer state + RepositoryBroken // repository is in a permanently broken state +) + +// Repository represents a git repository. +type Repository struct { + ID int64 `xorm:"pk autoincr"` + OwnerID int64 `xorm:"UNIQUE(s) index"` + OwnerName string + Owner *user_model.User `xorm:"-"` + LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"` + Name string `xorm:"INDEX NOT NULL"` + Description string `xorm:"TEXT"` + Website string `xorm:"VARCHAR(2048)"` + OriginalServiceType api.GitServiceType `xorm:"index"` + OriginalURL string `xorm:"VARCHAR(2048)"` + DefaultBranch string + + NumWatches int + NumStars int + NumForks int + NumIssues int + NumClosedIssues int + NumOpenIssues int `xorm:"-"` + NumPulls int + NumClosedPulls int + NumOpenPulls int `xorm:"-"` + NumMilestones int `xorm:"NOT NULL DEFAULT 0"` + NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"` + NumOpenMilestones int `xorm:"-"` + NumProjects int `xorm:"NOT NULL DEFAULT 0"` + NumClosedProjects int `xorm:"NOT NULL DEFAULT 0"` + NumOpenProjects int `xorm:"-"` + + IsPrivate bool `xorm:"INDEX"` + IsEmpty bool `xorm:"INDEX"` + IsArchived bool `xorm:"INDEX"` + IsMirror bool `xorm:"INDEX"` + *Mirror `xorm:"-"` + Status RepositoryStatus `xorm:"NOT NULL DEFAULT 0"` + + RenderingMetas map[string]string `xorm:"-"` + DocumentRenderingMetas map[string]string `xorm:"-"` + Units []*RepoUnit `xorm:"-"` + PrimaryLanguage *LanguageStat `xorm:"-"` + + IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"` + ForkID int64 `xorm:"INDEX"` + BaseRepo *Repository `xorm:"-"` + IsTemplate bool `xorm:"INDEX NOT NULL DEFAULT false"` + TemplateID int64 `xorm:"INDEX"` + Size int64 `xorm:"NOT NULL DEFAULT 0"` + CodeIndexerStatus *RepoIndexerStatus `xorm:"-"` + StatsIndexerStatus *RepoIndexerStatus `xorm:"-"` + IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"` + CloseIssuesViaCommitInAnyBranch bool `xorm:"NOT NULL DEFAULT false"` + Topics []string `xorm:"TEXT JSON"` + + TrustModel TrustModelType + + // Avatar: ID(10-20)-md5(32) - must fit into 64 symbols + Avatar string `xorm:"VARCHAR(64)"` + + CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` + UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` +} + +func init() { + db.RegisterModel(new(Repository)) +} + +// SanitizedOriginalURL returns a sanitized OriginalURL +func (repo *Repository) SanitizedOriginalURL() string { + if repo.OriginalURL == "" { + return "" + } + u, err := url.Parse(repo.OriginalURL) + if err != nil { + return "" + } + u.User = nil + return u.String() +} + +// ColorFormat returns a colored string to represent this repo +func (repo *Repository) ColorFormat(s fmt.State) { + log.ColorFprintf(s, "%d:%s/%s", + log.NewColoredIDValue(repo.ID), + repo.OwnerName, + repo.Name) +} + +// IsBeingMigrated indicates that repository is being migrated +func (repo *Repository) IsBeingMigrated() bool { + return repo.Status == RepositoryBeingMigrated +} + +// IsBeingCreated indicates that repository is being migrated or forked +func (repo *Repository) IsBeingCreated() bool { + return repo.IsBeingMigrated() +} + +// IsBroken indicates that repository is broken +func (repo *Repository) IsBroken() bool { + return repo.Status == RepositoryBroken +} + +// AfterLoad is invoked from XORM after setting the values of all fields of this object. +func (repo *Repository) AfterLoad() { + // FIXME: use models migration to solve all at once. + if len(repo.DefaultBranch) == 0 { + repo.DefaultBranch = setting.Repository.DefaultBranch + } + + repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues + repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls + repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones + repo.NumOpenProjects = repo.NumProjects - repo.NumClosedProjects +} + +// MustOwner always returns a valid *user_model.User object to avoid +// conceptually impossible error handling. +// It creates a fake object that contains error details +// when error occurs. +func (repo *Repository) MustOwner() *user_model.User { + return repo.mustOwner(db.DefaultContext) +} + +// FullName returns the repository full name +func (repo *Repository) FullName() string { + return repo.OwnerName + "/" + repo.Name +} + +// HTMLURL returns the repository HTML URL +func (repo *Repository) HTMLURL() string { + return setting.AppURL + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) +} + +// CommitLink make link to by commit full ID +// note: won't check whether it's an right id +func (repo *Repository) CommitLink(commitID string) (result string) { + if commitID == "" || commitID == "0000000000000000000000000000000000000000" { + result = "" + } else { + result = repo.HTMLURL() + "/commit/" + url.PathEscape(commitID) + } + return +} + +// APIURL returns the repository API URL +func (repo *Repository) APIURL() string { + return setting.AppURL + "api/v1/repos/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) +} + +// GetCommitsCountCacheKey returns cache key used for commits count caching. +func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) string { + var prefix string + if isRef { + prefix = "ref" + } else { + prefix = "commit" + } + return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName) +} + +// LoadUnits loads repo units into repo.Units +func (repo *Repository) LoadUnits(ctx context.Context) (err error) { + if repo.Units != nil { + return nil + } + + repo.Units, err = getUnitsByRepoID(db.GetEngine(ctx), repo.ID) + log.Trace("repo.Units: %-+v", repo.Units) + return err +} + +// UnitEnabled if this repository has the given unit enabled +func (repo *Repository) UnitEnabled(tp unit.Type) bool { + if err := repo.LoadUnits(db.DefaultContext); err != nil { + log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error()) + } + for _, unit := range repo.Units { + if unit.Type == tp { + return true + } + } + return false +} + +// MustGetUnit always returns a RepoUnit object +func (repo *Repository) MustGetUnit(tp unit.Type) *RepoUnit { + ru, err := repo.GetUnit(tp) + if err == nil { + return ru + } + + if tp == unit.TypeExternalWiki { + return &RepoUnit{ + Type: tp, + Config: new(ExternalWikiConfig), + } + } else if tp == unit.TypeExternalTracker { + return &RepoUnit{ + Type: tp, + Config: new(ExternalTrackerConfig), + } + } else if tp == unit.TypePullRequests { + return &RepoUnit{ + Type: tp, + Config: new(PullRequestsConfig), + } + } else if tp == unit.TypeIssues { + return &RepoUnit{ + Type: tp, + Config: new(IssuesConfig), + } + } + return &RepoUnit{ + Type: tp, + Config: new(UnitConfig), + } +} + +// GetUnit returns a RepoUnit object +func (repo *Repository) GetUnit(tp unit.Type) (*RepoUnit, error) { + return repo.getUnit(db.DefaultContext, tp) +} + +func (repo *Repository) getUnit(ctx context.Context, tp unit.Type) (*RepoUnit, error) { + if err := repo.LoadUnits(ctx); err != nil { + return nil, err + } + for _, unit := range repo.Units { + if unit.Type == tp { + return unit, nil + } + } + return nil, ErrUnitTypeNotExist{tp} +} + +// GetOwner returns the repository owner +func (repo *Repository) GetOwner(ctx context.Context) (err error) { + if repo.Owner != nil { + return nil + } + + repo.Owner, err = user_model.GetUserByIDEngine(db.GetEngine(ctx), repo.OwnerID) + return err +} + +func (repo *Repository) mustOwner(ctx context.Context) *user_model.User { + if err := repo.GetOwner(ctx); err != nil { + return &user_model.User{ + Name: "error", + FullName: err.Error(), + } + } + + return repo.Owner +} + +// ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers. +func (repo *Repository) ComposeMetas() map[string]string { + if len(repo.RenderingMetas) == 0 { + metas := map[string]string{ + "user": repo.OwnerName, + "repo": repo.Name, + "repoPath": repo.RepoPath(), + "mode": "comment", + } + + unit, err := repo.GetUnit(unit.TypeExternalTracker) + if err == nil { + metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat + switch unit.ExternalTrackerConfig().ExternalTrackerStyle { + case markup.IssueNameStyleAlphanumeric: + metas["style"] = markup.IssueNameStyleAlphanumeric + default: + metas["style"] = markup.IssueNameStyleNumeric + } + } + + repo.MustOwner() + if repo.Owner.IsOrganization() { + teams := make([]string, 0, 5) + _ = db.GetEngine(db.DefaultContext).Table("team_repo"). + Join("INNER", "team", "team.id = team_repo.team_id"). + Where("team_repo.repo_id = ?", repo.ID). + Select("team.lower_name"). + OrderBy("team.lower_name"). + Find(&teams) + metas["teams"] = "," + strings.Join(teams, ",") + "," + metas["org"] = strings.ToLower(repo.OwnerName) + } + + repo.RenderingMetas = metas + } + return repo.RenderingMetas +} + +// ComposeDocumentMetas composes a map of metas for properly rendering documents +func (repo *Repository) ComposeDocumentMetas() map[string]string { + if len(repo.DocumentRenderingMetas) == 0 { + metas := map[string]string{} + for k, v := range repo.ComposeMetas() { + metas[k] = v + } + metas["mode"] = "document" + repo.DocumentRenderingMetas = metas + } + return repo.DocumentRenderingMetas +} + +// GetBaseRepo populates repo.BaseRepo for a fork repository and +// returns an error on failure (NOTE: no error is returned for +// non-fork repositories, and BaseRepo will be left untouched) +func (repo *Repository) GetBaseRepo() (err error) { + return repo.getBaseRepo(db.GetEngine(db.DefaultContext)) +} + +func (repo *Repository) getBaseRepo(e db.Engine) (err error) { + if !repo.IsFork { + return nil + } + + repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID) + return err +} + +// IsGenerated returns whether _this_ repository was generated from a template +func (repo *Repository) IsGenerated() bool { + return repo.TemplateID != 0 +} + +// RepoPath returns repository path by given user and repository name. +func RepoPath(userName, repoName string) string { //revive:disable-line:exported + return filepath.Join(user_model.UserPath(userName), strings.ToLower(repoName)+".git") +} + +// RepoPath returns the repository path +func (repo *Repository) RepoPath() string { + return RepoPath(repo.OwnerName, repo.Name) +} + +// GitConfigPath returns the path to a repository's git config/ directory +func GitConfigPath(repoPath string) string { + return filepath.Join(repoPath, "config") +} + +// GitConfigPath returns the repository git config path +func (repo *Repository) GitConfigPath() string { + return GitConfigPath(repo.RepoPath()) +} + +// Link returns the repository link +func (repo *Repository) Link() string { + return setting.AppSubURL + "/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) +} + +// ComposeCompareURL returns the repository comparison URL +func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { + return fmt.Sprintf("%s/%s/compare/%s...%s", url.PathEscape(repo.OwnerName), url.PathEscape(repo.Name), util.PathEscapeSegments(oldCommitID), util.PathEscapeSegments(newCommitID)) +} + +// IsOwnedBy returns true when user owns this repository +func (repo *Repository) IsOwnedBy(userID int64) bool { + return repo.OwnerID == userID +} + +// CanCreateBranch returns true if repository meets the requirements for creating new branches. +func (repo *Repository) CanCreateBranch() bool { + return !repo.IsMirror +} + +// CanEnablePulls returns true if repository meets the requirements of accepting pulls. +func (repo *Repository) CanEnablePulls() bool { + return !repo.IsMirror && !repo.IsEmpty +} + +// AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled. +func (repo *Repository) AllowsPulls() bool { + return repo.CanEnablePulls() && repo.UnitEnabled(unit.TypePullRequests) +} + +// CanEnableEditor returns true if repository meets the requirements of web editor. +func (repo *Repository) CanEnableEditor() bool { + return !repo.IsMirror +} + +// DescriptionHTML does special handles to description and return HTML string. +func (repo *Repository) DescriptionHTML() template.HTML { + desc, err := markup.RenderDescriptionHTML(&markup.RenderContext{ + URLPrefix: repo.HTMLURL(), + Metas: repo.ComposeMetas(), + }, repo.Description) + if err != nil { + log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err) + return template.HTML(markup.Sanitize(repo.Description)) + } + return template.HTML(markup.Sanitize(string(desc))) +} + +// CloneLink represents different types of clone URLs of repository. +type CloneLink struct { + SSH string + HTTPS string + Git string +} + +// ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name. +func ComposeHTTPSCloneURL(owner, repo string) string { + return fmt.Sprintf("%s%s/%s.git", setting.AppURL, url.PathEscape(owner), url.PathEscape(repo)) +} + +func (repo *Repository) cloneLink(isWiki bool) *CloneLink { + repoName := repo.Name + if isWiki { + repoName += ".wiki" + } + + sshUser := setting.RunUser + if setting.SSH.StartBuiltinServer { + sshUser = setting.SSH.BuiltinServerUser + } + + cl := new(CloneLink) + + // if we have a ipv6 literal we need to put brackets around it + // for the git cloning to work. + sshDomain := setting.SSH.Domain + ip := net.ParseIP(setting.SSH.Domain) + if ip != nil && ip.To4() == nil { + sshDomain = "[" + setting.SSH.Domain + "]" + } + + if setting.SSH.Port != 22 { + cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, net.JoinHostPort(setting.SSH.Domain, strconv.Itoa(setting.SSH.Port)), url.PathEscape(repo.OwnerName), url.PathEscape(repoName)) + } else if setting.Repository.UseCompatSSHURI { + cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, sshDomain, url.PathEscape(repo.OwnerName), url.PathEscape(repoName)) + } else { + cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, sshDomain, url.PathEscape(repo.OwnerName), url.PathEscape(repoName)) + } + cl.HTTPS = ComposeHTTPSCloneURL(repo.OwnerName, repoName) + return cl +} + +// CloneLink returns clone URLs of repository. +func (repo *Repository) CloneLink() (cl *CloneLink) { + return repo.cloneLink(false) +} + +// GetOriginalURLHostname returns the hostname of a URL or the URL +func (repo *Repository) GetOriginalURLHostname() string { + u, err := url.Parse(repo.OriginalURL) + if err != nil { + return repo.OriginalURL + } + + return u.Host +} + +// GetTrustModel will get the TrustModel for the repo or the default trust model +func (repo *Repository) GetTrustModel() TrustModelType { + trustModel := repo.TrustModel + if trustModel == DefaultTrustModel { + trustModel = ToTrustModel(setting.Repository.Signing.DefaultTrustModel) + if trustModel == DefaultTrustModel { + return CollaboratorTrustModel + } + } + return trustModel +} + +// GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. +func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { + return GetRepositoryByOwnerAndNameCtx(db.DefaultContext, ownerName, repoName) +} + +// __________ .__ __ +// \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. +// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | +// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ | +// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| +// \/ \/|__| \/ \/ + +// 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) +} + +// GetRepositoryByOwnerAndNameCtx returns the repository by given owner name and repo name +func GetRepositoryByOwnerAndNameCtx(ctx context.Context, ownerName, repoName string) (*Repository, error) { + var repo Repository + has, err := db.GetEngine(ctx).Table("repository").Select("repository.*"). + Join("INNER", "`user`", "`user`.id = repository.owner_id"). + Where("repository.lower_name = ?", strings.ToLower(repoName)). + And("`user`.lower_name = ?", strings.ToLower(ownerName)). + Get(&repo) + if err != nil { + return nil, err + } else if !has { + return nil, ErrRepoNotExist{0, 0, ownerName, repoName} + } + return &repo, nil +} + +// GetRepositoryByName returns the repository by given name under user if exists. +func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { + repo := &Repository{ + OwnerID: ownerID, + LowerName: strings.ToLower(name), + } + has, err := db.GetEngine(db.DefaultContext).Get(repo) + if err != nil { + return nil, err + } else if !has { + return nil, ErrRepoNotExist{0, ownerID, "", name} + } + return repo, err +} + +func getRepositoryByID(e db.Engine, id int64) (*Repository, error) { + repo := new(Repository) + has, err := e.ID(id).Get(repo) + if err != nil { + return nil, err + } else if !has { + return nil, ErrRepoNotExist{id, 0, "", ""} + } + return repo, nil +} + +// GetRepositoryByID returns the repository by given id if exists. +func GetRepositoryByID(id int64) (*Repository, error) { + return getRepositoryByID(db.GetEngine(db.DefaultContext), id) +} + +// GetRepositoryByIDCtx returns the repository by given id if exists. +func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { + return getRepositoryByID(db.GetEngine(ctx), id) +} + +// GetRepositoriesMapByIDs returns the repositories by given id slice. +func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { + repos := make(map[int64]*Repository, len(ids)) + return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos) +} + +// IsRepositoryExistCtx returns true if the repository with given name under user has already existed. +func IsRepositoryExistCtx(ctx context.Context, u *user_model.User, repoName string) (bool, error) { + has, err := db.GetEngine(ctx).Get(&Repository{ + OwnerID: u.ID, + LowerName: strings.ToLower(repoName), + }) + if err != nil { + return false, err + } + isDir, err := util.IsDir(RepoPath(u.Name, repoName)) + return has && isDir, err +} + +// IsRepositoryExist returns true if the repository with given name under user has already existed. +func IsRepositoryExist(u *user_model.User, repoName string) (bool, error) { + return IsRepositoryExistCtx(db.DefaultContext, u, repoName) +} + +// GetTemplateRepo populates repo.TemplateRepo for a generated repository and +// returns an error on failure (NOTE: no error is returned for +// non-generated repositories, and TemplateRepo will be left untouched) +func GetTemplateRepo(repo *Repository) (*Repository, error) { + return getTemplateRepo(db.GetEngine(db.DefaultContext), repo) +} + +func getTemplateRepo(e db.Engine, repo *Repository) (*Repository, error) { + if !repo.IsGenerated() { + return nil, nil + } + + return getRepositoryByID(e, repo.TemplateID) +} + +func countRepositories(userID int64, private bool) int64 { + sess := db.GetEngine(db.DefaultContext).Where("id > 0") + + if userID > 0 { + sess.And("owner_id = ?", userID) + } + if !private { + sess.And("is_private=?", false) + } + + count, err := sess.Count(new(Repository)) + if err != nil { + log.Error("countRepositories: %v", err) + } + return count +} + +// CountRepositories returns number of repositories. +// Argument private only takes effect when it is false, +// set it true to count all repositories. +func CountRepositories(private bool) int64 { + return countRepositories(-1, private) +} + +// CountUserRepositories returns number of repositories user owns. +// Argument private only takes effect when it is false, +// set it true to count all repositories. +func CountUserRepositories(userID int64, private bool) int64 { + return countRepositories(userID, private) +} + +// GetUserMirrorRepositories returns a list of mirror repositories of given user. +func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, db.GetEngine(db.DefaultContext). + Where("owner_id = ?", userID). + And("is_mirror = ?", true). + Find(&repos) +} + +func getRepositoryCount(e db.Engine, ownerID int64) (int64, error) { + return e.Count(&Repository{OwnerID: ownerID}) +} + +func getPublicRepositoryCount(e db.Engine, u *user_model.User) (int64, error) { + return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID}) +} + +func getPrivateRepositoryCount(e db.Engine, u *user_model.User) (int64, error) { + return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID}) +} + +// GetRepositoryCount returns the total number of repositories of user. +func GetRepositoryCount(ctx context.Context, ownerID int64) (int64, error) { + return getRepositoryCount(db.GetEngine(ctx), ownerID) +} + +// GetPublicRepositoryCount returns the total number of public repositories of user. +func GetPublicRepositoryCount(u *user_model.User) (int64, error) { + return getPublicRepositoryCount(db.GetEngine(db.DefaultContext), u) +} + +// GetPrivateRepositoryCount returns the total number of private repositories of user. +func GetPrivateRepositoryCount(u *user_model.User) (int64, error) { + return getPrivateRepositoryCount(db.GetEngine(db.DefaultContext), u) +} diff --git a/models/repo_indexer.go b/models/repo/repo_indexer.go similarity index 81% rename from models/repo_indexer.go rename to models/repo/repo_indexer.go index e0511b325..f442cad4d 100644 --- a/models/repo_indexer.go +++ b/models/repo/repo_indexer.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "fmt" @@ -13,7 +13,7 @@ import ( ) // RepoIndexerType specifies the repository indexer type -type RepoIndexerType int +type RepoIndexerType int //revive:disable-line:exported const ( // RepoIndexerTypeCode code indexer @@ -24,7 +24,7 @@ const ( // RepoIndexerStatus status of a repo's entry in the repo indexer // For now, implicitly refers to default branch -type RepoIndexerStatus struct { +type RepoIndexerStatus struct { //revive:disable-line:exported ID int64 `xorm:"pk autoincr"` RepoID int64 `xorm:"INDEX(s)"` CommitSha string `xorm:"VARCHAR(40)"` @@ -63,7 +63,7 @@ func GetUnindexedRepos(indexerType RepoIndexerType, maxRepoID int64, page, pageS } // getIndexerStatus loads repo codes indxer status -func (repo *Repository) getIndexerStatus(e db.Engine, indexerType RepoIndexerType) (*RepoIndexerStatus, error) { +func getIndexerStatus(e db.Engine, repo *Repository, indexerType RepoIndexerType) (*RepoIndexerStatus, error) { switch indexerType { case RepoIndexerTypeCode: if repo.CodeIndexerStatus != nil { @@ -91,13 +91,13 @@ func (repo *Repository) getIndexerStatus(e db.Engine, indexerType RepoIndexerTyp } // GetIndexerStatus loads repo codes indxer status -func (repo *Repository) GetIndexerStatus(indexerType RepoIndexerType) (*RepoIndexerStatus, error) { - return repo.getIndexerStatus(db.GetEngine(db.DefaultContext), indexerType) +func GetIndexerStatus(repo *Repository, indexerType RepoIndexerType) (*RepoIndexerStatus, error) { + return getIndexerStatus(db.GetEngine(db.DefaultContext), repo, indexerType) } // updateIndexerStatus updates indexer status -func (repo *Repository) updateIndexerStatus(e db.Engine, indexerType RepoIndexerType, sha string) error { - status, err := repo.getIndexerStatus(e, indexerType) +func updateIndexerStatus(e db.Engine, repo *Repository, indexerType RepoIndexerType, sha string) error { + status, err := getIndexerStatus(e, repo, indexerType) if err != nil { return fmt.Errorf("UpdateIndexerStatus: Unable to getIndexerStatus for repo: %s Error: %v", repo.FullName(), err) } @@ -120,6 +120,6 @@ func (repo *Repository) updateIndexerStatus(e db.Engine, indexerType RepoIndexer } // UpdateIndexerStatus updates indexer status -func (repo *Repository) UpdateIndexerStatus(indexerType RepoIndexerType, sha string) error { - return repo.updateIndexerStatus(db.GetEngine(db.DefaultContext), indexerType, sha) +func UpdateIndexerStatus(repo *Repository, indexerType RepoIndexerType, sha string) error { + return updateIndexerStatus(db.GetEngine(db.DefaultContext), repo, indexerType, sha) } diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go new file mode 100644 index 000000000..6f48a22e4 --- /dev/null +++ b/models/repo/repo_test.go @@ -0,0 +1,44 @@ +// Copyright 2017 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 repo + +import ( + "testing" + + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + user_model "code.gitea.io/gitea/models/user" + + "github.com/stretchr/testify/assert" +) + +func TestGetRepositoryCount(t *testing.T) { + assert.NoError(t, unittest.PrepareTestDatabase()) + + count, err1 := GetRepositoryCount(db.DefaultContext, 10) + privateCount, err2 := GetPrivateRepositoryCount(&user_model.User{ID: int64(10)}) + publicCount, err3 := GetPublicRepositoryCount(&user_model.User{ID: int64(10)}) + assert.NoError(t, err1) + assert.NoError(t, err2) + assert.NoError(t, err3) + assert.Equal(t, int64(3), count) + assert.Equal(t, privateCount+publicCount, count) +} + +func TestGetPublicRepositoryCount(t *testing.T) { + assert.NoError(t, unittest.PrepareTestDatabase()) + + count, err := GetPublicRepositoryCount(&user_model.User{ID: int64(10)}) + assert.NoError(t, err) + assert.Equal(t, int64(1), count) +} + +func TestGetPrivateRepositoryCount(t *testing.T) { + assert.NoError(t, unittest.PrepareTestDatabase()) + + count, err := GetPrivateRepositoryCount(&user_model.User{ID: int64(10)}) + assert.NoError(t, err) + assert.Equal(t, int64(2), count) +} diff --git a/models/repo_unit.go b/models/repo/repo_unit.go similarity index 89% rename from models/repo_unit.go rename to models/repo/repo_unit.go index 4dac15366..5f6c43f02 100644 --- a/models/repo_unit.go +++ b/models/repo/repo_unit.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "fmt" @@ -17,8 +17,23 @@ import ( "xorm.io/xorm/convert" ) +// ErrUnitTypeNotExist represents a "UnitTypeNotExist" kind of error. +type ErrUnitTypeNotExist struct { + UT unit.Type +} + +// IsErrUnitTypeNotExist checks if an error is a ErrUnitNotExist. +func IsErrUnitTypeNotExist(err error) bool { + _, ok := err.(ErrUnitTypeNotExist) + return ok +} + +func (err ErrUnitTypeNotExist) Error() string { + return fmt.Sprintf("Unit type does not exist: %s", err.UT.String()) +} + // RepoUnit describes all units of a repository -type RepoUnit struct { +type RepoUnit struct { //revive:disable-line:exported ID int64 RepoID int64 `xorm:"INDEX(s)"` Type unit.Type `xorm:"INDEX(s)"` @@ -35,7 +50,7 @@ type UnitConfig struct{} // FromDB fills up a UnitConfig from serialized format. func (cfg *UnitConfig) FromDB(bs []byte) error { - return JSONUnmarshalHandleDoubleEncode(bs, &cfg) + return json.UnmarshalHandleDoubleEncode(bs, &cfg) } // ToDB exports a UnitConfig to a serialized format. @@ -50,7 +65,7 @@ type ExternalWikiConfig struct { // FromDB fills up a ExternalWikiConfig from serialized format. func (cfg *ExternalWikiConfig) FromDB(bs []byte) error { - return JSONUnmarshalHandleDoubleEncode(bs, &cfg) + return json.UnmarshalHandleDoubleEncode(bs, &cfg) } // ToDB exports a ExternalWikiConfig to a serialized format. @@ -67,7 +82,7 @@ type ExternalTrackerConfig struct { // FromDB fills up a ExternalTrackerConfig from serialized format. func (cfg *ExternalTrackerConfig) FromDB(bs []byte) error { - return JSONUnmarshalHandleDoubleEncode(bs, &cfg) + return json.UnmarshalHandleDoubleEncode(bs, &cfg) } // ToDB exports a ExternalTrackerConfig to a serialized format. @@ -84,7 +99,7 @@ type IssuesConfig struct { // FromDB fills up a IssuesConfig from serialized format. func (cfg *IssuesConfig) FromDB(bs []byte) error { - return JSONUnmarshalHandleDoubleEncode(bs, &cfg) + return json.UnmarshalHandleDoubleEncode(bs, &cfg) } // ToDB exports a IssuesConfig to a serialized format. @@ -107,7 +122,7 @@ type PullRequestsConfig struct { // FromDB fills up a PullRequestsConfig from serialized format. func (cfg *PullRequestsConfig) FromDB(bs []byte) error { - return JSONUnmarshalHandleDoubleEncode(bs, &cfg) + return json.UnmarshalHandleDoubleEncode(bs, &cfg) } // ToDB exports a PullRequestsConfig to a serialized format. diff --git a/models/wiki.go b/models/repo/wiki.go similarity index 98% rename from models/wiki.go rename to models/repo/wiki.go index f80696542..abf0155ca 100644 --- a/models/wiki.go +++ b/models/repo/wiki.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "path/filepath" diff --git a/models/wiki_test.go b/models/repo/wiki_test.go similarity index 99% rename from models/wiki_test.go rename to models/repo/wiki_test.go index ae6b090db..72f5280ce 100644 --- a/models/wiki_test.go +++ b/models/repo/wiki_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package repo import ( "path/filepath" diff --git a/models/repo_activity.go b/models/repo_activity.go index d3d4c7bbd..5bdea80b9 100644 --- a/models/repo_activity.go +++ b/models/repo_activity.go @@ -10,6 +10,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/git" @@ -42,7 +43,7 @@ type ActivityStats struct { } // GetActivityStats return stats for repository at given time range -func GetActivityStats(repo *Repository, timeFrom time.Time, releases, issues, prs, code bool) (*ActivityStats, error) { +func GetActivityStats(repo *repo_model.Repository, timeFrom time.Time, releases, issues, prs, code bool) (*ActivityStats, error) { stats := &ActivityStats{Code: &git.CodeActivityStats{}} if releases { if err := stats.FillReleases(repo.ID, timeFrom); err != nil { @@ -79,7 +80,7 @@ func GetActivityStats(repo *Repository, timeFrom time.Time, releases, issues, pr } // GetActivityStatsTopAuthors returns top author stats for git commits for all branches -func GetActivityStatsTopAuthors(repo *Repository, timeFrom time.Time, count int) ([]*ActivityAuthorData, error) { +func GetActivityStatsTopAuthors(repo *repo_model.Repository, timeFrom time.Time, count int) ([]*ActivityAuthorData, error) { gitRepo, err := git.OpenRepository(repo.RepoPath()) if err != nil { return nil, fmt.Errorf("OpenRepository: %v", err) diff --git a/models/repo_archiver.go b/models/repo_archiver.go index 9363d0957..1ac05da04 100644 --- a/models/repo_archiver.go +++ b/models/repo_archiver.go @@ -10,14 +10,14 @@ import ( ) // LoadArchiverRepo loads repository -func LoadArchiverRepo(archiver *repo_model.RepoArchiver) (*Repository, error) { - var repo Repository +func LoadArchiverRepo(archiver *repo_model.RepoArchiver) (*repo_model.Repository, error) { + var repo repo_model.Repository has, err := db.GetEngine(db.DefaultContext).ID(archiver.RepoID).Get(&repo) if err != nil { return nil, err } if !has { - return nil, ErrRepoNotExist{ + return nil, repo_model.ErrRepoNotExist{ ID: archiver.RepoID, } } diff --git a/models/repo_avatar.go b/models/repo_avatar.go index 1d9705fe9..27af911a7 100644 --- a/models/repo_avatar.go +++ b/models/repo_avatar.go @@ -10,59 +10,23 @@ import ( "fmt" "image/png" "io" - "net/url" "strconv" - "strings" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/avatar" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/storage" ) -// CustomAvatarRelativePath returns repository custom avatar file path. -func (repo *Repository) CustomAvatarRelativePath() string { - return repo.Avatar -} - -// generateRandomAvatar generates a random avatar for repository. -func (repo *Repository) generateRandomAvatar(e db.Engine) error { - idToString := fmt.Sprintf("%d", repo.ID) - - seed := idToString - img, err := avatar.RandomImage([]byte(seed)) - if err != nil { - return fmt.Errorf("RandomImage: %v", err) - } - - repo.Avatar = idToString - - if err := storage.SaveFrom(storage.RepoAvatars, repo.CustomAvatarRelativePath(), func(w io.Writer) error { - if err := png.Encode(w, img); err != nil { - log.Error("Encode: %v", err) - } - return err - }); err != nil { - return fmt.Errorf("Failed to create dir %s: %v", repo.CustomAvatarRelativePath(), err) - } - - log.Info("New random avatar created for repository: %d", repo.ID) - - if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil { - return err - } - - return nil -} - // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories func RemoveRandomAvatars(ctx context.Context) error { return db.GetEngine(db.DefaultContext). Where("id > 0").BufferSize(setting.Database.IterateBufferSize). - Iterate(new(Repository), + Iterate(new(repo_model.Repository), func(idx int, bean interface{}) error { - repository := bean.(*Repository) + repository := bean.(*repo_model.Repository) select { case <-ctx.Done(): return db.ErrCancelledf("before random avatars removed for %s", repository.FullName()) @@ -70,55 +34,15 @@ func RemoveRandomAvatars(ctx context.Context) error { } stringifiedID := strconv.FormatInt(repository.ID, 10) if repository.Avatar == stringifiedID { - return repository.DeleteAvatar() + return DeleteRepoAvatar(repository) } return nil }) } -// RelAvatarLink returns a relative link to the repository's avatar. -func (repo *Repository) RelAvatarLink() string { - return repo.relAvatarLink(db.GetEngine(db.DefaultContext)) -} - -func (repo *Repository) relAvatarLink(e db.Engine) string { - // If no avatar - path is empty - avatarPath := repo.CustomAvatarRelativePath() - if len(avatarPath) == 0 { - switch mode := setting.RepoAvatar.Fallback; mode { - case "image": - return setting.RepoAvatar.FallbackImage - case "random": - if err := repo.generateRandomAvatar(e); err != nil { - log.Error("generateRandomAvatar: %v", err) - } - default: - // default behaviour: do not display avatar - return "" - } - } - return setting.AppSubURL + "/repo-avatars/" + url.PathEscape(repo.Avatar) -} - -// AvatarLink returns a link to the repository's avatar. -func (repo *Repository) AvatarLink() string { - return repo.avatarLink(db.GetEngine(db.DefaultContext)) -} - -// avatarLink returns user avatar absolute link. -func (repo *Repository) avatarLink(e db.Engine) string { - link := repo.relAvatarLink(e) - // we only prepend our AppURL to our known (relative, internal) avatar link to get an absolute URL - if strings.HasPrefix(link, "/") && !strings.HasPrefix(link, "//") { - return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:] - } - // otherwise, return the link as it is - return link -} - -// UploadAvatar saves custom avatar for repository. +// UploadRepoAvatar saves custom avatar for repository. // FIXME: split uploads to different subdirs in case we have massive number of repos. -func (repo *Repository) UploadAvatar(data []byte) error { +func UploadRepoAvatar(repo *repo_model.Repository, data []byte) error { m, err := avatar.Prepare(data) if err != nil { return err @@ -162,8 +86,8 @@ func (repo *Repository) UploadAvatar(data []byte) error { return committer.Commit() } -// DeleteAvatar deletes the repos's custom avatar. -func (repo *Repository) DeleteAvatar() error { +// DeleteRepoAvatar deletes the repos's custom avatar. +func DeleteRepoAvatar(repo *repo_model.Repository) error { // Avatar not exists if len(repo.Avatar) == 0 { return nil diff --git a/models/repo_branch.go b/models/repo_branch.go deleted file mode 100644 index 08e8fccb5..000000000 --- a/models/repo_branch.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2016 The Gogs Authors. All rights reserved. -// Copyright 2019 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 models - -// CanCreateBranch returns true if repository meets the requirements for creating new branches. -func (repo *Repository) CanCreateBranch() bool { - return !repo.IsMirror -} diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index 08682eef6..ab6a3bafb 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -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" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" @@ -32,11 +34,12 @@ func init() { db.RegisterModel(new(Collaboration)) } -func (repo *Repository) addCollaborator(e db.Engine, u *user_model.User) error { +func addCollaborator(ctx context.Context, repo *repo_model.Repository, u *user_model.User) error { collaboration := &Collaboration{ RepoID: repo.ID, UserID: u.ID, } + e := db.GetEngine(ctx) has, err := e.Get(collaboration) if err != nil { @@ -50,34 +53,34 @@ func (repo *Repository) addCollaborator(e db.Engine, u *user_model.User) error { return err } - return repo.recalculateUserAccess(e, u.ID) + return recalculateUserAccess(ctx, repo, u.ID) } // AddCollaborator adds new collaboration to a repository with default access mode. -func (repo *Repository) AddCollaborator(u *user_model.User) error { +func AddCollaborator(repo *repo_model.Repository, u *user_model.User) error { ctx, committer, err := db.TxContext() if err != nil { return err } defer committer.Close() - if err := repo.addCollaborator(db.GetEngine(ctx), u); err != nil { + if err := addCollaborator(ctx, repo, u); err != nil { return err } return committer.Commit() } -func (repo *Repository) getCollaborations(e db.Engine, listOptions db.ListOptions) ([]*Collaboration, error) { +func getCollaborations(e db.Engine, repoID int64, listOptions db.ListOptions) ([]*Collaboration, error) { if listOptions.Page == 0 { collaborations := make([]*Collaboration, 0, 8) - return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repo.ID}) + return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repoID}) } e = db.SetEnginePagination(e, &listOptions) collaborations := make([]*Collaboration, 0, listOptions.PageSize) - return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repo.ID}) + return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repoID}) } // Collaborator represents a user with collaboration details. @@ -86,8 +89,8 @@ type Collaborator struct { Collaboration *Collaboration } -func (repo *Repository) getCollaborators(e db.Engine, listOptions db.ListOptions) ([]*Collaborator, error) { - collaborations, err := repo.getCollaborations(e, listOptions) +func getCollaborators(e db.Engine, repoID int64, listOptions db.ListOptions) ([]*Collaborator, error) { + collaborations, err := getCollaborations(e, repoID, listOptions) if err != nil { return nil, fmt.Errorf("getCollaborations: %v", err) } @@ -97,7 +100,7 @@ func (repo *Repository) getCollaborators(e db.Engine, listOptions db.ListOptions user, err := user_model.GetUserByIDEngine(e, c.UserID) if err != nil { if user_model.IsErrUserNotExist(err) { - log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repo) + log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repoID) user = user_model.NewGhostUser() } else { return nil, err @@ -112,18 +115,18 @@ func (repo *Repository) getCollaborators(e db.Engine, listOptions db.ListOptions } // GetCollaborators returns the collaborators for a repository -func (repo *Repository) GetCollaborators(listOptions db.ListOptions) ([]*Collaborator, error) { - return repo.getCollaborators(db.GetEngine(db.DefaultContext), listOptions) +func GetCollaborators(repoID int64, listOptions db.ListOptions) ([]*Collaborator, error) { + return getCollaborators(db.GetEngine(db.DefaultContext), repoID, listOptions) } // CountCollaborators returns total number of collaborators for a repository -func (repo *Repository) CountCollaborators() (int64, error) { - return db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Count(&Collaboration{}) +func CountCollaborators(repoID int64) (int64, error) { + return db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repoID).Count(&Collaboration{}) } -func (repo *Repository) getCollaboration(e db.Engine, uid int64) (*Collaboration, error) { +func getCollaboration(e db.Engine, repoID, uid int64) (*Collaboration, error) { collaboration := &Collaboration{ - RepoID: repo.ID, + RepoID: repoID, UserID: uid, } has, err := e.Get(collaboration) @@ -133,16 +136,16 @@ func (repo *Repository) getCollaboration(e db.Engine, uid int64) (*Collaboration return collaboration, err } -func (repo *Repository) isCollaborator(e db.Engine, userID int64) (bool, error) { - return e.Get(&Collaboration{RepoID: repo.ID, UserID: userID}) +func isCollaborator(e db.Engine, repoID, userID int64) (bool, error) { + return e.Get(&Collaboration{RepoID: repoID, UserID: userID}) } // IsCollaborator check if a user is a collaborator of a repository -func (repo *Repository) IsCollaborator(userID int64) (bool, error) { - return repo.isCollaborator(db.GetEngine(db.DefaultContext), userID) +func IsCollaborator(repoID, userID int64) (bool, error) { + return isCollaborator(db.GetEngine(db.DefaultContext), repoID, userID) } -func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mode perm.AccessMode) error { +func changeCollaborationAccessMode(e db.Engine, repo *repo_model.Repository, uid int64, mode perm.AccessMode) error { // Discard invalid input if mode <= perm.AccessModeNone || mode > perm.AccessModeOwner { return nil @@ -177,14 +180,14 @@ func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mo } // ChangeCollaborationAccessMode sets new access mode for the collaboration. -func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode perm.AccessMode) error { +func ChangeCollaborationAccessMode(repo *repo_model.Repository, uid int64, mode perm.AccessMode) error { ctx, committer, err := db.TxContext() if err != nil { return err } defer committer.Close() - if err := repo.changeCollaborationAccessMode(db.GetEngine(ctx), uid, mode); err != nil { + if err := changeCollaborationAccessMode(db.GetEngine(ctx), repo, uid, mode); err != nil { return err } @@ -192,7 +195,7 @@ func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode perm.Acces } // DeleteCollaboration removes collaboration relation between the user and repository. -func (repo *Repository) DeleteCollaboration(uid int64) (err error) { +func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) { collaboration := &Collaboration{ RepoID: repo.ID, UserID: uid, @@ -208,7 +211,7 @@ func (repo *Repository) DeleteCollaboration(uid int64) (err error) { if has, err := sess.Delete(collaboration); err != nil || has == 0 { return err - } else if err = repo.recalculateAccesses(sess); err != nil { + } else if err = recalculateAccesses(ctx, repo); err != nil { return err } @@ -216,29 +219,29 @@ func (repo *Repository) DeleteCollaboration(uid int64) (err error) { return err } - if err = repo.reconsiderWatches(sess, uid); err != nil { + if err = reconsiderWatches(ctx, repo, uid); err != nil { return err } // Unassign a user from any issue (s)he has been assigned to in the repository - if err := repo.reconsiderIssueAssignees(sess, uid); err != nil { + if err := reconsiderRepoIssuesAssignee(ctx, repo, uid); err != nil { return err } return committer.Commit() } -func (repo *Repository) reconsiderIssueAssignees(e db.Engine, uid int64) error { - user, err := user_model.GetUserByIDEngine(e, uid) +func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error { + user, err := user_model.GetUserByIDEngine(db.GetEngine(ctx), uid) if err != nil { return err } - if canAssigned, err := canBeAssigned(e, user, repo, true); err != nil || canAssigned { + if canAssigned, err := canBeAssigned(ctx, user, repo, true); err != nil || canAssigned { return err } - if _, err := e.Where(builder.Eq{"assignee_id": uid}). + if _, err := db.GetEngine(ctx).Where(builder.Eq{"assignee_id": uid}). In("issue_id", builder.Select("id").From("issue").Where(builder.Eq{"repo_id": repo.ID})). Delete(&IssueAssignees{}); err != nil { return fmt.Errorf("Could not delete assignee[%d] %v", uid, err) @@ -246,11 +249,11 @@ func (repo *Repository) reconsiderIssueAssignees(e db.Engine, uid int64) error { return nil } -func (repo *Repository) reconsiderWatches(e db.Engine, uid int64) error { - if has, err := hasAccess(e, uid, repo); err != nil || has { +func reconsiderWatches(ctx context.Context, repo *repo_model.Repository, uid int64) error { + if has, err := hasAccess(ctx, uid, repo); err != nil || has { return err } - + e := db.GetEngine(ctx) if err := watchRepo(e, uid, repo.ID, false); err != nil { return err } @@ -259,7 +262,7 @@ func (repo *Repository) reconsiderWatches(e db.Engine, uid int64) error { return removeIssueWatchersByRepoID(e, uid, repo.ID) } -func (repo *Repository) getRepoTeams(e db.Engine) (teams []*Team, err error) { +func getRepoTeams(e db.Engine, repo *repo_model.Repository) (teams []*Team, err error) { return teams, e. Join("INNER", "team_repo", "team_repo.team_id = team.id"). Where("team.org_id = ?", repo.OwnerID). @@ -269,12 +272,12 @@ func (repo *Repository) getRepoTeams(e db.Engine) (teams []*Team, err error) { } // GetRepoTeams gets the list of teams that has access to the repository -func (repo *Repository) GetRepoTeams() ([]*Team, error) { - return repo.getRepoTeams(db.GetEngine(db.DefaultContext)) +func GetRepoTeams(repo *repo_model.Repository) ([]*Team, error) { + return getRepoTeams(db.GetEngine(db.DefaultContext), repo) } // IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository -func (repo *Repository) IsOwnerMemberCollaborator(userID int64) (bool, error) { +func IsOwnerMemberCollaborator(repo *repo_model.Repository, userID int64) (bool, error) { if repo.OwnerID == userID { return true, nil } diff --git a/models/repo_collaboration_test.go b/models/repo_collaboration_test.go index 94df6c27b..8b4c712f0 100644 --- a/models/repo_collaboration_test.go +++ b/models/repo_collaboration_test.go @@ -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" @@ -19,11 +20,11 @@ func TestRepository_AddCollaborator(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID, userID int64) { - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) - assert.NoError(t, repo.GetOwner()) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository) + assert.NoError(t, repo.GetOwner(db.DefaultContext)) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}).(*user_model.User) - assert.NoError(t, repo.AddCollaborator(user)) - unittest.CheckConsistencyFor(t, &Repository{ID: repoID}, &user_model.User{ID: userID}) + assert.NoError(t, AddCollaborator(repo, user)) + unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}, &user_model.User{ID: userID}) } testSuccess(1, 4) testSuccess(1, 4) @@ -33,8 +34,8 @@ func TestRepository_AddCollaborator(t *testing.T) { func TestRepository_GetCollaborators(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) - collaborators, err := repo.GetCollaborators(db.ListOptions{}) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository) + collaborators, err := GetCollaborators(repo.ID, db.ListOptions{}) assert.NoError(t, err) expectedLen, err := db.GetEngine(db.DefaultContext).Count(&Collaboration{RepoID: repoID}) assert.NoError(t, err) @@ -54,8 +55,8 @@ func TestRepository_IsCollaborator(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID, userID int64, expected bool) { - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) - actual, err := repo.IsCollaborator(userID) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository) + actual, err := IsCollaborator(repo.ID, userID) assert.NoError(t, err) assert.Equal(t, expected, actual) } @@ -68,8 +69,8 @@ func TestRepository_IsCollaborator(t *testing.T) { func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) - assert.NoError(t, repo.ChangeCollaborationAccessMode(4, perm.AccessModeAdmin)) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}).(*repo_model.Repository) + assert.NoError(t, ChangeCollaborationAccessMode(repo, 4, perm.AccessModeAdmin)) collaboration := unittest.AssertExistsAndLoadBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}).(*Collaboration) assert.EqualValues(t, perm.AccessModeAdmin, collaboration.Mode) @@ -77,23 +78,23 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { access := unittest.AssertExistsAndLoadBean(t, &Access{UserID: 4, RepoID: repo.ID}).(*Access) assert.EqualValues(t, perm.AccessModeAdmin, access.Mode) - assert.NoError(t, repo.ChangeCollaborationAccessMode(4, perm.AccessModeAdmin)) + assert.NoError(t, ChangeCollaborationAccessMode(repo, 4, perm.AccessModeAdmin)) - assert.NoError(t, repo.ChangeCollaborationAccessMode(unittest.NonexistentID, perm.AccessModeAdmin)) + assert.NoError(t, ChangeCollaborationAccessMode(repo, unittest.NonexistentID, perm.AccessModeAdmin)) - unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID}) + unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) } func TestRepository_DeleteCollaboration(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) - assert.NoError(t, repo.GetOwner()) - assert.NoError(t, repo.DeleteCollaboration(4)) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}).(*repo_model.Repository) + assert.NoError(t, repo.GetOwner(db.DefaultContext)) + assert.NoError(t, DeleteCollaboration(repo, 4)) unittest.AssertNotExistsBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}) - assert.NoError(t, repo.DeleteCollaboration(4)) + assert.NoError(t, DeleteCollaboration(repo, 4)) unittest.AssertNotExistsBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}) - unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID}) + unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) } diff --git a/models/repo_generate.go b/models/repo_generate.go index cef5fa792..6b5b8e5bc 100644 --- a/models/repo_generate.go +++ b/models/repo_generate.go @@ -12,6 +12,7 @@ import ( "strings" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -70,7 +71,7 @@ func (gt GiteaTemplate) Globs() []glob.Glob { } // GenerateTopics generates topics from a template repository -func GenerateTopics(ctx context.Context, templateRepo, generateRepo *Repository) error { +func GenerateTopics(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { for _, topic := range templateRepo.Topics { if _, err := addTopicByNameToRepo(db.GetEngine(ctx), generateRepo.ID, topic); err != nil { return err @@ -80,7 +81,7 @@ func GenerateTopics(ctx context.Context, templateRepo, generateRepo *Repository) } // GenerateGitHooks generates git hooks from a template repository -func GenerateGitHooks(ctx context.Context, templateRepo, generateRepo *Repository) error { +func GenerateGitHooks(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { generateGitRepo, err := git.OpenRepository(generateRepo.RepoPath()) if err != nil { return err @@ -113,7 +114,7 @@ func GenerateGitHooks(ctx context.Context, templateRepo, generateRepo *Repositor } // GenerateWebhooks generates webhooks from a template repository -func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *Repository) error { +func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { templateWebhooks, err := webhook.ListWebhooksByOpts(&webhook.ListWebhookOptions{RepoID: templateRepo.ID}) if err != nil { return err @@ -141,7 +142,7 @@ func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *Repositor } // GenerateAvatar generates the avatar from a template repository -func GenerateAvatar(ctx context.Context, templateRepo, generateRepo *Repository) error { +func GenerateAvatar(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { generateRepo.Avatar = strings.Replace(templateRepo.Avatar, strconv.FormatInt(templateRepo.ID, 10), strconv.FormatInt(generateRepo.ID, 10), 1) if _, err := storage.Copy(storage.RepoAvatars, generateRepo.CustomAvatarRelativePath(), storage.RepoAvatars, templateRepo.CustomAvatarRelativePath()); err != nil { return err @@ -151,7 +152,7 @@ func GenerateAvatar(ctx context.Context, templateRepo, generateRepo *Repository) } // GenerateIssueLabels generates issue labels from a template repository -func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *Repository) error { +func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { templateLabels, err := getLabelsByRepoID(db.GetEngine(ctx), templateRepo.ID, "", db.ListOptions{}) if err != nil { return err diff --git a/models/repo_list.go b/models/repo_list.go index dbcf0609b..02440bec9 100644 --- a/models/repo_list.go +++ b/models/repo_list.go @@ -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" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -25,7 +26,7 @@ import ( const RepositoryListDefaultPageSize = 64 // RepositoryList contains a list of repositories -type RepositoryList []*Repository +type RepositoryList []*repo_model.Repository func (repos RepositoryList) Len() int { return len(repos) @@ -40,7 +41,7 @@ func (repos RepositoryList) Swap(i, j int) { } // RepositoryListOfMap make list from values of map -func RepositoryListOfMap(repoMap map[int64]*Repository) RepositoryList { +func RepositoryListOfMap(repoMap map[int64]*repo_model.Repository) RepositoryList { return RepositoryList(valuesRepository(repoMap)) } @@ -69,14 +70,14 @@ func (repos RepositoryList) loadAttributes(e db.Engine) error { } // Load primary language. - stats := make(LanguageStatList, 0, len(repos)) + stats := make(repo_model.LanguageStatList, 0, len(repos)) if err := e. Where("`is_primary` = ? AND `language` != ?", true, "other"). In("`repo_id`", repoIDs). Find(&stats); err != nil { return fmt.Errorf("find primary languages: %v", err) } - stats.loadAttributes() + stats.LoadAttributes() for i := range repos { for _, st := range stats { if st.RepoID == repos[i].ID { @@ -94,46 +95,6 @@ func (repos RepositoryList) LoadAttributes() error { return repos.loadAttributes(db.GetEngine(db.DefaultContext)) } -// MirrorRepositoryList contains the mirror repositories -type MirrorRepositoryList []*Repository - -func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error { - if len(repos) == 0 { - return nil - } - - // Load mirrors. - repoIDs := make([]int64, 0, len(repos)) - for i := range repos { - if !repos[i].IsMirror { - continue - } - - repoIDs = append(repoIDs, repos[i].ID) - } - mirrors := make([]*Mirror, 0, len(repoIDs)) - if err := e. - Where("id > 0"). - In("repo_id", repoIDs). - Find(&mirrors); err != nil { - return fmt.Errorf("find mirrors: %v", err) - } - - set := make(map[int64]*Mirror) - for i := range mirrors { - set[mirrors[i].RepoID] = mirrors[i] - } - for i := range repos { - repos[i].Mirror = set[repos[i].ID] - } - return nil -} - -// LoadAttributes loads the attributes for the given MirrorRepositoryList -func (repos MirrorRepositoryList) LoadAttributes() error { - return repos.loadAttributes(db.GetEngine(db.DefaultContext)) -} - // SearchRepoOptions holds the search options type SearchRepoOptions struct { db.ListOptions @@ -392,7 +353,7 @@ func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (db var err error count, err = sess. Where(cond). - Count(new(Repository)) + Count(new(repo_model.Repository)) if err != nil { return nil, 0, fmt.Errorf("Count: %v", err) } @@ -502,3 +463,31 @@ func FindUserAccessibleRepoIDs(user *user_model.User) ([]int64, error) { } return repoIDs, nil } + +// GetUserRepositories returns a list of repositories of given user. +func GetUserRepositories(opts *SearchRepoOptions) ([]*repo_model.Repository, int64, error) { + if len(opts.OrderBy) == 0 { + opts.OrderBy = "updated_unix DESC" + } + + cond := builder.NewCond() + cond = cond.And(builder.Eq{"owner_id": opts.Actor.ID}) + if !opts.Private { + cond = cond.And(builder.Eq{"is_private": false}) + } + + if opts.LowerNames != nil && len(opts.LowerNames) > 0 { + cond = cond.And(builder.In("lower_name", opts.LowerNames)) + } + + sess := db.GetEngine(db.DefaultContext) + + count, err := sess.Where(cond).Count(new(repo_model.Repository)) + if err != nil { + return nil, 0, fmt.Errorf("Count: %v", err) + } + + sess = sess.Where(cond).OrderBy(opts.OrderBy.String()) + repos := make([]*repo_model.Repository, 0, opts.PageSize) + return repos, count, db.SetSessionPagination(sess, opts).Find(&repos) +} diff --git a/models/repo_permission.go b/models/repo_permission.go index 61d3d24e3..3dc8db92b 100644 --- a/models/repo_permission.go +++ b/models/repo_permission.go @@ -5,10 +5,12 @@ package models import ( + "context" "fmt" "code.gitea.io/gitea/models/db" perm_model "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" @@ -17,7 +19,7 @@ import ( // Permission contains all the permissions related variables to a repository for a user type Permission struct { AccessMode perm_model.AccessMode - Units []*RepoUnit + Units []*repo_model.RepoUnit UnitsMode map[unit.Type]perm_model.AccessMode } @@ -142,11 +144,11 @@ func (p *Permission) ColorFormat(s fmt.State) { } // GetUserRepoPermission returns the user permissions to the repository -func GetUserRepoPermission(repo *Repository, user *user_model.User) (Permission, error) { - return getUserRepoPermission(db.GetEngine(db.DefaultContext), repo, user) +func GetUserRepoPermission(repo *repo_model.Repository, user *user_model.User) (Permission, error) { + return getUserRepoPermission(db.DefaultContext, repo, user) } -func getUserRepoPermission(e db.Engine, repo *Repository, user *user_model.User) (perm Permission, err error) { +func getUserRepoPermission(ctx context.Context, repo *repo_model.Repository, user *user_model.User) (perm Permission, err error) { if log.IsTrace() { defer func() { if user == nil { @@ -168,26 +170,28 @@ func getUserRepoPermission(e db.Engine, repo *Repository, user *user_model.User) return } - var isCollaborator bool + e := db.GetEngine(ctx) + + var is bool if user != nil { - isCollaborator, err = repo.isCollaborator(e, user.ID) + is, err = isCollaborator(e, repo.ID, user.ID) if err != nil { return perm, err } } - if err = repo.getOwner(e); err != nil { + if err = repo.GetOwner(ctx); err != nil { return } // Prevent strangers from checking out public repo of private organization/users // Allow user if they are collaborator of a repo within a private user or a private organization but not a member of the organization itself - if !hasOrgOrUserVisible(e, repo.Owner, user) && !isCollaborator { + if !hasOrgOrUserVisible(e, repo.Owner, user) && !is { perm.AccessMode = perm_model.AccessModeNone return } - if err = repo.getUnits(e); err != nil { + if err = repo.LoadUnits(ctx); err != nil { return } @@ -211,7 +215,7 @@ func getUserRepoPermission(e db.Engine, repo *Repository, user *user_model.User) return } - if err = repo.getOwner(e); err != nil { + if err = repo.GetOwner(ctx); err != nil { return } if !repo.Owner.IsOrganization() { @@ -221,7 +225,7 @@ func getUserRepoPermission(e db.Engine, repo *Repository, user *user_model.User) perm.UnitsMode = make(map[unit.Type]perm_model.AccessMode) // Collaborators on organization - if isCollaborator { + if is { for _, u := range repo.Units { perm.UnitsMode[u.Type] = perm.AccessMode } @@ -263,7 +267,7 @@ func getUserRepoPermission(e db.Engine, repo *Repository, user *user_model.User) } // remove no permission units - perm.Units = make([]*RepoUnit, 0, len(repo.Units)) + perm.Units = make([]*repo_model.RepoUnit, 0, len(repo.Units)) for t := range perm.UnitsMode { for _, u := range repo.Units { if u.Type == t { @@ -276,18 +280,16 @@ func getUserRepoPermission(e db.Engine, repo *Repository, user *user_model.User) } // IsUserRealRepoAdmin check if this user is real repo admin -func IsUserRealRepoAdmin(repo *Repository, user *user_model.User) (bool, error) { +func IsUserRealRepoAdmin(repo *repo_model.Repository, user *user_model.User) (bool, error) { if repo.OwnerID == user.ID { return true, nil } - sess := db.GetEngine(db.DefaultContext) - - if err := repo.getOwner(sess); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { return false, err } - accessMode, err := accessLevel(sess, user, repo) + accessMode, err := accessLevel(db.GetEngine(db.DefaultContext), user, repo) if err != nil { return false, err } @@ -296,11 +298,11 @@ func IsUserRealRepoAdmin(repo *Repository, user *user_model.User) (bool, error) } // IsUserRepoAdmin return true if user has admin right of a repo -func IsUserRepoAdmin(repo *Repository, user *user_model.User) (bool, error) { +func IsUserRepoAdmin(repo *repo_model.Repository, user *user_model.User) (bool, error) { return isUserRepoAdmin(db.GetEngine(db.DefaultContext), repo, user) } -func isUserRepoAdmin(e db.Engine, repo *Repository, user *user_model.User) (bool, error) { +func isUserRepoAdmin(e db.Engine, repo *repo_model.Repository, user *user_model.User) (bool, error) { if user == nil || repo == nil { return false, nil } @@ -331,62 +333,62 @@ func isUserRepoAdmin(e db.Engine, repo *Repository, user *user_model.User) (bool // AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // user does not have access. -func AccessLevel(user *user_model.User, repo *Repository) (perm_model.AccessMode, error) { - return accessLevelUnit(db.GetEngine(db.DefaultContext), user, repo, unit.TypeCode) +func AccessLevel(user *user_model.User, repo *repo_model.Repository) (perm_model.AccessMode, error) { + return accessLevelUnit(db.DefaultContext, user, repo, unit.TypeCode) } // AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the // user does not have access. -func AccessLevelUnit(user *user_model.User, repo *Repository, unitType unit.Type) (perm_model.AccessMode, error) { - return accessLevelUnit(db.GetEngine(db.DefaultContext), user, repo, unitType) +func AccessLevelUnit(user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { + return accessLevelUnit(db.DefaultContext, user, repo, unitType) } -func accessLevelUnit(e db.Engine, user *user_model.User, repo *Repository, unitType unit.Type) (perm_model.AccessMode, error) { - perm, err := getUserRepoPermission(e, repo, user) +func accessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { + perm, err := getUserRepoPermission(ctx, repo, user) if err != nil { return perm_model.AccessModeNone, err } return perm.UnitAccessMode(unitType), nil } -func hasAccessUnit(e db.Engine, user *user_model.User, repo *Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) { - mode, err := accessLevelUnit(e, user, repo, unitType) +func hasAccessUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) { + mode, err := accessLevelUnit(ctx, user, repo, unitType) return testMode <= mode, err } // HasAccessUnit returns true if user has testMode to the unit of the repository -func HasAccessUnit(user *user_model.User, repo *Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) { - return hasAccessUnit(db.GetEngine(db.DefaultContext), user, repo, unitType, testMode) +func HasAccessUnit(user *user_model.User, repo *repo_model.Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) { + return hasAccessUnit(db.DefaultContext, user, repo, unitType, testMode) } // CanBeAssigned return true if user can be assigned to issue or pull requests in repo // Currently any write access (code, issues or pr's) is assignable, to match assignee list in user interface. // FIXME: user could send PullRequest also could be assigned??? -func CanBeAssigned(user *user_model.User, repo *Repository, isPull bool) (bool, error) { - return canBeAssigned(db.GetEngine(db.DefaultContext), user, repo, isPull) +func CanBeAssigned(user *user_model.User, repo *repo_model.Repository, isPull bool) (bool, error) { + return canBeAssigned(db.DefaultContext, user, repo, isPull) } -func canBeAssigned(e db.Engine, user *user_model.User, repo *Repository, _ bool) (bool, error) { +func canBeAssigned(ctx context.Context, user *user_model.User, repo *repo_model.Repository, _ bool) (bool, error) { if user.IsOrganization() { return false, fmt.Errorf("Organization can't be added as assignee [user_id: %d, repo_id: %d]", user.ID, repo.ID) } - perm, err := getUserRepoPermission(e, repo, user) + perm, err := getUserRepoPermission(ctx, repo, user) if err != nil { return false, err } return perm.CanAccessAny(perm_model.AccessModeWrite, unit.TypeCode, unit.TypeIssues, unit.TypePullRequests), nil } -func hasAccess(e db.Engine, userID int64, repo *Repository) (bool, error) { +func hasAccess(ctx context.Context, userID int64, repo *repo_model.Repository) (bool, error) { var user *user_model.User var err error if userID > 0 { - user, err = user_model.GetUserByIDEngine(e, userID) + user, err = user_model.GetUserByIDEngine(db.GetEngine(ctx), userID) if err != nil { return false, err } } - perm, err := getUserRepoPermission(e, repo, user) + perm, err := getUserRepoPermission(ctx, repo, user) if err != nil { return false, err } @@ -394,15 +396,15 @@ func hasAccess(e db.Engine, userID int64, repo *Repository) (bool, error) { } // HasAccess returns true if user has access to repo -func HasAccess(userID int64, repo *Repository) (bool, error) { - return hasAccess(db.GetEngine(db.DefaultContext), userID, repo) +func HasAccess(userID int64, repo *repo_model.Repository) (bool, error) { + return hasAccess(db.DefaultContext, userID, repo) } // FilterOutRepoIdsWithoutUnitAccess filter out repos where user has no access to repositories func FilterOutRepoIdsWithoutUnitAccess(u *user_model.User, repoIDs []int64, units ...unit.Type) ([]int64, error) { i := 0 for _, rID := range repoIDs { - repo, err := GetRepositoryByID(rID) + repo, err := repo_model.GetRepositoryByID(rID) if err != nil { return nil, err } diff --git a/models/repo_permission_test.go b/models/repo_permission_test.go index 795b5f211..f2664d810 100644 --- a/models/repo_permission_test.go +++ b/models/repo_permission_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models/db" perm_model "code.gitea.io/gitea/models/perm" + 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" @@ -20,8 +21,8 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // public non-organization repo - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) - assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}).(*repo_model.Repository) + assert.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) @@ -33,7 +34,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } // change to collaborator - assert.NoError(t, repo.AddCollaborator(user)) + assert.NoError(t, AddCollaborator(repo, user)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -73,8 +74,8 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // private non-organization repo - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) - assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) + assert.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) @@ -86,7 +87,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } // change to collaborator to default write access - assert.NoError(t, repo.AddCollaborator(user)) + assert.NoError(t, AddCollaborator(repo, user)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -94,7 +95,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo.ChangeCollaborationAccessMode(user.ID, perm_model.AccessModeRead)) + assert.NoError(t, ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -125,8 +126,8 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // public organization repo - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository) - assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 32}).(*repo_model.Repository) + assert.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) @@ -138,7 +139,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } // change to collaborator to default write access - assert.NoError(t, repo.AddCollaborator(user)) + assert.NoError(t, AddCollaborator(repo, user)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -146,7 +147,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo.ChangeCollaborationAccessMode(user.ID, perm_model.AccessModeRead)) + assert.NoError(t, ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -187,8 +188,8 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // private organization repo - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) - assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24}).(*repo_model.Repository) + assert.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) @@ -200,7 +201,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { } // change to collaborator to default write access - assert.NoError(t, repo.AddCollaborator(user)) + assert.NoError(t, AddCollaborator(repo, user)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -208,7 +209,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo.ChangeCollaborationAccessMode(user.ID, perm_model.AccessModeRead)) + assert.NoError(t, ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) perm, err = GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { diff --git a/models/repo_redirect_test.go b/models/repo_redirect_test.go index 6e5b9fc08..c6d471448 100644 --- a/models/repo_redirect_test.go +++ b/models/repo_redirect_test.go @@ -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" @@ -28,7 +29,7 @@ func TestNewRepoRedirect(t *testing.T) { // redirect to a completely new name 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) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ @@ -47,7 +48,7 @@ func TestNewRepoRedirect2(t *testing.T) { // redirect to previously used name 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) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ @@ -66,7 +67,7 @@ func TestNewRepoRedirect3(t *testing.T) { // redirect for a previously-unredirected repo assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ diff --git a/models/repo_sign.go b/models/repo_sign.go index f30ba4748..1c736a62d 100644 --- a/models/repo_sign.go +++ b/models/repo_sign.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/login" + 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" @@ -144,7 +145,7 @@ Loop: } // SignWikiCommit determines if we should sign the commits to this repository wiki -func (repo *Repository) SignWikiCommit(u *user_model.User) (bool, string, *git.Signature, error) { +func SignWikiCommit(repo *repo_model.Repository, u *user_model.User) (bool, string, *git.Signature, error) { rules := signingModeFromStrings(setting.Repository.Signing.Wiki) signingKey, sig := SigningKey(repo.WikiPath()) if signingKey == "" { @@ -197,7 +198,7 @@ Loop: } // SignCRUDAction determines if we should sign a CRUD commit to this repository -func (repo *Repository) SignCRUDAction(u *user_model.User, tmpBasePath, parentCommit string) (bool, string, *git.Signature, error) { +func SignCRUDAction(repo *repo_model.Repository, u *user_model.User, tmpBasePath, parentCommit string) (bool, string, *git.Signature, error) { rules := signingModeFromStrings(setting.Repository.Signing.CRUDActions) signingKey, sig := SigningKey(repo.RepoPath()) if signingKey == "" { diff --git a/models/repo_test.go b/models/repo_test.go index e6aaedaae..72a297734 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -25,7 +25,7 @@ import ( func TestMetas(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := &Repository{Name: "testRepo"} + repo := &repo_model.Repository{Name: "testRepo"} repo.Owner = &user_model.User{Name: "testOwner"} repo.OwnerName = repo.Owner.Name @@ -35,15 +35,15 @@ func TestMetas(t *testing.T) { assert.Equal(t, "testRepo", metas["repo"]) assert.Equal(t, "testOwner", metas["user"]) - externalTracker := RepoUnit{ + externalTracker := repo_model.RepoUnit{ Type: unit.TypeExternalTracker, - Config: &ExternalTrackerConfig{ + Config: &repo_model.ExternalTrackerConfig{ ExternalTrackerFormat: "https://someurl.com/{user}/{repo}/{issue}", }, } testSuccess := func(expectedStyle string) { - repo.Units = []*RepoUnit{&externalTracker} + repo.Units = []*repo_model.RepoUnit{&externalTracker} repo.RenderingMetas = nil metas := repo.ComposeMetas() assert.Equal(t, expectedStyle, metas["style"]) @@ -60,7 +60,7 @@ func TestMetas(t *testing.T) { externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleNumeric testSuccess(markup.IssueNameStyleNumeric) - repo, err := GetRepositoryByID(3) + repo, err := repo_model.GetRepositoryByID(3) assert.NoError(t, err) metas = repo.ComposeMetas() @@ -70,40 +70,11 @@ func TestMetas(t *testing.T) { assert.Equal(t, ",owners,team1,", metas["teams"]) } -func TestGetRepositoryCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - - count, err1 := GetRepositoryCount(db.DefaultContext, 10) - privateCount, err2 := GetPrivateRepositoryCount(&user_model.User{ID: int64(10)}) - publicCount, err3 := GetPublicRepositoryCount(&user_model.User{ID: int64(10)}) - assert.NoError(t, err1) - assert.NoError(t, err2) - assert.NoError(t, err3) - assert.Equal(t, int64(3), count) - assert.Equal(t, privateCount+publicCount, count) -} - -func TestGetPublicRepositoryCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - - count, err := GetPublicRepositoryCount(&user_model.User{ID: int64(10)}) - assert.NoError(t, err) - assert.Equal(t, int64(1), count) -} - -func TestGetPrivateRepositoryCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - - count, err := GetPrivateRepositoryCount(&user_model.User{ID: int64(10)}) - assert.NoError(t, err) - assert.Equal(t, int64(2), count) -} - func TestUpdateRepositoryVisibilityChanged(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility - repo, err := GetRepositoryByID(9) + repo, err := repo_model.GetRepositoryByID(9) assert.NoError(t, err) repo.IsPrivate = true @@ -123,24 +94,24 @@ func TestGetUserFork(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // User13 has repo 11 forked from repo10 - repo, err := GetRepositoryByID(10) + repo, err := repo_model.GetRepositoryByID(10) assert.NoError(t, err) assert.NotNil(t, repo) - repo, err = repo.GetUserFork(13) + repo, err = GetUserFork(repo.ID, 13) assert.NoError(t, err) assert.NotNil(t, repo) - repo, err = GetRepositoryByID(9) + repo, err = repo_model.GetRepositoryByID(9) assert.NoError(t, err) assert.NotNil(t, repo) - repo, err = repo.GetUserFork(13) + repo, err = GetUserFork(repo.ID, 13) assert.NoError(t, err) assert.Nil(t, repo) } func TestRepoAPIURL(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL()) } @@ -152,9 +123,9 @@ func TestUploadAvatar(t *testing.T) { png.Encode(&buff, myImage) assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository) - err := repo.UploadAvatar(buff.Bytes()) + err := UploadRepoAvatar(repo, buff.Bytes()) assert.NoError(t, err) assert.Equal(t, fmt.Sprintf("%d-%x", 10, md5.Sum(buff.Bytes())), repo.Avatar) } @@ -166,9 +137,9 @@ func TestUploadBigAvatar(t *testing.T) { png.Encode(&buff, myImage) assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository) - err := repo.UploadAvatar(buff.Bytes()) + err := UploadRepoAvatar(repo, buff.Bytes()) assert.Error(t, err) } @@ -179,12 +150,12 @@ func TestDeleteAvatar(t *testing.T) { png.Encode(&buff, myImage) assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository) - err := repo.UploadAvatar(buff.Bytes()) + err := UploadRepoAvatar(repo, buff.Bytes()) assert.NoError(t, err) - err = repo.DeleteAvatar() + err = DeleteRepoAvatar(repo) assert.NoError(t, err) assert.Equal(t, "", repo.Avatar) @@ -200,15 +171,15 @@ func TestRepoGetReviewers(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // test public repo - repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) - reviewers, err := repo1.GetReviewers(2, 2) + reviewers, err := GetReviewers(repo1, 2, 2) assert.NoError(t, err) assert.Len(t, reviewers, 4) // test private repo - repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) - reviewers, err = repo2.GetReviewers(2, 2) + repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) + reviewers, err = GetReviewers(repo2, 2, 2) assert.NoError(t, err) assert.Empty(t, reviewers) } @@ -216,13 +187,13 @@ func TestRepoGetReviewers(t *testing.T) { func TestRepoGetReviewerTeams(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) - teams, err := repo2.GetReviewerTeams() + repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) + teams, err := GetReviewerTeams(repo2) assert.NoError(t, err) assert.Empty(t, teams) - repo3 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) - teams, err = repo3.GetReviewerTeams() + repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) + teams, err = GetReviewerTeams(repo3) assert.NoError(t, err) assert.Len(t, teams, 2) } @@ -232,12 +203,12 @@ func TestLinkedRepository(t *testing.T) { testCases := []struct { name string attachID int64 - expectedRepo *Repository + expectedRepo *repo_model.Repository expectedUnitType unit.Type }{ - {"LinkedIssue", 1, &Repository{ID: 1}, unit.TypeIssues}, - {"LinkedComment", 3, &Repository{ID: 1}, unit.TypePullRequests}, - {"LinkedRelease", 9, &Repository{ID: 1}, unit.TypeReleases}, + {"LinkedIssue", 1, &repo_model.Repository{ID: 1}, unit.TypeIssues}, + {"LinkedComment", 3, &repo_model.Repository{ID: 1}, unit.TypePullRequests}, + {"LinkedRelease", 9, &repo_model.Repository{ID: 1}, unit.TypeReleases}, {"Notlinked", 10, nil, -1}, } for _, tc := range testCases { diff --git a/models/repo_transfer.go b/models/repo_transfer.go index 9918a10d7..398ed0755 100644 --- a/models/repo_transfer.go +++ b/models/repo_transfer.go @@ -9,6 +9,7 @@ import ( "os" "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/timeutil" @@ -96,7 +97,7 @@ func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool { // GetPendingRepositoryTransfer fetches the most recent and ongoing transfer // process for the repository -func GetPendingRepositoryTransfer(repo *Repository) (*RepoTransfer, error) { +func GetPendingRepositoryTransfer(repo *repo_model.Repository) (*RepoTransfer, error) { transfer := new(RepoTransfer) has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Get(transfer) @@ -118,7 +119,7 @@ func deleteRepositoryTransfer(e db.Engine, repoID int64) error { // CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry, // thus cancel the transfer process. -func CancelRepositoryTransfer(repo *Repository) error { +func CancelRepositoryTransfer(repo *repo_model.Repository) error { ctx, committer, err := db.TxContext() if err != nil { return err @@ -126,7 +127,7 @@ func CancelRepositoryTransfer(repo *Repository) error { defer committer.Close() sess := db.GetEngine(ctx) - repo.Status = RepositoryReady + repo.Status = repo_model.RepositoryReady if err := updateRepositoryCols(sess, repo, "status"); err != nil { return err } @@ -139,11 +140,11 @@ func CancelRepositoryTransfer(repo *Repository) error { } // TestRepositoryReadyForTransfer make sure repo is ready to transfer -func TestRepositoryReadyForTransfer(status RepositoryStatus) error { +func TestRepositoryReadyForTransfer(status repo_model.RepositoryStatus) error { switch status { - case RepositoryBeingMigrated: + case repo_model.RepositoryBeingMigrated: return fmt.Errorf("repo is not ready, currently migrating") - case RepositoryPendingTransfer: + case repo_model.RepositoryPendingTransfer: return ErrRepoTransferInProgress{} } return nil @@ -159,7 +160,7 @@ func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int defer committer.Close() sess := db.GetEngine(ctx) - repo, err := getRepositoryByID(sess, repoID) + repo, err := repo_model.GetRepositoryByIDCtx(ctx, repoID) if err != nil { return err } @@ -169,13 +170,13 @@ func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int return err } - repo.Status = RepositoryPendingTransfer + repo.Status = repo_model.RepositoryPendingTransfer if err := updateRepositoryCols(sess, repo, "status"); err != nil { return err } // Check if new owner has repository with same name. - if has, err := isRepositoryExist(sess, newOwner, repo.Name); err != nil { + if has, err := repo_model.IsRepositoryExistCtx(ctx, newOwner, repo.Name); err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { return ErrRepoAlreadyExist{newOwner.LowerName, repo.Name} @@ -202,7 +203,7 @@ func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int } // TransferOwnership transfers all corresponding repository items from old user to new one. -func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Repository) (err error) { +func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_model.Repository) (err error) { repoRenamed := false wikiRenamed := false oldOwnerName := doer.Name @@ -218,14 +219,16 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Reposit } if repoRenamed { - if err := util.Rename(RepoPath(newOwnerName, repo.Name), RepoPath(oldOwnerName, repo.Name)); err != nil { - log.Critical("Unable to move repository %s/%s directory from %s back to correct place %s: %v", oldOwnerName, repo.Name, RepoPath(newOwnerName, repo.Name), RepoPath(oldOwnerName, repo.Name), err) + if err := util.Rename(repo_model.RepoPath(newOwnerName, repo.Name), repo_model.RepoPath(oldOwnerName, repo.Name)); err != nil { + log.Critical("Unable to move repository %s/%s directory from %s back to correct place %s: %v", oldOwnerName, repo.Name, + repo_model.RepoPath(newOwnerName, repo.Name), repo_model.RepoPath(oldOwnerName, repo.Name), err) } } if wikiRenamed { - if err := util.Rename(WikiPath(newOwnerName, repo.Name), WikiPath(oldOwnerName, repo.Name)); err != nil { - log.Critical("Unable to move wiki for repository %s/%s directory from %s back to correct place %s: %v", oldOwnerName, repo.Name, WikiPath(newOwnerName, repo.Name), WikiPath(oldOwnerName, repo.Name), err) + if err := util.Rename(repo_model.WikiPath(newOwnerName, repo.Name), repo_model.WikiPath(oldOwnerName, repo.Name)); err != nil { + log.Critical("Unable to move wiki for repository %s/%s directory from %s back to correct place %s: %v", oldOwnerName, repo.Name, + repo_model.WikiPath(newOwnerName, repo.Name), repo_model.WikiPath(oldOwnerName, repo.Name), err) } } @@ -250,7 +253,7 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Reposit newOwnerName = newOwner.Name // ensure capitalisation matches // Check if new owner has repository with same name. - if has, err := isRepositoryExist(sess, newOwner, repo.Name); err != nil { + if has, err := repo_model.IsRepositoryExistCtx(ctx, newOwner, repo.Name); err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { return ErrRepoAlreadyExist{newOwnerName, repo.Name} @@ -271,7 +274,7 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Reposit } // Remove redundant collaborators. - collaborators, err := repo.getCollaborators(sess, db.ListOptions{}) + collaborators, err := getCollaborators(sess, repo.ID, db.ListOptions{}) if err != nil { return fmt.Errorf("getCollaborators: %v", err) } @@ -316,12 +319,12 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Reposit } for _, t := range teams { if t.IncludesAllRepositories { - if err := t.addRepository(sess, repo); err != nil { + if err := t.addRepository(ctx, repo); err != nil { return fmt.Errorf("addRepository: %v", err) } } } - } else if err := repo.recalculateAccesses(sess); err != nil { + } else if err := recalculateAccesses(ctx, repo); err != nil { // Organization called this in addRepository method. return fmt.Errorf("recalculateAccesses: %v", err) } @@ -378,19 +381,19 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Reposit return fmt.Errorf("Failed to create dir %s: %v", dir, err) } - if err := util.Rename(RepoPath(oldOwner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil { + if err := util.Rename(repo_model.RepoPath(oldOwner.Name, repo.Name), repo_model.RepoPath(newOwner.Name, repo.Name)); err != nil { return fmt.Errorf("rename repository directory: %v", err) } repoRenamed = true // Rename remote wiki repository to new path and delete local copy. - wikiPath := WikiPath(oldOwner.Name, repo.Name) + wikiPath := repo_model.WikiPath(oldOwner.Name, repo.Name) if isExist, err := util.IsExist(wikiPath); err != nil { log.Error("Unable to check if %s exists. Error: %v", wikiPath, err) return err } else if isExist { - if err := util.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil { + if err := util.Rename(wikiPath, repo_model.WikiPath(newOwner.Name, repo.Name)); err != nil { return fmt.Errorf("rename repository wiki: %v", err) } wikiRenamed = true @@ -399,7 +402,7 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *Reposit if err := deleteRepositoryTransfer(sess, repo.ID); err != nil { return fmt.Errorf("deleteRepositoryTransfer: %v", err) } - repo.Status = RepositoryReady + repo.Status = repo_model.RepositoryReady if err := updateRepositoryCols(sess, repo, "status"); err != nil { return err } diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 1bde5628c..9125bb8c8 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -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" @@ -17,7 +18,7 @@ func TestRepositoryTransfer(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) transfer, err := GetPendingRepositoryTransfer(repo) assert.NoError(t, err) diff --git a/models/repo_watch.go b/models/repo_watch.go index e225c945e..6ae478d65 100644 --- a/models/repo_watch.go +++ b/models/repo_watch.go @@ -5,9 +5,11 @@ package models import ( + "context" "fmt" "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/setting" @@ -166,9 +168,9 @@ func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) { Find(&ids) } -// GetWatchers returns range of users watching given repository. -func (repo *Repository) GetWatchers(opts db.ListOptions) ([]*user_model.User, error) { - sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repo.ID). +// GetRepoWatchers returns range of users watching given repository. +func GetRepoWatchers(repoID int64, opts db.ListOptions) ([]*user_model.User, error) { + sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repoID). Join("LEFT", "watch", "`user`.id=`watch`.user_id"). And("`watch`.mode<>?", RepoWatchModeDont) if opts.Page > 0 { @@ -182,14 +184,16 @@ func (repo *Repository) GetWatchers(opts db.ListOptions) ([]*user_model.User, er return users, sess.Find(&users) } -func notifyWatchers(e db.Engine, actions ...*Action) error { +func notifyWatchers(ctx context.Context, actions ...*Action) error { var watchers []*Watch - var repo *Repository + var repo *repo_model.Repository var err error var permCode []bool var permIssue []bool var permPR []bool + e := db.GetEngine(ctx) + for _, act := range actions { repoChanged := repo == nil || repo.ID != act.RepoID @@ -212,7 +216,7 @@ func notifyWatchers(e db.Engine, actions ...*Action) error { repo = act.Repo // check repo owner exist. - if err := act.Repo.getOwner(e); err != nil { + if err := act.Repo.GetOwner(ctx); err != nil { return fmt.Errorf("can't get repo owner: %v", err) } } else if act.Repo == nil { @@ -240,7 +244,7 @@ func notifyWatchers(e db.Engine, actions ...*Action) error { permPR[i] = false continue } - perm, err := getUserRepoPermission(e, repo, user) + perm, err := getUserRepoPermission(ctx, repo, user) if err != nil { permCode[i] = false permIssue[i] = false @@ -286,7 +290,7 @@ func notifyWatchers(e db.Engine, actions ...*Action) error { // NotifyWatchers creates batch of actions for every watcher. func NotifyWatchers(actions ...*Action) error { - return notifyWatchers(db.GetEngine(db.DefaultContext), actions...) + return notifyWatchers(db.DefaultContext, actions...) } // NotifyWatchersActions creates batch of actions for every watcher. @@ -297,7 +301,7 @@ func NotifyWatchersActions(acts []*Action) error { } defer committer.Close() for _, act := range acts { - if err := notifyWatchers(db.GetEngine(ctx), act); err != nil { + if err := notifyWatchers(ctx, act); err != nil { return err } } diff --git a/models/repo_watch_test.go b/models/repo_watch_test.go index b7efcba71..1a6052139 100644 --- a/models/repo_watch_test.go +++ b/models/repo_watch_test.go @@ -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/setting" @@ -33,17 +34,17 @@ func TestWatchRepo(t *testing.T) { assert.NoError(t, WatchRepo(userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &Watch{RepoID: repoID, UserID: userID}) - unittest.CheckConsistencyFor(t, &Repository{ID: repoID}) + unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) assert.NoError(t, WatchRepo(userID, repoID, false)) unittest.AssertNotExistsBean(t, &Watch{RepoID: repoID, UserID: userID}) - unittest.CheckConsistencyFor(t, &Repository{ID: repoID}) + unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) } func TestGetWatchers(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) watches, err := GetWatchers(repo.ID) assert.NoError(t, err) // One watchers are inactive, thus minus 1 @@ -60,16 +61,16 @@ func TestGetWatchers(t *testing.T) { func TestRepository_GetWatchers(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) + watchers, err := GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) for _, watcher := range watchers { unittest.AssertExistsAndLoadBean(t, &Watch{UserID: watcher.ID, RepoID: repo.ID}) } - repo = unittest.AssertExistsAndLoadBean(t, &Repository{ID: 9}).(*Repository) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9}).(*repo_model.Repository) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, 0) } @@ -114,8 +115,8 @@ func TestNotifyWatchers(t *testing.T) { func TestWatchIfAuto(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) + watchers, err := GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) @@ -125,13 +126,13 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, WatchIfAuto(8, 1, true)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, WatchIfAuto(10, 1, true)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) @@ -139,31 +140,31 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, WatchIfAuto(8, 1, true)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, WatchIfAuto(12, 1, false)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should add watch assert.NoError(t, WatchIfAuto(12, 1, true)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount+1) // Should remove watch, inhibit from adding auto assert.NoError(t, WatchRepo(12, 1, false)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Must not add watch assert.NoError(t, WatchIfAuto(12, 1, true)) - watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) + watchers, err = GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) } diff --git a/models/review.go b/models/review.go index eebf79687..eeb33611c 100644 --- a/models/review.go +++ b/models/review.go @@ -5,6 +5,7 @@ package models import ( + "context" "fmt" "strings" @@ -85,20 +86,20 @@ func init() { db.RegisterModel(new(Review)) } -func (r *Review) loadCodeComments(e db.Engine) (err error) { +func (r *Review) loadCodeComments(ctx context.Context) (err error) { if r.CodeComments != nil { return } - if err = r.loadIssue(e); err != nil { + if err = r.loadIssue(db.GetEngine(ctx)); err != nil { return } - r.CodeComments, err = fetchCodeCommentsByReview(e, r.Issue, nil, r) + r.CodeComments, err = fetchCodeCommentsByReview(ctx, r.Issue, nil, r) return } // LoadCodeComments loads CodeComments func (r *Review) LoadCodeComments() error { - return r.loadCodeComments(db.GetEngine(db.DefaultContext)) + return r.loadCodeComments(db.DefaultContext) } func (r *Review) loadIssue(e db.Engine) (err error) { @@ -136,11 +137,12 @@ func (r *Review) LoadReviewerTeam() error { return r.loadReviewerTeam(db.GetEngine(db.DefaultContext)) } -func (r *Review) loadAttributes(e db.Engine) (err error) { +func (r *Review) loadAttributes(ctx context.Context) (err error) { + e := db.GetEngine(ctx) if err = r.loadIssue(e); err != nil { return } - if err = r.loadCodeComments(e); err != nil { + if err = r.loadCodeComments(ctx); err != nil { return } if err = r.loadReviewer(e); err != nil { @@ -154,7 +156,7 @@ func (r *Review) loadAttributes(e db.Engine) (err error) { // LoadAttributes loads all attributes except CodeComments func (r *Review) LoadAttributes() error { - return r.loadAttributes(db.GetEngine(db.DefaultContext)) + return r.loadAttributes(db.DefaultContext) } func getReviewByID(e db.Engine, id int64) (*Review, error) { @@ -235,15 +237,15 @@ type CreateReviewOptions struct { // IsOfficialReviewer check if at least one of the provided reviewers can make official reviews in issue (counts towards required approvals) func IsOfficialReviewer(issue *Issue, reviewers ...*user_model.User) (bool, error) { - return isOfficialReviewer(db.GetEngine(db.DefaultContext), issue, reviewers...) + return isOfficialReviewer(db.DefaultContext, issue, reviewers...) } -func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*user_model.User) (bool, error) { - pr, err := getPullRequestByIssueID(e, issue.ID) +func isOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_model.User) (bool, error) { + pr, err := getPullRequestByIssueID(db.GetEngine(ctx), issue.ID) if err != nil { return false, err } - if err = pr.loadProtectedBranch(e); err != nil { + if err = pr.loadProtectedBranch(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -251,7 +253,7 @@ func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*user_model.User } for _, reviewer := range reviewers { - official, err := pr.ProtectedBranch.isUserOfficialReviewer(e, reviewer) + official, err := isUserOfficialReviewer(ctx, pr.ProtectedBranch, reviewer) if official || err != nil { return official, err } @@ -262,15 +264,15 @@ func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*user_model.User // IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals) func IsOfficialReviewerTeam(issue *Issue, team *Team) (bool, error) { - return isOfficialReviewerTeam(db.GetEngine(db.DefaultContext), issue, team) + return isOfficialReviewerTeam(db.DefaultContext, issue, team) } -func isOfficialReviewerTeam(e db.Engine, issue *Issue, team *Team) (bool, error) { - pr, err := getPullRequestByIssueID(e, issue.ID) +func isOfficialReviewerTeam(ctx context.Context, issue *Issue, team *Team) (bool, error) { + pr, err := getPullRequestByIssueID(db.GetEngine(ctx), issue.ID) if err != nil { return false, err } - if err = pr.loadProtectedBranch(e); err != nil { + if err = pr.loadProtectedBranch(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -385,7 +387,7 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co if _, err := sess.Exec("UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil { return nil, nil, err } - if official, err = isOfficialReviewer(sess, issue, doer); err != nil { + if official, err = isOfficialReviewer(ctx, issue, doer); err != nil { return nil, nil, err } } @@ -403,7 +405,7 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co return nil, nil, err } } else { - if err := review.loadCodeComments(sess); err != nil { + if err := review.loadCodeComments(ctx); err != nil { return nil, nil, err } if reviewType != ReviewTypeApprove && len(review.CodeComments) == 0 && len(strings.TrimSpace(content)) == 0 { @@ -415,7 +417,7 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co if _, err := sess.Exec("UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil { return nil, nil, err } - if official, err = isOfficialReviewer(sess, issue, doer); err != nil { + if official, err = isOfficialReviewer(ctx, issue, doer); err != nil { return nil, nil, err } } @@ -647,7 +649,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment, return nil, nil } - official, err := isOfficialReviewer(sess, issue, reviewer, doer) + official, err := isOfficialReviewer(ctx, issue, reviewer, doer) if err != nil { return nil, err } else if official { @@ -705,7 +707,7 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Commen return nil, err } - official, err := isOfficialReviewer(sess, issue, reviewer) + official, err := isOfficialReviewer(ctx, issue, reviewer) if err != nil { return nil, err } else if official { @@ -756,11 +758,11 @@ func AddTeamReviewRequest(issue *Issue, reviewer *Team, doer *user_model.User) ( return nil, nil } - official, err := isOfficialReviewerTeam(sess, issue, reviewer) + official, err := isOfficialReviewerTeam(ctx, issue, reviewer) if err != nil { return nil, fmt.Errorf("isOfficialReviewerTeam(): %v", err) } else if !official { - if official, err = isOfficialReviewer(sess, issue, doer); err != nil { + if official, err = isOfficialReviewer(ctx, issue, doer); err != nil { return nil, fmt.Errorf("isOfficialReviewer(): %v", err) } } @@ -819,7 +821,7 @@ func RemoveTeamReviewRequest(issue *Issue, reviewer *Team, doer *user_model.User return nil, err } - official, err := isOfficialReviewerTeam(sess, issue, reviewer) + official, err := isOfficialReviewerTeam(ctx, issue, reviewer) if err != nil { return nil, fmt.Errorf("isOfficialReviewerTeam(): %v", err) } diff --git a/models/ssh_key_deploy.go b/models/ssh_key_deploy.go index 187af3ca9..672974afb 100644 --- a/models/ssh_key_deploy.go +++ b/models/ssh_key_deploy.go @@ -5,11 +5,13 @@ package models import ( + "context" "fmt" "time" "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" "code.gitea.io/gitea/modules/timeutil" @@ -221,13 +223,14 @@ func DeleteDeployKey(doer *user_model.User, id int64) error { } defer committer.Close() - if err := deleteDeployKey(db.GetEngine(ctx), doer, id); err != nil { + if err := deleteDeployKey(ctx, doer, id); err != nil { return err } return committer.Commit() } -func deleteDeployKey(sess db.Engine, doer *user_model.User, id int64) error { +func deleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error { + sess := db.GetEngine(ctx) key, err := getDeployKeyByID(sess, id) if err != nil { if IsErrDeployKeyNotExist(err) { @@ -238,9 +241,9 @@ func deleteDeployKey(sess db.Engine, doer *user_model.User, id int64) error { // Check if user has access to delete this key. if !doer.IsAdmin { - repo, err := getRepositoryByID(sess, key.RepoID) + repo, err := repo_model.GetRepositoryByIDCtx(ctx, key.RepoID) if err != nil { - return fmt.Errorf("GetRepositoryByID: %v", err) + return fmt.Errorf("repo_model.GetRepositoryByID: %v", err) } has, err := isUserRepoAdmin(sess, repo, doer) if err != nil { diff --git a/models/star.go b/models/star.go index 58bc77132..de3207797 100644 --- a/models/star.go +++ b/models/star.go @@ -6,6 +6,7 @@ package models import ( "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/timeutil" ) @@ -75,7 +76,7 @@ func isStaring(e db.Engine, userID, repoID int64) bool { } // GetStargazers returns the users that starred the repo. -func GetStargazers(repo *Repository, opts db.ListOptions) ([]*user_model.User, error) { +func GetStargazers(repo *repo_model.Repository, opts db.ListOptions) ([]*user_model.User, error) { sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID). Join("LEFT", "star", "`user`.id = star.uid") if opts.Page > 0 { diff --git a/models/star_test.go b/models/star_test.go index eef1a0c5f..8da83661c 100644 --- a/models/star_test.go +++ b/models/star_test.go @@ -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" @@ -35,7 +36,7 @@ func TestIsStaring(t *testing.T) { func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}).(*repo_model.Repository) gazers, err := GetStargazers(repo, db.ListOptions{Page: 0}) assert.NoError(t, err) if assert.Len(t, gazers, 1) { @@ -46,7 +47,7 @@ func TestRepository_GetStargazers(t *testing.T) { func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) gazers, err := GetStargazers(repo, db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) diff --git a/models/statistic.go b/models/statistic.go index 9a2a0d5c4..055f312c1 100644 --- a/models/statistic.go +++ b/models/statistic.go @@ -48,7 +48,7 @@ func GetStatistic() (stats Statistic) { stats.Counter.User = user_model.CountUsers() stats.Counter.Org = CountOrganizations() stats.Counter.PublicKey, _ = e.Count(new(PublicKey)) - stats.Counter.Repo = CountRepositories(true) + stats.Counter.Repo = repo_model.CountRepositories(true) stats.Counter.Watch, _ = e.Count(new(Watch)) stats.Counter.Star, _ = e.Count(new(Star)) stats.Counter.Action, _ = e.Count(new(Action)) @@ -95,7 +95,7 @@ func GetStatistic() (stats Statistic) { stats.Counter.Comment, _ = e.Count(new(Comment)) stats.Counter.Oauth = 0 stats.Counter.Follow, _ = e.Count(new(user_model.Follow)) - stats.Counter.Mirror, _ = e.Count(new(Mirror)) + stats.Counter.Mirror, _ = e.Count(new(repo_model.Mirror)) stats.Counter.Release, _ = e.Count(new(Release)) stats.Counter.LoginSource = login.CountSources() stats.Counter.Webhook, _ = e.Count(new(webhook.Webhook)) diff --git a/models/task.go b/models/task.go index 199995727..64c858921 100644 --- a/models/task.go +++ b/models/task.go @@ -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" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/migration" @@ -23,12 +24,12 @@ import ( // Task represents a task type Task struct { ID int64 - DoerID int64 `xorm:"index"` // operator - Doer *user_model.User `xorm:"-"` - OwnerID int64 `xorm:"index"` // repo owner id, when creating, the repoID maybe zero - Owner *user_model.User `xorm:"-"` - RepoID int64 `xorm:"index"` - Repo *Repository `xorm:"-"` + DoerID int64 `xorm:"index"` // operator + Doer *user_model.User `xorm:"-"` + OwnerID int64 `xorm:"index"` // repo owner id, when creating, the repoID maybe zero + Owner *user_model.User `xorm:"-"` + RepoID int64 `xorm:"index"` + Repo *repo_model.Repository `xorm:"-"` Type structs.TaskType Status structs.TaskStatus `xorm:"index"` StartTime timeutil.TimeStamp @@ -57,12 +58,12 @@ func (task *Task) loadRepo(e db.Engine) error { if task.Repo != nil { return nil } - var repo Repository + var repo repo_model.Repository has, err := e.ID(task.RepoID).Get(&repo) if err != nil { return err } else if !has { - return ErrRepoNotExist{ + return repo_model.ErrRepoNotExist{ ID: task.RepoID, } } diff --git a/models/topic.go b/models/topic.go index 79c47e233..2767d6c58 100644 --- a/models/topic.go +++ b/models/topic.go @@ -10,6 +10,7 @@ import ( "strings" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/timeutil" "xorm.io/builder" @@ -253,7 +254,7 @@ func AddTopic(repoID int64, topicName string) (*Topic, error) { return nil, err } - if _, err := sess.ID(repoID).Cols("topics").Update(&Repository{ + if _, err := sess.ID(repoID).Cols("topics").Update(&repo_model.Repository{ Topics: topicNames, }); err != nil { return nil, err @@ -347,7 +348,7 @@ func SaveTopics(repoID int64, topicNames ...string) error { return err } - if _, err := sess.ID(repoID).Cols("topics").Update(&Repository{ + if _, err := sess.ID(repoID).Cols("topics").Update(&repo_model.Repository{ Topics: topicNames, }); err != nil { return err diff --git a/models/update.go b/models/update.go index 0898ab54c..14333ed98 100644 --- a/models/update.go +++ b/models/update.go @@ -10,14 +10,15 @@ import ( "strings" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" ) // PushUpdateDeleteTagsContext updates a number of delete tags with context -func PushUpdateDeleteTagsContext(ctx context.Context, repo *Repository, tags []string) error { +func PushUpdateDeleteTagsContext(ctx context.Context, repo *repo_model.Repository, tags []string) error { return pushUpdateDeleteTags(db.GetEngine(ctx), repo, tags) } -func pushUpdateDeleteTags(e db.Engine, repo *Repository, tags []string) error { +func pushUpdateDeleteTags(e db.Engine, repo *repo_model.Repository, tags []string) error { if len(tags) == 0 { return nil } @@ -47,7 +48,7 @@ func pushUpdateDeleteTags(e db.Engine, repo *Repository, tags []string) error { } // PushUpdateDeleteTag must be called for any push actions to delete tag -func PushUpdateDeleteTag(repo *Repository, tagName string) error { +func PushUpdateDeleteTag(repo *repo_model.Repository, tagName string) error { rel, err := GetRelease(repo.ID, tagName) if err != nil { if IsErrReleaseNotExist(err) { @@ -72,7 +73,7 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error { } // SaveOrUpdateTag must be called for any push actions to add tag -func SaveOrUpdateTag(repo *Repository, newRel *Release) error { +func SaveOrUpdateTag(repo *repo_model.Repository, newRel *Release) error { rel, err := GetRelease(repo.ID, newRel.TagName) if err != nil && !IsErrReleaseNotExist(err) { return fmt.Errorf("GetRelease: %v", err) diff --git a/models/user.go b/models/user.go index e604c871b..1427833e2 100644 --- a/models/user.go +++ b/models/user.go @@ -13,6 +13,7 @@ import ( _ "image/jpeg" // Needed for jpeg support "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/setting" @@ -151,7 +152,7 @@ func DeleteUser(ctx context.Context, u *user_model.User) (err error) { Where("watch.user_id = ?", u.ID).And("watch.mode <>?", RepoWatchModeDont).Find(&watchedRepoIDs); err != nil { return fmt.Errorf("get all watches: %v", err) } - if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil { + if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(repo_model.Repository)); err != nil { return fmt.Errorf("decrease repository num_watches: %v", err) } // ***** END: Watch ***** @@ -161,7 +162,7 @@ func DeleteUser(ctx context.Context, u *user_model.User) (err error) { if err = e.Table("star").Cols("star.repo_id"). Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil { return fmt.Errorf("get all stars: %v", err) - } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil { + } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(repo_model.Repository)); err != nil { return fmt.Errorf("decrease repository num_stars: %v", err) } // ***** END: Star ***** @@ -273,7 +274,7 @@ func DeleteUser(ctx context.Context, u *user_model.User) (err error) { } // GetStarredRepos returns the repos starred by a particular user -func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) { +func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*repo_model.Repository, error) { sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID). Join("LEFT", "star", "`repository`.id=`star`.repo_id") if !private { @@ -283,16 +284,16 @@ func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([] if listOptions.Page != 0 { sess = db.SetSessionPagination(sess, &listOptions) - repos := make([]*Repository, 0, listOptions.PageSize) + repos := make([]*repo_model.Repository, 0, listOptions.PageSize) return repos, sess.Find(&repos) } - repos := make([]*Repository, 0, 10) + repos := make([]*repo_model.Repository, 0, 10) return repos, sess.Find(&repos) } // GetWatchedRepos returns the repos watched by a particular user -func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) { +func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*repo_model.Repository, int64, error) { sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID). And("`watch`.mode<>?", RepoWatchModeDont). Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") @@ -303,12 +304,12 @@ func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([] if listOptions.Page != 0 { sess = db.SetSessionPagination(sess, &listOptions) - repos := make([]*Repository, 0, listOptions.PageSize) + repos := make([]*repo_model.Repository, 0, listOptions.PageSize) total, err := sess.FindAndCount(&repos) return repos, total, err } - repos := make([]*Repository, 0, 10) + repos := make([]*repo_model.Repository, 0, 10) total, err := sess.FindAndCount(&repos) return repos, total, err } diff --git a/modules/context/api.go b/modules/context/api.go index 4a2d5d166..b6fcdd2a1 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -13,8 +13,8 @@ import ( "net/url" "strings" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -327,7 +327,7 @@ func ReferencesGitRepo(allowEmpty bool) func(http.Handler) http.Handler { // For API calls. if ctx.Repo.GitRepo == nil { - repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) + repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) gitRepo, err := git.OpenRepository(repoPath) if err != nil { ctx.Error(http.StatusInternalServerError, "RepoRef Invalid repo "+repoPath, err) @@ -385,7 +385,7 @@ func RepoRefForAPI(next http.Handler) http.Handler { var err error if ctx.Repo.GitRepo == nil { - repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) + repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) ctx.Repo.GitRepo, err = git.OpenRepository(repoPath) if err != nil { ctx.InternalServerError(err) diff --git a/modules/context/repo.go b/modules/context/repo.go index b2844c04c..694c483bd 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -14,6 +14,8 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/cache" @@ -42,7 +44,7 @@ var IssueTemplateDirCandidates = []string{ // PullRequest contains information to make a pull request type PullRequest struct { - BaseRepo *models.Repository + BaseRepo *repo_model.Repository Allowed bool SameRepo bool HeadInfoSubURL string // [:] url segment @@ -55,7 +57,7 @@ type Repository struct { IsViewBranch bool IsViewTag bool IsViewCommit bool - Repository *models.Repository + Repository *repo_model.Repository Owner *user_model.User Commit *git.Commit Tag *git.Tag @@ -66,9 +68,9 @@ type Repository struct { TreePath string CommitID string RepoLink string - CloneLink models.CloneLink + CloneLink repo_model.CloneLink CommitsCount int64 - Mirror *models.Mirror + Mirror *repo_model.Mirror PullRequest *PullRequest } @@ -118,7 +120,7 @@ func (r *Repository) CanCommitToBranch(doer *user_model.User) (CanCommitToBranch requireSigned = protectedBranch.RequireSignedCommits } - sign, keyID, _, err := r.Repository.SignCRUDAction(doer, r.Repository.RepoPath(), git.BranchPrefix+r.BranchName) + sign, keyID, _, err := models.SignCRUDAction(r.Repository, doer, r.Repository.RepoPath(), git.BranchPrefix+r.BranchName) canCommit := r.CanEnableEditor() && userCanPush if requireSigned { @@ -242,38 +244,39 @@ func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) { } // RetrieveBaseRepo retrieves base repository -func RetrieveBaseRepo(ctx *Context, repo *models.Repository) { +func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository) { // Non-fork repository will not return error in this method. if err := repo.GetBaseRepo(); err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { repo.IsFork = false repo.ForkID = 0 return } ctx.ServerError("GetBaseRepo", err) return - } else if err = repo.BaseRepo.GetOwner(); err != nil { + } else if err = repo.BaseRepo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("BaseRepo.GetOwner", err) return } } // RetrieveTemplateRepo retrieves template repository used to generate this repository -func RetrieveTemplateRepo(ctx *Context, repo *models.Repository) { +func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository) { // Non-generated repository will not return error in this method. - if err := repo.GetTemplateRepo(); err != nil { - if models.IsErrRepoNotExist(err) { + templateRepo, err := repo_model.GetTemplateRepo(repo) + if err != nil { + if repo_model.IsErrRepoNotExist(err) { repo.TemplateID = 0 return } ctx.ServerError("GetTemplateRepo", err) return - } else if err = repo.TemplateRepo.GetOwner(); err != nil { + } else if err = templateRepo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("TemplateRepo.GetOwner", err) return } - perm, err := models.GetUserRepoPermission(repo.TemplateRepo, ctx.User) + perm, err := models.GetUserRepoPermission(templateRepo, ctx.User) if err != nil { ctx.ServerError("GetUserRepoPermission", err) return @@ -307,7 +310,7 @@ func EarlyResponseForGoGetMeta(ctx *Context) { ctx.PlainText(200, []byte(com.Expand(``, map[string]string{ "GoGetImport": ComposeGoGetImport(username, reponame), - "CloneLink": models.ComposeHTTPSCloneURL(username, reponame), + "CloneLink": repo_model.ComposeHTTPSCloneURL(username, reponame), }))) } @@ -316,7 +319,7 @@ func RedirectToRepo(ctx *Context, redirectRepoID int64) { ownerName := ctx.Params(":username") previousRepoName := ctx.Params(":reponame") - repo, err := models.GetRepositoryByID(redirectRepoID) + repo, err := repo_model.GetRepositoryByID(redirectRepoID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -334,9 +337,9 @@ func RedirectToRepo(ctx *Context, redirectRepoID int64) { ctx.Redirect(path.Join(setting.AppSubURL, redirectPath)) } -func repoAssignment(ctx *Context, repo *models.Repository) { +func repoAssignment(ctx *Context, repo *repo_model.Repository) { var err error - if err = repo.GetOwner(); err != nil { + if err = repo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("GetOwner", err) return } @@ -361,21 +364,24 @@ func repoAssignment(ctx *Context, repo *models.Repository) { if repo.IsMirror { var err error - ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID) + mirror, err := repo_model.GetMirrorByRepoID(repo.ID) if err != nil { ctx.ServerError("GetMirrorByRepoID", err) return } - ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune - ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval - ctx.Data["Mirror"] = ctx.Repo.Mirror + ctx.Data["MirrorEnablePrune"] = mirror.EnablePrune + ctx.Data["MirrorInterval"] = mirror.Interval + ctx.Data["Mirror"] = mirror } - if err = repo.LoadPushMirrors(); err != nil { - ctx.ServerError("LoadPushMirrors", err) + + pushMirrors, err := repo_model.GetPushMirrorsByRepoID(repo.ID) + if err != nil { + ctx.ServerError("GetPushMirrorsByRepoID", err) return } ctx.Repo.Repository = repo + ctx.Data["PushMirrors"] = pushMirrors ctx.Data["RepoName"] = ctx.Repo.Repository.Name ctx.Data["IsEmptyRepo"] = ctx.Repo.Repository.IsEmpty } @@ -386,9 +392,9 @@ func RepoIDAssignment() func(ctx *Context) { repoID := ctx.ParamsInt64(":repoid") // Get repository. - repo, err := models.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(repoID) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) } else { ctx.ServerError("GetRepositoryByID", err) @@ -433,9 +439,9 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { ctx.Data["Username"] = ctx.Repo.Owner.Name // Get repository. - repo, err := models.GetRepositoryByName(owner.ID, repoName) + repo, err := repo_model.GetRepositoryByName(owner.ID, repoName) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName) if err == nil { RedirectToRepo(ctx, redirectRepoID) @@ -534,11 +540,11 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { return } - gitRepo, err := git.OpenRepositoryCtx(ctx, models.RepoPath(userName, repoName)) + gitRepo, err := git.OpenRepositoryCtx(ctx, repo_model.RepoPath(userName, repoName)) if err != nil { if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "no such file or directory") { log.Error("Repository %-v has a broken repository on the file system: %s Error: %v", ctx.Repo.Repository, ctx.Repo.Repository.RepoPath(), err) - ctx.Repo.Repository.Status = models.RepositoryBroken + ctx.Repo.Repository.Status = repo_model.RepositoryBroken ctx.Repo.Repository.IsEmpty = true ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch // Only allow access to base of repo or settings @@ -547,7 +553,7 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { } return } - ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) + ctx.ServerError("RepoAssignment Invalid repo "+repo_model.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo @@ -570,7 +576,7 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { if err != nil { if strings.Contains(err.Error(), "fatal: not a git repository ") { log.Error("Repository %-v has a broken repository on the file system: %s Error: %v", ctx.Repo.Repository, ctx.Repo.Repository.RepoPath(), err) - ctx.Repo.Repository.Status = models.RepositoryBroken + ctx.Repo.Repository.Status = repo_model.RepositoryBroken ctx.Repo.Repository.IsEmpty = true ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch // Only allow access to base of repo or settings @@ -629,7 +635,7 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { ctx.Data["CanCompareOrPull"] = canCompare ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest - if ctx.Repo.Repository.Status == models.RepositoryPendingTransfer { + if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer { repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository) if err != nil { ctx.ServerError("GetPendingRepositoryTransfer", err) @@ -791,7 +797,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context ) if ctx.Repo.GitRepo == nil { - repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) + repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) ctx.Repo.GitRepo, err = git.OpenRepositoryCtx(ctx, repoPath) if err != nil { ctx.ServerError("RepoRef Invalid repo "+repoPath, err) diff --git a/modules/convert/convert.go b/modules/convert/convert.go index 8c6a61062..eda9f23cd 100644 --- a/modules/convert/convert.go +++ b/modules/convert/convert.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" "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/models/webhook" @@ -34,7 +35,7 @@ func ToEmail(email *user_model.EmailAddress) *api.Email { } // ToBranch convert a git.Commit and git.Branch to an api.Branch -func ToBranch(repo *models.Repository, b *git.Branch, c *git.Commit, bp *models.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) { +func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *models.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) { if bp == nil { var hasPerm bool var err error @@ -76,7 +77,7 @@ func ToBranch(repo *models.Repository, b *git.Branch, c *git.Commit, bp *models. return nil, err } branch.UserCanPush = bp.CanUserPush(user.ID) - branch.UserCanMerge = bp.IsUserMergeWhitelisted(user.ID, permission) + branch.UserCanMerge = models.IsUserMergeWhitelisted(bp, user.ID, permission) } return branch, nil @@ -138,7 +139,7 @@ func ToBranchProtection(bp *models.ProtectedBranch) *api.BranchProtection { } // ToTag convert a git.Tag to an api.Tag -func ToTag(repo *models.Repository, t *git.Tag) *api.Tag { +func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag { return &api.Tag{ Name: t.Name, Message: strings.TrimSpace(t.Message), @@ -310,7 +311,7 @@ func ToTeam(team *models.Team) *api.Team { } // ToAnnotatedTag convert git.Tag to api.AnnotatedTag -func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag { +func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag { return &api.AnnotatedTag{ Tag: t.Name, SHA: t.ID.String(), @@ -323,7 +324,7 @@ func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.Ann } // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject -func ToAnnotatedTagObject(repo *models.Repository, commit *git.Commit) *api.AnnotatedTagObject { +func ToAnnotatedTagObject(repo *repo_model.Repository, commit *git.Commit) *api.AnnotatedTagObject { return &api.AnnotatedTagObject{ SHA: commit.ID.String(), Type: string(git.ObjectCommit), diff --git a/modules/convert/git_commit.go b/modules/convert/git_commit.go index 3148d880f..55cac5fd5 100644 --- a/modules/convert/git_commit.go +++ b/modules/convert/git_commit.go @@ -8,7 +8,7 @@ import ( "net/url" "time" - "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/git" "code.gitea.io/gitea/modules/log" @@ -28,7 +28,7 @@ func ToCommitUser(sig *git.Signature) *api.CommitUser { } // ToCommitMeta convert a git.Tag to an api.CommitMeta -func ToCommitMeta(repo *models.Repository, tag *git.Tag) *api.CommitMeta { +func ToCommitMeta(repo *repo_model.Repository, tag *git.Tag) *api.CommitMeta { return &api.CommitMeta{ SHA: tag.Object.String(), URL: util.URLJoin(repo.APIURL(), "git/commits", tag.ID.String()), @@ -37,7 +37,7 @@ func ToCommitMeta(repo *models.Repository, tag *git.Tag) *api.CommitMeta { } // ToPayloadCommit convert a git.Commit to api.PayloadCommit -func ToPayloadCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit { +func ToPayloadCommit(repo *repo_model.Repository, c *git.Commit) *api.PayloadCommit { authorUsername := "" if author, err := user_model.GetUserByEmail(c.Author.Email); err == nil { authorUsername = author.Name @@ -72,7 +72,7 @@ func ToPayloadCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit } // ToCommit convert a git.Commit to api.Commit -func ToCommit(repo *models.Repository, commit *git.Commit, userCache map[string]*user_model.User) (*api.Commit, error) { +func ToCommit(repo *repo_model.Repository, commit *git.Commit, userCache map[string]*user_model.User) (*api.Commit, error) { var apiAuthor, apiCommitter *api.User diff --git a/modules/convert/git_commit_test.go b/modules/convert/git_commit_test.go index aacdb1ad7..118ba3a00 100644 --- a/modules/convert/git_commit_test.go +++ b/modules/convert/git_commit_test.go @@ -8,7 +8,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/git" api "code.gitea.io/gitea/modules/structs" @@ -19,7 +19,7 @@ import ( func TestToCommitMeta(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - headRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) sha1, _ := git.NewIDFromString("0000000000000000000000000000000000000000") signature := &git.Signature{Name: "Test Signature", Email: "test@email.com", When: time.Unix(0, 0)} tag := &git.Tag{ diff --git a/modules/convert/issue.go b/modules/convert/issue.go index c67ff5427..4972b070a 100644 --- a/modules/convert/issue.go +++ b/modules/convert/issue.go @@ -10,6 +10,8 @@ import ( "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" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -30,7 +32,7 @@ func ToAPIIssue(issue *models.Issue) *api.Issue { if err := issue.LoadRepo(); err != nil { return &api.Issue{} } - if err := issue.Repo.GetOwner(); err != nil { + if err := issue.Repo.GetOwner(db.DefaultContext); err != nil { return &api.Issue{} } @@ -129,10 +131,10 @@ func ToStopWatches(sws []*models.Stopwatch) (api.StopWatches, error) { result := api.StopWatches(make([]api.StopWatch, 0, len(sws))) issueCache := make(map[int64]*models.Issue) - repoCache := make(map[int64]*models.Repository) + repoCache := make(map[int64]*repo_model.Repository) var ( issue *models.Issue - repo *models.Repository + repo *repo_model.Repository ok bool err error ) @@ -147,7 +149,7 @@ func ToStopWatches(sws []*models.Stopwatch) (api.StopWatches, error) { } repo, ok = repoCache[issue.RepoID] if !ok { - repo, err = models.GetRepositoryByID(issue.RepoID) + repo, err = repo_model.GetRepositoryByID(issue.RepoID) if err != nil { return nil, err } @@ -176,7 +178,7 @@ func ToTrackedTimeList(tl models.TrackedTimeList) api.TrackedTimeList { } // ToLabel converts Label to API format -func ToLabel(label *models.Label, repo *models.Repository, org *user_model.User) *api.Label { +func ToLabel(label *models.Label, repo *repo_model.Repository, org *user_model.User) *api.Label { result := &api.Label{ ID: label.ID, Name: label.Name, @@ -203,7 +205,7 @@ func ToLabel(label *models.Label, repo *models.Repository, org *user_model.User) } // ToLabelList converts list of Label to API format -func ToLabelList(labels []*models.Label, repo *models.Repository, org *user_model.User) []*api.Label { +func ToLabelList(labels []*models.Label, repo *repo_model.Repository, org *user_model.User) []*api.Label { result := make([]*api.Label, len(labels)) for i := range labels { result[i] = ToLabel(labels[i], repo, org) diff --git a/modules/convert/issue_test.go b/modules/convert/issue_test.go index 21ca7469e..fb75413ea 100644 --- a/modules/convert/issue_test.go +++ b/modules/convert/issue_test.go @@ -10,6 +10,7 @@ import ( "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" api "code.gitea.io/gitea/modules/structs" @@ -21,7 +22,7 @@ import ( func TestLabel_ToLabel(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &models.Label{ID: 1}).(*models.Label) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: label.RepoID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: label.RepoID}).(*repo_model.Repository) assert.Equal(t, &api.Label{ ID: label.ID, Name: label.Name, diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index 1bac5d3a4..11789b120 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -9,6 +9,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" "code.gitea.io/gitea/modules/structs" @@ -18,7 +19,7 @@ import ( func TestPullRequest_APIFormat(t *testing.T) { //with HeadRepo assert.NoError(t, unittest.PrepareTestDatabase()) - headRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadAttributes()) assert.NoError(t, pr.LoadIssue()) diff --git a/modules/convert/repository.go b/modules/convert/repository.go index 46b2745b3..9859ea267 100644 --- a/modules/convert/repository.go +++ b/modules/convert/repository.go @@ -6,17 +6,19 @@ package convert import ( "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" api "code.gitea.io/gitea/modules/structs" ) // ToRepo converts a Repository to api.Repository -func ToRepo(repo *models.Repository, mode perm.AccessMode) *api.Repository { +func ToRepo(repo *repo_model.Repository, mode perm.AccessMode) *api.Repository { return innerToRepo(repo, mode, false) } -func innerToRepo(repo *models.Repository, mode perm.AccessMode, isParent bool) *api.Repository { +func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository { var parent *api.Repository cloneLink := repo.CloneLink() @@ -73,7 +75,7 @@ func innerToRepo(repo *models.Repository, mode perm.AccessMode, isParent bool) * allowRebase := false allowRebaseMerge := false allowSquash := false - defaultMergeStyle := models.MergeStyleMerge + defaultMergeStyle := repo_model.MergeStyleMerge if unit, err := repo.GetUnit(unit_model.TypePullRequests); err == nil { config := unit.PullRequestsConfig() hasPullRequests = true @@ -89,7 +91,7 @@ func innerToRepo(repo *models.Repository, mode perm.AccessMode, isParent bool) * hasProjects = true } - if err := repo.GetOwner(); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { return nil } @@ -97,7 +99,9 @@ func innerToRepo(repo *models.Repository, mode perm.AccessMode, isParent bool) * mirrorInterval := "" if repo.IsMirror { - if err := repo.GetMirror(); err == nil { + var err error + repo.Mirror, err = repo_model.GetMirrorByRepoID(repo.ID) + if err == nil { mirrorInterval = repo.Mirror.Interval.String() } } diff --git a/modules/convert/wiki.go b/modules/convert/wiki.go index 9563f1544..1112da43f 100644 --- a/modules/convert/wiki.go +++ b/modules/convert/wiki.go @@ -7,7 +7,7 @@ package convert import ( "time" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -49,7 +49,7 @@ func ToWikiCommitList(commits []*git.Commit, total int64) *api.WikiCommitList { } // ToWikiPageMetaData converts meta information to a WikiPageMetaData -func ToWikiPageMetaData(title string, lastCommit *git.Commit, repo *models.Repository) *api.WikiPageMetaData { +func ToWikiPageMetaData(title string, lastCommit *git.Commit, repo *repo_model.Repository) *api.WikiPageMetaData { suburl := wiki_service.NameToSubURL(title) return &api.WikiPageMetaData{ Title: title, diff --git a/modules/doctor/checkOldArchives.go b/modules/doctor/checkOldArchives.go index a4e2ffbd1..0db879408 100644 --- a/modules/doctor/checkOldArchives.go +++ b/modules/doctor/checkOldArchives.go @@ -8,7 +8,7 @@ import ( "os" "path/filepath" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/util" ) @@ -16,7 +16,7 @@ import ( func checkOldArchives(logger log.Logger, autofix bool) error { numRepos := 0 numReposUpdated := 0 - err := iterateRepositories(func(repo *models.Repository) error { + err := iterateRepositories(func(repo *repo_model.Repository) error { if repo.IsEmpty { return nil } diff --git a/modules/doctor/fix16961.go b/modules/doctor/fix16961.go index 2e1db834c..4797c97ef 100644 --- a/modules/doctor/fix16961.go +++ b/modules/doctor/fix16961.go @@ -8,9 +8,10 @@ import ( "bytes" "fmt" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/timeutil" @@ -36,8 +37,8 @@ func parseBool16961(bs []byte) (bool, error) { return false, fmt.Errorf("unexpected bool format: %s", string(bs)) } -func fixUnitConfig16961(bs []byte, cfg *models.UnitConfig) (fixed bool, err error) { - err = models.JSONUnmarshalHandleDoubleEncode(bs, &cfg) +func fixUnitConfig16961(bs []byte, cfg *repo_model.UnitConfig) (fixed bool, err error) { + err = json.UnmarshalHandleDoubleEncode(bs, &cfg) if err == nil { return } @@ -50,8 +51,8 @@ func fixUnitConfig16961(bs []byte, cfg *models.UnitConfig) (fixed bool, err erro return true, nil } -func fixExternalWikiConfig16961(bs []byte, cfg *models.ExternalWikiConfig) (fixed bool, err error) { - err = models.JSONUnmarshalHandleDoubleEncode(bs, &cfg) +func fixExternalWikiConfig16961(bs []byte, cfg *repo_model.ExternalWikiConfig) (fixed bool, err error) { + err = json.UnmarshalHandleDoubleEncode(bs, &cfg) if err == nil { return } @@ -66,8 +67,8 @@ func fixExternalWikiConfig16961(bs []byte, cfg *models.ExternalWikiConfig) (fixe return true, nil } -func fixExternalTrackerConfig16961(bs []byte, cfg *models.ExternalTrackerConfig) (fixed bool, err error) { - err = models.JSONUnmarshalHandleDoubleEncode(bs, &cfg) +func fixExternalTrackerConfig16961(bs []byte, cfg *repo_model.ExternalTrackerConfig) (fixed bool, err error) { + err = json.UnmarshalHandleDoubleEncode(bs, &cfg) if err == nil { return } @@ -91,8 +92,8 @@ func fixExternalTrackerConfig16961(bs []byte, cfg *models.ExternalTrackerConfig) return true, nil } -func fixPullRequestsConfig16961(bs []byte, cfg *models.PullRequestsConfig) (fixed bool, err error) { - err = models.JSONUnmarshalHandleDoubleEncode(bs, &cfg) +func fixPullRequestsConfig16961(bs []byte, cfg *repo_model.PullRequestsConfig) (fixed bool, err error) { + err = json.UnmarshalHandleDoubleEncode(bs, &cfg) if err == nil { return } @@ -169,12 +170,12 @@ func fixPullRequestsConfig16961(bs []byte, cfg *models.PullRequestsConfig) (fixe return } - cfg.DefaultMergeStyle = models.MergeStyle(string(bytes.Join(parts[8:], []byte{' '}))) + cfg.DefaultMergeStyle = repo_model.MergeStyle(string(bytes.Join(parts[8:], []byte{' '}))) return true, nil } -func fixIssuesConfig16961(bs []byte, cfg *models.IssuesConfig) (fixed bool, err error) { - err = models.JSONUnmarshalHandleDoubleEncode(bs, &cfg) +func fixIssuesConfig16961(bs []byte, cfg *repo_model.IssuesConfig) (fixed bool, err error) { + err = json.UnmarshalHandleDoubleEncode(bs, &cfg) if err == nil { return } @@ -208,7 +209,7 @@ func fixIssuesConfig16961(bs []byte, cfg *models.IssuesConfig) (fixed bool, err return true, nil } -func fixBrokenRepoUnit16961(repoUnit *models.RepoUnit, bs []byte) (fixed bool, err error) { +func fixBrokenRepoUnit16961(repoUnit *repo_model.RepoUnit, bs []byte) (fixed bool, err error) { // Shortcut empty or null values if len(bs) == 0 { return false, nil @@ -216,33 +217,33 @@ func fixBrokenRepoUnit16961(repoUnit *models.RepoUnit, bs []byte) (fixed bool, e switch unit.Type(repoUnit.Type) { case unit.TypeCode, unit.TypeReleases, unit.TypeWiki, unit.TypeProjects: - cfg := &models.UnitConfig{} + cfg := &repo_model.UnitConfig{} repoUnit.Config = cfg if fixed, err := fixUnitConfig16961(bs, cfg); !fixed { return false, err } case unit.TypeExternalWiki: - cfg := &models.ExternalWikiConfig{} + cfg := &repo_model.ExternalWikiConfig{} repoUnit.Config = cfg if fixed, err := fixExternalWikiConfig16961(bs, cfg); !fixed { return false, err } case unit.TypeExternalTracker: - cfg := &models.ExternalTrackerConfig{} + cfg := &repo_model.ExternalTrackerConfig{} repoUnit.Config = cfg if fixed, err := fixExternalTrackerConfig16961(bs, cfg); !fixed { return false, err } case unit.TypePullRequests: - cfg := &models.PullRequestsConfig{} + cfg := &repo_model.PullRequestsConfig{} repoUnit.Config = cfg if fixed, err := fixPullRequestsConfig16961(bs, cfg); !fixed { return false, err } case unit.TypeIssues: - cfg := &models.IssuesConfig{} + cfg := &repo_model.IssuesConfig{} repoUnit.Config = cfg if fixed, err := fixIssuesConfig16961(bs, cfg); !fixed { return false, err @@ -275,7 +276,7 @@ func fixBrokenRepoUnits16961(logger log.Logger, autofix bool) error { unit := bean.(*RepoUnit) bs := unit.Config - repoUnit := &models.RepoUnit{ + repoUnit := &repo_model.RepoUnit{ ID: unit.ID, RepoID: unit.RepoID, Type: unit.Type, @@ -291,7 +292,7 @@ func fixBrokenRepoUnits16961(logger log.Logger, autofix bool) error { return nil } - return models.UpdateRepoUnit(repoUnit) + return repo_model.UpdateRepoUnit(repoUnit) }, ) diff --git a/modules/doctor/fix16961_test.go b/modules/doctor/fix16961_test.go index 986425b4d..f5e5667c0 100644 --- a/modules/doctor/fix16961_test.go +++ b/modules/doctor/fix16961_test.go @@ -7,7 +7,7 @@ package doctor import ( "testing" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "github.com/stretchr/testify/assert" ) @@ -46,7 +46,7 @@ func Test_fixUnitConfig_16961(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - gotFixed, err := fixUnitConfig16961([]byte(tt.bs), &models.UnitConfig{}) + gotFixed, err := fixUnitConfig16961([]byte(tt.bs), &repo_model.UnitConfig{}) if (err != nil) != tt.wantErr { t.Errorf("fixUnitConfig_16961() error = %v, wantErr %v", err, tt.wantErr) return @@ -89,7 +89,7 @@ func Test_fixExternalWikiConfig_16961(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cfg := &models.ExternalWikiConfig{} + cfg := &repo_model.ExternalWikiConfig{} gotFixed, err := fixExternalWikiConfig16961([]byte(tt.bs), cfg) if (err != nil) != tt.wantErr { t.Errorf("fixExternalWikiConfig_16961() error = %v, wantErr %v", err, tt.wantErr) @@ -109,14 +109,14 @@ func Test_fixExternalTrackerConfig_16961(t *testing.T) { tests := []struct { name string bs string - expected models.ExternalTrackerConfig + expected repo_model.ExternalTrackerConfig wantFixed bool wantErr bool }{ { name: "normal", bs: `{"ExternalTrackerURL":"a","ExternalTrackerFormat":"b","ExternalTrackerStyle":"c"}`, - expected: models.ExternalTrackerConfig{ + expected: repo_model.ExternalTrackerConfig{ ExternalTrackerURL: "a", ExternalTrackerFormat: "b", ExternalTrackerStyle: "c", @@ -127,7 +127,7 @@ func Test_fixExternalTrackerConfig_16961(t *testing.T) { { name: "broken", bs: "&{a b c}", - expected: models.ExternalTrackerConfig{ + expected: repo_model.ExternalTrackerConfig{ ExternalTrackerURL: "a", ExternalTrackerFormat: "b", ExternalTrackerStyle: "c", @@ -150,7 +150,7 @@ func Test_fixExternalTrackerConfig_16961(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cfg := &models.ExternalTrackerConfig{} + cfg := &repo_model.ExternalTrackerConfig{} gotFixed, err := fixExternalTrackerConfig16961([]byte(tt.bs), cfg) if (err != nil) != tt.wantErr { t.Errorf("fixExternalTrackerConfig_16961() error = %v, wantErr %v", err, tt.wantErr) @@ -176,7 +176,7 @@ func Test_fixPullRequestsConfig_16961(t *testing.T) { tests := []struct { name string bs string - expected models.PullRequestsConfig + expected repo_model.PullRequestsConfig wantFixed bool wantErr bool }{ @@ -187,7 +187,7 @@ func Test_fixPullRequestsConfig_16961(t *testing.T) { { name: "broken - 1.14", bs: `&{%!s(bool=false) %!s(bool=true) %!s(bool=true) %!s(bool=true) %!s(bool=true) %!s(bool=false) %!s(bool=false)}`, - expected: models.PullRequestsConfig{ + expected: repo_model.PullRequestsConfig{ IgnoreWhitespaceConflicts: false, AllowMerge: true, AllowRebase: true, @@ -201,19 +201,19 @@ func Test_fixPullRequestsConfig_16961(t *testing.T) { { name: "broken - 1.15", bs: `&{%!s(bool=false) %!s(bool=true) %!s(bool=true) %!s(bool=true) %!s(bool=true) %!s(bool=false) %!s(bool=false) %!s(bool=false) merge}`, - expected: models.PullRequestsConfig{ + expected: repo_model.PullRequestsConfig{ AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true, - DefaultMergeStyle: models.MergeStyleMerge, + DefaultMergeStyle: repo_model.MergeStyleMerge, }, wantFixed: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cfg := &models.PullRequestsConfig{} + cfg := &repo_model.PullRequestsConfig{} gotFixed, err := fixPullRequestsConfig16961([]byte(tt.bs), cfg) if (err != nil) != tt.wantErr { t.Errorf("fixPullRequestsConfig_16961() error = %v, wantErr %v", err, tt.wantErr) @@ -231,14 +231,14 @@ func Test_fixIssuesConfig_16961(t *testing.T) { tests := []struct { name string bs string - expected models.IssuesConfig + expected repo_model.IssuesConfig wantFixed bool wantErr bool }{ { name: "normal", bs: `{"EnableTimetracker":true,"AllowOnlyContributorsToTrackTime":true,"EnableDependencies":true}`, - expected: models.IssuesConfig{ + expected: repo_model.IssuesConfig{ EnableTimetracker: true, AllowOnlyContributorsToTrackTime: true, EnableDependencies: true, @@ -247,7 +247,7 @@ func Test_fixIssuesConfig_16961(t *testing.T) { { name: "broken", bs: `&{%!s(bool=true) %!s(bool=true) %!s(bool=true)}`, - expected: models.IssuesConfig{ + expected: repo_model.IssuesConfig{ EnableTimetracker: true, AllowOnlyContributorsToTrackTime: true, EnableDependencies: true, @@ -257,7 +257,7 @@ func Test_fixIssuesConfig_16961(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cfg := &models.IssuesConfig{} + cfg := &repo_model.IssuesConfig{} gotFixed, err := fixIssuesConfig16961([]byte(tt.bs), cfg) if (err != nil) != tt.wantErr { t.Errorf("fixIssuesConfig_16961() error = %v, wantErr %v", err, tt.wantErr) diff --git a/modules/doctor/mergebase.go b/modules/doctor/mergebase.go index c959da8d7..ef78cc49d 100644 --- a/modules/doctor/mergebase.go +++ b/modules/doctor/mergebase.go @@ -10,13 +10,14 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "xorm.io/builder" ) -func iteratePRs(repo *models.Repository, each func(*models.Repository, *models.PullRequest) error) error { +func iteratePRs(repo *repo_model.Repository, each func(*repo_model.Repository, *models.PullRequest) error) error { return db.Iterate( db.DefaultContext, new(models.PullRequest), @@ -31,9 +32,9 @@ func checkPRMergeBase(logger log.Logger, autofix bool) error { numRepos := 0 numPRs := 0 numPRsUpdated := 0 - err := iterateRepositories(func(repo *models.Repository) error { + err := iterateRepositories(func(repo *repo_model.Repository) error { numRepos++ - return iteratePRs(repo, func(repo *models.Repository, pr *models.PullRequest) error { + return iteratePRs(repo, func(repo *repo_model.Repository, pr *models.PullRequest) error { numPRs++ pr.BaseRepo = repo repoPath := repo.RepoPath() diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index 1cf8024b9..a788e5f6a 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -25,13 +26,13 @@ import ( "xorm.io/builder" ) -func iterateRepositories(each func(*models.Repository) error) error { +func iterateRepositories(each func(*repo_model.Repository) error) error { err := db.Iterate( db.DefaultContext, - new(models.Repository), + new(repo_model.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { - return each(bean.(*models.Repository)) + return each(bean.(*repo_model.Repository)) }, ) return err @@ -48,7 +49,7 @@ func checkScriptType(logger log.Logger, autofix bool) error { } func checkHooks(logger log.Logger, autofix bool) error { - if err := iterateRepositories(func(repo *models.Repository) error { + if err := iterateRepositories(func(repo *repo_model.Repository) error { results, err := repository.CheckDelegateHooks(repo.RepoPath()) if err != nil { logger.Critical("Unable to check delegate hooks for repo %-v. ERROR: %v", repo, err) @@ -84,7 +85,7 @@ func checkEnablePushOptions(logger log.Logger, autofix bool) error { numRepos := 0 numNeedUpdate := 0 - if err := iterateRepositories(func(repo *models.Repository) error { + if err := iterateRepositories(func(repo *repo_model.Repository) error { numRepos++ r, err := git.OpenRepository(repo.RepoPath()) if err != nil { @@ -131,13 +132,13 @@ func checkDaemonExport(logger log.Logger, autofix bool) error { logger.Critical("Unable to create cache: %v", err) return err } - if err := iterateRepositories(func(repo *models.Repository) error { + if err := iterateRepositories(func(repo *repo_model.Repository) error { numRepos++ if owner, has := cache.Get(repo.OwnerID); has { repo.Owner = owner.(*user_model.User) } else { - if err := repo.GetOwner(); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { return err } cache.Add(repo.OwnerID, repo.Owner) diff --git a/modules/gitgraph/graph_models.go b/modules/gitgraph/graph_models.go index d7d198e01..e7280e2ad 100644 --- a/modules/gitgraph/graph_models.go +++ b/modules/gitgraph/graph_models.go @@ -11,6 +11,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -87,7 +88,7 @@ func (graph *Graph) AddCommit(row, column int, flowID int64, data []byte) error // LoadAndProcessCommits will load the git.Commits for each commit in the graph, // the associate the commit with the user author, and check the commit verification // before finally retrieving the latest status -func (graph *Graph) LoadAndProcessCommits(repository *models.Repository, gitRepo *git.Repository) error { +func (graph *Graph) LoadAndProcessCommits(repository *repo_model.Repository, gitRepo *git.Repository) error { var err error var ok bool diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 97d5fb082..1affdf73b 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -13,7 +13,7 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/analyze" "code.gitea.io/gitea/modules/charset" "code.gitea.io/gitea/modules/git" @@ -181,7 +181,7 @@ func NewBleveIndexer(indexDir string) (*BleveIndexer, bool, error) { } func (b *BleveIndexer) addUpdate(batchWriter git.WriteCloserError, batchReader *bufio.Reader, commitSha string, - update fileUpdate, repo *models.Repository, batch *gitea_bleve.FlushingBatch) error { + update fileUpdate, repo *repo_model.Repository, batch *gitea_bleve.FlushingBatch) error { // Ignore vendored files in code search if setting.Indexer.ExcludeVendored && analyze.IsVendor(update.Filename) { return nil @@ -234,7 +234,7 @@ func (b *BleveIndexer) addUpdate(batchWriter git.WriteCloserError, batchReader * }) } -func (b *BleveIndexer) addDelete(filename string, repo *models.Repository, batch *gitea_bleve.FlushingBatch) error { +func (b *BleveIndexer) addDelete(filename string, repo *repo_model.Repository, batch *gitea_bleve.FlushingBatch) error { id := filenameIndexerID(repo.ID, filename) return batch.Delete(id) } @@ -271,7 +271,7 @@ func (b *BleveIndexer) Close() { } // Index indexes the data -func (b *BleveIndexer) Index(repo *models.Repository, sha string, changes *repoChanges) error { +func (b *BleveIndexer) Index(repo *repo_model.Repository, sha string, changes *repoChanges) error { batch := gitea_bleve.NewFlushingBatch(b.indexer, maxBatchSize) if len(changes.Updates) > 0 { diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index 6e0813dc1..bd5faf3b0 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -13,7 +13,7 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/analyze" "code.gitea.io/gitea/modules/charset" "code.gitea.io/gitea/modules/git" @@ -177,7 +177,7 @@ func (b *ElasticSearchIndexer) init() (bool, error) { return exists, nil } -func (b *ElasticSearchIndexer) addUpdate(batchWriter git.WriteCloserError, batchReader *bufio.Reader, sha string, update fileUpdate, repo *models.Repository) ([]elastic.BulkableRequest, error) { +func (b *ElasticSearchIndexer) addUpdate(batchWriter git.WriteCloserError, batchReader *bufio.Reader, sha string, update fileUpdate, repo *repo_model.Repository) ([]elastic.BulkableRequest, error) { // Ignore vendored files in code search if setting.Indexer.ExcludeVendored && analyze.IsVendor(update.Filename) { return nil, nil @@ -236,7 +236,7 @@ func (b *ElasticSearchIndexer) addUpdate(batchWriter git.WriteCloserError, batch }, nil } -func (b *ElasticSearchIndexer) addDelete(filename string, repo *models.Repository) elastic.BulkableRequest { +func (b *ElasticSearchIndexer) addDelete(filename string, repo *repo_model.Repository) elastic.BulkableRequest { id := filenameIndexerID(repo.ID, filename) return elastic.NewBulkDeleteRequest(). Index(b.indexerAliasName). @@ -244,7 +244,7 @@ func (b *ElasticSearchIndexer) addDelete(filename string, repo *models.Repositor } // Index will save the index data -func (b *ElasticSearchIndexer) Index(repo *models.Repository, sha string, changes *repoChanges) error { +func (b *ElasticSearchIndexer) Index(repo *repo_model.Repository, sha string, changes *repoChanges) error { reqs := make([]elastic.BulkableRequest, 0) if len(changes.Updates) > 0 { diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 919d78540..b76f6d677 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -27,7 +27,7 @@ type repoChanges struct { RemovedFilenames []string } -func getDefaultBranchSha(repo *models.Repository) (string, error) { +func getDefaultBranchSha(repo *repo_model.Repository) (string, error) { stdout, err := git.NewCommand("show-ref", "-s", git.BranchPrefix+repo.DefaultBranch).RunInDir(repo.RepoPath()) if err != nil { return "", err @@ -36,8 +36,8 @@ func getDefaultBranchSha(repo *models.Repository) (string, error) { } // getRepoChanges returns changes to repo since last indexer update -func getRepoChanges(repo *models.Repository, revision string) (*repoChanges, error) { - status, err := repo.GetIndexerStatus(models.RepoIndexerTypeCode) +func getRepoChanges(repo *repo_model.Repository, revision string) (*repoChanges, error) { + status, err := repo_model.GetIndexerStatus(repo, repo_model.RepoIndexerTypeCode) if err != nil { return nil, err } @@ -89,7 +89,7 @@ func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) { } // genesisChanges get changes to add repo to the indexer for the first time -func genesisChanges(repo *models.Repository, revision string) (*repoChanges, error) { +func genesisChanges(repo *repo_model.Repository, revision string) (*repoChanges, error) { var changes repoChanges stdout, err := git.NewCommand("ls-tree", "--full-tree", "-l", "-r", revision). RunInDirBytes(repo.RepoPath()) @@ -101,7 +101,7 @@ func genesisChanges(repo *models.Repository, revision string) (*repoChanges, err } // nonGenesisChanges get changes since the previous indexer update -func nonGenesisChanges(repo *models.Repository, revision string) (*repoChanges, error) { +func nonGenesisChanges(repo *repo_model.Repository, revision string) (*repoChanges, error) { diffCmd := git.NewCommand("diff", "--name-status", repo.CodeIndexerStatus.CommitSha, revision) stdout, err := diffCmd.RunInDir(repo.RepoPath()) diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index c56b1b2bb..a616d0e66 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -11,8 +11,8 @@ import ( "strings" "time" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/queue" @@ -42,7 +42,7 @@ type SearchResultLanguages struct { // Indexer defines an interface to index and search code contents type Indexer interface { - Index(repo *models.Repository, sha string, changes *repoChanges) error + Index(repo *repo_model.Repository, sha string, changes *repoChanges) error Delete(repoID int64) error Search(repoIDs []int64, language, keyword string, page, pageSize int, isMatch bool) (int64, []*SearchResult, []*SearchResultLanguages, error) Close() @@ -83,8 +83,8 @@ var ( ) func index(indexer Indexer, repoID int64) error { - repo, err := models.GetRepositoryByID(repoID) - if models.IsErrRepoNotExist(err) { + repo, err := repo_model.GetRepositoryByID(repoID) + if repo_model.IsErrRepoNotExist(err) { return indexer.Delete(repoID) } if err != nil { @@ -106,7 +106,7 @@ func index(indexer Indexer, repoID int64) error { return err } - return repo.UpdateIndexerStatus(models.RepoIndexerTypeCode, sha) + return repo_model.UpdateIndexerStatus(repo, repo_model.RepoIndexerTypeCode, sha) } // Init initialize the repo indexer @@ -256,7 +256,7 @@ func Init() { } // UpdateRepoIndexer update a repository's entries in the indexer -func UpdateRepoIndexer(repo *models.Repository) { +func UpdateRepoIndexer(repo *repo_model.Repository) { indexData := &IndexerData{RepoID: repo.ID} if err := indexerQueue.Push(indexData); err != nil { log.Error("Update repo index data %v failed: %v", indexData, err) @@ -297,7 +297,7 @@ func populateRepoIndexer(ctx context.Context) { return default: } - ids, err := models.GetUnindexedRepos(models.RepoIndexerTypeCode, maxRepoID, 0, 50) + ids, err := repo_model.GetUnindexedRepos(repo_model.RepoIndexerTypeCode, maxRepoID, 0, 50) if err != nil { log.Error("populateRepoIndexer: %v", err) return diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index b8fedcb32..98494afce 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "testing" + _ "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" diff --git a/modules/indexer/code/wrapped.go b/modules/indexer/code/wrapped.go index 5b19f9c62..7e97a6a32 100644 --- a/modules/indexer/code/wrapped.go +++ b/modules/indexer/code/wrapped.go @@ -8,7 +8,7 @@ import ( "fmt" "sync" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" ) var ( @@ -57,7 +57,7 @@ func (w *wrappedIndexer) get() (Indexer, error) { return w.internal, nil } -func (w *wrappedIndexer) Index(repo *models.Repository, sha string, changes *repoChanges) error { +func (w *wrappedIndexer) Index(repo *repo_model.Repository, sha string, changes *repoChanges) error { indexer, err := w.get() if err != nil { return err diff --git a/modules/indexer/issues/indexer.go b/modules/indexer/issues/indexer.go index 0b855460b..4db509176 100644 --- a/modules/indexer/issues/indexer.go +++ b/modules/indexer/issues/indexer.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/queue" @@ -269,7 +270,7 @@ func populateIssueIndexer(ctx context.Context) { } // UpdateRepoIndexer add/update all issues of the repositories -func UpdateRepoIndexer(repo *models.Repository) { +func UpdateRepoIndexer(repo *repo_model.Repository) { is, err := models.Issues(&models.IssuesOptions{ RepoIDs: []int64{repo.ID}, IsClosed: util.OptionalBoolNone, @@ -310,7 +311,7 @@ func UpdateIssueIndexer(issue *models.Issue) { } // DeleteRepoIssueIndexer deletes repo's all issues indexes -func DeleteRepoIssueIndexer(repo *models.Repository) { +func DeleteRepoIssueIndexer(repo *repo_model.Repository) { var ids []int64 ids, err := models.GetIssueIDsByRepoID(repo.ID) if err != nil { diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 8353891c7..085516555 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + _ "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go index 9e251d0f6..9d2942a26 100644 --- a/modules/indexer/stats/db.go +++ b/modules/indexer/stats/db.go @@ -7,7 +7,7 @@ package stats import ( "fmt" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" @@ -23,7 +23,7 @@ func (db *DBIndexer) Index(id int64) error { ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("Stats.DB Index Repo[%d]", id)) defer finished() - repo, err := models.GetRepositoryByID(id) + repo, err := repo_model.GetRepositoryByID(id) if err != nil { return err } @@ -31,7 +31,7 @@ func (db *DBIndexer) Index(id int64) error { return nil } - status, err := repo.GetIndexerStatus(models.RepoIndexerTypeStats) + status, err := repo_model.GetIndexerStatus(repo, repo_model.RepoIndexerTypeStats) if err != nil { return err } @@ -64,7 +64,7 @@ func (db *DBIndexer) Index(id int64) error { log.Error("Unable to get language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err) return err } - err = repo.UpdateLanguageStats(commitID, stats) + err = repo_model.UpdateLanguageStats(repo, commitID, stats) if err != nil { log.Error("Unable to update language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err) return err diff --git a/modules/indexer/stats/indexer.go b/modules/indexer/stats/indexer.go index fe87a2268..f4fe54b8c 100644 --- a/modules/indexer/stats/indexer.go +++ b/modules/indexer/stats/indexer.go @@ -5,8 +5,8 @@ package stats import ( - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" ) @@ -62,7 +62,7 @@ func populateRepoIndexer() { return default: } - ids, err := models.GetUnindexedRepos(models.RepoIndexerTypeStats, maxRepoID, 0, 50) + ids, err := repo_model.GetUnindexedRepos(repo_model.RepoIndexerTypeStats, maxRepoID, 0, 50) if err != nil { log.Error("populateRepoIndexer: %v", err) return diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index f52d73a32..b32100b45 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -9,7 +9,8 @@ import ( "testing" "time" - "code.gitea.io/gitea/models" + _ "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" @@ -32,12 +33,12 @@ func TestRepoStatsIndex(t *testing.T) { time.Sleep(5 * time.Second) - repo, err := models.GetRepositoryByID(1) + repo, err := repo_model.GetRepositoryByID(1) assert.NoError(t, err) - status, err := repo.GetIndexerStatus(models.RepoIndexerTypeStats) + status, err := repo_model.GetIndexerStatus(repo, repo_model.RepoIndexerTypeStats) assert.NoError(t, err) assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.CommitSha) - langs, err := repo.GetTopLanguageStats(5) + langs, err := repo_model.GetTopLanguageStats(repo, 5) assert.NoError(t, err) assert.Empty(t, langs) } diff --git a/modules/indexer/stats/queue.go b/modules/indexer/stats/queue.go index fde3f2ff0..b45844469 100644 --- a/modules/indexer/stats/queue.go +++ b/modules/indexer/stats/queue.go @@ -7,7 +7,7 @@ package stats import ( "fmt" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/queue" @@ -38,7 +38,7 @@ func initStatsQueue() error { } // UpdateRepoIndexer update a repository's entries in the indexer -func UpdateRepoIndexer(repo *models.Repository) error { +func UpdateRepoIndexer(repo *repo_model.Repository) error { if err := statsQueue.Push(repo.ID); err != nil { if err != queue.ErrAlreadyInQueue { return err diff --git a/modules/json/json.go b/modules/json/json.go index be42b6ae6..1cbb65826 100644 --- a/modules/json/json.go +++ b/modules/json/json.go @@ -6,6 +6,7 @@ package json import ( "bytes" + "encoding/binary" "encoding/json" "io" @@ -140,3 +141,32 @@ func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { func Valid(data []byte) bool { return json.Valid(data) } + +// UnmarshalHandleDoubleEncode - 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 UnmarshalHandleDoubleEncode(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 +} diff --git a/modules/notification/action/action.go b/modules/notification/action/action.go index 81a011fbe..376c5d103 100644 --- a/modules/notification/action/action.go +++ b/modules/notification/action/action.go @@ -10,6 +10,7 @@ import ( "strings" "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/json" "code.gitea.io/gitea/modules/log" @@ -89,7 +90,7 @@ func (a *actionNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *m } // NotifyCreateIssueComment notifies comment on an issue to notifiers -func (a *actionNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func (a *actionNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { act := &models.Action{ ActUserID: doer.ID, @@ -150,7 +151,7 @@ func (a *actionNotifier) NotifyNewPullRequest(pull *models.PullRequest, mentions } } -func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *models.Repository, oldRepoName string) { +func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { log.Trace("action.ChangeRepositoryName: %s/%s", doer.Name, repo.Name) if err := models.NotifyWatchers(&models.Action{ @@ -166,7 +167,7 @@ func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *mod } } -func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *models.Repository, oldOwnerName string) { +func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { if err := models.NotifyWatchers(&models.Action{ ActUserID: doer.ID, ActUser: doer, @@ -180,7 +181,7 @@ func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *m } } -func (a *actionNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func (a *actionNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { if err := models.NotifyWatchers(&models.Action{ ActUserID: doer.ID, ActUser: doer, @@ -193,7 +194,7 @@ func (a *actionNotifier) NotifyCreateRepository(doer *user_model.User, u *user_m } } -func (a *actionNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *models.Repository) { +func (a *actionNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { if err := models.NotifyWatchers(&models.Action{ ActUserID: doer.ID, ActUser: doer, @@ -298,7 +299,7 @@ func (*actionNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *m } } -func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { data, err := json.Marshal(commits) if err != nil { log.Error("Marshal: %v", err) @@ -331,7 +332,7 @@ func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *models } } -func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { opType := models.ActionCommitRepo if refType == "tag" { // has sent same action in `NotifyPushCommits`, so skip it. @@ -350,7 +351,7 @@ func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *models.Rep } } -func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { opType := models.ActionDeleteBranch if refType == "tag" { // has sent same action in `NotifyPushCommits`, so skip it. @@ -369,7 +370,7 @@ func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *models.Rep } } -func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { data, err := json.Marshal(commits) if err != nil { log.Error("json.Marshal: %v", err) @@ -390,7 +391,7 @@ func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *mo } } -func (a *actionNotifier) NotifySyncCreateRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (a *actionNotifier) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { if err := models.NotifyWatchers(&models.Action{ ActUserID: repo.OwnerID, ActUser: repo.MustOwner(), @@ -404,7 +405,7 @@ func (a *actionNotifier) NotifySyncCreateRef(doer *user_model.User, repo *models } } -func (a *actionNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (a *actionNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { if err := models.NotifyWatchers(&models.Action{ ActUserID: repo.OwnerID, ActUser: repo.MustOwner(), diff --git a/modules/notification/action/action_test.go b/modules/notification/action/action_test.go index 2218bd46c..3664b8210 100644 --- a/modules/notification/action/action_test.go +++ b/modules/notification/action/action_test.go @@ -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" @@ -24,7 +25,7 @@ func TestRenameRepoAction(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID}).(*repo_model.Repository) repo.Owner = user oldRepoName := repo.Name diff --git a/modules/notification/base/notifier.go b/modules/notification/base/notifier.go index 24f6375a6..937476475 100644 --- a/modules/notification/base/notifier.go +++ b/modules/notification/base/notifier.go @@ -6,6 +6,7 @@ package base import ( "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/repository" ) @@ -14,12 +15,12 @@ import ( type Notifier interface { Run() - NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) - NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) - NotifyDeleteRepository(doer *user_model.User, repo *models.Repository) - NotifyForkRepository(doer *user_model.User, oldRepo, repo *models.Repository) - NotifyRenameRepository(doer *user_model.User, repo *models.Repository, oldRepoName string) - NotifyTransferRepository(doer *user_model.User, repo *models.Repository, oldOwnerName string) + NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) + NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) + NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) + NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) + NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) + NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) NotifyNewIssue(issue *models.Issue, mentions []*user_model.User) NotifyIssueChangeStatus(*user_model.User, *models.Issue, *models.Comment, bool) @@ -42,7 +43,7 @@ type Notifier interface { NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment) NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment) - NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, + NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) NotifyUpdateComment(*user_model.User, *models.Comment, string) NotifyDeleteComment(*user_model.User, *models.Comment) @@ -51,13 +52,13 @@ type Notifier interface { NotifyUpdateRelease(doer *user_model.User, rel *models.Release) NotifyDeleteRelease(doer *user_model.User, rel *models.Release) - NotifyPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) - NotifyCreateRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) - NotifyDeleteRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) + NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) + NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) + NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) - NotifySyncPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) - NotifySyncCreateRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) - NotifySyncDeleteRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) + NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) + NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) + NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) - NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *models.Repository) + NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) } diff --git a/modules/notification/base/null.go b/modules/notification/base/null.go index 8a977e122..062edf400 100644 --- a/modules/notification/base/null.go +++ b/modules/notification/base/null.go @@ -6,6 +6,7 @@ package base import ( "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/repository" ) @@ -23,7 +24,7 @@ func (*NullNotifier) Run() { } // NotifyCreateIssueComment places a place holder function -func (*NullNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func (*NullNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { } @@ -121,53 +122,53 @@ func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *model } // NotifyCreateRepository places a place holder function -func (*NullNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func (*NullNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { } // NotifyDeleteRepository places a place holder function -func (*NullNotifier) NotifyDeleteRepository(doer *user_model.User, repo *models.Repository) { +func (*NullNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { } // NotifyForkRepository places a place holder function -func (*NullNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *models.Repository) { +func (*NullNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { } // NotifyMigrateRepository places a place holder function -func (*NullNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func (*NullNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { } // NotifyPushCommits notifies commits pushed to notifiers -func (*NullNotifier) NotifyPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (*NullNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { } // NotifyCreateRef notifies branch or tag creation to notifiers -func (*NullNotifier) NotifyCreateRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (*NullNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { } // NotifyDeleteRef notifies branch or tag deletion to notifiers -func (*NullNotifier) NotifyDeleteRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (*NullNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { } // NotifyRenameRepository places a place holder function -func (*NullNotifier) NotifyRenameRepository(doer *user_model.User, repo *models.Repository, oldRepoName string) { +func (*NullNotifier) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { } // NotifyTransferRepository places a place holder function -func (*NullNotifier) NotifyTransferRepository(doer *user_model.User, repo *models.Repository, oldOwnerName string) { +func (*NullNotifier) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { } // NotifySyncPushCommits places a place holder function -func (*NullNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (*NullNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { } // NotifySyncCreateRef places a place holder function -func (*NullNotifier) NotifySyncCreateRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (*NullNotifier) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { } // NotifySyncDeleteRef places a place holder function -func (*NullNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *models.Repository, refType, refFullName string) { +func (*NullNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { } // NotifyRepoPendingTransfer places a place holder function -func (*NullNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *models.Repository) { +func (*NullNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { } diff --git a/modules/notification/indexer/indexer.go b/modules/notification/indexer/indexer.go index 03914db03..92fe3c501 100644 --- a/modules/notification/indexer/indexer.go +++ b/modules/notification/indexer/indexer.go @@ -6,6 +6,7 @@ package indexer import ( "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/git" code_indexer "code.gitea.io/gitea/modules/indexer/code" @@ -30,7 +31,7 @@ func NewNotifier() base.Notifier { return &indexerNotifier{} } -func (r *indexerNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func (r *indexerNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { if comment.Type == models.CommentTypeComment { if issue.Comments == nil { @@ -107,14 +108,14 @@ func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *mo } } -func (r *indexerNotifier) NotifyDeleteRepository(doer *user_model.User, repo *models.Repository) { +func (r *indexerNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { issue_indexer.DeleteRepoIssueIndexer(repo) if setting.Indexer.RepoIndexerEnabled { code_indexer.UpdateRepoIndexer(repo) } } -func (r *indexerNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func (r *indexerNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { issue_indexer.UpdateRepoIndexer(repo) if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty { code_indexer.UpdateRepoIndexer(repo) @@ -124,7 +125,7 @@ func (r *indexerNotifier) NotifyMigrateRepository(doer *user_model.User, u *user } } -func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch { code_indexer.UpdateRepoIndexer(repo) } @@ -133,7 +134,7 @@ func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *model } } -func (r *indexerNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (r *indexerNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch { code_indexer.UpdateRepoIndexer(repo) } diff --git a/modules/notification/mail/mail.go b/modules/notification/mail/mail.go index c1c9e9613..6ad0ca0d8 100644 --- a/modules/notification/mail/mail.go +++ b/modules/notification/mail/mail.go @@ -8,6 +8,7 @@ import ( "fmt" "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/log" "code.gitea.io/gitea/modules/notification/base" @@ -27,7 +28,7 @@ func NewNotifier() base.Notifier { return &mailNotifier{} } -func (m *mailNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func (m *mailNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { var act models.ActionType if comment.Type == models.CommentTypeClose { @@ -184,7 +185,7 @@ func (m *mailNotifier) NotifyNewRelease(rel *models.Release) { mailer.MailNewRelease(rel) } -func (m *mailNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *models.Repository) { +func (m *mailNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { if err := mailer.SendRepoTransferNotifyMail(doer, newOwner, repo); err != nil { log.Error("NotifyRepoPendingTransfer: %v", err) } diff --git a/modules/notification/notification.go b/modules/notification/notification.go index 9bea38faf..d976dfea6 100644 --- a/modules/notification/notification.go +++ b/modules/notification/notification.go @@ -6,6 +6,7 @@ package notification import ( "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/notification/action" "code.gitea.io/gitea/modules/notification/base" @@ -39,7 +40,7 @@ func NewContext() { } // NotifyCreateIssueComment notifies issue comment related message to notifiers -func NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { for _, notifier := range notifiers { notifier.NotifyCreateIssueComment(doer, repo, issue, comment, mentions) @@ -209,91 +210,91 @@ func NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, } // NotifyCreateRepository notifies create repository to notifiers -func NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { notifier.NotifyCreateRepository(doer, u, repo) } } // NotifyMigrateRepository notifies create repository to notifiers -func NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { notifier.NotifyMigrateRepository(doer, u, repo) } } // NotifyTransferRepository notifies create repository to notifiers -func NotifyTransferRepository(doer *user_model.User, repo *models.Repository, newOwnerName string) { +func NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, newOwnerName string) { for _, notifier := range notifiers { notifier.NotifyTransferRepository(doer, repo, newOwnerName) } } // NotifyDeleteRepository notifies delete repository to notifiers -func NotifyDeleteRepository(doer *user_model.User, repo *models.Repository) { +func NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { notifier.NotifyDeleteRepository(doer, repo) } } // NotifyForkRepository notifies fork repository to notifiers -func NotifyForkRepository(doer *user_model.User, oldRepo, repo *models.Repository) { +func NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { for _, notifier := range notifiers { notifier.NotifyForkRepository(doer, oldRepo, repo) } } // NotifyRenameRepository notifies repository renamed -func NotifyRenameRepository(doer *user_model.User, repo *models.Repository, oldName string) { +func NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldName string) { for _, notifier := range notifiers { notifier.NotifyRenameRepository(doer, repo, oldName) } } // NotifyPushCommits notifies commits pushed to notifiers -func NotifyPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { for _, notifier := range notifiers { notifier.NotifyPushCommits(pusher, repo, opts, commits) } } // NotifyCreateRef notifies branch or tag creation to notifiers -func NotifyCreateRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func NotifyCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { for _, notifier := range notifiers { notifier.NotifyCreateRef(pusher, repo, refType, refFullName) } } // NotifyDeleteRef notifies branch or tag deletion to notifiers -func NotifyDeleteRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func NotifyDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { for _, notifier := range notifiers { notifier.NotifyDeleteRef(pusher, repo, refType, refFullName) } } // NotifySyncPushCommits notifies commits pushed to notifiers -func NotifySyncPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { for _, notifier := range notifiers { notifier.NotifySyncPushCommits(pusher, repo, opts, commits) } } // NotifySyncCreateRef notifies branch or tag creation to notifiers -func NotifySyncCreateRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func NotifySyncCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { for _, notifier := range notifiers { notifier.NotifySyncCreateRef(pusher, repo, refType, refFullName) } } // NotifySyncDeleteRef notifies branch or tag deletion to notifiers -func NotifySyncDeleteRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func NotifySyncDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { for _, notifier := range notifiers { notifier.NotifySyncDeleteRef(pusher, repo, refType, refFullName) } } // NotifyRepoPendingTransfer notifies creation of pending transfer to notifiers -func NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *models.Repository) { +func NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { notifier.NotifyRepoPendingTransfer(doer, newOwner, repo) } diff --git a/modules/notification/ui/ui.go b/modules/notification/ui/ui.go index 04967fc58..25f015d0e 100644 --- a/modules/notification/ui/ui.go +++ b/modules/notification/ui/ui.go @@ -6,6 +6,7 @@ package ui import ( "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/graceful" "code.gitea.io/gitea/modules/log" @@ -51,7 +52,7 @@ func (ns *notificationService) Run() { graceful.GetManager().RunWithShutdownFns(ns.issueQueue.Run) } -func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { var opts = issueNotificationOpts{ IssueID: issue.ID, @@ -233,7 +234,7 @@ func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, is } } -func (ns *notificationService) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *models.Repository) { +func (ns *notificationService) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { if err := models.CreateRepoTransferNotification(doer, newOwner, repo); err != nil { log.Error("NotifyRepoPendingTransfer: %v", err) } diff --git a/modules/notification/webhook/webhook.go b/modules/notification/webhook/webhook.go index 378e7fd20..7e96ed050 100644 --- a/modules/notification/webhook/webhook.go +++ b/modules/notification/webhook/webhook.go @@ -7,6 +7,7 @@ package webhook 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/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/models/webhook" @@ -73,7 +74,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *m } } -func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *models.Repository) { +func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { oldMode, _ := models.AccessLevel(doer, oldRepo) mode, _ := models.AccessLevel(doer, repo) @@ -101,7 +102,7 @@ func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, r } } -func (m *webhookNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func (m *webhookNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { // Add to hook queue for created repo after session commit. if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, @@ -113,7 +114,7 @@ func (m *webhookNotifier) NotifyCreateRepository(doer *user_model.User, u *user_ } } -func (m *webhookNotifier) NotifyDeleteRepository(doer *user_model.User, repo *models.Repository) { +func (m *webhookNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { u := repo.MustOwner() if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{ @@ -126,7 +127,7 @@ func (m *webhookNotifier) NotifyDeleteRepository(doer *user_model.User, repo *mo } } -func (m *webhookNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *models.Repository) { +func (m *webhookNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { // Add to hook queue for created repo after session commit. if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, @@ -402,7 +403,7 @@ func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *models.C } } -func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *models.Repository, +func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { mode, _ := models.AccessLevel(doer, repo) @@ -564,7 +565,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu } } -func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { apiPusher := convert.ToUser(pusher, nil) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(repo.RepoPath(), repo.HTMLURL()) if err != nil { @@ -697,7 +698,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(pr *models.PullRequest, review } } -func (m *webhookNotifier) NotifyCreateRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func (m *webhookNotifier) NotifyCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { apiPusher := convert.ToUser(pusher, nil) apiRepo := convert.ToRepo(repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) @@ -748,7 +749,7 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(doer *user_model.User, p } } -func (m *webhookNotifier) NotifyDeleteRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func (m *webhookNotifier) NotifyDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { apiPusher := convert.ToUser(pusher, nil) apiRepo := convert.ToRepo(repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) @@ -793,7 +794,7 @@ func (m *webhookNotifier) NotifyDeleteRelease(doer *user_model.User, rel *models sendReleaseHook(doer, rel, api.HookReleaseDeleted) } -func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { apiPusher := convert.ToUser(pusher, nil) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(repo.RepoPath(), repo.HTMLURL()) if err != nil { @@ -816,10 +817,10 @@ func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *m } } -func (m *webhookNotifier) NotifySyncCreateRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func (m *webhookNotifier) NotifySyncCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { m.NotifyCreateRef(pusher, repo, refType, refFullName) } -func (m *webhookNotifier) NotifySyncDeleteRef(pusher *user_model.User, repo *models.Repository, refType, refFullName string) { +func (m *webhookNotifier) NotifySyncDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { m.NotifyDeleteRef(pusher, repo, refType, refFullName) } diff --git a/modules/repofiles/commit_status.go b/modules/repofiles/commit_status.go index 2074b4b46..21aaa9ee5 100644 --- a/modules/repofiles/commit_status.go +++ b/modules/repofiles/commit_status.go @@ -8,6 +8,7 @@ import ( "fmt" "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/git" ) @@ -15,7 +16,7 @@ import ( // CreateCommitStatus creates a new CommitStatus given a bunch of parameters // NOTE: All text-values will be trimmed from whitespaces. // Requires: Repo, Creator, SHA -func CreateCommitStatus(repo *models.Repository, creator *user_model.User, sha string, status *models.CommitStatus) error { +func CreateCommitStatus(repo *repo_model.Repository, creator *user_model.User, sha string, status *models.CommitStatus) error { repoPath := repo.RepoPath() // confirm that commit is exist diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index b6a63dc12..30edf3362 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -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/git" @@ -49,7 +49,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { } pushCommits.HeadCommit = &PushCommit{Sha1: "69554a6"} - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}).(*repo_model.Repository) payloadCommits, headCommit, err := pushCommits.ToAPIPayloadCommits(repo.RepoPath(), "/user2/repo16") assert.NoError(t, err) assert.Len(t, payloadCommits, 3) diff --git a/modules/repository/create.go b/modules/repository/create.go index 850f7488b..ddc001d60 100644 --- a/modules/repository/create.go +++ b/modules/repository/create.go @@ -11,6 +11,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -19,7 +20,7 @@ import ( ) // CreateRepository creates a repository for the user/organization. -func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (*models.Repository, error) { +func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (*repo_model.Repository, error) { if !doer.IsAdmin && !u.CanCreateRepo() { return nil, models.ErrReachLimitOfRepo{ Limit: u.MaxRepoCreation, @@ -37,7 +38,7 @@ func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) ( } } - repo := &models.Repository{ + repo := &repo_model.Repository{ OwnerID: u.ID, Owner: u, OwnerName: u.Name, @@ -55,7 +56,7 @@ func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) ( TrustModel: opts.TrustModel, } - var rollbackRepo *models.Repository + var rollbackRepo *repo_model.Repository if err := db.WithTx(func(ctx context.Context) error { if err := models.CreateRepository(ctx, doer, u, repo, false); err != nil { @@ -67,7 +68,7 @@ func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) ( return nil } - repoPath := models.RepoPath(u.Name, repo.Name) + repoPath := repo_model.RepoPath(u.Name, repo.Name) isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) @@ -106,7 +107,7 @@ func CreateRepository(doer, u *user_model.User, opts models.CreateRepoOptions) ( } } - if err := repo.CheckDaemonExportOK(ctx); err != nil { + if err := models.CheckDaemonExportOK(ctx, repo); err != nil { return fmt.Errorf("checkDaemonExportOK: %v", err) } diff --git a/modules/repository/generate.go b/modules/repository/generate.go index 61a8b0d11..756cfe227 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -14,6 +14,7 @@ import ( "time" "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/git" "code.gitea.io/gitea/modules/log" @@ -45,7 +46,7 @@ var defaultTransformers = []transformer{ {Name: "TITLE", Transform: strings.Title}, } -func generateExpansion(src string, templateRepo, generateRepo *models.Repository) string { +func generateExpansion(src string, templateRepo, generateRepo *repo_model.Repository) string { expansions := []expansion{ {Name: "REPO_NAME", Value: generateRepo.Name, Transformers: defaultTransformers}, {Name: "TEMPLATE_NAME", Value: templateRepo.Name, Transformers: defaultTransformers}, @@ -98,7 +99,7 @@ func checkGiteaTemplate(tmpDir string) (*models.GiteaTemplate, error) { return gt, nil } -func generateRepoCommit(repo, templateRepo, generateRepo *models.Repository, tmpDir string) error { +func generateRepoCommit(repo, templateRepo, generateRepo *repo_model.Repository, tmpDir string) error { commitTimeStr := time.Now().Format(time.RFC3339) authorSig := repo.Owner.NewGitSig() @@ -186,7 +187,7 @@ func generateRepoCommit(repo, templateRepo, generateRepo *models.Repository, tmp return initRepoCommit(tmpDir, repo, repo.Owner, templateRepo.DefaultBranch) } -func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *models.Repository) (err error) { +func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *repo_model.Repository) (err error) { tmpDir, err := os.MkdirTemp(os.TempDir(), "gitea-"+repo.Name) if err != nil { return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err) @@ -203,7 +204,7 @@ func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *m } // re-fetch repo - if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %v", err) } @@ -224,12 +225,12 @@ func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *m } // GenerateGitContent generates git content from a template repository -func GenerateGitContent(ctx context.Context, templateRepo, generateRepo *models.Repository) error { +func GenerateGitContent(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error { if err := generateGitContent(ctx, generateRepo, templateRepo, generateRepo); err != nil { return err } - if err := generateRepo.UpdateSize(ctx); err != nil { + if err := models.UpdateRepoSize(ctx, generateRepo); err != nil { return fmt.Errorf("failed to update size for repository: %v", err) } @@ -240,8 +241,8 @@ func GenerateGitContent(ctx context.Context, templateRepo, generateRepo *models. } // GenerateRepository generates a repository from a template -func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templateRepo *models.Repository, opts models.GenerateRepoOptions) (_ *models.Repository, err error) { - generateRepo := &models.Repository{ +func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templateRepo *repo_model.Repository, opts models.GenerateRepoOptions) (_ *repo_model.Repository, err error) { + generateRepo := &repo_model.Repository{ OwnerID: owner.ID, Owner: owner, OwnerName: owner.Name, @@ -276,7 +277,7 @@ func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templ return generateRepo, err } - if err = generateRepo.CheckDaemonExportOK(ctx); err != nil { + if err = models.CheckDaemonExportOK(ctx, generateRepo); err != nil { return generateRepo, fmt.Errorf("checkDaemonExportOK: %v", err) } diff --git a/modules/repository/init.go b/modules/repository/init.go index d7f31fabd..cfee1a321 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -14,6 +14,7 @@ import ( "time" "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/git" "code.gitea.io/gitea/modules/log" @@ -23,7 +24,7 @@ import ( "github.com/unknwon/com" ) -func prepareRepoCommit(ctx context.Context, repo *models.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error { +func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error { commitTimeStr := time.Now().Format(time.RFC3339) authorSig := repo.Owner.NewGitSig() @@ -101,7 +102,7 @@ func prepareRepoCommit(ctx context.Context, repo *models.Repository, tmpDir, rep } // initRepoCommit temporarily changes with work directory. -func initRepoCommit(tmpPath string, repo *models.Repository, u *user_model.User, defaultBranch string) (err error) { +func initRepoCommit(tmpPath string, repo *repo_model.Repository, u *user_model.User, defaultBranch string) (err error) { commitTimeStr := time.Now().Format(time.RFC3339) sig := u.NewGitSig() @@ -137,7 +138,7 @@ func initRepoCommit(tmpPath string, repo *models.Repository, u *user_model.User, if sign { args = append(args, "-S"+keyID) - if repo.GetTrustModel() == models.CommitterTrustModel || repo.GetTrustModel() == models.CollaboratorCommitterTrustModel { + if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel { // need to set the committer to the KeyID owner committerName = signer.Name committerEmail = signer.Email @@ -175,7 +176,7 @@ func initRepoCommit(tmpPath string, repo *models.Repository, u *user_model.User, func checkInitRepository(owner, name string) (err error) { // Somehow the directory could exist. - repoPath := models.RepoPath(owner, name) + repoPath := repo_model.RepoPath(owner, name) isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) @@ -198,7 +199,7 @@ func checkInitRepository(owner, name string) (err error) { } // InitRepository initializes README and .gitignore if needed. -func initRepository(ctx context.Context, repoPath string, u *user_model.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) { +func initRepository(ctx context.Context, repoPath string, u *user_model.User, repo *repo_model.Repository, opts models.CreateRepoOptions) (err error) { if err = checkInitRepository(repo.OwnerName, repo.Name); err != nil { return err } @@ -227,7 +228,7 @@ func initRepository(ctx context.Context, repoPath string, u *user_model.User, re // Re-fetch the repository from database before updating it (else it would // override changes that were done earlier with sql) - if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %v", err) } diff --git a/modules/repository/push.go b/modules/repository/push.go index 11272f883..038735f58 100644 --- a/modules/repository/push.go +++ b/modules/repository/push.go @@ -7,7 +7,7 @@ package repository import ( "strings" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" ) @@ -104,7 +104,7 @@ func IsForcePush(opts *PushUpdateOptions) (bool, error) { } output, err := git.NewCommand("rev-list", "--max-count=1", opts.OldCommitID, "^"+opts.NewCommitID). - RunInDir(models.RepoPath(opts.RepoUserName, opts.RepoName)) + RunInDir(repo_model.RepoPath(opts.RepoUserName, opts.RepoName)) if err != nil { return false, err } else if len(output) > 0 { diff --git a/modules/repository/repo.go b/modules/repository/repo.go index c7145658f..d04cd28a5 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -15,6 +15,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/lfs" @@ -48,10 +49,10 @@ func WikiRemoteURL(remote string) string { // MigrateRepositoryGitData starts migrating git related data after created migrating repository func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, - repo *models.Repository, opts migration.MigrateOptions, + repo *repo_model.Repository, opts migration.MigrateOptions, httpTransport *http.Transport, -) (*models.Repository, error) { - repoPath := models.RepoPath(u.Name, opts.RepoName) +) (*repo_model.Repository, error) { + repoPath := repo_model.RepoPath(u.Name, opts.RepoName) if u.IsOrganization() { t, err := models.OrgFromUser(u).GetOwnerTeam() @@ -79,7 +80,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, } if opts.Wiki { - wikiPath := models.WikiPath(u.Name, opts.RepoName) + wikiPath := repo_model.WikiPath(u.Name, opts.RepoName) wikiRemotePath := WikiRemoteURL(opts.CloneAddr) if len(wikiRemotePath) > 0 { if err := util.RemoveAll(wikiPath); err != nil { @@ -104,7 +105,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, repo.Owner = u } - if err = repo.CheckDaemonExportOK(ctx); err != nil { + if err = models.CheckDaemonExportOK(ctx, repo); err != nil { return repo, fmt.Errorf("checkDaemonExportOK: %v", err) } @@ -153,12 +154,12 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, } } - if err = repo.UpdateSize(db.DefaultContext); err != nil { + if err = models.UpdateRepoSize(db.DefaultContext, repo); err != nil { log.Error("Failed to update size for repository: %v", err) } if opts.Mirror { - mirrorModel := models.Mirror{ + mirrorModel := repo_model.Mirror{ RepoID: repo.ID, Interval: setting.Mirror.DefaultInterval, EnablePrune: true, @@ -188,7 +189,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, } } - if err = models.InsertMirror(&mirrorModel); err != nil { + if err = repo_model.InsertMirror(&mirrorModel); err != nil { return repo, fmt.Errorf("InsertOne: %v", err) } @@ -216,7 +217,7 @@ func cleanUpMigrateGitConfig(configPath string) error { } // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors. -func CleanUpMigrateInfo(repo *models.Repository) (*models.Repository, error) { +func CleanUpMigrateInfo(repo *repo_model.Repository) (*repo_model.Repository, error) { repoPath := repo.RepoPath() if err := createDelegateHooks(repoPath); err != nil { return repo, fmt.Errorf("createDelegateHooks: %v", err) @@ -242,7 +243,7 @@ func CleanUpMigrateInfo(repo *models.Repository) (*models.Repository, error) { } // SyncReleasesWithTags synchronizes release table with repository tags -func SyncReleasesWithTags(repo *models.Repository, gitRepo *git.Repository) error { +func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) error { existingRelTags := make(map[string]struct{}) opts := models.FindReleasesOptions{ IncludeDrafts: true, @@ -290,7 +291,7 @@ func SyncReleasesWithTags(repo *models.Repository, gitRepo *git.Repository) erro } // PushUpdateAddTag must be called for any push actions to add tag -func PushUpdateAddTag(repo *models.Repository, gitRepo *git.Repository, tagName string) error { +func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagName string) error { tag, err := gitRepo.GetTag(tagName) if err != nil { return fmt.Errorf("GetTag: %v", err) @@ -341,7 +342,7 @@ func PushUpdateAddTag(repo *models.Repository, gitRepo *git.Repository, tagName } // StoreMissingLfsObjectsInRepository downloads missing LFS objects -func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *models.Repository, gitRepo *git.Repository, lfsClient lfs.Client) error { +func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, lfsClient lfs.Client) error { contentStore := lfs.NewContentStore() pointerChan := make(chan lfs.PointerBlob) @@ -364,7 +365,7 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *models.Reposi if err := contentStore.Put(p, content); err != nil { log.Error("Error storing content for LFS meta object %v: %v", p, err) - if _, err2 := repo.RemoveLFSMetaObjectByOid(p.Oid); err2 != nil { + if _, err2 := models.RemoveLFSMetaObjectByOid(repo.ID, p.Oid); err2 != nil { log.Error("Error removing LFS meta object %v: %v", p, err2) } return err @@ -383,7 +384,7 @@ func StoreMissingLfsObjectsInRepository(ctx context.Context, repo *models.Reposi var batch []lfs.Pointer for pointerBlob := range pointerChan { - meta, err := repo.GetLFSMetaObjectByOid(pointerBlob.Oid) + meta, err := models.GetLFSMetaObjectByOid(repo.ID, pointerBlob.Oid) if err != nil && err != models.ErrLFSObjectNotExist { log.Error("Error querying LFS meta object %v: %v", pointerBlob.Pointer, err) return err diff --git a/modules/templates/helper.go b/modules/templates/helper.go index eb0c7f7e7..f4529503d 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/avatars" + 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/emoji" @@ -581,7 +582,7 @@ func AvatarByAction(action *models.Action, others ...interface{}) template.HTML } // RepoAvatar renders repo avatars. args: repo, size(int), class (string) -func RepoAvatar(repo *models.Repository, others ...interface{}) template.HTML { +func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTML { size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar image", others...) src := repo.RelAvatarLink() @@ -953,7 +954,7 @@ type remoteAddress struct { Password string } -func mirrorRemoteAddress(m models.RemoteMirrorer) remoteAddress { +func mirrorRemoteAddress(m repo_model.RemoteMirrorer) remoteAddress { a := remoteAddress{} u, err := git.GetRemoteAddress(git.DefaultContext, m.GetRepository().RepoPath(), m.GetRemoteName()) diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index 548e454c8..1f893122f 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -14,6 +14,8 @@ import ( "testing" "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" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -54,7 +56,7 @@ func MockContext(t *testing.T, path string) *context.Context { // LoadRepo load a repo into a test context. func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) { ctx.Repo = &context.Repository{} - ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository) + ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}).(*repo_model.Repository) var err error ctx.Repo.Owner, err = user_model.GetUserByID(ctx.Repo.Repository.OwnerID) assert.NoError(t, err) @@ -85,7 +87,7 @@ func LoadUser(t *testing.T, ctx *context.Context, userID int64) { // LoadGitRepo load a git repo into a test context. Requires that ctx.Repo has // already been populated. func LoadGitRepo(t *testing.T, ctx *context.Context) { - assert.NoError(t, ctx.Repo.Repository.GetOwner()) + assert.NoError(t, ctx.Repo.Repository.GetOwner(db.DefaultContext)) var err error ctx.Repo.GitRepo, err = git.OpenRepository(ctx.Repo.Repository.RepoPath()) assert.NoError(t, err) diff --git a/routers/api/v1/admin/adopt.go b/routers/api/v1/admin/adopt.go index 85262bc83..1c0e237cd 100644 --- a/routers/api/v1/admin/adopt.go +++ b/routers/api/v1/admin/adopt.go @@ -8,6 +8,7 @@ import ( "net/http" "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/context" "code.gitea.io/gitea/modules/util" @@ -91,12 +92,12 @@ func AdoptRepository(ctx *context.APIContext) { } // check not a repo - has, err := models.IsRepositoryExist(ctxUser, repoName) + has, err := repo_model.IsRepositoryExist(ctxUser, repoName) if err != nil { ctx.InternalServerError(err) return } - isDir, err := util.IsDir(models.RepoPath(ctxUser.Name, repoName)) + isDir, err := util.IsDir(repo_model.RepoPath(ctxUser.Name, repoName)) if err != nil { ctx.InternalServerError(err) return @@ -153,12 +154,12 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) { } // check not a repo - has, err := models.IsRepositoryExist(ctxUser, repoName) + has, err := repo_model.IsRepositoryExist(ctxUser, repoName) if err != nil { ctx.InternalServerError(err) return } - isDir, err := util.IsDir(models.RepoPath(ctxUser.Name, repoName)) + isDir, err := util.IsDir(repo_model.RepoPath(ctxUser.Name, repoName)) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 867803f8d..1d7d4251d 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -71,6 +71,7 @@ import ( "strings" "code.gitea.io/gitea/models" + 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/context" @@ -157,9 +158,9 @@ func repoAssignment() func(ctx *context.APIContext) { ctx.Repo.Owner = owner // Get repository. - repo, err := models.GetRepositoryByName(owner.ID, repoName) + repo, err := repo_model.GetRepositoryByName(owner.ID, repoName) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName) if err == nil { context.RedirectToRepo(ctx.Context, redirectRepoID) diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index 371f1dc86..074d6fd00 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/perm" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -512,10 +513,10 @@ func GetTeamRepos(ctx *context.APIContext) { } // getRepositoryByParams get repository by a team's organization ID and repo name -func getRepositoryByParams(ctx *context.APIContext) *models.Repository { - repo, err := models.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame")) +func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository { + repo, err := repo_model.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame")) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound() } else { ctx.Error(http.StatusInternalServerError, "GetRepositoryByName", err) diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index e511152e5..56266b406 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -69,7 +69,7 @@ func GetBranch(ctx *context.APIContext) { return } - branchProtection, err := ctx.Repo.Repository.GetBranchProtection(branchName) + branchProtection, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branchName) if err != nil { ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) return @@ -210,7 +210,7 @@ func CreateBranch(ctx *context.APIContext) { return } - branchProtection, err := ctx.Repo.Repository.GetBranchProtection(branch.Name) + branchProtection, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branch.Name) if err != nil { ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) return @@ -270,7 +270,7 @@ func ListBranches(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetCommit", err) return } - branchProtection, err := ctx.Repo.Repository.GetBranchProtection(branches[i].Name) + branchProtection, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branches[i].Name) if err != nil { ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) return @@ -354,7 +354,7 @@ func ListBranchProtections(ctx *context.APIContext) { // "$ref": "#/responses/BranchProtectionList" repo := ctx.Repo.Repository - bps, err := repo.GetProtectedBranches() + bps, err := models.GetProtectedBranches(repo.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetProtectedBranches", err) return @@ -811,7 +811,7 @@ func DeleteBranchProtection(ctx *context.APIContext) { return } - if err := ctx.Repo.Repository.DeleteProtectedBranch(bp.ID); err != nil { + if err := models.DeleteProtectedBranch(ctx.Repo.Repository.ID, bp.ID); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteProtectedBranch", err) return } diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 80794fa44..d49b6357b 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -9,6 +9,7 @@ import ( "errors" "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/perm" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -48,13 +49,13 @@ func ListCollaborators(ctx *context.APIContext) { // "200": // "$ref": "#/responses/UserList" - count, err := ctx.Repo.Repository.CountCollaborators() + count, err := models.CountCollaborators(ctx.Repo.Repository.ID) if err != nil { ctx.InternalServerError(err) return } - collaborators, err := ctx.Repo.Repository.GetCollaborators(utils.GetListOptions(ctx)) + collaborators, err := models.GetCollaborators(ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "ListCollaborators", err) return @@ -109,7 +110,7 @@ func IsCollaborator(ctx *context.APIContext) { } return } - isColab, err := ctx.Repo.Repository.IsCollaborator(user.ID) + isColab, err := models.IsCollaborator(ctx.Repo.Repository.ID, user.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "IsCollaborator", err) return @@ -171,13 +172,13 @@ func AddCollaborator(ctx *context.APIContext) { return } - if err := ctx.Repo.Repository.AddCollaborator(collaborator); err != nil { + if err := models.AddCollaborator(ctx.Repo.Repository, collaborator); err != nil { ctx.Error(http.StatusInternalServerError, "AddCollaborator", err) return } if form.Permission != nil { - if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, perm.ParseAccessMode(*form.Permission)); err != nil { + if err := models.ChangeCollaborationAccessMode(ctx.Repo.Repository, collaborator.ID, perm.ParseAccessMode(*form.Permission)); err != nil { ctx.Error(http.StatusInternalServerError, "ChangeCollaborationAccessMode", err) return } @@ -225,7 +226,7 @@ func DeleteCollaborator(ctx *context.APIContext) { return } - if err := ctx.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil { + if err := models.DeleteCollaboration(ctx.Repo.Repository, collaborator.ID); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteCollaboration", err) return } @@ -254,7 +255,7 @@ func GetReviewers(ctx *context.APIContext) { // "200": // "$ref": "#/responses/UserList" - reviewers, err := ctx.Repo.Repository.GetReviewers(ctx.User.ID, 0) + reviewers, err := models.GetReviewers(ctx.Repo.Repository, ctx.User.ID, 0) if err != nil { ctx.Error(http.StatusInternalServerError, "ListCollaborators", err) return @@ -284,7 +285,7 @@ func GetAssignees(ctx *context.APIContext) { // "200": // "$ref": "#/responses/UserList" - assignees, err := ctx.Repo.Repository.GetAssignees() + assignees, err := models.GetRepoAssignees(ctx.Repo.Repository) if err != nil { ctx.Error(http.StatusInternalServerError, "ListCollaborators", err) return diff --git a/routers/api/v1/repo/commits.go b/routers/api/v1/repo/commits.go index 9907054b8..117fef08d 100644 --- a/routers/api/v1/repo/commits.go +++ b/routers/api/v1/repo/commits.go @@ -11,7 +11,7 @@ import ( "net/http" "strconv" - "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/context" "code.gitea.io/gitea/modules/convert" @@ -249,7 +249,7 @@ func DownloadCommitDiffOrPatch(ctx *context.APIContext) { // "$ref": "#/responses/string" // "404": // "$ref": "#/responses/notFound" - repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) + repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) if err := git.GetRawDiff( repoPath, ctx.Params(":sha"), diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index e84f652ed..98decfcb6 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -12,6 +12,7 @@ import ( "time" "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" @@ -119,7 +120,7 @@ func GetArchive(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) + repoPath := repo_model.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) if ctx.Repo.GitRepo == nil { gitRepo, err := git.OpenRepository(repoPath) if err != nil { diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index 33321e6a0..aa51019eb 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -50,7 +50,7 @@ func ListForks(ctx *context.APIContext) { // "200": // "$ref": "#/responses/RepositoryList" - forks, err := ctx.Repo.Repository.GetForks(utils.GetListOptions(ctx)) + forks, err := models.GetForks(ctx.Repo.Repository, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetForks", err) return diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index ad94da5b2..03ebcb8f7 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -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/modules/context" "code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/setting" @@ -21,12 +22,12 @@ import ( ) // appendPrivateInformation appends the owner and key type information to api.PublicKey -func appendPrivateInformation(apiKey *api.DeployKey, key *models.DeployKey, repository *models.Repository) (*api.DeployKey, error) { +func appendPrivateInformation(apiKey *api.DeployKey, key *models.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) { apiKey.ReadOnly = key.Mode == perm.AccessModeRead if repository.ID == key.RepoID { apiKey.Repository = convert.ToRepo(repository, key.Mode) } else { - repo, err := models.GetRepositoryByID(key.RepoID) + repo, err := repo_model.GetRepositoryByID(key.RepoID) if err != nil { return apiKey, err } diff --git a/routers/api/v1/repo/language.go b/routers/api/v1/repo/language.go index c45911ee6..427a8fd6b 100644 --- a/routers/api/v1/repo/language.go +++ b/routers/api/v1/repo/language.go @@ -9,12 +9,12 @@ import ( "net/http" "strconv" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" ) -type languageResponse []*models.LanguageStat +type languageResponse []*repo_model.LanguageStat func (l languageResponse) MarshalJSON() ([]byte, error) { var buf bytes.Buffer @@ -68,7 +68,7 @@ func GetLanguages(ctx *context.APIContext) { // "200": // "$ref": "#/responses/LanguageStatistics" - langs, err := ctx.Repo.Repository.GetLanguageStats() + langs, err := repo_model.GetLanguageStats(ctx.Repo.Repository) if err != nil { log.Error("GetLanguageStats failed: %v", err) ctx.InternalServerError(err) diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go index dba44efb2..108d78ef2 100644 --- a/routers/api/v1/repo/migrate.go +++ b/routers/api/v1/repo/migrate.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/models" "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" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -173,7 +174,7 @@ func Migrate(ctx *context.APIContext) { GitServiceType: gitServiceType, IsPrivate: opts.Private, IsMirror: opts.Mirror, - Status: models.RepositoryBeingMigrated, + Status: repo_model.RepositoryBeingMigrated, }) if err != nil { handleMigrateError(ctx, repoOwner, remoteAddr, err) diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index dd415a34a..3e37da24e 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -14,6 +14,7 @@ import ( "time" "code.gitea.io/gitea/models" + 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/context" @@ -763,10 +764,10 @@ func MergePullRequest(ctx *context.APIContext) { } // handle manually-merged mark - if models.MergeStyle(form.Do) == models.MergeStyleManuallyMerged { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged { if err = pull_service.MergedManually(pr, ctx.User, ctx.Repo.GitRepo, form.MergeCommitID); err != nil { if models.IsErrInvalidMergeStyle(err) { - ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", models.MergeStyle(form.Do))) + ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do))) return } if strings.Contains(err.Error(), "Wrong commit ID") { @@ -818,15 +819,15 @@ func MergePullRequest(ctx *context.APIContext) { } if len(form.Do) == 0 { - form.Do = string(models.MergeStyleMerge) + form.Do = string(repo_model.MergeStyleMerge) } message := strings.TrimSpace(form.MergeTitleField) if len(message) == 0 { - if models.MergeStyle(form.Do) == models.MergeStyleMerge { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleMerge { message = pr.GetDefaultMergeMessage() } - if models.MergeStyle(form.Do) == models.MergeStyleSquash { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleSquash { message = pr.GetDefaultSquashMessage() } } @@ -836,9 +837,9 @@ func MergePullRequest(ctx *context.APIContext) { message += "\n\n" + form.MergeMessageField } - if err := pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil { + if err := pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), message); err != nil { if models.IsErrInvalidMergeStyle(err) { - ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", models.MergeStyle(form.Do))) + ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do))) return } else if models.IsErrMergeConflicts(err) { conflictError := err.(models.ErrMergeConflicts) @@ -901,7 +902,7 @@ func MergePullRequest(ctx *context.APIContext) { ctx.Status(http.StatusOK) } -func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*user_model.User, *models.Repository, *git.Repository, *git.CompareInfo, string, string) { +func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*user_model.User, *repo_model.Repository, *git.Repository, *git.CompareInfo, string, string) { baseRepo := ctx.Repo.Repository // Get compared branches information @@ -966,7 +967,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) headRepo = ctx.Repo.Repository headGitRepo = ctx.Repo.GitRepo } else { - headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name)) + headGitRepo, err = git.OpenRepository(repo_model.RepoPath(headUser.Name, headRepo.Name)) if err != nil { ctx.Error(http.StatusInternalServerError, "OpenRepository", err) return nil, nil, nil, nil, "", "" @@ -1018,7 +1019,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) return nil, nil, nil, nil, "", "" } - compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch, true, false) + compareInfo, err := headGitRepo.GetCompareInfo(repo_model.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch, true, false) if err != nil { headGitRepo.Close() ctx.Error(http.StatusInternalServerError, "GetCompareInfo", err) diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 2f37e1098..4486e33fe 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -216,7 +217,7 @@ func Search(ctx *context.APIContext) { results := make([]*api.Repository, len(repos)) for i, repo := range repos { - if err = repo.GetOwner(); err != nil { + if err = repo.GetOwner(db.DefaultContext); err != nil { ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, Error: err.Error(), @@ -256,7 +257,7 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre IsPrivate: opt.Private, AutoInit: opt.AutoInit, DefaultBranch: opt.DefaultBranch, - TrustModel: models.ToTrustModel(opt.TrustModel), + TrustModel: repo_model.ToTrustModel(opt.TrustModel), IsTemplate: opt.Template, }) if err != nil { @@ -272,7 +273,7 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre } // reload repo from db to get a real state after creation - repo, err = models.GetRepositoryByID(repo.ID) + repo, err = repo_model.GetRepositoryByID(repo.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err) } @@ -553,9 +554,9 @@ func GetByID(ctx *context.APIContext) { // "200": // "$ref": "#/responses/Repository" - repo, err := models.GetRepositoryByID(ctx.ParamsInt64(":id")) + repo, err := repo_model.GetRepositoryByID(ctx.ParamsInt64(":id")) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound() } else { ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err) @@ -628,7 +629,7 @@ func Edit(ctx *context.APIContext) { } } - repo, err := models.GetRepositoryByID(ctx.Repo.Repository.ID) + repo, err := repo_model.GetRepositoryByID(ctx.Repo.Repository.ID) if err != nil { ctx.InternalServerError(err) return @@ -738,7 +739,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { owner := ctx.Repo.Owner repo := ctx.Repo.Repository - var units []models.RepoUnit + var units []repo_model.RepoUnit var deleteUnitTypes []unit_model.Type if opts.HasIssues != nil { @@ -755,10 +756,10 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { return err } - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeExternalTracker, - Config: &models.ExternalTrackerConfig{ + Config: &repo_model.ExternalTrackerConfig{ ExternalTrackerURL: opts.ExternalTracker.ExternalTrackerURL, ExternalTrackerFormat: opts.ExternalTracker.ExternalTrackerFormat, ExternalTrackerStyle: opts.ExternalTracker.ExternalTrackerStyle, @@ -767,17 +768,17 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { deleteUnitTypes = append(deleteUnitTypes, unit_model.TypeIssues) } else if *opts.HasIssues && opts.ExternalTracker == nil && !unit_model.TypeIssues.UnitGlobalDisabled() { // Default to built-in tracker - var config *models.IssuesConfig + var config *repo_model.IssuesConfig if opts.InternalTracker != nil { - config = &models.IssuesConfig{ + config = &repo_model.IssuesConfig{ EnableTimetracker: opts.InternalTracker.EnableTimeTracker, AllowOnlyContributorsToTrackTime: opts.InternalTracker.AllowOnlyContributorsToTrackTime, EnableDependencies: opts.InternalTracker.EnableIssueDependencies, } } else if unit, err := repo.GetUnit(unit_model.TypeIssues); err != nil { // Unit type doesn't exist so we make a new config file with default values - config = &models.IssuesConfig{ + config = &repo_model.IssuesConfig{ EnableTimetracker: true, AllowOnlyContributorsToTrackTime: true, EnableDependencies: true, @@ -786,7 +787,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { config = unit.IssuesConfig() } - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeIssues, Config: config, @@ -811,17 +812,17 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { return err } - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeExternalWiki, - Config: &models.ExternalWikiConfig{ + Config: &repo_model.ExternalWikiConfig{ ExternalWikiURL: opts.ExternalWiki.ExternalWikiURL, }, }) deleteUnitTypes = append(deleteUnitTypes, unit_model.TypeWiki) } else if *opts.HasWiki && opts.ExternalWiki == nil && !unit_model.TypeWiki.UnitGlobalDisabled() { - config := &models.UnitConfig{} - units = append(units, models.RepoUnit{ + config := &repo_model.UnitConfig{} + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeWiki, Config: config, @@ -843,10 +844,10 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { // we get the config settings and then set them // if those settings were provided in the opts. unit, err := repo.GetUnit(unit_model.TypePullRequests) - var config *models.PullRequestsConfig + var config *repo_model.PullRequestsConfig if err != nil { // Unit type doesn't exist so we make a new config file with default values - config = &models.PullRequestsConfig{ + config = &repo_model.PullRequestsConfig{ IgnoreWhitespaceConflicts: false, AllowMerge: true, AllowRebase: true, @@ -855,7 +856,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { AllowManualMerge: true, AutodetectManualMerge: false, DefaultDeleteBranchAfterMerge: false, - DefaultMergeStyle: models.MergeStyleMerge, + DefaultMergeStyle: repo_model.MergeStyleMerge, } } else { config = unit.PullRequestsConfig() @@ -886,10 +887,10 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { config.DefaultDeleteBranchAfterMerge = *opts.DefaultDeleteBranchAfterMerge } if opts.DefaultMergeStyle != nil { - config.DefaultMergeStyle = models.MergeStyle(*opts.DefaultMergeStyle) + config.DefaultMergeStyle = repo_model.MergeStyle(*opts.DefaultMergeStyle) } - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypePullRequests, Config: config, @@ -901,7 +902,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { if opts.HasProjects != nil && !unit_model.TypeProjects.UnitGlobalDisabled() { if *opts.HasProjects { - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeProjects, }) @@ -930,14 +931,14 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e return err } if *opts.Archived { - if err := repo.SetArchiveRepoState(*opts.Archived); err != nil { + if err := models.SetArchiveRepoState(repo, *opts.Archived); err != nil { log.Error("Tried to archive a repo: %s", err) ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) return err } log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name) } else { - if err := repo.SetArchiveRepoState(*opts.Archived); err != nil { + if err := models.SetArchiveRepoState(repo, *opts.Archived); err != nil { log.Error("Tried to un-archive a repo: %s", err) ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) return err @@ -958,14 +959,16 @@ func updateMirrorInterval(ctx *context.APIContext, opts api.EditRepoOption) erro ctx.Error(http.StatusUnprocessableEntity, err.Error(), err) return err } - if err := repo.GetMirror(); err != nil { + mirror, err := repo_model.GetMirrorByRepoID(repo.ID) + if err != nil { log.Error("Failed to get mirror: %s", err) ctx.Error(http.StatusInternalServerError, "MirrorInterval", err) return err } if interval, err := time.ParseDuration(*opts.MirrorInterval); err == nil { - repo.Mirror.Interval = interval - if err := models.UpdateMirror(repo.Mirror); err != nil { + mirror.Interval = interval + mirror.Repo = repo + if err := repo_model.UpdateMirror(mirror); err != nil { log.Error("Failed to Set Mirror Interval: %s", err) ctx.Error(http.StatusUnprocessableEntity, "MirrorInterval", err) return err @@ -1007,7 +1010,7 @@ func Delete(ctx *context.APIContext) { owner := ctx.Repo.Owner repo := ctx.Repo.Repository - canDelete, err := repo.CanUserDelete(ctx.User) + canDelete, err := models.CanUserDelete(repo, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "CanUserDelete", err) return diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go index 4d4093582..17b49f7f5 100644 --- a/routers/api/v1/repo/repo_test.go +++ b/routers/api/v1/repo/repo_test.go @@ -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" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -60,7 +60,7 @@ func TestRepoEdit(t *testing.T) { Edit(apiCtx) assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) - unittest.AssertExistsAndLoadBean(t, &models.Repository{ + unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ ID: 1, }, unittest.Cond("name = ? AND is_archived = 1", *opts.Name)) } @@ -82,7 +82,7 @@ func TestRepoEditNameChange(t *testing.T) { Edit(apiCtx) assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) - unittest.AssertExistsAndLoadBean(t, &models.Repository{ + unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ ID: 1, }, unittest.Cond("name = ?", opts.Name)) } diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index dae92969b..64a0fc1d5 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -7,6 +7,7 @@ package repo import ( "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -43,7 +44,7 @@ func ListSubscribers(ctx *context.APIContext) { // "200": // "$ref": "#/responses/UserList" - subscribers, err := ctx.Repo.Repository.GetWatchers(utils.GetListOptions(ctx)) + subscribers, err := models.GetRepoWatchers(ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetWatchers", err) return diff --git a/routers/api/v1/repo/teams.go b/routers/api/v1/repo/teams.go index 1348205ec..024224b5a 100644 --- a/routers/api/v1/repo/teams.go +++ b/routers/api/v1/repo/teams.go @@ -41,7 +41,7 @@ func ListTeams(ctx *context.APIContext) { return } - teams, err := ctx.Repo.Repository.GetRepoTeams() + teams, err := models.GetRepoTeams(ctx.Repo.Repository) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/repo/transfer.go b/routers/api/v1/repo/transfer.go index 0a698383e..e2a83c70e 100644 --- a/routers/api/v1/repo/transfer.go +++ b/routers/api/v1/repo/transfer.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/perm" + repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -112,7 +113,7 @@ func Transfer(ctx *context.APIContext) { return } - if ctx.Repo.Repository.Status == models.RepositoryPendingTransfer { + if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer { log.Trace("Repository transfer initiated: %s -> %s", ctx.Repo.Repository.FullName(), newOwner.Name) ctx.JSON(http.StatusCreated, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) return diff --git a/routers/api/v1/user/repo.go b/routers/api/v1/user/repo.go index 760032460..3d5c84185 100644 --- a/routers/api/v1/user/repo.go +++ b/routers/api/v1/user/repo.go @@ -8,6 +8,7 @@ import ( "net/http" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -118,7 +119,7 @@ func ListMyRepos(ctx *context.APIContext) { results := make([]*api.Repository, len(repos)) for i, repo := range repos { - if err = repo.GetOwner(); err != nil { + if err = repo.GetOwner(db.DefaultContext); err != nil { ctx.Error(http.StatusInternalServerError, "GetOwner", err) return } diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index 54d5e74bc..5c7a4d8d8 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -9,6 +9,7 @@ import ( "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" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -201,6 +202,6 @@ func Unwatch(ctx *context.APIContext) { } // subscriptionURL returns the URL of the subscription API endpoint of a repo -func subscriptionURL(repo *models.Repository) string { +func subscriptionURL(repo *repo_model.Repository) string { return repo.APIURL() + "/subscription" } diff --git a/routers/private/default_branch.go b/routers/private/default_branch.go index ec6adc480..974534c21 100644 --- a/routers/private/default_branch.go +++ b/routers/private/default_branch.go @@ -9,7 +9,7 @@ import ( "fmt" "net/http" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -34,7 +34,7 @@ func SetDefaultBranch(ctx *gitea_context.PrivateContext) { ownerName := ctx.Params(":owner") repoName := ctx.Params(":repo") branch := ctx.Params(":branch") - repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) if err != nil { log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err) ctx.JSON(http.StatusInternalServerError, private.Response{ @@ -65,7 +65,7 @@ func SetDefaultBranch(ctx *gitea_context.PrivateContext) { } gitRepo.Close() - if err := repo.UpdateDefaultBranch(); err != nil { + if err := repo_model.UpdateDefaultBranch(repo); err != nil { ctx.JSON(http.StatusInternalServerError, private.Response{ Err: fmt.Sprintf("Unable to set default branch on repository: %s/%s Error: %v", ownerName, repoName, err), }) diff --git a/routers/private/hook_post_receive.go b/routers/private/hook_post_receive.go index 0d559250e..a71f46591 100644 --- a/routers/private/hook_post_receive.go +++ b/routers/private/hook_post_receive.go @@ -11,6 +11,7 @@ import ( "strings" "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -35,7 +36,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) { repoName := ctx.Params(":repo") // defer getting the repository at this point - as we should only retrieve it if we're going to call update - var repo *models.Repository + var repo *repo_model.Repository updates := make([]*repo_module.PushUpdateOptions, 0, len(opts.OldCommitIDs)) wasEmpty := false @@ -116,7 +117,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) { // We have to reload the repo in case its state is changed above repo = nil - var baseRepo *models.Repository + var baseRepo *repo_model.Repository // Now handle the pull request notification trailers for i := range opts.OldCommitIDs { diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go index 5ab21d525..17ccf010a 100644 --- a/routers/private/hook_pre_receive.go +++ b/routers/private/hook_pre_receive.go @@ -363,7 +363,7 @@ func preReceiveTag(ctx *preReceiveContext, oldCommitID, newCommitID, refFullName if !ctx.gotProtectedTags { var err error - ctx.protectedTags, err = ctx.Repo.Repository.GetProtectedTags() + ctx.protectedTags, err = models.GetProtectedTags(ctx.Repo.Repository.ID) if err != nil { log.Error("Unable to get protected tags for %-v Error: %v", ctx.Repo.Repository, err) ctx.JSON(http.StatusInternalServerError, private.Response{ diff --git a/routers/private/internal_repo.go b/routers/private/internal_repo.go index 60daa1dbe..8d0fd7223 100644 --- a/routers/private/internal_repo.go +++ b/routers/private/internal_repo.go @@ -10,7 +10,7 @@ import ( "fmt" "net/http" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -68,8 +68,8 @@ func RepoAssignment(ctx *gitea_context.PrivateContext) context.CancelFunc { return cancel } -func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *models.Repository { - repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName) +func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *repo_model.Repository { + repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) if err != nil { log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err) ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ diff --git a/routers/private/serv.go b/routers/private/serv.go index 9cbd0c2c8..f28d5a745 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -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/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -126,9 +127,9 @@ func ServCommand(ctx *context.PrivateContext) { // Now get the Repository and set the results section repoExist := true - repo, err := models.GetRepositoryByName(owner.ID, results.RepoName) + repo, err := repo_model.GetRepositoryByName(owner.ID, results.RepoName) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { repoExist = false for _, verb := range ctx.FormStrings("verb") { if "git-upload-pack" == verb { @@ -374,7 +375,7 @@ func ServCommand(ctx *context.PrivateContext) { if results.IsWiki { // Ensure the wiki is enabled before we allow access to it if _, err := repo.GetUnit(unit.TypeWiki); err != nil { - if models.IsErrUnitTypeNotExist(err) { + if repo_model.IsErrUnitTypeNotExist(err) { ctx.JSON(http.StatusForbidden, private.ErrServCommand{ Results: results, Err: "repository wiki is disabled", diff --git a/routers/web/admin/repos.go b/routers/web/admin/repos.go index 69e522ef7..7db8b4d33 100644 --- a/routers/web/admin/repos.go +++ b/routers/web/admin/repos.go @@ -11,6 +11,7 @@ import ( "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" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -41,7 +42,7 @@ func Repos(ctx *context.Context) { // DeleteRepo delete one repository func DeleteRepo(ctx *context.Context) { - repo, err := models.GetRepositoryByID(ctx.FormInt64("id")) + repo, err := repo_model.GetRepositoryByID(ctx.FormInt64("id")) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -134,12 +135,12 @@ func AdoptOrDeleteRepository(ctx *context.Context) { repoName := dirSplit[1] // check not a repo - has, err := models.IsRepositoryExist(ctxUser, repoName) + has, err := repo_model.IsRepositoryExist(ctxUser, repoName) if err != nil { ctx.ServerError("IsRepositoryExist", err) return } - isDir, err := util.IsDir(models.RepoPath(ctxUser.Name, repoName)) + isDir, err := util.IsDir(repo_model.RepoPath(ctxUser.Name, repoName)) if err != nil { ctx.ServerError("IsDir", err) return diff --git a/routers/web/explore/code.go b/routers/web/explore/code.go index 6ff48be0f..b61f25a96 100644 --- a/routers/web/explore/code.go +++ b/routers/web/explore/code.go @@ -8,6 +8,7 @@ import ( "net/http" "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -69,16 +70,16 @@ func Code(ctx *context.Context) { // if non-admin login user, we need check UnitTypeCode at first if ctx.User != nil && len(repoIDs) > 0 { - repoMaps, err := models.GetRepositoriesMapByIDs(repoIDs) + repoMaps, err := repo_model.GetRepositoriesMapByIDs(repoIDs) if err != nil { ctx.ServerError("SearchResults", err) return } - var rightRepoMap = make(map[int64]*models.Repository, len(repoMaps)) + var rightRepoMap = make(map[int64]*repo_model.Repository, len(repoMaps)) repoIDs = make([]int64, 0, len(repoMaps)) for id, repo := range repoMaps { - if repo.CheckUnitUser(ctx.User, unit.TypeCode) { + if models.CheckRepoUnitUser(repo, ctx.User, unit.TypeCode) { rightRepoMap[id] = repo repoIDs = append(repoIDs, id) } @@ -113,7 +114,7 @@ func Code(ctx *context.Context) { } } - repoMaps, err := models.GetRepositoriesMapByIDs(loadRepoIDs) + repoMaps, err := repo_model.GetRepositoriesMapByIDs(loadRepoIDs) if err != nil { ctx.ServerError("SearchResults", err) return diff --git a/routers/web/explore/repo.go b/routers/web/explore/repo.go index a81386b5f..0a78e9e29 100644 --- a/routers/web/explore/repo.go +++ b/routers/web/explore/repo.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" @@ -36,7 +37,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) { } var ( - repos []*models.Repository + repos []*repo_model.Repository count int64 err error orderBy db.SearchOrderBy diff --git a/routers/web/goget.go b/routers/web/goget.go index 8a8e1797d..6898f0f43 100644 --- a/routers/web/goget.go +++ b/routers/web/goget.go @@ -10,7 +10,7 @@ import ( "path" "strings" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -53,7 +53,7 @@ func goGet(ctx *context.Context) { } branchName := setting.Repository.DefaultBranch - repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) if err == nil && len(repo.DefaultBranch) > 0 { branchName = repo.DefaultBranch } @@ -79,7 +79,7 @@ func goGet(ctx *context.Context) { `, map[string]string{ "GoGetImport": context.ComposeGoGetImport(ownerName, trimmedRepoName), - "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName), + "CloneLink": repo_model.ComposeHTTPSCloneURL(ownerName, repoName), "GoDocDirectory": prefix + "{/dir}", "GoDocFile": prefix + "{/dir}/{file}#L{line}", "Insecure": insecure, diff --git a/routers/web/org/home.go b/routers/web/org/home.go index 52f0282b5..3a4204428 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/markup" @@ -87,7 +88,7 @@ func Home(ctx *context.Context) { } var ( - repos []*models.Repository + repos []*repo_model.Repository count int64 err error ) diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index 8d39f2697..40fba5cd0 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/perm" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" @@ -178,10 +179,10 @@ func TeamsRepoAction(ctx *context.Context) { switch action { case "add": repoName := path.Base(ctx.FormString("repo_name")) - var repo *models.Repository - repo, err = models.GetRepositoryByName(ctx.Org.Organization.ID, repoName) + var repo *repo_model.Repository + repo, err = repo_model.GetRepositoryByName(ctx.Org.Organization.ID, repoName) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo")) ctx.Redirect(ctx.Org.OrgLink + "/teams/" + url.PathEscape(ctx.Org.Team.LowerName) + "/repositories") return diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index 5786aa1eb..75246c3ac 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -11,7 +11,7 @@ import ( "net/url" "strings" - "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" "code.gitea.io/gitea/modules/context" @@ -103,7 +103,7 @@ func RefBlame(ctx *context.Context) { return } - blameReader, err := git.CreateBlameReader(ctx, models.RepoPath(userName, repoName), commitID, fileName) + blameReader, err := git.CreateBlameReader(ctx, repo_model.RepoPath(userName, repoName), commitID, fileName) if err != nil { ctx.NotFound("CreateBlameReader", err) return diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index 9c2518059..f6a475c3c 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -12,6 +12,7 @@ import ( "strings" "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -117,7 +118,7 @@ func RestoreBranchPost(ctx *context.Context) { branchID := ctx.FormInt64("branch_id") branchName := ctx.FormString("name") - deletedBranch, err := ctx.Repo.Repository.GetDeletedBranchByID(branchID) + deletedBranch, err := models.GetDeletedBranchByID(ctx.Repo.Repository.ID, branchID) if err != nil { log.Error("GetDeletedBranchByID: %v", err) ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName)) @@ -179,13 +180,13 @@ func loadBranches(ctx *context.Context, skip, limit int) ([]*Branch, int) { return nil, 0 } - protectedBranches, err := ctx.Repo.Repository.GetProtectedBranches() + protectedBranches, err := models.GetProtectedBranches(ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("GetProtectedBranches", err) return nil, 0 } - repoIDToRepo := map[int64]*models.Repository{} + repoIDToRepo := map[int64]*repo_model.Repository{} repoIDToRepo[ctx.Repo.Repository.ID] = ctx.Repo.Repository repoIDToGitRepo := map[int64]*git.Repository{} @@ -223,7 +224,7 @@ func loadBranches(ctx *context.Context, skip, limit int) ([]*Branch, int) { } func loadOneBranch(ctx *context.Context, rawBranch *git.Branch, protectedBranches []*models.ProtectedBranch, - repoIDToRepo map[int64]*models.Repository, + repoIDToRepo map[int64]*repo_model.Repository, repoIDToGitRepo map[int64]*git.Repository) *Branch { log.Trace("loadOneBranch: '%s'", rawBranch.Name) @@ -311,7 +312,7 @@ func loadOneBranch(ctx *context.Context, rawBranch *git.Branch, protectedBranche func getDeletedBranches(ctx *context.Context) ([]*Branch, error) { branches := []*Branch{} - deletedBranches, err := ctx.Repo.Repository.GetDeletedBranches() + deletedBranches, err := models.GetDeletedBranches(ctx.Repo.Repository.ID) if err != nil { return branches, err } diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index 993fc1c33..ef21017a3 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -12,6 +12,7 @@ import ( "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" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/charset" @@ -382,7 +383,7 @@ func RawDiff(ctx *context.Context) { if ctx.Data["PageIsWiki"] != nil { repoPath = ctx.Repo.Repository.WikiPath() } else { - repoPath = models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) + repoPath = repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) } if err := git.GetRawDiff( repoPath, diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index 4cd817a39..21311ba97 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -17,6 +17,8 @@ import ( "strings" "code.gitea.io/gitea/models" + "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/base" @@ -165,7 +167,7 @@ func setCsvCompareContext(ctx *context.Context) { // CompareInfo represents the collected results from ParseCompareInfo type CompareInfo struct { HeadUser *user_model.User - HeadRepo *models.Repository + HeadRepo *repo_model.Repository HeadGitRepo *git.Repository CompareInfo *git.CompareInfo BaseBranch string @@ -259,16 +261,16 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { ci.HeadRepo = baseRepo } } else { - ci.HeadRepo, err = models.GetRepositoryByOwnerAndName(headInfosSplit[0], headInfosSplit[1]) + ci.HeadRepo, err = repo_model.GetRepositoryByOwnerAndName(headInfosSplit[0], headInfosSplit[1]) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByOwnerAndName", nil) } else { ctx.ServerError("GetRepositoryByOwnerAndName", err) } return nil } - if err := ci.HeadRepo.GetOwner(); err != nil { + if err := ci.HeadRepo.GetOwner(db.DefaultContext); err != nil { if user_model.IsErrUserNotExist(err) { ctx.NotFound("GetUserByName", nil) } else { @@ -320,11 +322,11 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { // 1. First if the baseRepo is a fork get the "RootRepo" it was // forked from - var rootRepo *models.Repository + var rootRepo *repo_model.Repository if baseRepo.IsFork { err = baseRepo.GetBaseRepo() if err != nil { - if !models.IsErrRepoNotExist(err) { + if !repo_model.IsErrRepoNotExist(err) { ctx.ServerError("Unable to find root repo", err) return nil } @@ -336,7 +338,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { // 2. Now if the current user is not the owner of the baseRepo, // check if they have a fork of the base repo and offer that as // "OwnForkRepo" - var ownForkRepo *models.Repository + var ownForkRepo *repo_model.Repository if ctx.User != nil && baseRepo.OwnerID != ctx.User.ID { repo := models.GetForkedRepo(ctx.User.ID, baseRepo.ID) if repo != nil { @@ -438,7 +440,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { if rootRepo != nil && rootRepo.ID != ci.HeadRepo.ID && rootRepo.ID != baseRepo.ID { - canRead := rootRepo.CheckUnitUser(ctx.User, unit.TypeCode) + canRead := models.CheckRepoUnitUser(rootRepo, ctx.User, unit.TypeCode) if canRead { ctx.Data["RootRepo"] = rootRepo if !fileOnly { @@ -463,7 +465,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { ownForkRepo.ID != ci.HeadRepo.ID && ownForkRepo.ID != baseRepo.ID && (rootRepo == nil || ownForkRepo.ID != rootRepo.ID) { - canRead := ownForkRepo.CheckUnitUser(ctx.User, unit.TypeCode) + canRead := models.CheckRepoUnitUser(ownForkRepo, ctx.User, unit.TypeCode) if canRead { ctx.Data["OwnForkRepo"] = ownForkRepo if !fileOnly { @@ -653,7 +655,7 @@ func PrepareCompareDiff( return false } -func getBranchesAndTagsForRepo(repo *models.Repository) (branches, tags []string, err error) { +func getBranchesAndTagsForRepo(repo *repo_model.Repository) (branches, tags []string, err error) { gitRepo, err := git.OpenRepository(repo.RepoPath()) if err != nil { return nil, nil, err diff --git a/routers/web/repo/download.go b/routers/web/repo/download.go index 2307f736a..430de24c6 100644 --- a/routers/web/repo/download.go +++ b/routers/web/repo/download.go @@ -6,6 +6,7 @@ package repo import ( + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/httpcache" @@ -38,7 +39,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob) error { pointer, _ := lfs.ReadPointer(dataRc) if pointer.IsValid() { - meta, _ := ctx.Repo.Repository.GetLFSMetaObjectByOid(pointer.Oid) + meta, _ := models.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) if meta == nil { if err = dataRc.Close(); err != nil { log.Error("ServeBlobOrLFS: Close: %v", err) diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index 3aa8e84f5..3e12cd326 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -20,8 +20,10 @@ import ( "time" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/login" "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/context" @@ -129,9 +131,9 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { } repoExist := true - repo, err := models.GetRepositoryByName(owner.ID, reponame) + repo, err := repo_model.GetRepositoryByName(owner.ID, reponame) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { if redirectRepoID, err := models.LookupRepoRedirect(owner.ID, reponame); err == nil { context.RedirectToRepo(ctx, redirectRepoID) return @@ -158,7 +160,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { // don't allow anonymous pulls if organization is not public if isPublicPull { - if err := repo.GetOwner(); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("GetOwner", err) return } @@ -273,7 +275,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { if isWiki { // Ensure the wiki is enabled before we allow access to it if _, err := repo.GetUnit(unit.TypeWiki); err != nil { - if models.IsErrUnitTypeNotExist(err) { + if repo_model.IsErrUnitTypeNotExist(err) { ctx.HandleText(http.StatusForbidden, "repository wiki is disabled") return } @@ -295,9 +297,9 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name - dir := models.RepoPath(username, reponame) + dir := repo_model.RepoPath(username, reponame) if isWiki { - dir = models.RepoPath(username, wikiRepoName) + dir = repo_model.RepoPath(username, wikiRepoName) } return &serviceHandler{cfg, w, r, dir, cfg.Env} diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 398aa26cc..df977d2c1 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -272,7 +272,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti ctx.Data["CommitStatus"] = commitStatus // Get assignees. - ctx.Data["Assignees"], err = repo.GetAssignees() + ctx.Data["Assignees"], err = models.GetRepoAssignees(repo) if err != nil { ctx.ServerError("GetAssignees", err) return @@ -412,7 +412,7 @@ func Issues(ctx *context.Context) { } // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository -func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) { +func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.Repository) { var err error ctx.Data["OpenMilestones"], _, err = models.GetMilestones(models.GetMilestonesOption{ RepoID: repo.ID, @@ -431,7 +431,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repos return } - ctx.Data["Assignees"], err = repo.GetAssignees() + ctx.Data["Assignees"], err = models.GetRepoAssignees(repo) if err != nil { ctx.ServerError("GetAssignees", err) return @@ -440,7 +440,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repos handleTeamMentions(ctx) } -func retrieveProjects(ctx *context.Context, repo *models.Repository) { +func retrieveProjects(ctx *context.Context, repo *repo_model.Repository) { var err error @@ -479,7 +479,7 @@ type repoReviewerSelection struct { } // RetrieveRepoReviewers find all reviewers of a repository -func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issue *models.Issue, canChooseReviewer bool) { +func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, issue *models.Issue, canChooseReviewer bool) { ctx.Data["CanChooseReviewer"] = canChooseReviewer originalAuthorReviews, err := models.GetReviewersFromOriginalAuthorsByIssueID(issue.ID) @@ -513,13 +513,13 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issue posterID = 0 } - reviewers, err = repo.GetReviewers(ctx.User.ID, posterID) + reviewers, err = models.GetReviewers(repo, ctx.User.ID, posterID) if err != nil { ctx.ServerError("GetReviewers", err) return } - teamReviewers, err = repo.GetReviewerTeams() + teamReviewers, err = models.GetReviewerTeams(repo) if err != nil { ctx.ServerError("GetReviewerTeams", err) return @@ -659,7 +659,7 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issue } // RetrieveRepoMetas find all the meta information of a repository -func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository, isPull bool) []*models.Label { +func RetrieveRepoMetas(ctx *context.Context, repo *repo_model.Repository, isPull bool) []*models.Label { if !ctx.Repo.CanWriteIssuesOrPulls(isPull) { return nil } @@ -887,11 +887,16 @@ func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull // Check milestone. milestoneID := form.MilestoneID if milestoneID > 0 { - ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID) + milestone, err := models.GetMilestoneByID(milestoneID) if err != nil { ctx.ServerError("GetMilestoneByID", err) return nil, nil, 0, 0 } + if milestone.RepoID != repo.ID { + ctx.ServerError("GetMilestoneByID", err) + return nil, nil, 0, 0 + } + ctx.Data["Milestone"] = milestone ctx.Data["milestone_id"] = milestoneID } @@ -1019,7 +1024,7 @@ func NewIssuePost(ctx *context.Context) { } // roleDescriptor returns the Role Decriptor for a comment in/with the given repo, poster and issue -func roleDescriptor(repo *models.Repository, poster *user_model.User, issue *models.Issue) (models.RoleDescriptor, error) { +func roleDescriptor(repo *repo_model.Repository, poster *user_model.User, issue *models.Issue) (models.RoleDescriptor, error) { perm, err := models.GetUserRepoPermission(repo, poster) if err != nil { return models.RoleDescriptorNone, err @@ -1085,7 +1090,7 @@ func ViewIssue(ctx *context.Context) { ctx.Redirect(com.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas)) return } - } else if err != nil && !models.IsErrUnitTypeNotExist(err) { + } else if err != nil && !repo_model.IsErrUnitTypeNotExist(err) { ctx.ServerError("GetUnit", err) return } @@ -1498,7 +1503,7 @@ func ViewIssue(ctx *context.Context) { } if perm.CanWrite(unit.TypeCode) { // Check if branch is not protected - if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch); err != nil { + if protected, err := models.IsProtectedBranch(pull.HeadRepo.ID, pull.HeadBranch); err != nil { log.Error("IsProtectedBranch: %v", err) } else if !protected { canDelete = true @@ -1535,21 +1540,21 @@ func ViewIssue(ctx *context.Context) { prConfig := prUnit.PullRequestsConfig() // Check correct values and select default - if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok || + if ms, ok := ctx.Data["MergeStyle"].(repo_model.MergeStyle); !ok || !prConfig.IsMergeStyleAllowed(ms) { defaultMergeStyle := prConfig.GetDefaultMergeStyle() if prConfig.IsMergeStyleAllowed(defaultMergeStyle) && !ok { ctx.Data["MergeStyle"] = defaultMergeStyle } else if prConfig.AllowMerge { - ctx.Data["MergeStyle"] = models.MergeStyleMerge + ctx.Data["MergeStyle"] = repo_model.MergeStyleMerge } else if prConfig.AllowRebase { - ctx.Data["MergeStyle"] = models.MergeStyleRebase + ctx.Data["MergeStyle"] = repo_model.MergeStyleRebase } else if prConfig.AllowRebaseMerge { - ctx.Data["MergeStyle"] = models.MergeStyleRebaseMerge + ctx.Data["MergeStyle"] = repo_model.MergeStyleRebaseMerge } else if prConfig.AllowSquash { - ctx.Data["MergeStyle"] = models.MergeStyleSquash + ctx.Data["MergeStyle"] = repo_model.MergeStyleSquash } else if prConfig.AllowManualMerge { - ctx.Data["MergeStyle"] = models.MergeStyleManuallyMerged + ctx.Data["MergeStyle"] = repo_model.MergeStyleManuallyMerged } else { ctx.Data["MergeStyle"] = "" } @@ -1897,7 +1902,7 @@ func UpdatePullReviewRequest(ctx *context.Context) { } if reviewID < 0 { // negative reviewIDs represent team requests - if err := issue.Repo.GetOwner(); err != nil { + if err := issue.Repo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("issue.Repo.GetOwner", err) return } @@ -2467,7 +2472,7 @@ func filterXRefComments(ctx *context.Context, issue *models.Issue) error { if models.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 { var err error // Set RefRepo for description in template - c.RefRepo, err = models.GetRepositoryByID(c.RefRepoID) + c.RefRepo, err = repo_model.GetRepositoryByID(c.RefRepoID) if err != nil { return err } diff --git a/routers/web/repo/lfs.go b/routers/web/repo/lfs.go index b1bc06f08..28d6b1286 100644 --- a/routers/web/repo/lfs.go +++ b/routers/web/repo/lfs.go @@ -47,7 +47,7 @@ func LFSFiles(ctx *context.Context) { if page <= 1 { page = 1 } - total, err := ctx.Repo.Repository.CountLFSMetaObjects() + total, err := models.CountLFSMetaObjects(ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("LFSFiles", err) return @@ -57,7 +57,7 @@ func LFSFiles(ctx *context.Context) { pager := context.NewPagination(int(total), setting.UI.ExplorePagingNum, page, 5) ctx.Data["Title"] = ctx.Tr("repo.settings.lfs") ctx.Data["PageIsSettingsLFS"] = true - lfsMetaObjects, err := ctx.Repo.Repository.GetLFSMetaObjects(pager.Paginater.Current(), setting.UI.ExplorePagingNum) + lfsMetaObjects, err := models.GetLFSMetaObjects(ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) if err != nil { ctx.ServerError("LFSFiles", err) return @@ -215,8 +215,7 @@ func LFSLockFile(ctx *context.Context) { return } - _, err := models.CreateLFSLock(&models.LFSLock{ - Repo: ctx.Repo.Repository, + _, err := models.CreateLFSLock(ctx.Repo.Repository, &models.LFSLock{ Path: lockPath, OwnerID: ctx.User.ID, }) @@ -238,7 +237,7 @@ func LFSUnlock(ctx *context.Context) { ctx.NotFound("LFSUnlock", nil) return } - _, err := models.DeleteLFSLockByID(ctx.ParamsInt64("lid"), ctx.User, true) + _, err := models.DeleteLFSLockByID(ctx.ParamsInt64("lid"), ctx.Repo.Repository, ctx.User, true) if err != nil { ctx.ServerError("LFSUnlock", err) return @@ -256,7 +255,7 @@ func LFSFileGet(ctx *context.Context) { oid := ctx.Params("oid") ctx.Data["Title"] = oid ctx.Data["PageIsSettingsLFS"] = true - meta, err := ctx.Repo.Repository.GetLFSMetaObjectByOid(oid) + meta, err := models.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, oid) if err != nil { if err == models.ErrLFSObjectNotExist { ctx.NotFound("LFSFileGet", nil) @@ -343,7 +342,7 @@ func LFSDelete(ctx *context.Context) { return } oid := ctx.Params("oid") - count, err := ctx.Repo.Repository.RemoveLFSMetaObjectByOid(oid) + count, err := models.RemoveLFSMetaObjectByOid(ctx.Repo.Repository.ID, oid) if err != nil { ctx.ServerError("LFSDelete", err) return @@ -444,7 +443,7 @@ func LFSPointerFiles(ctx *context.Context) { Size: pointerBlob.Size, } - if _, err := repo.GetLFSMetaObjectByOid(pointerBlob.Oid); err != nil { + if _, err := models.GetLFSMetaObjectByOid(repo.ID, pointerBlob.Oid); err != nil { if err != models.ErrLFSObjectNotExist { return err } diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 7593e7fbc..b08f749cd 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/models" "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/base" @@ -59,10 +60,10 @@ var ( } ) -func getRepository(ctx *context.Context, repoID int64) *models.Repository { - repo, err := models.GetRepositoryByID(repoID) +func getRepository(ctx *context.Context, repoID int64) *repo_model.Repository { + repo, err := repo_model.GetRepositoryByID(repoID) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) } else { ctx.ServerError("GetRepositoryByID", err) @@ -89,7 +90,7 @@ func getRepository(ctx *context.Context, repoID int64) *models.Repository { return repo } -func getForkRepository(ctx *context.Context) *models.Repository { +func getForkRepository(ctx *context.Context) *repo_model.Repository { forkRepo := getRepository(ctx, ctx.ParamsInt64(":repoid")) if ctx.Written() { return nil @@ -101,7 +102,7 @@ func getForkRepository(ctx *context.Context) *models.Repository { return nil } - if err := forkRepo.GetOwner(); err != nil { + if err := forkRepo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("GetOwner", err) return nil } @@ -141,7 +142,7 @@ func getForkRepository(ctx *context.Context) *models.Repository { if !traverseParentRepo.IsFork { break } - traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID) + traverseParentRepo, err = repo_model.GetRepositoryByID(traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return nil @@ -209,7 +210,7 @@ func ForkPost(ctx *context.Context) { if !traverseParentRepo.IsFork { break } - traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID) + traverseParentRepo, err = repo_model.GetRepositoryByID(traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -702,7 +703,7 @@ func ViewPullFiles(ctx *context.Context) { ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireSimpleMDE"] = true ctx.Data["RequireTribute"] = true - if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil { + if ctx.Data["Assignees"], err = models.GetRepoAssignees(ctx.Repo.Repository); err != nil { ctx.ServerError("GetAssignees", err) return } @@ -847,7 +848,7 @@ func MergePullRequest(ctx *context.Context) { } // handle manually-merged mark - if models.MergeStyle(form.Do) == models.MergeStyleManuallyMerged { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged { if err = pull_service.MergedManually(pr, ctx.User, ctx.Repo.GitRepo, form.MergeCommitID); err != nil { if models.IsErrInvalidMergeStyle(err) { ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option")) @@ -902,13 +903,13 @@ func MergePullRequest(ctx *context.Context) { message := strings.TrimSpace(form.MergeTitleField) if len(message) == 0 { - if models.MergeStyle(form.Do) == models.MergeStyleMerge { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleMerge { message = pr.GetDefaultMergeMessage() } - if models.MergeStyle(form.Do) == models.MergeStyleRebaseMerge { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleRebaseMerge { message = pr.GetDefaultMergeMessage() } - if models.MergeStyle(form.Do) == models.MergeStyleSquash { + if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleSquash { message = pr.GetDefaultSquashMessage() } } @@ -932,7 +933,7 @@ func MergePullRequest(ctx *context.Context) { return } - if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil { + if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), message); err != nil { if models.IsErrInvalidMergeStyle(err) { ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option")) ctx.Redirect(issue.Link()) @@ -1227,7 +1228,7 @@ func CleanUpPullRequest(ctx *context.Context) { } else if err = pr.LoadBaseRepo(); err != nil { ctx.ServerError("LoadBaseRepo", err) return - } else if err = pr.HeadRepo.GetOwner(); err != nil { + } else if err = pr.HeadRepo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("HeadRepo.GetOwner", err) return } diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 69bd1ed41..b4bab5960 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -146,8 +146,8 @@ func Create(ctx *context.Context) { ctx.Data["repo_template_name"] = ctx.Tr("repo.template_select") templateID := ctx.FormInt64("template_id") if templateID > 0 { - templateRepo, err := models.GetRepositoryByID(templateID) - if err == nil && templateRepo.CheckUnitUser(ctxUser, unit.TypeCode) { + templateRepo, err := repo_model.GetRepositoryByID(templateID) + if err == nil && models.CheckRepoUnitUser(templateRepo, ctxUser, unit.TypeCode) { ctx.Data["repo_template"] = templateID ctx.Data["repo_template_name"] = templateRepo.Name } @@ -213,7 +213,7 @@ func CreatePost(ctx *context.Context) { return } - var repo *models.Repository + var repo *repo_model.Repository var err error if form.RepoTemplate > 0 { opts := models.GenerateRepoOptions{ @@ -261,7 +261,7 @@ func CreatePost(ctx *context.Context) { DefaultBranch: form.DefaultBranch, AutoInit: form.AutoInit, IsTemplate: form.Template, - TrustModel: models.ToTrustModel(form.TrustModel), + TrustModel: repo_model.ToTrustModel(form.TrustModel), }) if err == nil { log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) diff --git a/routers/web/repo/setting.go b/routers/web/repo/setting.go index 4fc1e91c2..68b53f2e9 100644 --- a/routers/web/repo/setting.go +++ b/routers/web/repo/setting.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" @@ -64,6 +65,12 @@ func Settings(ctx *context.Context) { signing, _ := models.SigningKey(ctx.Repo.Repository.RepoPath()) ctx.Data["SigningKeyAvailable"] = len(signing) > 0 ctx.Data["SigningSettings"] = setting.Repository.Signing + pushMirrors, err := repo_model.GetPushMirrorsByRepoID(ctx.Repo.Repository.ID) + if err != nil { + ctx.ServerError("GetPushMirrorsByRepoID", err) + return + } + ctx.Data["PushMirrors"] = pushMirrors ctx.HTML(http.StatusOK, tplSettingsOptions) } @@ -171,7 +178,7 @@ func SettingsPost(ctx *context.Context) { } else { ctx.Repo.Mirror.NextUpdateUnix = 0 } - if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil { + if err := repo_model.UpdateMirror(ctx.Repo.Mirror); err != nil { ctx.Data["Err_Interval"] = true ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form) return @@ -217,7 +224,7 @@ func SettingsPost(ctx *context.Context) { ctx.Repo.Mirror.LFS = form.LFS ctx.Repo.Mirror.LFSEndpoint = form.LFSEndpoint - if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil { + if err := repo_model.UpdateMirror(ctx.Repo.Mirror); err != nil { ctx.ServerError("UpdateMirror", err) return } @@ -274,7 +281,7 @@ func SettingsPost(ctx *context.Context) { return } - if err = models.DeletePushMirrorByID(m.ID); err != nil { + if err = repo_model.DeletePushMirrorByID(m.ID); err != nil { ctx.ServerError("DeletePushMirrorByID", err) return } @@ -315,19 +322,19 @@ func SettingsPost(ctx *context.Context) { return } - m := &models.PushMirror{ + m := &repo_model.PushMirror{ RepoID: repo.ID, Repo: repo, RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix), Interval: interval, } - if err := models.InsertPushMirror(m); err != nil { + if err := repo_model.InsertPushMirror(m); err != nil { ctx.ServerError("InsertPushMirror", err) return } if err := mirror_service.AddPushMirrorRemote(m, address); err != nil { - if err := models.DeletePushMirrorByID(m.ID); err != nil { + if err := repo_model.DeletePushMirrorByID(m.ID); err != nil { log.Error("DeletePushMirrorByID %v", err) } ctx.ServerError("AddPushMirrorRemote", err) @@ -339,7 +346,7 @@ func SettingsPost(ctx *context.Context) { case "advanced": var repoChanged bool - var units []models.RepoUnit + var units []repo_model.RepoUnit var deleteUnitTypes []unit_model.Type // This section doesn't require repo_name/RepoName to be set in the form, don't show it @@ -358,19 +365,19 @@ func SettingsPost(ctx *context.Context) { return } - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeExternalWiki, - Config: &models.ExternalWikiConfig{ + Config: &repo_model.ExternalWikiConfig{ ExternalWikiURL: form.ExternalWikiURL, }, }) deleteUnitTypes = append(deleteUnitTypes, unit_model.TypeWiki) } else if form.EnableWiki && !form.EnableExternalWiki && !unit_model.TypeWiki.UnitGlobalDisabled() { - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeWiki, - Config: new(models.UnitConfig), + Config: new(repo_model.UnitConfig), }) deleteUnitTypes = append(deleteUnitTypes, unit_model.TypeExternalWiki) } else { @@ -393,10 +400,10 @@ func SettingsPost(ctx *context.Context) { ctx.Redirect(repo.Link() + "/settings") return } - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeExternalTracker, - Config: &models.ExternalTrackerConfig{ + Config: &repo_model.ExternalTrackerConfig{ ExternalTrackerURL: form.ExternalTrackerURL, ExternalTrackerFormat: form.TrackerURLFormat, ExternalTrackerStyle: form.TrackerIssueStyle, @@ -404,10 +411,10 @@ func SettingsPost(ctx *context.Context) { }) deleteUnitTypes = append(deleteUnitTypes, unit_model.TypeIssues) } else if form.EnableIssues && !form.EnableExternalTracker && !unit_model.TypeIssues.UnitGlobalDisabled() { - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeIssues, - Config: &models.IssuesConfig{ + Config: &repo_model.IssuesConfig{ EnableTimetracker: form.EnableTimetracker, AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime, EnableDependencies: form.EnableIssueDependencies, @@ -424,7 +431,7 @@ func SettingsPost(ctx *context.Context) { } if form.EnableProjects && !unit_model.TypeProjects.UnitGlobalDisabled() { - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypeProjects, }) @@ -433,10 +440,10 @@ func SettingsPost(ctx *context.Context) { } if form.EnablePulls && !unit_model.TypePullRequests.UnitGlobalDisabled() { - units = append(units, models.RepoUnit{ + units = append(units, repo_model.RepoUnit{ RepoID: repo.ID, Type: unit_model.TypePullRequests, - Config: &models.PullRequestsConfig{ + Config: &repo_model.PullRequestsConfig{ IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace, AllowMerge: form.PullsAllowMerge, AllowRebase: form.PullsAllowRebase, @@ -445,7 +452,7 @@ func SettingsPost(ctx *context.Context) { AllowManualMerge: form.PullsAllowManualMerge, AutodetectManualMerge: form.EnableAutodetectManualMerge, DefaultDeleteBranchAfterMerge: form.DefaultDeleteBranchAfterMerge, - DefaultMergeStyle: models.MergeStyle(form.PullsDefaultMergeStyle), + DefaultMergeStyle: repo_model.MergeStyle(form.PullsDefaultMergeStyle), }, }) } else if !unit_model.TypePullRequests.UnitGlobalDisabled() { @@ -470,7 +477,7 @@ func SettingsPost(ctx *context.Context) { case "signing": changed := false - trustModel := models.ToTrustModel(form.TrustModel) + trustModel := repo_model.ToTrustModel(form.TrustModel) if trustModel != repo.TrustModel { repo.TrustModel = trustModel changed = true @@ -526,7 +533,7 @@ func SettingsPost(ctx *context.Context) { if _, err := repository.CleanUpMigrateInfo(repo); err != nil { ctx.ServerError("CleanUpMigrateInfo", err) return - } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil { + } else if err = repo_model.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil { ctx.ServerError("DeleteMirrorByRepoID", err) return } @@ -539,7 +546,7 @@ func SettingsPost(ctx *context.Context) { ctx.Error(http.StatusNotFound) return } - if err := repo.GetOwner(); err != nil { + if err := repo.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("Convert Fork", err) return } @@ -706,7 +713,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := repo.SetArchiveRepoState(true); err != nil { + if err := models.SetArchiveRepoState(repo, true); err != nil { log.Error("Tried to archive a repo: %s", err) ctx.Flash.Error(ctx.Tr("repo.settings.archive.error")) ctx.Redirect(ctx.Repo.RepoLink + "/settings") @@ -724,7 +731,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := repo.SetArchiveRepoState(false); err != nil { + if err := models.SetArchiveRepoState(repo, false); err != nil { log.Error("Tried to unarchive a repo: %s", err) ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error")) ctx.Redirect(ctx.Repo.RepoLink + "/settings") @@ -770,14 +777,14 @@ func Collaboration(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsCollaboration"] = true - users, err := ctx.Repo.Repository.GetCollaborators(db.ListOptions{}) + users, err := models.GetCollaborators(ctx.Repo.Repository.ID, db.ListOptions{}) if err != nil { ctx.ServerError("GetCollaborators", err) return } ctx.Data["Collaborators"] = users - teams, err := ctx.Repo.Repository.GetRepoTeams() + teams, err := models.GetRepoTeams(ctx.Repo.Repository) if err != nil { ctx.ServerError("GetRepoTeams", err) return @@ -824,13 +831,13 @@ func CollaborationPost(ctx *context.Context) { return } - if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got { + if got, err := models.IsCollaborator(ctx.Repo.Repository.ID, u.ID); err == nil && got { ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate")) ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration") return } - if err = ctx.Repo.Repository.AddCollaborator(u); err != nil { + if err = models.AddCollaborator(ctx.Repo.Repository, u); err != nil { ctx.ServerError("AddCollaborator", err) return } @@ -845,7 +852,8 @@ func CollaborationPost(ctx *context.Context) { // ChangeCollaborationAccessMode response for changing access of a collaboration func ChangeCollaborationAccessMode(ctx *context.Context) { - if err := ctx.Repo.Repository.ChangeCollaborationAccessMode( + if err := models.ChangeCollaborationAccessMode( + ctx.Repo.Repository, ctx.FormInt64("uid"), perm.AccessMode(ctx.FormInt("mode"))); err != nil { log.Error("ChangeCollaborationAccessMode: %v", err) @@ -854,7 +862,7 @@ func ChangeCollaborationAccessMode(ctx *context.Context) { // DeleteCollaboration delete a collaboration for a repository func DeleteCollaboration(ctx *context.Context) { - if err := ctx.Repo.Repository.DeleteCollaboration(ctx.FormInt64("id")); err != nil { + if err := models.DeleteCollaboration(ctx.Repo.Repository, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteCollaboration: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success")) @@ -937,7 +945,7 @@ func DeleteTeam(ctx *context.Context) { } // parseOwnerAndRepo get repos by owner -func parseOwnerAndRepo(ctx *context.Context) (*user_model.User, *models.Repository) { +func parseOwnerAndRepo(ctx *context.Context) (*user_model.User, *repo_model.Repository) { owner, err := user_model.GetUserByName(ctx.Params(":username")) if err != nil { if user_model.IsErrUserNotExist(err) { @@ -948,9 +956,9 @@ func parseOwnerAndRepo(ctx *context.Context) (*user_model.User, *models.Reposito return nil, nil } - repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame")) + repo, err := repo_model.GetRepositoryByName(owner.ID, ctx.Params(":reponame")) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByName", err) } else { ctx.ServerError("GetRepositoryByName", err) @@ -1136,7 +1144,7 @@ func UpdateAvatarSetting(ctx *context.Context, form forms.AvatarForm) error { if !(st.IsImage() && !st.IsSvgImage()) { return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image")) } - if err = ctxRepo.UploadAvatar(data); err != nil { + if err = models.UploadRepoAvatar(ctxRepo, data); err != nil { return fmt.Errorf("UploadAvatar: %v", err) } return nil @@ -1156,23 +1164,24 @@ func SettingsAvatar(ctx *context.Context) { // SettingsDeleteAvatar delete repository avatar func SettingsDeleteAvatar(ctx *context.Context) { - if err := ctx.Repo.Repository.DeleteAvatar(); err != nil { + if err := models.DeleteRepoAvatar(ctx.Repo.Repository); err != nil { ctx.Flash.Error(fmt.Sprintf("DeleteAvatar: %v", err)) } ctx.Redirect(ctx.Repo.RepoLink + "/settings") } -func selectPushMirrorByForm(form *forms.RepoSettingForm, repo *models.Repository) (*models.PushMirror, error) { +func selectPushMirrorByForm(form *forms.RepoSettingForm, repo *repo_model.Repository) (*repo_model.PushMirror, error) { id, err := strconv.ParseInt(form.PushMirrorID, 10, 64) if err != nil { return nil, err } - if err = repo.LoadPushMirrors(); err != nil { + pushMirrors, err := repo_model.GetPushMirrorsByRepoID(repo.ID) + if err != nil { return nil, err } - for _, m := range repo.PushMirrors { + for _, m := range pushMirrors { if m.ID == id { return m, nil } diff --git a/routers/web/repo/setting_protected_branch.go b/routers/web/repo/setting_protected_branch.go index e0580ac6d..1435b820a 100644 --- a/routers/web/repo/setting_protected_branch.go +++ b/routers/web/repo/setting_protected_branch.go @@ -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/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" @@ -29,7 +30,7 @@ func ProtectedBranch(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsBranches"] = true - protectedBranches, err := ctx.Repo.Repository.GetProtectedBranches() + protectedBranches, err := models.GetProtectedBranches(ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("GetProtectedBranches", err) return @@ -82,7 +83,7 @@ func ProtectedBranchPost(ctx *context.Context) { return } } - if err := repo.UpdateDefaultBranch(); err != nil { + if err := repo_model.UpdateDefaultBranch(repo); err != nil { ctx.ServerError("SetDefaultBranch", err) return } @@ -123,7 +124,7 @@ func SettingsProtectedBranch(c *context.Context) { } } - users, err := c.Repo.Repository.GetReaders() + users, err := models.GetRepoReaders(c.Repo.Repository) if err != nil { c.ServerError("Repo.Repository.GetReaders", err) return @@ -279,7 +280,7 @@ func SettingsProtectedBranchPost(ctx *context.Context) { ctx.Redirect(fmt.Sprintf("%s/settings/branches/%s", ctx.Repo.RepoLink, util.PathEscapeSegments(branch))) } else { if protectBranch != nil { - if err := ctx.Repo.Repository.DeleteProtectedBranch(protectBranch.ID); err != nil { + if err := models.DeleteProtectedBranch(ctx.Repo.Repository.ID, protectBranch.ID); err != nil { ctx.ServerError("DeleteProtectedBranch", err) return } diff --git a/routers/web/repo/settings_test.go b/routers/web/repo/settings_test.go index 5f997bc36..fe6e9b52b 100644 --- a/routers/web/repo/settings_test.go +++ b/routers/web/repo/settings_test.go @@ -11,6 +11,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/context" @@ -112,7 +113,7 @@ func TestCollaborationPost(t *testing.T) { Type: user_model.UserTypeIndividual, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 2, Owner: u, } @@ -128,7 +129,7 @@ func TestCollaborationPost(t *testing.T) { assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) - exists, err := re.IsCollaborator(4) + exists, err := models.IsCollaborator(re.ID, 4) assert.NoError(t, err) assert.True(t, exists) } @@ -172,7 +173,7 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { Type: user_model.UserTypeIndividual, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 2, Owner: u, } @@ -188,7 +189,7 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) - exists, err := re.IsCollaborator(4) + exists, err := models.IsCollaborator(re.ID, 4) assert.NoError(t, err) assert.True(t, exists) @@ -238,7 +239,7 @@ func TestAddTeamPost(t *testing.T) { OrgID: 26, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 43, Owner: org, OwnerID: 26, @@ -278,7 +279,7 @@ func TestAddTeamPost_NotAllowed(t *testing.T) { OrgID: 26, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 43, Owner: org, OwnerID: 26, @@ -319,7 +320,7 @@ func TestAddTeamPost_AddTeamTwice(t *testing.T) { OrgID: 26, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 43, Owner: org, OwnerID: 26, @@ -355,7 +356,7 @@ func TestAddTeamPost_NonExistentTeam(t *testing.T) { Type: user_model.UserTypeOrganization, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 43, Owner: org, OwnerID: 26, @@ -393,7 +394,7 @@ func TestDeleteTeam(t *testing.T) { OrgID: 3, } - re := &models.Repository{ + re := &repo_model.Repository{ ID: 3, Owner: org, OwnerID: 3, diff --git a/routers/web/repo/tag.go b/routers/web/repo/tag.go index 671c388cb..0114704f8 100644 --- a/routers/web/repo/tag.go +++ b/routers/web/repo/tag.go @@ -135,14 +135,14 @@ func setTagsContext(ctx *context.Context) error { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsTags"] = true - protectedTags, err := ctx.Repo.Repository.GetProtectedTags() + protectedTags, err := models.GetProtectedTags(ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("GetProtectedTags", err) return err } ctx.Data["ProtectedTags"] = protectedTags - users, err := ctx.Repo.Repository.GetReaders() + users, err := models.GetRepoReaders(ctx.Repo.Repository) if err != nil { ctx.ServerError("Repo.Repository.GetReaders", err) return err diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 33420aab3..bc8396ab7 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" @@ -269,7 +270,7 @@ func renderDirectory(ctx *context.Context, treeLink string) { if isTextFile && setting.LFS.StartServer { pointer, _ := lfs.ReadPointerFromBuffer(buf) if pointer.IsValid() { - meta, err := ctx.Repo.Repository.GetLFSMetaObjectByOid(pointer.Oid) + meta, err := models.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) if err != nil && err != models.ErrLFSObjectNotExist { ctx.ServerError("GetLFSMetaObject", err) return @@ -394,7 +395,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st if isTextFile && setting.LFS.StartServer { pointer, _ := lfs.ReadPointerFromBuffer(buf) if pointer.IsValid() { - meta, err := ctx.Repo.Repository.GetLFSMetaObjectByOid(pointer.Oid) + meta, err := models.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) if err != nil && err != models.ErrLFSObjectNotExist { ctx.ServerError("GetLFSMetaObject", err) return @@ -443,7 +444,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st ctx.Data["IsTextSource"] = isTextFile || isDisplayingSource // Check LFS Lock - lfsLock, err := ctx.Repo.Repository.GetTreePathLock(ctx.Repo.TreePath) + lfsLock, err := models.GetTreePathLock(ctx.Repo.Repository.ID, ctx.Repo.TreePath) ctx.Data["LFSLock"] = lfsLock if err != nil { ctx.ServerError("GetTreePathLock", err) @@ -641,7 +642,7 @@ func checkHomeCodeViewable(ctx *context.Context) { if ctx.IsSigned { // Set repo notification-status read if unread - if err := ctx.Repo.Repository.ReadBy(ctx.User.ID); err != nil { + if err := models.SetRepoReadBy(ctx.Repo.Repository.ID, ctx.User.ID); err != nil { ctx.ServerError("ReadBy", err) return } @@ -808,7 +809,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri } func renderLanguageStats(ctx *context.Context) { - langs, err := ctx.Repo.Repository.GetTopLanguageStats(5) + langs, err := repo_model.GetTopLanguageStats(ctx.Repo.Repository, 5) if err != nil { ctx.ServerError("Repo.GetTopLanguageStats", err) return @@ -926,7 +927,9 @@ func Watchers(ctx *context.Context) { ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers") ctx.Data["PageIsWatchers"] = true - RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers) + RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) { + return models.GetRepoWatchers(ctx.Repo.Repository.ID, opts) + }, tplWatchers) } // Stars render repository's starred users @@ -951,7 +954,7 @@ func Forks(ctx *context.Context) { pager := context.NewPagination(ctx.Repo.Repository.NumForks, models.ItemsPerPage, page, 5) ctx.Data["Page"] = pager - forks, err := ctx.Repo.Repository.GetForks(db.ListOptions{ + forks, err := models.GetForks(ctx.Repo.Repository, db.ListOptions{ Page: pager.Paginater.Current(), PageSize: models.ItemsPerPage, }) @@ -961,7 +964,7 @@ func Forks(ctx *context.Context) { } for _, fork := range forks { - if err = fork.GetOwner(); err != nil { + if err = fork.GetOwner(db.DefaultContext); err != nil { ctx.ServerError("GetOwner", err) return } diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go index 87f2779c1..1bfda50d1 100644 --- a/routers/web/repo/wiki_test.go +++ b/routers/web/repo/wiki_test.go @@ -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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/test" @@ -23,7 +23,7 @@ import ( const content = "Wiki contents for unit tests" const message = "Wiki commit message for unit tests" -func wikiEntry(t *testing.T, repo *models.Repository, wikiName string) *git.TreeEntry { +func wikiEntry(t *testing.T, repo *repo_model.Repository, wikiName string) *git.TreeEntry { wikiRepo, err := git.OpenRepository(repo.WikiPath()) assert.NoError(t, err) defer wikiRepo.Close() @@ -39,7 +39,7 @@ func wikiEntry(t *testing.T, repo *models.Repository, wikiName string) *git.Tree return nil } -func wikiContent(t *testing.T, repo *models.Repository, wikiName string) string { +func wikiContent(t *testing.T, repo *repo_model.Repository, wikiName string) string { entry := wikiEntry(t, repo, wikiName) if !assert.NotNil(t, entry) { return "" @@ -52,11 +52,11 @@ func wikiContent(t *testing.T, repo *models.Repository, wikiName string) string return string(bytes) } -func assertWikiExists(t *testing.T, repo *models.Repository, wikiName string) { +func assertWikiExists(t *testing.T, repo *repo_model.Repository, wikiName string) { assert.NotNil(t, wikiEntry(t, repo, wikiName)) } -func assertWikiNotExists(t *testing.T, repo *models.Repository, wikiName string) { +func assertWikiNotExists(t *testing.T, repo *repo_model.Repository, wikiName string) { assert.Nil(t, wikiEntry(t, repo, wikiName)) } diff --git a/routers/web/user/home.go b/routers/web/user/home.go index ca2705a42..d3883571e 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/models" "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/base" @@ -96,7 +97,7 @@ func Dashboard(ctx *context.Context) { } var err error - var mirrors []*models.Repository + var mirrors []*repo_model.Repository if ctxUser.IsOrganization() { var env models.AccessibleReposEnvironment if ctx.Org.Team != nil { @@ -114,7 +115,7 @@ func Dashboard(ctx *context.Context) { return } } else { - mirrors, err = models.GetUserMirrorRepositories(ctxUser.ID) + mirrors, err = repo_model.GetUserMirrorRepositories(ctxUser.ID) if err != nil { ctx.ServerError("GetUserMirrorRepositories", err) return @@ -122,7 +123,7 @@ func Dashboard(ctx *context.Context) { } ctx.Data["MaxShowRepoNum"] = setting.UI.User.RepoPagingNum - if err := models.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil { + if err := repo_model.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil { ctx.ServerError("MirrorRepositoryList.LoadAttributes", err) return } @@ -524,7 +525,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) { // showReposMap maps repository IDs to their Repository pointers. showReposMap, err := repoIDMap(ctxUser, issueCountByRepo, unitType) if err != nil { - if models.IsErrRepoNotExist(err) { + if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", err) return } @@ -795,15 +796,15 @@ func issueIDsFromSearch(ctxUser *user_model.User, keyword string, opts *models.I return issueIDsFromSearch, nil } -func repoIDMap(ctxUser *user_model.User, issueCountByRepo map[int64]int64, unitType unit.Type) (map[int64]*models.Repository, error) { - repoByID := make(map[int64]*models.Repository, len(issueCountByRepo)) +func repoIDMap(ctxUser *user_model.User, issueCountByRepo map[int64]int64, unitType unit.Type) (map[int64]*repo_model.Repository, error) { + repoByID := make(map[int64]*repo_model.Repository, len(issueCountByRepo)) for id := range issueCountByRepo { if id <= 0 { continue } if _, ok := repoByID[id]; !ok { - repo, err := models.GetRepositoryByID(id) - if models.IsErrRepoNotExist(err) { + repo, err := repo_model.GetRepositoryByID(id) + if repo_model.IsErrRepoNotExist(err) { return nil, err } else if err != nil { return nil, fmt.Errorf("GetRepositoryByID: [%d]%v", id, err) diff --git a/routers/web/user/profile.go b/routers/web/user/profile.go index 32d2bdde8..77b357c22 100644 --- a/routers/web/user/profile.go +++ b/routers/web/user/profile.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/markup" @@ -196,7 +197,7 @@ func Profile(ctx *context.Context) { topicOnly := ctx.FormBool("topic") var ( - repos []*models.Repository + repos []*repo_model.Repository count int64 total int orderBy db.SearchOrderBy diff --git a/routers/web/user/setting/adopt.go b/routers/web/user/setting/adopt.go index 56ab6ec99..348705b74 100644 --- a/routers/web/user/setting/adopt.go +++ b/routers/web/user/setting/adopt.go @@ -8,6 +8,7 @@ import ( "path/filepath" "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/context" "code.gitea.io/gitea/modules/setting" @@ -31,7 +32,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) { root := user_model.UserPath(ctxUser.LowerName) // check not a repo - has, err := models.IsRepositoryExist(ctxUser, dir) + has, err := repo_model.IsRepositoryExist(ctxUser, dir) if err != nil { ctx.ServerError("IsRepositoryExist", err) return diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index 0475398a9..089177874 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -16,6 +16,7 @@ import ( "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" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -271,7 +272,7 @@ func Repos(ctx *context.Context) { if adoptOrDelete { repoNames := make([]string, 0, setting.UI.Admin.UserPagingNum) - repos := map[string]*models.Repository{} + repos := map[string]*repo_model.Repository{} // We're going to iterate by pagesize. root := user_model.UserPath(ctxUser.Name) if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { diff --git a/services/auth/source/ldap/source.go b/services/auth/source/ldap/source.go index 3e751f512..be4a4b2d6 100644 --- a/services/auth/source/ldap/source.go +++ b/services/auth/source/ldap/source.go @@ -7,7 +7,6 @@ package ldap import ( "strings" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/secret" @@ -62,7 +61,7 @@ type Source struct { // FromDB fills up a LDAPConfig from serialized format. func (source *Source) FromDB(bs []byte) error { - err := models.JSONUnmarshalHandleDoubleEncode(bs, &source) + err := json.UnmarshalHandleDoubleEncode(bs, &source) if err != nil { return err } diff --git a/services/auth/source/oauth2/source.go b/services/auth/source/oauth2/source.go index 60845e3b0..bedaed7ef 100644 --- a/services/auth/source/oauth2/source.go +++ b/services/auth/source/oauth2/source.go @@ -5,7 +5,6 @@ package oauth2 import ( - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/json" ) @@ -33,7 +32,7 @@ type Source struct { // FromDB fills up an OAuth2Config from serialized format. func (source *Source) FromDB(bs []byte) error { - return models.JSONUnmarshalHandleDoubleEncode(bs, &source) + return json.UnmarshalHandleDoubleEncode(bs, &source) } // ToDB exports an SMTPConfig to a serialized format. diff --git a/services/auth/source/pam/source.go b/services/auth/source/pam/source.go index 73850cd9a..65ae76138 100644 --- a/services/auth/source/pam/source.go +++ b/services/auth/source/pam/source.go @@ -5,7 +5,6 @@ package pam import ( - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/json" ) @@ -29,7 +28,7 @@ type Source struct { // FromDB fills up a PAMConfig from serialized format. func (source *Source) FromDB(bs []byte) error { - return models.JSONUnmarshalHandleDoubleEncode(bs, &source) + return json.UnmarshalHandleDoubleEncode(bs, &source) } // ToDB exports a PAMConfig to a serialized format. diff --git a/services/auth/source/smtp/source.go b/services/auth/source/smtp/source.go index 52e250567..006202e0d 100644 --- a/services/auth/source/smtp/source.go +++ b/services/auth/source/smtp/source.go @@ -5,7 +5,6 @@ package smtp import ( - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/json" ) @@ -35,7 +34,7 @@ type Source struct { // FromDB fills up an SMTPConfig from serialized format. func (source *Source) FromDB(bs []byte) error { - return models.JSONUnmarshalHandleDoubleEncode(bs, &source) + return json.UnmarshalHandleDoubleEncode(bs, &source) } // ToDB exports an SMTPConfig to a serialized format. diff --git a/services/auth/source/sspi/source.go b/services/auth/source/sspi/source.go index 68fd6a607..8d469d481 100644 --- a/services/auth/source/sspi/source.go +++ b/services/auth/source/sspi/source.go @@ -5,7 +5,6 @@ package sspi import ( - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/json" ) @@ -28,7 +27,7 @@ type Source struct { // FromDB fills up an SSPIConfig from serialized format. func (cfg *Source) FromDB(bs []byte) error { - return models.JSONUnmarshalHandleDoubleEncode(bs, &cfg) + return json.UnmarshalHandleDoubleEncode(bs, &cfg) } // ToDB exports an SSPIConfig to a serialized format. diff --git a/services/comments/comments.go b/services/comments/comments.go index 6e9630127..296f06d75 100644 --- a/services/comments/comments.go +++ b/services/comments/comments.go @@ -8,13 +8,14 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/issues" + repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/timeutil" ) // CreateIssueComment creates a plain issue comment. -func CreateIssueComment(doer *user_model.User, repo *models.Repository, issue *models.Issue, content string, attachments []string) (*models.Comment, error) { +func CreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, content string, attachments []string) (*models.Comment, error) { comment, err := models.CreateComment(&models.CreateCommentOptions{ Type: models.CommentTypeComment, Doer: doer, diff --git a/services/issue/commit.go b/services/issue/commit.go index 3e2f6c471..0dda5f202 100644 --- a/services/issue/commit.go +++ b/services/issue/commit.go @@ -14,6 +14,7 @@ import ( "time" "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/references" "code.gitea.io/gitea/modules/repository" @@ -85,7 +86,7 @@ func issueAddTime(issue *models.Issue, doer *user_model.User, time time.Time, ti // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue // if the provided ref references a non-existent issue. -func getIssueFromRef(repo *models.Repository, index int64) (*models.Issue, error) { +func getIssueFromRef(repo *repo_model.Repository, index int64) (*models.Issue, error) { issue, err := models.GetIssueByIndex(repo.ID, index) if err != nil { if models.IsErrIssueNotExist(err) { @@ -97,7 +98,7 @@ func getIssueFromRef(repo *models.Repository, index int64) (*models.Issue, error } // UpdateIssuesCommit checks if issues are manipulated by commit message. -func UpdateIssuesCommit(doer *user_model.User, repo *models.Repository, commits []*repository.PushCommit, branchName string) error { +func UpdateIssuesCommit(doer *user_model.User, repo *repo_model.Repository, commits []*repository.PushCommit, branchName string) error { // Commits are appended in the reverse order. for i := len(commits) - 1; i >= 0; i-- { c := commits[i] @@ -108,7 +109,7 @@ func UpdateIssuesCommit(doer *user_model.User, repo *models.Repository, commits } refMarked := make(map[markKey]bool) - var refRepo *models.Repository + var refRepo *repo_model.Repository var refIssue *models.Issue var err error for _, ref := range references.FindAllIssueReferences(c.Message) { diff --git a/services/issue/commit_test.go b/services/issue/commit_test.go index 1addbd080..37283a789 100644 --- a/services/issue/commit_test.go +++ b/services/issue/commit_test.go @@ -8,6 +8,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/repository" @@ -46,7 +47,7 @@ func TestUpdateIssuesCommit(t *testing.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) repo.Owner = user commentBean := &models.Comment{ @@ -75,7 +76,7 @@ func TestUpdateIssuesCommit(t *testing.T) { Message: "close #1", }, } - repo = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) commentBean = &models.Comment{ Type: models.CommentTypeCommitRef, CommitSHA: "abcdef1", @@ -101,7 +102,7 @@ func TestUpdateIssuesCommit(t *testing.T) { Message: "close " + setting.AppURL + repo.FullName() + "/pulls/1", }, } - repo = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) commentBean = &models.Comment{ Type: models.CommentTypeCommitRef, CommitSHA: "abcdef3", @@ -132,7 +133,7 @@ func TestUpdateIssuesCommit_Colon(t *testing.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) repo.Owner = user issueBean := &models.Issue{RepoID: repo.ID, Index: 4} @@ -159,7 +160,7 @@ func TestUpdateIssuesCommit_Issue5957(t *testing.T) { }, } - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) commentBean := &models.Comment{ Type: models.CommentTypeCommitRef, CommitSHA: "abcdef1", @@ -194,7 +195,7 @@ func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { }, } - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) commentBean := &models.Comment{ Type: models.CommentTypeCommitRef, CommitSHA: "abcdef1", @@ -229,7 +230,7 @@ func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { }, } - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) commentBean := &models.Comment{ Type: models.CommentTypeCommitRef, CommitSHA: "abcdef1", @@ -272,7 +273,7 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { }, } - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 6}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 6}).(*repo_model.Repository) commentBean := &models.Comment{ Type: models.CommentTypeCommitRef, CommitSHA: "abcdef3", diff --git a/services/issue/issue.go b/services/issue/issue.go index cb34a9eac..ef2894b92 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -7,6 +7,7 @@ package issue import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/notification" @@ -14,7 +15,7 @@ import ( ) // NewIssue creates new issue with labels for repository. -func NewIssue(repo *models.Repository, issue *models.Issue, labelIDs []int64, uuids []string, assigneeIDs []int64) error { +func NewIssue(repo *repo_model.Repository, issue *models.Issue, labelIDs []int64, uuids []string, assigneeIDs []int64) error { if err := models.NewIssue(repo, issue, labelIDs, uuids); err != nil { return err } diff --git a/services/lfs/locks.go b/services/lfs/locks.go index 11cf5c16b..c2ede20b7 100644 --- a/services/lfs/locks.go +++ b/services/lfs/locks.go @@ -10,6 +10,7 @@ import ( "strings" "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/json" @@ -19,7 +20,7 @@ import ( api "code.gitea.io/gitea/modules/structs" ) -func handleLockListOut(ctx *context.Context, repo *models.Repository, lock *models.LFSLock, err error) { +func handleLockListOut(ctx *context.Context, repo *repo_model.Repository, lock *models.LFSLock, err error) { if err != nil { if models.IsErrLFSLockNotExist(err) { ctx.JSON(http.StatusOK, api.LFSLockList{ @@ -47,7 +48,7 @@ func handleLockListOut(ctx *context.Context, repo *models.Repository, lock *mode func GetListLockHandler(ctx *context.Context) { rv := getRequestContext(ctx) - repository, err := models.GetRepositoryByOwnerAndName(rv.User, rv.Repo) + repository, err := repo_model.GetRepositoryByOwnerAndName(rv.User, rv.Repo) if err != nil { log.Debug("Could not find repository: %s/%s - %s", rv.User, rv.Repo, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -134,7 +135,7 @@ func PostLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := models.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -167,8 +168,7 @@ func PostLockHandler(ctx *context.Context) { return } - lock, err := models.CreateLFSLock(&models.LFSLock{ - Repo: repository, + lock, err := models.CreateLFSLock(repository, &models.LFSLock{ Path: req.Path, OwnerID: ctx.User.ID, }) @@ -202,7 +202,7 @@ func VerifyLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := models.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -268,7 +268,7 @@ func UnLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := models.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -301,7 +301,7 @@ func UnLockHandler(ctx *context.Context) { return } - lock, err := models.DeleteLFSLockByID(ctx.ParamsInt64("lid"), ctx.User, req.Force) + lock, err := models.DeleteLFSLockByID(ctx.ParamsInt64("lid"), repository, ctx.User, req.Force) if err != nil { if models.IsErrLFSUnauthorizedAction(err) { ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") diff --git a/services/lfs/server.go b/services/lfs/server.go index 2b0c8265c..df0a8bd39 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -20,6 +20,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/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -195,7 +196,7 @@ func BatchHandler(ctx *context.Context) { return } - meta, err := repository.GetLFSMetaObjectByOid(p.Oid) + meta, err := models.GetLFSMetaObjectByOid(repository.ID, p.Oid) if err != nil && err != models.ErrLFSObjectNotExist { log.Error("Unable to get LFS MetaObject [%s] for %s/%s. Error: %v", p.Oid, rc.User, rc.Repo, err) writeStatus(ctx, http.StatusInternalServerError) @@ -333,7 +334,7 @@ func UploadHandler(ctx *context.Context) { } else { writeStatus(ctx, http.StatusInternalServerError) } - if _, err = repository.RemoveLFSMetaObjectByOid(p.Oid); err != nil { + if _, err = models.RemoveLFSMetaObjectByOid(repository.ID, p.Oid); err != nil { log.Error("Error whilst removing metaobject for LFS OID[%s]: %v", p.Oid, err) } return @@ -396,7 +397,7 @@ func getAuthenticatedMeta(ctx *context.Context, rc *requestContext, p lfs_module return nil } - meta, err := repository.GetLFSMetaObjectByOid(p.Oid) + meta, err := models.GetLFSMetaObjectByOid(repository.ID, p.Oid) if err != nil { log.Error("Unable to get LFS OID[%s] Error: %v", p.Oid, err) writeStatus(ctx, http.StatusNotFound) @@ -406,8 +407,8 @@ func getAuthenticatedMeta(ctx *context.Context, rc *requestContext, p lfs_module return meta } -func getAuthenticatedRepository(ctx *context.Context, rc *requestContext, requireWrite bool) *models.Repository { - repository, err := models.GetRepositoryByOwnerAndName(rc.User, rc.Repo) +func getAuthenticatedRepository(ctx *context.Context, rc *requestContext, requireWrite bool) *repo_model.Repository { + repository, err := repo_model.GetRepositoryByOwnerAndName(rc.User, rc.Repo) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", rc.User, rc.Repo, err) writeStatus(ctx, http.StatusNotFound) @@ -480,7 +481,7 @@ func writeStatusMessage(ctx *context.Context, status int, message string) { // authenticate uses the authorization string to determine whether // or not to proceed. This server assumes an HTTP Basic auth format. -func authenticate(ctx *context.Context, repository *models.Repository, authorization string, requireSigned, requireWrite bool) bool { +func authenticate(ctx *context.Context, repository *repo_model.Repository, authorization string, requireSigned, requireWrite bool) bool { accessMode := perm.AccessModeRead if requireWrite { accessMode = perm.AccessModeWrite @@ -508,7 +509,7 @@ func authenticate(ctx *context.Context, repository *models.Repository, authoriza return true } -func handleLFSToken(tokenSHA string, target *models.Repository, mode perm.AccessMode) (*user_model.User, error) { +func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { if !strings.Contains(tokenSHA, ".") { return nil, nil } @@ -543,7 +544,7 @@ func handleLFSToken(tokenSHA string, target *models.Repository, mode perm.Access return u, nil } -func parseToken(authorization string, target *models.Repository, mode perm.AccessMode) (*user_model.User, error) { +func parseToken(authorization string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { if authorization == "" { return nil, fmt.Errorf("no token") } diff --git a/services/mailer/mail.go b/services/mailer/mail.go index a9978be8b..91d39abea 100644 --- a/services/mailer/mail.go +++ b/services/mailer/mail.go @@ -16,6 +16,7 @@ import ( texttmpl "text/template" "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" "code.gitea.io/gitea/modules/emoji" @@ -176,7 +177,7 @@ func SendRegisterNotifyMail(u *user_model.User) { } // SendCollaboratorMail sends mail notification to new collaborator. -func SendCollaboratorMail(u, doer *user_model.User, repo *models.Repository) { +func SendCollaboratorMail(u, doer *user_model.User, repo *repo_model.Repository) { if setting.MailService == nil { // No mail service configured return diff --git a/services/mailer/mail_issue.go b/services/mailer/mail_issue.go index 1fbe68e02..22ebbb1a9 100644 --- a/services/mailer/mail_issue.go +++ b/services/mailer/mail_issue.go @@ -139,7 +139,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 !ctx.Issue.Repo.CheckUnitUser(user, checkUnit) { + if !models.CheckRepoUnitUser(ctx.Issue.Repo, user, checkUnit) { continue } diff --git a/services/mailer/mail_repo.go b/services/mailer/mail_repo.go index 8a2eeac08..51b16aa7e 100644 --- a/services/mailer/mail_repo.go +++ b/services/mailer/mail_repo.go @@ -9,6 +9,7 @@ import ( "fmt" "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/setting" "code.gitea.io/gitea/modules/templates" @@ -16,7 +17,7 @@ import ( ) // SendRepoTransferNotifyMail triggers a notification e-mail when a pending repository transfer was created -func SendRepoTransferNotifyMail(doer, newOwner *user_model.User, repo *models.Repository) error { +func SendRepoTransferNotifyMail(doer, newOwner *user_model.User, repo *repo_model.Repository) error { if setting.MailService == nil { // No mail service configured return nil @@ -46,7 +47,7 @@ func SendRepoTransferNotifyMail(doer, newOwner *user_model.User, repo *models.Re } // sendRepoTransferNotifyMail triggers a notification e-mail when a pending repository transfer was created for each language -func sendRepoTransferNotifyMailPerLang(lang string, newOwner, doer *user_model.User, emails []string, repo *models.Repository) error { +func sendRepoTransferNotifyMailPerLang(lang string, newOwner, doer *user_model.User, emails []string, repo *repo_model.Repository) error { var ( locale = translation.NewLocale(lang) content bytes.Buffer diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index 8e8cd9823..1ce1020d0 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -11,6 +11,7 @@ import ( texttmpl "text/template" "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" @@ -41,7 +42,7 @@ const bodyTpl = ` ` -func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *models.Repository, issue *models.Issue, comment *models.Comment) { +func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment) { assert.NoError(t, unittest.PrepareTestDatabase()) var mailService = setting.Mailer{ From: "test@gitea.com", @@ -51,7 +52,7 @@ func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *models.Reposi setting.Domain = "localhost" doer = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - repo = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1, Owner: doer}).(*models.Repository) + repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1, Owner: doer}).(*repo_model.Repository) issue = unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 1, Repo: repo, Poster: doer}).(*models.Issue) assert.NoError(t, issue.LoadRepo()) comment = unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 2, Issue: issue}).(*models.Comment) diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index 4808916c1..0887aa113 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -43,7 +43,7 @@ type GiteaLocalUploader struct { doer *user_model.User repoOwner string repoName string - repo *models.Repository + repo *repo_model.Repository labels sync.Map milestones sync.Map issues sync.Map @@ -93,7 +93,7 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate return err } - var r *models.Repository + var r *repo_model.Repository if opts.MigrateToRepoID <= 0 { r, err = repo_module.CreateRepository(g.doer, owner, models.CreateRepoOptions{ Name: g.repoName, @@ -102,10 +102,10 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate GitServiceType: opts.GitServiceType, IsPrivate: opts.Private, IsMirror: opts.Mirror, - Status: models.RepositoryBeingMigrated, + Status: repo_model.RepositoryBeingMigrated, }) } else { - r, err = models.GetRepositoryByID(opts.MigrateToRepoID) + r, err = repo_model.GetRepositoryByID(opts.MigrateToRepoID) } if err != nil { return err @@ -979,6 +979,6 @@ func (g *GiteaLocalUploader) Finish() error { return err } - g.repo.Status = models.RepositoryReady + g.repo.Status = repo_model.RepositoryReady return models.UpdateRepositoryCols(g.repo, "status") } diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 45876dd96..7d4f77eac 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -12,6 +12,7 @@ import ( "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" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/graceful" @@ -53,9 +54,9 @@ func TestGiteaUploadRepo(t *testing.T) { }, nil) assert.NoError(t, err) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID, Name: repoName}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, Name: repoName}).(*repo_model.Repository) assert.True(t, repo.HasWiki()) - assert.EqualValues(t, models.RepositoryReady, repo.Status) + assert.EqualValues(t, repo_model.RepositoryReady, repo.Status) milestones, _, err := models.GetMilestones(models.GetMilestonesOption{ RepoID: repo.ID, diff --git a/services/migrations/migrate.go b/services/migrations/migrate.go index 02b167b27..65ecceddb 100644 --- a/services/migrations/migrate.go +++ b/services/migrations/migrate.go @@ -15,6 +15,7 @@ import ( "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/hostmatcher" "code.gitea.io/gitea/modules/log" @@ -106,7 +107,7 @@ func IsMigrateURLAllowed(remoteURL string, doer *user_model.User) error { } // MigrateRepository migrate repository according MigrateOptions -func MigrateRepository(ctx context.Context, doer *user_model.User, ownerName string, opts base.MigrateOptions, messenger base.Messenger) (*models.Repository, error) { +func MigrateRepository(ctx context.Context, doer *user_model.User, ownerName string, opts base.MigrateOptions, messenger base.Messenger) (*repo_model.Repository, error) { err := IsMigrateURLAllowed(opts.CloneAddr, doer) if err != nil { return nil, err diff --git a/services/mirror/mirror.go b/services/mirror/mirror.go index dae6f2807..264320017 100644 --- a/services/mirror/mirror.go +++ b/services/mirror/mirror.go @@ -8,7 +8,7 @@ import ( "context" "fmt" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/queue" @@ -59,7 +59,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error { handler := func(idx int, bean interface{}, limit int) error { var item SyncRequest - if m, ok := bean.(*models.Mirror); ok { + if m, ok := bean.(*repo_model.Mirror); ok { if m.Repo == nil { log.Error("Disconnected mirror found: %d", m.ID) return nil @@ -68,7 +68,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error { Type: PullMirrorType, RepoID: m.RepoID, } - } else if m, ok := bean.(*models.PushMirror); ok { + } else if m, ok := bean.(*repo_model.PushMirror); ok { if m.Repo == nil { log.Error("Disconnected push-mirror found: %d", m.ID) return nil @@ -111,7 +111,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error { } if pullLimit != 0 { - if err := models.MirrorsIterate(func(idx int, bean interface{}) error { + if err := repo_model.MirrorsIterate(func(idx int, bean interface{}) error { return handler(idx, bean, pullLimit) }); err != nil && err != errLimit { log.Error("MirrorsIterate: %v", err) @@ -119,7 +119,7 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error { } } if pushLimit != 0 { - if err := models.PushMirrorsIterate(func(idx int, bean interface{}) error { + if err := repo_model.PushMirrorsIterate(func(idx int, bean interface{}) error { return handler(idx, bean, pushLimit) }); err != nil && err != errLimit { log.Error("PushMirrorsIterate: %v", err) diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go index 7a2bc125c..1a1584922 100644 --- a/services/mirror/mirror_pull.go +++ b/services/mirror/mirror_pull.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/lfs" @@ -29,7 +30,7 @@ import ( const gitShortEmptySha = "0000000" // UpdateAddress writes new address to Git repository and database -func UpdateAddress(m *models.Mirror, addr string) error { +func UpdateAddress(m *repo_model.Mirror, addr string) error { remoteName := m.GetRemoteName() repoPath := m.Repo.RepoPath() // Remove old remote @@ -144,7 +145,7 @@ func parseRemoteUpdateOutput(output string) []*mirrorSyncResult { } func pruneBrokenReferences(ctx context.Context, - m *models.Mirror, + m *repo_model.Mirror, repoPath string, timeout time.Duration, stdoutBuilder, stderrBuilder *strings.Builder, @@ -181,7 +182,7 @@ func pruneBrokenReferences(ctx context.Context, } // runSync returns true if sync finished without error. -func runSync(ctx context.Context, m *models.Mirror) ([]*mirrorSyncResult, bool) { +func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bool) { repoPath := m.Repo.RepoPath() wikiPath := m.Repo.WikiPath() timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second @@ -271,7 +272,7 @@ func runSync(ctx context.Context, m *models.Mirror) ([]*mirrorSyncResult, bool) gitRepo.Close() log.Trace("SyncMirrors [repo: %-v]: updating size of repository", m.Repo) - if err := m.Repo.UpdateSize(db.DefaultContext); err != nil { + if err := models.UpdateRepoSize(db.DefaultContext, m.Repo); err != nil { log.Error("Failed to update size for mirror repository: %v", err) } @@ -362,7 +363,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool { log.Error("PANIC whilst syncMirrors[%d] Panic: %v\nStacktrace: %s", repoID, err, log.Stack(2)) }() - m, err := models.GetMirrorByRepoID(repoID) + m, err := repo_model.GetMirrorByRepoID(repoID) if err != nil { log.Error("GetMirrorByRepoID [%d]: %v", repoID, err) return false @@ -379,7 +380,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool { log.Trace("SyncMirrors [repo: %-v]: Scheduling next update", m.Repo) m.ScheduleNextUpdate() - if err = models.UpdateMirror(m); err != nil { + if err = repo_model.UpdateMirror(m); err != nil { log.Error("UpdateMirror [%d]: %v", m.RepoID, err) return false } @@ -485,7 +486,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool { return true } -func checkAndUpdateEmptyRepository(m *models.Mirror, gitRepo *git.Repository, results []*mirrorSyncResult) bool { +func checkAndUpdateEmptyRepository(m *repo_model.Mirror, gitRepo *git.Repository, results []*mirrorSyncResult) bool { if !m.Repo.IsEmpty { return true } diff --git a/services/mirror/mirror_push.go b/services/mirror/mirror_push.go index cf205e7b5..e1c395ea7 100644 --- a/services/mirror/mirror_push.go +++ b/services/mirror/mirror_push.go @@ -12,7 +12,7 @@ import ( "regexp" "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/lfs" "code.gitea.io/gitea/modules/log" @@ -26,7 +26,7 @@ import ( var stripExitStatus = regexp.MustCompile(`exit status \d+ - `) // AddPushMirrorRemote registers the push mirror remote. -func AddPushMirrorRemote(m *models.PushMirror, addr string) error { +func AddPushMirrorRemote(m *repo_model.PushMirror, addr string) error { addRemoteAndConfig := func(addr, path string) error { if _, err := git.NewCommand("remote", "add", "--mirror=push", m.RemoteName, addr).RunInDir(path); err != nil { return err @@ -57,7 +57,7 @@ func AddPushMirrorRemote(m *models.PushMirror, addr string) error { } // RemovePushMirrorRemote removes the push mirror remote. -func RemovePushMirrorRemote(m *models.PushMirror) error { +func RemovePushMirrorRemote(m *repo_model.PushMirror) error { cmd := git.NewCommand("remote", "rm", m.RemoteName) if _, err := cmd.RunInDir(m.Repo.RepoPath()); err != nil { @@ -86,7 +86,7 @@ func SyncPushMirror(ctx context.Context, mirrorID int64) bool { log.Error("PANIC whilst syncPushMirror[%d] Panic: %v\nStacktrace: %s", mirrorID, err, log.Stack(2)) }() - m, err := models.GetPushMirrorByID(mirrorID) + m, err := repo_model.GetPushMirrorByID(mirrorID) if err != nil { log.Error("GetPushMirrorByID [%d]: %v", mirrorID, err) return false @@ -106,7 +106,7 @@ func SyncPushMirror(ctx context.Context, mirrorID int64) bool { m.LastUpdateUnix = timeutil.TimeStampNow() - if err := models.UpdatePushMirror(m); err != nil { + if err := repo_model.UpdatePushMirror(m); err != nil { log.Error("UpdatePushMirror [%d]: %v", m.ID, err) return false @@ -117,7 +117,7 @@ func SyncPushMirror(ctx context.Context, mirrorID int64) bool { return err == nil } -func runPushSync(ctx context.Context, m *models.PushMirror) error { +func runPushSync(ctx context.Context, m *repo_model.PushMirror) error { timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second performPush := func(path string) error { diff --git a/services/org/org.go b/services/org/org.go index 834c6e5ab..4c0cfe87f 100644 --- a/services/org/org.go +++ b/services/org/org.go @@ -9,6 +9,7 @@ import ( "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" "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/util" @@ -23,7 +24,7 @@ func DeleteOrganization(org *models.Organization) error { defer commiter.Close() // Check ownership of repository. - count, err := models.GetRepositoryCount(ctx, org.ID) + count, err := repo_model.GetRepositoryCount(ctx, org.ID) if err != nil { return fmt.Errorf("GetRepositoryCount: %v", err) } else if count > 0 { diff --git a/services/pull/check.go b/services/pull/check.go index 03d4a3991..363a716b2 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -13,6 +13,8 @@ import ( "strings" "code.gitea.io/gitea/models" + "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" @@ -70,7 +72,7 @@ func checkAndUpdateStatus(pr *models.PullRequest) { func getMergeCommit(pr *models.PullRequest) (*git.Commit, error) { if pr.BaseRepo == nil { var err error - pr.BaseRepo, err = models.GetRepositoryByID(pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(pr.BaseRepoID) if err != nil { return nil, fmt.Errorf("GetRepositoryByID: %v", err) } @@ -165,7 +167,7 @@ func manuallyMerged(pr *models.PullRequest) bool { // When the commit author is unknown set the BaseRepo owner as merger if merger == nil { if pr.BaseRepo.Owner == nil { - if err = pr.BaseRepo.GetOwner(); err != nil { + if err = pr.BaseRepo.GetOwner(db.DefaultContext); err != nil { log.Error("BaseRepo.GetOwner[%d]: %v", pr.ID, err) return false } @@ -240,7 +242,7 @@ func handle(data ...queue.Data) { } // CheckPrsForBaseBranch check all pulls with bseBrannch -func CheckPrsForBaseBranch(baseRepo *models.Repository, baseBranchName string) error { +func CheckPrsForBaseBranch(baseRepo *repo_model.Repository, baseBranchName string) error { prs, err := models.GetUnmergedPullRequestsByBaseInfo(baseRepo.ID, baseBranchName) if err != nil { return err diff --git a/services/pull/lfs.go b/services/pull/lfs.go index b902c6361..c9ec415cb 100644 --- a/services/pull/lfs.go +++ b/services/pull/lfs.go @@ -114,7 +114,7 @@ func createLFSMetaObjectsFromCatFileBatch(catFileBatchReader *io.PipeReader, wg } // Then we need to check that this pointer is in the db - if _, err := pr.HeadRepo.GetLFSMetaObjectByOid(pointer.Oid); err != nil { + if _, err := models.GetLFSMetaObjectByOid(pr.HeadRepo.ID, pointer.Oid); err != nil { if err == models.ErrLFSObjectNotExist { log.Warn("During merge of: %d in %-v, there is a pointer to LFS Oid: %s which although present in the LFS store is not associated with the head repo %-v", pr.Index, pr.BaseRepo, pointer.Oid, pr.HeadRepo) continue diff --git a/services/pull/merge.go b/services/pull/merge.go index 75c089eee..49050d6be 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -16,6 +16,8 @@ import ( "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/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/cache" @@ -31,7 +33,7 @@ import ( // Merge merges pull request to base repository. // Caller should check PR is ready to be merged (review and status checks) // FIXME: add repoWorkingPull make sure two merges does not happen at same time. -func Merge(pr *models.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, mergeStyle models.MergeStyle, message string) (err error) { +func Merge(pr *models.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, mergeStyle repo_model.MergeStyle, message string) (err error) { if err = pr.LoadHeadRepo(); err != nil { log.Error("LoadHeadRepo: %v", err) return fmt.Errorf("LoadHeadRepo: %v", err) @@ -76,7 +78,7 @@ func Merge(pr *models.PullRequest, doer *user_model.User, baseGitRepo *git.Repos if err := pr.Issue.LoadRepo(); err != nil { log.Error("loadRepo for issue [%d]: %v", pr.ID, err) } - if err := pr.Issue.Repo.GetOwner(); err != nil { + if err := pr.Issue.Repo.GetOwner(db.DefaultContext); err != nil { log.Error("GetOwner for issue repo [%d]: %v", pr.ID, err) } @@ -111,7 +113,7 @@ func Merge(pr *models.PullRequest, doer *user_model.User, baseGitRepo *git.Repos } // rawMerge perform the merge operation without changing any pull information in database -func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.MergeStyle, message string) (string, error) { +func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle repo_model.MergeStyle, message string) (string, error) { err := git.LoadGitVersion() if err != nil { log.Error("git.LoadGitVersion: %v", err) @@ -219,7 +221,7 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M sign, keyID, signer, _ := pr.SignMerge(doer, tmpBasePath, "HEAD", trackingBranch) if sign { signArg = "-S" + keyID - if pr.BaseRepo.GetTrustModel() == models.CommitterTrustModel || pr.BaseRepo.GetTrustModel() == models.CollaboratorCommitterTrustModel { + if pr.BaseRepo.GetTrustModel() == repo_model.CommitterTrustModel || pr.BaseRepo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel { committer = signer } } else if git.CheckGitVersionAtLeast("2.0.0") == nil { @@ -241,7 +243,7 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M // Merge commits. switch mergeStyle { - case models.MergeStyleMerge: + case repo_model.MergeStyleMerge: cmd := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch) if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { log.Error("Unable to merge tracking into base: %v", err) @@ -252,11 +254,11 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M log.Error("Unable to make final commit: %v", err) return "", err } - case models.MergeStyleRebase: + case repo_model.MergeStyleRebase: fallthrough - case models.MergeStyleRebaseUpdate: + case repo_model.MergeStyleRebaseUpdate: fallthrough - case models.MergeStyleRebaseMerge: + case repo_model.MergeStyleRebaseMerge: // Checkout head branch if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { log.Error("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String()) @@ -309,7 +311,7 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M errbuf.Reset() // not need merge, just update by rebase. so skip - if mergeStyle == models.MergeStyleRebaseUpdate { + if mergeStyle == repo_model.MergeStyleRebaseUpdate { break } @@ -322,7 +324,7 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M errbuf.Reset() cmd := git.NewCommand("merge") - if mergeStyle == models.MergeStyleRebase { + if mergeStyle == repo_model.MergeStyleRebase { cmd.AddArguments("--ff-only") } else { cmd.AddArguments("--no-ff", "--no-commit") @@ -334,13 +336,13 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M log.Error("Unable to merge staging into base: %v", err) return "", err } - if mergeStyle == models.MergeStyleRebaseMerge { + if mergeStyle == repo_model.MergeStyleRebaseMerge { if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil { log.Error("Unable to make final commit: %v", err) return "", err } } - case models.MergeStyleSquash: + case repo_model.MergeStyleSquash: // Merge with squash cmd := git.NewCommand("merge", "--squash", trackingBranch) if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { @@ -398,7 +400,7 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M } var headUser *user_model.User - err = pr.HeadRepo.GetOwner() + err = pr.HeadRepo.GetOwner(db.DefaultContext) if err != nil { if !user_model.IsErrUserNotExist(err) { log.Error("Can't find user: %d for head repository - %v", pr.HeadRepo.OwnerID, err) @@ -419,7 +421,7 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M ) var pushCmd *git.Command - if mergeStyle == models.MergeStyleRebaseUpdate { + if mergeStyle == repo_model.MergeStyleRebaseUpdate { // force push the rebase result to head brach pushCmd = git.NewCommand("push", "-f", "head_repo", stagingBranch+":"+git.BranchPrefix+pr.HeadBranch) } else { @@ -467,7 +469,7 @@ func commitAndSignNoAuthor(pr *models.PullRequest, message, signArg, tmpBasePath return nil } -func runMergeCommand(pr *models.PullRequest, mergeStyle models.MergeStyle, cmd *git.Command, tmpBasePath string) error { +func runMergeCommand(pr *models.PullRequest, mergeStyle repo_model.MergeStyle, cmd *git.Command, tmpBasePath string) error { var outbuf, errbuf strings.Builder if err := cmd.RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { // Merge will leave a MERGE_HEAD file in the .git folder if there is a conflict @@ -567,7 +569,7 @@ func IsUserAllowedToMerge(pr *models.PullRequest, p models.Permission, user *use return false, err } - if (p.CanWrite(unit.TypeCode) && pr.ProtectedBranch == nil) || (pr.ProtectedBranch != nil && pr.ProtectedBranch.IsUserMergeWhitelisted(user.ID, p)) { + if (p.CanWrite(unit.TypeCode) && pr.ProtectedBranch == nil) || (pr.ProtectedBranch != nil && models.IsUserMergeWhitelisted(pr.ProtectedBranch, user.ID, p)) { return true, nil } @@ -641,8 +643,8 @@ func MergedManually(pr *models.PullRequest, doer *user_model.User, baseGitRepo * prConfig := prUnit.PullRequestsConfig() // Check if merge style is correct and allowed - if !prConfig.IsMergeStyleAllowed(models.MergeStyleManuallyMerged) { - return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: models.MergeStyleManuallyMerged} + if !prConfig.IsMergeStyleAllowed(repo_model.MergeStyleManuallyMerged) { + return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: repo_model.MergeStyleManuallyMerged} } if len(commitID) < 40 { diff --git a/services/pull/pull.go b/services/pull/pull.go index 8bfe20c80..474c21162 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -15,6 +15,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/graceful" @@ -26,7 +27,7 @@ import ( ) // NewPullRequest creates new pull request with labels for repository. -func NewPullRequest(repo *models.Repository, pull *models.Issue, labelIDs []int64, uuids []string, pr *models.PullRequest, assigneeIDs []int64) error { +func NewPullRequest(repo *repo_model.Repository, pull *models.Issue, labelIDs []int64, uuids []string, pr *models.PullRequest, assigneeIDs []int64) error { if err := TestPatch(pr); err != nil { return err } @@ -211,7 +212,7 @@ func ChangeTargetBranch(pr *models.PullRequest, doer *user_model.User, targetBra } func checkForInvalidation(requests models.PullRequestList, repoID int64, doer *user_model.User, branch string) error { - repo, err := models.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(repoID) if err != nil { return fmt.Errorf("GetRepositoryByID: %v", err) } @@ -524,7 +525,7 @@ func CloseBranchPulls(doer *user_model.User, repoID int64, branch string) error } // CloseRepoBranchesPulls close all pull requests which head branches are in the given repository, but only whose base repo is not in the given repository -func CloseRepoBranchesPulls(doer *user_model.User, repo *models.Repository) error { +func CloseRepoBranchesPulls(doer *user_model.User, repo *repo_model.Repository) error { branches, _, err := git.GetBranchesByPath(repo.RepoPath(), 0, 0) if err != nil { return err @@ -575,7 +576,7 @@ func GetSquashMergeCommitMessages(pr *models.PullRequest) string { if pr.HeadRepo == nil { var err error - pr.HeadRepo, err = models.GetRepositoryByID(pr.HeadRepoID) + pr.HeadRepo, err = repo_model.GetRepositoryByID(pr.HeadRepoID) if err != nil { log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err) return "" diff --git a/services/pull/review.go b/services/pull/review.go index 31c2e9978..3f2e4bdf5 100644 --- a/services/pull/review.go +++ b/services/pull/review.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -115,7 +116,7 @@ func CreateCodeComment(doer *user_model.User, gitRepo *git.Repository, issue *mo var notEnoughLines = regexp.MustCompile(`exit status 128 - fatal: file .* has only \d+ lines?`) // createCodeComment creates a plain code comment at the specified line / path -func createCodeComment(doer *user_model.User, repo *models.Repository, issue *models.Issue, content, treePath string, line, reviewID int64) (*models.Comment, error) { +func createCodeComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, content, treePath string, line, reviewID int64) (*models.Comment, error) { var commitID, patch string if err := issue.LoadPullRequest(); err != nil { return nil, fmt.Errorf("GetPullRequestByIssueID: %v", err) diff --git a/services/pull/temp_repo.go b/services/pull/temp_repo.go index e30dba7ad..d5dc8a5c4 100644 --- a/services/pull/temp_repo.go +++ b/services/pull/temp_repo.go @@ -12,6 +12,8 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" ) @@ -24,7 +26,7 @@ func createTemporaryRepo(pr *models.PullRequest) (string, error) { return "", fmt.Errorf("LoadHeadRepo: %v", err) } else if pr.HeadRepo == nil { log.Error("Pr %d HeadRepo %d does not exist", pr.ID, pr.HeadRepoID) - return "", &models.ErrRepoNotExist{ + return "", &repo_model.ErrRepoNotExist{ ID: pr.HeadRepoID, } } else if err := pr.LoadBaseRepo(); err != nil { @@ -32,13 +34,13 @@ func createTemporaryRepo(pr *models.PullRequest) (string, error) { return "", fmt.Errorf("LoadBaseRepo: %v", err) } else if pr.BaseRepo == nil { log.Error("Pr %d BaseRepo %d does not exist", pr.ID, pr.BaseRepoID) - return "", &models.ErrRepoNotExist{ + return "", &repo_model.ErrRepoNotExist{ ID: pr.BaseRepoID, } - } else if err := pr.HeadRepo.GetOwner(); err != nil { + } else if err := pr.HeadRepo.GetOwner(db.DefaultContext); err != nil { log.Error("HeadRepo.GetOwner: %v", err) return "", fmt.Errorf("HeadRepo.GetOwner: %v", err) - } else if err := pr.BaseRepo.GetOwner(); err != nil { + } else if err := pr.BaseRepo.GetOwner(db.DefaultContext); err != nil { log.Error("BaseRepo.GetOwner: %v", err) return "", fmt.Errorf("BaseRepo.GetOwner: %v", err) } diff --git a/services/pull/update.go b/services/pull/update.go index ef6e84598..25c6d3630 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -8,6 +8,7 @@ import ( "fmt" "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/git" "code.gitea.io/gitea/modules/log" @@ -17,12 +18,12 @@ import ( func Update(pull *models.PullRequest, doer *user_model.User, message string, rebase bool) error { var ( pr *models.PullRequest - style models.MergeStyle + style repo_model.MergeStyle ) if rebase { pr = pull - style = models.MergeStyleRebaseUpdate + style = repo_model.MergeStyleRebaseUpdate } else { //use merge functions but switch repo's and branch's pr = &models.PullRequest{ @@ -31,7 +32,7 @@ func Update(pull *models.PullRequest, doer *user_model.User, message string, reb HeadBranch: pull.BaseBranch, BaseBranch: pull.HeadBranch, } - style = models.MergeStyleMerge + style = repo_model.MergeStyleMerge } if pull.Flow == models.PullRequestFlowAGit { diff --git a/services/release/release.go b/services/release/release.go index ec1494d42..e20b91ece 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -31,7 +31,7 @@ func createTag(gitRepo *git.Repository, rel *models.Release, msg string) (bool, return false, err } - protectedTags, err := rel.Repo.GetProtectedTags() + protectedTags, err := models.GetProtectedTags(rel.Repo.ID) if err != nil { return false, fmt.Errorf("GetProtectedTags: %v", err) } @@ -137,7 +137,7 @@ func CreateRelease(gitRepo *git.Repository, rel *models.Release, attachmentUUIDs } // CreateNewTag creates a new repository tag -func CreateNewTag(doer *user_model.User, repo *models.Repository, commit, tagName, msg string) error { +func CreateNewTag(doer *user_model.User, repo *repo_model.Repository, commit, tagName, msg string) error { isExist, err := models.IsReleaseExist(repo.ID, tagName) if err != nil { return err @@ -285,7 +285,7 @@ func DeleteReleaseByID(id int64, doer *user_model.User, delTag bool) error { return fmt.Errorf("GetReleaseByID: %v", err) } - repo, err := models.GetRepositoryByID(rel.RepoID) + repo, err := repo_model.GetRepositoryByID(rel.RepoID) if err != nil { return fmt.Errorf("GetRepositoryByID: %v", err) } diff --git a/services/release/release_test.go b/services/release/release_test.go index 29ff78ca3..b41eea7e9 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -28,8 +28,8 @@ func TestRelease_Create(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) 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) gitRepo, err := git.OpenRepository(repoPath) assert.NoError(t, err) @@ -132,8 +132,8 @@ func TestRelease_Update(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) 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) gitRepo, err := git.OpenRepository(repoPath) assert.NoError(t, err) @@ -274,8 +274,8 @@ func TestRelease_createTag(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) 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) gitRepo, err := git.OpenRepository(repoPath) assert.NoError(t, err) @@ -356,7 +356,7 @@ func TestRelease_createTag(t *testing.T) { func TestCreateNewTag(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) 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) assert.NoError(t, CreateNewTag(user, repo, "master", "v2.0", "v2.0 is released \n\n BUGFIX: .... \n\n 123")) diff --git a/services/repository/adopt.go b/services/repository/adopt.go index 5503155ab..d5b851d10 100644 --- a/services/repository/adopt.go +++ b/services/repository/adopt.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -25,7 +26,7 @@ import ( ) // AdoptRepository adopts pre-existing repository files for the user/organization. -func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (*models.Repository, error) { +func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (*repo_model.Repository, error) { if !doer.IsAdmin && !u.CanCreateRepo() { return nil, models.ErrReachLimitOfRepo{ Limit: u.MaxRepoCreation, @@ -36,7 +37,7 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (* opts.DefaultBranch = setting.Repository.DefaultBranch } - repo := &models.Repository{ + repo := &repo_model.Repository{ OwnerID: u.ID, Owner: u, OwnerName: u.Name, @@ -53,14 +54,14 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (* } if err := db.WithTx(func(ctx context.Context) error { - repoPath := models.RepoPath(u.Name, repo.Name) + repoPath := repo_model.RepoPath(u.Name, repo.Name) isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) return err } if !isExist { - return models.ErrRepoNotExist{ + return repo_model.ErrRepoNotExist{ OwnerName: u.Name, Name: repo.Name, } @@ -72,7 +73,7 @@ func AdoptRepository(doer, u *user_model.User, opts models.CreateRepoOptions) (* if err := adoptRepository(ctx, repoPath, doer, repo, opts); err != nil { return fmt.Errorf("createDelegateHooks: %v", err) } - if err := repo.CheckDaemonExportOK(ctx); err != nil { + if err := models.CheckDaemonExportOK(ctx, repo); err != nil { return fmt.Errorf("checkDaemonExportOK: %v", err) } @@ -99,7 +100,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 *models.Repository, opts models.CreateRepoOptions) (err error) { +func adoptRepository(ctx context.Context, repoPath string, u *user_model.User, repo *repo_model.Repository, opts models.CreateRepoOptions) (err error) { isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) @@ -115,7 +116,7 @@ func adoptRepository(ctx context.Context, repoPath string, u *user_model.User, r // Re-fetch the repository from database before updating it (else it would // override changes that were done earlier with sql) - if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %v", err) } @@ -191,20 +192,20 @@ func DeleteUnadoptedRepository(doer, u *user_model.User, repoName string) error return err } - repoPath := models.RepoPath(u.Name, repoName) + repoPath := repo_model.RepoPath(u.Name, repoName) isExist, err := util.IsExist(repoPath) if err != nil { log.Error("Unable to check if %s exists. Error: %v", repoPath, err) return err } if !isExist { - return models.ErrRepoNotExist{ + return repo_model.ErrRepoNotExist{ OwnerName: u.Name, Name: repoName, } } - if exist, err := models.IsRepositoryExist(u, repoName); err != nil { + if exist, err := repo_model.IsRepositoryExist(u, repoName); err != nil { return err } else if exist { return models.ErrRepoAlreadyExist{ diff --git a/services/repository/branch.go b/services/repository/branch.go index 08310134b..e1775fc12 100644 --- a/services/repository/branch.go +++ b/services/repository/branch.go @@ -11,6 +11,7 @@ import ( "strings" "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/git" "code.gitea.io/gitea/modules/log" @@ -20,7 +21,7 @@ import ( ) // CreateNewBranch creates a new repository branch -func CreateNewBranch(doer *user_model.User, repo *models.Repository, oldBranchName, branchName string) (err error) { +func CreateNewBranch(doer *user_model.User, repo *repo_model.Repository, oldBranchName, branchName string) (err error) { // Check if branch name can be used if err := checkBranchName(git.DefaultContext, repo, branchName); err != nil { return err @@ -47,7 +48,7 @@ func CreateNewBranch(doer *user_model.User, repo *models.Repository, oldBranchNa } // GetBranch returns a branch by its name -func GetBranch(repo *models.Repository, branch string) (*git.Branch, error) { +func GetBranch(repo *repo_model.Repository, branch string) (*git.Branch, error) { if len(branch) == 0 { return nil, fmt.Errorf("GetBranch: empty string for branch") } @@ -62,12 +63,12 @@ func GetBranch(repo *models.Repository, branch string) (*git.Branch, error) { // GetBranches returns branches from the repository, skipping skip initial branches and // returning at most limit branches, or all branches if limit is 0. -func GetBranches(repo *models.Repository, skip, limit int) ([]*git.Branch, int, error) { +func GetBranches(repo *repo_model.Repository, skip, limit int) ([]*git.Branch, int, error) { return git.GetBranchesByPath(repo.RepoPath(), skip, limit) } // checkBranchName validates branch name with existing repository branches -func checkBranchName(ctx context.Context, repo *models.Repository, name string) error { +func checkBranchName(ctx context.Context, repo *repo_model.Repository, name string) error { _, err := git.WalkReferences(ctx, repo.RepoPath(), func(refName string) error { branchRefName := strings.TrimPrefix(refName, git.BranchPrefix) switch { @@ -97,7 +98,7 @@ func checkBranchName(ctx context.Context, repo *models.Repository, name string) } // CreateNewBranchFromCommit creates a new repository branch -func CreateNewBranchFromCommit(doer *user_model.User, repo *models.Repository, commit, branchName string) (err error) { +func CreateNewBranchFromCommit(doer *user_model.User, repo *repo_model.Repository, commit, branchName string) (err error) { // Check if branch name can be used if err := checkBranchName(git.DefaultContext, repo, branchName); err != nil { return err @@ -118,7 +119,7 @@ func CreateNewBranchFromCommit(doer *user_model.User, repo *models.Repository, c } // RenameBranch rename a branch -func RenameBranch(repo *models.Repository, doer *user_model.User, gitRepo *git.Repository, from, to string) (string, error) { +func RenameBranch(repo *repo_model.Repository, doer *user_model.User, gitRepo *git.Repository, from, to string) (string, error) { if from == to { return "target_exist", nil } @@ -131,7 +132,7 @@ func RenameBranch(repo *models.Repository, doer *user_model.User, gitRepo *git.R return "from_not_exist", nil } - if err := repo.RenameBranch(from, to, func(isDefault bool) error { + if err := models.RenameBranch(repo, from, to, func(isDefault bool) error { err2 := gitRepo.RenameBranch(from, to) if err2 != nil { return err2 @@ -162,12 +163,12 @@ var ( ) // DeleteBranch delete branch -func DeleteBranch(doer *user_model.User, repo *models.Repository, gitRepo *git.Repository, branchName string) error { +func DeleteBranch(doer *user_model.User, repo *repo_model.Repository, gitRepo *git.Repository, branchName string) error { if branchName == repo.DefaultBranch { return ErrBranchIsDefault } - isProtected, err := repo.IsProtectedBranch(branchName) + isProtected, err := models.IsProtectedBranch(repo.ID, branchName) if err != nil { return err } @@ -205,7 +206,7 @@ func DeleteBranch(doer *user_model.User, repo *models.Repository, gitRepo *git.R log.Error("Update: %v", err) } - if err := repo.AddDeletedBranch(branchName, commit.ID.String(), doer.ID); err != nil { + if err := models.AddDeletedBranch(repo.ID, branchName, commit.ID.String(), doer.ID); err != nil { log.Warn("AddDeletedBranch: %v", err) } diff --git a/services/repository/cache.go b/services/repository/cache.go index e574f1adb..5b0c929be 100644 --- a/services/repository/cache.go +++ b/services/repository/cache.go @@ -8,7 +8,7 @@ import ( "context" "strings" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" @@ -24,7 +24,7 @@ func getRefName(fullRefName string) string { } // CacheRef cachhe last commit information of the branch or the tag -func CacheRef(ctx context.Context, repo *models.Repository, gitRepo *git.Repository, fullRefName string) error { +func CacheRef(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, fullRefName string) error { if !setting.CacheService.LastCommit.Enabled { return nil } diff --git a/services/repository/check.go b/services/repository/check.go index ab7539e55..7118b006b 100644 --- a/services/repository/check.go +++ b/services/repository/check.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -27,10 +28,10 @@ func GitFsck(ctx context.Context, timeout time.Duration, args []string) error { if err := db.Iterate( db.DefaultContext, - new(models.Repository), + new(repo_model.Repository), builder.Expr("id>0 AND is_fsck_enabled=?", true), func(idx int, bean interface{}) error { - repo := bean.(*models.Repository) + repo := bean.(*repo_model.Repository) select { case <-ctx.Done(): return db.ErrCancelledf("before fsck of %s", repo.FullName()) @@ -62,10 +63,10 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro if err := db.Iterate( db.DefaultContext, - new(models.Repository), + new(repo_model.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { - repo := bean.(*models.Repository) + repo := bean.(*repo_model.Repository) select { case <-ctx.Done(): return db.ErrCancelledf("before GC of %s", repo.FullName()) @@ -96,7 +97,7 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro } // Now update the size of the repository - if err := repo.UpdateSize(db.DefaultContext); err != nil { + if err := models.UpdateRepoSize(db.DefaultContext, repo); err != nil { log.Error("Updating size as part of garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err) desc := fmt.Sprintf("Updating size as part of garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) if err = admin_model.CreateRepositoryNotice(desc); err != nil { @@ -115,14 +116,14 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...string) erro return nil } -func gatherMissingRepoRecords(ctx context.Context) ([]*models.Repository, error) { - repos := make([]*models.Repository, 0, 10) +func gatherMissingRepoRecords(ctx context.Context) ([]*repo_model.Repository, error) { + repos := make([]*repo_model.Repository, 0, 10) if err := db.Iterate( db.DefaultContext, - new(models.Repository), + new(repo_model.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { - repo := bean.(*models.Repository) + repo := bean.(*repo_model.Repository) select { case <-ctx.Done(): return db.ErrCancelledf("during gathering missing repo records before checking %s", repo.FullName()) diff --git a/services/repository/files/commit.go b/services/repository/files/commit.go index 8f14ed892..6bff1bb97 100644 --- a/services/repository/files/commit.go +++ b/services/repository/files/commit.go @@ -8,6 +8,7 @@ import ( "fmt" "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/git" "code.gitea.io/gitea/modules/structs" @@ -16,7 +17,7 @@ import ( // CreateCommitStatus creates a new CommitStatus given a bunch of parameters // NOTE: All text-values will be trimmed from whitespaces. // Requires: Repo, Creator, SHA -func CreateCommitStatus(repo *models.Repository, creator *user_model.User, sha string, status *models.CommitStatus) error { +func CreateCommitStatus(repo *repo_model.Repository, creator *user_model.User, sha string, status *models.CommitStatus) error { repoPath := repo.RepoPath() // confirm that commit is exist @@ -43,7 +44,7 @@ func CreateCommitStatus(repo *models.Repository, creator *user_model.User, sha s } // CountDivergingCommits determines how many commits a branch is ahead or behind the repository's base branch -func CountDivergingCommits(repo *models.Repository, branch string) (*git.DivergeObject, error) { +func CountDivergingCommits(repo *repo_model.Repository, branch string) (*git.DivergeObject, error) { divergence, err := git.GetDivergingCommits(repo.RepoPath(), repo.DefaultBranch, branch) if err != nil { return nil, err diff --git a/services/repository/files/content.go b/services/repository/files/content.go index afb775fed..10461c82a 100644 --- a/services/repository/files/content.go +++ b/services/repository/files/content.go @@ -11,6 +11,7 @@ import ( "strings" "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" @@ -38,7 +39,7 @@ func (ct *ContentType) String() string { // GetContentsOrList gets the meta data of a file's contents (*ContentsResponse) if treePath not a tree // directory, otherwise a listing of file contents ([]*ContentsResponse). Ref can be a branch, commit or tag -func GetContentsOrList(repo *models.Repository, treePath, ref string) (interface{}, error) { +func GetContentsOrList(repo *repo_model.Repository, treePath, ref string) (interface{}, error) { if repo.IsEmpty { return make([]interface{}, 0), nil } @@ -100,7 +101,7 @@ func GetContentsOrList(repo *models.Repository, treePath, ref string) (interface } // GetContents gets the meta data on a file's contents. Ref can be a branch, commit or tag -func GetContents(repo *models.Repository, treePath, ref string, forList bool) (*api.ContentsResponse, error) { +func GetContents(repo *repo_model.Repository, treePath, ref string, forList bool) (*api.ContentsResponse, error) { if ref == "" { ref = repo.DefaultBranch } @@ -218,7 +219,7 @@ func GetContents(repo *models.Repository, treePath, ref string, forList bool) (* } // GetBlobBySHA get the GitBlobResponse of a repository using a sha hash. -func GetBlobBySHA(repo *models.Repository, sha string) (*api.GitBlobResponse, error) { +func GetBlobBySHA(repo *repo_model.Repository, sha string) (*api.GitBlobResponse, error) { gitRepo, err := git.OpenRepository(repo.RepoPath()) if err != nil { return nil, err diff --git a/services/repository/files/delete.go b/services/repository/files/delete.go index f7b342db3..15208addd 100644 --- a/services/repository/files/delete.go +++ b/services/repository/files/delete.go @@ -9,6 +9,7 @@ import ( "strings" "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/git" api "code.gitea.io/gitea/modules/structs" @@ -30,7 +31,7 @@ type DeleteRepoFileOptions struct { } // DeleteRepoFile deletes a file in the given repository -func DeleteRepoFile(repo *models.Repository, doer *user_model.User, opts *DeleteRepoFileOptions) (*api.FileResponse, error) { +func DeleteRepoFile(repo *repo_model.Repository, doer *user_model.User, opts *DeleteRepoFileOptions) (*api.FileResponse, error) { // If no branch name is set, assume the repo's default branch if opts.OldBranch == "" { opts.OldBranch = repo.DefaultBranch diff --git a/services/repository/files/diff.go b/services/repository/files/diff.go index fadaf2023..fb41237e1 100644 --- a/services/repository/files/diff.go +++ b/services/repository/files/diff.go @@ -7,12 +7,12 @@ package files import ( "strings" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/services/gitdiff" ) // GetDiffPreview produces and returns diff result of a file which is not yet committed. -func GetDiffPreview(repo *models.Repository, branch, treePath, content string) (*gitdiff.Diff, error) { +func GetDiffPreview(repo *repo_model.Repository, branch, treePath, content string) (*gitdiff.Diff, error) { if branch == "" { branch = repo.DefaultBranch } diff --git a/services/repository/files/diff_test.go b/services/repository/files/diff_test.go index be8e92033..2f256e888 100644 --- a/services/repository/files/diff_test.go +++ b/services/repository/files/diff_test.go @@ -7,7 +7,7 @@ package files 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" "code.gitea.io/gitea/modules/test" @@ -152,7 +152,7 @@ func TestGetDiffPreviewErrors(t *testing.T) { content := "# repo1\n\nDescription for repo1\nthis is a new line" t.Run("empty repo", func(t *testing.T) { - diff, err := GetDiffPreview(&models.Repository{}, branch, treePath, content) + diff, err := GetDiffPreview(&repo_model.Repository{}, branch, treePath, content) assert.Nil(t, diff) assert.EqualError(t, err, "repository does not exist [id: 0, uid: 0, owner_name: , name: ]") }) diff --git a/services/repository/files/file.go b/services/repository/files/file.go index 8de60c4cb..788611958 100644 --- a/services/repository/files/file.go +++ b/services/repository/files/file.go @@ -11,14 +11,14 @@ import ( "strings" "time" - "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/git" api "code.gitea.io/gitea/modules/structs" ) // GetFileResponseFromCommit Constructs a FileResponse from a Commit object -func GetFileResponseFromCommit(repo *models.Repository, commit *git.Commit, branch, treeName string) (*api.FileResponse, error) { +func GetFileResponseFromCommit(repo *repo_model.Repository, commit *git.Commit, branch, treeName string) (*api.FileResponse, error) { fileContents, _ := GetContents(repo, treeName, branch, false) // ok if fails, then will be nil fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil verification := GetPayloadCommitVerification(commit) @@ -31,7 +31,7 @@ func GetFileResponseFromCommit(repo *models.Repository, commit *git.Commit, bran } // GetFileCommitResponse Constructs a FileCommitResponse from a Commit object -func GetFileCommitResponse(repo *models.Repository, commit *git.Commit) (*api.FileCommitResponse, error) { +func GetFileCommitResponse(repo *repo_model.Repository, commit *git.Commit) (*api.FileCommitResponse, error) { if repo == nil { return nil, fmt.Errorf("repo cannot be nil") } diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go index 55dcd7436..815aa2c69 100644 --- a/services/repository/files/temp_repo.go +++ b/services/repository/files/temp_repo.go @@ -15,6 +15,7 @@ import ( "time" "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/git" "code.gitea.io/gitea/modules/log" @@ -24,13 +25,13 @@ import ( // TemporaryUploadRepository is a type to wrap our upload repositories as a shallow clone type TemporaryUploadRepository struct { - repo *models.Repository + repo *repo_model.Repository gitRepo *git.Repository basePath string } // NewTemporaryUploadRepository creates a new temporary upload repository -func NewTemporaryUploadRepository(repo *models.Repository) (*TemporaryUploadRepository, error) { +func NewTemporaryUploadRepository(repo *repo_model.Repository) (*TemporaryUploadRepository, error) { basePath, err := models.CreateTemporaryPath("upload") if err != nil { return nil, err @@ -56,7 +57,7 @@ func (t *TemporaryUploadRepository) Clone(branch string) error { Name: branch, } } else if matched, _ := regexp.MatchString(".* repository .* does not exist.*", stderr); matched { - return models.ErrRepoNotExist{ + return repo_model.ErrRepoNotExist{ ID: t.repo.ID, UID: t.repo.OwnerID, OwnerName: t.repo.OwnerName, @@ -216,10 +217,10 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *user_m // Determine if we should sign if git.CheckGitVersionAtLeast("1.7.9") == nil { - sign, keyID, signer, _ := t.repo.SignCRUDAction(author, t.basePath, "HEAD") + sign, keyID, signer, _ := models.SignCRUDAction(t.repo, author, t.basePath, "HEAD") if sign { args = append(args, "-S"+keyID) - if t.repo.GetTrustModel() == models.CommitterTrustModel || t.repo.GetTrustModel() == models.CollaboratorCommitterTrustModel { + if t.repo.GetTrustModel() == repo_model.CommitterTrustModel || t.repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel { if committerSig.Name != authorSig.Name || committerSig.Email != authorSig.Email { // Add trailers _, _ = messageBytes.WriteString("\n") diff --git a/services/repository/files/tree.go b/services/repository/files/tree.go index ede206274..c6b77355e 100644 --- a/services/repository/files/tree.go +++ b/services/repository/files/tree.go @@ -9,13 +9,14 @@ import ( "net/url" "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" ) // GetTreeBySHA get the GitTreeResponse of a repository using a sha hash. -func GetTreeBySHA(repo *models.Repository, sha string, page, perPage int, recursive bool) (*api.GitTreeResponse, error) { +func GetTreeBySHA(repo *repo_model.Repository, sha string, page, perPage int, recursive bool) (*api.GitTreeResponse, error) { gitRepo, err := git.OpenRepository(repo.RepoPath()) if err != nil { return nil, err diff --git a/services/repository/files/update.go b/services/repository/files/update.go index eeb98f363..9a069acbf 100644 --- a/services/repository/files/update.go +++ b/services/repository/files/update.go @@ -12,6 +12,7 @@ import ( "time" "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/charset" "code.gitea.io/gitea/modules/git" @@ -55,7 +56,7 @@ type UpdateRepoFileOptions struct { Signoff bool } -func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string, bool) { +func detectEncodingAndBOM(entry *git.TreeEntry, repo *repo_model.Repository) (string, bool) { reader, err := entry.Blob().DataAsync() if err != nil { // return default @@ -73,7 +74,7 @@ func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string if setting.LFS.StartServer { pointer, _ := lfs.ReadPointerFromBuffer(buf) if pointer.IsValid() { - meta, err := repo.GetLFSMetaObjectByOid(pointer.Oid) + meta, err := models.GetLFSMetaObjectByOid(repo.ID, pointer.Oid) if err != nil && err != models.ErrLFSObjectNotExist { // return default return "UTF-8", false @@ -123,7 +124,7 @@ func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string } // CreateOrUpdateRepoFile adds or updates a file in the given repository -func CreateOrUpdateRepoFile(repo *models.Repository, doer *user_model.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) { +func CreateOrUpdateRepoFile(repo *repo_model.Repository, doer *user_model.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) { // If no branch name is set, assume default branch if opts.OldBranch == "" { opts.OldBranch = repo.DefaultBranch @@ -413,7 +414,7 @@ func CreateOrUpdateRepoFile(repo *models.Repository, doer *user_model.User, opts } if !exist { if err := contentStore.Put(lfsMetaObject.Pointer, strings.NewReader(opts.Content)); err != nil { - if _, err2 := repo.RemoveLFSMetaObjectByOid(lfsMetaObject.Oid); err2 != nil { + if _, err2 := models.RemoveLFSMetaObjectByOid(repo.ID, lfsMetaObject.Oid); err2 != nil { return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %v)", lfsMetaObject.Oid, err2, err) } return nil, err @@ -440,8 +441,8 @@ func CreateOrUpdateRepoFile(repo *models.Repository, doer *user_model.User, opts } // VerifyBranchProtection verify the branch protection for modifying the given treePath on the given branch -func VerifyBranchProtection(repo *models.Repository, doer *user_model.User, branchName string, treePath string) error { - protectedBranch, err := repo.GetBranchProtection(branchName) +func VerifyBranchProtection(repo *repo_model.Repository, doer *user_model.User, branchName string, treePath string) error { + protectedBranch, err := models.GetProtectedBranchBy(repo.ID, branchName) if err != nil { return err } @@ -457,7 +458,7 @@ func VerifyBranchProtection(repo *models.Repository, doer *user_model.User, bran } } if protectedBranch.RequireSignedCommits { - _, _, _, err := repo.SignCRUDAction(doer, repo.RepoPath(), branchName) + _, _, _, err := models.SignCRUDAction(repo, doer, repo.RepoPath(), branchName) if err != nil { if !models.IsErrWontSign(err) { return err diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index 7a0ea3108..5e9c93611 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -11,6 +11,7 @@ import ( "strings" "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/git" "code.gitea.io/gitea/modules/lfs" @@ -39,7 +40,7 @@ func cleanUpAfterFailure(infos *[]uploadInfo, t *TemporaryUploadRepository, orig continue } if !info.lfsMetaObject.Existing { - if _, err := t.repo.RemoveLFSMetaObjectByOid(info.lfsMetaObject.Oid); err != nil { + if _, err := models.RemoveLFSMetaObjectByOid(t.repo.ID, info.lfsMetaObject.Oid); err != nil { original = fmt.Errorf("%v, %v", original, err) } } @@ -48,7 +49,7 @@ func cleanUpAfterFailure(infos *[]uploadInfo, t *TemporaryUploadRepository, orig } // UploadRepoFiles uploads files to the given repository -func UploadRepoFiles(repo *models.Repository, doer *user_model.User, opts *UploadRepoFileOptions) error { +func UploadRepoFiles(repo *repo_model.Repository, doer *user_model.User, opts *UploadRepoFileOptions) error { if len(opts.Files) == 0 { return nil } @@ -63,7 +64,7 @@ func UploadRepoFiles(repo *models.Repository, doer *user_model.User, opts *Uploa for i, upload := range uploads { // Check file is not lfs locked, will return nil if lock setting not enabled filepath := path.Join(opts.TreePath, upload.Name) - lfsLock, err := repo.GetTreePathLock(filepath) + lfsLock, err := models.GetTreePathLock(repo.ID, filepath) if err != nil { return err } diff --git a/services/repository/fork.go b/services/repository/fork.go index 3fc08b498..027877cfd 100644 --- a/services/repository/fork.go +++ b/services/repository/fork.go @@ -12,6 +12,7 @@ import ( "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" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -22,8 +23,8 @@ import ( ) // ForkRepository forks a repository -func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) (_ *models.Repository, err error) { - forkedRepo, err := opts.BaseRepo.GetUserFork(owner.ID) +func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) (_ *repo_model.Repository, err error) { + forkedRepo, err := models.GetUserFork(opts.BaseRepo.ID, owner.ID) if err != nil { return nil, err } @@ -35,7 +36,7 @@ func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) ( } } - repo := &models.Repository{ + repo := &repo_model.Repository{ OwnerID: owner.ID, Owner: owner, OwnerName: owner.Name, @@ -57,7 +58,7 @@ func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) ( return } - repoPath := models.RepoPath(owner.Name, repo.Name) + repoPath := repo_model.RepoPath(owner.Name, repo.Name) if exists, _ := util.IsExist(repoPath); !exists { return @@ -99,7 +100,7 @@ func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) ( needsRollback = true - repoPath := models.RepoPath(owner.Name, repo.Name) + repoPath := repo_model.RepoPath(owner.Name, repo.Name) if stdout, err := git.NewCommandContext(ctx, "clone", "--bare", oldRepoPath, repoPath). SetDescription(fmt.Sprintf("ForkRepository(git clone): %s to %s", opts.BaseRepo.FullName(), repo.FullName())). @@ -108,7 +109,7 @@ func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) ( return fmt.Errorf("git clone: %v", err) } - if err := repo.CheckDaemonExportOK(ctx); err != nil { + if err := models.CheckDaemonExportOK(ctx, repo); err != nil { return fmt.Errorf("checkDaemonExportOK: %v", err) } @@ -131,11 +132,10 @@ func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) ( } // even if below operations failed, it could be ignored. And they will be retried - ctx := db.DefaultContext - if err := repo.UpdateSize(ctx); err != nil { + if err := models.UpdateRepoSize(db.DefaultContext, repo); err != nil { log.Error("Failed to update size for repository: %v", err) } - if err := models.CopyLanguageStat(opts.BaseRepo, repo); err != nil { + if err := repo_model.CopyLanguageStat(opts.BaseRepo, repo); err != nil { log.Error("Copy language stat from oldRepo failed") } @@ -145,9 +145,9 @@ func ForkRepository(doer, owner *user_model.User, opts models.ForkRepoOptions) ( } // ConvertForkToNormalRepository convert the provided repo from a forked repo to normal repo -func ConvertForkToNormalRepository(repo *models.Repository) error { +func ConvertForkToNormalRepository(repo *repo_model.Repository) error { err := db.WithTx(func(ctx context.Context) error { - repo, err := models.GetRepositoryByIDCtx(ctx, repo.ID) + repo, err := repo_model.GetRepositoryByIDCtx(ctx, repo.ID) if err != nil { return err } diff --git a/services/repository/fork_test.go b/services/repository/fork_test.go index befb60613..859889fc5 100644 --- a/services/repository/fork_test.go +++ b/services/repository/fork_test.go @@ -8,6 +8,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" @@ -19,7 +20,7 @@ func TestForkRepository(t *testing.T) { // user 13 has already forked repo10 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 13}).(*user_model.User) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}).(*repo_model.Repository) fork, err := ForkRepository(user, user, models.ForkRepoOptions{ BaseRepo: repo, diff --git a/services/repository/generate.go b/services/repository/generate.go index 031648666..2b5a750ad 100644 --- a/services/repository/generate.go +++ b/services/repository/generate.go @@ -9,6 +9,7 @@ import ( "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" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification" @@ -16,14 +17,14 @@ import ( ) // GenerateRepository generates a repository from a template -func GenerateRepository(doer, owner *user_model.User, templateRepo *models.Repository, opts models.GenerateRepoOptions) (_ *models.Repository, err error) { +func GenerateRepository(doer, owner *user_model.User, templateRepo *repo_model.Repository, opts models.GenerateRepoOptions) (_ *repo_model.Repository, err error) { if !doer.IsAdmin && !owner.CanCreateRepo() { return nil, models.ErrReachLimitOfRepo{ Limit: owner.MaxRepoCreation, } } - var generateRepo *models.Repository + var generateRepo *repo_model.Repository if err = db.WithTx(func(ctx context.Context) error { generateRepo, err = repo_module.GenerateRepository(ctx, doer, owner, templateRepo, opts) if err != nil { diff --git a/services/repository/hooks.go b/services/repository/hooks.go index a50853f6a..714cd6b2e 100644 --- a/services/repository/hooks.go +++ b/services/repository/hooks.go @@ -8,8 +8,8 @@ import ( "context" "fmt" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" @@ -23,10 +23,10 @@ func SyncRepositoryHooks(ctx context.Context) error { if err := db.Iterate( db.DefaultContext, - new(models.Repository), + new(repo_model.Repository), builder.Gt{"id": 0}, func(idx int, bean interface{}) error { - repo := bean.(*models.Repository) + repo := bean.(*repo_model.Repository) select { case <-ctx.Done(): return db.ErrCancelledf("before sync repository hooks for %s", repo.FullName()) diff --git a/services/repository/push.go b/services/repository/push.go index 7b439a41f..60d2f0c58 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -13,6 +13,7 @@ import ( "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" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" @@ -76,7 +77,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { return nil } - repo, err := models.GetRepositoryByOwnerAndName(optsList[0].RepoUserName, optsList[0].RepoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(optsList[0].RepoUserName, optsList[0].RepoName) if err != nil { return fmt.Errorf("GetRepositoryByOwnerAndName failed: %v", err) } @@ -88,7 +89,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { } defer gitRepo.Close() - if err = repo.UpdateSize(db.DefaultContext); err != nil { + if err = models.UpdateRepoSize(db.DefaultContext, repo); err != nil { log.Error("Failed to update size for repository: %v", err) } @@ -209,7 +210,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID) notification.NotifyPushCommits(pusher, repo, opts, commits) - if err = models.RemoveDeletedBranch(repo.ID, branch); err != nil { + if err = models.RemoveDeletedBranchByName(repo.ID, branch); err != nil { log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, branch, err) } @@ -246,7 +247,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { } // PushUpdateAddDeleteTags updates a number of added and delete tags -func PushUpdateAddDeleteTags(repo *models.Repository, gitRepo *git.Repository, addTags, delTags []string) error { +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 { return err @@ -256,7 +257,7 @@ func PushUpdateAddDeleteTags(repo *models.Repository, gitRepo *git.Repository, a } // pushUpdateAddTags updates a number of add tags -func pushUpdateAddTags(ctx context.Context, repo *models.Repository, gitRepo *git.Repository, tags []string) error { +func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, tags []string) error { if len(tags) == 0 { return nil } diff --git a/services/repository/repository.go b/services/repository/repository.go index 4929f9f44..0b97148f6 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -8,6 +8,7 @@ import ( "fmt" "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/log" "code.gitea.io/gitea/modules/notification" @@ -17,7 +18,7 @@ import ( ) // CreateRepository creates a repository for the user/organization. -func CreateRepository(doer, owner *user_model.User, opts models.CreateRepoOptions) (*models.Repository, error) { +func CreateRepository(doer, owner *user_model.User, opts models.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... @@ -30,7 +31,7 @@ func CreateRepository(doer, owner *user_model.User, opts models.CreateRepoOption } // DeleteRepository deletes a repository for a user or organization. -func DeleteRepository(doer *user_model.User, repo *models.Repository) error { +func DeleteRepository(doer *user_model.User, repo *repo_model.Repository) error { if err := pull_service.CloseRepoBranchesPulls(doer, repo); err != nil { log.Error("CloseRepoBranchesPulls failed: %v", err) } @@ -43,7 +44,7 @@ func DeleteRepository(doer *user_model.User, repo *models.Repository) error { } // PushCreateRepo creates a repository when a new repository is pushed to an appropriate namespace -func PushCreateRepo(authUser, owner *user_model.User, repoName string) (*models.Repository, error) { +func PushCreateRepo(authUser, owner *user_model.User, repoName string) (*repo_model.Repository, error) { if !authUser.IsAdmin { if owner.IsOrganization() { if ok, err := models.CanCreateOrgRepo(owner.ID, authUser.ID); err != nil { diff --git a/services/repository/transfer.go b/services/repository/transfer.go index d6aea70ff..b60338300 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -8,7 +8,9 @@ import ( "fmt" "code.gitea.io/gitea/models" + "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" "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/sync" @@ -18,8 +20,8 @@ import ( var repoWorkingPool = sync.NewExclusivePool() // TransferOwnership transfers all corresponding setting from old user to new one. -func TransferOwnership(doer, newOwner *user_model.User, repo *models.Repository, teams []*models.Team) error { - if err := repo.GetOwner(); err != nil { +func TransferOwnership(doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*models.Team) error { + if err := repo.GetOwner(db.DefaultContext); err != nil { return err } for _, team := range teams { @@ -37,7 +39,7 @@ func TransferOwnership(doer, newOwner *user_model.User, repo *models.Repository, } repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) - newRepo, err := models.GetRepositoryByID(repo.ID) + newRepo, err := repo_model.GetRepositoryByID(repo.ID) if err != nil { return err } @@ -54,7 +56,7 @@ func TransferOwnership(doer, newOwner *user_model.User, repo *models.Repository, } // ChangeRepositoryName changes all corresponding setting from old repository name to new one. -func ChangeRepositoryName(doer *user_model.User, repo *models.Repository, newRepoName string) error { +func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, newRepoName string) error { oldRepoName := repo.Name // Change repository directory name. We must lock the local copy of the @@ -75,7 +77,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *models.Repository, newRep // StartRepositoryTransfer transfer a repo from one owner to a new one. // it make repository into pending transfer state, if doer can not create repo for new owner. -func StartRepositoryTransfer(doer, newOwner *user_model.User, repo *models.Repository, teams []*models.Team) error { +func StartRepositoryTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*models.Team) error { if err := models.TestRepositoryReadyForTransfer(repo.Status); err != nil { return err } @@ -102,16 +104,16 @@ func StartRepositoryTransfer(doer, newOwner *user_model.User, repo *models.Repos return err } if !hasAccess { - if err := repo.AddCollaborator(newOwner); err != nil { + if err := models.AddCollaborator(repo, newOwner); err != nil { return err } - if err := repo.ChangeCollaborationAccessMode(newOwner.ID, perm.AccessModeRead); err != nil { + if err := models.ChangeCollaborationAccessMode(repo, newOwner.ID, perm.AccessModeRead); err != nil { return err } } // Make repo as pending for transfer - repo.Status = models.RepositoryPendingTransfer + repo.Status = repo_model.RepositoryPendingTransfer if err := models.CreatePendingRepositoryTransfer(doer, newOwner, repo.ID, teams); err != nil { return err } diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index 866e49c86..d4fbe9583 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -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/notification" @@ -32,17 +33,17 @@ func TestTransferOwnership(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) repo.Owner = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User) assert.NoError(t, TransferOwnership(doer, doer, repo, nil)) - transferredRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + transferredRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) assert.EqualValues(t, 2, transferredRepo.OwnerID) - exist, err := util.IsExist(models.RepoPath("user3", "repo3")) + exist, err := util.IsExist(repo_model.RepoPath("user3", "repo3")) assert.NoError(t, err) assert.False(t, exist) - exist, err = util.IsExist(models.RepoPath("user2", "repo3")) + exist, err = util.IsExist(repo_model.RepoPath("user2", "repo3")) assert.NoError(t, err) assert.True(t, exist) unittest.AssertExistsAndLoadBean(t, &models.Action{ @@ -52,7 +53,7 @@ func TestTransferOwnership(t *testing.T) { Content: "user3/repo3", }) - unittest.CheckConsistencyFor(t, &models.Repository{}, &user_model.User{}, &models.Team{}) + unittest.CheckConsistencyFor(t, &repo_model.Repository{}, &user_model.User{}, &models.Team{}) } func TestStartRepositoryTransferSetPermission(t *testing.T) { @@ -60,7 +61,7 @@ func TestStartRepositoryTransferSetPermission(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) recipient := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) repo.Owner = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User) hasAccess, err := models.HasAccess(recipient.ID, repo) @@ -73,5 +74,5 @@ func TestStartRepositoryTransferSetPermission(t *testing.T) { assert.NoError(t, err) assert.True(t, hasAccess) - unittest.CheckConsistencyFor(t, &models.Repository{}, &user_model.User{}, &models.Team{}) + unittest.CheckConsistencyFor(t, &repo_model.Repository{}, &user_model.User{}, &models.Team{}) } diff --git a/services/task/migrate.go b/services/task/migrate.go index 8e9f6115b..dbe237b69 100644 --- a/services/task/migrate.go +++ b/services/task/migrate.go @@ -11,6 +11,7 @@ import ( "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" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/json" @@ -79,7 +80,7 @@ func runMigrateTask(t *models.Task) (err error) { } // if repository is ready, then just finish the task - if t.Repo.Status == models.RepositoryReady { + if t.Repo.Status == repo_model.RepositoryReady { return nil } diff --git a/services/task/task.go b/services/task/task.go index 350b8206b..4994be87d 100644 --- a/services/task/task.go +++ b/services/task/task.go @@ -8,6 +8,7 @@ import ( "fmt" "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/graceful" "code.gitea.io/gitea/modules/json" @@ -110,7 +111,7 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*mod GitServiceType: opts.GitServiceType, IsPrivate: opts.Private, IsMirror: opts.Mirror, - Status: models.RepositoryBeingMigrated, + Status: repo_model.RepositoryBeingMigrated, }) if err != nil { task.EndTime = timeutil.TimeStampNow() diff --git a/services/user/user.go b/services/user/user.go index 6df9eec13..72052f4ec 100644 --- a/services/user/user.go +++ b/services/user/user.go @@ -15,6 +15,7 @@ import ( "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" "code.gitea.io/gitea/modules/avatar" "code.gitea.io/gitea/modules/log" @@ -40,7 +41,7 @@ func DeleteUser(u *user_model.User) error { // cannot perform delete operation. // Check ownership of repository. - count, err := models.GetRepositoryCount(ctx, u.ID) + count, err := repo_model.GetRepositoryCount(ctx, u.ID) if err != nil { return fmt.Errorf("GetRepositoryCount: %v", err) } else if count > 0 { diff --git a/services/user/user_test.go b/services/user/user_test.go index e18b76030..5b35db790 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -10,6 +10,7 @@ import ( "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" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" @@ -26,8 +27,8 @@ func TestDeleteUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}).(*user_model.User) - ownedRepos := make([]*models.Repository, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &models.Repository{OwnerID: userID})) + ownedRepos := make([]*repo_model.Repository, 0, 10) + assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &repo_model.Repository{OwnerID: userID})) if len(ownedRepos) > 0 { err := DeleteUser(user) assert.Error(t, err) @@ -45,7 +46,7 @@ func TestDeleteUser(t *testing.T) { } assert.NoError(t, DeleteUser(user)) unittest.AssertNotExistsBean(t, &user_model.User{ID: userID}) - unittest.CheckConsistencyFor(t, &user_model.User{}, &models.Repository{}) + unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{}) } test(2) test(4) diff --git a/services/webhook/main_test.go b/services/webhook/main_test.go index fc58f7256..e64acf3b6 100644 --- a/services/webhook/main_test.go +++ b/services/webhook/main_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "testing" + _ "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/unittest" ) diff --git a/services/webhook/webhook.go b/services/webhook/webhook.go index d4fe4e3bc..9356f4ee1 100644 --- a/services/webhook/webhook.go +++ b/services/webhook/webhook.go @@ -8,7 +8,7 @@ import ( "fmt" "strings" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -99,7 +99,7 @@ func getPayloadBranch(p api.Payloader) string { } // PrepareWebhook adds special webhook to task queue for given payload. -func PrepareWebhook(w *webhook_model.Webhook, repo *models.Repository, event webhook_model.HookEventType, p api.Payloader) error { +func PrepareWebhook(w *webhook_model.Webhook, repo *repo_model.Repository, event webhook_model.HookEventType, p api.Payloader) error { if err := prepareWebhook(w, repo, event, p); err != nil { return err } @@ -123,7 +123,7 @@ func checkBranch(w *webhook_model.Webhook, branch string) bool { return g.Match(branch) } -func prepareWebhook(w *webhook_model.Webhook, repo *models.Repository, event webhook_model.HookEventType, p api.Payloader) error { +func prepareWebhook(w *webhook_model.Webhook, repo *repo_model.Repository, event webhook_model.HookEventType, p api.Payloader) error { // Skip sending if webhooks are disabled. if setting.DisableWebhooks { return nil @@ -180,7 +180,7 @@ func prepareWebhook(w *webhook_model.Webhook, repo *models.Repository, event web } // PrepareWebhooks adds new webhooks to task queue for given payload. -func PrepareWebhooks(repo *models.Repository, event webhook_model.HookEventType, p api.Payloader) error { +func PrepareWebhooks(repo *repo_model.Repository, event webhook_model.HookEventType, p api.Payloader) error { if err := prepareWebhooks(repo, event, p); err != nil { return err } @@ -189,7 +189,7 @@ func PrepareWebhooks(repo *models.Repository, event webhook_model.HookEventType, return nil } -func prepareWebhooks(repo *models.Repository, event webhook_model.HookEventType, p api.Payloader) error { +func prepareWebhooks(repo *repo_model.Repository, event webhook_model.HookEventType, p api.Payloader) error { ws, err := webhook_model.ListWebhooksByOpts(&webhook_model.ListWebhookOptions{ RepoID: repo.ID, IsActive: util.OptionalBoolTrue, diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index c33233278..85fc39770 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -7,7 +7,7 @@ package webhook import ( "testing" - "code.gitea.io/gitea/models" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" @@ -30,7 +30,7 @@ func TestWebhook_GetSlackHook(t *testing.T) { func TestPrepareWebhooks(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) hookTasks := []*webhook_model.HookTask{ {RepoID: repo.ID, HookID: 1, EventType: webhook_model.HookEventPush}, } @@ -46,7 +46,7 @@ func TestPrepareWebhooks(t *testing.T) { func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) hookTasks := []*webhook_model.HookTask{ {RepoID: repo.ID, HookID: 4, EventType: webhook_model.HookEventPush}, } @@ -63,7 +63,7 @@ func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) hookTasks := []*webhook_model.HookTask{ {RepoID: repo.ID, HookID: 4, EventType: webhook_model.HookEventPush}, } diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index cf25c3327..18e9b26d8 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -14,6 +14,7 @@ import ( "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" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" @@ -70,7 +71,7 @@ func FilenameToName(filename string) (string, error) { // InitWiki initializes a wiki for repository, // it does nothing when repository already has wiki. -func InitWiki(repo *models.Repository) error { +func InitWiki(repo *repo_model.Repository) error { if repo.HasWiki() { return nil } @@ -117,7 +118,7 @@ func prepareWikiFileName(gitRepo *git.Repository, wikiName string) (bool, string } // updateWikiPage adds a new page to the repository wiki. -func updateWikiPage(doer *user_model.User, repo *models.Repository, oldWikiName, newWikiName, content, message string, isNew bool) (err error) { +func updateWikiPage(doer *user_model.User, repo *repo_model.Repository, oldWikiName, newWikiName, content, message string, isNew bool) (err error) { if err = nameAllowed(newWikiName); err != nil { return err } @@ -224,10 +225,10 @@ func updateWikiPage(doer *user_model.User, repo *models.Repository, oldWikiName, committer := doer.NewGitSig() - sign, signingKey, signer, _ := repo.SignWikiCommit(doer) + sign, signingKey, signer, _ := models.SignWikiCommit(repo, doer) if sign { commitTreeOpts.KeyID = signingKey - if repo.GetTrustModel() == models.CommitterTrustModel || repo.GetTrustModel() == models.CollaboratorCommitterTrustModel { + if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel { committer = signer } } else { @@ -265,18 +266,18 @@ func updateWikiPage(doer *user_model.User, repo *models.Repository, oldWikiName, } // AddWikiPage adds a new wiki page with a given wikiPath. -func AddWikiPage(doer *user_model.User, repo *models.Repository, wikiName, content, message string) error { +func AddWikiPage(doer *user_model.User, repo *repo_model.Repository, wikiName, content, message string) error { return updateWikiPage(doer, repo, "", wikiName, content, message, true) } // EditWikiPage updates a wiki page identified by its wikiPath, // optionally also changing wikiPath. -func EditWikiPage(doer *user_model.User, repo *models.Repository, oldWikiName, newWikiName, content, message string) error { +func EditWikiPage(doer *user_model.User, repo *repo_model.Repository, oldWikiName, newWikiName, content, message string) error { return updateWikiPage(doer, repo, oldWikiName, newWikiName, content, message, false) } // DeleteWikiPage deletes a wiki page identified by its path. -func DeleteWikiPage(doer *user_model.User, repo *models.Repository, wikiName string) (err error) { +func DeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, wikiName string) (err error) { wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID)) defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID)) @@ -342,10 +343,10 @@ func DeleteWikiPage(doer *user_model.User, repo *models.Repository, wikiName str committer := doer.NewGitSig() - sign, signingKey, signer, _ := repo.SignWikiCommit(doer) + sign, signingKey, signer, _ := models.SignWikiCommit(repo, doer) if sign { commitTreeOpts.KeyID = signingKey - if repo.GetTrustModel() == models.CommitterTrustModel || repo.GetTrustModel() == models.CollaboratorCommitterTrustModel { + if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel { committer = signer } } else { @@ -372,7 +373,7 @@ func DeleteWikiPage(doer *user_model.User, repo *models.Repository, wikiName str } // DeleteWiki removes the actual and local copy of repository wiki. -func DeleteWiki(repo *models.Repository) error { +func DeleteWiki(repo *repo_model.Repository) error { if err := models.UpdateRepositoryUnits(repo, nil, []unit.Type{unit.TypeWiki}); err != nil { return err } diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index 5b42dd590..659666f97 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -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" @@ -113,11 +114,11 @@ func TestWikiNameToFilenameToName(t *testing.T) { func TestRepository_InitWiki(t *testing.T) { unittest.PrepareTestEnv(t) // repo1 already has a wiki - repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) assert.NoError(t, InitWiki(repo1)) // repo2 does not already have a wiki - repo2 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}).(*repo_model.Repository) assert.NoError(t, InitWiki(repo2)) assert.True(t, repo2.HasWiki()) } @@ -126,7 +127,7 @@ func TestRepository_AddWikiPage(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) const wikiContent = "This is the wiki content" const commitMsg = "Commit message" - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) for _, wikiName := range []string{ "Another page", @@ -171,7 +172,7 @@ func TestRepository_EditWikiPage(t *testing.T) { const newWikiContent = "This is the new content" const commitMsg = "Commit message" - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) for _, newWikiName := range []string{ "Home", // same name as before @@ -201,7 +202,7 @@ func TestRepository_EditWikiPage(t *testing.T) { func TestRepository_DeleteWikiPage(t *testing.T) { unittest.PrepareTestEnv(t) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) assert.NoError(t, DeleteWikiPage(doer, repo, "Home")) @@ -218,7 +219,7 @@ func TestRepository_DeleteWikiPage(t *testing.T) { func TestPrepareWikiFileName(t *testing.T) { unittest.PrepareTestEnv(t) - repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) gitRepo, err := git.OpenRepository(repo.WikiPath()) defer gitRepo.Close() assert.NoError(t, err) diff --git a/templates/repo/settings/options.tmpl b/templates/repo/settings/options.tmpl index c911a83c9..5a4c8ace6 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -78,7 +78,7 @@
{{$.i18n.Tr "repo.settings.mirror_settings.docs" | Safe}} - {{if or .Repository.IsMirror .Repository.PushMirrors}} + {{if or .Repository.IsMirror .PushMirrors}} @@ -166,7 +166,7 @@ {{end}} - {{range .Repository.PushMirrors}} + {{range .PushMirrors}} {{$address := MirrorRemoteAddress .}}
{{$.i18n.Tr "repo.settings.mirror_settings.mirrored_repository"}}
{{$address.Address}}