From 8d0343e028cf5b1794ba2bfebf23c863e340d108 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Thu, 14 Sep 2023 16:20:16 +0200 Subject: [PATCH 01/23] Fix issue templates when blank isses are disabled (#27061) Fixes #27060 --------- Co-authored-by: silverwind Co-authored-by: delvh --- routers/web/repo/compare.go | 2 +- routers/web/repo/issue.go | 23 +++++++++++++---------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index aee34956124c1..7f51cb01f32c7 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -804,7 +804,7 @@ func CompareDiff(ctx *context.Context) { ctx.Data["IsRepoToolbarCommits"] = true ctx.Data["IsDiffCompare"] = true - templateErrs := setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates) + _, templateErrs := setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates) if len(templateErrs) > 0 { ctx.Flash.Warning(renderErrorOfTemplates(ctx, templateErrs), true) diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index c95d54532aad1..3796fb7d3e1dc 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -830,10 +830,11 @@ func RetrieveRepoMetas(ctx *context.Context, repo *repo_model.Repository, isPull return labels } -func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles []string) map[string]error { +// Tries to load and set an issue template. The first return value indicates if a template was loaded. +func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles []string) (bool, map[string]error) { commit, err := ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch) if err != nil { - return nil + return false, nil } templateCandidates := make([]string, 0, 1+len(possibleFiles)) @@ -896,20 +897,15 @@ func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles ctx.Data["label_ids"] = strings.Join(labelIDs, ",") ctx.Data["Reference"] = template.Ref ctx.Data["RefEndName"] = git.RefName(template.Ref).ShortName() - return templateErrs + return true, templateErrs } - return templateErrs + return false, templateErrs } // NewIssue render creating issue page func NewIssue(ctx *context.Context) { issueConfig, _ := issue_service.GetTemplateConfigFromDefaultBranch(ctx.Repo.Repository, ctx.Repo.GitRepo) hasTemplates := issue_service.HasTemplatesOrContactLinks(ctx.Repo.Repository, ctx.Repo.GitRepo) - if !issueConfig.BlankIssuesEnabled && hasTemplates { - // The "issues/new" and "issues/new/choose" share the same query parameters "project" and "milestone", if blank issues are disabled, just redirect to the "issues/choose" page with these parameters. - ctx.Redirect(fmt.Sprintf("%s/issues/new/choose?%s", ctx.Repo.Repository.Link(), ctx.Req.URL.RawQuery), http.StatusSeeOther) - return - } ctx.Data["Title"] = ctx.Tr("repo.issues.new") ctx.Data["PageIsIssueList"] = true @@ -963,7 +959,8 @@ func NewIssue(ctx *context.Context) { ctx.Data["Tags"] = tags _, templateErrs := issue_service.GetTemplatesFromDefaultBranch(ctx.Repo.Repository, ctx.Repo.GitRepo) - if errs := setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates); len(errs) > 0 { + templateLoaded, errs := setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates) + if len(errs) > 0 { for k, v := range errs { templateErrs[k] = v } @@ -978,6 +975,12 @@ func NewIssue(ctx *context.Context) { ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(unit.TypeIssues) + if !issueConfig.BlankIssuesEnabled && hasTemplates && !templateLoaded { + // The "issues/new" and "issues/new/choose" share the same query parameters "project" and "milestone", if blank issues are disabled, just redirect to the "issues/choose" page with these parameters. + ctx.Redirect(fmt.Sprintf("%s/issues/new/choose?%s", ctx.Repo.Repository.Link(), ctx.Req.URL.RawQuery), http.StatusSeeOther) + return + } + ctx.HTML(http.StatusOK, tplIssueNew) } From 0de09d3afcb5394cbd97e4a1c5609eb8b2acb6cf Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Fri, 15 Sep 2023 00:35:53 +0800 Subject: [PATCH 02/23] Remove the useless function `GetUserIssueStats` and move relevant tests to `indexer_test.go` (#27067) Since the issue indexer has been refactored, the issue overview webpage is built by the `buildIssueOverview` function and underlying `indexer.Search` function and `GetIssueStats` instead of `GetUserIssueStats`. So the function is no longer used. I moved the relevant tests to `indexer_test.go` and since the search option changed from `IssueOptions` to `SearchOptions`, most of the tests are useless now. We need more tests about the db indexer because those tests are highly connected with the issue overview webpage and now this page has several bugs. Any advice about those test cases is appreciated. --------- Co-authored-by: CaiCandong <50507092+CaiCandong@users.noreply.github.com> --- models/issues/issue_stats.go | 190 ------------------------- models/issues/issue_test.go | 124 ---------------- modules/indexer/issues/indexer_test.go | 83 ++++++++++- 3 files changed, 82 insertions(+), 315 deletions(-) diff --git a/models/issues/issue_stats.go b/models/issues/issue_stats.go index 1654e6ce756ff..d01ee44462eb8 100644 --- a/models/issues/issue_stats.go +++ b/models/issues/issue_stats.go @@ -5,7 +5,6 @@ package issues import ( "context" - "errors" "fmt" "code.gitea.io/gitea/models/db" @@ -181,195 +180,6 @@ func applyIssuesOptions(sess *xorm.Session, opts *IssuesOptions, issueIDs []int6 return sess } -// GetUserIssueStats returns issue statistic information for dashboard by given conditions. -func GetUserIssueStats(filterMode int, opts IssuesOptions) (*IssueStats, error) { - if opts.User == nil { - return nil, errors.New("issue stats without user") - } - if opts.IsPull.IsNone() { - return nil, errors.New("unaccepted ispull option") - } - - var err error - stats := &IssueStats{} - - cond := builder.NewCond() - - cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull.IsTrue()}) - - if len(opts.RepoIDs) > 0 { - cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs)) - } - if len(opts.IssueIDs) > 0 { - cond = cond.And(builder.In("issue.id", opts.IssueIDs)) - } - if opts.RepoCond != nil { - cond = cond.And(opts.RepoCond) - } - - if opts.User != nil { - cond = cond.And(issuePullAccessibleRepoCond("issue.repo_id", opts.User.ID, opts.Org, opts.Team, opts.IsPull.IsTrue())) - } - - sess := func(cond builder.Cond) *xorm.Session { - s := db.GetEngine(db.DefaultContext). - Join("INNER", "repository", "`issue`.repo_id = `repository`.id"). - Where(cond) - if len(opts.LabelIDs) > 0 { - s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id"). - In("issue_label.label_id", opts.LabelIDs) - } - - if opts.IsArchived != util.OptionalBoolNone { - s.And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()}) - } - return s - } - - switch filterMode { - case FilterModeAll, FilterModeYourRepositories: - stats.OpenCount, err = sess(cond). - And("issue.is_closed = ?", false). - Count(new(Issue)) - if err != nil { - return nil, err - } - stats.ClosedCount, err = sess(cond). - And("issue.is_closed = ?", true). - Count(new(Issue)) - if err != nil { - return nil, err - } - case FilterModeAssign: - stats.OpenCount, err = applyAssigneeCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", false). - Count(new(Issue)) - if err != nil { - return nil, err - } - stats.ClosedCount, err = applyAssigneeCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", true). - Count(new(Issue)) - if err != nil { - return nil, err - } - case FilterModeCreate: - stats.OpenCount, err = applyPosterCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", false). - Count(new(Issue)) - if err != nil { - return nil, err - } - stats.ClosedCount, err = applyPosterCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", true). - Count(new(Issue)) - if err != nil { - return nil, err - } - case FilterModeMention: - stats.OpenCount, err = applyMentionedCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", false). - Count(new(Issue)) - if err != nil { - return nil, err - } - stats.ClosedCount, err = applyMentionedCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", true). - Count(new(Issue)) - if err != nil { - return nil, err - } - case FilterModeReviewRequested: - stats.OpenCount, err = applyReviewRequestedCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", false). - Count(new(Issue)) - if err != nil { - return nil, err - } - stats.ClosedCount, err = applyReviewRequestedCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", true). - Count(new(Issue)) - if err != nil { - return nil, err - } - case FilterModeReviewed: - stats.OpenCount, err = applyReviewedCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", false). - Count(new(Issue)) - if err != nil { - return nil, err - } - stats.ClosedCount, err = applyReviewedCondition(sess(cond), opts.User.ID). - And("issue.is_closed = ?", true). - Count(new(Issue)) - if err != nil { - return nil, err - } - } - - cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed.IsTrue()}) - stats.AssignCount, err = applyAssigneeCondition(sess(cond), opts.User.ID).Count(new(Issue)) - if err != nil { - return nil, err - } - - stats.CreateCount, err = applyPosterCondition(sess(cond), opts.User.ID).Count(new(Issue)) - if err != nil { - return nil, err - } - - stats.MentionCount, err = applyMentionedCondition(sess(cond), opts.User.ID).Count(new(Issue)) - if err != nil { - return nil, err - } - - stats.YourRepositoriesCount, err = sess(cond).Count(new(Issue)) - if err != nil { - return nil, err - } - - stats.ReviewRequestedCount, err = applyReviewRequestedCondition(sess(cond), opts.User.ID).Count(new(Issue)) - if err != nil { - return nil, err - } - - stats.ReviewedCount, err = applyReviewedCondition(sess(cond), opts.User.ID).Count(new(Issue)) - if err != nil { - return nil, err - } - - return stats, nil -} - -// GetRepoIssueStats returns number of open and closed repository issues by given filter mode. -func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen, numClosed int64) { - countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session { - sess := db.GetEngine(db.DefaultContext). - Where("is_closed = ?", isClosed). - And("is_pull = ?", isPull). - And("repo_id = ?", repoID) - - return sess - } - - openCountSession := countSession(false, isPull, repoID) - closedCountSession := countSession(true, isPull, repoID) - - switch filterMode { - case FilterModeAssign: - applyAssigneeCondition(openCountSession, uid) - applyAssigneeCondition(closedCountSession, uid) - case FilterModeCreate: - applyPosterCondition(openCountSession, uid) - applyPosterCondition(closedCountSession, uid) - } - - openResult, _ := openCountSession.Count(new(Issue)) - closedResult, _ := closedCountSession.Count(new(Issue)) - - return openResult, closedResult -} - // CountOrphanedIssues count issues without a repo func CountOrphanedIssues(ctx context.Context) (int64, error) { return db.GetEngine(ctx). diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index b2ff74f0cf53b..747fbbc78caef 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -13,12 +13,10 @@ import ( "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" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" "xorm.io/builder" @@ -204,128 +202,6 @@ func TestIssues(t *testing.T) { } } -func TestGetUserIssueStats(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - for _, test := range []struct { - FilterMode int - Opts issues_model.IssuesOptions - ExpectedIssueStats issues_model.IssueStats - }{ - { - issues_model.FilterModeAll, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), - RepoIDs: []int64{1}, - IsPull: util.OptionalBoolFalse, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 1, // 6 - AssignCount: 1, // 6 - CreateCount: 1, // 6 - OpenCount: 1, // 6 - ClosedCount: 1, // 1 - }, - }, - { - issues_model.FilterModeAll, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), - RepoIDs: []int64{1}, - IsPull: util.OptionalBoolFalse, - IsClosed: util.OptionalBoolTrue, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 1, // 6 - AssignCount: 0, - CreateCount: 0, - OpenCount: 1, // 6 - ClosedCount: 1, // 1 - }, - }, - { - issues_model.FilterModeAssign, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), - IsPull: util.OptionalBoolFalse, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 1, // 6 - AssignCount: 1, // 6 - CreateCount: 1, // 6 - OpenCount: 1, // 6 - ClosedCount: 0, - }, - }, - { - issues_model.FilterModeCreate, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), - IsPull: util.OptionalBoolFalse, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 1, // 6 - AssignCount: 1, // 6 - CreateCount: 1, // 6 - OpenCount: 1, // 6 - ClosedCount: 0, - }, - }, - { - issues_model.FilterModeMention, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), - IsPull: util.OptionalBoolFalse, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 1, // 6 - AssignCount: 1, // 6 - CreateCount: 1, // 6 - MentionCount: 0, - OpenCount: 0, - ClosedCount: 0, - }, - }, - { - issues_model.FilterModeCreate, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), - IssueIDs: []int64{1}, - IsPull: util.OptionalBoolFalse, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 1, // 1 - AssignCount: 1, // 1 - CreateCount: 1, // 1 - OpenCount: 1, // 1 - ClosedCount: 0, - }, - }, - { - issues_model.FilterModeAll, - issues_model.IssuesOptions{ - User: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}), - Org: unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}), - Team: unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 7}), - IsPull: util.OptionalBoolFalse, - }, - issues_model.IssueStats{ - YourRepositoriesCount: 2, - AssignCount: 1, - CreateCount: 1, - OpenCount: 2, - }, - }, - } { - t.Run(fmt.Sprintf("%#v", test.Opts), func(t *testing.T) { - stats, err := issues_model.GetUserIssueStats(test.FilterMode, test.Opts) - if !assert.NoError(t, err) { - return - } - assert.Equal(t, test.ExpectedIssueStats, *stats) - }) - } -} - func TestIssue_loadTotalTimes(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) ms, err := issues_model.GetIssueByID(db.DefaultContext, 2) diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index a4e1c899fc1eb..c3a6d88685147 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -5,6 +5,7 @@ package issues import ( "context" + "fmt" "path" "path/filepath" "testing" @@ -13,6 +14,7 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/indexer/issues/bleve" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/util" _ "code.gitea.io/gitea/models" _ "code.gitea.io/gitea/models/actions" @@ -89,7 +91,7 @@ func TestBleveSearchIssues(t *testing.T) { }) } -func TestDBSearchIssues(t *testing.T) { +func TestDBSearchIssuesWithKeyword(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) setting.Indexer.IssueType = "db" @@ -131,3 +133,82 @@ func TestDBSearchIssues(t *testing.T) { assert.EqualValues(t, []int64{1}, ids) }) } + +// TODO: add more tests +func TestDBSearchIssueWithoutKeyword(t *testing.T) { + assert.NoError(t, unittest.PrepareTestDatabase()) + + setting.Indexer.IssueType = "db" + InitIssueIndexer(true) + + int64Pointer := func(x int64) *int64 { + return &x + } + for _, test := range []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + RepoIDs: []int64{1}, + }, + []int64{11, 5, 3, 2, 1}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + AssigneeID: int64Pointer(1), + }, + []int64{1}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + PosterID: int64Pointer(1), + }, + []int64{11, 3, 2, 1}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + IsClosed: util.OptionalBoolFalse, + }, + []int64{11, 3, 2, 1}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + IsClosed: util.OptionalBoolTrue, + }, + []int64{5}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + }, + []int64{11, 5, 3, 2, 1}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + AssigneeID: int64Pointer(1), + }, + []int64{1}, + }, + { + SearchOptions{ + RepoIDs: []int64{1}, + PosterID: int64Pointer(1), + }, + []int64{11, 3, 2, 1}, + }, + } { + t.Run(fmt.Sprintf("%#v", test.opts), func(t *testing.T) { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + }) + } +} From 76659b1114153603050de810006e04a938e9dcb7 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Thu, 14 Sep 2023 19:09:32 +0200 Subject: [PATCH 03/23] Reduce usage of `db.DefaultContext` (#27073) Part of #27065 This reduces the usage of `db.DefaultContext`. I think I've got enough files for the first PR. When this is merged, I will continue working on this. Considering how many files this PR affect, I hope it won't take to long to merge, so I don't end up in the merge conflict hell. --------- Co-authored-by: wxiaoguang --- cmd/admin_user_create.go | 4 +- cmd/admin_user_list.go | 4 +- models/activities/statistic.go | 10 +-- models/asymkey/gpg_key.go | 10 +-- models/asymkey/gpg_key_add.go | 2 +- models/asymkey/gpg_key_commit_verification.go | 21 ++++--- models/asymkey/ssh_key_commit_verification.go | 5 +- models/asymkey/ssh_key_principals.go | 5 +- models/org_team.go | 44 ++++++------- models/org_team_test.go | 22 +++---- models/organization/org.go | 14 ++--- models/organization/org_test.go | 2 +- models/organization/org_user_test.go | 4 +- models/repo/fork.go | 12 ++-- models/repo/git.go | 6 +- models/user/email_address.go | 52 ++++++++-------- models/user/email_address_test.go | 42 ++++++------- models/user/list.go | 10 +-- models/user/search.go | 11 ++-- models/user/user.go | 62 +++++++++---------- models/user/user_test.go | 24 +++---- modules/context/repo.go | 4 +- modules/doctor/fix8312.go | 2 +- modules/doctor/usertype.go | 4 +- modules/metrics/collector.go | 3 +- modules/repository/fork.go | 10 +-- routers/api/v1/admin/email.go | 2 +- routers/api/v1/admin/org.go | 2 +- routers/api/v1/admin/user.go | 4 +- routers/api/v1/misc/nodeinfo.go | 6 +- routers/api/v1/org/member.go | 2 +- routers/api/v1/org/org.go | 2 +- routers/api/v1/org/team.go | 10 +-- routers/api/v1/repo/branch.go | 8 +-- routers/api/v1/repo/fork.go | 2 +- routers/api/v1/repo/issue_subscription.go | 2 +- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/user/email.go | 6 +- routers/api/v1/user/user.go | 2 +- routers/install/install.go | 2 +- routers/private/default_branch.go | 2 +- routers/web/admin/admin.go | 2 +- routers/web/admin/emails.go | 4 +- routers/web/admin/users.go | 4 +- routers/web/auth/auth.go | 20 +++--- routers/web/auth/linkaccount.go | 2 +- routers/web/auth/oauth.go | 8 +-- routers/web/auth/openid.go | 4 +- routers/web/auth/password.go | 2 +- routers/web/explore/user.go | 4 +- routers/web/home.go | 2 +- routers/web/org/home.go | 2 +- routers/web/org/members.go | 4 +- routers/web/org/teams.go | 20 +++--- routers/web/repo/branch.go | 2 +- routers/web/repo/compare.go | 6 +- routers/web/repo/issue.go | 2 +- routers/web/repo/middlewares.go | 2 +- routers/web/repo/pull.go | 8 +-- routers/web/repo/repo.go | 2 +- routers/web/repo/setting/default_branch.go | 2 +- routers/web/repo/view.go | 2 +- routers/web/user/search.go | 2 +- routers/web/user/setting/account.go | 12 ++-- routers/web/user/setting/keys.go | 2 +- routers/web/user/setting/profile.go | 6 +- services/auth/basic.go | 2 +- services/auth/interface.go | 2 +- services/auth/reverseproxy.go | 2 +- services/auth/signin.go | 11 ++-- services/auth/source/db/authenticate.go | 6 +- services/auth/source/db/source.go | 6 +- .../auth/source/ldap/source_authenticate.go | 14 ++--- services/auth/source/ldap/source_sync.go | 4 +- .../auth/source/oauth2/source_authenticate.go | 6 +- .../auth/source/pam/source_authenticate.go | 5 +- .../auth/source/smtp/source_authenticate.go | 5 +- services/auth/source/source_group_sync.go | 4 +- services/auth/sspi_windows.go | 7 ++- services/convert/convert.go | 8 +-- services/repository/create_test.go | 4 +- services/user/user_test.go | 4 +- tests/integration/auth_ldap_test.go | 4 +- 83 files changed, 339 insertions(+), 324 deletions(-) diff --git a/cmd/admin_user_create.go b/cmd/admin_user_create.go index 52ce46c353bf1..73afcdcf32455 100644 --- a/cmd/admin_user_create.go +++ b/cmd/admin_user_create.go @@ -115,7 +115,7 @@ func runCreateUser(c *cli.Context) error { // If this is the first user being created. // Take it as the admin and don't force a password update. - if n := user_model.CountUsers(nil); n == 0 { + if n := user_model.CountUsers(ctx, nil); n == 0 { changePassword = false } @@ -146,7 +146,7 @@ func runCreateUser(c *cli.Context) error { IsRestricted: restricted, } - if err := user_model.CreateUser(u, overwriteDefault); err != nil { + if err := user_model.CreateUser(ctx, u, overwriteDefault); err != nil { return fmt.Errorf("CreateUser: %w", err) } diff --git a/cmd/admin_user_list.go b/cmd/admin_user_list.go index 9db9b5e56f7a8..4c2b26d1dfd97 100644 --- a/cmd/admin_user_list.go +++ b/cmd/admin_user_list.go @@ -33,7 +33,7 @@ func runListUsers(c *cli.Context) error { return err } - users, err := user_model.GetAllUsers() + users, err := user_model.GetAllUsers(ctx) if err != nil { return err } @@ -48,7 +48,7 @@ func runListUsers(c *cli.Context) error { } } } else { - twofa := user_model.UserList(users).GetTwoFaStatus() + twofa := user_model.UserList(users).GetTwoFaStatus(ctx) fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\t2FA\n") for _, u := range users { fmt.Fprintf(w, "%d\t%s\t%s\t%t\t%t\t%t\n", u.ID, u.Name, u.Email, u.IsActive, u.IsAdmin, twofa[u.ID]) diff --git a/models/activities/statistic.go b/models/activities/statistic.go index 9d379cd0c4f1a..5479db20ebae1 100644 --- a/models/activities/statistic.go +++ b/models/activities/statistic.go @@ -4,6 +4,8 @@ package activities import ( + "context" + asymkey_model "code.gitea.io/gitea/models/asymkey" "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" @@ -47,12 +49,12 @@ type IssueByRepositoryCount struct { } // GetStatistic returns the database statistics -func GetStatistic() (stats Statistic) { - e := db.GetEngine(db.DefaultContext) - stats.Counter.User = user_model.CountUsers(nil) +func GetStatistic(ctx context.Context) (stats Statistic) { + e := db.GetEngine(ctx) + stats.Counter.User = user_model.CountUsers(ctx, nil) stats.Counter.Org, _ = organization.CountOrgs(organization.FindOrgOptions{IncludePrivate: true}) stats.Counter.PublicKey, _ = e.Count(new(asymkey_model.PublicKey)) - stats.Counter.Repo, _ = repo_model.CountRepositories(db.DefaultContext, repo_model.CountRepositoryOptions{}) + stats.Counter.Repo, _ = repo_model.CountRepositories(ctx, repo_model.CountRepositoryOptions{}) stats.Counter.Watch, _ = e.Count(new(repo_model.Watch)) stats.Counter.Star, _ = e.Count(new(repo_model.Star)) stats.Counter.Access, _ = e.Count(new(access_model.Access)) diff --git a/models/asymkey/gpg_key.go b/models/asymkey/gpg_key.go index be019184eb5bb..e5e5fdb2f3c9e 100644 --- a/models/asymkey/gpg_key.go +++ b/models/asymkey/gpg_key.go @@ -144,7 +144,7 @@ func parseSubGPGKey(ownerID int64, primaryID string, pubkey *packet.PublicKey, e } // parseGPGKey parse a PrimaryKey entity (primary key + subs keys + self-signature) -func parseGPGKey(ownerID int64, e *openpgp.Entity, verified bool) (*GPGKey, error) { +func parseGPGKey(ctx context.Context, ownerID int64, e *openpgp.Entity, verified bool) (*GPGKey, error) { pubkey := e.PrimaryKey expiry := getExpiryTime(e) @@ -159,7 +159,7 @@ func parseGPGKey(ownerID int64, e *openpgp.Entity, verified bool) (*GPGKey, erro } // Check emails - userEmails, err := user_model.GetEmailAddresses(ownerID) + userEmails, err := user_model.GetEmailAddresses(ctx, ownerID) if err != nil { return nil, err } @@ -251,7 +251,7 @@ func DeleteGPGKey(doer *user_model.User, id int64) (err error) { return committer.Commit() } -func checkKeyEmails(email string, keys ...*GPGKey) (bool, string) { +func checkKeyEmails(ctx context.Context, email string, keys ...*GPGKey) (bool, string) { uid := int64(0) var userEmails []*user_model.EmailAddress var user *user_model.User @@ -263,10 +263,10 @@ func checkKeyEmails(email string, keys ...*GPGKey) (bool, string) { } if key.Verified && key.OwnerID != 0 { if uid != key.OwnerID { - userEmails, _ = user_model.GetEmailAddresses(key.OwnerID) + userEmails, _ = user_model.GetEmailAddresses(ctx, key.OwnerID) uid = key.OwnerID user = &user_model.User{ID: uid} - _, _ = user_model.GetUser(user) + _, _ = user_model.GetUser(ctx, user) } for _, e := range userEmails { if e.IsActivated && (email == "" || strings.EqualFold(e.Email, email)) { diff --git a/models/asymkey/gpg_key_add.go b/models/asymkey/gpg_key_add.go index eb4027b3a444a..6926fd2143415 100644 --- a/models/asymkey/gpg_key_add.go +++ b/models/asymkey/gpg_key_add.go @@ -153,7 +153,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro // Get DB session - key, err := parseGPGKey(ownerID, ekey, verified) + key, err := parseGPGKey(ctx, ownerID, ekey, verified) if err != nil { return nil, err } diff --git a/models/asymkey/gpg_key_commit_verification.go b/models/asymkey/gpg_key_commit_verification.go index 65af0bc94532b..bf0fdd9a9a3d2 100644 --- a/models/asymkey/gpg_key_commit_verification.go +++ b/models/asymkey/gpg_key_commit_verification.go @@ -125,7 +125,7 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific // If this a SSH signature handle it differently if strings.HasPrefix(c.Signature.Signature, "-----BEGIN SSH SIGNATURE-----") { - return ParseCommitWithSSHSignature(c, committer) + return ParseCommitWithSSHSignature(ctx, c, committer) } // Parsing signature @@ -150,6 +150,7 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific // First check if the sig has a keyID and if so just look at that if commitVerification := hashAndVerifyForKeyID( + ctx, sig, c.Signature.Payload, committer, @@ -165,7 +166,7 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific // Now try to associate the signature with the committer, if present if committer.ID != 0 { - keys, err := ListGPGKeys(db.DefaultContext, committer.ID, db.ListOptions{}) + keys, err := ListGPGKeys(ctx, committer.ID, db.ListOptions{}) if err != nil { // Skipping failed to get gpg keys of user log.Error("ListGPGKeys: %v", err) return &CommitVerification{ @@ -175,7 +176,7 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific } } - committerEmailAddresses, _ := user_model.GetEmailAddresses(committer.ID) + committerEmailAddresses, _ := user_model.GetEmailAddresses(ctx, committer.ID) activated := false for _, e := range committerEmailAddresses { if e.IsActivated && strings.EqualFold(e.Email, c.Committer.Email) { @@ -222,7 +223,7 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific } if err := gpgSettings.LoadPublicKeyContent(); err != nil { log.Error("Error getting default signing key: %s %v", gpgSettings.KeyID, err) - } else if commitVerification := verifyWithGPGSettings(&gpgSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil { + } else if commitVerification := verifyWithGPGSettings(ctx, &gpgSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil { if commitVerification.Reason == BadSignature { defaultReason = BadSignature } else { @@ -237,7 +238,7 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific } else if defaultGPGSettings == nil { log.Warn("Unable to get defaultGPGSettings for unattached commit: %s", c.ID.String()) } else if defaultGPGSettings.Sign { - if commitVerification := verifyWithGPGSettings(defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil { + if commitVerification := verifyWithGPGSettings(ctx, defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil { if commitVerification.Reason == BadSignature { defaultReason = BadSignature } else { @@ -257,9 +258,9 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific } } -func verifyWithGPGSettings(gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *user_model.User, keyID string) *CommitVerification { +func verifyWithGPGSettings(ctx context.Context, gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *user_model.User, keyID string) *CommitVerification { // First try to find the key in the db - if commitVerification := hashAndVerifyForKeyID(sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil { + if commitVerification := hashAndVerifyForKeyID(ctx, sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil { return commitVerification } @@ -387,7 +388,7 @@ func hashAndVerifyWithSubKeysCommitVerification(sig *packet.Signature, payload s return nil } -func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *user_model.User, keyID, name, email string) *CommitVerification { +func hashAndVerifyForKeyID(ctx context.Context, sig *packet.Signature, payload string, committer *user_model.User, keyID, name, email string) *CommitVerification { if keyID == "" { return nil } @@ -417,7 +418,7 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use } } - activated, email := checkKeyEmails(email, append([]*GPGKey{key}, primaryKeys...)...) + activated, email := checkKeyEmails(ctx, email, append([]*GPGKey{key}, primaryKeys...)...) if !activated { continue } @@ -427,7 +428,7 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use Email: email, } if key.OwnerID != 0 { - owner, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) + owner, err := user_model.GetUserByID(ctx, key.OwnerID) if err == nil { signer = owner } else if !user_model.IsErrUserNotExist(err) { diff --git a/models/asymkey/ssh_key_commit_verification.go b/models/asymkey/ssh_key_commit_verification.go index af73637c4a89c..80931c9af46c1 100644 --- a/models/asymkey/ssh_key_commit_verification.go +++ b/models/asymkey/ssh_key_commit_verification.go @@ -5,6 +5,7 @@ package asymkey import ( "bytes" + "context" "fmt" "strings" @@ -17,7 +18,7 @@ import ( ) // ParseCommitWithSSHSignature check if signature is good against keystore. -func ParseCommitWithSSHSignature(c *git.Commit, committer *user_model.User) *CommitVerification { +func ParseCommitWithSSHSignature(ctx context.Context, c *git.Commit, committer *user_model.User) *CommitVerification { // Now try to associate the signature with the committer, if present if committer.ID != 0 { keys, err := ListPublicKeys(committer.ID, db.ListOptions{}) @@ -30,7 +31,7 @@ func ParseCommitWithSSHSignature(c *git.Commit, committer *user_model.User) *Com } } - committerEmailAddresses, err := user_model.GetEmailAddresses(committer.ID) + committerEmailAddresses, err := user_model.GetEmailAddresses(ctx, committer.ID) if err != nil { log.Error("GetEmailAddresses: %v", err) } diff --git a/models/asymkey/ssh_key_principals.go b/models/asymkey/ssh_key_principals.go index 6d43437ec106a..150b77c7b204c 100644 --- a/models/asymkey/ssh_key_principals.go +++ b/models/asymkey/ssh_key_principals.go @@ -4,6 +4,7 @@ package asymkey import ( + "context" "fmt" "strings" @@ -63,7 +64,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public } // CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines -func CheckPrincipalKeyString(user *user_model.User, content string) (_ string, err error) { +func CheckPrincipalKeyString(ctx context.Context, user *user_model.User, content string) (_ string, err error) { if setting.SSH.Disabled { return "", db.ErrSSHDisabled{} } @@ -80,7 +81,7 @@ func CheckPrincipalKeyString(user *user_model.User, content string) (_ string, e case "anything": return content, nil case "email": - emails, err := user_model.GetEmailAddresses(user.ID) + emails, err := user_model.GetEmailAddresses(ctx, user.ID) if err != nil { return "", err } diff --git a/models/org_team.go b/models/org_team.go index cf3680990df98..7ddf986ce9fa6 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -73,8 +73,8 @@ func addAllRepositories(ctx context.Context, t *organization.Team) error { } // AddAllRepositories adds all repositories to the team -func AddAllRepositories(t *organization.Team) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func AddAllRepositories(ctx context.Context, t *organization.Team) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -88,12 +88,12 @@ func AddAllRepositories(t *organization.Team) (err error) { } // RemoveAllRepositories removes all repositories from team and recalculates access -func RemoveAllRepositories(t *organization.Team) (err error) { +func RemoveAllRepositories(ctx context.Context, t *organization.Team) (err error) { if t.IncludesAllRepositories { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -153,7 +153,7 @@ func removeAllRepositories(ctx context.Context, t *organization.Team) (err error // NewTeam creates a record of new team. // It's caller's responsibility to assign organization ID. -func NewTeam(t *organization.Team) (err error) { +func NewTeam(ctx context.Context, t *organization.Team) (err error) { if len(t.Name) == 0 { return util.NewInvalidArgumentErrorf("empty team name") } @@ -162,7 +162,7 @@ func NewTeam(t *organization.Team) (err error) { return err } - has, err := db.GetEngine(db.DefaultContext).ID(t.OrgID).Get(new(user_model.User)) + has, err := db.GetEngine(ctx).ID(t.OrgID).Get(new(user_model.User)) if err != nil { return err } @@ -171,7 +171,7 @@ func NewTeam(t *organization.Team) (err error) { } t.LowerName = strings.ToLower(t.Name) - has, err = db.GetEngine(db.DefaultContext). + has, err = db.GetEngine(ctx). Where("org_id=?", t.OrgID). And("lower_name=?", t.LowerName). Get(new(organization.Team)) @@ -182,7 +182,7 @@ func NewTeam(t *organization.Team) (err error) { return organization.ErrTeamAlreadyExist{OrgID: t.OrgID, Name: t.LowerName} } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -218,7 +218,7 @@ func NewTeam(t *organization.Team) (err error) { } // UpdateTeam updates information of team. -func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err error) { +func UpdateTeam(ctx context.Context, t *organization.Team, authChanged, includeAllChanged bool) (err error) { if len(t.Name) == 0 { return util.NewInvalidArgumentErrorf("empty team name") } @@ -227,7 +227,7 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err t.Description = t.Description[:255] } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -293,8 +293,8 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err // DeleteTeam deletes given team. // It's caller's responsibility to assign organization ID. -func DeleteTeam(t *organization.Team) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func DeleteTeam(ctx context.Context, t *organization.Team) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -356,8 +356,8 @@ func DeleteTeam(t *organization.Team) error { // AddTeamMember adds new membership of given team to given organization, // the user will have membership to given organization automatically when needed. -func AddTeamMember(team *organization.Team, userID int64) error { - isAlreadyMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, userID) +func AddTeamMember(ctx context.Context, team *organization.Team, userID int64) error { + isAlreadyMember, err := organization.IsTeamMember(ctx, team.OrgID, team.ID, userID) if err != nil || isAlreadyMember { return err } @@ -366,7 +366,7 @@ func AddTeamMember(team *organization.Team, userID int64) error { return err } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -423,18 +423,14 @@ func AddTeamMember(team *organization.Team, userID int64) error { } } - 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.LoadRepositories(db.DefaultContext); err != nil { + if err := team.LoadRepositories(ctx); err != nil { log.Error("getRepositories failed: %v", err) } + // FIXME: in the goroutine, it can't access the "ctx", it could only use db.DefaultContext at the moment go func(repos []*repo_model.Repository) { for _, repo := range repos { if err = repo_model.WatchRepo(db.DefaultContext, userID, repo.ID, true); err != nil { @@ -444,7 +440,7 @@ func AddTeamMember(team *organization.Team, userID int64) error { }(team.Repos) } - return nil + return committer.Commit() } func removeTeamMember(ctx context.Context, team *organization.Team, userID int64) error { @@ -512,8 +508,8 @@ func removeInvalidOrgUser(ctx context.Context, userID, orgID int64) error { } // RemoveTeamMember removes member from given team of given organization. -func RemoveTeamMember(team *organization.Team, userID int64) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func RemoveTeamMember(ctx context.Context, team *organization.Team, userID int64) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/org_team_test.go b/models/org_team_test.go index 4978f8ef99bd2..e4b7b917e8528 100644 --- a/models/org_team_test.go +++ b/models/org_team_test.go @@ -23,7 +23,7 @@ func TestTeam_AddMember(t *testing.T) { test := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, AddTeamMember(team, userID)) + assert.NoError(t, AddTeamMember(db.DefaultContext, team, userID)) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &user_model.User{ID: team.OrgID}) } @@ -37,7 +37,7 @@ func TestTeam_RemoveMember(t *testing.T) { testSuccess := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, RemoveTeamMember(team, userID)) + assert.NoError(t, RemoveTeamMember(db.DefaultContext, team, userID)) unittest.AssertNotExistsBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}) } @@ -47,7 +47,7 @@ func TestTeam_RemoveMember(t *testing.T) { testSuccess(3, unittest.NonexistentID) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) - err := RemoveTeamMember(team, 2) + err := RemoveTeamMember(db.DefaultContext, team, 2) assert.True(t, organization.IsErrLastOrgOwner(err)) } @@ -61,7 +61,7 @@ func TestNewTeam(t *testing.T) { const teamName = "newTeamName" team := &organization.Team{Name: teamName, OrgID: 3} - assert.NoError(t, NewTeam(team)) + assert.NoError(t, NewTeam(db.DefaultContext, team)) unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: teamName}) unittest.CheckConsistencyFor(t, &organization.Team{}, &user_model.User{ID: team.OrgID}) } @@ -75,7 +75,7 @@ func TestUpdateTeam(t *testing.T) { team.Name = "newName" team.Description = strings.Repeat("A long description!", 100) team.AccessMode = perm.AccessModeAdmin - assert.NoError(t, UpdateTeam(team, true, false)) + assert.NoError(t, UpdateTeam(db.DefaultContext, team, true, false)) team = unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: "newName"}) assert.True(t, strings.HasPrefix(team.Description, "A long description!")) @@ -94,7 +94,7 @@ func TestUpdateTeam2(t *testing.T) { team.LowerName = "owners" team.Name = "Owners" team.Description = strings.Repeat("A long description!", 100) - err := UpdateTeam(team, true, false) + err := UpdateTeam(db.DefaultContext, team, true, false) assert.True(t, organization.IsErrTeamAlreadyExist(err)) unittest.CheckConsistencyFor(t, &organization.Team{ID: team.ID}) @@ -104,7 +104,7 @@ func TestDeleteTeam(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) - assert.NoError(t, DeleteTeam(team)) + assert.NoError(t, DeleteTeam(db.DefaultContext, team)) unittest.AssertNotExistsBean(t, &organization.Team{ID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamUser{TeamID: team.ID}) @@ -122,7 +122,7 @@ func TestAddTeamMember(t *testing.T) { test := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, AddTeamMember(team, userID)) + assert.NoError(t, AddTeamMember(db.DefaultContext, team, userID)) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &user_model.User{ID: team.OrgID}) } @@ -136,7 +136,7 @@ func TestRemoveTeamMember(t *testing.T) { testSuccess := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, RemoveTeamMember(team, userID)) + assert.NoError(t, RemoveTeamMember(db.DefaultContext, team, userID)) unittest.AssertNotExistsBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}) } @@ -146,7 +146,7 @@ func TestRemoveTeamMember(t *testing.T) { testSuccess(3, unittest.NonexistentID) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) - err := RemoveTeamMember(team, 2) + err := RemoveTeamMember(db.DefaultContext, team, 2) assert.True(t, organization.IsErrLastOrgOwner(err)) } @@ -161,7 +161,7 @@ func TestRepository_RecalculateAccesses3(t *testing.T) { // adding user29 to team5 should add an explicit access row for repo 23 // even though repo 23 is public - assert.NoError(t, AddTeamMember(team5, user29.ID)) + assert.NoError(t, AddTeamMember(db.DefaultContext, team5, user29.ID)) has, err = db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 29, RepoID: 23}) assert.NoError(t, err) diff --git a/models/organization/org.go b/models/organization/org.go index 8fd4ad076bd2d..260571b4b242a 100644 --- a/models/organization/org.go +++ b/models/organization/org.go @@ -140,8 +140,8 @@ func (org *Organization) LoadTeams() ([]*Team, error) { } // GetMembers returns all members of organization. -func (org *Organization) GetMembers() (user_model.UserList, map[int64]bool, error) { - return FindOrgMembers(&FindOrgMembersOpts{ +func (org *Organization) GetMembers(ctx context.Context) (user_model.UserList, map[int64]bool, error) { + return FindOrgMembers(ctx, &FindOrgMembersOpts{ OrgID: org.ID, }) } @@ -208,8 +208,8 @@ func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) { } // FindOrgMembers loads organization members according conditions -func FindOrgMembers(opts *FindOrgMembersOpts) (user_model.UserList, map[int64]bool, error) { - ous, err := GetOrgUsersByOrgID(db.DefaultContext, opts) +func FindOrgMembers(ctx context.Context, opts *FindOrgMembersOpts) (user_model.UserList, map[int64]bool, error) { + ous, err := GetOrgUsersByOrgID(ctx, opts) if err != nil { return nil, nil, err } @@ -221,7 +221,7 @@ func FindOrgMembers(opts *FindOrgMembersOpts) (user_model.UserList, map[int64]bo idsIsPublic[ou.UID] = ou.IsPublic } - users, err := user_model.GetUsersByIDs(ids) + users, err := user_model.GetUsersByIDs(ctx, ids) if err != nil { return nil, nil, err } @@ -520,10 +520,10 @@ func HasOrgsVisible(orgs []*Organization, user *user_model.User) bool { // GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID // are allowed to create repos. -func GetOrgsCanCreateRepoByUserID(userID int64) ([]*Organization, error) { +func GetOrgsCanCreateRepoByUserID(ctx context.Context, userID int64) ([]*Organization, error) { orgs := make([]*Organization, 0, 10) - return orgs, db.GetEngine(db.DefaultContext).Where(builder.In("id", builder.Select("`user`.id").From("`user`"). + return orgs, db.GetEngine(ctx).Where(builder.In("id", builder.Select("`user`.id").From("`user`"). Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id"). Join("INNER", "`team`", "`team`.id = `team_user`.team_id"). Where(builder.Eq{"`team_user`.uid": userID}). diff --git a/models/organization/org_test.go b/models/organization/org_test.go index d36736b5c2a7e..b5dff9ec01a23 100644 --- a/models/organization/org_test.go +++ b/models/organization/org_test.go @@ -103,7 +103,7 @@ func TestUser_GetTeams(t *testing.T) { func TestUser_GetMembers(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) - members, _, err := org.GetMembers() + members, _, err := org.GetMembers(db.DefaultContext) assert.NoError(t, err) if assert.Len(t, members, 3) { assert.Equal(t, int64(2), members[0].ID) diff --git a/models/organization/org_user_test.go b/models/organization/org_user_test.go index b6477f859c795..1c3cf2798d215 100644 --- a/models/organization/org_user_test.go +++ b/models/organization/org_user_test.go @@ -94,7 +94,7 @@ func TestUserListIsPublicMember(t *testing.T) { func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) { org, err := organization.GetOrgByID(db.DefaultContext, orgID) assert.NoError(t, err) - _, membersIsPublic, err := org.GetMembers() + _, membersIsPublic, err := org.GetMembers(db.DefaultContext) assert.NoError(t, err) assert.Equal(t, expected, membersIsPublic) } @@ -121,7 +121,7 @@ func TestUserListIsUserOrgOwner(t *testing.T) { func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) { org, err := organization.GetOrgByID(db.DefaultContext, orgID) assert.NoError(t, err) - members, _, err := org.GetMembers() + members, _, err := org.GetMembers(db.DefaultContext) assert.NoError(t, err) assert.Equal(t, expected, organization.IsUserOrgOwner(members, orgID)) } diff --git a/models/repo/fork.go b/models/repo/fork.go index eafbab0fb171c..6be6ebc3f523c 100644 --- a/models/repo/fork.go +++ b/models/repo/fork.go @@ -21,9 +21,9 @@ func GetRepositoriesByForkID(ctx context.Context, forkID int64) ([]*Repository, } // GetForkedRepo checks if given user has already forked a repository with given ID. -func GetForkedRepo(ownerID, repoID int64) *Repository { +func GetForkedRepo(ctx context.Context, ownerID, repoID int64) *Repository { repo := new(Repository) - has, _ := db.GetEngine(db.DefaultContext). + has, _ := db.GetEngine(ctx). Where("owner_id=? AND fork_id=?", ownerID, repoID). Get(repo) if has { @@ -33,8 +33,8 @@ func GetForkedRepo(ownerID, repoID int64) *Repository { } // HasForkedRepo checks if given user has already forked a repository with given ID. -func HasForkedRepo(ownerID, repoID int64) bool { - has, _ := db.GetEngine(db.DefaultContext). +func HasForkedRepo(ctx context.Context, ownerID, repoID int64) bool { + has, _ := db.GetEngine(ctx). Table("repository"). Where("owner_id=? AND fork_id=?", ownerID, repoID). Exist() @@ -55,10 +55,10 @@ func GetUserFork(ctx context.Context, repoID, userID int64) (*Repository, error) } // GetForks returns all the forks of the repository -func GetForks(repo *Repository, listOptions db.ListOptions) ([]*Repository, error) { +func GetForks(ctx context.Context, repo *Repository, listOptions db.ListOptions) ([]*Repository, error) { if listOptions.Page == 0 { forks := make([]*Repository, 0, repo.NumForks) - return forks, db.GetEngine(db.DefaultContext).Find(&forks, &Repository{ForkID: repo.ID}) + return forks, db.GetEngine(ctx).Find(&forks, &Repository{ForkID: repo.ID}) } sess := db.GetPaginatedSession(&listOptions) diff --git a/models/repo/git.go b/models/repo/git.go index 2f71128b5aa26..610c55429657c 100644 --- a/models/repo/git.go +++ b/models/repo/git.go @@ -4,6 +4,8 @@ package repo import ( + "context" + "code.gitea.io/gitea/models/db" ) @@ -26,7 +28,7 @@ const ( ) // UpdateDefaultBranch updates the default branch -func UpdateDefaultBranch(repo *Repository) error { - _, err := db.GetEngine(db.DefaultContext).ID(repo.ID).Cols("default_branch").Update(repo) +func UpdateDefaultBranch(ctx context.Context, repo *Repository) error { + _, err := db.GetEngine(ctx).ID(repo.ID).Cols("default_branch").Update(repo) return err } diff --git a/models/user/email_address.go b/models/user/email_address.go index e916249e30bbe..f1ed6692cfefc 100644 --- a/models/user/email_address.go +++ b/models/user/email_address.go @@ -178,9 +178,9 @@ func ValidateEmail(email string) error { } // GetEmailAddresses returns all email addresses belongs to given user. -func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { +func GetEmailAddresses(ctx context.Context, uid int64) ([]*EmailAddress, error) { emails := make([]*EmailAddress, 0, 5) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("uid=?", uid). Asc("id"). Find(&emails); err != nil { @@ -190,10 +190,10 @@ func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { } // GetEmailAddressByID gets a user's email address by ID -func GetEmailAddressByID(uid, id int64) (*EmailAddress, error) { +func GetEmailAddressByID(ctx context.Context, uid, id int64) (*EmailAddress, error) { // User ID is required for security reasons email := &EmailAddress{UID: uid} - if has, err := db.GetEngine(db.DefaultContext).ID(id).Get(email); err != nil { + if has, err := db.GetEngine(ctx).ID(id).Get(email); err != nil { return nil, err } else if !has { return nil, nil @@ -253,7 +253,7 @@ func AddEmailAddress(ctx context.Context, email *EmailAddress) error { } // AddEmailAddresses adds an email address to given user. -func AddEmailAddresses(emails []*EmailAddress) error { +func AddEmailAddresses(ctx context.Context, emails []*EmailAddress) error { if len(emails) == 0 { return nil } @@ -261,7 +261,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { // Check if any of them has been used for i := range emails { emails[i].Email = strings.TrimSpace(emails[i].Email) - used, err := IsEmailUsed(db.DefaultContext, emails[i].Email) + used, err := IsEmailUsed(ctx, emails[i].Email) if err != nil { return err } else if used { @@ -272,7 +272,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { } } - if err := db.Insert(db.DefaultContext, emails); err != nil { + if err := db.Insert(ctx, emails); err != nil { return fmt.Errorf("Insert: %w", err) } @@ -280,7 +280,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { } // DeleteEmailAddress deletes an email address of given user. -func DeleteEmailAddress(email *EmailAddress) (err error) { +func DeleteEmailAddress(ctx context.Context, email *EmailAddress) (err error) { if email.IsPrimary { return ErrPrimaryEmailCannotDelete{Email: email.Email} } @@ -291,12 +291,12 @@ func DeleteEmailAddress(email *EmailAddress) (err error) { UID: email.UID, } if email.ID > 0 { - deleted, err = db.GetEngine(db.DefaultContext).ID(email.ID).Delete(&address) + deleted, err = db.GetEngine(ctx).ID(email.ID).Delete(&address) } else { if email.Email != "" && email.LowerEmail == "" { email.LowerEmail = strings.ToLower(email.Email) } - deleted, err = db.GetEngine(db.DefaultContext). + deleted, err = db.GetEngine(ctx). Where("lower_email=?", email.LowerEmail). Delete(&address) } @@ -310,9 +310,9 @@ func DeleteEmailAddress(email *EmailAddress) (err error) { } // DeleteEmailAddresses deletes multiple email addresses -func DeleteEmailAddresses(emails []*EmailAddress) (err error) { +func DeleteEmailAddresses(ctx context.Context, emails []*EmailAddress) (err error) { for i := range emails { - if err = DeleteEmailAddress(emails[i]); err != nil { + if err = DeleteEmailAddress(ctx, emails[i]); err != nil { return err } } @@ -329,8 +329,8 @@ func DeleteInactiveEmailAddresses(ctx context.Context) error { } // ActivateEmail activates the email address to given user. -func ActivateEmail(email *EmailAddress) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func ActivateEmail(ctx context.Context, email *EmailAddress) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -357,8 +357,8 @@ func updateActivation(ctx context.Context, email *EmailAddress, activate bool) e } // MakeEmailPrimary sets primary email address of given user. -func MakeEmailPrimary(email *EmailAddress) error { - has, err := db.GetEngine(db.DefaultContext).Get(email) +func MakeEmailPrimary(ctx context.Context, email *EmailAddress) error { + has, err := db.GetEngine(ctx).Get(email) if err != nil { return err } else if !has { @@ -370,7 +370,7 @@ func MakeEmailPrimary(email *EmailAddress) error { } user := &User{} - has, err = db.GetEngine(db.DefaultContext).ID(email.UID).Get(user) + has, err = db.GetEngine(ctx).ID(email.UID).Get(user) if err != nil { return err } else if !has { @@ -381,7 +381,7 @@ func MakeEmailPrimary(email *EmailAddress) error { } } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -411,17 +411,17 @@ func MakeEmailPrimary(email *EmailAddress) error { } // VerifyActiveEmailCode verifies active email code when active account -func VerifyActiveEmailCode(code, email string) *EmailAddress { +func VerifyActiveEmailCode(ctx context.Context, code, email string) *EmailAddress { minutes := setting.Service.ActiveCodeLives - if user := GetVerifyUser(code); user != nil { + if user := GetVerifyUser(ctx, code); user != nil { // time limit code prefix := code[:base.TimeLimitCodeLength] data := fmt.Sprintf("%d%s%s%s%s", user.ID, email, user.LowerName, user.Passwd, user.Rands) if base.VerifyTimeLimitCode(data, minutes, prefix) { emailAddress := &EmailAddress{UID: user.ID, Email: email} - if has, _ := db.GetEngine(db.DefaultContext).Get(emailAddress); has { + if has, _ := db.GetEngine(ctx).Get(emailAddress); has { return emailAddress } } @@ -466,7 +466,7 @@ type SearchEmailResult struct { // SearchEmails takes options i.e. keyword and part of email name to search, // it returns results in given range and number of total results. -func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) { +func SearchEmails(ctx context.Context, opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) { var cond builder.Cond = builder.Eq{"`user`.`type`": UserTypeIndividual} if len(opts.Keyword) > 0 { likeStr := "%" + strings.ToLower(opts.Keyword) + "%" @@ -491,7 +491,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) cond = cond.And(builder.Eq{"email_address.is_activated": false}) } - count, err := db.GetEngine(db.DefaultContext).Join("INNER", "`user`", "`user`.ID = email_address.uid"). + count, err := db.GetEngine(ctx).Join("INNER", "`user`", "`user`.ID = email_address.uid"). Where(cond).Count(new(EmailAddress)) if err != nil { return nil, 0, fmt.Errorf("Count: %w", err) @@ -505,7 +505,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) opts.SetDefaultValues() emails := make([]*SearchEmailResult, 0, opts.PageSize) - err = db.GetEngine(db.DefaultContext).Table("email_address"). + err = db.GetEngine(ctx).Table("email_address"). Select("email_address.*, `user`.name, `user`.full_name"). Join("INNER", "`user`", "`user`.ID = email_address.uid"). Where(cond). @@ -518,8 +518,8 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) // ActivateUserEmail will change the activated state of an email address, // either primary or secondary (all in the email_address table) -func ActivateUserEmail(userID int64, email string, activate bool) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func ActivateUserEmail(ctx context.Context, userID int64, email string, activate bool) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index f2b383fe4b249..7f3ca75cfdc00 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -17,14 +17,14 @@ import ( func TestGetEmailAddresses(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - emails, _ := user_model.GetEmailAddresses(int64(1)) + emails, _ := user_model.GetEmailAddresses(db.DefaultContext, int64(1)) if assert.Len(t, emails, 3) { assert.True(t, emails[0].IsPrimary) assert.True(t, emails[2].IsActivated) assert.False(t, emails[2].IsPrimary) } - emails, _ = user_model.GetEmailAddresses(int64(2)) + emails, _ = user_model.GetEmailAddresses(db.DefaultContext, int64(2)) if assert.Len(t, emails, 2) { assert.True(t, emails[0].IsPrimary) assert.True(t, emails[0].IsActivated) @@ -76,10 +76,10 @@ func TestAddEmailAddresses(t *testing.T) { LowerEmail: "user5678@example.com", IsActivated: true, } - assert.NoError(t, user_model.AddEmailAddresses(emails)) + assert.NoError(t, user_model.AddEmailAddresses(db.DefaultContext, emails)) // ErrEmailAlreadyUsed - err := user_model.AddEmailAddresses(emails) + err := user_model.AddEmailAddresses(db.DefaultContext, emails) assert.Error(t, err) assert.True(t, user_model.IsErrEmailAlreadyUsed(err)) } @@ -87,21 +87,21 @@ func TestAddEmailAddresses(t *testing.T) { func TestDeleteEmailAddress(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, user_model.DeleteEmailAddress(&user_model.EmailAddress{ + assert.NoError(t, user_model.DeleteEmailAddress(db.DefaultContext, &user_model.EmailAddress{ UID: int64(1), ID: int64(33), Email: "user1-2@example.com", LowerEmail: "user1-2@example.com", })) - assert.NoError(t, user_model.DeleteEmailAddress(&user_model.EmailAddress{ + assert.NoError(t, user_model.DeleteEmailAddress(db.DefaultContext, &user_model.EmailAddress{ UID: int64(1), Email: "user1-3@example.com", LowerEmail: "user1-3@example.com", })) // Email address does not exist - err := user_model.DeleteEmailAddress(&user_model.EmailAddress{ + err := user_model.DeleteEmailAddress(db.DefaultContext, &user_model.EmailAddress{ UID: int64(1), Email: "user1234567890@example.com", LowerEmail: "user1234567890@example.com", @@ -125,10 +125,10 @@ func TestDeleteEmailAddresses(t *testing.T) { Email: "user2-2@example.com", LowerEmail: "user2-2@example.com", } - assert.NoError(t, user_model.DeleteEmailAddresses(emails)) + assert.NoError(t, user_model.DeleteEmailAddresses(db.DefaultContext, emails)) // ErrEmailAlreadyUsed - err := user_model.DeleteEmailAddresses(emails) + err := user_model.DeleteEmailAddresses(db.DefaultContext, emails) assert.Error(t, err) } @@ -138,28 +138,28 @@ func TestMakeEmailPrimary(t *testing.T) { email := &user_model.EmailAddress{ Email: "user567890@example.com", } - err := user_model.MakeEmailPrimary(email) + err := user_model.MakeEmailPrimary(db.DefaultContext, email) assert.Error(t, err) assert.EqualError(t, err, user_model.ErrEmailAddressNotExist{Email: email.Email}.Error()) email = &user_model.EmailAddress{ Email: "user11@example.com", } - err = user_model.MakeEmailPrimary(email) + err = user_model.MakeEmailPrimary(db.DefaultContext, email) assert.Error(t, err) assert.EqualError(t, err, user_model.ErrEmailNotActivated.Error()) email = &user_model.EmailAddress{ Email: "user9999999@example.com", } - err = user_model.MakeEmailPrimary(email) + err = user_model.MakeEmailPrimary(db.DefaultContext, email) assert.Error(t, err) assert.True(t, user_model.IsErrUserNotExist(err)) email = &user_model.EmailAddress{ Email: "user101@example.com", } - err = user_model.MakeEmailPrimary(email) + err = user_model.MakeEmailPrimary(db.DefaultContext, email) assert.NoError(t, err) user, _ := user_model.GetUserByID(db.DefaultContext, int64(10)) @@ -174,9 +174,9 @@ func TestActivate(t *testing.T) { UID: int64(1), Email: "user11@example.com", } - assert.NoError(t, user_model.ActivateEmail(email)) + assert.NoError(t, user_model.ActivateEmail(db.DefaultContext, email)) - emails, _ := user_model.GetEmailAddresses(int64(1)) + emails, _ := user_model.GetEmailAddresses(db.DefaultContext, int64(1)) assert.Len(t, emails, 3) assert.True(t, emails[0].IsActivated) assert.True(t, emails[0].IsPrimary) @@ -194,7 +194,7 @@ func TestListEmails(t *testing.T) { PageSize: 10000, }, } - emails, count, err := user_model.SearchEmails(opts) + emails, count, err := user_model.SearchEmails(db.DefaultContext, opts) assert.NoError(t, err) assert.NotEqual(t, int64(0), count) assert.True(t, count > 5) @@ -214,13 +214,13 @@ func TestListEmails(t *testing.T) { // Must find no records opts = &user_model.SearchEmailOptions{Keyword: "NOTFOUND"} - emails, count, err = user_model.SearchEmails(opts) + emails, count, err = user_model.SearchEmails(db.DefaultContext, opts) assert.NoError(t, err) assert.Equal(t, int64(0), count) // Must find users 'user2', 'user28', etc. opts = &user_model.SearchEmailOptions{Keyword: "user2"} - emails, count, err = user_model.SearchEmails(opts) + emails, count, err = user_model.SearchEmails(db.DefaultContext, opts) assert.NoError(t, err) assert.NotEqual(t, int64(0), count) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 2 })) @@ -228,14 +228,14 @@ func TestListEmails(t *testing.T) { // Must find only primary addresses (i.e. from the `user` table) opts = &user_model.SearchEmailOptions{IsPrimary: util.OptionalBoolTrue} - emails, _, err = user_model.SearchEmails(opts) + emails, _, err = user_model.SearchEmails(db.DefaultContext, opts) assert.NoError(t, err) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsPrimary })) assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsPrimary })) // Must find only inactive addresses (i.e. not validated) opts = &user_model.SearchEmailOptions{IsActivated: util.OptionalBoolFalse} - emails, _, err = user_model.SearchEmails(opts) + emails, _, err = user_model.SearchEmails(db.DefaultContext, opts) assert.NoError(t, err) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsActivated })) assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsActivated })) @@ -247,7 +247,7 @@ func TestListEmails(t *testing.T) { Page: 1, }, } - emails, count, err = user_model.SearchEmails(opts) + emails, count, err = user_model.SearchEmails(db.DefaultContext, opts) assert.NoError(t, err) assert.Len(t, emails, 5) assert.Greater(t, count, int64(len(emails))) diff --git a/models/user/list.go b/models/user/list.go index 6b3b7bea9ad38..ca589d1e0201a 100644 --- a/models/user/list.go +++ b/models/user/list.go @@ -25,19 +25,19 @@ func (users UserList) GetUserIDs() []int64 { } // GetTwoFaStatus return state of 2FA enrollement -func (users UserList) GetTwoFaStatus() map[int64]bool { +func (users UserList) GetTwoFaStatus(ctx context.Context) map[int64]bool { results := make(map[int64]bool, len(users)) for _, user := range users { results[user.ID] = false // Set default to false } - if tokenMaps, err := users.loadTwoFactorStatus(db.DefaultContext); err == nil { + if tokenMaps, err := users.loadTwoFactorStatus(ctx); err == nil { for _, token := range tokenMaps { results[token.UID] = true } } - if ids, err := users.userIDsWithWebAuthn(db.DefaultContext); err == nil { + if ids, err := users.userIDsWithWebAuthn(ctx); err == nil { for _, id := range ids { results[id] = true } @@ -71,12 +71,12 @@ func (users UserList) userIDsWithWebAuthn(ctx context.Context) ([]int64, error) } // GetUsersByIDs returns all resolved users from a list of Ids. -func GetUsersByIDs(ids []int64) (UserList, error) { +func GetUsersByIDs(ctx context.Context, ids []int64) (UserList, error) { ous := make([]*User, 0, len(ids)) if len(ids) == 0 { return ous, nil } - err := db.GetEngine(db.DefaultContext).In("id", ids). + err := db.GetEngine(ctx).In("id", ids). Asc("name"). Find(&ous) return ous, err diff --git a/models/user/search.go b/models/user/search.go index 446556f89b77d..0fa278c257217 100644 --- a/models/user/search.go +++ b/models/user/search.go @@ -4,6 +4,7 @@ package user import ( + "context" "fmt" "strings" @@ -39,7 +40,7 @@ type SearchUserOptions struct { ExtraParamStrings map[string]string } -func (opts *SearchUserOptions) toSearchQueryBase() *xorm.Session { +func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) *xorm.Session { var cond builder.Cond cond = builder.Eq{"type": opts.Type} if opts.IncludeReserved { @@ -101,7 +102,7 @@ func (opts *SearchUserOptions) toSearchQueryBase() *xorm.Session { cond = cond.And(builder.Eq{"prohibit_login": opts.IsProhibitLogin.IsTrue()}) } - e := db.GetEngine(db.DefaultContext) + e := db.GetEngine(ctx) if opts.IsTwoFactorEnabled.IsNone() { return e.Where(cond) } @@ -122,8 +123,8 @@ func (opts *SearchUserOptions) toSearchQueryBase() *xorm.Session { // SearchUsers takes options i.e. keyword and part of user name to search, // it returns results in given range and number of total results. -func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { - sessCount := opts.toSearchQueryBase() +func SearchUsers(ctx context.Context, opts *SearchUserOptions) (users []*User, _ int64, _ error) { + sessCount := opts.toSearchQueryBase(ctx) defer sessCount.Close() count, err := sessCount.Count(new(User)) if err != nil { @@ -134,7 +135,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { opts.OrderBy = db.SearchOrderByAlphabetically } - sessQuery := opts.toSearchQueryBase().OrderBy(opts.OrderBy.String()) + sessQuery := opts.toSearchQueryBase(ctx).OrderBy(opts.OrderBy.String()) defer sessQuery.Close() if opts.Page != 0 { sessQuery = db.SetSessionPagination(sessQuery, opts) diff --git a/models/user/user.go b/models/user/user.go index 86cf2ad28060f..b3956da1cb865 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -192,15 +192,15 @@ func (u *User) SetLastLogin() { } // UpdateUserDiffViewStyle updates the users diff view style -func UpdateUserDiffViewStyle(u *User, style string) error { +func UpdateUserDiffViewStyle(ctx context.Context, u *User, style string) error { u.DiffViewStyle = style - return UpdateUserCols(db.DefaultContext, u, "diff_view_style") + return UpdateUserCols(ctx, u, "diff_view_style") } // UpdateUserTheme updates a users' theme irrespective of the site wide theme -func UpdateUserTheme(u *User, themeName string) error { +func UpdateUserTheme(ctx context.Context, u *User, themeName string) error { u.Theme = themeName - return UpdateUserCols(db.DefaultContext, u, "theme") + return UpdateUserCols(ctx, u, "theme") } // GetPlaceholderEmail returns an noreply email @@ -218,9 +218,9 @@ func (u *User) GetEmail() string { } // GetAllUsers returns a slice of all individual users found in DB. -func GetAllUsers() ([]*User, error) { +func GetAllUsers(ctx context.Context) ([]*User, error) { users := make([]*User, 0) - return users, db.GetEngine(db.DefaultContext).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users) + return users, db.GetEngine(ctx).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users) } // IsLocal returns true if user login type is LoginPlain. @@ -478,9 +478,9 @@ func (u *User) EmailNotifications() string { } // SetEmailNotifications sets the user's email notification preference -func SetEmailNotifications(u *User, set string) error { +func SetEmailNotifications(ctx context.Context, u *User, set string) error { u.EmailNotificationsPreference = set - if err := UpdateUserCols(db.DefaultContext, u, "email_notifications_preference"); err != nil { + if err := UpdateUserCols(ctx, u, "email_notifications_preference"); err != nil { log.Error("SetEmailNotifications: %v", err) return err } @@ -582,7 +582,7 @@ type CreateUserOverwriteOptions struct { } // CreateUser creates record of a new user. -func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) { +func CreateUser(ctx context.Context, u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) { if err = IsUsableUsername(u.Name); err != nil { return err } @@ -640,7 +640,7 @@ func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err e return err } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -711,8 +711,8 @@ type CountUserFilter struct { } // CountUsers returns number of users. -func CountUsers(opts *CountUserFilter) int64 { - return countUsers(db.DefaultContext, opts) +func CountUsers(ctx context.Context, opts *CountUserFilter) int64 { + return countUsers(ctx, opts) } func countUsers(ctx context.Context, opts *CountUserFilter) int64 { @@ -727,7 +727,7 @@ func countUsers(ctx context.Context, opts *CountUserFilter) int64 { } // GetVerifyUser get user by verify code -func GetVerifyUser(code string) (user *User) { +func GetVerifyUser(ctx context.Context, code string) (user *User) { if len(code) <= base.TimeLimitCodeLength { return nil } @@ -735,7 +735,7 @@ func GetVerifyUser(code string) (user *User) { // use tail hex username query user hexStr := code[base.TimeLimitCodeLength:] if b, err := hex.DecodeString(hexStr); err == nil { - if user, err = GetUserByName(db.DefaultContext, string(b)); user != nil { + if user, err = GetUserByName(ctx, string(b)); user != nil { return user } log.Error("user.getVerifyUser: %v", err) @@ -745,10 +745,10 @@ func GetVerifyUser(code string) (user *User) { } // VerifyUserActiveCode verifies active code when active account -func VerifyUserActiveCode(code string) (user *User) { +func VerifyUserActiveCode(ctx context.Context, code string) (user *User) { minutes := setting.Service.ActiveCodeLives - if user = GetVerifyUser(code); user != nil { + if user = GetVerifyUser(ctx, code); user != nil { // time limit code prefix := code[:base.TimeLimitCodeLength] data := fmt.Sprintf("%d%s%s%s%s", user.ID, user.Email, user.LowerName, user.Passwd, user.Rands) @@ -872,8 +872,8 @@ func UpdateUserCols(ctx context.Context, u *User, cols ...string) error { } // UpdateUserSetting updates user's settings. -func UpdateUserSetting(u *User) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func UpdateUserSetting(ctx context.Context, u *User) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -1021,9 +1021,9 @@ func GetMaileableUsersByIDs(ctx context.Context, ids []int64, isMention bool) ([ } // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids. -func GetUserNamesByIDs(ids []int64) ([]string, error) { +func GetUserNamesByIDs(ctx context.Context, ids []int64) ([]string, error) { unames := make([]string, 0, len(ids)) - err := db.GetEngine(db.DefaultContext).In("id", ids). + err := db.GetEngine(ctx).In("id", ids). Table("user"). Asc("name"). Cols("name"). @@ -1062,9 +1062,9 @@ func GetUserIDsByNames(ctx context.Context, names []string, ignoreNonExistent bo } // GetUsersBySource returns a list of Users for a login source -func GetUsersBySource(s *auth.Source) ([]*User, error) { +func GetUsersBySource(ctx context.Context, s *auth.Source) ([]*User, error) { var users []*User - err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users) + err := db.GetEngine(ctx).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users) return users, err } @@ -1145,12 +1145,12 @@ func GetUserByEmail(ctx context.Context, email string) (*User, error) { } // GetUser checks if a user already exists -func GetUser(user *User) (bool, error) { - return db.GetEngine(db.DefaultContext).Get(user) +func GetUser(ctx context.Context, user *User) (bool, error) { + return db.GetEngine(ctx).Get(user) } // GetUserByOpenID returns the user object by given OpenID if exists. -func GetUserByOpenID(uri string) (*User, error) { +func GetUserByOpenID(ctx context.Context, uri string) (*User, error) { if len(uri) == 0 { return nil, ErrUserNotExist{0, uri, 0} } @@ -1164,12 +1164,12 @@ func GetUserByOpenID(uri string) (*User, error) { // Otherwise, check in openid table oid := &UserOpenID{} - has, err := db.GetEngine(db.DefaultContext).Where("uri=?", uri).Get(oid) + has, err := db.GetEngine(ctx).Where("uri=?", uri).Get(oid) if err != nil { return nil, err } if has { - return GetUserByID(db.DefaultContext, oid.UID) + return GetUserByID(ctx, oid.UID) } return nil, ErrUserNotExist{0, uri, 0} @@ -1279,13 +1279,13 @@ func IsUserVisibleToViewer(ctx context.Context, u, viewer *User) bool { } // CountWrongUserType count OrgUser who have wrong type -func CountWrongUserType() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User)) +func CountWrongUserType(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User)) } // FixWrongUserType fix OrgUser who have wrong type -func FixWrongUserType() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1}) +func FixWrongUserType(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1}) } func GetOrderByName() string { diff --git a/models/user/user_test.go b/models/user/user_test.go index 032dcba676e3c..b15f0cbc59bdc 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -63,7 +63,7 @@ func TestCanCreateOrganization(t *testing.T) { func TestSearchUsers(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(opts *user_model.SearchUserOptions, expectedUserOrOrgIDs []int64) { - users, _, err := user_model.SearchUsers(opts) + users, _, err := user_model.SearchUsers(db.DefaultContext, opts) assert.NoError(t, err) cassText := fmt.Sprintf("ids: %v, opts: %v", expectedUserOrOrgIDs, opts) if assert.Len(t, users, len(expectedUserOrOrgIDs), "case: %s", cassText) { @@ -150,16 +150,16 @@ func TestEmailNotificationPreferences(t *testing.T) { assert.Equal(t, test.expected, user.EmailNotifications()) // Try all possible settings - assert.NoError(t, user_model.SetEmailNotifications(user, user_model.EmailNotificationsEnabled)) + assert.NoError(t, user_model.SetEmailNotifications(db.DefaultContext, user, user_model.EmailNotificationsEnabled)) assert.Equal(t, user_model.EmailNotificationsEnabled, user.EmailNotifications()) - assert.NoError(t, user_model.SetEmailNotifications(user, user_model.EmailNotificationsOnMention)) + assert.NoError(t, user_model.SetEmailNotifications(db.DefaultContext, user, user_model.EmailNotificationsOnMention)) assert.Equal(t, user_model.EmailNotificationsOnMention, user.EmailNotifications()) - assert.NoError(t, user_model.SetEmailNotifications(user, user_model.EmailNotificationsDisabled)) + assert.NoError(t, user_model.SetEmailNotifications(db.DefaultContext, user, user_model.EmailNotificationsDisabled)) assert.Equal(t, user_model.EmailNotificationsDisabled, user.EmailNotifications()) - assert.NoError(t, user_model.SetEmailNotifications(user, user_model.EmailNotificationsAndYourOwn)) + assert.NoError(t, user_model.SetEmailNotifications(db.DefaultContext, user, user_model.EmailNotificationsAndYourOwn)) assert.Equal(t, user_model.EmailNotificationsAndYourOwn, user.EmailNotifications()) } } @@ -239,7 +239,7 @@ func TestCreateUserInvalidEmail(t *testing.T) { MustChangePassword: false, } - err := user_model.CreateUser(user) + err := user_model.CreateUser(db.DefaultContext, user) assert.Error(t, err) assert.True(t, user_model.IsErrEmailCharIsNotSupported(err)) } @@ -253,7 +253,7 @@ func TestCreateUserEmailAlreadyUsed(t *testing.T) { user.Name = "testuser" user.LowerName = strings.ToLower(user.Name) user.ID = 0 - err := user_model.CreateUser(user) + err := user_model.CreateUser(db.DefaultContext, user) assert.Error(t, err) assert.True(t, user_model.IsErrEmailAlreadyUsed(err)) } @@ -270,7 +270,7 @@ func TestCreateUserCustomTimestamps(t *testing.T) { user.ID = 0 user.Email = "unique@example.com" user.CreatedUnix = creationTimestamp - err := user_model.CreateUser(user) + err := user_model.CreateUser(db.DefaultContext, user) assert.NoError(t, err) fetched, err := user_model.GetUserByID(context.Background(), user.ID) @@ -295,7 +295,7 @@ func TestCreateUserWithoutCustomTimestamps(t *testing.T) { user.Email = "unique@example.com" user.CreatedUnix = 0 user.UpdatedUnix = 0 - err := user_model.CreateUser(user) + err := user_model.CreateUser(db.DefaultContext, user) assert.NoError(t, err) timestampEnd := time.Now().Unix() @@ -429,17 +429,17 @@ func TestNewUserRedirect3(t *testing.T) { func TestGetUserByOpenID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - _, err := user_model.GetUserByOpenID("https://unknown") + _, err := user_model.GetUserByOpenID(db.DefaultContext, "https://unknown") if assert.Error(t, err) { assert.True(t, user_model.IsErrUserNotExist(err)) } - user, err := user_model.GetUserByOpenID("https://user1.domain1.tld") + user, err := user_model.GetUserByOpenID(db.DefaultContext, "https://user1.domain1.tld") if assert.NoError(t, err) { assert.Equal(t, int64(1), user.ID) } - user, err = user_model.GetUserByOpenID("https://domain1.tld/user2/") + user, err = user_model.GetUserByOpenID(db.DefaultContext, "https://domain1.tld/user2/") if assert.NoError(t, err) { assert.Equal(t, int64(2), user.ID) } diff --git a/modules/context/repo.go b/modules/context/repo.go index 8a16d311b1406..126196b0d3754 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -561,7 +561,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(unit_model.TypeIssues) ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(unit_model.TypePullRequests) - canSignedUserFork, err := repo_module.CanUserForkRepo(ctx.Doer, ctx.Repo.Repository) + canSignedUserFork, err := repo_module.CanUserForkRepo(ctx, ctx.Doer, ctx.Repo.Repository) if err != nil { ctx.ServerError("CanUserForkRepo", err) return nil @@ -703,7 +703,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { // People who have push access or have forked repository can propose a new pull request. canPush := ctx.Repo.CanWrite(unit_model.TypeCode) || - (ctx.IsSigned && repo_model.HasForkedRepo(ctx.Doer.ID, ctx.Repo.Repository.ID)) + (ctx.IsSigned && repo_model.HasForkedRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID)) canCompare := false // Pull request is allowed if this is a fork repository diff --git a/modules/doctor/fix8312.go b/modules/doctor/fix8312.go index 8de3113663b9f..4fc049873adb7 100644 --- a/modules/doctor/fix8312.go +++ b/modules/doctor/fix8312.go @@ -29,7 +29,7 @@ func fixOwnerTeamCreateOrgRepo(ctx context.Context, logger log.Logger, autofix b return nil } - return models.UpdateTeam(team, false, false) + return models.UpdateTeam(ctx, team, false, false) }, ) if err != nil { diff --git a/modules/doctor/usertype.go b/modules/doctor/usertype.go index 550e536cbd803..ab32b78e62fbc 100644 --- a/modules/doctor/usertype.go +++ b/modules/doctor/usertype.go @@ -11,14 +11,14 @@ import ( ) func checkUserType(ctx context.Context, logger log.Logger, autofix bool) error { - count, err := user_model.CountWrongUserType() + count, err := user_model.CountWrongUserType(ctx) if err != nil { logger.Critical("Error: %v whilst counting wrong user types") return err } if count > 0 { if autofix { - if count, err = user_model.FixWrongUserType(); err != nil { + if count, err = user_model.FixWrongUserType(ctx); err != nil { logger.Critical("Error: %v whilst fixing wrong user types") return err } diff --git a/modules/metrics/collector.go b/modules/metrics/collector.go index 33678256c3cb3..1bf8f58b93a66 100755 --- a/modules/metrics/collector.go +++ b/modules/metrics/collector.go @@ -7,6 +7,7 @@ import ( "runtime" activities_model "code.gitea.io/gitea/models/activities" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/setting" "github.com/prometheus/client_golang/prometheus" @@ -232,7 +233,7 @@ func (c Collector) Describe(ch chan<- *prometheus.Desc) { // Collect returns the metrics with values func (c Collector) Collect(ch chan<- prometheus.Metric) { - stats := activities_model.GetStatistic() + stats := activities_model.GetStatistic(db.DefaultContext) ch <- prometheus.MustNewConstMetric( c.Accesses, diff --git a/modules/repository/fork.go b/modules/repository/fork.go index 8e9f3a8976f65..fbf00087167c7 100644 --- a/modules/repository/fork.go +++ b/modules/repository/fork.go @@ -4,25 +4,27 @@ package repository import ( + "context" + "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" ) // CanUserForkRepo returns true if specified user can fork repository. -func CanUserForkRepo(user *user_model.User, repo *repo_model.Repository) (bool, error) { +func CanUserForkRepo(ctx context.Context, user *user_model.User, repo *repo_model.Repository) (bool, error) { if user == nil { return false, nil } - if repo.OwnerID != user.ID && !repo_model.HasForkedRepo(user.ID, repo.ID) { + if repo.OwnerID != user.ID && !repo_model.HasForkedRepo(ctx, user.ID, repo.ID) { return true, nil } - ownedOrgs, err := organization.GetOrgsCanCreateRepoByUserID(user.ID) + ownedOrgs, err := organization.GetOrgsCanCreateRepoByUserID(ctx, user.ID) if err != nil { return false, err } for _, org := range ownedOrgs { - if repo.OwnerID != org.ID && !repo_model.HasForkedRepo(org.ID, repo.ID) { + if repo.OwnerID != org.ID && !repo_model.HasForkedRepo(ctx, org.ID, repo.ID) { return true, nil } } diff --git a/routers/api/v1/admin/email.go b/routers/api/v1/admin/email.go index 8d0491e07024b..5914215bc2a12 100644 --- a/routers/api/v1/admin/email.go +++ b/routers/api/v1/admin/email.go @@ -37,7 +37,7 @@ func GetAllEmails(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - emails, maxResults, err := user_model.SearchEmails(&user_model.SearchEmailOptions{ + emails, maxResults, err := user_model.SearchEmails(ctx, &user_model.SearchEmailOptions{ Keyword: ctx.Params(":email"), ListOptions: listOptions, }) diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index 6d50a12674a33..65620459b7a8a 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -101,7 +101,7 @@ func GetAllOrgs(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{ + users, maxResults, err := user_model.SearchUsers(ctx, &user_model.SearchUserOptions{ Actor: ctx.Doer, Type: user_model.UserTypeOrganization, OrderBy: db.SearchOrderByAlphabetically, diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 4f1e9a3f5373a..66946e5797a74 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -128,7 +128,7 @@ func CreateUser(ctx *context.APIContext) { u.UpdatedUnix = u.CreatedUnix } - if err := user_model.CreateUser(u, overwriteDefault); err != nil { + if err := user_model.CreateUser(ctx, u, overwriteDefault); err != nil { if user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err) || db.IsErrNameReserved(err) || @@ -450,7 +450,7 @@ func SearchUsers(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{ + users, maxResults, err := user_model.SearchUsers(ctx, &user_model.SearchUserOptions{ Actor: ctx.Doer, Type: user_model.UserTypeIndividual, LoginName: ctx.FormTrim("login_name"), diff --git a/routers/api/v1/misc/nodeinfo.go b/routers/api/v1/misc/nodeinfo.go index 319c3483e10c9..22004a8a88445 100644 --- a/routers/api/v1/misc/nodeinfo.go +++ b/routers/api/v1/misc/nodeinfo.go @@ -34,12 +34,12 @@ func NodeInfo(ctx *context.APIContext) { nodeInfoUsage, cached = ctx.Cache.Get(cacheKeyNodeInfoUsage).(structs.NodeInfoUsage) } if !cached { - usersTotal := int(user_model.CountUsers(nil)) + usersTotal := int(user_model.CountUsers(ctx, nil)) now := time.Now() timeOneMonthAgo := now.AddDate(0, -1, 0).Unix() timeHaveYearAgo := now.AddDate(0, -6, 0).Unix() - usersActiveMonth := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeOneMonthAgo})) - usersActiveHalfyear := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeHaveYearAgo})) + usersActiveMonth := int(user_model.CountUsers(ctx, &user_model.CountUserFilter{LastLoginSince: &timeOneMonthAgo})) + usersActiveHalfyear := int(user_model.CountUsers(ctx, &user_model.CountUserFilter{LastLoginSince: &timeHaveYearAgo})) allIssues, _ := issues_model.CountIssues(ctx, &issues_model.IssuesOptions{}) allComments, _ := issues_model.CountComments(&issues_model.FindCommentsOptions{}) diff --git a/routers/api/v1/org/member.go b/routers/api/v1/org/member.go index e5ea584d5d716..67956e66bd2be 100644 --- a/routers/api/v1/org/member.go +++ b/routers/api/v1/org/member.go @@ -31,7 +31,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) { return } - members, _, err := organization.FindOrgMembers(opts) + members, _, err := organization.FindOrgMembers(ctx, opts) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index 0216b62352010..c5f531923b6f1 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -203,7 +203,7 @@ func GetAll(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - publicOrgs, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{ + publicOrgs, maxResults, err := user_model.SearchUsers(ctx, &user_model.SearchUserOptions{ Actor: ctx.Doer, ListOptions: listOptions, Type: user_model.UserTypeOrganization, diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index abb5381a70df7..944fd763ca2c1 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -239,7 +239,7 @@ func CreateTeam(ctx *context.APIContext) { attachAdminTeamUnits(team) } - if err := models.NewTeam(team); err != nil { + if err := models.NewTeam(ctx, team); err != nil { if organization.IsErrTeamAlreadyExist(err) { ctx.Error(http.StatusUnprocessableEntity, "", err) } else { @@ -330,7 +330,7 @@ func EditTeam(ctx *context.APIContext) { attachAdminTeamUnits(team) } - if err := models.UpdateTeam(team, isAuthChanged, isIncludeAllChanged); err != nil { + if err := models.UpdateTeam(ctx, team, isAuthChanged, isIncludeAllChanged); err != nil { ctx.Error(http.StatusInternalServerError, "EditTeam", err) return } @@ -361,7 +361,7 @@ func DeleteTeam(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - if err := models.DeleteTeam(ctx.Org.Team); err != nil { + if err := models.DeleteTeam(ctx, ctx.Org.Team); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteTeam", err) return } @@ -493,7 +493,7 @@ func AddTeamMember(ctx *context.APIContext) { if ctx.Written() { return } - if err := models.AddTeamMember(ctx.Org.Team, u.ID); err != nil { + if err := models.AddTeamMember(ctx, ctx.Org.Team, u.ID); err != nil { ctx.Error(http.StatusInternalServerError, "AddMember", err) return } @@ -530,7 +530,7 @@ func RemoveTeamMember(ctx *context.APIContext) { return } - if err := models.RemoveTeamMember(ctx.Org.Team, u.ID); err != nil { + if err := models.RemoveTeamMember(ctx, ctx.Org.Team, u.ID); err != nil { ctx.Error(http.StatusInternalServerError, "RemoveTeamMember", err) return } diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index cdc176b8e4573..c851525c0f023 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -447,7 +447,7 @@ func GetBranchProtection(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToBranchProtection(bp)) + ctx.JSON(http.StatusOK, convert.ToBranchProtection(ctx, bp)) } // ListBranchProtections list branch protections for a repo @@ -480,7 +480,7 @@ func ListBranchProtections(ctx *context.APIContext) { } apiBps := make([]*api.BranchProtection, len(bps)) for i := range bps { - apiBps[i] = convert.ToBranchProtection(bps[i]) + apiBps[i] = convert.ToBranchProtection(ctx, bps[i]) } ctx.JSON(http.StatusOK, apiBps) @@ -688,7 +688,7 @@ func CreateBranchProtection(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToBranchProtection(bp)) + ctx.JSON(http.StatusCreated, convert.ToBranchProtection(ctx, bp)) } // EditBranchProtection edits a branch protection for a repo @@ -960,7 +960,7 @@ func EditBranchProtection(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToBranchProtection(bp)) + ctx.JSON(http.StatusOK, convert.ToBranchProtection(ctx, bp)) } // DeleteBranchProtection deletes a branch protection for a repo diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index 7ae4356204389..ef152eef85913 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -55,7 +55,7 @@ func ListForks(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - forks, err := repo_model.GetForks(ctx.Repo.Repository, utils.GetListOptions(ctx)) + forks, err := repo_model.GetForks(ctx, ctx.Repo.Repository, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetForks", err) return diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 5a05471264653..1fec0294658d9 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -273,7 +273,7 @@ func GetIssueSubscribers(ctx *context.APIContext) { userIDs = append(userIDs, iw.UserID) } - users, err := user_model.GetUsersByIDs(userIDs) + users, err := user_model.GetUsersByIDs(ctx, userIDs) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUsersByIDs", err) return diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 01ce754c74a8b..0fe657d245271 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -985,7 +985,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) } // Check if current user has fork of repository or in the same repository. - headRepo := repo_model.GetForkedRepo(headUser.ID, baseRepo.ID) + headRepo := repo_model.GetForkedRepo(ctx, headUser.ID, baseRepo.ID) if headRepo == nil && !isSameRepo { log.Trace("parseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID) ctx.NotFound("GetForkedRepo") diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index fc74c8d148460..68f6c974a59c9 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -27,7 +27,7 @@ func ListEmails(ctx *context.APIContext) { // "200": // "$ref": "#/responses/EmailList" - emails, err := user_model.GetEmailAddresses(ctx.Doer.ID) + emails, err := user_model.GetEmailAddresses(ctx, ctx.Doer.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetEmailAddresses", err) return @@ -71,7 +71,7 @@ func AddEmail(ctx *context.APIContext) { } } - if err := user_model.AddEmailAddresses(emails); err != nil { + if err := user_model.AddEmailAddresses(ctx, emails); err != nil { if user_model.IsErrEmailAlreadyUsed(err) { ctx.Error(http.StatusUnprocessableEntity, "", "Email address has been used: "+err.(user_model.ErrEmailAlreadyUsed).Email) } else if user_model.IsErrEmailCharIsNotSupported(err) || user_model.IsErrEmailInvalid(err) { @@ -129,7 +129,7 @@ func DeleteEmail(ctx *context.APIContext) { } } - if err := user_model.DeleteEmailAddresses(emails); err != nil { + if err := user_model.DeleteEmailAddresses(ctx, emails); err != nil { if user_model.IsErrEmailAddressNotExist(err) { ctx.Error(http.StatusNotFound, "DeleteEmailAddresses", err) return diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 2a2361be678bf..251e7a601391b 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -54,7 +54,7 @@ func Search(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{ + users, maxResults, err := user_model.SearchUsers(ctx, &user_model.SearchUserOptions{ Actor: ctx.Doer, Keyword: ctx.FormTrim("q"), UID: ctx.FormInt64("uid"), diff --git a/routers/install/install.go b/routers/install/install.go index 6d60dfdca3963..3eb16b9ce8555 100644 --- a/routers/install/install.go +++ b/routers/install/install.go @@ -536,7 +536,7 @@ func SubmitInstall(ctx *context.Context) { IsActive: util.OptionalBoolTrue, } - if err = user_model.CreateUser(u, overwriteDefault); err != nil { + if err = user_model.CreateUser(ctx, u, overwriteDefault); err != nil { if !user_model.IsErrUserAlreadyExist(err) { setting.InstallLock = false ctx.Data["Err_AdminName"] = true diff --git a/routers/private/default_branch.go b/routers/private/default_branch.go index b15d6ba33a4b7..a23e101e9d1ed 100644 --- a/routers/private/default_branch.go +++ b/routers/private/default_branch.go @@ -29,7 +29,7 @@ func SetDefaultBranch(ctx *gitea_context.PrivateContext) { } } - if err := repo_model.UpdateDefaultBranch(ctx.Repo.Repository); err != nil { + if err := repo_model.UpdateDefaultBranch(ctx, ctx.Repo.Repository); err != nil { ctx.JSON(http.StatusInternalServerError, private.Response{ Err: fmt.Sprintf("Unable to set default branch on repository: %s/%s Error: %v", ownerName, repoName, err), }) diff --git a/routers/web/admin/admin.go b/routers/web/admin/admin.go index fe3e1d2206a07..e34124049e79e 100644 --- a/routers/web/admin/admin.go +++ b/routers/web/admin/admin.go @@ -182,7 +182,7 @@ func CronTasks(ctx *context.Context) { func MonitorStats(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("admin.monitor.stats") ctx.Data["PageIsAdminMonitorStats"] = true - bs, err := json.Marshal(activities_model.GetStatistic().Counter) + bs, err := json.Marshal(activities_model.GetStatistic(ctx).Counter) if err != nil { ctx.ServerError("MonitorStats", err) return diff --git a/routers/web/admin/emails.go b/routers/web/admin/emails.go index 4618a78c3a7c8..59f80035d89b6 100644 --- a/routers/web/admin/emails.go +++ b/routers/web/admin/emails.go @@ -75,7 +75,7 @@ func Emails(ctx *context.Context) { } if len(opts.Keyword) == 0 || isKeywordValid(opts.Keyword) { - baseEmails, count, err = user_model.SearchEmails(opts) + baseEmails, count, err = user_model.SearchEmails(ctx, opts) if err != nil { ctx.ServerError("SearchEmails", err) return @@ -121,7 +121,7 @@ func ActivateEmail(ctx *context.Context) { log.Info("Changing activation for User ID: %d, email: %s, primary: %v to %v", uid, email, primary, activate) - if err := user_model.ActivateUserEmail(uid, email, activate); err != nil { + if err := user_model.ActivateUserEmail(ctx, uid, email, activate); err != nil { log.Error("ActivateUserEmail(%v,%v,%v): %v", uid, email, activate, err) if user_model.IsErrEmailAlreadyUsed(err) { ctx.Flash.Error(ctx.Tr("admin.emails.duplicate_active")) diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 03ffaf5f3f80f..0414a60e18013 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -170,7 +170,7 @@ func NewUserPost(ctx *context.Context) { u.MustChangePassword = form.MustChangePassword } - if err := user_model.CreateUser(u, overwriteDefault); err != nil { + if err := user_model.CreateUser(ctx, u, overwriteDefault); err != nil { switch { case user_model.IsErrUserAlreadyExist(err): ctx.Data["Err_UserName"] = true @@ -282,7 +282,7 @@ func ViewUser(ctx *context.Context) { ctx.Data["Repos"] = repos ctx.Data["ReposTotal"] = int(count) - emails, err := user_model.GetEmailAddresses(u.ID) + emails, err := user_model.GetEmailAddresses(ctx, u.ID) if err != nil { ctx.ServerError("GetEmailAddresses", err) return diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index dac8eb7afbb43..f8549f68f614a 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -199,7 +199,7 @@ func SignInPost(ctx *context.Context) { } } - u, source, err := auth_service.UserSignIn(form.UserName, form.Password) + u, source, err := auth_service.UserSignIn(ctx, form.UserName, form.Password) if err != nil { if errors.Is(err, util.ErrNotExist) || errors.Is(err, util.ErrInvalidArgument) { ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form) @@ -509,15 +509,15 @@ func createAndHandleCreatedUser(ctx *context.Context, tpl base.TplName, form any // createUserInContext creates a user and handles errors within a given context. // Optionally a template can be specified. func createUserInContext(ctx *context.Context, tpl base.TplName, form any, u *user_model.User, overwrites *user_model.CreateUserOverwriteOptions, gothUser *goth.User, allowLink bool) (ok bool) { - if err := user_model.CreateUser(u, overwrites); err != nil { + if err := user_model.CreateUser(ctx, u, overwrites); err != nil { if allowLink && (user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err)) { if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingAuto { var user *user_model.User user = &user_model.User{Name: u.Name} - hasUser, err := user_model.GetUser(user) + hasUser, err := user_model.GetUser(ctx, user) if !hasUser || err != nil { user = &user_model.User{Email: u.Email} - hasUser, err = user_model.GetUser(user) + hasUser, err = user_model.GetUser(ctx, user) if !hasUser || err != nil { ctx.ServerError("UserLinkAccount", err) return false @@ -576,7 +576,7 @@ func createUserInContext(ctx *context.Context, tpl base.TplName, form any, u *us // sends a confirmation email if required. func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.User) (ok bool) { // Auto-set admin for the only user. - if user_model.CountUsers(nil) == 1 { + if user_model.CountUsers(ctx, nil) == 1 { u.IsAdmin = true u.IsActive = true u.SetLastLogin() @@ -652,7 +652,7 @@ func Activate(ctx *context.Context) { return } - user := user_model.VerifyUserActiveCode(code) + user := user_model.VerifyUserActiveCode(ctx, code) // if code is wrong if user == nil { ctx.Data["IsCodeInvalid"] = true @@ -679,7 +679,7 @@ func ActivatePost(ctx *context.Context) { return } - user := user_model.VerifyUserActiveCode(code) + user := user_model.VerifyUserActiveCode(ctx, code) // if code is wrong if user == nil { ctx.Data["IsCodeInvalid"] = true @@ -722,7 +722,7 @@ func handleAccountActivation(ctx *context.Context, user *user_model.User) { return } - if err := user_model.ActivateUserEmail(user.ID, user.Email, true); err != nil { + if err := user_model.ActivateUserEmail(ctx, user.ID, user.Email, true); err != nil { log.Error("Unable to activate email for user: %-v with email: %s: %v", user, user.Email, err) ctx.ServerError("ActivateUserEmail", err) return @@ -767,8 +767,8 @@ func ActivateEmail(ctx *context.Context) { emailStr := ctx.FormString("email") // Verify code. - if email := user_model.VerifyActiveEmailCode(code, emailStr); email != nil { - if err := user_model.ActivateEmail(email); err != nil { + if email := user_model.VerifyActiveEmailCode(ctx, code, emailStr); email != nil { + if err := user_model.ActivateEmail(ctx, email); err != nil { ctx.ServerError("ActivateEmail", err) } diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index 0f7ecf1af49ae..e6791cafcee82 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -142,7 +142,7 @@ func LinkAccountPostSignIn(ctx *context.Context) { return } - u, _, err := auth_service.UserSignIn(signInForm.UserName, signInForm.Password) + u, _, err := auth_service.UserSignIn(ctx, signInForm.UserName, signInForm.Password) if err != nil { handleSignInError(ctx, signInForm.UserName, &signInForm, tplLinkAccount, "UserLinkAccount", err) return diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 78dc84472a129..178ae8436633c 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -859,7 +859,7 @@ func SignInOAuth(ctx *context.Context) { } // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user - user, gothUser, err := oAuth2UserLoginCallback(authSource, ctx.Req, ctx.Resp) + user, gothUser, err := oAuth2UserLoginCallback(ctx, authSource, ctx.Req, ctx.Resp) if err == nil && user != nil { // we got the user without going through the whole OAuth2 authentication flow again handleOAuth2SignIn(ctx, authSource, user, gothUser) @@ -909,7 +909,7 @@ func SignInOAuthCallback(ctx *context.Context) { return } - u, gothUser, err := oAuth2UserLoginCallback(authSource, ctx.Req, ctx.Resp) + u, gothUser, err := oAuth2UserLoginCallback(ctx, authSource, ctx.Req, ctx.Resp) if err != nil { if user_model.IsErrUserProhibitLogin(err) { uplerr := err.(user_model.ErrUserProhibitLogin) @@ -1208,7 +1208,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful // login the user -func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, response http.ResponseWriter) (*user_model.User, goth.User, error) { +func oAuth2UserLoginCallback(ctx *context.Context, authSource *auth.Source, request *http.Request, response http.ResponseWriter) (*user_model.User, goth.User, error) { oauth2Source := authSource.Cfg.(*oauth2.Source) // Make sure that the response is not an error response. @@ -1260,7 +1260,7 @@ func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, res LoginSource: authSource.ID, } - hasUser, err := user_model.GetUser(user) + hasUser, err := user_model.GetUser(ctx, user) if err != nil { return nil, goth.User{}, err } diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go index 00fc17f098019..aa07129632590 100644 --- a/routers/web/auth/openid.go +++ b/routers/web/auth/openid.go @@ -157,7 +157,7 @@ func signInOpenIDVerify(ctx *context.Context) { /* Now we should seek for the user and log him in, or prompt * to register if not found */ - u, err := user_model.GetUserByOpenID(id) + u, err := user_model.GetUserByOpenID(ctx, id) if err != nil { if !user_model.IsErrUserNotExist(err) { ctx.RenderWithErr(err.Error(), tplSignInOpenID, &forms.SignInOpenIDForm{ @@ -280,7 +280,7 @@ func ConnectOpenIDPost(ctx *context.Context) { ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp ctx.Data["OpenID"] = oid - u, _, err := auth.UserSignIn(form.UserName, form.Password) + u, _, err := auth.UserSignIn(ctx, form.UserName, form.Password) if err != nil { handleSignInError(ctx, form.UserName, &form, tplConnectOID, "ConnectOpenIDPost", err) return diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index 1432338e70832..970d316300bea 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -114,7 +114,7 @@ func commonResetPassword(ctx *context.Context) (*user_model.User, *auth.TwoFacto } // Fail early, don't frustrate the user - u := user_model.VerifyUserActiveCode(code) + u := user_model.VerifyUserActiveCode(ctx, code) if u == nil { ctx.Flash.Error(ctx.Tr("auth.invalid_code_forgot_password", fmt.Sprintf("%s/user/forgot_password", setting.AppSubURL)), true) return nil, nil diff --git a/routers/web/explore/user.go b/routers/web/explore/user.go index a2b5f80099429..c760004088ea3 100644 --- a/routers/web/explore/user.go +++ b/routers/web/explore/user.go @@ -87,7 +87,7 @@ func RenderUserSearch(ctx *context.Context, opts *user_model.SearchUserOptions, opts.Keyword = ctx.FormTrim("q") opts.OrderBy = orderBy if len(opts.Keyword) == 0 || isKeywordValid(opts.Keyword) { - users, count, err = user_model.SearchUsers(opts) + users, count, err = user_model.SearchUsers(ctx, opts) if err != nil { ctx.ServerError("SearchUsers", err) return @@ -108,7 +108,7 @@ func RenderUserSearch(ctx *context.Context, opts *user_model.SearchUserOptions, ctx.Data["Keyword"] = opts.Keyword ctx.Data["Total"] = count ctx.Data["Users"] = users - ctx.Data["UsersTwoFaStatus"] = user_model.UserList(users).GetTwoFaStatus() + ctx.Data["UsersTwoFaStatus"] = user_model.UserList(users).GetTwoFaStatus(ctx) ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled diff --git a/routers/web/home.go b/routers/web/home.go index b94e3e9eb593d..ab3fbde2c9a80 100644 --- a/routers/web/home.go +++ b/routers/web/home.go @@ -69,7 +69,7 @@ func Home(ctx *context.Context) { func HomeSitemap(ctx *context.Context) { m := sitemap.NewSitemapIndex() if !setting.Service.Explore.DisableUsersPage { - _, cnt, err := user_model.SearchUsers(&user_model.SearchUserOptions{ + _, cnt, err := user_model.SearchUsers(ctx, &user_model.SearchUserOptions{ Type: user_model.UserTypeIndividual, ListOptions: db.ListOptions{PageSize: 1}, IsActive: util.OptionalBoolTrue, diff --git a/routers/web/org/home.go b/routers/web/org/home.go index a69fdedba4608..15386393e9f1e 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -123,7 +123,7 @@ func Home(ctx *context.Context) { PublicOnly: ctx.Org.PublicMemberOnly, ListOptions: db.ListOptions{Page: 1, PageSize: 25}, } - members, _, err := organization.FindOrgMembers(opts) + members, _, err := organization.FindOrgMembers(ctx, opts) if err != nil { ctx.ServerError("FindOrgMembers", err) return diff --git a/routers/web/org/members.go b/routers/web/org/members.go index f963ad55efd37..34cff05ea0b92 100644 --- a/routers/web/org/members.go +++ b/routers/web/org/members.go @@ -62,7 +62,7 @@ func Members(ctx *context.Context) { pager := context.NewPagination(int(total), setting.UI.MembersPagingNum, page, 5) opts.ListOptions.Page = page opts.ListOptions.PageSize = setting.UI.MembersPagingNum - members, membersIsPublic, err := organization.FindOrgMembers(opts) + members, membersIsPublic, err := organization.FindOrgMembers(ctx, opts) if err != nil { ctx.ServerError("GetMembers", err) return @@ -71,7 +71,7 @@ func Members(ctx *context.Context) { ctx.Data["Members"] = members ctx.Data["MembersIsPublicMember"] = membersIsPublic ctx.Data["MembersIsUserOrgOwner"] = organization.IsUserOrgOwner(members, org.ID) - ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus() + ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus(ctx) ctx.HTML(http.StatusOK, tplMembers) } diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index 2fd2a681af47e..46ca68b61258e 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -78,9 +78,9 @@ func TeamsAction(ctx *context.Context) { ctx.Error(http.StatusNotFound) return } - err = models.AddTeamMember(ctx.Org.Team, ctx.Doer.ID) + err = models.AddTeamMember(ctx, ctx.Org.Team, ctx.Doer.ID) case "leave": - err = models.RemoveTeamMember(ctx.Org.Team, ctx.Doer.ID) + err = models.RemoveTeamMember(ctx, ctx.Org.Team, ctx.Doer.ID) if err != nil { if org_model.IsErrLastOrgOwner(err) { ctx.Flash.Error(ctx.Tr("form.last_org_owner")) @@ -107,7 +107,7 @@ func TeamsAction(ctx *context.Context) { return } - err = models.RemoveTeamMember(ctx.Org.Team, uid) + err = models.RemoveTeamMember(ctx, ctx.Org.Team, uid) if err != nil { if org_model.IsErrLastOrgOwner(err) { ctx.Flash.Error(ctx.Tr("form.last_org_owner")) @@ -162,7 +162,7 @@ func TeamsAction(ctx *context.Context) { if ctx.Org.Team.IsMember(u.ID) { ctx.Flash.Error(ctx.Tr("org.teams.add_duplicate_users")) } else { - err = models.AddTeamMember(ctx.Org.Team, u.ID) + err = models.AddTeamMember(ctx, ctx.Org.Team, u.ID) } page = "team" @@ -251,9 +251,9 @@ func TeamsRepoAction(ctx *context.Context) { case "remove": err = repo_service.RemoveRepositoryFromTeam(ctx, ctx.Org.Team, ctx.FormInt64("repoid")) case "addall": - err = models.AddAllRepositories(ctx.Org.Team) + err = models.AddAllRepositories(ctx, ctx.Org.Team) case "removeall": - err = models.RemoveAllRepositories(ctx.Org.Team) + err = models.RemoveAllRepositories(ctx, ctx.Org.Team) } if err != nil { @@ -352,7 +352,7 @@ func NewTeamPost(ctx *context.Context) { return } - if err := models.NewTeam(t); err != nil { + if err := models.NewTeam(ctx, t); err != nil { ctx.Data["Err_TeamName"] = true switch { case org_model.IsErrTeamAlreadyExist(err): @@ -526,7 +526,7 @@ func EditTeamPost(ctx *context.Context) { return } - if err := models.UpdateTeam(t, isAuthChanged, isIncludeAllChanged); err != nil { + if err := models.UpdateTeam(ctx, t, isAuthChanged, isIncludeAllChanged); err != nil { ctx.Data["Err_TeamName"] = true switch { case org_model.IsErrTeamAlreadyExist(err): @@ -541,7 +541,7 @@ func EditTeamPost(ctx *context.Context) { // DeleteTeam response for the delete team request func DeleteTeam(ctx *context.Context) { - if err := models.DeleteTeam(ctx.Org.Team); err != nil { + if err := models.DeleteTeam(ctx, ctx.Org.Team); err != nil { ctx.Flash.Error("DeleteTeam: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("org.teams.delete_team_success")) @@ -583,7 +583,7 @@ func TeamInvitePost(ctx *context.Context) { return } - if err := models.AddTeamMember(team, ctx.Doer.ID); err != nil { + if err := models.AddTeamMember(ctx, team, ctx.Doer.ID); err != nil { ctx.ServerError("AddTeamMember", err) return } diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index d71d555bc2b54..f5831df28f6ad 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -41,7 +41,7 @@ func Branches(ctx *context.Context) { ctx.Data["IsWriter"] = ctx.Repo.CanWrite(unit.TypeCode) ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror ctx.Data["CanPull"] = ctx.Repo.CanWrite(unit.TypeCode) || - (ctx.IsSigned && repo_model.HasForkedRepo(ctx.Doer.ID, ctx.Repo.Repository.ID)) + (ctx.IsSigned && repo_model.HasForkedRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID)) ctx.Data["PageIsViewCode"] = true ctx.Data["PageIsBranches"] = true diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index 7f51cb01f32c7..ecc8e66702b6f 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -357,7 +357,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { // "OwnForkRepo" var ownForkRepo *repo_model.Repository if ctx.Doer != nil && baseRepo.OwnerID != ctx.Doer.ID { - repo := repo_model.GetForkedRepo(ctx.Doer.ID, baseRepo.ID) + repo := repo_model.GetForkedRepo(ctx, ctx.Doer.ID, baseRepo.ID) if repo != nil { ownForkRepo = repo ctx.Data["OwnForkRepo"] = ownForkRepo @@ -381,13 +381,13 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { // 5. If the headOwner has a fork of the baseRepo - use that if !has { - ci.HeadRepo = repo_model.GetForkedRepo(ci.HeadUser.ID, baseRepo.ID) + ci.HeadRepo = repo_model.GetForkedRepo(ctx, ci.HeadUser.ID, baseRepo.ID) has = ci.HeadRepo != nil } // 6. If the baseRepo is a fork and the headUser has a fork of that use that if !has && baseRepo.IsFork { - ci.HeadRepo = repo_model.GetForkedRepo(ci.HeadUser.ID, baseRepo.ForkID) + ci.HeadRepo = repo_model.GetForkedRepo(ctx, ci.HeadUser.ID, baseRepo.ForkID) has = ci.HeadRepo != nil } diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 3796fb7d3e1dc..820c5d723346d 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -130,7 +130,7 @@ func MustAllowPulls(ctx *context.Context) { } // User can send pull request if owns a forked repository. - if ctx.IsSigned && repo_model.HasForkedRepo(ctx.Doer.ID, ctx.Repo.Repository.ID) { + if ctx.IsSigned && repo_model.HasForkedRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID) { ctx.Repo.PullRequest.Allowed = true ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.Doer.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName) } diff --git a/routers/web/repo/middlewares.go b/routers/web/repo/middlewares.go index 216550ca996c6..5efc1a82b3825 100644 --- a/routers/web/repo/middlewares.go +++ b/routers/web/repo/middlewares.go @@ -56,7 +56,7 @@ func SetDiffViewStyle(ctx *context.Context) { } ctx.Data["IsSplitStyle"] = style == "split" - if err := user_model.UpdateUserDiffViewStyle(ctx.Doer, style); err != nil { + if err := user_model.UpdateUserDiffViewStyle(ctx, ctx.Doer, style); err != nil { ctx.ServerError("ErrUpdateDiffViewStyle", err) } } diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 0de3ace792b8e..0ef4a29f0c999 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -128,18 +128,18 @@ func getForkRepository(ctx *context.Context) *repo_model.Repository { ctx.Data["repo_name"] = forkRepo.Name ctx.Data["description"] = forkRepo.Description ctx.Data["IsPrivate"] = forkRepo.IsPrivate || forkRepo.Owner.Visibility == structs.VisibleTypePrivate - canForkToUser := forkRepo.OwnerID != ctx.Doer.ID && !repo_model.HasForkedRepo(ctx.Doer.ID, forkRepo.ID) + canForkToUser := forkRepo.OwnerID != ctx.Doer.ID && !repo_model.HasForkedRepo(ctx, ctx.Doer.ID, forkRepo.ID) ctx.Data["ForkRepo"] = forkRepo - ownedOrgs, err := organization.GetOrgsCanCreateRepoByUserID(ctx.Doer.ID) + ownedOrgs, err := organization.GetOrgsCanCreateRepoByUserID(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetOrgsCanCreateRepoByUserID", err) return nil } var orgs []*organization.Organization for _, org := range ownedOrgs { - if forkRepo.OwnerID != org.ID && !repo_model.HasForkedRepo(org.ID, forkRepo.ID) { + if forkRepo.OwnerID != org.ID && !repo_model.HasForkedRepo(ctx, org.ID, forkRepo.ID) { orgs = append(orgs, org) } } @@ -233,7 +233,7 @@ func ForkPost(ctx *context.Context) { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form) return } - repo := repo_model.GetForkedRepo(ctxUser.ID, traverseParentRepo.ID) + repo := repo_model.GetForkedRepo(ctx, ctxUser.ID, traverseParentRepo.ID) if repo != nil { ctx.Redirect(ctxUser.HomeLink() + "/" + url.PathEscape(repo.Name)) return diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 3ed7ca1c91737..7772799557814 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -80,7 +80,7 @@ func CommitInfoCache(ctx *context.Context) { } func checkContextUser(ctx *context.Context, uid int64) *user_model.User { - orgs, err := organization.GetOrgsCanCreateRepoByUserID(ctx.Doer.ID) + orgs, err := organization.GetOrgsCanCreateRepoByUserID(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetOrgsCanCreateRepoByUserID", err) return nil diff --git a/routers/web/repo/setting/default_branch.go b/routers/web/repo/setting/default_branch.go index f0aa1a89e7e9c..9bf54e706a37e 100644 --- a/routers/web/repo/setting/default_branch.go +++ b/routers/web/repo/setting/default_branch.go @@ -46,7 +46,7 @@ func SetDefaultBranchPost(ctx *context.Context) { return } } - if err := repo_model.UpdateDefaultBranch(repo); err != nil { + if err := repo_model.UpdateDefaultBranch(ctx, repo); err != nil { ctx.ServerError("SetDefaultBranch", err) return } diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index f0fe6140dfb8e..540a82e8650a0 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -1091,7 +1091,7 @@ func Forks(ctx *context.Context) { pager := context.NewPagination(ctx.Repo.Repository.NumForks, setting.ItemsPerPage, page, 5) ctx.Data["Page"] = pager - forks, err := repo_model.GetForks(ctx.Repo.Repository, db.ListOptions{ + forks, err := repo_model.GetForks(ctx, ctx.Repo.Repository, db.ListOptions{ Page: pager.Paginater.Current(), PageSize: setting.ItemsPerPage, }) diff --git a/routers/web/user/search.go b/routers/web/user/search.go index fa2e52dd4194f..4d090a3784cc7 100644 --- a/routers/web/user/search.go +++ b/routers/web/user/search.go @@ -19,7 +19,7 @@ func Search(ctx *context.Context) { PageSize: convert.ToCorrectPageSize(ctx.FormInt("limit")), } - users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{ + users, maxResults, err := user_model.SearchUsers(ctx, &user_model.SearchUserOptions{ Actor: ctx.Doer, Keyword: ctx.FormTrim("q"), UID: ctx.FormInt64("uid"), diff --git a/routers/web/user/setting/account.go b/routers/web/user/setting/account.go index ecb846e91bb38..5c14f3ad4b522 100644 --- a/routers/web/user/setting/account.go +++ b/routers/web/user/setting/account.go @@ -93,7 +93,7 @@ func EmailPost(ctx *context.Context) { // Make emailaddress primary. if ctx.FormString("_method") == "PRIMARY" { - if err := user_model.MakeEmailPrimary(&user_model.EmailAddress{ID: ctx.FormInt64("id")}); err != nil { + if err := user_model.MakeEmailPrimary(ctx, &user_model.EmailAddress{ID: ctx.FormInt64("id")}); err != nil { ctx.ServerError("MakeEmailPrimary", err) return } @@ -112,7 +112,7 @@ func EmailPost(ctx *context.Context) { } id := ctx.FormInt64("id") - email, err := user_model.GetEmailAddressByID(ctx.Doer.ID, id) + email, err := user_model.GetEmailAddressByID(ctx, ctx.Doer.ID, id) if err != nil { log.Error("GetEmailAddressByID(%d,%d) error: %v", ctx.Doer.ID, id, err) ctx.Redirect(setting.AppSubURL + "/user/settings/account") @@ -161,7 +161,7 @@ func EmailPost(ctx *context.Context) { ctx.ServerError("SetEmailPreference", errors.New("option unrecognized")) return } - if err := user_model.SetEmailNotifications(ctx.Doer, preference); err != nil { + if err := user_model.SetEmailNotifications(ctx, ctx.Doer, preference); err != nil { log.Error("Set Email Notifications failed: %v", err) ctx.ServerError("SetEmailNotifications", err) return @@ -220,7 +220,7 @@ func EmailPost(ctx *context.Context) { // DeleteEmail response for delete user's email func DeleteEmail(ctx *context.Context) { - if err := user_model.DeleteEmailAddress(&user_model.EmailAddress{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { + if err := user_model.DeleteEmailAddress(ctx, &user_model.EmailAddress{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { ctx.ServerError("DeleteEmail", err) return } @@ -235,7 +235,7 @@ func DeleteAccount(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsAccount"] = true - if _, _, err := auth.UserSignIn(ctx.Doer.Name, ctx.FormString("password")); err != nil { + if _, _, err := auth.UserSignIn(ctx, ctx.Doer.Name, ctx.FormString("password")); err != nil { if user_model.IsErrUserNotExist(err) { loadAccountData(ctx) @@ -267,7 +267,7 @@ func DeleteAccount(ctx *context.Context) { } func loadAccountData(ctx *context.Context) { - emlist, err := user_model.GetEmailAddresses(ctx.Doer.ID) + emlist, err := user_model.GetEmailAddresses(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetEmailAddresses", err) return diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go index 2336c04bbed22..2c274f4c1cb11 100644 --- a/routers/web/user/setting/keys.go +++ b/routers/web/user/setting/keys.go @@ -51,7 +51,7 @@ func KeysPost(ctx *context.Context) { } switch form.Type { case "principal": - content, err := asymkey_model.CheckPrincipalKeyString(ctx.Doer, form.Content) + content, err := asymkey_model.CheckPrincipalKeyString(ctx, ctx.Doer, form.Content) if err != nil { if db.IsErrSSHDisabled(err) { ctx.Flash.Info(ctx.Tr("settings.ssh_disabled")) diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index 0321a5759b22c..13c9f0809800b 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -114,7 +114,7 @@ func ProfilePost(ctx *context.Context) { ctx.Doer.Description = form.Description ctx.Doer.KeepActivityPrivate = form.KeepActivityPrivate ctx.Doer.Visibility = form.Visibility - if err := user_model.UpdateUserSetting(ctx.Doer); err != nil { + if err := user_model.UpdateUserSetting(ctx, ctx.Doer); err != nil { if _, ok := err.(user_model.ErrEmailAlreadyUsed); ok { ctx.Flash.Error(ctx.Tr("form.email_been_used")) ctx.Redirect(setting.AppSubURL + "/user/settings") @@ -379,7 +379,7 @@ func UpdateUIThemePost(ctx *context.Context) { return } - if err := user_model.UpdateUserTheme(ctx.Doer, form.Theme); err != nil { + if err := user_model.UpdateUserTheme(ctx, ctx.Doer, form.Theme); err != nil { ctx.Flash.Error(ctx.Tr("settings.theme_update_error")) ctx.Redirect(setting.AppSubURL + "/user/settings/appearance") return @@ -405,7 +405,7 @@ func UpdateUserLang(ctx *context.Context) { ctx.Doer.Language = form.Language } - if err := user_model.UpdateUserSetting(ctx.Doer); err != nil { + if err := user_model.UpdateUserSetting(ctx, ctx.Doer); err != nil { ctx.ServerError("UpdateUserSetting", err) return } diff --git a/services/auth/basic.go b/services/auth/basic.go index ea8df3d0ea9ff..f3a9a8abce21d 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -123,7 +123,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } log.Trace("Basic Authorization: Attempting SignIn for %s", uname) - u, source, err := UserSignIn(uname, passwd) + u, source, err := UserSignIn(req.Context(), uname, passwd) if err != nil { if !user_model.IsErrUserNotExist(err) { log.Error("UserSignIn: %v", err) diff --git a/services/auth/interface.go b/services/auth/interface.go index dc91747a46025..ece28af12d1be 100644 --- a/services/auth/interface.go +++ b/services/auth/interface.go @@ -33,7 +33,7 @@ type Method interface { // PasswordAuthenticator represents a source of authentication type PasswordAuthenticator interface { - Authenticate(user *user_model.User, login, password string) (*user_model.User, error) + Authenticate(ctx context.Context, user *user_model.User, login, password string) (*user_model.User, error) } // LocalTwoFASkipper represents a source of authentication that can skip local 2fa diff --git a/services/auth/reverseproxy.go b/services/auth/reverseproxy.go index 62e60ccdc14ed..ad525f5c95fef 100644 --- a/services/auth/reverseproxy.go +++ b/services/auth/reverseproxy.go @@ -164,7 +164,7 @@ func (r *ReverseProxy) newUser(req *http.Request) *user_model.User { IsActive: util.OptionalBoolTrue, } - if err := user_model.CreateUser(user, &overwriteDefault); err != nil { + if err := user_model.CreateUser(req.Context(), user, &overwriteDefault); err != nil { // FIXME: should I create a system notice? log.Error("CreateUser: %v", err) return nil diff --git a/services/auth/signin.go b/services/auth/signin.go index 1095b27fe2da6..6d515ac628a39 100644 --- a/services/auth/signin.go +++ b/services/auth/signin.go @@ -4,6 +4,7 @@ package auth import ( + "context" "strings" "code.gitea.io/gitea/models/auth" @@ -20,14 +21,14 @@ import ( ) // UserSignIn validates user name and password. -func UserSignIn(username, password string) (*user_model.User, *auth.Source, error) { +func UserSignIn(ctx context.Context, username, password string) (*user_model.User, *auth.Source, error) { var user *user_model.User isEmail := false if strings.Contains(username, "@") { isEmail = true emailAddress := user_model.EmailAddress{LowerEmail: strings.ToLower(strings.TrimSpace(username))} // check same email - has, err := db.GetEngine(db.DefaultContext).Get(&emailAddress) + has, err := db.GetEngine(ctx).Get(&emailAddress) if err != nil { return nil, nil, err } @@ -49,7 +50,7 @@ func UserSignIn(username, password string) (*user_model.User, *auth.Source, erro } if user != nil { - hasUser, err := user_model.GetUser(user) + hasUser, err := user_model.GetUser(ctx, user) if err != nil { return nil, nil, err } @@ -69,7 +70,7 @@ func UserSignIn(username, password string) (*user_model.User, *auth.Source, erro return nil, nil, smtp.ErrUnsupportedLoginType } - user, err := authenticator.Authenticate(user, user.LoginName, password) + user, err := authenticator.Authenticate(ctx, user, user.LoginName, password) if err != nil { return nil, nil, err } @@ -100,7 +101,7 @@ func UserSignIn(username, password string) (*user_model.User, *auth.Source, erro continue } - authUser, err := authenticator.Authenticate(nil, username, password) + authUser, err := authenticator.Authenticate(ctx, nil, username, password) if err == nil { if !authUser.ProhibitLogin { diff --git a/services/auth/source/db/authenticate.go b/services/auth/source/db/authenticate.go index 34a0459149a9e..8160141863a15 100644 --- a/services/auth/source/db/authenticate.go +++ b/services/auth/source/db/authenticate.go @@ -4,9 +4,9 @@ package db import ( + "context" "fmt" - "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -43,7 +43,7 @@ func (err ErrUserPasswordInvalid) Unwrap() error { } // Authenticate authenticates the provided user against the DB -func Authenticate(user *user_model.User, login, password string) (*user_model.User, error) { +func Authenticate(ctx context.Context, user *user_model.User, login, password string) (*user_model.User, error) { if user == nil { return nil, user_model.ErrUserNotExist{Name: login} } @@ -61,7 +61,7 @@ func Authenticate(user *user_model.User, login, password string) (*user_model.Us if err := user.SetPassword(password); err != nil { return nil, err } - if err := user_model.UpdateUserCols(db.DefaultContext, user, "passwd", "passwd_hash_algo", "salt"); err != nil { + if err := user_model.UpdateUserCols(ctx, user, "passwd", "passwd_hash_algo", "salt"); err != nil { return nil, err } } diff --git a/services/auth/source/db/source.go b/services/auth/source/db/source.go index 3f4113c790479..50eae2743933c 100644 --- a/services/auth/source/db/source.go +++ b/services/auth/source/db/source.go @@ -4,6 +4,8 @@ package db import ( + "context" + "code.gitea.io/gitea/models/auth" user_model "code.gitea.io/gitea/models/user" ) @@ -23,8 +25,8 @@ func (source *Source) ToDB() ([]byte, error) { // Authenticate queries if login/password is valid against the PAM, // and create a local user if success when enabled. -func (source *Source) Authenticate(user *user_model.User, login, password string) (*user_model.User, error) { - return Authenticate(user, login, password) +func (source *Source) Authenticate(ctx context.Context, user *user_model.User, login, password string) (*user_model.User, error) { + return Authenticate(ctx, user, login, password) } func init() { diff --git a/services/auth/source/ldap/source_authenticate.go b/services/auth/source/ldap/source_authenticate.go index 3f3219adb9463..dc166d9eb413b 100644 --- a/services/auth/source/ldap/source_authenticate.go +++ b/services/auth/source/ldap/source_authenticate.go @@ -4,12 +4,12 @@ package ldap import ( + "context" "fmt" "strings" asymkey_model "code.gitea.io/gitea/models/asymkey" "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" auth_module "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/util" @@ -19,7 +19,7 @@ import ( // Authenticate queries if login/password is valid against the LDAP directory pool, // and create a local user if success when enabled. -func (source *Source) Authenticate(user *user_model.User, userName, password string) (*user_model.User, error) { +func (source *Source) Authenticate(ctx context.Context, user *user_model.User, userName, password string) (*user_model.User, error) { loginName := userName if user != nil { loginName = user.LoginName @@ -33,11 +33,11 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str isAttributeSSHPublicKeySet := len(strings.TrimSpace(source.AttributeSSHPublicKey)) > 0 // Update User admin flag if exist - if isExist, err := user_model.IsUserExist(db.DefaultContext, 0, sr.Username); err != nil { + if isExist, err := user_model.IsUserExist(ctx, 0, sr.Username); err != nil { return nil, err } else if isExist { if user == nil { - user, err = user_model.GetUserByName(db.DefaultContext, sr.Username) + user, err = user_model.GetUserByName(ctx, sr.Username) if err != nil { return nil, err } @@ -55,7 +55,7 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str cols = append(cols, "is_restricted") } if len(cols) > 0 { - err = user_model.UpdateUserCols(db.DefaultContext, user, cols...) + err = user_model.UpdateUserCols(ctx, user, cols...) if err != nil { return nil, err } @@ -94,7 +94,7 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str IsActive: util.OptionalBoolTrue, } - err := user_model.CreateUser(user, overwriteDefault) + err := user_model.CreateUser(ctx, user, overwriteDefault) if err != nil { return user, err } @@ -116,7 +116,7 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str if err != nil { return user, err } - if err := source_service.SyncGroupsToTeams(db.DefaultContext, user, sr.Groups, groupTeamMapping, source.GroupTeamMapRemoval); err != nil { + if err := source_service.SyncGroupsToTeams(ctx, user, sr.Groups, groupTeamMapping, source.GroupTeamMapRemoval); err != nil { return user, err } } diff --git a/services/auth/source/ldap/source_sync.go b/services/auth/source/ldap/source_sync.go index df5eb60393866..8fb1363fc2989 100644 --- a/services/auth/source/ldap/source_sync.go +++ b/services/auth/source/ldap/source_sync.go @@ -28,7 +28,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error { var sshKeysNeedUpdate bool // Find all users with this login type - FIXME: Should this be an iterator? - users, err := user_model.GetUsersBySource(source.authSource) + users, err := user_model.GetUsersBySource(ctx, source.authSource) if err != nil { log.Error("SyncExternalUsers: %v", err) return err @@ -128,7 +128,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error { IsActive: util.OptionalBoolTrue, } - err = user_model.CreateUser(usr, overwriteDefault) + err = user_model.CreateUser(ctx, usr, overwriteDefault) if err != nil { log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", source.authSource.Name, su.Username, err) } diff --git a/services/auth/source/oauth2/source_authenticate.go b/services/auth/source/oauth2/source_authenticate.go index e3e2a9e192f55..bbda35dee003a 100644 --- a/services/auth/source/oauth2/source_authenticate.go +++ b/services/auth/source/oauth2/source_authenticate.go @@ -4,13 +4,15 @@ package oauth2 import ( + "context" + user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/services/auth/source/db" ) // Authenticate falls back to the db authenticator -func (source *Source) Authenticate(user *user_model.User, login, password string) (*user_model.User, error) { - return db.Authenticate(user, login, password) +func (source *Source) Authenticate(ctx context.Context, user *user_model.User, login, password string) (*user_model.User, error) { + return db.Authenticate(ctx, user, login, password) } // NB: Oauth2 does not implement LocalTwoFASkipper for password authentication diff --git a/services/auth/source/pam/source_authenticate.go b/services/auth/source/pam/source_authenticate.go index e3a74e495cd65..0891a86392c49 100644 --- a/services/auth/source/pam/source_authenticate.go +++ b/services/auth/source/pam/source_authenticate.go @@ -4,6 +4,7 @@ package pam import ( + "context" "fmt" "strings" @@ -18,7 +19,7 @@ import ( // Authenticate queries if login/password is valid against the PAM, // and create a local user if success when enabled. -func (source *Source) Authenticate(user *user_model.User, userName, password string) (*user_model.User, error) { +func (source *Source) Authenticate(ctx context.Context, user *user_model.User, userName, password string) (*user_model.User, error) { pamLogin, err := pam.Auth(source.ServiceName, userName, password) if err != nil { if strings.Contains(err.Error(), "Authentication failure") { @@ -62,7 +63,7 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str IsActive: util.OptionalBoolTrue, } - if err := user_model.CreateUser(user, overwriteDefault); err != nil { + if err := user_model.CreateUser(ctx, user, overwriteDefault); err != nil { return user, err } diff --git a/services/auth/source/smtp/source_authenticate.go b/services/auth/source/smtp/source_authenticate.go index 7d7d1aa8b6bc9..b244fc7d40899 100644 --- a/services/auth/source/smtp/source_authenticate.go +++ b/services/auth/source/smtp/source_authenticate.go @@ -4,6 +4,7 @@ package smtp import ( + "context" "errors" "net/smtp" "net/textproto" @@ -16,7 +17,7 @@ import ( // Authenticate queries if the provided login/password is authenticates against the SMTP server // Users will be autoregistered as required -func (source *Source) Authenticate(user *user_model.User, userName, password string) (*user_model.User, error) { +func (source *Source) Authenticate(ctx context.Context, user *user_model.User, userName, password string) (*user_model.User, error) { // Verify allowed domains. if len(source.AllowedDomains) > 0 { idx := strings.Index(userName, "@") @@ -77,7 +78,7 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str IsActive: util.OptionalBoolTrue, } - if err := user_model.CreateUser(user, overwriteDefault); err != nil { + if err := user_model.CreateUser(ctx, user, overwriteDefault); err != nil { return user, err } diff --git a/services/auth/source/source_group_sync.go b/services/auth/source/source_group_sync.go index e42f60bde248c..3a2411ec55f1b 100644 --- a/services/auth/source/source_group_sync.go +++ b/services/auth/source/source_group_sync.go @@ -100,12 +100,12 @@ func syncGroupsToTeamsCached(ctx context.Context, user *user_model.User, orgTeam } if action == syncAdd && !isMember { - if err := models.AddTeamMember(team, user.ID); err != nil { + if err := models.AddTeamMember(ctx, team, user.ID); err != nil { log.Error("group sync: Could not add user to team: %v", err) return err } } else if action == syncRemove && isMember { - if err := models.RemoveTeamMember(team, user.ID); err != nil { + if err := models.RemoveTeamMember(ctx, team, user.ID); err != nil { log.Error("group sync: Could not remove user from team: %v", err) return err } diff --git a/services/auth/sspi_windows.go b/services/auth/sspi_windows.go index a4880c7334604..e29bd715293c9 100644 --- a/services/auth/sspi_windows.go +++ b/services/auth/sspi_windows.go @@ -4,6 +4,7 @@ package auth import ( + "context" "errors" "net/http" "strings" @@ -113,7 +114,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore, log.Error("User '%s' not found", username) return nil, nil } - user, err = s.newUser(username, cfg) + user, err = s.newUser(req.Context(), username, cfg) if err != nil { log.Error("CreateUser: %v", err) return nil, err @@ -161,7 +162,7 @@ func (s *SSPI) shouldAuthenticate(req *http.Request) (shouldAuth bool) { // newUser creates a new user object for the purpose of automatic registration // and populates its name and email with the information present in request headers. -func (s *SSPI) newUser(username string, cfg *sspi.Source) (*user_model.User, error) { +func (s *SSPI) newUser(ctx context.Context, username string, cfg *sspi.Source) (*user_model.User, error) { email := gouuid.New().String() + "@localhost.localdomain" user := &user_model.User{ Name: username, @@ -177,7 +178,7 @@ func (s *SSPI) newUser(username string, cfg *sspi.Source) (*user_model.User, err KeepEmailPrivate: util.OptionalBoolTrue, EmailNotificationsPreference: &emailNotificationPreference, } - if err := user_model.CreateUser(user, overwriteDefault); err != nil { + if err := user_model.CreateUser(ctx, user, overwriteDefault); err != nil { return nil, err } diff --git a/services/convert/convert.go b/services/convert/convert.go index a7a777e8bd6ba..a87352f51d111 100644 --- a/services/convert/convert.go +++ b/services/convert/convert.go @@ -107,16 +107,16 @@ func ToBranch(ctx context.Context, repo *repo_model.Repository, branchName strin } // ToBranchProtection convert a ProtectedBranch to api.BranchProtection -func ToBranchProtection(bp *git_model.ProtectedBranch) *api.BranchProtection { - pushWhitelistUsernames, err := user_model.GetUserNamesByIDs(bp.WhitelistUserIDs) +func ToBranchProtection(ctx context.Context, bp *git_model.ProtectedBranch) *api.BranchProtection { + pushWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.WhitelistUserIDs) if err != nil { log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err) } - mergeWhitelistUsernames, err := user_model.GetUserNamesByIDs(bp.MergeWhitelistUserIDs) + mergeWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.MergeWhitelistUserIDs) if err != nil { log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err) } - approvalsWhitelistUsernames, err := user_model.GetUserNamesByIDs(bp.ApprovalsWhitelistUserIDs) + approvalsWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.ApprovalsWhitelistUserIDs) if err != nil { log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err) } diff --git a/services/repository/create_test.go b/services/repository/create_test.go index 78be93bf121b6..7ffdcc38fb1c5 100644 --- a/services/repository/create_test.go +++ b/services/repository/create_test.go @@ -101,7 +101,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } for i, team := range teams { if i > 0 { // first team is Owner. - assert.NoError(t, models.NewTeam(team), "%s: NewTeam", team.Name) + assert.NoError(t, models.NewTeam(db.DefaultContext, team), "%s: NewTeam", team.Name) } testTeamRepositories(team.ID, teamRepos[i]) } @@ -111,7 +111,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { teams[4].IncludesAllRepositories = true teamRepos[4] = repoIds for i, team := range teams { - assert.NoError(t, models.UpdateTeam(team, false, true), "%s: UpdateTeam", team.Name) + assert.NoError(t, models.UpdateTeam(db.DefaultContext, team, false, true), "%s: UpdateTeam", team.Name) testTeamRepositories(team.ID, teamRepos[i]) } diff --git a/services/user/user_test.go b/services/user/user_test.go index 3f1bf9a0f8c71..7a9713c79f5d3 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -92,7 +92,7 @@ func TestCreateUser(t *testing.T) { MustChangePassword: false, } - assert.NoError(t, user_model.CreateUser(user)) + assert.NoError(t, user_model.CreateUser(db.DefaultContext, user)) assert.NoError(t, DeleteUser(db.DefaultContext, user, false)) } @@ -177,7 +177,7 @@ func TestCreateUser_Issue5882(t *testing.T) { for _, v := range tt { setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation - assert.NoError(t, user_model.CreateUser(v.user)) + assert.NoError(t, user_model.CreateUser(db.DefaultContext, v.user)) u, err := user_model.GetUserByEmail(db.DefaultContext, v.user.Email) assert.NoError(t, err) diff --git a/tests/integration/auth_ldap_test.go b/tests/integration/auth_ldap_test.go index cf4c66734a676..eb6486fde1f0a 100644 --- a/tests/integration/auth_ldap_test.go +++ b/tests/integration/auth_ldap_test.go @@ -428,7 +428,7 @@ func TestLDAPGroupTeamSyncAddMember(t *testing.T) { isMember, err := organization.IsTeamMember(db.DefaultContext, usersOrgs[0].ID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember, "Membership should be added to the right team") - err = models.RemoveTeamMember(team, user.ID) + err = models.RemoveTeamMember(db.DefaultContext, team, user.ID) assert.NoError(t, err) err = models.RemoveOrgUser(usersOrgs[0].ID, user.ID) assert.NoError(t, err) @@ -460,7 +460,7 @@ func TestLDAPGroupTeamSyncRemoveMember(t *testing.T) { }) err = organization.AddOrgUser(org.ID, user.ID) assert.NoError(t, err) - err = models.AddTeamMember(team, user.ID) + err = models.AddTeamMember(db.DefaultContext, team, user.ID) assert.NoError(t, err) isMember, err := organization.IsOrganizationMember(db.DefaultContext, org.ID, user.ID) assert.NoError(t, err) From f8a109440655b77e8554e1744e31bf52a7c63df7 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Fri, 15 Sep 2023 00:22:32 +0000 Subject: [PATCH 04/23] [skip ci] Updated translations via Crowdin --- options/locale/locale_ja-JP.ini | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index aed68018bd123..e4a479ecf9e4c 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -3230,6 +3230,7 @@ desc=リポジトリ パッケージを管理します。 empty=パッケージはまだありません。 empty.documentation=パッケージレジストリの詳細については、 ドキュメント を参照してください。 empty.repo=パッケージはアップロードしたけども、ここに表示されない? パッケージ設定を開いて、パッケージをこのリポジトリにリンクしてください。 +registry.documentation=%sレジストリの詳細については、 ドキュメント を参照してください。 filter.type=タイプ filter.type.all=すべて filter.no_result=フィルタの結果、空になりました。 @@ -3319,6 +3320,8 @@ pub.install=Dart を使用してパッケージをインストールするには pypi.requires=必要なPython pypi.install=pip を使用してパッケージをインストールするには、次のコマンドを実行します: rpm.registry=このレジストリをコマンドラインからセットアップします: +rpm.distros.redhat=RedHat系ディストリビューションの場合 +rpm.distros.suse=SUSE系ディストリビューションの場合 rpm.install=パッケージをインストールするには、次のコマンドを実行します: rubygems.install=gem を使用してパッケージをインストールするには、次のコマンドを実行します: rubygems.install2=または Gemfile に追加します: @@ -3416,6 +3419,7 @@ runners.labels=ラベル runners.last_online=最終オンライン時刻 runners.runner_title=ランナー runners.task_list=このランナーの最近のタスク +runners.task_list.no_tasks=タスクはまだありません。 runners.task_list.run=実行 runners.task_list.status=ステータス runners.task_list.repository=リポジトリ From c548dde205244a39a26ba98377c0f5cc11da7041 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Fri, 15 Sep 2023 08:13:19 +0200 Subject: [PATCH 05/23] More refactoring of `db.DefaultContext` (#27083) Next step of #27065 --- cmd/admin_user_create.go | 2 +- cmd/admin_user_generate_access_token.go | 4 +-- models/auth/token.go | 31 ++++++++-------- models/auth/token_test.go | 35 ++++++++++--------- models/auth/twofactor.go | 21 +++++------ models/issues/comment.go | 4 +-- models/issues/pull_list.go | 14 ++++---- models/issues/pull_test.go | 4 +-- models/repo/attachment.go | 20 +++++------ models/repo/attachment_test.go | 8 ++--- models/repo/star.go | 8 ++--- models/repo/star_test.go | 16 ++++----- models/repo/upload.go | 23 ++++++------ models/repo/watch.go | 8 ++--- models/repo/watch_test.go | 32 ++++++++--------- models/user/openid.go | 14 ++++---- models/user/openid_test.go | 15 ++++---- models/user/setting.go | 32 ++++++++--------- models/user/setting_test.go | 19 +++++----- modules/activitypub/client.go | 5 +-- modules/activitypub/client_test.go | 3 +- modules/activitypub/user_settings.go | 18 +++++----- modules/activitypub/user_settings_test.go | 7 ++-- modules/context/api.go | 2 +- modules/context/repo.go | 2 +- routers/api/packages/alpine/alpine.go | 2 +- routers/api/packages/chef/auth.go | 7 ++-- routers/api/packages/debian/debian.go | 2 +- routers/api/packages/nuget/auth.go | 4 +-- routers/api/packages/rpm/rpm.go | 2 +- routers/api/v1/activitypub/person.go | 2 +- routers/api/v1/api.go | 2 +- routers/api/v1/org/team.go | 2 +- routers/api/v1/repo/issue_attachment.go | 4 +-- .../api/v1/repo/issue_comment_attachment.go | 2 +- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/repo/release_attachment.go | 2 +- routers/api/v1/repo/star.go | 2 +- routers/api/v1/repo/subscriber.go | 2 +- routers/api/v1/repo/teams.go | 6 ++-- routers/api/v1/user/app.go | 12 +++---- routers/api/v1/user/star.go | 4 +-- routers/api/v1/user/watch.go | 2 +- routers/web/admin/users.go | 6 ++-- routers/web/auth/2fa.go | 8 ++--- routers/web/auth/auth.go | 2 +- routers/web/auth/linkaccount.go | 2 +- routers/web/auth/oauth.go | 2 +- routers/web/auth/password.go | 6 ++-- routers/web/org/teams.go | 2 +- routers/web/repo/attachment.go | 4 +-- routers/web/repo/editor.go | 4 +-- routers/web/repo/http.go | 2 +- routers/web/repo/issue.go | 6 ++-- routers/web/repo/middlewares.go | 8 ++--- routers/web/repo/repo.go | 4 +-- routers/web/repo/setting/collaboration.go | 2 +- routers/web/repo/setting/settings_test.go | 9 ++--- routers/web/repo/view.go | 4 +-- routers/web/shared/user/header.go | 2 +- routers/web/user/setting/applications.go | 8 ++--- routers/web/user/setting/packages.go | 2 +- routers/web/user/setting/profile.go | 4 +-- routers/web/user/setting/security/2fa.go | 14 ++++---- routers/web/user/setting/security/openid.go | 6 ++-- routers/web/user/setting/security/security.go | 6 ++-- services/asymkey/sign.go | 8 ++--- services/auth/basic.go | 6 ++-- services/auth/oauth2.go | 18 +++++----- services/issue/content.go | 7 ++-- services/migrations/gitea_uploader_test.go | 2 +- services/org/repo.go | 6 ++-- services/org/repo_test.go | 5 +-- services/packages/alpine/repository.go | 12 +++---- services/packages/debian/repository.go | 12 +++---- services/packages/rpm/repository.go | 15 ++++---- services/pull/check.go | 2 +- services/repository/create_test.go | 2 +- services/repository/delete.go | 20 +++++------ services/repository/delete_test.go | 2 +- services/repository/files/upload.go | 13 ++++--- .../api_activitypub_person_test.go | 3 +- tests/integration/api_packages_chef_test.go | 2 +- 83 files changed, 336 insertions(+), 320 deletions(-) diff --git a/cmd/admin_user_create.go b/cmd/admin_user_create.go index 73afcdcf32455..fefe18d39c5d8 100644 --- a/cmd/admin_user_create.go +++ b/cmd/admin_user_create.go @@ -156,7 +156,7 @@ func runCreateUser(c *cli.Context) error { UID: u.ID, } - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { return err } diff --git a/cmd/admin_user_generate_access_token.go b/cmd/admin_user_generate_access_token.go index 0febb9166137d..6e78939680a2f 100644 --- a/cmd/admin_user_generate_access_token.go +++ b/cmd/admin_user_generate_access_token.go @@ -63,7 +63,7 @@ func runGenerateAccessToken(c *cli.Context) error { UID: user.ID, } - exist, err := auth_model.AccessTokenByNameExists(t) + exist, err := auth_model.AccessTokenByNameExists(ctx, t) if err != nil { return err } @@ -79,7 +79,7 @@ func runGenerateAccessToken(c *cli.Context) error { t.Scope = accessTokenScope // create the token - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { return err } diff --git a/models/auth/token.go b/models/auth/token.go index fed03803d56b7..8abcc622bc89c 100644 --- a/models/auth/token.go +++ b/models/auth/token.go @@ -5,6 +5,7 @@ package auth import ( + "context" "crypto/subtle" "encoding/hex" "fmt" @@ -95,7 +96,7 @@ func init() { } // NewAccessToken creates new access token. -func NewAccessToken(t *AccessToken) error { +func NewAccessToken(ctx context.Context, t *AccessToken) error { salt, err := util.CryptoRandomString(10) if err != nil { return err @@ -108,7 +109,7 @@ func NewAccessToken(t *AccessToken) error { t.Token = hex.EncodeToString(token) t.TokenHash = HashToken(t.Token, t.TokenSalt) t.TokenLastEight = t.Token[len(t.Token)-8:] - _, err = db.GetEngine(db.DefaultContext).Insert(t) + _, err = db.GetEngine(ctx).Insert(t) return err } @@ -137,7 +138,7 @@ func getAccessTokenIDFromCache(token string) int64 { } // GetAccessTokenBySHA returns access token by given token value -func GetAccessTokenBySHA(token string) (*AccessToken, error) { +func GetAccessTokenBySHA(ctx context.Context, token string) (*AccessToken, error) { if token == "" { return nil, ErrAccessTokenEmpty{} } @@ -158,7 +159,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { TokenLastEight: lastEight, } // Re-get the token from the db in case it has been deleted in the intervening period - has, err := db.GetEngine(db.DefaultContext).ID(id).Get(accessToken) + has, err := db.GetEngine(ctx).ID(id).Get(accessToken) if err != nil { return nil, err } @@ -169,7 +170,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { } var tokens []AccessToken - err := db.GetEngine(db.DefaultContext).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) + err := db.GetEngine(ctx).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) if err != nil { return nil, err } else if len(tokens) == 0 { @@ -189,8 +190,8 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { } // AccessTokenByNameExists checks if a token name has been used already by a user. -func AccessTokenByNameExists(token *AccessToken) (bool, error) { - return db.GetEngine(db.DefaultContext).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() +func AccessTokenByNameExists(ctx context.Context, token *AccessToken) (bool, error) { + return db.GetEngine(ctx).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() } // ListAccessTokensOptions contain filter options @@ -201,8 +202,8 @@ type ListAccessTokensOptions struct { } // ListAccessTokens returns a list of access tokens belongs to given user. -func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { - sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) +func ListAccessTokens(ctx context.Context, opts ListAccessTokensOptions) ([]*AccessToken, error) { + sess := db.GetEngine(ctx).Where("uid=?", opts.UserID) if len(opts.Name) != 0 { sess = sess.Where("name=?", opts.Name) @@ -222,14 +223,14 @@ func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { } // UpdateAccessToken updates information of access token. -func UpdateAccessToken(t *AccessToken) error { - _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) +func UpdateAccessToken(ctx context.Context, t *AccessToken) error { + _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t) return err } // CountAccessTokens count access tokens belongs to given user by options -func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { - sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) +func CountAccessTokens(ctx context.Context, opts ListAccessTokensOptions) (int64, error) { + sess := db.GetEngine(ctx).Where("uid=?", opts.UserID) if len(opts.Name) != 0 { sess = sess.Where("name=?", opts.Name) } @@ -237,8 +238,8 @@ func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { } // DeleteAccessTokenByID deletes access token by given ID. -func DeleteAccessTokenByID(id, userID int64) error { - cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&AccessToken{ +func DeleteAccessTokenByID(ctx context.Context, id, userID int64) error { + cnt, err := db.GetEngine(ctx).ID(id).Delete(&AccessToken{ UID: userID, }) if err != nil { diff --git a/models/auth/token_test.go b/models/auth/token_test.go index 8a1e664950220..72c937ffd6a74 100644 --- a/models/auth/token_test.go +++ b/models/auth/token_test.go @@ -7,6 +7,7 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" @@ -18,7 +19,7 @@ func TestNewAccessToken(t *testing.T) { UID: 3, Name: "Token C", } - assert.NoError(t, auth_model.NewAccessToken(token)) + assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) invalidToken := &auth_model.AccessToken{ @@ -26,7 +27,7 @@ func TestNewAccessToken(t *testing.T) { UID: 2, Name: "Token F", } - assert.Error(t, auth_model.NewAccessToken(invalidToken)) + assert.Error(t, auth_model.NewAccessToken(db.DefaultContext, invalidToken)) } func TestAccessTokenByNameExists(t *testing.T) { @@ -39,16 +40,16 @@ func TestAccessTokenByNameExists(t *testing.T) { } // Check to make sure it doesn't exists already - exist, err := auth_model.AccessTokenByNameExists(token) + exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token) assert.NoError(t, err) assert.False(t, exist) // Save it to the database - assert.NoError(t, auth_model.NewAccessToken(token)) + assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) // This token must be found by name in the DB now - exist, err = auth_model.AccessTokenByNameExists(token) + exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token) assert.NoError(t, err) assert.True(t, exist) @@ -59,32 +60,32 @@ func TestAccessTokenByNameExists(t *testing.T) { // Name matches but different user ID, this shouldn't exists in the // database - exist, err = auth_model.AccessTokenByNameExists(user4Token) + exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token) assert.NoError(t, err) assert.False(t, exist) } func TestGetAccessTokenBySHA(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - token, err := auth_model.GetAccessTokenBySHA("d2c6c1ba3890b309189a8e618c72a162e4efbf36") + token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "d2c6c1ba3890b309189a8e618c72a162e4efbf36") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) assert.Equal(t, "Token A", token.Name) assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) assert.Equal(t, "e4efbf36", token.TokenLastEight) - _, err = auth_model.GetAccessTokenBySHA("notahash") + _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash") assert.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) - _, err = auth_model.GetAccessTokenBySHA("") + _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "") assert.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenEmpty(err)) } func TestListAccessTokens(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 1}) + tokens, err := auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1}) assert.NoError(t, err) if assert.Len(t, tokens, 2) { assert.Equal(t, int64(1), tokens[0].UID) @@ -93,39 +94,39 @@ func TestListAccessTokens(t *testing.T) { assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B") } - tokens, err = auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 2}) + tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2}) assert.NoError(t, err) if assert.Len(t, tokens, 1) { assert.Equal(t, int64(2), tokens[0].UID) assert.Equal(t, "Token A", tokens[0].Name) } - tokens, err = auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 100}) + tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100}) assert.NoError(t, err) assert.Empty(t, tokens) } func TestUpdateAccessToken(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - token, err := auth_model.GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") + token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) token.Name = "Token Z" - assert.NoError(t, auth_model.UpdateAccessToken(token)) + assert.NoError(t, auth_model.UpdateAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) } func TestDeleteAccessTokenByID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - token, err := auth_model.GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") + token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) - assert.NoError(t, auth_model.DeleteAccessTokenByID(token.ID, 1)) + assert.NoError(t, auth_model.DeleteAccessTokenByID(db.DefaultContext, token.ID, 1)) unittest.AssertNotExistsBean(t, token) - err = auth_model.DeleteAccessTokenByID(100, 100) + err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100) assert.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) } diff --git a/models/auth/twofactor.go b/models/auth/twofactor.go index 751a281f7e8b9..51061e520558b 100644 --- a/models/auth/twofactor.go +++ b/models/auth/twofactor.go @@ -4,6 +4,7 @@ package auth import ( + "context" "crypto/md5" "crypto/subtle" "encoding/base32" @@ -121,22 +122,22 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) { } // NewTwoFactor creates a new two-factor authentication token. -func NewTwoFactor(t *TwoFactor) error { - _, err := db.GetEngine(db.DefaultContext).Insert(t) +func NewTwoFactor(ctx context.Context, t *TwoFactor) error { + _, err := db.GetEngine(ctx).Insert(t) return err } // UpdateTwoFactor updates a two-factor authentication token. -func UpdateTwoFactor(t *TwoFactor) error { - _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) +func UpdateTwoFactor(ctx context.Context, t *TwoFactor) error { + _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t) return err } // GetTwoFactorByUID returns the two-factor authentication token associated with // the user, if any. -func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { +func GetTwoFactorByUID(ctx context.Context, uid int64) (*TwoFactor, error) { twofa := &TwoFactor{} - has, err := db.GetEngine(db.DefaultContext).Where("uid=?", uid).Get(twofa) + has, err := db.GetEngine(ctx).Where("uid=?", uid).Get(twofa) if err != nil { return nil, err } else if !has { @@ -147,13 +148,13 @@ func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { // HasTwoFactorByUID returns the two-factor authentication token associated with // the user, if any. -func HasTwoFactorByUID(uid int64) (bool, error) { - return db.GetEngine(db.DefaultContext).Where("uid=?", uid).Exist(&TwoFactor{}) +func HasTwoFactorByUID(ctx context.Context, uid int64) (bool, error) { + return db.GetEngine(ctx).Where("uid=?", uid).Exist(&TwoFactor{}) } // DeleteTwoFactorByID deletes two-factor authentication token by given ID. -func DeleteTwoFactorByID(id, userID int64) error { - cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&TwoFactor{ +func DeleteTwoFactorByID(ctx context.Context, id, userID int64) error { + cnt, err := db.GetEngine(ctx).ID(id).Delete(&TwoFactor{ UID: userID, }) if err != nil { diff --git a/models/issues/comment.go b/models/issues/comment.go index e045b71d23ba9..66b3a8527ffd2 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -359,12 +359,12 @@ func (c *Comment) LoadPoster(ctx context.Context) (err error) { } // AfterDelete is invoked from XORM after the object is deleted. -func (c *Comment) AfterDelete() { +func (c *Comment) AfterDelete(ctx context.Context) { if c.ID <= 0 { return } - _, err := repo_model.DeleteAttachmentsByComment(c.ID, true) + _, err := repo_model.DeleteAttachmentsByComment(ctx, c.ID, true) if err != nil { log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err) } diff --git a/models/issues/pull_list.go b/models/issues/pull_list.go index c4506ef15085e..c209386e2e07d 100644 --- a/models/issues/pull_list.go +++ b/models/issues/pull_list.go @@ -27,8 +27,8 @@ type PullRequestsOptions struct { MilestoneID int64 } -func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { - sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", baseRepoID) +func listPullRequestStatement(ctx context.Context, baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { + sess := db.GetEngine(ctx).Where("pull_request.base_repo_id=?", baseRepoID) sess.Join("INNER", "issue", "pull_request.issue_id = issue.id") switch opts.State { @@ -115,21 +115,21 @@ func GetUnmergedPullRequestsByBaseInfo(ctx context.Context, repoID int64, branch } // GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status. -func GetPullRequestIDsByCheckStatus(status PullRequestStatus) ([]int64, error) { +func GetPullRequestIDsByCheckStatus(ctx context.Context, status PullRequestStatus) ([]int64, error) { prs := make([]int64, 0, 10) - return prs, db.GetEngine(db.DefaultContext).Table("pull_request"). + return prs, db.GetEngine(ctx).Table("pull_request"). Where("status=?", status). Cols("pull_request.id"). Find(&prs) } // PullRequests returns all pull requests for a base Repo by the given conditions -func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) { +func PullRequests(ctx context.Context, baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) { if opts.Page <= 0 { opts.Page = 1 } - countSession, err := listPullRequestStatement(baseRepoID, opts) + countSession, err := listPullRequestStatement(ctx, baseRepoID, opts) if err != nil { log.Error("listPullRequestStatement: %v", err) return nil, 0, err @@ -140,7 +140,7 @@ func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, return nil, maxResults, err } - findSession, err := listPullRequestStatement(baseRepoID, opts) + findSession, err := listPullRequestStatement(ctx, baseRepoID, opts) applySorts(findSession, opts.SortType, 0) if err != nil { log.Error("listPullRequestStatement: %v", err) diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go index 1105608858f75..3636263c46d4b 100644 --- a/models/issues/pull_test.go +++ b/models/issues/pull_test.go @@ -60,7 +60,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) { func TestPullRequestsNewest(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - prs, count, err := issues_model.PullRequests(1, &issues_model.PullRequestsOptions{ + prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, }, @@ -107,7 +107,7 @@ func TestLoadRequestedReviewers(t *testing.T) { func TestPullRequestsOldest(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - prs, count, err := issues_model.PullRequests(1, &issues_model.PullRequestsOptions{ + prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, }, diff --git a/models/repo/attachment.go b/models/repo/attachment.go index df3b9cd2137b0..1a588398c1a40 100644 --- a/models/repo/attachment.go +++ b/models/repo/attachment.go @@ -37,9 +37,9 @@ func init() { } // IncreaseDownloadCount is update download count + 1 -func (a *Attachment) IncreaseDownloadCount() error { +func (a *Attachment) IncreaseDownloadCount(ctx context.Context) error { // Update download count. - if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { + if _, err := db.GetEngine(ctx).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { return fmt.Errorf("increase attachment count: %w", err) } @@ -164,8 +164,8 @@ func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, file } // DeleteAttachment deletes the given attachment and optionally the associated file. -func DeleteAttachment(a *Attachment, remove bool) error { - _, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove) +func DeleteAttachment(ctx context.Context, a *Attachment, remove bool) error { + _, err := DeleteAttachments(ctx, []*Attachment{a}, remove) return err } @@ -196,23 +196,23 @@ func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bo } // DeleteAttachmentsByIssue deletes all attachments associated with the given issue. -func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) { - attachments, err := GetAttachmentsByIssueID(db.DefaultContext, issueID) +func DeleteAttachmentsByIssue(ctx context.Context, issueID int64, remove bool) (int, error) { + attachments, err := GetAttachmentsByIssueID(ctx, issueID) if err != nil { return 0, err } - return DeleteAttachments(db.DefaultContext, attachments, remove) + return DeleteAttachments(ctx, attachments, remove) } // DeleteAttachmentsByComment deletes all attachments associated with the given comment. -func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) { - attachments, err := GetAttachmentsByCommentID(db.DefaultContext, commentID) +func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) { + attachments, err := GetAttachmentsByCommentID(ctx, commentID) if err != nil { return 0, err } - return DeleteAttachments(db.DefaultContext, attachments, remove) + return DeleteAttachments(ctx, attachments, remove) } // UpdateAttachmentByUUID Updates attachment via uuid diff --git a/models/repo/attachment_test.go b/models/repo/attachment_test.go index 21fba227a5c0f..c059ffd39a91e 100644 --- a/models/repo/attachment_test.go +++ b/models/repo/attachment_test.go @@ -21,7 +21,7 @@ func TestIncreaseDownloadCount(t *testing.T) { assert.Equal(t, int64(0), attachment.DownloadCount) // increase download count - err = attachment.IncreaseDownloadCount() + err = attachment.IncreaseDownloadCount(db.DefaultContext) assert.NoError(t, err) attachment, err = repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") @@ -45,15 +45,15 @@ func TestGetByCommentOrIssueID(t *testing.T) { func TestDeleteAttachments(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - count, err := repo_model.DeleteAttachmentsByIssue(4, false) + count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false) assert.NoError(t, err) assert.Equal(t, 2, count) - count, err = repo_model.DeleteAttachmentsByComment(2, false) + count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false) assert.NoError(t, err) assert.Equal(t, 2, count) - err = repo_model.DeleteAttachment(&repo_model.Attachment{ID: 8}, false) + err = repo_model.DeleteAttachment(db.DefaultContext, &repo_model.Attachment{ID: 8}, false) assert.NoError(t, err) attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18") diff --git a/models/repo/star.go b/models/repo/star.go index 89bdb7ac05cf5..60737149da85e 100644 --- a/models/repo/star.go +++ b/models/repo/star.go @@ -24,8 +24,8 @@ func init() { } // StarRepo or unstar repository. -func StarRepo(userID, repoID int64, star bool) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func StarRepo(ctx context.Context, userID, repoID int64, star bool) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -72,8 +72,8 @@ func IsStaring(ctx context.Context, userID, repoID int64) bool { } // GetStargazers returns the users that starred the repo. -func GetStargazers(repo *Repository, opts db.ListOptions) ([]*user_model.User, error) { - sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID). +func GetStargazers(ctx context.Context, repo *Repository, opts db.ListOptions) ([]*user_model.User, error) { + sess := db.GetEngine(ctx).Where("star.repo_id = ?", repo.ID). Join("LEFT", "star", "`user`.id = star.uid") if opts.Page > 0 { sess = db.SetSessionPagination(sess, &opts) diff --git a/models/repo/star_test.go b/models/repo/star_test.go index f15ac12ebea65..62eac4e29a88d 100644 --- a/models/repo/star_test.go +++ b/models/repo/star_test.go @@ -18,11 +18,11 @@ func TestStarRepo(t *testing.T) { const userID = 2 const repoID = 1 unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, false)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) } @@ -36,7 +36,7 @@ func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) + gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) assert.NoError(t, err) if assert.Len(t, gazers, 1) { assert.Equal(t, int64(2), gazers[0].ID) @@ -47,7 +47,7 @@ func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) + gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) } @@ -57,15 +57,15 @@ func TestClearRepoStars(t *testing.T) { const userID = 2 const repoID = 1 unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, false)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) assert.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repoID)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) + gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) } diff --git a/models/repo/upload.go b/models/repo/upload.go index 3b1b97c6d61fa..d96ab21bcdead 100644 --- a/models/repo/upload.go +++ b/models/repo/upload.go @@ -5,6 +5,7 @@ package repo import ( + "context" "fmt" "io" "mime/multipart" @@ -61,7 +62,7 @@ func (upload *Upload) LocalPath() string { } // NewUpload creates a new upload object. -func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { +func NewUpload(ctx context.Context, name string, buf []byte, file multipart.File) (_ *Upload, err error) { upload := &Upload{ UUID: gouuid.New().String(), Name: name, @@ -84,7 +85,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err return nil, fmt.Errorf("Copy: %w", err) } - if _, err := db.GetEngine(db.DefaultContext).Insert(upload); err != nil { + if _, err := db.GetEngine(ctx).Insert(upload); err != nil { return nil, err } @@ -92,9 +93,9 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err } // GetUploadByUUID returns the Upload by UUID -func GetUploadByUUID(uuid string) (*Upload, error) { +func GetUploadByUUID(ctx context.Context, uuid string) (*Upload, error) { upload := &Upload{} - has, err := db.GetEngine(db.DefaultContext).Where("uuid=?", uuid).Get(upload) + has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(upload) if err != nil { return nil, err } else if !has { @@ -104,23 +105,23 @@ func GetUploadByUUID(uuid string) (*Upload, error) { } // GetUploadsByUUIDs returns multiple uploads by UUIDS -func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { +func GetUploadsByUUIDs(ctx context.Context, uuids []string) ([]*Upload, error) { if len(uuids) == 0 { return []*Upload{}, nil } // Silently drop invalid uuids. uploads := make([]*Upload, 0, len(uuids)) - return uploads, db.GetEngine(db.DefaultContext).In("uuid", uuids).Find(&uploads) + return uploads, db.GetEngine(ctx).In("uuid", uuids).Find(&uploads) } // DeleteUploads deletes multiple uploads -func DeleteUploads(uploads ...*Upload) (err error) { +func DeleteUploads(ctx context.Context, uploads ...*Upload) (err error) { if len(uploads) == 0 { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -159,8 +160,8 @@ func DeleteUploads(uploads ...*Upload) (err error) { } // DeleteUploadByUUID deletes a upload by UUID -func DeleteUploadByUUID(uuid string) error { - upload, err := GetUploadByUUID(uuid) +func DeleteUploadByUUID(ctx context.Context, uuid string) error { + upload, err := GetUploadByUUID(ctx, uuid) if err != nil { if IsErrUploadNotExist(err) { return nil @@ -168,7 +169,7 @@ func DeleteUploadByUUID(uuid string) error { return fmt.Errorf("GetUploadByUUID: %w", err) } - if err := DeleteUploads(upload); err != nil { + if err := DeleteUploads(ctx, upload); err != nil { return fmt.Errorf("DeleteUpload: %w", err) } diff --git a/models/repo/watch.go b/models/repo/watch.go index 00f313ca7cc5b..02a94ecac0538 100644 --- a/models/repo/watch.go +++ b/models/repo/watch.go @@ -59,8 +59,8 @@ func IsWatchMode(mode WatchMode) bool { } // IsWatching checks if user has watched given repository. -func IsWatching(userID, repoID int64) bool { - watch, err := GetWatch(db.DefaultContext, userID, repoID) +func IsWatching(ctx context.Context, userID, repoID int64) bool { + watch, err := GetWatch(ctx, userID, repoID) return err == nil && IsWatchMode(watch.Mode) } @@ -155,8 +155,8 @@ func GetRepoWatchersIDs(ctx context.Context, repoID int64) ([]int64, error) { } // GetRepoWatchers returns range of users watching given repository. -func GetRepoWatchers(repoID int64, opts db.ListOptions) ([]*user_model.User, error) { - sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repoID). +func GetRepoWatchers(ctx context.Context, repoID int64, opts db.ListOptions) ([]*user_model.User, error) { + sess := db.GetEngine(ctx).Where("watch.repo_id=?", repoID). Join("LEFT", "watch", "`user`.id=`watch`.user_id"). And("`watch`.mode<>?", WatchModeDont) if opts.Page > 0 { diff --git a/models/repo/watch_test.go b/models/repo/watch_test.go index 8b8c6d6250c4a..1384d1e1572e5 100644 --- a/models/repo/watch_test.go +++ b/models/repo/watch_test.go @@ -17,13 +17,13 @@ import ( func TestIsWatching(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.True(t, repo_model.IsWatching(1, 1)) - assert.True(t, repo_model.IsWatching(4, 1)) - assert.True(t, repo_model.IsWatching(11, 1)) + assert.True(t, repo_model.IsWatching(db.DefaultContext, 1, 1)) + assert.True(t, repo_model.IsWatching(db.DefaultContext, 4, 1)) + assert.True(t, repo_model.IsWatching(db.DefaultContext, 11, 1)) - assert.False(t, repo_model.IsWatching(1, 5)) - assert.False(t, repo_model.IsWatching(8, 1)) - assert.False(t, repo_model.IsWatching(unittest.NonexistentID, unittest.NonexistentID)) + assert.False(t, repo_model.IsWatching(db.DefaultContext, 1, 5)) + assert.False(t, repo_model.IsWatching(db.DefaultContext, 8, 1)) + assert.False(t, repo_model.IsWatching(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } func TestGetWatchers(t *testing.T) { @@ -47,7 +47,7 @@ func TestRepository_GetWatchers(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - watchers, err := repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) for _, watcher := range watchers { @@ -55,7 +55,7 @@ func TestRepository_GetWatchers(t *testing.T) { } repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9}) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, 0) } @@ -64,7 +64,7 @@ func TestWatchIfAuto(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - watchers, err := repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) @@ -74,13 +74,13 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) @@ -88,31 +88,31 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount+1) // Should remove watch, inhibit from adding auto assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, 12, 1, false)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Must not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) } diff --git a/models/user/openid.go b/models/user/openid.go index 596ff182bc751..ee4ecabae0b76 100644 --- a/models/user/openid.go +++ b/models/user/openid.go @@ -28,9 +28,9 @@ func init() { } // GetUserOpenIDs returns all openid addresses that belongs to given user. -func GetUserOpenIDs(uid int64) ([]*UserOpenID, error) { +func GetUserOpenIDs(ctx context.Context, uid int64) ([]*UserOpenID, error) { openids := make([]*UserOpenID, 0, 5) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("uid=?", uid). Asc("id"). Find(&openids); err != nil { @@ -82,16 +82,16 @@ func AddUserOpenID(ctx context.Context, openid *UserOpenID) error { } // DeleteUserOpenID deletes an openid address of given user. -func DeleteUserOpenID(openid *UserOpenID) (err error) { +func DeleteUserOpenID(ctx context.Context, openid *UserOpenID) (err error) { var deleted int64 // ask to check UID address := UserOpenID{ UID: openid.UID, } if openid.ID > 0 { - deleted, err = db.GetEngine(db.DefaultContext).ID(openid.ID).Delete(&address) + deleted, err = db.GetEngine(ctx).ID(openid.ID).Delete(&address) } else { - deleted, err = db.GetEngine(db.DefaultContext). + deleted, err = db.GetEngine(ctx). Where("openid=?", openid.URI). Delete(&address) } @@ -105,7 +105,7 @@ func DeleteUserOpenID(openid *UserOpenID) (err error) { } // ToggleUserOpenIDVisibility toggles visibility of an openid address of given user. -func ToggleUserOpenIDVisibility(id int64) (err error) { - _, err = db.GetEngine(db.DefaultContext).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) +func ToggleUserOpenIDVisibility(ctx context.Context, id int64) (err error) { + _, err = db.GetEngine(ctx).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) return err } diff --git a/models/user/openid_test.go b/models/user/openid_test.go index 6f0eae55e73a1..27e6edd1e0053 100644 --- a/models/user/openid_test.go +++ b/models/user/openid_test.go @@ -6,6 +6,7 @@ package user_test import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -15,7 +16,7 @@ import ( func TestGetUserOpenIDs(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - oids, err := user_model.GetUserOpenIDs(int64(1)) + oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(1)) if assert.NoError(t, err) && assert.Len(t, oids, 2) { assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI) assert.False(t, oids[0].Show) @@ -23,7 +24,7 @@ func TestGetUserOpenIDs(t *testing.T) { assert.True(t, oids[1].Show) } - oids, err = user_model.GetUserOpenIDs(int64(2)) + oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if assert.NoError(t, err) && assert.Len(t, oids, 1) { assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI) assert.True(t, oids[0].Show) @@ -32,28 +33,28 @@ func TestGetUserOpenIDs(t *testing.T) { func TestToggleUserOpenIDVisibility(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - oids, err := user_model.GetUserOpenIDs(int64(2)) + oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { return } assert.True(t, oids[0].Show) - err = user_model.ToggleUserOpenIDVisibility(oids[0].ID) + err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) if !assert.NoError(t, err) { return } - oids, err = user_model.GetUserOpenIDs(int64(2)) + oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { return } assert.False(t, oids[0].Show) - err = user_model.ToggleUserOpenIDVisibility(oids[0].ID) + err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) if !assert.NoError(t, err) { return } - oids, err = user_model.GetUserOpenIDs(int64(2)) + oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if !assert.NoError(t, err) { return } diff --git a/models/user/setting.go b/models/user/setting.go index a41e494db9b54..b4af0e5ccd684 100644 --- a/models/user/setting.go +++ b/models/user/setting.go @@ -59,9 +59,9 @@ func genSettingCacheKey(userID int64, key string) string { } // GetSetting returns the setting value via the key -func GetSetting(uid int64, key string) (string, error) { +func GetSetting(ctx context.Context, uid int64, key string) (string, error) { return cache.GetString(genSettingCacheKey(uid, key), func() (string, error) { - res, err := GetSettingNoCache(uid, key) + res, err := GetSettingNoCache(ctx, uid, key) if err != nil { return "", err } @@ -70,8 +70,8 @@ func GetSetting(uid int64, key string) (string, error) { } // GetSettingNoCache returns specific setting without using the cache -func GetSettingNoCache(uid int64, key string) (*Setting, error) { - v, err := GetSettings(uid, []string{key}) +func GetSettingNoCache(ctx context.Context, uid int64, key string) (*Setting, error) { + v, err := GetSettings(ctx, uid, []string{key}) if err != nil { return nil, err } @@ -82,9 +82,9 @@ func GetSettingNoCache(uid int64, key string) (*Setting, error) { } // GetSettings returns specific settings from user -func GetSettings(uid int64, keys []string) (map[string]*Setting, error) { +func GetSettings(ctx context.Context, uid int64, keys []string) (map[string]*Setting, error) { settings := make([]*Setting, 0, len(keys)) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("user_id=?", uid). And(builder.In("setting_key", keys)). Find(&settings); err != nil { @@ -98,9 +98,9 @@ func GetSettings(uid int64, keys []string) (map[string]*Setting, error) { } // GetUserAllSettings returns all settings from user -func GetUserAllSettings(uid int64) (map[string]*Setting, error) { +func GetUserAllSettings(ctx context.Context, uid int64) (map[string]*Setting, error) { settings := make([]*Setting, 0, 5) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("user_id=?", uid). Find(&settings); err != nil { return nil, err @@ -123,13 +123,13 @@ func validateUserSettingKey(key string) error { } // GetUserSetting gets a specific setting for a user -func GetUserSetting(userID int64, key string, def ...string) (string, error) { +func GetUserSetting(ctx context.Context, userID int64, key string, def ...string) (string, error) { if err := validateUserSettingKey(key); err != nil { return "", err } setting := &Setting{UserID: userID, SettingKey: key} - has, err := db.GetEngine(db.DefaultContext).Get(setting) + has, err := db.GetEngine(ctx).Get(setting) if err != nil { return "", err } @@ -143,24 +143,24 @@ func GetUserSetting(userID int64, key string, def ...string) (string, error) { } // DeleteUserSetting deletes a specific setting for a user -func DeleteUserSetting(userID int64, key string) error { +func DeleteUserSetting(ctx context.Context, userID int64, key string) error { if err := validateUserSettingKey(key); err != nil { return err } cache.Remove(genSettingCacheKey(userID, key)) - _, err := db.GetEngine(db.DefaultContext).Delete(&Setting{UserID: userID, SettingKey: key}) + _, err := db.GetEngine(ctx).Delete(&Setting{UserID: userID, SettingKey: key}) return err } // SetUserSetting updates a users' setting for a specific key -func SetUserSetting(userID int64, key, value string) error { +func SetUserSetting(ctx context.Context, userID int64, key, value string) error { if err := validateUserSettingKey(key); err != nil { return err } - if err := upsertUserSettingValue(userID, key, value); err != nil { + if err := upsertUserSettingValue(ctx, userID, key, value); err != nil { return err } @@ -172,8 +172,8 @@ func SetUserSetting(userID int64, key, value string) error { return nil } -func upsertUserSettingValue(userID int64, key, value string) error { - return db.WithTx(db.DefaultContext, func(ctx context.Context) error { +func upsertUserSettingValue(ctx context.Context, userID int64, key, value string) error { + return db.WithTx(ctx, func(ctx context.Context) error { e := db.GetEngine(ctx) // here we use a general method to do a safe upsert for different databases (and most transaction levels) diff --git a/models/user/setting_test.go b/models/user/setting_test.go index d0d612d25daf4..c56fe93075042 100644 --- a/models/user/setting_test.go +++ b/models/user/setting_test.go @@ -6,6 +6,7 @@ package user_test import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -19,41 +20,41 @@ func TestSettings(t *testing.T) { newSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Gitea User Setting Test"} // create setting - err := user_model.SetUserSetting(newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) + err := user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) assert.NoError(t, err) // test about saving unchanged values - err = user_model.SetUserSetting(newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) + err = user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) assert.NoError(t, err) // get specific setting - settings, err := user_model.GetSettings(99, []string{keyName}) + settings, err := user_model.GetSettings(db.DefaultContext, 99, []string{keyName}) assert.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, newSetting.SettingValue, settings[keyName].SettingValue) - settingValue, err := user_model.GetUserSetting(99, keyName) + settingValue, err := user_model.GetUserSetting(db.DefaultContext, 99, keyName) assert.NoError(t, err) assert.EqualValues(t, newSetting.SettingValue, settingValue) - settingValue, err = user_model.GetUserSetting(99, "no_such") + settingValue, err = user_model.GetUserSetting(db.DefaultContext, 99, "no_such") assert.NoError(t, err) assert.EqualValues(t, "", settingValue) // updated setting updatedSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Updated"} - err = user_model.SetUserSetting(updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue) + err = user_model.SetUserSetting(db.DefaultContext, updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue) assert.NoError(t, err) // get all settings - settings, err = user_model.GetUserAllSettings(99) + settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99) assert.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, updatedSetting.SettingValue, settings[updatedSetting.SettingKey].SettingValue) // delete setting - err = user_model.DeleteUserSetting(99, keyName) + err = user_model.DeleteUserSetting(db.DefaultContext, 99, keyName) assert.NoError(t, err) - settings, err = user_model.GetUserAllSettings(99) + settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99) assert.NoError(t, err) assert.Len(t, settings, 0) } diff --git a/modules/activitypub/client.go b/modules/activitypub/client.go index fa1b57638f3c4..66b977c01fbe6 100644 --- a/modules/activitypub/client.go +++ b/modules/activitypub/client.go @@ -5,6 +5,7 @@ package activitypub import ( "bytes" + "context" "crypto/rsa" "crypto/x509" "encoding/pem" @@ -61,14 +62,14 @@ type Client struct { } // NewClient function -func NewClient(user *user_model.User, pubID string) (c *Client, err error) { +func NewClient(ctx context.Context, user *user_model.User, pubID string) (c *Client, err error) { if err = containsRequiredHTTPHeaders(http.MethodGet, setting.Federation.GetHeaders); err != nil { return nil, err } else if err = containsRequiredHTTPHeaders(http.MethodPost, setting.Federation.PostHeaders); err != nil { return nil, err } - priv, err := GetPrivateKey(user) + priv, err := GetPrivateKey(ctx, user) if err != nil { return nil, err } diff --git a/modules/activitypub/client_test.go b/modules/activitypub/client_test.go index 83000b96d5b27..65ea8d4d5bf70 100644 --- a/modules/activitypub/client_test.go +++ b/modules/activitypub/client_test.go @@ -11,6 +11,7 @@ import ( "regexp" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" @@ -22,7 +23,7 @@ func TestActivityPubSignedPost(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) pubID := "https://example.com/pubID" - c, err := NewClient(user, pubID) + c, err := NewClient(db.DefaultContext, user, pubID) assert.NoError(t, err) expected := "BODY" diff --git a/modules/activitypub/user_settings.go b/modules/activitypub/user_settings.go index ef9bc0a864b60..d196a3806e7c4 100644 --- a/modules/activitypub/user_settings.go +++ b/modules/activitypub/user_settings.go @@ -4,6 +4,8 @@ package activitypub import ( + "context" + user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/util" ) @@ -11,19 +13,19 @@ import ( const rsaBits = 3072 // GetKeyPair function returns a user's private and public keys -func GetKeyPair(user *user_model.User) (pub, priv string, err error) { +func GetKeyPair(ctx context.Context, user *user_model.User) (pub, priv string, err error) { var settings map[string]*user_model.Setting - settings, err = user_model.GetSettings(user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) + settings, err = user_model.GetSettings(ctx, user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) if err != nil { return pub, priv, err } else if len(settings) == 0 { if priv, pub, err = util.GenerateKeyPair(rsaBits); err != nil { return pub, priv, err } - if err = user_model.SetUserSetting(user.ID, user_model.UserActivityPubPrivPem, priv); err != nil { + if err = user_model.SetUserSetting(ctx, user.ID, user_model.UserActivityPubPrivPem, priv); err != nil { return pub, priv, err } - if err = user_model.SetUserSetting(user.ID, user_model.UserActivityPubPubPem, pub); err != nil { + if err = user_model.SetUserSetting(ctx, user.ID, user_model.UserActivityPubPubPem, pub); err != nil { return pub, priv, err } return pub, priv, err @@ -35,13 +37,13 @@ func GetKeyPair(user *user_model.User) (pub, priv string, err error) { } // GetPublicKey function returns a user's public key -func GetPublicKey(user *user_model.User) (pub string, err error) { - pub, _, err = GetKeyPair(user) +func GetPublicKey(ctx context.Context, user *user_model.User) (pub string, err error) { + pub, _, err = GetKeyPair(ctx, user) return pub, err } // GetPrivateKey function returns a user's private key -func GetPrivateKey(user *user_model.User) (priv string, err error) { - _, priv, err = GetKeyPair(user) +func GetPrivateKey(ctx context.Context, user *user_model.User) (priv string, err error) { + _, priv, err = GetKeyPair(ctx, user) return priv, err } diff --git a/modules/activitypub/user_settings_test.go b/modules/activitypub/user_settings_test.go index 78ebf8e824e3e..2d77906521b8f 100644 --- a/modules/activitypub/user_settings_test.go +++ b/modules/activitypub/user_settings_test.go @@ -6,6 +6,7 @@ package activitypub import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -17,12 +18,12 @@ import ( func TestUserSettings(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - pub, priv, err := GetKeyPair(user1) + pub, priv, err := GetKeyPair(db.DefaultContext, user1) assert.NoError(t, err) - pub1, err := GetPublicKey(user1) + pub1, err := GetPublicKey(db.DefaultContext, user1) assert.NoError(t, err) assert.Equal(t, pub, pub1) - priv1, err := GetPrivateKey(user1) + priv1, err := GetPrivateKey(db.DefaultContext, user1) assert.NoError(t, err) assert.Equal(t, priv, priv1) } diff --git a/modules/context/api.go b/modules/context/api.go index 58532b883dde0..044ec51b56599 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -212,7 +212,7 @@ func (ctx *APIContext) CheckForOTP() { } otpHeader := ctx.Req.Header.Get("X-Gitea-OTP") - twofa, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + twofa, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { return // No 2FA enrollment for this user diff --git a/modules/context/repo.go b/modules/context/repo.go index 126196b0d3754..f9c966d5be9c1 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -598,7 +598,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { } if ctx.IsSigned { - ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx.Doer.ID, repo.ID) + ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx, ctx.Doer.ID, repo.ID) ctx.Data["IsStaringRepo"] = repo_model.IsStaring(ctx, ctx.Doer.ID, repo.ID) } diff --git a/routers/api/packages/alpine/alpine.go b/routers/api/packages/alpine/alpine.go index 51a5c784e0280..d499244dc3e66 100644 --- a/routers/api/packages/alpine/alpine.go +++ b/routers/api/packages/alpine/alpine.go @@ -31,7 +31,7 @@ func apiError(ctx *context.Context, status int, obj any) { } func GetRepositoryKey(ctx *context.Context) { - _, pub, err := alpine_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) + _, pub, err := alpine_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID) if err != nil { apiError(ctx, http.StatusInternalServerError, err) return diff --git a/routers/api/packages/chef/auth.go b/routers/api/packages/chef/auth.go index 53055bb6829e0..3aef8281a4ee9 100644 --- a/routers/api/packages/chef/auth.go +++ b/routers/api/packages/chef/auth.go @@ -4,6 +4,7 @@ package chef import ( + "context" "crypto" "crypto/rsa" "crypto/sha1" @@ -63,7 +64,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return nil, nil } - pub, err := getUserPublicKey(u) + pub, err := getUserPublicKey(req.Context(), u) if err != nil { return nil, err } @@ -93,8 +94,8 @@ func getUserFromRequest(req *http.Request) (*user_model.User, error) { return user_model.GetUserByName(req.Context(), username) } -func getUserPublicKey(u *user_model.User) (crypto.PublicKey, error) { - pubKey, err := user_model.GetSetting(u.ID, chef_module.SettingPublicPem) +func getUserPublicKey(ctx context.Context, u *user_model.User) (crypto.PublicKey, error) { + pubKey, err := user_model.GetSetting(ctx, u.ID, chef_module.SettingPublicPem) if err != nil { return nil, err } diff --git a/routers/api/packages/debian/debian.go b/routers/api/packages/debian/debian.go index 04ca2ed977c70..869bc1e901545 100644 --- a/routers/api/packages/debian/debian.go +++ b/routers/api/packages/debian/debian.go @@ -30,7 +30,7 @@ func apiError(ctx *context.Context, status int, obj any) { } func GetRepositoryKey(ctx *context.Context) { - _, pub, err := debian_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) + _, pub, err := debian_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID) if err != nil { apiError(ctx, http.StatusInternalServerError, err) return diff --git a/routers/api/packages/nuget/auth.go b/routers/api/packages/nuget/auth.go index 60b81b8d4b388..1bb68d059b2a5 100644 --- a/routers/api/packages/nuget/auth.go +++ b/routers/api/packages/nuget/auth.go @@ -23,7 +23,7 @@ func (a *Auth) Name() string { // https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#request-parameters func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataStore, sess auth.SessionStore) (*user_model.User, error) { - token, err := auth_model.GetAccessTokenBySHA(req.Header.Get("X-NuGet-ApiKey")) + token, err := auth_model.GetAccessTokenBySHA(req.Context(), req.Header.Get("X-NuGet-ApiKey")) if err != nil { if !(auth_model.IsErrAccessTokenNotExist(err) || auth_model.IsErrAccessTokenEmpty(err)) { log.Error("GetAccessTokenBySHA: %v", err) @@ -39,7 +39,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS } token.UpdatedUnix = timeutil.TimeStampNow() - if err := auth_model.UpdateAccessToken(token); err != nil { + if err := auth_model.UpdateAccessToken(req.Context(), token); err != nil { log.Error("UpdateAccessToken: %v", err) } diff --git a/routers/api/packages/rpm/rpm.go b/routers/api/packages/rpm/rpm.go index 1e462bb9080f4..65b7c74bdd355 100644 --- a/routers/api/packages/rpm/rpm.go +++ b/routers/api/packages/rpm/rpm.go @@ -45,7 +45,7 @@ gpgkey=`+url+`/repository.key`) // Gets or creates the PGP public key used to sign repository metadata files func GetRepositoryKey(ctx *context.Context) { - _, pub, err := rpm_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) + _, pub, err := rpm_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID) if err != nil { apiError(ctx, http.StatusInternalServerError, err) return diff --git a/routers/api/v1/activitypub/person.go b/routers/api/v1/activitypub/person.go index bc6b82b179921..cad5032d103c9 100644 --- a/routers/api/v1/activitypub/person.go +++ b/routers/api/v1/activitypub/person.go @@ -66,7 +66,7 @@ func Person(ctx *context.APIContext) { person.PublicKey.ID = ap.IRI(link + "#main-key") person.PublicKey.Owner = ap.IRI(link) - publicKeyPem, err := activitypub.GetPublicKey(ctx.ContextUser) + publicKeyPem, err := activitypub.GetPublicKey(ctx, ctx.ContextUser) if err != nil { ctx.ServerError("GetPublicKey", err) return diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index fd7d3687acbc4..ca74a23a4b89e 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -776,7 +776,7 @@ func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.APIC if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) { return // Skip 2FA } - twofa, err := auth_model.GetTwoFactorByUID(ctx.Doer.ID) + twofa, err := auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth_model.IsErrTwoFactorNotEnrolled(err) { return // No 2FA enrollment for this user diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index 944fd763ca2c1..519572ee51882 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -693,7 +693,7 @@ func AddTeamRepository(ctx *context.APIContext) { ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository") return } - if err := org_service.TeamAddRepository(ctx.Org.Team, repo); err != nil { + if err := org_service.TeamAddRepository(ctx, ctx.Org.Team, repo); err != nil { ctx.Error(http.StatusInternalServerError, "TeamAddRepository", err) return } diff --git a/routers/api/v1/repo/issue_attachment.go b/routers/api/v1/repo/issue_attachment.go index c689e70a085b9..60e554990f864 100644 --- a/routers/api/v1/repo/issue_attachment.go +++ b/routers/api/v1/repo/issue_attachment.go @@ -189,7 +189,7 @@ func CreateIssueAttachment(ctx *context.APIContext) { issue.Attachments = append(issue.Attachments, attachment) - if err := issue_service.ChangeContent(issue, ctx.Doer, issue.Content); err != nil { + if err := issue_service.ChangeContent(ctx, issue, ctx.Doer, issue.Content); err != nil { ctx.Error(http.StatusInternalServerError, "ChangeContent", err) return } @@ -298,7 +298,7 @@ func DeleteIssueAttachment(ctx *context.APIContext) { return } - if err := repo_model.DeleteAttachment(attachment, true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attachment, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } diff --git a/routers/api/v1/repo/issue_comment_attachment.go b/routers/api/v1/repo/issue_comment_attachment.go index 121e3f10e0dff..c30e8278dbc98 100644 --- a/routers/api/v1/repo/issue_comment_attachment.go +++ b/routers/api/v1/repo/issue_comment_attachment.go @@ -303,7 +303,7 @@ func DeleteIssueCommentAttachment(ctx *context.APIContext) { return } - if err := repo_model.DeleteAttachment(attach, true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attach, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 0fe657d245271..4f22a059a13c6 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -97,7 +97,7 @@ func ListPullRequests(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - prs, maxResults, err := issues_model.PullRequests(ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{ + prs, maxResults, err := issues_model.PullRequests(ctx, ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{ ListOptions: listOptions, State: ctx.FormTrim("state"), SortType: ctx.FormTrim("sort"), diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index 9571c8ebb90e4..e1421831287f5 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -345,7 +345,7 @@ func DeleteReleaseAttachment(ctx *context.APIContext) { } // FIXME Should prove the existence of the given repo, but results in unnecessary database requests - if err := repo_model.DeleteAttachment(attach, true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attach, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go index fccc76b518745..05227e33a0c61 100644 --- a/routers/api/v1/repo/star.go +++ b/routers/api/v1/repo/star.go @@ -45,7 +45,7 @@ func ListStargazers(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - stargazers, err := repo_model.GetStargazers(ctx.Repo.Repository, utils.GetListOptions(ctx)) + stargazers, err := repo_model.GetStargazers(ctx, ctx.Repo.Repository, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetStargazers", err) return diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index 61d9470707f00..05509fc4435c9 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -45,7 +45,7 @@ func ListSubscribers(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - subscribers, err := repo_model.GetRepoWatchers(ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) + subscribers, err := repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetRepoWatchers", err) return diff --git a/routers/api/v1/repo/teams.go b/routers/api/v1/repo/teams.go index 2887e89603640..1bacc7121187b 100644 --- a/routers/api/v1/repo/teams.go +++ b/routers/api/v1/repo/teams.go @@ -99,7 +99,7 @@ func IsTeam(ctx *context.APIContext) { return } - if repo_service.HasRepository(team, ctx.Repo.Repository.ID) { + if repo_service.HasRepository(ctx, team, ctx.Repo.Repository.ID) { apiTeam, err := convert.ToTeam(ctx, team) if err != nil { ctx.InternalServerError(err) @@ -198,14 +198,14 @@ func changeRepoTeam(ctx *context.APIContext, add bool) { return } - repoHasTeam := repo_service.HasRepository(team, ctx.Repo.Repository.ID) + repoHasTeam := repo_service.HasRepository(ctx, team, ctx.Repo.Repository.ID) var err error if add { if repoHasTeam { ctx.Error(http.StatusUnprocessableEntity, "alreadyAdded", fmt.Errorf("team '%s' is already added to repo", team.Name)) return } - err = org_service.TeamAddRepository(team, ctx.Repo.Repository) + err = org_service.TeamAddRepository(ctx, team, ctx.Repo.Repository) } else { if !repoHasTeam { ctx.Error(http.StatusUnprocessableEntity, "notAdded", fmt.Errorf("team '%s' was not added to repo", team.Name)) diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index f89d53945fa0b..e512ba9e4bd96 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -46,12 +46,12 @@ func ListAccessTokens(ctx *context.APIContext) { opts := auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID, ListOptions: utils.GetListOptions(ctx)} - count, err := auth_model.CountAccessTokens(opts) + count, err := auth_model.CountAccessTokens(ctx, opts) if err != nil { ctx.InternalServerError(err) return } - tokens, err := auth_model.ListAccessTokens(opts) + tokens, err := auth_model.ListAccessTokens(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -103,7 +103,7 @@ func CreateAccessToken(ctx *context.APIContext) { Name: form.Name, } - exist, err := auth_model.AccessTokenByNameExists(t) + exist, err := auth_model.AccessTokenByNameExists(ctx, t) if err != nil { ctx.InternalServerError(err) return @@ -120,7 +120,7 @@ func CreateAccessToken(ctx *context.APIContext) { } t.Scope = scope - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { ctx.Error(http.StatusInternalServerError, "NewAccessToken", err) return } @@ -162,7 +162,7 @@ func DeleteAccessToken(ctx *context.APIContext) { tokenID, _ := strconv.ParseInt(token, 0, 64) if tokenID == 0 { - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{ + tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{ Name: token, UserID: ctx.Doer.ID, }) @@ -187,7 +187,7 @@ func DeleteAccessToken(ctx *context.APIContext) { return } - if err := auth_model.DeleteAccessTokenByID(tokenID, ctx.Doer.ID); err != nil { + if err := auth_model.DeleteAccessTokenByID(ctx, tokenID, ctx.Doer.ID); err != nil { if auth_model.IsErrAccessTokenNotExist(err) { ctx.NotFound() } else { diff --git a/routers/api/v1/user/star.go b/routers/api/v1/user/star.go index 09f799cc6abb1..2659789ddd90c 100644 --- a/routers/api/v1/user/star.go +++ b/routers/api/v1/user/star.go @@ -155,7 +155,7 @@ func Star(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true) + err := repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true) if err != nil { ctx.Error(http.StatusInternalServerError, "StarRepo", err) return @@ -185,7 +185,7 @@ func Unstar(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false) + err := repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) if err != nil { ctx.Error(http.StatusInternalServerError, "StarRepo", err) return diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index b5899baa937eb..7f531eafaa6be 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -124,7 +124,7 @@ func IsWatching(ctx *context.APIContext) { // "404": // description: User is not watching this repo or repo do not exist - if repo_model.IsWatching(ctx.Doer.ID, ctx.Repo.Repository.ID) { + if repo_model.IsWatching(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID) { ctx.JSON(http.StatusOK, api.WatchInfo{ Subscribed: true, Ignored: false, diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 0414a60e18013..5562cc390c1f5 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -238,7 +238,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User { } ctx.Data["Sources"] = sources - hasTOTP, err := auth.HasTwoFactorByUID(u.ID) + hasTOTP, err := auth.HasTwoFactorByUID(ctx, u.ID) if err != nil { ctx.ServerError("auth.HasTwoFactorByUID", err) return nil @@ -410,12 +410,12 @@ func EditUserPost(ctx *context.Context) { } if form.Reset2FA { - tf, err := auth.GetTwoFactorByUID(u.ID) + tf, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("auth.GetTwoFactorByUID", err) return } else if tf != nil { - if err := auth.DeleteTwoFactorByID(tf.ID, u.ID); err != nil { + if err := auth.DeleteTwoFactorByID(ctx, tf.ID, u.ID); err != nil { ctx.ServerError("auth.DeleteTwoFactorByID", err) return } diff --git a/routers/web/auth/2fa.go b/routers/web/auth/2fa.go index 4791b043131db..31ede82f010fa 100644 --- a/routers/web/auth/2fa.go +++ b/routers/web/auth/2fa.go @@ -53,7 +53,7 @@ func TwoFactorPost(ctx *context.Context) { } id := idSess.(int64) - twofa, err := auth.GetTwoFactorByUID(id) + twofa, err := auth.GetTwoFactorByUID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -83,7 +83,7 @@ func TwoFactorPost(ctx *context.Context) { } twofa.LastUsedPasscode = form.Passcode - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("UserSignIn", err) return } @@ -126,7 +126,7 @@ func TwoFactorScratchPost(ctx *context.Context) { } id := idSess.(int64) - twofa, err := auth.GetTwoFactorByUID(id) + twofa, err := auth.GetTwoFactorByUID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -140,7 +140,7 @@ func TwoFactorScratchPost(ctx *context.Context) { ctx.ServerError("UserSignIn", err) return } - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("UserSignIn", err) return } diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index f8549f68f614a..b7a73e43796e2 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -236,7 +236,7 @@ func SignInPost(ctx *context.Context) { // If this user is enrolled in 2FA TOTP, we can't sign the user in just yet. // Instead, redirect them to the 2FA authentication page. - hasTOTPtwofa, err := auth.HasTwoFactorByUID(u.ID) + hasTOTPtwofa, err := auth.HasTwoFactorByUID(ctx, u.ID) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index e6791cafcee82..745b4e818cb2e 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -157,7 +157,7 @@ func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, r // If this user is enrolled in 2FA, we can't sign the user in just yet. // Instead, redirect them to the 2FA authentication page. // We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here - _, err := auth.GetTwoFactorByUID(u.ID) + _, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil { if !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("UserLinkAccount", err) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 178ae8436633c..640c01e203b49 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -1097,7 +1097,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model needs2FA := false if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA { - _, err := auth.GetTwoFactorByUID(u.ID) + _, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index 970d316300bea..bdfa8c40258f3 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -120,7 +120,7 @@ func commonResetPassword(ctx *context.Context) (*user_model.User, *auth.TwoFacto return nil, nil } - twofa, err := auth.GetTwoFactorByUID(u.ID) + twofa, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil { if !auth.IsErrTwoFactorNotEnrolled(err) { ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error()) @@ -217,7 +217,7 @@ func ResetPasswdPost(ctx *context.Context) { } twofa.LastUsedPasscode = passcode - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err) return } @@ -249,7 +249,7 @@ func ResetPasswdPost(ctx *context.Context) { ctx.ServerError("UserSignIn", err) return } - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("UserSignIn", err) return } diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index 46ca68b61258e..dfb87b28f8987 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -247,7 +247,7 @@ func TeamsRepoAction(ctx *context.Context) { ctx.ServerError("GetRepositoryByName", err) return } - err = org_service.TeamAddRepository(ctx.Org.Team, repo) + err = org_service.TeamAddRepository(ctx, ctx.Org.Team, repo) case "remove": err = repo_service.RemoveRepositoryFromTeam(ctx, ctx.Org.Team, ctx.FormInt64("repoid")) case "addall": diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go index b7be77914f045..7b7fa9e994ce4 100644 --- a/routers/web/repo/attachment.go +++ b/routers/web/repo/attachment.go @@ -77,7 +77,7 @@ func DeleteAttachment(ctx *context.Context) { ctx.Error(http.StatusForbidden) return } - err = repo_model.DeleteAttachment(attach, true) + err = repo_model.DeleteAttachment(ctx, attach, true) if err != nil { ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteAttachment: %v", err)) return @@ -122,7 +122,7 @@ func ServeAttachment(ctx *context.Context, uuid string) { } } - if err := attach.IncreaseDownloadCount(); err != nil { + if err := attach.IncreaseDownloadCount(ctx); err != nil { ctx.ServerError("IncreaseDownloadCount", err) return } diff --git a/routers/web/repo/editor.go b/routers/web/repo/editor.go index b053e3c63f4a7..0a606582e583b 100644 --- a/routers/web/repo/editor.go +++ b/routers/web/repo/editor.go @@ -812,7 +812,7 @@ func UploadFileToServer(ctx *context.Context) { return } - upload, err := repo_model.NewUpload(name, buf, file) + upload, err := repo_model.NewUpload(ctx, name, buf, file) if err != nil { ctx.Error(http.StatusInternalServerError, fmt.Sprintf("NewUpload: %v", err)) return @@ -832,7 +832,7 @@ func RemoveUploadFileFromServer(ctx *context.Context) { return } - if err := repo_model.DeleteUploadByUUID(form.File); err != nil { + if err := repo_model.DeleteUploadByUUID(ctx, form.File); err != nil { ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteUploadByUUID: %v", err)) return } diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index c8ecb3b1d8ad7..1fd784a40a0b9 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -158,7 +158,7 @@ func httpBase(ctx *context.Context) *serviceHandler { } if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && ctx.Data["IsActionsToken"] != true { - _, err = auth_model.GetTwoFactorByUID(ctx.Doer.ID) + _, err = auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err == nil { // TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page") diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 820c5d723346d..94c9382f23b38 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -1975,7 +1975,7 @@ func ViewIssue(ctx *context.Context) { var hiddenCommentTypes *big.Int if ctx.IsSigned { - val, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) + val, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) if err != nil { ctx.ServerError("GetUserSetting", err) return @@ -2205,7 +2205,7 @@ func UpdateIssueContent(ctx *context.Context) { return } - if err := issue_service.ChangeContent(issue, ctx.Doer, ctx.Req.FormValue("content")); err != nil { + if err := issue_service.ChangeContent(ctx, issue, ctx.Doer, ctx.Req.FormValue("content")); err != nil { ctx.ServerError("ChangeContent", err) return } @@ -3451,7 +3451,7 @@ func updateAttachments(ctx *context.Context, item any, files []string) error { if util.SliceContainsString(files, attachments[i].UUID) { continue } - if err := repo_model.DeleteAttachment(attachments[i], true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attachments[i], true); err != nil { return err } } diff --git a/routers/web/repo/middlewares.go b/routers/web/repo/middlewares.go index 5efc1a82b3825..b50e96be3c4ca 100644 --- a/routers/web/repo/middlewares.go +++ b/routers/web/repo/middlewares.go @@ -72,12 +72,12 @@ func SetWhitespaceBehavior(ctx *context.Context) { whitespaceBehavior = defaultWhitespaceBehavior } if ctx.IsSigned { - userWhitespaceBehavior, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, defaultWhitespaceBehavior) + userWhitespaceBehavior, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, defaultWhitespaceBehavior) if err == nil { if whitespaceBehavior == "" { whitespaceBehavior = userWhitespaceBehavior } else if whitespaceBehavior != userWhitespaceBehavior { - _ = user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, whitespaceBehavior) + _ = user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, whitespaceBehavior) } } // else: we can ignore the error safely } @@ -98,7 +98,7 @@ func SetShowOutdatedComments(ctx *context.Context) { if showOutdatedCommentsValue != "true" && showOutdatedCommentsValue != "false" { // invalid or no value for this form string -> use default or stored user setting if ctx.IsSigned { - showOutdatedCommentsValue, _ = user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, "false") + showOutdatedCommentsValue, _ = user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, "false") } else { // not logged in user -> use the default value showOutdatedCommentsValue = "false" @@ -106,7 +106,7 @@ func SetShowOutdatedComments(ctx *context.Context) { } else { // valid value -> update user setting if user is logged in if ctx.IsSigned { - _ = user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, showOutdatedCommentsValue) + _ = user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, showOutdatedCommentsValue) } } diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 7772799557814..799c2268de867 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -308,9 +308,9 @@ func Action(ctx *context.Context) { case "unwatch": err = repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) case "star": - err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true) + err = repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true) case "unstar": - err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false) + err = repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) case "accept_transfer": err = acceptOrRejectRepoTransfer(ctx, true) case "reject_transfer": diff --git a/routers/web/repo/setting/collaboration.go b/routers/web/repo/setting/collaboration.go index 212b0346bc758..1e71d33c08d41 100644 --- a/routers/web/repo/setting/collaboration.go +++ b/routers/web/repo/setting/collaboration.go @@ -173,7 +173,7 @@ func AddTeamPost(ctx *context.Context) { return } - if err = org_service.TeamAddRepository(team, ctx.Repo.Repository); err != nil { + if err = org_service.TeamAddRepository(ctx, team, ctx.Repo.Repository); err != nil { ctx.ServerError("TeamAddRepository", err) return } diff --git a/routers/web/repo/setting/settings_test.go b/routers/web/repo/setting/settings_test.go index 55f292f143628..066d2ef2a9f03 100644 --- a/routers/web/repo/setting/settings_test.go +++ b/routers/web/repo/setting/settings_test.go @@ -8,6 +8,7 @@ import ( "testing" asymkey_model "code.gitea.io/gitea/models/asymkey" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" @@ -248,7 +249,7 @@ func TestAddTeamPost(t *testing.T) { AddTeamPost(ctx) - assert.True(t, repo_service.HasRepository(team, re.ID)) + assert.True(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.Empty(t, ctx.Flash.ErrorMsg) } @@ -288,7 +289,7 @@ func TestAddTeamPost_NotAllowed(t *testing.T) { AddTeamPost(ctx) - assert.False(t, repo_service.HasRepository(team, re.ID)) + assert.False(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.NotEmpty(t, ctx.Flash.ErrorMsg) } @@ -329,7 +330,7 @@ func TestAddTeamPost_AddTeamTwice(t *testing.T) { AddTeamPost(ctx) AddTeamPost(ctx) - assert.True(t, repo_service.HasRepository(team, re.ID)) + assert.True(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.NotEmpty(t, ctx.Flash.ErrorMsg) } @@ -402,5 +403,5 @@ func TestDeleteTeam(t *testing.T) { DeleteTeam(ctx) - assert.False(t, repo_service.HasRepository(team, re.ID)) + assert.False(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) } diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 540a82e8650a0..26e9cedd3ab65 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -1065,7 +1065,7 @@ func Watchers(ctx *context.Context) { ctx.Data["PageIsWatchers"] = true RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) { - return repo_model.GetRepoWatchers(ctx.Repo.Repository.ID, opts) + return repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, opts) }, tplWatchers) } @@ -1075,7 +1075,7 @@ func Stars(ctx *context.Context) { ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers") ctx.Data["PageIsStargazers"] = true RenderUserCards(ctx, ctx.Repo.Repository.NumStars, func(opts db.ListOptions) ([]*user_model.User, error) { - return repo_model.GetStargazers(ctx.Repo.Repository, opts) + return repo_model.GetStargazers(ctx, ctx.Repo.Repository, opts) }, tplWatchers) } diff --git a/routers/web/shared/user/header.go b/routers/web/shared/user/header.go index 6273e11fc5ba9..649537ec63521 100644 --- a/routers/web/shared/user/header.go +++ b/routers/web/shared/user/header.go @@ -34,7 +34,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) { ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail && ctx.ContextUser.Email != "" && ctx.IsSigned && !ctx.ContextUser.KeepEmailPrivate // Show OpenID URIs - openIDs, err := user_model.GetUserOpenIDs(ctx.ContextUser.ID) + openIDs, err := user_model.GetUserOpenIDs(ctx, ctx.ContextUser.ID) if err != nil { ctx.ServerError("GetUserOpenIDs", err) return diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index 088aba38b6925..ee44d48dce566 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -53,7 +53,7 @@ func ApplicationsPost(ctx *context.Context) { Scope: scope, } - exist, err := auth_model.AccessTokenByNameExists(t) + exist, err := auth_model.AccessTokenByNameExists(ctx, t) if err != nil { ctx.ServerError("AccessTokenByNameExists", err) return @@ -64,7 +64,7 @@ func ApplicationsPost(ctx *context.Context) { return } - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { ctx.ServerError("NewAccessToken", err) return } @@ -77,7 +77,7 @@ func ApplicationsPost(ctx *context.Context) { // DeleteApplication response for delete user access token func DeleteApplication(ctx *context.Context) { - if err := auth_model.DeleteAccessTokenByID(ctx.FormInt64("id"), ctx.Doer.ID); err != nil { + if err := auth_model.DeleteAccessTokenByID(ctx, ctx.FormInt64("id"), ctx.Doer.ID); err != nil { ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("settings.delete_token_success")) @@ -88,7 +88,7 @@ func DeleteApplication(ctx *context.Context) { func loadApplicationsData(ctx *context.Context) { ctx.Data["AccessTokenScopePublicOnly"] = auth_model.AccessTokenScopePublicOnly - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) + tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) if err != nil { ctx.ServerError("ListAccessTokens", err) return diff --git a/routers/web/user/setting/packages.go b/routers/web/user/setting/packages.go index 0d2eb14c202d6..34d18f999e23d 100644 --- a/routers/web/user/setting/packages.go +++ b/routers/web/user/setting/packages.go @@ -107,7 +107,7 @@ func RegenerateChefKeyPair(ctx *context.Context) { return } - if err := user_model.SetUserSetting(ctx.Doer.ID, chef_module.SettingPublicPem, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ctx.Doer.ID, chef_module.SettingPublicPem, pub); err != nil { ctx.ServerError("SetUserSetting", err) return } diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index 13c9f0809800b..2aa6619a4995d 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -348,7 +348,7 @@ func Appearance(ctx *context.Context) { ctx.Data["PageIsSettingsAppearance"] = true var hiddenCommentTypes *big.Int - val, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) + val, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) if err != nil { ctx.ServerError("GetUserSetting", err) return @@ -420,7 +420,7 @@ func UpdateUserLang(ctx *context.Context) { // UpdateUserHiddenComments update a user's shown comment types func UpdateUserHiddenComments(ctx *context.Context) { - err := user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes, forms.UserHiddenCommentTypesFromRequest(ctx).String()) + err := user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes, forms.UserHiddenCommentTypesFromRequest(ctx).String()) if err != nil { ctx.ServerError("SetUserSetting", err) return diff --git a/routers/web/user/setting/security/2fa.go b/routers/web/user/setting/security/2fa.go index 0cecb1aa37fef..7858b634ce3c3 100644 --- a/routers/web/user/setting/security/2fa.go +++ b/routers/web/user/setting/security/2fa.go @@ -28,7 +28,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) @@ -44,7 +44,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) { return } - if err = auth.UpdateTwoFactor(t); err != nil { + if err = auth.UpdateTwoFactor(ctx, t); err != nil { ctx.ServerError("SettingsTwoFactor: Failed to UpdateTwoFactor", err) return } @@ -58,7 +58,7 @@ func DisableTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) @@ -68,7 +68,7 @@ func DisableTwoFactor(ctx *context.Context) { return } - if err = auth.DeleteTwoFactorByID(t.ID, ctx.Doer.ID); err != nil { + if err = auth.DeleteTwoFactorByID(ctx, t.ID, ctx.Doer.ID); err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { // There is a potential DB race here - we must have been disabled by another request in the intervening period ctx.Flash.Success(ctx.Tr("settings.twofa_disabled")) @@ -145,7 +145,7 @@ func EnrollTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if t != nil { // already enrolled - we should redirect back! log.Warn("Trying to re-enroll %-v in twofa when already enrolled", ctx.Doer) @@ -171,7 +171,7 @@ func EnrollTwoFactorPost(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if t != nil { // already enrolled ctx.Flash.Error(ctx.Tr("settings.twofa_is_enrolled")) @@ -237,7 +237,7 @@ func EnrollTwoFactorPost(ctx *context.Context) { log.Error("Unable to save changes to the session: %v", err) } - if err = auth.NewTwoFactor(t); err != nil { + if err = auth.NewTwoFactor(ctx, t); err != nil { // FIXME: We need to handle a unique constraint fail here it's entirely possible that another request has beaten us. // If there is a unique constraint fail we should just tolerate the error ctx.ServerError("SettingsTwoFactor: Failed to save two factor", err) diff --git a/routers/web/user/setting/security/openid.go b/routers/web/user/setting/security/openid.go index b5509f570fd6a..9a207e149d1df 100644 --- a/routers/web/user/setting/security/openid.go +++ b/routers/web/user/setting/security/openid.go @@ -44,7 +44,7 @@ func OpenIDPost(ctx *context.Context) { form.Openid = id log.Trace("Normalized id: " + id) - oids, err := user_model.GetUserOpenIDs(ctx.Doer.ID) + oids, err := user_model.GetUserOpenIDs(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetUserOpenIDs", err) return @@ -105,7 +105,7 @@ func settingsOpenIDVerify(ctx *context.Context) { // DeleteOpenID response for delete user's openid func DeleteOpenID(ctx *context.Context) { - if err := user_model.DeleteUserOpenID(&user_model.UserOpenID{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { + if err := user_model.DeleteUserOpenID(ctx, &user_model.UserOpenID{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { ctx.ServerError("DeleteUserOpenID", err) return } @@ -117,7 +117,7 @@ func DeleteOpenID(ctx *context.Context) { // ToggleOpenIDVisibility response for toggle visibility of user's openid func ToggleOpenIDVisibility(ctx *context.Context) { - if err := user_model.ToggleUserOpenIDVisibility(ctx.FormInt64("id")); err != nil { + if err := user_model.ToggleUserOpenIDVisibility(ctx, ctx.FormInt64("id")); err != nil { ctx.ServerError("ToggleUserOpenIDVisibility", err) return } diff --git a/routers/web/user/setting/security/security.go b/routers/web/user/setting/security/security.go index dae9bf950dce7..1ce59fef0905b 100644 --- a/routers/web/user/setting/security/security.go +++ b/routers/web/user/setting/security/security.go @@ -52,7 +52,7 @@ func DeleteAccountLink(ctx *context.Context) { } func loadSecurityData(ctx *context.Context) { - enrolled, err := auth_model.HasTwoFactorByUID(ctx.Doer.ID) + enrolled, err := auth_model.HasTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("SettingsTwoFactor", err) return @@ -66,7 +66,7 @@ func loadSecurityData(ctx *context.Context) { } ctx.Data["WebAuthnCredentials"] = credentials - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) + tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) if err != nil { ctx.ServerError("ListAccessTokens", err) return @@ -113,7 +113,7 @@ func loadSecurityData(ctx *context.Context) { ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names ctx.Data["OAuth2Providers"] = oauth2Providers - openid, err := user_model.GetUserOpenIDs(ctx.Doer.ID) + openid, err := user_model.GetUserOpenIDs(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetUserOpenIDs", err) return diff --git a/services/asymkey/sign.go b/services/asymkey/sign.go index 252277e1bcd64..1598f32165349 100644 --- a/services/asymkey/sign.go +++ b/services/asymkey/sign.go @@ -151,7 +151,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } @@ -187,7 +187,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } @@ -240,7 +240,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } @@ -302,7 +302,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } diff --git a/services/auth/basic.go b/services/auth/basic.go index f3a9a8abce21d..bb9eb7a321636 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -71,7 +71,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } // check oauth2 token - uid := CheckOAuthAccessToken(authToken) + uid := CheckOAuthAccessToken(req.Context(), authToken) if uid != 0 { log.Trace("Basic Authorization: Valid OAuthAccessToken for user[%d]", uid) @@ -86,7 +86,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } // check personal access token - token, err := auth_model.GetAccessTokenBySHA(authToken) + token, err := auth_model.GetAccessTokenBySHA(req.Context(), authToken) if err == nil { log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid) u, err := user_model.GetUserByID(req.Context(), token.UID) @@ -96,7 +96,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } token.UpdatedUnix = timeutil.TimeStampNow() - if err = auth_model.UpdateAccessToken(token); err != nil { + if err = auth_model.UpdateAccessToken(req.Context(), token); err != nil { log.Error("UpdateAccessToken: %v", err) } diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index e621b5ffad713..6572d661e87f9 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -5,13 +5,13 @@ package auth import ( + "context" "net/http" "strings" "time" actions_model "code.gitea.io/gitea/models/actions" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/timeutil" @@ -25,7 +25,7 @@ var ( ) // CheckOAuthAccessToken returns uid of user from oauth token -func CheckOAuthAccessToken(accessToken string) int64 { +func CheckOAuthAccessToken(ctx context.Context, accessToken string) int64 { // JWT tokens require a "." if !strings.Contains(accessToken, ".") { return 0 @@ -36,7 +36,7 @@ func CheckOAuthAccessToken(accessToken string) int64 { return 0 } var grant *auth_model.OAuth2Grant - if grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, token.GrantID); err != nil || grant == nil { + if grant, err = auth_model.GetOAuth2GrantByID(ctx, token.GrantID); err != nil || grant == nil { return 0 } if token.Type != oauth2.TypeAccessToken { @@ -83,21 +83,21 @@ func parseToken(req *http.Request) (string, bool) { // userIDFromToken returns the user id corresponding to the OAuth token. // It will set 'IsApiToken' to true if the token is an API token and // set 'ApiTokenScope' to the scope of the access token -func (o *OAuth2) userIDFromToken(tokenSHA string, store DataStore) int64 { +func (o *OAuth2) userIDFromToken(ctx context.Context, tokenSHA string, store DataStore) int64 { // Let's see if token is valid. if strings.Contains(tokenSHA, ".") { - uid := CheckOAuthAccessToken(tokenSHA) + uid := CheckOAuthAccessToken(ctx, tokenSHA) if uid != 0 { store.GetData()["IsApiToken"] = true store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all } return uid } - t, err := auth_model.GetAccessTokenBySHA(tokenSHA) + t, err := auth_model.GetAccessTokenBySHA(ctx, tokenSHA) if err != nil { if auth_model.IsErrAccessTokenNotExist(err) { // check task token - task, err := actions_model.GetRunningTaskByToken(db.DefaultContext, tokenSHA) + task, err := actions_model.GetRunningTaskByToken(ctx, tokenSHA) if err == nil && task != nil { log.Trace("Basic Authorization: Valid AccessToken for task[%d]", task.ID) @@ -112,7 +112,7 @@ func (o *OAuth2) userIDFromToken(tokenSHA string, store DataStore) int64 { return 0 } t.UpdatedUnix = timeutil.TimeStampNow() - if err = auth_model.UpdateAccessToken(t); err != nil { + if err = auth_model.UpdateAccessToken(ctx, t); err != nil { log.Error("UpdateAccessToken: %v", err) } store.GetData()["IsApiToken"] = true @@ -134,7 +134,7 @@ func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStor return nil, nil } - id := o.userIDFromToken(token, store) + id := o.userIDFromToken(req.Context(), token, store) if id <= 0 && id != -2 { // -2 means actions, so we need to allow it. return nil, user_model.ErrUserNotExist{} diff --git a/services/issue/content.go b/services/issue/content.go index cda11dbb18fc4..41f1bfefe8c4b 100644 --- a/services/issue/content.go +++ b/services/issue/content.go @@ -4,21 +4,22 @@ package issue import ( - "code.gitea.io/gitea/models/db" + "context" + issues_model "code.gitea.io/gitea/models/issues" user_model "code.gitea.io/gitea/models/user" notify_service "code.gitea.io/gitea/services/notify" ) // ChangeContent changes issue content, as the given user. -func ChangeContent(issue *issues_model.Issue, doer *user_model.User, content string) (err error) { +func ChangeContent(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, content string) (err error) { oldContent := issue.Content if err := issues_model.ChangeIssueContent(issue, doer, content); err != nil { return err } - notify_service.IssueChangeContent(db.DefaultContext, doer, issue, oldContent) + notify_service.IssueChangeContent(ctx, doer, issue, oldContent) return nil } diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 878b6d6b8453f..e42d9e928618a 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -113,7 +113,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) assert.Empty(t, issues[0].Comments) - pulls, _, err := issues_model.PullRequests(repo.ID, &issues_model.PullRequestsOptions{ + pulls, _, err := issues_model.PullRequests(db.DefaultContext, repo.ID, &issues_model.PullRequestsOptions{ SortType: "oldest", }) assert.NoError(t, err) diff --git a/services/org/repo.go b/services/org/repo.go index 0edbf2d46487c..78a829ef25952 100644 --- a/services/org/repo.go +++ b/services/org/repo.go @@ -14,14 +14,14 @@ import ( ) // TeamAddRepository adds new repository to team of organization. -func TeamAddRepository(t *organization.Team, repo *repo_model.Repository) (err error) { +func TeamAddRepository(ctx context.Context, t *organization.Team, repo *repo_model.Repository) (err error) { if repo.OwnerID != t.OrgID { return errors.New("repository does not belong to organization") - } else if organization.HasTeamRepo(db.DefaultContext, t.OrgID, t.ID, repo.ID) { + } else if organization.HasTeamRepo(ctx, t.OrgID, t.ID, repo.ID) { return nil } - return db.WithTx(db.DefaultContext, func(ctx context.Context) error { + return db.WithTx(ctx, func(ctx context.Context) error { return models.AddRepository(ctx, t, repo) }) } diff --git a/services/org/repo_test.go b/services/org/repo_test.go index 40b0d17077b6b..68c64a01ab4a7 100644 --- a/services/org/repo_test.go +++ b/services/org/repo_test.go @@ -6,6 +6,7 @@ package org import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -19,7 +20,7 @@ func TestTeam_AddRepository(t *testing.T) { testSuccess := func(teamID, repoID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, TeamAddRepository(team, repo)) + assert.NoError(t, TeamAddRepository(db.DefaultContext, team, repo)) unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) } @@ -28,6 +29,6 @@ func TestTeam_AddRepository(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.Error(t, TeamAddRepository(team, repo)) + assert.Error(t, TeamAddRepository(db.DefaultContext, team, repo)) unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1}) } diff --git a/services/packages/alpine/repository.go b/services/packages/alpine/repository.go index 5264bd6c4a8c4..24e673289a9a2 100644 --- a/services/packages/alpine/repository.go +++ b/services/packages/alpine/repository.go @@ -39,13 +39,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion } // GetOrCreateKeyPair gets or creates the RSA keys used to sign repository files -func GetOrCreateKeyPair(ownerID int64) (string, string, error) { - priv, err := user_model.GetSetting(ownerID, alpine_module.SettingKeyPrivate) +func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) { + priv, err := user_model.GetSetting(ctx, ownerID, alpine_module.SettingKeyPrivate) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } - pub, err := user_model.GetSetting(ownerID, alpine_module.SettingKeyPublic) + pub, err := user_model.GetSetting(ctx, ownerID, alpine_module.SettingKeyPublic) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } @@ -56,11 +56,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) { return "", "", err } - if err := user_model.SetUserSetting(ownerID, alpine_module.SettingKeyPrivate, priv); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, alpine_module.SettingKeyPrivate, priv); err != nil { return "", "", err } - if err := user_model.SetUserSetting(ownerID, alpine_module.SettingKeyPublic, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, alpine_module.SettingKeyPublic, pub); err != nil { return "", "", err } } @@ -244,7 +244,7 @@ func buildPackagesIndex(ctx context.Context, ownerID int64, repoVersion *package return err } - priv, _, err := GetOrCreateKeyPair(ownerID) + priv, _, err := GetOrCreateKeyPair(ctx, ownerID) if err != nil { return err } diff --git a/services/packages/debian/repository.go b/services/packages/debian/repository.go index be82fbed6e76b..46b1a94b81513 100644 --- a/services/packages/debian/repository.go +++ b/services/packages/debian/repository.go @@ -37,13 +37,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion } // GetOrCreateKeyPair gets or creates the PGP keys used to sign repository files -func GetOrCreateKeyPair(ownerID int64) (string, string, error) { - priv, err := user_model.GetSetting(ownerID, debian_module.SettingKeyPrivate) +func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) { + priv, err := user_model.GetSetting(ctx, ownerID, debian_module.SettingKeyPrivate) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } - pub, err := user_model.GetSetting(ownerID, debian_module.SettingKeyPublic) + pub, err := user_model.GetSetting(ctx, ownerID, debian_module.SettingKeyPublic) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } @@ -54,11 +54,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) { return "", "", err } - if err := user_model.SetUserSetting(ownerID, debian_module.SettingKeyPrivate, priv); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, debian_module.SettingKeyPrivate, priv); err != nil { return "", "", err } - if err := user_model.SetUserSetting(ownerID, debian_module.SettingKeyPublic, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, debian_module.SettingKeyPublic, pub); err != nil { return "", "", err } } @@ -306,7 +306,7 @@ func buildReleaseFiles(ctx context.Context, ownerID int64, repoVersion *packages sort.Strings(architectures) - priv, _, err := GetOrCreateKeyPair(ownerID) + priv, _, err := GetOrCreateKeyPair(ctx, ownerID) if err != nil { return err } diff --git a/services/packages/rpm/repository.go b/services/packages/rpm/repository.go index cfd70ec23e2c7..d115197197be5 100644 --- a/services/packages/rpm/repository.go +++ b/services/packages/rpm/repository.go @@ -38,13 +38,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion } // GetOrCreateKeyPair gets or creates the PGP keys used to sign repository metadata files -func GetOrCreateKeyPair(ownerID int64) (string, string, error) { - priv, err := user_model.GetSetting(ownerID, rpm_module.SettingKeyPrivate) +func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) { + priv, err := user_model.GetSetting(ctx, ownerID, rpm_module.SettingKeyPrivate) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } - pub, err := user_model.GetSetting(ownerID, rpm_module.SettingKeyPublic) + pub, err := user_model.GetSetting(ctx, ownerID, rpm_module.SettingKeyPublic) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } @@ -55,11 +55,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) { return "", "", err } - if err := user_model.SetUserSetting(ownerID, rpm_module.SettingKeyPrivate, priv); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, rpm_module.SettingKeyPrivate, priv); err != nil { return "", "", err } - if err := user_model.SetUserSetting(ownerID, rpm_module.SettingKeyPublic, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, rpm_module.SettingKeyPublic, pub); err != nil { return "", "", err } } @@ -212,6 +212,7 @@ func BuildRepositoryFiles(ctx context.Context, ownerID int64) error { } return buildRepomd( + ctx, pv, ownerID, []*repoData{ @@ -223,7 +224,7 @@ func BuildRepositoryFiles(ctx context.Context, ownerID int64) error { } // https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#repomd-xml -func buildRepomd(pv *packages_model.PackageVersion, ownerID int64, data []*repoData) error { +func buildRepomd(ctx context.Context, pv *packages_model.PackageVersion, ownerID int64, data []*repoData) error { type Repomd struct { XMLName xml.Name `xml:"repomd"` Xmlns string `xml:"xmlns,attr"` @@ -241,7 +242,7 @@ func buildRepomd(pv *packages_model.PackageVersion, ownerID int64, data []*repoD return err } - priv, _, err := GetOrCreateKeyPair(ownerID) + priv, _, err := GetOrCreateKeyPair(ctx, ownerID) if err != nil { return err } diff --git a/services/pull/check.go b/services/pull/check.go index dcb488c309fc6..e4a0f6b27bb79 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -303,7 +303,7 @@ func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool { // InitializePullRequests checks and tests untested patches of pull requests. func InitializePullRequests(ctx context.Context) { - prs, err := issues_model.GetPullRequestIDsByCheckStatus(issues_model.PullRequestStatusChecking) + prs, err := issues_model.GetPullRequestIDsByCheckStatus(ctx, issues_model.PullRequestStatusChecking) if err != nil { log.Error("Find Checking PRs: %v", err) return diff --git a/services/repository/create_test.go b/services/repository/create_test.go index 7ffdcc38fb1c5..36065cafff8e0 100644 --- a/services/repository/create_test.go +++ b/services/repository/create_test.go @@ -28,7 +28,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) for i, rid := range repoIds { if rid > 0 { - assert.True(t, HasRepository(team, rid), "%s: HasRepository(%d) %d", rid, i) + assert.True(t, HasRepository(db.DefaultContext, team, rid), "%s: HasRepository(%d) %d", rid, i) } } } diff --git a/services/repository/delete.go b/services/repository/delete.go index 8e28c9b25588b..f2b47814585f8 100644 --- a/services/repository/delete.go +++ b/services/repository/delete.go @@ -286,36 +286,36 @@ func DeleteRepositoryDirectly(ctx context.Context, doer *user_model.User, uid, r // Remove repository files. repoPath := repo.RepoPath() - system_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository files", repoPath) + system_model.RemoveAllWithNotice(ctx, "Delete repository files", repoPath) // Remove wiki files if repo.HasWiki() { - system_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository wiki", repo.WikiPath()) + system_model.RemoveAllWithNotice(ctx, "Delete repository wiki", repo.WikiPath()) } // Remove archives for _, archive := range archivePaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.RepoArchives, "Delete repo archive file", archive) + system_model.RemoveStorageWithNotice(ctx, storage.RepoArchives, "Delete repo archive file", archive) } // Remove lfs objects for _, lfsObj := range lfsPaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.LFS, "Delete orphaned LFS file", lfsObj) + system_model.RemoveStorageWithNotice(ctx, storage.LFS, "Delete orphaned LFS file", lfsObj) } // Remove issue attachment files. for _, attachment := range attachmentPaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete issue attachment", attachment) + system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", attachment) } // Remove release attachment files. for _, releaseAttachment := range releaseAttachments { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete release attachment", releaseAttachment) + system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete release attachment", releaseAttachment) } // Remove attachment with no issue_id and release_id. for _, newAttachment := range newAttachmentPaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete issue attachment", newAttachment) + system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", newAttachment) } if len(repo.Avatar) > 0 { @@ -390,14 +390,14 @@ func removeRepositoryFromTeam(ctx context.Context, t *organization.Team, repo *r } // HasRepository returns true if given repository belong to team. -func HasRepository(t *organization.Team, repoID int64) bool { - return organization.HasTeamRepo(db.DefaultContext, t.OrgID, t.ID, repoID) +func HasRepository(ctx context.Context, t *organization.Team, repoID int64) bool { + return organization.HasTeamRepo(ctx, t.OrgID, t.ID, repoID) } // RemoveRepositoryFromTeam removes repository from team of organization. // If the team shall include all repositories the request is ignored. func RemoveRepositoryFromTeam(ctx context.Context, t *organization.Team, repoID int64) error { - if !HasRepository(t, repoID) { + if !HasRepository(ctx, t, repoID) { return nil } diff --git a/services/repository/delete_test.go b/services/repository/delete_test.go index 2905c01868676..ae5fd53962102 100644 --- a/services/repository/delete_test.go +++ b/services/repository/delete_test.go @@ -19,7 +19,7 @@ func TestTeam_HasRepository(t *testing.T) { test := func(teamID, repoID int64, expected bool) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.Equal(t, expected, HasRepository(team, repoID)) + assert.Equal(t, expected, HasRepository(db.DefaultContext, team, repoID)) } test(1, 1, false) test(1, 3, true) diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index 338811f0f1cff..f4e1da7bb1a35 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -10,7 +10,6 @@ import ( "path" "strings" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -35,13 +34,13 @@ type uploadInfo struct { lfsMetaObject *git_model.LFSMetaObject } -func cleanUpAfterFailure(infos *[]uploadInfo, t *TemporaryUploadRepository, original error) error { +func cleanUpAfterFailure(ctx context.Context, infos *[]uploadInfo, t *TemporaryUploadRepository, original error) error { for _, info := range *infos { if info.lfsMetaObject == nil { continue } if !info.lfsMetaObject.Existing { - if _, err := git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, t.repo.ID, info.lfsMetaObject.Oid); err != nil { + if _, err := git_model.RemoveLFSMetaObjectByOid(ctx, t.repo.ID, info.lfsMetaObject.Oid); err != nil { original = fmt.Errorf("%w, %v", original, err) // We wrap the original error - as this is the underlying error that required the fallback } } @@ -55,7 +54,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return nil } - uploads, err := repo_model.GetUploadsByUUIDs(opts.Files) + uploads, err := repo_model.GetUploadsByUUIDs(ctx, opts.Files) if err != nil { return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %w", opts.Files, err) } @@ -147,7 +146,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use infos[i].lfsMetaObject, err = git_model.NewLFSMetaObject(ctx, infos[i].lfsMetaObject) if err != nil { // OK Now we need to cleanup - return cleanUpAfterFailure(&infos, t, err) + return cleanUpAfterFailure(ctx, &infos, t, err) } // Don't move the files yet - we need to ensure that // everything can be inserted first @@ -158,7 +157,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use contentStore := lfs.NewContentStore() for _, info := range infos { if err := uploadToLFSContentStore(info, contentStore); err != nil { - return cleanUpAfterFailure(&infos, t, err) + return cleanUpAfterFailure(ctx, &infos, t, err) } } @@ -167,7 +166,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return err } - return repo_model.DeleteUploads(uploads...) + return repo_model.DeleteUploads(ctx, uploads...) } func copyUploadedLFSFileIntoRepository(info *uploadInfo, filename2attribute2info map[string]map[string]string, t *TemporaryUploadRepository, treePath string) error { diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go index 1a8a38ce56208..3222dfc807134 100644 --- a/tests/integration/api_activitypub_person_test.go +++ b/tests/integration/api_activitypub_person_test.go @@ -11,6 +11,7 @@ import ( "net/url" "testing" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/activitypub" "code.gitea.io/gitea/modules/setting" @@ -96,7 +97,7 @@ func TestActivityPubPersonInbox(t *testing.T) { user1, err := user_model.GetUserByName(ctx, username1) assert.NoError(t, err) user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL) - c, err := activitypub.NewClient(user1, user1url) + c, err := activitypub.NewClient(db.DefaultContext, user1, user1url) assert.NoError(t, err) user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL) diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 0ee43e1741860..4a1fe2607e4cd 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -83,7 +83,7 @@ kPuCu6vH9brvOuYo0q8hLVNkBeXcimRpsDjLhQYzEJjoMTbaiVGnjBky+PWNiofJ nwIDAQAB -----END PUBLIC KEY-----` - err := user_model.SetUserSetting(user.ID, chef_module.SettingPublicPem, pubPem) + err := user_model.SetUserSetting(db.DefaultContext, user.ID, chef_module.SettingPublicPem, pubPem) assert.NoError(t, err) t.Run("Authenticate", func(t *testing.T) { From 3cd719a63d3ef8125eff87f4759f2be2c7a1ec92 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 15 Sep 2023 14:14:24 +0800 Subject: [PATCH 06/23] Update brew installation documentation since gitea moved to brew core package (#27070) ref: https://gitea.com/gitea/homebrew-gitea/pulls/178 --- docs/content/installation/from-package.en-us.md | 1 - docs/content/installation/from-package.fr-fr.md | 1 - docs/content/installation/from-package.zh-cn.md | 1 - docs/content/installation/from-package.zh-tw.md | 1 - 4 files changed, 4 deletions(-) diff --git a/docs/content/installation/from-package.en-us.md b/docs/content/installation/from-package.en-us.md index 4c29c31efca28..aa559f28336df 100644 --- a/docs/content/installation/from-package.en-us.md +++ b/docs/content/installation/from-package.en-us.md @@ -24,7 +24,6 @@ Following the [deployment from binary](installation/from-binary.md) guide may wo but is not supported. To install Gitea via `brew`: ``` -brew tap gitea/tap https://gitea.com/gitea/homebrew-gitea brew install gitea ``` diff --git a/docs/content/installation/from-package.fr-fr.md b/docs/content/installation/from-package.fr-fr.md index 256c913dcffc6..32e020dc7be34 100644 --- a/docs/content/installation/from-package.fr-fr.md +++ b/docs/content/installation/from-package.fr-fr.md @@ -30,7 +30,6 @@ Nous n'avons pas encore publié de paquet pour Windows, nous allons mettre à jo Actuellement, nous ne supportons que l'installation via `brew` pour macOS. Si vous n'utilisez pas [Homebrew](http://brew.sh/), vous pouvez suivre les [instructions d'installation](installation/from-binary.md) avec le binaire pré-compilé. Pour installer Gitea depuis `brew`, utilisez les commandes suivantes : ``` -brew tap go-gitea/gitea brew install gitea ``` diff --git a/docs/content/installation/from-package.zh-cn.md b/docs/content/installation/from-package.zh-cn.md index 66db4d322d179..929782f23c7e2 100644 --- a/docs/content/installation/from-package.zh-cn.md +++ b/docs/content/installation/from-package.zh-cn.md @@ -22,7 +22,6 @@ menu: macOS 平台下当前我们仅支持通过 `brew` 来安装。如果你没有安装 [Homebrew](http://brew.sh/),你也可以查看 [从二进制安装](installation/from-binary.md)。在你安装了 `brew` 之后, 你可以执行以下命令: ``` -brew tap gitea/tap https://gitea.com/gitea/homebrew-gitea brew install gitea ``` diff --git a/docs/content/installation/from-package.zh-tw.md b/docs/content/installation/from-package.zh-tw.md index 5a417ee202997..8a2de2997d58a 100644 --- a/docs/content/installation/from-package.zh-tw.md +++ b/docs/content/installation/from-package.zh-tw.md @@ -36,7 +36,6 @@ choco install gitea 目前我們只支援透過 `brew` 來安裝套件。假如您尚未使用 [Homebrew](http://brew.sh/),您就必須參考[執行檔安裝](installation/from-binary.md)方式。透過 `brew` 安裝 Gitea,您只需要執行底下指令: ``` -brew tap go-gitea/gitea brew install gitea ``` From e5ec57cd608a81be6e0a6b897b165e9b322ceab4 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 15 Sep 2023 14:43:39 +0800 Subject: [PATCH 07/23] Actions are no longer experimental, so enable them by default (#27054) This PR makes the actions enabled by default, so people will find it easier to enable actions in repository setting. --- custom/conf/app.example.ini | 2 +- docs/content/administration/config-cheat-sheet.en-us.md | 2 +- docs/content/administration/config-cheat-sheet.zh-cn.md | 2 +- modules/setting/actions.go | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index f0b0cc298b6c1..cd6b2a914d237 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -2562,7 +2562,7 @@ LEVEL = Info ; [actions] ;; Enable/Disable actions capabilities -;ENABLED = false +;ENABLED = true ;; ;; Default platform to get action plugins, `github` for `https://github.com`, `self` for the current Gitea instance. ;DEFAULT_ACTIONS_URL = github diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index acfb6ce77e653..aa29f8be4b8ca 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -1384,7 +1384,7 @@ PROXY_HOSTS = *.github.com ## Actions (`actions`) -- `ENABLED`: **false**: Enable/Disable actions capabilities +- `ENABLED`: **true**: Enable/Disable actions capabilities - `DEFAULT_ACTIONS_URL`: **github**: Default platform to get action plugins, `github` for `https://github.com`, `self` for the current Gitea instance. - `STORAGE_TYPE`: **local**: Storage type for actions logs, `local` for local disk or `minio` for s3 compatible object storage service, default is `local` or other name defined with `[storage.xxx]` - `MINIO_BASE_PATH`: **actions_log/**: Minio base path on the bucket only available when STORAGE_TYPE is `minio` diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index b3e7d1024a14c..2849752c0ab5f 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -1331,7 +1331,7 @@ PROXY_HOSTS = *.github.com ## Actions (`actions`) -- `ENABLED`: **false**:启用/禁用操作功能 +- `ENABLED`: **true**:启用/禁用操作功能 - `DEFAULT_ACTIONS_URL`: **github**:获取操作插件的默认平台,`github`表示`https://github.com`,`self`表示当前的 Gitea 实例。 - `STORAGE_TYPE`: **local**:用于操作日志的存储类型,`local`表示本地磁盘,`minio`表示与S3兼容的对象存储服务,默认为`local`,或者使用定义为`[storage.xxx]`的其他名称。 - `MINIO_BASE_PATH`: **actions_log/**:Minio存储桶上的基本路径,仅在`STORAGE_TYPE`为`minio`时可用。 diff --git a/modules/setting/actions.go b/modules/setting/actions.go index bfc502c0cbea5..28c84f01491aa 100644 --- a/modules/setting/actions.go +++ b/modules/setting/actions.go @@ -19,7 +19,7 @@ var ( Enabled bool DefaultActionsURL defaultActionsURL `ini:"DEFAULT_ACTIONS_URL"` }{ - Enabled: false, + Enabled: true, DefaultActionsURL: defaultActionsURLGitHub, } ) From d513628db90415a27e887c3cf349309b3ad44d55 Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Sat, 16 Sep 2023 01:14:36 +0200 Subject: [PATCH 08/23] Allow empty Conan files (#27092) Fixes #27090 Looks like the Conan upload process has changed since last year. The empty uploads don't occur anymore. --- routers/api/packages/conan/conan.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/routers/api/packages/conan/conan.go b/routers/api/packages/conan/conan.go index 58e1642442212..8edbe98b30bf3 100644 --- a/routers/api/packages/conan/conan.go +++ b/routers/api/packages/conan/conan.go @@ -326,13 +326,8 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey } defer buf.Close() - if buf.Size() == 0 { - // ignore empty uploads, second request contains content - jsonResponse(ctx, http.StatusOK, nil) - return - } - isConanfileFile := filename == conanfileFile + isConaninfoFile := filename == conaninfoFile pci := &packages_service.PackageCreationInfo{ PackageInfo: packages_service.PackageInfo{ @@ -364,7 +359,7 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey pfci.Properties[conan_module.PropertyPackageRevision] = pref.RevisionOrDefault() } - if isConanfileFile || filename == conaninfoFile { + if isConanfileFile || isConaninfoFile { if isConanfileFile { metadata, err := conan_module.ParseConanfile(buf) if err != nil { From 684ab403aa89c8df7bcbaef5754f7bed7306c3e1 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Sat, 16 Sep 2023 00:21:59 +0000 Subject: [PATCH 09/23] [skip ci] Updated translations via Crowdin --- options/locale/locale_cs-CZ.ini | 23 ++++++--------- options/locale/locale_de-DE.ini | 23 ++++++--------- options/locale/locale_el-GR.ini | 23 ++++++--------- options/locale/locale_es-ES.ini | 21 +++++-------- options/locale/locale_fa-IR.ini | 20 ++++--------- options/locale/locale_fi-FI.ini | 14 ++++----- options/locale/locale_fr-FR.ini | 23 ++++++--------- options/locale/locale_hu-HU.ini | 14 ++++----- options/locale/locale_id-ID.ini | 13 ++------- options/locale/locale_is-IS.ini | 12 ++++---- options/locale/locale_it-IT.ini | 21 +++++-------- options/locale/locale_ja-JP.ini | 23 ++++++--------- options/locale/locale_ko-KR.ini | 11 +++---- options/locale/locale_lv-LV.ini | 23 ++++++--------- options/locale/locale_nl-NL.ini | 18 ++++-------- options/locale/locale_pl-PL.ini | 20 ++++--------- options/locale/locale_pt-BR.ini | 23 ++++++--------- options/locale/locale_pt-PT.ini | 52 ++++++++++++++++++++++++--------- options/locale/locale_ru-RU.ini | 23 ++++++--------- options/locale/locale_si-LK.ini | 20 ++++--------- options/locale/locale_sk-SK.ini | 12 +++----- options/locale/locale_sv-SE.ini | 15 ++++------ options/locale/locale_tr-TR.ini | 23 ++++++--------- options/locale/locale_uk-UA.ini | 20 ++++--------- options/locale/locale_zh-CN.ini | 23 ++++++--------- options/locale/locale_zh-HK.ini | 9 ++---- options/locale/locale_zh-TW.ini | 23 ++++++--------- 27 files changed, 219 insertions(+), 326 deletions(-) diff --git a/options/locale/locale_cs-CZ.ini b/options/locale/locale_cs-CZ.ini index 819e3e85e87f2..57c1635c1cd76 100644 --- a/options/locale/locale_cs-CZ.ini +++ b/options/locale/locale_cs-CZ.ini @@ -175,7 +175,6 @@ network_error=Chyba sítě [startpage] app_desc=Snadno přístupný vlastní Git install=Jednoduchá na instalaci -install_desc=Jednoduše spusťte binárku pro vaši platformu, nasaďte ji pomocí Docker, nebo ji získejte zbalíčku. platform=Multiplatformní platform_desc=Gitea běží všude, kde Go může kompilovat: Windows, macOS, Linux, ARM, atd. Vyberte si ten, který milujete! lightweight=Lehká @@ -308,6 +307,7 @@ filter_by_team_repositories=Filtrovat podle repozitářů týmu feed_of=Kanál z „%s“ show_archived=Archivováno +archived=Archivováno show_both_archived_unarchived=Zobrazeny jak archivované tak nearchivované show_only_archived=Zobrazeny pouze archivované show_only_unarchived=Zobrazeny pouze nearchivované @@ -574,7 +574,6 @@ overview=Přehled following=Sledovaní follow=Sledovat unfollow=Přestat sledovat -heatmap.loading=Načítání teplotní mapy… user_bio=Životopis disabled_public_activity=Tento uživatel zakázal veřejnou viditelnost aktivity. email_visibility.limited=Vaše e-mailová adresa je viditelná pro všechny ověřené uživatele @@ -644,7 +643,6 @@ choose_new_avatar=Vybrat nový avatar update_avatar=Aktualizovat avatar delete_current_avatar=Smazat aktuální avatar uploaded_avatar_not_a_image=Nahraný soubor není obrázek. -uploaded_avatar_is_too_big=Nahraný soubor překročil maximální velikost. update_avatar_success=Vaše avatar byl aktualizován. update_user_avatar_success=Uživatelův avatar byl aktualizován. @@ -1192,6 +1190,11 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=Vyberte větev pro Cherry-pick na: +commitstatus.error=Chyba +commitstatus.failure=Chyba +commitstatus.pending=Čekající +commitstatus.success=Úspěch + ext_issues=Přístup k externím úkolům ext_issues.desc=Odkaz na externí systém úkolů. @@ -1379,9 +1382,9 @@ issues.ref_reopening_from=`odkazoval/a na požadavek na natažen issues.ref_closed_from=`uzavřel/a tento úkol %[4]s %[2]s` issues.ref_reopened_from=`znovu otevřel/a tento úkol %[4]s %[2]s` issues.ref_from=`z %[1]s` -issues.poster=Autor -issues.collaborator=Spolupracovník -issues.owner=Vlastník +issues.author=Autor +issues.role.owner=Vlastník +issues.role.member=Člen issues.re_request_review=Znovu požádat o posouzení issues.is_stale=Od tohoto posouzení došlo ke změnám v tomto požadavku na natažení issues.remove_request_review=Odstranit žádost o posouzení @@ -1685,8 +1688,6 @@ milestones.modify=Aktualizovat milník milestones.deletion=Smazat milník milestones.deletion_desc=Odstranění milníku jej smaže ze všech souvisejících úkolů. Pokračovat? milestones.deletion_success=Milník byl odstraněn. -milestones.filter_sort.closest_due_date=Nejbližší datum dokončení -milestones.filter_sort.furthest_due_date=Nejvzdálenější datum dokončení milestones.filter_sort.least_complete=Nejméně dokončené milestones.filter_sort.most_complete=Nejvíce dokončené milestones.filter_sort.most_issues=Nejvíce úkolů @@ -2127,7 +2128,6 @@ settings.tags.protection.allowed.teams=Povolené týmy settings.tags.protection.allowed.noone=Nikdo settings.tags.protection.create=Chránit značku settings.tags.protection.none=Neexistují žádné chráněné značky. -settings.tags.protection.pattern.description=Můžete použít jediné jméno nebo vzor glob nebo regulární výraz, který bude odpovídat více značek. Přečtěte si více v průvodci chráněnými značkami. settings.bot_token=Token pro robota settings.chat_id=ID chatu settings.matrix.homeserver_url=URL adresa Homeserveru @@ -2605,12 +2605,10 @@ packages.size=Velikost packages.published=Publikováno defaulthooks=Výchozí webové háčky -defaulthooks.desc=Webové háčky automaticky vytvářejí HTTP POST dotazy na server při určitých Gitea událostech. Webové háčky definované zde jsou výchozí a budou zkopírovány do všech nových repozitářů. Přečtěte si více v průvodci webovými háčky. defaulthooks.add_webhook=Přidat výchozí webový háček defaulthooks.update_webhook=Aktualizovat výchozí webový háček systemhooks=Systémové webové háčky -systemhooks.desc=Webové háčky automaticky vytvářejí HTTP POST dotazy na server při určitých Gitea událostech. Webové háčky definované zde budou vykonány na všech repozitářích systému, proto prosím zvažte jakékoli důsledky, které to může mít na výkon. Přečtěte si více v průvodci webovými háčky. systemhooks.add_webhook=Přidat systémový webový háček systemhooks.update_webhook=Aktualizovat systémový webový háček @@ -2713,7 +2711,6 @@ auths.tip.google_plus=Získejte klientské pověření OAuth2 z Google API konzo auths.tip.openid_connect=Použijte OpenID URL pro objevování spojení (/.well-known/openid-configuration) k nastavení koncových bodů auths.tip.twitter=Jděte na https://dev.twitter.com/apps, vytvořte aplikaci a ujistěte se, že volba „Allow this application to be used to Sign in with Twitter“ je povolená auths.tip.discord=Registrujte novou aplikaci na https://discordapp.com/developers/applications/me -auths.tip.gitea=Registrovat novou Oauth2 aplikaci. Návod naleznete na https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=Vytvořte novou aplikaci na https://oauth.yandex.com/client/new. Vyberte následující oprávnění z „Yandex.Passport API“ sekce: „Přístup k e-mailové adrese“, „Přístup k uživatelskému avataru“ a „Přístup k uživatelskému jménu, jménu a příjmení, pohlaví“ auths.tip.mastodon=Vložte vlastní URL instance pro mastodon, kterou se chcete autentizovat (nebo použijte výchozí) auths.edit=Upravit zdroj ověřování @@ -2885,8 +2882,6 @@ monitor.queue.exemplar=Typ vzoru monitor.queue.numberworkers=Počet workerů monitor.queue.maxnumberworkers=Maximální počet workerů monitor.queue.numberinqueue=Číslo ve frontě -monitor.queue.review=Konfigurace posouzení -monitor.queue.review_add=Posoudit/přidat workery monitor.queue.settings.title=Nastavení fondu monitor.queue.settings.maxnumberworkers=Maximální počet workerů monitor.queue.settings.maxnumberworkers.placeholder=V současné době %[1]d diff --git a/options/locale/locale_de-DE.ini b/options/locale/locale_de-DE.ini index d9773c0f5eeae..e3ee15a873c36 100644 --- a/options/locale/locale_de-DE.ini +++ b/options/locale/locale_de-DE.ini @@ -181,7 +181,6 @@ network_error=Netzwerkfehler [startpage] app_desc=Ein einfacher, selbst gehosteter Git-Service install=Einfach zu installieren -install_desc=Starte einfach die Anwendung für deine Plattform. Oder nutze Docker. Es existieren auch paketierte Versionen. platform=Plattformübergreifend platform_desc=Gitea läuft überall, wo Go kompiliert: Windows, macOS, Linux, ARM, etc. Wähle das System, das dir am meisten gefällt! lightweight=Leichtgewicht @@ -317,6 +316,7 @@ filter_by_team_repositories=Nach Team-Repositories filtern feed_of=`Feed von "%s"` show_archived=Archiviert +archived=Archiviert show_both_archived_unarchived=Archivierte und nicht archivierte anzeigen show_only_archived=Nur archivierte anzeigen show_only_unarchived=Nur nicht archivierte anzeigen @@ -592,7 +592,6 @@ overview=Übersicht following=Folge ich follow=Folgen unfollow=Nicht mehr folgen -heatmap.loading=Heatmap wird geladen… user_bio=Biografie disabled_public_activity=Dieser Benutzer hat die öffentliche Sichtbarkeit der Aktivität deaktiviert. email_visibility.limited=Ihre E-Mail-Adresse ist für alle authentifizierten Benutzer sichtbar @@ -666,7 +665,6 @@ choose_new_avatar=Neues Profilbild auswählen update_avatar=Profilbild aktualisieren delete_current_avatar=Aktuelles Profilbild löschen uploaded_avatar_not_a_image=Die hochgeladene Datei ist kein Bild. -uploaded_avatar_is_too_big=Die hochgeladene Datei hat die maximale Größe überschritten. update_avatar_success=Dein Profilbild wurde geändert. update_user_avatar_success=Der Avatar des Benutzers wurde aktualisiert. @@ -1229,6 +1227,11 @@ commit.cherry-pick=Cherry-Pick commit.cherry-pick-header=Cherry-Picke: %s commit.cherry-pick-content=Branch auswählen, auf dem Cherry-Picked werden soll: +commitstatus.error=Fehler +commitstatus.failure=Fehler +commitstatus.pending=Ausstehend +commitstatus.success=Erfolg + ext_issues=Zugriff auf Externe Issues ext_issues.desc=Link zu externem Issuetracker. @@ -1423,9 +1426,9 @@ issues.ref_reopening_from=`hat auf einen Pull Request %[4]s verw issues.ref_closed_from=`hat dieses Issue %[4]s geschlossen %[2]s` issues.ref_reopened_from=`hat dieses Issue %[4]s %[2]s wieder geöffnet` issues.ref_from=`von %[1]s` -issues.poster=Ersteller -issues.collaborator=Mitarbeiter -issues.owner=Besitzer +issues.author=Autor +issues.role.owner=Besitzer +issues.role.member=Mitglied issues.re_request_review=Review erneut anfordern issues.is_stale=Seit diesem Review gab es Änderungen an diesem PR issues.remove_request_review=Review-Anfrage entfernen @@ -1743,8 +1746,6 @@ milestones.edit_success=Meilenstein "%s" wurde aktualisiert. milestones.deletion=Meilenstein löschen milestones.deletion_desc=Das Löschen des Meilensteins entfernt ihn von allen Issues. Fortfahren? milestones.deletion_success=Der Meilenstein wurde gelöscht. -milestones.filter_sort.closest_due_date=Nächster Stichtag -milestones.filter_sort.furthest_due_date=Fernster Stichtag milestones.filter_sort.least_complete=Am wenigsten vollständig milestones.filter_sort.most_complete=Vollständigste milestones.filter_sort.most_issues=Meiste Issues @@ -2225,7 +2226,6 @@ settings.tags.protection.allowed.teams=Erlaubte Teams settings.tags.protection.allowed.noone=Niemand settings.tags.protection.create=Tag schützen settings.tags.protection.none=Es gibt keine geschützten Tags. -settings.tags.protection.pattern.description=Du kannst einen einzigen Namen oder ein globales Schema oder einen regulären Ausdruck verwenden, um mehrere Tags zu schützen. Mehr dazu im geschützte Tags Guide (Englisch). settings.bot_token=Bot-Token settings.chat_id=Chat-ID settings.matrix.homeserver_url=Homeserver-URL @@ -2740,12 +2740,10 @@ packages.size=Größe packages.published=Veröffentlicht defaulthooks=Standard-Webhooks -defaulthooks.desc=Webhooks senden automatisch eine HTTP-POST-Anfrage an einen Server, wenn bestimmte Gitea-Events ausgelöst werden. Hier definierte Webhooks sind die Standardwerte, die in alle neuen Repositories kopiert werden. Mehr Infos findest du in der Webhooks-Anleitung (auf Englisch). defaulthooks.add_webhook=Standard-Webhook hinzufügen defaulthooks.update_webhook=Standard-Webhook aktualisieren systemhooks=System-Webhooks -systemhooks.desc=Webhooks senden automatisch HTTP-POST-Anfragen an einen Server, wenn bestimmte Gitea-Events ausgelöst werden. Hier definierte Webhooks werden auf alle Repositories des Systems übertragen, beachte daher mögliche Performance-Einbrüche. Mehr Infos findest du in der Webhooks-Anleitung (auf Englisch). systemhooks.add_webhook=System-Webhook hinzufügen systemhooks.update_webhook=System-Webhook aktualisieren @@ -2849,7 +2847,6 @@ auths.tip.google_plus=Du erhältst die OAuth2-Client-Zugangsdaten in der Google- auths.tip.openid_connect=Benutze die OpenID-Connect-Discovery-URL (/.well-known/openid-configuration), um die Endpunkte zu spezifizieren auths.tip.twitter=Gehe auf https://dev.twitter.com/apps, erstelle eine Anwendung und stelle sicher, dass die Option „Allow this application to be used to Sign in with Twitter“ aktiviert ist auths.tip.discord=Erstelle unter https://discordapp.com/developers/applications/me eine neue Anwendung. -auths.tip.gitea=Registriere eine neue OAuth2-Anwendung. Eine Anleitung findest du unter https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Erstelle eine neue Anwendung auf https://oauth.yandex.com/client/new. Wähle folgende Berechtigungen aus dem "Yandex.Passport API" Bereich: "Zugriff auf E-Mail-Adresse", "Zugriff auf Benutzeravatar" und "Zugriff auf Benutzername, Vor- und Nachname, Geschlecht"` auths.tip.mastodon=Gebe eine benutzerdefinierte URL für die Mastodon-Instanz ein, mit der du dich authentifizieren möchtest (oder benutze die standardmäßige) auths.edit=Authentifikationsquelle bearbeiten @@ -3032,8 +3029,6 @@ monitor.queue.exemplar=Beispieltyp monitor.queue.numberworkers=Anzahl der Worker monitor.queue.maxnumberworkers=Maximale Anzahl der Worker monitor.queue.numberinqueue=Nummer in der Warteschlange -monitor.queue.review=Konfiguration überprüfen -monitor.queue.review_add=Worker hinzufügen/prüfen monitor.queue.settings.title=Pool-Einstellungen monitor.queue.settings.desc=Pools wachsen dynamisch basierend auf der Blockierung der Arbeitswarteschlange. monitor.queue.settings.maxnumberworkers=Maximale Anzahl an Workern diff --git a/options/locale/locale_el-GR.ini b/options/locale/locale_el-GR.ini index a07db7132bfdc..63cc1ca2e53de 100644 --- a/options/locale/locale_el-GR.ini +++ b/options/locale/locale_el-GR.ini @@ -175,7 +175,6 @@ network_error=Σφάλμα δικτύου [startpage] app_desc=Μια ανώδυνη, αυτο-φιλοξενούμενη υπηρεσία Git install=Εύκολο στην εγκατάσταση -install_desc=Απλά εκτελέστε το δυαδικό για την πλατφόρμα σας, στείλτε το με Docker, ή πάρτε το πακέτο. platform=Πολυπλατφορμικό platform_desc=Ο Gitea τρέχει οπουδήποτε Go μπορεί να γίνει compile για: Windows, macOS, Linux, ARM, κλπ. Επιλέξτε αυτό που αγαπάτε! lightweight=Ελαφρύ @@ -308,6 +307,7 @@ filter_by_team_repositories=Φιλτράρισμα ανά αποθετήρια feed_of=`Τροφοδοσία του "%s"` show_archived=Αρχειοθετήθηκε +archived=Αρχειοθετήθηκε show_both_archived_unarchived=Εμφάνιση και αρχειοθετημένων και μη αρχειοθετημένων show_only_archived=Εμφάνιση μόνο αρχειοθετημένων show_only_unarchived=Εμφάνιση μόνο μη αρχειοθετημένων @@ -582,7 +582,6 @@ overview=Επισκόπηση following=Ακολουθεί follow=Ακολουθήστε unfollow=Να μην ακολουθώ -heatmap.loading=Φόρτωση heatmap… user_bio=Βιογραφικό disabled_public_activity=Αυτός ο χρήστης έχει απενεργοποιήσει τη δημόσια προβολή της δραστηριότητας. email_visibility.limited=Η διεύθυνση email σας είναι ορατή σε όλους τους ταυτοποιημένους χρήστες @@ -655,7 +654,6 @@ choose_new_avatar=Επιλέξτε νέα εικόνα update_avatar=Ενημέρωση Εικόνας delete_current_avatar=Διαγραφή Τρέχουσας Εικόνας uploaded_avatar_not_a_image=Το αρχείο που ανεβάσατε δεν είναι εικόνα. -uploaded_avatar_is_too_big=Το αρχείο έχει υπερβεί το μέγιστο μέγεθος. update_avatar_success=Η εικόνα σας έχει ενημερωθεί. update_user_avatar_success=Το avatar του χρήστη ενημερώθηκε. @@ -1217,6 +1215,11 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Ανθολόγηση: %s commit.cherry-pick-content=Επιλέξτε κλάδο για να κάνετε ανθολόγηση σε αυτό: +commitstatus.error=Σφάλμα +commitstatus.failure=Αποτυχία +commitstatus.pending=Εκκρεμεί +commitstatus.success=Επιτυχές + ext_issues=Πρόσβαση στα Εξωτερικά Ζητήματα ext_issues.desc=Σύνδεση σε εξωτερικό εφαρμογή ζητημάτων. @@ -1408,9 +1411,9 @@ issues.ref_reopening_from=`αναφέρθηκε σε ένα pull issues.ref_closed_from=`έκλεισε αυτό το ζήτημα %[4]s %[2]s` issues.ref_reopened_from=`άνοιξε ξανά αυτό το ζήτημα %[4]s %[2]s` issues.ref_from=`από %[1]s` -issues.poster=Συντάκτης -issues.collaborator=Συνεργάτης -issues.owner=Ιδιοκτήτης +issues.author=Συγγραφέας +issues.role.owner=Ιδιοκτήτης +issues.role.member=Μέλος issues.re_request_review=Επαναίτηση ανασκόπησης issues.is_stale=Έχουν υπάρξει αλλαγές σε αυτό το PR από αυτή την αναθεώρηση issues.remove_request_review=Αφαίρεση αιτήματος αναθεώρησης @@ -1725,8 +1728,6 @@ milestones.edit_success=Το ορόσημο "%s" ενημερώθηκε. milestones.deletion=Διαγραφή Ορόσημου milestones.deletion_desc=Η διαγραφή ενός ορόσημου το αφαιρεί από όλα τα συναφή ζητήματα. Συνέχεια; milestones.deletion_success=Το ορόσημο έχει διαγραφεί. -milestones.filter_sort.closest_due_date=Πλησιέστερη παράδοση -milestones.filter_sort.furthest_due_date=Απώτερη παράδοση milestones.filter_sort.least_complete=Λιγότερο πλήρη milestones.filter_sort.most_complete=Περισσότερο πλήρη milestones.filter_sort.most_issues=Περισσότερα ζητήματα @@ -2207,7 +2208,6 @@ settings.tags.protection.allowed.teams=Επιτρεπόμενες ομάδες settings.tags.protection.allowed.noone=Καμία settings.tags.protection.create=Προστασία Ετικέτας settings.tags.protection.none=Δεν υπάρχουν προστατευμένες ετικέτες. -settings.tags.protection.pattern.description=Μπορείτε να χρησιμοποιήσετε ένα μόνο όνομα ή ένα μοτίβο glob ή μια κανονική έκφραση για να ταιριάξετε πολλαπλές ετικέτες. Διαβάστε περισσότερα στον οδηγό προστατευμένων ετικετών. settings.bot_token=Διακριτικό Bot settings.chat_id=ID Συνομιλίας settings.matrix.homeserver_url=Homeserver URL @@ -2722,12 +2722,10 @@ packages.size=Μέγεθος packages.published=Δημοσιευμένα defaulthooks=Προεπιλεγμένα Webhooks -defaulthooks.desc=Τα Webhooks κάνουν αυτόματα αιτήσεις HTTP POST σε ένα διακομιστή όταν συμβαίνουν ορισμένα γεγονότα στο Gitea. Τα Webhooks που ορίζονται εδώ είναι προεπιλογή και θα αντιγραφούν σε όλα τα νέα αποθετήρια. Διαβάστε περισσότερα στον οδηγό webhooks. defaulthooks.add_webhook=Προσθήκη Προεπιλεγμένου Webhook defaulthooks.update_webhook=Ενημέρωση Προεπιλεγμένου Webhook systemhooks=Webhooks Συστήματος -systemhooks.desc=Τα Webhooks κάνουν αυτόματα αιτήσεις HTTP POST σε ένα διακομιστή όταν συμβαίνουν ορισμένα γεγονότα στο Gitea. Τα Webhooks που ορίζονται εδώ θα ενεργούν σε όλα τα αποθετήρια του συστήματος, γι 'αυτό παρακαλώ εξετάστε τυχόν επιπτώσεις απόδοσης που μπορεί να υπάρξουν. Διαβάστε περισσότερα στον οδηγό webhooks. systemhooks.add_webhook=Προσθήκη Webhook Συστήματος systemhooks.update_webhook=Ενημέρωση Webhook Συστήματος @@ -2831,7 +2829,6 @@ auths.tip.google_plus=Αποκτήστε τα διαπιστευτήρια πε auths.tip.openid_connect=Χρησιμοποιήστε το OpenID Connect Discovery URL (/.well known/openid-configuration) για να καθορίσετε τα τελικά σημεία auths.tip.twitter=Πηγαίνετε στο https://dev.twitter.com/apps, δημιουργήστε μια εφαρμογή και βεβαιωθείτε ότι η επιλογή “Allow this application to be used to Sign in with Twitter” είναι ενεργοποιημένη auths.tip.discord=Καταχωρήστε μια νέα εφαρμογή στο https://discordapp.com/developers/applications/me -auths.tip.gitea=Καταχωρήστε μια νέα εφαρμογή OAuth2. Ο οδηγός μπορεί να βρεθεί στο https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Δημιουργήστε μια νέα εφαρμογή στο https://oauth.yandex.com/client/new. Επιλέξτε τα ακόλουθα δικαιώματα από την ενότητα "Yandex.Passport API": "Access to email address", "Access to user avatar" και "Access to username, first name and surname, gender"` auths.tip.mastodon=Εισαγάγετε ένα προσαρμομένο URL για την υπηρεσία mastodon με την οποία θέλετε να πιστοποιήσετε (ή να χρησιμοποιήσετε την προεπιλεγμένη) auths.edit=Επεξεργασία Πηγής Ταυτοποίησης @@ -3014,8 +3011,6 @@ monitor.queue.exemplar=Τύπος Υποδείγματος monitor.queue.numberworkers=Αριθμός Εργατών monitor.queue.maxnumberworkers=Μέγιστος Αριθμός Εργατών monitor.queue.numberinqueue=Πλήθος Ουράς -monitor.queue.review=Εξέταση Ρυθμίσεων -monitor.queue.review_add=Εξέταση/Προσθήκη Εργατών monitor.queue.settings.title=Ρυθμίσεις Δεξαμενής monitor.queue.settings.desc=Οι δεξαμενές αυξάνονται δυναμικά όταν υπάρχει φραγή της ουράς των εργατών τους. monitor.queue.settings.maxnumberworkers=Μέγιστος Αριθμός Εργατών diff --git a/options/locale/locale_es-ES.ini b/options/locale/locale_es-ES.ini index ff6175cf019dd..c8ff04c1574a4 100644 --- a/options/locale/locale_es-ES.ini +++ b/options/locale/locale_es-ES.ini @@ -137,7 +137,6 @@ network_error=Error de red [startpage] app_desc=Un servicio de Git autoalojado y sin complicaciones install=Fácil de instalar -install_desc=Simplemente arranca el binario para su plataforma. O utilice Gitea con Docker, o utilice el paquete. platform=Multiplataforma platform_desc=Gitea funciona en cualquier platforma Go puede compilarlo en: Windows, macOS, Linux, ARM, etc. ¡Elige tu favorita! lightweight=Ligero @@ -264,6 +263,7 @@ filter_by_team_repositories=Filtrar por repositorios de equipo feed_of=`Suministro de noticias de "%s"` show_archived=Archivado +archived=Archivado show_both_archived_unarchived=Mostrar respositorios archivados y desarchivados show_only_archived=Mostrar sólo repositorios archivados show_only_unarchived=Mostrar sólo repositorios desarchivados @@ -518,7 +518,6 @@ overview=Resumen following=Siguiendo follow=Seguir unfollow=Dejar de seguir -heatmap.loading=Cargando mapa de calor… user_bio=Biografía disabled_public_activity=Este usuario ha desactivado la visibilidad pública de la actividad. @@ -582,7 +581,6 @@ choose_new_avatar=Selecciona nuevo avatar update_avatar=Actualizar Avatar delete_current_avatar=Eliminar avatar uploaded_avatar_not_a_image=El archivo subido no es una imagen. -uploaded_avatar_is_too_big=El archivo subido ha excedido el tamaño máximo. update_avatar_success=Su avatar ha sido actualizado. update_user_avatar_success=El avatar del usuario se ha actualizado. @@ -1090,6 +1088,9 @@ commit.cherry-pick=Hacer Cherry-pick commit.cherry-pick-header=Hacer Cherry-pick: %s commit.cherry-pick-content=Seleccionar rama en la que hacer cherry-pick: +commitstatus.error=Error +commitstatus.pending=Pendiente + ext_issues=Acceso a incidencias externas ext_issues.desc=Enlace a un gestor de incidencias externo. @@ -1253,9 +1254,9 @@ issues.ref_reopening_from=`referenció un pull request %[4]s que issues.ref_closed_from=`cerró esta incidencia %[4]s %[2]s` issues.ref_reopened_from=`reabrió esta incidencia %[4]s %[2]s` issues.ref_from=`de %[1]s` -issues.poster=Autor -issues.collaborator=Colaborador -issues.owner=Propietario +issues.author=Autoría +issues.role.owner=Propietario +issues.role.member=Miembro issues.re_request_review=Solicitar revisión de nuevo issues.is_stale=Ha habido cambios en este PR desde esta revisión issues.remove_request_review=Eliminar solicitud de revisión @@ -1547,8 +1548,6 @@ milestones.modify=Actualizar hito milestones.deletion=Eliminar hito milestones.deletion_desc=Eliminando un hito lo elimina de todos los problemas relacionados. ¿Continuar? milestones.deletion_success=El hito se ha eliminado. -milestones.filter_sort.closest_due_date=Más cerca de la fecha de vencimiento -milestones.filter_sort.furthest_due_date=Más lejos de la fecha de vencimiento milestones.filter_sort.least_complete=Menos completa milestones.filter_sort.most_complete=Más completa milestones.filter_sort.most_issues=Mayoría de los problemas @@ -1980,7 +1979,6 @@ settings.tags.protection.allowed.teams=Equipos permitidos settings.tags.protection.allowed.noone=Ningún settings.tags.protection.create=Proteger Etiqueta settings.tags.protection.none=No hay etiquetas protegidas. -settings.tags.protection.pattern.description=Puede usar un solo nombre o un patrón de glob o expresión regular para que coincida con varias etiquetas. Lea más en la guía de etiquetas protegida. settings.bot_token=Token del Bot settings.chat_id=ID Chat settings.matrix.homeserver_url=URL de Homeserver @@ -2449,12 +2447,10 @@ packages.size=Tamaño packages.published=Publicado defaulthooks=Webhooks por defecto -defaulthooks.desc=Los Webhooks automáticamente hacen peticiones HTTP POST a un servidor cuando ciertos eventos de Gitea se activan. Los ganchos definidos aquí son predeterminados y serán copiados en todos los nuevos repositorios. Leer más en la guía webhooks. defaulthooks.add_webhook=Añadir Webhook por defecto defaulthooks.update_webhook=Actualizar Webhook por defecto systemhooks=Webhooks del sistema -systemhooks.desc=Los webhooks automáticamente hacen peticiones HTTP POST a un servidor cuando ciertos eventos de Gitea se activan. Los webhooks definidos actuarán en todos los repositorios del sistema, así que por favor considere las implicaciones de rendimiento que esto pueda tener. Lea más en la guía de webhooks. systemhooks.add_webhook=Añadir Webhook del Sistema systemhooks.update_webhook=Actualizar Webhook del Sistema @@ -2556,7 +2552,6 @@ auths.tip.google_plus=Obtener credenciales de cliente OAuth2 desde la consola AP auths.tip.openid_connect=Use el OpenID Connect Discovery URL (/.well-known/openid-configuration) para especificar los puntos finales auths.tip.twitter=Ir a https://dev.twitter.com/apps, crear una aplicación y asegurarse de que la opción "Permitir que esta aplicación sea usada para iniciar sesión con Twitter" está activada auths.tip.discord=Registrar una nueva aplicación en https://discordapp.com/developers/applications/me -auths.tip.gitea=Registra una nueva aplicación OAuth2. La guía puede ser encontrada en https://docs.gitea.io/es-us/oauth2-provider/ auths.tip.yandex=`Crear una nueva aplicación en https://oauth.yandex.com/client/new. Seleccione los siguientes permisos del "Yandex.Passport API": "Access to email address", "Access to user avatar" y "Access to username, first name and surname, gender"` auths.tip.mastodon=Introduzca una URL de instancia personalizada para la instancia mastodon con la que desea autenticarse (o utilice la predeterminada) auths.edit=Editar origen de autenticación @@ -2727,8 +2722,6 @@ monitor.queue.exemplar=Ejemplo monitor.queue.numberworkers=Número de trabajadores monitor.queue.maxnumberworkers=Número máximo de trabajadores monitor.queue.numberinqueue=Número en cola -monitor.queue.review=Revisar configuración -monitor.queue.review_add=Revisar/Añadir trabajadores monitor.queue.settings.title=Ajustes del grupo monitor.queue.settings.maxnumberworkers=Número máximo de trabajadores monitor.queue.settings.maxnumberworkers.placeholder=Actualmente %[1]d diff --git a/options/locale/locale_fa-IR.ini b/options/locale/locale_fa-IR.ini index b451eae80924f..46601a8cc703d 100644 --- a/options/locale/locale_fa-IR.ini +++ b/options/locale/locale_fa-IR.ini @@ -115,7 +115,6 @@ missing_csrf=درخواست بد: بلیط CSRF ندارد [startpage] app_desc=یک سرویس گیت بی‌درد سر و راحت install=راه‌اندازی ساده -install_desc=به سادگی فایل اجرایی را برای پلتفرم موردنظر خود اجرا کنید یا آن را در قالب یک کانتینر Docker آماده کنید و یا بصورت یک بسته دریافت کنید. platform=مستقل از سکو platform_desc=گیت همه جا اجرا می‌شود بریم! می‌توانید Windows, macOS, Linux, ARM و ... هر کدام را دوست داشتید انتخاب کنید! lightweight=ابزارک سبک @@ -241,6 +240,7 @@ filter_by_team_repositories=فیلتر کردن با مخازن تیم‌ها feed_of=`خوراک از "%s"` show_archived=بایگانی شده +archived=بایگانی شده show_both_archived_unarchived=نمایش دادن موارد بایگانی شده و غیر بایگانی نشده show_only_archived=نمایش دادن موارد بایگانی شده show_only_unarchived=نمایش دادن موارد بایگانی نشده @@ -478,7 +478,6 @@ overview=مرور following=دنبال میکنید follow=دنبال کردن unfollow=عدم دنبال کردن -heatmap.loading=بارگذاری Heatmap… user_bio=زندگی‌نامه disabled_public_activity=این کاربر نمایش عمومی فعالیت های خود را غیرفعال کرده است. @@ -526,7 +525,6 @@ choose_new_avatar=انتخاب آواتار جدید update_avatar=بروزرسانی آواتار delete_current_avatar=حذف آواتار فعلی uploaded_avatar_not_a_image=فایل بار‌گذاری شده تصویر نمی‌باشد. -uploaded_avatar_is_too_big=حجم فایل بارگزاری بیش از حد مجاز است. update_avatar_success=آواتار شما تغییر کرد. update_user_avatar_success=آواتار کاربر بروز رسانی شده است. @@ -991,6 +989,9 @@ commits.signed_by_untrusted_user_unmatched=امضا شده توسط یک کار commits.gpg_key_id=شناسه کلید GPG +commitstatus.error=خطا +commitstatus.pending=در انتظار + ext_issues.desc=پیوند به ردیاب خارجی برای موضوع. projects=پروژه‌ها @@ -1144,9 +1145,8 @@ issues.ref_reopening_from=` تقاضای واکشی ارجاع issues.ref_closed_from=` بسته شده این مسائله %[4] %[2]s` issues.ref_reopened_from=` بازگشایی این مسائله %[4] %[2]s` issues.ref_from=`از %[1]` -issues.poster=نویسنده -issues.collaborator=همكار -issues.owner=مالک +issues.role.owner=مالک +issues.role.member=عضو issues.re_request_review=درخواست دوباره برای بازبینی issues.is_stale=از زمان این بررسی تغییراتی در این پروژه ایجاد شده است issues.remove_request_review=حذف درخواست بازبینی @@ -1409,8 +1409,6 @@ milestones.modify=به روزرسانی نقطه عطف milestones.deletion=حذف نقطه عطف milestones.deletion_desc=نقاط عطف از تمام مسائل مرتبط حذف میشوند. آیا ادامه میدهید؟ milestones.deletion_success=نقطه عطف حذف شد. -milestones.filter_sort.closest_due_date=نزدیکترین موعد مقرر -milestones.filter_sort.furthest_due_date=دورترین موعد مقرر milestones.filter_sort.least_complete=حداقل کامل شده milestones.filter_sort.most_complete=بیشترین کامل شده milestones.filter_sort.most_issues=بیشترین مسائل @@ -1800,7 +1798,6 @@ settings.tags.protection.allowed.teams=تیم‌های مجاز settings.tags.protection.allowed.noone=هیچیک settings.tags.protection.create=تگ حفاظتی settings.tags.protection.none=هیچ تگ حفاظتی وجود ندارد. -settings.tags.protection.pattern.description=می توانید از یک نام واحد یا یک الگوی glob یا عبارت منظم برای تطبیق چندین برچسب استفاده کنید. در راهنمای برچسب های محافظت شده بیشتر بخوانید. settings.bot_token=Token ربات settings.chat_id=شناسه گپ settings.matrix.homeserver_url=URL سرورخانه @@ -2243,12 +2240,10 @@ packages.repository=مخزن packages.size=اندازه defaulthooks=وب هوک های پیش فرض -defaulthooks.desc=هنگامی که برخی رویدادهای Gitea فعال می شوند، Webhook ها به طور خودکار درخواست های HTTP POST را به سرور ارسال می کنند. هوک های تعریف شده در اینجا پیش فرض هستند و در تمام مخازن جدید کپی می شوند. در راهنمای هوک‌های وب بیشتر بخوانید. defaulthooks.add_webhook=اضافه کردن Webhook پیش فرض defaulthooks.update_webhook=Webhook پیش فرض را به روز کنید systemhooks=وب هوک های سیستم -systemhooks.desc=هنگامی که برخی رویدادهای Gitea فعال می شوند، Webhook ها به طور خودکار درخواست های HTTP POST را به سرور ارسال می کنند. وب هوک های تعریف شده در اینجا بر روی تمام انبارها سیستم عمل می کنند، بنابراین لطفاً هر گونه پیامدهای عملکردی که ممکن است داشته باشد را در نظر بگیرید. در راهنمای هوک‌های وب بیشتر بخوانید. systemhooks.add_webhook=System Webhook را اضافه کنید systemhooks.update_webhook=به روز رسانی Webhook سیستم @@ -2338,7 +2333,6 @@ auths.tip.google_plus=اطلاعات مربوط به مشتری OAuth2 را از auths.tip.openid_connect=برای مشخص کردن نقاط پایانی از آدرس OpenID Connect Discovery URL ( /.well-known/openid-configuration) استفاده کنید. auths.tip.twitter=به https://dev.twitter.com/apps بروید ، برنامه ای ایجاد کنید و اطمینان حاصل کنید که گزینه "اجازه استفاده از این برنامه برای ورود به سیستم با Twitter" را فعال کنید auths.tip.discord=یک برنامه جدید را در https://discordapp.com/developers/applications/me ثبت کنید -auths.tip.gitea=یک برنامه OAuth2 ثبت کنید. راهنمایی بیشتر https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`یک برنامه جدید در https://oauth.yandex.com/client/new ایجاد کنید. مجوزهای زیر را از بخش "Yandex.Passport API" انتخاب کنید: "دسترسی به آدرس ایمیل"، "دسترسی به آواتار کاربر" و "دسترسی به نام کاربری، نام و نام خانوادگی، جنسیت"` auths.tip.mastodon=یک URL نمونه سفارشی برای نمونه ماستودون که می خواهید با آن احراز هویت کنید وارد کنید (یا از یک پیش فرض استفاده کنید) auths.edit=ویرایش منبع احراز هویت @@ -2499,8 +2493,6 @@ monitor.queue.type=نوع monitor.queue.exemplar=نوع نمونه monitor.queue.numberworkers=تعداد کارگران monitor.queue.maxnumberworkers=بیشینه تعداد کارگران -monitor.queue.review=بررسی پیکربندی -monitor.queue.review_add=بررسی/افزودن کارگران monitor.queue.settings.title=تنظیمات استخر monitor.queue.settings.maxnumberworkers=بیشینه تعداد کارگران monitor.queue.settings.maxnumberworkers.placeholder=در حال حاضر %[1]v diff --git a/options/locale/locale_fi-FI.ini b/options/locale/locale_fi-FI.ini index d9a6cd5dec7be..cce13fb88a389 100644 --- a/options/locale/locale_fi-FI.ini +++ b/options/locale/locale_fi-FI.ini @@ -133,7 +133,6 @@ network_error=Verkkovirhe [startpage] app_desc=Kivuton, itsehostattu Git-palvelu install=Helppo asentaa -install_desc=Yksinkertaisesti aja binääri alustallasi, toimita se Dockerilla, tai saa se pakettina. platform=Alustariippumaton platform_desc=Gitea käy missä tahansa alustassa, johon Go kykenee kääntämään. Windows, macOS, Linux, ARM, jne. Valitse omasi! lightweight=Kevyt @@ -251,6 +250,7 @@ filter_by_team_repositories=Suodata tiimin repojen mukaan feed_of=`Syöte "%s"` show_archived=Arkistoidut +archived=Arkistoidut show_both_archived_unarchived=Näytetään arkistoidut ja arkistoimattomat show_only_archived=Näytetään vain arkistoidut show_only_unarchived=Näytetään vain arkistoimattomat @@ -439,7 +439,6 @@ overview=Yleiskatsaus following=Seurataan follow=Seuraa unfollow=Lopeta seuraaminen -heatmap.loading=Ladataan lämpökarttaa… user_bio=Elämäkerta @@ -794,6 +793,9 @@ commits.gpg_key_id=GPG avaimen ID commits.ssh_key_fingerprint=SSH avaimen sormenjälki +commitstatus.error=Virhe +commitstatus.pending=Odottaa + projects=Projektit projects.description_placeholder=Kuvaus @@ -900,9 +902,9 @@ issues.create_comment=Kommentoi issues.closed_at=`sulki tämän ongelman %[2]s` issues.reopened_at=`uudelleenavasi tämän ongelman %[2]s` issues.commit_ref_at=`viittasi tähän ongelmaan commitissa %[2]s` -issues.poster=Tekijä -issues.collaborator=Yhteistyökumppani -issues.owner=Omistaja +issues.author=Tekijä +issues.role.owner=Omistaja +issues.role.member=Jäsen issues.edit=Muokkaa issues.cancel=Peruuta issues.save=Tallenna @@ -1108,7 +1110,6 @@ settings.transfer=Siirrä omistajuus settings.transfer_form_title=Syötä repon nimi vahvistuksena: settings.transfer_notices_3=- Jos arkisto on yksityinen ja se siirretään yksittäiselle käyttäjälle, tämä toiminto varmistaa, että käyttäjällä on ainakin lukuoikeudet (ja muuttaa käyttöoikeuksia tarvittaessa). settings.transfer_owner=Uusi omistaja -settings.trust_model.collaborator=Yhteistyökumppani settings.wiki_delete=Poista Wiki data settings.wiki_delete_desc=Repon wikin data poistaminen on pysyvä eikä voi peruuttaa. settings.confirm_wiki_delete=Wiki datan poistaminen @@ -1220,7 +1221,6 @@ settings.tags.protection.allowed.teams=Sallitut tiimit settings.tags.protection.allowed.noone=Ei kukaan settings.tags.protection.create=Suojaa tagi settings.tags.protection.none=Suojattuja tageja ei ole. -settings.tags.protection.pattern.description=Voit käyttää yhtä nimeä tai glob-kuviota tai säännöllistä lauseketta, joka täsmää useisiin tageihin. Lue lisää suojatut tagit oppaasta. settings.bot_token=Botti pääsymerkki settings.matrix.homeserver_url=Kotipalvelimen URL settings.archive.button=Arkistoi repo diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index ec1babb17656a..2f6ed5ae873f7 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -181,7 +181,6 @@ network_error=Erreur réseau [startpage] app_desc=Un service Git auto-hébergé sans prise de tête install=Facile à installer -install_desc=Il suffit de lancer l’exécutable pour votre plateforme, le déployer avec Docker, ou l’installer depuis un paquet. platform=Multi-plateforme platform_desc=Gitea tourne partout où Go peut être compilé : Windows, macOS, Linux, ARM, etc. Choisissez votre préféré ! lightweight=Léger @@ -317,6 +316,7 @@ filter_by_team_repositories=Dépôts filtrés par équipe feed_of=Flux de « %s » show_archived=Archivé +archived=Archivé show_both_archived_unarchived=Afficher à la fois archivé et non archivé show_only_archived=Afficher uniquement les archivés show_only_unarchived=Afficher uniquement les non archivés @@ -598,7 +598,6 @@ overview=Vue d'ensemble following=Abonnements follow=Suivre unfollow=Ne plus suivre -heatmap.loading=Chargement de la Heatmap… user_bio=Biographie disabled_public_activity=Cet utilisateur a désactivé la visibilité publique de l'activité. email_visibility.limited=Votre adresse courriel est visible pour tous les utilisateurs authentifiés @@ -680,7 +679,6 @@ choose_new_avatar=Sélectionner un nouvel avatar update_avatar=Modifier l’avatar delete_current_avatar=Supprimer l'avatar actuel uploaded_avatar_not_a_image=Le fichier téléchargé n'est pas une image. -uploaded_avatar_is_too_big=Le fichier téléchargé dépasse la taille limite. update_avatar_success=Votre avatar a été mis à jour. update_user_avatar_success=L'avatar de l'utilisateur a été mis à jour. @@ -1280,6 +1278,11 @@ commit.cherry-pick=Picorer commit.cherry-pick-header=Picorer : %s commit.cherry-pick-content=Sélectionner la branche à picorer : +commitstatus.error=Erreur +commitstatus.failure=Échec +commitstatus.pending=En attente +commitstatus.success=Succès + ext_issues=Accès aux tickets externes ext_issues.desc=Lien vers un gestionnaire de tickets externe. @@ -1475,9 +1478,9 @@ issues.ref_reopening_from=`a référencé une pull request %[4]s issues.ref_closed_from=`a fermé ce ticket %[4]s %[2]s` issues.ref_reopened_from=`a rouvert ce ticket %[4]s %[2]s.` issues.ref_from=`de %[1]s` -issues.poster=Éditeur -issues.collaborator=Collaborateur -issues.owner=Propriétaire +issues.author=Auteur +issues.role.owner=Propriétaire +issues.role.member=Membre issues.re_request_review=Redemander une évaluation issues.is_stale=Cette demande d’ajout a été corrigée depuis sa dernière évaluation. issues.remove_request_review=Retirer la demande d’évaluation @@ -1815,8 +1818,6 @@ milestones.edit_success=Le jalon "%s" a été mis à jour. milestones.deletion=Supprimer un Jalon milestones.deletion_desc=Supprimer un jalon le retire de tous les tickets. Continuer ? milestones.deletion_success=Le jalon a été supprimé. -milestones.filter_sort.closest_due_date=Date d'échéance la plus proche -milestones.filter_sort.furthest_due_date=Date d'échéance la plus éloignée milestones.filter_sort.least_complete=Le moins complété milestones.filter_sort.most_complete=Le plus complété milestones.filter_sort.most_issues=Le plus de tickets @@ -2314,7 +2315,6 @@ settings.tags.protection.allowed.teams=Équipes autorisées settings.tags.protection.allowed.noone=Personne settings.tags.protection.create=Protéger l'étiquette settings.tags.protection.none=Il n'y a pas d'étiquettes protégées. -settings.tags.protection.pattern.description=Vous pouvez utiliser soit un nom unique, soit un motif de glob ou une expression régulière qui correspondront à plusieurs étiquettes. Pour plus d'informations, veuillez vous reporter au guide sur les étiquettes protégées. settings.bot_token=Jeton de Bot settings.chat_id=ID de conversation settings.thread_id=ID du fil @@ -2851,12 +2851,10 @@ packages.size=Taille packages.published=Publiés defaulthooks=Déclencheurs web par défaut -defaulthooks.desc=Les Déclencheurs Web font des requêtes HTTP POST à un serveur lorsque certains événements Gitea se produisent. Les Déclencheurs déclarés ici seront prédéfinit dans tous nouveaux dépôts. Consultez le guide sur les Déclencheurs Web. defaulthooks.add_webhook=Ajouter un déclencheur web par défaut defaulthooks.update_webhook=Mettre à jour le déclencheur web par défaut systemhooks=Rappels système -systemhooks.desc=Les Webhooks font automatiquement des requêtes HTTP POST à un serveur lorsque certains événements Gitea se déclenchent. Les Webhooks définis ici agiront sur tous les dépots du système, donc veuillez prendre en compte les implications en termes de performances que cela peut avoir. Lire la suite dans le guide des Webhooks. systemhooks.add_webhook=Ajouter un rappel système systemhooks.update_webhook=Mettre à jour un rappel système @@ -2961,7 +2959,6 @@ auths.tip.google_plus=Obtenez des identifiants OAuth2 sur la console API de Goog auths.tip.openid_connect=Utilisez l'URL de découvert OpenID (/.well-known/openid-configuration) pour spécifier les points d'accès auths.tip.twitter=Rendez-vous sur https://dev.twitter.com/apps, créez une application et assurez-vous que l'option "Autoriser l'application à être utilisée avec Twitter Connect" est activée auths.tip.discord=Enregistrer une nouvelle application sur https://discordapp.com/developers/applications/me -auths.tip.gitea=Enregistrez une nouvelle application OAuth2. Un guide peut être trouvé sur https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Créez une nouvelle application sur https://oauth.yandex.com/client/new. Sélectionnez les autorisations suivantes dans la section "Yandex API passport" : "Accès à l'adresse e-mail", "Accès à l'avatar de l'utilisateur" et "Accès au nom d'utilisateur, prénom et prénom, genre"` auths.tip.mastodon=Entrez une URL d'instance personnalisée pour l'instance mastodon avec laquelle vous voulez vous authentifier (ou utiliser celle par défaut) auths.edit=Mettre à jour la source d'authentification @@ -3145,8 +3142,6 @@ monitor.queue.exemplar=Type d'exemple monitor.queue.numberworkers=Nombre de processus monitor.queue.maxnumberworkers=Nombre maximale de processus monitor.queue.numberinqueue=Position dans la queue -monitor.queue.review=Revoir la configuration -monitor.queue.review_add=Réviser/Ajouter des processus monitor.queue.settings.title=Paramètres du réservoir monitor.queue.settings.desc=Les bassins croissent proportionnellement au besoin de leurs exécuteurs. monitor.queue.settings.maxnumberworkers=Nombre maximale de processus diff --git a/options/locale/locale_hu-HU.ini b/options/locale/locale_hu-HU.ini index ee94e3d40b613..b53d34f1a2f83 100644 --- a/options/locale/locale_hu-HU.ini +++ b/options/locale/locale_hu-HU.ini @@ -211,6 +211,7 @@ view_home=Nézet %s search_repos=Tároló keresés… show_archived=Archivált +archived=Archivált show_private=Privát show_both_private_public=Publikus és privát mutatása @@ -382,7 +383,6 @@ overview=Áttekintés following=Követve follow=Követés unfollow=Követés törlése -heatmap.loading=Hőtérkép betöltése… user_bio=Életrajz @@ -425,7 +425,6 @@ choose_new_avatar=Új profilkép kiválasztása update_avatar=Profilkép Frissítése delete_current_avatar=Jelenlegi profilkép törlése uploaded_avatar_not_a_image=A feltöltött fájl nem kép. -uploaded_avatar_is_too_big=A feltöltött file mérete meghaladta a maximumot. update_avatar_success=A profilképe frissítve lett. change_password=Jelszó frissítése @@ -737,6 +736,8 @@ commits.signed_by=Aláírta commits.gpg_key_id=GPG kulcs azonosító +commitstatus.pending=Függőben + ext_issues.desc=Külső hibakövető csatlakoztatás. projects=Projektek @@ -835,9 +836,8 @@ issues.reopen_issue=Újranyitás issues.reopen_comment_issue=Hozzászólás és újranyitás issues.create_comment=Hozzászólás issues.commit_ref_at=`hivatkozott erre a hibajegyre egy commit-ból %[2]s` -issues.poster=Posztoló -issues.collaborator=Közreműködő -issues.owner=Tulajdonos +issues.role.owner=Tulajdonos +issues.role.member=Tag issues.re_request_review=Véleményezés újrakérése issues.sign_in_require_desc=Jelentkezz be hogy csatlakozz a beszélgetéshez. issues.edit=Szerkesztés @@ -973,8 +973,6 @@ milestones.modify=Mérföldkő frissítése milestones.deletion=Mérföldkő törlése milestones.deletion_desc=A mérföldkő törlése eltávolítja az összes hozzárendelt hibajegyet. Biztosan folytatja? milestones.deletion_success=A mérföldkő törölve. -milestones.filter_sort.closest_due_date=Legközelebbi határidő -milestones.filter_sort.furthest_due_date=Legtávolabbi határidő milestones.filter_sort.least_complete=Legkevésbé befejezve milestones.filter_sort.most_complete=Leginkább befejezve milestones.filter_sort.most_issues=Legtöbb hibajegy @@ -1072,7 +1070,6 @@ settings.githooks=Git Hook-ok settings.site=Webhely settings.update_settings=Beállítások frissítése settings.enable_timetracker=Időmérés bekapcsolása -settings.trust_model.collaborator=Közreműködő settings.delete_collaborator=Eltávolítás settings.teams=Csoportok settings.webhook_deletion=Webhook törlése @@ -1423,7 +1420,6 @@ auths.tip.openid_connect=Használja az OpenID kapcsolódás felfedező URL-t (%[2]s` -issues.poster=Poster -issues.collaborator=Kalaborator -issues.owner=Pemilik +issues.role.owner=Pemilik +issues.role.member=Anggota issues.sign_in_require_desc=Masuk untuk bergabung dengan percakapan ini. issues.edit=Sunting issues.cancel=Batal @@ -780,8 +778,6 @@ milestones.due_date=Jatuh Tempo (opsional) milestones.clear=Bersihkan milestones.edit=Ubah Milestone milestones.cancel=Batal -milestones.filter_sort.closest_due_date=Jatuh tempo terdekat -milestones.filter_sort.furthest_due_date=Jatuh tempo terjauh milestones.filter_sort.least_complete=Paling tidak lengkap milestones.filter_sort.most_complete=Paling lengkap milestones.filter_sort.most_issues=Paling banyak masalah @@ -871,7 +867,6 @@ settings.danger_zone=Zona Bahaya settings.new_owner_has_same_repo=Pemilik baru sudah memiliki repositori dengan nama yang sama. Silakan pilih nama lain. settings.transfer=Transfer Kepemilikan settings.transfer_owner=Pemilik Baru -settings.trust_model.collaborator=Kalaborator settings.delete=Menghapus Repositori Ini settings.delete_notices_1=- Operasi ini TIDAK BISA dibatalkan. settings.delete_collaborator=Menghapus @@ -1250,8 +1245,6 @@ monitor.queue.type=Tipe monitor.queue.exemplar=Contoh Tipe monitor.queue.numberworkers=Jumlah Worker monitor.queue.maxnumberworkers=Jumlah Maks. Worker -monitor.queue.review=Tinjau Konfigurasi -monitor.queue.review_add=Tinjau/Tambah Worker monitor.queue.settings.title=Pengaturan Kelompok monitor.queue.settings.maxnumberworkers=Jumlah Maks. Worker monitor.queue.settings.maxnumberworkers.error=Jumlah maks. worker haruslah sebuah angka diff --git a/options/locale/locale_is-IS.ini b/options/locale/locale_is-IS.ini index 5c9c4a040a334..d0031dd65508d 100644 --- a/options/locale/locale_is-IS.ini +++ b/options/locale/locale_is-IS.ini @@ -130,7 +130,6 @@ network_error=Netkerfisvilla [startpage] app_desc=Þrautalaus og sjálfhýst Git þjónusta install=Einföld uppsetning -install_desc=Einfaldlega keyrðu forritiðfyrir vettvanginn þinn, Docker, eða fáðu það í pakka. platform=Fjölvettvangur platform_desc=Gitea virkar hvar sem að Go gerir: Linux, macOS, Windows, ARM o. s. frv. Veldu það sem þú vilt! lightweight=Létt @@ -230,6 +229,7 @@ search_repos=Finna hugbúnaðarsafn… filter=Aðrar Síur show_archived=Safnvistað +archived=Safnvistað show_private=Einka show_only_private=Að sýna aðeins einka @@ -416,7 +416,6 @@ overview=Yfirlit following=Fylgir follow=Fylgja unfollow=Affylgja -heatmap.loading=Hleð Hitakorti… user_bio=Lífssaga disabled_public_activity=Þessi notandi hefur slökkt á opinberum sýnileika virkninnar. @@ -472,7 +471,6 @@ choose_new_avatar=Veldu nýja notandamynd update_avatar=Uppfæra Notandamynd delete_current_avatar=Eyða Núverandi Notandamynd uploaded_avatar_not_a_image=Skráin sem hlaðin var upp er ekki mynd. -uploaded_avatar_is_too_big=Skráin sem hlaðin var upp er yfir hámarksstærð. update_avatar_success=Notandamynd þín hefur verið uppfærð. update_user_avatar_success=Notandamynd þessara notanda hefur verið uppfærð. @@ -717,6 +715,9 @@ commits.older=Eldri commits.newer=Nýrri +commitstatus.error=Villa +commitstatus.pending=Í bið + projects=Verkefni projects.description=Lýsing (valfrjálst) @@ -804,7 +805,9 @@ issues.create_comment=Senda Ummæli issues.closed_at=`lokaði þessu vandamáli %[2]s` issues.reopened_at=`enduropnaði þetta vandamál %[2]s` issues.ref_reopened_from=`enduropnaði þetta vandamál %[4]s %[2]s` -issues.owner=Eigandi +issues.author=Höfundur +issues.role.owner=Eigandi +issues.role.member=Meðlimur issues.edit=Breyta issues.cancel=Hætta við issues.save=Vista @@ -1211,7 +1214,6 @@ packages.type=Tegund packages.repository=Hugbúnaðarsafn packages.size=Stærð -defaulthooks.desc=Vefkrókar senda sjálfkrafa HTTP POST beiðnir til netþjóns þegar ákveðnir Gitea atburðir koma af stað. Vefkrókar sem eru skilgreindir hér eru sjálfgefnir og verða afritaðir í allar nýjar geymslur. Frekari upplýsingar eru í handbókini. auths.name=Heiti diff --git a/options/locale/locale_it-IT.ini b/options/locale/locale_it-IT.ini index 42d19e1f1d39a..95a3f5dee4cbc 100644 --- a/options/locale/locale_it-IT.ini +++ b/options/locale/locale_it-IT.ini @@ -135,7 +135,6 @@ network_error=Errore di rete [startpage] app_desc=Un servizio auto-ospitato per Git pronto all'uso install=Facile da installare -install_desc=Semplicemente avvia l'eseguibile per la tua piattaforma. Oppure avvia Gitea con Docker, oppure ottienilo pacchettizzato. platform=Multipiattaforma platform_desc=Gitea funziona ovunque Go possa essere compilato: Windows, macOS, Linux, ARM, etc. Scegli ciò che ami! lightweight=Leggero @@ -262,6 +261,7 @@ filter_by_team_repositories=Filtra per repository del team feed_of=`Feed di "%s"` show_archived=Archiviato +archived=Archiviato show_both_archived_unarchived=Mostra sia gli archiviati che i non archiviati show_only_archived=Visualizzazione solo archiviati show_only_unarchived=Visualizzazione solo non archiviati @@ -505,7 +505,6 @@ overview=Riepilogo following=Seguiti follow=Segui unfollow=Non seguire più -heatmap.loading=Caricamento della Heatmap… user_bio=Biografia disabled_public_activity=L'utente ha disabilitato la vista pubblica dell'attività. @@ -569,7 +568,6 @@ choose_new_avatar=Scegli un nuovo avatar update_avatar=Aggiorna Avatar delete_current_avatar=Elimina Avatar attuale uploaded_avatar_not_a_image=Il file caricato non è un'immagine. -uploaded_avatar_is_too_big=Il file inviato eccede le dimensioni massime. update_avatar_success=Il tuo avatar è stato aggiornato. update_user_avatar_success=L'avatar dell'utente è stato aggiornato. @@ -1077,6 +1075,9 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=Seleziona il ramo su cui scegliere: +commitstatus.error=Errore +commitstatus.pending=In sospeso + ext_issues=Accesso ai Problemi Esterni ext_issues.desc=Collegamento al puntatore di una issue esterna. @@ -1238,9 +1239,9 @@ issues.ref_reopening_from=`ha fatto riferimento ad una pull requ issues.ref_closed_from=`chiuso questo problema %[4]s %[2]s` issues.ref_reopened_from=`riaperto questo problema %[4]s %[2]s` issues.ref_from=`da %[1]s` -issues.poster=Autore -issues.collaborator=Collaboratori -issues.owner=Proprietario +issues.author=Autore +issues.role.owner=Proprietario +issues.role.member=Membro issues.re_request_review=Revisione ri-richiesta issues.is_stale=Ci sono stati cambiamenti a questa PR da questa revisione issues.remove_request_review=Elimina richiesta revisione @@ -1532,8 +1533,6 @@ milestones.modify=Aggiorna pietra miliare milestones.deletion=Elimina pietra miliare milestones.deletion_desc=Eliminare una pietra miliare la rimuove da tutte le relative issue. Continuare? milestones.deletion_success=La pietra miliare è stata eliminata. -milestones.filter_sort.closest_due_date=Data di scadenza più vicina -milestones.filter_sort.furthest_due_date=Data di scadenza più lontana milestones.filter_sort.least_complete=Meno completato milestones.filter_sort.most_complete=Più completato milestones.filter_sort.most_issues=Più problemi @@ -1958,7 +1957,6 @@ settings.tags.protection.allowed.teams=Squadre ammesse settings.tags.protection.allowed.noone=Nessuno settings.tags.protection.create=Proteggi Etichetta settings.tags.protection.none=Non ci sono etichette protette. -settings.tags.protection.pattern.description=È possibile utilizzare un singolo nome o un modello globo o un'espressione regolare per abbinare più tag. Leggi di più nella guida per i tag protetti. settings.bot_token=Token del Bot settings.chat_id=ID chat settings.matrix.homeserver_url=URL Homeserver @@ -2424,12 +2422,10 @@ packages.size=Dimensione packages.published=Pubblicata defaulthooks=Webhook predefiniti -defaulthooks.desc=I Webhooks effettuano automaticamente richieste HTTP POST ad un server quando si verificano determinati eventi Gitea. I Webhooks definiti qui sono predefiniti e verranno copiati in tutti i nuovi repository. Per saperne di più leggi la guida ai webhooks. defaulthooks.add_webhook=Aggiungi Webhook predefinito defaulthooks.update_webhook=Aggiorna Webhook predefinito systemhooks=Webhooks di Sistema -systemhooks.desc=I Webhooks effettuano automaticamente richieste HTTP POST ad un server quando si verificano determinati eventi Gitea. I Webhooks definiti qui agiranno su tutti i repository del sistema, quindi considera le eventuali implicazioni sulle performance che potrebbero avere. Per saperne di più leggi la guida ai webhooks. systemhooks.add_webhook=Aggiungi Webhook di Sistema systemhooks.update_webhook=Aggiorna Webhook di Sistema @@ -2531,7 +2527,6 @@ auths.tip.google_plus=Ottieni le credenziali del client OAuth2 dalla console API auths.tip.openid_connect=Utilizza l'OpenID Connect Discovery URL (/.well-known/openid-configuration) per specificare gli endpoint auths.tip.twitter=Vai su https://dev.twitter.com/apps, crea una applicazione e assicurati che l'opzione "Allow this application to be used to Sign In with Twitter" sia abilitata auths.tip.discord=Registra una nuova applicazione su https://discordapp.com/developers/applications/me -auths.tip.gitea=Registra una nuova applicazione OAuth2. La guida può essere trovata a https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Crea una nuova applicazione su https://oauth.yandex.com/client/new. Seleziona i seguenti permessi da "Yandex. assport API": "Access to email address", "Access to user avatar" e "Access to username, name and surname, gender"` auths.tip.mastodon=Inserisci un URL di istanza personalizzato per l'istanza mastodon con cui vuoi autenticarti (o usa quella predefinita) auths.edit=Modifica fonte di autenticazione @@ -2700,8 +2695,6 @@ monitor.queue.exemplar=Tipo di esemplare monitor.queue.numberworkers=Numero di workers monitor.queue.maxnumberworkers=Massimo numero di Workers monitor.queue.numberinqueue=Numero in coda -monitor.queue.review=Rivedi configurazione -monitor.queue.review_add=Rivedi/aggiungi Workers monitor.queue.settings.title=Impostazioni pool monitor.queue.settings.maxnumberworkers=Massimo numero di workers monitor.queue.settings.maxnumberworkers.placeholder=Attualmente %[1]d diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index e4a479ecf9e4c..c78c6811b44b4 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -180,7 +180,6 @@ network_error=ネットワークエラー [startpage] app_desc=自分で立てる、超簡単 Git サービス install=簡単インストール -install_desc=シンプルに、プラットフォームに応じてバイナリを実行したり、Dockerで動かしたり、パッケージを使うだけ。 platform=クロスプラットフォーム platform_desc=GiteaはGoでコンパイルできる環境ならどこでも動きます: Windows、macOS、Linux、ARM等々、好きなものを選んでください! lightweight=軽量 @@ -316,6 +315,7 @@ filter_by_team_repositories=チームリポジトリで絞り込み feed_of=`"%s" のフィード` show_archived=アーカイブ +archived=アーカイブ show_both_archived_unarchived=アーカイブと非アーカイブの両方を表示 show_only_archived=アーカイブのみ表示 show_only_unarchived=非アーカイブのみ表示 @@ -597,7 +597,6 @@ overview=概要 following=フォロー中 follow=フォロー unfollow=フォロー解除 -heatmap.loading=ヒートマップを読み込み中… user_bio=経歴 disabled_public_activity=このユーザーはアクティビティ表示を公開していません。 email_visibility.limited=あなたのメールアドレスはすべての認証済みユーザーに表示されています @@ -679,7 +678,6 @@ choose_new_avatar=新しいアバターを選択 update_avatar=アバターを更新 delete_current_avatar=現在のアバターを削除 uploaded_avatar_not_a_image=アップロードしたファイルは画像ファイルではありません。 -uploaded_avatar_is_too_big=アップロードしたファイルは最大サイズを超えています。 update_avatar_success=アバターを更新しました。 update_user_avatar_success=ユーザーのアバターを更新しました。 @@ -1271,6 +1269,11 @@ commit.cherry-pick=チェリーピック commit.cherry-pick-header=チェリーピック: %s commit.cherry-pick-content=チェリーピック先のブランチを選択: +commitstatus.error=エラー +commitstatus.failure=失敗 +commitstatus.pending=保留 +commitstatus.success=成功 + ext_issues=外部イシューへのアクセス ext_issues.desc=外部のイシュートラッカーへのリンク。 @@ -1463,9 +1466,9 @@ issues.ref_reopening_from=`が%[4]s、プルリクエストが issues.ref_closed_from=`が%[4]s、このイシューをクローズ %[2]s` issues.ref_reopened_from=`が%[4]s、このイシューを再オープン %[2]s` issues.ref_from=` %[1]s にて` -issues.poster=投稿者 -issues.collaborator=共同作業者 -issues.owner=オーナー +issues.author=著作者 +issues.role.owner=オーナー +issues.role.member=メンバー issues.re_request_review=レビューを再依頼 issues.is_stale=このレビューのあと、このPRに変更がありました issues.remove_request_review=レビュー依頼を取り消し @@ -1789,8 +1792,6 @@ milestones.edit_success=マイルストーン "%s" を更新しました。 milestones.deletion=マイルストーンの削除 milestones.deletion_desc=マイルストーンを削除すると、関連するすべてのイシューから除去されます。 続行しますか? milestones.deletion_success=マイルストーンを削除しました。 -milestones.filter_sort.closest_due_date=期日が近い順 -milestones.filter_sort.furthest_due_date=期日が遠い順 milestones.filter_sort.least_complete=消化率の低い順 milestones.filter_sort.most_complete=消化率の高い順 milestones.filter_sort.most_issues=イシューの多い順 @@ -2288,7 +2289,6 @@ settings.tags.protection.allowed.teams=許可するチーム settings.tags.protection.allowed.noone=なし settings.tags.protection.create=タグを保護 settings.tags.protection.none=タグは保護されていません。 -settings.tags.protection.pattern.description=ひとつのタグ名か、複数のタグにマッチするglobパターンまたは正規表現を使用できます。 詳しくは タグの保護ガイド をご覧ください。 settings.bot_token=Botトークン settings.chat_id=チャットID settings.matrix.homeserver_url=ホームサーバー URL @@ -2816,12 +2816,10 @@ packages.size=サイズ packages.published=配布 defaulthooks=デフォルトWebhook -defaulthooks.desc=Webhookは、特定のGiteaイベントトリガーが発生した際に、自動的にHTTP POSTリクエストをサーバーへ送信するものです。 ここで定義されたWebhookはデフォルトとなり、全ての新規リポジトリにコピーされます。 詳しくはwebhooks guideをご覧下さい。 defaulthooks.add_webhook=デフォルトWebhookの追加 defaulthooks.update_webhook=デフォルトWebhookの更新 systemhooks=システムWebhook -systemhooks.desc=Webhookは、特定のGiteaイベントトリガーが発生した際に、自動的にHTTP POSTリクエストをサーバーへ送信するものです。 ここで定義したWebhookはシステム内のすべてのリポジトリで呼び出されます。 そのため、パフォーマンスに及ぼす影響を考慮したうえで設定してください。 詳しくはwebhooks guideをご覧下さい。 systemhooks.add_webhook=システムWebhookを追加 systemhooks.update_webhook=システムWebhookを更新 @@ -2925,7 +2923,6 @@ auths.tip.google_plus=OAuth2クライアント資格情報を、Google APIコン auths.tip.openid_connect=OpenID Connect DiscoveryのURL (/.well-known/openid-configuration) をエンドポイントとして指定してください auths.tip.twitter=https://dev.twitter.com/apps へアクセスしてアプリケーションを作成し、“Allow this application to be used to Sign in with Twitter”オプションを有効にしてください。 auths.tip.discord=新しいアプリケーションを https://discordapp.com/developers/applications/me から登録してください。 -auths.tip.gitea=新しいOAuthアプリケーションを登録してください。 利用ガイドは https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`https://oauth.yandex.com/client/new で新しいアプリケーションを作成してください。 "Yandex.Passport API" セクションで次の項目を許可します: "Access to email address"、"Access to user avatar"、"Access to username, first name and surname, gender"` auths.tip.mastodon=認証したいMastodonインスタンスのカスタムURLを入力してください (入力しない場合はデフォルトのURLを使用します) auths.edit=認証ソースの編集 @@ -3108,8 +3105,6 @@ monitor.queue.exemplar=要素の型 monitor.queue.numberworkers=ワーカー数 monitor.queue.maxnumberworkers=ワーカー数上限 monitor.queue.numberinqueue=キュー内の数 -monitor.queue.review=設定確認 -monitor.queue.review_add=確認/ワーカー追加 monitor.queue.settings.title=プール設定 monitor.queue.settings.desc=プールはワーカーキューの待機状態に応じて動的に大きくなります。 monitor.queue.settings.maxnumberworkers=ワーカー数上限 diff --git a/options/locale/locale_ko-KR.ini b/options/locale/locale_ko-KR.ini index e8ed4b9695788..b9fd36e83d8f2 100644 --- a/options/locale/locale_ko-KR.ini +++ b/options/locale/locale_ko-KR.ini @@ -360,7 +360,6 @@ overview=개요 following=팔로우 중 follow=추적하기 unfollow=추적해제 -heatmap.loading=Heatmap 불러오는 중... user_bio=소개 @@ -402,7 +401,6 @@ choose_new_avatar=새로운 아바타 선택 update_avatar=아바타 변경하기 delete_current_avatar=현재 아바타 삭제 uploaded_avatar_not_a_image=업로드 된 파일은 이미지가 아닙니다. -uploaded_avatar_is_too_big=업로드된 파일이 최대 크기를 넘습니다. update_avatar_success=아바타가 변경되었습니다. change_password=비밀번호 변경 @@ -674,6 +672,8 @@ commits.signed_by=로그인 계정 commits.gpg_key_id=GPG 키 ID +commitstatus.pending=보류 + ext_issues.desc=외부 이슈 트래커 연결. projects.description_placeholder=설명 @@ -761,9 +761,8 @@ issues.reopen_issue=다시 열기 issues.reopen_comment_issue=다시 오픈 및 코멘트 issues.create_comment=코멘트 issues.commit_ref_at=` 커밋 %[2]s에서 이 이슈 언급` -issues.poster=포스터 -issues.collaborator=협업자 -issues.owner=소유자 +issues.role.owner=소유자 +issues.role.member=멤버 issues.sign_in_require_desc="로그인하여 이 대화에 참여" issues.edit=수정 issues.cancel=취소 @@ -884,8 +883,6 @@ milestones.modify=마일스톤 갱신 milestones.deletion=마일스톤 삭제 milestones.deletion_desc=마일스톤을 삭제하면 연관된 모든 이슈에서 삭제됩니다. 계속 하시겠습니까? milestones.deletion_success=마일스톤이 삭제되었습니다. -milestones.filter_sort.closest_due_date=마감일이 가까운 순 -milestones.filter_sort.furthest_due_date=마감일이 먼 순 milestones.filter_sort.least_complete=완료율이 낮은 순 milestones.filter_sort.most_complete=완료율이 높은 순 milestones.filter_sort.most_issues=이슈 많은 순 diff --git a/options/locale/locale_lv-LV.ini b/options/locale/locale_lv-LV.ini index 25e1371329bd3..2cc8085c18705 100644 --- a/options/locale/locale_lv-LV.ini +++ b/options/locale/locale_lv-LV.ini @@ -175,7 +175,6 @@ network_error=Tīkla kļūda [startpage] app_desc=Viegli uzstādāms Git serviss install=Vienkārši instalējams -install_desc=Nepieciešams tikai palaist izpildāmo failu vajadzīgajai platformai. Izmantot Docker vai izmantot pakotni. platform=Pieejama dažādām platformām platform_desc=Gitea iespējams uzstādīt jebkur, kam Go var nokompilēt: Windows, macOS, Linux, ARM utt. Izvēlies to, kas tev patīk! lightweight=Viegla @@ -308,6 +307,7 @@ filter_by_team_repositories=Filtrēt pēc komandas repozitorijiem feed_of=`"%s" plūsma` show_archived=Arhivētie +archived=Arhivētie show_both_archived_unarchived=Attēlot gan arhivētos, gan nearhivētos show_only_archived=Attēlot tikai arhivētos show_only_unarchived=Attēlot tikai nearhivētos @@ -582,7 +582,6 @@ overview=Pārskats following=Seko follow=Sekot unfollow=Nesekot -heatmap.loading=Ielādē intensitātes karti… user_bio=Biogrāfija disabled_public_activity=Šis lietotājs ir atslēdzies iespēju aplūkot tā aktivitāti. email_visibility.limited=E-pasta adrese ir redzama visiem autentificētajiem lietotājiem @@ -655,7 +654,6 @@ choose_new_avatar=Izvēlēties jaunu profila attēlu update_avatar=Saglabāt profila bildi delete_current_avatar=Dzēst pašreizējo profila bildi uploaded_avatar_not_a_image=Augšupielādētais fails nav attēls. -uploaded_avatar_is_too_big=Augšupielādētais fails parsniedz maksimālo izmēru. update_avatar_success=Profila attēls tika saglabāts. update_user_avatar_success=Lietotāja profila attēls tika atjaunots. @@ -1217,6 +1215,11 @@ commit.cherry-pick=Izlasīt commit.cherry-pick-header=Izlasīt: %s commit.cherry-pick-content=Norādiet atzaru uz kuru izlasīt: +commitstatus.error=Kļūda +commitstatus.failure=Neveiksmīgs +commitstatus.pending=Nav iesūtīts +commitstatus.success=Pabeigts + ext_issues=Piekļuve ārējām problēmām ext_issues.desc=Saite uz ārējo problēmu sekotāju. @@ -1408,9 +1411,9 @@ issues.ref_reopening_from=`atsaucās uz izmaiņu pieprasījumu % issues.ref_closed_from=`aizvēra problēmu %[4]s %[2]s` issues.ref_reopened_from=`atkārtoti atvēra problēmu %[4]s %[2]s` issues.ref_from=`no %[1]s` -issues.poster=Autors -issues.collaborator=Līdzstrādnieks -issues.owner=Īpašnieks +issues.author=Autors +issues.role.owner=Īpašnieks +issues.role.member=Biedri issues.re_request_review=Pieprasīt atkārtotu recenziju issues.is_stale=Šajā izmaiņu pieprasījumā ir notikušas izmaiņās, kopš veicāt tā recenziju issues.remove_request_review=Noņemt recenzijas pieprasījumu @@ -1725,8 +1728,6 @@ milestones.edit_success=Izmaiņas atskaites punktā "%s" tika veiksmīgi saglab milestones.deletion=Dzēst atskaites punktu milestones.deletion_desc=Dzēšot šo atskaites punktu, tas tiks noņemts no visām saistītajām problēmām un izmaiņu pieprasījumiem. Vai turpināt? milestones.deletion_success=Atskaites punkts tika veiksmīgi izdzēsts. -milestones.filter_sort.closest_due_date=Tuvākais termiņš -milestones.filter_sort.furthest_due_date=Tālākais termiņš milestones.filter_sort.least_complete=Vismazāk pabeigtais milestones.filter_sort.most_complete=Visvairāk pabeigtais milestones.filter_sort.most_issues=Visvairāk problēmu @@ -2207,7 +2208,6 @@ settings.tags.protection.allowed.teams=Atļauts komandām settings.tags.protection.allowed.noone=Nevienam settings.tags.protection.create=Aizsargāt tagus settings.tags.protection.none=Nav uzstādīta tagu aizsargāšana. -settings.tags.protection.pattern.description=Var izmantot pilnu nosaukumu, glob šablonu vai regulāro izteiksmi, lai aizsargātu vairākus tagus. Detalizētāk var izlasīt tagu aizsargāšanas pamācībā. settings.bot_token=Bota pilnvara settings.chat_id=Tērzēšanas ID settings.matrix.homeserver_url=Mājas servera URL @@ -2722,12 +2722,10 @@ packages.size=Izmērs packages.published=Publicēts defaulthooks=Noklusētie tīmekļa āķi -defaulthooks.desc=Tīmekļa āķi ļauj paziņot ārējiem servisiem par noteiktiem notikumiem, kas notiek Gitea. Kad iestāsies kāds notikums, katram ārējā servisa URL tiks nosūtīts POST pieprasījums. Šeit izveidotie tīmekļa āķi tiks pievienoti visiem jaunajajiem repozitorijiem. Lai uzzinātu sīkāk skatieties tīmekļa āķu rokasgrāmatā. defaulthooks.add_webhook=Pievienot noklusēto tīmekļa āķi defaulthooks.update_webhook=Mainīt noklusēto tīmekļa āķi systemhooks=Sistēmas tīmekļa āķi -systemhooks.desc=Tīmekļa āķi automātiski veic HTTP POST pieprasījumus uz serveri, kad notiek noteikti Gitea notikumi. Tīmekļa āķi izpildīsies uz visu servera repozitoriju notikumiem, tāpēc būtu jāņem vērā, ka tas var radīt ātrdarbības problēmas. Vairāk par tiem var uzzināt tīmekļa āķu dokumentācijā. systemhooks.add_webhook=Pievienot sistēmas tīmekļa āķi systemhooks.update_webhook=Mainīt sistēmas tīmekļa āķi @@ -2831,7 +2829,6 @@ auths.tip.google_plus=Iegūstiet OAuth2 klienta pilnvaru no Google API konsoles auths.tip.openid_connect=Izmantojiet OpenID pieslēgšanās atklāšanas URL (/.well-known/openid-configuration), lai norādītu galapunktus auths.tip.twitter=Dodieties uz adresi https://dev.twitter.com/apps, izveidojiet aplikāciju un pārliecinieties, ka ir atzīmēts “Allow this application to be used to Sign in with Twitter” auths.tip.discord=Reģistrējiet jaunu aplikāciju adresē https://discordapp.com/developers/applications/me -auths.tip.gitea=Reģistrēt jaunu OAuth2 lietojumprogrammu. Pamācību iespējams atrast https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Izveidojiet jaunu lietotni adresē https://oauth.yandex.com/client/new. Izvēlieties sekojošas tiesības "Yandex.Passport API" sadaļā: "Access to email address", "Access to user avatar" un "Access to username, first name and surname, gender"` auths.tip.mastodon=Norādiet pielāgotu mastodon instances URL, ar kuru vēlaties autorizēties (vai izmantojiet noklusēto) auths.edit=Labot autentifikācijas avotu @@ -3014,8 +3011,6 @@ monitor.queue.exemplar=Eksemplāra veids monitor.queue.numberworkers=Strādņu skaits monitor.queue.maxnumberworkers=Maksimālais strādņu skaits monitor.queue.numberinqueue=Skaits rindā -monitor.queue.review=Pārbaudīt konfigurāciju -monitor.queue.review_add=Pārbaudīt/Pievienot strādņus monitor.queue.settings.title=Pūla iestatījumi monitor.queue.settings.desc=Pūls dinamiski tiek palielināts atkarībā no bloķētiem darbiem rindā. monitor.queue.settings.maxnumberworkers=Maksimālais strādņu skaits diff --git a/options/locale/locale_nl-NL.ini b/options/locale/locale_nl-NL.ini index 0ad219f28334c..aa94a542f182b 100644 --- a/options/locale/locale_nl-NL.ini +++ b/options/locale/locale_nl-NL.ini @@ -134,7 +134,6 @@ network_error=Netwerk fout [startpage] app_desc=Een eenvoudige, self-hosted Git service install=Makkelijk te installeren -install_desc=Je hoeft alleen maar de binary uit te voeren, gebruik het met Docker, of download een installatiepakket. platform=Cross-platform platform_desc=Gitea werkt op alles waar Go op kan compileren: Windows, macOS, Linux, ARM, etc. Kies het platform dat bij je past! lightweight=Lichtgewicht @@ -261,6 +260,7 @@ filter_by_team_repositories=Filter op team repositories feed_of=`Feed van "%s"` show_archived=Gearchiveerd +archived=Gearchiveerd show_both_archived_unarchived=Toont zowel gearchiveerd als niet-gearchiveerd show_only_archived=Toon alleen gearchiveerd show_only_unarchived=Toon alleen niet gearchiveerd @@ -504,7 +504,6 @@ overview=Overzicht following=Volgt follow=Volg unfollow=Niet meer volgen -heatmap.loading=Heatmap wordt geladen… user_bio=Biografie disabled_public_activity=Deze gebruiker heeft de publieke zichtbaarheid van de activiteit uitgeschakeld. @@ -568,7 +567,6 @@ choose_new_avatar=Kies een nieuwe avatar update_avatar=Update Avatar delete_current_avatar=Verwijder huidige avatar uploaded_avatar_not_a_image=Het geüploade bestand is geen afbeelding. -uploaded_avatar_is_too_big=Het geüploade bestand heeft de maximale grootte overschreden. update_avatar_success=Je avatar is bijgewerkt. update_user_avatar_success=De avatar van de gebruiker is bijgewerkt. @@ -1075,6 +1073,9 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=Selecteer een branch om te cherry-pick op: +commitstatus.error=Fout +commitstatus.pending=In behandeling + ext_issues=Toegang tot Externe Issues ext_issues.desc=Koppelen aan een externe kwestie-tracker. @@ -1236,9 +1237,8 @@ issues.ref_reopening_from=`verwees naar een pull request %[4]s d issues.ref_closed_from=`sloot dit issue %[4]s %[2]s` issues.ref_reopened_from=`heropende dit issue %[4]s %[2]s` issues.ref_from=`van %[1]s` -issues.poster=Poster -issues.collaborator=Medewerker -issues.owner=Eigenaar +issues.role.owner=Eigenaar +issues.role.member=Lid issues.re_request_review=Opnieuw aanvragen review issues.is_stale=Er zijn wijzigingen aangebracht in deze PR sinds deze beoordeling issues.remove_request_review=Verwijder beoordelingsverzoek @@ -1528,8 +1528,6 @@ milestones.modify=Mijlpaal bijwerken milestones.deletion=Mijlpaal verwijderen milestones.deletion_desc=Als je een mijlpaal verwijdert, wordt hij van alle gerelateerde kwesties verwijderd. Doorgaan? milestones.deletion_success=De mijlpaal is verwijderd. -milestones.filter_sort.closest_due_date=Dichtstbijzijnde deadline -milestones.filter_sort.furthest_due_date=Verste deadline milestones.filter_sort.least_complete=Minst compleet milestones.filter_sort.most_complete=Meest compleet milestones.filter_sort.most_issues=Meeste problemen @@ -1686,7 +1684,6 @@ settings.enable_timetracker=Tijdregistratie inschakelen settings.allow_only_contributors_to_track_time=Sta alleen bijdragers toe tijdregistratie te gebruiken settings.pulls_desc=Repository-pull-aanvragen inschakelen settings.pulls.ignore_whitespace=Witruimte negeren voor conflicten -settings.trust_model.collaborator=Medewerker settings.trust_model.collaborator.long=Medewerker: Vertrouw handtekeningen door medewerkers settings.trust_model.committer=Committer settings.trust_model.committer.long=Committer: Vertrouw handtekeningen die overeenkomen met committers (Dit komt overeen met GitHub en zal Gitea ondertekende commits dwingen om Gitea als de committer te hebben) @@ -1898,7 +1895,6 @@ settings.tags.protection.allowed.teams=Toegestane teams settings.tags.protection.allowed.noone=Niemand settings.tags.protection.create=Beveilig Label settings.tags.protection.none=Er zijn geen beveiligde labels. -settings.tags.protection.pattern.description=U kunt een enkele naam gebruiken of een glob patroon of reguliere expressie om meerdere labels te matchen. Lees meer in de beschermde labels gids. settings.bot_token=Bot Token settings.chat_id=Chat-ID settings.matrix.homeserver_url=Homeserver URL @@ -2533,8 +2529,6 @@ monitor.queue.type=Type monitor.queue.exemplar=Type voorbeeld monitor.queue.numberworkers=Aantal workers monitor.queue.maxnumberworkers=Maximum aantal workers -monitor.queue.review=Configuratie herzien -monitor.queue.review_add=Beoordeel/Voeg workers toe monitor.queue.settings.title=Pool instellingen monitor.queue.settings.maxnumberworkers=Maximum aantal workers monitor.queue.settings.maxnumberworkers.placeholder=Momenteel %[1]d diff --git a/options/locale/locale_pl-PL.ini b/options/locale/locale_pl-PL.ini index 9a97b53c83764..255f36598c9af 100644 --- a/options/locale/locale_pl-PL.ini +++ b/options/locale/locale_pl-PL.ini @@ -132,7 +132,6 @@ network_error=Błąd sieci [startpage] app_desc=Bezbolesna usługa Git na własnym serwerze install=Łatwa instalacja -install_desc=Po prostu odpal plik binarny dla swojej platformy, uruchom przy pomocy Dockera, lub zainstaluj z paczki. platform=Wieloplatformowość platform_desc=Gitea ruszy gdziekolwiek Go jest możliwe do skompilowania: Windows, macOS, Linux, ARM, itd. Wybierz swój ulubiony system! lightweight=Niskie wymagania @@ -259,6 +258,7 @@ filter_by_team_repositories=Filtruj według repozytoriów zespołu feed_of=`Kanał "%s"` show_archived=Zarchiwizowane +archived=Zarchiwizowane show_both_archived_unarchived=Wyświetlanie zarchiwizowanych i niezarchiwizowanych show_only_archived=Wyświetlanie tylko zarchiwizowanych show_only_unarchived=Wyświetlanie tylko niezarchiwizowanych @@ -489,7 +489,6 @@ overview=Przegląd following=Obserwowani follow=Obserwuj unfollow=Przestań obserwować -heatmap.loading=Ładowanie mapy cieplnej… user_bio=Biografia disabled_public_activity=Ten użytkownik wyłączył publiczne wyświetlanie jego aktywności. @@ -537,7 +536,6 @@ choose_new_avatar=Wybierz nowy avatar update_avatar=Aktualizuj awatar delete_current_avatar=Usuń obecny Avatar uploaded_avatar_not_a_image=Załadowany plik nie jest obrazem. -uploaded_avatar_is_too_big=Przesłany plik przekroczył maksymalny rozmiar. update_avatar_success=Twój awatar został zmieniony. change_password=Aktualizuj hasło @@ -993,6 +991,9 @@ commits.signed_by_untrusted_user_unmatched=Podpisane przez niezaufanego użytkow commits.gpg_key_id=ID klucza GPG +commitstatus.error=Błąd +commitstatus.pending=Oczekująca + ext_issues.desc=Link do zewnętrznego systemu śledzenia zgłoszeń. projects=Projekty @@ -1139,9 +1140,8 @@ issues.ref_reopening_from=`odwołał(-a) się do Pull Requesta % issues.ref_closed_from=`zamknął(-ęła) to zgłoszenie %[4]s %[2]s` issues.ref_reopened_from=`ponownie otworzył(-a) to zgłoszenie %[4]s %[2]s` issues.ref_from=`z %[1]s` -issues.poster=Autor -issues.collaborator=Współpracownik -issues.owner=Właściciel +issues.role.owner=Właściciel +issues.role.member=Członek issues.re_request_review=Poproś o ponowną recenzję issues.remove_request_review=Usuń prośbę o recenzję issues.remove_request_review_block=Nie można usunąć prośby o recenzję @@ -1380,8 +1380,6 @@ milestones.modify=Zaktualizuj cel milestones.deletion=Usuń kamień milowy milestones.deletion_desc=Usunięcie celu usuwa go z wszystkich pozostałych zagadnień. Kontynuować? milestones.deletion_success=Cel został usunięty. -milestones.filter_sort.closest_due_date=Najbliżej daty realizacji -milestones.filter_sort.furthest_due_date=Najdalej daty realizacji milestones.filter_sort.least_complete=Najmniej kompletne milestones.filter_sort.most_complete=Najbardziej kompletne milestones.filter_sort.most_issues=Najwięcej zgłoszeń @@ -1761,7 +1759,6 @@ settings.tags.protection.allowed.teams=Dozwolone zespoły settings.tags.protection.allowed.noone=Brak settings.tags.protection.create=Chroń tag settings.tags.protection.none=Brak chronionych tagów. -settings.tags.protection.pattern.description=Możesz użyć pojedynczej nazwy lub wzoru glob lub wyrażenia regularnego, aby dopasować wiele tagów. Dowiedz się więcej w przewodniku tagów. settings.bot_token=Token bota settings.chat_id=ID czatu settings.matrix.homeserver_url=Adres URL serwera domowego @@ -2180,12 +2177,10 @@ packages.repository=Repozytorium packages.size=Rozmiar defaulthooks=Domyślne Webhooki -defaulthooks.desc=Webhooki automatycznie wysyłają zapytania HTTP POST na serwer, gdy niektóre zdarzenia Gitea je wyzwalają. Webhooki zdefiniowane tutaj są domyślne i zostaną skopiowane do wszystkich nowych repozytoriów. Przeczytaj więcej w przewodniku webhooków. defaulthooks.add_webhook=Dodaj domyślny Webhook defaulthooks.update_webhook=Zaktualizuj domyślny Webhook systemhooks=Webhooki Systemowe -systemhooks.desc=Webhooki automatycznie tworzą zapytania HTTP POST do serwera, kiedy następują pewne zdarzenia w Gitea. Webhooki zdefiniowane w tym miejscu będą wykonywane dla wszystkich repozytoriów, więc rozważ ewentualne konsekwencje pod względem wydajności. Przeczytaj o tym więcej w przewodniku o Webhookach. systemhooks.add_webhook=Dodaj Webhook Systemowy systemhooks.update_webhook=Aktualizuj Webhook Systemowy @@ -2265,7 +2260,6 @@ auths.tip.google_plus=Uzyskaj dane uwierzytelniające klienta OAuth2 z konsoli G auths.tip.openid_connect=Użyj adresu URL OpenID Connect Discovery (/.well-known/openid-configuration), aby określić punkty końcowe auths.tip.twitter=Przejdź na https://dev.twitter.com/apps, stwórz aplikację i upewnij się, że opcja “Allow this application to be used to Sign in with Twitter” jest włączona auths.tip.discord=Zarejestruj nową aplikację na https://discordapp.com/developers/applications/me -auths.tip.gitea=Zarejestruj nową aplikację OAuth2. Przewodnik można znaleźć na https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Utwórz nową aplikację na https://oauth.yandex.com/client/new. Wybierz następujące uprawnienia z "Yandex.Passport API": "Access to email address", "Access to user avatar" and "Access to username, first name and surname, gender"` auths.tip.mastodon=Wprowadź niestandardowy adres URL instancji mastodona, którą chcesz uwierzytelnić (lub użyj domyślnego) auths.edit=Edytuj źródło uwierzytelniania @@ -2423,8 +2417,6 @@ monitor.queue.type=Typ monitor.queue.exemplar=Przykładowy typ monitor.queue.numberworkers=Liczba procesów pracujących monitor.queue.maxnumberworkers=Maksymalna liczba procesów pracujących -monitor.queue.review=Przejrzyj konfigurację -monitor.queue.review_add=Przejrzyj/Dodaj procesy pracujące monitor.queue.settings.title=Ustawienia Puli monitor.queue.settings.maxnumberworkers=Maksymalna liczba procesów pracujących monitor.queue.settings.maxnumberworkers.placeholder=Obecnie %[1]d diff --git a/options/locale/locale_pt-BR.ini b/options/locale/locale_pt-BR.ini index 777805d8dc6e9..91881310778f6 100644 --- a/options/locale/locale_pt-BR.ini +++ b/options/locale/locale_pt-BR.ini @@ -175,7 +175,6 @@ network_error=Erro de rede [startpage] app_desc=Um serviço de hospedagem Git amigável install=Fácil de instalar -install_desc=Simplesmente execute o binário para seu sistema operacional, instale com o Docker ou faça download do pacote. platform=Multi-plataforma platform_desc=Gitea roda em qualquer sistema operacional em que Go consegue compilar: Windows, macOS, Linux, ARM, etc. Escolha qual você gosta mais! lightweight=Leve e rápido @@ -308,6 +307,7 @@ filter_by_team_repositories=Filtrar por repositórios da equipe feed_of=`Feed de "%s"` show_archived=Arquivado +archived=Arquivado show_both_archived_unarchived=Mostrando arquivados e não arquivados show_only_archived=Mostrando somente arquivados show_only_unarchived=Mostrando somente não arquivados @@ -582,7 +582,6 @@ overview=Visão geral following=Seguindo follow=Seguir unfollow=Deixar de seguir -heatmap.loading=Carregando mapa de calor... user_bio=Biografia disabled_public_activity=Este usuário desativou a visibilidade pública da atividade. email_visibility.limited=Seu endereço de e-mail está visível para todos os usuários autenticados @@ -655,7 +654,6 @@ choose_new_avatar=Escolha um novo avatar update_avatar=Atualizar o avatar delete_current_avatar=Excluir o avatar atual uploaded_avatar_not_a_image=O arquivo enviado não é uma imagem. -uploaded_avatar_is_too_big=O arquivo enviado excedeu o tamanho máximo. update_avatar_success=Seu avatar foi atualizado. update_user_avatar_success=O avatar do usuário foi atualizado. @@ -1216,6 +1214,11 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=Selecione o branch para receber o cherry-pick: +commitstatus.error=Erro +commitstatus.failure=Falha +commitstatus.pending=Pendente +commitstatus.success=Sucesso + ext_issues=Acesso a Issues Externos ext_issues.desc=Link para o issue tracker externo. @@ -1404,9 +1407,9 @@ issues.ref_reopening_from=`referenciado um pull request %[4]s qu issues.ref_closed_from=`fechou esta issue %[4]s %[2]s` issues.ref_reopened_from=`reabriu esta issue %[4]s %[2]s` issues.ref_from=`de %[1]s` -issues.poster=Autor -issues.collaborator=Colaborador -issues.owner=Proprietário +issues.author=Autor +issues.role.owner=Proprietário +issues.role.member=Membro issues.re_request_review=Re-solicitar revisão issues.is_stale=Houve alterações nessa PR desde essa revisão issues.remove_request_review=Remover solicitação de revisão @@ -1720,8 +1723,6 @@ milestones.edit_success=O marco "%s" foi atualizado. milestones.deletion=Excluir marco milestones.deletion_desc=A exclusão deste marco irá removê-lo de todas as issues. Tem certeza que deseja continuar? milestones.deletion_success=O marco foi excluído. -milestones.filter_sort.closest_due_date=Data limite mais próxima -milestones.filter_sort.furthest_due_date=Data limite mais distante milestones.filter_sort.least_complete=Menos completo milestones.filter_sort.most_complete=Mais completo milestones.filter_sort.most_issues=Com mais issues @@ -2181,7 +2182,6 @@ settings.tags.protection.allowed.teams=Equipes permitidas settings.tags.protection.allowed.noone=Ninguém settings.tags.protection.create=Proteger tag settings.tags.protection.none=Não há tags protegidas. -settings.tags.protection.pattern.description=Você pode usar um só nome ou um padrão glob ou uma expressão regular para corresponder a várias tags. Para mais informações leia o guia das tags protegidas. settings.bot_token=Token do Bot settings.chat_id=ID do Chat settings.matrix.homeserver_url=URL do Homeserver @@ -2693,12 +2693,10 @@ packages.size=Tamanho packages.published=Publicado defaulthooks=Webhooks Padrões -defaulthooks.desc=Webhooks automaticamente fazem requisições HTTP POST para um servidor quando acionados por determinados eventos do Gitea. Webhooks definidos aqui são os padrões e serão copiados para todos os novos repositórios. Leia mais no guia de webhooks. defaulthooks.add_webhook=Adicionar Webhook Padrão defaulthooks.update_webhook=Atualizar Webhook Padrão systemhooks=Webhooks do Sistema -systemhooks.desc=Webhooks automaticamente fazem requisições HTTP POST para um servidor quando acionados por determinados eventos do Gitea. Webhooks definidos aqui agirão em todos os repositórios do sistema, então, por favor, considere quaisquer implicações de desempenho que isso possa ter. Leia mais no guia de webhooks. systemhooks.add_webhook=Adicionar Webhook do Sistema systemhooks.update_webhook=Atualizar Webhook do Sistema @@ -2802,7 +2800,6 @@ auths.tip.google_plus=Obter credenciais de cliente OAuth2 do console de API do G auths.tip.openid_connect=Use o OpenID Connect Discovery URL (/.well-known/openid-configuration) para especificar os endpoints auths.tip.twitter=Vá em https://dev.twitter.com/apps, crie um aplicativo e certifique-se de que está habilitada a opção “Allow this application to be used to Sign in with Twitter“ auths.tip.discord=Cadastrar um novo aplicativo em https://discordapp.com/developers/applications/me -auths.tip.gitea=Cadastrar um novo aplicativo OAuth2. Guia pode ser encontrado em https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Crie um novo aplicativo em https://oauth.yandex.com/client/new. Selecione as seguintes permissões da seção "Yandex.Passport API": "Access to email address", "Access to user avatar" and "Access to username, first name and surname, gender"` auths.tip.mastodon=Insira a URL da instância personalizada do mastodon que você deseja usar para autenticar (ou use o padrão) auths.edit=Editar fonte de autenticação @@ -2983,8 +2980,6 @@ monitor.queue.exemplar=Tipo de modelo monitor.queue.numberworkers=Número de executores monitor.queue.maxnumberworkers=Número máximo de executores monitor.queue.numberinqueue=Número na Fila -monitor.queue.review=Revisar configuração -monitor.queue.review_add=Revisar/Adicionar executores monitor.queue.settings.title=Configurações do conjunto monitor.queue.settings.maxnumberworkers=Número máximo de executores monitor.queue.settings.maxnumberworkers.placeholder=Atualmente %[1]d diff --git a/options/locale/locale_pt-PT.ini b/options/locale/locale_pt-PT.ini index 2fb17ada7396d..6bc1d9d06c4c3 100644 --- a/options/locale/locale_pt-PT.ini +++ b/options/locale/locale_pt-PT.ini @@ -181,7 +181,7 @@ network_error=Erro de rede [startpage] app_desc=Um serviço Git auto-hospedado e fácil de usar install=Fácil de instalar -install_desc=Corra, simplesmente, o ficheiro binário executável para a sua plataforma, despache-o com o Docker, ou obtenha-o sob a forma de pacote. +install_desc=Corra, simplesmente, o ficheiro binário executável para a sua plataforma, despache-o com o Docker, ou obtenha-o sob a forma de pacote. platform=Multiplataforma platform_desc=Gitea corre em qualquer plataforma onde possa compilar em linguagem Go: Windows, macOS, Linux, ARM, etc. Escolha a sua preferida! lightweight=Leve @@ -317,6 +317,7 @@ filter_by_team_repositories=Filtrar por repositórios da equipa feed_of=`Fonte de "%s"` show_archived=Arquivado +archived=Arquivado show_both_archived_unarchived=Apresentando arquivados e não arquivados show_only_archived=Apresentando somente os arquivados show_only_unarchived=Apresentando somente os não arquivados @@ -378,6 +379,7 @@ email_not_associate=O endereço de email não está associado a qualquer conta. send_reset_mail=Enviar email de recuperação da conta reset_password=Recuperação de conta invalid_code=O seu código de confirmação é inválido ou expirou. +invalid_code_forgot_password=O seu código de confirmação é inválido ou já expirou. Clique aqui para iniciar uma nova sessão. invalid_password=A sua senha não corresponde à senha que foi usada para criar a conta. reset_password_helper=Recuperar conta reset_password_wrong_user=Tem conta iniciada como %s, mas a ligação de recuperação de conta é para %s @@ -598,7 +600,6 @@ overview=Panorama geral following=Que segue follow=Seguir unfollow=Deixar de seguir -heatmap.loading=Carregando mapa de laboração… user_bio=Biografia disabled_public_activity=Este utilizador desabilitou a visibilidade pública do trabalho. email_visibility.limited=O seu endereço de email é visível para todos os utilizadores autenticados @@ -680,7 +681,7 @@ choose_new_avatar=Escolher um novo avatar update_avatar=Substituir avatar delete_current_avatar=Eliminar o avatar corrente uploaded_avatar_not_a_image=O ficheiro carregado não é uma imagem. -uploaded_avatar_is_too_big=O ficheiro carregado excedeu o tamanho máximo. +uploaded_avatar_is_too_big=O tamanho do ficheiro carregado (%d KiB) excede o tamanho máximo (%d KiB). update_avatar_success=O seu avatar foi substituído. update_user_avatar_success=O avatar do utilizador foi modificado. @@ -970,6 +971,7 @@ trust_model_helper_collaborator_committer=Colaborador + Autor do cometimento: Co trust_model_helper_default=Padrão: Usar o modelo de confiança padrão para esta instalação create_repo=Criar repositório default_branch=Ramo principal +default_branch_label=predefinido default_branch_helper=O ramo principal é o ramo base para pedidos de integração e cometimentos. mirror_prune=Podar mirror_prune_desc=Remover referências obsoletas de seguimento remoto @@ -1280,6 +1282,11 @@ commit.cherry-pick=Escolher a dedo commit.cherry-pick-header=Escolher a dedo: %s commit.cherry-pick-content=Escolha o ramo para onde vai escolher a dedo: +commitstatus.error=Erro +commitstatus.failure=Falha +commitstatus.pending=Pendente +commitstatus.success=Sucesso + ext_issues=Acesso a questões externas ext_issues.desc=Ligação para um rastreador de questões externo. @@ -1475,9 +1482,18 @@ issues.ref_reopening_from=`referiu um pedido de integração %[4 issues.ref_closed_from=`encerrou esta questão %[4]s %[2]s` issues.ref_reopened_from=`reabriu esta questão %[4]s %[2]s` issues.ref_from=`de %[1]s` -issues.poster=Remetente -issues.collaborator=Colaborador(a) -issues.owner=Proprietário(a) +issues.author=Autor(a) +issues.author_helper=Este utilizador é o autor. +issues.role.owner=Proprietário(a) +issues.role.owner_helper=Este utilizador é o proprietário deste repositório. +issues.role.member=Membro +issues.role.member_helper=Este utilizador é um membro da organização que é proprietária deste repositório. +issues.role.collaborator=Colaborador +issues.role.collaborator_helper=Este utilizador foi convidado a colaborar neste repositório. +issues.role.first_time_contributor=Contribuidor pela primeira vez +issues.role.first_time_contributor_helper=Esta é a primeira contribuição deste utilizador para o repositório. +issues.role.contributor=Contribuidor +issues.role.contributor_helper=Este utilizador cometeu anteriormente para o repositório. issues.re_request_review=Voltar a solicitar revisão issues.is_stale=Houve modificações neste pedido de integração posteriormente a esta revisão issues.remove_request_review=Remover solicitação de revisão @@ -1748,6 +1764,7 @@ pulls.rebase_conflict_summary=Mensagem de erro pulls.unrelated_histories=A integração falhou: O topo da integração e a base não partilham um histórico comum. Dica: Tente uma estratégia diferente pulls.merge_out_of_date=Falhou a integração: Enquanto estava a gerar a integração, a base foi modificada. Dica: Tente de novo. pulls.head_out_of_date=Falhou a integração: Enquanto estava a gerar a integração, o topo foi modificado. Dica: Tente de novo. +pulls.has_merged=Falhou: A integração constante do pedido foi executada, não pode integrar novamente nem modificar o ramo alvo. pulls.push_rejected=A integração falhou: O envio foi rejeitado. Reveja os Automatismos do Git neste repositório. pulls.push_rejected_summary=Mensagem completa de rejeição pulls.push_rejected_no_message=A integração falhou: O envio foi rejeitado mas não houve qualquer mensagem remota.
Reveja os Automatismos do Git para este repositório @@ -1815,8 +1832,8 @@ milestones.edit_success=A etapa "%s" foi modificada. milestones.deletion=Eliminar etapa milestones.deletion_desc=Se eliminar uma etapa, irá removê-la de todas as questões relacionadas. Quer continuar? milestones.deletion_success=A etapa foi eliminada. -milestones.filter_sort.closest_due_date=Data de vencimento mais próxima -milestones.filter_sort.furthest_due_date=Data de vencimento mais distante +milestones.filter_sort.earliest_due_data=Data de vencimento mais próxima +milestones.filter_sort.latest_due_date=Data de vencimento mais distante milestones.filter_sort.least_complete=Menos completo milestones.filter_sort.most_complete=Mais completo milestones.filter_sort.most_issues=Mais questões @@ -2314,7 +2331,7 @@ settings.tags.protection.allowed.teams=Equipas com permissão settings.tags.protection.allowed.noone=Ninguém settings.tags.protection.create=Proteger etiqueta settings.tags.protection.none=Não há etiquetas protegidas. -settings.tags.protection.pattern.description=Pode usar um só nome ou um padrão glob ou uma expressão regular para corresponder a várias etiquetas. Para mais informações leia o guia das etiquetas protegidas. +settings.tags.protection.pattern.description=Pode usar um só nome ou um padrão glob ou uma expressão regular para corresponder a várias etiquetas. Para mais informações leia o guia das etiquetas protegidas. settings.bot_token=Código do bot settings.chat_id=ID do diálogo settings.thread_id=ID da discussão @@ -2752,6 +2769,7 @@ dashboard.stop_zombie_tasks=Parar tarefas zombies dashboard.stop_endless_tasks=Parar tarefas intermináveis dashboard.cancel_abandoned_jobs=Cancelar trabalhos abandonados dashboard.sync_branch.started=Sincronização de ramos iniciada +dashboard.rebuild_issue_indexer=Reconstruir indexador de questões users.user_manage_panel=Gestão das contas de utilizadores users.new_account=Criar conta de utilizador @@ -2760,6 +2778,9 @@ users.full_name=Nome completo users.activated=Em uso users.admin=Admin. users.restricted=Restrita +users.reserved=Reservado +users.bot=Bot +users.remote=Remoto users.2fa=Autenticação em dois passos users.repos=Repos. users.created=Criada @@ -2806,6 +2827,7 @@ users.list_status_filter.is_prohibit_login=Proibir início de sessão users.list_status_filter.not_prohibit_login=Permitir início de sessão users.list_status_filter.is_2fa_enabled=Autenticação em dois passos habilitada users.list_status_filter.not_2fa_enabled=Autenticação em dois passos desabilitada +users.details=Detalhes do utilizador emails.email_manage_panel=Gestão de endereços de email do utilizador emails.primary=Principal @@ -2853,12 +2875,12 @@ packages.size=Tamanho packages.published=Publicado defaulthooks=Automatismos web predefinidos -defaulthooks.desc=Os automatismos web fazem pedidos HTTP POST automaticamente a um servidor quando são despoletados determinados eventos do Gitea. Os automatismos web definidos aqui são os predefinidos e serão copiados para todos os novos repositórios. Leia mais no guia de automatismos web. +defaulthooks.desc=Os automatismos web fazem pedidos HTTP POST automaticamente a um servidor quando são despoletados determinados eventos do Gitea. Os automatismos web definidos aqui são os predefinidos e serão copiados para todos os novos repositórios. Leia mais no guia de automatismos web. defaulthooks.add_webhook=Adicionar automatismo web predefinido defaulthooks.update_webhook=Modificar automatismo web predefinido systemhooks=Automatismos web do sistema -systemhooks.desc=Os automatismos web fazem pedidos HTTP POST automaticamente a um servidor quando são despoletados determinados eventos do Gitea. Os automatismos web definidos aqui irão operar em todos os repositórios deste sistema, por isso tenha em consideração quaisquer implicações de desempenho que isso possa ter. Leia mais no guia de automatismos web. +systemhooks.desc=Os automatismos web fazem pedidos HTTP POST automaticamente a um servidor quando são despoletados determinados eventos do Gitea. Os automatismos web definidos aqui irão operar em todos os repositórios deste sistema, por isso tenha em consideração quaisquer implicações de desempenho que isso possa ter. Leia mais no guia de automatismos web. systemhooks.add_webhook=Adicionar automatismo web do sistema systemhooks.update_webhook=Modificar automatismo web do sistema @@ -2963,7 +2985,7 @@ auths.tip.google_plus=Obtenha credenciais de cliente OAuth2 a partir da consola auths.tip.openid_connect=Use o URL da descoberta de conexão OpenID (/.well-known/openid-configuration) para especificar os extremos auths.tip.twitter=`Vá a https://dev.twitter.com/apps, crie uma aplicação e certifique-se de que está habilitada a opção "Allow this application to be used to Sign in with Twitter"` auths.tip.discord=Registe uma nova aplicação em https://discordapp.com/developers/applications/me -auths.tip.gitea=Registe uma nova aplicação OAuth2. O guia pode ser encontrado em https://docs.gitea.io/en-us/oauth2-provider/ +auths.tip.gitea=Registe uma nova aplicação OAuth2. O guia pode ser encontrado em https://docs.gitea.com/development/oauth2-provider auths.tip.yandex=`Crie uma nova aplicação em https://oauth.yandex.com/client/new. Escolha as seguintes permissões da secção "Yandex.Passport API": "Acesso ao endereço de email", "Acesso ao avatar do utilizador" e "Acesso ao nome de utilizador, nome e sobrenome, género"` auths.tip.mastodon=Insira o URL de uma instância personalizada para a instância do mastodon com que se pretende autenticar (ou então use a predefinida) auths.edit=Editar fonte de autenticação @@ -3145,10 +3167,10 @@ monitor.queue.name=Nome monitor.queue.type=Tipo monitor.queue.exemplar=Tipo de exemplar monitor.queue.numberworkers=Número de trabalhadores +monitor.queue.activeworkers=Trabalhadores operantes monitor.queue.maxnumberworkers=Número máximo de trabalhadores monitor.queue.numberinqueue=Número na fila -monitor.queue.review=Rever configuração -monitor.queue.review_add=Rever/Adicionar trabalhadores +monitor.queue.review_add=Rever / Adicionar trabalhadores monitor.queue.settings.title=Configurações do agregado monitor.queue.settings.desc=Agregados crescem dinamicamente em resposta aos bloqueios da sua fila de trabalhadores. monitor.queue.settings.maxnumberworkers=Número máximo de trabalhadores @@ -3483,6 +3505,7 @@ runners.reset_registration_token_success=O código de incrição do executor foi runs.all_workflows=Todas as sequências de trabalho runs.commit=Cometimento +runs.scheduled=Agendadas runs.pushed_by=enviado por runs.invalid_workflow_helper=O ficheiro de configuração da sequência de trabalho é inválido. Verifique o seu ficheiro de configuração: %s runs.no_matching_runner_helper=Não há qualquer executor que corresponda: %s @@ -3497,6 +3520,7 @@ workflow.disable=Desabilitar sequência de trabalho workflow.disable_success=A sequência de trabalho '%s' foi desabilitada com sucesso. workflow.enable=Habilitar sequência de trabalho workflow.enable_success=A sequência de trabalho '%s' foi habilitada com sucesso. +workflow.disabled=A sequência de trabalho está desabilitada. need_approval_desc=É necessária aprovação para executar sequências de trabalho para a derivação do pedido de integração. diff --git a/options/locale/locale_ru-RU.ini b/options/locale/locale_ru-RU.ini index edf3b0b981c2c..709a173df3d1e 100644 --- a/options/locale/locale_ru-RU.ini +++ b/options/locale/locale_ru-RU.ini @@ -175,7 +175,6 @@ network_error=Ошибка сети [startpage] app_desc=Удобный сервис собственного хостинга репозиториев Git install=Простой в установке -install_desc=Просто запустите исполняемый файл для вашей платформы, разверните через Docker, или установите с помощью менеджера пакетов. platform=Кроссплатформенный platform_desc=Gitea работает на любой платформе, поддерживаемой Go: Windows, macOS, Linux, ARM и т. д. Выбирайте, что вам больше нравится! lightweight=Легковесный @@ -308,6 +307,7 @@ filter_by_team_repositories=Фильтровать по репозиториям feed_of=Лента «%s» show_archived=Архивировано +archived=Архивировано show_both_archived_unarchived=Показаны архивированные и разархивированные show_only_archived=Показаны только архивированные show_only_unarchived=Показаны только разархивированные @@ -582,7 +582,6 @@ overview=Обзор following=Подписки follow=Подписаться unfollow=Отписаться -heatmap.loading=Загрузка карты активности… user_bio=О себе disabled_public_activity=Этот пользователь отключил публичную видимость активности. email_visibility.limited=Ваш адрес электронной почты виден всем выполнившим вход пользователям @@ -655,7 +654,6 @@ choose_new_avatar=Выбрать новый аватар update_avatar=Обновить аватар delete_current_avatar=Удалить текущий аватар uploaded_avatar_not_a_image=Загружаемый файл не является изображением. -uploaded_avatar_is_too_big=Загруженный файл превысил максимальный размер. update_avatar_success=Ваш аватар был изменен. update_user_avatar_success=Аватар пользователя обновлён. @@ -1216,6 +1214,11 @@ commit.cherry-pick=Перенос commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=Выбрать ветку для переноса: +commitstatus.error=Ошибка +commitstatus.failure=Неудача +commitstatus.pending=Ожидание +commitstatus.success=Успешно + ext_issues=Доступ к внешним задачам ext_issues.desc=Ссылка на внешнюю систему отслеживания ошибок. @@ -1407,9 +1410,9 @@ issues.ref_reopening_from=`сослался(ась) на зап issues.ref_closed_from=`закрыл этот запрос %[4]s %[2]s` issues.ref_reopened_from=`переоткрыл эту задачу %[4]s %[2]s` issues.ref_from=`из %[1]s` -issues.poster=Автор -issues.collaborator=Соавтор -issues.owner=Владелец +issues.author=Автор +issues.role.owner=Владелец +issues.role.member=Участник issues.re_request_review=Повторить запрос на отзыв issues.is_stale=Со времени этого обзора в этот PR были внесены некоторые изменения issues.remove_request_review=Удалить запрос на отзыв @@ -1724,8 +1727,6 @@ milestones.edit_success=Этап «%s» обновлён. milestones.deletion=Удалить этап milestones.deletion_desc=Удаление этапа приведет к его удалению из всех связанных задач. Продолжить? milestones.deletion_success=Этап успешно удалён. -milestones.filter_sort.closest_due_date=Ближайшее по дате -milestones.filter_sort.furthest_due_date=Дальнее по дате milestones.filter_sort.least_complete=Менее полное milestones.filter_sort.most_complete=Более полное milestones.filter_sort.most_issues=Большинство задач @@ -2196,7 +2197,6 @@ settings.tags.protection.allowed.teams=Разрешенные команды settings.tags.protection.allowed.noone=Ни один settings.tags.protection.create=Защитить тег settings.tags.protection.none=Нет защищенных тегов. -settings.tags.protection.pattern.description=Вы можете использовать одно имя или глоб-шаблон или регулярное выражение, для выбора нескольких тегов. Подробнее о защищенных тэгах. settings.bot_token=Токен для бота settings.chat_id=ID чата settings.matrix.homeserver_url=URL домашнего сервера @@ -2710,12 +2710,10 @@ packages.size=Размер packages.published=Опубликовано defaulthooks=Стандартные Веб-хуки -defaulthooks.desc=Веб-хуки автоматически делают HTTP-POST запросы на сервер, когда вызываются определенные события Gitea. Веб-хуки, определённые здесь, по умолчанию и будут скопированы во все новые репозитории. Подробнее читайте в руководстве по веб-хукам. defaulthooks.add_webhook=Добавить стандартный Веб-хук defaulthooks.update_webhook=Обновить стандартный Веб-хук systemhooks=Системные веб-хуки -systemhooks.desc=Веб-хуки автоматически делают HTTP-POST запросы на сервер, когда вызываются определённые события Gitea. Определённые веб-хуки будут действовать на всех репозиториях системы, поэтому пожалуйста, учитывайте любые последствия для производительности. Подробнее читайте в руководстве по веб-хукам. systemhooks.add_webhook=Добавить системный веб-хук systemhooks.update_webhook=Обновить системный веб-хук @@ -2819,7 +2817,6 @@ auths.tip.google_plus=Получите учётные данные клиент auths.tip.openid_connect=Используйте OpenID Connect Discovery URL (/.well-known/openid-configuration) для автоматической настройки входа OAuth auths.tip.twitter=Перейдите на https://dev.twitter.com/apps, создайте приложение и убедитесь, что включена опция «Разрешить это приложение для входа в систему с помощью Twitter» auths.tip.discord=Добавьте новое приложение на https://discordapp.com/developers/applications/me -auths.tip.gitea=Зарегистрировать новое приложение OAuth2. Руководство можно найти на https://docs.gitea.io/ru-us/oauth2-provider/ auths.tip.yandex=`Создайте новое приложение по адресу https://oauth.yandex.com/client/new. В разделе "API Яндекс.Паспорта" выберите следующие разрешения: "Доступ к адресу электронной почты", "Доступ к аватару пользователя" и "Доступ к имени пользователя, фамилии и полу"` auths.tip.mastodon=Введите пользовательский URL экземпляра для экземпляра mastodon, с которым вы хотите аутентифицироваться (или использовать его по умолчанию) auths.edit=Обновить параметры аутентификации @@ -3002,8 +2999,6 @@ monitor.queue.exemplar=Тип образца monitor.queue.numberworkers=Количество рабочих monitor.queue.maxnumberworkers=Максимальное количество рабочих monitor.queue.numberinqueue=Позиция в очереди -monitor.queue.review=Просмотр конфигурации -monitor.queue.review_add=Просмотреть/добавить рабочих monitor.queue.settings.title=Настройки пула monitor.queue.settings.desc=Пулы увеличиваются динамически в ответ на блокировку очередей своих рабочих. monitor.queue.settings.maxnumberworkers=Максимальное количество рабочих diff --git a/options/locale/locale_si-LK.ini b/options/locale/locale_si-LK.ini index ad20959152644..fd790b14ccf31 100644 --- a/options/locale/locale_si-LK.ini +++ b/options/locale/locale_si-LK.ini @@ -115,7 +115,6 @@ missing_csrf=නරක ඉල්ලීම: CSRF ටෝකන් නොමැත [startpage] app_desc=වේදනාකාරී, ස්වයං-සත්කාරක Git සේවාවක් install=ස්ථාපනයට පහසුය -install_desc=සරලවම ඔබේ වේදිකාව සඳහා ද්විමය ධාවනය කරන්න, ඩොකර්සමඟ නැව්ගත කරන්න, නැතහොත් එය ලබා ගන්න ඇසුරුම්. platform=හරස් වේදිකාව platform_desc=Gitea ඕනෑම තැනක ධාවනය Go සඳහා සම්පාදනය කළ හැකිය: වින්ඩෝස්, මැකෝස්, ලිනක්ස්, ARM, ආදිය ඔබ ආදරය කරන එකක් තෝරන්න! lightweight=සැහැල්ලු @@ -230,6 +229,7 @@ filter=වෙනත් පෙරහන් filter_by_team_repositories=කණ්ඩායම් කෝෂ්ඨ අනුව පෙරන්න show_archived=සංරක්ෂිත +archived=සංරක්ෂිත show_both_archived_unarchived=සංරක්ෂිත සහ අක්රීය දෙකම පෙන්වීම show_only_archived=සංරක්ෂිත පමණක් පෙන්වයි show_only_unarchived=සංරක්ෂිත පමණක් පෙන්වීම @@ -465,7 +465,6 @@ overview=දළ විශ්ලේෂණය following=පහත සඳහන් follow=අනුගමනය කරන්න unfollow=අනුගමනය නොකරන්න -heatmap.loading=තාප සිතියම් පූරණය… user_bio=චරිතාපදානය disabled_public_activity=මෙම පරිශීලකයා ක්රියාකාරකම්වල මහජන දෘශ්යතාව අක්රීය කර ඇත. @@ -513,7 +512,6 @@ choose_new_avatar=නව අවතාරය තෝරන්න update_avatar=යාවත්කාලීන අවතාර් delete_current_avatar=වත්මන් අවතාරය මකන්න uploaded_avatar_not_a_image=උඩුගත කරන ලද ගොනුව රූපයක් නොවේ. -uploaded_avatar_is_too_big=උඩුගත කරන ලද ගොනුව උපරිම ප්රමාණය ඉක්මවා ඇත. update_avatar_success=ඔබගේ අවතාරය යාවත්කාලීන කර ඇත. update_user_avatar_success=පරිශීලකයාගේ අවතාරය යාවත්කාලීන කර ඇත. @@ -960,6 +958,9 @@ commits.signed_by_untrusted_user_unmatched=කමිටුව නොගැලප commits.gpg_key_id=ජීපීජී යතුරෙහි හැඳු. +commitstatus.error=දෝෂයකි +commitstatus.pending=වංගු + ext_issues.desc=බාහිර නිකුතුවකට සම්බන්ධ වන්න ට්රැකර්. projects=ව්‍යාපෘති @@ -1104,9 +1105,8 @@ issues.ref_reopening_from=මෙම ගැටළුව නැව issues.ref_closed_from=මෙම නිකුතුව%[4]s %[2]s issues.ref_reopened_from=මෙම නිකුතුව%[4]s %[2]sනැවත විවෘත කරන ලදි issues.ref_from=`හිම%[1]s` -issues.poster=පෝස්ටර් -issues.collaborator=සහයෝගීතාව -issues.owner=හිමිකරු +issues.role.owner=හිමිකරු +issues.role.member=සාමාජික issues.re_request_review=නැවත ඉල්ලීම සමාලෝචනය issues.is_stale=මෙම සමාලෝචනයේ සිට මෙම මහජන සම්බන්ධතා සඳහා වෙනස්කම් සිදුවී ඇත issues.remove_request_review=සමාලෝචන ඉල්ලීම ඉවත් කරන්න @@ -1369,8 +1369,6 @@ milestones.modify=සන්ධිස්ථානයක් යාවත්කා milestones.deletion=සන්ධිස්ථානය මකන්න milestones.deletion_desc=සන්ධිස්ථානයක් මකා දැමීම සම්බන්ධ සියලු ගැටළු වලින් එය ඉවත් කරයි. දිගටම? milestones.deletion_success=සන්ධිස්ථානය මකා දමා ඇත. -milestones.filter_sort.closest_due_date=ආසන්නතම නියමිත දිනය -milestones.filter_sort.furthest_due_date=වඩාත්ම නියමිත දිනය milestones.filter_sort.least_complete=අවම වශයෙන් සම්පූර්ණයි milestones.filter_sort.most_complete=වඩාත්ම සම්පූර්ණයි milestones.filter_sort.most_issues=බොහෝ ප්රශ්න @@ -1759,7 +1757,6 @@ settings.tags.protection.allowed.teams=ඉඩ දී ඇති කණ්ඩා settings.tags.protection.allowed.noone=එකක් නැත settings.tags.protection.create=ටැග ආරක්ෂා settings.tags.protection.none=ආරක්ෂිත ටැග් නොමැත. -settings.tags.protection.pattern.description=බහු ටැග් වලට ගැලපෙන පරිදි ඔබට තනි නමක් හෝ ග්ලෝබ් රටාවක් හෝ සාමාන්ය ප්රකාශනයක් භාවිතා කළ හැකිය. තව දුරටත් කියවන්න ආරක්ෂිත ටැග් මාර්ගෝපදේශය. settings.bot_token=බොට් ටෝකනය settings.chat_id=චැට් හැඳුනුම්පත settings.matrix.homeserver_url=හෝම්සර්වර් URL @@ -2199,12 +2196,10 @@ packages.repository=කෝෂ්ඨය packages.size=ප්‍රමාණය defaulthooks=පෙරනිමි වෙබ් කොකු -defaulthooks.desc=ඇතැම් Gitea සිදුවීම් අවුලුවාලන විට වෙබ් හූක්ස් ස්වයංක්රීයව සේවාදායකයකට HTTP පෝස්ට් ඉල්ලීම් කරයි. මෙහි අර්ථ දක්වා ඇති වෙබ්කොකු පැහැර හැරීම් වන අතර සියලු නව ගබඩාවන් වෙත පිටපත් කරනු ලැබේ. තව දුරටත් කියවන්න වෙබ් කොකු මාර්ගෝපදේශය. defaulthooks.add_webhook=පෙරනිමි වෙබ් හූක් එකතු කරන්න defaulthooks.update_webhook=පෙරනිමි වෙබ් හූක් යාවත්කාලීන කරන්න systemhooks=වෙබ් කොකු පද්ධතිය -systemhooks.desc=ඇතැම් Gitea සිදුවීම් අවුලුවාලන විට වෙබ් හූක්ස් ස්වයංක්රීයව සේවාදායකයකට HTTP පෝස්ට් ඉල්ලීම් කරයි. මෙහි අර්ථ Webhooks පද්ධතිය මත සියලු ගබඩාවන් මත ක්රියා කරනු ඇත, ඒ නිසා මෙම ඇති විය හැකි ඕනෑම කාර්ය සාධන ඇඟවුම් සලකා බලන්න. තව දුරටත් කියවන්න වෙබ් කොකු මාර්ගෝපදේශය. systemhooks.add_webhook=පද්ධතිය වෙබ්හූක් එකතු කරන්න systemhooks.update_webhook=වෙබ්හූක් පද්ධතිය යාවත්කාලීන @@ -2293,7 +2288,6 @@ auths.tip.google_plus=ගූගල් API කොන්සෝලය වෙති auths.tip.openid_connect=අන්ත ලක්ෂ්ය නියම කිරීම සඳහා OpenID Connect ඩිස්කවරි URL (/.හොඳින් දැන /openid-වින්යාසය) භාවිතා කරන්න auths.tip.twitter=https://dev.twitter.com/apps වෙත යන්න, යෙදුමක් සාදන්න සහ “මෙම යෙදුම ට්විටර් සමඟ පුරනය වීමට භාවිතා කිරීමට ඉඩ දෙන්න” විකල්පය සක්රීය කර ඇති බවට සහතික වන්න auths.tip.discord=https://discordapp.com/developers/applications/me හි නව අයදුම්පතක් ලියාපදිංචි කරන්න -auths.tip.gitea=නව OUTU2 අයදුම්පතක් ලියාපදිංචි කරන්න. මාර්ගෝපදේශය https://docs.gitea.io/en-us/oauth2-provider/ හි සොයාගත හැකිය auths.tip.yandex=https://oauth.yandex.com/client/new හි නව යෙදුමක් සාදන්න. “Yandex.Passport API” කොටසේ පහත සඳහන් අවසරයන් තෝරන්න: “විද්යුත් තැපැල් ලිපිනය වෙත ප්රවේශය”, “පරිශීලක අවතාර් වෙත ප්රවේශය” සහ “පරිශීලක නාමය, මුල් නම සහ වාසගම, ස්ත්රී පුරුෂ භාවය” auths.tip.mastodon=ඔබට සත්යාපනය කිරීමට අවශ්ය mastodon උදාහරණයක් සඳහා අභිරුචි උදාහරණයක් URL එකක් ආදාන කරන්න (හෝ පෙරනිමි එකක් භාවිතා කරන්න) auths.edit=සත්යාපන මූලාශ්රය සංස්කරණය කරන්න @@ -2452,8 +2446,6 @@ monitor.queue.type=වර්ගය monitor.queue.exemplar=ආදර්ශ වර්ගය monitor.queue.numberworkers=කම්කරුවන් සංඛ්යාව monitor.queue.maxnumberworkers=මැක්ස් කම්කරු සංඛ්යාව -monitor.queue.review=සමාලෝචන වින්යාසය -monitor.queue.review_add=සමාලෝචනය/කම්කරුවන් එකතු කරන්න monitor.queue.settings.title=තටාකය සැකසුම් monitor.queue.settings.maxnumberworkers=මැක්ස් කම්කරුවන් සංඛ්යාව monitor.queue.settings.maxnumberworkers.placeholder=වත්මන්%[1]d diff --git a/options/locale/locale_sk-SK.ini b/options/locale/locale_sk-SK.ini index 9eea6c4039ef1..4dfb27e7daf6f 100644 --- a/options/locale/locale_sk-SK.ini +++ b/options/locale/locale_sk-SK.ini @@ -130,7 +130,6 @@ network_error=Chyba siete [startpage] app_desc=Jednoducho prístupný vlastný Git install=Jednoduchá inštalácia -install_desc=Jednoducho spusťte binárku pre vašu platformu, dodávanú ako Docker, alebo ju získajte ako balík. platform=Multiplatformový platform_desc=Gitea beží všade kde je možné preložiť Go: Windows, macOS, Linux, ARM, a podobne. Vyberte si! lightweight=Ľahká @@ -257,6 +256,7 @@ filter_by_team_repositories=Filtrovať podľa tímových repozitárov feed_of=Informačný kanál „%s“ show_archived=Archivované +archived=Archivované show_both_archived_unarchived=Zobrazujú sa archivované aj nearchivované show_only_archived=Zobrazuje sa iba archivované show_only_unarchived=Zobrazuje sa iba nearchivované @@ -501,7 +501,6 @@ projects=Projekty following=Sledovaní follow=Sledovať unfollow=Zrušiť sledovanie -heatmap.loading=Načítanie teplotnej mapy… user_bio=Životopis disabled_public_activity=Tento používateľ zákázal verejnú viditeľnosť aktivity. @@ -565,7 +564,6 @@ choose_new_avatar=Vybrať nový avatar update_avatar=Aktualizovať avatar delete_current_avatar=Odstrániť aktuálny avatar uploaded_avatar_not_a_image=Nahraný súbor nieje obrázok. -uploaded_avatar_is_too_big=Nahraný súbor prekročil maximálnu veľkosť. update_avatar_success=Váš avatar sa aktualizoval. update_user_avatar_success=Užívateľov avatar bol aktualizovaný. @@ -951,6 +949,8 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=Vyberte vetvu pre cherry-pick na: +commitstatus.error=Chyba + ext_issues=Prístup k externým úkolom ext_issues.desc=Odkaz na externé sledovanie úkolov. @@ -996,7 +996,7 @@ issues.ref_closing_from=`odkazoval/a na pull request %[4]s, ktor issues.ref_reopening_from=`odkazoval/a na pull request %[4]s, ktorý znovu otvorí tento úkol %[2]s` issues.ref_closed_from=`uzavrel/a tento úkol %[4]s %[2]s` issues.ref_reopened_from=`znovu otvoril/a tento úkol %[4]s %[2]s` -issues.owner=Vlastník +issues.role.owner=Vlastník issues.re_request_review=Znovu požiadať o revíziu issues.is_stale=Od tejto kontroly došlo k zmenám v tomto pull requeste issues.remove_request_review=Odstrániť žiadosť o revíziu @@ -1213,12 +1213,10 @@ packages.owner=Vlastník packages.repository=Repozitár defaulthooks=Defaultné webhooky -defaulthooks.desc=Webhooky automaticky odosielajú požiadavky HTTP POST na server, keď sa spustia určité udalosti Gitea. Tu definované webhooky sú predvolené a skopírujú sa do všetkých nových repozitárov. Prečítajte si viac v sprievodcovi webhookmi. defaulthooks.add_webhook=Pridať defaultný webhook defaulthooks.update_webhook=Aktualizovať defaultný webhook systemhooks=Systémové webhooky -systemhooks.desc=Webhooky automaticky odosielajú požiadavky HTTP POST na server, keď sa spustia určité udalosti Gitea. Tu definované webhooky budú pôsobiť na všetky repozitáre v systéme, takže zvážte akékoľvek dôsledky na výkon, ktoré to môže mať. Prečítajte si viac v sprievodcovi webhookmi. systemhooks.add_webhook=Pridať systémový webhook systemhooks.update_webhook=Aktualizovať defaultný webhook @@ -1253,8 +1251,6 @@ config.oauth_enabled=Povolené monitor.process.cancel=Zrušiť proces -monitor.queue.review=Konfigurácia revidovania -monitor.queue.review_add=Revidovať/Pridať revidentov [action] diff --git a/options/locale/locale_sv-SE.ini b/options/locale/locale_sv-SE.ini index 2ae499b3ca897..f87f22b806f7f 100644 --- a/options/locale/locale_sv-SE.ini +++ b/options/locale/locale_sv-SE.ini @@ -103,7 +103,6 @@ name=Namn [startpage] app_desc=En smidig, självhostad Git-tjänst install=Lätt att installera -install_desc=Helt enkelt kör binären för din plattform, skicka den med Docker, eller få den paketerad. platform=Plattformsoberoende platform_desc=Gitea kan köra överallt där Go kan kompileras: Windows, macOS, Linux, ARM, etc. Välj den du gillar! lightweight=Lättviktig @@ -216,6 +215,7 @@ search_repos=Hitta en utvecklingskatalog… filter=Övriga Filter show_archived=Arkiverade +archived=Arkiverade show_both_archived_unarchived=Visar både arkiverade och icke arkiverade show_only_archived=Visar endast arkiverade show_only_unarchived=Visa endast icke arkiverade @@ -402,7 +402,6 @@ overview=Översikt following=Följer follow=Följ unfollow=Sluta följa -heatmap.loading=Laddar färgdiagram… user_bio=Biografi disabled_public_activity=Den här användaren har inaktiverat den publika synligheten av aktiviteten. @@ -447,7 +446,6 @@ choose_new_avatar=Välj ny avatar update_avatar=Uppdatera Avatar delete_current_avatar=Tag bort aktuell avatar uploaded_avatar_not_a_image=Den uppladdade filen är inte en bild. -uploaded_avatar_is_too_big=Den uppladdade filen överstiger den maximala filstorleken. update_avatar_success=Din avatar har blivit uppdaterad. change_password=Ändra Lösenordet @@ -815,6 +813,8 @@ commits.signed_by_untrusted_user_unmatched=Signerad av opålitlig användare som commits.gpg_key_id=GPG-nyckel ID +commitstatus.pending=Väntande + ext_issues.desc=Länk till externt ärendehanteringssystem. projects=Projekt @@ -948,9 +948,8 @@ issues.ref_reopening_from=`refererade till en pull-förfrågan % issues.ref_closed_from=`stängde detta ärende %[4]s %[2]s` issues.ref_reopened_from=`öpnnade detta ärende igen %[4]s %[2]s` issues.ref_from=`från %[1]s` -issues.poster=Skapare -issues.collaborator=Deltagare -issues.owner=Ägare +issues.role.owner=Ägare +issues.role.member=Medlem issues.re_request_review=Begär omgranskning issues.remove_request_review=Ta bort granskningsbegäran issues.remove_request_review_block=Kan inte ta bort granskningsbegäran @@ -1144,8 +1143,6 @@ milestones.modify=Uppdatera milstolpe milestones.deletion=Ta bort milstolpe milestones.deletion_desc=Borttagning av en milstolpe tar bort den från samtliga relaterade ärende. Fortsätta? milestones.deletion_success=Milstolpen har blivit borttagen. -milestones.filter_sort.closest_due_date=Närmaste förfallodatum -milestones.filter_sort.furthest_due_date=Mest avlägsna förfallodatum milestones.filter_sort.least_complete=Minst klar milestones.filter_sort.most_complete=Mest klar milestones.filter_sort.most_issues=Mest ärenden @@ -1962,8 +1959,6 @@ monitor.queue.name=Namn monitor.queue.type=Typ monitor.queue.numberworkers=Antal arbetare monitor.queue.maxnumberworkers=Max antal arbetare -monitor.queue.review=Granska konfiguration -monitor.queue.review_add=Granska/Lägg till arbetare monitor.queue.settings.submit=Uppdatera inställningar monitor.queue.settings.changed=Inställningar uppdaterade diff --git a/options/locale/locale_tr-TR.ini b/options/locale/locale_tr-TR.ini index d0250b5b34777..e35564ee535ea 100644 --- a/options/locale/locale_tr-TR.ini +++ b/options/locale/locale_tr-TR.ini @@ -181,7 +181,6 @@ network_error=Ağ hatası [startpage] app_desc=Zahmetsiz, kendi sunucunuzda barındırabileceğiniz Git servisi install=Kurulumu kolay -install_desc=Platformunuz için ikili dosyayı çalıştırın, Docker ile gönderin veya paketleyin. platform=Farklı platformlarda çalışablir platform_desc=Gitea Go ile derleme yapılabilecek her yerde çalışmaktadır: Windows, macOS, Linux, ARM, vb. Hangisini seviyorsanız onu seçin! lightweight=Hafif @@ -317,6 +316,7 @@ filter_by_team_repositories=Takım depolarına göre süz feed_of=`"%s" beslemesi` show_archived=Arşivlenmiş +archived=Arşivlenmiş show_both_archived_unarchived=Arşivlenenlerin ve arşivlenmeyenlerin tümü gösteriliyor show_only_archived=Yalnızca arşivlenenler gösteriliyor show_only_unarchived=Yalnızca arşivlenmeyenler gösteriliyor @@ -598,7 +598,6 @@ overview=Genel Bakış following=Takip Edilenler follow=Takip Et unfollow=Takibi Bırak -heatmap.loading=Isı haritası yükleniyor… user_bio=Biyografi disabled_public_activity=Bu kullanıcı, etkinliğin herkese görünür olmasını devre dışı bıraktı. email_visibility.limited=E-posta adresiniz giriş yapmış tüm kullanıcılar tarafından görünür @@ -680,7 +679,6 @@ choose_new_avatar=Yeni Avatar Seç update_avatar=Profil Resmini Güncelle delete_current_avatar=Güncel Avatarı Sil uploaded_avatar_not_a_image=Yüklenen dosya bir resim dosyası değil. -uploaded_avatar_is_too_big=Yüklenen dosya maksimum boyutu aştı. update_avatar_success=Profil resminiz değiştirildi. update_user_avatar_success=Kullanıcının avatarı güncellendi. @@ -1280,6 +1278,11 @@ commit.cherry-pick=Cımbızla commit.cherry-pick-header=Cımbızla: %s commit.cherry-pick-content=Cımbızlamak için dal seçin: +commitstatus.error=Hata +commitstatus.failure=Başarısız +commitstatus.pending=Beklemede +commitstatus.success=Başarılı + ext_issues=Harici Konulara Erişim ext_issues.desc=Dışsal konu takip sistemine bağla. @@ -1475,9 +1478,9 @@ issues.ref_reopening_from=`bir değişiklik isteğine referansta issues.ref_closed_from=`bu konuyu kapat%[4]s %[2]s` issues.ref_reopened_from=`konuyu yeniden aç%[4]s %[2]s` issues.ref_from=`%[1]s'den` -issues.poster=Poster -issues.collaborator=Katkıcı -issues.owner=Sahibi +issues.author=Yazar +issues.role.owner=Sahibi +issues.role.member=Üye issues.re_request_review=İncelemeyi yeniden iste issues.is_stale=Bu incelemeden bu yana bu istekte değişiklikler oldu issues.remove_request_review=İnceleme isteğini kaldır @@ -1815,8 +1818,6 @@ milestones.edit_success=`"%s" dönüm noktası güncellendi.` milestones.deletion=Kilometre Taşını Sil milestones.deletion_desc=Bir kilometre taşını silmek, onu ilgili tüm sorunlardan kaldırır. Devam edilsin mi? milestones.deletion_success=Kilometre taşı silindi. -milestones.filter_sort.closest_due_date=En yakın zamanı gelmiş tarih -milestones.filter_sort.furthest_due_date=En uzak zamanı gelmiş tarih milestones.filter_sort.least_complete=En az tamamlama milestones.filter_sort.most_complete=En çok tamamlama milestones.filter_sort.most_issues=En çok konu @@ -2314,7 +2315,6 @@ settings.tags.protection.allowed.teams=İzin verilen takımlar settings.tags.protection.allowed.noone=Hiç kimse settings.tags.protection.create=Etiketi Koru settings.tags.protection.none=Korumalı etiket yok. -settings.tags.protection.pattern.description=Birden çok etiketi eşleştirmek için tek bir ad, glob deseni veya normal ifade kullanabilirsiniz. Daha fazlası için korumalı etiketler rehberini okuyun. settings.bot_token=Bot Jetonu settings.chat_id=Sohbet Kimliği settings.thread_id=İş Parçacığı ID @@ -2853,12 +2853,10 @@ packages.size=Boyut packages.published=Yayınlandı defaulthooks=Varsayılan Web İstemcileri -defaulthooks.desc=Web İstemcileri, belirli Gitea olayları tetiklendiğinde otomatik olarak HTTP POST isteklerini sunucuya yapar. Burada tanımlanan Web İstemcileri varsayılandır ve tüm yeni depolara kopyalanır. web istemcileri kılavuzunda daha fazla bilgi edinin. defaulthooks.add_webhook=Varsayılan Web İstemcisi Ekle defaulthooks.update_webhook=Varsayılan Web İstemcisini Güncelle systemhooks=Sistem Web İstemcileri -systemhooks.desc=Belirli Gitea olayları tetiklendiğinde Web istemcileri otomatik olarak bir sunucuya HTTP POST istekleri yapar. Burada tanımlanan web istemcileri sistemdeki tüm depolar üzerinde çalışır, bu yüzden lütfen bunun olabilecek tüm performans sonuçlarını göz önünde bulundurun. web istemcileri kılavuzunda daha fazla bilgi edinin. systemhooks.add_webhook=Sistem Web İstemcisi Ekle systemhooks.update_webhook=Sistem Web İstemcisi Güncelle @@ -2963,7 +2961,6 @@ auths.tip.google_plus=OAuth2 istemci kimlik bilgilerini https://console.develope auths.tip.openid_connect=Bitiş noktalarını belirlemek için OpenID Connect Discovery URL'sini kullanın (/.well-known/openid-configuration) auths.tip.twitter=https://dev.twitter.com/apps adresine gidin, bir uygulama oluşturun ve “Bu uygulamanın Twitter ile oturum açmak için kullanılmasına izin ver” seçeneğinin etkin olduğundan emin olun auths.tip.discord=https://discordapp.com/developers/applications/me adresinde yeni bir uygulama kaydedin -auths.tip.gitea=Yeni bir OAuth2 uygulaması kaydedin. Rehber https://docs.gitea.io/en-us/oauth2-provider/ adresinde bulunabilir auths.tip.yandex=`https://oauth.yandex.com/client/new adresinde yeni bir uygulama oluşturun. "Yandex.Passport API'sı" bölümünden aşağıdaki izinleri seçin: "E-posta adresine erişim", "Kullanıcı avatarına erişim" ve "Kullanıcı adına, ad ve soyadına, cinsiyete erişim"` auths.tip.mastodon=Kimlik doğrulaması yapmak istediğiniz mastodon örneği için özel bir örnek URL girin (veya varsayılan olanı kullanın) auths.edit=Kimlik Doğrulama Kaynağı Düzenle @@ -3147,8 +3144,6 @@ monitor.queue.exemplar=Örnek Türü monitor.queue.numberworkers=Çalışan Sayısı monitor.queue.maxnumberworkers=En Fazla Çalışan Sayısı monitor.queue.numberinqueue=Kuyruktaki Sayı -monitor.queue.review=Yapılandırmayı İncele -monitor.queue.review_add=Çalışanları İncele/Ekle monitor.queue.settings.title=Havuz Ayarları monitor.queue.settings.desc=Havuzlar, çalışan kuyruğu tıkanmasına bir yanıt olarak dinamik olarak büyürler. monitor.queue.settings.maxnumberworkers=En fazla çalışan Sayısı diff --git a/options/locale/locale_uk-UA.ini b/options/locale/locale_uk-UA.ini index 85f34881d3209..be686dcdcc293 100644 --- a/options/locale/locale_uk-UA.ini +++ b/options/locale/locale_uk-UA.ini @@ -118,7 +118,6 @@ network_error=Помилка мережі [startpage] app_desc=Зручний власний сервіс хостингу репозиторіїв Git install=Легко встановити -install_desc=Просто запустіть виконуваний файл для вашої платформи, розміщуйте в Docker або встановіть пакунок. platform=Платформонезалежність platform_desc=Gitea виконується на платформі, для якої можливо скомпілювати Go: Windows, macOS, Linux, ARM, та інших. Оберіть ту, яка вам до вподоби! lightweight=Невибагливість @@ -244,6 +243,7 @@ filter_by_team_repositories=Фільтрувати за репозиторіям feed_of=`Стрічка "%s"` show_archived=Архівовані +archived=Архівовані show_both_archived_unarchived=Показано архівовані і не архівовані show_only_archived=Показано тільки архівовані show_only_unarchived=Показано тільки не архівовані @@ -481,7 +481,6 @@ overview=Огляд following=Читає follow=Підписатися unfollow=Відписатися -heatmap.loading=Завантаження карти активності… user_bio=Біографія disabled_public_activity=Цей користувач вимкнув публічний показ діяльності. @@ -534,7 +533,6 @@ choose_new_avatar=Оберіть новий аватар update_avatar=Оновити аватар delete_current_avatar=Видалити поточний аватар uploaded_avatar_not_a_image=Завантажений файл не є зображенням. -uploaded_avatar_is_too_big=Файл, що завантажувався, перевищив максимальний розмір. update_avatar_success=Ваш аватар був змінений. update_user_avatar_success=Аватар користувача оновлено. @@ -999,6 +997,9 @@ commits.signed_by_untrusted_user_unmatched=Підписаний недовіре commits.gpg_key_id=Ідентифікатор GPG ключа +commitstatus.error=Помилка +commitstatus.pending=Очікування + ext_issues=Доступ до зовнішніх задач ext_issues.desc=Посилання на зовнішню систему відстеження задач. @@ -1154,9 +1155,8 @@ issues.ref_reopening_from=`згадав запит на злит issues.ref_closed_from=`закрив цю задачу %[4]s %[2]s` issues.ref_reopened_from=`повторно відкрито цю задачу %[4]s %[2]s` issues.ref_from=`із %[1]s` -issues.poster=Автор -issues.collaborator=Співавтор -issues.owner=Власник +issues.role.owner=Власник +issues.role.member=Учасник issues.re_request_review=Повторно попросити рецензію issues.is_stale=З часу останньої перевірки в цей PR було внесено деякі зміни issues.remove_request_review=Видалити запит рецензування @@ -1419,8 +1419,6 @@ milestones.modify=Оновити етап milestones.deletion=Видалити етап milestones.deletion_desc=Видалення етапу призведе до його видалення з усіх пов'язаних задач. Продовжити? milestones.deletion_success=Етап успішно видалено. -milestones.filter_sort.closest_due_date=Найближче за датою -milestones.filter_sort.furthest_due_date=Далі за датою milestones.filter_sort.least_complete=Менш повне milestones.filter_sort.most_complete=Більш повне milestones.filter_sort.most_issues=Найбільш задач @@ -1810,7 +1808,6 @@ settings.tags.protection.allowed.teams=Дозволені команди settings.tags.protection.allowed.noone=Ніхто settings.tags.protection.create=Захистна мітка settings.tags.protection.none=Там не немає захищених міток. -settings.tags.protection.pattern.description=Ви можете використовувати одне ім'я або глобальний шаблон або регулярний вираз для декількох тегів.. Детальніше в посібнику із захищених тегів. settings.bot_token=Токен для бота settings.chat_id=Чат ID settings.matrix.homeserver_url=URL домашньої сторінки @@ -2253,12 +2250,10 @@ packages.repository=Репозиторій packages.size=Розмір defaulthooks=Веб-хуки за замовчуванням -defaulthooks.desc=Веб-хуки автоматично створюють HTTP POST-запити до сервера, коли виконуються певні події Gitea. Визначені тут веб-хуки є типовими і копіюються у всі нові сховища. Детальніше читайте в інструкції по використанню web-хуків. defaulthooks.add_webhook=Додати веб-хук за замовчуванням defaulthooks.update_webhook=Змінити веб-хук за замовчуванням systemhooks=Системні вебхуки -systemhooks.desc=Веб-хуки автоматично створюють HTTP POST-запити до сервера, коли виконуються певні тригери в Gitea. Визначені веб-хуки є типовими і копіюються у всі нові сховища. Детальніше читайте в інструкції по використанню web-хуків. systemhooks.add_webhook=Додати системний вебхук systemhooks.update_webhook=Оновити системний вебхук @@ -2347,7 +2342,6 @@ auths.tip.google_plus=Отримайте облікові дані клієнт auths.tip.openid_connect=Використовуйте OpenID Connect Discovery URL (/.well-known/openid-configuration) для автоматичної настройки входу OAuth auths.tip.twitter=Перейдіть на https://dev.twitter.com/apps, створіть програму і переконайтеся, що включена опція «Дозволити цю програму для входу в систему за допомогою Twitter» auths.tip.discord=Зареєструйте новий додаток на https://discordapp.com/developers/applications/me -auths.tip.gitea=Зареєструйте новий додаток OAuth2. Керівництво можна знайти на https://docs.gitea.io/en-us/oauth2-provider/ auths.tip.yandex=`Створіть нову програму в https://oauth.yandex.com/client/new. Виберіть наступні дозволи з "Yandex. assport API": "Доступ до адреси електронної пошти", "Доступ до аватара" і "Доступ до імені користувача, імені та прізвища, статі"` auths.tip.mastodon=Введіть URL спеціального екземпляра для екземпляра mastodon, який ви хочете автентифікувати за допомогою (або використовувати за замовчуванням) auths.edit=Редагувати джерело автентифікації @@ -2508,8 +2502,6 @@ monitor.queue.type=Тип monitor.queue.exemplar=Приклад типу monitor.queue.numberworkers=Кількість робочих потоків monitor.queue.maxnumberworkers=Максимальна кількість робочих потоків -monitor.queue.review=Переглянути налаштування -monitor.queue.review_add=Перевірка/додавання потоків monitor.queue.settings.title=Налаштування пулу monitor.queue.settings.maxnumberworkers=Максимальна кількість робочих потоків monitor.queue.settings.maxnumberworkers.placeholder=Поточний %[1]d diff --git a/options/locale/locale_zh-CN.ini b/options/locale/locale_zh-CN.ini index 58d1e80a37da8..0cd71af710733 100644 --- a/options/locale/locale_zh-CN.ini +++ b/options/locale/locale_zh-CN.ini @@ -166,7 +166,6 @@ network_error=网络错误 [startpage] app_desc=一款极易搭建的自助 Git 服务 install=易安装 -install_desc=您除了可以根据操作系统平台通过 二进制运行,还可以通过 DockerVagrant,以及 包管理 安装。 platform=跨平台 platform_desc=任何 Go 语言 支持的平台都可以运行 Gitea,包括 Windows、Mac、Linux 以及 ARM。挑一个您喜欢的就行! lightweight=轻量级 @@ -299,6 +298,7 @@ filter_by_team_repositories=按团队仓库筛选 feed_of=`"%s"的源` show_archived=已归档 +archived=已归档 show_both_archived_unarchived=显示已归档和未归档的 show_only_archived=只显示已归档的 show_only_unarchived=只显示未归档的 @@ -570,7 +570,6 @@ overview=概览 following=关注中 follow=关注 unfollow=取消关注 -heatmap.loading=正在加载热图... user_bio=简历 disabled_public_activity=该用户已隐藏活动记录。 email_visibility.limited=所有已认证用户均可看到您的电子邮件地址 @@ -643,7 +642,6 @@ choose_new_avatar=选择新的头像 update_avatar=更新头像 delete_current_avatar=删除当前头像 uploaded_avatar_not_a_image=上传的文件不是一张图片。 -uploaded_avatar_is_too_big=上传的文件超过了最大大小。 update_avatar_success=您的头像已更新。 update_user_avatar_success=用户头像已更新。 @@ -1190,6 +1188,11 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=选择 cherry-pick 的目标分支: +commitstatus.error=错误 +commitstatus.failure=失败 +commitstatus.pending=待定 +commitstatus.success=成功 + ext_issues=访问外部工单 ext_issues.desc=链接到外部工单跟踪系统。 @@ -1375,9 +1378,9 @@ issues.ref_reopening_from=`于 %[2]s 关闭了这个工单 %[4]s %[2]s` issues.ref_reopened_from=`重新打开这个工单 %[4]s %[2]s` issues.ref_from=`来自 %[1]s` -issues.poster=发布者 -issues.collaborator=协作者 -issues.owner=所有者 +issues.author=作者 +issues.role.owner=管理员 +issues.role.member=普通成员 issues.re_request_review=再次请求审核 issues.is_stale=此评审之后代码有更新 issues.remove_request_review=移除审核请求 @@ -1687,8 +1690,6 @@ milestones.edit_success=里程碑 %s 已经更新。 milestones.deletion=删除里程碑 milestones.deletion_desc=删除该里程碑将会移除所有工单中相关的信息。是否继续? milestones.deletion_success=里程碑已被删除。 -milestones.filter_sort.closest_due_date=到期日从近到远 -milestones.filter_sort.furthest_due_date=到期日从远到近 milestones.filter_sort.least_complete=完成度从低到高 milestones.filter_sort.most_complete=完成度从高到低 milestones.filter_sort.most_issues=工单从多到少 @@ -2144,7 +2145,6 @@ settings.tags.protection.allowed.teams=允许的团队 settings.tags.protection.allowed.noone=无 settings.tags.protection.create=保护Git标签 settings.tags.protection.none=没有受保护的Git标签 -settings.tags.protection.pattern.description=你可以使用单个名称或 glob 模式匹配或正则表达式来匹配多个标签。了解更多请阅读 受保护Git标签指南 settings.bot_token=Bot 令牌 settings.chat_id=聊天 ID settings.matrix.homeserver_url=主服务器网址 @@ -2656,12 +2656,10 @@ packages.size=大小 packages.published=已发布 defaulthooks=默认Web钩子 -defaulthooks.desc=当某些 Gitea 事件触发时,Web 钩子自动向服务器发出 HTTP POST 请求。这里定义的 Web 钩子是默认配置,将被复制到所有新的仓库中。详情请访问 Web 钩子指南。 defaulthooks.add_webhook=添加默认Web 钩子 defaulthooks.update_webhook=更新默认 Web 钩子 systemhooks=系统 Web 钩子 -systemhooks.desc=当某些 Gitea 事件触发时,Web 钩子自动向服务器发出HTTP POST请求。这里定义的 Web 钩子将作用于系统上的所有仓库,所以请考虑这可能带来的任何性能影响。了解详情请访问 Web 钩子指南。 systemhooks.add_webhook=添加系统 Web 钩子 systemhooks.update_webhook=更新系统 Web 钩子 @@ -2765,7 +2763,6 @@ auths.tip.google_plus=从谷歌 API 控制台 (https://console.developers.google auths.tip.openid_connect=使用 OpenID 连接发现 URL (/.well-known/openid-configuration) 来指定终点 auths.tip.twitter=访问 https://dev.twitter.com/apps,创建应用并确保启用了"允许此应用程序用于登录 Twitter"的选项。 auths.tip.discord=在 https://discordapp.com/developers/applications/me 上注册新应用程序 -auths.tip.gitea=注册一个新的 OAuth2 应用程序,可以访问 https://docs.gitea.io/en-us/oauth2-provider/ 查看帮助 。 auths.tip.yandex=在 https://oauth.yandex.com/client/new 上创建一个新的应用程序。在“ Yandex.Passport API”这部分中选择以下权限:“访问电子邮件地址(Access to email address)”,“访问用户头像(Access to user avatar)”和“访问用户名,名字和姓氏,性别(Access to username, first name and surname, genderAccess to username, first name and surname, gender)” auths.tip.mastodon=输入您想要认证的 mastodon 实例的自定义 URL (或使用默认值) auths.edit=修改认证源 @@ -2942,8 +2939,6 @@ monitor.queue.exemplar=数据类型 monitor.queue.numberworkers=工作者数量 monitor.queue.maxnumberworkers=最大工作者数量 monitor.queue.numberinqueue=队列中的数量 -monitor.queue.review=查看配置 -monitor.queue.review_add=查看/添加工作者 monitor.queue.settings.title=池设置 monitor.queue.settings.maxnumberworkers=最大工作者数量 monitor.queue.settings.maxnumberworkers.placeholder=当前 %[1]d diff --git a/options/locale/locale_zh-HK.ini b/options/locale/locale_zh-HK.ini index 8ec1051916c21..2cdea9feadc88 100644 --- a/options/locale/locale_zh-HK.ini +++ b/options/locale/locale_zh-HK.ini @@ -384,6 +384,7 @@ commits.signed_by=簽署人 + projects.description_placeholder=組織描述 projects.title=標題 projects.template.desc=樣板 @@ -449,9 +450,8 @@ issues.context.edit=編輯 issues.reopen_issue=重新開啟 issues.create_comment=評論 issues.commit_ref_at=`在代碼提交 %[2]s 中引用了該問題` -issues.poster=發佈者 -issues.collaborator=協同者 -issues.owner=所有者 +issues.role.owner=管理員 +issues.role.member=普通成員 issues.sign_in_require_desc= 登入 才能加入這對話。 issues.edit=編輯 issues.cancel=取消 @@ -509,8 +509,6 @@ milestones.due_date=截止日期(可選) milestones.clear=清除 milestones.edit=編輯里程碑 milestones.cancel=取消 -milestones.filter_sort.closest_due_date=到期日由近到遠 -milestones.filter_sort.furthest_due_date=到期日由遠到近 milestones.filter_sort.least_complete=完成度由低到高 milestones.filter_sort.most_complete=完成度由高到低 milestones.filter_sort.most_issues=問題由多到少 @@ -565,7 +563,6 @@ settings.danger_zone=危險操作區 settings.new_owner_has_same_repo=新的儲存庫擁有者已經存在同名儲存庫! settings.transfer=轉移儲存庫所有權 settings.transfer_owner=新擁有者 -settings.trust_model.collaborator=協同者 settings.delete=刪除本儲存庫 settings.delete_notices_1=- 此操作 不可以 被回滾。 settings.delete_collaborator=移除成員 diff --git a/options/locale/locale_zh-TW.ini b/options/locale/locale_zh-TW.ini index 1d0342a48d916..3c23f9eb2037e 100644 --- a/options/locale/locale_zh-TW.ini +++ b/options/locale/locale_zh-TW.ini @@ -167,7 +167,6 @@ network_error=網路錯誤 [startpage] app_desc=一套極易架設的 Git 服務 install=安裝容易 -install_desc=簡單地執行您平台的二進位檔,或是使用 Docker,你也可以從套件管理員安裝。 platform=跨平台 platform_desc=Gitea 可以在所有能編譯 Go 語言的平台上執行: Windows, macOS, Linux, ARM 等等。挑一個您喜歡的吧! lightweight=輕量級 @@ -300,6 +299,7 @@ filter_by_team_repositories=以團隊儲存庫篩選 feed_of=「%s」的訊息來源 show_archived=已封存 +archived=已封存 show_both_archived_unarchived=顯示已封存和未封存 show_only_archived=只顯示已封存 show_only_unarchived=只顯示未封存 @@ -571,7 +571,6 @@ overview=概覽 following=追蹤中 follow=追蹤 unfollow=取消追蹤 -heatmap.loading=正在載入熱點圖... user_bio=個人簡介 disabled_public_activity=這個使用者已對外隱藏動態 email_visibility.limited=所有已驗證的使用者都可以看到您的電子信箱地址 @@ -641,7 +640,6 @@ choose_new_avatar=選擇新的大頭貼 update_avatar=更新大頭貼 delete_current_avatar=刪除目前的大頭貼 uploaded_avatar_not_a_image=上傳的檔案不是圖片 -uploaded_avatar_is_too_big=上傳的檔案大小超過了最大限制 update_avatar_success=您的大頭貼已更新 update_user_avatar_success=已更新使用者的大頭貼。 @@ -1183,6 +1181,11 @@ commit.cherry-pick=Cherry-pick commit.cherry-pick-header=Cherry-pick: %s commit.cherry-pick-content=選擇 Cherry-pick 的目標分支: +commitstatus.error=錯誤 +commitstatus.failure=失敗 +commitstatus.pending=待處理 +commitstatus.success=成功 + ext_issues=存取外部問題 ext_issues.desc=連結到外部問題追蹤器。 @@ -1367,9 +1370,9 @@ issues.ref_reopening_from=`關聯了合併請求 %[4]s 將重新 issues.ref_closed_from=`關閉了這個問題 %[4]s %[2]s` issues.ref_reopened_from=`重新開放了這個問題 %[4]s %[2]s` issues.ref_from=`自 %[1]s` -issues.poster=發布者 -issues.collaborator=協作者 -issues.owner=擁有者 +issues.author=作者 +issues.role.owner=擁有者 +issues.role.member=普通成員 issues.re_request_review=再次請求審核 issues.is_stale=經過此審核以後,此合併請求有被修改 issues.remove_request_review=移除審核請求 @@ -1679,8 +1682,6 @@ milestones.edit_success=已更新里程碑「%s」。 milestones.deletion=刪除里程碑 milestones.deletion_desc=刪除里程碑會從所有相關的問題移除它。是否繼續? milestones.deletion_success=里程碑已刪除 -milestones.filter_sort.closest_due_date=截止日期由近到遠 -milestones.filter_sort.furthest_due_date=截止日期由遠到近 milestones.filter_sort.least_complete=完成度由低到高 milestones.filter_sort.most_complete=完成度由高到低 milestones.filter_sort.most_issues=問題由多到少 @@ -2134,7 +2135,6 @@ settings.tags.protection.allowed.teams=允許的團隊 settings.tags.protection.allowed.noone=無 settings.tags.protection.create=保護標籤 settings.tags.protection.none=沒有受保護的標籤。 -settings.tags.protection.pattern.description=您可以使用單一名稱、Glob 模式、正規表示式來配對多個標籤。在受保護的標籤指南閱讀更多內容。 settings.bot_token=Bot Token settings.chat_id=Chat ID settings.matrix.homeserver_url=Homeserver 網址 @@ -2642,12 +2642,10 @@ packages.size=大小 packages.published=已發布 defaulthooks=預設 Webhook -defaulthooks.desc=當觸發某些 Gitea 事件時,Webhook 會自動發出 HTTP POST 請求到指定的伺服器。這裡所定義的 Webhook 是預設的,並且會複製到所有新儲存庫。在 Webhook 指南閱讀更多內容。 defaulthooks.add_webhook=新增預設 Webhook defaulthooks.update_webhook=更新預設 Webhook systemhooks=系統 Webhook -systemhooks.desc=當觸發某些 Gitea 事件時,Webhook 會自動發出 HTTP POST 請求到指定的伺服器。由於這裡所定義的 Webhook 會影響此系統上的所有儲存庫,因此請評估這會對效能造成多少影響。在 Webhook 指南閱讀更多內容。 systemhooks.add_webhook=新增系統 Webhook systemhooks.update_webhook=更新系統 Webhook @@ -2751,7 +2749,6 @@ auths.tip.google_plus=從 Google API 控制台取得 OAuth2 用戶端憑證。 auths.tip.openid_connect=使用 OpenID 連接探索 URL (/.well-known/openid-configuration) 來指定節點 auths.tip.twitter=建立應用程式並確保有啟用「Allow this application to be used to Sign in with Twitter」。網址:https://dev.twitter.com/apps auths.tip.discord=註冊新的應用程式。網址:https://discordapp.com/developers/applications/me -auths.tip.gitea=註冊新的 OAuth2 應用程式。到 https://docs.gitea.io/en-us/oauth2-provider/ 觀看指南 auths.tip.yandex=建立新的應用程式,從「Yandex.Passport API」區塊選擇「Access to email address」、「Access to user avatar」和「Access to username, first name and surname, gender」。網址:https://oauth.yandex.com/client/new auths.tip.mastodon=輸入您欲認證的 Mastodon 執行個體的自訂網址 (或使用預設值) auths.edit=修改認證來源 @@ -2928,8 +2925,6 @@ monitor.queue.exemplar=型別 monitor.queue.numberworkers=工作者數量 monitor.queue.maxnumberworkers=最大工作者數量 monitor.queue.numberinqueue=佇列中的數量 -monitor.queue.review=檢視組態 -monitor.queue.review_add=檢視/新增工作者 monitor.queue.settings.title=集區設定 monitor.queue.settings.maxnumberworkers=最大工作者數量 monitor.queue.settings.maxnumberworkers.placeholder=目前 %[1]d From 7cdbe65a2c3ea5a4d958d40428713f6699a22337 Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Sat, 16 Sep 2023 11:15:21 +0800 Subject: [PATCH 10/23] Add tests for db indexer in indexer_test.go (#27087) As described in the title. Some points: 1. Why need those tests? Because `buildIssueOverview` is not well tested, there are several continuous bugs in the issue overview webpage. 2. Why in indexer_test.go? It's hard to put those tests in `./modules/indexer/issue/db/db_test.go` because those tests need 'real' data in db mocked by fixtures instead of random data in `./modules/indexer/issue/internal/tests`. When using 'real' data(`unittest.PrepareTestDatabase`), `InitIssueIndexer` and the package `init()` function of `indexer` are required to init indexer. 3. Why only db? The other three indexer engines are well tested by random data and it's okay to also test them with 'real' data in db mocked by fixtures. Any follow-up PR is welcome. 4. Those tests are really basic, any more complicated tests are welcome. 5. I think it's also necessary to add tests in `TestAPISearchIssues` in`api_test_issue.go` and `TestIssues` in `home_test.go` --- modules/indexer/issues/indexer_test.go | 455 ++++++++++++++++++------- 1 file changed, 324 insertions(+), 131 deletions(-) diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index c3a6d88685147..0e36d21313737 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -5,14 +5,12 @@ package issues import ( "context" - "fmt" - "path" "path/filepath" "testing" - "time" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" - "code.gitea.io/gitea/modules/indexer/issues/bleve" + "code.gitea.io/gitea/modules/indexer/issues/internal" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -29,186 +27,381 @@ func TestMain(m *testing.M) { }) } -func TestBleveSearchIssues(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - setting.CfgProvider, _ = setting.NewConfigProviderFromData("") - - tmpIndexerDir := t.TempDir() - - setting.CfgProvider.Section("queue.issue_indexer").Key("DATADIR").MustString(path.Join(tmpIndexerDir, "issues.queue")) - - oldIssuePath := setting.Indexer.IssuePath - setting.Indexer.IssuePath = path.Join(tmpIndexerDir, "issues.queue") - defer func() { - setting.Indexer.IssuePath = oldIssuePath - }() - - setting.Indexer.IssueType = "bleve" - setting.LoadQueueSettings() - InitIssueIndexer(true) - defer func() { - if bleveIndexer, ok := (*globalIndexer.Load()).(*bleve.Indexer); ok { - bleveIndexer.Close() - } - }() - - time.Sleep(5 * time.Second) - - t.Run("issue2", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "issue2", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.EqualValues(t, []int64{2}, ids) - }) - - t.Run("first", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "first", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.EqualValues(t, []int64{1}, ids) - }) - - t.Run("for", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "for", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.ElementsMatch(t, []int64{1, 2, 3, 5, 11}, ids) - }) - - t.Run("good", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "good", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.EqualValues(t, []int64{1}, ids) - }) -} - -func TestDBSearchIssuesWithKeyword(t *testing.T) { +func TestDBSearchIssues(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) setting.Indexer.IssueType = "db" InitIssueIndexer(true) - t.Run("issue2", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "issue2", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.EqualValues(t, []int64{2}, ids) - }) - - t.Run("first", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "first", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.EqualValues(t, []int64{1}, ids) - }) + t.Run("search issues with keyword", searchIssueWithKeyword) + t.Run("search issues in repo", searchIssueInRepo) + t.Run("search issues by ID", searchIssueByID) + t.Run("search issues is pr", searchIssueIsPull) + t.Run("search issues is closed", searchIssueIsClosed) + t.Run("search issues by milestone", searchIssueByMilestoneID) + t.Run("search issues by label", searchIssueByLabelID) + t.Run("search issues by time", searchIssueByTime) + t.Run("search issues with order", searchIssueWithOrder) + t.Run("search issues in project", searchIssueInProject) + t.Run("search issues with paginator", searchIssueWithPaginator) +} - t.Run("for", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "for", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.ElementsMatch(t, []int64{1, 2, 3, 5, 11}, ids) - }) +func searchIssueWithKeyword(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + Keyword: "issue2", + RepoIDs: []int64{1}, + }, + []int64{2}, + }, + { + SearchOptions{ + Keyword: "first", + RepoIDs: []int64{1}, + }, + []int64{1}, + }, + { + SearchOptions{ + Keyword: "for", + RepoIDs: []int64{1}, + }, + []int64{11, 5, 3, 2, 1}, + }, + { + SearchOptions{ + Keyword: "good", + RepoIDs: []int64{1}, + }, + []int64{1}, + }, + } - t.Run("good", func(t *testing.T) { - ids, _, err := SearchIssues(context.TODO(), &SearchOptions{ - Keyword: "good", - RepoIDs: []int64{1}, - }) - assert.NoError(t, err) - assert.EqualValues(t, []int64{1}, ids) - }) + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } } -// TODO: add more tests -func TestDBSearchIssueWithoutKeyword(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) +func searchIssueInRepo(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + RepoIDs: []int64{1}, + }, + []int64{11, 5, 3, 2, 1}, + }, + { + SearchOptions{ + RepoIDs: []int64{2}, + }, + []int64{7, 4}, + }, + { + SearchOptions{ + RepoIDs: []int64{3}, + }, + []int64{12, 6}, + }, + { + SearchOptions{ + RepoIDs: []int64{4}, + }, + []int64{}, + }, + { + SearchOptions{ + RepoIDs: []int64{5}, + }, + []int64{15}, + }, + } - setting.Indexer.IssueType = "db" - InitIssueIndexer(true) + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} +func searchIssueByID(t *testing.T) { int64Pointer := func(x int64) *int64 { return &x } - for _, test := range []struct { + tests := []struct { opts SearchOptions expectedIDs []int64 }{ { SearchOptions{ - RepoIDs: []int64{1}, + PosterID: int64Pointer(1), }, - []int64{11, 5, 3, 2, 1}, + []int64{11, 6, 3, 2, 1}, }, { SearchOptions{ - RepoIDs: []int64{1}, AssigneeID: int64Pointer(1), }, + []int64{6, 1}, + }, + { + SearchOptions{ + MentionID: int64Pointer(4), + }, []int64{1}, }, { SearchOptions{ - RepoIDs: []int64{1}, - PosterID: int64Pointer(1), + ReviewedID: int64Pointer(1), + }, + []int64{}, + }, + { + SearchOptions{ + ReviewRequestedID: int64Pointer(1), + }, + []int64{12}, + }, + { + SearchOptions{ + SubscriberID: int64Pointer(1), + }, + []int64{11, 6, 5, 3, 2, 1}, + }, + } + + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueIsPull(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + IsPull: util.OptionalBoolFalse, + }, + []int64{17, 16, 15, 14, 13, 6, 5, 18, 10, 7, 4, 1}, + }, + { + SearchOptions{ + IsPull: util.OptionalBoolTrue, }, - []int64{11, 3, 2, 1}, + []int64{12, 11, 19, 9, 8, 3, 2}, }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueIsClosed(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ { SearchOptions{ - RepoIDs: []int64{1}, IsClosed: util.OptionalBoolFalse, }, - []int64{11, 3, 2, 1}, + []int64{17, 16, 15, 14, 13, 12, 11, 6, 19, 18, 10, 7, 9, 8, 3, 2, 1}, }, { SearchOptions{ - RepoIDs: []int64{1}, IsClosed: util.OptionalBoolTrue, }, - []int64{5}, + []int64{5, 4}, + }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueByMilestoneID(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + MilestoneIDs: []int64{1}, + }, + []int64{2}, }, { SearchOptions{ - RepoIDs: []int64{1}, + MilestoneIDs: []int64{3}, }, - []int64{11, 5, 3, 2, 1}, + []int64{3}, + }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueByLabelID(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + IncludedLabelIDs: []int64{1}, + }, + []int64{2, 1}, }, { SearchOptions{ - RepoIDs: []int64{1}, - AssigneeID: int64Pointer(1), + IncludedLabelIDs: []int64{4}, + }, + []int64{2}, + }, + { + SearchOptions{ + ExcludedLabelIDs: []int64{1}, + }, + []int64{17, 16, 15, 14, 13, 12, 11, 6, 5, 19, 18, 10, 7, 4, 9, 8, 3}, + }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueByTime(t *testing.T) { + int64Pointer := func(i int64) *int64 { + return &i + } + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + UpdatedAfterUnix: int64Pointer(0), + }, + []int64{17, 16, 15, 14, 13, 12, 11, 6, 5, 19, 18, 10, 7, 4, 9, 8, 3, 2, 1}, + }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueWithOrder(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + SortBy: internal.SortByCreatedAsc, + }, + []int64{1, 2, 3, 8, 9, 4, 7, 10, 18, 19, 5, 6, 11, 12, 13, 14, 15, 16, 17}, + }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueInProject(t *testing.T) { + int64Pointer := func(i int64) *int64 { + return &i + } + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + ProjectID: int64Pointer(1), + }, + []int64{5, 3, 2, 1}, + }, + { + SearchOptions{ + ProjectBoardID: int64Pointer(1), }, []int64{1}, }, + } + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueWithPaginator(t *testing.T) { + tests := []struct { + opts SearchOptions + expectedIDs []int64 + expectedTotal int64 + }{ { SearchOptions{ - RepoIDs: []int64{1}, - PosterID: int64Pointer(1), + Paginator: &db.ListOptions{ + PageSize: 5, + }, }, - []int64{11, 3, 2, 1}, + []int64{17, 16, 15, 14, 13}, + 19, }, - } { - t.Run(fmt.Sprintf("%#v", test.opts), func(t *testing.T) { - issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } - assert.Equal(t, test.expectedIDs, issueIDs) - }) + } + for _, test := range tests { + issueIDs, total, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + assert.Equal(t, test.expectedTotal, total) } } From f3f445862e0962b673b5e0d3d12b00c3f7001d85 Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Sat, 16 Sep 2023 05:51:54 +0200 Subject: [PATCH 11/23] Use `print` instead of `printf` (#27093) A bit more performant when we only use it for appending strings. --- templates/explore/repo_search.tmpl | 2 +- templates/repo/commit_page.tmpl | 10 +++++----- templates/repo/commits_list.tmpl | 10 +++++----- templates/repo/commits_list_small.tmpl | 10 +++++----- templates/repo/create_helper.tmpl | 2 +- templates/repo/graph/commits.tmpl | 10 +++++----- templates/repo/home.tmpl | 2 +- 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/templates/explore/repo_search.tmpl b/templates/explore/repo_search.tmpl index c056662fb89c8..0731368e85da2 100644 --- a/templates/explore/repo_search.tmpl +++ b/templates/explore/repo_search.tmpl @@ -36,7 +36,7 @@ {{if and .PageIsExploreRepositories .OnlyShowRelevant}}
- {{.locale.Tr "explore.relevant_repositories" ((printf "%s%s" $.Link "?only_show_relevant=0")|Escape) | Safe}} + {{.locale.Tr "explore.relevant_repositories" ((print $.Link "?only_show_relevant=0")|Escape) | Safe}}
{{end}}
diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl index 612c0f94cab60..8e56b435536b4 100644 --- a/templates/repo/commit_page.tmpl +++ b/templates/repo/commit_page.tmpl @@ -4,17 +4,17 @@
{{$class := ""}} {{if .Commit.Signature}} - {{$class = (printf "%s%s" $class " isSigned")}} + {{$class = (print $class " isSigned")}} {{if .Verification.Verified}} {{if eq .Verification.TrustStatus "trusted"}} - {{$class = (printf "%s%s" $class " isVerified")}} + {{$class = (print $class " isVerified")}} {{else if eq .Verification.TrustStatus "untrusted"}} - {{$class = (printf "%s%s" $class " isVerifiedUntrusted")}} + {{$class = (print $class " isVerifiedUntrusted")}} {{else}} - {{$class = (printf "%s%s" $class " isVerifiedUnmatched")}} + {{$class = (print $class " isVerifiedUnmatched")}} {{end}} {{else if .Verification.Warning}} - {{$class = (printf "%s%s" $class " isWarning")}} + {{$class = (print $class " isWarning")}} {{end}} {{end}}
diff --git a/templates/repo/commits_list.tmpl b/templates/repo/commits_list.tmpl index a06c425b73dff..7ecbc8f8844bf 100644 --- a/templates/repo/commits_list.tmpl +++ b/templates/repo/commits_list.tmpl @@ -28,17 +28,17 @@ {{$class := "ui sha label"}} {{if .Signature}} - {{$class = (printf "%s%s" $class " isSigned")}} + {{$class = (print $class " isSigned")}} {{if .Verification.Verified}} {{if eq .Verification.TrustStatus "trusted"}} - {{$class = (printf "%s%s" $class " isVerified")}} + {{$class = (print $class " isVerified")}} {{else if eq .Verification.TrustStatus "untrusted"}} - {{$class = (printf "%s%s" $class " isVerifiedUntrusted")}} + {{$class = (print $class " isVerifiedUntrusted")}} {{else}} - {{$class = (printf "%s%s" $class " isVerifiedUnmatched")}} + {{$class = (print $class " isVerifiedUnmatched")}} {{end}} {{else if .Verification.Warning}} - {{$class = (printf "%s%s" $class " isWarning")}} + {{$class = (print $class " isWarning")}} {{end}} {{end}} {{$commitShaLink := ""}} diff --git a/templates/repo/commits_list_small.tmpl b/templates/repo/commits_list_small.tmpl index b5a7134294da0..645bd73bb82f8 100644 --- a/templates/repo/commits_list_small.tmpl +++ b/templates/repo/commits_list_small.tmpl @@ -17,17 +17,17 @@ {{template "repo/commit_statuses" dict "Status" .Status "Statuses" .Statuses "root" $.root}} {{$class := "ui sha label"}} {{if .Signature}} - {{$class = (printf "%s%s" $class " isSigned")}} + {{$class = (print $class " isSigned")}} {{if .Verification.Verified}} {{if eq .Verification.TrustStatus "trusted"}} - {{$class = (printf "%s%s" $class " isVerified")}} + {{$class = (print $class " isVerified")}} {{else if eq .Verification.TrustStatus "untrusted"}} - {{$class = (printf "%s%s" $class " isVerifiedUntrusted")}} + {{$class = (print $class " isVerifiedUntrusted")}} {{else}} - {{$class = (printf "%s%s" $class " isVerifiedUnmatched")}} + {{$class = (print $class " isVerifiedUnmatched")}} {{end}} {{else if .Verification.Warning}} - {{$class = (printf "%s%s" $class " isWarning")}} + {{$class = (print $class " isWarning")}} {{end}} {{end}} diff --git a/templates/repo/create_helper.tmpl b/templates/repo/create_helper.tmpl index ec253e961d3a7..4b91cdf075e71 100644 --- a/templates/repo/create_helper.tmpl +++ b/templates/repo/create_helper.tmpl @@ -1,3 +1,3 @@ {{if not $.DisableMigrations}} -

{{.locale.Tr "repo.new_repo_helper" ((printf "%s%s" AppSubUrl "/repo/migrate")|Escape) | Safe}}

+

{{.locale.Tr "repo.new_repo_helper" ((print AppSubUrl "/repo/migrate")|Escape) | Safe}}

{{end}} diff --git a/templates/repo/graph/commits.tmpl b/templates/repo/graph/commits.tmpl index 58ede56579d3a..b8817f5c88dd5 100644 --- a/templates/repo/graph/commits.tmpl +++ b/templates/repo/graph/commits.tmpl @@ -8,17 +8,17 @@ {{$class := "ui sha label"}} {{if $commit.Commit.Signature}} - {{$class = (printf "%s%s" $class " isSigned")}} + {{$class = (print $class " isSigned")}} {{if $commit.Verification.Verified}} {{if eq $commit.Verification.TrustStatus "trusted"}} - {{$class = (printf "%s%s" $class " isVerified")}} + {{$class = (print $class " isVerified")}} {{else if eq $commit.Verification.TrustStatus "untrusted"}} - {{$class = (printf "%s%s" $class " isVerifiedUntrusted")}} + {{$class = (print $class " isVerifiedUntrusted")}} {{else}} - {{$class = (printf "%s%s" $class " isVerifiedUnmatched")}} + {{$class = (print $class " isVerifiedUnmatched")}} {{end}} {{else if $commit.Verification.Warning}} - {{$class = (printf "%s%s" $class " isWarning")}} + {{$class = (print $class " isWarning")}} {{end}} {{end}}
diff --git a/templates/repo/home.tmpl b/templates/repo/home.tmpl index 11dc47f555990..616cb7a938024 100644 --- a/templates/repo/home.tmpl +++ b/templates/repo/home.tmpl @@ -70,7 +70,7 @@ {{if ne .Repository.ID .BaseRepo.ID}} {{$cmpBranch = printf "%s/%s:" (.Repository.OwnerName|PathEscape) (.Repository.Name|PathEscape)}} {{end}} - {{$cmpBranch = printf "%s%s" $cmpBranch (.BranchName|PathEscapeSegments)}} + {{$cmpBranch = print $cmpBranch (.BranchName|PathEscapeSegments)}} {{$compareLink := printf "%s/compare/%s...%s" .BaseRepo.Link (.BaseRepo.DefaultBranch|PathEscapeSegments) $cmpBranch}} From efecbbaca15e5b28cd6d6356f99612d062678b8a Mon Sep 17 00:00:00 2001 From: JakobDev Date: Sat, 16 Sep 2023 11:13:26 +0200 Subject: [PATCH 12/23] Fix NPE when editing OAuth2 applications (#27078) Fixes #27072 It looks like there are some cases where `ContextUser` is not set here --------- Co-authored-by: techknowlogick --- routers/web/user/setting/oauth2_common.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/routers/web/user/setting/oauth2_common.go b/routers/web/user/setting/oauth2_common.go index 5786118f50d97..5ac03e4a7467b 100644 --- a/routers/web/user/setting/oauth2_common.go +++ b/routers/web/user/setting/oauth2_common.go @@ -27,9 +27,8 @@ func (oa *OAuth2CommonHandlers) renderEditPage(ctx *context.Context) { app := ctx.Data["App"].(*auth.OAuth2Application) ctx.Data["FormActionPath"] = fmt.Sprintf("%s/%d", oa.BasePathEditPrefix, app.ID) - if ctx.ContextUser.IsOrganization() { - err := shared_user.LoadHeaderCount(ctx) - if err != nil { + if ctx.ContextUser != nil && ctx.ContextUser.IsOrganization() { + if err := shared_user.LoadHeaderCount(ctx); err != nil { ctx.ServerError("LoadHeaderCount", err) return } @@ -68,6 +67,7 @@ func (oa *OAuth2CommonHandlers) AddApp(ctx *context.Context) { ctx.ServerError("GenerateClientSecret", err) return } + oa.renderEditPage(ctx) } From 7046065c0ed321af156e84d2a10a25c8df047ddd Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Sat, 16 Sep 2023 07:36:35 -0400 Subject: [PATCH 13/23] Drop Node.js 16 and update js dependencies (#27094) - Drop Node.js 16 since it reached EOL - Upgrade js dependencies - Two packages have major version bump - `updates`: require node 18 - `eslint-plugin-array-func`: require `eslint` 8.40.0, which is satisfied - Run `make svg` for `@primer/octicons` update --- package-lock.json | 342 +++++++++++------- package.json | 24 +- .../img/svg/octicon-feed-issue-closed.svg | 2 +- .../img/svg/octicon-feed-issue-draft.svg | 2 +- .../img/svg/octicon-feed-issue-open.svg | 2 +- .../img/svg/octicon-feed-issue-reopen.svg | 1 + public/assets/img/svg/octicon-feed-plus.svg | 2 +- public/assets/img/svg/octicon-feed-public.svg | 2 +- .../svg/octicon-feed-pull-request-closed.svg | 2 +- .../svg/octicon-feed-pull-request-draft.svg | 2 +- .../svg/octicon-feed-pull-request-open.svg | 2 +- 11 files changed, 231 insertions(+), 152 deletions(-) create mode 100644 public/assets/img/svg/octicon-feed-issue-reopen.svg diff --git a/package-lock.json b/package-lock.json index db0480a5e8d89..34478cb00fd94 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,11 +14,11 @@ "@github/relative-time-element": "4.3.0", "@github/text-expander-element": "2.5.0", "@mcaptcha/vanilla-glue": "0.1.0-alpha-3", - "@primer/octicons": "19.6.0", + "@primer/octicons": "19.7.0", "@webcomponents/custom-elements": "1.6.0", "add-asset-webpack-plugin": "2.0.1", "ansi_up": "6.0.2", - "asciinema-player": "3.5.0", + "asciinema-player": "3.6.1", "clippie": "4.0.6", "css-loader": "6.8.1", "dropzone": "6.0.0-beta.2", @@ -33,12 +33,12 @@ "mermaid": "10.4.0", "mini-css-extract-plugin": "2.7.6", "minimatch": "9.0.3", - "monaco-editor": "0.41.0", + "monaco-editor": "0.43.0", "monaco-editor-webpack-plugin": "7.1.0", "pdfobject": "2.2.12", "pretty-ms": "8.0.0", "sortablejs": "1.15.0", - "swagger-ui-dist": "5.4.2", + "swagger-ui-dist": "5.7.1", "throttle-debounce": "5.0.0", "tinycolor2": "1.6.0", "tippy.js": "6.3.7", @@ -55,11 +55,11 @@ }, "devDependencies": { "@eslint-community/eslint-plugin-eslint-comments": "4.1.0", - "@playwright/test": "1.37.1", - "@stoplight/spectral-cli": "6.10.1", + "@playwright/test": "1.38.0", + "@stoplight/spectral-cli": "6.11.0", "@vitejs/plugin-vue": "4.3.4", - "eslint": "8.48.0", - "eslint-plugin-array-func": "3.1.8", + "eslint": "8.49.0", + "eslint-plugin-array-func": "4.0.0", "eslint-plugin-custom-elements": "0.0.8", "eslint-plugin-import": "2.28.1", "eslint-plugin-jquery": "1.5.1", @@ -72,19 +72,19 @@ "eslint-plugin-vue-scoped-css": "2.5.0", "eslint-plugin-wc": "1.5.0", "jsdom": "22.1.0", - "markdownlint-cli": "0.35.0", + "markdownlint-cli": "0.36.0", "postcss-html": "1.5.0", "stylelint": "15.10.3", "stylelint-declaration-block-no-ignored-properties": "2.7.0", "stylelint-declaration-strict-value": "1.9.2", "stylelint-stylistic": "0.4.3", "svgo": "3.0.2", - "updates": "14.4.0", + "updates": "15.0.0", "vite-string-plugin": "1.1.2", - "vitest": "0.34.3" + "vitest": "0.34.4" }, "engines": { - "node": ">= 16.0.0" + "node": ">= 18.0.0" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -991,9 +991,9 @@ } }, "node_modules/@eslint/js": { - "version": "8.48.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.48.0.tgz", - "integrity": "sha512-ZSjtmelB7IJfWD2Fvb7+Z+ChTIKWq6kjda95fLcQKNS5aheVHn4IkfgRQE3sIIzTcSLwLcLZUD9UBt+V7+h+Pw==", + "version": "8.49.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.49.0.tgz", + "integrity": "sha512-1S8uAY/MTJqVx0SC4epBq+N2yhuwtNwLbJYNZyhL2pO1ZVKn5HFXav5T41Ryzy9K9V7ZId2JB2oy/W4aCd9/2w==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -1023,9 +1023,9 @@ } }, "node_modules/@humanwhocodes/config-array": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.10.tgz", - "integrity": "sha512-KVVjQmNUepDVGXNuoRRdmmEjruj0KfiGSbS8LVc12LMsWDQzRXJ0qdhN8L8uUigKpfEHRhlaQFY0ib1tnUbNeQ==", + "version": "0.11.11", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.11.tgz", + "integrity": "sha512-N2brEuAadi0CcdeMXUkhbZB84eskAc8MEX1By6qEchoVywSgXPIjou4rYsl0V3Hj0ZnuGycGCjdNgockbzeWNA==", "dev": true, "dependencies": { "@humanwhocodes/object-schema": "^1.2.1", @@ -1324,22 +1324,18 @@ } }, "node_modules/@playwright/test": { - "version": "1.37.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.37.1.tgz", - "integrity": "sha512-bq9zTli3vWJo8S3LwB91U0qDNQDpEXnw7knhxLM0nwDvexQAwx9tO8iKDZSqqneVq+URd/WIoz+BALMqUTgdSg==", + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.38.0.tgz", + "integrity": "sha512-xis/RXXsLxwThKnlIXouxmIvvT3zvQj1JE39GsNieMUrMpb3/GySHDh2j8itCG22qKVD4MYLBp7xB73cUW/UUw==", "dev": true, "dependencies": { - "@types/node": "*", - "playwright-core": "1.37.1" + "playwright": "1.38.0" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=16" - }, - "optionalDependencies": { - "fsevents": "2.3.2" } }, "node_modules/@popperjs/core": { @@ -1352,9 +1348,9 @@ } }, "node_modules/@primer/octicons": { - "version": "19.6.0", - "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-19.6.0.tgz", - "integrity": "sha512-/10tz0hyJijS9hCLKw5Wb3LfRmVSQjtiUDPfvf582bhe+/xZDybgf3VLJncD5SZaetC4zNhz31VwV8nnG2PdSQ==", + "version": "19.7.0", + "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-19.7.0.tgz", + "integrity": "sha512-24lel5MYOTXXdm2VPKAT2JIAJU7rnirVfa/1HGBjTvLdUpk789Lz/QA4o7klYhVdjIJW0rw5nOmU+bWSmfuNwg==", "dependencies": { "object-assign": "^4.1.1" } @@ -1501,15 +1497,15 @@ } }, "node_modules/@stoplight/spectral-cli": { - "version": "6.10.1", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-cli/-/spectral-cli-6.10.1.tgz", - "integrity": "sha512-yjal3WE42buthVnqfwppw2YmjeXZJ8rmMaHjpx9/94xbbfS79RsReExH9sj1QZam6A9XPGWtjLdWSrklqydpYg==", + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-cli/-/spectral-cli-6.11.0.tgz", + "integrity": "sha512-IURDN47BPIf3q4ZyUPujGpBzuHWFE5yT34w9rTJ1GKA4SgdscEdQO9KoTjOPT4G4cvDlEV3bNxwQ3uRm7+wRlA==", "dev": true, "dependencies": { "@stoplight/json": "~3.21.0", "@stoplight/path": "1.3.2", "@stoplight/spectral-core": "^1.18.3", - "@stoplight/spectral-formatters": "^1.2.0", + "@stoplight/spectral-formatters": "^1.3.0", "@stoplight/spectral-parsers": "^1.0.3", "@stoplight/spectral-ref-resolver": "^1.0.4", "@stoplight/spectral-ruleset-bundler": "^1.5.2", @@ -1644,9 +1640,9 @@ } }, "node_modules/@stoplight/spectral-formatters": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-formatters/-/spectral-formatters-1.2.0.tgz", - "integrity": "sha512-1IrQksU1fpuvK7oT8t0jk419vkvzHbwqKYtnyoF9yZa+MV1AcSsieD5I6wBFL0WlgFr6iCg23s1V99VXlrFelw==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-formatters/-/spectral-formatters-1.3.0.tgz", + "integrity": "sha512-ryuMwlzbPUuyn7ybSEbFYsljYmvTaTyD51wyCQs4ROzgfm3Yo5QDD0IsiJUzUpKK/Ml61ZX8ebgiPiRFEJtBpg==", "dev": true, "dependencies": { "@stoplight/path": "^1.3.2", @@ -1656,6 +1652,7 @@ "chalk": "4.1.2", "cliui": "7.0.4", "lodash": "^4.17.21", + "node-sarif-builder": "^2.0.3", "strip-ansi": "6.0", "text-table": "^0.2.0", "tslib": "^2.5.0" @@ -2009,6 +2006,12 @@ "integrity": "sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==", "dev": true }, + "node_modules/@types/sarif": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@types/sarif/-/sarif-2.1.4.tgz", + "integrity": "sha512-4xKHMdg3foh3Va1fxTzY1qt8QVqmaJpGWsVvtjQrJBn+/bkig2pWFKJ4FPI2yLI4PAj0SUKiPO4Vd7ggYIMZjQ==", + "dev": true + }, "node_modules/@types/tern": { "version": "0.23.4", "resolved": "https://registry.npmjs.org/@types/tern/-/tern-0.23.4.tgz", @@ -2042,13 +2045,13 @@ } }, "node_modules/@vitest/expect": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-0.34.3.tgz", - "integrity": "sha512-F8MTXZUYRBVsYL1uoIft1HHWhwDbSzwAU9Zgh8S6WFC3YgVb4AnFV2GXO3P5Em8FjEYaZtTnQYoNwwBrlOMXgg==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-0.34.4.tgz", + "integrity": "sha512-XlMKX8HyYUqB8dsY8Xxrc64J2Qs9pKMt2Z8vFTL4mBWXJsg4yoALHzJfDWi8h5nkO4Zua4zjqtapQ/IluVkSnA==", "dev": true, "dependencies": { - "@vitest/spy": "0.34.3", - "@vitest/utils": "0.34.3", + "@vitest/spy": "0.34.4", + "@vitest/utils": "0.34.4", "chai": "^4.3.7" }, "funding": { @@ -2056,12 +2059,12 @@ } }, "node_modules/@vitest/runner": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-0.34.3.tgz", - "integrity": "sha512-lYNq7N3vR57VMKMPLVvmJoiN4bqwzZ1euTW+XXYH5kzr3W/+xQG3b41xJn9ChJ3AhYOSoweu974S1V3qDcFESA==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-0.34.4.tgz", + "integrity": "sha512-hwwdB1StERqUls8oV8YcpmTIpVeJMe4WgYuDongVzixl5hlYLT2G8afhcdADeDeqCaAmZcSgLTLtqkjPQF7x+w==", "dev": true, "dependencies": { - "@vitest/utils": "0.34.3", + "@vitest/utils": "0.34.4", "p-limit": "^4.0.0", "pathe": "^1.1.1" }, @@ -2097,9 +2100,9 @@ } }, "node_modules/@vitest/snapshot": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-0.34.3.tgz", - "integrity": "sha512-QyPaE15DQwbnIBp/yNJ8lbvXTZxS00kRly0kfFgAD5EYmCbYcA+1EEyRalc93M0gosL/xHeg3lKAClIXYpmUiQ==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-0.34.4.tgz", + "integrity": "sha512-GCsh4coc3YUSL/o+BPUo7lHQbzpdttTxL6f4q0jRx2qVGoYz/cyTRDJHbnwks6TILi6560bVWoBpYC10PuTLHw==", "dev": true, "dependencies": { "magic-string": "^0.30.1", @@ -2123,9 +2126,9 @@ } }, "node_modules/@vitest/spy": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-0.34.3.tgz", - "integrity": "sha512-N1V0RFQ6AI7CPgzBq9kzjRdPIgThC340DGjdKdPSE8r86aUSmeliTUgkTqLSgtEwWWsGfBQ+UetZWhK0BgJmkQ==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-0.34.4.tgz", + "integrity": "sha512-PNU+fd7DUPgA3Ya924b1qKuQkonAW6hL7YUjkON3wmBwSTIlhOSpy04SJ0NrRsEbrXgMMj6Morh04BMf8k+w0g==", "dev": true, "dependencies": { "tinyspy": "^2.1.1" @@ -2135,9 +2138,9 @@ } }, "node_modules/@vitest/utils": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-0.34.3.tgz", - "integrity": "sha512-kiSnzLG6m/tiT0XEl4U2H8JDBjFtwVlaE8I3QfGiMFR0QvnRDfYfdP3YvTBWM/6iJDAyaPY6yVQiCTUc7ZzTHA==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-0.34.4.tgz", + "integrity": "sha512-yR2+5CHhp/K4ySY0Qtd+CAL9f5Yh1aXrKfAT42bq6CtlGPh92jIDDDSg7ydlRow1CP+dys4TrOrbELOyNInHSg==", "dev": true, "dependencies": { "diff-sequences": "^29.4.3", @@ -2783,9 +2786,9 @@ } }, "node_modules/asciinema-player": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/asciinema-player/-/asciinema-player-3.5.0.tgz", - "integrity": "sha512-o4B2AscBuCZo4+JB9TBGrfZ7GQL99wsbm08WwmuNJTPd1lyLQJq8wgacnBsdvb2sC0K875ScYr8T5XmfeH/6dg==", + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/asciinema-player/-/asciinema-player-3.6.1.tgz", + "integrity": "sha512-FfTABH/N6pjG74A6cCfsrirTSM4UAOLMzcFXb0zS34T5czvg3CyUy2TAqa3WEs5owUFHcuN1Y2y8o0n2yjeMvQ==", "dependencies": { "@babel/runtime": "^7.21.0", "solid-js": "^1.3.0" @@ -4643,16 +4646,16 @@ } }, "node_modules/eslint": { - "version": "8.48.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.48.0.tgz", - "integrity": "sha512-sb6DLeIuRXxeM1YljSe1KEx9/YYeZFQWcV8Rq9HfigmdDEugjLEVEa1ozDjL6YDjBpQHPJxJzze+alxi4T3OLg==", + "version": "8.49.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.49.0.tgz", + "integrity": "sha512-jw03ENfm6VJI0jA9U+8H5zfl5b+FvuU3YYvZRdZHOlU2ggJkxrlkJH4HcDrZpj6YwD8kuYqvQM8LyesoazrSOQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.2", - "@eslint/js": "8.48.0", - "@humanwhocodes/config-array": "^0.11.10", + "@eslint/js": "8.49.0", + "@humanwhocodes/config-array": "^0.11.11", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", "ajv": "^6.12.4", @@ -4743,15 +4746,15 @@ } }, "node_modules/eslint-plugin-array-func": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/eslint-plugin-array-func/-/eslint-plugin-array-func-3.1.8.tgz", - "integrity": "sha512-BjnbJvw+knaHgVddIL3q5xYcoqAZoK8wOdT7QF+mkvSAjXdZCdhL0z71Y7oRtgXA8BpN9QLJ2uHgD3I6ymlbOw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-array-func/-/eslint-plugin-array-func-4.0.0.tgz", + "integrity": "sha512-p3NY2idNIvgmQLF2/62ZskYt8gOuUgQ51smRc3Lh7FtSozpNc2sg+lniz9VaCagLZHEZTl8qGJKqE7xy8O/D/g==", "dev": true, "engines": { - "node": ">= 6.8.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "peerDependencies": { - "eslint": ">=3.0.0" + "eslint": ">=8.40.0" } }, "node_modules/eslint-plugin-custom-elements": { @@ -5357,6 +5360,29 @@ "node": ">= 6" } }, + "node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/fs-extra/node_modules/universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -6020,12 +6046,12 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/ini": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ini/-/ini-3.0.1.tgz", - "integrity": "sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", + "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", "dev": true, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, "node_modules/internal-slot": { @@ -6416,9 +6442,9 @@ } }, "node_modules/jackspeak": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-2.3.0.tgz", - "integrity": "sha512-uKmsITSsF4rUWQHzqaRUuyAir3fZfW3f202Ee34lz/gZCi970CPZwyQXLGNgWJvvZbvFyzeyGq0+4fcG/mBKZg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-2.3.3.tgz", + "integrity": "sha512-R2bUw+kVZFS/h1AZqBKrSgDmdmjApzgY0AlCPumopFiAlbUxE2gf+SCuBzQ0cP5hHmUmFYF5yw55T97Th5Kstg==", "dev": true, "dependencies": { "@isaacs/cliui": "^8.0.2" @@ -6605,6 +6631,27 @@ "integrity": "sha512-o6/yDBYccGvTz1+QFevz6l6OBZ2+fMVu2JZ9CIhzsYRX4mjaK5IyX9eldUdCmga16zlgQxyrj5pt9kzuj2C02w==", "dev": true }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonfile/node_modules/universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/jsonpath-plus": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/jsonpath-plus/-/jsonpath-plus-7.1.0.tgz", @@ -7141,33 +7188,33 @@ } }, "node_modules/markdownlint": { - "version": "0.29.0", - "resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.29.0.tgz", - "integrity": "sha512-ASAzqpODstu/Qsk0xW5BPgWnK/qjpBQ4e7IpsSvvFXcfYIjanLTdwFRJK1SIEEh0fGSMKXcJf/qhaZYHyME0wA==", + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.30.0.tgz", + "integrity": "sha512-nInuFvI/rEzanAOArW5490Ez4EYpB5ODqVM0mcDYCPx9DKJWCQqCgejjiCvbSeE7sjbDscVtZmwr665qpF5xGA==", "dev": true, "dependencies": { "markdown-it": "13.0.1", - "markdownlint-micromark": "0.1.5" + "markdownlint-micromark": "0.1.7" }, "engines": { "node": ">=16" } }, "node_modules/markdownlint-cli": { - "version": "0.35.0", - "resolved": "https://registry.npmjs.org/markdownlint-cli/-/markdownlint-cli-0.35.0.tgz", - "integrity": "sha512-lVIIIV1MrUtjoocgDqXLxUCxlRbn7Ve8rsWppfwciUNwLlNS28AhNiyQ3PU7jjj4Qvj+rWTTvwkqg7AcdG988g==", + "version": "0.36.0", + "resolved": "https://registry.npmjs.org/markdownlint-cli/-/markdownlint-cli-0.36.0.tgz", + "integrity": "sha512-h4WdqOam3+QOVOcJSOQuG8KvvN8dlS0OiJhbPwYWBk7VMZR40UtSSMIOpSP5B4EHPHg3W3ILSQUvqg1HNpTCxA==", "dev": true, "dependencies": { "commander": "~11.0.0", "get-stdin": "~9.0.0", - "glob": "~10.2.7", + "glob": "~10.3.4", "ignore": "~5.2.4", "js-yaml": "^4.1.0", "jsonc-parser": "~3.2.0", - "markdownlint": "~0.29.0", - "minimatch": "~9.0.1", - "run-con": "~1.2.11" + "markdownlint": "~0.30.0", + "minimatch": "~9.0.3", + "run-con": "~1.3.2" }, "bin": { "markdownlint": "markdownlint.js" @@ -7186,16 +7233,16 @@ } }, "node_modules/markdownlint-cli/node_modules/glob": { - "version": "10.2.7", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.2.7.tgz", - "integrity": "sha512-jTKehsravOJo8IJxUGfZILnkvVJM/MOfHRs8QcXolVef2zNI9Tqyy5+SeuOAZd3upViEZQLyFpQhYiHLrMUNmA==", + "version": "10.3.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.4.tgz", + "integrity": "sha512-6LFElP3A+i/Q8XQKEvZjkEWEOTgAIALR9AO2rwT8bgPhDd1anmqDJDZ6lLddI4ehxxxR1S5RIqKe1uapMQfYaQ==", "dev": true, "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^2.0.3", "minimatch": "^9.0.1", - "minipass": "^5.0.0 || ^6.0.2", - "path-scurry": "^1.7.0" + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", + "path-scurry": "^1.10.1" }, "bin": { "glob": "dist/cjs/src/bin.js" @@ -7214,9 +7261,9 @@ "dev": true }, "node_modules/markdownlint-micromark": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/markdownlint-micromark/-/markdownlint-micromark-0.1.5.tgz", - "integrity": "sha512-HvofNU4QCvfUCWnocQP1IAWaqop5wpWrB0mKB6SSh0fcpV0PdmQNS6tdUuFew1utpYlUvYYzz84oDkrD76GB9A==", + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/markdownlint-micromark/-/markdownlint-micromark-0.1.7.tgz", + "integrity": "sha512-BbRPTC72fl5vlSKv37v/xIENSRDYL/7X/XoFzZ740FGEbs9vZerLrIkFRY0rv7slQKxDczToYuMmqQFN61fi4Q==", "dev": true, "engines": { "node": ">=16" @@ -7947,18 +7994,18 @@ } }, "node_modules/minipass": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-6.0.2.tgz", - "integrity": "sha512-MzWSV5nYVT7mVyWCwn2o7JH13w2TBRmmSqSRCKzTw+lmft9X4z+3wjvs06Tzijo5z4W/kahUCDpRXTF+ZrmF/w==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.0.3.tgz", + "integrity": "sha512-LhbbwCfz3vsb12j/WkWQPZfKTsgqIe1Nf/ti1pKjYESGLHIVjWU96G9/ljLH4F9mWNVhlQOm0VySdAWzf05dpg==", "dev": true, "engines": { "node": ">=16 || 14 >=14.17" } }, "node_modules/mlly": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.4.1.tgz", - "integrity": "sha512-SCDs78Q2o09jiZiE2WziwVBEqXQ02XkGdUy45cbJf+BpYRIjArXRJ1Wbowxkb+NaM9DWvS3UC9GiO/6eqvQ/pg==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.4.2.tgz", + "integrity": "sha512-i/Ykufi2t1EZ6NaPLdfnZk2AX8cs0d+mTzVKuPfqPKPatxLApaBoxJQ9x1/uckXtrS/U5oisPMDkNs0yQTaBRg==", "dev": true, "dependencies": { "acorn": "^8.10.0", @@ -7968,9 +8015,9 @@ } }, "node_modules/monaco-editor": { - "version": "0.41.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.41.0.tgz", - "integrity": "sha512-1o4olnZJsiLmv5pwLEAmzHTE/5geLKQ07BrGxlF4Ri/AXAc2yyDGZwHjiTqD8D/ROKUZmwMA28A+yEowLNOEcA==" + "version": "0.43.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.43.0.tgz", + "integrity": "sha512-cnoqwQi/9fml2Szamv1XbSJieGJ1Dc8tENVMD26Kcfl7xGQWp7OBKMjlwKVGYFJ3/AXJjSOGvcqK7Ry/j9BM1Q==" }, "node_modules/monaco-editor-webpack-plugin": { "version": "7.1.0", @@ -8102,6 +8149,19 @@ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==" }, + "node_modules/node-sarif-builder": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/node-sarif-builder/-/node-sarif-builder-2.0.3.tgz", + "integrity": "sha512-Pzr3rol8fvhG/oJjIq2NTVB0vmdNNlz22FENhhPojYRZ4/ee08CfK4YuKmuL54V9MLhI1kpzxfOJ/63LzmZzDg==", + "dev": true, + "dependencies": { + "@types/sarif": "^2.1.4", + "fs-extra": "^10.0.0" + }, + "engines": { + "node": ">=14" + } + }, "node_modules/non-layered-tidy-tree-layout": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/non-layered-tidy-tree-layout/-/non-layered-tidy-tree-layout-2.0.2.tgz", @@ -8557,10 +8617,28 @@ "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", "dev": true }, + "node_modules/playwright": { + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.38.0.tgz", + "integrity": "sha512-fJGw+HO0YY+fU/F1N57DMO+TmXHTrmr905J05zwAQE9xkuwP/QLDk63rVhmyxh03dYnEhnRbsdbH9B0UVVRB3A==", + "dev": true, + "dependencies": { + "playwright-core": "1.38.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, "node_modules/playwright-core": { - "version": "1.37.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.37.1.tgz", - "integrity": "sha512-17EuQxlSIYCmEMwzMqusJ2ztDgJePjrbttaefgdsiqeLWidjYz9BxXaTaZWxH1J95SHGk6tjE+dwgWILJoUZfA==", + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.38.0.tgz", + "integrity": "sha512-f8z1y8J9zvmHoEhKgspmCvOExF2XdcxMW8jNRuX4vkQFrzV4MlZ55iwb5QeyiFQgOFCUolXiRHgpjSEnqvO48g==", "dev": true, "bin": { "playwright-core": "cli.js" @@ -8784,9 +8862,9 @@ } }, "node_modules/pretty-format": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.6.3.tgz", - "integrity": "sha512-ZsBgjVhFAj5KeK+nHfF1305/By3lechHQSMWCTl8iHSbfOm2TN5nHEtFc/+W7fAyUeCs2n5iow72gld4gW0xDw==", + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", "dev": true, "dependencies": { "@jest/schemas": "^29.6.3", @@ -9271,13 +9349,13 @@ "dev": true }, "node_modules/run-con": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/run-con/-/run-con-1.2.12.tgz", - "integrity": "sha512-5257ILMYIF4RztL9uoZ7V9Q97zHtNHn5bN3NobeAnzB1P3ASLgg8qocM2u+R18ttp+VEM78N2LK8XcNVtnSRrg==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/run-con/-/run-con-1.3.2.tgz", + "integrity": "sha512-CcfE+mYiTcKEzg0IqS08+efdnH0oJ3zV0wSUFBNrMHMuxCtXvBCLzCJHatwuXDcu/RlhjTziTo/a1ruQik6/Yg==", "dev": true, "dependencies": { "deep-extend": "^0.6.0", - "ini": "~3.0.0", + "ini": "~4.1.0", "minimist": "^1.2.8", "strip-json-comments": "~3.1.1" }, @@ -10093,9 +10171,9 @@ } }, "node_modules/swagger-ui-dist": { - "version": "5.4.2", - "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.4.2.tgz", - "integrity": "sha512-vT5QxP/NOr9m4gLZl+SpavWI3M9Fdh30+Sdw9rEtZbkqNmNNEPhjXas2xTD9rsJYYdLzAiMfwXvtooWH3xbLJA==" + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.7.1.tgz", + "integrity": "sha512-mY+htL+asLQTrwbCOcbzOtgch2TA5A4IqMleEtVleegFAIgzd2w0jyY2IvA8upDOR/AmftudyiI1/h+VBPIc7A==" }, "node_modules/symbol-tree": { "version": "3.2.4", @@ -10574,15 +10652,15 @@ } }, "node_modules/updates": { - "version": "14.4.0", - "resolved": "https://registry.npmjs.org/updates/-/updates-14.4.0.tgz", - "integrity": "sha512-fAB49LEq46XlJfQmLDWHt3Yt7XpSAxj1GwO6MxgEMHlGbhyGLSNu2hPYuSzipNRhO7phJNp8UDi0kikn/RAwwQ==", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/updates/-/updates-15.0.0.tgz", + "integrity": "sha512-+26xgn2p7kMGffHf+/xRVJn37c+ZLVdWTsleQ7hzYejEIkbrKZ0qP2QO/QSSurBHwO4fXs4RGtRWaM2U5XEHmg==", "dev": true, "bin": { "updates": "bin/updates.js" }, "engines": { - "node": ">=16" + "node": ">=18" } }, "node_modules/uri-js": { @@ -10723,9 +10801,9 @@ } }, "node_modules/vite-node": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-0.34.3.tgz", - "integrity": "sha512-+0TzJf1g0tYXj6tR2vEyiA42OPq68QkRZCu/ERSo2PtsDJfBpDyEfuKbRvLmZqi/CgC7SCBtyC+WjTGNMRIaig==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-0.34.4.tgz", + "integrity": "sha512-ho8HtiLc+nsmbwZMw8SlghESEE3KxJNp04F/jPUCLVvaURwt0d+r9LxEqCX5hvrrOQ0GSyxbYr5ZfRYhQ0yVKQ==", "dev": true, "dependencies": { "cac": "^6.7.14", @@ -11160,19 +11238,19 @@ } }, "node_modules/vitest": { - "version": "0.34.3", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.34.3.tgz", - "integrity": "sha512-7+VA5Iw4S3USYk+qwPxHl8plCMhA5rtfwMjgoQXMT7rO5ldWcdsdo3U1QD289JgglGK4WeOzgoLTsGFu6VISyQ==", + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.34.4.tgz", + "integrity": "sha512-SE/laOsB6995QlbSE6BtkpXDeVNLJc1u2LHRG/OpnN4RsRzM3GQm4nm3PQCK5OBtrsUqnhzLdnT7se3aeNGdlw==", "dev": true, "dependencies": { "@types/chai": "^4.3.5", "@types/chai-subset": "^1.3.3", "@types/node": "*", - "@vitest/expect": "0.34.3", - "@vitest/runner": "0.34.3", - "@vitest/snapshot": "0.34.3", - "@vitest/spy": "0.34.3", - "@vitest/utils": "0.34.3", + "@vitest/expect": "0.34.4", + "@vitest/runner": "0.34.4", + "@vitest/snapshot": "0.34.4", + "@vitest/spy": "0.34.4", + "@vitest/utils": "0.34.4", "acorn": "^8.9.0", "acorn-walk": "^8.2.0", "cac": "^6.7.14", @@ -11186,8 +11264,8 @@ "strip-literal": "^1.0.1", "tinybench": "^2.5.0", "tinypool": "^0.7.0", - "vite": "^3.0.0 || ^4.0.0", - "vite-node": "0.34.3", + "vite": "^3.1.0 || ^4.0.0 || ^5.0.0-0", + "vite-node": "0.34.4", "why-is-node-running": "^2.2.2" }, "bin": { diff --git a/package.json b/package.json index 224a1422ec807..cbecc287e495a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "type": "module", "engines": { - "node": ">= 16.0.0" + "node": ">= 18.0.0" }, "dependencies": { "@citation-js/core": "0.6.8", @@ -13,11 +13,11 @@ "@github/relative-time-element": "4.3.0", "@github/text-expander-element": "2.5.0", "@mcaptcha/vanilla-glue": "0.1.0-alpha-3", - "@primer/octicons": "19.6.0", + "@primer/octicons": "19.7.0", "@webcomponents/custom-elements": "1.6.0", "add-asset-webpack-plugin": "2.0.1", "ansi_up": "6.0.2", - "asciinema-player": "3.5.0", + "asciinema-player": "3.6.1", "clippie": "4.0.6", "css-loader": "6.8.1", "dropzone": "6.0.0-beta.2", @@ -32,12 +32,12 @@ "mermaid": "10.4.0", "mini-css-extract-plugin": "2.7.6", "minimatch": "9.0.3", - "monaco-editor": "0.41.0", + "monaco-editor": "0.43.0", "monaco-editor-webpack-plugin": "7.1.0", "pdfobject": "2.2.12", "pretty-ms": "8.0.0", "sortablejs": "1.15.0", - "swagger-ui-dist": "5.4.2", + "swagger-ui-dist": "5.7.1", "throttle-debounce": "5.0.0", "tinycolor2": "1.6.0", "tippy.js": "6.3.7", @@ -54,11 +54,11 @@ }, "devDependencies": { "@eslint-community/eslint-plugin-eslint-comments": "4.1.0", - "@playwright/test": "1.37.1", - "@stoplight/spectral-cli": "6.10.1", + "@playwright/test": "1.38.0", + "@stoplight/spectral-cli": "6.11.0", "@vitejs/plugin-vue": "4.3.4", - "eslint": "8.48.0", - "eslint-plugin-array-func": "3.1.8", + "eslint": "8.49.0", + "eslint-plugin-array-func": "4.0.0", "eslint-plugin-custom-elements": "0.0.8", "eslint-plugin-import": "2.28.1", "eslint-plugin-jquery": "1.5.1", @@ -71,16 +71,16 @@ "eslint-plugin-vue-scoped-css": "2.5.0", "eslint-plugin-wc": "1.5.0", "jsdom": "22.1.0", - "markdownlint-cli": "0.35.0", + "markdownlint-cli": "0.36.0", "postcss-html": "1.5.0", "stylelint": "15.10.3", "stylelint-declaration-block-no-ignored-properties": "2.7.0", "stylelint-declaration-strict-value": "1.9.2", "stylelint-stylistic": "0.4.3", "svgo": "3.0.2", - "updates": "14.4.0", + "updates": "15.0.0", "vite-string-plugin": "1.1.2", - "vitest": "0.34.3" + "vitest": "0.34.4" }, "browserslist": [ "defaults", diff --git a/public/assets/img/svg/octicon-feed-issue-closed.svg b/public/assets/img/svg/octicon-feed-issue-closed.svg index 4fea50bac65ed..f31776e661ff2 100644 --- a/public/assets/img/svg/octicon-feed-issue-closed.svg +++ b/public/assets/img/svg/octicon-feed-issue-closed.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-issue-draft.svg b/public/assets/img/svg/octicon-feed-issue-draft.svg index 3720b5d9b3af3..b50504935eb33 100644 --- a/public/assets/img/svg/octicon-feed-issue-draft.svg +++ b/public/assets/img/svg/octicon-feed-issue-draft.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-issue-open.svg b/public/assets/img/svg/octicon-feed-issue-open.svg index 4e497682e5680..6a6697a31ab81 100644 --- a/public/assets/img/svg/octicon-feed-issue-open.svg +++ b/public/assets/img/svg/octicon-feed-issue-open.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-issue-reopen.svg b/public/assets/img/svg/octicon-feed-issue-reopen.svg new file mode 100644 index 0000000000000..6cac76da58120 --- /dev/null +++ b/public/assets/img/svg/octicon-feed-issue-reopen.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-plus.svg b/public/assets/img/svg/octicon-feed-plus.svg index a453bf11e998b..8606bdef20334 100644 --- a/public/assets/img/svg/octicon-feed-plus.svg +++ b/public/assets/img/svg/octicon-feed-plus.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-public.svg b/public/assets/img/svg/octicon-feed-public.svg index 4decd913004dd..7c6c5b2529a9e 100644 --- a/public/assets/img/svg/octicon-feed-public.svg +++ b/public/assets/img/svg/octicon-feed-public.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-pull-request-closed.svg b/public/assets/img/svg/octicon-feed-pull-request-closed.svg index 824a4e06ab3bc..10f89d48552f8 100644 --- a/public/assets/img/svg/octicon-feed-pull-request-closed.svg +++ b/public/assets/img/svg/octicon-feed-pull-request-closed.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-pull-request-draft.svg b/public/assets/img/svg/octicon-feed-pull-request-draft.svg index 5091a4a0a9fb3..78596ff78889b 100644 --- a/public/assets/img/svg/octicon-feed-pull-request-draft.svg +++ b/public/assets/img/svg/octicon-feed-pull-request-draft.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/public/assets/img/svg/octicon-feed-pull-request-open.svg b/public/assets/img/svg/octicon-feed-pull-request-open.svg index 276e02f925c7f..82dd8e0aea5fd 100644 --- a/public/assets/img/svg/octicon-feed-pull-request-open.svg +++ b/public/assets/img/svg/octicon-feed-pull-request-open.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file From 4ffc30cb842d6631fad1e6b45c77ac1101b405a3 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Sat, 16 Sep 2023 20:54:23 +0800 Subject: [PATCH 14/23] Use db.WithTx for AddTeamMember to avoid ctx abuse (#27095) Compare with ignoring spaces: https://github.com/go-gitea/gitea/pull/27095/files?diff=split&w=1 --- models/org_team.go | 96 +++++++++++++++++++++++----------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/models/org_team.go b/models/org_team.go index 7ddf986ce9fa6..ea7391843582c 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -366,61 +366,61 @@ func AddTeamMember(ctx context.Context, team *organization.Team, userID int64) e return err } - ctx, committer, err := db.TxContext(ctx) - if err != nil { - return err - } - defer committer.Close() - - // check in transaction - isAlreadyMember, err = organization.IsTeamMember(ctx, team.OrgID, team.ID, userID) - if err != nil || isAlreadyMember { - return err - } + err = db.WithTx(ctx, func(ctx context.Context) error { + // check in transaction + isAlreadyMember, err = organization.IsTeamMember(ctx, team.OrgID, team.ID, userID) + if err != nil || isAlreadyMember { + return err + } - sess := db.GetEngine(ctx) + sess := db.GetEngine(ctx) - if err := db.Insert(ctx, &organization.TeamUser{ - UID: userID, - OrgID: team.OrgID, - TeamID: team.ID, - }); err != nil { - return err - } else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(organization.Team)); err != nil { - return err - } + if err := db.Insert(ctx, &organization.TeamUser{ + UID: userID, + OrgID: team.OrgID, + TeamID: team.ID, + }); err != nil { + return err + } else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(organization.Team)); err != nil { + return err + } - team.NumMembers++ + team.NumMembers++ - // Give access to team repositories. - // update exist access if mode become bigger - subQuery := builder.Select("repo_id").From("team_repo"). - Where(builder.Eq{"team_id": team.ID}) + // Give access to team repositories. + // update exist access if mode become bigger + subQuery := builder.Select("repo_id").From("team_repo"). + Where(builder.Eq{"team_id": team.ID}) - if _, err := sess.Where("user_id=?", userID). - In("repo_id", subQuery). - And("mode < ?", team.AccessMode). - SetExpr("mode", team.AccessMode). - Update(new(access_model.Access)); err != nil { - return fmt.Errorf("update user accesses: %w", err) - } + if _, err := sess.Where("user_id=?", userID). + In("repo_id", subQuery). + And("mode < ?", team.AccessMode). + SetExpr("mode", team.AccessMode). + Update(new(access_model.Access)); err != nil { + return fmt.Errorf("update user accesses: %w", err) + } - // for not exist access - var repoIDs []int64 - accessSubQuery := builder.Select("repo_id").From("access").Where(builder.Eq{"user_id": userID}) - if err := sess.SQL(subQuery.And(builder.NotIn("repo_id", accessSubQuery))).Find(&repoIDs); err != nil { - return fmt.Errorf("select id accesses: %w", err) - } + // for not exist access + var repoIDs []int64 + accessSubQuery := builder.Select("repo_id").From("access").Where(builder.Eq{"user_id": userID}) + if err := sess.SQL(subQuery.And(builder.NotIn("repo_id", accessSubQuery))).Find(&repoIDs); err != nil { + return fmt.Errorf("select id accesses: %w", err) + } - accesses := make([]*access_model.Access, 0, 100) - for i, repoID := range repoIDs { - accesses = append(accesses, &access_model.Access{RepoID: repoID, UserID: userID, Mode: team.AccessMode}) - if (i%100 == 0 || i == len(repoIDs)-1) && len(accesses) > 0 { - if err = db.Insert(ctx, accesses); err != nil { - return fmt.Errorf("insert new user accesses: %w", err) + accesses := make([]*access_model.Access, 0, 100) + for i, repoID := range repoIDs { + accesses = append(accesses, &access_model.Access{RepoID: repoID, UserID: userID, Mode: team.AccessMode}) + if (i%100 == 0 || i == len(repoIDs)-1) && len(accesses) > 0 { + if err = db.Insert(ctx, accesses); err != nil { + return fmt.Errorf("insert new user accesses: %w", err) + } + accesses = accesses[:0] } - accesses = accesses[:0] } + return nil + }) + if err != nil { + return err } // this behaviour may spend much time so run it in a goroutine @@ -428,7 +428,7 @@ func AddTeamMember(ctx context.Context, team *organization.Team, userID int64) e if setting.Service.AutoWatchNewRepos { // Get team and its repositories. if err := team.LoadRepositories(ctx); err != nil { - log.Error("getRepositories failed: %v", err) + log.Error("team.LoadRepositories failed: %v", err) } // FIXME: in the goroutine, it can't access the "ctx", it could only use db.DefaultContext at the moment go func(repos []*repo_model.Repository) { @@ -440,7 +440,7 @@ func AddTeamMember(ctx context.Context, team *organization.Team, userID int64) e }(team.Repos) } - return committer.Commit() + return nil } func removeTeamMember(ctx context.Context, team *organization.Team, userID int64) error { From 5fc2a3f63ade0a0439c2825717a61649898a02d1 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 16 Sep 2023 15:23:06 +0200 Subject: [PATCH 15/23] Add missing deps to files-changed (#27100) The `docs` and `yaml` actions categories need to run when the dependencies `markdownlin-cli` or `yamllint` change, so add those to the list of dependencies for these actions. Fixes: https://github.com/go-gitea/gitea/issues/27098 --- .github/workflows/files-changed.yml | 5 +++ package-lock.json | 62 ++++++++++++++--------------- package.json | 2 +- 3 files changed, 37 insertions(+), 32 deletions(-) diff --git a/.github/workflows/files-changed.yml b/.github/workflows/files-changed.yml index 48db7a732e6d6..ef6b8022ff61f 100644 --- a/.github/workflows/files-changed.yml +++ b/.github/workflows/files-changed.yml @@ -64,9 +64,12 @@ jobs: - "**/*.md" - "docs/**" - ".markdownlint.yaml" + - "package.json" + - "package-lock.json" actions: - ".github/workflows/*" + - "Makefile" templates: - "templates/**/*.tmpl" @@ -90,3 +93,5 @@ jobs: - "**/*.yml" - "**/*.yaml" - ".yamllint.yaml" + - "pyproject.toml" + - "poetry.lock" diff --git a/package-lock.json b/package-lock.json index 34478cb00fd94..028f1e24abb90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -72,7 +72,7 @@ "eslint-plugin-vue-scoped-css": "2.5.0", "eslint-plugin-wc": "1.5.0", "jsdom": "22.1.0", - "markdownlint-cli": "0.36.0", + "markdownlint-cli": "0.35.0", "postcss-html": "1.5.0", "stylelint": "15.10.3", "stylelint-declaration-block-no-ignored-properties": "2.7.0", @@ -6046,12 +6046,12 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/ini": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", - "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ini/-/ini-3.0.1.tgz", + "integrity": "sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ==", "dev": true, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" } }, "node_modules/internal-slot": { @@ -7188,33 +7188,33 @@ } }, "node_modules/markdownlint": { - "version": "0.30.0", - "resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.30.0.tgz", - "integrity": "sha512-nInuFvI/rEzanAOArW5490Ez4EYpB5ODqVM0mcDYCPx9DKJWCQqCgejjiCvbSeE7sjbDscVtZmwr665qpF5xGA==", + "version": "0.29.0", + "resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.29.0.tgz", + "integrity": "sha512-ASAzqpODstu/Qsk0xW5BPgWnK/qjpBQ4e7IpsSvvFXcfYIjanLTdwFRJK1SIEEh0fGSMKXcJf/qhaZYHyME0wA==", "dev": true, "dependencies": { "markdown-it": "13.0.1", - "markdownlint-micromark": "0.1.7" + "markdownlint-micromark": "0.1.5" }, "engines": { "node": ">=16" } }, "node_modules/markdownlint-cli": { - "version": "0.36.0", - "resolved": "https://registry.npmjs.org/markdownlint-cli/-/markdownlint-cli-0.36.0.tgz", - "integrity": "sha512-h4WdqOam3+QOVOcJSOQuG8KvvN8dlS0OiJhbPwYWBk7VMZR40UtSSMIOpSP5B4EHPHg3W3ILSQUvqg1HNpTCxA==", + "version": "0.35.0", + "resolved": "https://registry.npmjs.org/markdownlint-cli/-/markdownlint-cli-0.35.0.tgz", + "integrity": "sha512-lVIIIV1MrUtjoocgDqXLxUCxlRbn7Ve8rsWppfwciUNwLlNS28AhNiyQ3PU7jjj4Qvj+rWTTvwkqg7AcdG988g==", "dev": true, "dependencies": { "commander": "~11.0.0", "get-stdin": "~9.0.0", - "glob": "~10.3.4", + "glob": "~10.2.7", "ignore": "~5.2.4", "js-yaml": "^4.1.0", "jsonc-parser": "~3.2.0", - "markdownlint": "~0.30.0", - "minimatch": "~9.0.3", - "run-con": "~1.3.2" + "markdownlint": "~0.29.0", + "minimatch": "~9.0.1", + "run-con": "~1.2.11" }, "bin": { "markdownlint": "markdownlint.js" @@ -7233,16 +7233,16 @@ } }, "node_modules/markdownlint-cli/node_modules/glob": { - "version": "10.3.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.4.tgz", - "integrity": "sha512-6LFElP3A+i/Q8XQKEvZjkEWEOTgAIALR9AO2rwT8bgPhDd1anmqDJDZ6lLddI4ehxxxR1S5RIqKe1uapMQfYaQ==", + "version": "10.2.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.2.7.tgz", + "integrity": "sha512-jTKehsravOJo8IJxUGfZILnkvVJM/MOfHRs8QcXolVef2zNI9Tqyy5+SeuOAZd3upViEZQLyFpQhYiHLrMUNmA==", "dev": true, "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^2.0.3", "minimatch": "^9.0.1", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", - "path-scurry": "^1.10.1" + "minipass": "^5.0.0 || ^6.0.2", + "path-scurry": "^1.7.0" }, "bin": { "glob": "dist/cjs/src/bin.js" @@ -7261,9 +7261,9 @@ "dev": true }, "node_modules/markdownlint-micromark": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/markdownlint-micromark/-/markdownlint-micromark-0.1.7.tgz", - "integrity": "sha512-BbRPTC72fl5vlSKv37v/xIENSRDYL/7X/XoFzZ740FGEbs9vZerLrIkFRY0rv7slQKxDczToYuMmqQFN61fi4Q==", + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/markdownlint-micromark/-/markdownlint-micromark-0.1.5.tgz", + "integrity": "sha512-HvofNU4QCvfUCWnocQP1IAWaqop5wpWrB0mKB6SSh0fcpV0PdmQNS6tdUuFew1utpYlUvYYzz84oDkrD76GB9A==", "dev": true, "engines": { "node": ">=16" @@ -7994,9 +7994,9 @@ } }, "node_modules/minipass": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.0.3.tgz", - "integrity": "sha512-LhbbwCfz3vsb12j/WkWQPZfKTsgqIe1Nf/ti1pKjYESGLHIVjWU96G9/ljLH4F9mWNVhlQOm0VySdAWzf05dpg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-6.0.2.tgz", + "integrity": "sha512-MzWSV5nYVT7mVyWCwn2o7JH13w2TBRmmSqSRCKzTw+lmft9X4z+3wjvs06Tzijo5z4W/kahUCDpRXTF+ZrmF/w==", "dev": true, "engines": { "node": ">=16 || 14 >=14.17" @@ -9349,13 +9349,13 @@ "dev": true }, "node_modules/run-con": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/run-con/-/run-con-1.3.2.tgz", - "integrity": "sha512-CcfE+mYiTcKEzg0IqS08+efdnH0oJ3zV0wSUFBNrMHMuxCtXvBCLzCJHatwuXDcu/RlhjTziTo/a1ruQik6/Yg==", + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/run-con/-/run-con-1.2.12.tgz", + "integrity": "sha512-5257ILMYIF4RztL9uoZ7V9Q97zHtNHn5bN3NobeAnzB1P3ASLgg8qocM2u+R18ttp+VEM78N2LK8XcNVtnSRrg==", "dev": true, "dependencies": { "deep-extend": "^0.6.0", - "ini": "~4.1.0", + "ini": "~3.0.0", "minimist": "^1.2.8", "strip-json-comments": "~3.1.1" }, diff --git a/package.json b/package.json index cbecc287e495a..87182ab214472 100644 --- a/package.json +++ b/package.json @@ -71,7 +71,7 @@ "eslint-plugin-vue-scoped-css": "2.5.0", "eslint-plugin-wc": "1.5.0", "jsdom": "22.1.0", - "markdownlint-cli": "0.36.0", + "markdownlint-cli": "0.35.0", "postcss-html": "1.5.0", "stylelint": "15.10.3", "stylelint-declaration-block-no-ignored-properties": "2.7.0", From a1b2a118123e0abd1d4737f4a6c0cf56d15eff57 Mon Sep 17 00:00:00 2001 From: puni9869 <80308335+puni9869@users.noreply.github.com> Date: Sat, 16 Sep 2023 19:39:25 +0530 Subject: [PATCH 16/23] Ui correction in mobile view nav bar left aligned items. (#27046) As title From the long time I was looking for this UI, Now its the time to fix it. Before image image --------- Co-authored-by: wxiaoguang Co-authored-by: Giteabot --- web_src/css/modules/navbar.css | 1 - 1 file changed, 1 deletion(-) diff --git a/web_src/css/modules/navbar.css b/web_src/css/modules/navbar.css index 61dffb3c80e15..b6fd2ff20ab76 100644 --- a/web_src/css/modules/navbar.css +++ b/web_src/css/modules/navbar.css @@ -31,7 +31,6 @@ padding-top: 3px; padding-bottom: 3px; display: flex; - justify-content: center; } #navbar > .menu > .item { From f91dbbba98c841f11d99be998ed5dd98122a457c Mon Sep 17 00:00:00 2001 From: JakobDev Date: Sat, 16 Sep 2023 16:39:12 +0200 Subject: [PATCH 17/23] Next round of `db.DefaultContext` refactor (#27089) Part of #27065 --- models/actions/schedule.go | 8 +-- models/actions/schedule_spec_list.go | 8 +-- models/admin/task.go | 34 +++++------ models/auth/session.go | 29 +++++----- models/auth/webauthn.go | 56 ++++--------------- models/auth/webauthn_test.go | 13 +++-- models/issues/issue_test.go | 4 +- models/issues/issue_watch.go | 14 ++--- models/issues/issue_watch_test.go | 4 +- models/issues/label.go | 34 +++++------ models/issues/label_test.go | 18 +++--- models/issues/milestone.go | 40 ++++++------- models/issues/milestone_list.go | 35 ++++++------ models/issues/milestone_test.go | 28 +++++----- models/issues/stopwatch.go | 28 +++++----- models/issues/stopwatch_test.go | 12 ++-- models/organization/mini_org.go | 5 +- models/repo/archiver.go | 14 ++--- models/repo/topic.go | 30 +++++----- models/repo/topic_test.go | 20 +++---- models/repo/update.go | 20 +++---- models/repo_transfer.go | 14 ++--- models/repo_transfer_test.go | 4 +- models/user/follow.go | 18 +++--- models/user/follow_test.go | 11 ++-- models/user/user.go | 2 +- models/user/user_test.go | 6 +- modules/auth/webauthn/webauthn.go | 2 +- modules/context/repo.go | 2 +- modules/eventsource/manager_run.go | 2 +- modules/indexer/issues/db/options.go | 2 +- modules/session/db.go | 15 ++--- routers/api/v1/org/label.go | 6 +- routers/api/v1/repo/collaborators.go | 2 +- routers/api/v1/repo/issue.go | 4 +- routers/api/v1/repo/issue_label.go | 10 ++-- routers/api/v1/repo/issue_stopwatch.go | 8 +-- routers/api/v1/repo/issue_subscription.go | 6 +- routers/api/v1/repo/label.go | 6 +- routers/api/v1/repo/milestone.go | 8 +-- routers/api/v1/repo/repo.go | 4 +- routers/api/v1/repo/topic.go | 12 ++-- routers/api/v1/repo/transfer.go | 4 +- routers/api/v1/user/follower.go | 6 +- routers/init.go | 2 +- routers/web/admin/users.go | 6 +- routers/web/auth/auth.go | 2 +- routers/web/auth/linkaccount.go | 2 +- routers/web/auth/oauth.go | 10 ++-- routers/web/auth/webauthn.go | 6 +- routers/web/explore/topic.go | 2 +- routers/web/org/home.go | 2 +- routers/web/org/org_labels.go | 4 +- routers/web/repo/issue.go | 10 ++-- routers/web/repo/issue_label.go | 10 ++-- routers/web/repo/issue_stopwatch.go | 8 +-- routers/web/repo/issue_watch.go | 2 +- routers/web/repo/migrate.go | 10 ++-- routers/web/repo/milestone.go | 12 ++-- routers/web/repo/pull.go | 8 +-- routers/web/repo/repo.go | 4 +- routers/web/repo/setting/collaboration.go | 2 +- routers/web/repo/setting/setting.go | 6 +- routers/web/repo/topic.go | 2 +- routers/web/repo/view.go | 4 +- routers/web/shared/user/header.go | 2 +- routers/web/user/home.go | 12 ++-- routers/web/user/profile.go | 4 +- routers/web/user/setting/security/security.go | 2 +- routers/web/user/setting/security/webauthn.go | 8 +-- routers/web/user/stop_watch.go | 4 +- routers/web/user/task.go | 2 +- services/issue/label.go | 32 ++++++----- services/issue/label_test.go | 5 +- services/mailer/incoming/incoming_handler.go | 2 +- services/migrations/dump.go | 4 +- services/migrations/gitea_uploader.go | 11 ++-- services/migrations/gitea_uploader_test.go | 2 +- services/migrations/migrate.go | 4 +- services/mirror/mirror_pull.go | 2 +- services/repository/archiver/archiver.go | 4 +- services/repository/collaboration.go | 6 +- services/repository/collaboration_test.go | 4 +- services/repository/push.go | 2 +- services/repository/repository.go | 6 +- services/repository/transfer.go | 4 +- services/task/migrate.go | 21 +++---- services/task/task.go | 27 ++++----- services/user/user.go | 2 +- tests/integration/incoming_email_test.go | 4 +- 90 files changed, 434 insertions(+), 464 deletions(-) diff --git a/models/actions/schedule.go b/models/actions/schedule.go index b0bc40dadc7dd..34d23f1c0179c 100644 --- a/models/actions/schedule.go +++ b/models/actions/schedule.go @@ -41,15 +41,15 @@ func init() { } // GetSchedulesMapByIDs returns the schedules by given id slice. -func GetSchedulesMapByIDs(ids []int64) (map[int64]*ActionSchedule, error) { +func GetSchedulesMapByIDs(ctx context.Context, ids []int64) (map[int64]*ActionSchedule, error) { schedules := make(map[int64]*ActionSchedule, len(ids)) - return schedules, db.GetEngine(db.DefaultContext).In("id", ids).Find(&schedules) + return schedules, db.GetEngine(ctx).In("id", ids).Find(&schedules) } // GetReposMapByIDs returns the repos by given id slice. -func GetReposMapByIDs(ids []int64) (map[int64]*repo_model.Repository, error) { +func GetReposMapByIDs(ctx context.Context, ids []int64) (map[int64]*repo_model.Repository, error) { repos := make(map[int64]*repo_model.Repository, len(ids)) - return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos) + return repos, db.GetEngine(ctx).In("id", ids).Find(&repos) } var cronParser = cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor) diff --git a/models/actions/schedule_spec_list.go b/models/actions/schedule_spec_list.go index d379490b4e91c..2c017fdabc90e 100644 --- a/models/actions/schedule_spec_list.go +++ b/models/actions/schedule_spec_list.go @@ -23,9 +23,9 @@ func (specs SpecList) GetScheduleIDs() []int64 { return ids.Values() } -func (specs SpecList) LoadSchedules() error { +func (specs SpecList) LoadSchedules(ctx context.Context) error { scheduleIDs := specs.GetScheduleIDs() - schedules, err := GetSchedulesMapByIDs(scheduleIDs) + schedules, err := GetSchedulesMapByIDs(ctx, scheduleIDs) if err != nil { return err } @@ -34,7 +34,7 @@ func (specs SpecList) LoadSchedules() error { } repoIDs := specs.GetRepoIDs() - repos, err := GetReposMapByIDs(repoIDs) + repos, err := GetReposMapByIDs(ctx, repoIDs) if err != nil { return err } @@ -95,7 +95,7 @@ func FindSpecs(ctx context.Context, opts FindSpecOptions) (SpecList, int64, erro return nil, 0, err } - if err := specs.LoadSchedules(); err != nil { + if err := specs.LoadSchedules(ctx); err != nil { return nil, 0, err } return specs, total, nil diff --git a/models/admin/task.go b/models/admin/task.go index 8aa397ad351ad..c8bc95f981425 100644 --- a/models/admin/task.go +++ b/models/admin/task.go @@ -48,11 +48,7 @@ type TranslatableMessage struct { } // LoadRepo loads repository of the task -func (task *Task) LoadRepo() error { - return task.loadRepo(db.DefaultContext) -} - -func (task *Task) loadRepo(ctx context.Context) error { +func (task *Task) LoadRepo(ctx context.Context) error { if task.Repo != nil { return nil } @@ -70,13 +66,13 @@ func (task *Task) loadRepo(ctx context.Context) error { } // LoadDoer loads do user -func (task *Task) LoadDoer() error { +func (task *Task) LoadDoer(ctx context.Context) error { if task.Doer != nil { return nil } var doer user_model.User - has, err := db.GetEngine(db.DefaultContext).ID(task.DoerID).Get(&doer) + has, err := db.GetEngine(ctx).ID(task.DoerID).Get(&doer) if err != nil { return err } else if !has { @@ -90,13 +86,13 @@ func (task *Task) LoadDoer() error { } // LoadOwner loads owner user -func (task *Task) LoadOwner() error { +func (task *Task) LoadOwner(ctx context.Context) error { if task.Owner != nil { return nil } var owner user_model.User - has, err := db.GetEngine(db.DefaultContext).ID(task.OwnerID).Get(&owner) + has, err := db.GetEngine(ctx).ID(task.OwnerID).Get(&owner) if err != nil { return err } else if !has { @@ -110,8 +106,8 @@ func (task *Task) LoadOwner() error { } // UpdateCols updates some columns -func (task *Task) UpdateCols(cols ...string) error { - _, err := db.GetEngine(db.DefaultContext).ID(task.ID).Cols(cols...).Update(task) +func (task *Task) UpdateCols(ctx context.Context, cols ...string) error { + _, err := db.GetEngine(ctx).ID(task.ID).Cols(cols...).Update(task) return err } @@ -169,12 +165,12 @@ func (err ErrTaskDoesNotExist) Unwrap() error { } // GetMigratingTask returns the migrating task by repo's id -func GetMigratingTask(repoID int64) (*Task, error) { +func GetMigratingTask(ctx context.Context, repoID int64) (*Task, error) { task := Task{ RepoID: repoID, Type: structs.TaskTypeMigrateRepo, } - has, err := db.GetEngine(db.DefaultContext).Get(&task) + has, err := db.GetEngine(ctx).Get(&task) if err != nil { return nil, err } else if !has { @@ -184,13 +180,13 @@ func GetMigratingTask(repoID int64) (*Task, error) { } // GetMigratingTaskByID returns the migrating task by repo's id -func GetMigratingTaskByID(id, doerID int64) (*Task, *migration.MigrateOptions, error) { +func GetMigratingTaskByID(ctx context.Context, id, doerID int64) (*Task, *migration.MigrateOptions, error) { task := Task{ ID: id, DoerID: doerID, Type: structs.TaskTypeMigrateRepo, } - has, err := db.GetEngine(db.DefaultContext).Get(&task) + has, err := db.GetEngine(ctx).Get(&task) if err != nil { return nil, nil, err } else if !has { @@ -205,12 +201,12 @@ func GetMigratingTaskByID(id, doerID int64) (*Task, *migration.MigrateOptions, e } // CreateTask creates a task on database -func CreateTask(task *Task) error { - return db.Insert(db.DefaultContext, task) +func CreateTask(ctx context.Context, task *Task) error { + return db.Insert(ctx, task) } // FinishMigrateTask updates database when migrate task finished -func FinishMigrateTask(task *Task) error { +func FinishMigrateTask(ctx context.Context, task *Task) error { task.Status = structs.TaskStatusFinished task.EndTime = timeutil.TimeStampNow() @@ -231,6 +227,6 @@ func FinishMigrateTask(task *Task) error { } task.PayloadContent = string(confBytes) - _, err = db.GetEngine(db.DefaultContext).ID(task.ID).Cols("status", "end_time", "payload_content").Update(task) + _, err = db.GetEngine(ctx).ID(task.ID).Cols("status", "end_time", "payload_content").Update(task) return err } diff --git a/models/auth/session.go b/models/auth/session.go index b60e6a903b9d7..28f25170eec93 100644 --- a/models/auth/session.go +++ b/models/auth/session.go @@ -4,6 +4,7 @@ package auth import ( + "context" "fmt" "code.gitea.io/gitea/models/db" @@ -22,8 +23,8 @@ func init() { } // UpdateSession updates the session with provided id -func UpdateSession(key string, data []byte) error { - _, err := db.GetEngine(db.DefaultContext).ID(key).Update(&Session{ +func UpdateSession(ctx context.Context, key string, data []byte) error { + _, err := db.GetEngine(ctx).ID(key).Update(&Session{ Data: data, Expiry: timeutil.TimeStampNow(), }) @@ -31,12 +32,12 @@ func UpdateSession(key string, data []byte) error { } // ReadSession reads the data for the provided session -func ReadSession(key string) (*Session, error) { +func ReadSession(ctx context.Context, key string) (*Session, error) { session := Session{ Key: key, } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -55,24 +56,24 @@ func ReadSession(key string) (*Session, error) { } // ExistSession checks if a session exists -func ExistSession(key string) (bool, error) { +func ExistSession(ctx context.Context, key string) (bool, error) { session := Session{ Key: key, } - return db.GetEngine(db.DefaultContext).Get(&session) + return db.GetEngine(ctx).Get(&session) } // DestroySession destroys a session -func DestroySession(key string) error { - _, err := db.GetEngine(db.DefaultContext).Delete(&Session{ +func DestroySession(ctx context.Context, key string) error { + _, err := db.GetEngine(ctx).Delete(&Session{ Key: key, }) return err } // RegenerateSession regenerates a session from the old id -func RegenerateSession(oldKey, newKey string) (*Session, error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func RegenerateSession(ctx context.Context, oldKey, newKey string) (*Session, error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -114,12 +115,12 @@ func RegenerateSession(oldKey, newKey string) (*Session, error) { } // CountSessions returns the number of sessions -func CountSessions() (int64, error) { - return db.GetEngine(db.DefaultContext).Count(&Session{}) +func CountSessions(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Count(&Session{}) } // CleanupSessions cleans up expired sessions -func CleanupSessions(maxLifetime int64) error { - _, err := db.GetEngine(db.DefaultContext).Where("expiry <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{}) +func CleanupSessions(ctx context.Context, maxLifetime int64) error { + _, err := db.GetEngine(ctx).Where("expiry <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{}) return err } diff --git a/models/auth/webauthn.go b/models/auth/webauthn.go index db5dd7eea5810..d12713bd37c89 100644 --- a/models/auth/webauthn.go +++ b/models/auth/webauthn.go @@ -67,11 +67,7 @@ func (cred WebAuthnCredential) TableName() string { } // UpdateSignCount will update the database value of SignCount -func (cred *WebAuthnCredential) UpdateSignCount() error { - return cred.updateSignCount(db.DefaultContext) -} - -func (cred *WebAuthnCredential) updateSignCount(ctx context.Context) error { +func (cred *WebAuthnCredential) UpdateSignCount(ctx context.Context) error { _, err := db.GetEngine(ctx).ID(cred.ID).Cols("sign_count").Update(cred) return err } @@ -113,30 +109,18 @@ func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential { } // GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user -func GetWebAuthnCredentialsByUID(uid int64) (WebAuthnCredentialList, error) { - return getWebAuthnCredentialsByUID(db.DefaultContext, uid) -} - -func getWebAuthnCredentialsByUID(ctx context.Context, uid int64) (WebAuthnCredentialList, error) { +func GetWebAuthnCredentialsByUID(ctx context.Context, uid int64) (WebAuthnCredentialList, error) { creds := make(WebAuthnCredentialList, 0) return creds, db.GetEngine(ctx).Where("user_id = ?", uid).Find(&creds) } // ExistsWebAuthnCredentialsForUID returns if the given user has credentials -func ExistsWebAuthnCredentialsForUID(uid int64) (bool, error) { - return existsWebAuthnCredentialsByUID(db.DefaultContext, uid) -} - -func existsWebAuthnCredentialsByUID(ctx context.Context, uid int64) (bool, error) { +func ExistsWebAuthnCredentialsForUID(ctx context.Context, uid int64) (bool, error) { return db.GetEngine(ctx).Where("user_id = ?", uid).Exist(&WebAuthnCredential{}) } // GetWebAuthnCredentialByName returns WebAuthn credential by id -func GetWebAuthnCredentialByName(uid int64, name string) (*WebAuthnCredential, error) { - return getWebAuthnCredentialByName(db.DefaultContext, uid, name) -} - -func getWebAuthnCredentialByName(ctx context.Context, uid int64, name string) (*WebAuthnCredential, error) { +func GetWebAuthnCredentialByName(ctx context.Context, uid int64, name string) (*WebAuthnCredential, error) { cred := new(WebAuthnCredential) if found, err := db.GetEngine(ctx).Where("user_id = ? AND lower_name = ?", uid, strings.ToLower(name)).Get(cred); err != nil { return nil, err @@ -147,11 +131,7 @@ func getWebAuthnCredentialByName(ctx context.Context, uid int64, name string) (* } // GetWebAuthnCredentialByID returns WebAuthn credential by id -func GetWebAuthnCredentialByID(id int64) (*WebAuthnCredential, error) { - return getWebAuthnCredentialByID(db.DefaultContext, id) -} - -func getWebAuthnCredentialByID(ctx context.Context, id int64) (*WebAuthnCredential, error) { +func GetWebAuthnCredentialByID(ctx context.Context, id int64) (*WebAuthnCredential, error) { cred := new(WebAuthnCredential) if found, err := db.GetEngine(ctx).ID(id).Get(cred); err != nil { return nil, err @@ -162,16 +142,12 @@ func getWebAuthnCredentialByID(ctx context.Context, id int64) (*WebAuthnCredenti } // HasWebAuthnRegistrationsByUID returns whether a given user has WebAuthn registrations -func HasWebAuthnRegistrationsByUID(uid int64) (bool, error) { - return db.GetEngine(db.DefaultContext).Where("user_id = ?", uid).Exist(&WebAuthnCredential{}) +func HasWebAuthnRegistrationsByUID(ctx context.Context, uid int64) (bool, error) { + return db.GetEngine(ctx).Where("user_id = ?", uid).Exist(&WebAuthnCredential{}) } // GetWebAuthnCredentialByCredID returns WebAuthn credential by credential ID -func GetWebAuthnCredentialByCredID(userID int64, credID []byte) (*WebAuthnCredential, error) { - return getWebAuthnCredentialByCredID(db.DefaultContext, userID, credID) -} - -func getWebAuthnCredentialByCredID(ctx context.Context, userID int64, credID []byte) (*WebAuthnCredential, error) { +func GetWebAuthnCredentialByCredID(ctx context.Context, userID int64, credID []byte) (*WebAuthnCredential, error) { cred := new(WebAuthnCredential) if found, err := db.GetEngine(ctx).Where("user_id = ? AND credential_id = ?", userID, credID).Get(cred); err != nil { return nil, err @@ -182,11 +158,7 @@ func getWebAuthnCredentialByCredID(ctx context.Context, userID int64, credID []b } // CreateCredential will create a new WebAuthnCredential from the given Credential -func CreateCredential(userID int64, name string, cred *webauthn.Credential) (*WebAuthnCredential, error) { - return createCredential(db.DefaultContext, userID, name, cred) -} - -func createCredential(ctx context.Context, userID int64, name string, cred *webauthn.Credential) (*WebAuthnCredential, error) { +func CreateCredential(ctx context.Context, userID int64, name string, cred *webauthn.Credential) (*WebAuthnCredential, error) { c := &WebAuthnCredential{ UserID: userID, Name: name, @@ -205,18 +177,14 @@ func createCredential(ctx context.Context, userID int64, name string, cred *weba } // DeleteCredential will delete WebAuthnCredential -func DeleteCredential(id, userID int64) (bool, error) { - return deleteCredential(db.DefaultContext, id, userID) -} - -func deleteCredential(ctx context.Context, id, userID int64) (bool, error) { +func DeleteCredential(ctx context.Context, id, userID int64) (bool, error) { had, err := db.GetEngine(ctx).ID(id).Where("user_id = ?", userID).Delete(&WebAuthnCredential{}) return had > 0, err } // WebAuthnCredentials implementns the webauthn.User interface -func WebAuthnCredentials(userID int64) ([]webauthn.Credential, error) { - dbCreds, err := GetWebAuthnCredentialsByUID(userID) +func WebAuthnCredentials(ctx context.Context, userID int64) ([]webauthn.Credential, error) { + dbCreds, err := GetWebAuthnCredentialsByUID(ctx, userID) if err != nil { return nil, err } diff --git a/models/auth/webauthn_test.go b/models/auth/webauthn_test.go index 6f2ec087c7aa0..f1cf398adf558 100644 --- a/models/auth/webauthn_test.go +++ b/models/auth/webauthn_test.go @@ -7,6 +7,7 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "github.com/go-webauthn/webauthn/webauthn" @@ -16,11 +17,11 @@ import ( func TestGetWebAuthnCredentialByID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - res, err := auth_model.GetWebAuthnCredentialByID(1) + res, err := auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 1) assert.NoError(t, err) assert.Equal(t, "WebAuthn credential", res.Name) - _, err = auth_model.GetWebAuthnCredentialByID(342432) + _, err = auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 342432) assert.Error(t, err) assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err)) } @@ -28,7 +29,7 @@ func TestGetWebAuthnCredentialByID(t *testing.T) { func TestGetWebAuthnCredentialsByUID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - res, err := auth_model.GetWebAuthnCredentialsByUID(32) + res, err := auth_model.GetWebAuthnCredentialsByUID(db.DefaultContext, 32) assert.NoError(t, err) assert.Len(t, res, 1) assert.Equal(t, "WebAuthn credential", res[0].Name) @@ -42,7 +43,7 @@ func TestWebAuthnCredential_UpdateSignCount(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1}) cred.SignCount = 1 - assert.NoError(t, cred.UpdateSignCount()) + assert.NoError(t, cred.UpdateSignCount(db.DefaultContext)) unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{ID: 1, SignCount: 1}) } @@ -50,14 +51,14 @@ func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1}) cred.SignCount = 0xffffffff - assert.NoError(t, cred.UpdateSignCount()) + assert.NoError(t, cred.UpdateSignCount(db.DefaultContext)) unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{ID: 1, SignCount: 0xffffffff}) } func TestCreateCredential(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - res, err := auth_model.CreateCredential(1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")}) + res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")}) assert.NoError(t, err) assert.Equal(t, "WebAuthn Created Credential", res.Name) assert.Equal(t, []byte("Test"), res.CredentialID) diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index 747fbbc78caef..b7fa7eff1c150 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -385,7 +385,7 @@ func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}), } - assert.NoError(t, miles.LoadTotalTrackedTimes()) + assert.NoError(t, miles.LoadTotalTrackedTimes(db.DefaultContext)) assert.Equal(t, int64(3682), miles[0].TotalTrackedTime) } @@ -394,7 +394,7 @@ func TestLoadTotalTrackedTime(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) - assert.NoError(t, milestone.LoadTotalTrackedTime()) + assert.NoError(t, milestone.LoadTotalTrackedTime(db.DefaultContext)) assert.Equal(t, int64(3682), milestone.TotalTrackedTime) } diff --git a/models/issues/issue_watch.go b/models/issues/issue_watch.go index 1efc0ea6871c4..b7e9504c6762b 100644 --- a/models/issues/issue_watch.go +++ b/models/issues/issue_watch.go @@ -30,8 +30,8 @@ func init() { type IssueWatchList []*IssueWatch // CreateOrUpdateIssueWatch set watching for a user and issue -func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { - iw, exists, err := GetIssueWatch(db.DefaultContext, userID, issueID) +func CreateOrUpdateIssueWatch(ctx context.Context, userID, issueID int64, isWatching bool) error { + iw, exists, err := GetIssueWatch(ctx, userID, issueID) if err != nil { return err } @@ -43,13 +43,13 @@ func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { IsWatching: isWatching, } - if _, err := db.GetEngine(db.DefaultContext).Insert(iw); err != nil { + if _, err := db.GetEngine(ctx).Insert(iw); err != nil { return err } } else { iw.IsWatching = isWatching - if _, err := db.GetEngine(db.DefaultContext).ID(iw.ID).Cols("is_watching", "updated_unix").Update(iw); err != nil { + if _, err := db.GetEngine(ctx).ID(iw.ID).Cols("is_watching", "updated_unix").Update(iw); err != nil { return err } } @@ -69,15 +69,15 @@ func GetIssueWatch(ctx context.Context, userID, issueID int64) (iw *IssueWatch, // CheckIssueWatch check if an user is watching an issue // it takes participants and repo watch into account -func CheckIssueWatch(user *user_model.User, issue *Issue) (bool, error) { - iw, exist, err := GetIssueWatch(db.DefaultContext, user.ID, issue.ID) +func CheckIssueWatch(ctx context.Context, user *user_model.User, issue *Issue) (bool, error) { + iw, exist, err := GetIssueWatch(ctx, user.ID, issue.ID) if err != nil { return false, err } if exist { return iw.IsWatching, nil } - w, err := repo_model.GetWatch(db.DefaultContext, user.ID, issue.RepoID) + w, err := repo_model.GetWatch(ctx, user.ID, issue.RepoID) if err != nil { return false, err } diff --git a/models/issues/issue_watch_test.go b/models/issues/issue_watch_test.go index 4f44487f567ad..d4ce8d8d3d6f1 100644 --- a/models/issues/issue_watch_test.go +++ b/models/issues/issue_watch_test.go @@ -16,11 +16,11 @@ import ( func TestCreateOrUpdateIssueWatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(3, 1, true)) + assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 3, 1, true)) iw := unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 3, IssueID: 1}) assert.True(t, iw.IsWatching) - assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(1, 1, false)) + assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 1, 1, false)) iw = unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 1, IssueID: 1}) assert.False(t, iw.IsWatching) } diff --git a/models/issues/label.go b/models/issues/label.go index 0087c933a6cdb..f8dbb9e39cd46 100644 --- a/models/issues/label.go +++ b/models/issues/label.go @@ -199,8 +199,8 @@ func NewLabel(ctx context.Context, l *Label) error { } // NewLabels creates new labels -func NewLabels(labels ...*Label) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func NewLabels(ctx context.Context, labels ...*Label) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -221,19 +221,19 @@ func NewLabels(labels ...*Label) error { } // UpdateLabel updates label information. -func UpdateLabel(l *Label) error { +func UpdateLabel(ctx context.Context, l *Label) error { color, err := label.NormalizeColor(l.Color) if err != nil { return err } l.Color = color - return updateLabelCols(db.DefaultContext, l, "name", "description", "color", "exclusive", "archived_unix") + return updateLabelCols(ctx, l, "name", "description", "color", "exclusive", "archived_unix") } // DeleteLabel delete a label -func DeleteLabel(id, labelID int64) error { - l, err := GetLabelByID(db.DefaultContext, labelID) +func DeleteLabel(ctx context.Context, id, labelID int64) error { + l, err := GetLabelByID(ctx, labelID) if err != nil { if IsErrLabelNotExist(err) { return nil @@ -241,7 +241,7 @@ func DeleteLabel(id, labelID int64) error { return err } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -289,9 +289,9 @@ func GetLabelByID(ctx context.Context, labelID int64) (*Label, error) { } // GetLabelsByIDs returns a list of labels by IDs -func GetLabelsByIDs(labelIDs []int64, cols ...string) ([]*Label, error) { +func GetLabelsByIDs(ctx context.Context, labelIDs []int64, cols ...string) ([]*Label, error) { labels := make([]*Label, 0, len(labelIDs)) - return labels, db.GetEngine(db.DefaultContext).Table("label"). + return labels, db.GetEngine(ctx).Table("label"). In("id", labelIDs). Asc("name"). Cols(cols...). @@ -339,9 +339,9 @@ func GetLabelInRepoByID(ctx context.Context, repoID, labelID int64) (*Label, err // GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given // repository. // it silently ignores label names that do not belong to the repository. -func GetLabelIDsInRepoByNames(repoID int64, labelNames []string) ([]int64, error) { +func GetLabelIDsInRepoByNames(ctx context.Context, repoID int64, labelNames []string) ([]int64, error) { labelIDs := make([]int64, 0, len(labelNames)) - return labelIDs, db.GetEngine(db.DefaultContext).Table("label"). + return labelIDs, db.GetEngine(ctx).Table("label"). Where("repo_id = ?", repoID). In("name", labelNames). Asc("name"). @@ -398,8 +398,8 @@ func GetLabelsByRepoID(ctx context.Context, repoID int64, sortType string, listO } // CountLabelsByRepoID count number of all labels that belong to given repository by ID. -func CountLabelsByRepoID(repoID int64) (int64, error) { - return db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Count(&Label{}) +func CountLabelsByRepoID(ctx context.Context, repoID int64) (int64, error) { + return db.GetEngine(ctx).Where("repo_id = ?", repoID).Count(&Label{}) } // GetLabelInOrgByName returns a label by name in given organization. @@ -442,13 +442,13 @@ func GetLabelInOrgByID(ctx context.Context, orgID, labelID int64) (*Label, error // GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given // organization. -func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error) { +func GetLabelIDsInOrgByNames(ctx context.Context, orgID int64, labelNames []string) ([]int64, error) { if orgID <= 0 { return nil, ErrOrgLabelNotExist{0, orgID} } labelIDs := make([]int64, 0, len(labelNames)) - return labelIDs, db.GetEngine(db.DefaultContext).Table("label"). + return labelIDs, db.GetEngine(ctx).Table("label"). Where("org_id = ?", orgID). In("name", labelNames). Asc("name"). @@ -506,8 +506,8 @@ func GetLabelIDsByNames(ctx context.Context, labelNames []string) ([]int64, erro } // CountLabelsByOrgID count all labels that belong to given organization by ID. -func CountLabelsByOrgID(orgID int64) (int64, error) { - return db.GetEngine(db.DefaultContext).Where("org_id = ?", orgID).Count(&Label{}) +func CountLabelsByOrgID(ctx context.Context, orgID int64) (int64, error) { + return db.GetEngine(ctx).Where("org_id = ?", orgID).Count(&Label{}) } func updateLabelCols(ctx context.Context, l *Label, cols ...string) error { diff --git a/models/issues/label_test.go b/models/issues/label_test.go index 3f0e980b318be..9f44cd3e03746 100644 --- a/models/issues/label_test.go +++ b/models/issues/label_test.go @@ -48,7 +48,7 @@ func TestNewLabels(t *testing.T) { for _, label := range labels { unittest.AssertNotExistsBean(t, label) } - assert.NoError(t, issues_model.NewLabels(labels...)) + assert.NoError(t, issues_model.NewLabels(db.DefaultContext, labels...)) for _, label := range labels { unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID)) } @@ -81,7 +81,7 @@ func TestGetLabelInRepoByName(t *testing.T) { func TestGetLabelInRepoByNames(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - labelIDs, err := issues_model.GetLabelIDsInRepoByNames(1, []string{"label1", "label2"}) + labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2"}) assert.NoError(t, err) assert.Len(t, labelIDs, 2) @@ -93,7 +93,7 @@ func TestGetLabelInRepoByNames(t *testing.T) { func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // label3 doesn't exists.. See labels.yml - labelIDs, err := issues_model.GetLabelIDsInRepoByNames(1, []string{"label1", "label2", "label3"}) + labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2", "label3"}) assert.NoError(t, err) assert.Len(t, labelIDs, 2) @@ -166,7 +166,7 @@ func TestGetLabelInOrgByName(t *testing.T) { func TestGetLabelInOrgByNames(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - labelIDs, err := issues_model.GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4"}) + labelIDs, err := issues_model.GetLabelIDsInOrgByNames(db.DefaultContext, 3, []string{"orglabel3", "orglabel4"}) assert.NoError(t, err) assert.Len(t, labelIDs, 2) @@ -178,7 +178,7 @@ func TestGetLabelInOrgByNames(t *testing.T) { func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // orglabel99 doesn't exists.. See labels.yml - labelIDs, err := issues_model.GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4", "orglabel99"}) + labelIDs, err := issues_model.GetLabelIDsInOrgByNames(db.DefaultContext, 3, []string{"orglabel3", "orglabel4", "orglabel99"}) assert.NoError(t, err) assert.Len(t, labelIDs, 2) @@ -269,7 +269,7 @@ func TestUpdateLabel(t *testing.T) { } label.Color = update.Color label.Name = update.Name - assert.NoError(t, issues_model.UpdateLabel(update)) + assert.NoError(t, issues_model.UpdateLabel(db.DefaultContext, update)) newLabel := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) assert.EqualValues(t, label.ID, newLabel.ID) assert.EqualValues(t, label.Color, newLabel.Color) @@ -282,13 +282,13 @@ func TestUpdateLabel(t *testing.T) { func TestDeleteLabel(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) - assert.NoError(t, issues_model.DeleteLabel(label.RepoID, label.ID)) + assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID)) unittest.AssertNotExistsBean(t, &issues_model.Label{ID: label.ID, RepoID: label.RepoID}) - assert.NoError(t, issues_model.DeleteLabel(label.RepoID, label.ID)) + assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID)) unittest.AssertNotExistsBean(t, &issues_model.Label{ID: label.ID}) - assert.NoError(t, issues_model.DeleteLabel(unittest.NonexistentID, unittest.NonexistentID)) + assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{}) } diff --git a/models/issues/milestone.go b/models/issues/milestone.go index c15b2a41fe344..ad1d5d0453282 100644 --- a/models/issues/milestone.go +++ b/models/issues/milestone.go @@ -103,8 +103,8 @@ func (m *Milestone) State() api.StateType { } // NewMilestone creates new milestone of repository. -func NewMilestone(m *Milestone) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func NewMilestone(ctx context.Context, m *Milestone) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -140,9 +140,9 @@ func GetMilestoneByRepoID(ctx context.Context, repoID, id int64) (*Milestone, er } // GetMilestoneByRepoIDANDName return a milestone if one exist by name and repo -func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) { +func GetMilestoneByRepoIDANDName(ctx context.Context, repoID int64, name string) (*Milestone, error) { var mile Milestone - has, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, name).Get(&mile) + has, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, name).Get(&mile) if err != nil { return nil, err } @@ -153,8 +153,8 @@ func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) } // UpdateMilestone updates information of given milestone. -func UpdateMilestone(m *Milestone, oldIsClosed bool) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func UpdateMilestone(ctx context.Context, m *Milestone, oldIsClosed bool) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -211,8 +211,8 @@ func UpdateMilestoneCounters(ctx context.Context, id int64) error { } // ChangeMilestoneStatusByRepoIDAndID changes a milestone open/closed status if the milestone ID is in the repo. -func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func ChangeMilestoneStatusByRepoIDAndID(ctx context.Context, repoID, milestoneID int64, isClosed bool) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -238,8 +238,8 @@ func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool } // ChangeMilestoneStatus changes the milestone open/closed status. -func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func ChangeMilestoneStatus(ctx context.Context, m *Milestone, isClosed bool) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -269,8 +269,8 @@ func changeMilestoneStatus(ctx context.Context, m *Milestone, isClosed bool) err } // DeleteMilestoneByRepoID deletes a milestone from a repository. -func DeleteMilestoneByRepoID(repoID, id int64) error { - m, err := GetMilestoneByRepoID(db.DefaultContext, repoID, id) +func DeleteMilestoneByRepoID(ctx context.Context, repoID, id int64) error { + m, err := GetMilestoneByRepoID(ctx, repoID, id) if err != nil { if IsErrMilestoneNotExist(err) { return nil @@ -278,12 +278,12 @@ func DeleteMilestoneByRepoID(repoID, id int64) error { return err } - repo, err := repo_model.GetRepositoryByID(db.DefaultContext, m.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, m.RepoID) if err != nil { return err } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -332,7 +332,8 @@ func updateRepoMilestoneNum(ctx context.Context, repoID int64) error { return err } -func (m *Milestone) loadTotalTrackedTime(ctx context.Context) error { +// LoadTotalTrackedTime loads the tracked time for the milestone +func (m *Milestone) LoadTotalTrackedTime(ctx context.Context) error { type totalTimesByMilestone struct { MilestoneID int64 Time int64 @@ -355,18 +356,13 @@ func (m *Milestone) loadTotalTrackedTime(ctx context.Context) error { return nil } -// LoadTotalTrackedTime loads the tracked time for the milestone -func (m *Milestone) LoadTotalTrackedTime() error { - return m.loadTotalTrackedTime(db.DefaultContext) -} - // InsertMilestones creates milestones of repository. -func InsertMilestones(ms ...*Milestone) (err error) { +func InsertMilestones(ctx context.Context, ms ...*Milestone) (err error) { if len(ms) == 0 { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/issues/milestone_list.go b/models/issues/milestone_list.go index b0c29106a037a..d5c9b1358c847 100644 --- a/models/issues/milestone_list.go +++ b/models/issues/milestone_list.go @@ -100,9 +100,9 @@ func GetMilestoneIDsByNames(ctx context.Context, names []string) ([]int64, error } // SearchMilestones search milestones -func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType, keyword string) (MilestoneList, error) { +func SearchMilestones(ctx context.Context, repoCond builder.Cond, page int, isClosed bool, sortType, keyword string) (MilestoneList, error) { miles := make([]*Milestone, 0, setting.UI.IssuePagingNum) - sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) + sess := db.GetEngine(ctx).Where("is_closed = ?", isClosed) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -131,8 +131,9 @@ func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType, } // GetMilestonesByRepoIDs returns a list of milestones of given repositories and status. -func GetMilestonesByRepoIDs(repoIDs []int64, page int, isClosed bool, sortType string) (MilestoneList, error) { +func GetMilestonesByRepoIDs(ctx context.Context, repoIDs []int64, page int, isClosed bool, sortType string) (MilestoneList, error) { return SearchMilestones( + ctx, builder.In("repo_id", repoIDs), page, isClosed, @@ -141,7 +142,8 @@ func GetMilestonesByRepoIDs(repoIDs []int64, page int, isClosed bool, sortType s ) } -func (milestones MilestoneList) loadTotalTrackedTimes(ctx context.Context) error { +// LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request +func (milestones MilestoneList) LoadTotalTrackedTimes(ctx context.Context) error { type totalTimesByMilestone struct { MilestoneID int64 Time int64 @@ -181,11 +183,6 @@ func (milestones MilestoneList) loadTotalTrackedTimes(ctx context.Context) error return nil } -// LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request -func (milestones MilestoneList) LoadTotalTrackedTimes() error { - return milestones.loadTotalTrackedTimes(db.DefaultContext) -} - // CountMilestones returns number of milestones in given repository with other options func CountMilestones(ctx context.Context, opts GetMilestonesOption) (int64, error) { return db.GetEngine(ctx). @@ -194,8 +191,8 @@ func CountMilestones(ctx context.Context, opts GetMilestonesOption) (int64, erro } // CountMilestonesByRepoCond map from repo conditions to number of milestones matching the options` -func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64]int64, error) { - sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) +func CountMilestonesByRepoCond(ctx context.Context, repoCond builder.Cond, isClosed bool) (map[int64]int64, error) { + sess := db.GetEngine(ctx).Where("is_closed = ?", isClosed) if repoCond.IsValid() { sess.In("repo_id", builder.Select("id").From("repository").Where(repoCond)) } @@ -219,8 +216,8 @@ func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64] } // CountMilestonesByRepoCondAndKw map from repo conditions and the keyword of milestones' name to number of milestones matching the options` -func CountMilestonesByRepoCondAndKw(repoCond builder.Cond, keyword string, isClosed bool) (map[int64]int64, error) { - sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) +func CountMilestonesByRepoCondAndKw(ctx context.Context, repoCond builder.Cond, keyword string, isClosed bool) (map[int64]int64, error) { + sess := db.GetEngine(ctx).Where("is_closed = ?", isClosed) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -257,11 +254,11 @@ func (m MilestonesStats) Total() int64 { } // GetMilestonesStatsByRepoCond returns milestone statistic information for dashboard by given conditions. -func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, error) { +func GetMilestonesStatsByRepoCond(ctx context.Context, repoCond builder.Cond) (*MilestonesStats, error) { var err error stats := &MilestonesStats{} - sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", false) + sess := db.GetEngine(ctx).Where("is_closed = ?", false) if repoCond.IsValid() { sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) } @@ -270,7 +267,7 @@ func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, erro return nil, err } - sess = db.GetEngine(db.DefaultContext).Where("is_closed = ?", true) + sess = db.GetEngine(ctx).Where("is_closed = ?", true) if repoCond.IsValid() { sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) } @@ -283,11 +280,11 @@ func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, erro } // GetMilestonesStatsByRepoCondAndKw returns milestone statistic information for dashboard by given repo conditions and name keyword. -func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (*MilestonesStats, error) { +func GetMilestonesStatsByRepoCondAndKw(ctx context.Context, repoCond builder.Cond, keyword string) (*MilestonesStats, error) { var err error stats := &MilestonesStats{} - sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", false) + sess := db.GetEngine(ctx).Where("is_closed = ?", false) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } @@ -299,7 +296,7 @@ func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (* return nil, err } - sess = db.GetEngine(db.DefaultContext).Where("is_closed = ?", true) + sess = db.GetEngine(ctx).Where("is_closed = ?", true) if len(keyword) > 0 { sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) } diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go index e85d77ebc8408..403eeaadb3211 100644 --- a/models/issues/milestone_test.go +++ b/models/issues/milestone_test.go @@ -201,12 +201,12 @@ func TestCountMilestonesByRepoIDs(t *testing.T) { repo1OpenCount, repo1ClosedCount := milestonesCount(1) repo2OpenCount, repo2ClosedCount := milestonesCount(2) - openCounts, err := issues_model.CountMilestonesByRepoCond(builder.In("repo_id", []int64{1, 2}), false) + openCounts, err := issues_model.CountMilestonesByRepoCond(db.DefaultContext, builder.In("repo_id", []int64{1, 2}), false) assert.NoError(t, err) assert.EqualValues(t, repo1OpenCount, openCounts[1]) assert.EqualValues(t, repo2OpenCount, openCounts[2]) - closedCounts, err := issues_model.CountMilestonesByRepoCond(builder.In("repo_id", []int64{1, 2}), true) + closedCounts, err := issues_model.CountMilestonesByRepoCond(db.DefaultContext, builder.In("repo_id", []int64{1, 2}), true) assert.NoError(t, err) assert.EqualValues(t, repo1ClosedCount, closedCounts[1]) assert.EqualValues(t, repo2ClosedCount, closedCounts[2]) @@ -218,7 +218,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) test := func(sortType string, sortCond func(*issues_model.Milestone) int) { for _, page := range []int{0, 1} { - openMilestones, err := issues_model.GetMilestonesByRepoIDs([]int64{repo1.ID, repo2.ID}, page, false, sortType) + openMilestones, err := issues_model.GetMilestonesByRepoIDs(db.DefaultContext, []int64{repo1.ID, repo2.ID}, page, false, sortType) assert.NoError(t, err) assert.Len(t, openMilestones, repo1.NumOpenMilestones+repo2.NumOpenMilestones) values := make([]int, len(openMilestones)) @@ -227,7 +227,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { } assert.True(t, sort.IntsAreSorted(values)) - closedMilestones, err := issues_model.GetMilestonesByRepoIDs([]int64{repo1.ID, repo2.ID}, page, true, sortType) + closedMilestones, err := issues_model.GetMilestonesByRepoIDs(db.DefaultContext, []int64{repo1.ID, repo2.ID}, page, true, sortType) assert.NoError(t, err) assert.Len(t, closedMilestones, repo1.NumClosedMilestones+repo2.NumClosedMilestones) values = make([]int, len(closedMilestones)) @@ -262,7 +262,7 @@ func TestGetMilestonesStats(t *testing.T) { test := func(repoID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - stats, err := issues_model.GetMilestonesStatsByRepoCond(builder.And(builder.Eq{"repo_id": repoID})) + stats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.And(builder.Eq{"repo_id": repoID})) assert.NoError(t, err) assert.EqualValues(t, repo.NumMilestones-repo.NumClosedMilestones, stats.OpenCount) assert.EqualValues(t, repo.NumClosedMilestones, stats.ClosedCount) @@ -271,7 +271,7 @@ func TestGetMilestonesStats(t *testing.T) { test(2) test(3) - stats, err := issues_model.GetMilestonesStatsByRepoCond(builder.And(builder.Eq{"repo_id": unittest.NonexistentID})) + stats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.And(builder.Eq{"repo_id": unittest.NonexistentID})) assert.NoError(t, err) assert.EqualValues(t, 0, stats.OpenCount) assert.EqualValues(t, 0, stats.ClosedCount) @@ -279,7 +279,7 @@ func TestGetMilestonesStats(t *testing.T) { repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - milestoneStats, err := issues_model.GetMilestonesStatsByRepoCond(builder.In("repo_id", []int64{repo1.ID, repo2.ID})) + milestoneStats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.In("repo_id", []int64{repo1.ID, repo2.ID})) assert.NoError(t, err) assert.EqualValues(t, repo1.NumOpenMilestones+repo2.NumOpenMilestones, milestoneStats.OpenCount) assert.EqualValues(t, repo1.NumClosedMilestones+repo2.NumClosedMilestones, milestoneStats.ClosedCount) @@ -293,7 +293,7 @@ func TestNewMilestone(t *testing.T) { Content: "milestoneContent", } - assert.NoError(t, issues_model.NewMilestone(milestone)) + assert.NoError(t, issues_model.NewMilestone(db.DefaultContext, milestone)) unittest.AssertExistsAndLoadBean(t, milestone) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) } @@ -302,22 +302,22 @@ func TestChangeMilestoneStatus(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) - assert.NoError(t, issues_model.ChangeMilestoneStatus(milestone, true)) + assert.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, true)) unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=1") unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) - assert.NoError(t, issues_model.ChangeMilestoneStatus(milestone, false)) + assert.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, false)) unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=0") unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) } func TestDeleteMilestoneByRepoID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, issues_model.DeleteMilestoneByRepoID(1, 1)) + assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, 1, 1)) unittest.AssertNotExistsBean(t, &issues_model.Milestone{ID: 1}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: 1}) - assert.NoError(t, issues_model.DeleteMilestoneByRepoID(unittest.NonexistentID, unittest.NonexistentID)) + assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } func TestUpdateMilestone(t *testing.T) { @@ -326,7 +326,7 @@ func TestUpdateMilestone(t *testing.T) { milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) milestone.Name = " newMilestoneName " milestone.Content = "newMilestoneContent" - assert.NoError(t, issues_model.UpdateMilestone(milestone, milestone.IsClosed)) + assert.NoError(t, issues_model.UpdateMilestone(db.DefaultContext, milestone, milestone.IsClosed)) milestone = unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) assert.EqualValues(t, "newMilestoneName", milestone.Name) unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) @@ -361,7 +361,7 @@ func TestMigrate_InsertMilestones(t *testing.T) { RepoID: repo.ID, Name: name, } - err := issues_model.InsertMilestones(ms) + err := issues_model.InsertMilestones(db.DefaultContext, ms) assert.NoError(t, err) unittest.AssertExistsAndLoadBean(t, ms) repoModified := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) diff --git a/models/issues/stopwatch.go b/models/issues/stopwatch.go index c8cd5ad33f26a..2c662bdb06a80 100644 --- a/models/issues/stopwatch.go +++ b/models/issues/stopwatch.go @@ -81,9 +81,9 @@ type UserStopwatch struct { } // GetUIDsAndNotificationCounts between the two provided times -func GetUIDsAndStopwatch() ([]*UserStopwatch, error) { +func GetUIDsAndStopwatch(ctx context.Context) ([]*UserStopwatch, error) { sws := []*Stopwatch{} - if err := db.GetEngine(db.DefaultContext).Where("issue_id != 0").Find(&sws); err != nil { + if err := db.GetEngine(ctx).Where("issue_id != 0").Find(&sws); err != nil { return nil, err } if len(sws) == 0 { @@ -107,9 +107,9 @@ func GetUIDsAndStopwatch() ([]*UserStopwatch, error) { } // GetUserStopwatches return list of all stopwatches of a user -func GetUserStopwatches(userID int64, listOptions db.ListOptions) ([]*Stopwatch, error) { +func GetUserStopwatches(ctx context.Context, userID int64, listOptions db.ListOptions) ([]*Stopwatch, error) { sws := make([]*Stopwatch, 0, 8) - sess := db.GetEngine(db.DefaultContext).Where("stopwatch.user_id = ?", userID) + sess := db.GetEngine(ctx).Where("stopwatch.user_id = ?", userID) if listOptions.Page != 0 { sess = db.SetSessionPagination(sess, &listOptions) } @@ -122,13 +122,13 @@ func GetUserStopwatches(userID int64, listOptions db.ListOptions) ([]*Stopwatch, } // CountUserStopwatches return count of all stopwatches of a user -func CountUserStopwatches(userID int64) (int64, error) { - return db.GetEngine(db.DefaultContext).Where("user_id = ?", userID).Count(&Stopwatch{}) +func CountUserStopwatches(ctx context.Context, userID int64) (int64, error) { + return db.GetEngine(ctx).Where("user_id = ?", userID).Count(&Stopwatch{}) } // StopwatchExists returns true if the stopwatch exists -func StopwatchExists(userID, issueID int64) bool { - _, exists, _ := getStopwatch(db.DefaultContext, userID, issueID) +func StopwatchExists(ctx context.Context, userID, issueID int64) bool { + _, exists, _ := getStopwatch(ctx, userID, issueID) return exists } @@ -168,15 +168,15 @@ func FinishIssueStopwatchIfPossible(ctx context.Context, user *user_model.User, } // CreateOrStopIssueStopwatch create an issue stopwatch if it's not exist, otherwise finish it -func CreateOrStopIssueStopwatch(user *user_model.User, issue *Issue) error { - _, exists, err := getStopwatch(db.DefaultContext, user.ID, issue.ID) +func CreateOrStopIssueStopwatch(ctx context.Context, user *user_model.User, issue *Issue) error { + _, exists, err := getStopwatch(ctx, user.ID, issue.ID) if err != nil { return err } if exists { - return FinishIssueStopwatch(db.DefaultContext, user, issue) + return FinishIssueStopwatch(ctx, user, issue) } - return CreateIssueStopwatch(db.DefaultContext, user, issue) + return CreateIssueStopwatch(ctx, user, issue) } // FinishIssueStopwatch if stopwatch exist then finish it otherwise return an error @@ -269,8 +269,8 @@ func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss } // CancelStopwatch removes the given stopwatch and logs it into issue's timeline. -func CancelStopwatch(user *user_model.User, issue *Issue) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func CancelStopwatch(ctx context.Context, user *user_model.User, issue *Issue) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/issues/stopwatch_test.go b/models/issues/stopwatch_test.go index fa937ecbedde3..39958a7f36bf6 100644 --- a/models/issues/stopwatch_test.go +++ b/models/issues/stopwatch_test.go @@ -26,20 +26,20 @@ func TestCancelStopwatch(t *testing.T) { issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) assert.NoError(t, err) - err = issues_model.CancelStopwatch(user1, issue1) + err = issues_model.CancelStopwatch(db.DefaultContext, user1, issue1) assert.NoError(t, err) unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: user1.ID, IssueID: issue1.ID}) _ = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeCancelTracking, PosterID: user1.ID, IssueID: issue1.ID}) - assert.Nil(t, issues_model.CancelStopwatch(user1, issue2)) + assert.Nil(t, issues_model.CancelStopwatch(db.DefaultContext, user1, issue2)) } func TestStopwatchExists(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.True(t, issues_model.StopwatchExists(1, 1)) - assert.False(t, issues_model.StopwatchExists(1, 2)) + assert.True(t, issues_model.StopwatchExists(db.DefaultContext, 1, 1)) + assert.False(t, issues_model.StopwatchExists(db.DefaultContext, 1, 2)) } func TestHasUserStopwatch(t *testing.T) { @@ -68,11 +68,11 @@ func TestCreateOrStopIssueStopwatch(t *testing.T) { issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) assert.NoError(t, err) - assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(org3, issue1)) + assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(db.DefaultContext, org3, issue1)) sw := unittest.AssertExistsAndLoadBean(t, &issues_model.Stopwatch{UserID: 3, IssueID: 1}) assert.LessOrEqual(t, sw.CreatedUnix, timeutil.TimeStampNow()) - assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(user2, issue2)) + assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(db.DefaultContext, user2, issue2)) unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: 2, IssueID: 2}) unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{UserID: 2, IssueID: 2}) } diff --git a/models/organization/mini_org.go b/models/organization/mini_org.go index b1627b5e6c645..b1b24624c5a21 100644 --- a/models/organization/mini_org.go +++ b/models/organization/mini_org.go @@ -4,6 +4,7 @@ package organization import ( + "context" "fmt" "strings" @@ -19,7 +20,7 @@ import ( type MinimalOrg = Organization // GetUserOrgsList returns all organizations the given user has access to -func GetUserOrgsList(user *user_model.User) ([]*MinimalOrg, error) { +func GetUserOrgsList(ctx context.Context, user *user_model.User) ([]*MinimalOrg, error) { schema, err := db.TableInfo(new(user_model.User)) if err != nil { return nil, err @@ -42,7 +43,7 @@ func GetUserOrgsList(user *user_model.User) ([]*MinimalOrg, error) { groupByStr := groupByCols.String() groupByStr = groupByStr[0 : len(groupByStr)-1] - sess := db.GetEngine(db.DefaultContext) + sess := db.GetEngine(ctx) sess = sess.Select(groupByStr+", count(distinct repo_id) as org_count"). Table("user"). Join("INNER", "team", "`team`.org_id = `user`.id"). diff --git a/models/repo/archiver.go b/models/repo/archiver.go index 70f53cfe158d0..6d0ed42877f53 100644 --- a/models/repo/archiver.go +++ b/models/repo/archiver.go @@ -72,7 +72,7 @@ var delRepoArchiver = new(RepoArchiver) // DeleteRepoArchiver delete archiver func DeleteRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { - _, err := db.GetEngine(db.DefaultContext).ID(archiver.ID).Delete(delRepoArchiver) + _, err := db.GetEngine(ctx).ID(archiver.ID).Delete(delRepoArchiver) return err } @@ -113,8 +113,8 @@ func UpdateRepoArchiverStatus(ctx context.Context, archiver *RepoArchiver) error } // DeleteAllRepoArchives deletes all repo archives records -func DeleteAllRepoArchives() error { - _, err := db.GetEngine(db.DefaultContext).Where("1=1").Delete(new(RepoArchiver)) +func DeleteAllRepoArchives(ctx context.Context) error { + _, err := db.GetEngine(ctx).Where("1=1").Delete(new(RepoArchiver)) return err } @@ -133,10 +133,10 @@ func (opts FindRepoArchiversOption) toConds() builder.Cond { } // FindRepoArchives find repo archivers -func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) { +func FindRepoArchives(ctx context.Context, opts FindRepoArchiversOption) ([]*RepoArchiver, error) { archivers := make([]*RepoArchiver, 0, opts.PageSize) start, limit := opts.GetSkipTake() - err := db.GetEngine(db.DefaultContext).Where(opts.toConds()). + err := db.GetEngine(ctx).Where(opts.toConds()). Asc("created_unix"). Limit(limit, start). Find(&archivers) @@ -144,7 +144,7 @@ func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) { } // SetArchiveRepoState sets if a repo is archived -func SetArchiveRepoState(repo *Repository, isArchived bool) (err error) { +func SetArchiveRepoState(ctx context.Context, repo *Repository, isArchived bool) (err error) { repo.IsArchived = isArchived if isArchived { @@ -153,6 +153,6 @@ func SetArchiveRepoState(repo *Repository, isArchived bool) (err error) { repo.ArchivedUnix = timeutil.TimeStamp(0) } - _, err = db.GetEngine(db.DefaultContext).ID(repo.ID).Cols("is_archived", "archived_unix").NoAutoTime().Update(repo) + _, err = db.GetEngine(ctx).ID(repo.ID).Cols("is_archived", "archived_unix").NoAutoTime().Update(repo) return err } diff --git a/models/repo/topic.go b/models/repo/topic.go index 71302388b940a..ca533fc1e0919 100644 --- a/models/repo/topic.go +++ b/models/repo/topic.go @@ -92,9 +92,9 @@ func SanitizeAndValidateTopics(topics []string) (validTopics, invalidTopics []st } // GetTopicByName retrieves topic by name -func GetTopicByName(name string) (*Topic, error) { +func GetTopicByName(ctx context.Context, name string) (*Topic, error) { var topic Topic - if has, err := db.GetEngine(db.DefaultContext).Where("name = ?", name).Get(&topic); err != nil { + if has, err := db.GetEngine(ctx).Where("name = ?", name).Get(&topic); err != nil { return nil, err } else if !has { return nil, ErrTopicNotExist{name} @@ -192,8 +192,8 @@ func (opts *FindTopicOptions) toConds() builder.Cond { } // FindTopics retrieves the topics via FindTopicOptions -func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) { - sess := db.GetEngine(db.DefaultContext).Select("topic.*").Where(opts.toConds()) +func FindTopics(ctx context.Context, opts *FindTopicOptions) ([]*Topic, int64, error) { + sess := db.GetEngine(ctx).Select("topic.*").Where(opts.toConds()) orderBy := "topic.repo_count DESC" if opts.RepoID > 0 { sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") @@ -208,8 +208,8 @@ func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) { } // CountTopics counts the number of topics matching the FindTopicOptions -func CountTopics(opts *FindTopicOptions) (int64, error) { - sess := db.GetEngine(db.DefaultContext).Where(opts.toConds()) +func CountTopics(ctx context.Context, opts *FindTopicOptions) (int64, error) { + sess := db.GetEngine(ctx).Where(opts.toConds()) if opts.RepoID > 0 { sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") } @@ -231,8 +231,8 @@ func GetRepoTopicByName(ctx context.Context, repoID int64, topicName string) (*T } // AddTopic adds a topic name to a repository (if it does not already have it) -func AddTopic(repoID int64, topicName string) (*Topic, error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func AddTopic(ctx context.Context, repoID int64, topicName string) (*Topic, error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -261,8 +261,8 @@ func AddTopic(repoID int64, topicName string) (*Topic, error) { } // DeleteTopic removes a topic name from a repository (if it has it) -func DeleteTopic(repoID int64, topicName string) (*Topic, error) { - topic, err := GetRepoTopicByName(db.DefaultContext, repoID, topicName) +func DeleteTopic(ctx context.Context, repoID int64, topicName string) (*Topic, error) { + topic, err := GetRepoTopicByName(ctx, repoID, topicName) if err != nil { return nil, err } @@ -271,26 +271,26 @@ func DeleteTopic(repoID int64, topicName string) (*Topic, error) { return nil, nil } - err = removeTopicFromRepo(db.DefaultContext, repoID, topic) + err = removeTopicFromRepo(ctx, repoID, topic) if err != nil { return nil, err } - err = syncTopicsInRepository(db.GetEngine(db.DefaultContext), repoID) + err = syncTopicsInRepository(db.GetEngine(ctx), repoID) return topic, err } // SaveTopics save topics to a repository -func SaveTopics(repoID int64, topicNames ...string) error { - topics, _, err := FindTopics(&FindTopicOptions{ +func SaveTopics(ctx context.Context, repoID int64, topicNames ...string) error { + topics, _, err := FindTopics(ctx, &FindTopicOptions{ RepoID: repoID, }) if err != nil { return err } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/repo/topic_test.go b/models/repo/topic_test.go index aaed91bdd3aec..2b609e6d6676e 100644 --- a/models/repo/topic_test.go +++ b/models/repo/topic_test.go @@ -19,47 +19,47 @@ func TestAddTopic(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - topics, _, err := repo_model.FindTopics(&repo_model.FindTopicOptions{}) + topics, _, err := repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) assert.NoError(t, err) assert.Len(t, topics, totalNrOfTopics) - topics, total, err := repo_model.FindTopics(&repo_model.FindTopicOptions{ + topics, total, err := repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ ListOptions: db.ListOptions{Page: 1, PageSize: 2}, }) assert.NoError(t, err) assert.Len(t, topics, 2) assert.EqualValues(t, 6, total) - topics, _, err = repo_model.FindTopics(&repo_model.FindTopicOptions{ + topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ RepoID: 1, }) assert.NoError(t, err) assert.Len(t, topics, repo1NrOfTopics) - assert.NoError(t, repo_model.SaveTopics(2, "golang")) + assert.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang")) repo2NrOfTopics := 1 - topics, _, err = repo_model.FindTopics(&repo_model.FindTopicOptions{}) + topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) assert.NoError(t, err) assert.Len(t, topics, totalNrOfTopics) - topics, _, err = repo_model.FindTopics(&repo_model.FindTopicOptions{ + topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ RepoID: 2, }) assert.NoError(t, err) assert.Len(t, topics, repo2NrOfTopics) - assert.NoError(t, repo_model.SaveTopics(2, "golang", "gitea")) + assert.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea")) repo2NrOfTopics = 2 totalNrOfTopics++ - topic, err := repo_model.GetTopicByName("gitea") + topic, err := repo_model.GetTopicByName(db.DefaultContext, "gitea") assert.NoError(t, err) assert.EqualValues(t, 1, topic.RepoCount) - topics, _, err = repo_model.FindTopics(&repo_model.FindTopicOptions{}) + topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) assert.NoError(t, err) assert.Len(t, topics, totalNrOfTopics) - topics, _, err = repo_model.FindTopics(&repo_model.FindTopicOptions{ + topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ RepoID: 2, }) assert.NoError(t, err) diff --git a/models/repo/update.go b/models/repo/update.go index c4fba32ad205c..6ddf1a8905eb8 100644 --- a/models/repo/update.go +++ b/models/repo/update.go @@ -16,11 +16,11 @@ import ( ) // UpdateRepositoryOwnerNames updates repository owner_names (this should only be used when the ownerName has changed case) -func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { +func UpdateRepositoryOwnerNames(ctx context.Context, ownerID int64, ownerName string) error { if ownerID == 0 { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -36,8 +36,8 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { } // UpdateRepositoryUpdatedTime updates a repository's updated time -func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error { - _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) +func UpdateRepositoryUpdatedTime(ctx context.Context, repoID int64, updateTime time.Time) error { + _, err := db.GetEngine(ctx).Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) return err } @@ -107,7 +107,7 @@ func (err ErrRepoFilesAlreadyExist) Unwrap() error { } // CheckCreateRepository check if could created a repository -func CheckCreateRepository(doer, u *user_model.User, name string, overwriteOrAdopt bool) error { +func CheckCreateRepository(ctx context.Context, doer, u *user_model.User, name string, overwriteOrAdopt bool) error { if !doer.CanCreateRepo() { return ErrReachLimitOfRepo{u.MaxRepoCreation} } @@ -116,7 +116,7 @@ func CheckCreateRepository(doer, u *user_model.User, name string, overwriteOrAdo return err } - has, err := IsRepositoryModelOrDirExist(db.DefaultContext, u, name) + has, err := IsRepositoryModelOrDirExist(ctx, u, name) if err != nil { return fmt.Errorf("IsRepositoryExist: %w", err) } else if has { @@ -136,18 +136,18 @@ func CheckCreateRepository(doer, u *user_model.User, name string, overwriteOrAdo } // ChangeRepositoryName changes all corresponding setting from old repository name to new one. -func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName string) (err error) { +func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *Repository, newRepoName string) (err error) { oldRepoName := repo.Name newRepoName = strings.ToLower(newRepoName) if err = IsUsableRepoName(newRepoName); err != nil { return err } - if err := repo.LoadOwner(db.DefaultContext); err != nil { + if err := repo.LoadOwner(ctx); err != nil { return err } - has, err := IsRepositoryModelOrDirExist(db.DefaultContext, repo.Owner, newRepoName) + has, err := IsRepositoryModelOrDirExist(ctx, repo.Owner, newRepoName) if err != nil { return fmt.Errorf("IsRepositoryExist: %w", err) } else if has { @@ -171,7 +171,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName s } } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/repo_transfer.go b/models/repo_transfer.go index 1c873cec57624..630c243c8e958 100644 --- a/models/repo_transfer.go +++ b/models/repo_transfer.go @@ -79,8 +79,8 @@ func (r *RepoTransfer) LoadAttributes(ctx context.Context) error { // CanUserAcceptTransfer checks if the user has the rights to accept/decline a repo transfer. // For user, it checks if it's himself // For organizations, it checks if the user is able to create repos -func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool { - if err := r.LoadAttributes(db.DefaultContext); err != nil { +func (r *RepoTransfer) CanUserAcceptTransfer(ctx context.Context, u *user_model.User) bool { + if err := r.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return false } @@ -89,7 +89,7 @@ func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool { return r.RecipientID == u.ID } - allowed, err := organization.CanCreateOrgRepo(db.DefaultContext, r.RecipientID, u.ID) + allowed, err := organization.CanCreateOrgRepo(ctx, r.RecipientID, u.ID) if err != nil { log.Error("CanCreateOrgRepo: %v", err) return false @@ -122,8 +122,8 @@ func deleteRepositoryTransfer(ctx context.Context, repoID int64) error { // CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry, // thus cancel the transfer process. -func CancelRepositoryTransfer(repo *repo_model.Repository) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func CancelRepositoryTransfer(ctx context.Context, repo *repo_model.Repository) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -199,7 +199,7 @@ func CreatePendingRepositoryTransfer(ctx context.Context, doer, newOwner *user_m } // TransferOwnership transfers all corresponding repository items from old user to new one. -func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_model.Repository) (err error) { +func TransferOwnership(ctx context.Context, doer *user_model.User, newOwnerName string, repo *repo_model.Repository) (err error) { repoRenamed := false wikiRenamed := false oldOwnerName := doer.Name @@ -234,7 +234,7 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_mo } }() - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 7364d4d02cd47..b55cef9473860 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -25,7 +25,7 @@ func TestRepositoryTransfer(t *testing.T) { assert.NotNil(t, transfer) // Cancel transfer - assert.NoError(t, CancelRepositoryTransfer(repo)) + assert.NoError(t, CancelRepositoryTransfer(db.DefaultContext, repo)) transfer, err = GetPendingRepositoryTransfer(db.DefaultContext, repo) assert.Error(t, err) @@ -53,5 +53,5 @@ func TestRepositoryTransfer(t *testing.T) { assert.Error(t, err) // Cancel transfer - assert.NoError(t, CancelRepositoryTransfer(repo)) + assert.NoError(t, CancelRepositoryTransfer(db.DefaultContext, repo)) } diff --git a/models/user/follow.go b/models/user/follow.go index 7efecc26a781b..f4dd2891ff402 100644 --- a/models/user/follow.go +++ b/models/user/follow.go @@ -4,6 +4,8 @@ package user import ( + "context" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/timeutil" ) @@ -21,18 +23,18 @@ func init() { } // IsFollowing returns true if user is following followID. -func IsFollowing(userID, followID int64) bool { - has, _ := db.GetEngine(db.DefaultContext).Get(&Follow{UserID: userID, FollowID: followID}) +func IsFollowing(ctx context.Context, userID, followID int64) bool { + has, _ := db.GetEngine(ctx).Get(&Follow{UserID: userID, FollowID: followID}) return has } // FollowUser marks someone be another's follower. -func FollowUser(userID, followID int64) (err error) { - if userID == followID || IsFollowing(userID, followID) { +func FollowUser(ctx context.Context, userID, followID int64) (err error) { + if userID == followID || IsFollowing(ctx, userID, followID) { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -53,12 +55,12 @@ func FollowUser(userID, followID int64) (err error) { } // UnfollowUser unmarks someone as another's follower. -func UnfollowUser(userID, followID int64) (err error) { - if userID == followID || !IsFollowing(userID, followID) { +func UnfollowUser(ctx context.Context, userID, followID int64) (err error) { + if userID == followID || !IsFollowing(ctx, userID, followID) { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/models/user/follow_test.go b/models/user/follow_test.go index fc408d5257c16..c327d935aee0a 100644 --- a/models/user/follow_test.go +++ b/models/user/follow_test.go @@ -6,6 +6,7 @@ package user_test import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -14,9 +15,9 @@ import ( func TestIsFollowing(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.True(t, user_model.IsFollowing(4, 2)) - assert.False(t, user_model.IsFollowing(2, 4)) - assert.False(t, user_model.IsFollowing(5, unittest.NonexistentID)) - assert.False(t, user_model.IsFollowing(unittest.NonexistentID, 5)) - assert.False(t, user_model.IsFollowing(unittest.NonexistentID, unittest.NonexistentID)) + assert.True(t, user_model.IsFollowing(db.DefaultContext, 4, 2)) + assert.False(t, user_model.IsFollowing(db.DefaultContext, 2, 4)) + assert.False(t, user_model.IsFollowing(db.DefaultContext, 5, unittest.NonexistentID)) + assert.False(t, user_model.IsFollowing(db.DefaultContext, unittest.NonexistentID, 5)) + assert.False(t, user_model.IsFollowing(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } diff --git a/models/user/user.go b/models/user/user.go index b3956da1cb865..63b95816cefce 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -1246,7 +1246,7 @@ func IsUserVisibleToViewer(ctx context.Context, u, viewer *User) bool { } // If they follow - they see each over - follower := IsFollowing(u.ID, viewer.ID) + follower := IsFollowing(ctx, u.ID, viewer.ID) if follower { return true } diff --git a/models/user/user_test.go b/models/user/user_test.go index b15f0cbc59bdc..971117482c2d4 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -449,13 +449,13 @@ func TestFollowUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { - assert.NoError(t, user_model.FollowUser(followerID, followedID)) + assert.NoError(t, user_model.FollowUser(db.DefaultContext, followerID, followedID)) unittest.AssertExistsAndLoadBean(t, &user_model.Follow{UserID: followerID, FollowID: followedID}) } testSuccess(4, 2) testSuccess(5, 2) - assert.NoError(t, user_model.FollowUser(2, 2)) + assert.NoError(t, user_model.FollowUser(db.DefaultContext, 2, 2)) unittest.CheckConsistencyFor(t, &user_model.User{}) } @@ -464,7 +464,7 @@ func TestUnfollowUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { - assert.NoError(t, user_model.UnfollowUser(followerID, followedID)) + assert.NoError(t, user_model.UnfollowUser(db.DefaultContext, followerID, followedID)) unittest.AssertNotExistsBean(t, &user_model.Follow{UserID: followerID, FollowID: followedID}) } testSuccess(4, 2) diff --git a/modules/auth/webauthn/webauthn.go b/modules/auth/webauthn/webauthn.go index e732878f8590f..189d197333e00 100644 --- a/modules/auth/webauthn/webauthn.go +++ b/modules/auth/webauthn/webauthn.go @@ -68,7 +68,7 @@ func (u *User) WebAuthnIcon() string { // WebAuthnCredentials implementns the webauthn.User interface func (u *User) WebAuthnCredentials() []webauthn.Credential { - dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ID) + dbCreds, err := auth.GetWebAuthnCredentialsByUID(db.DefaultContext, u.ID) if err != nil { return nil } diff --git a/modules/context/repo.go b/modules/context/repo.go index f9c966d5be9c1..7355dc9af28d0 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -740,7 +740,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { ctx.Data["RepoTransfer"] = repoTransfer if ctx.Doer != nil { - ctx.Data["CanUserAcceptTransfer"] = repoTransfer.CanUserAcceptTransfer(ctx.Doer) + ctx.Data["CanUserAcceptTransfer"] = repoTransfer.CanUserAcceptTransfer(ctx, ctx.Doer) } } diff --git a/modules/eventsource/manager_run.go b/modules/eventsource/manager_run.go index 35dfc62f1ed97..2785836b89c47 100644 --- a/modules/eventsource/manager_run.go +++ b/modules/eventsource/manager_run.go @@ -84,7 +84,7 @@ loop: then = now if setting.Service.EnableTimetracking { - usersStopwatches, err := issues_model.GetUIDsAndStopwatch() + usersStopwatches, err := issues_model.GetUIDsAndStopwatch(ctx) if err != nil { log.Error("Unable to get GetUIDsAndStopwatch: %v", err) return diff --git a/modules/indexer/issues/db/options.go b/modules/indexer/issues/db/options.go index 0d6a8406d3b2f..4d3fa44ca6cf7 100644 --- a/modules/indexer/issues/db/options.go +++ b/modules/indexer/issues/db/options.go @@ -97,7 +97,7 @@ func ToDBOptions(ctx context.Context, options *internal.SearchOptions) (*issue_m if len(options.IncludedLabelIDs) == 0 && len(options.IncludedAnyLabelIDs) > 0 { _ = ctx // issue_model.GetLabelsByIDs should be called with ctx, this line can be removed when it's done. - labels, err := issue_model.GetLabelsByIDs(options.IncludedAnyLabelIDs, "name") + labels, err := issue_model.GetLabelsByIDs(ctx, options.IncludedAnyLabelIDs, "name") if err != nil { return nil, fmt.Errorf("GetLabelsByIDs: %v", err) } diff --git a/modules/session/db.go b/modules/session/db.go index f86f7d1e9cf9e..9909f2dc1e986 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -8,6 +8,7 @@ import ( "sync" "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/timeutil" "gitea.com/go-chi/session" @@ -71,7 +72,7 @@ func (s *DBStore) Release() error { return err } - return auth.UpdateSession(s.sid, data) + return auth.UpdateSession(db.DefaultContext, s.sid, data) } // Flush deletes all session data. @@ -97,7 +98,7 @@ func (p *DBProvider) Init(maxLifetime int64, connStr string) error { // Read returns raw session store by session ID. func (p *DBProvider) Read(sid string) (session.RawStore, error) { - s, err := auth.ReadSession(sid) + s, err := auth.ReadSession(db.DefaultContext, sid) if err != nil { return nil, err } @@ -117,7 +118,7 @@ func (p *DBProvider) Read(sid string) (session.RawStore, error) { // Exist returns true if session with given ID exists. func (p *DBProvider) Exist(sid string) bool { - has, err := auth.ExistSession(sid) + has, err := auth.ExistSession(db.DefaultContext, sid) if err != nil { panic("session/DB: error checking existence: " + err.Error()) } @@ -126,12 +127,12 @@ func (p *DBProvider) Exist(sid string) bool { // Destroy deletes a session by session ID. func (p *DBProvider) Destroy(sid string) error { - return auth.DestroySession(sid) + return auth.DestroySession(db.DefaultContext, sid) } // Regenerate regenerates a session store from old session ID to new one. func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) { - s, err := auth.RegenerateSession(oldsid, sid) + s, err := auth.RegenerateSession(db.DefaultContext, oldsid, sid) if err != nil { return nil, err } @@ -151,7 +152,7 @@ func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err err // Count counts and returns number of sessions. func (p *DBProvider) Count() int { - total, err := auth.CountSessions() + total, err := auth.CountSessions(db.DefaultContext) if err != nil { panic("session/DB: error counting records: " + err.Error()) } @@ -160,7 +161,7 @@ func (p *DBProvider) Count() int { // GC calls GC to clean expired sessions. func (p *DBProvider) GC() { - if err := auth.CleanupSessions(p.maxLifetime); err != nil { + if err := auth.CleanupSessions(db.DefaultContext, p.maxLifetime); err != nil { log.Printf("session/DB: error garbage collecting: %v", err) } } diff --git a/routers/api/v1/org/label.go b/routers/api/v1/org/label.go index 2dd4505a91d71..5a03059deda26 100644 --- a/routers/api/v1/org/label.go +++ b/routers/api/v1/org/label.go @@ -50,7 +50,7 @@ func ListLabels(ctx *context.APIContext) { return } - count, err := issues_model.CountLabelsByOrgID(ctx.Org.Organization.ID) + count, err := issues_model.CountLabelsByOrgID(ctx, ctx.Org.Organization.ID) if err != nil { ctx.InternalServerError(err) return @@ -218,7 +218,7 @@ func EditLabel(ctx *context.APIContext) { l.Description = *form.Description } l.SetArchived(form.IsArchived != nil && *form.IsArchived) - if err := issues_model.UpdateLabel(l); err != nil { + if err := issues_model.UpdateLabel(ctx, l); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateLabel", err) return } @@ -249,7 +249,7 @@ func DeleteLabel(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - if err := issues_model.DeleteLabel(ctx.Org.Organization.ID, ctx.ParamsInt64(":id")); err != nil { + if err := issues_model.DeleteLabel(ctx, ctx.Org.Organization.ID, ctx.ParamsInt64(":id")); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteLabel", err) return } diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 4be43d46adf55..206e3fb29bc9b 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -234,7 +234,7 @@ func DeleteCollaborator(ctx *context.APIContext) { return } - if err := repo_service.DeleteCollaboration(ctx.Repo.Repository, collaborator.ID); err != nil { + if err := repo_service.DeleteCollaboration(ctx, ctx.Repo.Repository, collaborator.ID); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteCollaboration", err) return } diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index c6248bacecd2c..05dfa45e3d94c 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -413,7 +413,7 @@ func ListIssues(ctx *context.APIContext) { var labelIDs []int64 if splitted := strings.Split(ctx.FormString("labels"), ","); len(splitted) > 0 { - labelIDs, err = issues_model.GetLabelIDsInRepoByNames(ctx.Repo.Repository.ID, splitted) + labelIDs, err = issues_model.GetLabelIDsInRepoByNames(ctx, ctx.Repo.Repository.ID, splitted) if err != nil { ctx.Error(http.StatusInternalServerError, "GetLabelIDsInRepoByNames", err) return @@ -425,7 +425,7 @@ func ListIssues(ctx *context.APIContext) { for i := range part { // uses names and fall back to ids // non existent milestones are discarded - mile, err := issues_model.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, part[i]) + mile, err := issues_model.GetMilestoneByRepoIDANDName(ctx, ctx.Repo.Repository.ID, part[i]) if err == nil { mileIDs = append(mileIDs, mile.ID) continue diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index b050a397f2b88..2f9ad7060ce7b 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -107,7 +107,7 @@ func AddIssueLabels(ctx *context.APIContext) { return } - if err = issue_service.AddLabels(issue, ctx.Doer, labels); err != nil { + if err = issue_service.AddLabels(ctx, issue, ctx.Doer, labels); err != nil { ctx.Error(http.StatusInternalServerError, "AddLabels", err) return } @@ -186,7 +186,7 @@ func DeleteIssueLabel(ctx *context.APIContext) { return } - if err := issue_service.RemoveLabel(issue, ctx.Doer, label); err != nil { + if err := issue_service.RemoveLabel(ctx, issue, ctx.Doer, label); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteIssueLabel", err) return } @@ -237,7 +237,7 @@ func ReplaceIssueLabels(ctx *context.APIContext) { return } - if err := issue_service.ReplaceLabels(issue, ctx.Doer, labels); err != nil { + if err := issue_service.ReplaceLabels(ctx, issue, ctx.Doer, labels); err != nil { ctx.Error(http.StatusInternalServerError, "ReplaceLabels", err) return } @@ -298,7 +298,7 @@ func ClearIssueLabels(ctx *context.APIContext) { return } - if err := issue_service.ClearLabels(issue, ctx.Doer); err != nil { + if err := issue_service.ClearLabels(ctx, issue, ctx.Doer); err != nil { ctx.Error(http.StatusInternalServerError, "ClearLabels", err) return } @@ -317,7 +317,7 @@ func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption) return nil, nil, err } - labels, err := issues_model.GetLabelsByIDs(form.Labels, "id", "repo_id", "org_id") + labels, err := issues_model.GetLabelsByIDs(ctx, form.Labels, "id", "repo_id", "org_id") if err != nil { ctx.Error(http.StatusInternalServerError, "GetLabelsByIDs", err) return nil, nil, err diff --git a/routers/api/v1/repo/issue_stopwatch.go b/routers/api/v1/repo/issue_stopwatch.go index 75fa86313857a..384532ab879c7 100644 --- a/routers/api/v1/repo/issue_stopwatch.go +++ b/routers/api/v1/repo/issue_stopwatch.go @@ -152,7 +152,7 @@ func DeleteIssueStopwatch(ctx *context.APIContext) { return } - if err := issues_model.CancelStopwatch(ctx.Doer, issue); err != nil { + if err := issues_model.CancelStopwatch(ctx, ctx.Doer, issue); err != nil { ctx.Error(http.StatusInternalServerError, "CancelStopwatch", err) return } @@ -182,7 +182,7 @@ func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*issues_m return nil, errors.New("Cannot use time tracker") } - if issues_model.StopwatchExists(ctx.Doer.ID, issue.ID) != shouldExist { + if issues_model.StopwatchExists(ctx, ctx.Doer.ID, issue.ID) != shouldExist { if shouldExist { ctx.Error(http.StatusConflict, "StopwatchExists", "cannot stop/cancel a non existent stopwatch") err = errors.New("cannot stop/cancel a non existent stopwatch") @@ -218,13 +218,13 @@ func GetStopwatches(ctx *context.APIContext) { // "200": // "$ref": "#/responses/StopWatchList" - sws, err := issues_model.GetUserStopwatches(ctx.Doer.ID, utils.GetListOptions(ctx)) + sws, err := issues_model.GetUserStopwatches(ctx, ctx.Doer.ID, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserStopwatches", err) return } - count, err := issues_model.CountUserStopwatches(ctx.Doer.ID) + count, err := issues_model.CountUserStopwatches(ctx, ctx.Doer.ID) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 1fec0294658d9..ab9a037040377 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -132,7 +132,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) { return } - current, err := issues_model.CheckIssueWatch(user, issue) + current, err := issues_model.CheckIssueWatch(ctx, user, issue) if err != nil { ctx.Error(http.StatusInternalServerError, "CheckIssueWatch", err) return @@ -145,7 +145,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) { } // Update watch state - if err := issues_model.CreateOrUpdateIssueWatch(user.ID, issue.ID, watch); err != nil { + if err := issues_model.CreateOrUpdateIssueWatch(ctx, user.ID, issue.ID, watch); err != nil { ctx.Error(http.StatusInternalServerError, "CreateOrUpdateIssueWatch", err) return } @@ -196,7 +196,7 @@ func CheckIssueSubscription(ctx *context.APIContext) { return } - watching, err := issues_model.CheckIssueWatch(ctx.Doer, issue) + watching, err := issues_model.CheckIssueWatch(ctx, ctx.Doer, issue) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/repo/label.go b/routers/api/v1/repo/label.go index e93c72a9f5f39..420d3ab5b49bc 100644 --- a/routers/api/v1/repo/label.go +++ b/routers/api/v1/repo/label.go @@ -55,7 +55,7 @@ func ListLabels(ctx *context.APIContext) { return } - count, err := issues_model.CountLabelsByRepoID(ctx.Repo.Repository.ID) + count, err := issues_model.CountLabelsByRepoID(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.InternalServerError(err) return @@ -240,7 +240,7 @@ func EditLabel(ctx *context.APIContext) { l.Description = *form.Description } l.SetArchived(form.IsArchived != nil && *form.IsArchived) - if err := issues_model.UpdateLabel(l); err != nil { + if err := issues_model.UpdateLabel(ctx, l); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateLabel", err) return } @@ -276,7 +276,7 @@ func DeleteLabel(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - if err := issues_model.DeleteLabel(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { + if err := issues_model.DeleteLabel(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteLabel", err) return } diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index fff9493a23756..1a86444660a81 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -163,7 +163,7 @@ func CreateMilestone(ctx *context.APIContext) { milestone.ClosedDateUnix = timeutil.TimeStampNow() } - if err := issues_model.NewMilestone(milestone); err != nil { + if err := issues_model.NewMilestone(ctx, milestone); err != nil { ctx.Error(http.StatusInternalServerError, "NewMilestone", err) return } @@ -225,7 +225,7 @@ func EditMilestone(ctx *context.APIContext) { milestone.IsClosed = *form.State == string(api.StateClosed) } - if err := issues_model.UpdateMilestone(milestone, oldIsClosed); err != nil { + if err := issues_model.UpdateMilestone(ctx, milestone, oldIsClosed); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateMilestone", err) return } @@ -264,7 +264,7 @@ func DeleteMilestone(ctx *context.APIContext) { return } - if err := issues_model.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, m.ID); err != nil { + if err := issues_model.DeleteMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, m.ID); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteMilestoneByRepoID", err) return } @@ -286,7 +286,7 @@ func getMilestoneByIDOrName(ctx *context.APIContext) *issues_model.Milestone { } } - milestone, err := issues_model.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, mile) + milestone, err := issues_model.GetMilestoneByRepoIDANDName(ctx, ctx.Repo.Repository.ID, mile) if err != nil { if issues_model.IsErrMilestoneNotExist(err) { ctx.NotFound() diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index e06fc2df6641f..5f25fdce14ea9 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -1003,14 +1003,14 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e return err } if *opts.Archived { - if err := repo_model.SetArchiveRepoState(repo, *opts.Archived); err != nil { + if err := repo_model.SetArchiveRepoState(ctx, repo, *opts.Archived); err != nil { log.Error("Tried to archive a repo: %s", err) ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) return err } log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name) } else { - if err := repo_model.SetArchiveRepoState(repo, *opts.Archived); err != nil { + if err := repo_model.SetArchiveRepoState(ctx, repo, *opts.Archived); err != nil { log.Error("Tried to un-archive a repo: %s", err) ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) return err diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index c0c05154c47e8..d662b9b5832b5 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -53,7 +53,7 @@ func ListTopics(ctx *context.APIContext) { RepoID: ctx.Repo.Repository.ID, } - topics, total, err := repo_model.FindTopics(opts) + topics, total, err := repo_model.FindTopics(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -120,7 +120,7 @@ func UpdateTopics(ctx *context.APIContext) { return } - err := repo_model.SaveTopics(ctx.Repo.Repository.ID, validTopics...) + err := repo_model.SaveTopics(ctx, ctx.Repo.Repository.ID, validTopics...) if err != nil { log.Error("SaveTopics failed: %v", err) ctx.InternalServerError(err) @@ -172,7 +172,7 @@ func AddTopic(ctx *context.APIContext) { } // Prevent adding more topics than allowed to repo - count, err := repo_model.CountTopics(&repo_model.FindTopicOptions{ + count, err := repo_model.CountTopics(ctx, &repo_model.FindTopicOptions{ RepoID: ctx.Repo.Repository.ID, }) if err != nil { @@ -187,7 +187,7 @@ func AddTopic(ctx *context.APIContext) { return } - _, err = repo_model.AddTopic(ctx.Repo.Repository.ID, topicName) + _, err = repo_model.AddTopic(ctx, ctx.Repo.Repository.ID, topicName) if err != nil { log.Error("AddTopic failed: %v", err) ctx.InternalServerError(err) @@ -238,7 +238,7 @@ func DeleteTopic(ctx *context.APIContext) { return } - topic, err := repo_model.DeleteTopic(ctx.Repo.Repository.ID, topicName) + topic, err := repo_model.DeleteTopic(ctx, ctx.Repo.Repository.ID, topicName) if err != nil { log.Error("DeleteTopic failed: %v", err) ctx.InternalServerError(err) @@ -287,7 +287,7 @@ func TopicSearch(ctx *context.APIContext) { ListOptions: utils.GetListOptions(ctx), } - topics, total, err := repo_model.FindTopics(opts) + topics, total, err := repo_model.FindTopics(ctx, opts) if err != nil { ctx.InternalServerError(err) return diff --git a/routers/api/v1/repo/transfer.go b/routers/api/v1/repo/transfer.go index 8ff22a1193f16..326895918e3d0 100644 --- a/routers/api/v1/repo/transfer.go +++ b/routers/api/v1/repo/transfer.go @@ -221,7 +221,7 @@ func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { return err } - if !repoTransfer.CanUserAcceptTransfer(ctx.Doer) { + if !repoTransfer.CanUserAcceptTransfer(ctx, ctx.Doer) { ctx.Error(http.StatusForbidden, "CanUserAcceptTransfer", nil) return fmt.Errorf("user does not have permissions to do this") } @@ -230,5 +230,5 @@ func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { return repo_service.TransferOwnership(ctx, repoTransfer.Doer, repoTransfer.Recipient, ctx.Repo.Repository, repoTransfer.Teams) } - return models.CancelRepositoryTransfer(ctx.Repo.Repository) + return models.CancelRepositoryTransfer(ctx, ctx.Repo.Repository) } diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index 1aa906ccb11c9..5815ed4f0b445 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -151,7 +151,7 @@ func ListFollowing(ctx *context.APIContext) { } func checkUserFollowing(ctx *context.APIContext, u *user_model.User, followID int64) { - if user_model.IsFollowing(u.ID, followID) { + if user_model.IsFollowing(ctx, u.ID, followID) { ctx.Status(http.StatusNoContent) } else { ctx.NotFound() @@ -224,7 +224,7 @@ func Follow(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - if err := user_model.FollowUser(ctx.Doer.ID, ctx.ContextUser.ID); err != nil { + if err := user_model.FollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID); err != nil { ctx.Error(http.StatusInternalServerError, "FollowUser", err) return } @@ -248,7 +248,7 @@ func Unfollow(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - if err := user_model.UnfollowUser(ctx.Doer.ID, ctx.ContextUser.ID); err != nil { + if err := user_model.UnfollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID); err != nil { ctx.Error(http.StatusInternalServerError, "UnfollowUser", err) return } diff --git a/routers/init.go b/routers/init.go index 6369a39754b07..150a5c56f2d71 100644 --- a/routers/init.go +++ b/routers/init.go @@ -140,7 +140,7 @@ func InitWebInstalled(ctx context.Context) { mustInitCtx(ctx, models.Init) mustInitCtx(ctx, authmodel.Init) - mustInit(repo_service.Init) + mustInitCtx(ctx, repo_service.Init) // Booting long running goroutines. mustInit(indexer_service.Init) diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 5562cc390c1f5..af49b00ad6280 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -243,7 +243,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User { ctx.ServerError("auth.HasTwoFactorByUID", err) return nil } - hasWebAuthn, err := auth.HasWebAuthnRegistrationsByUID(u.ID) + hasWebAuthn, err := auth.HasWebAuthnRegistrationsByUID(ctx, u.ID) if err != nil { ctx.ServerError("auth.HasWebAuthnRegistrationsByUID", err) return nil @@ -421,13 +421,13 @@ func EditUserPost(ctx *context.Context) { } } - wn, err := auth.GetWebAuthnCredentialsByUID(u.ID) + wn, err := auth.GetWebAuthnCredentialsByUID(ctx, u.ID) if err != nil { ctx.ServerError("auth.GetTwoFactorByUID", err) return } for _, cred := range wn { - if _, err := auth.DeleteCredential(cred.ID, u.ID); err != nil { + if _, err := auth.DeleteCredential(ctx, cred.ID, u.ID); err != nil { ctx.ServerError("auth.DeleteCredential", err) return } diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index b7a73e43796e2..8017602d99026 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -243,7 +243,7 @@ func SignInPost(ctx *context.Context) { } // Check if the user has webauthn registration - hasWebAuthnTwofa, err := auth.HasWebAuthnRegistrationsByUID(u.ID) + hasWebAuthnTwofa, err := auth.HasWebAuthnRegistrationsByUID(ctx, u.ID) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index 745b4e818cb2e..c6e3d1231b4d1 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -185,7 +185,7 @@ func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, r } // If WebAuthn is enrolled -> Redirect to WebAuthn instead - regs, err := auth.GetWebAuthnCredentialsByUID(u.ID) + regs, err := auth.GetWebAuthnCredentialsByUID(ctx, u.ID) if err == nil && len(regs) > 0 { ctx.Redirect(setting.AppSubURL + "/user/webauthn") return diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 640c01e203b49..40c91b3f856a8 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -237,7 +237,7 @@ func newAccessTokenResponse(ctx go_context.Context, grant *auth.OAuth2Grant, ser idToken.EmailVerified = user.IsActive } if grant.ScopeContains("groups") { - groups, err := getOAuthGroupsForUser(user) + groups, err := getOAuthGroupsForUser(ctx, user) if err != nil { log.Error("Error getting groups: %v", err) return nil, &AccessTokenError{ @@ -291,7 +291,7 @@ func InfoOAuth(ctx *context.Context) { Picture: ctx.Doer.AvatarLink(ctx), } - groups, err := getOAuthGroupsForUser(ctx.Doer) + groups, err := getOAuthGroupsForUser(ctx, ctx.Doer) if err != nil { ctx.ServerError("Oauth groups for user", err) return @@ -303,8 +303,8 @@ func InfoOAuth(ctx *context.Context) { // returns a list of "org" and "org:team" strings, // that the given user is a part of. -func getOAuthGroupsForUser(user *user_model.User) ([]string, error) { - orgs, err := org_model.GetUserOrgsList(user) +func getOAuthGroupsForUser(ctx go_context.Context, user *user_model.User) ([]string, error) { + orgs, err := org_model.GetUserOrgsList(ctx, user) if err != nil { return nil, fmt.Errorf("GetUserOrgList: %w", err) } @@ -1197,7 +1197,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model } // If WebAuthn is enrolled -> Redirect to WebAuthn instead - regs, err := auth.GetWebAuthnCredentialsByUID(u.ID) + regs, err := auth.GetWebAuthnCredentialsByUID(ctx, u.ID) if err == nil && len(regs) > 0 { ctx.Redirect(setting.AppSubURL + "/user/webauthn") return diff --git a/routers/web/auth/webauthn.go b/routers/web/auth/webauthn.go index 013e11eacce0a..b19e18aa8e585 100644 --- a/routers/web/auth/webauthn.go +++ b/routers/web/auth/webauthn.go @@ -55,7 +55,7 @@ func WebAuthnLoginAssertion(ctx *context.Context) { return } - exists, err := auth.ExistsWebAuthnCredentialsForUID(user.ID) + exists, err := auth.ExistsWebAuthnCredentialsForUID(ctx, user.ID) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -127,14 +127,14 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) { } // Success! Get the credential and update the sign count with the new value we received. - dbCred, err := auth.GetWebAuthnCredentialByCredID(user.ID, cred.ID) + dbCred, err := auth.GetWebAuthnCredentialByCredID(ctx, user.ID, cred.ID) if err != nil { ctx.ServerError("GetWebAuthnCredentialByCredID", err) return } dbCred.SignCount = cred.Authenticator.SignCount - if err := dbCred.UpdateSignCount(); err != nil { + if err := dbCred.UpdateSignCount(ctx); err != nil { ctx.ServerError("UpdateSignCount", err) return } diff --git a/routers/web/explore/topic.go b/routers/web/explore/topic.go index 132ef23fa757d..bb1be310de777 100644 --- a/routers/web/explore/topic.go +++ b/routers/web/explore/topic.go @@ -23,7 +23,7 @@ func TopicSearch(ctx *context.Context) { }, } - topics, total, err := repo_model.FindTopics(opts) + topics, total, err := repo_model.FindTopics(ctx, opts) if err != nil { ctx.Error(http.StatusInternalServerError) return diff --git a/routers/web/org/home.go b/routers/web/org/home.go index 15386393e9f1e..ec866eb6b3ba1 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -131,7 +131,7 @@ func Home(ctx *context.Context) { var isFollowing bool if ctx.Doer != nil { - isFollowing = user_model.IsFollowing(ctx.Doer.ID, ctx.ContextUser.ID) + isFollowing = user_model.IsFollowing(ctx, ctx.Doer.ID, ctx.ContextUser.ID) } ctx.Data["Repos"] = repos diff --git a/routers/web/org/org_labels.go b/routers/web/org/org_labels.go index 2c7725e38da5c..f78bd00274263 100644 --- a/routers/web/org/org_labels.go +++ b/routers/web/org/org_labels.go @@ -76,7 +76,7 @@ func UpdateLabel(ctx *context.Context) { l.Description = form.Description l.Color = form.Color l.SetArchived(form.IsArchived) - if err := issues_model.UpdateLabel(l); err != nil { + if err := issues_model.UpdateLabel(ctx, l); err != nil { ctx.ServerError("UpdateLabel", err) return } @@ -85,7 +85,7 @@ func UpdateLabel(ctx *context.Context) { // DeleteLabel delete a label func DeleteLabel(ctx *context.Context) { - if err := issues_model.DeleteLabel(ctx.Org.Organization.ID, ctx.FormInt64("id")); err != nil { + if err := issues_model.DeleteLabel(ctx, ctx.Org.Organization.ID, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteLabel: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success")) diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 94c9382f23b38..f4aa357fac77b 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -1412,7 +1412,7 @@ func ViewIssue(ctx *context.Context) { if ctx.Doer != nil { iw.UserID = ctx.Doer.ID iw.IssueID = issue.ID - iw.IsWatching, err = issues_model.CheckIssueWatch(ctx.Doer, issue) + iw.IsWatching, err = issues_model.CheckIssueWatch(ctx, ctx.Doer, issue) if err != nil { ctx.ServerError("CheckIssueWatch", err) return @@ -1530,7 +1530,7 @@ func ViewIssue(ctx *context.Context) { if ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { if ctx.IsSigned { // Deal with the stopwatch - ctx.Data["IsStopwatchRunning"] = issues_model.StopwatchExists(ctx.Doer.ID, issue.ID) + ctx.Data["IsStopwatchRunning"] = issues_model.StopwatchExists(ctx, ctx.Doer.ID, issue.ID) if !ctx.Data["IsStopwatchRunning"].(bool) { var exists bool var swIssue *issues_model.Issue @@ -2708,7 +2708,7 @@ func ListIssues(ctx *context.Context) { var labelIDs []int64 if splitted := strings.Split(ctx.FormString("labels"), ","); len(splitted) > 0 { - labelIDs, err = issues_model.GetLabelIDsInRepoByNames(ctx.Repo.Repository.ID, splitted) + labelIDs, err = issues_model.GetLabelIDsInRepoByNames(ctx, ctx.Repo.Repository.ID, splitted) if err != nil { ctx.Error(http.StatusInternalServerError, err.Error()) return @@ -2720,7 +2720,7 @@ func ListIssues(ctx *context.Context) { for i := range part { // uses names and fall back to ids // non existent milestones are discarded - mile, err := issues_model.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, part[i]) + mile, err := issues_model.GetMilestoneByRepoIDANDName(ctx, ctx.Repo.Repository.ID, part[i]) if err == nil { mileIDs = append(mileIDs, mile.ID) continue @@ -3037,7 +3037,7 @@ func NewComment(ctx *context.Context) { return } } else { - if err := stopTimerIfAvailable(ctx.Doer, issue); err != nil { + if err := stopTimerIfAvailable(ctx, ctx.Doer, issue); err != nil { ctx.ServerError("CreateOrStopIssueStopwatch", err) return } diff --git a/routers/web/repo/issue_label.go b/routers/web/repo/issue_label.go index 257610d3af54b..2d129490f5128 100644 --- a/routers/web/repo/issue_label.go +++ b/routers/web/repo/issue_label.go @@ -145,7 +145,7 @@ func UpdateLabel(ctx *context.Context) { l.Color = form.Color l.SetArchived(form.IsArchived) - if err := issues_model.UpdateLabel(l); err != nil { + if err := issues_model.UpdateLabel(ctx, l); err != nil { ctx.ServerError("UpdateLabel", err) return } @@ -154,7 +154,7 @@ func UpdateLabel(ctx *context.Context) { // DeleteLabel delete a label func DeleteLabel(ctx *context.Context) { - if err := issues_model.DeleteLabel(ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil { + if err := issues_model.DeleteLabel(ctx, ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteLabel: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success")) @@ -173,7 +173,7 @@ func UpdateIssueLabel(ctx *context.Context) { switch action := ctx.FormString("action"); action { case "clear": for _, issue := range issues { - if err := issue_service.ClearLabels(issue, ctx.Doer); err != nil { + if err := issue_service.ClearLabels(ctx, issue, ctx.Doer); err != nil { ctx.ServerError("ClearLabels", err) return } @@ -208,14 +208,14 @@ func UpdateIssueLabel(ctx *context.Context) { if action == "attach" { for _, issue := range issues { - if err = issue_service.AddLabel(issue, ctx.Doer, label); err != nil { + if err = issue_service.AddLabel(ctx, issue, ctx.Doer, label); err != nil { ctx.ServerError("AddLabel", err) return } } } else { for _, issue := range issues { - if err = issue_service.RemoveLabel(issue, ctx.Doer, label); err != nil { + if err = issue_service.RemoveLabel(ctx, issue, ctx.Doer, label); err != nil { ctx.ServerError("RemoveLabel", err) return } diff --git a/routers/web/repo/issue_stopwatch.go b/routers/web/repo/issue_stopwatch.go index 3e715437e6c6c..d42af573297b6 100644 --- a/routers/web/repo/issue_stopwatch.go +++ b/routers/web/repo/issue_stopwatch.go @@ -22,7 +22,7 @@ func IssueStopwatch(c *context.Context) { var showSuccessMessage bool - if !issues_model.StopwatchExists(c.Doer.ID, issue.ID) { + if !issues_model.StopwatchExists(c, c.Doer.ID, issue.ID) { showSuccessMessage = true } @@ -31,7 +31,7 @@ func IssueStopwatch(c *context.Context) { return } - if err := issues_model.CreateOrStopIssueStopwatch(c.Doer, issue); err != nil { + if err := issues_model.CreateOrStopIssueStopwatch(c, c.Doer, issue); err != nil { c.ServerError("CreateOrStopIssueStopwatch", err) return } @@ -55,12 +55,12 @@ func CancelStopwatch(c *context.Context) { return } - if err := issues_model.CancelStopwatch(c.Doer, issue); err != nil { + if err := issues_model.CancelStopwatch(c, c.Doer, issue); err != nil { c.ServerError("CancelStopwatch", err) return } - stopwatches, err := issues_model.GetUserStopwatches(c.Doer.ID, db.ListOptions{}) + stopwatches, err := issues_model.GetUserStopwatches(c, c.Doer.ID, db.ListOptions{}) if err != nil { c.ServerError("GetUserStopwatches", err) return diff --git a/routers/web/repo/issue_watch.go b/routers/web/repo/issue_watch.go index d3d3a2af21e36..1cb5cc7162d89 100644 --- a/routers/web/repo/issue_watch.go +++ b/routers/web/repo/issue_watch.go @@ -47,7 +47,7 @@ func IssueWatch(ctx *context.Context) { return } - if err := issues_model.CreateOrUpdateIssueWatch(ctx.Doer.ID, issue.ID, watch); err != nil { + if err := issues_model.CreateOrUpdateIssueWatch(ctx, ctx.Doer.ID, issue.ID, watch); err != nil { ctx.ServerError("CreateOrUpdateIssueWatch", err) return } diff --git a/routers/web/repo/migrate.go b/routers/web/repo/migrate.go index a6125a1a5811c..b70901d5f28d9 100644 --- a/routers/web/repo/migrate.go +++ b/routers/web/repo/migrate.go @@ -232,13 +232,13 @@ func MigratePost(ctx *context.Context) { opts.Releases = false } - err = repo_model.CheckCreateRepository(ctx.Doer, ctxUser, opts.RepoName, false) + err = repo_model.CheckCreateRepository(ctx, ctx.Doer, ctxUser, opts.RepoName, false) if err != nil { handleMigrateError(ctx, ctxUser, err, "MigratePost", tpl, form) return } - err = task.MigrateRepository(ctx.Doer, ctxUser, opts) + err = task.MigrateRepository(ctx, ctx.Doer, ctxUser, opts) if err == nil { ctx.Redirect(ctxUser.HomeLink() + "/" + url.PathEscape(opts.RepoName)) return @@ -260,7 +260,7 @@ func setMigrationContextData(ctx *context.Context, serviceType structs.GitServic } func MigrateRetryPost(ctx *context.Context) { - if err := task.RetryMigrateTask(ctx.Repo.Repository.ID); err != nil { + if err := task.RetryMigrateTask(ctx, ctx.Repo.Repository.ID); err != nil { log.Error("Retry task failed: %v", err) ctx.ServerError("task.RetryMigrateTask", err) return @@ -269,7 +269,7 @@ func MigrateRetryPost(ctx *context.Context) { } func MigrateCancelPost(ctx *context.Context) { - migratingTask, err := admin_model.GetMigratingTask(ctx.Repo.Repository.ID) + migratingTask, err := admin_model.GetMigratingTask(ctx, ctx.Repo.Repository.ID) if err != nil { log.Error("GetMigratingTask: %v", err) ctx.Redirect(ctx.Repo.Repository.Link()) @@ -277,7 +277,7 @@ func MigrateCancelPost(ctx *context.Context) { } if migratingTask.Status == structs.TaskStatusRunning { taskUpdate := &admin_model.Task{ID: migratingTask.ID, Status: structs.TaskStatusFailed, Message: "canceled"} - if err = taskUpdate.UpdateCols("status", "message"); err != nil { + if err = taskUpdate.UpdateCols(ctx, "status", "message"); err != nil { ctx.ServerError("task.UpdateCols", err) return } diff --git a/routers/web/repo/milestone.go b/routers/web/repo/milestone.go index ad355ce5d7d92..df52ca3528984 100644 --- a/routers/web/repo/milestone.go +++ b/routers/web/repo/milestone.go @@ -65,7 +65,7 @@ func Milestones(ctx *context.Context) { return } - stats, err := issues_model.GetMilestonesStatsByRepoCondAndKw(builder.And(builder.Eq{"id": ctx.Repo.Repository.ID}), keyword) + stats, err := issues_model.GetMilestonesStatsByRepoCondAndKw(ctx, builder.And(builder.Eq{"id": ctx.Repo.Repository.ID}), keyword) if err != nil { ctx.ServerError("GetMilestoneStats", err) return @@ -74,7 +74,7 @@ func Milestones(ctx *context.Context) { ctx.Data["ClosedCount"] = stats.ClosedCount if ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { - if err := miles.LoadTotalTrackedTimes(); err != nil { + if err := miles.LoadTotalTrackedTimes(ctx); err != nil { ctx.ServerError("LoadTotalTrackedTimes", err) return } @@ -142,7 +142,7 @@ func NewMilestonePost(ctx *context.Context) { } deadline = time.Date(deadline.Year(), deadline.Month(), deadline.Day(), 23, 59, 59, 0, deadline.Location()) - if err = issues_model.NewMilestone(&issues_model.Milestone{ + if err = issues_model.NewMilestone(ctx, &issues_model.Milestone{ RepoID: ctx.Repo.Repository.ID, Name: form.Title, Content: form.Content, @@ -214,7 +214,7 @@ func EditMilestonePost(ctx *context.Context) { m.Name = form.Title m.Content = form.Content m.DeadlineUnix = timeutil.TimeStamp(deadline.Unix()) - if err = issues_model.UpdateMilestone(m, m.IsClosed); err != nil { + if err = issues_model.UpdateMilestone(ctx, m, m.IsClosed); err != nil { ctx.ServerError("UpdateMilestone", err) return } @@ -236,7 +236,7 @@ func ChangeMilestoneStatus(ctx *context.Context) { } id := ctx.ParamsInt64(":id") - if err := issues_model.ChangeMilestoneStatusByRepoIDAndID(ctx.Repo.Repository.ID, id, toClose); err != nil { + if err := issues_model.ChangeMilestoneStatusByRepoIDAndID(ctx, ctx.Repo.Repository.ID, id, toClose); err != nil { if issues_model.IsErrMilestoneNotExist(err) { ctx.NotFound("", err) } else { @@ -249,7 +249,7 @@ func ChangeMilestoneStatus(ctx *context.Context) { // DeleteMilestone delete a milestone func DeleteMilestone(ctx *context.Context) { - if err := issues_model.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil { + if err := issues_model.DeleteMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success")) diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 0ef4a29f0c999..63dfd0f7b50be 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -1270,7 +1270,7 @@ func MergePullRequest(ctx *context.Context) { } log.Trace("Pull request merged: %d", pr.ID) - if err := stopTimerIfAvailable(ctx.Doer, issue); err != nil { + if err := stopTimerIfAvailable(ctx, ctx.Doer, issue); err != nil { ctx.ServerError("CreateOrStopIssueStopwatch", err) return } @@ -1326,9 +1326,9 @@ func CancelAutoMergePullRequest(ctx *context.Context) { ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index)) } -func stopTimerIfAvailable(user *user_model.User, issue *issues_model.Issue) error { - if issues_model.StopwatchExists(user.ID, issue.ID) { - if err := issues_model.CreateOrStopIssueStopwatch(user, issue); err != nil { +func stopTimerIfAvailable(ctx *context.Context, user *user_model.User, issue *issues_model.Issue) error { + if issues_model.StopwatchExists(ctx, user.ID, issue.ID) { + if err := issues_model.CreateOrStopIssueStopwatch(ctx, user, issue); err != nil { return err } } diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 799c2268de867..b31ebb1971b9d 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -344,7 +344,7 @@ func acceptOrRejectRepoTransfer(ctx *context.Context, accept bool) error { return err } - if !repoTransfer.CanUserAcceptTransfer(ctx.Doer) { + if !repoTransfer.CanUserAcceptTransfer(ctx, ctx.Doer) { return errors.New("user does not have enough permissions") } @@ -359,7 +359,7 @@ func acceptOrRejectRepoTransfer(ctx *context.Context, accept bool) error { } ctx.Flash.Success(ctx.Tr("repo.settings.transfer.success")) } else { - if err := models.CancelRepositoryTransfer(ctx.Repo.Repository); err != nil { + if err := models.CancelRepositoryTransfer(ctx, ctx.Repo.Repository); err != nil { return err } ctx.Flash.Success(ctx.Tr("repo.settings.transfer.rejected")) diff --git a/routers/web/repo/setting/collaboration.go b/routers/web/repo/setting/collaboration.go index 1e71d33c08d41..e217697cc0adc 100644 --- a/routers/web/repo/setting/collaboration.go +++ b/routers/web/repo/setting/collaboration.go @@ -127,7 +127,7 @@ func ChangeCollaborationAccessMode(ctx *context.Context) { // DeleteCollaboration delete a collaboration for a repository func DeleteCollaboration(ctx *context.Context) { - if err := repo_service.DeleteCollaboration(ctx.Repo.Repository, ctx.FormInt64("id")); err != nil { + if err := repo_service.DeleteCollaboration(ctx, ctx.Repo.Repository, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteCollaboration: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success")) diff --git a/routers/web/repo/setting/setting.go b/routers/web/repo/setting/setting.go index af09e240d584d..7c85ff207835d 100644 --- a/routers/web/repo/setting/setting.go +++ b/routers/web/repo/setting/setting.go @@ -799,7 +799,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := models.CancelRepositoryTransfer(ctx.Repo.Repository); err != nil { + if err := models.CancelRepositoryTransfer(ctx, ctx.Repo.Repository); err != nil { ctx.ServerError("CancelRepositoryTransfer", err) return } @@ -863,7 +863,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := repo_model.SetArchiveRepoState(repo, true); err != nil { + if err := repo_model.SetArchiveRepoState(ctx, repo, true); err != nil { log.Error("Tried to archive a repo: %s", err) ctx.Flash.Error(ctx.Tr("repo.settings.archive.error")) ctx.Redirect(ctx.Repo.RepoLink + "/settings") @@ -881,7 +881,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := repo_model.SetArchiveRepoState(repo, false); err != nil { + if err := repo_model.SetArchiveRepoState(ctx, repo, false); err != nil { log.Error("Tried to unarchive a repo: %s", err) ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error")) ctx.Redirect(ctx.Repo.RepoLink + "/settings") diff --git a/routers/web/repo/topic.go b/routers/web/repo/topic.go index d22c3c6aa3748..d0e706c5bd7aa 100644 --- a/routers/web/repo/topic.go +++ b/routers/web/repo/topic.go @@ -45,7 +45,7 @@ func TopicsPost(ctx *context.Context) { return } - err := repo_model.SaveTopics(ctx.Repo.Repository.ID, validTopics...) + err := repo_model.SaveTopics(ctx, ctx.Repo.Repository.ID, validTopics...) if err != nil { log.Error("SaveTopics failed: %v", err) ctx.JSON(http.StatusInternalServerError, map[string]any{ diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 26e9cedd3ab65..37da76e3e50ee 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -640,7 +640,7 @@ func safeURL(address string) string { func checkHomeCodeViewable(ctx *context.Context) { if len(ctx.Repo.Units) > 0 { if ctx.Repo.Repository.IsBeingCreated() { - task, err := admin_model.GetMigratingTask(ctx.Repo.Repository.ID) + task, err := admin_model.GetMigratingTask(ctx, ctx.Repo.Repository.ID) if err != nil { if admin_model.IsErrTaskDoesNotExist(err) { ctx.Data["Repo"] = ctx.Repo @@ -893,7 +893,7 @@ func renderLanguageStats(ctx *context.Context) { } func renderRepoTopics(ctx *context.Context) { - topics, _, err := repo_model.FindTopics(&repo_model.FindTopicOptions{ + topics, _, err := repo_model.FindTopics(ctx, &repo_model.FindTopicOptions{ RepoID: ctx.Repo.Repository.ID, }) if err != nil { diff --git a/routers/web/shared/user/header.go b/routers/web/shared/user/header.go index 649537ec63521..16d9321e80a14 100644 --- a/routers/web/shared/user/header.go +++ b/routers/web/shared/user/header.go @@ -30,7 +30,7 @@ func prepareContextForCommonProfile(ctx *context.Context) { func PrepareContextForProfileBigAvatar(ctx *context.Context) { prepareContextForCommonProfile(ctx) - ctx.Data["IsFollowing"] = ctx.Doer != nil && user_model.IsFollowing(ctx.Doer.ID, ctx.ContextUser.ID) + ctx.Data["IsFollowing"] = ctx.Doer != nil && user_model.IsFollowing(ctx, ctx.Doer.ID, ctx.ContextUser.ID) ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail && ctx.ContextUser.Email != "" && ctx.IsSigned && !ctx.ContextUser.KeepEmailPrivate // Show OpenID URIs diff --git a/routers/web/user/home.go b/routers/web/user/home.go index a88479e1293a9..9efb536a7f905 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -59,7 +59,7 @@ func getDashboardContextUser(ctx *context.Context) *user_model.User { } ctx.Data["ContextUser"] = ctxUser - orgs, err := organization.GetUserOrgsList(ctx.Doer) + orgs, err := organization.GetUserOrgsList(ctx, ctx.Doer) if err != nil { ctx.ServerError("GetUserOrgsList", err) return nil @@ -213,13 +213,13 @@ func Milestones(ctx *context.Context) { } } - counts, err := issues_model.CountMilestonesByRepoCondAndKw(userRepoCond, keyword, isShowClosed) + counts, err := issues_model.CountMilestonesByRepoCondAndKw(ctx, userRepoCond, keyword, isShowClosed) if err != nil { ctx.ServerError("CountMilestonesByRepoIDs", err) return } - milestones, err := issues_model.SearchMilestones(repoCond, page, isShowClosed, sortType, keyword) + milestones, err := issues_model.SearchMilestones(ctx, repoCond, page, isShowClosed, sortType, keyword) if err != nil { ctx.ServerError("SearchMilestones", err) return @@ -256,7 +256,7 @@ func Milestones(ctx *context.Context) { } if milestones[i].Repo.IsTimetrackerEnabled(ctx) { - err := milestones[i].LoadTotalTrackedTime() + err := milestones[i].LoadTotalTrackedTime(ctx) if err != nil { ctx.ServerError("LoadTotalTrackedTime", err) return @@ -265,7 +265,7 @@ func Milestones(ctx *context.Context) { i++ } - milestoneStats, err := issues_model.GetMilestonesStatsByRepoCondAndKw(repoCond, keyword) + milestoneStats, err := issues_model.GetMilestonesStatsByRepoCondAndKw(ctx, repoCond, keyword) if err != nil { ctx.ServerError("GetMilestoneStats", err) return @@ -275,7 +275,7 @@ func Milestones(ctx *context.Context) { if len(repoIDs) == 0 { totalMilestoneStats = milestoneStats } else { - totalMilestoneStats, err = issues_model.GetMilestonesStatsByRepoCondAndKw(userRepoCond, keyword) + totalMilestoneStats, err = issues_model.GetMilestonesStatsByRepoCondAndKw(ctx, userRepoCond, keyword) if err != nil { ctx.ServerError("GetMilestoneStats", err) return diff --git a/routers/web/user/profile.go b/routers/web/user/profile.go index 87505b94b19c7..71d10ab4c1251 100644 --- a/routers/web/user/profile.go +++ b/routers/web/user/profile.go @@ -292,9 +292,9 @@ func Action(ctx *context.Context) { var err error switch ctx.FormString("action") { case "follow": - err = user_model.FollowUser(ctx.Doer.ID, ctx.ContextUser.ID) + err = user_model.FollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID) case "unfollow": - err = user_model.UnfollowUser(ctx.Doer.ID, ctx.ContextUser.ID) + err = user_model.UnfollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID) } if err != nil { diff --git a/routers/web/user/setting/security/security.go b/routers/web/user/setting/security/security.go index 1ce59fef0905b..5a17c161fe2cc 100644 --- a/routers/web/user/setting/security/security.go +++ b/routers/web/user/setting/security/security.go @@ -59,7 +59,7 @@ func loadSecurityData(ctx *context.Context) { } ctx.Data["TOTPEnrolled"] = enrolled - credentials, err := auth_model.GetWebAuthnCredentialsByUID(ctx.Doer.ID) + credentials, err := auth_model.GetWebAuthnCredentialsByUID(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetWebAuthnCredentialsByUID", err) return diff --git a/routers/web/user/setting/security/webauthn.go b/routers/web/user/setting/security/webauthn.go index 990e506d6fdf7..ce103528c57ea 100644 --- a/routers/web/user/setting/security/webauthn.go +++ b/routers/web/user/setting/security/webauthn.go @@ -29,7 +29,7 @@ func WebAuthnRegister(ctx *context.Context) { form.Name = strconv.FormatInt(time.Now().UnixNano(), 16) } - cred, err := auth.GetWebAuthnCredentialByName(ctx.Doer.ID, form.Name) + cred, err := auth.GetWebAuthnCredentialByName(ctx, ctx.Doer.ID, form.Name) if err != nil && !auth.IsErrWebAuthnCredentialNotExist(err) { ctx.ServerError("GetWebAuthnCredentialsByUID", err) return @@ -88,7 +88,7 @@ func WebauthnRegisterPost(ctx *context.Context) { return } - dbCred, err := auth.GetWebAuthnCredentialByName(ctx.Doer.ID, name) + dbCred, err := auth.GetWebAuthnCredentialByName(ctx, ctx.Doer.ID, name) if err != nil && !auth.IsErrWebAuthnCredentialNotExist(err) { ctx.ServerError("GetWebAuthnCredentialsByUID", err) return @@ -99,7 +99,7 @@ func WebauthnRegisterPost(ctx *context.Context) { } // Create the credential - _, err = auth.CreateCredential(ctx.Doer.ID, name, cred) + _, err = auth.CreateCredential(ctx, ctx.Doer.ID, name, cred) if err != nil { ctx.ServerError("CreateCredential", err) return @@ -112,7 +112,7 @@ func WebauthnRegisterPost(ctx *context.Context) { // WebauthnDelete deletes an security key by id func WebauthnDelete(ctx *context.Context) { form := web.GetForm(ctx).(*forms.WebauthnDeleteForm) - if _, err := auth.DeleteCredential(form.ID, ctx.Doer.ID); err != nil { + if _, err := auth.DeleteCredential(ctx, form.ID, ctx.Doer.ID); err != nil { ctx.ServerError("GetWebAuthnCredentialByID", err) return } diff --git a/routers/web/user/stop_watch.go b/routers/web/user/stop_watch.go index d262c777c30f7..cac446d84a28d 100644 --- a/routers/web/user/stop_watch.go +++ b/routers/web/user/stop_watch.go @@ -14,7 +14,7 @@ import ( // GetStopwatches get all stopwatches func GetStopwatches(ctx *context.Context) { - sws, err := issues_model.GetUserStopwatches(ctx.Doer.ID, db.ListOptions{ + sws, err := issues_model.GetUserStopwatches(ctx, ctx.Doer.ID, db.ListOptions{ Page: ctx.FormInt("page"), PageSize: convert.ToCorrectPageSize(ctx.FormInt("limit")), }) @@ -23,7 +23,7 @@ func GetStopwatches(ctx *context.Context) { return } - count, err := issues_model.CountUserStopwatches(ctx.Doer.ID) + count, err := issues_model.CountUserStopwatches(ctx, ctx.Doer.ID) if err != nil { ctx.Error(http.StatusInternalServerError, err.Error()) return diff --git a/routers/web/user/task.go b/routers/web/user/task.go index d92bf64af0fb3..f35f40e6a0fc1 100644 --- a/routers/web/user/task.go +++ b/routers/web/user/task.go @@ -14,7 +14,7 @@ import ( // TaskStatus returns task's status func TaskStatus(ctx *context.Context) { - task, opts, err := admin_model.GetMigratingTaskByID(ctx.ParamsInt64("task"), ctx.Doer.ID) + task, opts, err := admin_model.GetMigratingTaskByID(ctx, ctx.ParamsInt64("task"), ctx.Doer.ID) if err != nil { if admin_model.IsErrTaskDoesNotExist(err) { ctx.JSON(http.StatusNotFound, map[string]any{ diff --git a/services/issue/label.go b/services/issue/label.go index f830aab0e796e..91f0308d9f6a3 100644 --- a/services/issue/label.go +++ b/services/issue/label.go @@ -4,6 +4,8 @@ package issue import ( + "context" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" access_model "code.gitea.io/gitea/models/perm/access" @@ -12,49 +14,49 @@ import ( ) // ClearLabels clears all of an issue's labels -func ClearLabels(issue *issues_model.Issue, doer *user_model.User) error { +func ClearLabels(ctx context.Context, issue *issues_model.Issue, doer *user_model.User) error { if err := issues_model.ClearIssueLabels(issue, doer); err != nil { return err } - notify_service.IssueClearLabels(db.DefaultContext, doer, issue) + notify_service.IssueClearLabels(ctx, doer, issue) return nil } // AddLabel adds a new label to the issue. -func AddLabel(issue *issues_model.Issue, doer *user_model.User, label *issues_model.Label) error { +func AddLabel(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, label *issues_model.Label) error { if err := issues_model.NewIssueLabel(issue, label, doer); err != nil { return err } - notify_service.IssueChangeLabels(db.DefaultContext, doer, issue, []*issues_model.Label{label}, nil) + notify_service.IssueChangeLabels(ctx, doer, issue, []*issues_model.Label{label}, nil) return nil } // AddLabels adds a list of new labels to the issue. -func AddLabels(issue *issues_model.Issue, doer *user_model.User, labels []*issues_model.Label) error { +func AddLabels(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, labels []*issues_model.Label) error { if err := issues_model.NewIssueLabels(issue, labels, doer); err != nil { return err } - notify_service.IssueChangeLabels(db.DefaultContext, doer, issue, labels, nil) + notify_service.IssueChangeLabels(ctx, doer, issue, labels, nil) return nil } // RemoveLabel removes a label from issue by given ID. -func RemoveLabel(issue *issues_model.Issue, doer *user_model.User, label *issues_model.Label) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func RemoveLabel(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, label *issues_model.Label) error { + dbCtx, committer, err := db.TxContext(ctx) if err != nil { return err } defer committer.Close() - if err := issue.LoadRepo(ctx); err != nil { + if err := issue.LoadRepo(dbCtx); err != nil { return err } - perm, err := access_model.GetUserRepoPermission(ctx, issue.Repo, doer) + perm, err := access_model.GetUserRepoPermission(dbCtx, issue.Repo, doer) if err != nil { return err } @@ -65,7 +67,7 @@ func RemoveLabel(issue *issues_model.Issue, doer *user_model.User, label *issues return issues_model.ErrRepoLabelNotExist{} } - if err := issues_model.DeleteIssueLabel(ctx, issue, label, doer); err != nil { + if err := issues_model.DeleteIssueLabel(dbCtx, issue, label, doer); err != nil { return err } @@ -73,13 +75,13 @@ func RemoveLabel(issue *issues_model.Issue, doer *user_model.User, label *issues return err } - notify_service.IssueChangeLabels(db.DefaultContext, doer, issue, nil, []*issues_model.Label{label}) + notify_service.IssueChangeLabels(ctx, doer, issue, nil, []*issues_model.Label{label}) return nil } // ReplaceLabels removes all current labels and add new labels to the issue. -func ReplaceLabels(issue *issues_model.Issue, doer *user_model.User, labels []*issues_model.Label) error { - old, err := issues_model.GetLabelsByIssueID(db.DefaultContext, issue.ID) +func ReplaceLabels(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, labels []*issues_model.Label) error { + old, err := issues_model.GetLabelsByIssueID(ctx, issue.ID) if err != nil { return err } @@ -88,6 +90,6 @@ func ReplaceLabels(issue *issues_model.Issue, doer *user_model.User, labels []*i return err } - notify_service.IssueChangeLabels(db.DefaultContext, doer, issue, labels, old) + notify_service.IssueChangeLabels(ctx, doer, issue, labels, old) return nil } diff --git a/services/issue/label_test.go b/services/issue/label_test.go index af220601f145c..90608c9e2691a 100644 --- a/services/issue/label_test.go +++ b/services/issue/label_test.go @@ -6,6 +6,7 @@ package issue import ( "testing" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -32,7 +33,7 @@ func TestIssue_AddLabels(t *testing.T) { labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID}) } doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) - assert.NoError(t, AddLabels(issue, doer, labels)) + assert.NoError(t, AddLabels(db.DefaultContext, issue, doer, labels)) for _, labelID := range test.labelIDs { unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: test.issueID, LabelID: labelID}) } @@ -55,7 +56,7 @@ func TestIssue_AddLabel(t *testing.T) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: test.labelID}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) - assert.NoError(t, AddLabel(issue, doer, label)) + assert.NoError(t, AddLabel(db.DefaultContext, issue, doer, label)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: test.issueID, LabelID: test.labelID}) } } diff --git a/services/mailer/incoming/incoming_handler.go b/services/mailer/incoming/incoming_handler.go index b594e35189bf5..78f9f89fc9eaa 100644 --- a/services/mailer/incoming/incoming_handler.go +++ b/services/mailer/incoming/incoming_handler.go @@ -170,7 +170,7 @@ func (h *UnsubscribeHandler) Handle(ctx context.Context, _ *MailContent, doer *u return nil } - return issues_model.CreateOrUpdateIssueWatch(doer.ID, issue.ID, false) + return issues_model.CreateOrUpdateIssueWatch(ctx, doer.ID, issue.ID, false) } return fmt.Errorf("unsupported unsubscribe reference: %v", ref) diff --git a/services/migrations/dump.go b/services/migrations/dump.go index 603954810cffa..07812002afa75 100644 --- a/services/migrations/dump.go +++ b/services/migrations/dump.go @@ -655,7 +655,7 @@ func DumpRepository(ctx context.Context, baseDir, ownerName string, opts base.Mi return err } - if err := migrateRepository(doer, downloader, uploader, opts, nil); err != nil { + if err := migrateRepository(ctx, doer, downloader, uploader, opts, nil); err != nil { if err1 := uploader.Rollback(); err1 != nil { log.Error("rollback failed: %v", err1) } @@ -727,7 +727,7 @@ func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string, return err } - if err = migrateRepository(doer, downloader, uploader, migrateOpts, nil); err != nil { + if err = migrateRepository(ctx, doer, downloader, uploader, migrateOpts, nil); err != nil { if err1 := uploader.Rollback(); err1 != nil { log.Error("rollback failed: %v", err1) } diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index 4c21efae44fea..9f1e613bb22d4 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -162,7 +162,7 @@ func (g *GiteaLocalUploader) CreateTopics(topics ...string) error { c++ } topics = topics[:c] - return repo_model.SaveTopics(g.repo.ID, topics...) + return repo_model.SaveTopics(g.ctx, g.repo.ID, topics...) } // CreateMilestones creates milestones @@ -205,7 +205,7 @@ func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) err mss = append(mss, &ms) } - err := issues_model.InsertMilestones(mss...) + err := issues_model.InsertMilestones(g.ctx, mss...) if err != nil { return err } @@ -236,7 +236,7 @@ func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error { }) } - err := issues_model.NewLabels(lbs...) + err := issues_model.NewLabels(g.ctx, lbs...) if err != nil { return err } @@ -516,7 +516,6 @@ func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error { // CreatePullRequests creates pull requests func (g *GiteaLocalUploader) CreatePullRequests(prs ...*base.PullRequest) error { gprs := make([]*issues_model.PullRequest, 0, len(prs)) - ctx := db.DefaultContext for _, pr := range prs { gpr, err := g.newPullRequest(pr) if err != nil { @@ -529,12 +528,12 @@ func (g *GiteaLocalUploader) CreatePullRequests(prs ...*base.PullRequest) error gprs = append(gprs, gpr) } - if err := issues_model.InsertPullRequests(ctx, gprs...); err != nil { + if err := issues_model.InsertPullRequests(g.ctx, gprs...); err != nil { return err } for _, pr := range gprs { g.issues[pr.Issue.Index] = pr.Issue - pull.AddToTaskQueue(ctx, pr) + pull.AddToTaskQueue(g.ctx, pr) } return nil } diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index e42d9e928618a..4c6dfddc08d31 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -44,7 +44,7 @@ func TestGiteaUploadRepo(t *testing.T) { uploader = NewGiteaLocalUploader(graceful.GetManager().HammerContext(), user, user.Name, repoName) ) - err := migrateRepository(user, downloader, uploader, base.MigrateOptions{ + err := migrateRepository(db.DefaultContext, user, downloader, uploader, base.MigrateOptions{ CloneAddr: "https://github.com/go-xorm/builder", RepoName: repoName, AuthUsername: "", diff --git a/services/migrations/migrate.go b/services/migrations/migrate.go index 0ebb3411fdb2f..0b83f3b4a3262 100644 --- a/services/migrations/migrate.go +++ b/services/migrations/migrate.go @@ -127,7 +127,7 @@ func MigrateRepository(ctx context.Context, doer *user_model.User, ownerName str uploader := NewGiteaLocalUploader(ctx, doer, ownerName, opts.RepoName) uploader.gitServiceType = opts.GitServiceType - if err := migrateRepository(doer, downloader, uploader, opts, messenger); err != nil { + if err := migrateRepository(ctx, doer, downloader, uploader, opts, messenger); err != nil { if err1 := uploader.Rollback(); err1 != nil { log.Error("rollback failed: %v", err1) } @@ -176,7 +176,7 @@ func newDownloader(ctx context.Context, ownerName string, opts base.MigrateOptio // migrateRepository will download information and then upload it to Uploader, this is a simple // process for small repository. For a big repository, save all the data to disk // before upload is better -func migrateRepository(doer *user_model.User, downloader base.Downloader, uploader base.Uploader, opts base.MigrateOptions, messenger base.Messenger) error { +func migrateRepository(ctx context.Context, doer *user_model.User, downloader base.Downloader, uploader base.Uploader, opts base.MigrateOptions, messenger base.Messenger) error { if messenger == nil { messenger = base.NilMessenger } diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go index 321bd38fc3245..d2b7d37eaa1bd 100644 --- a/services/mirror/mirror_pull.go +++ b/services/mirror/mirror_pull.go @@ -540,7 +540,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool { return false } - if err = repo_model.UpdateRepositoryUpdatedTime(m.RepoID, commitDate); err != nil { + if err = repo_model.UpdateRepositoryUpdatedTime(ctx, m.RepoID, commitDate); err != nil { log.Error("SyncMirrors [repo: %-v]: unable to update repository 'updated_unix': %v", m.Repo, err) return false } diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go index 2e3defee8d15e..f6f03e75ae59f 100644 --- a/services/repository/archiver/archiver.go +++ b/services/repository/archiver/archiver.go @@ -346,7 +346,7 @@ func DeleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration) e log.Trace("Doing: ArchiveCleanup") for { - archivers, err := repo_model.FindRepoArchives(repo_model.FindRepoArchiversOption{ + archivers, err := repo_model.FindRepoArchives(ctx, repo_model.FindRepoArchiversOption{ ListOptions: db.ListOptions{ PageSize: 100, Page: 1, @@ -374,7 +374,7 @@ func DeleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration) e // DeleteRepositoryArchives deletes all repositories' archives. func DeleteRepositoryArchives(ctx context.Context) error { - if err := repo_model.DeleteAllRepoArchives(); err != nil { + if err := repo_model.DeleteAllRepoArchives(ctx); err != nil { return err } return storage.Clean(storage.RepoArchives) diff --git a/services/repository/collaboration.go b/services/repository/collaboration.go index 28824d83f5f94..eff33c71f3ccf 100644 --- a/services/repository/collaboration.go +++ b/services/repository/collaboration.go @@ -5,6 +5,8 @@ package repository import ( + "context" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" access_model "code.gitea.io/gitea/models/perm/access" @@ -12,13 +14,13 @@ import ( ) // DeleteCollaboration removes collaboration relation between the user and repository. -func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) { +func DeleteCollaboration(ctx context.Context, repo *repo_model.Repository, uid int64) (err error) { collaboration := &repo_model.Collaboration{ RepoID: repo.ID, UserID: uid, } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } diff --git a/services/repository/collaboration_test.go b/services/repository/collaboration_test.go index 08159af7bcfdb..c3d006bfd8c27 100644 --- a/services/repository/collaboration_test.go +++ b/services/repository/collaboration_test.go @@ -18,10 +18,10 @@ func TestRepository_DeleteCollaboration(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) assert.NoError(t, repo.LoadOwner(db.DefaultContext)) - assert.NoError(t, DeleteCollaboration(repo, 4)) + assert.NoError(t, DeleteCollaboration(db.DefaultContext, repo, 4)) unittest.AssertNotExistsBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4}) - assert.NoError(t, DeleteCollaboration(repo, 4)) + assert.NoError(t, DeleteCollaboration(db.DefaultContext, repo, 4)) unittest.AssertNotExistsBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) diff --git a/services/repository/push.go b/services/repository/push.go index 9b00b57e71ec6..97da45f52b4bf 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -292,7 +292,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { } // Change repository last updated time. - if err := repo_model.UpdateRepositoryUpdatedTime(repo.ID, time.Now()); err != nil { + if err := repo_model.UpdateRepositoryUpdatedTime(ctx, repo.ID, time.Now()); err != nil { return fmt.Errorf("UpdateRepositoryUpdatedTime: %w", err) } diff --git a/services/repository/repository.go b/services/repository/repository.go index 60f9568b54118..fb52980bbda58 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -95,12 +95,12 @@ func PushCreateRepo(ctx context.Context, authUser, owner *user_model.User, repoN } // Init start repository service -func Init() error { +func Init(ctx context.Context) error { if err := repo_module.LoadRepoConfig(); err != nil { return err } - system_model.RemoveAllWithNotice(db.DefaultContext, "Clean up temporary repository uploads", setting.Repository.Upload.TempPath) - system_model.RemoveAllWithNotice(db.DefaultContext, "Clean up temporary repositories", repo_module.LocalCopyPath()) + system_model.RemoveAllWithNotice(ctx, "Clean up temporary repository uploads", setting.Repository.Upload.TempPath) + system_model.RemoveAllWithNotice(ctx, "Clean up temporary repositories", repo_module.LocalCopyPath()) if err := initPushQueue(); err != nil { return err } diff --git a/services/repository/transfer.go b/services/repository/transfer.go index 2edb61816fb98..574b6c6a56342 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -37,7 +37,7 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner repoWorkingPool.CheckIn(fmt.Sprint(repo.ID)) - if err := models.TransferOwnership(doer, newOwner.Name, repo); err != nil { + if err := models.TransferOwnership(ctx, doer, newOwner.Name, repo); err != nil { repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) return err } @@ -70,7 +70,7 @@ func ChangeRepositoryName(ctx context.Context, doer *user_model.User, repo *repo // local copy's origin accordingly. repoWorkingPool.CheckIn(fmt.Sprint(repo.ID)) - if err := repo_model.ChangeRepositoryName(doer, repo, newRepoName); err != nil { + if err := repo_model.ChangeRepositoryName(ctx, doer, repo, newRepoName); err != nil { repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) return err } diff --git a/services/task/migrate.go b/services/task/migrate.go index ebf179045e0ac..70e5abdee6ebd 100644 --- a/services/task/migrate.go +++ b/services/task/migrate.go @@ -4,6 +4,7 @@ package task import ( + "context" "errors" "fmt" "strings" @@ -40,7 +41,7 @@ func handleCreateError(owner *user_model.User, err error) error { } } -func runMigrateTask(t *admin_model.Task) (err error) { +func runMigrateTask(ctx context.Context, t *admin_model.Task) (err error) { defer func() { if e := recover(); e != nil { err = fmt.Errorf("PANIC whilst trying to do migrate task: %v", e) @@ -48,9 +49,9 @@ func runMigrateTask(t *admin_model.Task) (err error) { } if err == nil { - err = admin_model.FinishMigrateTask(t) + err = admin_model.FinishMigrateTask(ctx, t) if err == nil { - notify_service.MigrateRepository(db.DefaultContext, t.Doer, t.Owner, t.Repo) + notify_service.MigrateRepository(ctx, t.Doer, t.Owner, t.Repo) return } @@ -63,14 +64,14 @@ func runMigrateTask(t *admin_model.Task) (err error) { t.Status = structs.TaskStatusFailed t.Message = err.Error() - if err := t.UpdateCols("status", "message", "end_time"); err != nil { + if err := t.UpdateCols(ctx, "status", "message", "end_time"); err != nil { log.Error("Task UpdateCols failed: %v", err) } // then, do not delete the repository, otherwise the users won't be able to see the last error }() - if err = t.LoadRepo(); err != nil { + if err = t.LoadRepo(ctx); err != nil { return err } @@ -79,10 +80,10 @@ func runMigrateTask(t *admin_model.Task) (err error) { return nil } - if err = t.LoadDoer(); err != nil { + if err = t.LoadDoer(ctx); err != nil { return err } - if err = t.LoadOwner(); err != nil { + if err = t.LoadOwner(ctx); err != nil { return err } @@ -100,7 +101,7 @@ func runMigrateTask(t *admin_model.Task) (err error) { t.StartTime = timeutil.TimeStampNow() t.Status = structs.TaskStatusRunning - if err = t.UpdateCols("start_time", "status"); err != nil { + if err = t.UpdateCols(ctx, "start_time", "status"); err != nil { return err } @@ -112,7 +113,7 @@ func runMigrateTask(t *admin_model.Task) (err error) { case <-ctx.Done(): return } - task, _ := admin_model.GetMigratingTask(t.RepoID) + task, _ := admin_model.GetMigratingTask(ctx, t.RepoID) if task != nil && task.Status != structs.TaskStatusRunning { log.Debug("MigrateTask[%d] by DoerID[%d] to RepoID[%d] for OwnerID[%d] is canceled due to status is not 'running'", t.ID, t.DoerID, t.RepoID, t.OwnerID) cancel() @@ -128,7 +129,7 @@ func runMigrateTask(t *admin_model.Task) (err error) { } bs, _ := json.Marshal(message) t.Message = string(bs) - _ = t.UpdateCols("message") + _ = t.UpdateCols(ctx, "message") }) if err == nil { diff --git a/services/task/task.go b/services/task/task.go index 3a40faef90ac3..e15cab7b3c97f 100644 --- a/services/task/task.go +++ b/services/task/task.go @@ -4,6 +4,7 @@ package task import ( + "context" "fmt" admin_model "code.gitea.io/gitea/models/admin" @@ -27,10 +28,10 @@ import ( var taskQueue *queue.WorkerPoolQueue[*admin_model.Task] // Run a task -func Run(t *admin_model.Task) error { +func Run(ctx context.Context, t *admin_model.Task) error { switch t.Type { case structs.TaskTypeMigrateRepo: - return runMigrateTask(t) + return runMigrateTask(ctx, t) default: return fmt.Errorf("Unknown task type: %d", t.Type) } @@ -48,7 +49,7 @@ func Init() error { func handler(items ...*admin_model.Task) []*admin_model.Task { for _, task := range items { - if err := Run(task); err != nil { + if err := Run(db.DefaultContext, task); err != nil { log.Error("Run task failed: %v", err) } } @@ -56,8 +57,8 @@ func handler(items ...*admin_model.Task) []*admin_model.Task { } // MigrateRepository add migration repository to task -func MigrateRepository(doer, u *user_model.User, opts base.MigrateOptions) error { - task, err := CreateMigrateTask(doer, u, opts) +func MigrateRepository(ctx context.Context, doer, u *user_model.User, opts base.MigrateOptions) error { + task, err := CreateMigrateTask(ctx, doer, u, opts) if err != nil { return err } @@ -66,7 +67,7 @@ func MigrateRepository(doer, u *user_model.User, opts base.MigrateOptions) error } // CreateMigrateTask creates a migrate task -func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*admin_model.Task, error) { +func CreateMigrateTask(ctx context.Context, doer, u *user_model.User, opts base.MigrateOptions) (*admin_model.Task, error) { // encrypt credentials for persistence var err error opts.CloneAddrEncrypted, err = secret.EncryptSecret(setting.SecretKey, opts.CloneAddr) @@ -97,11 +98,11 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*adm PayloadContent: string(bs), } - if err := admin_model.CreateTask(task); err != nil { + if err := admin_model.CreateTask(ctx, task); err != nil { return nil, err } - repo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, doer, u, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepositoryDirectly(ctx, doer, u, repo_service.CreateRepoOptions{ Name: opts.RepoName, Description: opts.Description, OriginalURL: opts.OriginalURL, @@ -113,7 +114,7 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*adm if err != nil { task.EndTime = timeutil.TimeStampNow() task.Status = structs.TaskStatusFailed - err2 := task.UpdateCols("end_time", "status") + err2 := task.UpdateCols(ctx, "end_time", "status") if err2 != nil { log.Error("UpdateCols Failed: %v", err2.Error()) } @@ -121,7 +122,7 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*adm } task.RepoID = repo.ID - if err = task.UpdateCols("repo_id"); err != nil { + if err = task.UpdateCols(ctx, "repo_id"); err != nil { return nil, err } @@ -129,8 +130,8 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*adm } // RetryMigrateTask retry a migrate task -func RetryMigrateTask(repoID int64) error { - migratingTask, err := admin_model.GetMigratingTask(repoID) +func RetryMigrateTask(ctx context.Context, repoID int64) error { + migratingTask, err := admin_model.GetMigratingTask(ctx, repoID) if err != nil { log.Error("GetMigratingTask: %v", err) return err @@ -144,7 +145,7 @@ func RetryMigrateTask(repoID int64) error { // Reset task status and messages migratingTask.Status = structs.TaskStatusQueued migratingTask.Message = "" - if err = migratingTask.UpdateCols("status", "message"); err != nil { + if err = migratingTask.UpdateCols(ctx, "status", "message"); err != nil { log.Error("task.UpdateCols failed: %v", err) return err } diff --git a/services/user/user.go b/services/user/user.go index 72bea0b4688b0..5b2e74eb828dd 100644 --- a/services/user/user.go +++ b/services/user/user.go @@ -59,7 +59,7 @@ func RenameUser(ctx context.Context, u *user_model.User, newUserName string) err u.Name = oldUserName return err } - return repo_model.UpdateRepositoryOwnerNames(u.ID, newUserName) + return repo_model.UpdateRepositoryOwnerNames(ctx, u.ID, newUserName) } ctx, committer, err := db.TxContext(ctx) diff --git a/tests/integration/incoming_email_test.go b/tests/integration/incoming_email_test.go index b4478f57809fa..12848338648af 100644 --- a/tests/integration/incoming_email_test.go +++ b/tests/integration/incoming_email_test.go @@ -154,7 +154,7 @@ func TestIncomingEmail(t *testing.T) { t.Run("Unsubscribe", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - watching, err := issues_model.CheckIssueWatch(user, issue) + watching, err := issues_model.CheckIssueWatch(db.DefaultContext, user, issue) assert.NoError(t, err) assert.True(t, watching) @@ -169,7 +169,7 @@ func TestIncomingEmail(t *testing.T) { assert.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) - watching, err = issues_model.CheckIssueWatch(user, issue) + watching, err = issues_model.CheckIssueWatch(db.DefaultContext, user, issue) assert.NoError(t, err) assert.False(t, watching) }) From 5e039b05801a2ceeb29b23c657110af02834b57e Mon Sep 17 00:00:00 2001 From: puni9869 <80308335+puni9869@users.noreply.github.com> Date: Sat, 16 Sep 2023 20:36:27 +0530 Subject: [PATCH 18/23] Upgrading the actions/checkout@4 (#27096) as title ..Upgrading the actions/checkout@4 Signed-off-by: puni9869 Co-authored-by: silverwind --- .github/workflows/cron-licenses.yml | 2 +- .github/workflows/cron-translations.yml | 4 ++-- .github/workflows/files-changed.yml | 2 +- .github/workflows/pull-compliance.yml | 22 +++++++++++----------- .github/workflows/pull-db-tests.yml | 12 ++++++------ .github/workflows/pull-e2e-tests.yml | 2 +- .github/workflows/release-nightly.yml | 6 +++--- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/.github/workflows/cron-licenses.yml b/.github/workflows/cron-licenses.yml index acdf7cd3646a4..5de165487c1e7 100644 --- a/.github/workflows/cron-licenses.yml +++ b/.github/workflows/cron-licenses.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest if: github.repository == 'go-gitea/gitea' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" diff --git a/.github/workflows/cron-translations.yml b/.github/workflows/cron-translations.yml index 3f147c685d8c5..b0effdee9d6a2 100644 --- a/.github/workflows/cron-translations.yml +++ b/.github/workflows/cron-translations.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest if: github.repository == 'go-gitea/gitea' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: download from crowdin uses: docker://jonasfranz/crowdin env: @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest if: github.repository == 'go-gitea/gitea' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: push translations to crowdin uses: docker://jonasfranz/crowdin env: diff --git a/.github/workflows/files-changed.yml b/.github/workflows/files-changed.yml index ef6b8022ff61f..e7039053af9de 100644 --- a/.github/workflows/files-changed.yml +++ b/.github/workflows/files-changed.yml @@ -34,7 +34,7 @@ jobs: swagger: ${{ steps.changes.outputs.swagger }} yaml: ${{ steps.changes.outputs.yaml }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: dorny/paths-filter@v2 id: changes with: diff --git a/.github/workflows/pull-compliance.yml b/.github/workflows/pull-compliance.yml index bcbd21884616c..d19fa16024d27 100644 --- a/.github/workflows/pull-compliance.yml +++ b/.github/workflows/pull-compliance.yml @@ -16,7 +16,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -31,7 +31,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 with: python-version: "3.11" @@ -44,7 +44,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 with: python-version: "3.11" @@ -57,7 +57,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 20 @@ -69,7 +69,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -86,7 +86,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -101,7 +101,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -114,7 +114,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 20 @@ -129,7 +129,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -161,7 +161,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 20 @@ -174,6 +174,6 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 - run: make lint-actions diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index bbe589d5c8dac..a6fb85937cd26 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -38,7 +38,7 @@ jobs: ports: - "9000:9000" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -63,7 +63,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -128,7 +128,7 @@ jobs: ports: - "9000:9000" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -178,7 +178,7 @@ jobs: - "587:587" - "993:993" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -210,7 +210,7 @@ jobs: ports: - "3306:3306" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" @@ -241,7 +241,7 @@ jobs: ports: - "1433:1433" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" diff --git a/.github/workflows/pull-e2e-tests.yml b/.github/workflows/pull-e2e-tests.yml index 7b950bfd38085..3fca2bee80bd6 100644 --- a/.github/workflows/pull-e2e-tests.yml +++ b/.github/workflows/pull-e2e-tests.yml @@ -16,7 +16,7 @@ jobs: needs: files-changed runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-go@v4 with: go-version: "~1.21" diff --git a/.github/workflows/release-nightly.yml b/.github/workflows/release-nightly.yml index 0671ecee8bce2..ef3db2db73e03 100644 --- a/.github/workflows/release-nightly.yml +++ b/.github/workflows/release-nightly.yml @@ -12,7 +12,7 @@ jobs: nightly-binary: runs-on: actuated-4cpu-16gb steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force @@ -58,7 +58,7 @@ jobs: nightly-docker-rootful: runs-on: actuated-4cpu-16gb steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force @@ -95,7 +95,7 @@ jobs: nightly-docker-rootless: runs-on: actuated-4cpu-16gb steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force From c766140dad3408048ad843d0e7b4ab5d9f5777c6 Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Sat, 16 Sep 2023 18:03:02 +0200 Subject: [PATCH 19/23] Add `RemoteAddress` to mirrors (#26952) This PR adds a new field `RemoteAddress` to both mirror types which contains the sanitized remote address for easier (database) access to that information. Will be used in the audit PR if merged. --- models/migrations/migrations.go | 2 + models/migrations/v1_21/v276.go | 132 +++++++++++++++++++++++++++ models/repo/mirror.go | 2 +- models/repo/pushmirror.go | 10 +- models/repo/repo.go | 8 +- modules/repository/repo.go | 5 + modules/util/url.go | 9 ++ routers/api/v1/repo/mirror.go | 17 +++- routers/web/repo/setting/setting.go | 24 ++++- routers/web/repo/view.go | 11 +-- services/convert/mirror.go | 17 +--- templates/repo/header.tmpl | 3 +- templates/repo/settings/options.tmpl | 7 +- 13 files changed, 194 insertions(+), 53 deletions(-) create mode 100644 models/migrations/v1_21/v276.go diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index f0a8b05d5337d..3524077ea4b7c 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -532,6 +532,8 @@ var migrations = []Migration{ NewMigration("Add Actions artifacts expiration date", v1_21.AddExpiredUnixColumnInActionArtifactTable), // v275 -> v276 NewMigration("Add ScheduleID for ActionRun", v1_21.AddScheduleIDForActionRun), + // v276 -> v277 + NewMigration("Add RemoteAddress to mirrors", v1_21.AddRemoteAddressToMirrors), } // GetCurrentDBVersion returns the current db version diff --git a/models/migrations/v1_21/v276.go b/models/migrations/v1_21/v276.go new file mode 100644 index 0000000000000..8933f186dc04e --- /dev/null +++ b/models/migrations/v1_21/v276.go @@ -0,0 +1,132 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package v1_21 //nolint + +import ( + "context" + "fmt" + "path/filepath" + "strings" + + "code.gitea.io/gitea/modules/git" + giturl "code.gitea.io/gitea/modules/git/url" + "code.gitea.io/gitea/modules/setting" + + "xorm.io/xorm" +) + +func AddRemoteAddressToMirrors(x *xorm.Engine) error { + type Mirror struct { + RemoteAddress string `xorm:"VARCHAR(2048)"` + } + + type PushMirror struct { + RemoteAddress string `xorm:"VARCHAR(2048)"` + } + + if err := x.Sync(new(Mirror), new(PushMirror)); err != nil { + return err + } + + if err := migratePullMirrors(x); err != nil { + return err + } + + return migratePushMirrors(x) +} + +func migratePullMirrors(x *xorm.Engine) error { + type Mirror struct { + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"INDEX"` + RemoteAddress string `xorm:"VARCHAR(2048)"` + } + + sess := x.NewSession() + defer sess.Close() + + if err := sess.Begin(); err != nil { + return err + } + + if err := sess.Iterate(new(Mirror), func(_ int, bean any) error { + m := bean.(*Mirror) + remoteAddress, err := getRemoteAddress(sess, m.RepoID, "origin") + if err != nil { + return err + } + + m.RemoteAddress = remoteAddress + + _, err = sess.ID(m.ID).Cols("remote_address").Update(m) + return err + }); err != nil { + return err + } + + return sess.Commit() +} + +func migratePushMirrors(x *xorm.Engine) error { + type PushMirror struct { + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"INDEX"` + RemoteName string + RemoteAddress string `xorm:"VARCHAR(2048)"` + } + + sess := x.NewSession() + defer sess.Close() + + if err := sess.Begin(); err != nil { + return err + } + + if err := sess.Iterate(new(PushMirror), func(_ int, bean any) error { + m := bean.(*PushMirror) + remoteAddress, err := getRemoteAddress(sess, m.RepoID, m.RemoteName) + if err != nil { + return err + } + + m.RemoteAddress = remoteAddress + + _, err = sess.ID(m.ID).Cols("remote_address").Update(m) + return err + }); err != nil { + return err + } + + return sess.Commit() +} + +func getRemoteAddress(sess *xorm.Session, repoID int64, remoteName string) (string, error) { + var ownerName string + var repoName string + has, err := sess. + Table("repository"). + Cols("owner_name", "lower_name"). + Where("id=?", repoID). + Get(&ownerName, &repoName) + if err != nil { + return "", err + } else if !has { + return "", fmt.Errorf("repository [%v] not found", repoID) + } + + repoPath := filepath.Join(setting.RepoRootPath, strings.ToLower(ownerName), strings.ToLower(repoName)+".git") + + remoteURL, err := git.GetRemoteAddress(context.Background(), repoPath, remoteName) + if err != nil { + return "", err + } + + u, err := giturl.Parse(remoteURL) + if err != nil { + return "", err + } + u.User = nil + + return u.String(), nil +} diff --git a/models/repo/mirror.go b/models/repo/mirror.go index 39482037b2032..fffc7577c7b09 100644 --- a/models/repo/mirror.go +++ b/models/repo/mirror.go @@ -31,7 +31,7 @@ type Mirror struct { LFS bool `xorm:"lfs_enabled NOT NULL DEFAULT false"` LFSEndpoint string `xorm:"lfs_endpoint TEXT"` - Address string `xorm:"-"` + RemoteAddress string `xorm:"VARCHAR(2048)"` } func init() { diff --git a/models/repo/pushmirror.go b/models/repo/pushmirror.go index 3edbcceb9b389..73c1384444ddc 100644 --- a/models/repo/pushmirror.go +++ b/models/repo/pushmirror.go @@ -20,10 +20,11 @@ var ErrPushMirrorNotExist = util.NewNotExistErrorf("PushMirror does not exist") // PushMirror represents mirror information of a repository. type PushMirror struct { - ID int64 `xorm:"pk autoincr"` - RepoID int64 `xorm:"INDEX"` - Repo *Repository `xorm:"-"` - RemoteName string + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"INDEX"` + Repo *Repository `xorm:"-"` + RemoteName string + RemoteAddress string `xorm:"VARCHAR(2048)"` SyncOnCommit bool `xorm:"NOT NULL DEFAULT true"` Interval time.Duration @@ -31,6 +32,7 @@ type PushMirror struct { LastUpdateUnix timeutil.TimeStamp `xorm:"INDEX last_update"` LastError string `xorm:"text"` } + type PushMirrorOptions struct { ID int64 RepoID int64 diff --git a/models/repo/repo.go b/models/repo/repo.go index b37948fea77a6..5ebc7bfc24208 100644 --- a/models/repo/repo.go +++ b/models/repo/repo.go @@ -191,12 +191,8 @@ func (repo *Repository) SanitizedOriginalURL() string { if repo.OriginalURL == "" { return "" } - u, err := url.Parse(repo.OriginalURL) - if err != nil { - return "" - } - u.User = nil - return u.String() + u, _ := util.SanitizeURL(repo.OriginalURL) + return u } // text representations to be returned in SizeDetail.Name diff --git a/modules/repository/repo.go b/modules/repository/repo.go index 6bf88e775262b..b50c8f75ca789 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -180,12 +180,17 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, defer committer.Close() if opts.Mirror { + remoteAddress, err := util.SanitizeURL(opts.CloneAddr) + if err != nil { + return repo, err + } mirrorModel := repo_model.Mirror{ RepoID: repo.ID, Interval: setting.Mirror.DefaultInterval, EnablePrune: true, NextUpdateUnix: timeutil.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval), LFS: opts.LFS, + RemoteAddress: remoteAddress, } if opts.LFS { mirrorModel.LFSEndpoint = opts.LFSEndpoint diff --git a/modules/util/url.go b/modules/util/url.go index 75fcf634a9677..62370339c8d87 100644 --- a/modules/util/url.go +++ b/modules/util/url.go @@ -39,3 +39,12 @@ func URLJoin(base string, elems ...string) string { } return joinedURL } + +func SanitizeURL(s string) (string, error) { + u, err := url.Parse(s) + if err != nil { + return "", err + } + u.User = nil + return u.String(), nil +} diff --git a/routers/api/v1/repo/mirror.go b/routers/api/v1/repo/mirror.go index 12542c808f64b..15c7046b49336 100644 --- a/routers/api/v1/repo/mirror.go +++ b/routers/api/v1/repo/mirror.go @@ -353,12 +353,19 @@ func CreatePushMirror(ctx *context.APIContext, mirrorOption *api.CreatePushMirro return } + remoteAddress, err := util.SanitizeURL(mirrorOption.RemoteAddress) + if err != nil { + ctx.ServerError("SanitizeURL", err) + return + } + pushMirror := &repo_model.PushMirror{ - RepoID: repo.ID, - Repo: repo, - RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix), - Interval: interval, - SyncOnCommit: mirrorOption.SyncOnCommit, + RepoID: repo.ID, + Repo: repo, + RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix), + Interval: interval, + SyncOnCommit: mirrorOption.SyncOnCommit, + RemoteAddress: remoteAddress, } if err = repo_model.InsertPushMirror(ctx, pushMirror); err != nil { diff --git a/routers/web/repo/setting/setting.go b/routers/web/repo/setting/setting.go index 7c85ff207835d..68943586ef588 100644 --- a/routers/web/repo/setting/setting.go +++ b/routers/web/repo/setting/setting.go @@ -243,6 +243,13 @@ func SettingsPost(ctx *context.Context) { return } + remoteAddress, err := util.SanitizeURL(form.MirrorAddress) + if err != nil { + ctx.ServerError("SanitizeURL", err) + return + } + pullMirror.RemoteAddress = remoteAddress + form.LFS = form.LFS && setting.LFS.StartServer if len(form.LFSEndpoint) > 0 { @@ -397,12 +404,19 @@ func SettingsPost(ctx *context.Context) { return } + remoteAddress, err := util.SanitizeURL(form.PushMirrorAddress) + if err != nil { + ctx.ServerError("SanitizeURL", err) + return + } + m := &repo_model.PushMirror{ - RepoID: repo.ID, - Repo: repo, - RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix), - SyncOnCommit: form.PushMirrorSyncOnCommit, - Interval: interval, + RepoID: repo.ID, + Repo: repo, + RemoteName: fmt.Sprintf("remote_mirror_%s", remoteSuffix), + SyncOnCommit: form.PushMirrorSyncOnCommit, + Interval: interval, + RemoteAddress: remoteAddress, } if err := repo_model.InsertPushMirror(ctx, m); err != nil { ctx.ServerError("InsertPushMirror", err) diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 37da76e3e50ee..91c00b049e9f7 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -628,15 +628,6 @@ func markupRender(ctx *context.Context, renderCtx *markup.RenderContext, input i return escaped, output, err } -func safeURL(address string) string { - u, err := url.Parse(address) - if err != nil { - return address - } - u.User = nil - return u.String() -} - func checkHomeCodeViewable(ctx *context.Context) { if len(ctx.Repo.Units) > 0 { if ctx.Repo.Repository.IsBeingCreated() { @@ -660,7 +651,7 @@ func checkHomeCodeViewable(ctx *context.Context) { ctx.Data["Repo"] = ctx.Repo ctx.Data["MigrateTask"] = task - ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr) + ctx.Data["CloneAddr"], _ = util.SanitizeURL(cfg.CloneAddr) ctx.Data["Failed"] = task.Status == structs.TaskStatusFailed ctx.HTML(http.StatusOK, tplMigrating) return diff --git a/services/convert/mirror.go b/services/convert/mirror.go index f7a8e17fd0c9c..505110452616a 100644 --- a/services/convert/mirror.go +++ b/services/convert/mirror.go @@ -5,21 +5,16 @@ package convert import ( repo_model "code.gitea.io/gitea/models/repo" - "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" ) // ToPushMirror convert from repo_model.PushMirror and remoteAddress to api.TopicResponse func ToPushMirror(pm *repo_model.PushMirror) (*api.PushMirror, error) { repo := pm.GetRepository() - remoteAddress, err := getRemoteAddress(repo, pm.RemoteName) - if err != nil { - return nil, err - } return &api.PushMirror{ RepoName: repo.Name, RemoteName: pm.RemoteName, - RemoteAddress: remoteAddress, + RemoteAddress: pm.RemoteAddress, CreatedUnix: pm.CreatedUnix.FormatLong(), LastUpdateUnix: pm.LastUpdateUnix.FormatLong(), LastError: pm.LastError, @@ -27,13 +22,3 @@ func ToPushMirror(pm *repo_model.PushMirror) (*api.PushMirror, error) { SyncOnCommit: pm.SyncOnCommit, }, nil } - -func getRemoteAddress(repo *repo_model.Repository, remoteName string) (string, error) { - url, err := git.GetRemoteURL(git.DefaultContext, repo.RepoPath(), remoteName) - if err != nil { - return "", err - } - // remove confidential information - url.User = nil - return url.String(), nil -} diff --git a/templates/repo/header.tmpl b/templates/repo/header.tmpl index 984e9f044eb06..935060816cb22 100644 --- a/templates/repo/header.tmpl +++ b/templates/repo/header.tmpl @@ -37,8 +37,7 @@ {{end}}
{{if $.PullMirror}} - {{$address := MirrorRemoteAddress $.Context . $.PullMirror.GetRemoteName false}} - +
{{$.locale.Tr "repo.mirror_from"}} {{$.PullMirror.RemoteAddress}}
{{end}} {{if .IsFork}}
{{$.locale.Tr "repo.forked_from"}} {{.BaseRepo.FullName}}
{{end}} {{if .IsGenerated}}
{{$.locale.Tr "repo.generated_from"}} {{.TemplateRepo.FullName}}
{{end}} diff --git a/templates/repo/settings/options.tmpl b/templates/repo/settings/options.tmpl index 16944506f18b5..78700e05b7d8f 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -123,7 +123,7 @@ {{else if $isWorkingPullMirror}} - {{(MirrorRemoteAddress $.Context .Repository .PullMirror.GetRemoteName false).Address}} + {{.PullMirror.RemoteAddress}} {{$.locale.Tr "repo.settings.mirror_settings.direction.pull"}} {{DateTime "full" .PullMirror.UpdatedUnix}} @@ -200,8 +200,7 @@ {{range .PushMirrors}} - {{$address := MirrorRemoteAddress $.Context $.Repository .GetRemoteName true}} - {{$address.Address}} + {{.RemoteAddress}} {{$.locale.Tr "repo.settings.mirror_settings.direction.push"}} {{if .LastUpdateUnix}}{{DateTime "full" .LastUpdateUnix}}{{else}}{{$.locale.Tr "never"}}{{end}} {{if .LastError}}
{{$.locale.Tr "error"}}
{{end}} @@ -211,7 +210,7 @@ data-tooltip-content="{{$.locale.Tr "repo.settings.mirror_settings.push_mirror.edit_sync_time"}}" data-modal-push-mirror-edit-id="{{.ID}}" data-modal-push-mirror-edit-interval="{{.Interval}}" - data-modal-push-mirror-edit-address="{{$address.Address}}" + data-modal-push-mirror-edit-address="{{.RemoteAddress}}" > {{svg "octicon-pencil" 14}} From ed64f1c2b835bf9332bf8347be9675ef29c8274b Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Sat, 16 Sep 2023 19:42:34 +0200 Subject: [PATCH 20/23] Support `.git-blame-ignore-revs` file (#26395) Closes #26329 This PR adds the ability to ignore revisions specified in the `.git-blame-ignore-revs` file in the root of the repository. ![grafik](https://github.com/go-gitea/gitea/assets/1666336/9e91be0c-6e9c-431c-bbe9-5f80154251c8) The banner is displayed in this case. I intentionally did not add a UI way to bypass the ignore file (same behaviour as Github) but you can add `?bypass-blame-ignore=true` to the url manually. --------- Co-authored-by: wxiaoguang --- docs/content/usage/blame.en-us.md | 38 +++++ docs/static/octicon-versions.svg | 1 + modules/git/blame.go | 64 +++++++- modules/git/blame_test.go | 144 +++++++++++++++--- modules/git/tests/repos/repo6_blame/HEAD | 1 + modules/git/tests/repos/repo6_blame/config | 4 + .../31/bb4b42cecf0a98fc9a32fc5aaeaf53ec52643c | Bin 0 -> 98 bytes .../3b/0f66d8b065f8adbf2fef7d986528c655b98cb1 | Bin 0 -> 35 bytes .../45/fb6cbc12f970b04eacd5cd4165edd11c8d7376 | Bin 0 -> 167 bytes .../49/7701e5bb8676e419b93875d8f0808c7b31aed9 | Bin 0 -> 24 bytes .../54/4d8f7a3b15927cddf2299b4b562d6ebd71b6a7 | Bin 0 -> 175 bytes .../a8/9199e8dea077e4a8ba0bc01bc155275cfdd044 | Bin 0 -> 57 bytes .../af/7486bd54cfc39eea97207ca666aa69c9d6df93 | Bin 0 -> 134 bytes .../b8/d1ba1ccb58ee3744b3d1434aae7d26ce2d9421 | Bin 0 -> 54 bytes .../ca/411a3b842c3caec045772da42de16b3ffdafe8 | Bin 0 -> 54 bytes .../tests/repos/repo6_blame/refs/heads/master | 1 + options/locale/locale_en-US.ini | 2 + routers/web/repo/blame.go | 91 ++++++++--- templates/repo/blame.tmpl | 12 ++ 19 files changed, 306 insertions(+), 52 deletions(-) create mode 100644 docs/content/usage/blame.en-us.md create mode 100644 docs/static/octicon-versions.svg create mode 100644 modules/git/tests/repos/repo6_blame/HEAD create mode 100644 modules/git/tests/repos/repo6_blame/config create mode 100644 modules/git/tests/repos/repo6_blame/objects/31/bb4b42cecf0a98fc9a32fc5aaeaf53ec52643c create mode 100644 modules/git/tests/repos/repo6_blame/objects/3b/0f66d8b065f8adbf2fef7d986528c655b98cb1 create mode 100644 modules/git/tests/repos/repo6_blame/objects/45/fb6cbc12f970b04eacd5cd4165edd11c8d7376 create mode 100644 modules/git/tests/repos/repo6_blame/objects/49/7701e5bb8676e419b93875d8f0808c7b31aed9 create mode 100644 modules/git/tests/repos/repo6_blame/objects/54/4d8f7a3b15927cddf2299b4b562d6ebd71b6a7 create mode 100644 modules/git/tests/repos/repo6_blame/objects/a8/9199e8dea077e4a8ba0bc01bc155275cfdd044 create mode 100644 modules/git/tests/repos/repo6_blame/objects/af/7486bd54cfc39eea97207ca666aa69c9d6df93 create mode 100644 modules/git/tests/repos/repo6_blame/objects/b8/d1ba1ccb58ee3744b3d1434aae7d26ce2d9421 create mode 100644 modules/git/tests/repos/repo6_blame/objects/ca/411a3b842c3caec045772da42de16b3ffdafe8 create mode 100644 modules/git/tests/repos/repo6_blame/refs/heads/master diff --git a/docs/content/usage/blame.en-us.md b/docs/content/usage/blame.en-us.md new file mode 100644 index 0000000000000..7772bbc16d748 --- /dev/null +++ b/docs/content/usage/blame.en-us.md @@ -0,0 +1,38 @@ +--- +date: "2023-08-14T00:00:00+00:00" +title: "Blame File View" +slug: "blame" +sidebar_position: 13 +toc: false +draft: false +aliases: + - /en-us/blame +menu: + sidebar: + parent: "usage" + name: "Blame" + sidebar_position: 13 + identifier: "blame" +--- + +# Blame File View + +Gitea supports viewing the line-by-line revision history for a file also known as blame view. +You can also use [`git blame`](https://git-scm.com/docs/git-blame) on the command line to view the revision history of lines within a file. + +1. Navigate to and open the file whose line history you want to view. +1. Click the `Blame` button in the file header bar. +1. The new view shows the line-by-line revision history for a file with author and commit information on the left side. +1. To navigate to an older commit, click the ![versions](/octicon-versions.svg) icon. + +## Ignore commits in the blame view + +All revisions specified in the `.git-blame-ignore-revs` file are hidden from the blame view. +This is especially useful to hide reformatting changes and keep the benefits of `git blame`. +Lines that were changed or added by an ignored commit will be blamed on the previous commit that changed that line or nearby lines. +The `.git-blame-ignore-revs` file must be located in the root directory of the repository. +For more information like the file format, see [the `git blame --ignore-revs-file` documentation](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revs-fileltfilegt). + +### Bypassing `.git-blame-ignore-revs` in the blame view + +If the blame view for a file shows a message about ignored revisions, you can see the normal blame view by appending the url parameter `?bypass-blame-ignore=true`. diff --git a/docs/static/octicon-versions.svg b/docs/static/octicon-versions.svg new file mode 100644 index 0000000000000..aaf5f9cc2b25a --- /dev/null +++ b/docs/static/octicon-versions.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/modules/git/blame.go b/modules/git/blame.go index 4bd13dc32d27e..6728a6bed85f1 100644 --- a/modules/git/blame.go +++ b/modules/git/blame.go @@ -13,6 +13,7 @@ import ( "regexp" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/util" ) // BlamePart represents block of blame - continuous lines with one sha @@ -23,12 +24,16 @@ type BlamePart struct { // BlameReader returns part of file blame one by one type BlameReader struct { - cmd *Command output io.WriteCloser reader io.ReadCloser bufferedReader *bufio.Reader done chan error lastSha *string + ignoreRevsFile *string +} + +func (r *BlameReader) UsesIgnoreRevs() bool { + return r.ignoreRevsFile != nil } var shaLineRegex = regexp.MustCompile("^([a-z0-9]{40})") @@ -101,28 +106,44 @@ func (r *BlameReader) Close() error { r.bufferedReader = nil _ = r.reader.Close() _ = r.output.Close() + if r.ignoreRevsFile != nil { + _ = util.Remove(*r.ignoreRevsFile) + } return err } // CreateBlameReader creates reader for given repository, commit and file -func CreateBlameReader(ctx context.Context, repoPath, commitID, file string) (*BlameReader, error) { - cmd := NewCommandContextNoGlobals(ctx, "blame", "--porcelain"). - AddDynamicArguments(commitID). +func CreateBlameReader(ctx context.Context, repoPath string, commit *Commit, file string, bypassBlameIgnore bool) (*BlameReader, error) { + var ignoreRevsFile *string + if CheckGitVersionAtLeast("2.23") == nil && !bypassBlameIgnore { + ignoreRevsFile = tryCreateBlameIgnoreRevsFile(commit) + } + + cmd := NewCommandContextNoGlobals(ctx, "blame", "--porcelain") + if ignoreRevsFile != nil { + // Possible improvement: use --ignore-revs-file /dev/stdin on unix + // There is no equivalent on Windows. May be implemented if Gitea uses an external git backend. + cmd.AddOptionValues("--ignore-revs-file", *ignoreRevsFile) + } + cmd.AddDynamicArguments(commit.ID.String()). AddDashesAndList(file). SetDescription(fmt.Sprintf("GetBlame [repo_path: %s]", repoPath)) reader, stdout, err := os.Pipe() if err != nil { + if ignoreRevsFile != nil { + _ = util.Remove(*ignoreRevsFile) + } return nil, err } done := make(chan error, 1) - go func(cmd *Command, dir string, stdout io.WriteCloser, done chan error) { + go func() { stderr := bytes.Buffer{} // TODO: it doesn't work for directories (the directories shouldn't be "blamed"), and the "err" should be returned by "Read" but not by "Close" err := cmd.Run(&RunOpts{ UseContextTimeout: true, - Dir: dir, + Dir: repoPath, Stdout: stdout, Stderr: &stderr, }) @@ -131,15 +152,42 @@ func CreateBlameReader(ctx context.Context, repoPath, commitID, file string) (*B if err != nil { log.Error("Error running git blame (dir: %v): %v, stderr: %v", repoPath, err, stderr.String()) } - }(cmd, repoPath, stdout, done) + }() bufferedReader := bufio.NewReader(reader) return &BlameReader{ - cmd: cmd, output: stdout, reader: reader, bufferedReader: bufferedReader, done: done, + ignoreRevsFile: ignoreRevsFile, }, nil } + +func tryCreateBlameIgnoreRevsFile(commit *Commit) *string { + entry, err := commit.GetTreeEntryByPath(".git-blame-ignore-revs") + if err != nil { + return nil + } + + r, err := entry.Blob().DataAsync() + if err != nil { + return nil + } + defer r.Close() + + f, err := os.CreateTemp("", "gitea_git-blame-ignore-revs") + if err != nil { + return nil + } + + _, err = io.Copy(f, r) + _ = f.Close() + if err != nil { + _ = util.Remove(f.Name()) + return nil + } + + return util.ToPointer(f.Name()) +} diff --git a/modules/git/blame_test.go b/modules/git/blame_test.go index 1c0cd5c4aa20d..013350ac2f4eb 100644 --- a/modules/git/blame_test.go +++ b/modules/git/blame_test.go @@ -14,27 +14,127 @@ func TestReadingBlameOutput(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - blameReader, err := CreateBlameReader(ctx, "./tests/repos/repo5_pulls", "f32b0a9dfd09a60f616f29158f772cedd89942d2", "README.md") - assert.NoError(t, err) - defer blameReader.Close() - - parts := []*BlamePart{ - { - "72866af952e98d02a73003501836074b286a78f6", - []string{ - "# test_repo", - "Test repository for testing migration from github to gitea", - }, - }, - { - "f32b0a9dfd09a60f616f29158f772cedd89942d2", - []string{"", "Do not make any changes to this repo it is used for unit testing"}, - }, - } - - for _, part := range parts { - actualPart, err := blameReader.NextPart() + t.Run("Without .git-blame-ignore-revs", func(t *testing.T) { + repo, err := OpenRepository(ctx, "./tests/repos/repo5_pulls") assert.NoError(t, err) - assert.Equal(t, part, actualPart) - } + defer repo.Close() + + commit, err := repo.GetCommit("f32b0a9dfd09a60f616f29158f772cedd89942d2") + assert.NoError(t, err) + + parts := []*BlamePart{ + { + "72866af952e98d02a73003501836074b286a78f6", + []string{ + "# test_repo", + "Test repository for testing migration from github to gitea", + }, + }, + { + "f32b0a9dfd09a60f616f29158f772cedd89942d2", + []string{"", "Do not make any changes to this repo it is used for unit testing"}, + }, + } + + for _, bypass := range []bool{false, true} { + blameReader, err := CreateBlameReader(ctx, "./tests/repos/repo5_pulls", commit, "README.md", bypass) + assert.NoError(t, err) + assert.NotNil(t, blameReader) + defer blameReader.Close() + + assert.False(t, blameReader.UsesIgnoreRevs()) + + for _, part := range parts { + actualPart, err := blameReader.NextPart() + assert.NoError(t, err) + assert.Equal(t, part, actualPart) + } + + // make sure all parts have been read + actualPart, err := blameReader.NextPart() + assert.Nil(t, actualPart) + assert.NoError(t, err) + } + }) + + t.Run("With .git-blame-ignore-revs", func(t *testing.T) { + repo, err := OpenRepository(ctx, "./tests/repos/repo6_blame") + assert.NoError(t, err) + defer repo.Close() + + full := []*BlamePart{ + { + "af7486bd54cfc39eea97207ca666aa69c9d6df93", + []string{"line", "line"}, + }, + { + "45fb6cbc12f970b04eacd5cd4165edd11c8d7376", + []string{"changed line"}, + }, + { + "af7486bd54cfc39eea97207ca666aa69c9d6df93", + []string{"line", "line", ""}, + }, + } + + cases := []struct { + CommitID string + UsesIgnoreRevs bool + Bypass bool + Parts []*BlamePart + }{ + { + CommitID: "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7", + UsesIgnoreRevs: true, + Bypass: false, + Parts: []*BlamePart{ + { + "af7486bd54cfc39eea97207ca666aa69c9d6df93", + []string{"line", "line", "changed line", "line", "line", ""}, + }, + }, + }, + { + CommitID: "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7", + UsesIgnoreRevs: false, + Bypass: true, + Parts: full, + }, + { + CommitID: "45fb6cbc12f970b04eacd5cd4165edd11c8d7376", + UsesIgnoreRevs: false, + Bypass: false, + Parts: full, + }, + { + CommitID: "45fb6cbc12f970b04eacd5cd4165edd11c8d7376", + UsesIgnoreRevs: false, + Bypass: false, + Parts: full, + }, + } + + for _, c := range cases { + commit, err := repo.GetCommit(c.CommitID) + assert.NoError(t, err) + + blameReader, err := CreateBlameReader(ctx, "./tests/repos/repo6_blame", commit, "blame.txt", c.Bypass) + assert.NoError(t, err) + assert.NotNil(t, blameReader) + defer blameReader.Close() + + assert.Equal(t, c.UsesIgnoreRevs, blameReader.UsesIgnoreRevs()) + + for _, part := range c.Parts { + actualPart, err := blameReader.NextPart() + assert.NoError(t, err) + assert.Equal(t, part, actualPart) + } + + // make sure all parts have been read + actualPart, err := blameReader.NextPart() + assert.Nil(t, actualPart) + assert.NoError(t, err) + } + }) } diff --git a/modules/git/tests/repos/repo6_blame/HEAD b/modules/git/tests/repos/repo6_blame/HEAD new file mode 100644 index 0000000000000..cb089cd89a7d7 --- /dev/null +++ b/modules/git/tests/repos/repo6_blame/HEAD @@ -0,0 +1 @@ +ref: refs/heads/master diff --git a/modules/git/tests/repos/repo6_blame/config b/modules/git/tests/repos/repo6_blame/config new file mode 100644 index 0000000000000..07d359d07cf1e --- /dev/null +++ b/modules/git/tests/repos/repo6_blame/config @@ -0,0 +1,4 @@ +[core] + repositoryformatversion = 0 + filemode = true + bare = true diff --git a/modules/git/tests/repos/repo6_blame/objects/31/bb4b42cecf0a98fc9a32fc5aaeaf53ec52643c b/modules/git/tests/repos/repo6_blame/objects/31/bb4b42cecf0a98fc9a32fc5aaeaf53ec52643c new file mode 100644 index 0000000000000000000000000000000000000000..6cde9108e7ae046364b5594f4cce3bdff4a19875 GIT binary patch literal 98 zcmV-o0G&UL zdke~+tk}hUK>A>)dd%MoE>Im{#d;+bB@EX5X*V{c{#d(T|9$O@RE=YyJ9{<)0GWIz E0ukRT-T(jq literal 0 HcmV?d00001 diff --git a/modules/git/tests/repos/repo6_blame/objects/3b/0f66d8b065f8adbf2fef7d986528c655b98cb1 b/modules/git/tests/repos/repo6_blame/objects/3b/0f66d8b065f8adbf2fef7d986528c655b98cb1 new file mode 100644 index 0000000000000000000000000000000000000000..b8db01dc3571b63df1438da1e809c14f6144c81d GIT binary patch literal 35 rcmbY6Oq3cmxmd;Coa{ zxi#%v+O$Vkwy6SBKqNn=;Mg-M+i-}{2?ZyL{pfQR%9;$l+f+9g?%_802b@UC{JhjvUOd&h oPQ*)B^bFV^F}UQDg}p^<4gbcb|5$SsfpMjxUHdfi1%zffCT#*haR2}S literal 0 HcmV?d00001 diff --git a/modules/git/tests/repos/repo6_blame/objects/b8/d1ba1ccb58ee3744b3d1434aae7d26ce2d9421 b/modules/git/tests/repos/repo6_blame/objects/b8/d1ba1ccb58ee3744b3d1434aae7d26ce2d9421 new file mode 100644 index 0000000000000000000000000000000000000000..bb26889ed3fd09178b5a2be3af1bb428e43461f1 GIT binary patch literal 54 zcmV-60LlM&0V^p=O;s>9XD~D{Ff%bxNXkjfP1P%@C}FVXPrI=p^~c)%`tNIJq-q=s M-PyAd094=+>p#&LMF0Q* literal 0 HcmV?d00001 diff --git a/modules/git/tests/repos/repo6_blame/objects/ca/411a3b842c3caec045772da42de16b3ffdafe8 b/modules/git/tests/repos/repo6_blame/objects/ca/411a3b842c3caec045772da42de16b3ffdafe8 new file mode 100644 index 0000000000000000000000000000000000000000..1653ed9544617c25c22b3fdcedaea8a1b778d6dc GIT binary patch literal 54 zcmV-60LlM&0V^p=O;s>9XD~D{Ff%bxNXkjfP1P%@C}Hp{XMDQ5t?Y^9PK(kT9~ye9 M4cFZS08*e4;2ZcA>i_@% literal 0 HcmV?d00001 diff --git a/modules/git/tests/repos/repo6_blame/refs/heads/master b/modules/git/tests/repos/repo6_blame/refs/heads/master new file mode 100644 index 0000000000000..01c9922c5f586 --- /dev/null +++ b/modules/git/tests/repos/repo6_blame/refs/heads/master @@ -0,0 +1 @@ +544d8f7a3b15927cddf2299b4b562d6ebd71b6a7 diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index ad7d35127eb59..c38c9d9e4667d 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1007,6 +1007,8 @@ delete_preexisting = Delete pre-existing files delete_preexisting_content = Delete files in %s delete_preexisting_success = Deleted unadopted files in %s blame_prior = View blame prior to this change +blame.ignore_revs = Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view. +blame.ignore_revs.failed = Failed to ignore revisions in .git-blame-ignore-revs. author_search_tooltip = Shows a maximum of 30 users transfer.accept = Accept Transfer diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index b1cb42297c1a6..e4506a857e730 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -8,9 +8,9 @@ import ( gotemplate "html/template" "net/http" "net/url" + "strconv" "strings" - repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/charset" "code.gitea.io/gitea/modules/context" @@ -45,10 +45,6 @@ func RefBlame(ctx *context.Context) { return } - userName := ctx.Repo.Owner.Name - repoName := ctx.Repo.Repository.Name - commitID := ctx.Repo.CommitID - branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL() treeLink := branchLink rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL() @@ -101,26 +97,16 @@ func RefBlame(ctx *context.Context) { return } - blameReader, err := git.CreateBlameReader(ctx, repo_model.RepoPath(userName, repoName), commitID, fileName) + bypassBlameIgnore, _ := strconv.ParseBool(ctx.FormString("bypass-blame-ignore")) + + result, err := performBlame(ctx, ctx.Repo.Repository.RepoPath(), ctx.Repo.Commit, fileName, bypassBlameIgnore) if err != nil { ctx.NotFound("CreateBlameReader", err) return } - defer blameReader.Close() - - blameParts := make([]git.BlamePart, 0) - for { - blamePart, err := blameReader.NextPart() - if err != nil { - ctx.NotFound("NextPart", err) - return - } - if blamePart == nil { - break - } - blameParts = append(blameParts, *blamePart) - } + ctx.Data["UsesIgnoreRevs"] = result.UsesIgnoreRevs + ctx.Data["FaultyIgnoreRevsFile"] = result.FaultyIgnoreRevsFile // Get Topics of this repo renderRepoTopics(ctx) @@ -128,16 +114,77 @@ func RefBlame(ctx *context.Context) { return } - commitNames, previousCommits := processBlameParts(ctx, blameParts) + commitNames, previousCommits := processBlameParts(ctx, result.Parts) if ctx.Written() { return } - renderBlame(ctx, blameParts, commitNames, previousCommits) + renderBlame(ctx, result.Parts, commitNames, previousCommits) ctx.HTML(http.StatusOK, tplRepoHome) } +type blameResult struct { + Parts []git.BlamePart + UsesIgnoreRevs bool + FaultyIgnoreRevsFile bool +} + +func performBlame(ctx *context.Context, repoPath string, commit *git.Commit, file string, bypassBlameIgnore bool) (*blameResult, error) { + blameReader, err := git.CreateBlameReader(ctx, repoPath, commit, file, bypassBlameIgnore) + if err != nil { + return nil, err + } + + r := &blameResult{} + if err := fillBlameResult(blameReader, r); err != nil { + _ = blameReader.Close() + return nil, err + } + + err = blameReader.Close() + if err != nil { + if len(r.Parts) == 0 && r.UsesIgnoreRevs { + // try again without ignored revs + + blameReader, err = git.CreateBlameReader(ctx, repoPath, commit, file, true) + if err != nil { + return nil, err + } + + r := &blameResult{ + FaultyIgnoreRevsFile: true, + } + if err := fillBlameResult(blameReader, r); err != nil { + _ = blameReader.Close() + return nil, err + } + + return r, blameReader.Close() + } + return nil, err + } + return r, nil +} + +func fillBlameResult(br *git.BlameReader, r *blameResult) error { + r.UsesIgnoreRevs = br.UsesIgnoreRevs() + + r.Parts = make([]git.BlamePart, 0, 5) + for { + blamePart, err := br.NextPart() + if err != nil { + return fmt.Errorf("BlameReader.NextPart failed: %w", err) + } + if blamePart == nil { + break + } + r.Parts = append(r.Parts, *blamePart) + } + + return nil +} + func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) (map[string]*user_model.UserCommit, map[string]string) { // store commit data by SHA to look up avatar info etc commitNames := make(map[string]*user_model.UserCommit) diff --git a/templates/repo/blame.tmpl b/templates/repo/blame.tmpl index b253c4d90143b..3078e9bef3603 100644 --- a/templates/repo/blame.tmpl +++ b/templates/repo/blame.tmpl @@ -1,3 +1,15 @@ +{{if or .UsesIgnoreRevs .FaultyIgnoreRevsFile}} + {{$revsFileLink := URLJoin .RepoLink "src" .BranchNameSubURL "/.git-blame-ignore-revs"}} + {{if .UsesIgnoreRevs}} +
+

{{.locale.Tr "repo.blame.ignore_revs" $revsFileLink (print $revsFileLink "?bypass-blame-ignore=true") | Str2html}}

+
+ {{else}} +
+

{{.locale.Tr "repo.blame.ignore_revs.failed" $revsFileLink | Str2html}}

+
+ {{end}} +{{end}}

From ea83c0647c533fd2152ba014561d8c1d4420fa4a Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Sun, 17 Sep 2023 00:24:27 +0000 Subject: [PATCH 21/23] [skip ci] Updated translations via Crowdin --- options/locale/locale_pt-PT.ini | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/options/locale/locale_pt-PT.ini b/options/locale/locale_pt-PT.ini index 6bc1d9d06c4c3..eeb2a3ce8bfa1 100644 --- a/options/locale/locale_pt-PT.ini +++ b/options/locale/locale_pt-PT.ini @@ -203,7 +203,7 @@ db_name=Nome da base de dados db_schema=Esquema db_schema_helper=Deixe em branco para ficar o predefinido da base de dados ("público"). ssl_mode=SSL -path=Caminho +path=Localização sqlite_helper=Localização do ficheiro da base de dados em SQLite3.
Insira um caminho absoluto se corre o Gitea como um serviço. reinstall_error=Está a tentar instalar numa base de dados do Gitea já existente reinstall_confirm_message=Reinstalar com uma base de dados do Gitea já existente pode causar múltiplos problemas. Na maioria dos casos deve usar o seu "app.ini" existente para correr o Gitea. Se souber o que está a fazer, confirme o seguinte: @@ -278,7 +278,7 @@ sqlite3_not_available=Esta versão do Gitea não suporta o SQLite3. Descarregue invalid_db_setting=As configurações da base de dados são inválidas: %v invalid_db_table=A tabela "%s" da base de dados é inválida: %v invalid_repo_path=A localização base dos repositórios é inválida: %v -invalid_app_data_path=O caminho dos dados da aplicação é inválido: %v +invalid_app_data_path=A localização dos dados da aplicação é inválido: %v run_user_not_match=O nome de utilizador para 'executar como' não é o nome de utilizador corrente: %s → %s internal_token_failed=Falha ao gerar o código interno: %v secret_key_failed=Falha ao gerar a chave secreta: %v @@ -512,7 +512,7 @@ NewBranchName=Novo nome de ramo CommitSummary=Sumário do cometimento CommitMessage=Mensagem do cometimento CommitChoice=Escolha do cometimento -TreeName=Caminho do ficheiro +TreeName=Localização do ficheiro Content=Conteúdo SSPISeparatorReplacement=Separador @@ -842,7 +842,7 @@ create_oauth2_application_button=Criar aplicação create_oauth2_application_success=Criou com sucesso uma nova aplicação OAuth2. update_oauth2_application_success=Modificou com sucesso a aplicação OAuth2. oauth2_application_name=Nome da aplicação -oauth2_confidential_client=Cliente confidencial. Escolha para aplicações que mantêm o segredo confidencial, tais como aplicações web. Não escolha para aplicações nativas, incluindo aplicações para computador e aplicações móveis. +oauth2_confidential_client=Cliente confidencial. Escolha esta opção para aplicações que mantêm o segredo confidencial, tais como aplicações web. Não escolha esta opção para aplicações nativas, incluindo aplicações para computador e aplicações móveis. oauth2_redirect_uris=URIs de reencaminhamento. Use uma linha por URI. save_application=Guardar oauth2_client_id=ID do cliente @@ -1052,7 +1052,7 @@ migrate_options_mirror_helper=Este repositório irá ser uma réplica migrate_options_lfs=Migrar ficheiros LFS migrate_options_lfs_endpoint.label=Destino LFS migrate_options_lfs_endpoint.description=A migração irá tentar usar o seu controlo remoto do Git para determinar o servidor LFS. Também pode especificar um destino personalizado se os dados do repositório LFS forem armazenados noutro lugar. -migrate_options_lfs_endpoint.description.local=Um caminho de servidor local também é suportado. +migrate_options_lfs_endpoint.description.local=Uma localização de servidor local também é suportada. migrate_options_lfs_endpoint.placeholder=Se for deixado em branco, o destino será determinado a partir do URL do clone migrate_items=Itens da migração migrate_items_wiki=Wiki @@ -1066,10 +1066,10 @@ migrate_repo=Migrar o repositório migrate.clone_address=Migrar / clonar a partir do URL migrate.clone_address_desc=O URL de clonagem HTTP(S) ou Git de um repositório existente migrate.github_token_desc=Pode colocar aqui um ou mais códigos separados por vírgulas para tornar mais rápida a migração, para compensar a limitação de velocidade da API do GitHub. AVISO: O abuso desta funcionalidade poderá violar a política do seu fornecedor de serviço e levar ao bloqueio da conta. -migrate.clone_local_path=ou um caminho no servidor local +migrate.clone_local_path=ou uma localização no servidor local migrate.permission_denied=Não está autorizado a importar repositórios locais. migrate.permission_denied_blocked=Não pode importar de servidores não permitidos, por favor peça ao administrador para verificar as configurações ALLOWED_DOMAINS/ALLOW_LOCALNETWORKS/BLOCKED_DOMAINS. -migrate.invalid_local_path=O caminho local é inválido. Não existe ou não é uma pasta. +migrate.invalid_local_path=A localização local é inválida. Não existe ou não é uma pasta. migrate.invalid_lfs_endpoint=O destino LFS não é válido. migrate.failed=A migração falhou: %v migrate.migrate_items_options=É necessário um código de acesso para migrar itens adicionais @@ -2357,16 +2357,16 @@ settings.lfs_filelist=Ficheiros LFS armazenados neste repositório settings.lfs_no_lfs_files=Não existem quaisquer ficheiros LFS armazenados neste repositório settings.lfs_findcommits=Procurar cometimentos settings.lfs_lfs_file_no_commits=Não foram encontrados quaisquer cometimentos para este ficheiro LFS -settings.lfs_noattribute=Este caminho não tem o atributo bloqueável no ramo principal +settings.lfs_noattribute=Esta localização não tem o atributo bloqueável no ramo principal settings.lfs_delete=Eliminar ficheiro LFS com o OID %s settings.lfs_delete_warning=Eliminar um ficheiro LFS pode causar erros do tipo 'elemento não existe' no checkout. Tem a certeza? settings.lfs_findpointerfiles=Procurar ficheiros apontadores settings.lfs_locks=Bloqueios -settings.lfs_invalid_locking_path=Caminho inválido: %s +settings.lfs_invalid_locking_path=Localização inválida: %s settings.lfs_invalid_lock_directory=Não foi possível bloquear a pasta: %s settings.lfs_lock_already_exists=Já existe um bloqueio: %s settings.lfs_lock=Bloquear -settings.lfs_lock_path=Caminho de ficheiro a bloquear... +settings.lfs_lock_path=Localização do ficheiro a bloquear... settings.lfs_locks_no_locks=Sem bloqueios settings.lfs_lock_file_no_exist=O ficheiro bloqueado não existe no ramo principal settings.lfs_force_unlock=Forçar desbloqueio @@ -2731,6 +2731,7 @@ dashboard.reinit_missing_repos=Reinicializar todos os repositórios Git em falta dashboard.sync_external_users=Sincronizar dados externos do utilizador dashboard.cleanup_hook_task_table=Limpar tabela hook_task dashboard.cleanup_packages=Limpar pacotes expirados +dashboard.cleanup_actions=Registos expirados e artefactos das operações de limpeza dashboard.server_uptime=Tempo em funcionamento contínuo do servidor dashboard.current_goroutine=Goroutines em execução dashboard.current_memory_usage=Utilização de memória corrente @@ -2768,6 +2769,7 @@ dashboard.gc_lfs=Recolher lixo dos meta-elementos LFS dashboard.stop_zombie_tasks=Parar tarefas zombies dashboard.stop_endless_tasks=Parar tarefas intermináveis dashboard.cancel_abandoned_jobs=Cancelar trabalhos abandonados +dashboard.start_schedule_tasks=Iniciar tarefas de agendamento dashboard.sync_branch.started=Sincronização de ramos iniciada dashboard.rebuild_issue_indexer=Reconstruir indexador de questões @@ -3007,7 +3009,7 @@ config.server_config=Configuração do servidor config.app_name=Título do sítio config.app_ver=Versão do Gitea config.app_url=URL base do Gitea -config.custom_conf=Caminho do ficheiro de configuração +config.custom_conf=Localização do ficheiro de configuração config.custom_file_root_path=Localização dos ficheiros personalizados config.domain=Domínio do servidor config.offline_mode=Modo local @@ -3015,7 +3017,7 @@ config.disable_router_log=Desabilitar registos do encaminhador config.run_user=Executa com este nome de utilizador config.run_mode=Modo de execução config.git_version=Versão do Git -config.app_data_path=Adicionar caminho dos dados +config.app_data_path=Localização dos dados da aplicação config.repo_root_path=Localização dos repositórios config.lfs_root_path=Localização dos LFS config.log_file_root_path=Localização dos registos @@ -3046,7 +3048,7 @@ config.db_name=Nome config.db_user=Nome de utilizador config.db_schema=Esquema config.db_ssl_mode=SSL -config.db_path=Caminho +config.db_path=Localização config.service_config=Configuração do serviço config.register_email_confirm=Exigir confirmação de email para se inscrever @@ -3085,7 +3087,7 @@ config.mailer_smtp_addr=Endereço SMTP config.mailer_smtp_port=Porto do SMTP config.mailer_user=Utilizador config.mailer_use_sendmail=Usar o sendmail -config.mailer_sendmail_path=Caminho do sendmail +config.mailer_sendmail_path=Localização do sendmail config.mailer_sendmail_args=Argumentos extras para o sendmail config.mailer_sendmail_timeout=Tempo limite do Sendmail config.mailer_use_dummy=Fictício @@ -3199,7 +3201,7 @@ notices.delete_success=As notificações do sistema foram eliminadas. [action] create_repo=criou o repositório %s rename_repo=renomeou o repositório de %[1]s para %[3]s -commit_repo=enviado para %[3]s em %[4]s +commit_repo=enviou para %[3]s em %[4]s create_issue=`abriu a questão %[3]s#%[2]s` close_issue=`fechou a questão %[3]s#%[2]s` reopen_issue=`reabriu a questão %[3]s#%[2]s` From dcf4b9e3146db7bb8359538acb7c5fbd6fce9e6f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 17 Sep 2023 11:15:04 +0800 Subject: [PATCH 22/23] Fix wrong migration for email address (#27106) On Iterate, `sess` should not be used in the closure function body. Caused by #26952 --- models/migrations/v1_21/v276.go | 88 ++++++++++++++++++++++++++------- 1 file changed, 70 insertions(+), 18 deletions(-) diff --git a/models/migrations/v1_21/v276.go b/models/migrations/v1_21/v276.go index 8933f186dc04e..8746c8851e63a 100644 --- a/models/migrations/v1_21/v276.go +++ b/models/migrations/v1_21/v276.go @@ -50,19 +50,45 @@ func migratePullMirrors(x *xorm.Engine) error { return err } - if err := sess.Iterate(new(Mirror), func(_ int, bean any) error { - m := bean.(*Mirror) - remoteAddress, err := getRemoteAddress(sess, m.RepoID, "origin") - if err != nil { + limit := setting.Database.IterateBufferSize + if limit <= 0 { + limit = 50 + } + + start := 0 + + for { + var mirrors []Mirror + if err := sess.Limit(limit, start).Find(&mirrors); err != nil { return err } - m.RemoteAddress = remoteAddress + if len(mirrors) == 0 { + break + } + start += len(mirrors) - _, err = sess.ID(m.ID).Cols("remote_address").Update(m) - return err - }); err != nil { - return err + for _, m := range mirrors { + remoteAddress, err := getRemoteAddress(sess, m.RepoID, "origin") + if err != nil { + return err + } + + m.RemoteAddress = remoteAddress + + if _, err = sess.ID(m.ID).Cols("remote_address").Update(m); err != nil { + return err + } + } + + if start%1000 == 0 { // avoid a too big transaction + if err := sess.Commit(); err != nil { + return err + } + if err := sess.Begin(); err != nil { + return err + } + } } return sess.Commit() @@ -83,19 +109,45 @@ func migratePushMirrors(x *xorm.Engine) error { return err } - if err := sess.Iterate(new(PushMirror), func(_ int, bean any) error { - m := bean.(*PushMirror) - remoteAddress, err := getRemoteAddress(sess, m.RepoID, m.RemoteName) - if err != nil { + limit := setting.Database.IterateBufferSize + if limit <= 0 { + limit = 50 + } + + start := 0 + + for { + var mirrors []PushMirror + if err := sess.Limit(limit, start).Find(&mirrors); err != nil { return err } - m.RemoteAddress = remoteAddress + if len(mirrors) == 0 { + break + } + start += len(mirrors) - _, err = sess.ID(m.ID).Cols("remote_address").Update(m) - return err - }); err != nil { - return err + for _, m := range mirrors { + remoteAddress, err := getRemoteAddress(sess, m.RepoID, m.RemoteName) + if err != nil { + return err + } + + m.RemoteAddress = remoteAddress + + if _, err = sess.ID(m.ID).Cols("remote_address").Update(m); err != nil { + return err + } + } + + if start%1000 == 0 { // avoid a too big transaction + if err := sess.Commit(); err != nil { + return err + } + if err := sess.Begin(); err != nil { + return err + } + } } return sess.Commit() From 47b878858ada27fc4c74eeadcc1e467d2da90e04 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 17 Sep 2023 16:24:40 +0800 Subject: [PATCH 23/23] Search branches (#27055) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve #25233 图片 图片 --- models/git/branch_list.go | 4 ++++ options/locale/locale_en-US.ini | 1 + routers/web/repo/branch.go | 5 ++++- services/repository/branch.go | 3 ++- templates/repo/branch/list.tmpl | 15 +++++++++++++-- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/models/git/branch_list.go b/models/git/branch_list.go index 131a149782e27..b5c1301a1dc00 100644 --- a/models/git/branch_list.go +++ b/models/git/branch_list.go @@ -70,6 +70,7 @@ type FindBranchOptions struct { ExcludeBranchNames []string IsDeletedBranch util.OptionalBool OrderBy string + Keyword string } func (opts *FindBranchOptions) Cond() builder.Cond { @@ -84,6 +85,9 @@ func (opts *FindBranchOptions) Cond() builder.Cond { if !opts.IsDeletedBranch.IsNone() { cond = cond.And(builder.Eq{"is_deleted": opts.IsDeletedBranch.IsTrue()}) } + if opts.Keyword != "" { + cond = cond.And(builder.Like{"name", opts.Keyword}) + } return cond } diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index c38c9d9e4667d..e11d5167aa769 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -2515,6 +2515,7 @@ branch.default_deletion_failed = Branch "%s" is the default branch. It cannot be branch.restore = Restore Branch "%s" branch.download = Download Branch "%s" branch.rename = Rename Branch "%s" +branch.search = Search Branch branch.included_desc = This branch is part of the default branch branch.included = Included branch.create_new_branch = Create branch from branch: diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index f5831df28f6ad..e0e27fd4823ce 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -51,7 +51,9 @@ func Branches(ctx *context.Context) { } pageSize := setting.Git.BranchesRangeSize - defaultBranch, branches, branchesCount, err := repo_service.LoadBranches(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, util.OptionalBoolNone, page, pageSize) + kw := ctx.FormString("q") + + defaultBranch, branches, branchesCount, err := repo_service.LoadBranches(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, util.OptionalBoolNone, kw, page, pageSize) if err != nil { ctx.ServerError("LoadBranches", err) return @@ -73,6 +75,7 @@ func Branches(ctx *context.Context) { commitStatus[commitID] = git_model.CalcCommitStatus(cs) } + ctx.Data["Keyword"] = kw ctx.Data["Branches"] = branches ctx.Data["CommitStatus"] = commitStatus ctx.Data["CommitStatuses"] = commitStatuses diff --git a/services/repository/branch.go b/services/repository/branch.go index 620e0b6c9f699..011dc5568ec0a 100644 --- a/services/repository/branch.go +++ b/services/repository/branch.go @@ -66,7 +66,7 @@ type Branch struct { } // LoadBranches loads branches from the repository limited by page & pageSize. -func LoadBranches(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, isDeletedBranch util.OptionalBool, page, pageSize int) (*Branch, []*Branch, int64, error) { +func LoadBranches(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, isDeletedBranch util.OptionalBool, keyword string, page, pageSize int) (*Branch, []*Branch, int64, error) { defaultDBBranch, err := git_model.GetBranch(ctx, repo.ID, repo.DefaultBranch) if err != nil { return nil, nil, 0, err @@ -79,6 +79,7 @@ func LoadBranches(ctx context.Context, repo *repo_model.Repository, gitRepo *git Page: page, PageSize: pageSize, }, + Keyword: keyword, } totalNumOfBranches, err := git_model.CountBranches(ctx, branchOpts) diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl index d2535e1e307fc..f309b1c60a623 100644 --- a/templates/repo/branch/list.tmpl +++ b/templates/repo/branch/list.tmpl @@ -70,9 +70,20 @@ {{end}} {{if .Branches}} -

- {{.locale.Tr "repo.branches"}} +

+
+ {{.locale.Tr "repo.branches"}} +
+
+
+ + +
+

+