From f5998140013850f386329796bb707d92091badce Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Tue, 12 Sep 2023 00:21:32 +0000 Subject: [PATCH 001/289] [skip ci] Updated translations via Crowdin --- options/locale/locale_fr-FR.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index 19e2d97dc6..ec1babb176 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -1612,7 +1612,7 @@ issues.dependency.add_error_cannot_create_circular=Vous ne pouvez pas créer une issues.dependency.add_error_dep_not_same_repo=Les deux tickets doivent être dans le même dépôt. issues.review.self.approval=Vous ne pouvez approuver vos propres demandes d'ajout. issues.review.self.rejection=Vous ne pouvez demander de changements sur vos propres demandes de changement. -issues.review.approve=ces changements ont été approuvés %s +issues.review.approve=a approuvé ces modifications %s. issues.review.comment=a évalué cette demande d’ajout %s. issues.review.dismissed=a révoqué l’évaluation de %s %s. issues.review.dismissed_label=Révoquée From 7818121d50fd9ce3739c3d2221402841781e04b9 Mon Sep 17 00:00:00 2001 From: Earl Warren <109468362+earl-warren@users.noreply.github.com> Date: Tue, 12 Sep 2023 04:19:39 +0200 Subject: [PATCH 002/289] S3: log human readable error on connection failure (#26856) Should BucketExists (HeadBucket) fail because of an error related to the connection rather than the existence of the bucket, no information is available and the admin is left guessing. https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadBucket.html > This action is useful to determine if a bucket exists and you have > permission to access it. The action returns a 200 OK if the bucket > exists and you have permission to access it. > > If the bucket does not exist or you do not have permission to access > it, the HEAD request returns a generic 400 Bad Request, 403 > Forbidden or 404 Not Found code. A message body is not included, so > you cannot determine the exception beyond these error codes. GetBucketVersioning is used instead and exclusively dedicated to asserting if using the connection does not return a BadRequest. If it does the NewMinioStorage logs an error and returns. Otherwise it keeps going knowing that BucketExists is not going to fail for reasons unrelated to the existence of the bucket and the permissions to access it. (cherry picked from commit d1df4b3bc62e5e61893a923f1c4b58f084eb03af) Refs: https://codeberg.org/forgejo/forgejo/issues/1338 --- modules/storage/minio.go | 22 ++++++++++++++++++++++ modules/storage/minio_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/modules/storage/minio.go b/modules/storage/minio.go index 3246993bb1..714530ab50 100644 --- a/modules/storage/minio.go +++ b/modules/storage/minio.go @@ -71,6 +71,11 @@ func convertMinioErr(err error) error { return err } +var getBucketVersioning = func(ctx context.Context, minioClient *minio.Client, bucket string) error { + _, err := minioClient.GetBucketVersioning(ctx, bucket) + return err +} + // NewMinioStorage returns a minio storage func NewMinioStorage(ctx context.Context, cfg *setting.Storage) (ObjectStorage, error) { config := cfg.MinioConfig @@ -90,6 +95,23 @@ func NewMinioStorage(ctx context.Context, cfg *setting.Storage) (ObjectStorage, return nil, convertMinioErr(err) } + // The GetBucketVersioning is only used for checking whether the Object Storage parameters are generally good. It doesn't need to succeed. + // The assumption is that if the API returns the HTTP code 400, then the parameters could be incorrect. + // Otherwise even if the request itself fails (403, 404, etc), the code should still continue because the parameters seem "good" enough. + // Keep in mind that GetBucketVersioning requires "owner" to really succeed, so it can't be used to check the existence. + // Not using "BucketExists (HeadBucket)" because it doesn't include detailed failure reasons. + err = getBucketVersioning(ctx, minioClient, config.Bucket) + if err != nil { + errResp, ok := err.(minio.ErrorResponse) + if !ok { + return nil, err + } + if errResp.StatusCode == http.StatusBadRequest { + log.Error("S3 storage connection failure at %s:%s with base path %s and region: %s", config.Endpoint, config.Bucket, config.Location, errResp.Message) + return nil, err + } + } + // Check to see if we already own this bucket exists, err := minioClient.BucketExists(ctx, config.Bucket) if err != nil { diff --git a/modules/storage/minio_test.go b/modules/storage/minio_test.go index af392b7e22..56dfd9100a 100644 --- a/modules/storage/minio_test.go +++ b/modules/storage/minio_test.go @@ -4,10 +4,15 @@ package storage import ( + "context" + "net/http" "os" "testing" "code.gitea.io/gitea/modules/setting" + + "github.com/minio/minio-go/v7" + "github.com/stretchr/testify/assert" ) func TestMinioStorageIterator(t *testing.T) { @@ -25,3 +30,31 @@ func TestMinioStorageIterator(t *testing.T) { }, }) } + +func TestS3StorageBadRequest(t *testing.T) { + if os.Getenv("CI") == "" { + t.Skip("S3Storage not present outside of CI") + return + } + cfg := &setting.Storage{ + MinioConfig: setting.MinioStorageConfig{ + Endpoint: "minio:9000", + AccessKeyID: "123456", + SecretAccessKey: "12345678", + Bucket: "bucket", + Location: "us-east-1", + }, + } + message := "ERROR" + old := getBucketVersioning + defer func() { getBucketVersioning = old }() + getBucketVersioning = func(ctx context.Context, minioClient *minio.Client, bucket string) error { + return minio.ErrorResponse{ + StatusCode: http.StatusBadRequest, + Code: "FixtureError", + Message: message, + } + } + _, err := NewStorage(setting.MinioStorageType, cfg) + assert.ErrorContains(t, err, message) +} From 591f586bf1c40114451284318a8c4f37e196a51a Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Tue, 12 Sep 2023 08:15:16 +0200 Subject: [PATCH 003/289] Extract auth middleware from service (#27028) Related #27027 Extract the router logic from `services/auth/middleware.go` into `routers/web` <-> `routers/common` <-> `routers/api`. --- routers/api/v1/api.go | 105 ++++++++++++++- routers/common/auth.go | 45 +++++++ routers/web/web.go | 123 +++++++++++++++-- services/auth/middleware.go | 255 ------------------------------------ 4 files changed, 262 insertions(+), 266 deletions(-) create mode 100644 routers/common/auth.go delete mode 100644 services/auth/middleware.go diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 757b406799..fd7d3687ac 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -90,6 +90,7 @@ import ( "code.gitea.io/gitea/routers/api/v1/repo" "code.gitea.io/gitea/routers/api/v1/settings" "code.gitea.io/gitea/routers/api/v1/user" + "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/services/auth" context_service "code.gitea.io/gitea/services/context" "code.gitea.io/gitea/services/forms" @@ -709,6 +710,106 @@ func buildAuthGroup() *auth.Group { return group } +func apiAuth(authMethod auth.Method) func(*context.APIContext) { + return func(ctx *context.APIContext) { + ar, err := common.AuthShared(ctx.Base, nil, authMethod) + if err != nil { + ctx.Error(http.StatusUnauthorized, "APIAuth", err) + return + } + ctx.Doer = ar.Doer + ctx.IsSigned = ar.Doer != nil + ctx.IsBasicAuth = ar.IsBasicAuth + } +} + +// verifyAuthWithOptions checks authentication according to options +func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.APIContext) { + return func(ctx *context.APIContext) { + // Check prohibit login users. + if ctx.IsSigned { + if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { + ctx.Data["Title"] = ctx.Tr("auth.active_your_account") + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "This account is not activated.", + }) + return + } + if !ctx.Doer.IsActive || ctx.Doer.ProhibitLogin { + log.Info("Failed authentication attempt for %s from %s", ctx.Doer.Name, ctx.RemoteAddr()) + ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "This account is prohibited from signing in, please contact your site administrator.", + }) + return + } + + if ctx.Doer.MustChangePassword { + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "You must change your password. Change it at: " + setting.AppURL + "/user/change_password", + }) + return + } + } + + // Redirect to dashboard if user tries to visit any non-login page. + if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" { + ctx.Redirect(setting.AppSubURL + "/") + return + } + + if options.SignInRequired { + if !ctx.IsSigned { + // Restrict API calls with error message. + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "Only signed in user is allowed to call APIs.", + }) + return + } else if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { + ctx.Data["Title"] = ctx.Tr("auth.active_your_account") + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "This account is not activated.", + }) + return + } + if ctx.IsSigned && ctx.IsBasicAuth { + if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) { + return // Skip 2FA + } + twofa, err := auth_model.GetTwoFactorByUID(ctx.Doer.ID) + if err != nil { + if auth_model.IsErrTwoFactorNotEnrolled(err) { + return // No 2FA enrollment for this user + } + ctx.InternalServerError(err) + return + } + otpHeader := ctx.Req.Header.Get("X-Gitea-OTP") + ok, err := twofa.ValidateTOTP(otpHeader) + if err != nil { + ctx.InternalServerError(err) + return + } + if !ok { + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "Only signed in user is allowed to call APIs.", + }) + return + } + } + } + + if options.AdminRequired { + if !ctx.Doer.IsAdmin { + ctx.JSON(http.StatusForbidden, map[string]string{ + "message": "You have no permission to request for this.", + }) + return + } + } + } +} + // Routes registers all v1 APIs routes to web application. func Routes() *web.Route { m := web.NewRoute() @@ -728,9 +829,9 @@ func Routes() *web.Route { m.Use(context.APIContexter()) // Get user from session if logged in. - m.Use(auth.APIAuth(buildAuthGroup())) + m.Use(apiAuth(buildAuthGroup())) - m.Use(auth.VerifyAuthWithOptionsAPI(&auth.VerifyOptions{ + m.Use(verifyAuthWithOptions(&common.VerifyOptions{ SignInRequired: setting.Service.RequireSignInView, })) diff --git a/routers/common/auth.go b/routers/common/auth.go new file mode 100644 index 0000000000..8904785d51 --- /dev/null +++ b/routers/common/auth.go @@ -0,0 +1,45 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package common + +import ( + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/web/middleware" + auth_service "code.gitea.io/gitea/services/auth" +) + +type AuthResult struct { + Doer *user_model.User + IsBasicAuth bool +} + +func AuthShared(ctx *context.Base, sessionStore auth_service.SessionStore, authMethod auth_service.Method) (ar AuthResult, err error) { + ar.Doer, err = authMethod.Verify(ctx.Req, ctx.Resp, ctx, sessionStore) + if err != nil { + return ar, err + } + if ar.Doer != nil { + if ctx.Locale.Language() != ar.Doer.Language { + ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req) + } + ar.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == auth_service.BasicMethodName + + ctx.Data["IsSigned"] = true + ctx.Data[middleware.ContextDataKeySignedUser] = ar.Doer + ctx.Data["SignedUserID"] = ar.Doer.ID + ctx.Data["IsAdmin"] = ar.Doer.IsAdmin + } else { + ctx.Data["SignedUserID"] = int64(0) + } + return ar, nil +} + +// VerifyOptions contains required or check options +type VerifyOptions struct { + SignInRequired bool + SignOutRequired bool + AdminRequired bool + DisableCSRF bool +} diff --git a/routers/web/web.go b/routers/web/web.go index ec6742f6ce..077a076864 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -6,6 +6,7 @@ package web import ( gocontext "context" "net/http" + "strings" "code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/unit" @@ -19,6 +20,7 @@ import ( "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/modules/web/middleware" "code.gitea.io/gitea/modules/web/routing" "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/routers/web/admin" @@ -46,7 +48,7 @@ import ( "gitea.com/go-chi/captcha" "github.com/NYTimes/gziphandler" - "github.com/go-chi/chi/v5/middleware" + chi_middleware "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" "github.com/prometheus/client_golang/prometheus" ) @@ -95,6 +97,109 @@ func buildAuthGroup() *auth_service.Group { return group } +func webAuth(authMethod auth_service.Method) func(*context.Context) { + return func(ctx *context.Context) { + ar, err := common.AuthShared(ctx.Base, ctx.Session, authMethod) + if err != nil { + log.Error("Failed to verify user: %v", err) + ctx.Error(http.StatusUnauthorized, "Verify") + return + } + ctx.Doer = ar.Doer + ctx.IsSigned = ar.Doer != nil + ctx.IsBasicAuth = ar.IsBasicAuth + if ctx.Doer == nil { + // ensure the session uid is deleted + _ = ctx.Session.Delete("uid") + } + } +} + +// verifyAuthWithOptions checks authentication according to options +func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.Context) { + return func(ctx *context.Context) { + // Check prohibit login users. + if ctx.IsSigned { + if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { + ctx.Data["Title"] = ctx.Tr("auth.active_your_account") + ctx.HTML(http.StatusOK, "user/auth/activate") + return + } + if !ctx.Doer.IsActive || ctx.Doer.ProhibitLogin { + log.Info("Failed authentication attempt for %s from %s", ctx.Doer.Name, ctx.RemoteAddr()) + ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") + ctx.HTML(http.StatusOK, "user/auth/prohibit_login") + return + } + + if ctx.Doer.MustChangePassword { + if ctx.Req.URL.Path != "/user/settings/change_password" { + if strings.HasPrefix(ctx.Req.UserAgent(), "git") { + ctx.Error(http.StatusUnauthorized, ctx.Tr("auth.must_change_password")) + return + } + ctx.Data["Title"] = ctx.Tr("auth.must_change_password") + ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password" + if ctx.Req.URL.Path != "/user/events" { + middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI()) + } + ctx.Redirect(setting.AppSubURL + "/user/settings/change_password") + return + } + } else if ctx.Req.URL.Path == "/user/settings/change_password" { + // make sure that the form cannot be accessed by users who don't need this + ctx.Redirect(setting.AppSubURL + "/") + return + } + } + + // Redirect to dashboard (or alternate location) if user tries to visit any non-login page. + if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" { + ctx.RedirectToFirst(ctx.FormString("redirect_to")) + return + } + + if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" { + ctx.Csrf.Validate(ctx) + if ctx.Written() { + return + } + } + + if options.SignInRequired { + if !ctx.IsSigned { + if ctx.Req.URL.Path != "/user/events" { + middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI()) + } + ctx.Redirect(setting.AppSubURL + "/user/login") + return + } else if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { + ctx.Data["Title"] = ctx.Tr("auth.active_your_account") + ctx.HTML(http.StatusOK, "user/auth/activate") + return + } + } + + // Redirect to log in page if auto-signin info is provided and has not signed in. + if !options.SignOutRequired && !ctx.IsSigned && + len(ctx.GetSiteCookie(setting.CookieUserName)) > 0 { + if ctx.Req.URL.Path != "/user/events" { + middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI()) + } + ctx.Redirect(setting.AppSubURL + "/user/login") + return + } + + if options.AdminRequired { + if !ctx.Doer.IsAdmin { + ctx.Error(http.StatusForbidden) + return + } + ctx.Data["PageIsAdmin"] = true + } + } +} + func ctxDataSet(args ...any) func(ctx *context.Context) { return func(ctx *context.Context) { for i := 0; i < len(args); i += 2 { @@ -144,10 +249,10 @@ func Routes() *web.Route { mid = append(mid, common.Sessioner(), context.Contexter()) // Get user from session if logged in. - mid = append(mid, auth_service.Auth(buildAuthGroup())) + mid = append(mid, webAuth(buildAuthGroup())) // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route - mid = append(mid, middleware.GetHead) + mid = append(mid, chi_middleware.GetHead) if setting.API.EnableSwagger { // Note: The route is here but no in API routes because it renders a web page @@ -168,12 +273,12 @@ func Routes() *web.Route { // registerRoutes register routes func registerRoutes(m *web.Route) { - reqSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: true}) - reqSignOut := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignOutRequired: true}) + reqSignIn := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: true}) + reqSignOut := verifyAuthWithOptions(&common.VerifyOptions{SignOutRequired: true}) // TODO: rename them to "optSignIn", which means that the "sign-in" could be optional, depends on the VerifyOptions (RequireSignInView) - ignSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: setting.Service.RequireSignInView}) - ignExploreSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: setting.Service.RequireSignInView || setting.Service.Explore.RequireSigninView}) - ignSignInAndCsrf := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{DisableCSRF: true}) + ignSignIn := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: setting.Service.RequireSignInView}) + ignExploreSignIn := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: setting.Service.RequireSignInView || setting.Service.Explore.RequireSigninView}) + ignSignInAndCsrf := verifyAuthWithOptions(&common.VerifyOptions{DisableCSRF: true}) validation.AddBindingRules() linkAccountEnabled := func(ctx *context.Context) { @@ -543,7 +648,7 @@ func registerRoutes(m *web.Route) { m.Get("/avatar/{hash}", user.AvatarByEmailHash) - adminReq := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: true, AdminRequired: true}) + adminReq := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: true, AdminRequired: true}) // ***** START: Admin ***** m.Group("/admin", func() { diff --git a/services/auth/middleware.go b/services/auth/middleware.go deleted file mode 100644 index 4a0b613fa6..0000000000 --- a/services/auth/middleware.go +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package auth - -import ( - "net/http" - "strings" - - "code.gitea.io/gitea/models/auth" - user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/web/middleware" -) - -// Auth is a middleware to authenticate a web user -func Auth(authMethod Method) func(*context.Context) { - return func(ctx *context.Context) { - ar, err := authShared(ctx.Base, ctx.Session, authMethod) - if err != nil { - log.Error("Failed to verify user: %v", err) - ctx.Error(http.StatusUnauthorized, "Verify") - return - } - ctx.Doer = ar.Doer - ctx.IsSigned = ar.Doer != nil - ctx.IsBasicAuth = ar.IsBasicAuth - if ctx.Doer == nil { - // ensure the session uid is deleted - _ = ctx.Session.Delete("uid") - } - } -} - -// APIAuth is a middleware to authenticate an api user -func APIAuth(authMethod Method) func(*context.APIContext) { - return func(ctx *context.APIContext) { - ar, err := authShared(ctx.Base, nil, authMethod) - if err != nil { - ctx.Error(http.StatusUnauthorized, "APIAuth", err) - return - } - ctx.Doer = ar.Doer - ctx.IsSigned = ar.Doer != nil - ctx.IsBasicAuth = ar.IsBasicAuth - } -} - -type authResult struct { - Doer *user_model.User - IsBasicAuth bool -} - -func authShared(ctx *context.Base, sessionStore SessionStore, authMethod Method) (ar authResult, err error) { - ar.Doer, err = authMethod.Verify(ctx.Req, ctx.Resp, ctx, sessionStore) - if err != nil { - return ar, err - } - if ar.Doer != nil { - if ctx.Locale.Language() != ar.Doer.Language { - ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req) - } - ar.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == BasicMethodName - - ctx.Data["IsSigned"] = true - ctx.Data[middleware.ContextDataKeySignedUser] = ar.Doer - ctx.Data["SignedUserID"] = ar.Doer.ID - ctx.Data["IsAdmin"] = ar.Doer.IsAdmin - } else { - ctx.Data["SignedUserID"] = int64(0) - } - return ar, nil -} - -// VerifyOptions contains required or check options -type VerifyOptions struct { - SignInRequired bool - SignOutRequired bool - AdminRequired bool - DisableCSRF bool -} - -// VerifyAuthWithOptions checks authentication according to options -func VerifyAuthWithOptions(options *VerifyOptions) func(ctx *context.Context) { - return func(ctx *context.Context) { - // Check prohibit login users. - if ctx.IsSigned { - if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.HTML(http.StatusOK, "user/auth/activate") - return - } - if !ctx.Doer.IsActive || ctx.Doer.ProhibitLogin { - log.Info("Failed authentication attempt for %s from %s", ctx.Doer.Name, ctx.RemoteAddr()) - ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") - ctx.HTML(http.StatusOK, "user/auth/prohibit_login") - return - } - - if ctx.Doer.MustChangePassword { - if ctx.Req.URL.Path != "/user/settings/change_password" { - if strings.HasPrefix(ctx.Req.UserAgent(), "git") { - ctx.Error(http.StatusUnauthorized, ctx.Tr("auth.must_change_password")) - return - } - ctx.Data["Title"] = ctx.Tr("auth.must_change_password") - ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password" - if ctx.Req.URL.Path != "/user/events" { - middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI()) - } - ctx.Redirect(setting.AppSubURL + "/user/settings/change_password") - return - } - } else if ctx.Req.URL.Path == "/user/settings/change_password" { - // make sure that the form cannot be accessed by users who don't need this - ctx.Redirect(setting.AppSubURL + "/") - return - } - } - - // Redirect to dashboard (or alternate location) if user tries to visit any non-login page. - if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" { - ctx.RedirectToFirst(ctx.FormString("redirect_to")) - return - } - - if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" { - ctx.Csrf.Validate(ctx) - if ctx.Written() { - return - } - } - - if options.SignInRequired { - if !ctx.IsSigned { - if ctx.Req.URL.Path != "/user/events" { - middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI()) - } - ctx.Redirect(setting.AppSubURL + "/user/login") - return - } else if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.HTML(http.StatusOK, "user/auth/activate") - return - } - } - - // Redirect to log in page if auto-signin info is provided and has not signed in. - if !options.SignOutRequired && !ctx.IsSigned && - len(ctx.GetSiteCookie(setting.CookieUserName)) > 0 { - if ctx.Req.URL.Path != "/user/events" { - middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI()) - } - ctx.Redirect(setting.AppSubURL + "/user/login") - return - } - - if options.AdminRequired { - if !ctx.Doer.IsAdmin { - ctx.Error(http.StatusForbidden) - return - } - ctx.Data["PageIsAdmin"] = true - } - } -} - -// VerifyAuthWithOptionsAPI checks authentication according to options -func VerifyAuthWithOptionsAPI(options *VerifyOptions) func(ctx *context.APIContext) { - return func(ctx *context.APIContext) { - // Check prohibit login users. - if ctx.IsSigned { - if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "This account is not activated.", - }) - return - } - if !ctx.Doer.IsActive || ctx.Doer.ProhibitLogin { - log.Info("Failed authentication attempt for %s from %s", ctx.Doer.Name, ctx.RemoteAddr()) - ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "This account is prohibited from signing in, please contact your site administrator.", - }) - return - } - - if ctx.Doer.MustChangePassword { - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "You must change your password. Change it at: " + setting.AppURL + "/user/change_password", - }) - return - } - } - - // Redirect to dashboard if user tries to visit any non-login page. - if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" { - ctx.Redirect(setting.AppSubURL + "/") - return - } - - if options.SignInRequired { - if !ctx.IsSigned { - // Restrict API calls with error message. - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "Only signed in user is allowed to call APIs.", - }) - return - } else if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "This account is not activated.", - }) - return - } - if ctx.IsSigned && ctx.IsBasicAuth { - if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) { - return // Skip 2FA - } - twofa, err := auth.GetTwoFactorByUID(ctx.Doer.ID) - if err != nil { - if auth.IsErrTwoFactorNotEnrolled(err) { - return // No 2FA enrollment for this user - } - ctx.InternalServerError(err) - return - } - otpHeader := ctx.Req.Header.Get("X-Gitea-OTP") - ok, err := twofa.ValidateTOTP(otpHeader) - if err != nil { - ctx.InternalServerError(err) - return - } - if !ok { - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "Only signed in user is allowed to call APIs.", - }) - return - } - } - } - - if options.AdminRequired { - if !ctx.Doer.IsAdmin { - ctx.JSON(http.StatusForbidden, map[string]string{ - "message": "You have no permission to request for this.", - }) - return - } - } - } -} From e481638010b669133a9106abbbf14fd6d76fb32e Mon Sep 17 00:00:00 2001 From: JakobDev Date: Tue, 12 Sep 2023 08:29:09 +0200 Subject: [PATCH 004/289] Add more package registry paths to the labeler (#27032) Found this while working on #26960 --- .github/labeler.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index ee6c7d6ae8..06a5cd99d1 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -19,6 +19,9 @@ kind/build: theme/package-registry: - "modules/packages/**" + - "services/packages/**" + - "routers/api/packages/**" + - "routers/web/shared/packages/**" kind/cli: - "cmd/**" From e33f112e01d2453f8674c05556944277bf38567b Mon Sep 17 00:00:00 2001 From: jladbrook Date: Tue, 12 Sep 2023 13:26:51 +0100 Subject: [PATCH 005/289] resolve issue with sort icons on admin/users and admin/runners (#24360) Fixes #24327 to avoid the sort icon changing the table header over multiple lines and adds missing sort icons on the runners page. --- models/actions/runner.go | 6 ++++++ routers/web/shared/actions/runners.go | 1 + templates/shared/actions/runner_list.tmpl | 15 ++++++++++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/models/actions/runner.go b/models/actions/runner.go index c79a6827fc..ec6b49cf16 100644 --- a/models/actions/runner.go +++ b/models/actions/runner.go @@ -189,6 +189,12 @@ func (opts FindRunnerOptions) toOrder() string { return "last_online ASC" case "alphabetically": return "name ASC" + case "reversealphabetically": + return "name DESC" + case "newest": + return "id DESC" + case "oldest": + return "id ASC" } return "last_online DESC" } diff --git a/routers/web/shared/actions/runners.go b/routers/web/shared/actions/runners.go index cab3d78cac..7ff1f3e33f 100644 --- a/routers/web/shared/actions/runners.go +++ b/routers/web/shared/actions/runners.go @@ -53,6 +53,7 @@ func RunnersList(ctx *context.Context, opts actions_model.FindRunnerOptions) { ctx.Data["RegistrationToken"] = token.Token ctx.Data["RunnerOwnerID"] = opts.OwnerID ctx.Data["RunnerRepoID"] = opts.RepoID + ctx.Data["SortType"] = opts.Sort pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) diff --git a/templates/shared/actions/runner_list.tmpl b/templates/shared/actions/runner_list.tmpl index c4b70282ae..ead260f128 100644 --- a/templates/shared/actions/runner_list.tmpl +++ b/templates/shared/actions/runner_list.tmpl @@ -45,9 +45,18 @@ - - - + + + From e986265ecb633a6db1af6b8382c65b209faf0579 Mon Sep 17 00:00:00 2001 From: Sienna Lloyd Date: Tue, 12 Sep 2023 06:47:53 -0600 Subject: [PATCH 006/289] update snap package (#27021) --- .gitignore | 1 + snap/snapcraft.yaml | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index e3b9c3c43e..53365ed0b4 100644 --- a/.gitignore +++ b/.gitignore @@ -95,6 +95,7 @@ cpu.out /.go-licenses # Snapcraft +/gitea_a*.txt snap/.snapcraft/ parts/ stage/ diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 2bd8c600cb..fa2b4a3979 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -8,7 +8,7 @@ description: | icon: public/assets/img/logo.png confinement: strict -base: core18 +base: core22 adopt-info: gitea architectures: @@ -44,12 +44,13 @@ parts: source: . stage-packages: [ git, sqlite3, openssh-client ] build-packages: [ git, libpam0g-dev, libsqlite3-dev, build-essential] - build-snaps: [ go, node/18/stable ] + build-snaps: [ go/1.21/stable, node/18/stable ] build-environment: - LDFLAGS: "" override-pull: | - snapcraftctl pull + craftctl default + git config --global --add safe.directory /root/parts/gitea/src last_committed_tag="$(git for-each-ref --sort=taggerdate --format '%(tag)' refs/tags | tail -n 1)" last_released_tag="$(snap info gitea | awk '$1 == "latest/candidate:" { print $2 }')" # If the latest tag from the upstream project has not been released to @@ -61,8 +62,8 @@ parts: version="$(git describe --always | sed -e 's/-/+git/;y/-/./')" [ -n "$(echo $version | grep "+git")" ] && grade=devel || grade=stable - snapcraftctl set-version "$version" - snapcraftctl set-grade "$grade" + craftctl set version "$version" + craftctl set grade="$grade" override-build: | set -x From e6b68c579b75e818f6a3a80ef9811f739bcb4f86 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Tue, 12 Sep 2023 12:15:05 -0400 Subject: [PATCH 007/289] Use Actuated.dev runner for nightly builds --- .github/workflows/release-nightly.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-nightly.yml b/.github/workflows/release-nightly.yml index 8387f615d9..ca01ccfaa7 100644 --- a/.github/workflows/release-nightly.yml +++ b/.github/workflows/release-nightly.yml @@ -6,7 +6,7 @@ on: jobs: nightly-binary: - runs-on: ubuntu-latest + runs-on: actuated-4cpu-8gb steps: - uses: actions/checkout@v3 # fetch all commits instead of only the last as some branches are long lived and could have many between versions @@ -52,7 +52,7 @@ jobs: SOURCE_DIR: dist/release DEST_DIR: gitea/${{ steps.clean_name.outputs.branch }} nightly-docker: - runs-on: ubuntu-latest + runs-on: actuated-4cpu-8gb steps: - uses: actions/checkout@v3 # fetch all commits instead of only the last as some branches are long lived and could have many between versions From 739e47cd80db34f2ab0a63da76adc235f1f2ab06 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 13 Sep 2023 00:44:48 +0800 Subject: [PATCH 008/289] Improve repo/user/org search (#27030) * Fix a regression from #26809 (the `data-org` is missing) * Remove unnecessary style Screenshots: ![image](https://github.com/go-gitea/gitea/assets/2114189/3f5cf628-db7f-4705-898a-7a4a1fbfbba8) ![image](https://github.com/go-gitea/gitea/assets/2114189/453d1fad-1090-4524-bf45-6c5da2465f04) ![image](https://github.com/go-gitea/gitea/assets/2114189/f14d9808-7596-42c8-84b4-0d57a0bf2278) --- templates/repo/settings/collaboration.tmpl | 2 +- web_src/css/repo.css | 10 ++-------- web_src/js/features/repo-settings.js | 2 +- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/templates/repo/settings/collaboration.tmpl b/templates/repo/settings/collaboration.tmpl index 4c6721eb24..c40265c6a6 100644 --- a/templates/repo/settings/collaboration.tmpl +++ b/templates/repo/settings/collaboration.tmpl @@ -89,7 +89,7 @@ {{if $allowedToChangeTeams}}
{{.CsrfTokenHtml}} - From cda97a725347cdadd43af812749732b9d1ee6429 Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Wed, 13 Sep 2023 12:43:31 +0800 Subject: [PATCH 016/289] Update status and code index after changing the default branch (#27018) Fix #26723 Add `ChangeDefaultBranch` to the `notifier` interface and implement it in `indexerNotifier`. So when changing the default branch, `indexerNotifier` sends a message to the `indexer queue` to update the index. --------- Co-authored-by: techknowlogick --- models/repo/git.go | 4 +- modules/indexer/code/git.go | 9 ++- routers/web/repo/setting/default_branch.go | 64 ++++++++++++++++++++ routers/web/repo/setting/protected_branch.go | 50 --------------- services/indexer/notify.go | 9 +++ services/notify/notifier.go | 2 + services/notify/notify.go | 7 +++ services/notify/null.go | 4 ++ 8 files changed, 97 insertions(+), 52 deletions(-) create mode 100644 routers/web/repo/setting/default_branch.go diff --git a/models/repo/git.go b/models/repo/git.go index c1af7ee960..2f71128b5a 100644 --- a/models/repo/git.go +++ b/models/repo/git.go @@ -3,7 +3,9 @@ package repo -import "code.gitea.io/gitea/models/db" +import ( + "code.gitea.io/gitea/models/db" +) // MergeStyle represents the approach to merge commits into base branch. type MergeStyle string diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 1ba6b849d1..e4686fa01f 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -30,7 +30,14 @@ func getRepoChanges(ctx context.Context, repo *repo_model.Repository, revision s return nil, err } - if len(status.CommitSha) == 0 { + needGenesis := len(status.CommitSha) == 0 + if !needGenesis { + hasAncestorCmd := git.NewCommand(ctx, "merge-base").AddDynamicArguments(repo.CodeIndexerStatus.CommitSha, revision) + stdout, _, _ := hasAncestorCmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) + needGenesis = len(stdout) == 0 + } + + if needGenesis { return genesisChanges(ctx, repo, revision) } return nonGenesisChanges(ctx, repo, revision) diff --git a/routers/web/repo/setting/default_branch.go b/routers/web/repo/setting/default_branch.go new file mode 100644 index 0000000000..f0aa1a89e7 --- /dev/null +++ b/routers/web/repo/setting/default_branch.go @@ -0,0 +1,64 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import ( + "net/http" + + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/routers/web/repo" + notify_service "code.gitea.io/gitea/services/notify" +) + +// SetDefaultBranchPost set default branch +func SetDefaultBranchPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("repo.settings.branches.update_default_branch") + ctx.Data["PageIsSettingsBranches"] = true + + repo.PrepareBranchList(ctx) + if ctx.Written() { + return + } + + repo := ctx.Repo.Repository + + switch ctx.FormString("action") { + case "default_branch": + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplBranches) + return + } + + branch := ctx.FormString("branch") + if !ctx.Repo.GitRepo.IsBranchExist(branch) { + ctx.Status(http.StatusNotFound) + return + } else if repo.DefaultBranch != branch { + repo.DefaultBranch = branch + if err := ctx.Repo.GitRepo.SetDefaultBranch(branch); err != nil { + if !git.IsErrUnsupportedVersion(err) { + ctx.ServerError("SetDefaultBranch", err) + return + } + } + if err := repo_model.UpdateDefaultBranch(repo); err != nil { + ctx.ServerError("SetDefaultBranch", err) + return + } + + notify_service.ChangeDefaultBranch(ctx, repo) + } + + log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name) + + ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath()) + default: + ctx.NotFound("", nil) + } +} diff --git a/routers/web/repo/setting/protected_branch.go b/routers/web/repo/setting/protected_branch.go index 5bfdb8f515..e0f2294a14 100644 --- a/routers/web/repo/setting/protected_branch.go +++ b/routers/web/repo/setting/protected_branch.go @@ -14,12 +14,8 @@ import ( "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" access_model "code.gitea.io/gitea/models/perm/access" - repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/web/repo" "code.gitea.io/gitea/services/forms" @@ -53,52 +49,6 @@ func ProtectedBranchRules(ctx *context.Context) { ctx.HTML(http.StatusOK, tplBranches) } -// SetDefaultBranchPost set default branch -func SetDefaultBranchPost(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.settings.branches.update_default_branch") - ctx.Data["PageIsSettingsBranches"] = true - - repo.PrepareBranchList(ctx) - if ctx.Written() { - return - } - - repo := ctx.Repo.Repository - - switch ctx.FormString("action") { - case "default_branch": - if ctx.HasError() { - ctx.HTML(http.StatusOK, tplBranches) - return - } - - branch := ctx.FormString("branch") - if !ctx.Repo.GitRepo.IsBranchExist(branch) { - ctx.Status(http.StatusNotFound) - return - } else if repo.DefaultBranch != branch { - repo.DefaultBranch = branch - if err := ctx.Repo.GitRepo.SetDefaultBranch(branch); err != nil { - if !git.IsErrUnsupportedVersion(err) { - ctx.ServerError("SetDefaultBranch", err) - return - } - } - if err := repo_model.UpdateDefaultBranch(repo); err != nil { - ctx.ServerError("SetDefaultBranch", err) - return - } - } - - log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name) - - ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) - ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath()) - default: - ctx.NotFound("", nil) - } -} - // SettingsProtectedBranch renders the protected branch setting page func SettingsProtectedBranch(c *context.Context) { ruleName := c.FormString("rule_name") diff --git a/services/indexer/notify.go b/services/indexer/notify.go index 22306c691b..a07bf38b06 100644 --- a/services/indexer/notify.go +++ b/services/indexer/notify.go @@ -110,6 +110,15 @@ func (r *indexerNotifier) SyncPushCommits(ctx context.Context, pusher *user_mode } } +func (r *indexerNotifier) ChangeDefaultBranch(ctx context.Context, repo *repo_model.Repository) { + if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty { + code_indexer.UpdateRepoIndexer(repo) + } + if err := stats_indexer.UpdateRepoIndexer(repo); err != nil { + log.Error("stats_indexer.UpdateRepoIndexer(%d) failed: %v", repo.ID, err) + } +} + func (r *indexerNotifier) IssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) { issue_indexer.UpdateIssueIndexer(issue.ID) } diff --git a/services/notify/notifier.go b/services/notify/notifier.go index d1dbe44c11..ed053a812a 100644 --- a/services/notify/notifier.go +++ b/services/notify/notifier.go @@ -72,4 +72,6 @@ type Notifier interface { PackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) PackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) + + ChangeDefaultBranch(ctx context.Context, repo *repo_model.Repository) } diff --git a/services/notify/notify.go b/services/notify/notify.go index 71bc1c7d58..16fbb6325d 100644 --- a/services/notify/notify.go +++ b/services/notify/notify.go @@ -360,3 +360,10 @@ func PackageDelete(ctx context.Context, doer *user_model.User, pd *packages_mode notifier.PackageDelete(ctx, doer, pd) } } + +// ChangeDefaultBranch notifies change default branch to notifiers +func ChangeDefaultBranch(ctx context.Context, repo *repo_model.Repository) { + for _, notifier := range notifiers { + notifier.ChangeDefaultBranch(ctx, repo) + } +} diff --git a/services/notify/null.go b/services/notify/null.go index c5b31f83d6..dddd421bef 100644 --- a/services/notify/null.go +++ b/services/notify/null.go @@ -204,3 +204,7 @@ func (*NullNotifier) PackageCreate(ctx context.Context, doer *user_model.User, p // PackageDelete places a place holder function func (*NullNotifier) PackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { } + +// ChangeDefaultBranch places a place holder function +func (*NullNotifier) ChangeDefaultBranch(ctx context.Context, repo *repo_model.Repository) { +} From 63b53af933d748f9b4e0f1273e3701b4c3d08ac3 Mon Sep 17 00:00:00 2001 From: Dmitry Sharshakov Date: Wed, 13 Sep 2023 08:14:21 +0300 Subject: [PATCH 017/289] Show OpenID Connect and OAuth on signup page (#20242) Fix #19809 --------- Signed-off-by: Dmitry Sharshakov Co-authored-by: jackHay22 --- routers/web/auth/auth.go | 18 ++++++++++++++++++ templates/user/auth/signin_navbar.tmpl | 3 +++ templates/user/auth/signup.tmpl | 1 + templates/user/auth/signup_inner.tmpl | 19 +++++++++++++++++++ 4 files changed, 41 insertions(+) diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index c20a45ebc9..dac8eb7afb 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -392,7 +392,16 @@ func SignUp(ctx *context.Context) { ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + if err != nil { + ctx.ServerError("UserSignUp", err) + return + } + + ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names + ctx.Data["OAuth2Providers"] = oauth2Providers context.SetCaptchaData(ctx) + ctx.Data["PageIsSignUp"] = true // Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true @@ -413,7 +422,16 @@ func SignUpPost(ctx *context.Context) { ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + if err != nil { + ctx.ServerError("UserSignUp", err) + return + } + + ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names + ctx.Data["OAuth2Providers"] = oauth2Providers context.SetCaptchaData(ctx) + ctx.Data["PageIsSignUp"] = true // Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true diff --git a/templates/user/auth/signin_navbar.tmpl b/templates/user/auth/signin_navbar.tmpl index 40f34cc01b..84574aa2c2 100644 --- a/templates/user/auth/signin_navbar.tmpl +++ b/templates/user/auth/signin_navbar.tmpl @@ -4,6 +4,9 @@ {{.locale.Tr "auth.login_userpass"}} + + {{.locale.Tr "auth.create_new_account"}} + {{if .EnableOpenIDSignIn}} {{svg "fontawesome-openid"}} diff --git a/templates/user/auth/signup.tmpl b/templates/user/auth/signup.tmpl index 1d03f610dc..f238413ce2 100644 --- a/templates/user/auth/signup.tmpl +++ b/templates/user/auth/signup.tmpl @@ -1,5 +1,6 @@ {{template "base/head" .}}
+ {{template "user/auth/signin_navbar" .}}
{{template "user/auth/signup_inner" .}}
diff --git a/templates/user/auth/signup_inner.tmpl b/templates/user/auth/signup_inner.tmpl index 8dfcb7b7d0..184b8b88fe 100644 --- a/templates/user/auth/signup_inner.tmpl +++ b/templates/user/auth/signup_inner.tmpl @@ -55,6 +55,25 @@
{{end}} {{end}} + + {{if and .OrderedOAuth2Names .OAuth2Providers}} +
+ {{.locale.Tr "sign_in_or"}} +
+
+ {{end}} From 79afd280e1ece4711c0236f06942b3281fcfcf7d Mon Sep 17 00:00:00 2001 From: Earl Warren <109468362+earl-warren@users.noreply.github.com> Date: Wed, 13 Sep 2023 07:44:59 +0200 Subject: [PATCH 018/289] fix media description render for orgmode (#26895) - In org mode you can specify an description for media via the following syntax `[[description][media link]]`. The description is then used as title or alt. - This patch fixes the rendering of the description by seperating the description and non-description cases and using `org.String()`. - Added unit tests. - Inspired by https://github.com/niklasfasching/go-org/blob/6eb20dbda93cb88c3503f7508dc78cbbc639378f/org/html_writer.go#L406-L427 - Resolves https://codeberg.org/Codeberg/Community/issues/848 (cherry picked from commit 8b8aab83113b34bade61964e2097ed497abc39e9) Co-authored-by: Gusted --- modules/markup/orgmode/orgmode.go | 29 +++++++++++++++++++------- modules/markup/orgmode/orgmode_test.go | 14 ++++++++++++- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/modules/markup/orgmode/orgmode.go b/modules/markup/orgmode/orgmode.go index a6dac12039..9b6175649f 100644 --- a/modules/markup/orgmode/orgmode.go +++ b/modules/markup/orgmode/orgmode.go @@ -153,18 +153,31 @@ func (r *Writer) WriteRegularLink(l org.RegularLink) { link = []byte(util.URLJoin(r.URLPrefix, lnk)) } - description := string(link) - if l.Description != nil { - description = r.WriteNodesAsString(l.Description...) - } + // Inspired by https://github.com/niklasfasching/go-org/blob/6eb20dbda93cb88c3503f7508dc78cbbc639378f/org/html_writer.go#L406-L427 switch l.Kind() { case "image": - imageSrc := getMediaURL(link) - fmt.Fprintf(r, `%s`, imageSrc, description, description) + if l.Description == nil { + imageSrc := getMediaURL(link) + fmt.Fprintf(r, `%s`, imageSrc, link, link) + } else { + description := strings.TrimPrefix(org.String(l.Description...), "file:") + imageSrc := getMediaURL([]byte(description)) + fmt.Fprintf(r, `%s`, link, imageSrc, imageSrc) + } case "video": - videoSrc := getMediaURL(link) - fmt.Fprintf(r, ``, videoSrc, description, description) + if l.Description == nil { + imageSrc := getMediaURL(link) + fmt.Fprintf(r, ``, imageSrc, link, link) + } else { + description := strings.TrimPrefix(org.String(l.Description...), "file:") + videoSrc := getMediaURL([]byte(description)) + fmt.Fprintf(r, ``, link, videoSrc, videoSrc) + } default: + description := string(link) + if l.Description != nil { + description = r.WriteNodesAsString(l.Description...) + } fmt.Fprintf(r, `%s`, link, description, description) } } diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index d6467c36f7..8f454e9955 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -42,7 +42,7 @@ func TestRender_StandardLinks(t *testing.T) { "

WikiPage

") } -func TestRender_Images(t *testing.T) { +func TestRender_Media(t *testing.T) { setting.AppURL = AppURL setting.AppSubURL = AppSubURL @@ -60,6 +60,18 @@ func TestRender_Images(t *testing.T) { test("[[file:"+url+"]]", "

\""+result+"\"

") + + // With description. + test("[[https://example.com][https://example.com/example.svg]]", + `

https://example.com/example.svg

`) + test("[[https://example.com][https://example.com/example.mp4]]", + `

`) + + // Without description. + test("[[https://example.com/example.svg]]", + `

https://example.com/example.svg

`) + test("[[https://example.com/example.mp4]]", + `

`) } func TestRender_Source(t *testing.T) { From 0989f437df8d006a6acb13fe14e1ed05445582c9 Mon Sep 17 00:00:00 2001 From: puni9869 <80308335+puni9869@users.noreply.github.com> Date: Wed, 13 Sep 2023 12:45:36 +0530 Subject: [PATCH 019/289] Dashboard context dropdown position fix on landing page in mobile view. (#27047) as title. Screensots before ![image](https://github.com/go-gitea/gitea/assets/80308335/d72da379-1fb1-4d75-9f3e-f70e06ad4065) after ![image](https://github.com/go-gitea/gitea/assets/80308335/110ea806-feed-4947-bf56-2985b1e1ec5f) --- web_src/css/dashboard.css | 6 ------ 1 file changed, 6 deletions(-) diff --git a/web_src/css/dashboard.css b/web_src/css/dashboard.css index 0168ee0bd7..51ddd45e31 100644 --- a/web_src/css/dashboard.css +++ b/web_src/css/dashboard.css @@ -89,9 +89,3 @@ .dashboard .dashboard-navbar .ui.dropdown { max-width: 100%; } - -@media (max-width: 767.98px) { - .dashboard .dashboard-navbar .ui.dropdown > .menu { - position: static; - } -} From a38eca3f52f691667f8075263badffba4e9b97ae Mon Sep 17 00:00:00 2001 From: Kerwin Bryant Date: Wed, 13 Sep 2023 17:08:45 +0800 Subject: [PATCH 020/289] Fix Fomantic's line-height causing vertical scrollbars to appear (#26961) Before: ![before](https://github.com/go-gitea/gitea/assets/3371163/bc5a3b20-3490-4e14-ab1d-2fcfbc4a2e20) After: ![after](https://github.com/go-gitea/gitea/assets/3371163/70e8be6a-11a2-46af-9e1e-78ac153cd2a4) --- 1. **Remove the scroll bar exception that in the a tag** 2. **Reduce the actual width of the a tag to the actual width of the content** ![c363a5b5883e105a0c65d7337893b50](https://github.com/go-gitea/gitea/assets/3371163/789d9b83-ad14-46d2-8a1b-df551a063f6a) As shown in the screenshot, the red box area should not be clickable --- templates/repo/settings/webhook/base_list.tmpl | 4 +++- web_src/css/base.css | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/templates/repo/settings/webhook/base_list.tmpl b/templates/repo/settings/webhook/base_list.tmpl index 1bc9447110..b0e8ace410 100644 --- a/templates/repo/settings/webhook/base_list.tmpl +++ b/templates/repo/settings/webhook/base_list.tmpl @@ -60,7 +60,9 @@ {{range .Webhooks}}
{{svg "octicon-dot-fill" 22}} - {{.URL}} +
+ {{.URL}} +
{{svg "octicon-pencil"}} {{svg "octicon-trash"}}
diff --git a/web_src/css/base.css b/web_src/css/base.css index 8542248d90..b41bfc6942 100644 --- a/web_src/css/base.css +++ b/web_src/css/base.css @@ -481,6 +481,14 @@ a.label, text-align: start; /* Override fomantic's `text-align: left` to make RTL work via HTML `dir="auto"` */ } +/* fix Fomantic's line-height causing vertical scrollbars to appear */ +ul.ui.list li, +ol.ui.list li, +.ui.list > .item, +.ui.list .list > .item { + line-height: var(--line-height-default); +} + .ui.input.focus > input, .ui.input > input:focus { border-color: var(--color-primary); From e0aacc7624238caaf959c512362ec2b69565c444 Mon Sep 17 00:00:00 2001 From: puni9869 <80308335+puni9869@users.noreply.github.com> Date: Wed, 13 Sep 2023 16:17:35 +0530 Subject: [PATCH 021/289] Show the repo count in code tab on both user profile and org page. (#27048) as title Screenshot before User Profile page image after image Org page image --------- Co-authored-by: wxiaoguang --- routers/web/user/code.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/routers/web/user/code.go b/routers/web/user/code.go index 29b8b91c89..42d7284189 100644 --- a/routers/web/user/code.go +++ b/routers/web/user/code.go @@ -27,6 +27,11 @@ func CodeSearch(ctx *context.Context) { shared_user.PrepareContextForProfileBigAvatar(ctx) shared_user.RenderUserHeader(ctx) + if err := shared_user.LoadHeaderCount(ctx); err != nil { + ctx.ServerError("LoadHeaderCount", err) + return + } + ctx.Data["IsPackageEnabled"] = setting.Packages.Enabled ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled ctx.Data["Title"] = ctx.Tr("explore.code") From 5d755ac6aef13e396341d5ce20238e86b8e08277 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 13 Sep 2023 10:43:03 -0400 Subject: [PATCH 022/289] bump all nightly builds to 16gb --- .github/workflows/release-nightly.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release-nightly.yml b/.github/workflows/release-nightly.yml index 519fd3f02a..0671ecee8b 100644 --- a/.github/workflows/release-nightly.yml +++ b/.github/workflows/release-nightly.yml @@ -5,12 +5,12 @@ on: branches: [ main, release/v* ] concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: nightly-binary: - runs-on: actuated-4cpu-8gb + runs-on: actuated-4cpu-16gb steps: - uses: actions/checkout@v3 # fetch all commits instead of only the last as some branches are long lived and could have many between versions @@ -93,7 +93,7 @@ jobs: push: true tags: gitea/gitea:${{ steps.clean_name.outputs.branch }} nightly-docker-rootless: - runs-on: actuated-4cpu-8gb + runs-on: actuated-4cpu-16gb steps: - uses: actions/checkout@v3 # fetch all commits instead of only the last as some branches are long lived and could have many between versions From e116ad4500bbaac140d53a6a699d4609fa066fa7 Mon Sep 17 00:00:00 2001 From: sebastian-sauer Date: Wed, 13 Sep 2023 21:48:36 +0200 Subject: [PATCH 023/289] Load reviewer before sending notification (#27063) The [template](https://github.com/go-gitea/gitea/blob/main/templates/mail/issue/default.tmpl#L51) uses the Reviewer.Name property - this was not loaded. Fixes #27035 --- services/mailer/notify.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/mailer/notify.go b/services/mailer/notify.go index f0419e2cbb..9eaf268d0a 100644 --- a/services/mailer/notify.go +++ b/services/mailer/notify.go @@ -176,6 +176,9 @@ func (m *mailNotifier) PullRequestPushCommits(ctx context.Context, doer *user_mo } func (m *mailNotifier) PullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { + if err := comment.Review.LoadReviewer(ctx); err != nil { + log.Error("Error in PullReviewDismiss while loading reviewer for issue[%d], review[%d] and reviewer[%d]: %v", review.Issue.ID, comment.Review.ID, comment.Review.ReviewerID, err) + } if err := MailParticipantsComment(ctx, comment, activities_model.ActionPullReviewDismissed, review.Issue, nil); err != nil { log.Error("MailParticipantsComment: %v", err) } From d0318c4ae004e754a6e0e10a44df7552ad9a2712 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Thu, 14 Sep 2023 00:22:27 +0000 Subject: [PATCH 024/289] [skip ci] Updated translations via Crowdin --- options/locale/locale_ja-JP.ini | 3 +++ 1 file changed, 3 insertions(+) diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index 259bb46bc4..aed68018bd 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -3440,9 +3440,12 @@ runners.reset_registration_token_success=ランナー登録トークンをリセ runs.all_workflows=すべてのワークフロー runs.commit=コミット +runs.pushed_by=pushed by runs.invalid_workflow_helper=ワークフロー設定ファイルは無効です。あなたの設定ファイルを確認してください: %s runs.no_matching_runner_helper=一致するランナーがありません: %s +runs.actor=アクター runs.status=ステータス +runs.actors_no_select=すべてのアクター runs.status_no_select=すべてのステータス runs.no_results=一致する結果はありません。 runs.no_runs=ワークフローはまだ実行されていません。 From da50be73604589be9381e8811af5465fa47558f1 Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Thu, 14 Sep 2023 10:59:53 +0800 Subject: [PATCH 025/289] Replace 'userxx' with 'orgxx' in all test files when the user type is org (#27052) Currently 'userxx' and 'orgxx' are both used as username in test files when the user type is org, which is confusing. This PR replaces all 'userxx' with 'orgxx' when the user type is org(`user.type==1`). Some non-trivial changes 1. Rename `user3` dir to `org3` in `tests/git-repositories-meta` 2. Change `end` in `issue reference` because 'org3' is one char shorter than 'user3' ![ksnip_20230913-112819](https://github.com/go-gitea/gitea/assets/70063547/442988c5-4cf4-49b8-aa01-4dd6bf0ca954) 3. Change the search result number of `user/repo2` because `user3/repo21` can't be searched now ![ksnip_20230913-112931](https://github.com/go-gitea/gitea/assets/70063547/d9ebeba4-479f-4110-9a85-825efbc981fd) 4. Change the first org name getting from API because the result is ordered by alphabet asc and now `org 17` is before `org25` ![JW8U7NIO(J$H _YCRB36H)T](https://github.com/go-gitea/gitea/assets/70063547/f55a685c-cf24-40e5-a87f-3a2327319548) ![)KFD411O4I8RB5ZOH7E0 Z3](https://github.com/go-gitea/gitea/assets/70063547/a0dc3299-249c-46f6-91cb-d15d4ee88dd5) Other modifications are just find all and replace all. Unit tests with SQLite are all passed. --------- Co-authored-by: caicandong <1290147055@qq.com> --- models/fixtures/email_address.yml | 20 +++--- models/fixtures/repository.yml | 14 ++--- models/fixtures/review.yml | 2 +- models/fixtures/user.yml | 58 +++++++++--------- models/issues/assignees_test.go | 6 +- models/issues/issue_test.go | 6 +- models/issues/issue_xref_test.go | 4 +- models/issues/pull_test.go | 8 +-- models/issues/reaction_test.go | 10 +-- models/issues/review_test.go | 6 +- models/issues/stopwatch_test.go | 4 +- models/issues/tracked_time_test.go | 4 +- models/organization/org_test.go | 18 +++--- models/organization/team_invite_test.go | 4 +- models/repo/repo_list_test.go | 10 +-- models/repo/repo_test.go | 2 +- models/repo_transfer_test.go | 4 +- models/user/email_address_test.go | 2 +- models/user/user_test.go | 6 +- modules/references/references_test.go | 30 ++++----- services/issue/commit_test.go | 4 +- services/repository/transfer_test.go | 4 +- .../{user3 => org3}/repo3.git/HEAD | 0 .../{user3 => org3}/repo3.git/config | 0 .../{user3 => org3}/repo3.git/description | 0 .../repo3.git/hooks/post-receive | 0 .../repo3.git/hooks/post-receive.d/gitea | 0 .../repo3.git/hooks/pre-receive | 0 .../repo3.git/hooks/pre-receive.d/gitea | 0 .../{user3 => org3}/repo3.git/hooks/update | 0 .../repo3.git/hooks/update.d/gitea | 0 .../{user3 => org3}/repo3.git/info/exclude | 0 .../20/ade30d25e0ecaeec84e7f542a8456900858240 | Bin .../27/74debeea6dc742cc4971a92db0e08b95b60588 | Bin .../2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 | Bin .../2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f | Bin .../d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 | Bin .../d5/6a3073c1dbb7b15963110a049d50cdb5db99fc | Bin .../ec/f0db3c1ec806522de4b491fb9a3c7457398c61 | Bin .../ee/16d127df463aa491e08958120f2108b02468df | Bin .../repo3.git/refs/heads/master | 0 .../repo3.git/refs/heads/test_branch | 0 .../{user3 => org3}/repo5.git/HEAD | 0 .../{user3 => org3}/repo5.git/config | 0 .../{user3 => org3}/repo5.git/description | 0 .../repo5.git/hooks/post-receive | 0 .../repo5.git/hooks/post-receive.d/gitea | 0 .../repo5.git/hooks/pre-receive | 0 .../repo5.git/hooks/pre-receive.d/gitea | 0 .../{user3 => org3}/repo5.git/hooks/update | 0 .../repo5.git/hooks/update.d/gitea | 0 .../{user3 => org3}/repo5.git/info/exclude | 0 .../20/ade30d25e0ecaeec84e7f542a8456900858240 | Bin .../27/74debeea6dc742cc4971a92db0e08b95b60588 | Bin .../2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 | Bin .../2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f | Bin .../d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 | Bin .../d5/6a3073c1dbb7b15963110a049d50cdb5db99fc | Bin .../ec/f0db3c1ec806522de4b491fb9a3c7457398c61 | Bin .../ee/16d127df463aa491e08958120f2108b02468df | Bin .../repo5.git/refs/heads/master | 0 .../repo5.git/refs/heads/test_branch | 0 tests/integration/actions_trigger_test.go | 32 +++++----- tests/integration/api_issue_test.go | 4 +- tests/integration/api_org_avatar_test.go | 8 +-- tests/integration/api_org_test.go | 12 ++-- tests/integration/api_repo_branch_test.go | 10 +-- tests/integration/api_repo_edit_test.go | 12 ++-- .../integration/api_repo_file_create_test.go | 10 +-- .../integration/api_repo_file_delete_test.go | 14 ++--- .../integration/api_repo_file_update_test.go | 14 ++--- .../integration/api_repo_files_change_test.go | 18 +++--- .../api_repo_get_contents_list_test.go | 6 +- .../integration/api_repo_get_contents_test.go | 6 +- tests/integration/api_repo_git_blobs_test.go | 18 +++--- tests/integration/api_repo_git_trees_test.go | 14 ++--- tests/integration/api_repo_teams_test.go | 2 +- tests/integration/api_repo_test.go | 36 +++++------ tests/integration/api_repo_topic_test.go | 6 +- tests/integration/api_user_info_test.go | 10 +-- tests/integration/api_user_org_perm_test.go | 10 +-- tests/integration/api_user_orgs_test.go | 48 +++++++-------- tests/integration/issue_test.go | 4 +- tests/integration/org_project_test.go | 16 ++--- tests/integration/org_test.go | 2 +- tests/integration/privateactivity_test.go | 2 +- tests/integration/repo_fork_test.go | 4 +- tests/integration/repo_test.go | 6 +- tests/integration/repo_watch_test.go | 2 +- tests/integration/timetracking_test.go | 2 +- web_src/js/test/setup.js | 6 +- 91 files changed, 280 insertions(+), 280 deletions(-) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/HEAD (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/config (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/description (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/hooks/post-receive (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/hooks/post-receive.d/gitea (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/hooks/pre-receive (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/hooks/pre-receive.d/gitea (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/hooks/update (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/hooks/update.d/gitea (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/info/exclude (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/objects/ee/16d127df463aa491e08958120f2108b02468df (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/refs/heads/master (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo3.git/refs/heads/test_branch (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/HEAD (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/config (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/description (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/hooks/post-receive (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/hooks/post-receive.d/gitea (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/hooks/pre-receive (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/hooks/pre-receive.d/gitea (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/hooks/update (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/hooks/update.d/gitea (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/info/exclude (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/objects/ee/16d127df463aa491e08958120f2108b02468df (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/refs/heads/master (100%) rename tests/gitea-repositories-meta/{user3 => org3}/repo5.git/refs/heads/test_branch (100%) diff --git a/models/fixtures/email_address.yml b/models/fixtures/email_address.yml index 1c32379b60..ce4d5208df 100644 --- a/models/fixtures/email_address.yml +++ b/models/fixtures/email_address.yml @@ -73,8 +73,8 @@ - id: 10 uid: 3 - email: user3@example.com - lower_email: user3@example.com + email: org3@example.com + lower_email: org3@example.com is_activated: true is_primary: true @@ -97,16 +97,16 @@ - id: 13 uid: 6 - email: user6@example.com - lower_email: user6@example.com + email: org6@example.com + lower_email: org6@example.com is_activated: true is_primary: true - id: 14 uid: 7 - email: user7@example.com - lower_email: user7@example.com + email: org7@example.com + lower_email: org7@example.com is_activated: true is_primary: true @@ -153,8 +153,8 @@ - id: 20 uid: 17 - email: user17@example.com - lower_email: user17@example.com + email: org17@example.com + lower_email: org17@example.com is_activated: true is_primary: true @@ -169,8 +169,8 @@ - id: 22 uid: 19 - email: user19@example.com - lower_email: user19@example.com + email: org19@example.com + lower_email: org19@example.com is_activated: true is_primary: true diff --git a/models/fixtures/repository.yml b/models/fixtures/repository.yml index 15668e6cae..c63b7ebd48 100644 --- a/models/fixtures/repository.yml +++ b/models/fixtures/repository.yml @@ -64,7 +64,7 @@ - id: 3 owner_id: 3 - owner_name: user3 + owner_name: org3 lower_name: repo3 name: repo3 default_branch: master @@ -126,7 +126,7 @@ - id: 5 owner_id: 3 - owner_name: user3 + owner_name: org3 lower_name: repo5 name: repo5 num_watches: 0 @@ -671,7 +671,7 @@ - id: 23 owner_id: 17 - owner_name: user17 + owner_name: org17 lower_name: big_test_public_4 name: big_test_public_4 num_watches: 0 @@ -701,7 +701,7 @@ - id: 24 owner_id: 17 - owner_name: user17 + owner_name: org17 lower_name: big_test_private_4 name: big_test_private_4 num_watches: 0 @@ -791,7 +791,7 @@ - id: 27 owner_id: 19 - owner_name: user19 + owner_name: org19 lower_name: big_test_public_mirror_6 name: big_test_public_mirror_6 num_watches: 0 @@ -821,7 +821,7 @@ - id: 28 owner_id: 19 - owner_name: user19 + owner_name: org19 lower_name: big_test_private_mirror_6 name: big_test_private_mirror_6 num_watches: 0 @@ -942,7 +942,7 @@ - id: 32 # org public repo owner_id: 3 - owner_name: user3 + owner_name: org3 lower_name: repo21 name: repo21 num_watches: 0 diff --git a/models/fixtures/review.yml b/models/fixtures/review.yml index cc2c7e06e7..dda13dc468 100644 --- a/models/fixtures/review.yml +++ b/models/fixtures/review.yml @@ -129,6 +129,6 @@ type: 1 reviewer_id: 6 issue_id: 11 - content: "singular review from user6 and final review for this pr" + content: "singular review from org6 and final review for this pr" updated_unix: 946684831 created_unix: 946684831 diff --git a/models/fixtures/user.yml b/models/fixtures/user.yml index f24d098a7e..fd51379816 100644 --- a/models/fixtures/user.yml +++ b/models/fixtures/user.yml @@ -76,17 +76,17 @@ - id: 3 - lower_name: user3 - name: user3 + lower_name: org3 + name: org3 full_name: ' <<<< >> >> > >> > >>> >> ' - email: user3@example.com + email: org3@example.com keep_email_private: false email_notifications_preference: onmention passwd: ZogKvWdyEx:password passwd_hash_algo: dummy must_change_password: false login_source: 0 - login_name: user3 + login_name: org3 type: 1 salt: ZogKvWdyEx max_repo_creation: -1 @@ -98,7 +98,7 @@ allow_create_organization: true prohibit_login: false avatar: avatar3 - avatar_email: user3@example.com + avatar_email: org3@example.com use_custom_avatar: false num_followers: 0 num_following: 0 @@ -187,17 +187,17 @@ - id: 6 - lower_name: user6 - name: user6 - full_name: User Six - email: user6@example.com + lower_name: org6 + name: org6 + full_name: Org Six + email: org6@example.com keep_email_private: false email_notifications_preference: enabled passwd: ZogKvWdyEx:password passwd_hash_algo: dummy must_change_password: false login_source: 0 - login_name: user6 + login_name: org6 type: 1 salt: ZogKvWdyEx max_repo_creation: -1 @@ -209,7 +209,7 @@ allow_create_organization: true prohibit_login: false avatar: avatar6 - avatar_email: user6@example.com + avatar_email: org6@example.com use_custom_avatar: false num_followers: 0 num_following: 0 @@ -224,17 +224,17 @@ - id: 7 - lower_name: user7 - name: user7 - full_name: User Seven - email: user7@example.com + lower_name: org7 + name: org7 + full_name: Org Seven + email: org7@example.com keep_email_private: false email_notifications_preference: disabled passwd: ZogKvWdyEx:password passwd_hash_algo: dummy must_change_password: false login_source: 0 - login_name: user7 + login_name: org7 type: 1 salt: ZogKvWdyEx max_repo_creation: -1 @@ -246,7 +246,7 @@ allow_create_organization: true prohibit_login: false avatar: avatar7 - avatar_email: user7@example.com + avatar_email: org7@example.com use_custom_avatar: false num_followers: 0 num_following: 0 @@ -594,17 +594,17 @@ - id: 17 - lower_name: user17 - name: user17 - full_name: User 17 - email: user17@example.com + lower_name: org17 + name: org17 + full_name: org 17 + email: org17@example.com keep_email_private: false email_notifications_preference: enabled passwd: ZogKvWdyEx:password passwd_hash_algo: dummy must_change_password: false login_source: 0 - login_name: user17 + login_name: org17 type: 1 salt: ZogKvWdyEx max_repo_creation: -1 @@ -616,7 +616,7 @@ allow_create_organization: true prohibit_login: false avatar: avatar17 - avatar_email: user17@example.com + avatar_email: org17@example.com use_custom_avatar: false num_followers: 0 num_following: 0 @@ -668,17 +668,17 @@ - id: 19 - lower_name: user19 - name: user19 - full_name: User 19 - email: user19@example.com + lower_name: org19 + name: org19 + full_name: Org 19 + email: org19@example.com keep_email_private: false email_notifications_preference: enabled passwd: ZogKvWdyEx:password passwd_hash_algo: dummy must_change_password: false login_source: 0 - login_name: user19 + login_name: org19 type: 1 salt: ZogKvWdyEx max_repo_creation: -1 @@ -690,7 +690,7 @@ allow_create_organization: true prohibit_login: false avatar: avatar19 - avatar_email: user19@example.com + avatar_email: org19@example.com use_custom_avatar: false num_followers: 0 num_following: 0 diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 2185f6fc42..65a5ddba31 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -27,9 +27,9 @@ func TestUpdateAssignee(t *testing.T) { _, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, user2.ID) assert.NoError(t, err) - user3, err := user_model.GetUserByID(db.DefaultContext, 3) + org3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) - _, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, user3.ID) + _, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, org3.ID) assert.NoError(t, err) user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him @@ -47,7 +47,7 @@ func TestUpdateAssignee(t *testing.T) { assert.NoError(t, err) var expectedAssignees []*user_model.User - expectedAssignees = append(expectedAssignees, user2, user3) + expectedAssignees = append(expectedAssignees, user2, org3) for in, assignee := range issue.Assignees { assert.Equal(t, assignee.ID, expectedAssignees[in].ID) diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index f1bccc0cf8..b2ff74f0cf 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -430,11 +430,11 @@ func TestIssue_ResolveMentions(t *testing.T) { // Public repo, doer testSuccess("user2", "repo1", "user1", []string{"user1"}, []int64{}) // Private repo, team member - testSuccess("user17", "big_test_private_4", "user20", []string{"user2"}, []int64{2}) + testSuccess("org17", "big_test_private_4", "user20", []string{"user2"}, []int64{2}) // Private repo, not a team member - testSuccess("user17", "big_test_private_4", "user20", []string{"user5"}, []int64{}) + testSuccess("org17", "big_test_private_4", "user20", []string{"user5"}, []int64{}) // Private repo, whole team - testSuccess("user17", "big_test_private_4", "user15", []string{"user17/owners"}, []int64{18}) + testSuccess("org17", "big_test_private_4", "user15", []string{"org17/owners"}, []int64{18}) } func TestResourceIndex(t *testing.T) { diff --git a/models/issues/issue_xref_test.go b/models/issues/issue_xref_test.go index 6e94c26272..5bcaf75518 100644 --- a/models/issues/issue_xref_test.go +++ b/models/issues/issue_xref_test.go @@ -54,7 +54,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { itarget = testCreateIssue(t, 3, 3, "title4", "content4", false) // Cross-reference to issue #4 by admin - content = fmt.Sprintf("content5, mentions user3/repo3#%d", itarget.Index) + content = fmt.Sprintf("content5, mentions org3/repo3#%d", itarget.Index) i = testCreateIssue(t, 2, 1, "title5", content, false) ref = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}) assert.Equal(t, issues_model.CommentTypeIssueRef, ref.Type) @@ -63,7 +63,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { assert.Equal(t, references.XRefActionNone, ref.RefAction) // Cross-reference to issue #4 with no permission - content = fmt.Sprintf("content6, mentions user3/repo3#%d", itarget.Index) + content = fmt.Sprintf("content6, mentions org3/repo3#%d", itarget.Index) i = testCreateIssue(t, 4, 5, "title6", content, false) unittest.AssertNotExistsBean(t, &issues_model.Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}) } diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go index 83977560ae..1105608858 100644 --- a/models/issues/pull_test.go +++ b/models/issues/pull_test.go @@ -317,9 +317,9 @@ func TestParseCodeOwnersLine(t *testing.T) { {Line: "# comment", Tokens: []string{}}, {Line: "!.* @user1 @org1/team1", Tokens: []string{"!.*", "@user1", "@org1/team1"}}, {Line: `.*\\.js @user2 #comment`, Tokens: []string{`.*\.js`, "@user2"}}, - {Line: `docs/(aws|google|azure)/[^/]*\\.(md|txt) @user3 @org2/team2`, Tokens: []string{`docs/(aws|google|azure)/[^/]*\.(md|txt)`, "@user3", "@org2/team2"}}, - {Line: `\#path @user3`, Tokens: []string{`#path`, "@user3"}}, - {Line: `path\ with\ spaces/ @user3`, Tokens: []string{`path with spaces/`, "@user3"}}, + {Line: `docs/(aws|google|azure)/[^/]*\\.(md|txt) @org3 @org2/team2`, Tokens: []string{`docs/(aws|google|azure)/[^/]*\.(md|txt)`, "@org3", "@org2/team2"}}, + {Line: `\#path @org3`, Tokens: []string{`#path`, "@org3"}}, + {Line: `path\ with\ spaces/ @org3`, Tokens: []string{`path with spaces/`, "@org3"}}, } for _, g := range given { @@ -335,7 +335,7 @@ func TestGetApprovers(t *testing.T) { // to assert that there are no duplicated approvers. setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly = false approvers := pr.GetApprovers() - expected := "Reviewed-by: User Five \nReviewed-by: User Six \n" + expected := "Reviewed-by: User Five \nReviewed-by: Org Six \n" assert.EqualValues(t, expected, approvers) } diff --git a/models/issues/reaction_test.go b/models/issues/reaction_test.go index e397568ac0..ceb7f2c2a6 100644 --- a/models/issues/reaction_test.go +++ b/models/issues/reaction_test.go @@ -83,7 +83,7 @@ func TestIssueReactionCount(t *testing.T) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) ghost := user_model.NewGhostUser() @@ -92,8 +92,8 @@ func TestIssueReactionCount(t *testing.T) { addReaction(t, user1.ID, issueID, 0, "heart") addReaction(t, user2.ID, issueID, 0, "heart") - addReaction(t, user3.ID, issueID, 0, "heart") - addReaction(t, user3.ID, issueID, 0, "+1") + addReaction(t, org3.ID, issueID, 0, "heart") + addReaction(t, org3.ID, issueID, 0, "+1") addReaction(t, user4.ID, issueID, 0, "+1") addReaction(t, user4.ID, issueID, 0, "heart") addReaction(t, ghost.ID, issueID, 0, "-1") @@ -136,7 +136,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) var issue1ID int64 = 1 @@ -144,7 +144,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) { addReaction(t, user1.ID, issue1ID, comment1ID, "heart") addReaction(t, user2.ID, issue1ID, comment1ID, "heart") - addReaction(t, user3.ID, issue1ID, comment1ID, "heart") + addReaction(t, org3.ID, issue1ID, comment1ID, "heart") addReaction(t, user4.ID, issue1ID, comment1ID, "+1") reactionsList, _, err := issues_model.FindReactions(db.DefaultContext, issues_model.FindReactionsOptions{ diff --git a/models/issues/review_test.go b/models/issues/review_test.go index 19816e864b..8f0e773f4c 100644 --- a/models/issues/review_test.go +++ b/models/issues/review_test.go @@ -80,7 +80,7 @@ func TestFindLatestReviews(t *testing.T) { assert.NoError(t, err) assert.Len(t, reviews, 2) assert.Equal(t, "duplicate review from user5 (latest)", reviews[0].Content) - assert.Equal(t, "singular review from user6 and final review for this pr", reviews[1].Content) + assert.Equal(t, "singular review from org6 and final review for this pr", reviews[1].Content) } func TestGetCurrentReview(t *testing.T) { @@ -123,13 +123,13 @@ func TestGetReviewersByIssueID(t *testing.T) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) expectedReviews := []*issues_model.Review{} expectedReviews = append(expectedReviews, &issues_model.Review{ - Reviewer: user3, + Reviewer: org3, Type: issues_model.ReviewTypeReject, UpdatedUnix: 946684812, }, diff --git a/models/issues/stopwatch_test.go b/models/issues/stopwatch_test.go index ea3827a1f6..fa937ecbed 100644 --- a/models/issues/stopwatch_test.go +++ b/models/issues/stopwatch_test.go @@ -60,7 +60,7 @@ func TestCreateOrStopIssueStopwatch(t *testing.T) { user2, err := user_model.GetUserByID(db.DefaultContext, 2) assert.NoError(t, err) - user3, err := user_model.GetUserByID(db.DefaultContext, 3) + org3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) @@ -68,7 +68,7 @@ func TestCreateOrStopIssueStopwatch(t *testing.T) { issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) assert.NoError(t, err) - assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(user3, issue1)) + assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(org3, issue1)) sw := unittest.AssertExistsAndLoadBean(t, &issues_model.Stopwatch{UserID: 3, IssueID: 1}) assert.LessOrEqual(t, sw.CreatedUnix, timeutil.TimeStampNow()) diff --git a/models/issues/tracked_time_test.go b/models/issues/tracked_time_test.go index 1d88109183..caced78c9e 100644 --- a/models/issues/tracked_time_test.go +++ b/models/issues/tracked_time_test.go @@ -18,14 +18,14 @@ import ( func TestAddTime(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user3, err := user_model.GetUserByID(db.DefaultContext, 3) + org3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) assert.NoError(t, err) // 3661 = 1h 1min 1s - trackedTime, err := issues_model.AddTime(db.DefaultContext, user3, issue1, 3661, time.Now()) + trackedTime, err := issues_model.AddTime(db.DefaultContext, org3, issue1, 3661, time.Now()) assert.NoError(t, err) assert.Equal(t, int64(3), trackedTime.UserID) assert.Equal(t, int64(1), trackedTime.IssueID) diff --git a/models/organization/org_test.go b/models/organization/org_test.go index 226807232c..d36736b5c2 100644 --- a/models/organization/org_test.go +++ b/models/organization/org_test.go @@ -115,10 +115,10 @@ func TestUser_GetMembers(t *testing.T) { func TestGetOrgByName(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - org, err := organization.GetOrgByName(db.DefaultContext, "user3") + org, err := organization.GetOrgByName(db.DefaultContext, "org3") assert.NoError(t, err) assert.EqualValues(t, 3, org.ID) - assert.Equal(t, "user3", org.Name) + assert.Equal(t, "org3", org.Name) _, err = organization.GetOrgByName(db.DefaultContext, "user2") // user2 is an individual assert.True(t, organization.IsErrOrgNotExist(err)) @@ -343,7 +343,7 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { func TestHasOrgVisibleTypePublic(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) const newOrgName = "test-org-public" org := &organization.Organization{ @@ -356,7 +356,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) - test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user3) + test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), org3) test3 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil) assert.True(t, test1) // owner of org assert.True(t, test2) // user not a part of org @@ -366,7 +366,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { func TestHasOrgVisibleTypeLimited(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) const newOrgName = "test-org-limited" org := &organization.Organization{ @@ -379,7 +379,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) - test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user3) + test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), org3) test3 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil) assert.True(t, test1) // owner of org assert.True(t, test2) // user not a part of org @@ -389,7 +389,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { func TestHasOrgVisibleTypePrivate(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) const newOrgName = "test-org-private" org := &organization.Organization{ @@ -402,7 +402,7 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) { org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) - test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user3) + test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), org3) test3 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil) assert.True(t, test1) // owner of org assert.False(t, test2) // user not a part of org @@ -493,7 +493,7 @@ func TestCreateOrganization3(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - org := &organization.Organization{Name: "user3"} // should already exist + org := &organization.Organization{Name: "org3"} // should already exist unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check err := organization.CreateOrganization(org, owner) assert.Error(t, err) diff --git a/models/organization/team_invite_test.go b/models/organization/team_invite_test.go index cd6e1fe2ef..45db8494e8 100644 --- a/models/organization/team_invite_test.go +++ b/models/organization/team_invite_test.go @@ -30,12 +30,12 @@ func TestTeamInvite(t *testing.T) { t.Run("CreateAndRemove", func(t *testing.T) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - invite, err := organization.CreateTeamInvite(db.DefaultContext, user1, team, "user3@example.com") + invite, err := organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com") assert.NotNil(t, invite) assert.NoError(t, err) // Shouldn't allow duplicate invite - _, err = organization.CreateTeamInvite(db.DefaultContext, user1, team, "user3@example.com") + _, err = organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com") assert.Error(t, err) // should remove invite diff --git a/models/repo/repo_list_test.go b/models/repo/repo_list_test.go index 7097b6ea14..8a1799aac0 100644 --- a/models/repo/repo_list_test.go +++ b/models/repo/repo_list_test.go @@ -66,7 +66,7 @@ func getTestCases() []struct { count: 0, }, { - name: "PublicRepositoriesOfUser3", + name: "PublicRepositoriesOfOrg3", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Collaborate: util.OptionalBoolFalse}, count: 2, }, @@ -81,7 +81,7 @@ func getTestCases() []struct { count: 0, }, { - name: "PublicAndPrivateRepositoriesOfUser3", + name: "PublicAndPrivateRepositoriesOfOrg3", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Private: true, Collaborate: util.OptionalBoolFalse}, count: 4, }, @@ -96,7 +96,7 @@ func getTestCases() []struct { count: 1, }, { - name: "PublicRepositoriesOfUser3IncludingCollaborative", + name: "PublicRepositoriesOfOrg3IncludingCollaborative", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20}, count: 3, }, @@ -111,7 +111,7 @@ func getTestCases() []struct { count: 4, }, { - name: "PublicAndPrivateRepositoriesOfUser3IncludingCollaborative", + name: "PublicAndPrivateRepositoriesOfOrg3IncludingCollaborative", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Private: true}, count: 7, }, @@ -168,7 +168,7 @@ func getTestCases() []struct { { name: "OwnerSlashRepoSearch", opts: &repo_model.SearchRepoOptions{Keyword: "user/repo2", ListOptions: db.ListOptions{Page: 1, PageSize: 10}, Private: true, OwnerID: 0}, - count: 3, + count: 2, }, { name: "OwnerSlashSearch", diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go index 92a58ea3f9..fb021561c3 100644 --- a/models/repo/repo_test.go +++ b/models/repo/repo_test.go @@ -121,7 +121,7 @@ func TestMetas(t *testing.T) { metas = repo.ComposeMetas() assert.Contains(t, metas, "org") assert.Contains(t, metas, "teams") - assert.Equal(t, "user3", metas["org"]) + assert.Equal(t, "org3", metas["org"]) assert.Equal(t, ",owners,team1,", metas["teams"]) } diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 8352adc948..7364d4d02c 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -41,10 +41,10 @@ func TestRepositoryTransfer(t *testing.T) { assert.NoError(t, transfer.LoadAttributes(db.DefaultContext)) assert.Equal(t, "user2", transfer.Recipient.Name) - user6 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) + org6 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Only transfer can be started at any given time - err = CreatePendingRepositoryTransfer(db.DefaultContext, doer, user6, repo.ID, nil) + err = CreatePendingRepositoryTransfer(db.DefaultContext, doer, org6, repo.ID, nil) assert.Error(t, err) assert.True(t, IsErrRepoTransferInProgress(err)) diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index 53fd18c303..f2b383fe4b 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -209,7 +209,7 @@ func TestListEmails(t *testing.T) { } assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 18 })) - // 'user3' is an organization + // 'org3' is an organization assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 3 })) // Must find no records diff --git a/models/user/user_test.go b/models/user/user_test.go index 44eaf63556..032dcba676 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -39,7 +39,7 @@ func TestGetUserEmailsByNames(t *testing.T) { assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "user9"})) assert.ElementsMatch(t, []string{"user8@example.com", "user5@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "user5"})) - assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "user7"})) + assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "org7"})) } func TestCanCreateOrganization(t *testing.T) { @@ -372,9 +372,9 @@ func TestUpdateUser(t *testing.T) { func TestUpdateUserEmailAlreadyUsed(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) - user2.Email = user3.Email + user2.Email = org3.Email err := user_model.UpdateUser(db.DefaultContext, user2, true) assert.True(t, user_model.IsErrEmailAlreadyUsed(err)) } diff --git a/modules/references/references_test.go b/modules/references/references_test.go index 75e002c99a..b60d6b0459 100644 --- a/modules/references/references_test.go +++ b/modules/references/references_test.go @@ -78,15 +78,15 @@ func TestFindAllIssueReferences(t *testing.T) { []testResult{}, }, { - "This user3/repo4#200 yes.", + "This org3/repo4#200 yes.", []testResult{ - {200, "user3", "repo4", "200", false, XRefActionNone, &RefSpan{Start: 5, End: 20}, nil, ""}, + {200, "org3", "repo4", "200", false, XRefActionNone, &RefSpan{Start: 5, End: 19}, nil, ""}, }, }, { - "This user3/repo4!200 yes.", + "This org3/repo4!200 yes.", []testResult{ - {200, "user3", "repo4", "200", true, XRefActionNone, &RefSpan{Start: 5, End: 20}, nil, ""}, + {200, "org3", "repo4", "200", true, XRefActionNone, &RefSpan{Start: 5, End: 19}, nil, ""}, }, }, { @@ -106,13 +106,13 @@ func TestFindAllIssueReferences(t *testing.T) { }, }, { - "This [four](http://gitea.com:3000/user3/repo4/issues/203) yes.", + "This [four](http://gitea.com:3000/org3/repo4/issues/203) yes.", []testResult{ - {203, "user3", "repo4", "203", false, XRefActionNone, nil, nil, ""}, + {203, "org3", "repo4", "203", false, XRefActionNone, nil, nil, ""}, }, }, { - "This [five](http://github.com/user3/repo4/issues/204) no.", + "This [five](http://github.com/org3/repo4/issues/204) no.", []testResult{}, }, { @@ -151,9 +151,9 @@ func TestFindAllIssueReferences(t *testing.T) { }, }, { - "Do you fix user6/repo6#300 ? yes", + "Do you fix org6/repo6#300 ? yes", []testResult{ - {300, "user6", "repo6", "300", false, XRefActionCloses, &RefSpan{Start: 11, End: 26}, &RefSpan{Start: 7, End: 10}, ""}, + {300, "org6", "repo6", "300", false, XRefActionCloses, &RefSpan{Start: 11, End: 25}, &RefSpan{Start: 7, End: 10}, ""}, }, }, { @@ -190,9 +190,9 @@ func TestFindAllIssueReferences(t *testing.T) { }, }, { - "This user3/repo4#200, yes.", + "This org3/repo4#200, yes.", []testResult{ - {200, "user3", "repo4", "200", false, XRefActionNone, &RefSpan{Start: 5, End: 20}, nil, ""}, + {200, "org3", "repo4", "200", false, XRefActionNone, &RefSpan{Start: 5, End: 19}, nil, ""}, }, }, { @@ -498,15 +498,15 @@ func TestCustomizeCloseKeywords(t *testing.T) { }, }, { - "Cerró user6/repo6#300 yes", + "Cerró org6/repo6#300 yes", []testResult{ - {300, "user6", "repo6", "300", false, XRefActionCloses, &RefSpan{Start: 7, End: 22}, &RefSpan{Start: 0, End: 6}, ""}, + {300, "org6", "repo6", "300", false, XRefActionCloses, &RefSpan{Start: 7, End: 21}, &RefSpan{Start: 0, End: 6}, ""}, }, }, { - "Reabre user3/repo4#200 yes", + "Reabre org3/repo4#200 yes", []testResult{ - {200, "user3", "repo4", "200", false, XRefActionReopens, &RefSpan{Start: 7, End: 22}, &RefSpan{Start: 0, End: 6}, ""}, + {200, "org3", "repo4", "200", false, XRefActionReopens, &RefSpan{Start: 7, End: 21}, &RefSpan{Start: 0, End: 6}, ""}, }, }, } diff --git a/services/issue/commit_test.go b/services/issue/commit_test.go index 1bc9f6f951..0518803683 100644 --- a/services/issue/commit_test.go +++ b/services/issue/commit_test.go @@ -262,7 +262,7 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { CommitterName: "User Ten", AuthorEmail: "user10@example.com", AuthorName: "User Ten", - Message: "close user3/repo3#1", + Message: "close org3/repo3#1", }, { Sha1: "abcdef4", @@ -270,7 +270,7 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { CommitterName: "User Ten", AuthorEmail: "user10@example.com", AuthorName: "User Ten", - Message: "close " + setting.AppURL + "user3/repo3/issues/1", + Message: "close " + setting.AppURL + "org3/repo3/issues/1", }, } diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index 45a5b381fe..d55c76ea47 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -42,7 +42,7 @@ func TestTransferOwnership(t *testing.T) { transferredRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) assert.EqualValues(t, 2, transferredRepo.OwnerID) - exist, err := util.IsExist(repo_model.RepoPath("user3", "repo3")) + exist, err := util.IsExist(repo_model.RepoPath("org3", "repo3")) assert.NoError(t, err) assert.False(t, exist) exist, err = util.IsExist(repo_model.RepoPath("user2", "repo3")) @@ -52,7 +52,7 @@ func TestTransferOwnership(t *testing.T) { OpType: activities_model.ActionTransferRepo, ActUserID: 2, RepoID: 3, - Content: "user3/repo3", + Content: "org3/repo3", }) unittest.CheckConsistencyFor(t, &repo_model.Repository{}, &user_model.User{}, &organization.Team{}) diff --git a/tests/gitea-repositories-meta/user3/repo3.git/HEAD b/tests/gitea-repositories-meta/org3/repo3.git/HEAD similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/HEAD rename to tests/gitea-repositories-meta/org3/repo3.git/HEAD diff --git a/tests/gitea-repositories-meta/user3/repo3.git/config b/tests/gitea-repositories-meta/org3/repo3.git/config similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/config rename to tests/gitea-repositories-meta/org3/repo3.git/config diff --git a/tests/gitea-repositories-meta/user3/repo3.git/description b/tests/gitea-repositories-meta/org3/repo3.git/description similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/description rename to tests/gitea-repositories-meta/org3/repo3.git/description diff --git a/tests/gitea-repositories-meta/user3/repo3.git/hooks/post-receive b/tests/gitea-repositories-meta/org3/repo3.git/hooks/post-receive similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/hooks/post-receive rename to tests/gitea-repositories-meta/org3/repo3.git/hooks/post-receive diff --git a/tests/gitea-repositories-meta/user3/repo3.git/hooks/post-receive.d/gitea b/tests/gitea-repositories-meta/org3/repo3.git/hooks/post-receive.d/gitea similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/hooks/post-receive.d/gitea rename to tests/gitea-repositories-meta/org3/repo3.git/hooks/post-receive.d/gitea diff --git a/tests/gitea-repositories-meta/user3/repo3.git/hooks/pre-receive b/tests/gitea-repositories-meta/org3/repo3.git/hooks/pre-receive similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/hooks/pre-receive rename to tests/gitea-repositories-meta/org3/repo3.git/hooks/pre-receive diff --git a/tests/gitea-repositories-meta/user3/repo3.git/hooks/pre-receive.d/gitea b/tests/gitea-repositories-meta/org3/repo3.git/hooks/pre-receive.d/gitea similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/hooks/pre-receive.d/gitea rename to tests/gitea-repositories-meta/org3/repo3.git/hooks/pre-receive.d/gitea diff --git a/tests/gitea-repositories-meta/user3/repo3.git/hooks/update b/tests/gitea-repositories-meta/org3/repo3.git/hooks/update similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/hooks/update rename to tests/gitea-repositories-meta/org3/repo3.git/hooks/update diff --git a/tests/gitea-repositories-meta/user3/repo3.git/hooks/update.d/gitea b/tests/gitea-repositories-meta/org3/repo3.git/hooks/update.d/gitea similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/hooks/update.d/gitea rename to tests/gitea-repositories-meta/org3/repo3.git/hooks/update.d/gitea diff --git a/tests/gitea-repositories-meta/user3/repo3.git/info/exclude b/tests/gitea-repositories-meta/org3/repo3.git/info/exclude similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/info/exclude rename to tests/gitea-repositories-meta/org3/repo3.git/info/exclude diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 b/tests/gitea-repositories-meta/org3/repo3.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 rename to tests/gitea-repositories-meta/org3/repo3.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 b/tests/gitea-repositories-meta/org3/repo3.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 rename to tests/gitea-repositories-meta/org3/repo3.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 b/tests/gitea-repositories-meta/org3/repo3.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 rename to tests/gitea-repositories-meta/org3/repo3.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f b/tests/gitea-repositories-meta/org3/repo3.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f rename to tests/gitea-repositories-meta/org3/repo3.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 b/tests/gitea-repositories-meta/org3/repo3.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 rename to tests/gitea-repositories-meta/org3/repo3.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc b/tests/gitea-repositories-meta/org3/repo3.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc rename to tests/gitea-repositories-meta/org3/repo3.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 b/tests/gitea-repositories-meta/org3/repo3.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 rename to tests/gitea-repositories-meta/org3/repo3.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 diff --git a/tests/gitea-repositories-meta/user3/repo3.git/objects/ee/16d127df463aa491e08958120f2108b02468df b/tests/gitea-repositories-meta/org3/repo3.git/objects/ee/16d127df463aa491e08958120f2108b02468df similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/objects/ee/16d127df463aa491e08958120f2108b02468df rename to tests/gitea-repositories-meta/org3/repo3.git/objects/ee/16d127df463aa491e08958120f2108b02468df diff --git a/tests/gitea-repositories-meta/user3/repo3.git/refs/heads/master b/tests/gitea-repositories-meta/org3/repo3.git/refs/heads/master similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/refs/heads/master rename to tests/gitea-repositories-meta/org3/repo3.git/refs/heads/master diff --git a/tests/gitea-repositories-meta/user3/repo3.git/refs/heads/test_branch b/tests/gitea-repositories-meta/org3/repo3.git/refs/heads/test_branch similarity index 100% rename from tests/gitea-repositories-meta/user3/repo3.git/refs/heads/test_branch rename to tests/gitea-repositories-meta/org3/repo3.git/refs/heads/test_branch diff --git a/tests/gitea-repositories-meta/user3/repo5.git/HEAD b/tests/gitea-repositories-meta/org3/repo5.git/HEAD similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/HEAD rename to tests/gitea-repositories-meta/org3/repo5.git/HEAD diff --git a/tests/gitea-repositories-meta/user3/repo5.git/config b/tests/gitea-repositories-meta/org3/repo5.git/config similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/config rename to tests/gitea-repositories-meta/org3/repo5.git/config diff --git a/tests/gitea-repositories-meta/user3/repo5.git/description b/tests/gitea-repositories-meta/org3/repo5.git/description similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/description rename to tests/gitea-repositories-meta/org3/repo5.git/description diff --git a/tests/gitea-repositories-meta/user3/repo5.git/hooks/post-receive b/tests/gitea-repositories-meta/org3/repo5.git/hooks/post-receive similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/hooks/post-receive rename to tests/gitea-repositories-meta/org3/repo5.git/hooks/post-receive diff --git a/tests/gitea-repositories-meta/user3/repo5.git/hooks/post-receive.d/gitea b/tests/gitea-repositories-meta/org3/repo5.git/hooks/post-receive.d/gitea similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/hooks/post-receive.d/gitea rename to tests/gitea-repositories-meta/org3/repo5.git/hooks/post-receive.d/gitea diff --git a/tests/gitea-repositories-meta/user3/repo5.git/hooks/pre-receive b/tests/gitea-repositories-meta/org3/repo5.git/hooks/pre-receive similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/hooks/pre-receive rename to tests/gitea-repositories-meta/org3/repo5.git/hooks/pre-receive diff --git a/tests/gitea-repositories-meta/user3/repo5.git/hooks/pre-receive.d/gitea b/tests/gitea-repositories-meta/org3/repo5.git/hooks/pre-receive.d/gitea similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/hooks/pre-receive.d/gitea rename to tests/gitea-repositories-meta/org3/repo5.git/hooks/pre-receive.d/gitea diff --git a/tests/gitea-repositories-meta/user3/repo5.git/hooks/update b/tests/gitea-repositories-meta/org3/repo5.git/hooks/update similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/hooks/update rename to tests/gitea-repositories-meta/org3/repo5.git/hooks/update diff --git a/tests/gitea-repositories-meta/user3/repo5.git/hooks/update.d/gitea b/tests/gitea-repositories-meta/org3/repo5.git/hooks/update.d/gitea similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/hooks/update.d/gitea rename to tests/gitea-repositories-meta/org3/repo5.git/hooks/update.d/gitea diff --git a/tests/gitea-repositories-meta/user3/repo5.git/info/exclude b/tests/gitea-repositories-meta/org3/repo5.git/info/exclude similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/info/exclude rename to tests/gitea-repositories-meta/org3/repo5.git/info/exclude diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 b/tests/gitea-repositories-meta/org3/repo5.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 rename to tests/gitea-repositories-meta/org3/repo5.git/objects/20/ade30d25e0ecaeec84e7f542a8456900858240 diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 b/tests/gitea-repositories-meta/org3/repo5.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 rename to tests/gitea-repositories-meta/org3/repo5.git/objects/27/74debeea6dc742cc4971a92db0e08b95b60588 diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 b/tests/gitea-repositories-meta/org3/repo5.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 rename to tests/gitea-repositories-meta/org3/repo5.git/objects/2a/47ca4b614a9f5a43abbd5ad851a54a616ffee6 diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f b/tests/gitea-repositories-meta/org3/repo5.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f rename to tests/gitea-repositories-meta/org3/repo5.git/objects/2f/9b22fd3159a43b7b4e5dd806fcd544edf8716f diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 b/tests/gitea-repositories-meta/org3/repo5.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 rename to tests/gitea-repositories-meta/org3/repo5.git/objects/d2/2b4d4daa5be07329fcef6ed458f00cf3392da0 diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc b/tests/gitea-repositories-meta/org3/repo5.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc rename to tests/gitea-repositories-meta/org3/repo5.git/objects/d5/6a3073c1dbb7b15963110a049d50cdb5db99fc diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 b/tests/gitea-repositories-meta/org3/repo5.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 rename to tests/gitea-repositories-meta/org3/repo5.git/objects/ec/f0db3c1ec806522de4b491fb9a3c7457398c61 diff --git a/tests/gitea-repositories-meta/user3/repo5.git/objects/ee/16d127df463aa491e08958120f2108b02468df b/tests/gitea-repositories-meta/org3/repo5.git/objects/ee/16d127df463aa491e08958120f2108b02468df similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/objects/ee/16d127df463aa491e08958120f2108b02468df rename to tests/gitea-repositories-meta/org3/repo5.git/objects/ee/16d127df463aa491e08958120f2108b02468df diff --git a/tests/gitea-repositories-meta/user3/repo5.git/refs/heads/master b/tests/gitea-repositories-meta/org3/repo5.git/refs/heads/master similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/refs/heads/master rename to tests/gitea-repositories-meta/org3/repo5.git/refs/heads/master diff --git a/tests/gitea-repositories-meta/user3/repo5.git/refs/heads/test_branch b/tests/gitea-repositories-meta/org3/repo5.git/refs/heads/test_branch similarity index 100% rename from tests/gitea-repositories-meta/user3/repo5.git/refs/heads/test_branch rename to tests/gitea-repositories-meta/org3/repo5.git/refs/heads/test_branch diff --git a/tests/integration/actions_trigger_test.go b/tests/integration/actions_trigger_test.go index 56718397f4..82c1967b52 100644 --- a/tests/integration/actions_trigger_test.go +++ b/tests/integration/actions_trigger_test.go @@ -28,7 +28,7 @@ import ( func TestPullRequestTargetEvent(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the base repo - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the forked repo + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the forked repo // create the base repo baseRepo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ @@ -52,7 +52,7 @@ func TestPullRequestTargetEvent(t *testing.T) { assert.NoError(t, err) // create the forked repo - forkedRepo, err := repo_service.ForkRepository(git.DefaultContext, user2, user3, repo_service.ForkRepoOptions{ + forkedRepo, err := repo_service.ForkRepository(git.DefaultContext, user2, org3, repo_service.ForkRepoOptions{ BaseRepo: baseRepo, Name: "forked-repo-pull-request-target", Description: "test pull-request-target event", @@ -89,7 +89,7 @@ func TestPullRequestTargetEvent(t *testing.T) { assert.NotEmpty(t, addWorkflowToBaseResp) // add a new file to the forked repo - addFileToForkedResp, err := files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, user3, &files_service.ChangeRepoFilesOptions{ + addFileToForkedResp, err := files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, org3, &files_service.ChangeRepoFilesOptions{ Files: []*files_service.ChangeRepoFile{ { Operation: "create", @@ -101,12 +101,12 @@ func TestPullRequestTargetEvent(t *testing.T) { OldBranch: "main", NewBranch: "fork-branch-1", Author: &files_service.IdentityOptions{ - Name: user3.Name, - Email: user3.Email, + Name: org3.Name, + Email: org3.Email, }, Committer: &files_service.IdentityOptions{ - Name: user3.Name, - Email: user3.Email, + Name: org3.Name, + Email: org3.Email, }, Dates: &files_service.CommitDateOptions{ Author: time.Now(), @@ -120,8 +120,8 @@ func TestPullRequestTargetEvent(t *testing.T) { pullIssue := &issues_model.Issue{ RepoID: baseRepo.ID, Title: "Test pull-request-target-event", - PosterID: user3.ID, - Poster: user3, + PosterID: org3.ID, + Poster: org3, IsPull: true, } pullRequest := &issues_model.PullRequest{ @@ -143,7 +143,7 @@ func TestPullRequestTargetEvent(t *testing.T) { assert.Equal(t, actions_module.GithubEventPullRequestTarget, actionRun.TriggerEvent) // add another file whose name cannot match the specified path - addFileToForkedResp, err = files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, user3, &files_service.ChangeRepoFilesOptions{ + addFileToForkedResp, err = files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, org3, &files_service.ChangeRepoFilesOptions{ Files: []*files_service.ChangeRepoFile{ { Operation: "create", @@ -155,12 +155,12 @@ func TestPullRequestTargetEvent(t *testing.T) { OldBranch: "main", NewBranch: "fork-branch-2", Author: &files_service.IdentityOptions{ - Name: user3.Name, - Email: user3.Email, + Name: org3.Name, + Email: org3.Email, }, Committer: &files_service.IdentityOptions{ - Name: user3.Name, - Email: user3.Email, + Name: org3.Name, + Email: org3.Email, }, Dates: &files_service.CommitDateOptions{ Author: time.Now(), @@ -174,8 +174,8 @@ func TestPullRequestTargetEvent(t *testing.T) { pullIssue = &issues_model.Issue{ RepoID: baseRepo.ID, Title: "A mismatched path cannot trigger pull-request-target-event", - PosterID: user3.ID, - Poster: user3, + PosterID: org3.ID, + Poster: org3, IsPull: true, } pullRequest = &issues_model.PullRequest{ diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 5d4b9725dd..808d288356 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -298,14 +298,14 @@ func TestAPISearchIssues(t *testing.T) { DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 8) - query = url.Values{"owner": {"user3"}, "token": {token}} // organization + query = url.Values{"owner": {"org3"}, "token": {token}} // organization link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 5) - query = url.Values{"owner": {"user3"}, "team": {"team1"}, "token": {token}} // organization + team + query = url.Values{"owner": {"org3"}, "team": {"team1"}, "token": {token}} // organization + team link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_org_avatar_test.go b/tests/integration/api_org_avatar_test.go index e0a4150e9f..91100c8eb7 100644 --- a/tests/integration/api_org_avatar_test.go +++ b/tests/integration/api_org_avatar_test.go @@ -34,7 +34,7 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs/user3/avatar?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) MakeRequest(t, req, http.StatusNoContent) // Test what happens if you don't have a valid Base64 string @@ -42,7 +42,7 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/user3/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -56,7 +56,7 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/user3/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) MakeRequest(t, req, http.StatusInternalServerError) } @@ -67,6 +67,6 @@ func TestAPIDeleteOrgAvatar(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization) - req := NewRequest(t, "DELETE", "/api/v1/orgs/user3/avatar?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/orgs/org3/avatar?token="+token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 83a101716b..f19b46c2f4 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -102,19 +102,19 @@ func TestAPIOrgEdit(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization) org := api.EditOrgOption{ - FullName: "User3 organization new full name", + FullName: "Org3 organization new full name", Description: "A new description", Website: "https://try.gitea.io/new", Location: "Beijing", Visibility: "private", } - req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/user3?token="+token, &org) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3?token="+token, &org) resp := MakeRequest(t, req, http.StatusOK) var apiOrg api.Organization DecodeJSON(t, resp, &apiOrg) - assert.Equal(t, "user3", apiOrg.Name) + assert.Equal(t, "org3", apiOrg.Name) assert.Equal(t, org.FullName, apiOrg.FullName) assert.Equal(t, org.Description, apiOrg.Description) assert.Equal(t, org.Website, apiOrg.Website) @@ -129,13 +129,13 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization) org := api.EditOrgOption{ - FullName: "User3 organization new full name", + FullName: "Org3 organization new full name", Description: "A new description", Website: "https://try.gitea.io/new", Location: "Beijing", Visibility: "badvisibility", } - req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/user3?token="+token, &org) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3?token="+token, &org) MakeRequest(t, req, http.StatusUnprocessableEntity) }) } @@ -180,7 +180,7 @@ func TestAPIGetAll(t *testing.T) { DecodeJSON(t, resp, &apiOrgList) assert.Len(t, apiOrgList, 7) - assert.Equal(t, "org25", apiOrgList[0].FullName) + assert.Equal(t, "org 17", apiOrgList[0].FullName) assert.Equal(t, "public", apiOrgList[0].Visibility) } diff --git a/tests/integration/api_repo_branch_test.go b/tests/integration/api_repo_branch_test.go index 3065a92d69..852c666c34 100644 --- a/tests/integration/api_repo_branch_test.go +++ b/tests/integration/api_repo_branch_test.go @@ -30,7 +30,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { session := loginUser(t, user1.LowerName) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/user3/%s/branches", repo3.Name)) // a plain repo + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches", repo3.Name)) // a plain repo link.RawQuery = url.Values{"token": {token}}.Encode() resp := MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) bs, err := io.ReadAll(resp.Body) @@ -42,7 +42,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { assert.EqualValues(t, "test_branch", branches[0].Name) assert.EqualValues(t, "master", branches[1].Name) - link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/user3/%s/branches/test_branch", repo3.Name)) + link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch", repo3.Name)) link2.RawQuery = url.Values{"token": {token}}.Encode() resp = MakeRequest(t, NewRequest(t, "GET", link2.String()), http.StatusOK) bs, err = io.ReadAll(resp.Body) @@ -73,7 +73,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { assert.EqualValues(t, "test_branch2", branches[1].Name) assert.EqualValues(t, "master", branches[2].Name) - link3, _ := url.Parse(fmt.Sprintf("/api/v1/repos/user3/%s/branches/test_branch2", repo3.Name)) + link3, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch2", repo3.Name)) MakeRequest(t, NewRequest(t, "DELETE", link3.String()), http.StatusNotFound) link3.RawQuery = url.Values{"token": {token}}.Encode() @@ -90,7 +90,7 @@ func TestAPIRepoBranchesMirror(t *testing.T) { session := loginUser(t, user1.LowerName) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/user3/%s/branches", repo5.Name)) // a mirror repo + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches", repo5.Name)) // a mirror repo link.RawQuery = url.Values{"token": {token}}.Encode() resp := MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) bs, err := io.ReadAll(resp.Body) @@ -102,7 +102,7 @@ func TestAPIRepoBranchesMirror(t *testing.T) { assert.EqualValues(t, "test_branch", branches[0].Name) assert.EqualValues(t, "master", branches[1].Name) - link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/user3/%s/branches/test_branch", repo5.Name)) + link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch", repo5.Name)) link2.RawQuery = url.Values{"token": {token}}.Encode() resp = MakeRequest(t, NewRequest(t, "GET", link2.String()), http.StatusOK) bs, err = io.ReadAll(resp.Body) diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index b7242fb316..0e992c2df2 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -138,7 +138,7 @@ func TestAPIRepoEdit(t *testing.T) { bFalse, bTrue := false, true user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -330,21 +330,21 @@ func TestAPIRepoEdit(t *testing.T) { }) _ = MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" where user2 is a collaborator + // Test using org repo "org3/repo3" where user2 is a collaborator origRepoEditOption = getRepoEditOptionFromRepo(repo3) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user3.Name, repo3.Name, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", org3.Name, repo3.Name, token2) req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) MakeRequest(t, req, http.StatusOK) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user3.Name, *repoEditOption.Name, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", org3.Name, *repoEditOption.Name, token2) req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) _ = MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" with no user token + // Test using org repo "org3/repo3" with no user token origRepoEditOption = getRepoEditOptionFromRepo(repo3) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s", user3.Name, repo3.Name) + url = fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name) req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index c48abe7f0f..fbe0b5bcd0 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -141,7 +141,7 @@ func BenchmarkAPICreateFileMedium(b *testing.B) { func TestAPICreateFile(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -254,19 +254,19 @@ func TestAPICreateFile(t *testing.T) { req = NewRequestWithJSON(t, "POST", url, &createFileOptions) MakeRequest(t, req, http.StatusCreated) - // Test using org repo "user3/repo3" where user2 is a collaborator + // Test using org repo "org3/repo3" where user2 is a collaborator createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user3.Name, repo3.Name, treePath, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) req = NewRequestWithJSON(t, "POST", url, &createFileOptions) MakeRequest(t, req, http.StatusCreated) - // Test using org repo "user3/repo3" with no user token + // Test using org repo "org3/repo3" with no user token createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user3.Name, repo3.Name, treePath) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) req = NewRequestWithJSON(t, "POST", url, &createFileOptions) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index df9e801e2c..c6ab7a0e61 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -40,7 +40,7 @@ func getDeleteFileOptions() *api.DeleteFileOptions { func TestAPIDeleteFile(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -139,21 +139,21 @@ func TestAPIDeleteFile(t *testing.T) { req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" where user2 is a collaborator + // Test using org repo "org3/repo3" where user2 is a collaborator fileID++ treePath = fmt.Sprintf("delete/file%d.txt", fileID) - createFile(user3, repo3, treePath) + createFile(org3, repo3, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user3.Name, repo3.Name, treePath, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" with no user token + // Test using org repo "org3/repo3" with no user token fileID++ treePath = fmt.Sprintf("delete/file%d.txt", fileID) - createFile(user3, repo3, treePath) + createFile(org3, repo3, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user3.Name, repo3.Name, treePath) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index 9a29ccbf5e..ecf24cdbf9 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -108,7 +108,7 @@ func getExpectedFileResponseForUpdate(commitID, treePath, lastCommitSHA string) func TestAPIUpdateFile(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -247,21 +247,21 @@ func TestAPIUpdateFile(t *testing.T) { req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" where user2 is a collaborator + // Test using org repo "org3/repo3" where user2 is a collaborator fileID++ treePath = fmt.Sprintf("update/file%d.txt", fileID) - createFile(user3, repo3, treePath) + createFile(org3, repo3, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user3.Name, repo3.Name, treePath, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" with no user token + // Test using org repo "org3/repo3" with no user token fileID++ treePath = fmt.Sprintf("update/file%d.txt", fileID) - createFile(user3, repo3, treePath) + createFile(org3, repo3, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user3.Name, repo3.Name, treePath) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_repo_files_change_test.go b/tests/integration/api_repo_files_change_test.go index c79764a067..1ab759497f 100644 --- a/tests/integration/api_repo_files_change_test.go +++ b/tests/integration/api_repo_files_change_test.go @@ -63,7 +63,7 @@ func getChangeFilesOptions() *api.ChangeFilesOptions { func TestAPIChangeFiles(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -261,33 +261,33 @@ func TestAPIChangeFiles(t *testing.T) { req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) MakeRequest(t, req, http.StatusCreated) - // Test using org repo "user3/repo3" where user2 is a collaborator + // Test using org repo "org3/repo3" where user2 is a collaborator fileID++ createTreePath = fmt.Sprintf("new/file%d.txt", fileID) updateTreePath = fmt.Sprintf("update/file%d.txt", fileID) deleteTreePath = fmt.Sprintf("delete/file%d.txt", fileID) - createFile(user3, repo3, updateTreePath) - createFile(user3, repo3, deleteTreePath) + createFile(org3, repo3, updateTreePath) + createFile(org3, repo3, deleteTreePath) changeFilesOptions = getChangeFilesOptions() changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user3.Name, repo3.Name, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", org3.Name, repo3.Name, token2) req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) MakeRequest(t, req, http.StatusCreated) - // Test using org repo "user3/repo3" with no user token + // Test using org repo "org3/repo3" with no user token fileID++ createTreePath = fmt.Sprintf("new/file%d.txt", fileID) updateTreePath = fmt.Sprintf("update/file%d.txt", fileID) deleteTreePath = fmt.Sprintf("delete/file%d.txt", fileID) - createFile(user3, repo3, updateTreePath) - createFile(user3, repo3, deleteTreePath) + createFile(org3, repo3, updateTreePath) + createFile(org3, repo3, deleteTreePath) changeFilesOptions = getChangeFilesOptions() changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents", user3.Name, repo3.Name) + url = fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name) req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_repo_get_contents_list_test.go b/tests/integration/api_repo_get_contents_list_test.go index f91305abef..f3a5159115 100644 --- a/tests/integration/api_repo_get_contents_list_test.go +++ b/tests/integration/api_repo_get_contents_list_test.go @@ -56,7 +56,7 @@ func TestAPIGetContentsList(t *testing.T) { func testAPIGetContentsList(t *testing.T, u *url.URL) { /*** SETUP ***/ user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -160,7 +160,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md?token=%s", user2.Name, repo16.Name, token2) MakeRequest(t, req, http.StatusOK) - // Test access of org user3 private repo file by owner user2 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", user3.Name, repo3.Name, treePath, token2) + // Test access of org org3 private repo file by owner user2 + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_repo_get_contents_test.go b/tests/integration/api_repo_get_contents_test.go index be091cea4e..709bbe082a 100644 --- a/tests/integration/api_repo_get_contents_test.go +++ b/tests/integration/api_repo_get_contents_test.go @@ -58,7 +58,7 @@ func TestAPIGetContents(t *testing.T) { func testAPIGetContents(t *testing.T, u *url.URL) { /*** SETUP ***/ user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3, is an org user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -157,8 +157,8 @@ func testAPIGetContents(t *testing.T, u *url.URL) { req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md?token=%s", user2.Name, repo16.Name, token2) MakeRequest(t, req, http.StatusOK) - // Test access of org user3 private repo file by owner user2 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", user3.Name, repo3.Name, treePath, token2) + // Test access of org org3 private repo file by owner user2 + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_repo_git_blobs_test.go b/tests/integration/api_repo_git_blobs_test.go index 9a0bb6d0f2..866234d0a6 100644 --- a/tests/integration/api_repo_git_blobs_test.go +++ b/tests/integration/api_repo_git_blobs_test.go @@ -20,7 +20,7 @@ import ( func TestAPIReposGitBlobs(t *testing.T) { defer tests.PrepareTestEnv(t)() user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3 + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3 user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -55,23 +55,23 @@ func TestAPIReposGitBlobs(t *testing.T) { req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", user2.Name, repo1.Name, badSHA) MakeRequest(t, req, http.StatusBadRequest) - // Test using org repo "user3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", user3.Name, repo3.Name, repo3ReadmeSHA, token) + // Test using org repo "org3/repo3" where user2 is a collaborator + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", org3.Name, repo3.Name, repo3ReadmeSHA, token) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", user3.Name, repo3.Name, repo3ReadmeSHA, token) + // Test using org repo "org3/repo3" where user2 is a collaborator + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", org3.Name, repo3.Name, repo3ReadmeSHA, token) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" with no user token - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", user3.Name, repo3ReadmeSHA, repo3.Name) + // Test using org repo "org3/repo3" with no user token + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", org3.Name, repo3ReadmeSHA, repo3.Name) MakeRequest(t, req, http.StatusNotFound) // Login as User4. session = loginUser(t, user4.Name) token4 := getTokenForLoggedInUser(t, session) - // Test using org repo "user3/repo3" where user4 is a NOT collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", user3.Name, repo3.Name, token4) + // Test using org repo "org3/repo3" where user4 is a NOT collaborator + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", org3.Name, repo3.Name, token4) MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/api_repo_git_trees_test.go b/tests/integration/api_repo_git_trees_test.go index 7a7ece120c..aa732b9946 100644 --- a/tests/integration/api_repo_git_trees_test.go +++ b/tests/integration/api_repo_git_trees_test.go @@ -17,7 +17,7 @@ import ( func TestAPIReposGitTrees(t *testing.T) { defer tests.PrepareTestEnv(t)() user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3 + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the repo3 user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of neither repos repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo @@ -57,19 +57,19 @@ func TestAPIReposGitTrees(t *testing.T) { req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", user2.Name, repo1.Name, badSHA) MakeRequest(t, req, http.StatusBadRequest) - // Test using org repo "user3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s?token=%s", user3.Name, repo3.Name, repo3TreeSHA, token) + // Test using org repo "org3/repo3" where user2 is a collaborator + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s?token=%s", org3.Name, repo3.Name, repo3TreeSHA, token) MakeRequest(t, req, http.StatusOK) - // Test using org repo "user3/repo3" with no user token - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", user3.Name, repo3TreeSHA, repo3.Name) + // Test using org repo "org3/repo3" with no user token + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", org3.Name, repo3TreeSHA, repo3.Name) MakeRequest(t, req, http.StatusNotFound) // Login as User4. session = loginUser(t, user4.Name) token4 := getTokenForLoggedInUser(t, session) - // Test using org repo "user3/repo3" where user4 is a NOT collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", user3.Name, repo3.Name, token4) + // Test using org repo "org3/repo3" where user4 is a NOT collaborator + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", org3.Name, repo3.Name, token4) MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index 3d3200b291..23cf8a2567 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -23,7 +23,7 @@ import ( func TestAPIRepoTeams(t *testing.T) { defer tests.PrepareTestEnv(t)() - // publicOrgRepo = user3/repo21 + // publicOrgRepo = org3/repo21 publicOrgRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 32}) // user4 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index be4135b050..a6d32a89ea 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -69,7 +69,7 @@ func TestAPISearchRepo(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 18}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 18}) user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 20}) orgUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 17}) @@ -140,11 +140,11 @@ func TestAPISearchRepo(t *testing.T) { }, }, { - name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{ + name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", org3.ID), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 4, includesPrivate: true}, user2: {count: 3, includesPrivate: true}, - user3: {count: 4, includesPrivate: true}, + org3: {count: 4, includesPrivate: true}, }, }, { @@ -289,8 +289,8 @@ func TestAPIOrgRepos(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - // User3 is an Org. Check their repos. + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) + // org3 is an Org. Check their repos. sourceOrg := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) expectedResults := map[*user_model.User]struct { @@ -300,7 +300,7 @@ func TestAPIOrgRepos(t *testing.T) { user: {count: 1}, user: {count: 3, includesPrivate: true}, user2: {count: 3, includesPrivate: true}, - user3: {count: 1}, + org3: {count: 1}, } for userToLogin, expected := range expectedResults { @@ -438,11 +438,11 @@ func TestAPIOrgRepoCreate(t *testing.T) { orgName, repoName string expectedStatus int }{ - {ctxUserID: 1, orgName: "user3", repoName: "repo-admin", expectedStatus: http.StatusCreated}, - {ctxUserID: 2, orgName: "user3", repoName: "repo-own", expectedStatus: http.StatusCreated}, - {ctxUserID: 2, orgName: "user6", repoName: "repo-bad-org", expectedStatus: http.StatusForbidden}, - {ctxUserID: 28, orgName: "user3", repoName: "repo-creator", expectedStatus: http.StatusCreated}, - {ctxUserID: 28, orgName: "user6", repoName: "repo-not-creator", expectedStatus: http.StatusForbidden}, + {ctxUserID: 1, orgName: "org3", repoName: "repo-admin", expectedStatus: http.StatusCreated}, + {ctxUserID: 2, orgName: "org3", repoName: "repo-own", expectedStatus: http.StatusCreated}, + {ctxUserID: 2, orgName: "org6", repoName: "repo-bad-org", expectedStatus: http.StatusForbidden}, + {ctxUserID: 28, orgName: "org3", repoName: "repo-creator", expectedStatus: http.StatusCreated}, + {ctxUserID: 28, orgName: "org6", repoName: "repo-not-creator", expectedStatus: http.StatusForbidden}, } defer tests.PrepareTestEnv(t)() @@ -491,21 +491,21 @@ func TestAPIRepoTransfer(t *testing.T) { teams *[]int64 expectedStatus int }{ - // Disclaimer for test story: "user1" is an admin, "user2" is normal user and part of in owner team of org "user3" + // Disclaimer for test story: "user1" is an admin, "user2" is normal user and part of in owner team of org "org3" // Transfer to a user with teams in another org should fail - {ctxUserID: 1, newOwner: "user3", teams: &[]int64{5}, expectedStatus: http.StatusForbidden}, + {ctxUserID: 1, newOwner: "org3", teams: &[]int64{5}, expectedStatus: http.StatusForbidden}, // Transfer to a user with non-existent team IDs should fail {ctxUserID: 1, newOwner: "user2", teams: &[]int64{2}, expectedStatus: http.StatusUnprocessableEntity}, // Transfer should go through - {ctxUserID: 1, newOwner: "user3", teams: &[]int64{2}, expectedStatus: http.StatusAccepted}, + {ctxUserID: 1, newOwner: "org3", teams: &[]int64{2}, expectedStatus: http.StatusAccepted}, // Let user transfer it back to himself {ctxUserID: 2, newOwner: "user2", expectedStatus: http.StatusAccepted}, // And revert transfer - {ctxUserID: 2, newOwner: "user3", teams: &[]int64{2}, expectedStatus: http.StatusAccepted}, + {ctxUserID: 2, newOwner: "org3", teams: &[]int64{2}, expectedStatus: http.StatusAccepted}, // Cannot start transfer to an existing repo - {ctxUserID: 2, newOwner: "user3", teams: nil, expectedStatus: http.StatusUnprocessableEntity}, + {ctxUserID: 2, newOwner: "org3", teams: nil, expectedStatus: http.StatusUnprocessableEntity}, // Start transfer, repo is now in pending transfer mode - {ctxUserID: 2, newOwner: "user6", teams: nil, expectedStatus: http.StatusCreated}, + {ctxUserID: 2, newOwner: "org6", teams: nil, expectedStatus: http.StatusCreated}, } defer tests.PrepareTestEnv(t)() @@ -648,7 +648,7 @@ func TestAPIGenerateRepo(t *testing.T) { // org req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate?token=%s", templateRepo.OwnerName, templateRepo.Name, token), &api.GenerateRepoOption{ - Owner: "user3", + Owner: "org3", Name: "new-repo", Description: "test generate repo", Private: false, diff --git a/tests/integration/api_repo_topic_test.go b/tests/integration/api_repo_topic_test.go index 251b9a3b65..e7c9b95543 100644 --- a/tests/integration/api_repo_topic_test.go +++ b/tests/integration/api_repo_topic_test.go @@ -54,7 +54,7 @@ func TestAPITopicSearch(t *testing.T) { func TestAPIRepoTopic(t *testing.T) { defer tests.PrepareTestEnv(t)() user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of repo2 - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of repo3 + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of repo3 user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // write access to repo 3 repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) @@ -143,13 +143,13 @@ func TestAPIRepoTopic(t *testing.T) { token4 := getUserToken(t, user4.Name, auth_model.AccessTokenScopeWriteRepository) // Test read topics with write access - url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", user3.Name, repo3.Name, token4) + url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", org3.Name, repo3.Name, token4) req = NewRequest(t, "GET", url) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.Empty(t, topics.TopicNames) // Test add a topic to repo with write access (requires repo admin access) - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user3.Name, repo3.Name, "topicName", token4) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", org3.Name, repo3.Name, "topicName", token4) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_user_info_test.go b/tests/integration/api_user_info_test.go index f4edfd8941..cf42b50a4d 100644 --- a/tests/integration/api_user_info_test.go +++ b/tests/integration/api_user_info_test.go @@ -23,7 +23,7 @@ func TestAPIUserInfo(t *testing.T) { user := "user1" user2 := "user31" - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user3"}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "org3"}) session := loginUser(t, user) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) @@ -42,16 +42,16 @@ func TestAPIUserInfo(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) // test if the placaholder Mail is returned if a User is not logged in - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", user3.Name)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", org3.Name)) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &u) - assert.Equal(t, user3.GetPlaceholderEmail(), u.Email) + assert.Equal(t, org3.GetPlaceholderEmail(), u.Email) // Test if the correct Mail is returned if a User is logged in - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s?token=%s", user3.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s?token=%s", org3.Name, token)) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &u) - assert.Equal(t, user3.GetEmail(), u.Email) + assert.Equal(t, org3.GetEmail(), u.Email) }) t.Run("GetAuthenticatedUser", func(t *testing.T) { diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index 40870f39ff..c61004fab4 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -25,7 +25,7 @@ type apiUserOrgPermTestCase struct { func TestTokenNeeded(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/api/v1/users/user1/orgs/user6/permissions") + req := NewRequest(t, "GET", "/api/v1/users/user1/orgs/org6/permissions") MakeRequest(t, req, http.StatusUnauthorized) } @@ -51,7 +51,7 @@ func TestWithOwnerUser(t *testing.T) { sampleTest(t, apiUserOrgPermTestCase{ LoginUser: "user2", User: "user2", - Organization: "user3", + Organization: "org3", ExpectedOrganizationPermissions: api.OrganizationPermissions{ IsOwner: true, IsAdmin: true, @@ -66,7 +66,7 @@ func TestCanWriteUser(t *testing.T) { sampleTest(t, apiUserOrgPermTestCase{ LoginUser: "user4", User: "user4", - Organization: "user3", + Organization: "org3", ExpectedOrganizationPermissions: api.OrganizationPermissions{ IsOwner: false, IsAdmin: false, @@ -81,7 +81,7 @@ func TestAdminUser(t *testing.T) { sampleTest(t, apiUserOrgPermTestCase{ LoginUser: "user1", User: "user28", - Organization: "user3", + Organization: "org3", ExpectedOrganizationPermissions: api.OrganizationPermissions{ IsOwner: false, IsAdmin: true, @@ -96,7 +96,7 @@ func TestAdminCanNotCreateRepo(t *testing.T) { sampleTest(t, apiUserOrgPermTestCase{ LoginUser: "user1", User: "user28", - Organization: "user6", + Organization: "org6", ExpectedOrganizationPermissions: api.OrganizationPermissions{ IsOwner: false, IsAdmin: true, diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index f76c61f818..51830961ac 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -27,17 +27,17 @@ func TestUserOrgs(t *testing.T) { orgs := getUserOrgs(t, adminUsername, normalUsername) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user3"}) - user17 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user17"}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "org3"}) + org17 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "org17"}) assert.Equal(t, []*api.Organization{ { ID: 17, - Name: user17.Name, - UserName: user17.Name, - FullName: user17.FullName, - Email: user17.Email, - AvatarURL: user17.AvatarLink(db.DefaultContext), + Name: org17.Name, + UserName: org17.Name, + FullName: org17.FullName, + Email: org17.Email, + AvatarURL: org17.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", @@ -45,11 +45,11 @@ func TestUserOrgs(t *testing.T) { }, { ID: 3, - Name: user3.Name, - UserName: user3.Name, - FullName: user3.FullName, - Email: user3.Email, - AvatarURL: user3.AvatarLink(db.DefaultContext), + Name: org3.Name, + UserName: org3.Name, + FullName: org3.FullName, + Email: org3.Email, + AvatarURL: org3.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", @@ -99,17 +99,17 @@ func TestMyOrgs(t *testing.T) { resp := MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization DecodeJSON(t, resp, &orgs) - user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user3"}) - user17 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user17"}) + org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "org3"}) + org17 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "org17"}) assert.Equal(t, []*api.Organization{ { ID: 17, - Name: user17.Name, - UserName: user17.Name, - FullName: user17.FullName, - Email: user17.Email, - AvatarURL: user17.AvatarLink(db.DefaultContext), + Name: org17.Name, + UserName: org17.Name, + FullName: org17.FullName, + Email: org17.Email, + AvatarURL: org17.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", @@ -117,11 +117,11 @@ func TestMyOrgs(t *testing.T) { }, { ID: 3, - Name: user3.Name, - UserName: user3.Name, - FullName: user3.FullName, - Email: user3.Email, - AvatarURL: user3.AvatarLink(db.DefaultContext), + Name: org3.Name, + UserName: org3.Name, + FullName: org3.FullName, + Email: org3.Email, + AvatarURL: org3.AvatarLink(db.DefaultContext), Description: "", Website: "", Location: "", diff --git a/tests/integration/issue_test.go b/tests/integration/issue_test.go index 560f569513..4cae00f0bc 100644 --- a/tests/integration/issue_test.go +++ b/tests/integration/issue_test.go @@ -432,14 +432,14 @@ func TestSearchIssues(t *testing.T) { DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 8) - query = url.Values{"owner": {"user3"}} // organization + query = url.Values{"owner": {"org3"}} // organization link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 5) - query = url.Values{"owner": {"user3"}, "team": {"team1"}} // organization + team + query = url.Values{"owner": {"org3"}, "team": {"team1"}} // organization + team link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/org_project_test.go b/tests/integration/org_project_test.go index 4ae94b4d45..a14004f6b0 100644 --- a/tests/integration/org_project_test.go +++ b/tests/integration/org_project_test.go @@ -26,27 +26,27 @@ func TestOrgProjectAccess(t *testing.T) { MakeRequest(t, req, http.StatusOK) // org project, 200 - req = NewRequest(t, "GET", "/user3/-/projects") + req = NewRequest(t, "GET", "/org3/-/projects") MakeRequest(t, req, http.StatusOK) // change the org's visibility to private session := loginUser(t, "user2") - req = NewRequestWithValues(t, "POST", "/org/user3/settings", map[string]string{ - "_csrf": GetCSRF(t, session, "/user3/-/projects"), - "name": "user3", + req = NewRequestWithValues(t, "POST", "/org/org3/settings", map[string]string{ + "_csrf": GetCSRF(t, session, "/org3/-/projects"), + "name": "org3", "visibility": "2", }) session.MakeRequest(t, req, http.StatusSeeOther) // user4 can still access the org's project because its team(team1) has the permission session = loginUser(t, "user4") - req = NewRequest(t, "GET", "/user3/-/projects") + req = NewRequest(t, "GET", "/org3/-/projects") session.MakeRequest(t, req, http.StatusOK) // disable team1's project unit session = loginUser(t, "user2") - req = NewRequestWithValues(t, "POST", "/org/user3/teams/team1/edit", map[string]string{ - "_csrf": GetCSRF(t, session, "/user3/-/projects"), + req = NewRequestWithValues(t, "POST", "/org/org3/teams/team1/edit", map[string]string{ + "_csrf": GetCSRF(t, session, "/org3/-/projects"), "team_name": "team1", "repo_access": "specific", "permission": "read", @@ -56,6 +56,6 @@ func TestOrgProjectAccess(t *testing.T) { // user4 can no longer access the org's project session = loginUser(t, "user4") - req = NewRequest(t, "GET", "/user3/-/projects") + req = NewRequest(t, "GET", "/org3/-/projects") session.MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go index 64d93e4083..aa01678ea9 100644 --- a/tests/integration/org_test.go +++ b/tests/integration/org_test.go @@ -33,7 +33,7 @@ func TestOrgRepos(t *testing.T) { t.Run(user, func(t *testing.T) { session := loginUser(t, user) for sortBy, repos := range cases { - req := NewRequest(t, "GET", "/user3?sort="+sortBy) + req := NewRequest(t, "GET", "/org3?sort="+sortBy) resp := session.MakeRequest(t, req, http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index 8c95d7c8a6..2b9b814106 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -24,7 +24,7 @@ const ( privateActivityTestUser = "user2" ) -// user3 is an organization so it is not usable here +// org3 is an organization so it is not usable here const privateActivityTestOtherUser = "user4" // activity helpers diff --git a/tests/integration/repo_fork_test.go b/tests/integration/repo_fork_test.go index 26c81f5bee..594fba6796 100644 --- a/tests/integration/repo_fork_test.go +++ b/tests/integration/repo_fork_test.go @@ -63,10 +63,10 @@ func TestRepoFork(t *testing.T) { func TestRepoForkToOrg(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - testRepoFork(t, session, "user2", "repo1", "user3", "repo1") + testRepoFork(t, session, "user2", "repo1", "org3", "repo1") // Check that no more forking is allowed as user2 owns repository - // and user3 organization that owner user2 is also now has forked this repository + // and org3 organization that owner user2 is also now has forked this repository req := NewRequest(t, "GET", "/user2/repo1") resp := session.MakeRequest(t, req, http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) diff --git a/tests/integration/repo_test.go b/tests/integration/repo_test.go index 9ace3ca30c..99a27d6a7f 100644 --- a/tests/integration/repo_test.go +++ b/tests/integration/repo_test.go @@ -35,7 +35,7 @@ func TestViewRepo(t *testing.T) { assert.True(t, repoTopics.HasClass("repo-topic")) assert.True(t, repoSummary.HasClass("repository-menu")) - req = NewRequest(t, "GET", "/user3/repo3") + req = NewRequest(t, "GET", "/org3/repo3") MakeRequest(t, req, http.StatusNotFound) session = loginUser(t, "user1") @@ -45,7 +45,7 @@ func TestViewRepo(t *testing.T) { func testViewRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/user3/repo3") + req := NewRequest(t, "GET", "/org3/repo3") session := loginUser(t, "user2") resp := session.MakeRequest(t, req, http.StatusOK) @@ -116,7 +116,7 @@ func TestViewRepo2(t *testing.T) { func TestViewRepo3(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/user3/repo3") + req := NewRequest(t, "GET", "/org3/repo3") session := loginUser(t, "user4") session.MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/repo_watch_test.go b/tests/integration/repo_watch_test.go index c47080298e..ef3028f293 100644 --- a/tests/integration/repo_watch_test.go +++ b/tests/integration/repo_watch_test.go @@ -18,7 +18,7 @@ func TestRepoWatch(t *testing.T) { setting.Service.AutoWatchOnChanges = true session := loginUser(t, "user2") unittest.AssertNotExistsBean(t, &repo_model.Watch{UserID: 2, RepoID: 3}) - testEditFile(t, session, "user3", "repo3", "master", "README.md", "Hello, World (Edited for watch)\n") + testEditFile(t, session, "org3", "repo3", "master", "README.md", "Hello, World (Edited for watch)\n") unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{UserID: 2, RepoID: 3, Mode: repo_model.WatchModeAuto}) }) } diff --git a/tests/integration/timetracking_test.go b/tests/integration/timetracking_test.go index 52081615a0..10e539cbe6 100644 --- a/tests/integration/timetracking_test.go +++ b/tests/integration/timetracking_test.go @@ -32,7 +32,7 @@ func TestNotViewTimetrackingControls(t *testing.T) { func TestViewTimetrackingControlsDisabled(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - testViewTimetrackingControls(t, session, "user3", "repo3", "1", false) + testViewTimetrackingControls(t, session, "org3", "repo3", "1", false) } func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo, issue string, canTrackTime bool) { diff --git a/web_src/js/test/setup.js b/web_src/js/test/setup.js index 0b57193674..52355c7adc 100644 --- a/web_src/js/test/setup.js +++ b/web_src/js/test/setup.js @@ -6,10 +6,10 @@ window.config = { mentionValues: [ {key: 'user1 User 1', value: 'user1', name: 'user1', fullname: 'User 1', avatar: 'https://avatar1.com'}, {key: 'user2 User 2', value: 'user2', name: 'user2', fullname: 'User 2', avatar: 'https://avatar2.com'}, - {key: 'user3 User 3', value: 'user3', name: 'user3', fullname: 'User 3', avatar: 'https://avatar3.com'}, + {key: 'org3 User 3', value: 'org3', name: 'org3', fullname: 'User 3', avatar: 'https://avatar3.com'}, {key: 'user4 User 4', value: 'user4', name: 'user4', fullname: 'User 4', avatar: 'https://avatar4.com'}, {key: 'user5 User 5', value: 'user5', name: 'user5', fullname: 'User 5', avatar: 'https://avatar5.com'}, - {key: 'user6 User 6', value: 'user6', name: 'user6', fullname: 'User 6', avatar: 'https://avatar6.com'}, - {key: 'user7 User 7', value: 'user7', name: 'user7', fullname: 'User 7', avatar: 'https://avatar7.com'}, + {key: 'org6 User 6', value: 'org6', name: 'org6', fullname: 'User 6', avatar: 'https://avatar6.com'}, + {key: 'org7 User 7', value: 'org7', name: 'org7', fullname: 'User 7', avatar: 'https://avatar7.com'}, ], }; From b32998b3f55bfb4acebe78810fde94838eb75918 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 13 Sep 2023 23:20:46 -0400 Subject: [PATCH 026/289] set version in snapcraft yaml --- snap/snapcraft.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index fa2b4a3979..7c10074bc5 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -62,7 +62,7 @@ parts: version="$(git describe --always | sed -e 's/-/+git/;y/-/./')" [ -n "$(echo $version | grep "+git")" ] && grade=devel || grade=stable - craftctl set version "$version" + craftctl set version="$version" craftctl set grade="$grade" override-build: | From 076eca81587a286b2392e37beddc6d92a1849bb5 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Thu, 14 Sep 2023 12:54:25 +0900 Subject: [PATCH 027/289] Fix incorrect default branch label while switching between branches (#27053) Fix #27008 --- templates/repo/branch_dropdown.tmpl | 11 ++++++----- web_src/js/components/RepoBranchTagSelector.vue | 7 +++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/templates/repo/branch_dropdown.tmpl b/templates/repo/branch_dropdown.tmpl index 79eff1c53a..d826eee4f6 100644 --- a/templates/repo/branch_dropdown.tmpl +++ b/templates/repo/branch_dropdown.tmpl @@ -3,12 +3,12 @@ * ContainerClasses * (TODO: search "branch_dropdown" in the template direcotry) */}} -{{$defaultBranch := $.root.BranchName}} +{{$defaultSelectedRefName := $.root.BranchName}} {{if and .root.IsViewTag (not .noTag)}} - {{$defaultBranch = .root.TagName}} + {{$defaultSelectedRefName = .root.TagName}} {{end}} -{{if eq $defaultBranch ""}} - {{$defaultBranch = $.root.Repository.DefaultBranch}} +{{if eq $defaultSelectedRefName ""}} + {{$defaultSelectedRefName = $.root.Repository.DefaultBranch}} {{end}} {{$type := ""}} @@ -45,7 +45,8 @@ 'tagName': {{.root.TagName}}, 'branchName': {{.root.BranchName}}, 'noTag': {{.noTag}}, - 'defaultBranch': {{$defaultBranch}}, + 'defaultSelectedRefName': {{$defaultSelectedRefName}}, + 'repoDefaultBranch': {{.root.Repository.DefaultBranch}}, 'enableFeed': {{.root.EnableFeed}}, 'rssURLPrefix': '{{$.root.RepoLink}}/rss/branch/', 'branchURLPrefix': '{{if .branchURLPrefix}}{{.branchURLPrefix}}{{else}}{{$.root.RepoLink}}/{{if $.root.PageIsCommits}}commits{{else}}src{{end}}/branch/{{end}}', diff --git a/web_src/js/components/RepoBranchTagSelector.vue b/web_src/js/components/RepoBranchTagSelector.vue index b64b66d181..30bff6d23f 100644 --- a/web_src/js/components/RepoBranchTagSelector.vue +++ b/web_src/js/components/RepoBranchTagSelector.vue @@ -190,16 +190,15 @@ const sfc = { } this.isLoading = true; try { - // the "data.defaultBranch" is ambiguous, it could be "branch name" or "tag name" const reqUrl = `${this.repoLink}/${this.mode}/list`; const resp = await fetch(reqUrl); const {results} = await resp.json(); for (const result of results) { let selected = false; if (this.mode === 'branches') { - selected = result === this.defaultBranch; + selected = result === this.defaultSelectedRefName; } else { - selected = result === (this.release ? this.release.tagName : this.defaultBranch); + selected = result === (this.release ? this.release.tagName : this.defaultSelectedRefName); } this.items.push({name: result, url: pathEscapeSegments(result), branch: this.mode === 'branches', tag: this.mode === 'tags', selected}); } @@ -276,7 +275,7 @@ export default sfc; // activate IDE's Vue plugin
{{ item.name }} -
+
{{ textDefaultBranchLabel }}
From a457eb94151a718be64d12eff9d9b7eafd6511ad Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Thu, 14 Sep 2023 12:10:12 +0800 Subject: [PATCH 028/289] Apply lng2020 to maintainers (#27068) Hi all, I've very much enjoyed working on Gitea and was hoping to make it official by requesting maintainership. My [merged PRs list](https://github.com/go-gitea/gitea/pulls?q=is%3Apr+sort%3Aupdated-desc+author%3Alng2020+is%3Amerged) --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index ce35a2f420..5f38c28beb 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -56,3 +56,4 @@ Denys Konovalov (@denyskon) Punit Inani (@puni9869) CaiCandong <1290147055@qq.com> (@caicandong) Rui Chen (@chenrui333) +Nanguan Lin (@lng2020) From 198a9ca6350954a6d3327a408021fec2bc0fc805 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 14 Sep 2023 14:53:36 +0800 Subject: [PATCH 029/289] Display all user types and org types on admin management UI (#27050) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow #24026 图片 --------- Co-authored-by: delvh --- models/user/search.go | 16 +++++++++++++++- options/locale/locale_en-US.ini | 3 +++ routers/web/admin/orgs.go | 5 +++-- routers/web/admin/users.go | 1 + templates/admin/org/list.tmpl | 3 +++ templates/admin/user/list.tmpl | 8 +++++++- 6 files changed, 32 insertions(+), 4 deletions(-) diff --git a/models/user/search.go b/models/user/search.go index bf35fcd9eb..446556f89b 100644 --- a/models/user/search.go +++ b/models/user/search.go @@ -34,12 +34,26 @@ type SearchUserOptions struct { IsRestricted util.OptionalBool IsTwoFactorEnabled util.OptionalBool IsProhibitLogin util.OptionalBool + IncludeReserved bool ExtraParamStrings map[string]string } func (opts *SearchUserOptions) toSearchQueryBase() *xorm.Session { - var cond builder.Cond = builder.Eq{"type": opts.Type} + var cond builder.Cond + cond = builder.Eq{"type": opts.Type} + if opts.IncludeReserved { + if opts.Type == UserTypeIndividual { + cond = cond.Or(builder.Eq{"type": UserTypeUserReserved}).Or( + builder.Eq{"type": UserTypeBot}, + ).Or( + builder.Eq{"type": UserTypeRemoteUser}, + ) + } else if opts.Type == UserTypeOrganization { + cond = cond.Or(builder.Eq{"type": UserTypeOrganizationReserved}) + } + } + if len(opts.Keyword) > 0 { lowerKeyword := strings.ToLower(opts.Keyword) keywordCond := builder.Or( diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 39da4be179..ad7d35127e 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -2780,6 +2780,9 @@ users.full_name = Full Name users.activated = Activated users.admin = Admin users.restricted = Restricted +users.reserved = Reserved +users.bot = Bot +users.remote = Remote users.2fa = 2FA users.repos = Repos users.created = Created diff --git a/routers/web/admin/orgs.go b/routers/web/admin/orgs.go index d0fd0d5002..ab44f8048b 100644 --- a/routers/web/admin/orgs.go +++ b/routers/web/admin/orgs.go @@ -28,8 +28,9 @@ func Organizations(ctx *context.Context) { } explore.RenderUserSearch(ctx, &user_model.SearchUserOptions{ - Actor: ctx.Doer, - Type: user_model.UserTypeOrganization, + Actor: ctx.Doer, + Type: user_model.UserTypeOrganization, + IncludeReserved: true, // administrator needs to list all acounts include reserved ListOptions: db.ListOptions{ PageSize: setting.UI.Admin.OrgPagingNum, }, diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 47dff6e852..03ffaf5f3f 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -77,6 +77,7 @@ func Users(ctx *context.Context) { IsRestricted: util.OptionalBoolParse(statusFilterMap["is_restricted"]), IsTwoFactorEnabled: util.OptionalBoolParse(statusFilterMap["is_2fa_enabled"]), IsProhibitLogin: util.OptionalBoolParse(statusFilterMap["is_prohibit_login"]), + IncludeReserved: true, // administrator needs to list all acounts include reserved, bot, remote ones ExtraParamStrings: extraParamStrings, }, tplUsers) } diff --git a/templates/admin/org/list.tmpl b/templates/admin/org/list.tmpl index a400dcbc86..ac86e7606a 100644 --- a/templates/admin/org/list.tmpl +++ b/templates/admin/org/list.tmpl @@ -37,6 +37,9 @@ {{if .Visibility.IsPrivate}} {{svg "octicon-lock"}} {{end}} + {{if eq .Type 3}}{{/* Reserved organization */}} + {{$.locale.Tr "admin.users.reserved"}} + {{end}}
diff --git a/templates/admin/user/list.tmpl b/templates/admin/user/list.tmpl index b3e0caa169..7334828533 100644 --- a/templates/admin/user/list.tmpl +++ b/templates/admin/user/list.tmpl @@ -84,7 +84,13 @@ From 8d0343e028cf5b1794ba2bfebf23c863e340d108 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Thu, 14 Sep 2023 16:20:16 +0200 Subject: [PATCH 030/289] 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 aee3495612..7f51cb01f3 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 c95d54532a..3796fb7d3e 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 031/289] 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 1654e6ce75..d01ee44462 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 b2ff74f0cf..747fbbc78c 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 a4e1c899fc..c3a6d88685 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 032/289] 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 52ce46c353..73afcdcf32 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 9db9b5e56f..4c2b26d1df 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 9d379cd0c4..5479db20eb 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 be019184eb..e5e5fdb2f3 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 eb4027b3a4..6926fd2143 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 65af0bc945..bf0fdd9a9a 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 af73637c4a..80931c9af4 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 6d43437ec1..150b77c7b2 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 cf3680990d..7ddf986ce9 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 4978f8ef99..e4b7b917e8 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 8fd4ad076b..260571b4b2 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 d36736b5c2..b5dff9ec01 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 b6477f859c..1c3cf2798d 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 eafbab0fb1..6be6ebc3f5 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 2f71128b5a..610c554296 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 e916249e30..f1ed6692cf 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 f2b383fe4b..7f3ca75cfd 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 6b3b7bea9a..ca589d1e02 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 446556f89b..0fa278c257 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 86cf2ad280..b3956da1cb 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 032dcba676..b15f0cbc59 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 8a16d311b1..126196b0d3 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 8de3113663..4fc049873a 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 550e536cbd..ab32b78e62 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 33678256c3..1bf8f58b93 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 8e9f3a8976..fbf0008716 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 8d0491e070..5914215bc2 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 6d50a12674..65620459b7 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 4f1e9a3f53..66946e5797 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 319c3483e1..22004a8a88 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 e5ea584d5d..67956e66bd 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 0216b62352..c5f531923b 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 abb5381a70..944fd763ca 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 cdc176b8e4..c851525c0f 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 7ae4356204..ef152eef85 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 5a05471264..1fec029465 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 01ce754c74..0fe657d245 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 fc74c8d148..68f6c974a5 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 2a2361be67..251e7a6013 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 6d60dfdca3..3eb16b9ce8 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 b15d6ba33a..a23e101e9d 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 fe3e1d2206..e34124049e 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 4618a78c3a..59f80035d8 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 03ffaf5f3f..0414a60e18 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 dac8eb7afb..f8549f68f6 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 0f7ecf1af4..e6791cafce 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 78dc84472a..178ae84366 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 00fc17f098..aa07129632 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 1432338e70..970d316300 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 a2b5f80099..c760004088 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 b94e3e9eb5..ab3fbde2c9 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 a69fdedba4..15386393e9 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 f963ad55ef..34cff05ea0 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 2fd2a681af..46ca68b612 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 d71d555bc2..f5831df28f 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 7f51cb01f3..ecc8e66702 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 3796fb7d3e..820c5d7233 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 216550ca99..5efc1a82b3 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 0de3ace792..0ef4a29f0c 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 3ed7ca1c91..7772799557 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 f0aa1a89e7..9bf54e706a 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 f0fe6140df..540a82e865 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 fa2e52dd41..4d090a3784 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 ecb846e91b..5c14f3ad4b 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 2336c04bbe..2c274f4c1c 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 0321a5759b..13c9f08098 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 ea8df3d0ea..f3a9a8abce 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 dc91747a46..ece28af12d 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 62e60ccdc1..ad525f5c95 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 1095b27fe2..6d515ac628 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 34a0459149..8160141863 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 3f4113c790..50eae27439 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 3f3219adb9..dc166d9eb4 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 df5eb60393..8fb1363fc2 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 e3e2a9e192..bbda35dee0 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 e3a74e495c..0891a86392 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 7d7d1aa8b6..b244fc7d40 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 e42f60bde2..3a2411ec55 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 a4880c7334..e29bd71529 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 a7a777e8bd..a87352f51d 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 78be93bf12..7ffdcc38fb 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 3f1bf9a0f8..7a9713c79f 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 cf4c66734a..eb6486fde1 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 033/289] [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 aed68018bd..e4a479ecf9 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 034/289] 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 73afcdcf32..fefe18d39c 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 0febb91661..6e78939680 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 fed03803d5..8abcc622bc 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 8a1e664950..72c937ffd6 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 751a281f7e..51061e5205 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 e045b71d23..66b3a8527f 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 c4506ef150..c209386e2e 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 1105608858..3636263c46 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 df3b9cd213..1a588398c1 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 21fba227a5..c059ffd39a 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 89bdb7ac05..60737149da 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 f15ac12ebe..62eac4e29a 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 3b1b97c6d6..d96ab21bcd 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 00f313ca7c..02a94ecac0 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 8b8c6d6250..1384d1e157 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 596ff182bc..ee4ecabae0 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 6f0eae55e7..27e6edd1e0 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 a41e494db9..b4af0e5ccd 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 d0d612d25d..c56fe93075 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 fa1b57638f..66b977c01f 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 83000b96d5..65ea8d4d5b 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 ef9bc0a864..d196a3806e 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 78ebf8e824..2d77906521 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 58532b883d..044ec51b56 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 126196b0d3..f9c966d5be 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 51a5c784e0..d499244dc3 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 53055bb682..3aef8281a4 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 04ca2ed977..869bc1e901 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 60b81b8d4b..1bb68d059b 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 1e462bb908..65b7c74bdd 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 bc6b82b179..cad5032d10 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 fd7d3687ac..ca74a23a4b 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 944fd763ca..519572ee51 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 c689e70a08..60e554990f 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 121e3f10e0..c30e8278db 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 0fe657d245..4f22a059a1 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 9571c8ebb9..e142183128 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 fccc76b518..05227e33a0 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 61d9470707..05509fc443 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 2887e89603..1bacc71211 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 f89d53945f..e512ba9e4b 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 09f799cc6a..2659789ddd 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 b5899baa93..7f531eafaa 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 0414a60e18..5562cc390c 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 4791b04313..31ede82f01 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 f8549f68f6..b7a73e4379 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 e6791cafce..745b4e818c 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 178ae84366..640c01e203 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 970d316300..bdfa8c4025 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 46ca68b612..dfb87b28f8 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 b7be77914f..7b7fa9e994 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 b053e3c63f..0a606582e5 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 c8ecb3b1d8..1fd784a40a 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 820c5d7233..94c9382f23 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 5efc1a82b3..b50e96be3c 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 7772799557..799c2268de 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 212b0346bc..1e71d33c08 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 55f292f143..066d2ef2a9 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 540a82e865..26e9cedd3a 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 6273e11fc5..649537ec63 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 088aba38b6..ee44d48dce 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 0d2eb14c20..34d18f999e 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 13c9f08098..2aa6619a49 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 0cecb1aa37..7858b634ce 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 b5509f570f..9a207e149d 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 dae9bf950d..1ce59fef09 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 252277e1bc..1598f32165 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 f3a9a8abce..bb9eb7a321 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 e621b5ffad..6572d661e8 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 cda11dbb18..41f1bfefe8 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 878b6d6b84..e42d9e9286 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 0edbf2d464..78a829ef25 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 40b0d17077..68c64a01ab 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 5264bd6c4a..24e673289a 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 be82fbed6e..46b1a94b81 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 cfd70ec23e..d115197197 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 dcb488c309..e4a0f6b27b 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 7ffdcc38fb..36065cafff 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 8e28c9b255..f2b4781458 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 2905c01868..ae5fd53962 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 338811f0f1..f4e1da7bb1 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 1a8a38ce56..3222dfc807 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 0ee43e1741..4a1fe2607e 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 035/289] 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 4c29c31efc..aa559f2833 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 256c913dcf..32e020dc7b 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 66db4d322d..929782f23c 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 5a417ee202..8a2de2997d 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 036/289] 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 f0b0cc298b..cd6b2a914d 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 acfb6ce77e..aa29f8be4b 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 b3e7d1024a..2849752c0a 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 bfc502c0cb..28c84f0149 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 037/289] 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 58e1642442..8edbe98b30 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 038/289] [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 819e3e85e8..57c1635c1c 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 d9773c0f5e..e3ee15a873 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 a07db7132b..63cc1ca2e5 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 ff6175cf01..c8ff04c157 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 b451eae809..46601a8cc7 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 d9a6cd5dec..cce13fb88a 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 ec1babb176..2f6ed5ae87 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 ee94e3d40b..b53d34f1a2 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 5c9c4a040a..d0031dd655 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 42d19e1f1d..95a3f5dee4 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 e4a479ecf9..c78c6811b4 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 e8ed4b9695..b9fd36e83d 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 25e1371329..2cc8085c18 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 0ad219f283..aa94a542f1 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 9a97b53c83..255f36598c 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 777805d8dc..9188131077 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 2fb17ada73..6bc1d9d06c 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 edf3b0b981..709a173df3 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 ad20959152..fd790b14cc 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 9eea6c4039..4dfb27e7da 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 2ae499b3ca..f87f22b806 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 d0250b5b34..e35564ee53 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 85f34881d3..be686dcdcc 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 58d1e80a37..0cd71af710 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 8ec1051916..2cdea9fead 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 1d0342a48d..3c23f9eb20 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 039/289] 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 | 497 +++++++++++++++++-------- 1 file changed, 345 insertions(+), 152 deletions(-) diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index c3a6d88685..0e36d21313 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,122 +27,71 @@ 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("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) - }) + 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) } -// 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 +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}, + }, } - for _, test := range []struct { + + for _, test := range tests { + issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) + if !assert.NoError(t, err) { + return + } + assert.Equal(t, test.expectedIDs, issueIDs) + } +} + +func searchIssueInRepo(t *testing.T) { + tests := []struct { opts SearchOptions expectedIDs []int64 }{ @@ -156,59 +103,305 @@ func TestDBSearchIssueWithoutKeyword(t *testing.T) { }, { SearchOptions{ - RepoIDs: []int64{1}, - AssigneeID: int64Pointer(1), + RepoIDs: []int64{2}, }, - []int64{1}, + []int64{7, 4}, }, { SearchOptions{ - RepoIDs: []int64{1}, - PosterID: int64Pointer(1), + RepoIDs: []int64{3}, }, - []int64{11, 3, 2, 1}, + []int64{12, 6}, }, { SearchOptions{ - RepoIDs: []int64{1}, - IsClosed: util.OptionalBoolFalse, + RepoIDs: []int64{4}, }, - []int64{11, 3, 2, 1}, + []int64{}, }, { SearchOptions{ - RepoIDs: []int64{1}, - IsClosed: util.OptionalBoolTrue, + RepoIDs: []int64{5}, }, - []int64{5}, + []int64{15}, }, - { - 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) - }) + } + + 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 + } + tests := []struct { + opts SearchOptions + expectedIDs []int64 + }{ + { + SearchOptions{ + PosterID: int64Pointer(1), + }, + []int64{11, 6, 3, 2, 1}, + }, + { + SearchOptions{ + AssigneeID: int64Pointer(1), + }, + []int64{6, 1}, + }, + { + SearchOptions{ + MentionID: int64Pointer(4), + }, + []int64{1}, + }, + { + SearchOptions{ + 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{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{ + IsClosed: util.OptionalBoolFalse, + }, + []int64{17, 16, 15, 14, 13, 12, 11, 6, 19, 18, 10, 7, 9, 8, 3, 2, 1}, + }, + { + SearchOptions{ + IsClosed: util.OptionalBoolTrue, + }, + []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{ + MilestoneIDs: []int64{3}, + }, + []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{ + 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{ + Paginator: &db.ListOptions{ + PageSize: 5, + }, + }, + []int64{17, 16, 15, 14, 13}, + 19, + }, + } + 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 040/289] 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 c056662fb8..0731368e85 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 612c0f94ca..8e56b43553 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 a06c425b73..7ecbc8f884 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 b5a7134294..645bd73bb8 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 ec253e961d..4b91cdf075 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 58ede56579..b8817f5c88 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 11dc47f555..616cb7a938 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 041/289] 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 5786118f50..5ac03e4a74 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 042/289] 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 db0480a5e8..34478cb00f 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 224a1422ec..cbecc287e4 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 4fea50bac6..f31776e661 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 3720b5d9b3..b50504935e 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 4e497682e5..6a6697a31a 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 0000000000..6cac76da58 --- /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 a453bf11e9..8606bdef20 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 4decd91300..7c6c5b2529 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 824a4e06ab..10f89d4855 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 5091a4a0a9..78596ff788 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 276e02f925..82dd8e0aea 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 043/289] 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 | 110 ++++++++++++++++++++++----------------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/models/org_team.go b/models/org_team.go index 7ddf986ce9..ea73918435 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -366,69 +366,69 @@ func AddTeamMember(ctx context.Context, team *organization.Team, userID int64) e return err } - ctx, committer, err := db.TxContext(ctx) + 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) + + 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++ + + // 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) + } + + // 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 = accesses[:0] + } + } + return nil + }) 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 - } - - 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 - } - - 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}) - - 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) - } - - 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] - } - } // 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(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 044/289] 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 48db7a732e..ef6b8022ff 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 34478cb00f..028f1e24ab 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 cbecc287e4..87182ab214 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 045/289] 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 61dffb3c80..b6fd2ff20a 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 046/289] 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 b0bc40dadc..34d23f1c01 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 d379490b4e..2c017fdabc 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 8aa397ad35..c8bc95f981 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 b60e6a903b..28f25170ee 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 db5dd7eea5..d12713bd37 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 6f2ec087c7..f1cf398adf 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 747fbbc78c..b7fa7eff1c 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 1efc0ea687..b7e9504c67 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 4f44487f56..d4ce8d8d3d 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 0087c933a6..f8dbb9e39c 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 3f0e980b31..9f44cd3e03 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 c15b2a41fe..ad1d5d0453 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 b0c29106a0..d5c9b1358c 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 e85d77ebc8..403eeaadb3 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 c8cd5ad33f..2c662bdb06 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 fa937ecbed..39958a7f36 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 b1627b5e6c..b1b24624c5 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 70f53cfe15..6d0ed42877 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 71302388b9..ca533fc1e0 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 aaed91bdd3..2b609e6d66 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 c4fba32ad2..6ddf1a8905 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 1c873cec57..630c243c8e 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 7364d4d02c..b55cef9473 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 7efecc26a7..f4dd2891ff 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 fc408d5257..c327d935ae 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 b3956da1cb..63b95816ce 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 b15f0cbc59..971117482c 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 e732878f85..189d197333 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 f9c966d5be..7355dc9af2 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 35dfc62f1e..2785836b89 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 0d6a8406d3..4d3fa44ca6 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 f86f7d1e9c..9909f2dc1e 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 2dd4505a91..5a03059ded 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 4be43d46ad..206e3fb29b 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 c6248bacec..05dfa45e3d 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 b050a397f2..2f9ad7060c 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 75fa863138..384532ab87 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 1fec029465..ab9a037040 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 e93c72a9f5..420d3ab5b4 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 fff9493a23..1a86444660 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 e06fc2df66..5f25fdce14 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 c0c05154c4..d662b9b583 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 8ff22a1193..326895918e 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 1aa906ccb1..5815ed4f0b 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 6369a39754..150a5c56f2 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 5562cc390c..af49b00ad6 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 b7a73e4379..8017602d99 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 745b4e818c..c6e3d1231b 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 640c01e203..40c91b3f85 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 013e11eacc..b19e18aa8e 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 132ef23fa7..bb1be310de 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 15386393e9..ec866eb6b3 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 2c7725e38d..f78bd00274 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 94c9382f23..f4aa357fac 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 257610d3af..2d129490f5 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 3e715437e6..d42af57329 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 d3d3a2af21..1cb5cc7162 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 a6125a1a58..b70901d5f2 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 ad355ce5d7..df52ca3528 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 0ef4a29f0c..63dfd0f7b5 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 799c2268de..b31ebb1971 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 1e71d33c08..e217697cc0 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 af09e240d5..7c85ff2078 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 d22c3c6aa3..d0e706c5bd 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 26e9cedd3a..37da76e3e5 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 649537ec63..16d9321e80 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 a88479e129..9efb536a7f 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 87505b94b1..71d10ab4c1 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 1ce59fef09..5a17c161fe 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 990e506d6f..ce103528c5 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 d262c777c3..cac446d84a 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 d92bf64af0..f35f40e6a0 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 f830aab0e7..91f0308d9f 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 af220601f1..90608c9e26 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 b594e35189..78f9f89fc9 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 603954810c..07812002af 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 4c21efae44..9f1e613bb2 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 e42d9e9286..4c6dfddc08 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 0ebb3411fd..0b83f3b4a3 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 321bd38fc3..d2b7d37eaa 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 2e3defee8d..f6f03e75ae 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 28824d83f5..eff33c71f3 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 08159af7bc..c3d006bfd8 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 9b00b57e71..97da45f52b 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 60f9568b54..fb52980bbd 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 2edb61816f..574b6c6a56 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 ebf179045e..70e5abdee6 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 3a40faef90..e15cab7b3c 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 72bea0b468..5b2e74eb82 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 b4478f5780..1284833864 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 047/289] 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 acdf7cd364..5de165487c 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 3f147c685d..b0effdee9d 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 ef6b8022ff..e7039053af 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 bcbd218846..d19fa16024 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 bbe589d5c8..a6fb85937c 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 7b950bfd38..3fca2bee80 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 0671ecee8b..ef3db2db73 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 048/289] 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 f0a8b05d53..3524077ea4 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 0000000000..8933f186dc --- /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 39482037b2..fffc7577c7 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 3edbcceb9b..73c1384444 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 b37948fea7..5ebc7bfc24 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 6bf88e7752..b50c8f75ca 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 75fcf634a9..62370339c8 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 12542c808f..15c7046b49 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 7c85ff2078..68943586ef 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 37da76e3e5..91c00b049e 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 f7a8e17fd0..5051104526 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 984e9f044e..935060816c 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 16944506f1..78700e05b7 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -123,7 +123,7 @@ {{else if $isWorkingPullMirror}}
- + {{range .PushMirrors}} - {{$address := MirrorRemoteAddress $.Context $.Repository .GetRemoteName true}} - + @@ -271,7 +271,7 @@
- +
@@ -586,7 +586,7 @@
- +
@@ -632,7 +632,7 @@
- +
@@ -653,7 +653,7 @@
- +
@@ -675,7 +675,7 @@ {{end}}
- +
{{end}} @@ -694,7 +694,7 @@ {{end}}
- +
diff --git a/templates/repo/settings/protected_branch.tmpl b/templates/repo/settings/protected_branch.tmpl index eb5baff59b..74cb84aba3 100644 --- a/templates/repo/settings/protected_branch.tmpl +++ b/templates/repo/settings/protected_branch.tmpl @@ -255,7 +255,7 @@
- +
diff --git a/templates/repo/settings/tags.tmpl b/templates/repo/settings/tags.tmpl index c3d2fc38de..48b67697c8 100644 --- a/templates/repo/settings/tags.tmpl +++ b/templates/repo/settings/tags.tmpl @@ -57,14 +57,14 @@ {{end}}
{{if .PageIsEditProtectedTag}} - {{$.locale.Tr "cancel"}} {{else}} - {{end}} diff --git a/templates/repo/settings/webhook/settings.tmpl b/templates/repo/settings/webhook/settings.tmpl index d84c8eb110..a669d2c9a3 100644 --- a/templates/repo/settings/webhook/settings.tmpl +++ b/templates/repo/settings/webhook/settings.tmpl @@ -278,9 +278,9 @@
{{if $isNew}} - + {{else}} - + {{.locale.Tr "repo.settings.delete_webhook"}} {{end}}
diff --git a/templates/repo/wiki/new.tmpl b/templates/repo/wiki/new.tmpl index 2098a76755..d122ee5119 100644 --- a/templates/repo/wiki/new.tmpl +++ b/templates/repo/wiki/new.tmpl @@ -6,7 +6,7 @@
{{.locale.Tr "repo.wiki.new_page"}} {{if .PageIsWikiEdit}} - {{.locale.Tr "repo.wiki.new_page_button"}} + {{.locale.Tr "repo.wiki.new_page_button"}} {{end}}
@@ -37,7 +37,7 @@
-
diff --git a/templates/repo/wiki/pages.tmpl b/templates/repo/wiki/pages.tmpl index 6169109ce9..c778933e8b 100644 --- a/templates/repo/wiki/pages.tmpl +++ b/templates/repo/wiki/pages.tmpl @@ -6,7 +6,7 @@ {{.locale.Tr "repo.wiki.pages"}} {{if and .CanWriteWiki (not .Repository.IsMirror)}} - {{.locale.Tr "repo.wiki.new_page_button"}} + {{.locale.Tr "repo.wiki.new_page_button"}} {{end}} diff --git a/templates/repo/wiki/start.tmpl b/templates/repo/wiki/start.tmpl index 4885042fd8..dbe625c568 100644 --- a/templates/repo/wiki/start.tmpl +++ b/templates/repo/wiki/start.tmpl @@ -7,7 +7,7 @@

{{.locale.Tr "repo.wiki.welcome"}}

{{.locale.Tr "repo.wiki.welcome_desc"}}

{{if and .CanWriteWiki (not .Repository.IsMirror)}} - {{.locale.Tr "repo.wiki.create_first_page"}} + {{.locale.Tr "repo.wiki.create_first_page"}} {{end}} diff --git a/templates/repo/wiki/view.tmpl b/templates/repo/wiki/view.tmpl index be59064d2b..4427a986df 100644 --- a/templates/repo/wiki/view.tmpl +++ b/templates/repo/wiki/view.tmpl @@ -51,8 +51,8 @@ {{if and .CanWriteWiki (not .Repository.IsMirror)}} {{end}} diff --git a/templates/shared/actions/runner_edit.tmpl b/templates/shared/actions/runner_edit.tmpl index e69583b9e4..ec3c25ab87 100644 --- a/templates/shared/actions/runner_edit.tmpl +++ b/templates/shared/actions/runner_edit.tmpl @@ -39,7 +39,7 @@
- +
diff --git a/templates/shared/user/profile_big_avatar.tmpl b/templates/shared/user/profile_big_avatar.tmpl index 44797ff4a7..e328c26e1f 100644 --- a/templates/shared/user/profile_big_avatar.tmpl +++ b/templates/shared/user/profile_big_avatar.tmpl @@ -112,7 +112,7 @@ {{svg "octicon-person"}} {{.locale.Tr "user.unfollow"}} {{else}} - {{end}} diff --git a/templates/user/auth/activate.tmpl b/templates/user/auth/activate.tmpl index 9a2abd3cdf..3261836ee0 100644 --- a/templates/user/auth/activate.tmpl +++ b/templates/user/auth/activate.tmpl @@ -25,7 +25,7 @@
- +
{{else if .IsSendRegisterMail}} diff --git a/templates/user/auth/change_passwd_inner.tmpl b/templates/user/auth/change_passwd_inner.tmpl index 40281f8578..317a031f6b 100644 --- a/templates/user/auth/change_passwd_inner.tmpl +++ b/templates/user/auth/change_passwd_inner.tmpl @@ -17,7 +17,7 @@
- +
diff --git a/templates/user/auth/finalize_openid.tmpl b/templates/user/auth/finalize_openid.tmpl index 2b833d9b32..e81a565507 100644 --- a/templates/user/auth/finalize_openid.tmpl +++ b/templates/user/auth/finalize_openid.tmpl @@ -29,7 +29,7 @@
- + {{.locale.Tr "auth.forget_password"}}
{{if .ShowRegistrationButton}} diff --git a/templates/user/auth/signin_inner.tmpl b/templates/user/auth/signin_inner.tmpl index 6b118b7a26..ec48524226 100644 --- a/templates/user/auth/signin_inner.tmpl +++ b/templates/user/auth/signin_inner.tmpl @@ -35,7 +35,7 @@
-
- +
diff --git a/templates/user/auth/signup_inner.tmpl b/templates/user/auth/signup_inner.tmpl index 184b8b88fe..931efcf04b 100644 --- a/templates/user/auth/signup_inner.tmpl +++ b/templates/user/auth/signup_inner.tmpl @@ -39,7 +39,7 @@
-
- + {{.locale.Tr "auth.forgot_password"}}
diff --git a/templates/user/auth/signup_openid_register.tmpl b/templates/user/auth/signup_openid_register.tmpl index a490ea5a74..9736c53ed8 100644 --- a/templates/user/auth/signup_openid_register.tmpl +++ b/templates/user/auth/signup_openid_register.tmpl @@ -29,7 +29,7 @@
- +
diff --git a/templates/user/auth/twofa.tmpl b/templates/user/auth/twofa.tmpl index 4002266054..e303580956 100644 --- a/templates/user/auth/twofa.tmpl +++ b/templates/user/auth/twofa.tmpl @@ -16,7 +16,7 @@
- + {{.locale.Tr "auth.use_scratch_code" | Str2html}}
diff --git a/templates/user/auth/twofa_scratch.tmpl b/templates/user/auth/twofa_scratch.tmpl index 4ed7fce55e..58942050f5 100644 --- a/templates/user/auth/twofa_scratch.tmpl +++ b/templates/user/auth/twofa_scratch.tmpl @@ -16,7 +16,7 @@
- +
diff --git a/templates/user/dashboard/issues.tmpl b/templates/user/dashboard/issues.tmpl index 00c604bfc4..a973eb59e4 100644 --- a/templates/user/dashboard/issues.tmpl +++ b/templates/user/dashboard/issues.tmpl @@ -101,9 +101,9 @@ {{if .SingleRepoLink}} {{if eq .SingleRepoAction "issue"}} - {{.locale.Tr "repo.issues.new"}} + {{.locale.Tr "repo.issues.new"}} {{else if eq .SingleRepoAction "pull"}} - {{.locale.Tr "repo.pulls.new"}} + {{.locale.Tr "repo.pulls.new"}} {{end}} {{end}} diff --git a/templates/user/settings/account.tmpl b/templates/user/settings/account.tmpl index 0b57720c96..173cd5e991 100644 --- a/templates/user/settings/account.tmpl +++ b/templates/user/settings/account.tmpl @@ -24,7 +24,7 @@
- + {{.locale.Tr "auth.forgot_password"}}
@@ -58,7 +58,7 @@
{{$.locale.Tr "settings.email_notifications.disable"}}
- + @@ -118,7 +118,7 @@ - diff --git a/templates/user/settings/appearance.tmpl b/templates/user/settings/appearance.tmpl index 129fca2657..ca7ef15de5 100644 --- a/templates/user/settings/appearance.tmpl +++ b/templates/user/settings/appearance.tmpl @@ -35,7 +35,7 @@
- +
@@ -61,7 +61,7 @@
- +
@@ -162,7 +162,7 @@
- +
diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index f142af3876..bc7755eb77 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -86,7 +86,7 @@ > - {{/* Fomantic ".ui.form .warning.message" is hidden by default, so put the warning message out of the form*/}} diff --git a/templates/user/settings/applications_oauth2_edit_form.tmpl b/templates/user/settings/applications_oauth2_edit_form.tmpl index 74a0e13918..1437277009 100644 --- a/templates/user/settings/applications_oauth2_edit_form.tmpl +++ b/templates/user/settings/applications_oauth2_edit_form.tmpl @@ -45,7 +45,7 @@ - diff --git a/templates/user/settings/applications_oauth2_list.tmpl b/templates/user/settings/applications_oauth2_list.tmpl index 348bc82b4e..a92909f77f 100644 --- a/templates/user/settings/applications_oauth2_list.tmpl +++ b/templates/user/settings/applications_oauth2_list.tmpl @@ -65,7 +65,7 @@ - diff --git a/templates/user/settings/keys_gpg.tmpl b/templates/user/settings/keys_gpg.tmpl index 2ecebcd7c0..467b275d35 100644 --- a/templates/user/settings/keys_gpg.tmpl +++ b/templates/user/settings/keys_gpg.tmpl @@ -31,7 +31,7 @@ {{end}} - diff --git a/templates/user/settings/keys_principal.tmpl b/templates/user/settings/keys_principal.tmpl index 42c21373d5..d9cc8fb823 100644 --- a/templates/user/settings/keys_principal.tmpl +++ b/templates/user/settings/keys_principal.tmpl @@ -49,7 +49,7 @@ - diff --git a/templates/user/settings/keys_ssh.tmpl b/templates/user/settings/keys_ssh.tmpl index 8419f72ff5..626d34fd33 100644 --- a/templates/user/settings/keys_ssh.tmpl +++ b/templates/user/settings/keys_ssh.tmpl @@ -19,7 +19,7 @@ - diff --git a/templates/user/settings/packages.tmpl b/templates/user/settings/packages.tmpl index 304940feb8..f4933d3dae 100644 --- a/templates/user/settings/packages.tmpl +++ b/templates/user/settings/packages.tmpl @@ -13,7 +13,7 @@
{{.CsrfTokenHtml}} - +
diff --git a/templates/user/settings/profile.tmpl b/templates/user/settings/profile.tmpl index 6db58fe4db..34c790065a 100644 --- a/templates/user/settings/profile.tmpl +++ b/templates/user/settings/profile.tmpl @@ -88,7 +88,7 @@
- +
@@ -125,7 +125,7 @@
- +
diff --git a/templates/user/settings/repos.tmpl b/templates/user/settings/repos.tmpl index caee1135c5..db912770d2 100644 --- a/templates/user/settings/repos.tmpl +++ b/templates/user/settings/repos.tmpl @@ -34,7 +34,7 @@ {{$.ContextUser.Name}}/{{$dir}}
diff --git a/templates/user/settings/security/webauthn.tmpl b/templates/user/settings/security/webauthn.tmpl index 676754df59..6a74b8770a 100644 --- a/templates/user/settings/security/webauthn.tmpl +++ b/templates/user/settings/security/webauthn.tmpl @@ -25,7 +25,7 @@ - + - {{template "base/modal_actions_confirm" (dict "locale" $.locale "ModalButtonTypes" "confirm")}} + {{template "base/modal_actions_confirm" (dict "ModalButtonTypes" "confirm")}} diff --git a/templates/shared/variables/variable_list.tmpl b/templates/shared/variables/variable_list.tmpl index 3a389ffaf8..d3fcec63d7 100644 --- a/templates/shared/variables/variable_list.tmpl +++ b/templates/shared/variables/variable_list.tmpl @@ -86,7 +86,7 @@ > - {{template "base/modal_actions_confirm" (dict "locale" $.locale "ModalButtonTypes" "confirm")}} + {{template "base/modal_actions_confirm" (dict "ModalButtonTypes" "confirm")}} diff --git a/templates/user/dashboard/issues.tmpl b/templates/user/dashboard/issues.tmpl index a973eb59e4..769461cca8 100644 --- a/templates/user/dashboard/issues.tmpl +++ b/templates/user/dashboard/issues.tmpl @@ -77,7 +77,7 @@ - {{template "shared/searchinput" dict "locale" .locale "Value" $.Keyword}} + {{template "shared/searchinput" dict "Value" $.Keyword}} diff --git a/templates/user/dashboard/milestones.tmpl b/templates/user/dashboard/milestones.tmpl index d18ed37910..bb63994de4 100644 --- a/templates/user/dashboard/milestones.tmpl +++ b/templates/user/dashboard/milestones.tmpl @@ -51,7 +51,7 @@ - {{template "shared/searchinput" dict "locale" .locale "Value" $.Keyword}} + {{template "shared/searchinput" dict "Value" $.Keyword}} diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index bc7755eb77..0d37e717e6 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -109,7 +109,7 @@

{{.locale.Tr "settings.access_token_deletion_desc"}}

- {{template "base/modal_actions_confirm" (dict "locale" $.locale "ModalButtonColors" "yellow")}} + {{template "base/modal_actions_confirm" (dict "ModalButtonColors" "yellow")}} {{template "user/settings/layout_footer" .}} From 0816463cf47310a66fb526eaaeeedfd80710314d Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Sun, 24 Sep 2023 17:24:17 -0400 Subject: [PATCH 095/289] Update database-preparation and add note re: MariaDB (#27232) update DB docs per feedback. https://gitea.com/gitea/gitea-docusaurus/issues/69 --- docs/content/installation/database-preparation.en-us.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/content/installation/database-preparation.en-us.md b/docs/content/installation/database-preparation.en-us.md index 21360fa4d2..c980bf5ad1 100644 --- a/docs/content/installation/database-preparation.en-us.md +++ b/docs/content/installation/database-preparation.en-us.md @@ -17,13 +17,13 @@ menu: # Database Preparation -You need a database to use Gitea. Gitea supports PostgreSQL (>=10), MySQL (>=5.7), SQLite, and MSSQL (>=2008R2 SP3). This page will guide into preparing database. Only PostgreSQL and MySQL will be covered here since those database engines are widely-used in production. If you plan to use SQLite, you can ignore this chapter. +You need a database to use Gitea. Gitea supports PostgreSQL (>=10), MySQL (>=5.7), MariaDB, SQLite, and MSSQL (>=2008R2 SP3). This page will guide into preparing database. Only PostgreSQL and MySQL will be covered here since those database engines are widely-used in production. If you plan to use SQLite, you can ignore this chapter. Database instance can be on same machine as Gitea (local database setup), or on different machine (remote database). Note: All steps below requires that the database engine of your choice is installed on your system. For remote database setup, install the server application on database instance and client program on your Gitea server. The client program is used to test connection to the database from Gitea server, while Gitea itself use database driver provided by Go to accomplish the same thing. In addition, make sure you use same engine version for both server and client for some engine features to work. For security reason, protect `root` (MySQL) or `postgres` (PostgreSQL) database superuser with secure password. The steps assumes that you run Linux for both database and Gitea servers. -## MySQL +## MySQL/MariaDB 1. For remote database setup, you will need to make MySQL listen to your IP address. Edit `bind-address` option on `/etc/mysql/my.cnf` on database instance to: @@ -45,7 +45,7 @@ Note: All steps below requires that the database engine of your choice is instal ```sql SET old_passwords=0; - CREATE USER 'gitea' IDENTIFIED BY 'gitea'; + CREATE USER 'gitea'@'%' IDENTIFIED BY 'gitea'; ``` For remote database: From a50002c75c0acc3482826902bc8f4227cc98452d Mon Sep 17 00:00:00 2001 From: silverwind Date: Mon, 25 Sep 2023 01:29:36 +0200 Subject: [PATCH 096/289] Fix z-index on markdown completion (#27237) Fixes: https://github.com/go-gitea/gitea/issues/27230 --- web_src/css/editor/combomarkdowneditor.css | 1 + 1 file changed, 1 insertion(+) diff --git a/web_src/css/editor/combomarkdowneditor.css b/web_src/css/editor/combomarkdowneditor.css index a82e2b1768..12ec1866a5 100644 --- a/web_src/css/editor/combomarkdowneditor.css +++ b/web_src/css/editor/combomarkdowneditor.css @@ -86,6 +86,7 @@ text-expander .suggestions { border-radius: var(--border-radius); border: 1px solid var(--color-secondary); box-shadow: 0 .5rem 1rem var(--color-shadow); + z-index: 100; /* needs to be > 20 to be on top of dropzone's .dz-details */ } text-expander .suggestions li { From c2eed613299fb7f40497d6b92f53dbdaf2047f53 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Mon, 25 Sep 2023 00:24:48 +0000 Subject: [PATCH 097/289] [skip ci] Updated translations via Crowdin --- options/locale/locale_fr-FR.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index 2f6ed5ae87..69787e9ebc 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -1977,7 +1977,7 @@ settings.mirror_settings.last_update=Dernière mise à jour settings.mirror_settings.push_mirror.none=Aucun miroir push configuré settings.mirror_settings.push_mirror.remote_url=URL du dépôt distant Git settings.mirror_settings.push_mirror.add=Ajouter un miroir push -settings.mirror_settings.push_mirror.edit_sync_time=Modifier la fréquence de réflexion +settings.mirror_settings.push_mirror.edit_sync_time=Modifier la fréquence de synchronisation du miroir settings.sync_mirror=Synchroniser maintenant settings.mirror_sync_in_progress=La synchronisation est en cours. Revenez dans une minute. From 6af34c09a7fba3b987497ac09713bcfa03e3c35c Mon Sep 17 00:00:00 2001 From: silverwind Date: Mon, 25 Sep 2023 03:03:00 +0200 Subject: [PATCH 098/289] Use mask-based fade-out effect for `.new-menu` (#27181) The `.new-menu` was using a pseudo-element based fade-out effect. Replace this with a more modern mask-based effect which in this case required a child element to avoid fading out the background as well, so I applied it to child `new-menu-inner` which was present on all these menus except explore where I added it. There is no visual difference except that the items on the explore page have no `gap` between them any longer, making it consistent with other menus. Before and after: Screenshot 2023-09-21 at 21 13 19 Screenshot 2023-09-21 at 21 32 36 Also, this cleans up the related CSS vars: - `--color-header-wrapper-transparent` is removed, no longer needed - `--color-header-wrapper` is defined in base theme as well, was previously unset and therefor transparent. [no whitespace diff](https://github.com/go-gitea/gitea/pull/27181/files?diff=unified&w=1) [demo of mask fade](https://jsfiddle.net/silverwind/tsfadb3u/) --- templates/explore/navbar.tmpl | 32 ++++++++++++++------------ web_src/css/base.css | 20 ++++------------ web_src/css/themes/theme-arc-green.css | 1 - 3 files changed, 21 insertions(+), 32 deletions(-) diff --git a/templates/explore/navbar.tmpl b/templates/explore/navbar.tmpl index 3a556812f9..9dbb0320b2 100644 --- a/templates/explore/navbar.tmpl +++ b/templates/explore/navbar.tmpl @@ -1,18 +1,20 @@ diff --git a/web_src/css/base.css b/web_src/css/base.css index 6b33ec4111..5efb0bfae5 100644 --- a/web_src/css/base.css +++ b/web_src/css/base.css @@ -217,6 +217,7 @@ --color-input-toggle-background: #dedede; --color-input-border: var(--color-secondary); --color-input-border-hover: var(--color-secondary-dark-1); + --color-header-wrapper: transparent; --color-light: #00000006; --color-light-mimic-enabled: rgba(0, 0, 0, calc(6 / 255 * 222 / 255 / var(--opacity-disabled))); --color-light-border: #0000001d; @@ -1542,22 +1543,9 @@ img.ui.avatar, margin-left: auto; margin-right: auto; overflow-x: auto; -} - -.ui.menu.new-menu::after { - position: absolute; - display: block; - background: linear-gradient(to right, var(--color-header-wrapper-transparent), var(--color-header-wrapper) 100%); - content: ""; - right: 0; - height: 39px; - width: 60px; - visibility: visible; - pointer-events: none; -} - -.ui.menu.new-menu.shadow-body::after { - background: linear-gradient(to right, transparent, var(--color-body) 100%); + width: 100%; + mask-image: linear-gradient(to right, #000 0%, #000 calc(100% - 60px), transparent 100%); + -webkit-mask-image: linear-gradient(to right, #000 0%, #000 calc(100% - 60px), transparent 100%); } .ui.menu.new-menu .item { diff --git a/web_src/css/themes/theme-arc-green.css b/web_src/css/themes/theme-arc-green.css index ce0989a5f6..96d9f5821c 100644 --- a/web_src/css/themes/theme-arc-green.css +++ b/web_src/css/themes/theme-arc-green.css @@ -198,7 +198,6 @@ --color-input-border: var(--color-secondary); --color-input-border-hover: var(--color-secondary-dark-1); --color-header-wrapper: #202430; - --color-header-wrapper-transparent: #20243000; --color-light: #00000028; --color-light-mimic-enabled: rgba(0, 0, 0, calc(40 / 255 * 222 / 255 / var(--opacity-disabled))); --color-light-border: #ffffff28; From 65d0b7c13a1765f9d1714f153e164a82af5598d1 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Mon, 25 Sep 2023 15:27:03 +0900 Subject: [PATCH 099/289] Add missing public user visibility in user details page (#27246) It seems that `Public` user visibility is missing in the template. Before: ![image](https://github.com/go-gitea/gitea/assets/18380374/a8e7f3e0-1b77-41a0-921a-10adba90211e) After: ![image](https://github.com/go-gitea/gitea/assets/18380374/b0bffe13-0ca6-453e-95d7-0794528d5733) --- templates/admin/user/view_details.tmpl | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/admin/user/view_details.tmpl b/templates/admin/user/view_details.tmpl index ceb3b9a055..21425eecb4 100644 --- a/templates/admin/user/view_details.tmpl +++ b/templates/admin/user/view_details.tmpl @@ -36,6 +36,7 @@
{{ctx.Locale.Tr "settings.visibility"}}: + {{if .User.Visibility.IsPublic}}{{ctx.Locale.Tr "settings.visibility.public"}}{{end}} {{if .User.Visibility.IsLimited}}{{ctx.Locale.Tr "settings.visibility.limited"}}{{end}} {{if .User.Visibility.IsPrivate}}{{ctx.Locale.Tr "settings.visibility.private"}}{{end}}
From e6d8b146207de0f5d88b7c08dc75b1f2f078cbbe Mon Sep 17 00:00:00 2001 From: Yarden Shoham Date: Mon, 25 Sep 2023 10:33:00 +0300 Subject: [PATCH 100/289] Disable `Test Delivery` and `Replay` webhook buttons when webhook is inactive (#27211) These buttons are now disabled when the webhook is not active. The buttons were always enabled before this change. - Fixes #26824 - Replaces #26814 # Before ![image](https://github.com/go-gitea/gitea/assets/20454870/e783d0d8-b433-440e-b95f-50d7c42613d3) ![image](https://github.com/go-gitea/gitea/assets/20454870/b4886151-9f32-4e83-8001-dd3f20c23d70) # After ![image](https://github.com/go-gitea/gitea/assets/20454870/74b76a72-0818-4143-8548-5d42c4119a05) ![image](https://github.com/go-gitea/gitea/assets/20454870/d5ae4e5c-c1ac-4751-a072-e6f7511b1e07) Signed-off-by: Yarden Shoham --- options/locale/locale_en-US.ini | 2 ++ templates/repo/settings/webhook/history.tmpl | 10 ++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 035dc9b9e3..de25392d88 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -2133,12 +2133,14 @@ settings.webhook_deletion_desc = Removing a webhook deletes its settings and del settings.webhook_deletion_success = The webhook has been removed. settings.webhook.test_delivery = Test Delivery settings.webhook.test_delivery_desc = Test this webhook with a fake event. +settings.webhook.test_delivery_desc_disabled = To test this webhook with a fake event, activate it. settings.webhook.request = Request settings.webhook.response = Response settings.webhook.headers = Headers settings.webhook.payload = Content settings.webhook.body = Body settings.webhook.replay.description = Replay this webhook. +settings.webhook.replay.description_disabled = To replay this webhook, activate it. settings.webhook.delivery.success = An event has been added to the delivery queue. It may take few seconds before it shows up in the delivery history. settings.githooks_desc = "Git Hooks are powered by Git itself. You can edit hook files below to set up custom operations." settings.githook_edit_desc = If the hook is inactive, sample content will be presented. Leaving content to an empty value will disable this hook. diff --git a/templates/repo/settings/webhook/history.tmpl b/templates/repo/settings/webhook/history.tmpl index 07d6f4bede..69e50989e6 100644 --- a/templates/repo/settings/webhook/history.tmpl +++ b/templates/repo/settings/webhook/history.tmpl @@ -1,9 +1,13 @@ +{{$isNew:=or .PageIsSettingsHooksNew .PageIsAdminDefaultHooksNew .PageIsAdminSystemHooksNew}} {{if .PageIsSettingsHooksEdit}}

{{.locale.Tr "repo.settings.recent_deliveries"}} {{if .Permission.IsAdmin}}
- + + + +
{{end}}

@@ -43,7 +47,9 @@ {{end}} From 7960ba7e2bbe2eb6f98f6d99f2ce105468cdf56e Mon Sep 17 00:00:00 2001 From: delvh Date: Mon, 25 Sep 2023 10:56:50 +0200 Subject: [PATCH 101/289] Always use `ctx.Locale.Tr` inside templates (#27231) --- templates/admin/applications/list.tmpl | 2 +- templates/admin/auth/edit.tmpl | 188 ++++---- templates/admin/auth/list.tmpl | 16 +- templates/admin/auth/new.tmpl | 56 +-- templates/admin/auth/source/ldap.tmpl | 62 +-- templates/admin/auth/source/oauth.tmpl | 46 +- templates/admin/auth/source/smtp.tmpl | 26 +- templates/admin/auth/source/sspi.tmpl | 20 +- templates/admin/base/search.tmpl | 16 +- templates/admin/config.tmpl | 254 +++++----- templates/admin/cron.tmpl | 18 +- templates/admin/dashboard.tmpl | 114 ++--- templates/admin/emails/list.tmpl | 28 +- templates/admin/hook_new.tmpl | 8 +- templates/admin/navbar.tmpl | 48 +- templates/admin/notice.tmpl | 26 +- templates/admin/org/list.tmpl | 18 +- templates/admin/packages/list.tmpl | 36 +- templates/admin/queue.tmpl | 16 +- templates/admin/queue_manage.tmpl | 28 +- templates/admin/repo/list.tmpl | 44 +- templates/admin/repo/search.tmpl | 28 +- templates/admin/repo/unadopted.tmpl | 22 +- templates/admin/stacktrace.tmpl | 16 +- templates/admin/stats.tmpl | 2 +- templates/admin/user/edit.tmpl | 86 ++-- templates/admin/user/list.tmpl | 68 +-- templates/admin/user/new.tmpl | 36 +- templates/base/footer_content.tmpl | 16 +- templates/base/head_navbar.tmpl | 70 +-- templates/base/head_script.tmpl | 14 +- templates/base/paginate.tmpl | 8 +- templates/code/searchcombo.tmpl | 6 +- templates/code/searchform.tmpl | 10 +- templates/code/searchresults.tmpl | 4 +- templates/devtest/flex-list.tmpl | 2 +- templates/explore/navbar.tmpl | 8 +- templates/explore/repo_list.tmpl | 18 +- templates/explore/repo_search.tmpl | 26 +- templates/explore/search.tmpl | 16 +- templates/home.tmpl | 22 +- templates/install.tmpl | 150 +++--- templates/org/create.tmpl | 20 +- templates/org/header.tmpl | 4 +- templates/org/home.tmpl | 24 +- templates/org/member/members.tmpl | 24 +- templates/org/menu.tmpl | 14 +- templates/org/settings/applications.tmpl | 2 +- templates/org/settings/delete.tmpl | 12 +- templates/org/settings/hook_new.tmpl | 4 +- templates/org/settings/labels.tmpl | 4 +- templates/org/settings/navbar.tmpl | 22 +- templates/org/settings/options.tmpl | 40 +- templates/org/team/invite.tmpl | 8 +- templates/org/team/members.tmpl | 18 +- templates/org/team/navbar.tmpl | 4 +- templates/org/team/new.tmpl | 78 +-- templates/org/team/repositories.tmpl | 12 +- templates/org/team/sidebar.tmpl | 42 +- templates/org/team/teams.tmpl | 12 +- templates/package/content/alpine.tmpl | 22 +- templates/package/content/cargo.tmpl | 18 +- templates/package/content/chef.tmpl | 16 +- templates/package/content/composer.tmpl | 18 +- .../content/composer_dependencies.tmpl | 4 +- templates/package/content/conan.tmpl | 12 +- templates/package/content/conda.tmpl | 10 +- templates/package/content/container.tmpl | 26 +- templates/package/content/cran.tmpl | 12 +- templates/package/content/debian.tmpl | 22 +- templates/package/content/generic.tmpl | 6 +- templates/package/content/go.tmpl | 6 +- templates/package/content/helm.tmpl | 18 +- templates/package/content/maven.tmpl | 16 +- templates/package/content/npm.tmpl | 24 +- .../package/content/npm_dependencies.tmpl | 4 +- templates/package/content/nuget.tmpl | 18 +- templates/package/content/pub.tmpl | 8 +- templates/package/content/pypi.tmpl | 12 +- templates/package/content/rpm.tmpl | 18 +- templates/package/content/rubygems.tmpl | 22 +- .../content/rubygems_dependencies.tmpl | 4 +- templates/package/content/swift.tmpl | 14 +- templates/package/content/vagrant.tmpl | 8 +- templates/package/metadata/alpine.tmpl | 6 +- templates/package/metadata/cargo.tmpl | 10 +- templates/package/metadata/chef.tmpl | 6 +- templates/package/metadata/composer.tmpl | 6 +- templates/package/metadata/conan.tmpl | 8 +- templates/package/metadata/conda.tmpl | 6 +- templates/package/metadata/container.tmpl | 12 +- templates/package/metadata/cran.tmpl | 6 +- templates/package/metadata/debian.tmpl | 4 +- templates/package/metadata/helm.tmpl | 4 +- templates/package/metadata/maven.tmpl | 4 +- templates/package/metadata/npm.tmpl | 8 +- templates/package/metadata/nuget.tmpl | 4 +- templates/package/metadata/pub.tmpl | 6 +- templates/package/metadata/pypi.tmpl | 6 +- templates/package/metadata/rpm.tmpl | 4 +- templates/package/metadata/rubygems.tmpl | 6 +- templates/package/metadata/swift.tmpl | 4 +- templates/package/metadata/vagrant.tmpl | 6 +- templates/package/settings.tmpl | 22 +- templates/package/shared/cargo.tmpl | 12 +- .../package/shared/cleanup_rules/edit.tmpl | 54 +-- .../package/shared/cleanup_rules/list.tmpl | 20 +- .../package/shared/cleanup_rules/preview.tmpl | 18 +- templates/package/shared/list.tmpl | 18 +- templates/package/shared/versionlist.tmpl | 20 +- templates/package/view.tmpl | 16 +- templates/post-install.tmpl | 4 +- templates/projects/list.tmpl | 32 +- templates/projects/new.tmpl | 6 +- templates/repo/actions/list.tmpl | 18 +- templates/repo/actions/runs_list.tmpl | 8 +- templates/repo/actions/view.tmpl | 34 +- templates/repo/activity.tmpl | 106 ++--- templates/repo/blame.tmpl | 18 +- templates/repo/branch/list.tmpl | 62 +-- templates/repo/branch_dropdown.tmpl | 20 +- templates/repo/cite/cite_buttons.tmpl | 2 +- templates/repo/cite/cite_modal.tmpl | 6 +- templates/repo/clone_buttons.tmpl | 2 +- .../code/recently_pushed_new_branches.tmpl | 4 +- .../repo/commit_load_branches_and_tags.tmpl | 6 +- templates/repo/commit_page.tmpl | 82 ++-- templates/repo/commits.tmpl | 2 +- templates/repo/commits_list.tmpl | 6 +- templates/repo/commits_table.tmpl | 12 +- templates/repo/create.tmpl | 102 ++-- templates/repo/create_helper.tmpl | 2 +- templates/repo/diff/box.tmpl | 74 +-- templates/repo/diff/comment_form.tmpl | 2 +- templates/repo/diff/compare.tmpl | 48 +- templates/repo/diff/conversation.tmpl | 20 +- templates/repo/diff/image_diff.tmpl | 22 +- templates/repo/diff/new_review.tmpl | 22 +- templates/repo/diff/options_dropdown.tmpl | 24 +- templates/repo/diff/stats.tmpl | 2 +- templates/repo/diff/whitespace_dropdown.tmpl | 12 +- templates/repo/editor/cherry_pick.tmpl | 6 +- templates/repo/editor/commit_form.tmpl | 38 +- templates/repo/editor/edit.tmpl | 24 +- templates/repo/editor/patch.tmpl | 14 +- templates/repo/editor/upload.tmpl | 6 +- templates/repo/empty.tmpl | 20 +- templates/repo/file_info.tmpl | 8 +- templates/repo/find/files.tmpl | 2 +- templates/repo/forks.tmpl | 2 +- templates/repo/graph.tmpl | 10 +- templates/repo/header.tmpl | 70 +-- templates/repo/home.tmpl | 46 +- .../repo/issue/branch_selector_field.tmpl | 14 +- templates/repo/issue/choose.tmpl | 12 +- templates/repo/issue/comment_tab.tmpl | 2 +- templates/repo/issue/filters.tmpl | 84 ++-- templates/repo/issue/labels.tmpl | 2 +- .../repo/issue/labels/edit_delete_label.tmpl | 30 +- templates/repo/issue/labels/label_list.tmpl | 30 +- .../issue/labels/label_load_template.tmpl | 6 +- templates/repo/issue/labels/label_new.tmpl | 20 +- .../issue/labels/labels_selector_field.tmpl | 8 +- .../repo/issue/labels/labels_sidebar.tmpl | 2 +- templates/repo/issue/list.tmpl | 40 +- .../repo/issue/milestone/select_menu.tmpl | 10 +- templates/repo/issue/milestone_issues.tmpl | 14 +- templates/repo/issue/milestone_new.tmpl | 28 +- templates/repo/issue/milestones.tmpl | 44 +- templates/repo/issue/navbar.tmpl | 4 +- templates/repo/issue/new_form.tmpl | 36 +- templates/repo/issue/openclose.tmpl | 4 +- templates/repo/issue/search.tmpl | 4 +- templates/repo/issue/view_content.tmpl | 38 +- .../repo/issue/view_content/attachments.tmpl | 4 +- .../repo/issue/view_content/comments.tmpl | 164 +++---- .../view_content/comments_delete_time.tmpl | 4 +- .../repo/issue/view_content/context_menu.tmpl | 10 +- templates/repo/issue/view_content/pull.tmpl | 112 ++--- .../repo/issue/view_content/reactions.tmpl | 2 +- .../view_content/reference_issue_dialog.tmpl | 10 +- .../repo/issue/view_content/sidebar.tmpl | 192 ++++---- .../view_content/update_branch_by_merge.tmpl | 10 +- templates/repo/issue/view_title.tmpl | 44 +- templates/repo/migrate/codebase.tmpl | 34 +- templates/repo/migrate/git.tmpl | 24 +- templates/repo/migrate/gitbucket.tmpl | 40 +- templates/repo/migrate/gitea.tmpl | 38 +- templates/repo/migrate/github.tmpl | 40 +- templates/repo/migrate/gitlab.tmpl | 38 +- templates/repo/migrate/gogs.tmpl | 38 +- templates/repo/migrate/migrate.tmpl | 2 +- templates/repo/migrate/migrating.tmpl | 32 +- templates/repo/migrate/onedev.tmpl | 34 +- templates/repo/migrate/options.tmpl | 14 +- templates/repo/pulls/fork.tmpl | 18 +- templates/repo/pulls/status.tmpl | 16 +- templates/repo/pulls/tab_menu.tmpl | 6 +- templates/repo/release/list.tmpl | 28 +- templates/repo/release/new.tmpl | 48 +- templates/repo/release_tag_header.tmpl | 8 +- templates/repo/search.tmpl | 18 +- templates/repo/settings/branches.tmpl | 22 +- templates/repo/settings/collaboration.tmpl | 38 +- templates/repo/settings/deploy_keys.tmpl | 34 +- templates/repo/settings/githook_edit.tmpl | 10 +- templates/repo/settings/githooks.tmpl | 4 +- templates/repo/settings/lfs.tmpl | 16 +- templates/repo/settings/lfs_file.tmpl | 18 +- templates/repo/settings/lfs_file_find.tmpl | 8 +- templates/repo/settings/lfs_locks.tmpl | 14 +- templates/repo/settings/lfs_pointers.tmpl | 16 +- templates/repo/settings/nav.tmpl | 18 +- templates/repo/settings/navbar.tmpl | 26 +- templates/repo/settings/options.tmpl | 450 +++++++++--------- templates/repo/settings/protected_branch.tmpl | 108 ++--- .../repo/settings/push_mirror_sync_modal.tmpl | 10 +- templates/repo/settings/tags.tmpl | 34 +- .../repo/settings/webhook/base_list.tmpl | 24 +- .../repo/settings/webhook/delete_modal.tmpl | 4 +- templates/repo/settings/webhook/dingtalk.tmpl | 4 +- templates/repo/settings/webhook/discord.tmpl | 8 +- templates/repo/settings/webhook/feishu.tmpl | 6 +- templates/repo/settings/webhook/gitea.tmpl | 10 +- templates/repo/settings/webhook/gogs.tmpl | 8 +- templates/repo/settings/webhook/history.tmpl | 20 +- templates/repo/settings/webhook/matrix.tmpl | 8 +- templates/repo/settings/webhook/msteams.tmpl | 4 +- templates/repo/settings/webhook/new.tmpl | 4 +- .../repo/settings/webhook/packagist.tmpl | 8 +- templates/repo/settings/webhook/settings.tmpl | 116 ++--- templates/repo/settings/webhook/slack.tmpl | 12 +- templates/repo/settings/webhook/telegram.tmpl | 8 +- .../repo/settings/webhook/wechatwork.tmpl | 4 +- templates/repo/sub_menu.tmpl | 8 +- templates/repo/tag/list.tmpl | 12 +- templates/repo/upload.tmpl | 8 +- templates/repo/user_cards.tmpl | 2 +- templates/repo/view_file.tmpl | 42 +- templates/repo/wiki/new.tmpl | 18 +- templates/repo/wiki/pages.tmpl | 8 +- templates/repo/wiki/revision.tmpl | 8 +- templates/repo/wiki/start.tmpl | 6 +- templates/repo/wiki/view.tmpl | 30 +- templates/shared/actions/runner_edit.tmpl | 36 +- templates/shared/issuelist.tmpl | 20 +- templates/shared/searchbottom.tmpl | 2 +- templates/shared/secrets/add_list.tmpl | 24 +- templates/shared/user/org_profile_avatar.tmpl | 4 +- templates/shared/user/profile_big_avatar.tmpl | 18 +- templates/shared/variables/variable_list.tmpl | 28 +- templates/status/404.tmpl | 4 +- templates/swagger/ui.tmpl | 2 +- templates/user/auth/activate.tmpl | 24 +- templates/user/auth/captcha.tmpl | 2 +- templates/user/auth/change_passwd_inner.tmpl | 8 +- templates/user/auth/finalize_openid.tmpl | 14 +- templates/user/auth/forgot_passwd.tmpl | 14 +- templates/user/auth/grant.tmpl | 10 +- templates/user/auth/grant_error.tmpl | 4 +- templates/user/auth/link_account.tmpl | 4 +- templates/user/auth/prohibit_login.tmpl | 4 +- templates/user/auth/reset_passwd.tmpl | 22 +- templates/user/auth/signin_inner.tmpl | 22 +- templates/user/auth/signin_navbar.tmpl | 4 +- templates/user/auth/signin_openid.tmpl | 6 +- templates/user/auth/signup_inner.tmpl | 24 +- .../user/auth/signup_openid_connect.tmpl | 12 +- templates/user/auth/signup_openid_navbar.tmpl | 4 +- .../user/auth/signup_openid_register.tmpl | 10 +- templates/user/auth/twofa.tmpl | 8 +- templates/user/auth/twofa_scratch.tmpl | 6 +- templates/user/auth/webauthn.tmpl | 10 +- templates/user/auth/webauthn_error.tmpl | 16 +- templates/user/dashboard/feeds.tmpl | 52 +- templates/user/dashboard/issues.tmpl | 44 +- templates/user/dashboard/milestones.tmpl | 40 +- templates/user/dashboard/navbar.tmpl | 36 +- templates/user/dashboard/repolist.tmpl | 54 +-- templates/user/heatmap.tmpl | 8 +- .../user/notification/notification_div.tmpl | 16 +- .../notification_subscriptions.tmpl | 38 +- templates/user/overview/header.tmpl | 22 +- templates/user/profile.tmpl | 2 +- templates/user/settings/account.tmpl | 68 +-- templates/user/settings/appearance.tmpl | 50 +- templates/user/settings/applications.tmpl | 46 +- .../user/settings/applications_oauth2.tmpl | 2 +- .../applications_oauth2_edit_form.tmpl | 22 +- .../settings/applications_oauth2_list.tmpl | 24 +- templates/user/settings/grants_oauth2.tmpl | 12 +- templates/user/settings/hook_new.tmpl | 4 +- templates/user/settings/keys_gpg.tmpl | 64 +-- templates/user/settings/keys_principal.tmpl | 24 +- templates/user/settings/keys_ssh.tmpl | 50 +- templates/user/settings/navbar.tmpl | 30 +- templates/user/settings/organization.tmpl | 12 +- templates/user/settings/packages.tmpl | 8 +- templates/user/settings/profile.tmpl | 62 +-- templates/user/settings/repos.tmpl | 26 +- .../user/settings/security/accountlinks.tmpl | 14 +- templates/user/settings/security/openid.tmpl | 18 +- templates/user/settings/security/twofa.tmpl | 22 +- .../user/settings/security/twofa_enroll.tmpl | 12 +- .../user/settings/security/webauthn.tmpl | 14 +- 305 files changed, 3810 insertions(+), 3810 deletions(-) diff --git a/templates/admin/applications/list.tmpl b/templates/admin/applications/list.tmpl index a292051fd0..cbb66b1605 100644 --- a/templates/admin/applications/list.tmpl +++ b/templates/admin/applications/list.tmpl @@ -1,7 +1,7 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin config")}}

- {{.locale.Tr "settings.applications"}} + {{ctx.Locale.Tr "settings.applications"}}

{{template "user/settings/applications_oauth2_list" .}}
diff --git a/templates/admin/auth/edit.tmpl b/templates/admin/auth/edit.tmpl index 814bddd8a4..25abefae00 100644 --- a/templates/admin/auth/edit.tmpl +++ b/templates/admin/auth/edit.tmpl @@ -1,7 +1,7 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin edit authentication")}}

- {{.locale.Tr "admin.auths.edit"}} + {{ctx.Locale.Tr "admin.auths.edit"}}

@@ -9,12 +9,12 @@ {{.CsrfTokenHtml}}
- + {{.Source.TypeName}}
- +
@@ -22,7 +22,7 @@ {{if or .Source.IsLDAP .Source.IsDLDAP}} {{$cfg:=.Source.Cfg}}
- +
- +
- +
- +
{{if .Source.IsLDAP}}
- +
- +
{{end}}
- +
{{if .Source.IsDLDAP}}
- +
{{end}}
- +
- +
- + -

{{.locale.Tr "admin.auths.restricted_filter_helper"}}

+

{{ctx.Locale.Tr "admin.auths.restricted_filter_helper"}}

- - + +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
@@ -144,31 +144,31 @@ {{if .Source.IsLDAP}}
- +
- +
- +
{{end}}
- + -

{{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

+

{{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

- +
@@ -178,7 +178,7 @@ {{if .Source.IsSMTP}} {{$cfg:=.Source.Cfg}}
- +
- +
- +
- +
-

{{.locale.Tr "admin.auths.force_smtps_helper"}}

+

{{ctx.Locale.Tr "admin.auths.force_smtps_helper"}}

- +
- + -

{{.locale.Tr "admin.auths.helo_hostname_helper"}}

+

{{ctx.Locale.Tr "admin.auths.helo_hostname_helper"}}

- +
- + -

{{.locale.Tr "admin.auths.allowed_domains_helper"}}

+

{{ctx.Locale.Tr "admin.auths.allowed_domains_helper"}}

- + -

{{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

+

{{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

{{end}} @@ -240,18 +240,18 @@ {{if .Source.IsPAM}} {{$cfg:=.Source.Cfg}}
- +
- +
- + -

{{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

+

{{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

{{end}} @@ -260,7 +260,7 @@ {{if .Source.IsOAuth2}} {{$cfg:=.Source.Cfg}}
- +
- +
- +
- +
- +
- + -

{{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

+

{{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

- +
- +
- +
- +
- +
- +
@@ -332,37 +332,37 @@ {{end}}{{end}}
- +
- + -

{{.locale.Tr "admin.auths.oauth2_required_claim_name_helper"}}

+

{{ctx.Locale.Tr "admin.auths.oauth2_required_claim_name_helper"}}

- + -

{{.locale.Tr "admin.auths.oauth2_required_claim_value_helper"}}

+

{{ctx.Locale.Tr "admin.auths.oauth2_required_claim_value_helper"}}

- +
- +
- +
- +
- +
{{end}} @@ -372,32 +372,32 @@ {{$cfg:=.Source.Cfg}}
- + -

{{.locale.Tr "admin.auths.sspi_auto_create_users_helper"}}

+

{{ctx.Locale.Tr "admin.auths.sspi_auto_create_users_helper"}}

- + -

{{.locale.Tr "admin.auths.sspi_auto_activate_users_helper"}}

+

{{ctx.Locale.Tr "admin.auths.sspi_auto_activate_users_helper"}}

- + -

{{.locale.Tr "admin.auths.sspi_strip_domain_names_helper"}}

+

{{ctx.Locale.Tr "admin.auths.sspi_strip_domain_names_helper"}}

- + -

{{.locale.Tr "admin.auths.sspi_separator_replacement_helper"}}

+

{{ctx.Locale.Tr "admin.auths.sspi_separator_replacement_helper"}}

- +
-

{{.locale.Tr "admin.auths.sspi_default_language_helper"}}

+

{{ctx.Locale.Tr "admin.auths.sspi_default_language_helper"}}

{{end}} {{if .Source.IsLDAP}}
- +
{{end}}
- +
- - + +

- {{.locale.Tr "admin.auths.tips"}} + {{ctx.Locale.Tr "admin.auths.tips"}}

GMail Settings:

Host: smtp.gmail.com, Port: 587, Enable TLS Encryption: true

-
{{.locale.Tr "admin.auths.tips.oauth2.general"}}:
-

{{.locale.Tr "admin.auths.tips.oauth2.general.tip"}}

+
{{ctx.Locale.Tr "admin.auths.tips.oauth2.general"}}:
+

{{ctx.Locale.Tr "admin.auths.tips.oauth2.general.tip"}}

diff --git a/templates/admin/auth/list.tmpl b/templates/admin/auth/list.tmpl index c9f7c0d516..fd9f69aec7 100644 --- a/templates/admin/auth/list.tmpl +++ b/templates/admin/auth/list.tmpl @@ -1,9 +1,9 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin authentication")}}

- {{.locale.Tr "admin.auths.auth_manage_panel"}} ({{.locale.Tr "admin.total" .Total}}) + {{ctx.Locale.Tr "admin.auths.auth_manage_panel"}} ({{.locale.Tr "admin.total" .Total}})

@@ -11,12 +11,12 @@
- - - - - - + + + + + + diff --git a/templates/admin/auth/new.tmpl b/templates/admin/auth/new.tmpl index 31efa62e71..f32f77d5dc 100644 --- a/templates/admin/auth/new.tmpl +++ b/templates/admin/auth/new.tmpl @@ -1,7 +1,7 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin new authentication")}}

- {{.locale.Tr "admin.auths.new"}} + {{ctx.Locale.Tr "admin.auths.new"}}

@@ -9,7 +9,7 @@ {{.CsrfTokenHtml}}
- +
- +
@@ -34,16 +34,16 @@
- + - +
- + -

{{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

+

{{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

@@ -55,67 +55,67 @@
- +
- +
- +
- +

- {{.locale.Tr "admin.auths.tips"}} + {{ctx.Locale.Tr "admin.auths.tips"}}

GMail Settings:

Host: smtp.gmail.com, Port: 587, Enable TLS Encryption: true

-
{{.locale.Tr "admin.auths.tips.oauth2.general"}}:
-

{{.locale.Tr "admin.auths.tips.oauth2.general.tip"}}

+
{{ctx.Locale.Tr "admin.auths.tips.oauth2.general"}}:
+

{{ctx.Locale.Tr "admin.auths.tips.oauth2.general.tip"}}

-
{{.locale.Tr "admin.auths.tip.oauth2_provider"}}
+
{{ctx.Locale.Tr "admin.auths.tip.oauth2_provider"}}
  • Bitbucket
  • - {{.locale.Tr "admin.auths.tip.bitbucket"}} + {{ctx.Locale.Tr "admin.auths.tip.bitbucket"}}
  • Dropbox
  • - {{.locale.Tr "admin.auths.tip.dropbox"}} + {{ctx.Locale.Tr "admin.auths.tip.dropbox"}}
  • Facebook
  • - {{.locale.Tr "admin.auths.tip.facebook"}} + {{ctx.Locale.Tr "admin.auths.tip.facebook"}}
  • GitHub
  • - {{.locale.Tr "admin.auths.tip.github"}} + {{ctx.Locale.Tr "admin.auths.tip.github"}}
  • GitLab
  • - {{.locale.Tr "admin.auths.tip.gitlab"}} + {{ctx.Locale.Tr "admin.auths.tip.gitlab"}}
  • Google
  • - {{.locale.Tr "admin.auths.tip.google_plus"}} + {{ctx.Locale.Tr "admin.auths.tip.google_plus"}}
  • OpenID Connect
  • - {{.locale.Tr "admin.auths.tip.openid_connect"}} + {{ctx.Locale.Tr "admin.auths.tip.openid_connect"}}
  • Twitter
  • - {{.locale.Tr "admin.auths.tip.twitter"}} + {{ctx.Locale.Tr "admin.auths.tip.twitter"}}
  • Discord
  • - {{.locale.Tr "admin.auths.tip.discord"}} + {{ctx.Locale.Tr "admin.auths.tip.discord"}}
  • Gitea
  • - {{.locale.Tr "admin.auths.tip.gitea"}} + {{ctx.Locale.Tr "admin.auths.tip.gitea"}}
  • Nextcloud
  • - {{.locale.Tr "admin.auths.tip.nextcloud"}} + {{ctx.Locale.Tr "admin.auths.tip.nextcloud"}}
  • Yandex
  • - {{.locale.Tr "admin.auths.tip.yandex"}} + {{ctx.Locale.Tr "admin.auths.tip.yandex"}}
  • Mastodon
  • - {{.locale.Tr "admin.auths.tip.mastodon"}} + {{ctx.Locale.Tr "admin.auths.tip.mastodon"}}
    diff --git a/templates/admin/auth/source/ldap.tmpl b/templates/admin/auth/source/ldap.tmpl index a2bd37be0c..a584ac7628 100644 --- a/templates/admin/auth/source/ldap.tmpl +++ b/templates/admin/auth/source/ldap.tmpl @@ -1,6 +1,6 @@
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - + -

    {{.locale.Tr "admin.auths.restricted_filter_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.restricted_filter_helper"}}

    - - + +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    @@ -117,24 +117,24 @@
    - +
    - +
    - + -

    {{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

    - +
    diff --git a/templates/admin/auth/source/oauth.tmpl b/templates/admin/auth/source/oauth.tmpl index aaa8b7fe2d..63ad77e67b 100644 --- a/templates/admin/auth/source/oauth.tmpl +++ b/templates/admin/auth/source/oauth.tmpl @@ -1,6 +1,6 @@
    - +
    - +
    - +
    - +
    - +
    - + -

    {{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

    - +
    - +
    - +
    - +
    - +
    - +
    @@ -73,37 +73,37 @@ {{end}}{{end}}
    - +
    - + -

    {{.locale.Tr "admin.auths.oauth2_required_claim_name_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.oauth2_required_claim_name_helper"}}

    - + -

    {{.locale.Tr "admin.auths.oauth2_required_claim_value_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.oauth2_required_claim_value_helper"}}

    - +
    - +
    - +
    - +
    - +
    diff --git a/templates/admin/auth/source/smtp.tmpl b/templates/admin/auth/source/smtp.tmpl index e83f7afb69..c4b0b0e7e4 100644 --- a/templates/admin/auth/source/smtp.tmpl +++ b/templates/admin/auth/source/smtp.tmpl @@ -1,6 +1,6 @@
    - +
    - +
    - +
    - + -

    {{.locale.Tr "admin.auths.force_smtps_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.force_smtps_helper"}}

    - +
    - + -

    {{.locale.Tr "admin.auths.helo_hostname_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.helo_hostname_helper"}}

    - +
    - + -

    {{.locale.Tr "admin.auths.allowed_domains_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.allowed_domains_helper"}}

    - + -

    {{.locale.Tr "admin.auths.skip_local_two_fa_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.skip_local_two_fa_helper"}}

    diff --git a/templates/admin/auth/source/sspi.tmpl b/templates/admin/auth/source/sspi.tmpl index 9608616e1b..f835e89bdf 100644 --- a/templates/admin/auth/source/sspi.tmpl +++ b/templates/admin/auth/source/sspi.tmpl @@ -1,32 +1,32 @@
    - + -

    {{.locale.Tr "admin.auths.sspi_auto_create_users_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.sspi_auto_create_users_helper"}}

    - + -

    {{.locale.Tr "admin.auths.sspi_auto_activate_users_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.sspi_auto_activate_users_helper"}}

    - + -

    {{.locale.Tr "admin.auths.sspi_strip_domain_names_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.sspi_strip_domain_names_helper"}}

    - + -

    {{.locale.Tr "admin.auths.sspi_separator_replacement_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.sspi_separator_replacement_helper"}}

    - +
    -

    {{.locale.Tr "admin.auths.sspi_default_language_helper"}}

    +

    {{ctx.Locale.Tr "admin.auths.sspi_default_language_helper"}}

    diff --git a/templates/admin/base/search.tmpl b/templates/admin/base/search.tmpl index 22f839bf05..d4bba8c042 100644 --- a/templates/admin/base/search.tmpl +++ b/templates/admin/base/search.tmpl @@ -2,22 +2,22 @@
    {{template "shared/searchinput" dict "Value" .Keyword "AutoFocus" true}} - +
    diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index c29d1dbf30..57722f9898 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -1,82 +1,82 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin config")}}

    - {{.locale.Tr "admin.config.server_config"}} + {{ctx.Locale.Tr "admin.config.server_config"}}

    -
    {{.locale.Tr "admin.config.app_name"}}
    +
    {{ctx.Locale.Tr "admin.config.app_name"}}
    {{AppName}}
    -
    {{.locale.Tr "admin.config.app_ver"}}
    +
    {{ctx.Locale.Tr "admin.config.app_ver"}}
    {{AppVer}}{{.AppBuiltWith}}
    -
    {{.locale.Tr "admin.config.custom_conf"}}
    +
    {{ctx.Locale.Tr "admin.config.custom_conf"}}
    {{.CustomConf}}
    -
    {{.locale.Tr "admin.config.app_url"}}
    +
    {{ctx.Locale.Tr "admin.config.app_url"}}
    {{.AppUrl}}
    -
    {{.locale.Tr "admin.config.domain"}}
    +
    {{ctx.Locale.Tr "admin.config.domain"}}
    {{.Domain}}
    -
    {{.locale.Tr "admin.config.offline_mode"}}
    +
    {{ctx.Locale.Tr "admin.config.offline_mode"}}
    {{if .OfflineMode}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.disable_router_log"}}
    +
    {{ctx.Locale.Tr "admin.config.disable_router_log"}}
    {{if .DisableRouterLog}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.run_user"}}
    +
    {{ctx.Locale.Tr "admin.config.run_user"}}
    {{.RunUser}}
    -
    {{.locale.Tr "admin.config.run_mode"}}
    +
    {{ctx.Locale.Tr "admin.config.run_mode"}}
    {{.RunMode}}
    -
    {{.locale.Tr "admin.config.git_version"}}
    +
    {{ctx.Locale.Tr "admin.config.git_version"}}
    {{.GitVersion}}
    -
    {{.locale.Tr "admin.config.app_data_path"}}
    +
    {{ctx.Locale.Tr "admin.config.app_data_path"}}
    {{.AppDataPath}}
    -
    {{.locale.Tr "admin.config.repo_root_path"}}
    +
    {{ctx.Locale.Tr "admin.config.repo_root_path"}}
    {{.RepoRootPath}}
    -
    {{.locale.Tr "admin.config.custom_file_root_path"}}
    +
    {{ctx.Locale.Tr "admin.config.custom_file_root_path"}}
    {{.CustomRootPath}}
    -
    {{.locale.Tr "admin.config.log_file_root_path"}}
    +
    {{ctx.Locale.Tr "admin.config.log_file_root_path"}}
    {{.LogRootPath}}
    -
    {{.locale.Tr "admin.config.script_type"}}
    +
    {{ctx.Locale.Tr "admin.config.script_type"}}
    {{.ScriptType}}
    -
    {{.locale.Tr "admin.config.reverse_auth_user"}}
    +
    {{ctx.Locale.Tr "admin.config.reverse_auth_user"}}
    {{.ReverseProxyAuthUser}}

    - {{.locale.Tr "admin.config.ssh_config"}} + {{ctx.Locale.Tr "admin.config.ssh_config"}}

    -
    {{.locale.Tr "admin.config.ssh_enabled"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_enabled"}}
    {{if not .SSH.Disabled}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{if not .SSH.Disabled}} -
    {{.locale.Tr "admin.config.ssh_start_builtin_server"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_start_builtin_server"}}
    {{if .SSH.StartBuiltinServer}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.ssh_domain"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_domain"}}
    {{.SSH.Domain}}
    -
    {{.locale.Tr "admin.config.ssh_port"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_port"}}
    {{.SSH.Port}}
    -
    {{.locale.Tr "admin.config.ssh_listen_port"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_listen_port"}}
    {{.SSH.ListenPort}}
    {{if not .SSH.StartBuiltinServer}} -
    {{.locale.Tr "admin.config.ssh_root_path"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_root_path"}}
    {{.SSH.RootPath}}
    -
    {{.locale.Tr "admin.config.ssh_key_test_path"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_key_test_path"}}
    {{.SSH.KeyTestPath}}
    -
    {{.locale.Tr "admin.config.ssh_keygen_path"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_keygen_path"}}
    {{.SSH.KeygenPath}}
    -
    {{.locale.Tr "admin.config.ssh_minimum_key_size_check"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_minimum_key_size_check"}}
    {{if .SSH.MinimumKeySizeCheck}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{if .SSH.MinimumKeySizeCheck}} -
    {{.locale.Tr "admin.config.ssh_minimum_key_sizes"}}
    +
    {{ctx.Locale.Tr "admin.config.ssh_minimum_key_sizes"}}
    {{.SSH.MinimumKeySizes}}
    {{end}} {{end}} @@ -85,160 +85,160 @@

    - {{.locale.Tr "admin.config.lfs_config"}} + {{ctx.Locale.Tr "admin.config.lfs_config"}}

    -
    {{.locale.Tr "admin.config.lfs_enabled"}}
    +
    {{ctx.Locale.Tr "admin.config.lfs_enabled"}}
    {{if .LFS.StartServer}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{if .LFS.StartServer}} -
    {{.locale.Tr "admin.config.lfs_content_path"}}
    +
    {{ctx.Locale.Tr "admin.config.lfs_content_path"}}
    {{JsonUtils.EncodeToString .LFS.Storage.ToShadowCopy}}
    -
    {{.locale.Tr "admin.config.lfs_http_auth_expiry"}}
    +
    {{ctx.Locale.Tr "admin.config.lfs_http_auth_expiry"}}
    {{.LFS.HTTPAuthExpiry}}
    {{end}}

    - {{.locale.Tr "admin.config.db_config"}} + {{ctx.Locale.Tr "admin.config.db_config"}}

    -
    {{.locale.Tr "admin.config.db_type"}}
    +
    {{ctx.Locale.Tr "admin.config.db_type"}}
    {{.DbCfg.Type}}
    {{if not (eq .DbCfg.Type "sqlite3")}} -
    {{.locale.Tr "admin.config.db_host"}}
    +
    {{ctx.Locale.Tr "admin.config.db_host"}}
    {{if .DbCfg.Host}}{{.DbCfg.Host}}{{else}}-{{end}}
    -
    {{.locale.Tr "admin.config.db_name"}}
    +
    {{ctx.Locale.Tr "admin.config.db_name"}}
    {{if .DbCfg.Name}}{{.DbCfg.Name}}{{else}}-{{end}}
    -
    {{.locale.Tr "admin.config.db_user"}}
    +
    {{ctx.Locale.Tr "admin.config.db_user"}}
    {{if .DbCfg.User}}{{.DbCfg.User}}{{else}}-{{end}}
    {{end}} {{if eq .DbCfg.Type "postgres"}} -
    {{.locale.Tr "admin.config.db_schema"}}
    +
    {{ctx.Locale.Tr "admin.config.db_schema"}}
    {{if .DbCfg.Schema}}{{.DbCfg.Schema}}{{else}}-{{end}}
    -
    {{.locale.Tr "admin.config.db_ssl_mode"}}
    +
    {{ctx.Locale.Tr "admin.config.db_ssl_mode"}}
    {{if .DbCfg.SSLMode}}{{.DbCfg.SSLMode}}{{else}}-{{end}}
    {{end}} {{if eq .DbCfg.Type "sqlite3"}} -
    {{.locale.Tr "admin.config.db_path"}}
    +
    {{ctx.Locale.Tr "admin.config.db_path"}}
    {{if .DbCfg.Path}}{{.DbCfg.Path}}{{else}}-{{end}}
    {{end}}

    - {{.locale.Tr "admin.config.service_config"}} + {{ctx.Locale.Tr "admin.config.service_config"}}

    -
    {{.locale.Tr "admin.config.register_email_confirm"}}
    +
    {{ctx.Locale.Tr "admin.config.register_email_confirm"}}
    {{if .Service.RegisterEmailConfirm}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.disable_register"}}
    +
    {{ctx.Locale.Tr "admin.config.disable_register"}}
    {{if .Service.DisableRegistration}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.allow_only_internal_registration"}}
    +
    {{ctx.Locale.Tr "admin.config.allow_only_internal_registration"}}
    {{if .Service.AllowOnlyInternalRegistration}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.allow_only_external_registration"}}
    +
    {{ctx.Locale.Tr "admin.config.allow_only_external_registration"}}
    {{if .Service.AllowOnlyExternalRegistration}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.show_registration_button"}}
    +
    {{ctx.Locale.Tr "admin.config.show_registration_button"}}
    {{if .Service.ShowRegistrationButton}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.enable_openid_signup"}}
    +
    {{ctx.Locale.Tr "admin.config.enable_openid_signup"}}
    {{if .Service.EnableOpenIDSignUp}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.enable_openid_signin"}}
    +
    {{ctx.Locale.Tr "admin.config.enable_openid_signin"}}
    {{if .Service.EnableOpenIDSignIn}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.require_sign_in_view"}}
    +
    {{ctx.Locale.Tr "admin.config.require_sign_in_view"}}
    {{if .Service.RequireSignInView}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.mail_notify"}}
    +
    {{ctx.Locale.Tr "admin.config.mail_notify"}}
    {{if .Service.EnableNotifyMail}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.disable_key_size_check"}}
    +
    {{ctx.Locale.Tr "admin.config.disable_key_size_check"}}
    {{if .SSH.MinimumKeySizeCheck}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.enable_captcha"}}
    +
    {{ctx.Locale.Tr "admin.config.enable_captcha"}}
    {{if .Service.EnableCaptcha}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.default_keep_email_private"}}
    +
    {{ctx.Locale.Tr "admin.config.default_keep_email_private"}}
    {{if .Service.DefaultKeepEmailPrivate}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.default_allow_create_organization"}}
    +
    {{ctx.Locale.Tr "admin.config.default_allow_create_organization"}}
    {{if .Service.DefaultAllowCreateOrganization}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.enable_timetracking"}}
    +
    {{ctx.Locale.Tr "admin.config.enable_timetracking"}}
    {{if .Service.EnableTimetracking}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{if .Service.EnableTimetracking}} -
    {{.locale.Tr "admin.config.default_enable_timetracking"}}
    +
    {{ctx.Locale.Tr "admin.config.default_enable_timetracking"}}
    {{if .Service.DefaultEnableTimetracking}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.default_allow_only_contributors_to_track_time"}}
    +
    {{ctx.Locale.Tr "admin.config.default_allow_only_contributors_to_track_time"}}
    {{if .Service.DefaultAllowOnlyContributorsToTrackTime}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{end}} -
    {{.locale.Tr "admin.config.default_visibility_organization"}}
    +
    {{ctx.Locale.Tr "admin.config.default_visibility_organization"}}
    {{.Service.DefaultOrgVisibility}}
    -
    {{.locale.Tr "admin.config.no_reply_address"}}
    +
    {{ctx.Locale.Tr "admin.config.no_reply_address"}}
    {{if .Service.NoReplyAddress}}{{.Service.NoReplyAddress}}{{else}}-{{end}}
    -
    {{.locale.Tr "admin.config.default_enable_dependencies"}}
    +
    {{ctx.Locale.Tr "admin.config.default_enable_dependencies"}}
    {{if .Service.DefaultEnableDependencies}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.active_code_lives"}}
    -
    {{.Service.ActiveCodeLives}} {{.locale.Tr "tool.raw_minutes"}}
    -
    {{.locale.Tr "admin.config.reset_password_code_lives"}}
    -
    {{.Service.ResetPwdCodeLives}} {{.locale.Tr "tool.raw_minutes"}}
    +
    {{ctx.Locale.Tr "admin.config.active_code_lives"}}
    +
    {{.Service.ActiveCodeLives}} {{ctx.Locale.Tr "tool.raw_minutes"}}
    +
    {{ctx.Locale.Tr "admin.config.reset_password_code_lives"}}
    +
    {{.Service.ResetPwdCodeLives}} {{ctx.Locale.Tr "tool.raw_minutes"}}

    - {{.locale.Tr "admin.config.webhook_config"}} + {{ctx.Locale.Tr "admin.config.webhook_config"}}

    -
    {{.locale.Tr "admin.config.queue_length"}}
    +
    {{ctx.Locale.Tr "admin.config.queue_length"}}
    {{.Webhook.QueueLength}}
    -
    {{.locale.Tr "admin.config.deliver_timeout"}}
    -
    {{.Webhook.DeliverTimeout}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.skip_tls_verify"}}
    +
    {{ctx.Locale.Tr "admin.config.deliver_timeout"}}
    +
    {{.Webhook.DeliverTimeout}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.skip_tls_verify"}}
    {{if .Webhook.SkipTLSVerify}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}

    - {{.locale.Tr "admin.config.mailer_config"}} + {{ctx.Locale.Tr "admin.config.mailer_config"}}

    -
    {{.locale.Tr "admin.config.mailer_enabled"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_enabled"}}
    {{if .MailerEnabled}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{if .MailerEnabled}} -
    {{.locale.Tr "admin.config.mailer_name"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_name"}}
    {{.Mailer.Name}}
    {{if eq .Mailer.Protocol "sendmail"}} -
    {{.locale.Tr "admin.config.mailer_use_sendmail"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_use_sendmail"}}
    {{svg "octicon-check"}}
    -
    {{.locale.Tr "admin.config.mailer_sendmail_path"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_sendmail_path"}}
    {{.Mailer.SendmailPath}}
    -
    {{.locale.Tr "admin.config.mailer_sendmail_args"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_sendmail_args"}}
    {{.Mailer.SendmailArgs}}
    -
    {{.locale.Tr "admin.config.mailer_sendmail_timeout"}}
    -
    {{.Mailer.SendmailTimeout}} {{.locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_sendmail_timeout"}}
    +
    {{.Mailer.SendmailTimeout}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    {{else if eq .Mailer.Protocol "dummy"}} -
    {{.locale.Tr "admin.config.mailer_use_dummy"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_use_dummy"}}
    {{svg "octicon-check"}}
    {{else}}{{/* SMTP family */}} -
    {{.locale.Tr "admin.config.mailer_protocol"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_protocol"}}
    {{.Mailer.Protocol}}
    -
    {{.locale.Tr "admin.config.mailer_enable_helo"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_enable_helo"}}
    {{if .Mailer.EnableHelo}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.mailer_smtp_addr"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_smtp_addr"}}
    {{.Mailer.SMTPAddr}}
    -
    {{.locale.Tr "admin.config.mailer_smtp_port"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_smtp_port"}}
    {{.Mailer.SMTPPort}}
    {{end}} -
    {{.locale.Tr "admin.config.mailer_user"}}
    +
    {{ctx.Locale.Tr "admin.config.mailer_user"}}
    {{if .Mailer.User}}{{.Mailer.User}}{{else}}(empty){{end}}
    -
    {{.locale.Tr "admin.config.send_test_mail"}}
    +
    {{ctx.Locale.Tr "admin.config.send_test_mail"}}
    {{.CsrfTokenHtml}}
    - +
    - +
    {{end}} @@ -246,118 +246,118 @@

    - {{.locale.Tr "admin.config.cache_config"}} + {{ctx.Locale.Tr "admin.config.cache_config"}}

    -
    {{.locale.Tr "admin.config.cache_adapter"}}
    +
    {{ctx.Locale.Tr "admin.config.cache_adapter"}}
    {{.CacheAdapter}}
    {{if eq .CacheAdapter "memory"}} -
    {{.locale.Tr "admin.config.cache_interval"}}
    -
    {{.CacheInterval}} {{.locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.cache_interval"}}
    +
    {{.CacheInterval}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    {{end}} {{if .CacheConn}} -
    {{.locale.Tr "admin.config.cache_conn"}}
    +
    {{ctx.Locale.Tr "admin.config.cache_conn"}}
    {{.CacheConn}}
    -
    {{.locale.Tr "admin.config.cache_item_ttl"}}
    +
    {{ctx.Locale.Tr "admin.config.cache_item_ttl"}}
    {{.CacheItemTTL}}
    {{end}}

    - {{.locale.Tr "admin.config.session_config"}} + {{ctx.Locale.Tr "admin.config.session_config"}}

    -
    {{.locale.Tr "admin.config.session_provider"}}
    +
    {{ctx.Locale.Tr "admin.config.session_provider"}}
    {{.SessionConfig.Provider}}
    -
    {{.locale.Tr "admin.config.provider_config"}}
    +
    {{ctx.Locale.Tr "admin.config.provider_config"}}
    {{if .SessionConfig.ProviderConfig}}{{.SessionConfig.ProviderConfig}}{{else}}-{{end}}
    -
    {{.locale.Tr "admin.config.cookie_name"}}
    +
    {{ctx.Locale.Tr "admin.config.cookie_name"}}
    {{.SessionConfig.CookieName}}
    -
    {{.locale.Tr "admin.config.gc_interval_time"}}
    -
    {{.SessionConfig.Gclifetime}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.session_life_time"}}
    -
    {{.SessionConfig.Maxlifetime}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.https_only"}}
    +
    {{ctx.Locale.Tr "admin.config.gc_interval_time"}}
    +
    {{.SessionConfig.Gclifetime}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.session_life_time"}}
    +
    {{.SessionConfig.Maxlifetime}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.https_only"}}
    {{if .SessionConfig.Secure}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}

    - {{.locale.Tr "admin.config.picture_config"}} + {{ctx.Locale.Tr "admin.config.picture_config"}}

    -
    {{.locale.Tr "admin.config.disable_gravatar"}}
    +
    {{ctx.Locale.Tr "admin.config.disable_gravatar"}}
    - +
    -
    {{.locale.Tr "admin.config.enable_federated_avatar"}}
    +
    {{ctx.Locale.Tr "admin.config.enable_federated_avatar"}}
    - +

    - {{.locale.Tr "admin.config.git_config"}} + {{ctx.Locale.Tr "admin.config.git_config"}}

    -
    {{.locale.Tr "admin.config.git_disable_diff_highlight"}}
    +
    {{ctx.Locale.Tr "admin.config.git_disable_diff_highlight"}}
    {{if .Git.DisableDiffHighlight}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    -
    {{.locale.Tr "admin.config.git_max_diff_lines"}}
    +
    {{ctx.Locale.Tr "admin.config.git_max_diff_lines"}}
    {{.Git.MaxGitDiffLines}}
    -
    {{.locale.Tr "admin.config.git_max_diff_line_characters"}}
    +
    {{ctx.Locale.Tr "admin.config.git_max_diff_line_characters"}}
    {{.Git.MaxGitDiffLineCharacters}}
    -
    {{.locale.Tr "admin.config.git_max_diff_files"}}
    +
    {{ctx.Locale.Tr "admin.config.git_max_diff_files"}}
    {{.Git.MaxGitDiffFiles}}
    -
    {{.locale.Tr "admin.config.git_gc_args"}}
    +
    {{ctx.Locale.Tr "admin.config.git_gc_args"}}
    {{.Git.GCArgs}}
    -
    {{.locale.Tr "admin.config.git_migrate_timeout"}}
    -
    {{.Git.Timeout.Migrate}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.git_mirror_timeout"}}
    -
    {{.Git.Timeout.Mirror}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.git_clone_timeout"}}
    -
    {{.Git.Timeout.Clone}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.git_pull_timeout"}}
    -
    {{.Git.Timeout.Pull}} {{.locale.Tr "tool.raw_seconds"}}
    -
    {{.locale.Tr "admin.config.git_gc_timeout"}}
    -
    {{.Git.Timeout.GC}} {{.locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.git_migrate_timeout"}}
    +
    {{.Git.Timeout.Migrate}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.git_mirror_timeout"}}
    +
    {{.Git.Timeout.Mirror}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.git_clone_timeout"}}
    +
    {{.Git.Timeout.Clone}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.git_pull_timeout"}}
    +
    {{.Git.Timeout.Pull}} {{ctx.Locale.Tr "tool.raw_seconds"}}
    +
    {{ctx.Locale.Tr "admin.config.git_gc_timeout"}}
    +
    {{.Git.Timeout.GC}} {{ctx.Locale.Tr "tool.raw_seconds"}}

    - {{.locale.Tr "admin.config.log_config"}} + {{ctx.Locale.Tr "admin.config.log_config"}}

    {{if .Loggers.xorm.IsEnabled}} -
    {{$.locale.Tr "admin.config.xorm_log_sql"}}
    +
    {{ctx.Locale.Tr "admin.config.xorm_log_sql"}}
    {{if $.LogSQL}}{{svg "octicon-check"}}{{else}}{{svg "octicon-x"}}{{end}}
    {{end}} {{if .Loggers.access.IsEnabled}} -
    {{$.locale.Tr "admin.config.access_log_template"}}
    +
    {{ctx.Locale.Tr "admin.config.access_log_template"}}
    {{$.AccessLogTemplate}}
    {{end}} {{range $loggerName, $loggerDetail := .Loggers}} -
    {{$.locale.Tr "admin.config.logger_name_fmt" $loggerName}}
    +
    {{ctx.Locale.Tr "admin.config.logger_name_fmt" $loggerName}}
    {{if $loggerDetail.IsEnabled}}
    {{$loggerDetail.EventWriters | JsonUtils.EncodeToString | JsonUtils.PrettyIndent}}
    {{else}} -
    {{$.locale.Tr "admin.config.disabled_logger"}}
    +
    {{ctx.Locale.Tr "admin.config.disabled_logger"}}
    {{end}} {{end}}
    diff --git a/templates/admin/cron.tmpl b/templates/admin/cron.tmpl index 354cd18ed5..1886b48d0d 100644 --- a/templates/admin/cron.tmpl +++ b/templates/admin/cron.tmpl @@ -1,7 +1,7 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin monitor")}}

    - {{.locale.Tr "admin.monitor.cron"}} + {{ctx.Locale.Tr "admin.monitor.cron"}}

    @@ -9,19 +9,19 @@
    - - - - - - + + + + + + {{range .Entries}} - - + + diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 69c0376d6e..6cb6c38e15 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -2,11 +2,11 @@
    {{if .NeedUpdate}}
    -

    {{(.locale.Tr "admin.dashboard.new_version_hint" .RemoteVersion AppVer) | Str2html}}

    +

    {{(ctx.Locale.Tr "admin.dashboard.new_version_hint" .RemoteVersion AppVer) | Str2html}}

    {{end}}

    - {{.locale.Tr "admin.dashboard.operations"}} + {{ctx.Locale.Tr "admin.dashboard.operations"}}

    @@ -14,56 +14,56 @@
    {{.locale.Tr "actions.runners.status"}}{{.locale.Tr "actions.runners.id"}}{{.locale.Tr "actions.runners.name"}} + {{.locale.Tr "actions.runners.status"}} + {{SortArrow "online" "offline" .SortType false}} + + {{.locale.Tr "actions.runners.id"}} + {{SortArrow "oldest" "newest" .SortType false}} + + {{.locale.Tr "actions.runners.name"}} + {{SortArrow "alphabetically" "reversealphabetically" .SortType false}} + {{.locale.Tr "actions.runners.version"}} {{.locale.Tr "actions.runners.owner_type"}} {{.locale.Tr "actions.runners.labels"}}{{.NumTeams}} {{.NumMembers}} {{.Name}} {{if .IsAdmin}} - {{$.locale.Tr "admin.users.admin"}} + {{$.locale.Tr "admin.users.admin"}} + {{else if eq 2 .Type}}{{/* Reserved user */}} + {{$.locale.Tr "admin.users.reserved"}} + {{else if eq 4 .Type}}{{/* Bot "user" */}} + {{$.locale.Tr "admin.users.bot"}} + {{else if eq 5 .Type}}{{/* Remote user */}} + {{$.locale.Tr "admin.users.remote"}} {{end}} {{.Email}}
    {{(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 @@
    {{$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 049/289] 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 0000000000..7772bbc16d --- /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 0000000000..aaf5f9cc2b --- /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 4bd13dc32d..6728a6bed8 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 1c0cd5c4aa..013350ac2f 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 0000000000..cb089cd89a --- /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 0000000000..07d359d07c --- /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 0000000000..01c9922c5f --- /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 ad7d35127e..c38c9d9e46 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 b1cb42297c..e4506a857e 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 b253c4d901..3078e9bef3 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 050/289] [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 6bc1d9d06c..eeb2a3ce8b 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 051/289] 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 8933f186dc..8746c8851e 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 052/289] 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 131a149782..b5c1301a1d 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 c38c9d9e46..e11d5167aa 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 f5831df28f..e0e27fd482 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 620e0b6c9f..011dc5568e 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 d2535e1e30..f309b1c60a 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"}} +
    +
    +
    + + +
    +

    +
    From 8531ca08372dd4a4739564dec17766fffe34a385 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Mon, 18 Sep 2023 07:32:56 +0800 Subject: [PATCH 053/289] Make SSPI auth mockable (#27036) Before, the SSPI auth is only complied for Windows, it's difficult to test and it breaks a lot. Now, make the SSPI auth mockable and testable. --- routers/api/v1/api.go | 5 +++- routers/api/v1/auth.go | 10 -------- routers/api/v1/auth_windows.go | 19 -------------- routers/web/auth.go | 10 -------- routers/web/auth_windows.go | 19 -------------- routers/web/web.go | 6 ++++- services/auth/{sspi_windows.go => sspi.go} | 30 ++++++++++------------ services/auth/sspiauth_posix.go | 30 ++++++++++++++++++++++ services/auth/sspiauth_windows.go | 19 ++++++++++++++ 9 files changed, 72 insertions(+), 76 deletions(-) delete mode 100644 routers/api/v1/auth.go delete mode 100644 routers/api/v1/auth_windows.go delete mode 100644 routers/web/auth.go delete mode 100644 routers/web/auth_windows.go rename services/auth/{sspi_windows.go => sspi.go} (90%) create mode 100644 services/auth/sspiauth_posix.go create mode 100644 services/auth/sspiauth_windows.go diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index ca74a23a4b..d58e39920b 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -705,7 +705,10 @@ func buildAuthGroup() *auth.Group { if setting.Service.EnableReverseProxyAuthAPI { group.Add(&auth.ReverseProxy{}) } - specialAdd(group) + + if setting.IsWindows && auth_model.IsSSPIEnabled() { + group.Add(&auth.SSPI{}) // it MUST be the last, see the comment of SSPI + } return group } diff --git a/routers/api/v1/auth.go b/routers/api/v1/auth.go deleted file mode 100644 index e44271ba14..0000000000 --- a/routers/api/v1/auth.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -//go:build !windows - -package v1 - -import auth_service "code.gitea.io/gitea/services/auth" - -func specialAdd(group *auth_service.Group) {} diff --git a/routers/api/v1/auth_windows.go b/routers/api/v1/auth_windows.go deleted file mode 100644 index 3514e21baa..0000000000 --- a/routers/api/v1/auth_windows.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package v1 - -import ( - "code.gitea.io/gitea/models/auth" - auth_service "code.gitea.io/gitea/services/auth" -) - -// specialAdd registers the SSPI auth method as the last method in the list. -// The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation -// fails (or if negotiation should continue), which would prevent other authentication methods -// to execute at all. -func specialAdd(group *auth_service.Group) { - if auth.IsSSPIEnabled() { - group.Add(&auth_service.SSPI{}) - } -} diff --git a/routers/web/auth.go b/routers/web/auth.go deleted file mode 100644 index 1ca860ecc8..0000000000 --- a/routers/web/auth.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -//go:build !windows - -package web - -import auth_service "code.gitea.io/gitea/services/auth" - -func specialAdd(group *auth_service.Group) {} diff --git a/routers/web/auth_windows.go b/routers/web/auth_windows.go deleted file mode 100644 index 3125d7ce9a..0000000000 --- a/routers/web/auth_windows.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package web - -import ( - "code.gitea.io/gitea/models/auth" - auth_service "code.gitea.io/gitea/services/auth" -) - -// specialAdd registers the SSPI auth method as the last method in the list. -// The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation -// fails (or if negotiation should continue), which would prevent other authentication methods -// to execute at all. -func specialAdd(group *auth_service.Group) { - if auth.IsSSPIEnabled() { - group.Add(&auth_service.SSPI{}) - } -} diff --git a/routers/web/web.go b/routers/web/web.go index 077a076864..99862505b4 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/context" @@ -92,7 +93,10 @@ func buildAuthGroup() *auth_service.Group { if setting.Service.EnableReverseProxyAuth { group.Add(&auth_service.ReverseProxy{}) } - specialAdd(group) + + if setting.IsWindows && auth_model.IsSSPIEnabled() { + group.Add(&auth_service.SSPI{}) // it MUST be the last, see the comment of SSPI + } return group } diff --git a/services/auth/sspi_windows.go b/services/auth/sspi.go similarity index 90% rename from services/auth/sspi_windows.go rename to services/auth/sspi.go index e29bd71529..d4f7e3ec60 100644 --- a/services/auth/sspi_windows.go +++ b/services/auth/sspi.go @@ -22,19 +22,21 @@ import ( "code.gitea.io/gitea/services/auth/source/sspi" gouuid "github.com/google/uuid" - "github.com/quasoft/websspi" ) const ( tplSignIn base.TplName = "user/auth/signin" ) +type SSPIAuth interface { + AppendAuthenticateHeader(w http.ResponseWriter, data string) + Authenticate(r *http.Request, w http.ResponseWriter) (userInfo *SSPIUserInfo, outToken string, err error) +} + var ( - // sspiAuth is a global instance of the websspi authentication package, - // which is used to avoid acquiring the server credential handle on - // every request - sspiAuth *websspi.Authenticator - sspiAuthOnce sync.Once + sspiAuth SSPIAuth // a global instance of the websspi authenticator to avoid acquiring the server credential handle on every request + sspiAuthOnce sync.Once + sspiAuthErrInit error // Ensure the struct implements the interface. _ Method = &SSPI{} @@ -42,8 +44,9 @@ var ( // SSPI implements the SingleSignOn interface and authenticates requests // via the built-in SSPI module in Windows for SPNEGO authentication. -// On successful authentication returns a valid user object. -// Returns nil if authentication fails. +// The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation +// fails (or if negotiation should continue), which would prevent other authentication methods +// to execute at all. type SSPI struct{} // Name represents the name of auth method @@ -56,15 +59,10 @@ func (s *SSPI) Name() string { // If negotiation should continue or authentication fails, immediately returns a 401 HTTP // response code, as required by the SPNEGO protocol. func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) { - var errInit error - sspiAuthOnce.Do(func() { - config := websspi.NewConfig() - sspiAuth, errInit = websspi.New(config) - }) - if errInit != nil { - return nil, errInit + sspiAuthOnce.Do(func() { sspiAuthErrInit = sspiAuthInit() }) + if sspiAuthErrInit != nil { + return nil, sspiAuthErrInit } - if !s.shouldAuthenticate(req) { return nil, nil } diff --git a/services/auth/sspiauth_posix.go b/services/auth/sspiauth_posix.go new file mode 100644 index 0000000000..49b0ed4a52 --- /dev/null +++ b/services/auth/sspiauth_posix.go @@ -0,0 +1,30 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +//go:build !windows + +package auth + +import ( + "errors" + "net/http" +) + +type SSPIUserInfo struct { + Username string // Name of user, usually in the form DOMAIN\User + Groups []string // The global groups the user is a member of +} + +type sspiAuthMock struct{} + +func (s sspiAuthMock) AppendAuthenticateHeader(w http.ResponseWriter, data string) { +} + +func (s sspiAuthMock) Authenticate(r *http.Request, w http.ResponseWriter) (userInfo *SSPIUserInfo, outToken string, err error) { + return nil, "", errors.New("not implemented") +} + +func sspiAuthInit() error { + sspiAuth = &sspiAuthMock{} // TODO: we can mock the SSPI auth in tests + return nil +} diff --git a/services/auth/sspiauth_windows.go b/services/auth/sspiauth_windows.go new file mode 100644 index 0000000000..093caaed33 --- /dev/null +++ b/services/auth/sspiauth_windows.go @@ -0,0 +1,19 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +//go:build windows + +package auth + +import ( + "github.com/quasoft/websspi" +) + +type SSPIUserInfo = websspi.UserInfo + +func sspiAuthInit() error { + var err error + config := websspi.NewConfig() + sspiAuth, err = websspi.New(config) + return err +} From f93ee5937bcb43aaf1e3b527d852487e80ae570b Mon Sep 17 00:00:00 2001 From: CaiCandong <50507092+CaiCandong@users.noreply.github.com> Date: Mon, 18 Sep 2023 08:21:15 +0800 Subject: [PATCH 054/289] Fix token endpoints ignore specified account (#27080) Fix #26234 close #26323 close #27040 --------- Co-authored-by: silverwind --- routers/api/v1/api.go | 12 +++++++++++- routers/api/v1/user/app.go | 12 +++++++++--- templates/swagger/v1_json.tmpl | 9 +++++++++ tests/integration/api_token_test.go | 23 +++++++++++++++++++++++ 4 files changed, 52 insertions(+), 4 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index d58e39920b..763d56ecd2 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -367,6 +367,16 @@ func reqOwner() func(ctx *context.APIContext) { } } +// reqSelfOrAdmin doer should be the same as the contextUser or site admin +func reqSelfOrAdmin() func(ctx *context.APIContext) { + return func(ctx *context.APIContext) { + if !ctx.IsUserSiteAdmin() && ctx.ContextUser != ctx.Doer { + ctx.Error(http.StatusForbidden, "reqSelfOrAdmin", "doer should be the site admin or be same as the contextUser") + return + } + } +} + // reqAdmin user should be an owner or a collaborator with admin write of a repository, or site admin func reqAdmin() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { @@ -910,7 +920,7 @@ func Routes() *web.Route { m.Combo("").Get(user.ListAccessTokens). Post(bind(api.CreateAccessTokenOption{}), reqToken(), user.CreateAccessToken) m.Combo("/{id}").Delete(reqToken(), user.DeleteAccessToken) - }, reqBasicOrRevProxyAuth()) + }, reqSelfOrAdmin(), reqBasicOrRevProxyAuth()) m.Get("/activities/feeds", user.ListUserActivityFeeds) }, context_service.UserAssignmentAPI()) diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index e512ba9e4b..6972931abc 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -43,8 +43,10 @@ func ListAccessTokens(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/AccessTokenList" + // "403": + // "$ref": "#/responses/forbidden" - opts := auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID, ListOptions: utils.GetListOptions(ctx)} + opts := auth_model.ListAccessTokensOptions{UserID: ctx.ContextUser.ID, ListOptions: utils.GetListOptions(ctx)} count, err := auth_model.CountAccessTokens(ctx, opts) if err != nil { @@ -95,11 +97,13 @@ func CreateAccessToken(ctx *context.APIContext) { // "$ref": "#/responses/AccessToken" // "400": // "$ref": "#/responses/error" + // "403": + // "$ref": "#/responses/forbidden" form := web.GetForm(ctx).(*api.CreateAccessTokenOption) t := &auth_model.AccessToken{ - UID: ctx.Doer.ID, + UID: ctx.ContextUser.ID, Name: form.Name, } @@ -153,6 +157,8 @@ func DeleteAccessToken(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" // "404": // "$ref": "#/responses/notFound" // "422": @@ -164,7 +170,7 @@ func DeleteAccessToken(ctx *context.APIContext) { if tokenID == 0 { tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{ Name: token, - UserID: ctx.Doer.ID, + UserID: ctx.ContextUser.ID, }) if err != nil { ctx.Error(http.StatusInternalServerError, "ListAccessTokens", err) diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index 88dc9ea1ce..39c5a7fe11 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -16359,6 +16359,9 @@ "responses": { "200": { "$ref": "#/responses/AccessTokenList" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -16396,6 +16399,9 @@ }, "400": { "$ref": "#/responses/error" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -16430,6 +16436,9 @@ "204": { "$ref": "#/responses/empty" }, + "403": { + "$ref": "#/responses/forbidden" + }, "404": { "$ref": "#/responses/notFound" }, diff --git a/tests/integration/api_token_test.go b/tests/integration/api_token_test.go index 1c63d07f22..a713922982 100644 --- a/tests/integration/api_token_test.go +++ b/tests/integration/api_token_test.go @@ -40,6 +40,29 @@ func TestAPIDeleteMissingToken(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) } +// TestAPIGetTokensPermission ensures that only the admin can get tokens from other users +func TestAPIGetTokensPermission(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + // admin can get tokens for other users + user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) + req := NewRequestf(t, "GET", "/api/v1/users/user2/tokens") + req = AddBasicAuthHeader(req, user.Name) + MakeRequest(t, req, http.StatusOK) + + // non-admin can get tokens for himself + user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) + req = NewRequestf(t, "GET", "/api/v1/users/user2/tokens") + req = AddBasicAuthHeader(req, user.Name) + MakeRequest(t, req, http.StatusOK) + + // non-admin can't get tokens for other users + user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) + req = NewRequestf(t, "GET", "/api/v1/users/user2/tokens") + req = AddBasicAuthHeader(req, user.Name) + MakeRequest(t, req, http.StatusForbidden) +} + type permission struct { category auth_model.AccessTokenScopeCategory level auth_model.AccessTokenScopeLevel From 558eea69bd89f75f7b9d11b9643abf717d7ba029 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Mon, 18 Sep 2023 00:23:39 +0000 Subject: [PATCH 055/289] [skip ci] Updated licenses and gitignores --- options/license/BSD-3-Clause-Sun | 29 ++++++++++++++++++++++++ options/license/BSD-Systemics | 39 ++++++++++++++++++++++++++++++++ options/license/Crossword | 2 +- options/license/DL-DE-ZERO-2.0 | 25 ++++++++++++++++++++ options/license/FBM | 6 +++++ options/license/Ferguson-Twofish | 15 ++++++++++++ options/license/MPEG-SSG | 23 +++++++++++++++++++ options/license/NPL-1.0 | 6 ++--- options/license/pnmstitch | 23 +++++++++++++++++++ 9 files changed, 164 insertions(+), 4 deletions(-) create mode 100644 options/license/BSD-3-Clause-Sun create mode 100644 options/license/BSD-Systemics create mode 100644 options/license/DL-DE-ZERO-2.0 create mode 100644 options/license/FBM create mode 100644 options/license/Ferguson-Twofish create mode 100644 options/license/MPEG-SSG create mode 100644 options/license/pnmstitch diff --git a/options/license/BSD-3-Clause-Sun b/options/license/BSD-3-Clause-Sun new file mode 100644 index 0000000000..1d86449d90 --- /dev/null +++ b/options/license/BSD-3-Clause-Sun @@ -0,0 +1,29 @@ +Copyright (c) 2001-2013 Oracle and/or its affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistribution in binary form must reproduct the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +Neither the name of Sun Microsystems, Inc. or the names of +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +This software is provided "AS IS," without a warranty of any kind. ALL +EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, +INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND +ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES +SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION +OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL +SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, +OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR +PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF +LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, +EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. diff --git a/options/license/BSD-Systemics b/options/license/BSD-Systemics new file mode 100644 index 0000000000..6ca8a26c33 --- /dev/null +++ b/options/license/BSD-Systemics @@ -0,0 +1,39 @@ +Copyright (C) 1995, 1996 Systemics Ltd (http://www.systemics.com/) +All rights reserved. + +This library and applications are FREE FOR COMMERCIAL AND NON-COMMERCIAL USE +as long as the following conditions are adhered to. + +Copyright remains with Systemics Ltd, and as such any Copyright notices +in the code are not to be removed. If this code is used in a product, +Systemics should be given attribution as the author of the parts used. +This can be in the form of a textual message at program startup or +in documentation (online or textual) provided with the package. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by Systemics Ltd (http://www.systemics.com/) + +THIS SOFTWARE IS PROVIDED BY SYSTEMICS LTD ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +The licence and distribution terms for any publically available version or +derivative of this code cannot be changed. i.e. this code cannot simply be +copied and put under another distribution licence [including the GNU Public Licence.] diff --git a/options/license/Crossword b/options/license/Crossword index 6be940c33b..35d95a79d7 100644 --- a/options/license/Crossword +++ b/options/license/Crossword @@ -1,5 +1,5 @@ Copyright (C) 1995-2009 Gerd Neugebauer cwpuzzle.dtx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. No author or distributor accepts responsibility to anyone for the consequences of using it or for whether it serves any particular purpose or works at all, unless he says so in writing. -. + Everyone is granted permission to copy, modify and redistribute cwpuzzle.dtx, provided this copyright notice is preserved and any modifications are indicated. diff --git a/options/license/DL-DE-ZERO-2.0 b/options/license/DL-DE-ZERO-2.0 new file mode 100644 index 0000000000..7daacde13d --- /dev/null +++ b/options/license/DL-DE-ZERO-2.0 @@ -0,0 +1,25 @@ +DL-DE->Zero-2.0 +Datenlizenz Deutschland – Zero – Version 2.0 + +Jede Nutzung ist ohne Einschränkungen oder Bedingungen zulässig. + +Die bereitgestellten Daten und Metadaten dürfen für die kommerzielle und nicht kommerzielle Nutzung insbesondere + + vervielfältigt, ausgedruckt, präsentiert, verändert, bearbeitet sowie an Dritte übermittelt werden; + mit eigenen Daten und Daten Anderer zusammengeführt und zu selbständigen neuen Datensätzen verbunden werden; + in interne und externe Geschäftsprozesse, Produkte und Anwendungen in öffentlichen und nicht öffentlichen elektronischen Netzwerken eingebunden werden. + + +Data licence Germany – Zero – version 2.0 + +Any use is permitted without restrictions or conditions. + +The data and meta-data provided may, for commercial and non-commercial use, in particular + + be copied, printed, presented, altered, processed and transmitted to third parties; + be merged with own data and with the data of others and be combined to form new and independent datasets; + be integrated in internal and external business processes, products and applications in public and non-public electronic networks. + + + +URL: https://www.govdata.de/dl-de/zero-2-0 diff --git a/options/license/FBM b/options/license/FBM new file mode 100644 index 0000000000..68d9149b90 --- /dev/null +++ b/options/license/FBM @@ -0,0 +1,6 @@ +Portions of this code Copyright (C) 1989 by Michael Mauldin. +Permission is granted to use this file in whole or in +part for any purpose, educational, recreational or commercial, +provided that this copyright notice is retained unchanged. +This software is available to all free of charge by anonymous +FTP and in the UUNET archives. diff --git a/options/license/Ferguson-Twofish b/options/license/Ferguson-Twofish new file mode 100644 index 0000000000..43bb00c3ee --- /dev/null +++ b/options/license/Ferguson-Twofish @@ -0,0 +1,15 @@ + The author hereby grants a perpetual license to everybody to + use this code for any purpose as long as the copyright message is included + in the source code of this or any derived work. + + Yes, this means that you, your company, your club, and anyone else + can use this code anywhere you want. You can change it and distribute it + under the GPL, include it in your commercial product without releasing + the source code, put it on the web, etc. + The only thing you cannot do is remove my copyright message, + or distribute any source code based on this implementation that does not + include my copyright message. + + I appreciate a mention in the documentation or credits, + but I understand if that is difficult to do. + I also appreciate it if you tell me where and why you used my code. diff --git a/options/license/MPEG-SSG b/options/license/MPEG-SSG new file mode 100644 index 0000000000..a0b6f4ffff --- /dev/null +++ b/options/license/MPEG-SSG @@ -0,0 +1,23 @@ +Copyright (C) 1994, MPEG Software Simulation Group. All Rights Reserved. */ + +Disclaimer of Warranty + +These software programs are available to the user without any license fee or +royalty on an "as is" basis. The MPEG Software Simulation Group disclaims +any and all warranties, whether express, implied, or statuary, including any +implied warranties or merchantability or of fitness for a particular +purpose. In no event shall the copyright-holder be liable for any +incidental, punitive, or consequential damages of any kind whatsoever +arising from the use of these programs. + +This disclaimer of warranty extends to the user of these programs and user's +customers, employees, agents, transferees, successors, and assigns. + +The MPEG Software Simulation Group does not represent or warrant that the +programs furnished hereunder are free of infringement of any third-party +patents. + +Commercial implementations of MPEG-1 and MPEG-2 video, including shareware, +are subject to royalty fees to patent holders. Many of these patents are +general enough such that they are unavoidable regardless of implementation +design. diff --git a/options/license/NPL-1.0 b/options/license/NPL-1.0 index 7a5030e9f7..65983791a2 100644 --- a/options/license/NPL-1.0 +++ b/options/license/NPL-1.0 @@ -8,20 +8,20 @@ NETSCAPE PUBLIC LICENSE Version 1.0 1.3. ``Covered Code'' means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof. 1.4. ``Electronic Distribution Mechanism'' means a mechanism generally accepted in the software development community for the electronic transfer of data. 1.5. ``Executable'' means Covered Code in any form other than Source Code. - 1.6. ``Initial Developer'' means the individual or entity identified as the Initial Developer in the Source Code notice required byExhibit A. + 1.6. ``Initial Developer'' means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A. 1.7. ``Larger Work'' means a work which combines Covered Code or portions thereof with code not governed by the terms of this License. 1.8. ``License'' means this document. 1.9. ``Modifications'' means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is: A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications. B. Any new file that contains any part of the Original Code or previous Modifications. - 1.10. ``Original Code'' means Source Code of computer software code which is described in the Source Code notice required byExhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License. + 1.10. ``Original Code'' means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License. 1.11. ``Source Code'' means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or a list of source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor's choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge. 1.12. ``You'' means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, ``You'' includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, ``control'' means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of fifty percent (50%) or more of the outstanding shares or beneficial ownership of such entity. 2. Source Code License. 2.1. The Initial Developer Grant. The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: - a) to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, or as part of a Larger Work; and + (a) to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, or as part of a Larger Work; and (b) under patents now or hereafter owned or controlled by Initial Developer, to make, have made, use and sell (``Utilize'') the Original Code (or portions thereof), but solely to the extent that any such patent is reasonably necessary to enable You to Utilize the Original Code (or portions thereof) and not to any greater extent that may be necessary to Utilize further Modifications or combinations. 2.2. Contributor Grant. Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: diff --git a/options/license/pnmstitch b/options/license/pnmstitch new file mode 100644 index 0000000000..cb9dc762d9 --- /dev/null +++ b/options/license/pnmstitch @@ -0,0 +1,23 @@ +Copyright (c) 2002 Mark Salyzyn +All rights reserved. + +TERMS AND CONDITIONS OF USE + +Redistribution and use in source form, with or without modification, are +permitted provided that redistributions of source code must retain the +above copyright notice, this list of conditions and the following +disclaimer. + +This software is provided `as is' by Mark Salyzyn and any express or implied +warranties, including, but not limited to, the implied warranties of +merchantability and fitness for a particular purpose, are disclaimed. In no +event shall Mark Salyzyn be liable for any direct, indirect, incidental, +special, exemplary or consequential damages (including, but not limited to, +procurement of substitute goods or services; loss of use, data, or profits; +or business interruptions) however caused and on any theory of liability, +whether in contract, strict liability, or tort (including negligence or +otherwise) arising in any way out of the use of this software, even if +advised of the possibility of such damage. + +Any restrictions or encumberances added to this source code or derivitives, +is prohibited. From e97baed800ed9b83c5634492205318ab0c820719 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Mon, 18 Sep 2023 12:25:36 +0800 Subject: [PATCH 056/289] Remove a `gt-float-right` and some unnecessary helpers (#27110) Follow Remove polluted .ui.right #26825 Remove more `gt-float-right`, remove unnecessary helpers, remove negative margin tricks. ![image](https://github.com/go-gitea/gitea/assets/2114189/2785c6e6-7823-4699-a4f3-184eef50ceda) --- templates/repo/release/list.tmpl | 37 +++++++++++----------- web_src/css/repo/release-tag.css | 54 ++++++++++---------------------- 2 files changed, 35 insertions(+), 56 deletions(-) diff --git a/templates/repo/release/list.tmpl b/templates/repo/release/list.tmpl index b93134b5d9..a717fba651 100644 --- a/templates/repo/release/list.tmpl +++ b/templates/repo/release/list.tmpl @@ -16,19 +16,19 @@
    -

    +

    {{.Title}} {{if .IsDraft}} - {{$.locale.Tr "repo.release.draft"}} + {{$.locale.Tr "repo.release.draft"}} {{else if .IsPrerelease}} - {{$.locale.Tr "repo.release.prerelease"}} + {{$.locale.Tr "repo.release.prerelease"}} {{else if not .IsTag}} - {{$.locale.Tr "repo.release.stable"}} + {{$.locale.Tr "repo.release.stable"}} {{end}}

    -
    +
    {{if and $.CanCreateRelease (not .IsTag)}} - + {{svg "octicon-pencil"}} {{end}} @@ -38,7 +38,7 @@

    {{if gt .Publisher.ID 0}} - {{ctx.AvatarUtils.Avatar .Publisher 20}} + {{ctx.AvatarUtils.Avatar .Publisher 20 "gt-mr-2"}} {{.Publisher.Name}} @@ -55,9 +55,9 @@

    {{if .OriginalAuthor}} - {{svg "octicon-mark-github" 16 "gt-mr-2"}}{{.OriginalAuthor}} + {{svg "octicon-mark-github" 20 "gt-mr-2"}}{{.OriginalAuthor}} {{else if .Publisher}} - {{ctx.AvatarUtils.Avatar .Publisher 20}} + {{ctx.AvatarUtils.Avatar .Publisher 20 "gt-mr-2"}} {{.Publisher.GetDisplayName}} {{else}} Ghost @@ -77,8 +77,9 @@

    {{Str2html .Note}}
    -
    - +
    +
    + {{$.locale.Tr "repo.release.downloads"}}
    -   +
    {{end}} diff --git a/web_src/css/repo/release-tag.css b/web_src/css/repo/release-tag.css index 5d1830f16a..a146eda6a9 100644 --- a/web_src/css/repo/release-tag.css +++ b/web_src/css/repo/release-tag.css @@ -7,22 +7,14 @@ .repository.releases #release-list .release-list-title { font-size: 2rem; font-weight: var(--font-weight-normal); - margin-top: -4px; - margin-bottom: 0; -} - -.repository.releases #release-list > li { - list-style: none; -} - -.repository.releases #release-list > li .meta, -.repository.releases #release-list > li .detail { - padding-top: 30px; - padding-bottom: 40px; + display: flex; + align-items: center; + gap: 0.25em; + margin: 0; } .repository.releases #release-list > li .meta { - margin-top: 4px; + padding-top: 25px; position: relative; text-align: right; display: flex; @@ -31,44 +23,30 @@ } .repository.releases #release-list > li .detail { + padding-bottom: 20px; border-left: 1px solid var(--color-secondary); } .repository.releases #release-list > li .detail .author img { - margin-bottom: 3px; -} - -.repository.releases #release-list > li .detail .download > a .svg { - margin-left: 5px; - margin-right: 5px; + margin-bottom: 2px; /* the legacy trick to align the avatar vertically, no better solution at the moment */ } .repository.releases #release-list > li .detail .download .list { padding-left: 0; -} - -.repository.releases #release-list > li .detail .download .list li { - list-style: none; - display: block; - padding: 8px; border: 1px solid var(--color-secondary); + border-radius: var(--border-radius); background: var(--color-light); } -.repository.releases #release-list > li .detail .download .list li a > .text.right { - margin-right: 5px; +.repository.releases #release-list > li .detail .download .list li { + display: flex; + justify-content: space-between; + padding: 8px; + border-bottom: 1px solid var(--color-secondary); } -.repository.releases #release-list > li .detail .download .list li + li { - border-top: 0; -} - -.repository.releases #release-list > li .detail .download .list li:first-of-type { - border-radius: var(--border-radius) 0 0 var(--border-radius); -} - -.repository.releases #release-list > li .detail .download .list li:last-of-type { - border-radius: 0 var(--border-radius) var(--border-radius) 0; +.repository.releases #release-list > li .detail .download .list li:last-child { + border-bottom: none; } .repository.releases #release-list > li .detail .dot { @@ -77,7 +55,7 @@ background-color: var(--color-secondary-dark-3); position: absolute; left: -5.5px; - top: 40px; + top: 30px; border-radius: var(--border-radius-circle); border: 2.5px solid var(--color-body); } From a50d9af876435d007e6052c6ef8ebc838dd9709f Mon Sep 17 00:00:00 2001 From: puni9869 <80308335+puni9869@users.noreply.github.com> Date: Mon, 18 Sep 2023 10:24:05 +0530 Subject: [PATCH 057/289] Display archived labels specially when listing labels (#26820) Follow up https://github.com/go-gitea/gitea/pull/26741 Changes: Added archived label for org labels and added into issue filter list. Part of https://github.com/go-gitea/gitea/issues/25237 --------- Signed-off-by: puni9869 Co-authored-by: silverwind --- options/locale/locale_en-US.ini | 3 +- templates/repo/issue/filters.tmpl | 5 +++- .../repo/issue/labels/label_archived.tmpl | 5 ++++ templates/repo/issue/labels/label_list.tmpl | 30 +++++++++---------- web_src/css/base.css | 3 +- web_src/css/repo/issue-label.css | 5 +++- 6 files changed, 32 insertions(+), 19 deletions(-) create mode 100644 templates/repo/issue/labels/label_archived.tmpl diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index e11d5167aa..74b8931de8 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -123,6 +123,8 @@ unpin = Unpin artifacts = Artifacts +archived = Archived + concept_system_global = Global concept_user_individual = Individual concept_code_repository = Repository @@ -317,7 +319,6 @@ filter_by_team_repositories = Filter by team repositories feed_of = Feed of "%s" show_archived = Archived -archived = Archived show_both_archived_unarchived = Showing both archived and unarchived show_only_archived = Showing only archived show_only_unarchived = Showing only unarchived diff --git a/templates/repo/issue/filters.tmpl b/templates/repo/issue/filters.tmpl index b482e471e1..3bfced90d6 100644 --- a/templates/repo/issue/filters.tmpl +++ b/templates/repo/issue/filters.tmpl @@ -29,7 +29,10 @@
    {{end}} {{$previousExclusiveScope = $exclusiveScope}} - {{if .IsExcluded}}{{svg "octicon-circle-slash"}}{{else if .IsSelected}}{{if $exclusiveScope}}{{svg "octicon-dot-fill"}}{{else}}{{svg "octicon-check"}}{{end}}{{end}} {{RenderLabel $.Context .}} + {{if .IsExcluded}}{{svg "octicon-circle-slash"}}{{else if .IsSelected}}{{if $exclusiveScope}}{{svg "octicon-dot-fill"}}{{else}}{{svg "octicon-check"}}{{end}}{{end}} + {{RenderLabel $.Context .}} +

    {{template "repo/issue/labels/label_archived" .}}

    +
    {{end}}
    diff --git a/templates/repo/issue/labels/label_archived.tmpl b/templates/repo/issue/labels/label_archived.tmpl new file mode 100644 index 0000000000..feaf77e456 --- /dev/null +++ b/templates/repo/issue/labels/label_archived.tmpl @@ -0,0 +1,5 @@ +{{if .IsArchived}} + + {{ctx.Locale.Tr "archived"}} + +{{end}} diff --git a/templates/repo/issue/labels/label_list.tmpl b/templates/repo/issue/labels/label_list.tmpl index b29e606baa..d9addb439b 100644 --- a/templates/repo/issue/labels/label_list.tmpl +++ b/templates/repo/issue/labels/label_list.tmpl @@ -33,11 +33,6 @@
  • {{RenderLabel $.Context .}} - {{if not .ArchivedUnix.IsZero}} - - {{$.locale.Tr "home.archived"}} - - {{end}} {{if .Description}}
    {{.Description | RenderEmoji $.Context}}{{end}}
    -
    - {{if and (not $.PageIsOrgSettingsLabels) (not $.Repository.IsArchived) (or $.CanWriteIssues $.CanWritePulls)}} - {{svg "octicon-pencil"}} {{$.locale.Tr "repo.issues.label_edit"}} - {{svg "octicon-trash"}} {{$.locale.Tr "repo.issues.label_delete"}} - {{else if $.PageIsOrgSettingsLabels}} - {{svg "octicon-pencil"}} {{$.locale.Tr "repo.issues.label_edit"}} - {{svg "octicon-trash"}} {{$.locale.Tr "repo.issues.label_delete"}} - {{end}} +
    + {{template "repo/issue/labels/label_archived" .}} +
    + {{if and (not $.PageIsOrgSettingsLabels) (not $.Repository.IsArchived) (or $.CanWriteIssues $.CanWritePulls)}} + {{svg "octicon-pencil"}} {{$.locale.Tr "repo.issues.label_edit"}} + {{svg "octicon-trash"}} {{$.locale.Tr "repo.issues.label_delete"}} + {{else if $.PageIsOrgSettingsLabels}} + {{svg "octicon-pencil"}} {{$.locale.Tr "repo.issues.label_edit"}} + {{svg "octicon-trash"}} {{$.locale.Tr "repo.issues.label_delete"}} + {{end}} +
  • {{end}} @@ -78,9 +76,11 @@ {{if .Description}}
    {{.Description | RenderEmoji $.Context}}{{end}}
    +
    + {{template "repo/issue/labels/label_archived" .}}
    -
    {{end}} {{end}} diff --git a/web_src/css/base.css b/web_src/css/base.css index b41bfc6942..a305701332 100644 --- a/web_src/css/base.css +++ b/web_src/css/base.css @@ -1969,7 +1969,8 @@ a.ui.ui.ui.basic.primary.label:hover { } .ui.basic.labels .label, -.ui.basic.label { +.ui.basic.label, +.ui.secondary.labels .ui.basic.label { background: var(--color-button); border-color: var(--color-light-border); color: var(--color-text-light); diff --git a/web_src/css/repo/issue-label.css b/web_src/css/repo/issue-label.css index a2eb0344a5..1f83e81d96 100644 --- a/web_src/css/repo/issue-label.css +++ b/web_src/css/repo/issue-label.css @@ -30,7 +30,6 @@ .issue-label-list .item .label-operation { width: 33%; - text-align: right; } .issue-label-list .item a { @@ -42,3 +41,7 @@ .issue-label-list .item.org-label { opacity: 0.7; } + +.label-operation .label { + height: fit-content; +} From 9631958a82c70f30421fc4e292f700ec8881805e Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Mon, 18 Sep 2023 04:40:50 -0400 Subject: [PATCH 058/289] Refactor lfs requests (#26783) - Refactor lfs request code - The original code uses `performRequest` function to create the request, uses a callback to modify the request, and then send the request. - Now it's replaced with `createRequest` that only creates request and `performRequest` that only sends the request. - Reuse `createRequest` and `performRequest` in `http_client.go` and `transferadapter.go` --------- Co-authored-by: wxiaoguang --- modules/lfs/filesystem_client.go | 12 ++-- modules/lfs/http_client.go | 104 +++++++++++++++++++---------- modules/lfs/http_client_test.go | 36 ++++++----- modules/lfs/pointer.go | 4 +- modules/lfs/transferadapter.go | 108 +++++++++---------------------- modules/util/path.go | 1 + 6 files changed, 127 insertions(+), 138 deletions(-) diff --git a/modules/lfs/filesystem_client.go b/modules/lfs/filesystem_client.go index 835551e00c..3503a9effc 100644 --- a/modules/lfs/filesystem_client.go +++ b/modules/lfs/filesystem_client.go @@ -15,7 +15,7 @@ import ( // FilesystemClient is used to read LFS data from a filesystem path type FilesystemClient struct { - lfsdir string + lfsDir string } // BatchSize returns the preferred size of batchs to process @@ -25,16 +25,12 @@ func (c *FilesystemClient) BatchSize() int { func newFilesystemClient(endpoint *url.URL) *FilesystemClient { path, _ := util.FileURLToPath(endpoint) - - lfsdir := filepath.Join(path, "lfs", "objects") - - client := &FilesystemClient{lfsdir} - - return client + lfsDir := filepath.Join(path, "lfs", "objects") + return &FilesystemClient{lfsDir} } func (c *FilesystemClient) objectPath(oid string) string { - return filepath.Join(c.lfsdir, oid[0:2], oid[2:4], oid) + return filepath.Join(c.lfsDir, oid[0:2], oid[2:4], oid) } // Download reads the specific LFS object from the target path diff --git a/modules/lfs/http_client.go b/modules/lfs/http_client.go index ec0d6269bd..de0b1e4fed 100644 --- a/modules/lfs/http_client.go +++ b/modules/lfs/http_client.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "io" "net/http" "net/url" "strings" @@ -17,7 +18,7 @@ import ( "code.gitea.io/gitea/modules/proxy" ) -const batchSize = 20 +const httpBatchSize = 20 // HTTPClient is used to communicate with the LFS server // https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md @@ -29,7 +30,7 @@ type HTTPClient struct { // BatchSize returns the preferred size of batchs to process func (c *HTTPClient) BatchSize() int { - return batchSize + return httpBatchSize } func newHTTPClient(endpoint *url.URL, httpTransport *http.Transport) *HTTPClient { @@ -43,28 +44,25 @@ func newHTTPClient(endpoint *url.URL, httpTransport *http.Transport) *HTTPClient Transport: httpTransport, } - client := &HTTPClient{ - client: hc, - endpoint: strings.TrimSuffix(endpoint.String(), "/"), - transfers: make(map[string]TransferAdapter), - } - basic := &BasicTransferAdapter{hc} - - client.transfers[basic.Name()] = basic + client := &HTTPClient{ + client: hc, + endpoint: strings.TrimSuffix(endpoint.String(), "/"), + transfers: map[string]TransferAdapter{ + basic.Name(): basic, + }, + } return client } func (c *HTTPClient) transferNames() []string { keys := make([]string, len(c.transfers)) - i := 0 for k := range c.transfers { keys[i] = k i++ } - return keys } @@ -74,7 +72,6 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin url := fmt.Sprintf("%s/objects/batch", c.endpoint) request := &BatchRequest{operation, c.transferNames(), nil, objects} - payload := new(bytes.Buffer) err := json.NewEncoder(payload).Encode(request) if err != nil { @@ -82,32 +79,17 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin return nil, err } - log.Trace("Calling: %s", url) - - req, err := http.NewRequestWithContext(ctx, "POST", url, payload) + req, err := createRequest(ctx, http.MethodPost, url, map[string]string{"Content-Type": MediaType}, payload) if err != nil { - log.Error("Error creating request: %v", err) return nil, err } - req.Header.Set("Content-type", MediaType) - req.Header.Set("Accept", MediaType) - res, err := c.client.Do(req) + res, err := performRequest(ctx, c.client, req) if err != nil { - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - log.Error("Error while processing request: %v", err) return nil, err } defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("Unexpected server response: %s", res.Status) - } - var response BatchResponse err = json.NewDecoder(res.Body).Decode(&response) if err != nil { @@ -177,7 +159,7 @@ func (c *HTTPClient) performOperation(ctx context.Context, objects []Pointer, dc link, ok := object.Actions["upload"] if !ok { log.Debug("%+v", object) - return errors.New("Missing action 'upload'") + return errors.New("missing action 'upload'") } content, err := uc(object.Pointer, nil) @@ -187,8 +169,6 @@ func (c *HTTPClient) performOperation(ctx context.Context, objects []Pointer, dc err = transferAdapter.Upload(ctx, link, object.Pointer, content) - content.Close() - if err != nil { return err } @@ -203,7 +183,7 @@ func (c *HTTPClient) performOperation(ctx context.Context, objects []Pointer, dc link, ok := object.Actions["download"] if !ok { log.Debug("%+v", object) - return errors.New("Missing action 'download'") + return errors.New("missing action 'download'") } content, err := transferAdapter.Download(ctx, link) @@ -219,3 +199,59 @@ func (c *HTTPClient) performOperation(ctx context.Context, objects []Pointer, dc return nil } + +// createRequest creates a new request, and sets the headers. +func createRequest(ctx context.Context, method, url string, headers map[string]string, body io.Reader) (*http.Request, error) { + log.Trace("createRequest: %s", url) + req, err := http.NewRequestWithContext(ctx, method, url, body) + if err != nil { + log.Error("Error creating request: %v", err) + return nil, err + } + + for key, value := range headers { + req.Header.Set(key, value) + } + req.Header.Set("Accept", MediaType) + + return req, nil +} + +// performRequest sends a request, optionally performs a callback on the request and returns the response. +// If the status code is 200, the response is returned, and it will contain a non-nil Body. +// Otherwise, it will return an error, and the Body will be nil or closed. +func performRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + log.Trace("performRequest: %s", req.URL) + res, err := client.Do(req) + if err != nil { + select { + case <-ctx.Done(): + return res, ctx.Err() + default: + } + log.Error("Error while processing request: %v", err) + return res, err + } + + if res.StatusCode != http.StatusOK { + defer res.Body.Close() + return res, handleErrorResponse(res) + } + + return res, nil +} + +func handleErrorResponse(resp *http.Response) error { + var er ErrorResponse + err := json.NewDecoder(resp.Body).Decode(&er) + if err != nil { + if err == io.EOF { + return io.ErrUnexpectedEOF + } + log.Error("Error decoding json: %v", err) + return err + } + + log.Trace("ErrorResponse: %v", er) + return errors.New(er.Message) +} diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go index cb71b9008a..7459d9c0c9 100644 --- a/modules/lfs/http_client_test.go +++ b/modules/lfs/http_client_test.go @@ -177,7 +177,7 @@ func TestHTTPClientDownload(t *testing.T) { // case 0 { endpoint: "https://status-not-ok.io", - expectederror: "Unexpected server response: ", + expectederror: io.ErrUnexpectedEOF.Error(), }, // case 1 { @@ -207,7 +207,7 @@ func TestHTTPClientDownload(t *testing.T) { // case 6 { endpoint: "https://empty-actions-map.io", - expectederror: "Missing action 'download'", + expectederror: "missing action 'download'", }, // case 7 { @@ -217,27 +217,28 @@ func TestHTTPClientDownload(t *testing.T) { // case 8 { endpoint: "https://upload-actions-map.io", - expectederror: "Missing action 'download'", + expectederror: "missing action 'download'", }, // case 9 { endpoint: "https://verify-actions-map.io", - expectederror: "Missing action 'download'", + expectederror: "missing action 'download'", }, // case 10 { endpoint: "https://unknown-actions-map.io", - expectederror: "Missing action 'download'", + expectederror: "missing action 'download'", }, } for n, c := range cases { client := &HTTPClient{ - client: hc, - endpoint: c.endpoint, - transfers: make(map[string]TransferAdapter), + client: hc, + endpoint: c.endpoint, + transfers: map[string]TransferAdapter{ + "dummy": dummy, + }, } - client.transfers["dummy"] = dummy err := client.Download(context.Background(), []Pointer{p}, func(p Pointer, content io.ReadCloser, objectError error) error { if objectError != nil { @@ -284,7 +285,7 @@ func TestHTTPClientUpload(t *testing.T) { // case 0 { endpoint: "https://status-not-ok.io", - expectederror: "Unexpected server response: ", + expectederror: io.ErrUnexpectedEOF.Error(), }, // case 1 { @@ -319,7 +320,7 @@ func TestHTTPClientUpload(t *testing.T) { // case 7 { endpoint: "https://download-actions-map.io", - expectederror: "Missing action 'upload'", + expectederror: "missing action 'upload'", }, // case 8 { @@ -329,22 +330,23 @@ func TestHTTPClientUpload(t *testing.T) { // case 9 { endpoint: "https://verify-actions-map.io", - expectederror: "Missing action 'upload'", + expectederror: "missing action 'upload'", }, // case 10 { endpoint: "https://unknown-actions-map.io", - expectederror: "Missing action 'upload'", + expectederror: "missing action 'upload'", }, } for n, c := range cases { client := &HTTPClient{ - client: hc, - endpoint: c.endpoint, - transfers: make(map[string]TransferAdapter), + client: hc, + endpoint: c.endpoint, + transfers: map[string]TransferAdapter{ + "dummy": dummy, + }, } - client.transfers["dummy"] = dummy err := client.Upload(context.Background(), []Pointer{p}, func(p Pointer, objectError error) (io.ReadCloser, error) { return io.NopCloser(new(bytes.Buffer)), objectError diff --git a/modules/lfs/pointer.go b/modules/lfs/pointer.go index d7653e836c..3e5bb8f91d 100644 --- a/modules/lfs/pointer.go +++ b/modules/lfs/pointer.go @@ -29,10 +29,10 @@ const ( var ( // ErrMissingPrefix occurs if the content lacks the LFS prefix - ErrMissingPrefix = errors.New("Content lacks the LFS prefix") + ErrMissingPrefix = errors.New("content lacks the LFS prefix") // ErrInvalidStructure occurs if the content has an invalid structure - ErrInvalidStructure = errors.New("Content has an invalid structure") + ErrInvalidStructure = errors.New("content has an invalid structure") // ErrInvalidOIDFormat occurs if the oid has an invalid format ErrInvalidOIDFormat = errors.New("OID has an invalid format") diff --git a/modules/lfs/transferadapter.go b/modules/lfs/transferadapter.go index 649497aabb..d425b91946 100644 --- a/modules/lfs/transferadapter.go +++ b/modules/lfs/transferadapter.go @@ -6,8 +6,6 @@ package lfs import ( "bytes" "context" - "errors" - "fmt" "io" "net/http" @@ -15,7 +13,7 @@ import ( "code.gitea.io/gitea/modules/log" ) -// TransferAdapter represents an adapter for downloading/uploading LFS objects +// TransferAdapter represents an adapter for downloading/uploading LFS objects. type TransferAdapter interface { Name() string Download(ctx context.Context, l *Link) (io.ReadCloser, error) @@ -23,41 +21,48 @@ type TransferAdapter interface { Verify(ctx context.Context, l *Link, p Pointer) error } -// BasicTransferAdapter implements the "basic" adapter +// BasicTransferAdapter implements the "basic" adapter. type BasicTransferAdapter struct { client *http.Client } -// Name returns the name of the adapter +// Name returns the name of the adapter. func (a *BasicTransferAdapter) Name() string { return "basic" } -// Download reads the download location and downloads the data +// Download reads the download location and downloads the data. func (a *BasicTransferAdapter) Download(ctx context.Context, l *Link) (io.ReadCloser, error) { - resp, err := a.performRequest(ctx, "GET", l, nil, nil) + req, err := createRequest(ctx, http.MethodGet, l.Href, l.Header, nil) + if err != nil { + return nil, err + } + resp, err := performRequest(ctx, a.client, req) if err != nil { return nil, err } return resp.Body, nil } -// Upload sends the content to the LFS server +// Upload sends the content to the LFS server. func (a *BasicTransferAdapter) Upload(ctx context.Context, l *Link, p Pointer, r io.Reader) error { - _, err := a.performRequest(ctx, "PUT", l, r, func(req *http.Request) { - if len(req.Header.Get("Content-Type")) == 0 { - req.Header.Set("Content-Type", "application/octet-stream") - } - - if req.Header.Get("Transfer-Encoding") == "chunked" { - req.TransferEncoding = []string{"chunked"} - } - - req.ContentLength = p.Size - }) + req, err := createRequest(ctx, http.MethodPut, l.Href, l.Header, r) if err != nil { return err } + if req.Header.Get("Content-Type") == "" { + req.Header.Set("Content-Type", "application/octet-stream") + } + if req.Header.Get("Transfer-Encoding") == "chunked" { + req.TransferEncoding = []string{"chunked"} + } + req.ContentLength = p.Size + + res, err := performRequest(ctx, a.client, req) + if err != nil { + return err + } + defer res.Body.Close() return nil } @@ -69,66 +74,15 @@ func (a *BasicTransferAdapter) Verify(ctx context.Context, l *Link, p Pointer) e return err } - _, err = a.performRequest(ctx, "POST", l, bytes.NewReader(b), func(req *http.Request) { - req.Header.Set("Content-Type", MediaType) - }) + req, err := createRequest(ctx, http.MethodPost, l.Href, l.Header, bytes.NewReader(b)) if err != nil { return err } + req.Header.Set("Content-Type", MediaType) + res, err := performRequest(ctx, a.client, req) + if err != nil { + return err + } + defer res.Body.Close() return nil } - -func (a *BasicTransferAdapter) performRequest(ctx context.Context, method string, l *Link, body io.Reader, callback func(*http.Request)) (*http.Response, error) { - log.Trace("Calling: %s %s", method, l.Href) - - req, err := http.NewRequestWithContext(ctx, method, l.Href, body) - if err != nil { - log.Error("Error creating request: %v", err) - return nil, err - } - for key, value := range l.Header { - req.Header.Set(key, value) - } - req.Header.Set("Accept", MediaType) - - if callback != nil { - callback(req) - } - - res, err := a.client.Do(req) - if err != nil { - select { - case <-ctx.Done(): - return res, ctx.Err() - default: - } - log.Error("Error while processing request: %v", err) - return res, err - } - - if res.StatusCode != http.StatusOK { - return res, handleErrorResponse(res) - } - - return res, nil -} - -func handleErrorResponse(resp *http.Response) error { - defer resp.Body.Close() - - er, err := decodeResponseError(resp.Body) - if err != nil { - return fmt.Errorf("Request failed with status %s", resp.Status) - } - log.Trace("ErrorRespone: %v", er) - return errors.New(er.Message) -} - -func decodeResponseError(r io.Reader) (ErrorResponse, error) { - var er ErrorResponse - err := json.NewDecoder(r).Decode(&er) - if err != nil { - log.Error("Error decoding json: %v", err) - } - return er, err -} diff --git a/modules/util/path.go b/modules/util/path.go index 58258560dd..e8537fb6b9 100644 --- a/modules/util/path.go +++ b/modules/util/path.go @@ -225,6 +225,7 @@ func isOSWindows() bool { var driveLetterRegexp = regexp.MustCompile("/[A-Za-z]:/") // FileURLToPath extracts the path information from a file://... url. +// It returns an error only if the URL is not a file URL. func FileURLToPath(u *url.URL) (string, error) { if u.Scheme != "file" { return "", errors.New("URL scheme is not 'file': " + u.String()) From 323135b97b219d7fb10557fb9d9156c6bef3ae62 Mon Sep 17 00:00:00 2001 From: CaiCandong <50507092+CaiCandong@users.noreply.github.com> Date: Mon, 18 Sep 2023 20:08:09 +0800 Subject: [PATCH 059/289] Fix the incorrect route path in the user edit page. (#27007) Regression of #26713 After #26713 , the base path of user edit has been changed to `/admin/users/{userid}/edit` ## Before https://github.com/go-gitea/gitea/assets/50507092/5f4a3f64-fe2b-4499-b110-e01c9d87ea19 --- templates/admin/user/edit.tmpl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/templates/admin/user/edit.tmpl b/templates/admin/user/edit.tmpl index e99a4532d3..f7b70d8aff 100644 --- a/templates/admin/user/edit.tmpl +++ b/templates/admin/user/edit.tmpl @@ -4,7 +4,7 @@ {{.locale.Tr "admin.users.edit_account"}}
    -
    + {{template "base/disable_form_autofill"}} {{.CsrfTokenHtml}}
    @@ -157,7 +157,7 @@ {{.locale.Tr "settings.avatar"}}
    - + {{.CsrfTokenHtml}} {{if not .DisableGravatar}}
    @@ -186,7 +186,7 @@
    - +
    @@ -197,7 +197,7 @@ {{svg "octicon-trash"}} {{.locale.Tr "settings.delete_account_title"}}
    -
    +

    {{.locale.Tr "settings.delete_account_desc"}}

    {{$.CsrfTokenHtml}} From e644cc9448a9271bba9789507dcef0984ac02d7f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 19 Sep 2023 03:59:19 +0800 Subject: [PATCH 060/289] Fix wrong xorm get usage on migration (#27111) Fix the bug on try.gitea.io ```log 2023/09/18 01:48:41 ...ations/migrations.go:635:Migrate() [I] Migration[276]: Add RemoteAddress to mirrors 2023/09/18 01:48:41 routers/common/db.go:34:InitDBEngine() [E] ORM engine initialization attempt #7/10 failed. Error: migrate: migration[276]: Add RemoteAddress to mirrors failed: exit status 128 - fatal: not a git repository (or any parent up to mount point /) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). - fatal: not a git repository (or any parent up to mount point /) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). ``` Caused by #26952 --------- Co-authored-by: Jason Song --- models/migrations/v1_21/v276.go | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/models/migrations/v1_21/v276.go b/models/migrations/v1_21/v276.go index 8746c8851e..ed1bc3bda5 100644 --- a/models/migrations/v1_21/v276.go +++ b/models/migrations/v1_21/v276.go @@ -41,6 +41,8 @@ func migratePullMirrors(x *xorm.Engine) error { ID int64 `xorm:"pk autoincr"` RepoID int64 `xorm:"INDEX"` RemoteAddress string `xorm:"VARCHAR(2048)"` + RepoOwner string + RepoName string } sess := x.NewSession() @@ -59,7 +61,9 @@ func migratePullMirrors(x *xorm.Engine) error { for { var mirrors []Mirror - if err := sess.Limit(limit, start).Find(&mirrors); err != nil { + if err := sess.Select("mirror.id, mirror.repo_id, mirror.remote_address, repository.owner_name as repo_owner, repository.name as repo_name"). + Join("INNER", "repository", "repository.id = mirror.repo_id"). + Limit(limit, start).Find(&mirrors); err != nil { return err } @@ -69,7 +73,7 @@ func migratePullMirrors(x *xorm.Engine) error { start += len(mirrors) for _, m := range mirrors { - remoteAddress, err := getRemoteAddress(sess, m.RepoID, "origin") + remoteAddress, err := getRemoteAddress(m.RepoOwner, m.RepoName, "origin") if err != nil { return err } @@ -100,6 +104,8 @@ func migratePushMirrors(x *xorm.Engine) error { RepoID int64 `xorm:"INDEX"` RemoteName string RemoteAddress string `xorm:"VARCHAR(2048)"` + RepoOwner string + RepoName string } sess := x.NewSession() @@ -118,7 +124,9 @@ func migratePushMirrors(x *xorm.Engine) error { for { var mirrors []PushMirror - if err := sess.Limit(limit, start).Find(&mirrors); err != nil { + if err := sess.Select("push_mirror.id, push_mirror.repo_id, push_mirror.remote_name, push_mirror.remote_address, repository.owner_name as repo_owner, repository.name as repo_name"). + Join("INNER", "repository", "repository.id = push_mirror.repo_id"). + Limit(limit, start).Find(&mirrors); err != nil { return err } @@ -128,7 +136,7 @@ func migratePushMirrors(x *xorm.Engine) error { start += len(mirrors) for _, m := range mirrors { - remoteAddress, err := getRemoteAddress(sess, m.RepoID, m.RemoteName) + remoteAddress, err := getRemoteAddress(m.RepoOwner, m.RepoName, m.RemoteName) if err != nil { return err } @@ -153,25 +161,12 @@ func migratePushMirrors(x *xorm.Engine) error { 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) - } - +func getRemoteAddress(ownerName, repoName, remoteName string) (string, error) { 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 + return "", fmt.Errorf("get remote %s's address of %s/%s failed: %v", remoteName, ownerName, repoName, err) } u, err := giturl.Parse(remoteURL) From 8099238618f6573f1eb5cfeeb0902b641e7121ab Mon Sep 17 00:00:00 2001 From: silverwind Date: Tue, 19 Sep 2023 00:05:31 +0200 Subject: [PATCH 061/289] Change green buttons to primary color (#27099) I think it's better if the primary actions have primary color instead of green which fits better into the overall single-color UI design. This PR currently replaces every green button with primary: Screenshot 2023-09-16 at 14 07 59 Screenshot 2023-09-16 at 14 07 51 Modal actions now use uncolored/primary instead of previous green/red colors. I also removed the box-shadow on all basic buttons: Screenshot 2023-09-16 at 14 16 39 Screenshot 2023-09-16 at 14 17 42 The change currently includes the "Merge PR" button, for which we might want to make an exception to match the icon color there: Screenshot 2023-09-16 at 14 33 53 --- templates/admin/auth/edit.tmpl | 2 +- templates/admin/auth/new.tmpl | 2 +- templates/admin/config.tmpl | 2 +- templates/admin/cron.tmpl | 2 +- templates/admin/dashboard.tmpl | 24 +++++++++---------- templates/admin/repo/unadopted.tmpl | 2 +- templates/admin/user/edit.tmpl | 4 ++-- templates/admin/user/new.tmpl | 2 +- templates/base/modal_actions_confirm.tmpl | 6 ++--- templates/devtest/flex-list.tmpl | 4 ++-- templates/devtest/gitea-ui.tmpl | 4 ++-- templates/org/create.tmpl | 2 +- templates/org/home.tmpl | 4 ++-- templates/org/settings/labels.tmpl | 2 +- templates/org/settings/options.tmpl | 4 ++-- templates/org/team/invite.tmpl | 2 +- templates/org/team/members.tmpl | 2 +- templates/org/team/new.tmpl | 4 ++-- templates/org/team/repositories.tmpl | 4 ++-- templates/org/team/teams.tmpl | 2 +- templates/package/settings.tmpl | 2 +- templates/package/shared/cargo.tmpl | 4 ++-- .../package/shared/cleanup_rules/edit.tmpl | 4 ++-- templates/projects/list.tmpl | 2 +- templates/repo/commit_page.tmpl | 6 ++--- templates/repo/create.tmpl | 2 +- templates/repo/diff/box.tmpl | 4 ++-- templates/repo/diff/comment_form.tmpl | 6 ++--- templates/repo/diff/compare.tmpl | 6 ++--- templates/repo/diff/conversation.tmpl | 2 +- templates/repo/diff/new_review.tmpl | 6 ++--- templates/repo/editor/commit_form.tmpl | 2 +- templates/repo/editor/edit.tmpl | 4 ++-- templates/repo/editor/patch.tmpl | 4 ++-- templates/repo/header.tmpl | 2 +- templates/repo/issue/choose.tmpl | 6 ++--- templates/repo/issue/labels.tmpl | 2 +- templates/repo/issue/labels/label_new.tmpl | 4 ++-- templates/repo/issue/list.tmpl | 8 +++---- templates/repo/issue/milestone_issues.tmpl | 2 +- templates/repo/issue/milestone_new.tmpl | 6 ++--- templates/repo/issue/milestones.tmpl | 2 +- templates/repo/issue/new_form.tmpl | 2 +- templates/repo/issue/view_content.tmpl | 4 ++-- .../repo/issue/view_content/comments.tmpl | 2 +- .../view_content/reference_issue_dialog.tmpl | 2 +- .../repo/issue/view_content/sidebar.tmpl | 4 ++-- templates/repo/issue/view_title.tmpl | 2 +- templates/repo/migrate/codebase.tmpl | 2 +- templates/repo/migrate/git.tmpl | 2 +- templates/repo/migrate/gitbucket.tmpl | 2 +- templates/repo/migrate/gitea.tmpl | 2 +- templates/repo/migrate/github.tmpl | 2 +- templates/repo/migrate/gitlab.tmpl | 2 +- templates/repo/migrate/gogs.tmpl | 2 +- templates/repo/migrate/migrating.tmpl | 2 +- templates/repo/migrate/onedev.tmpl | 2 +- templates/repo/projects/view.tmpl | 2 +- templates/repo/pulls/fork.tmpl | 2 +- templates/repo/release_tag_header.tmpl | 2 +- templates/repo/settings/branches.tmpl | 2 +- templates/repo/settings/collaboration.tmpl | 4 ++-- templates/repo/settings/deploy_keys.tmpl | 2 +- templates/repo/settings/githook_edit.tmpl | 2 +- templates/repo/settings/lfs_pointers.tmpl | 2 +- templates/repo/settings/options.tmpl | 18 +++++++------- templates/repo/settings/protected_branch.tmpl | 2 +- templates/repo/settings/tags.tmpl | 4 ++-- templates/repo/settings/webhook/settings.tmpl | 4 ++-- templates/repo/wiki/new.tmpl | 4 ++-- templates/repo/wiki/pages.tmpl | 2 +- templates/repo/wiki/start.tmpl | 2 +- templates/repo/wiki/view.tmpl | 4 ++-- templates/shared/actions/runner_edit.tmpl | 2 +- templates/shared/user/profile_big_avatar.tmpl | 2 +- templates/user/auth/activate.tmpl | 2 +- templates/user/auth/change_passwd_inner.tmpl | 2 +- templates/user/auth/finalize_openid.tmpl | 2 +- templates/user/auth/signin_inner.tmpl | 2 +- templates/user/auth/signin_openid.tmpl | 2 +- templates/user/auth/signup_inner.tmpl | 2 +- .../user/auth/signup_openid_connect.tmpl | 2 +- .../user/auth/signup_openid_register.tmpl | 2 +- templates/user/auth/twofa.tmpl | 2 +- templates/user/auth/twofa_scratch.tmpl | 2 +- templates/user/dashboard/issues.tmpl | 4 ++-- templates/user/settings/account.tmpl | 6 ++--- templates/user/settings/appearance.tmpl | 6 ++--- templates/user/settings/applications.tmpl | 2 +- .../applications_oauth2_edit_form.tmpl | 2 +- .../settings/applications_oauth2_list.tmpl | 2 +- templates/user/settings/keys_gpg.tmpl | 4 ++-- templates/user/settings/keys_principal.tmpl | 2 +- templates/user/settings/keys_ssh.tmpl | 4 ++-- templates/user/settings/packages.tmpl | 2 +- templates/user/settings/profile.tmpl | 4 ++-- templates/user/settings/repos.tmpl | 2 +- templates/user/settings/security/openid.tmpl | 2 +- templates/user/settings/security/twofa.tmpl | 2 +- .../user/settings/security/twofa_enroll.tmpl | 2 +- .../user/settings/security/webauthn.tmpl | 2 +- tests/e2e/example.test.e2e.js | 4 ++-- tests/e2e/utils_e2e.js | 2 +- tests/integration/pull_merge_test.go | 2 +- web_src/css/modules/button.css | 7 ++++++ .../js/components/PullRequestMergeForm.vue | 6 ++--- web_src/js/features/common-global.js | 2 +- web_src/js/features/comp/ConfirmModal.js | 6 ++--- 108 files changed, 183 insertions(+), 176 deletions(-) diff --git a/templates/admin/auth/edit.tmpl b/templates/admin/auth/edit.tmpl index 6dfa86d9dd..814bddd8a4 100644 --- a/templates/admin/auth/edit.tmpl +++ b/templates/admin/auth/edit.tmpl @@ -428,7 +428,7 @@
    - +
    diff --git a/templates/admin/auth/new.tmpl b/templates/admin/auth/new.tmpl index 37d1635c11..31efa62e71 100644 --- a/templates/admin/auth/new.tmpl +++ b/templates/admin/auth/new.tmpl @@ -73,7 +73,7 @@
    - +
    diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index 36d9bcb8a5..c29d1dbf30 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -238,7 +238,7 @@
    - + {{end}} diff --git a/templates/admin/cron.tmpl b/templates/admin/cron.tmpl index c154619435..354cd18ed5 100644 --- a/templates/admin/cron.tmpl +++ b/templates/admin/cron.tmpl @@ -20,7 +20,7 @@
    {{range .Entries}} - + diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 8312fba039..69c0376d6e 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -15,55 +15,55 @@ - + - + - + - + {{if and (not .SSH.Disabled) (not .SSH.StartBuiltinServer)}} - + - + {{end}} - + - + - + - + - + - +
    {{$.locale.Tr (printf "admin.dashboard.%s" .Name)}} {{.Spec}} {{DateTime "full" .Next}}
    {{.locale.Tr "admin.dashboard.delete_inactive_accounts"}}
    {{.locale.Tr "admin.dashboard.delete_repo_archives"}}
    {{.locale.Tr "admin.dashboard.delete_missing_repos"}}
    {{.locale.Tr "admin.dashboard.git_gc_repos"}}
    {{.locale.Tr "admin.dashboard.resync_all_sshkeys"}}
    {{.locale.Tr "admin.dashboard.resync_all_sshkeys.desc"}}
    {{.locale.Tr "admin.dashboard.resync_all_sshprincipals"}}
    {{.locale.Tr "admin.dashboard.resync_all_sshprincipals.desc"}}
    {{.locale.Tr "admin.dashboard.resync_all_hooks"}}
    {{.locale.Tr "admin.dashboard.reinit_missing_repos"}}
    {{.locale.Tr "admin.dashboard.sync_external_users"}}
    {{.locale.Tr "admin.dashboard.repo_health_check"}}
    {{.locale.Tr "admin.dashboard.delete_generated_repository_avatars"}}
    {{.locale.Tr "admin.dashboard.sync_repo_branches"}}
    diff --git a/templates/admin/repo/unadopted.tmpl b/templates/admin/repo/unadopted.tmpl index 7b86b0defd..a903425b21 100644 --- a/templates/admin/repo/unadopted.tmpl +++ b/templates/admin/repo/unadopted.tmpl @@ -23,7 +23,7 @@
    {{svg "octicon-file-directory-fill"}} {{$dir}}
    - + diff --git a/templates/base/modal_actions_confirm.tmpl b/templates/base/modal_actions_confirm.tmpl index 6cf3ecbe3e..5b5f211fb1 100644 --- a/templates/base/modal_actions_confirm.tmpl +++ b/templates/base/modal_actions_confirm.tmpl @@ -4,7 +4,7 @@ Template Attributes: Two buttons (negative, positive): * ModalButtonTypes: "yes" (default) or "confirm" -* ModalButtonColors: "green" (default) / "blue" / "yellow" +* ModalButtonColors: "primary" (default) / "blue" / "yellow" * ModalButtonCancelText * ModalButtonOkText @@ -26,13 +26,13 @@ The ".ok.button" and ".cancel.button" selectors are also used by Fomantic Modal {{if .ModalButtonCancelText}}{{$textNegitive = .ModalButtonCancelText}}{{end}} {{if .ModalButtonOkText}}{{$textPositive = .ModalButtonOkText}}{{end}} - {{$stylePositive := "green"}} + {{$stylePositive := "primary"}} {{if eq .ModalButtonColors "blue"}} {{$stylePositive = "blue"}} {{else if eq .ModalButtonColors "yellow"}} {{$stylePositive = "yellow"}} {{end}} - + {{end}}
    diff --git a/templates/devtest/flex-list.tmpl b/templates/devtest/flex-list.tmpl index 80cd22440d..bbcbc4e816 100644 --- a/templates/devtest/flex-list.tmpl +++ b/templates/devtest/flex-list.tmpl @@ -27,10 +27,10 @@ - -
    diff --git a/templates/devtest/gitea-ui.tmpl b/templates/devtest/gitea-ui.tmpl index b3b68c4dba..258b72f8cd 100644 --- a/templates/devtest/gitea-ui.tmpl +++ b/templates/devtest/gitea-ui.tmpl @@ -31,8 +31,8 @@

    Recommended colors:

    - - + + diff --git a/templates/org/create.tmpl b/templates/org/create.tmpl index 966150aa93..cd2ffbb68e 100644 --- a/templates/org/create.tmpl +++ b/templates/org/create.tmpl @@ -45,7 +45,7 @@
    -
    diff --git a/templates/org/home.tmpl b/templates/org/home.tmpl index 72be948650..18d5282a31 100644 --- a/templates/org/home.tmpl +++ b/templates/org/home.tmpl @@ -47,9 +47,9 @@
    {{if .CanCreateOrgRepo}}
    diff --git a/templates/org/settings/labels.tmpl b/templates/org/settings/labels.tmpl index 81dde17455..b38481fea3 100644 --- a/templates/org/settings/labels.tmpl +++ b/templates/org/settings/labels.tmpl @@ -4,7 +4,7 @@
    {{$.locale.Tr "org.settings.labels_desc" | Str2html}}
    - +
    {{template "repo/issue/labels/label_new" .}} diff --git a/templates/org/settings/options.tmpl b/templates/org/settings/options.tmpl index ecc269481d..0b138094c3 100644 --- a/templates/org/settings/options.tmpl +++ b/templates/org/settings/options.tmpl @@ -79,7 +79,7 @@ {{end}}
    - +
    @@ -93,7 +93,7 @@
    - +
    diff --git a/templates/org/team/invite.tmpl b/templates/org/team/invite.tmpl index 60332a5f40..1b04c0cc2a 100644 --- a/templates/org/team/invite.tmpl +++ b/templates/org/team/invite.tmpl @@ -14,7 +14,7 @@
    {{.CsrfTokenHtml}} - +
    diff --git a/templates/org/team/members.tmpl b/templates/org/team/members.tmpl index cac0c1ce94..7c2fab4b80 100644 --- a/templates/org/team/members.tmpl +++ b/templates/org/team/members.tmpl @@ -17,7 +17,7 @@

    - + {{end}} diff --git a/templates/org/team/new.tmpl b/templates/org/team/new.tmpl index 3702198ae0..1d35564007 100644 --- a/templates/org/team/new.tmpl +++ b/templates/org/team/new.tmpl @@ -133,9 +133,9 @@
    {{if .PageIsOrgTeamsNew}} - + {{else}} - + {{if not (eq .Team.LowerName "owners")}} {{end}} diff --git a/templates/org/team/repositories.tmpl b/templates/org/team/repositories.tmpl index 44fb1ee083..032a0f496a 100644 --- a/templates/org/team/repositories.tmpl +++ b/templates/org/team/repositories.tmpl @@ -17,10 +17,10 @@
    - +
    - +
    diff --git a/templates/org/team/teams.tmpl b/templates/org/team/teams.tmpl index a96dd7d6be..0d7cc06ff9 100644 --- a/templates/org/team/teams.tmpl +++ b/templates/org/team/teams.tmpl @@ -5,7 +5,7 @@ {{template "base/alert" .}} {{if .IsOrganizationOwner}}
    {{end}} diff --git a/templates/package/settings.tmpl b/templates/package/settings.tmpl index af543328f8..d6c431de03 100644 --- a/templates/package/settings.tmpl +++ b/templates/package/settings.tmpl @@ -31,7 +31,7 @@
    - +
    diff --git a/templates/package/shared/cargo.tmpl b/templates/package/shared/cargo.tmpl index 8831cd8988..9761cb2133 100644 --- a/templates/package/shared/cargo.tmpl +++ b/templates/package/shared/cargo.tmpl @@ -8,14 +8,14 @@
    {{.CsrfTokenHtml}} - +
    {{.CsrfTokenHtml}} - +
    diff --git a/templates/package/shared/cleanup_rules/edit.tmpl b/templates/package/shared/cleanup_rules/edit.tmpl index 295ac1a6a4..1bfa6260a1 100644 --- a/templates/package/shared/cleanup_rules/edit.tmpl +++ b/templates/package/shared/cleanup_rules/edit.tmpl @@ -62,11 +62,11 @@
    {{if .IsEditRule}} - + {{.locale.Tr "packages.owner.settings.cleanuprules.preview"}} {{else}} - + {{end}}
    diff --git a/templates/projects/list.tmpl b/templates/projects/list.tmpl index 0cb619c066..1f3668be7a 100644 --- a/templates/projects/list.tmpl +++ b/templates/projects/list.tmpl @@ -11,7 +11,7 @@ {{end}} diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl index 8e56b43553..1663e76a40 100644 --- a/templates/repo/commit_page.tmpl +++ b/templates/repo/commit_page.tmpl @@ -75,7 +75,7 @@
    - + @@ -98,7 +98,7 @@
    - +
    @@ -123,7 +123,7 @@
    - +
    diff --git a/templates/repo/create.tmpl b/templates/repo/create.tmpl index 0fcdf13f1e..4125cb9c8f 100644 --- a/templates/repo/create.tmpl +++ b/templates/repo/create.tmpl @@ -220,7 +220,7 @@
    -
    diff --git a/templates/repo/diff/box.tmpl b/templates/repo/diff/box.tmpl index 0b5bf86371..2e1461226a 100644 --- a/templates/repo/diff/box.tmpl +++ b/templates/repo/diff/box.tmpl @@ -232,8 +232,8 @@ "DropzoneParentContainer" ".ui.form" )}}
    - - + +
    diff --git a/templates/repo/diff/comment_form.tmpl b/templates/repo/diff/comment_form.tmpl index 5aad8d9590..dff030a0b4 100644 --- a/templates/repo/diff/comment_form.tmpl +++ b/templates/repo/diff/comment_form.tmpl @@ -24,14 +24,14 @@ {{svg "octicon-markup"}} {{$.root.locale.Tr "repo.diff.comment.markdown_info"}}
    {{if $.reply}} - + {{else}} {{if $.root.CurrentReview}} - + {{else}} - + {{end}} {{end}} diff --git a/templates/repo/diff/compare.tmpl b/templates/repo/diff/compare.tmpl index e4ae7d4dc8..4d57fd6148 100644 --- a/templates/repo/diff/compare.tmpl +++ b/templates/repo/diff/compare.tmpl @@ -180,7 +180,7 @@ {{if and $.IsSigned $.AllowEmptyPr (not .Repository.IsArchived)}}
    {{.locale.Tr "repo.pulls.nothing_to_compare_and_allow_empty_pr"}}
    - +
    {{else}} {{if and $.IsSigned (not .Repository.IsArchived)}}
    - +
    {{else if .Repository.IsArchived}}
    diff --git a/templates/repo/diff/conversation.tmpl b/templates/repo/diff/conversation.tmpl index 639dd9cd04..c6ada10caf 100644 --- a/templates/repo/diff/conversation.tmpl +++ b/templates/repo/diff/conversation.tmpl @@ -56,7 +56,7 @@ {{end}} {{if and $.SignedUserID (not $.Repository.IsArchived)}} - {{end}} diff --git a/templates/repo/diff/new_review.tmpl b/templates/repo/diff/new_review.tmpl index 6a3fa7a823..908f488975 100644 --- a/templates/repo/diff/new_review.tmpl +++ b/templates/repo/diff/new_review.tmpl @@ -1,5 +1,5 @@
    - + {{else}} - + {{end}} {{if $showSelfTooltip}} diff --git a/templates/repo/editor/commit_form.tmpl b/templates/repo/editor/commit_form.tmpl index b07059777f..dd6537e1a0 100644 --- a/templates/repo/editor/commit_form.tmpl +++ b/templates/repo/editor/commit_form.tmpl @@ -67,7 +67,7 @@ {{end}}
    - {{.locale.Tr "repo.editor.cancel"}} diff --git a/templates/repo/editor/edit.tmpl b/templates/repo/editor/edit.tmpl index 3b5a63f3aa..2b303be97c 100644 --- a/templates/repo/editor/edit.tmpl +++ b/templates/repo/editor/edit.tmpl @@ -61,11 +61,11 @@

    {{.locale.Tr "repo.editor.commit_empty_file_text"}}

    - - diff --git a/templates/repo/editor/patch.tmpl b/templates/repo/editor/patch.tmpl index 1f948fbb19..57126c09ab 100644 --- a/templates/repo/editor/patch.tmpl +++ b/templates/repo/editor/patch.tmpl @@ -43,11 +43,11 @@

    {{.locale.Tr "repo.editor.commit_empty_file_text"}}

    - - diff --git a/templates/repo/header.tmpl b/templates/repo/header.tmpl index 935060816c..d0f24949c9 100644 --- a/templates/repo/header.tmpl +++ b/templates/repo/header.tmpl @@ -48,7 +48,7 @@
    {{$.CsrfTokenHtml}}
    -
    diff --git a/templates/repo/issue/choose.tmpl b/templates/repo/issue/choose.tmpl index 1bbfbbb2d1..9cc666a4bd 100644 --- a/templates/repo/issue/choose.tmpl +++ b/templates/repo/issue/choose.tmpl @@ -15,7 +15,7 @@
    {{.About | RenderEmojiPlain}}
    @@ -28,7 +28,7 @@
    {{.About | RenderEmojiPlain}} @@ -41,7 +41,7 @@
    {{.locale.Tr "repo.issues.choose.blank_about"}} diff --git a/templates/repo/issue/labels.tmpl b/templates/repo/issue/labels.tmpl index a34ce1bfbb..7de1b0f0ba 100644 --- a/templates/repo/issue/labels.tmpl +++ b/templates/repo/issue/labels.tmpl @@ -5,7 +5,7 @@ {{if and (or .CanWriteIssues .CanWritePulls) (not .Repository.IsArchived)}} diff --git a/templates/repo/issue/labels/label_new.tmpl b/templates/repo/issue/labels/label_new.tmpl index 1d3069f1bb..8edd6d4e8a 100644 --- a/templates/repo/issue/labels/label_new.tmpl +++ b/templates/repo/issue/labels/label_new.tmpl @@ -36,11 +36,11 @@
    - - diff --git a/templates/repo/issue/list.tmpl b/templates/repo/issue/list.tmpl index 789ba4020f..8087aaa68a 100644 --- a/templates/repo/issue/list.tmpl +++ b/templates/repo/issue/list.tmpl @@ -18,13 +18,13 @@ {{template "repo/issue/search" .}} {{if not .Repository.IsArchived}} {{if .PageIsIssueList}} - {{.locale.Tr "repo.issues.new"}} + {{.locale.Tr "repo.issues.new"}} {{else}} - {{.locale.Tr "repo.pulls.new"}} + {{.locale.Tr "repo.pulls.new"}} {{end}} {{else}} {{if not .PageIsIssueList}} - {{$.locale.Tr "action.compare_commits_general"}} + {{$.locale.Tr "action.compare_commits_general"}} {{end}} {{end}}
    @@ -40,7 +40,7 @@ {{if not .Repository.IsArchived}} {{if .IsShowClosed}} - + {{else}} {{end}} diff --git a/templates/repo/issue/milestone_issues.tmpl b/templates/repo/issue/milestone_issues.tmpl index dab6ef3de6..aa3d9b94cd 100644 --- a/templates/repo/issue/milestone_issues.tmpl +++ b/templates/repo/issue/milestone_issues.tmpl @@ -8,7 +8,7 @@ @@ -44,11 +44,11 @@ {{.locale.Tr "repo.milestones.cancel"}} - {{else}} - {{end}} diff --git a/templates/repo/issue/milestones.tmpl b/templates/repo/issue/milestones.tmpl index 3f481c95e4..cdc372cc55 100644 --- a/templates/repo/issue/milestones.tmpl +++ b/templates/repo/issue/milestones.tmpl @@ -5,7 +5,7 @@ {{template "base/alert" .}} diff --git a/templates/repo/issue/new_form.tmpl b/templates/repo/issue/new_form.tmpl index fc1a3d087f..9d0b666375 100644 --- a/templates/repo/issue/new_form.tmpl +++ b/templates/repo/issue/new_form.tmpl @@ -35,7 +35,7 @@ {{template "repo/issue/comment_tab" .}} {{end}}
    - {{else}} @@ -105,7 +105,7 @@ {{end}} {{end}} -
    diff --git a/templates/repo/issue/view_content/comments.tmpl b/templates/repo/issue/view_content/comments.tmpl index d43979ff59..cb897a692b 100644 --- a/templates/repo/issue/view_content/comments.tmpl +++ b/templates/repo/issue/view_content/comments.tmpl @@ -585,7 +585,7 @@ {{end}} {{if and $.SignedUserID (not $.Repository.IsArchived)}} - {{end}} diff --git a/templates/repo/issue/view_content/reference_issue_dialog.tmpl b/templates/repo/issue/view_content/reference_issue_dialog.tmpl index 861e7b97a4..3df85e7b81 100644 --- a/templates/repo/issue/view_content/reference_issue_dialog.tmpl +++ b/templates/repo/issue/view_content/reference_issue_dialog.tmpl @@ -22,7 +22,7 @@
    - +
    diff --git a/templates/repo/issue/view_content/sidebar.tmpl b/templates/repo/issue/view_content/sidebar.tmpl index 3d5be860bd..6405a6e180 100644 --- a/templates/repo/issue/view_content/sidebar.tmpl +++ b/templates/repo/issue/view_content/sidebar.tmpl @@ -327,8 +327,8 @@
    - - + +
    {{end}} {{if not .Issue.IsPull}} - {{.locale.Tr "repo.issues.new"}} + {{.locale.Tr "repo.issues.new"}} {{end}} {{if and (or .HasIssuesOrPullsWritePermission .IsIssuePoster) (not .Repository.IsArchived)}} diff --git a/templates/repo/migrate/codebase.tmpl b/templates/repo/migrate/codebase.tmpl index db607eebb4..394e7c2ecf 100644 --- a/templates/repo/migrate/codebase.tmpl +++ b/templates/repo/migrate/codebase.tmpl @@ -104,7 +104,7 @@
    -
    diff --git a/templates/repo/migrate/git.tmpl b/templates/repo/migrate/git.tmpl index 42ae642d26..1e449ae30e 100644 --- a/templates/repo/migrate/git.tmpl +++ b/templates/repo/migrate/git.tmpl @@ -78,7 +78,7 @@
    -
    diff --git a/templates/repo/migrate/gitbucket.tmpl b/templates/repo/migrate/gitbucket.tmpl index 372df0c2db..aa269e561c 100644 --- a/templates/repo/migrate/gitbucket.tmpl +++ b/templates/repo/migrate/gitbucket.tmpl @@ -120,7 +120,7 @@
    -
    diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl index 8022f63dc5..e4d8c62734 100644 --- a/templates/repo/migrate/gitea.tmpl +++ b/templates/repo/migrate/gitea.tmpl @@ -116,7 +116,7 @@
    -
    diff --git a/templates/repo/migrate/github.tmpl b/templates/repo/migrate/github.tmpl index 0ccad3a3ea..d3f0e0b8bd 100644 --- a/templates/repo/migrate/github.tmpl +++ b/templates/repo/migrate/github.tmpl @@ -118,7 +118,7 @@
    -
    diff --git a/templates/repo/migrate/gitlab.tmpl b/templates/repo/migrate/gitlab.tmpl index af20fa38e2..e055cce19e 100644 --- a/templates/repo/migrate/gitlab.tmpl +++ b/templates/repo/migrate/gitlab.tmpl @@ -115,7 +115,7 @@
    -
    diff --git a/templates/repo/migrate/gogs.tmpl b/templates/repo/migrate/gogs.tmpl index aeead61e41..2d66800608 100644 --- a/templates/repo/migrate/gogs.tmpl +++ b/templates/repo/migrate/gogs.tmpl @@ -118,7 +118,7 @@
    -
    diff --git a/templates/repo/migrate/migrating.tmpl b/templates/repo/migrate/migrating.tmpl index d1bdc5a90f..6effa05f97 100644 --- a/templates/repo/migrate/migrating.tmpl +++ b/templates/repo/migrate/migrating.tmpl @@ -38,7 +38,7 @@ {{if .Failed}} {{else}} - + {{end}} diff --git a/templates/repo/migrate/onedev.tmpl b/templates/repo/migrate/onedev.tmpl index f5ba11ab06..818b23fddc 100644 --- a/templates/repo/migrate/onedev.tmpl +++ b/templates/repo/migrate/onedev.tmpl @@ -104,7 +104,7 @@
    -
    diff --git a/templates/repo/projects/view.tmpl b/templates/repo/projects/view.tmpl index ac3d2cd77c..3f2dd9a548 100644 --- a/templates/repo/projects/view.tmpl +++ b/templates/repo/projects/view.tmpl @@ -4,7 +4,7 @@
    {{template "projects/view" .}}
    diff --git a/templates/repo/pulls/fork.tmpl b/templates/repo/pulls/fork.tmpl index 15635074ac..66b1c3a276 100644 --- a/templates/repo/pulls/fork.tmpl +++ b/templates/repo/pulls/fork.tmpl @@ -58,7 +58,7 @@
    -
    diff --git a/templates/repo/release_tag_header.tmpl b/templates/repo/release_tag_header.tmpl index ad42b9949f..89358e9dd4 100644 --- a/templates/repo/release_tag_header.tmpl +++ b/templates/repo/release_tag_header.tmpl @@ -15,7 +15,7 @@ {{end}} {{if and (not .PageIsTagList) .CanCreateRelease}} - + {{.locale.Tr "repo.release.new_release"}} {{end}} diff --git a/templates/repo/settings/branches.tmpl b/templates/repo/settings/branches.tmpl index ef227ff4aa..43203a7ad3 100644 --- a/templates/repo/settings/branches.tmpl +++ b/templates/repo/settings/branches.tmpl @@ -26,7 +26,7 @@ {{end}} - + {{end}} diff --git a/templates/repo/settings/collaboration.tmpl b/templates/repo/settings/collaboration.tmpl index c40265c6a6..290a1ae093 100644 --- a/templates/repo/settings/collaboration.tmpl +++ b/templates/repo/settings/collaboration.tmpl @@ -44,7 +44,7 @@ - + @@ -92,7 +92,7 @@ - + {{else}}
    diff --git a/templates/repo/settings/deploy_keys.tmpl b/templates/repo/settings/deploy_keys.tmpl index b776848a56..a7b7dd6511 100644 --- a/templates/repo/settings/deploy_keys.tmpl +++ b/templates/repo/settings/deploy_keys.tmpl @@ -34,7 +34,7 @@ {{$.locale.Tr "repo.settings.is_writable_info" | Str2html}}
    - + {{end}} diff --git a/templates/repo/settings/lfs_pointers.tmpl b/templates/repo/settings/lfs_pointers.tmpl index b6b58a3772..db3fdd2f85 100644 --- a/templates/repo/settings/lfs_pointers.tmpl +++ b/templates/repo/settings/lfs_pointers.tmpl @@ -11,7 +11,7 @@ {{end}} {{end}} - + {{end}} diff --git a/templates/repo/settings/options.tmpl b/templates/repo/settings/options.tmpl index 78700e05b7..28841de4cd 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -45,7 +45,7 @@
    - +
    @@ -57,7 +57,7 @@
    - +
    @@ -189,7 +189,7 @@ {{end}}
    - +
    ID{{.locale.Tr "admin.auths.name"}}{{.locale.Tr "admin.auths.type"}}{{.locale.Tr "admin.auths.enabled"}}{{.locale.Tr "admin.auths.updated"}}{{.locale.Tr "admin.users.created"}}{{.locale.Tr "admin.users.edit"}}{{ctx.Locale.Tr "admin.auths.name"}}{{ctx.Locale.Tr "admin.auths.type"}}{{ctx.Locale.Tr "admin.auths.enabled"}}{{ctx.Locale.Tr "admin.auths.updated"}}{{ctx.Locale.Tr "admin.users.created"}}{{ctx.Locale.Tr "admin.users.edit"}}
    {{.locale.Tr "admin.monitor.name"}}{{.locale.Tr "admin.monitor.schedule"}}{{.locale.Tr "admin.monitor.next"}}{{.locale.Tr "admin.monitor.previous"}}{{.locale.Tr "admin.monitor.execute_times"}}{{.locale.Tr "admin.monitor.last_execution_result"}}{{ctx.Locale.Tr "admin.monitor.name"}}{{ctx.Locale.Tr "admin.monitor.schedule"}}{{ctx.Locale.Tr "admin.monitor.next"}}{{ctx.Locale.Tr "admin.monitor.previous"}}{{ctx.Locale.Tr "admin.monitor.execute_times"}}{{ctx.Locale.Tr "admin.monitor.last_execution_result"}}
    {{$.locale.Tr (printf "admin.dashboard.%s" .Name)}}{{ctx.Locale.Tr (printf "admin.dashboard.%s" .Name)}} {{.Spec}} {{DateTime "full" .Next}} {{if gt .Prev.Year 1}}{{DateTime "full" .Prev}}{{else}}-{{end}}
    - - + + - - + + - - + + - - + + {{if and (not .SSH.Disabled) (not .SSH.StartBuiltinServer)}} - - + + - - + + {{end}} - - + + - - + + - - + + - - + + - - + + - - + +
    {{.locale.Tr "admin.dashboard.delete_inactive_accounts"}}{{ctx.Locale.Tr "admin.dashboard.delete_inactive_accounts"}}
    {{.locale.Tr "admin.dashboard.delete_repo_archives"}}{{ctx.Locale.Tr "admin.dashboard.delete_repo_archives"}}
    {{.locale.Tr "admin.dashboard.delete_missing_repos"}}{{ctx.Locale.Tr "admin.dashboard.delete_missing_repos"}}
    {{.locale.Tr "admin.dashboard.git_gc_repos"}}{{ctx.Locale.Tr "admin.dashboard.git_gc_repos"}}
    {{.locale.Tr "admin.dashboard.resync_all_sshkeys"}}
    - {{.locale.Tr "admin.dashboard.resync_all_sshkeys.desc"}}
    {{ctx.Locale.Tr "admin.dashboard.resync_all_sshkeys"}}
    + {{ctx.Locale.Tr "admin.dashboard.resync_all_sshkeys.desc"}}
    {{.locale.Tr "admin.dashboard.resync_all_sshprincipals"}}
    - {{.locale.Tr "admin.dashboard.resync_all_sshprincipals.desc"}}
    {{ctx.Locale.Tr "admin.dashboard.resync_all_sshprincipals"}}
    + {{ctx.Locale.Tr "admin.dashboard.resync_all_sshprincipals.desc"}}
    {{.locale.Tr "admin.dashboard.resync_all_hooks"}}{{ctx.Locale.Tr "admin.dashboard.resync_all_hooks"}}
    {{.locale.Tr "admin.dashboard.reinit_missing_repos"}}{{ctx.Locale.Tr "admin.dashboard.reinit_missing_repos"}}
    {{.locale.Tr "admin.dashboard.sync_external_users"}}{{ctx.Locale.Tr "admin.dashboard.sync_external_users"}}
    {{.locale.Tr "admin.dashboard.repo_health_check"}}{{ctx.Locale.Tr "admin.dashboard.repo_health_check"}}
    {{.locale.Tr "admin.dashboard.delete_generated_repository_avatars"}}{{ctx.Locale.Tr "admin.dashboard.delete_generated_repository_avatars"}}
    {{.locale.Tr "admin.dashboard.sync_repo_branches"}}{{ctx.Locale.Tr "admin.dashboard.sync_repo_branches"}}
    @@ -71,69 +71,69 @@

    - {{.locale.Tr "admin.dashboard.system_status"}} + {{ctx.Locale.Tr "admin.dashboard.system_status"}}

    -
    {{.locale.Tr "admin.dashboard.server_uptime"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.server_uptime"}}
    {{.SysStatus.StartTime}}
    -
    {{.locale.Tr "admin.dashboard.current_goroutine"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.current_goroutine"}}
    {{.SysStatus.NumGoroutine}}
    -
    {{.locale.Tr "admin.dashboard.current_memory_usage"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.current_memory_usage"}}
    {{.SysStatus.MemAllocated}}
    -
    {{.locale.Tr "admin.dashboard.total_memory_allocated"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.total_memory_allocated"}}
    {{.SysStatus.MemTotal}}
    -
    {{.locale.Tr "admin.dashboard.memory_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.memory_obtained"}}
    {{.SysStatus.MemSys}}
    -
    {{.locale.Tr "admin.dashboard.pointer_lookup_times"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.pointer_lookup_times"}}
    {{.SysStatus.Lookups}}
    -
    {{.locale.Tr "admin.dashboard.memory_allocate_times"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.memory_allocate_times"}}
    {{.SysStatus.MemMallocs}}
    -
    {{.locale.Tr "admin.dashboard.memory_free_times"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.memory_free_times"}}
    {{.SysStatus.MemFrees}}
    -
    {{.locale.Tr "admin.dashboard.current_heap_usage"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.current_heap_usage"}}
    {{.SysStatus.HeapAlloc}}
    -
    {{.locale.Tr "admin.dashboard.heap_memory_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.heap_memory_obtained"}}
    {{.SysStatus.HeapSys}}
    -
    {{.locale.Tr "admin.dashboard.heap_memory_idle"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.heap_memory_idle"}}
    {{.SysStatus.HeapIdle}}
    -
    {{.locale.Tr "admin.dashboard.heap_memory_in_use"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.heap_memory_in_use"}}
    {{.SysStatus.HeapInuse}}
    -
    {{.locale.Tr "admin.dashboard.heap_memory_released"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.heap_memory_released"}}
    {{.SysStatus.HeapReleased}}
    -
    {{.locale.Tr "admin.dashboard.heap_objects"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.heap_objects"}}
    {{.SysStatus.HeapObjects}}
    -
    {{.locale.Tr "admin.dashboard.bootstrap_stack_usage"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.bootstrap_stack_usage"}}
    {{.SysStatus.StackInuse}}
    -
    {{.locale.Tr "admin.dashboard.stack_memory_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.stack_memory_obtained"}}
    {{.SysStatus.StackSys}}
    -
    {{.locale.Tr "admin.dashboard.mspan_structures_usage"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.mspan_structures_usage"}}
    {{.SysStatus.MSpanInuse}}
    -
    {{.locale.Tr "admin.dashboard.mspan_structures_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.mspan_structures_obtained"}}
    {{.SysStatus.MSpanSys}}
    -
    {{.locale.Tr "admin.dashboard.mcache_structures_usage"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.mcache_structures_usage"}}
    {{.SysStatus.MCacheInuse}}
    -
    {{.locale.Tr "admin.dashboard.mcache_structures_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.mcache_structures_obtained"}}
    {{.SysStatus.MCacheSys}}
    -
    {{.locale.Tr "admin.dashboard.profiling_bucket_hash_table_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.profiling_bucket_hash_table_obtained"}}
    {{.SysStatus.BuckHashSys}}
    -
    {{.locale.Tr "admin.dashboard.gc_metadata_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.gc_metadata_obtained"}}
    {{.SysStatus.GCSys}}
    -
    {{.locale.Tr "admin.dashboard.other_system_allocation_obtained"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.other_system_allocation_obtained"}}
    {{.SysStatus.OtherSys}}
    -
    {{.locale.Tr "admin.dashboard.next_gc_recycle"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.next_gc_recycle"}}
    {{.SysStatus.NextGC}}
    -
    {{.locale.Tr "admin.dashboard.last_gc_time"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.last_gc_time"}}
    {{.SysStatus.LastGC}}
    -
    {{.locale.Tr "admin.dashboard.total_gc_pause"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.total_gc_pause"}}
    {{.SysStatus.PauseTotalNs}}
    -
    {{.locale.Tr "admin.dashboard.last_gc_pause"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.last_gc_pause"}}
    {{.SysStatus.PauseNs}}
    -
    {{.locale.Tr "admin.dashboard.gc_times"}}
    +
    {{ctx.Locale.Tr "admin.dashboard.gc_times"}}
    {{.SysStatus.NumGC}}
    diff --git a/templates/admin/emails/list.tmpl b/templates/admin/emails/list.tmpl index 0acd112e2b..89ea849da9 100644 --- a/templates/admin/emails/list.tmpl +++ b/templates/admin/emails/list.tmpl @@ -1,27 +1,27 @@ {{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin user")}}

    - {{.locale.Tr "admin.emails.email_manage_panel"}} ({{.locale.Tr "admin.total" .Total}}) + {{ctx.Locale.Tr "admin.emails.email_manage_panel"}} ({{.locale.Tr "admin.total" .Total}})

    @@ -31,16 +31,16 @@ - {{.locale.Tr "admin.users.name"}} + {{ctx.Locale.Tr "admin.users.name"}} {{SortArrow "username" "reverseusername" $.SortType false}} - {{.locale.Tr "admin.users.full_name"}} + {{ctx.Locale.Tr "admin.users.full_name"}} - {{.locale.Tr "email"}} + {{ctx.Locale.Tr "email"}} {{SortArrow "email" "reverseemail" $.SortType true}} - {{.locale.Tr "admin.emails.primary"}} - {{.locale.Tr "admin.emails.activated"}} + {{ctx.Locale.Tr "admin.emails.primary"}} + {{ctx.Locale.Tr "admin.emails.activated"}} @@ -72,10 +72,10 @@