From 350bc83d0072a5eb19d949ae3eb5bae6e74ef0a3 Mon Sep 17 00:00:00 2001 From: flynnnnnnnnnn <118399147+flynnnnnnnnnn@users.noreply.github.com> Date: Fri, 2 Dec 2022 11:23:26 -0500 Subject: [PATCH 01/13] Update to Alpine 3.17 (#21904) This pull request is for updating the base docker images to build with the latest version of Alpine. --- .drone.yml | 2 +- Dockerfile | 4 ++-- Dockerfile.rootless | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.drone.yml b/.drone.yml index d349a5f2fc1..1f92d877168 100644 --- a/.drone.yml +++ b/.drone.yml @@ -600,7 +600,7 @@ steps: from_secret: crowdin_key - name: update - image: alpine:3.13 + image: alpine:3.17 pull: always commands: - ./build/update-locales.sh diff --git a/Dockerfile b/Dockerfile index d5d98e69a83..3ee474bb342 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ #Build stage -FROM golang:1.19-alpine3.16 AS build-env +FROM golang:1.19-alpine3.17 AS build-env ARG GOPROXY ENV GOPROXY ${GOPROXY:-direct} @@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \ # Begin env-to-ini build RUN go build contrib/environment-to-ini/environment-to-ini.go -FROM alpine:3.16 +FROM alpine:3.17 LABEL maintainer="maintainers@gitea.io" EXPOSE 22 3000 diff --git a/Dockerfile.rootless b/Dockerfile.rootless index 8c2b8e98c95..46a14eae873 100644 --- a/Dockerfile.rootless +++ b/Dockerfile.rootless @@ -1,5 +1,5 @@ #Build stage -FROM golang:1.19-alpine3.16 AS build-env +FROM golang:1.19-alpine3.17 AS build-env ARG GOPROXY ENV GOPROXY ${GOPROXY:-direct} @@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \ # Begin env-to-ini build RUN go build contrib/environment-to-ini/environment-to-ini.go -FROM alpine:3.16 +FROM alpine:3.17 LABEL maintainer="maintainers@gitea.io" EXPOSE 2222 3000 From 21bcb929260d1e41fd84c650aeea552f540d0981 Mon Sep 17 00:00:00 2001 From: xtexChooser Date: Sat, 3 Dec 2022 00:23:47 +0800 Subject: [PATCH 02/13] Add pnpm to packages/overview (#22008) [`pnpm`](https://pnpm.io/) is a "fast, disk space efficient" node package manager. Co-authored-by: Lunny Xiao --- docs/content/doc/packages/overview.en-us.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/doc/packages/overview.en-us.md b/docs/content/doc/packages/overview.en-us.md index 0abb054b0f1..239ba6834e8 100644 --- a/docs/content/doc/packages/overview.en-us.md +++ b/docs/content/doc/packages/overview.en-us.md @@ -32,7 +32,7 @@ The following package managers are currently supported: | [Generic]({{< relref "doc/packages/generic.en-us.md" >}}) | - | any HTTP client | | [Helm]({{< relref "doc/packages/helm.en-us.md" >}}) | - | any HTTP client, `cm-push` | | [Maven]({{< relref "doc/packages/maven.en-us.md" >}}) | Java | `mvn`, `gradle` | -| [npm]({{< relref "doc/packages/npm.en-us.md" >}}) | JavaScript | `npm`, `yarn` | +| [npm]({{< relref "doc/packages/npm.en-us.md" >}}) | JavaScript | `npm`, `yarn`, `pnpm` | | [NuGet]({{< relref "doc/packages/nuget.en-us.md" >}}) | .NET | `nuget` | | [Pub]({{< relref "doc/packages/pub.en-us.md" >}}) | Dart | `dart`, `flutter` | | [PyPI]({{< relref "doc/packages/pypi.en-us.md" >}}) | Python | `pip`, `twine` | From 8698458f48eafeab21014db544aa7160368856e1 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Fri, 2 Dec 2022 17:06:23 -0500 Subject: [PATCH 03/13] Remove deprecated packages & staticcheck fixes (#22012) `ioutil` is deprecated and should use `io` instead --- modules/activitypub/client_test.go | 2 +- tests/integration/api_packages_nuget_test.go | 3 +-- tests/integration/api_packages_vagrant_test.go | 2 +- tests/integration/api_pull_test.go | 4 ++-- tests/integration/download_test.go | 16 ++++++++-------- tests/integration/nonascii_branches_test.go | 2 +- tests/integration/rename_branch_test.go | 2 +- 7 files changed, 15 insertions(+), 16 deletions(-) diff --git a/modules/activitypub/client_test.go b/modules/activitypub/client_test.go index b5f978c4ddd..0ab512c5ba7 100644 --- a/modules/activitypub/client_test.go +++ b/modules/activitypub/client_test.go @@ -35,7 +35,7 @@ func TestActivityPubSignedPost(t *testing.T) { body, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, expected, string(body)) - fmt.Fprintf(w, expected) + fmt.Fprint(w, expected) })) defer srv.Close() diff --git a/tests/integration/api_packages_nuget_test.go b/tests/integration/api_packages_nuget_test.go index 72329b66912..cc4ff180d04 100644 --- a/tests/integration/api_packages_nuget_test.go +++ b/tests/integration/api_packages_nuget_test.go @@ -10,7 +10,6 @@ import ( "encoding/xml" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "testing" @@ -105,7 +104,7 @@ func TestPackageNuGet(t *testing.T) { return &buf } - content, _ := ioutil.ReadAll(createPackage(packageName, packageVersion)) + content, _ := io.ReadAll(createPackage(packageName, packageVersion)) url := fmt.Sprintf("/api/packages/%s/nuget", user.Name) diff --git a/tests/integration/api_packages_vagrant_test.go b/tests/integration/api_packages_vagrant_test.go index d3e4449f295..b4f04b0c893 100644 --- a/tests/integration/api_packages_vagrant_test.go +++ b/tests/integration/api_packages_vagrant_test.go @@ -87,7 +87,7 @@ func TestPackageVagrant(t *testing.T) { req = NewRequest(t, "HEAD", boxURL) resp := MakeRequest(t, req, http.StatusOK) - assert.True(t, strings.HasPrefix(resp.HeaderMap.Get("Content-Type"), "application/json")) + assert.True(t, strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json")) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeVagrant) assert.NoError(t, err) diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 3d7256d30db..89d39179a68 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -5,7 +5,7 @@ package integration import ( "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -41,7 +41,7 @@ func TestAPIViewPulls(t *testing.T) { pull := pulls[0] if assert.EqualValues(t, 5, pull.ID) { resp = ctx.Session.MakeRequest(t, NewRequest(t, "GET", pull.DiffURL), http.StatusOK) - _, err := ioutil.ReadAll(resp.Body) + _, err := io.ReadAll(resp.Body) assert.NoError(t, err) // TODO: use diff to generate stats to test against diff --git a/tests/integration/download_test.go b/tests/integration/download_test.go index 9e03ec28825..efe5ac791cf 100644 --- a/tests/integration/download_test.go +++ b/tests/integration/download_test.go @@ -34,9 +34,9 @@ func TestDownloadByIDForSVGUsesSecureHeaders(t *testing.T) { req := NewRequest(t, "GET", "/user2/repo2/raw/blob/6395b68e1feebb1e4c657b4f9f6ba2676a283c0b") resp := session.MakeRequest(t, req, http.StatusOK) - assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.HeaderMap.Get("Content-Security-Policy")) - assert.Equal(t, "image/svg+xml", resp.HeaderMap.Get("Content-Type")) - assert.Equal(t, "nosniff", resp.HeaderMap.Get("X-Content-Type-Options")) + assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.Header().Get("Content-Security-Policy")) + assert.Equal(t, "image/svg+xml", resp.Header().Get("Content-Type")) + assert.Equal(t, "nosniff", resp.Header().Get("X-Content-Type-Options")) } func TestDownloadByIDMedia(t *testing.T) { @@ -60,9 +60,9 @@ func TestDownloadByIDMediaForSVGUsesSecureHeaders(t *testing.T) { req := NewRequest(t, "GET", "/user2/repo2/media/blob/6395b68e1feebb1e4c657b4f9f6ba2676a283c0b") resp := session.MakeRequest(t, req, http.StatusOK) - assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.HeaderMap.Get("Content-Security-Policy")) - assert.Equal(t, "image/svg+xml", resp.HeaderMap.Get("Content-Type")) - assert.Equal(t, "nosniff", resp.HeaderMap.Get("X-Content-Type-Options")) + assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.Header().Get("Content-Security-Policy")) + assert.Equal(t, "image/svg+xml", resp.Header().Get("Content-Type")) + assert.Equal(t, "nosniff", resp.Header().Get("X-Content-Type-Options")) } func TestDownloadRawTextFileWithoutMimeTypeMapping(t *testing.T) { @@ -73,7 +73,7 @@ func TestDownloadRawTextFileWithoutMimeTypeMapping(t *testing.T) { req := NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml") resp := session.MakeRequest(t, req, http.StatusOK) - assert.Equal(t, "text/plain; charset=utf-8", resp.HeaderMap.Get("Content-Type")) + assert.Equal(t, "text/plain; charset=utf-8", resp.Header().Get("Content-Type")) } func TestDownloadRawTextFileWithMimeTypeMapping(t *testing.T) { @@ -86,7 +86,7 @@ func TestDownloadRawTextFileWithMimeTypeMapping(t *testing.T) { req := NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml") resp := session.MakeRequest(t, req, http.StatusOK) - assert.Equal(t, "text/xml; charset=utf-8", resp.HeaderMap.Get("Content-Type")) + assert.Equal(t, "text/xml; charset=utf-8", resp.Header().Get("Content-Type")) delete(setting.MimeTypeMap.Map, ".xml") setting.MimeTypeMap.Enabled = false diff --git a/tests/integration/nonascii_branches_test.go b/tests/integration/nonascii_branches_test.go index d9e5b0fce3c..8917a9b5746 100644 --- a/tests/integration/nonascii_branches_test.go +++ b/tests/integration/nonascii_branches_test.go @@ -22,7 +22,7 @@ func testSrcRouteRedirect(t *testing.T, session *TestSession, user, repo, route, resp := session.MakeRequest(t, req, http.StatusSeeOther) // Check Location header - location := resp.HeaderMap.Get("Location") + location := resp.Header().Get("Location") assert.Equal(t, path.Join(prefix, expectedLocation), location) // Perform redirect diff --git a/tests/integration/rename_branch_test.go b/tests/integration/rename_branch_test.go index d8434c28bb1..9a55193ccfd 100644 --- a/tests/integration/rename_branch_test.go +++ b/tests/integration/rename_branch_test.go @@ -35,7 +35,7 @@ func TestRenameBranch(t *testing.T) { // check old branch link req = NewRequestWithValues(t, "GET", "/user2/repo1/src/branch/master/README.md", postData) resp = session.MakeRequest(t, req, http.StatusSeeOther) - location := resp.HeaderMap.Get("Location") + location := resp.Header().Get("Location") assert.Equal(t, "/user2/repo1/src/branch/main/README.md", location) // check db From 0a7d3ff786508284224ada17956a65bb759d9265 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 3 Dec 2022 10:48:26 +0800 Subject: [PATCH 04/13] refactor some functions to support ctx as first parameter (#21878) Co-authored-by: KN4CK3R Co-authored-by: Lauris BH --- cmd/admin.go | 2 +- models/activities/action.go | 22 +++--- models/activities/action_list.go | 2 +- models/activities/notification.go | 6 +- models/asymkey/gpg_key_commit_verification.go | 2 +- models/git/branches.go | 19 ++--- models/git/branches_test.go | 4 +- models/git/commit_status.go | 4 +- models/git/lfs_lock.go | 2 +- models/issues/assignees.go | 2 +- models/issues/assignees_test.go | 6 +- models/issues/comment.go | 6 +- models/issues/dependency_test.go | 2 +- models/issues/issue.go | 4 +- models/issues/issue_xref.go | 2 +- models/issues/milestone.go | 2 +- models/issues/pull.go | 17 ++--- models/issues/reaction.go | 2 +- models/issues/review.go | 8 +- models/issues/stopwatch_test.go | 6 +- models/issues/tracked_time.go | 4 +- models/issues/tracked_time_test.go | 2 +- models/org.go | 2 +- models/org_team.go | 26 ++++--- models/organization/org.go | 2 +- models/organization/org_user_test.go | 4 +- models/organization/team.go | 10 +-- models/organization/team_test.go | 4 +- models/packages/descriptor.go | 6 +- models/perm/access/access.go | 2 +- models/perm/access/repo_permission.go | 2 +- models/project/project.go | 2 +- models/pull/automerge.go | 2 +- models/repo.go | 8 +- models/repo/collaboration.go | 2 +- models/repo/fork_test.go | 4 +- models/repo/issue.go | 2 +- models/repo/mirror.go | 2 +- models/repo/pushmirror.go | 2 +- models/repo/release.go | 4 +- models/repo/repo.go | 32 +++----- models/repo/repo_test.go | 2 +- models/repo_collaboration.go | 2 +- models/repo_transfer.go | 6 +- models/user/email_address.go | 2 +- models/user/email_address_test.go | 2 +- models/user/user.go | 11 +-- models/user/user_test.go | 2 +- modules/context/context.go | 2 +- modules/context/repo.go | 6 +- modules/convert/convert.go | 5 +- modules/convert/issue.go | 2 +- modules/convert/issue_comment.go | 6 +- modules/convert/notification.go | 3 +- modules/convert/package.go | 2 +- modules/convert/pull.go | 4 +- modules/convert/pull_test.go | 2 +- modules/convert/repository.go | 11 +-- modules/convert/status.go | 10 ++- modules/indexer/code/indexer.go | 2 +- modules/indexer/stats/db.go | 2 +- modules/indexer/stats/indexer_test.go | 2 +- modules/notification/webhook/webhook.go | 74 +++++++++---------- modules/repository/create_test.go | 6 +- modules/repository/generate.go | 2 +- modules/repository/init.go | 2 +- modules/templates/helper.go | 3 +- modules/test/context_tests.go | 2 +- routers/api/packages/conan/auth.go | 2 +- routers/api/packages/container/auth.go | 2 +- routers/api/packages/nuget/auth.go | 2 +- routers/api/v1/org/team.go | 4 +- routers/api/v1/repo/fork.go | 4 +- routers/api/v1/repo/hook.go | 2 +- routers/api/v1/repo/issue.go | 2 +- routers/api/v1/repo/issue_comment.go | 2 +- routers/api/v1/repo/key.go | 13 ++-- routers/api/v1/repo/migrate.go | 4 +- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/repo/repo.go | 20 ++--- routers/api/v1/repo/status.go | 6 +- routers/api/v1/repo/transfer.go | 8 +- routers/api/v1/user/key.go | 3 +- routers/api/v1/user/repo.go | 4 +- routers/api/v1/user/star.go | 2 +- routers/api/v1/user/watch.go | 2 +- routers/private/hook_post_receive.go | 2 +- routers/private/hook_pre_receive.go | 2 +- routers/private/internal_repo.go | 2 +- routers/private/serv.go | 4 +- routers/web/admin/repos.go | 2 +- routers/web/admin/users.go | 4 +- routers/web/auth/2fa.go | 4 +- routers/web/auth/auth.go | 2 +- routers/web/auth/oauth.go | 6 +- routers/web/auth/webauthn.go | 4 +- routers/web/feed/convert.go | 2 +- routers/web/goget.go | 2 +- routers/web/org/teams.go | 10 +-- routers/web/repo/attachment.go | 2 +- routers/web/repo/branch.go | 2 +- routers/web/repo/compare.go | 4 +- routers/web/repo/issue.go | 10 +-- routers/web/repo/pull.go | 10 +-- routers/web/repo/release.go | 4 +- routers/web/repo/repo.go | 4 +- routers/web/repo/view.go | 2 +- routers/web/repo/webhook.go | 2 +- routers/web/user/package.go | 2 +- routers/web/user/setting/profile.go | 4 +- services/agit/agit.go | 4 +- services/auth/basic.go | 4 +- services/auth/httpsign.go | 2 +- services/auth/oauth2.go | 2 +- services/auth/session.go | 3 +- services/automerge/automerge.go | 2 +- services/issue/assignee.go | 2 +- services/issue/assignee_test.go | 2 +- services/issue/commit.go | 2 +- services/issue/issue.go | 2 +- services/issue/issue_test.go | 2 +- services/lfs/locks.go | 22 +++--- services/lfs/server.go | 13 ++-- services/mailer/mail_team_invite.go | 2 +- services/migrations/gitea_uploader.go | 2 +- services/pull/check.go | 4 +- services/pull/commit_status.go | 4 +- services/pull/merge.go | 4 +- services/pull/patch.go | 3 +- services/pull/pull.go | 4 +- services/pull/update.go | 2 +- services/release/release.go | 2 +- services/repository/adopt.go | 2 +- services/repository/archiver/archiver.go | 2 +- services/repository/files/upload.go | 2 +- services/repository/fork.go | 2 +- services/repository/push.go | 6 +- services/repository/repository.go | 10 +-- services/repository/repository_test.go | 2 +- services/repository/transfer.go | 2 +- .../api_issue_tracked_time_test.go | 2 +- tests/integration/api_repo_lfs_test.go | 3 +- tests/integration/git_test.go | 4 +- tests/integration/lfs_getobject_test.go | 3 +- tests/integration/repo_search_test.go | 5 +- 145 files changed, 360 insertions(+), 369 deletions(-) diff --git a/cmd/admin.go b/cmd/admin.go index a47d9ca1095..e4210213cde 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -665,7 +665,7 @@ func runDeleteUser(c *cli.Context) error { } else if c.IsSet("username") { user, err = user_model.GetUserByName(ctx, c.String("username")) } else { - user, err = user_model.GetUserByID(c.Int64("id")) + user, err = user_model.GetUserByID(ctx, c.Int64("id")) } if err != nil { return err diff --git a/models/activities/action.go b/models/activities/action.go index 80c117dc957..1ac1be7135d 100644 --- a/models/activities/action.go +++ b/models/activities/action.go @@ -114,12 +114,12 @@ func (a *Action) GetOpType() ActionType { } // LoadActUser loads a.ActUser -func (a *Action) LoadActUser() { +func (a *Action) LoadActUser(ctx context.Context) { if a.ActUser != nil { return } var err error - a.ActUser, err = user_model.GetUserByID(a.ActUserID) + a.ActUser, err = user_model.GetUserByID(ctx, a.ActUserID) if err == nil { return } else if user_model.IsErrUserNotExist(err) { @@ -129,12 +129,12 @@ func (a *Action) LoadActUser() { } } -func (a *Action) loadRepo() { +func (a *Action) loadRepo(ctx context.Context) { if a.Repo != nil { return } var err error - a.Repo, err = repo_model.GetRepositoryByID(a.RepoID) + a.Repo, err = repo_model.GetRepositoryByID(ctx, a.RepoID) if err != nil { log.Error("repo_model.GetRepositoryByID(%d): %v", a.RepoID, err) } @@ -142,13 +142,13 @@ func (a *Action) loadRepo() { // GetActFullName gets the action's user full name. func (a *Action) GetActFullName() string { - a.LoadActUser() + a.LoadActUser(db.DefaultContext) return a.ActUser.FullName } // GetActUserName gets the action's user name. func (a *Action) GetActUserName() string { - a.LoadActUser() + a.LoadActUser(db.DefaultContext) return a.ActUser.Name } @@ -179,7 +179,7 @@ func (a *Action) GetDisplayNameTitle() string { // GetRepoUserName returns the name of the action repository owner. func (a *Action) GetRepoUserName() string { - a.loadRepo() + a.loadRepo(db.DefaultContext) return a.Repo.OwnerName } @@ -191,7 +191,7 @@ func (a *Action) ShortRepoUserName() string { // GetRepoName returns the name of the action repository. func (a *Action) GetRepoName() string { - a.loadRepo() + a.loadRepo(db.DefaultContext) return a.Repo.Name } @@ -379,7 +379,7 @@ func activityQueryCondition(opts GetFeedsOptions) (builder.Cond, error) { cond := builder.NewCond() if opts.RequestedTeam != nil && opts.RequestedUser == nil { - org, err := user_model.GetUserByID(opts.RequestedTeam.OrgID) + org, err := user_model.GetUserByID(db.DefaultContext, opts.RequestedTeam.OrgID) if err != nil { return nil, err } @@ -489,7 +489,7 @@ func NotifyWatchers(ctx context.Context, actions ...*Action) error { } if repoChanged { - act.loadRepo() + act.loadRepo(ctx) repo = act.Repo // check repo owner exist. @@ -514,7 +514,7 @@ func NotifyWatchers(ctx context.Context, actions ...*Action) error { permIssue = make([]bool, len(watchers)) permPR = make([]bool, len(watchers)) for i, watcher := range watchers { - user, err := user_model.GetUserByIDCtx(ctx, watcher.UserID) + user, err := user_model.GetUserByID(ctx, watcher.UserID) if err != nil { permCode[i] = false permIssue[i] = false diff --git a/models/activities/action_list.go b/models/activities/action_list.go index 0979434f764..3d74397c692 100644 --- a/models/activities/action_list.go +++ b/models/activities/action_list.go @@ -81,7 +81,7 @@ func (actions ActionList) loadRepoOwner(ctx context.Context, userMap map[int64]* } repoOwner, ok := userMap[action.Repo.OwnerID] if !ok { - repoOwner, err = user_model.GetUserByIDCtx(ctx, action.Repo.OwnerID) + repoOwner, err = user_model.GetUserByID(ctx, action.Repo.OwnerID) if err != nil { if user_model.IsErrUserNotExist(err) { continue diff --git a/models/activities/notification.go b/models/activities/notification.go index 9aa4b87628b..d20a53a41d8 100644 --- a/models/activities/notification.go +++ b/models/activities/notification.go @@ -245,7 +245,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n // notify for userID := range toNotify { issue.Repo.Units = nil - user, err := user_model.GetUserByIDCtx(ctx, userID) + user, err := user_model.GetUserByID(ctx, userID) if err != nil { if user_model.IsErrUserNotExist(err) { continue @@ -388,7 +388,7 @@ func (n *Notification) LoadAttributes(ctx context.Context) (err error) { func (n *Notification) loadRepo(ctx context.Context) (err error) { if n.Repository == nil { - n.Repository, err = repo_model.GetRepositoryByIDCtx(ctx, n.RepoID) + n.Repository, err = repo_model.GetRepositoryByID(ctx, n.RepoID) if err != nil { return fmt.Errorf("getRepositoryByID [%d]: %w", n.RepoID, err) } @@ -425,7 +425,7 @@ func (n *Notification) loadComment(ctx context.Context) (err error) { func (n *Notification) loadUser(ctx context.Context) (err error) { if n.User == nil { - n.User, err = user_model.GetUserByIDCtx(ctx, n.UserID) + n.User, err = user_model.GetUserByID(ctx, n.UserID) if err != nil { return fmt.Errorf("getUserByID [%d]: %w", n.UserID, err) } diff --git a/models/asymkey/gpg_key_commit_verification.go b/models/asymkey/gpg_key_commit_verification.go index 1cdd748e35a..1b88fb8b138 100644 --- a/models/asymkey/gpg_key_commit_verification.go +++ b/models/asymkey/gpg_key_commit_verification.go @@ -426,7 +426,7 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use Email: email, } if key.OwnerID != 0 { - owner, err := user_model.GetUserByID(key.OwnerID) + owner, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) if err == nil { signer = owner } else if !user_model.IsErrUserNotExist(err) { diff --git a/models/git/branches.go b/models/git/branches.go index 87246ed149b..c02ab0a8886 100644 --- a/models/git/branches.go +++ b/models/git/branches.go @@ -73,10 +73,10 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool { } if !protectBranch.EnableWhitelist { - if user, err := user_model.GetUserByID(userID); err != nil { + if user, err := user_model.GetUserByID(db.DefaultContext, userID); err != nil { log.Error("GetUserByID: %v", err) return false - } else if repo, err := repo_model.GetRepositoryByID(protectBranch.RepoID); err != nil { + } else if repo, err := repo_model.GetRepositoryByID(db.DefaultContext, protectBranch.RepoID); err != nil { log.Error("repo_model.GetRepositoryByID: %v", err) return false } else if writeAccess, err := access_model.HasAccessUnit(db.DefaultContext, user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil { @@ -127,13 +127,8 @@ func IsUserMergeWhitelisted(ctx context.Context, protectBranch *ProtectedBranch, } // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals) -func IsUserOfficialReviewer(protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { - return IsUserOfficialReviewerCtx(db.DefaultContext, protectBranch, user) -} - -// IsUserOfficialReviewerCtx check if user is official reviewer for the branch (counts towards required approvals) -func IsUserOfficialReviewerCtx(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, protectBranch.RepoID) +func IsUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { + repo, err := repo_model.GetRepositoryByID(ctx, protectBranch.RepoID) if err != nil { return false, err } @@ -375,7 +370,7 @@ func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, curre whitelist = make([]int64, 0, len(newWhitelist)) for _, userID := range newWhitelist { - user, err := user_model.GetUserByIDCtx(ctx, userID) + user, err := user_model.GetUserByID(ctx, userID) if err != nil { return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %w", userID, repo.ID, err) } @@ -494,8 +489,8 @@ func RemoveDeletedBranchByID(repoID, id int64) (err error) { // LoadUser loads the user that deleted the branch // When there's no user found it returns a user_model.NewGhostUser -func (deletedBranch *DeletedBranch) LoadUser() { - user, err := user_model.GetUserByID(deletedBranch.DeletedByID) +func (deletedBranch *DeletedBranch) LoadUser(ctx context.Context) { + user, err := user_model.GetUserByID(ctx, deletedBranch.DeletedByID) if err != nil { user = user_model.NewGhostUser() } diff --git a/models/git/branches_test.go b/models/git/branches_test.go index 038a4f6686a..56f416622e1 100644 --- a/models/git/branches_test.go +++ b/models/git/branches_test.go @@ -48,13 +48,13 @@ func TestDeletedBranchLoadUser(t *testing.T) { branch := getDeletedBranch(t, firstBranch) assert.Nil(t, branch.DeletedBy) - branch.LoadUser() + branch.LoadUser(db.DefaultContext) assert.NotNil(t, branch.DeletedBy) assert.Equal(t, "user1", branch.DeletedBy.Name) branch = getDeletedBranch(t, secondBranch) assert.Nil(t, branch.DeletedBy) - branch.LoadUser() + branch.LoadUser(db.DefaultContext) assert.NotNil(t, branch.DeletedBy) assert.Equal(t, "Ghost", branch.DeletedBy.Name) } diff --git a/models/git/commit_status.go b/models/git/commit_status.go index 928f1771fe9..0fb0bc66af9 100644 --- a/models/git/commit_status.go +++ b/models/git/commit_status.go @@ -114,13 +114,13 @@ func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (in func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) { if status.Repo == nil { - status.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, status.RepoID) + status.Repo, err = repo_model.GetRepositoryByID(ctx, status.RepoID) if err != nil { return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err) } } if status.Creator == nil && status.CreatorID > 0 { - status.Creator, err = user_model.GetUserByIDCtx(ctx, status.CreatorID) + status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID) if err != nil { return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err) } diff --git a/models/git/lfs_lock.go b/models/git/lfs_lock.go index 3d765ea22bb..dc5b0a2cedd 100644 --- a/models/git/lfs_lock.go +++ b/models/git/lfs_lock.go @@ -167,7 +167,7 @@ func CheckLFSAccessForRepo(ctx context.Context, ownerID int64, repo *repo_model. if ownerID == 0 { return ErrLFSUnauthorizedAction{repo.ID, "undefined", mode} } - u, err := user_model.GetUserByIDCtx(ctx, ownerID) + u, err := user_model.GetUserByID(ctx, ownerID) if err != nil { return err } diff --git a/models/issues/assignees.go b/models/issues/assignees.go index 25ecd4b05ca..d3a1f5ffe83 100644 --- a/models/issues/assignees.go +++ b/models/issues/assignees.go @@ -118,7 +118,7 @@ func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.Use // toggles user assignee state in database func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (removed bool, err error) { // Check if the user exists - assignee, err := user_model.GetUserByIDCtx(ctx, assigneeID) + assignee, err := user_model.GetUserByID(ctx, assigneeID) if err != nil { return false, err } diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 7f18569d491..8a2cef8acd8 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -22,17 +22,17 @@ func TestUpdateAssignee(t *testing.T) { assert.NoError(t, err) // Assign multiple users - user2, err := user_model.GetUserByID(2) + user2, err := user_model.GetUserByID(db.DefaultContext, 2) assert.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user2.ID) assert.NoError(t, err) - user3, err := user_model.GetUserByID(3) + user3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user3.ID) assert.NoError(t, err) - user1, err := user_model.GetUserByID(1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him + user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him assert.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user1.ID) assert.NoError(t, err) diff --git a/models/issues/comment.go b/models/issues/comment.go index 0aaa870b465..f49c6e2c1f6 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -350,7 +350,7 @@ func (c *Comment) LoadPoster(ctx context.Context) (err error) { return nil } - c.Poster, err = user_model.GetUserByIDCtx(ctx, c.PosterID) + c.Poster, err = user_model.GetUserByID(ctx, c.PosterID) if err != nil { if user_model.IsErrUserNotExist(err) { c.PosterID = -1 @@ -580,7 +580,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error { var err error if c.AssigneeID > 0 && c.Assignee == nil { - c.Assignee, err = user_model.GetUserByIDCtx(db.DefaultContext, c.AssigneeID) + c.Assignee, err = user_model.GetUserByID(db.DefaultContext, c.AssigneeID) if err != nil { if !user_model.IsErrUserNotExist(err) { return err @@ -615,7 +615,7 @@ func (c *Comment) LoadResolveDoer() (err error) { if c.ResolveDoerID == 0 || c.Type != CommentTypeCode { return nil } - c.ResolveDoer, err = user_model.GetUserByIDCtx(db.DefaultContext, c.ResolveDoerID) + c.ResolveDoer, err = user_model.GetUserByID(db.DefaultContext, c.ResolveDoerID) if err != nil { if user_model.IsErrUserNotExist(err) { c.ResolveDoer = user_model.NewGhostUser() diff --git a/models/issues/dependency_test.go b/models/issues/dependency_test.go index 7af30b20193..cdc8e3182d3 100644 --- a/models/issues/dependency_test.go +++ b/models/issues/dependency_test.go @@ -18,7 +18,7 @@ func TestCreateIssueDependency(t *testing.T) { // Prepare assert.NoError(t, unittest.PrepareTestDatabase()) - user1, err := user_model.GetUserByID(1) + user1, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) diff --git a/models/issues/issue.go b/models/issues/issue.go index 488a17609e5..1d66996ee00 100644 --- a/models/issues/issue.go +++ b/models/issues/issue.go @@ -193,7 +193,7 @@ func (issue *Issue) IsOverdue() bool { // LoadRepo loads issue's repository func (issue *Issue) LoadRepo(ctx context.Context) (err error) { if issue.Repo == nil { - issue.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, issue.RepoID) + issue.Repo, err = repo_model.GetRepositoryByID(ctx, issue.RepoID) if err != nil { return fmt.Errorf("getRepositoryByID [%d]: %w", issue.RepoID, err) } @@ -242,7 +242,7 @@ func (issue *Issue) LoadLabels(ctx context.Context) (err error) { // LoadPoster loads poster func (issue *Issue) LoadPoster(ctx context.Context) (err error) { if issue.Poster == nil { - issue.Poster, err = user_model.GetUserByIDCtx(ctx, issue.PosterID) + issue.Poster, err = user_model.GetUserByID(ctx, issue.PosterID) if err != nil { issue.PosterID = -1 issue.Poster = user_model.NewGhostUser() diff --git a/models/issues/issue_xref.go b/models/issues/issue_xref.go index a965cf7340d..267ccc73a03 100644 --- a/models/issues/issue_xref.go +++ b/models/issues/issue_xref.go @@ -148,7 +148,7 @@ func (issue *Issue) getCrossReferences(stdCtx context.Context, ctx *crossReferen refRepo = ctx.OrigIssue.Repo } else { // Issues in other repositories - refRepo, err = repo_model.GetRepositoryByOwnerAndNameCtx(stdCtx, ref.Owner, ref.Name) + refRepo, err = repo_model.GetRepositoryByOwnerAndName(stdCtx, ref.Owner, ref.Name) if err != nil { if repo_model.IsErrRepoNotExist(err) { continue diff --git a/models/issues/milestone.go b/models/issues/milestone.go index 7c2ce407e68..8255db38f91 100644 --- a/models/issues/milestone.go +++ b/models/issues/milestone.go @@ -284,7 +284,7 @@ func DeleteMilestoneByRepoID(repoID, id int64) error { return err } - repo, err := repo_model.GetRepositoryByID(m.RepoID) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, m.RepoID) if err != nil { return err } diff --git a/models/issues/pull.go b/models/issues/pull.go index 9105dd4d3a6..7af9400d17c 100644 --- a/models/issues/pull.go +++ b/models/issues/pull.go @@ -223,7 +223,7 @@ func (pr *PullRequest) MustHeadUserName(ctx context.Context) string { // Note: don't try to get Issue because will end up recursive querying. func (pr *PullRequest) LoadAttributes(ctx context.Context) (err error) { if pr.HasMerged && pr.Merger == nil { - pr.Merger, err = user_model.GetUserByIDCtx(ctx, pr.MergerID) + pr.Merger, err = user_model.GetUserByID(ctx, pr.MergerID) if user_model.IsErrUserNotExist(err) { pr.MergerID = -1 pr.Merger = user_model.NewGhostUser() @@ -248,9 +248,9 @@ func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) { } } - pr.HeadRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.HeadRepoID) + pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID) if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work - return fmt.Errorf("getRepositoryByID(head): %w", err) + return fmt.Errorf("GetRepositoryByID(head): %w", err) } pr.isHeadRepoLoaded = true } @@ -273,7 +273,7 @@ func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) { return nil } - pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID) if err != nil { return fmt.Errorf("repo_model.GetRepositoryByID(base): %w", err) } @@ -294,18 +294,13 @@ func (pr *PullRequest) LoadIssue(ctx context.Context) (err error) { } // LoadProtectedBranch loads the protected branch of the base branch -func (pr *PullRequest) LoadProtectedBranch() (err error) { - return pr.LoadProtectedBranchCtx(db.DefaultContext) -} - -// LoadProtectedBranchCtx loads the protected branch of the base branch -func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (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 = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID) if err != nil { return } diff --git a/models/issues/reaction.go b/models/issues/reaction.go index 381881ff619..293dfa3fd11 100644 --- a/models/issues/reaction.go +++ b/models/issues/reaction.go @@ -75,7 +75,7 @@ func (r *Reaction) LoadUser() (*user_model.User, error) { if r.User != nil { return r.User, nil } - user, err := user_model.GetUserByIDCtx(db.DefaultContext, r.UserID) + user, err := user_model.GetUserByID(db.DefaultContext, r.UserID) if err != nil { return nil, err } diff --git a/models/issues/review.go b/models/issues/review.go index 0b50763fdc3..db2d2686cb6 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -158,7 +158,7 @@ func (r *Review) LoadReviewer(ctx context.Context) (err error) { if r.ReviewerID == 0 || r.Reviewer != nil { return } - r.Reviewer, err = user_model.GetUserByIDCtx(ctx, r.ReviewerID) + r.Reviewer, err = user_model.GetUserByID(ctx, r.ReviewerID) return err } @@ -263,7 +263,7 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo if err != nil { return false, err } - if err = pr.LoadProtectedBranchCtx(ctx); err != nil { + if err = pr.LoadProtectedBranch(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -271,7 +271,7 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo } for _, reviewer := range reviewers { - official, err := git_model.IsUserOfficialReviewerCtx(ctx, pr.ProtectedBranch, reviewer) + official, err := git_model.IsUserOfficialReviewer(ctx, pr.ProtectedBranch, reviewer) if official || err != nil { return official, err } @@ -286,7 +286,7 @@ func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio if err != nil { return false, err } - if err = pr.LoadProtectedBranchCtx(ctx); err != nil { + if err = pr.LoadProtectedBranch(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { diff --git a/models/issues/stopwatch_test.go b/models/issues/stopwatch_test.go index 7745bc513c8..ec2778aa81f 100644 --- a/models/issues/stopwatch_test.go +++ b/models/issues/stopwatch_test.go @@ -18,7 +18,7 @@ import ( func TestCancelStopwatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user1, err := user_model.GetUserByID(1) + user1, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) @@ -58,9 +58,9 @@ func TestHasUserStopwatch(t *testing.T) { func TestCreateOrStopIssueStopwatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user2, err := user_model.GetUserByID(2) + user2, err := user_model.GetUserByID(db.DefaultContext, 2) assert.NoError(t, err) - user3, err := user_model.GetUserByID(3) + user3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) diff --git a/models/issues/tracked_time.go b/models/issues/tracked_time.go index 6d259754591..2de63a3a45a 100644 --- a/models/issues/tracked_time.go +++ b/models/issues/tracked_time.go @@ -57,7 +57,7 @@ func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) { } } if t.User == nil { - t.User, err = user_model.GetUserByIDCtx(ctx, t.UserID) + t.User, err = user_model.GetUserByID(ctx, t.UserID) if err != nil { return } @@ -205,7 +205,7 @@ func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string, totalTimes := make(map[*user_model.User]string) // Fetching User and making time human readable for userID, total := range totalTimesByUser { - user, err := user_model.GetUserByID(userID) + user, err := user_model.GetUserByID(db.DefaultContext, userID) if err != nil { if user_model.IsErrUserNotExist(err) { continue diff --git a/models/issues/tracked_time_test.go b/models/issues/tracked_time_test.go index b3174c7c82d..becfd79d41b 100644 --- a/models/issues/tracked_time_test.go +++ b/models/issues/tracked_time_test.go @@ -18,7 +18,7 @@ import ( func TestAddTime(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user3, err := user_model.GetUserByID(3) + user3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) diff --git a/models/org.go b/models/org.go index 1c9383fe8d2..5f0e678ab45 100644 --- a/models/org.go +++ b/models/org.go @@ -43,7 +43,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error { return err } if t.NumMembers == 1 { - if err := t.GetMembersCtx(ctx); err != nil { + if err := t.LoadMembers(ctx); err != nil { return err } if t.Members[0].ID == userID { diff --git a/models/org_team.go b/models/org_team.go index 62376192ab5..a5a2575eec1 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -41,7 +41,7 @@ func AddRepository(ctx context.Context, t *organization.Team, repo *repo_model.R // Make all team members watch this repo if enabled in global settings if setting.Service.AutoWatchNewRepos { - if err = t.GetMembersCtx(ctx); err != nil { + if err = t.LoadMembers(ctx); err != nil { return fmt.Errorf("getMembers: %w", err) } for _, u := range t.Members { @@ -213,7 +213,7 @@ func RemoveRepository(t *organization.Team, repoID int64) error { return nil } - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, repoID) if err != nil { return err } @@ -349,8 +349,8 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err // Update access for team members if needed. if authChanged { - if err = t.GetRepositoriesCtx(ctx); err != nil { - return fmt.Errorf("getRepositories: %w", err) + if err = t.LoadRepositories(ctx); err != nil { + return fmt.Errorf("LoadRepositories: %w", err) } for _, repo := range t.Repos { @@ -381,11 +381,11 @@ func DeleteTeam(t *organization.Team) error { defer committer.Close() sess := db.GetEngine(ctx) - if err := t.GetRepositoriesCtx(ctx); err != nil { + if err := t.LoadRepositories(ctx); err != nil { return err } - if err := t.GetMembersCtx(ctx); err != nil { + if err := t.LoadMembers(ctx); err != nil { return err } @@ -516,10 +516,16 @@ func AddTeamMember(team *organization.Team, userID int64) error { } } - // watch could be failed, so run it in a goroutine + if err := committer.Commit(); err != nil { + return err + } + committer.Close() + + // this behaviour may spend much time so run it in a goroutine + // FIXME: Update watch repos batchly if setting.Service.AutoWatchNewRepos { // Get team and its repositories. - if err := team.GetRepositoriesCtx(db.DefaultContext); err != nil { + if err := team.LoadRepositories(db.DefaultContext); err != nil { log.Error("getRepositories failed: %v", err) } go func(repos []*repo_model.Repository) { @@ -531,7 +537,7 @@ func AddTeamMember(team *organization.Team, userID int64) error { }(team.Repos) } - return committer.Commit() + return nil } func removeTeamMember(ctx context.Context, team *organization.Team, userID int64) error { @@ -548,7 +554,7 @@ func removeTeamMember(ctx context.Context, team *organization.Team, userID int64 team.NumMembers-- - if err := team.GetRepositoriesCtx(ctx); err != nil { + if err := team.LoadRepositories(ctx); err != nil { return err } diff --git a/models/organization/org.go b/models/organization/org.go index ef7b834ad35..a5b07d5aae8 100644 --- a/models/organization/org.go +++ b/models/organization/org.go @@ -701,7 +701,7 @@ func AccessibleReposEnv(ctx context.Context, org *Organization, userID int64) (A var user *user_model.User if userID > 0 { - u, err := user_model.GetUserByIDCtx(ctx, userID) + u, err := user_model.GetUserByID(ctx, userID) if err != nil { return nil, err } diff --git a/models/organization/org_user_test.go b/models/organization/org_user_test.go index 1da17631e36..edd0aa3ea0c 100644 --- a/models/organization/org_user_test.go +++ b/models/organization/org_user_test.go @@ -37,7 +37,7 @@ func TestUserIsPublicMember(t *testing.T) { } func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { - user, err := user_model.GetUserByID(uid) + user, err := user_model.GetUserByID(db.DefaultContext, uid) assert.NoError(t, err) is, err := organization.IsPublicMembership(orgID, user.ID) assert.NoError(t, err) @@ -65,7 +65,7 @@ func TestIsUserOrgOwner(t *testing.T) { } func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { - user, err := user_model.GetUserByID(uid) + user, err := user_model.GetUserByID(db.DefaultContext, uid) assert.NoError(t, err) is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID) assert.NoError(t, err) diff --git a/models/organization/team.go b/models/organization/team.go index f6d71845df2..86ea30c8010 100644 --- a/models/organization/team.go +++ b/models/organization/team.go @@ -222,8 +222,8 @@ func (t *Team) IsMember(userID int64) bool { return isMember } -// GetRepositoriesCtx returns paginated repositories in team of organization. -func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) { +// LoadRepositories returns paginated repositories in team of organization. +func (t *Team) LoadRepositories(ctx context.Context) (err error) { if t.Repos != nil { return nil } @@ -233,8 +233,8 @@ func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) { return err } -// GetMembersCtx returns paginated members in team of organization. -func (t *Team) GetMembersCtx(ctx context.Context) (err error) { +// LoadMembers returns paginated members in team of organization. +func (t *Team) LoadMembers(ctx context.Context) (err error) { t.Members, err = GetTeamMembers(ctx, &SearchMembersOptions{ TeamID: t.ID, }) @@ -248,7 +248,7 @@ func (t *Team) UnitEnabled(tp unit.Type) bool { // UnitAccessMode returns if the team has the given unit type enabled // it is called in templates, should not be replaced by `UnitAccessModeCtx(ctx ...)` -func (t *Team) UnitAccessMode(tp unit.Type) perm.AccessMode { +func (t *Team) UnitAccessMode(tp unit.Type) perm.AccessMode { // Notice: It will be used in template, don't remove it directly return t.UnitAccessModeCtx(db.DefaultContext, tp) } diff --git a/models/organization/team_test.go b/models/organization/team_test.go index d324c6d0da1..c63b83aab77 100644 --- a/models/organization/team_test.go +++ b/models/organization/team_test.go @@ -42,7 +42,7 @@ func TestTeam_GetRepositories(t *testing.T) { test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext)) + assert.NoError(t, team.LoadRepositories(db.DefaultContext)) assert.Len(t, team.Repos, team.NumRepos) for _, repo := range team.Repos { unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID}) @@ -57,7 +57,7 @@ func TestTeam_GetMembers(t *testing.T) { test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.GetMembersCtx(db.DefaultContext)) + assert.NoError(t, team.LoadMembers(db.DefaultContext)) assert.Len(t, team.Members, team.NumMembers) for _, member := range team.Members { unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) diff --git a/models/packages/descriptor.go b/models/packages/descriptor.go index 7ffed2d8aad..34f1cad87dc 100644 --- a/models/packages/descriptor.go +++ b/models/packages/descriptor.go @@ -85,15 +85,15 @@ func GetPackageDescriptor(ctx context.Context, pv *PackageVersion) (*PackageDesc if err != nil { return nil, err } - o, err := user_model.GetUserByIDCtx(ctx, p.OwnerID) + o, err := user_model.GetUserByID(ctx, p.OwnerID) if err != nil { return nil, err } - repository, err := repo_model.GetRepositoryByIDCtx(ctx, p.RepoID) + repository, err := repo_model.GetRepositoryByID(ctx, p.RepoID) if err != nil && !repo_model.IsErrRepoNotExist(err) { return nil, err } - creator, err := user_model.GetUserByIDCtx(ctx, pv.CreatorID) + creator, err := user_model.GetUserByID(ctx, pv.CreatorID) if err != nil { return nil, err } diff --git a/models/perm/access/access.go b/models/perm/access/access.go index 55d3f78e01d..48ecf78a8c8 100644 --- a/models/perm/access/access.go +++ b/models/perm/access/access.go @@ -171,7 +171,7 @@ func RecalculateTeamAccesses(ctx context.Context, repo *repo_model.Repository, i continue } - if err = t.GetMembersCtx(ctx); err != nil { + if err = t.LoadMembers(ctx); err != nil { return fmt.Errorf("getMembers '%d': %w", t.ID, err) } for _, m := range t.Members { diff --git a/models/perm/access/repo_permission.go b/models/perm/access/repo_permission.go index 58c4299d165..88437dc4b25 100644 --- a/models/perm/access/repo_permission.go +++ b/models/perm/access/repo_permission.go @@ -364,7 +364,7 @@ func HasAccess(ctx context.Context, userID int64, repo *repo_model.Repository) ( var user *user_model.User var err error if userID > 0 { - user, err = user_model.GetUserByIDCtx(ctx, userID) + user, err = user_model.GetUserByID(ctx, userID) if err != nil { return false, err } diff --git a/models/project/project.go b/models/project/project.go index 0d655e333eb..384f51c5ac2 100644 --- a/models/project/project.go +++ b/models/project/project.go @@ -338,7 +338,7 @@ func DeleteProjectByIDCtx(ctx context.Context, id int64) error { return updateRepositoryProjectCount(ctx, p.RepoID) } -func DeleteProjectByRepoIDCtx(ctx context.Context, repoID int64) error { +func DeleteProjectByRepoID(ctx context.Context, repoID int64) error { switch { case setting.Database.UseSQLite3: if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil { diff --git a/models/pull/automerge.go b/models/pull/automerge.go index d7e04eafa6c..f68fb7c681e 100644 --- a/models/pull/automerge.go +++ b/models/pull/automerge.go @@ -74,7 +74,7 @@ func GetScheduledMergeByPullID(ctx context.Context, pullID int64) (bool, *AutoMe return false, nil, err } - doer, err := user_model.GetUserByIDCtx(ctx, scheduledPRM.DoerID) + doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID) if err != nil { return false, nil, err } diff --git a/models/repo.go b/models/repo.go index ca4f60a2f33..5d333a3aee4 100644 --- a/models/repo.go +++ b/models/repo.go @@ -52,7 +52,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { sess := db.GetEngine(ctx) // In case is a organization. - org, err := user_model.GetUserByIDCtx(ctx, uid) + org, err := user_model.GetUserByID(ctx, uid) if err != nil { return err } @@ -191,7 +191,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { } } - if err := project_model.DeleteProjectByRepoIDCtx(ctx, repoID); err != nil { + if err := project_model.DeleteProjectByRepoID(ctx, repoID); err != nil { return fmt.Errorf("unable to delete projects for repo[%d]: %w", repoID, err) } @@ -523,7 +523,7 @@ func CheckRepoStats(ctx context.Context) error { } log.Trace("Updating repository count 'num_forks': %d", id) - repo, err := repo_model.GetRepositoryByID(id) + repo, err := repo_model.GetRepositoryByID(ctx, id) if err != nil { log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err) continue @@ -618,7 +618,7 @@ func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error // Check if user has access to delete this key. if !doer.IsAdmin { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, key.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID) if err != nil { return fmt.Errorf("GetRepositoryByID: %w", err) } diff --git a/models/repo/collaboration.go b/models/repo/collaboration.go index 04d92c415fe..bd49b9aec9a 100644 --- a/models/repo/collaboration.go +++ b/models/repo/collaboration.go @@ -44,7 +44,7 @@ func GetCollaborators(ctx context.Context, repoID int64, listOptions db.ListOpti collaborators := make([]*Collaborator, 0, len(collaborations)) for _, c := range collaborations { - user, err := user_model.GetUserByIDCtx(ctx, c.UserID) + user, err := user_model.GetUserByID(ctx, 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, repoID) diff --git a/models/repo/fork_test.go b/models/repo/fork_test.go index d02bf91dd94..e8dca204cc4 100644 --- a/models/repo/fork_test.go +++ b/models/repo/fork_test.go @@ -17,14 +17,14 @@ func TestGetUserFork(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // User13 has repo 11 forked from repo10 - repo, err := repo_model.GetRepositoryByID(10) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10) assert.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) assert.NoError(t, err) assert.NotNil(t, repo) - repo, err = repo_model.GetRepositoryByID(9) + repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9) assert.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) diff --git a/models/repo/issue.go b/models/repo/issue.go index 0d27cc041e6..e27179caf51 100644 --- a/models/repo/issue.go +++ b/models/repo/issue.go @@ -26,7 +26,7 @@ func (repo *Repository) CanEnableTimetracker() bool { } // IsTimetrackerEnabled returns whether or not the timetracker is enabled. It returns the default value from config if an error occurs. -func (repo *Repository) IsTimetrackerEnabled() bool { +func (repo *Repository) IsTimetrackerEnabled() bool { // Notice: It will be used in template so don't remove directly return repo.IsTimetrackerEnabledCtx(db.DefaultContext) } diff --git a/models/repo/mirror.go b/models/repo/mirror.go index 63b26b5d0cd..2f59b85331d 100644 --- a/models/repo/mirror.go +++ b/models/repo/mirror.go @@ -52,7 +52,7 @@ func (m *Mirror) GetRepository() *Repository { return m.Repo } var err error - m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID) + m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID) if err != nil { log.Error("getRepositoryByID[%d]: %v", m.ID, err) } diff --git a/models/repo/pushmirror.go b/models/repo/pushmirror.go index 55fde8b838e..f79ce59ee22 100644 --- a/models/repo/pushmirror.go +++ b/models/repo/pushmirror.go @@ -61,7 +61,7 @@ func (m *PushMirror) GetRepository() *Repository { return m.Repo } var err error - m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID) + m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID) if err != nil { log.Error("getRepositoryByID[%d]: %v", m.ID, err) } diff --git a/models/repo/release.go b/models/repo/release.go index da6235988a7..c6cb7553445 100644 --- a/models/repo/release.go +++ b/models/repo/release.go @@ -93,13 +93,13 @@ func init() { func (r *Release) LoadAttributes(ctx context.Context) error { var err error if r.Repo == nil { - r.Repo, err = GetRepositoryByIDCtx(ctx, r.RepoID) + r.Repo, err = GetRepositoryByID(ctx, r.RepoID) if err != nil { return err } } if r.Publisher == nil { - r.Publisher, err = user_model.GetUserByIDCtx(ctx, r.PublisherID) + r.Publisher, err = user_model.GetUserByID(ctx, r.PublisherID) if err != nil { if user_model.IsErrUserNotExist(err) { r.Publisher = user_model.NewGhostUser() diff --git a/models/repo/repo.go b/models/repo/repo.go index f58b7de6edf..7cb7138523f 100644 --- a/models/repo/repo.go +++ b/models/repo/repo.go @@ -315,7 +315,7 @@ func (repo *Repository) LoadUnits(ctx context.Context) (err error) { } // UnitEnabled if this repository has the given unit enabled -func (repo *Repository) UnitEnabled(tp unit.Type) (result bool) { +func (repo *Repository) UnitEnabled(tp unit.Type) (result bool) { // Notice: Don't remove this function directly, because it has been used in go template. return repo.UnitEnabledCtx(db.DefaultContext, tp) } @@ -390,7 +390,7 @@ func (repo *Repository) GetOwner(ctx context.Context) (err error) { return nil } - repo.Owner, err = user_model.GetUserByIDCtx(ctx, repo.OwnerID) + repo.Owner, err = user_model.GetUserByID(ctx, repo.OwnerID) return err } @@ -467,16 +467,12 @@ func (repo *Repository) ComposeDocumentMetas() map[string]string { // 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.DefaultContext) -} - -func (repo *Repository) getBaseRepo(ctx context.Context) (err error) { +func (repo *Repository) GetBaseRepo(ctx context.Context) (err error) { if !repo.IsFork { return nil } - repo.BaseRepo, err = GetRepositoryByIDCtx(ctx, repo.ForkID) + repo.BaseRepo, err = GetRepositoryByID(ctx, repo.ForkID) return err } @@ -611,11 +607,6 @@ func (repo *Repository) GetTrustModel() TrustModelType { return trustModel } -// GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. -func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { - return GetRepositoryByOwnerAndNameCtx(db.DefaultContext, ownerName, repoName) -} - // __________ .__ __ // \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. // | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | @@ -647,8 +638,8 @@ func (err ErrRepoNotExist) Unwrap() error { return util.ErrNotExist } -// GetRepositoryByOwnerAndNameCtx returns the repository by given owner name and repo name -func GetRepositoryByOwnerAndNameCtx(ctx context.Context, ownerName, repoName string) (*Repository, error) { +// GetRepositoryByOwnerAndName returns the repository by given owner name and repo name +func GetRepositoryByOwnerAndName(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"). @@ -678,8 +669,8 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { return repo, err } -// GetRepositoryByIDCtx returns the repository by given id if exists. -func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { +// GetRepositoryByID returns the repository by given id if exists. +func GetRepositoryByID(ctx context.Context, id int64) (*Repository, error) { repo := new(Repository) has, err := db.GetEngine(ctx).ID(id).Get(repo) if err != nil { @@ -690,11 +681,6 @@ func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { return repo, nil } -// GetRepositoryByID returns the repository by given id if exists. -func GetRepositoryByID(id int64) (*Repository, error) { - return GetRepositoryByIDCtx(db.DefaultContext, id) -} - // GetRepositoriesMapByIDs returns the repositories by given id slice. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { repos := make(map[int64]*Repository, len(ids)) @@ -722,7 +708,7 @@ func GetTemplateRepo(ctx context.Context, repo *Repository) (*Repository, error) return nil, nil } - return GetRepositoryByIDCtx(ctx, repo.TemplateID) + return GetRepositoryByID(ctx, repo.TemplateID) } // TemplateRepo returns the repository, which is template of this repository diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go index 081221d1dfe..fb473151eb3 100644 --- a/models/repo/repo_test.go +++ b/models/repo/repo_test.go @@ -115,7 +115,7 @@ func TestMetas(t *testing.T) { externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp testSuccess(markup.IssueNameStyleRegexp) - repo, err := repo_model.GetRepositoryByID(3) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3) assert.NoError(t, err) metas = repo.ComposeMetas() diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index 2c04cb442b2..b85880eab9c 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -53,7 +53,7 @@ func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) { } func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error { - user, err := user_model.GetUserByIDCtx(ctx, uid) + user, err := user_model.GetUserByID(ctx, uid) if err != nil { return err } diff --git a/models/repo_transfer.go b/models/repo_transfer.go index 6f02ab45fe2..362253bdc8a 100644 --- a/models/repo_transfer.go +++ b/models/repo_transfer.go @@ -41,7 +41,7 @@ func init() { // LoadAttributes fetches the transfer recipient from the database func (r *RepoTransfer) LoadAttributes() error { if r.Recipient == nil { - u, err := user_model.GetUserByID(r.RecipientID) + u, err := user_model.GetUserByID(db.DefaultContext, r.RecipientID) if err != nil { return err } @@ -65,7 +65,7 @@ func (r *RepoTransfer) LoadAttributes() error { } if r.Doer == nil { - u, err := user_model.GetUserByID(r.DoerID) + u, err := user_model.GetUserByID(db.DefaultContext, r.DoerID) if err != nil { return err } @@ -161,7 +161,7 @@ func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int } defer committer.Close() - repo, err := repo_model.GetRepositoryByIDCtx(ctx, repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { return err } diff --git a/models/user/email_address.go b/models/user/email_address.go index 70394edb23f..69e94f8bb6b 100644 --- a/models/user/email_address.go +++ b/models/user/email_address.go @@ -332,7 +332,7 @@ func ActivateEmail(email *EmailAddress) error { } func updateActivation(ctx context.Context, email *EmailAddress, activate bool) error { - user, err := GetUserByIDCtx(ctx, email.UID) + user, err := GetUserByID(ctx, email.UID) if err != nil { return err } diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index 7e523a165df..53fd18c303e 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -162,7 +162,7 @@ func TestMakeEmailPrimary(t *testing.T) { err = user_model.MakeEmailPrimary(email) assert.NoError(t, err) - user, _ := user_model.GetUserByID(int64(10)) + user, _ := user_model.GetUserByID(db.DefaultContext, int64(10)) assert.Equal(t, "user101@example.com", user.Email) } diff --git a/models/user/user.go b/models/user/user.go index 915e4243cf2..71b036b06f1 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -993,12 +993,7 @@ func UserPath(userName string) string { //revive:disable-line:exported } // GetUserByID returns the user object by given ID if exists. -func GetUserByID(id int64) (*User, error) { - return GetUserByIDCtx(db.DefaultContext, id) -} - -// GetUserByIDCtx returns the user object by given ID if exists. -func GetUserByIDCtx(ctx context.Context, id int64) (*User, error) { +func GetUserByID(ctx context.Context, id int64) (*User, error) { u := new(User) has, err := db.GetEngine(ctx).ID(id).Get(u) if err != nil { @@ -1176,7 +1171,7 @@ func GetUserByEmailContext(ctx context.Context, email string) (*User, error) { return nil, err } if has { - return GetUserByIDCtx(ctx, emailAddress.UID) + return GetUserByID(ctx, emailAddress.UID) } // Finally, if email address is the protected email address: @@ -1220,7 +1215,7 @@ func GetUserByOpenID(uri string) (*User, error) { return nil, err } if has { - return GetUserByID(oid.UID) + return GetUserByID(db.DefaultContext, oid.UID) } return nil, ErrUserNotExist{0, uri, 0} diff --git a/models/user/user_test.go b/models/user/user_test.go index 2ee4da0d67f..525da531f23 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -22,7 +22,7 @@ import ( func TestOAuth2Application_LoadUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1}) - user, err := user_model.GetUserByID(app.UID) + user, err := user_model.GetUserByID(db.DefaultContext, app.UID) assert.NoError(t, err) assert.NotNil(t, user) } diff --git a/modules/context/context.go b/modules/context/context.go index 0d632b67c05..0fe00bf787e 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -139,7 +139,7 @@ func (ctx *Context) IsUserRepoReaderAny() bool { // RedirectToUser redirect to a differently-named user func RedirectToUser(ctx *Context, userName string, redirectUserID int64) { - user, err := user_model.GetUserByID(redirectUserID) + user, err := user_model.GetUserByID(ctx, redirectUserID) if err != nil { ctx.ServerError("GetUserByID", err) return diff --git a/modules/context/repo.go b/modules/context/repo.go index 57cf2fae5ac..a50cb15abe2 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -264,7 +264,7 @@ func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (*editorconfig.Ed // RetrieveBaseRepo retrieves base 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 err := repo.GetBaseRepo(ctx); err != nil { if repo_model.IsErrRepoNotExist(err) { repo.IsFork = false repo.ForkID = 0 @@ -335,7 +335,7 @@ func RedirectToRepo(ctx *Context, redirectRepoID int64) { ownerName := ctx.Params(":username") previousRepoName := ctx.Params(":reponame") - repo, err := repo_model.GetRepositoryByID(redirectRepoID) + repo, err := repo_model.GetRepositoryByID(ctx, redirectRepoID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -410,7 +410,7 @@ func RepoIDAssignment() func(ctx *Context) { repoID := ctx.ParamsInt64(":repoid") // Get repository. - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) diff --git a/modules/convert/convert.go b/modules/convert/convert.go index 107854e0133..756a1f95d90 100644 --- a/modules/convert/convert.go +++ b/modules/convert/convert.go @@ -5,6 +5,7 @@ package convert import ( + "context" "fmt" "strconv" "strings" @@ -408,8 +409,8 @@ func ToOAuth2Application(app *auth.OAuth2Application) *api.OAuth2Application { } // ToLFSLock convert a LFSLock to api.LFSLock -func ToLFSLock(l *git_model.LFSLock) *api.LFSLock { - u, err := user_model.GetUserByID(l.OwnerID) +func ToLFSLock(ctx context.Context, l *git_model.LFSLock) *api.LFSLock { + u, err := user_model.GetUserByID(ctx, l.OwnerID) if err != nil { return nil } diff --git a/modules/convert/issue.go b/modules/convert/issue.go index ff3466cb3f6..221aeb885a9 100644 --- a/modules/convert/issue.go +++ b/modules/convert/issue.go @@ -149,7 +149,7 @@ func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) { } repo, ok = repoCache[issue.RepoID] if !ok { - repo, err = repo_model.GetRepositoryByID(issue.RepoID) + repo, err = repo_model.GetRepositoryByID(db.DefaultContext, issue.RepoID) if err != nil { return nil, err } diff --git a/modules/convert/issue_comment.go b/modules/convert/issue_comment.go index 81cd1ac245e..c4fed6b8a1f 100644 --- a/modules/convert/issue_comment.go +++ b/modules/convert/issue_comment.go @@ -138,15 +138,15 @@ func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_ var repo *repo_model.Repository if c.Label.BelongsToOrg() { var err error - org, err = user_model.GetUserByIDCtx(ctx, c.Label.OrgID) + org, err = user_model.GetUserByID(ctx, c.Label.OrgID) if err != nil { - log.Error("GetUserByIDCtx(%d): %v", c.Label.OrgID, err) + log.Error("GetUserByID(%d): %v", c.Label.OrgID, err) return nil } } if c.Label.BelongsToRepo() { var err error - repo, err = repo_model.GetRepositoryByIDCtx(ctx, c.Label.RepoID) + repo, err = repo_model.GetRepositoryByID(ctx, c.Label.RepoID) if err != nil { log.Error("GetRepositoryByIDCtx(%d): %v", c.Label.RepoID, err) return nil diff --git a/modules/convert/notification.go b/modules/convert/notification.go index 49a1b148fb1..5d3b078a25d 100644 --- a/modules/convert/notification.go +++ b/modules/convert/notification.go @@ -7,6 +7,7 @@ import ( "net/url" activities_model "code.gitea.io/gitea/models/activities" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" api "code.gitea.io/gitea/modules/structs" ) @@ -23,7 +24,7 @@ func ToNotificationThread(n *activities_model.Notification) *api.NotificationThr // since user only get notifications when he has access to use minimal access mode if n.Repository != nil { - result.Repository = ToRepo(n.Repository, perm.AccessModeRead) + result.Repository = ToRepo(db.DefaultContext, n.Repository, perm.AccessModeRead) // This permission is not correct and we should not be reporting it for repository := result.Repository; repository != nil; repository = repository.Parent { diff --git a/modules/convert/package.go b/modules/convert/package.go index 900f1dd816b..68ae6f4e62d 100644 --- a/modules/convert/package.go +++ b/modules/convert/package.go @@ -22,7 +22,7 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m } if permission.HasAccess() { - repo = ToRepo(pd.Repository, permission.AccessMode) + repo = ToRepo(ctx, pd.Repository, permission.AccessMode) } } diff --git a/modules/convert/pull.go b/modules/convert/pull.go index 4291d737a4d..db0add6cdee 100644 --- a/modules/convert/pull.go +++ b/modules/convert/pull.go @@ -79,7 +79,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u Name: pr.BaseBranch, Ref: pr.BaseBranch, RepoID: pr.BaseRepoID, - Repository: ToRepo(pr.BaseRepo, p.AccessMode), + Repository: ToRepo(ctx, pr.BaseRepo, p.AccessMode), }, Head: &api.PRBranchInfo{ Name: pr.HeadBranch, @@ -139,7 +139,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u } apiPullRequest.Head.RepoID = pr.HeadRepo.ID - apiPullRequest.Head.Repository = ToRepo(pr.HeadRepo, p.AccessMode) + apiPullRequest.Head.Repository = ToRepo(ctx, pr.HeadRepo, p.AccessMode) headGitRepo, err := git.OpenRepository(ctx, pr.HeadRepo.RepoPath()) if err != nil { diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index 21d410cfcb5..0915d096e66 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -31,7 +31,7 @@ func TestPullRequest_APIFormat(t *testing.T) { Ref: "refs/pull/2/head", Sha: "4a357436d925b5c974181ff12a994538ddc5a269", RepoID: 1, - Repository: ToRepo(headRepo, perm.AccessModeRead), + Repository: ToRepo(db.DefaultContext, headRepo, perm.AccessModeRead), }, apiPullRequest.Head) // withOut HeadRepo diff --git a/modules/convert/repository.go b/modules/convert/repository.go index 3c75f588fdf..843556e1b12 100644 --- a/modules/convert/repository.go +++ b/modules/convert/repository.go @@ -4,6 +4,7 @@ package convert import ( + "context" "time" "code.gitea.io/gitea/models" @@ -16,11 +17,11 @@ import ( ) // ToRepo converts a Repository to api.Repository -func ToRepo(repo *repo_model.Repository, mode perm.AccessMode) *api.Repository { - return innerToRepo(repo, mode, false) +func ToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode) *api.Repository { + return innerToRepo(ctx, repo, mode, false) } -func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository { +func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository { var parent *api.Repository cloneLink := repo.CloneLink() @@ -30,12 +31,12 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo Pull: mode >= perm.AccessModeRead, } if !isParent { - err := repo.GetBaseRepo() + err := repo.GetBaseRepo(ctx) if err != nil { return nil } if repo.BaseRepo != nil { - parent = innerToRepo(repo.BaseRepo, mode, true) + parent = innerToRepo(ctx, repo.BaseRepo, mode, true) } } diff --git a/modules/convert/status.go b/modules/convert/status.go index 5eb38ad063d..5fcf04074f8 100644 --- a/modules/convert/status.go +++ b/modules/convert/status.go @@ -4,13 +4,15 @@ package convert import ( + "context" + git_model "code.gitea.io/gitea/models/git" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" ) // ToCommitStatus converts git_model.CommitStatus to api.CommitStatus -func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { +func ToCommitStatus(ctx context.Context, status *git_model.CommitStatus) *api.CommitStatus { apiStatus := &api.CommitStatus{ Created: status.CreatedUnix.AsTime(), Updated: status.CreatedUnix.AsTime(), @@ -23,7 +25,7 @@ func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { } if status.CreatorID != 0 { - creator, _ := user_model.GetUserByID(status.CreatorID) + creator, _ := user_model.GetUserByID(ctx, status.CreatorID) apiStatus.Creator = ToUser(creator, nil) } @@ -31,7 +33,7 @@ func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { } // ToCombinedStatus converts List of CommitStatus to a CombinedStatus -func ToCombinedStatus(statuses []*git_model.CommitStatus, repo *api.Repository) *api.CombinedStatus { +func ToCombinedStatus(ctx context.Context, statuses []*git_model.CommitStatus, repo *api.Repository) *api.CombinedStatus { if len(statuses) == 0 { return nil } @@ -45,7 +47,7 @@ func ToCombinedStatus(statuses []*git_model.CommitStatus, repo *api.Repository) retStatus.Statuses = make([]*api.CommitStatus, 0, len(statuses)) for _, status := range statuses { - retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(status)) + retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(ctx, status)) if status.State.NoBetterThan(retStatus.State) { retStatus.State = status.State } diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index d07ab10db06..027d13555c0 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -84,7 +84,7 @@ type IndexerData struct { var indexerQueue queue.UniqueQueue func index(ctx context.Context, indexer Indexer, repoID int64) error { - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if repo_model.IsErrRepoNotExist(err) { return indexer.Delete(repoID) } diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go index 068626c4fae..9bbdcad60d4 100644 --- a/modules/indexer/stats/db.go +++ b/modules/indexer/stats/db.go @@ -21,7 +21,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 := repo_model.GetRepositoryByID(id) + repo, err := repo_model.GetRepositoryByID(ctx, id) if err != nil { return err } diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index f9a1bc520a2..bc6c4cd7f85 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -36,7 +36,7 @@ func TestRepoStatsIndex(t *testing.T) { err := Init() assert.NoError(t, err) - repo, err := repo_model.GetRepositoryByID(1) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1) assert.NoError(t, err) err = UpdateRepoIndexer(repo) diff --git a/modules/notification/webhook/webhook.go b/modules/notification/webhook/webhook.go index 326d987ba53..63345830585 100644 --- a/modules/notification/webhook/webhook.go +++ b/modules/notification/webhook/webhook.go @@ -58,7 +58,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user Action: api.HookIssueLabelCleared, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { @@ -66,7 +66,7 @@ func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user Action: api.HookIssueLabelCleared, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -81,8 +81,8 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m // forked webhook if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{ - Forkee: convert.ToRepo(oldRepo, oldMode), - Repo: convert.ToRepo(repo, mode), + Forkee: convert.ToRepo(ctx, oldRepo, oldMode), + Repo: convert.ToRepo(ctx, repo, mode), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err) @@ -94,7 +94,7 @@ func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_m if u.IsOrganization() { if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -107,7 +107,7 @@ func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u // Add to hook queue for created repo after session commit. if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -118,7 +118,7 @@ func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *u func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoDeleted, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(repo.MustOwner(ctx), nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -130,7 +130,7 @@ func (m *webhookNotifier) NotifyMigrateRepository(ctx context.Context, doer, u * // Add to hook queue for created repo after session commit. if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -150,7 +150,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u apiPullRequest := &api.PullRequestPayload{ Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if removed { @@ -168,7 +168,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *u apiIssue := &api.IssuePayload{ Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if removed { @@ -202,7 +202,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user }, }, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { @@ -215,7 +215,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user }, }, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -237,7 +237,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use apiPullRequest := &api.PullRequestPayload{ Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if isClosed { @@ -250,7 +250,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *use apiIssue := &api.IssuePayload{ Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if isClosed { @@ -280,7 +280,7 @@ func (m *webhookNotifier) NotifyNewIssue(ctx context.Context, issue *issues_mode Action: api.HookIssueOpened, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(issue.Poster, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) @@ -306,7 +306,7 @@ func (m *webhookNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues Action: api.HookIssueOpened, Index: pull.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pull, nil), - Repository: convert.ToRepo(pull.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, pull.Issue.Repo, mode), Sender: convert.ToUser(pull.Issue.Poster, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) @@ -327,7 +327,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us }, }, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { @@ -340,7 +340,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *us }, }, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -381,7 +381,7 @@ func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_mo From: oldContent, }, }, - Repository: convert.ToRepo(c.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, c.Issue.Repo, mode), Sender: convert.ToUser(doer, nil), IsPull: c.Issue.IsPull, }); err != nil { @@ -404,7 +404,7 @@ func (m *webhookNotifier) NotifyCreateIssueComment(ctx context.Context, doer *us Action: api.HookIssueCommentCreated, Issue: convert.ToAPIIssue(ctx, issue), Comment: convert.ToComment(comment), - Repository: convert.ToRepo(repo, mode), + Repository: convert.ToRepo(ctx, repo, mode), Sender: convert.ToUser(doer, nil), IsPull: issue.IsPull, }); err != nil { @@ -441,7 +441,7 @@ func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_mo Action: api.HookIssueCommentDeleted, Issue: convert.ToAPIIssue(ctx, comment.Issue), Comment: convert.ToComment(comment), - Repository: convert.ToRepo(comment.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, comment.Issue.Repo, mode), Sender: convert.ToUser(doer, nil), IsPull: comment.Issue.IsPull, }); err != nil { @@ -453,7 +453,7 @@ func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_mode // Add to hook queue for created wiki page. if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), Page: page, Comment: comment, @@ -466,7 +466,7 @@ func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_mod // Add to hook queue for edit wiki page. if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiEdited, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), Page: page, Comment: comment, @@ -479,7 +479,7 @@ func (m *webhookNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_m // Add to hook queue for edit wiki page. if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiDeleted, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), Page: page, }); err != nil { @@ -516,7 +516,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use Action: api.HookIssueLabelUpdated, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, perm.AccessModeNone), + Repository: convert.ToRepo(ctx, issue.Repo, perm.AccessModeNone), Sender: convert.ToUser(doer, nil), }) } else { @@ -524,7 +524,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *use Action: api.HookIssueLabelUpdated, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -558,7 +558,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * Action: hookAction, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { @@ -566,7 +566,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer * Action: hookAction, Index: issue.Index, Issue: convert.ToAPIIssue(ctx, issue), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -591,7 +591,7 @@ func (m *webhookNotifier) NotifyPushCommits(ctx context.Context, pusher *user_mo Commits: apiCommits, TotalCommits: commits.Len, HeadCommit: apiHeadCommit, - Repo: convert.ToRepo(repo, perm.AccessModeOwner), + Repo: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Pusher: apiPusher, Sender: apiPusher, }); err != nil { @@ -631,7 +631,7 @@ func (*webhookNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_m apiPullRequest := &api.PullRequestPayload{ Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(pr.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, pr.Issue.Repo, mode), Sender: convert.ToUser(doer, nil), Action: api.HookIssueClosed, } @@ -659,7 +659,7 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Contex }, }, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks [pr: %d]: %v", pr.ID, err) @@ -696,7 +696,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue Action: api.HookIssueReviewed, Index: review.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(review.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, review.Issue.Repo, mode), Sender: convert.ToUser(review.Reviewer, nil), Review: &api.ReviewPayload{ Type: string(reviewHookType), @@ -709,7 +709,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issue func (m *webhookNotifier) NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { apiPusher := convert.ToUser(pusher, nil) - apiRepo := convert.ToRepo(repo, perm.AccessModeNone) + apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{ @@ -737,7 +737,7 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe Action: api.HookIssueSynchronized, Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(pr.Issue.Repo, perm.AccessModeNone), + Repository: convert.ToRepo(ctx, pr.Issue.Repo, perm.AccessModeNone), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err) @@ -746,7 +746,7 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doe func (m *webhookNotifier) NotifyDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { apiPusher := convert.ToUser(pusher, nil) - apiRepo := convert.ToRepo(repo, perm.AccessModeNone) + apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{ @@ -770,7 +770,7 @@ func sendReleaseHook(ctx context.Context, doer *user_model.User, rel *repo_model if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{ Action: action, Release: convert.ToRelease(rel), - Repository: convert.ToRepo(rel.Repo, mode), + Repository: convert.ToRepo(ctx, rel.Repo, mode), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) @@ -805,7 +805,7 @@ func (m *webhookNotifier) NotifySyncPushCommits(ctx context.Context, pusher *use Commits: apiCommits, TotalCommits: commits.Len, HeadCommit: apiHeadCommit, - Repo: convert.ToRepo(repo, perm.AccessModeOwner), + Repo: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Pusher: apiPusher, Sender: apiPusher, }); err != nil { diff --git a/modules/repository/create_test.go b/modules/repository/create_test.go index 94a9b26aa69..da4a738b649 100644 --- a/modules/repository/create_test.go +++ b/modules/repository/create_test.go @@ -25,7 +25,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { testTeamRepositories := func(teamID int64, repoIds []int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext), "%s: GetRepositories", team.Name) + assert.NoError(t, team.LoadRepositories(db.DefaultContext), "%s: GetRepositories", team.Name) assert.Len(t, team.Repos, team.NumRepos, "%s: len repo", team.Name) assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) for i, rid := range repoIds { @@ -36,7 +36,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } // Get an admin user. - user, err := user_model.GetUserByID(1) + user, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err, "GetUserByID") // Create org. @@ -153,7 +153,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility - repo, err := repo_model.GetRepositoryByID(9) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 9) assert.NoError(t, err) repo.IsPrivate = true diff --git a/modules/repository/generate.go b/modules/repository/generate.go index 5726a8fb1b4..d72934729cd 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -243,7 +243,7 @@ func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *r } // re-fetch repo - if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %w", err) } diff --git a/modules/repository/init.go b/modules/repository/init.go index cd7176c238d..59284a5bafc 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -414,7 +414,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 = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %w", err) } diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 5fa9e17c8a1..7b997b49d9e 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -25,6 +25,7 @@ import ( activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/avatars" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" @@ -631,7 +632,7 @@ func Avatar(item interface{}, others ...interface{}) template.HTML { // AvatarByAction renders user avatars from action. args: action, size (int), class (string) func AvatarByAction(action *activities_model.Action, others ...interface{}) template.HTML { - action.LoadActUser() + action.LoadActUser(db.DefaultContext) return Avatar(action.ActUser, others...) } diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index 61e49adb765..d50f8efc755 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -57,7 +57,7 @@ func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) { ctx.Repo = &context.Repository{} ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) var err error - ctx.Repo.Owner, err = user_model.GetUserByID(ctx.Repo.Repository.OwnerID) + ctx.Repo.Owner, err = user_model.GetUserByID(ctx, ctx.Repo.Repository.OwnerID) assert.NoError(t, err) ctx.Repo.RepoLink = ctx.Repo.Repository.Link() ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, ctx.Doer) diff --git a/routers/api/packages/conan/auth.go b/routers/api/packages/conan/auth.go index fe33e2c7404..f3adaf7beee 100644 --- a/routers/api/packages/conan/auth.go +++ b/routers/api/packages/conan/auth.go @@ -30,7 +30,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return nil } - u, err := user_model.GetUserByID(uid) + u, err := user_model.GetUserByID(req.Context(), uid) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/routers/api/packages/container/auth.go b/routers/api/packages/container/auth.go index 948001dcad7..e134f74c8f2 100644 --- a/routers/api/packages/container/auth.go +++ b/routers/api/packages/container/auth.go @@ -34,7 +34,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return user_model.NewGhostUser() } - u, err := user_model.GetUserByID(uid) + u, err := user_model.GetUserByID(req.Context(), uid) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/routers/api/packages/nuget/auth.go b/routers/api/packages/nuget/auth.go index 2be102a38ba..890c9301840 100644 --- a/routers/api/packages/nuget/auth.go +++ b/routers/api/packages/nuget/auth.go @@ -29,7 +29,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return nil } - u, err := user_model.GetUserByID(token.UID) + u, err := user_model.GetUserByID(req.Context(), token.UID) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index f233494fa52..798b792e71e 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -546,7 +546,7 @@ func GetTeamRepos(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) return } - repos[i] = convert.ToRepo(repo, access) + repos[i] = convert.ToRepo(ctx, repo, access) } ctx.SetTotalCountHeader(int64(team.NumRepos)) ctx.JSON(http.StatusOK, repos) @@ -598,7 +598,7 @@ func GetTeamRepo(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToRepo(repo, access)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, access)) } // getRepositoryByParams get repository by a team's organization ID and repo name diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index e2cb4400f59..f2cd10e711a 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -63,7 +63,7 @@ func ListForks(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } - apiForks[i] = convert.ToRepo(fork, access) + apiForks[i] = convert.ToRepo(ctx, fork, access) } ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumForks)) @@ -150,5 +150,5 @@ func CreateFork(ctx *context.APIContext) { } // TODO change back to 201 - ctx.JSON(http.StatusAccepted, convert.ToRepo(fork, perm.AccessModeOwner)) + ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, fork, perm.AccessModeOwner)) } diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 9b84fb2b301..0c3d59a4193 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -184,7 +184,7 @@ func TestHook(ctx *context.APIContext) { Commits: []*api.PayloadCommit{commit}, TotalCommits: 1, HeadCommit: commit, - Repo: convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone), + Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone), Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), }); err != nil { diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index c539a362388..30dc7a68326 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -623,7 +623,7 @@ func CreateIssue(ctx *context.APIContext) { // Check if the passed assignees is assignable for _, aID := range assigneeIDs { - assignee, err := user_model.GetUserByID(aID) + assignee, err := user_model.GetUserByID(ctx, aID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index 7f6f24605d0..120c1d88a0d 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -199,7 +199,7 @@ func isXRefCommentAccessible(ctx stdCtx.Context, user *user_model.User, c *issue if issues_model.CommentTypeIsRef(c.Type) && c.RefRepoID != issueRepoID && c.RefRepoID != 0 { var err error // Set RefRepo for description in template - c.RefRepo, err = repo_model.GetRepositoryByIDCtx(ctx, c.RefRepoID) + c.RefRepo, err = repo_model.GetRepositoryByID(ctx, c.RefRepoID) if err != nil { return false } diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index cff68504694..54313e8e764 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -5,6 +5,7 @@ package repo import ( + stdCtx "context" "fmt" "net/http" "net/url" @@ -23,16 +24,16 @@ import ( ) // appendPrivateInformation appends the owner and key type information to api.PublicKey -func appendPrivateInformation(apiKey *api.DeployKey, key *asymkey_model.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) { +func appendPrivateInformation(ctx stdCtx.Context, apiKey *api.DeployKey, key *asymkey_model.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) + apiKey.Repository = convert.ToRepo(ctx, repository, key.Mode) } else { - repo, err := repo_model.GetRepositoryByID(key.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID) if err != nil { return apiKey, err } - apiKey.Repository = convert.ToRepo(repo, key.Mode) + apiKey.Repository = convert.ToRepo(ctx, repo, key.Mode) } return apiKey, nil } @@ -107,7 +108,7 @@ func ListDeployKeys(ctx *context.APIContext) { } apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) { - apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], ctx.Repo.Repository) + apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], ctx.Repo.Repository) } } @@ -161,7 +162,7 @@ func GetDeployKey(ctx *context.APIContext) { apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) apiKey := convert.ToDeployKey(apiLink, key) if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) { - apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Repo.Repository) + apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Repo.Repository) } ctx.JSON(http.StatusOK, apiKey) } diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go index a0316c9a78f..35516ff58f3 100644 --- a/routers/api/v1/repo/migrate.go +++ b/routers/api/v1/repo/migrate.go @@ -66,7 +66,7 @@ func Migrate(ctx *context.APIContext) { if len(form.RepoOwner) != 0 { repoOwner, err = user_model.GetUserByName(ctx, form.RepoOwner) } else if form.RepoOwnerID != 0 { - repoOwner, err = user_model.GetUserByID(form.RepoOwnerID) + repoOwner, err = user_model.GetUserByID(ctx, form.RepoOwnerID) } else { repoOwner = ctx.Doer } @@ -211,7 +211,7 @@ func Migrate(ctx *context.APIContext) { } log.Trace("Repository migrated: %s/%s", repoOwner.Name, form.RepoName) - ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeAdmin)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeAdmin)) } func handleMigrateError(ctx *context.APIContext, repoOwner *user_model.User, remoteAddr string, err error) { diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 53505e998c2..1246ede9e6d 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -399,7 +399,7 @@ func CreatePullRequest(ctx *context.APIContext) { } // Check if the passed assignees is assignable for _, aID := range assigneeIDs { - assignee, err := user_model.GetUserByIDCtx(ctx, aID) + assignee, err := user_model.GetUserByID(ctx, aID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index e8603d19172..3b55b496a90 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -215,7 +215,7 @@ func Search(ctx *context.APIContext) { Error: err.Error(), }) } - results[i] = convert.ToRepo(repo, accessMode) + results[i] = convert.ToRepo(ctx, repo, accessMode) } ctx.SetLinkHeader(int(count), opts.PageSize) ctx.SetTotalCountHeader(count) @@ -257,12 +257,12 @@ 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 = repo_model.GetRepositoryByID(repo.ID) + repo, err = repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err) } - ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeOwner)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeOwner)) } // Create one repository of mine @@ -407,7 +407,7 @@ func Generate(ctx *context.APIContext) { } log.Trace("Repository generated [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) - ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeOwner)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeOwner)) } // CreateOrgRepoDeprecated create one repository of the organization @@ -523,7 +523,7 @@ func Get(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode)) } // GetByID returns a single Repository @@ -544,7 +544,7 @@ func GetByID(ctx *context.APIContext) { // "200": // "$ref": "#/responses/Repository" - repo, err := repo_model.GetRepositoryByID(ctx.ParamsInt64(":id")) + repo, err := repo_model.GetRepositoryByID(ctx, ctx.ParamsInt64(":id")) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound() @@ -562,7 +562,7 @@ func GetByID(ctx *context.APIContext) { ctx.NotFound() return } - ctx.JSON(http.StatusOK, convert.ToRepo(repo, perm.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, perm.AccessMode)) } // Edit edit repository properties @@ -618,13 +618,13 @@ func Edit(ctx *context.APIContext) { } } - repo, err := repo_model.GetRepositoryByID(ctx.Repo.Repository.ID) + repo, err := repo_model.GetRepositoryByID(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.InternalServerError(err) return } - ctx.JSON(http.StatusOK, convert.ToRepo(repo, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, ctx.Repo.AccessMode)) } // updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility @@ -669,7 +669,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if opts.Private != nil { // Visibility of forked repository is forced sync with base repository. if repo.IsFork { - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "Unable to load base repository", err) return err } diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index 84827a91adf..0b196d162c2 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -66,7 +66,7 @@ func NewCommitStatus(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToCommitStatus(status)) + ctx.JSON(http.StatusCreated, convert.ToCommitStatus(ctx, status)) } // GetCommitStatuses returns all statuses for any given commit hash @@ -199,7 +199,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) { apiStatuses := make([]*api.CommitStatus, 0, len(statuses)) for _, status := range statuses { - apiStatuses = append(apiStatuses, convert.ToCommitStatus(status)) + apiStatuses = append(apiStatuses, convert.ToCommitStatus(ctx, status)) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) @@ -263,7 +263,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) { return } - combiStatus := convert.ToCombinedStatus(statuses, convert.ToRepo(repo, ctx.Repo.AccessMode)) + combiStatus := convert.ToCombinedStatus(ctx, statuses, convert.ToRepo(ctx, repo, ctx.Repo.AccessMode)) ctx.SetTotalCountHeader(count) ctx.JSON(http.StatusOK, combiStatus) diff --git a/routers/api/v1/repo/transfer.go b/routers/api/v1/repo/transfer.go index a40419e13e3..fb15566a4b5 100644 --- a/routers/api/v1/repo/transfer.go +++ b/routers/api/v1/repo/transfer.go @@ -122,12 +122,12 @@ func Transfer(ctx *context.APIContext) { if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer { log.Trace("Repository transfer initiated: %s -> %s", oldFullname, ctx.Repo.Repository.FullName()) - ctx.JSON(http.StatusCreated, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeAdmin)) return } log.Trace("Repository transferred: %s -> %s", oldFullname, ctx.Repo.Repository.FullName()) - ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) + ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeAdmin)) } // AcceptTransfer accept a repo transfer @@ -165,7 +165,7 @@ func AcceptTransfer(ctx *context.APIContext) { return } - ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode)) } // RejectTransfer reject a repo transfer @@ -203,7 +203,7 @@ func RejectTransfer(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode)) } func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index d00eec85e49..25bda0444a5 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -7,6 +7,7 @@ import ( "net/http" asymkey_model "code.gitea.io/gitea/models/asymkey" + "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" @@ -29,7 +30,7 @@ func appendPrivateInformation(apiKey *api.PublicKey, key *asymkey_model.PublicKe if defaultUser.ID == key.OwnerID { apiKey.Owner = convert.ToUser(defaultUser, defaultUser) } else { - user, err := user_model.GetUserByID(key.OwnerID) + user, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) if err != nil { return apiKey, err } diff --git a/routers/api/v1/user/repo.go b/routers/api/v1/user/repo.go index 2af70f9ad39..e79a9d8f8b1 100644 --- a/routers/api/v1/user/repo.go +++ b/routers/api/v1/user/repo.go @@ -44,7 +44,7 @@ func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) { return } if ctx.IsSigned && ctx.Doer.IsAdmin || access >= perm.AccessModeRead { - apiRepos = append(apiRepos, convert.ToRepo(repos[i], access)) + apiRepos = append(apiRepos, convert.ToRepo(ctx, repos[i], access)) } } @@ -127,7 +127,7 @@ func ListMyRepos(ctx *context.APIContext) { if err != nil { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) } - results[i] = convert.ToRepo(repo, accessMode) + results[i] = convert.ToRepo(ctx, repo, accessMode) } ctx.SetLinkHeader(int(count), opts.ListOptions.PageSize) diff --git a/routers/api/v1/user/star.go b/routers/api/v1/user/star.go index 2ef5806974e..0475489640e 100644 --- a/routers/api/v1/user/star.go +++ b/routers/api/v1/user/star.go @@ -32,7 +32,7 @@ func getStarredRepos(ctx std_context.Context, user *user_model.User, private boo if err != nil { return nil, err } - repos[i] = convert.ToRepo(starred, access) + repos[i] = convert.ToRepo(ctx, starred, access) } return repos, nil } diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index 43c097444ec..707e5da0903 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -30,7 +30,7 @@ func getWatchedRepos(ctx std_context.Context, user *user_model.User, private boo if err != nil { return nil, 0, err } - repos[i] = convert.ToRepo(watched, access) + repos[i] = convert.ToRepo(ctx, watched, access) } return repos, total, nil } diff --git a/routers/private/hook_post_receive.go b/routers/private/hook_post_receive.go index 9c69f9c3458..c62038899d7 100644 --- a/routers/private/hook_post_receive.go +++ b/routers/private/hook_post_receive.go @@ -183,7 +183,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) { baseRepo = repo if repo.IsFork { - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err) ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{ Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err), diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go index 52a82bfa445..e49ae68a64b 100644 --- a/routers/private/hook_pre_receive.go +++ b/routers/private/hook_pre_receive.go @@ -464,7 +464,7 @@ func (ctx *preReceiveContext) loadPusherAndPermission() bool { return true } - user, err := user_model.GetUserByID(ctx.opts.UserID) + user, err := user_model.GetUserByID(ctx, ctx.opts.UserID) if err != nil { log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err) ctx.JSON(http.StatusInternalServerError, private.Response{ diff --git a/routers/private/internal_repo.go b/routers/private/internal_repo.go index 2e6f87d6b08..bd8db0a1854 100644 --- a/routers/private/internal_repo.go +++ b/routers/private/internal_repo.go @@ -68,7 +68,7 @@ func RepoAssignment(ctx *gitea_context.PrivateContext) context.CancelFunc { } func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *repo_model.Repository { - repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, 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 676d83d9e13..a86f6c05792 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -51,7 +51,7 @@ func ServNoCommand(ctx *context.PrivateContext) { results.Key = key if key.Type == asymkey_model.KeyTypeUser || key.Type == asymkey_model.KeyTypePrincipal { - user, err := user_model.GetUserByID(key.OwnerID) + user, err := user_model.GetUserByID(ctx, key.OwnerID) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.JSON(http.StatusUnauthorized, private.Response{ @@ -259,7 +259,7 @@ func ServCommand(ctx *context.PrivateContext) { } else { // Get the user represented by the Key var err error - user, err = user_model.GetUserByID(key.OwnerID) + user, err = user_model.GetUserByID(ctx, key.OwnerID) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.JSON(http.StatusUnauthorized, private.ErrServCommand{ diff --git a/routers/web/admin/repos.go b/routers/web/admin/repos.go index b488bbbd140..dc5432c5499 100644 --- a/routers/web/admin/repos.go +++ b/routers/web/admin/repos.go @@ -41,7 +41,7 @@ func Repos(ctx *context.Context) { // DeleteRepo delete one repository func DeleteRepo(ctx *context.Context) { - repo, err := repo_model.GetRepositoryByID(ctx.FormInt64("id")) + repo, err := repo_model.GetRepositoryByID(ctx, ctx.FormInt64("id")) if err != nil { ctx.ServerError("GetRepositoryByID", err) return diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 399633e39fe..38969dadaad 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -206,7 +206,7 @@ func NewUserPost(ctx *context.Context) { } func prepareUserInfo(ctx *context.Context) *user_model.User { - u, err := user_model.GetUserByID(ctx.ParamsInt64(":userid")) + u, err := user_model.GetUserByID(ctx, ctx.ParamsInt64(":userid")) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Redirect(setting.AppSubURL + "/admin/users") @@ -413,7 +413,7 @@ func EditUserPost(ctx *context.Context) { // DeleteUser response for deleting a user func DeleteUser(ctx *context.Context) { - u, err := user_model.GetUserByID(ctx.ParamsInt64(":userid")) + u, err := user_model.GetUserByID(ctx, ctx.ParamsInt64(":userid")) if err != nil { ctx.ServerError("GetUserByID", err) return diff --git a/routers/web/auth/2fa.go b/routers/web/auth/2fa.go index 2aacf230371..4791b043131 100644 --- a/routers/web/auth/2fa.go +++ b/routers/web/auth/2fa.go @@ -68,7 +68,7 @@ func TwoFactorPost(ctx *context.Context) { if ok && twofa.LastUsedPasscode != form.Passcode { remember := ctx.Session.Get("twofaRemember").(bool) - u, err := user_model.GetUserByID(id) + u, err := user_model.GetUserByID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -146,7 +146,7 @@ func TwoFactorScratchPost(ctx *context.Context) { } remember := ctx.Session.Get("twofaRemember").(bool) - u, err := user_model.GetUserByID(id) + u, err := user_model.GetUserByID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index 565a15bc11a..71a62bce654 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -747,7 +747,7 @@ func ActivateEmail(ctx *context.Context) { log.Trace("Email activated: %s", email.Email) ctx.Flash.Success(ctx.Tr("settings.add_email_success")) - if u, err := user_model.GetUserByID(email.UID); err != nil { + if u, err := user_model.GetUserByID(ctx, email.UID); err != nil { log.Warn("GetUserByID: %d", email.UID) } else if setting.CacheService.Enabled { // Allow user to validate more emails diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 2b872178cac..3d70ca9a506 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -194,7 +194,7 @@ func newAccessTokenResponse(ctx stdContext.Context, grant *auth.OAuth2Grant, ser ErrorDescription: "cannot find application", } } - user, err := user_model.GetUserByID(grant.UserID) + user, err := user_model.GetUserByID(ctx, grant.UserID) if err != nil { if user_model.IsErrUserNotExist(err) { return nil, &AccessTokenError{ @@ -385,7 +385,7 @@ func AuthorizeOAuth(ctx *context.Context) { var user *user_model.User if app.UID != 0 { - user, err = user_model.GetUserByID(app.UID) + user, err = user_model.GetUserByID(ctx, app.UID) if err != nil { ctx.ServerError("GetUserByID", err) return @@ -1222,7 +1222,7 @@ func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, res return nil, goth.User{}, err } if hasUser { - user, err = user_model.GetUserByID(externalLoginUser.UserID) + user, err = user_model.GetUserByID(request.Context(), externalLoginUser.UserID) return user, gothUser, err } diff --git a/routers/web/auth/webauthn.go b/routers/web/auth/webauthn.go index b60007bc032..965fc10fe7d 100644 --- a/routers/web/auth/webauthn.go +++ b/routers/web/auth/webauthn.go @@ -49,7 +49,7 @@ func WebAuthnLoginAssertion(ctx *context.Context) { return } - user, err := user_model.GetUserByID(idSess) + user, err := user_model.GetUserByID(ctx, idSess) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -91,7 +91,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) { }() // Load the user from the db - user, err := user_model.GetUserByID(idSess) + user, err := user_model.GetUserByID(ctx, idSess) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/feed/convert.go b/routers/web/feed/convert.go index e0e481d1a56..7d472a7f87c 100644 --- a/routers/web/feed/convert.go +++ b/routers/web/feed/convert.go @@ -68,7 +68,7 @@ func renderMarkdown(ctx *context.Context, act *activities_model.Action, content // feedActionsToFeedItems convert gitea's Action feed to feeds Item func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) { for _, act := range actions { - act.LoadActUser() + act.LoadActUser(ctx) var content, desc, title string diff --git a/routers/web/goget.go b/routers/web/goget.go index b8e264c4415..fb8afae9991 100644 --- a/routers/web/goget.go +++ b/routers/web/goget.go @@ -52,7 +52,7 @@ func goGet(ctx *context.Context) { } branchName := setting.Repository.DefaultBranch - repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, ownerName, repoName) if err == nil && len(repo.DefaultBranch) > 0 { branchName = repo.DefaultBranch } diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index d12e2fcc453..5dd86fdf117 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -49,7 +49,7 @@ func Teams(ctx *context.Context) { ctx.Data["PageIsOrgTeams"] = true for _, t := range ctx.Org.Teams { - if err := t.GetMembersCtx(ctx); err != nil { + if err := t.LoadMembers(ctx); err != nil { ctx.ServerError("GetMembers", err) return } @@ -346,7 +346,7 @@ func TeamMembers(ctx *context.Context) { ctx.Data["Title"] = ctx.Org.Team.Name ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamMembers"] = true - if err := ctx.Org.Team.GetMembersCtx(ctx); err != nil { + if err := ctx.Org.Team.LoadMembers(ctx); err != nil { ctx.ServerError("GetMembers", err) return } @@ -368,7 +368,7 @@ func TeamRepositories(ctx *context.Context) { ctx.Data["Title"] = ctx.Org.Team.Name ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamRepos"] = true - if err := ctx.Org.Team.GetRepositoriesCtx(ctx); err != nil { + if err := ctx.Org.Team.LoadRepositories(ctx); err != nil { ctx.ServerError("GetRepositories", err) return } @@ -570,7 +570,7 @@ func getTeamInviteFromContext(ctx *context.Context) (*org_model.TeamInvite, *org return nil, nil, nil, nil, err } - inviter, err := user_model.GetUserByIDCtx(ctx, invite.InviterID) + inviter, err := user_model.GetUserByID(ctx, invite.InviterID) if err != nil { return nil, nil, nil, nil, err } @@ -580,7 +580,7 @@ func getTeamInviteFromContext(ctx *context.Context) (*org_model.TeamInvite, *org return nil, nil, nil, nil, err } - org, err := user_model.GetUserByIDCtx(ctx, team.OrgID) + org, err := user_model.GetUserByID(ctx, team.OrgID) if err != nil { return nil, nil, nil, nil, err } diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go index d12fa60dafc..656e40f8781 100644 --- a/routers/web/repo/attachment.go +++ b/routers/web/repo/attachment.go @@ -94,7 +94,7 @@ func GetAttachment(ctx *context.Context) { return } - repository, unitType, err := repo_service.LinkedRepository(attach) + repository, unitType, err := repo_service.LinkedRepository(ctx, attach) if err != nil { ctx.ServerError("LinkedRepository", err) return diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index 61fb24d0587..18bb06ed1a2 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -337,7 +337,7 @@ func getDeletedBranches(ctx *context.Context) ([]*Branch, error) { } for i := range deletedBranches { - deletedBranches[i].LoadUser() + deletedBranches[i].LoadUser(ctx) branches = append(branches, &Branch{ Name: deletedBranches[i].Name, IsDeleted: true, diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index a9d6eea1ebe..b2d8f8645df 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -269,7 +269,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { ci.HeadRepo = baseRepo } } else { - ci.HeadRepo, err = repo_model.GetRepositoryByOwnerAndName(headInfosSplit[0], headInfosSplit[1]) + ci.HeadRepo, err = repo_model.GetRepositoryByOwnerAndName(ctx, headInfosSplit[0], headInfosSplit[1]) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByOwnerAndName", nil) @@ -339,7 +339,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { // forked from var rootRepo *repo_model.Repository if baseRepo.IsFork { - err = baseRepo.GetBaseRepo() + err = baseRepo.GetBaseRepo(ctx) if err != nil { if !repo_model.IsErrRepoNotExist(err) { ctx.ServerError("Unable to find root repo", err) diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 2a0a849b5ba..a531e832068 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -1007,7 +1007,7 @@ func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull // Check if the passed assignees actually exists and is assignable for _, aID := range assigneeIDs { - assignee, err := user_model.GetUserByID(aID) + assignee, err := user_model.GetUserByID(ctx, aID) if err != nil { ctx.ServerError("GetUserByID", err) return nil, nil, 0, 0 @@ -1679,7 +1679,7 @@ func ViewIssue(ctx *context.Context) { } ctx.Data["DefaultSquashMergeMessage"] = defaultSquashMergeMessage - if err = pull.LoadProtectedBranch(); err != nil { + if err = pull.LoadProtectedBranch(ctx); err != nil { ctx.ServerError("LoadProtectedBranch", err) return } @@ -2062,7 +2062,7 @@ func UpdateIssueAssignee(ctx *context.Context) { return } default: - assignee, err := user_model.GetUserByID(assigneeID) + assignee, err := user_model.GetUserByID(ctx, assigneeID) if err != nil { ctx.ServerError("GetUserByID", err) return @@ -2173,7 +2173,7 @@ func UpdatePullReviewRequest(ctx *context.Context) { continue } - reviewer, err := user_model.GetUserByID(reviewID) + reviewer, err := user_model.GetUserByID(ctx, reviewID) if err != nil { if user_model.IsErrUserNotExist(err) { log.Warn( @@ -3027,7 +3027,7 @@ func filterXRefComments(ctx *context.Context, issue *issues_model.Issue) error { if issues_model.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 { var err error // Set RefRepo for description in template - c.RefRepo, err = repo_model.GetRepositoryByID(c.RefRepoID) + c.RefRepo, err = repo_model.GetRepositoryByID(ctx, c.RefRepoID) if err != nil { return err } diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 682bc64ca29..bea6bfe433c 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -78,7 +78,7 @@ var pullRequestTemplateCandidates = []string{ } func getRepository(ctx *context.Context, repoID int64) *repo_model.Repository { - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) @@ -159,7 +159,7 @@ func getForkRepository(ctx *context.Context) *repo_model.Repository { if !traverseParentRepo.IsFork { break } - traverseParentRepo, err = repo_model.GetRepositoryByID(traverseParentRepo.ForkID) + traverseParentRepo, err = repo_model.GetRepositoryByID(ctx, traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return nil @@ -227,7 +227,7 @@ func ForkPost(ctx *context.Context) { if !traverseParentRepo.IsFork { break } - traverseParentRepo, err = repo_model.GetRepositoryByID(traverseParentRepo.ForkID) + traverseParentRepo, err = repo_model.GetRepositoryByID(ctx, traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -427,7 +427,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C setMergeTarget(ctx, pull) - if err := pull.LoadProtectedBranch(); err != nil { + if err := pull.LoadProtectedBranch(ctx); err != nil { ctx.ServerError("LoadProtectedBranch", err) return nil } @@ -739,7 +739,7 @@ func ViewPullFiles(ctx *context.Context) { return } - if err = pull.LoadProtectedBranch(); err != nil { + if err = pull.LoadProtectedBranch(ctx); err != nil { ctx.ServerError("LoadProtectedBranch", err) return } diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go index 9ef44eb5823..0aa1fde8de5 100644 --- a/routers/web/repo/release.go +++ b/routers/web/repo/release.go @@ -156,7 +156,7 @@ func releasesOrTags(ctx *context.Context, isTagList bool) { for _, r := range releases { if r.Publisher, ok = cacheUsers[r.PublisherID]; !ok { - r.Publisher, err = user_model.GetUserByID(r.PublisherID) + r.Publisher, err = user_model.GetUserByID(ctx, r.PublisherID) if err != nil { if user_model.IsErrUserNotExist(err) { r.Publisher = user_model.NewGhostUser() @@ -223,7 +223,7 @@ func SingleRelease(ctx *context.Context) { return } - release.Publisher, err = user_model.GetUserByID(release.PublisherID) + release.Publisher, err = user_model.GetUserByID(ctx, release.PublisherID) if err != nil { if user_model.IsErrUserNotExist(err) { release.Publisher = user_model.NewGhostUser() diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 0a8a1eb4e8b..c57564d3340 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -83,7 +83,7 @@ func checkContextUser(ctx *context.Context, uid int64) *user_model.User { return ctx.Doer } - org, err := user_model.GetUserByID(uid) + org, err := user_model.GetUserByID(ctx, uid) if user_model.IsErrUserNotExist(err) { return ctx.Doer } @@ -149,7 +149,7 @@ 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 := repo_model.GetRepositoryByID(templateID) + templateRepo, err := repo_model.GetRepositoryByID(ctx, templateID) if err == nil && access_model.CheckRepoUnitUser(ctx, templateRepo, ctxUser, unit.TypeCode) { ctx.Data["repo_template"] = templateID ctx.Data["repo_template_name"] = templateRepo.Name diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index c7f97410ff6..fa4eb6d61f2 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -457,7 +457,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st return } if lfsLock != nil { - u, err := user_model.GetUserByID(lfsLock.OwnerID) + u, err := user_model.GetUserByID(ctx, lfsLock.OwnerID) if err != nil { ctx.ServerError("GetTreePathLock", err) return diff --git a/routers/web/repo/webhook.go b/routers/web/repo/webhook.go index 677fbc92ed3..18d71c6435a 100644 --- a/routers/web/repo/webhook.go +++ b/routers/web/repo/webhook.go @@ -684,7 +684,7 @@ func TestWebhook(ctx *context.Context) { Commits: []*api.PayloadCommit{apiCommit}, TotalCommits: 1, HeadCommit: apiCommit, - Repo: convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone), + Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone), Pusher: apiUser, Sender: apiUser, } diff --git a/routers/web/user/package.go b/routers/web/user/package.go index ae4c239c70c..3782f46b424 100644 --- a/routers/web/user/package.go +++ b/routers/web/user/package.go @@ -336,7 +336,7 @@ func PackageSettingsPost(ctx *context.Context) { success := func() bool { repoID := int64(0) if form.RepoID != 0 { - repo, err := repo_model.GetRepositoryByID(form.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, form.RepoID) if err != nil { log.Error("Error getting repository: %v", err) return false diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index e46724f2e74..ef45ad8a862 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -323,7 +323,7 @@ func Repos(ctx *context.Context) { } for _, repo := range userRepos { if repo.IsFork { - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { ctx.ServerError("GetBaseRepo", err) return } @@ -342,7 +342,7 @@ func Repos(ctx *context.Context) { for i := range repos { if repos[i].IsFork { - if err := repos[i].GetBaseRepo(); err != nil { + if err := repos[i].GetBaseRepo(ctx); err != nil { ctx.ServerError("GetBaseRepo", err) return } diff --git a/services/agit/agit.go b/services/agit/agit.go index e21a1ea29d9..b4f4438791c 100644 --- a/services/agit/agit.go +++ b/services/agit/agit.go @@ -115,7 +115,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. description = opts.GitPushOptions["description"] } - pusher, err := user_model.GetUserByID(opts.UserID) + pusher, err := user_model.GetUserByID(ctx, opts.UserID) if err != nil { return nil, fmt.Errorf("Failed to get user. Error: %w", err) } @@ -198,7 +198,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. } pull_service.AddToTaskQueue(pr) - pusher, err := user_model.GetUserByID(opts.UserID) + pusher, err := user_model.GetUserByID(ctx, opts.UserID) if err != nil { return nil, fmt.Errorf("Failed to get user. Error: %w", err) } diff --git a/services/auth/basic.go b/services/auth/basic.go index 0a82fc5b723..839aaa7a4ed 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -74,7 +74,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore if uid != 0 { log.Trace("Basic Authorization: Valid OAuthAccessToken for user[%d]", uid) - u, err := user_model.GetUserByID(uid) + u, err := user_model.GetUserByID(req.Context(), uid) if err != nil { log.Error("GetUserByID: %v", err) return nil @@ -87,7 +87,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore token, err := auth_model.GetAccessTokenBySHA(authToken) if err == nil { log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid) - u, err := user_model.GetUserByID(token.UID) + u, err := user_model.GetUserByID(req.Context(), token.UID) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index dcdc2de83a8..e73db4f2480 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -72,7 +72,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt } } - u, err := user_model.GetUserByID(publicKey.OwnerID) + u, err := user_model.GetUserByID(req.Context(), publicKey.OwnerID) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index da8c526382d..7aea3eadf36 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -123,7 +123,7 @@ func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStor } log.Trace("OAuth2 Authorization: Found token for user[%d]", id) - user, err := user_model.GetUserByID(id) + user, err := user_model.GetUserByID(req.Context(), id) if err != nil { if !user_model.IsErrUserNotExist(err) { log.Error("GetUserByName: %v", err) diff --git a/services/auth/session.go b/services/auth/session.go index f35fad1a0c2..ef2c35d58a1 100644 --- a/services/auth/session.go +++ b/services/auth/session.go @@ -6,6 +6,7 @@ package auth import ( "net/http" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" ) @@ -55,7 +56,7 @@ func SessionUser(sess SessionStore) *user_model.User { } // Get user object - user, err := user_model.GetUserByID(id) + user, err := user_model.GetUserByID(db.DefaultContext, id) if err != nil { if !user_model.IsErrUserNotExist(err) { log.Error("GetUserById: %v", err) diff --git a/services/automerge/automerge.go b/services/automerge/automerge.go index f5bf1f4491a..15d94e79209 100644 --- a/services/automerge/automerge.go +++ b/services/automerge/automerge.go @@ -218,7 +218,7 @@ func handlePull(pullID int64, sha string) { } // Merge if all checks succeeded - doer, err := user_model.GetUserByIDCtx(ctx, scheduledPRM.DoerID) + doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID) if err != nil { log.Error("GetUserByIDCtx: %v", err) return diff --git a/services/issue/assignee.go b/services/issue/assignee.go index 2e62f7cf1ce..e5e1456c3f1 100644 --- a/services/issue/assignee.go +++ b/services/issue/assignee.go @@ -50,7 +50,7 @@ func ToggleAssignee(issue *issues_model.Issue, doer *user_model.User, assigneeID return } - assignee, err1 := user_model.GetUserByIDCtx(db.DefaultContext, assigneeID) + assignee, err1 := user_model.GetUserByID(db.DefaultContext, assigneeID) if err1 != nil { err = err1 return diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go index 946085cb91e..114ace078ed 100644 --- a/services/issue/assignee_test.go +++ b/services/issue/assignee_test.go @@ -22,7 +22,7 @@ func TestDeleteNotPassedAssignee(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, 1, len(issue.Assignees)) - user1, err := user_model.GetUserByID(1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him + user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him assert.NoError(t, err) // Check if he got removed diff --git a/services/issue/commit.go b/services/issue/commit.go index f9d59b6bd0f..efbcd639a59 100644 --- a/services/issue/commit.go +++ b/services/issue/commit.go @@ -119,7 +119,7 @@ func UpdateIssuesCommit(doer *user_model.User, repo *repo_model.Repository, comm // issue is from another repo if len(ref.Owner) > 0 && len(ref.Name) > 0 { - refRepo, err = repo_model.GetRepositoryByOwnerAndName(ref.Owner, ref.Name) + refRepo, err = repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ref.Owner, ref.Name) if err != nil { if repo_model.IsErrRepoNotExist(err) { log.Warn("Repository referenced in commit but does not exist: %v", err) diff --git a/services/issue/issue.go b/services/issue/issue.go index 23b48c28616..5073dff8191 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -160,7 +160,7 @@ func DeleteIssue(doer *user_model.User, gitRepo *git.Repository, issue *issues_m // AddAssigneeIfNotAssigned adds an assignee only if he isn't already assigned to the issue. // Also checks for access of assigned user func AddAssigneeIfNotAssigned(issue *issues_model.Issue, doer *user_model.User, assigneeID int64) (err error) { - assignee, err := user_model.GetUserByIDCtx(db.DefaultContext, assigneeID) + assignee, err := user_model.GetUserByID(db.DefaultContext, assigneeID) if err != nil { return err } diff --git a/services/issue/issue_test.go b/services/issue/issue_test.go index 44168388e63..b67d2e2e79a 100644 --- a/services/issue/issue_test.go +++ b/services/issue/issue_test.go @@ -66,7 +66,7 @@ func TestIssue_DeleteIssue(t *testing.T) { } // check issue dependencies - user, err := user_model.GetUserByID(1) + user, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) assert.NoError(t, err) diff --git a/services/lfs/locks.go b/services/lfs/locks.go index aab4f1a44ed..0dc51f063c8 100644 --- a/services/lfs/locks.go +++ b/services/lfs/locks.go @@ -39,7 +39,7 @@ func handleLockListOut(ctx *context.Context, repo *repo_model.Repository, lock * return } ctx.JSON(http.StatusOK, api.LFSLockList{ - Locks: []*api.LFSLock{convert.ToLFSLock(lock)}, + Locks: []*api.LFSLock{convert.ToLFSLock(ctx, lock)}, }) } @@ -47,7 +47,7 @@ func handleLockListOut(ctx *context.Context, repo *repo_model.Repository, lock * func GetListLockHandler(ctx *context.Context) { rv := getRequestContext(ctx) - repository, err := repo_model.GetRepositoryByOwnerAndName(rv.User, rv.Repo) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, 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") @@ -117,7 +117,7 @@ func GetListLockHandler(ctx *context.Context) { lockListAPI := make([]*api.LFSLock, len(lockList)) next := "" for i, l := range lockList { - lockListAPI[i] = convert.ToLFSLock(l) + lockListAPI[i] = convert.ToLFSLock(ctx, l) } if limit > 0 && len(lockList) == limit { next = strconv.Itoa(cursor + 1) @@ -134,7 +134,7 @@ func PostLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, 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") @@ -174,7 +174,7 @@ func PostLockHandler(ctx *context.Context) { if err != nil { if git_model.IsErrLFSLockAlreadyExist(err) { ctx.JSON(http.StatusConflict, api.LFSLockError{ - Lock: convert.ToLFSLock(lock), + Lock: convert.ToLFSLock(ctx, lock), Message: "already created lock", }) return @@ -192,7 +192,7 @@ func PostLockHandler(ctx *context.Context) { }) return } - ctx.JSON(http.StatusCreated, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)}) + ctx.JSON(http.StatusCreated, api.LFSLockResponse{Lock: convert.ToLFSLock(ctx, lock)}) } // VerifyLockHandler list locks for verification @@ -201,7 +201,7 @@ func VerifyLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, 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") @@ -249,9 +249,9 @@ func VerifyLockHandler(ctx *context.Context) { lockTheirsListAPI := make([]*api.LFSLock, 0, len(lockList)) for _, l := range lockList { if l.OwnerID == ctx.Doer.ID { - lockOursListAPI = append(lockOursListAPI, convert.ToLFSLock(l)) + lockOursListAPI = append(lockOursListAPI, convert.ToLFSLock(ctx, l)) } else { - lockTheirsListAPI = append(lockTheirsListAPI, convert.ToLFSLock(l)) + lockTheirsListAPI = append(lockTheirsListAPI, convert.ToLFSLock(ctx, l)) } } ctx.JSON(http.StatusOK, api.LFSLockListVerify{ @@ -267,7 +267,7 @@ func UnLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, 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") @@ -315,5 +315,5 @@ func UnLockHandler(ctx *context.Context) { }) return } - ctx.JSON(http.StatusOK, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)}) + ctx.JSON(http.StatusOK, api.LFSLockResponse{Lock: convert.ToLFSLock(ctx, lock)}) } diff --git a/services/lfs/server.go b/services/lfs/server.go index 32bd843ebfa..8fd2759132f 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -4,6 +4,7 @@ package lfs import ( + stdCtx "context" "crypto/sha256" "encoding/base64" "encoding/hex" @@ -408,7 +409,7 @@ func getAuthenticatedMeta(ctx *context.Context, rc *requestContext, p lfs_module } func getAuthenticatedRepository(ctx *context.Context, rc *requestContext, requireWrite bool) *repo_model.Repository { - repository, err := repo_model.GetRepositoryByOwnerAndName(rc.User, rc.Repo) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, 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) @@ -506,7 +507,7 @@ func authenticate(ctx *context.Context, repository *repo_model.Repository, autho return true } - user, err := parseToken(authorization, repository, accessMode) + user, err := parseToken(ctx, authorization, repository, accessMode) if err != nil { // Most of these are Warn level - the true internal server errors are logged in parseToken already log.Warn("Authentication failure for provided token with Error: %v", err) @@ -516,7 +517,7 @@ func authenticate(ctx *context.Context, repository *repo_model.Repository, autho return true } -func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { +func handleLFSToken(ctx stdCtx.Context, 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 *repo_model.Repository, mode perm.Ac return nil, fmt.Errorf("invalid token claim") } - u, err := user_model.GetUserByID(claims.UserID) + u, err := user_model.GetUserByID(ctx, claims.UserID) if err != nil { log.Error("Unable to GetUserById[%d]: Error: %v", claims.UserID, err) return nil, err @@ -551,7 +552,7 @@ func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.Ac return u, nil } -func parseToken(authorization string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { +func parseToken(ctx stdCtx.Context, authorization string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { if authorization == "" { return nil, fmt.Errorf("no token") } @@ -565,7 +566,7 @@ func parseToken(authorization string, target *repo_model.Repository, mode perm.A case "bearer": fallthrough case "token": - return handleLFSToken(tokenSHA, target, mode) + return handleLFSToken(ctx, tokenSHA, target, mode) } return nil, fmt.Errorf("token not found") } diff --git a/services/mailer/mail_team_invite.go b/services/mailer/mail_team_invite.go index f01d6f47dd1..54e82b02343 100644 --- a/services/mailer/mail_team_invite.go +++ b/services/mailer/mail_team_invite.go @@ -26,7 +26,7 @@ func MailTeamInvite(ctx context.Context, inviter *user_model.User, team *org_mod return nil } - org, err := user_model.GetUserByIDCtx(ctx, team.OrgID) + org, err := user_model.GetUserByID(ctx, team.OrgID) if err != nil { return err } diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index ea9b1a71424..f3848e616cc 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -109,7 +109,7 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate Status: repo_model.RepositoryBeingMigrated, }) } else { - r, err = repo_model.GetRepositoryByID(opts.MigrateToRepoID) + r, err = repo_model.GetRepositoryByID(g.ctx, opts.MigrateToRepoID) } if err != nil { return err diff --git a/services/pull/check.go b/services/pull/check.go index af8f2df0b6a..4f720f0a0cf 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -126,7 +126,7 @@ func CheckPullMergable(stdCtx context.Context, doer *user_model.User, perm *acce // isSignedIfRequired check if merge will be signed if required func isSignedIfRequired(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User) (bool, error) { - if err := pr.LoadProtectedBranchCtx(ctx); err != nil { + if err := pr.LoadProtectedBranch(ctx); err != nil { return false, err } @@ -165,7 +165,7 @@ func checkAndUpdateStatus(ctx context.Context, pr *issues_model.PullRequest) { func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Commit, error) { if pr.BaseRepo == nil { var err error - pr.BaseRepo, err = repo_model.GetRepositoryByID(pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID) if err != nil { return nil, fmt.Errorf("GetRepositoryByID: %w", err) } diff --git a/services/pull/commit_status.go b/services/pull/commit_status.go index 7e4db311d9a..e075248a366 100644 --- a/services/pull/commit_status.go +++ b/services/pull/commit_status.go @@ -83,7 +83,7 @@ func IsCommitStatusContextSuccess(commitStatuses []*git_model.CommitStatus, requ // IsPullCommitStatusPass returns if all required status checks PASS func IsPullCommitStatusPass(ctx context.Context, pr *issues_model.PullRequest) (bool, error) { - if err := pr.LoadProtectedBranchCtx(ctx); err != nil { + if err := pr.LoadProtectedBranch(ctx); err != nil { return false, errors.Wrap(err, "GetLatestCommitStatus") } if pr.ProtectedBranch == nil || !pr.ProtectedBranch.EnableStatusCheck { @@ -137,7 +137,7 @@ func GetPullRequestCommitStatusState(ctx context.Context, pr *issues_model.PullR return "", errors.Wrap(err, "GetLatestCommitStatus") } - if err := pr.LoadProtectedBranchCtx(ctx); err != nil { + if err := pr.LoadProtectedBranch(ctx); err != nil { return "", errors.Wrap(err, "LoadProtectedBranch") } var requiredContexts []string diff --git a/services/pull/merge.go b/services/pull/merge.go index afed98989b5..9270fb8cbc2 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -752,7 +752,7 @@ func IsUserAllowedToMerge(ctx context.Context, pr *issues_model.PullRequest, p a return false, nil } - err := pr.LoadProtectedBranchCtx(ctx) + err := pr.LoadProtectedBranch(ctx) if err != nil { return false, err } @@ -770,7 +770,7 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques return fmt.Errorf("LoadBaseRepo: %w", err) } - if err = pr.LoadProtectedBranchCtx(ctx); err != nil { + if err = pr.LoadProtectedBranch(ctx); err != nil { return fmt.Errorf("LoadProtectedBranch: %w", err) } if pr.ProtectedBranch == nil { diff --git a/services/pull/patch.go b/services/pull/patch.go index 925f310a2c0..2d495a3d72d 100644 --- a/services/pull/patch.go +++ b/services/pull/patch.go @@ -14,6 +14,7 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/container" @@ -533,7 +534,7 @@ func checkPullFilesProtection(pr *issues_model.PullRequest, gitRepo *git.Reposit return nil } - if err := pr.LoadProtectedBranch(); err != nil { + if err := pr.LoadProtectedBranch(db.DefaultContext); err != nil { return err } diff --git a/services/pull/pull.go b/services/pull/pull.go index ddb407b0538..fd907491d44 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -230,7 +230,7 @@ func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer } func checkForInvalidation(ctx context.Context, requests issues_model.PullRequestList, repoID int64, doer *user_model.User, branch string) error { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { return fmt.Errorf("GetRepositoryByIDCtx: %w", err) } @@ -594,7 +594,7 @@ func GetSquashMergeCommitMessages(ctx context.Context, pr *issues_model.PullRequ if pr.HeadRepo == nil { var err error - pr.HeadRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.HeadRepoID) + pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID) if err != nil { log.Error("GetRepositoryByIdCtx[%d]: %v", pr.HeadRepoID, err) return "" diff --git a/services/pull/update.go b/services/pull/update.go index 6ff554e612c..bd6a37b277e 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -99,7 +99,7 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest, BaseBranch: pull.HeadBranch, } - err = pr.LoadProtectedBranch() + err = pr.LoadProtectedBranch(ctx) if err != nil { return false, false, err } diff --git a/services/release/release.go b/services/release/release.go index 07e329cf43c..1d599fcda1d 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -289,7 +289,7 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del return fmt.Errorf("GetReleaseByID: %w", err) } - repo, err := repo_model.GetRepositoryByIDCtx(ctx, rel.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, rel.RepoID) if err != nil { return fmt.Errorf("GetRepositoryByID: %w", err) } diff --git a/services/repository/adopt.go b/services/repository/adopt.go index fb7adcfd294..828068e8ec1 100644 --- a/services/repository/adopt.go +++ b/services/repository/adopt.go @@ -116,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 = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %w", err) } diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go index 94fff6ffa26..1da4425cfc6 100644 --- a/services/repository/archiver/archiver.go +++ b/services/repository/archiver/archiver.go @@ -226,7 +226,7 @@ func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) { rd.Close() }() done := make(chan error, 1) // Ensure that there is some capacity which will ensure that the goroutine below can always finish - repo, err := repo_model.GetRepositoryByID(archiver.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, archiver.RepoID) if err != nil { return nil, fmt.Errorf("archiver.LoadRepo failed: %w", err) } diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index 0ada3885b1e..240564d4016 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -69,7 +69,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return err } if lfsLock != nil && lfsLock.OwnerID != doer.ID { - u, err := user_model.GetUserByID(lfsLock.OwnerID) + u, err := user_model.GetUserByID(ctx, lfsLock.OwnerID) if err != nil { return err } diff --git a/services/repository/fork.go b/services/repository/fork.go index cf9b3992cd0..3ed0f4ffa51 100644 --- a/services/repository/fork.go +++ b/services/repository/fork.go @@ -184,7 +184,7 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork // ConvertForkToNormalRepository convert the provided repo from a forked repo to normal repo func ConvertForkToNormalRepository(repo *repo_model.Repository) error { err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, repo.ID) + repo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { return err } diff --git a/services/repository/push.go b/services/repository/push.go index bce01cb76a5..f1eedb8e083 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -81,7 +81,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("PushUpdates: %s/%s", optsList[0].RepoUserName, optsList[0].RepoName)) defer finished() - repo, err := repo_model.GetRepositoryByOwnerAndName(optsList[0].RepoUserName, optsList[0].RepoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, optsList[0].RepoUserName, optsList[0].RepoName) if err != nil { return fmt.Errorf("GetRepositoryByOwnerAndName failed: %w", err) } @@ -109,7 +109,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { if opts.IsTag() { // If is tag reference if pusher == nil || pusher.ID != opts.PusherID { var err error - if pusher, err = user_model.GetUserByID(opts.PusherID); err != nil { + if pusher, err = user_model.GetUserByID(ctx, opts.PusherID); err != nil { return err } } @@ -149,7 +149,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { } else if opts.IsBranch() { // If is branch reference if pusher == nil || pusher.ID != opts.PusherID { var err error - if pusher, err = user_model.GetUserByID(opts.PusherID); err != nil { + if pusher, err = user_model.GetUserByID(ctx, opts.PusherID); err != nil { return err } } diff --git a/services/repository/repository.go b/services/repository/repository.go index 859c32cf8fd..41fae4b4cf6 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -103,24 +103,24 @@ func UpdateRepository(repo *repo_model.Repository, visibilityChanged bool) (err } // LinkedRepository returns the linked repo if any -func LinkedRepository(a *repo_model.Attachment) (*repo_model.Repository, unit.Type, error) { +func LinkedRepository(ctx context.Context, a *repo_model.Attachment) (*repo_model.Repository, unit.Type, error) { if a.IssueID != 0 { - iss, err := issues_model.GetIssueByID(db.DefaultContext, a.IssueID) + iss, err := issues_model.GetIssueByID(ctx, a.IssueID) if err != nil { return nil, unit.TypeIssues, err } - repo, err := repo_model.GetRepositoryByID(iss.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, iss.RepoID) unitType := unit.TypeIssues if iss.IsPull { unitType = unit.TypePullRequests } return repo, unitType, err } else if a.ReleaseID != 0 { - rel, err := repo_model.GetReleaseByID(db.DefaultContext, a.ReleaseID) + rel, err := repo_model.GetReleaseByID(ctx, a.ReleaseID) if err != nil { return nil, unit.TypeReleases, err } - repo, err := repo_model.GetRepositoryByID(rel.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, rel.RepoID) return repo, unit.TypeReleases, err } return nil, -1, nil diff --git a/services/repository/repository_test.go b/services/repository/repository_test.go index 5f5283bddb6..892a11a23e9 100644 --- a/services/repository/repository_test.go +++ b/services/repository/repository_test.go @@ -31,7 +31,7 @@ func TestLinkedRepository(t *testing.T) { t.Run(tc.name, func(t *testing.T) { attach, err := repo_model.GetAttachmentByID(db.DefaultContext, tc.attachID) assert.NoError(t, err) - repo, unitType, err := LinkedRepository(attach) + repo, unitType, err := LinkedRepository(db.DefaultContext, attach) assert.NoError(t, err) if tc.expectedRepo != nil { assert.Equal(t, tc.expectedRepo.ID, repo.ID) diff --git a/services/repository/transfer.go b/services/repository/transfer.go index af28f5a4a54..9fba9c44ebc 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -43,7 +43,7 @@ func TransferOwnership(doer, newOwner *user_model.User, repo *repo_model.Reposit } repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) - newRepo, err := repo_model.GetRepositoryByID(repo.ID) + newRepo, err := repo_model.GetRepositoryByID(db.DefaultContext, repo.ID) if err != nil { return err } diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index 3080b5e194e..eda4150f8c4 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -43,7 +43,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.EqualValues(t, issue2.ID, apiTimes[i].IssueID) assert.Equal(t, time.Created.Unix(), apiTimes[i].Created.Unix()) assert.Equal(t, time.Time, apiTimes[i].Time) - user, err := user_model.GetUserByID(time.UserID) + user, err := user_model.GetUserByID(db.DefaultContext, time.UserID) assert.NoError(t, err) assert.Equal(t, user.Name, apiTimes[i].UserName) } diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index d4334ff8b99..73599242dbc 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -61,7 +62,7 @@ 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 := repo_model.GetRepositoryByOwnerAndName("user2", "lfs-"+name+"-repo") + repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "lfs-"+name+"-repo") assert.NoError(t, err) return repo diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index 6508df1ef0d..8d29a161d51 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -570,7 +570,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 := repo_model.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame) + repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) assert.NoError(t, err) assert.False(t, repo.IsEmpty) assert.True(t, repo.IsPrivate) @@ -698,7 +698,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB pr1, pr2 *issues_model.PullRequest commit string ) - repo, err := repo_model.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame) + repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) if !assert.NoError(t, err) { return } diff --git a/tests/integration/lfs_getobject_test.go b/tests/integration/lfs_getobject_test.go index 1a486b60514..a191bcb61c4 100644 --- a/tests/integration/lfs_getobject_test.go +++ b/tests/integration/lfs_getobject_test.go @@ -11,6 +11,7 @@ import ( "net/http/httptest" "testing" + "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/json" @@ -40,7 +41,7 @@ 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 := repo_model.GetRepositoryByOwnerAndName("user2", "repo1") + repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") assert.NoError(t, err) oid := storeObjectInRepo(t, repo.ID, content) defer git_model.RemoveLFSMetaObjectByOid(repo.ID, oid) diff --git a/tests/integration/repo_search_test.go b/tests/integration/repo_search_test.go index 34328100fd9..d113d1e57d0 100644 --- a/tests/integration/repo_search_test.go +++ b/tests/integration/repo_search_test.go @@ -7,6 +7,7 @@ import ( "net/http" "testing" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" code_indexer "code.gitea.io/gitea/modules/indexer/code" "code.gitea.io/gitea/modules/setting" @@ -28,7 +29,7 @@ func resultFilenames(t testing.TB, doc *HTMLDoc) []string { func TestSearchRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() - repo, err := repo_model.GetRepositoryByOwnerAndName("user2", "repo1") + repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") assert.NoError(t, err) executeIndexer(t, repo, code_indexer.UpdateRepoIndexer) @@ -38,7 +39,7 @@ func TestSearchRepo(t *testing.T) { setting.Indexer.IncludePatterns = setting.IndexerGlobFromString("**.txt") setting.Indexer.ExcludePatterns = setting.IndexerGlobFromString("**/y/**") - repo, err = repo_model.GetRepositoryByOwnerAndName("user2", "glob") + repo, err = repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "glob") assert.NoError(t, err) executeIndexer(t, repo, code_indexer.UpdateRepoIndexer) From 181f4bfdb1a71f06e734d3c881b648f5eaaa1317 Mon Sep 17 00:00:00 2001 From: Xinyu Zhou Date: Sat, 3 Dec 2022 19:51:53 +0800 Subject: [PATCH 05/13] docs: add `Edit this page` (#21981) Update theme to support `Edit this page`: https://gitea.com/gitea/theme/pulls/116 Screenshot: ![Edit this page](https://user-images.githubusercontent.com/76462613/205257167-d6039d0c-c913-4ebc-98c1-834aece4b5e9.png) Signed-off-by: Xinyu Zhou Co-authored-by: John Olheiser Co-authored-by: techknowlogick Co-authored-by: Lunny Xiao --- docs/config.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/config.yaml b/docs/config.yaml index 66bd379c0ca..91afc2e9724 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -23,6 +23,8 @@ params: goVersion: 1.19 minNodeVersion: 14 search: nav + repo: "https://github.com/go-gitea/gitea" + docContentPath: "docs/content" outputs: home: From 0e46499258a20a8d701cdfc489c55a4246b4901e Mon Sep 17 00:00:00 2001 From: zeripath Date: Sat, 3 Dec 2022 15:47:00 +0000 Subject: [PATCH 06/13] Do not emit ambiguous character warning on rendered pages (#22016) The real sensitivity of ambiguous characters is in source code - therefore warning about them in rendered pages causes too many warnings. Therefore simply remove the warning on rendered pages. The escape button will remain available and it is present on the view source page. Fix #20999 Signed-off-by: Andrew Thornton --- templates/repo/view_file.tmpl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/templates/repo/view_file.tmpl b/templates/repo/view_file.tmpl index 0fe0a131985..9d82cc018c7 100644 --- a/templates/repo/view_file.tmpl +++ b/templates/repo/view_file.tmpl @@ -58,7 +58,9 @@
- {{template "repo/unicode_escape_prompt" dict "EscapeStatus" .EscapeStatus "root" $}} + {{if not (or .IsMarkup .IsRenderedHTML)}} + {{template "repo/unicode_escape_prompt" dict "EscapeStatus" .EscapeStatus "root" $}} + {{end}}
{{if .IsMarkup}} {{if .FileContent}}{{.FileContent | Safe}}{{end}} From d084ce306aabd99ee4d63934984544ee61760b27 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sun, 4 Dec 2022 00:19:34 +0000 Subject: [PATCH 07/13] [skip ci] Updated licenses and gitignores --- options/gitignore/Bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/options/gitignore/Bazel b/options/gitignore/Bazel index 4e1d5a2ba0a..bc3afc20ba6 100644 --- a/options/gitignore/Bazel +++ b/options/gitignore/Bazel @@ -6,7 +6,7 @@ /bazel-* # Directories for the Bazel IntelliJ plugin containing the generated -# IntelliJ project files and plugin configuration. Separate directories are +# IntelliJ project files and plugin configuration. Seperate directories are # for the IntelliJ, Android Studio and CLion versions of the plugin. /.ijwb/ /.aswb/ From 9eb9cf5153160e38a25dbbdeeb223fac769879db Mon Sep 17 00:00:00 2001 From: Percy Ma Date: Sun, 4 Dec 2022 16:56:10 +0800 Subject: [PATCH 08/13] fix(web): reduce page jitter on browsers that support overlay scrollbar (#21850) Reduce jitter caused by the presence or absence of scrollbars in page switching --- Ref [scrollbar-gutter | MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-gutter) https://user-images.githubusercontent.com/45708948/165972251-7d5a5017-f76d-4ba2-9106-a224b3ee521f.mp4 --- web_src/less/_base.less | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/web_src/less/_base.less b/web_src/less/_base.less index 14b69dec49a..e156ccd6cc0 100644 --- a/web_src/less/_base.less +++ b/web_src/less/_base.less @@ -222,6 +222,13 @@ body { overflow-wrap: break-word; } +@supports (overflow: overlay) { + body { + overflow: overlay; + scrollbar-gutter: stable; + } +} + img { border-radius: 3px; } From 36cbaec54cb4640e23a1edb3ba6d488867f73302 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 4 Dec 2022 16:57:17 +0800 Subject: [PATCH 09/13] Fix ListBranches to handle empty case (#21921) Fix #21910 Co-authored-by: KN4CK3R --- routers/api/v1/repo/branch.go | 64 ++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index f5b1eb1c42c..3060cf24064 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -251,42 +251,50 @@ func ListBranches(ctx *context.APIContext) { // "200": // "$ref": "#/responses/BranchList" - listOptions := utils.GetListOptions(ctx) - skip, _ := listOptions.GetStartEnd() - branches, totalNumOfBranches, err := ctx.Repo.GitRepo.GetBranches(skip, listOptions.PageSize) - if err != nil { - ctx.Error(http.StatusInternalServerError, "GetBranches", err) - return - } + var totalNumOfBranches int + var apiBranches []*api.Branch - apiBranches := make([]*api.Branch, 0, len(branches)) - for i := range branches { - c, err := branches[i].GetCommit() + listOptions := utils.GetListOptions(ctx) + + if !ctx.Repo.Repository.IsEmpty && ctx.Repo.GitRepo != nil { + skip, _ := listOptions.GetStartEnd() + branches, total, err := ctx.Repo.GitRepo.GetBranches(skip, listOptions.PageSize) if err != nil { - // Skip if this branch doesn't exist anymore. - if git.IsErrNotExist(err) { - totalNumOfBranches-- - continue + ctx.Error(http.StatusInternalServerError, "GetBranches", err) + return + } + + apiBranches = make([]*api.Branch, 0, len(branches)) + for i := range branches { + c, err := branches[i].GetCommit() + if err != nil { + // Skip if this branch doesn't exist anymore. + if git.IsErrNotExist(err) { + total-- + continue + } + ctx.Error(http.StatusInternalServerError, "GetCommit", err) + return } - ctx.Error(http.StatusInternalServerError, "GetCommit", err) - return + branchProtection, err := git_model.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branches[i].Name) + if err != nil { + ctx.Error(http.StatusInternalServerError, "GetProtectedBranchBy", err) + return + } + apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) + if err != nil { + ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) + return + } + apiBranches = append(apiBranches, apiBranch) } - branchProtection, err := git_model.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branches[i].Name) - if err != nil { - ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) - return - } - apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) - if err != nil { - ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) - return - } - apiBranches = append(apiBranches, apiBranch) + + totalNumOfBranches = total } ctx.SetLinkHeader(totalNumOfBranches, listOptions.PageSize) ctx.SetTotalCountHeader(int64(totalNumOfBranches)) - ctx.JSON(http.StatusOK, &apiBranches) + ctx.JSON(http.StatusOK, apiBranches) } // GetBranchProtection gets a branch protection From 46485848fa8580d7d1994e602590d5ac981110b7 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Sun, 4 Dec 2022 11:28:57 +0100 Subject: [PATCH 10/13] On tag/branch-exist check, dont panic if repo is nil (#21787) fix a panic found in gitea logs --- modules/git/repo_branch_nogogit.go | 2 +- modules/git/repo_tag_nogogit.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/git/repo_branch_nogogit.go b/modules/git/repo_branch_nogogit.go index b1d0df6474a..7559513c9b4 100644 --- a/modules/git/repo_branch_nogogit.go +++ b/modules/git/repo_branch_nogogit.go @@ -52,7 +52,7 @@ func (repo *Repository) IsReferenceExist(name string) bool { // IsBranchExist returns true if given branch exists in current repository. func (repo *Repository) IsBranchExist(name string) bool { - if name == "" { + if repo == nil || name == "" { return false } diff --git a/modules/git/repo_tag_nogogit.go b/modules/git/repo_tag_nogogit.go index 1fb631002b7..d3331cf9b73 100644 --- a/modules/git/repo_tag_nogogit.go +++ b/modules/git/repo_tag_nogogit.go @@ -15,7 +15,7 @@ import ( // IsTagExist returns true if given tag exists in the repository. func (repo *Repository) IsTagExist(name string) bool { - if name == "" { + if repo == nil || name == "" { return false } From 84d2a820e59f0d96d818d40205d705deab2af576 Mon Sep 17 00:00:00 2001 From: Michael Kriese Date: Sun, 4 Dec 2022 12:12:06 +0100 Subject: [PATCH 11/13] Add dumb-init to rootless docker (#21775) Add dumb-init as process reaper to the rootless image to reap defunct git processes. --- Dockerfile.rootless | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Dockerfile.rootless b/Dockerfile.rootless index 46a14eae873..a43a63fa10c 100644 --- a/Dockerfile.rootless +++ b/Dockerfile.rootless @@ -31,6 +31,7 @@ EXPOSE 2222 3000 RUN apk --no-cache add \ bash \ ca-certificates \ + dumb-init \ gettext \ git \ curl \ @@ -68,6 +69,6 @@ ENV HOME "/var/lib/gitea/git" VOLUME ["/var/lib/gitea", "/etc/gitea"] WORKDIR /var/lib/gitea -ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +ENTRYPOINT ["/usr/bin/dumb-init", "--", "/usr/local/bin/docker-entrypoint.sh"] CMD [] From ea86c2b56afeca6450a3e1081c0fd417a09e5434 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sun, 4 Dec 2022 17:48:18 +0000 Subject: [PATCH 12/13] Use GhostUser if needed for TrackedTimes (#22021) When getting tracked times out of the db and loading their attributes handle not exist errors in a nicer way. (Also prevent an NPE.) Fix #22006 Signed-off-by: Andrew Thornton --- models/issues/tracked_time.go | 53 ++++++++++++++++++++--------------- modules/convert/issue.go | 11 ++++---- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/models/issues/tracked_time.go b/models/issues/tracked_time.go index 2de63a3a45a..554b01bd407 100644 --- a/models/issues/tracked_time.go +++ b/models/issues/tracked_time.go @@ -5,6 +5,7 @@ package issues import ( "context" + "errors" "time" "code.gitea.io/gitea/models/db" @@ -46,33 +47,41 @@ func (t *TrackedTime) LoadAttributes() (err error) { } func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) { + // Load the issue if t.Issue == nil { t.Issue, err = GetIssueByID(ctx, t.IssueID) - if err != nil { - return - } - err = t.Issue.LoadRepo(ctx) - if err != nil { - return - } - } - if t.User == nil { - t.User, err = user_model.GetUserByID(ctx, t.UserID) - if err != nil { - return - } - } - return err -} - -// LoadAttributes load Issue, User -func (tl TrackedTimeList) LoadAttributes() (err error) { - for _, t := range tl { - if err = t.LoadAttributes(); err != nil { + if err != nil && !errors.Is(err, util.ErrNotExist) { return err } } - return err + // Now load the repo for the issue (which we may have just loaded) + if t.Issue != nil { + err = t.Issue.LoadRepo(ctx) + if err != nil && !errors.Is(err, util.ErrNotExist) { + return err + } + } + // Load the user + if t.User == nil { + t.User, err = user_model.GetUserByID(ctx, t.UserID) + if err != nil { + if !errors.Is(err, util.ErrNotExist) { + return err + } + t.User = user_model.NewGhostUser() + } + } + return nil +} + +// LoadAttributes load Issue, User +func (tl TrackedTimeList) LoadAttributes() error { + for _, t := range tl { + if err := t.LoadAttributes(); err != nil { + return err + } + } + return nil } // FindTrackedTimesOptions represent the filters for tracked times. If an ID is 0 it will be ignored. diff --git a/modules/convert/issue.go b/modules/convert/issue.go index 221aeb885a9..3bc10065073 100644 --- a/modules/convert/issue.go +++ b/modules/convert/issue.go @@ -110,12 +110,11 @@ func ToAPIIssueList(ctx context.Context, il issues_model.IssueList) []*api.Issue // ToTrackedTime converts TrackedTime to API format func ToTrackedTime(ctx context.Context, t *issues_model.TrackedTime) (apiT *api.TrackedTime) { apiT = &api.TrackedTime{ - ID: t.ID, - IssueID: t.IssueID, - UserID: t.UserID, - UserName: t.User.Name, - Time: t.Time, - Created: t.Created, + ID: t.ID, + IssueID: t.IssueID, + UserID: t.UserID, + Time: t.Time, + Created: t.Created, } if t.Issue != nil { apiT.Issue = ToAPIIssue(ctx, t.Issue) From a08584ee367d42de56c5ba6a0fd36ac1067578dd Mon Sep 17 00:00:00 2001 From: zeripath Date: Sun, 4 Dec 2022 17:57:30 +0000 Subject: [PATCH 13/13] Ensure that Chinese punctuation is not ambiguous when locale is Chinese (#22019) Although there are per-locale fallbacks for ambiguity the locale names for Chinese do not quite match our locales. This PR simply maps zh-CN on to zh-hans and other zh variants on to zh-hant. Ref #20999 Signed-off-by: Andrew Thornton --- modules/charset/ambiguous.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modules/charset/ambiguous.go b/modules/charset/ambiguous.go index c5b0c2c54d2..96e0561e155 100644 --- a/modules/charset/ambiguous.go +++ b/modules/charset/ambiguous.go @@ -28,6 +28,12 @@ func AmbiguousTablesForLocale(locale translation.Locale) []*AmbiguousTable { key = key[:idx] } } + if table == nil && (locale.Language() == "zh-CN" || locale.Language() == "zh_CN") { + table = AmbiguousCharacters["zh-hans"] + } + if table == nil && strings.HasPrefix(locale.Language(), "zh") { + table = AmbiguousCharacters["zh-hant"] + } if table == nil { table = AmbiguousCharacters["_default"] }