From e837c998b7355f23ae5802614d9ffcd02a47a56e Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 27 Aug 2025 19:00:01 +0800 Subject: [PATCH] Fix context usages (#35348) --- cmd/admin.go | 2 +- cmd/doctor.go | 2 +- cmd/dump_repo.go | 4 ++-- cmd/serv.go | 2 +- cmd/web.go | 9 +++++---- models/activities/action.go | 2 +- models/activities/notification.go | 6 +++--- models/issues/comment.go | 6 +++--- models/issues/issue.go | 4 ++-- models/migrations/base/tests.go | 3 +-- models/migrations/migrations.go | 2 +- models/organization/org.go | 4 ++-- models/packages/descriptor.go | 8 ++++---- models/repo/repo.go | 6 ++---- models/unittest/testdb.go | 2 +- models/user/user.go | 5 +++-- modules/git/attribute/main_test.go | 3 +-- modules/git/git.go | 11 ++++++----- modules/git/git_test.go | 3 +-- modules/git/languagestats/main_test.go | 3 +-- modules/graceful/manager.go | 9 ++++++++- modules/httplib/url.go | 2 +- routers/api/v1/activitypub/person.go | 2 +- routers/init.go | 4 ++-- routers/web/admin/auths.go | 8 ++++---- routers/web/auth/oauth_test.go | 2 +- routers/web/explore/user.go | 2 +- routers/web/feed/profile.go | 4 ++-- routers/web/webfinger.go | 4 ++-- services/auth/source/oauth2/providers.go | 9 ++------- services/convert/issue.go | 4 ++-- services/convert/notification.go | 4 ++-- services/convert/package.go | 2 +- services/convert/pull.go | 8 ++++---- services/convert/pull_review.go | 4 ++-- services/convert/user.go | 2 +- services/doctor/doctor.go | 2 +- services/mailer/mail_issue_common.go | 8 ++++---- services/mailer/mail_test.go | 8 ++++---- services/mailer/notify.go | 2 +- services/oauth2_provider/access_token.go | 2 +- templates/base/head.tmpl | 2 +- templates/base/head_opengraph.tmpl | 6 +++--- templates/shared/user/blocked_users.tmpl | 2 +- tests/integration/api_pull_review_test.go | 2 +- tests/integration/migration-test/migration_test.go | 2 +- tests/integration/webfinger_test.go | 2 +- tests/test_utils.go | 3 +-- 48 files changed, 98 insertions(+), 100 deletions(-) diff --git a/cmd/admin.go b/cmd/admin.go index 559544edd3..5c58a40ca2 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -100,7 +100,7 @@ func runRepoSyncReleases(ctx context.Context, _ *cli.Command) error { return err } - if err := git.InitSimple(ctx); err != nil { + if err := git.InitSimple(); err != nil { return err } diff --git a/cmd/doctor.go b/cmd/doctor.go index 9e0fcbf877..596dd61178 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -128,7 +128,7 @@ func runRecreateTable(ctx context.Context, cmd *cli.Command) error { } recreateTables := migrate_base.RecreateTables(beans...) - return db.InitEngineWithMigration(ctx, func(ctx context.Context, x *xorm.Engine) error { + return db.InitEngineWithMigration(context.Background(), func(ctx context.Context, x *xorm.Engine) error { if err := migrations.EnsureUpToDate(ctx, x); err != nil { return err } diff --git a/cmd/dump_repo.go b/cmd/dump_repo.go index a75b2d1b94..beda305c85 100644 --- a/cmd/dump_repo.go +++ b/cmd/dump_repo.go @@ -90,7 +90,7 @@ func runDumpRepository(ctx context.Context, cmd *cli.Command) error { } // migrations.GiteaLocalUploader depends on git module - if err := git.InitSimple(context.Background()); err != nil { + if err := git.InitSimple(); err != nil { return err } @@ -179,7 +179,7 @@ func runDumpRepository(ctx context.Context, cmd *cli.Command) error { } if err := migrations.DumpRepository( - context.Background(), + ctx, repoDir, cmd.String("owner_name"), opts, diff --git a/cmd/serv.go b/cmd/serv.go index 38c79f68cd..089d0e3bb7 100644 --- a/cmd/serv.go +++ b/cmd/serv.go @@ -65,7 +65,7 @@ func setup(ctx context.Context, debug bool) { _ = fail(ctx, "Unable to access repository path", "Unable to access repository path %q, err: %v", setting.RepoRootPath, err) return } - if err := git.InitSimple(context.Background()); err != nil { + if err := git.InitSimple(); err != nil { _ = fail(ctx, "Failed to init git", "Failed to init git, err: %v", err) } } diff --git a/cmd/web.go b/cmd/web.go index 61ee3cbc20..4723ddbbdd 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -236,15 +236,16 @@ func serveInstalled(c *cli.Command) error { } func servePprof() { + // FIXME: it shouldn't use the global DefaultServeMux, and it should use a proper context http.DefaultServeMux.Handle("/debug/fgprof", fgprof.Handler()) - _, _, finished := process.GetManager().AddTypedContext(context.Background(), "Web: PProf Server", process.SystemProcessType, true) - // The pprof server is for debug purpose only, it shouldn't be exposed on public network. At the moment it's not worth to introduce a configurable option for it. + _, _, finished := process.GetManager().AddTypedContext(context.TODO(), "Web: PProf Server", process.SystemProcessType, true) + // The pprof server is for debug purpose only, it shouldn't be exposed on public network. At the moment, it's not worth introducing a configurable option for it. log.Info("Starting pprof server on localhost:6060") log.Info("Stopped pprof server: %v", http.ListenAndServe("localhost:6060", nil)) finished() } -func runWeb(_ context.Context, cmd *cli.Command) error { +func runWeb(ctx context.Context, cmd *cli.Command) error { defer func() { if panicked := recover(); panicked != nil { log.Fatal("PANIC: %v\n%s", panicked, log.Stack(2)) @@ -255,7 +256,7 @@ func runWeb(_ context.Context, cmd *cli.Command) error { return fmt.Errorf("unknown command: %s", subCmdName) } - managerCtx, cancel := context.WithCancel(context.Background()) + managerCtx, cancel := context.WithCancel(ctx) graceful.InitManager(managerCtx) defer cancel() diff --git a/models/activities/action.go b/models/activities/action.go index 1a0dfe6412..8e589eda88 100644 --- a/models/activities/action.go +++ b/models/activities/action.go @@ -320,7 +320,7 @@ func (a *Action) GetCommentHTMLURL(ctx context.Context) string { return "#" } - return a.Issue.HTMLURL() + return a.Issue.HTMLURL(ctx) } // GetCommentLink returns link to action comment. diff --git a/models/activities/notification.go b/models/activities/notification.go index 6dde26fd53..b482e6020a 100644 --- a/models/activities/notification.go +++ b/models/activities/notification.go @@ -280,11 +280,11 @@ func (n *Notification) HTMLURL(ctx context.Context) string { if n.Comment != nil { return n.Comment.HTMLURL(ctx) } - return n.Issue.HTMLURL() + return n.Issue.HTMLURL(ctx) case NotificationSourceCommit: - return n.Repository.HTMLURL() + "/commit/" + url.PathEscape(n.CommitID) + return n.Repository.HTMLURL(ctx) + "/commit/" + url.PathEscape(n.CommitID) case NotificationSourceRepository: - return n.Repository.HTMLURL() + return n.Repository.HTMLURL(ctx) } return "" } diff --git a/models/issues/comment.go b/models/issues/comment.go index d22f08fa87..a366b7c6a9 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -414,7 +414,7 @@ func (c *Comment) HTMLURL(ctx context.Context) string { log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" } - return c.Issue.HTMLURL() + c.hashLink(ctx) + return c.Issue.HTMLURL(ctx) + c.hashLink(ctx) } // Link formats a relative URL-string to the issue-comment @@ -483,7 +483,7 @@ func (c *Comment) IssueURL(ctx context.Context) string { log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) return "" } - return c.Issue.HTMLURL() + return c.Issue.HTMLURL(ctx) } // PRURL formats a URL-string to the pull-request @@ -503,7 +503,7 @@ func (c *Comment) PRURL(ctx context.Context) string { if !c.Issue.IsPull { return "" } - return c.Issue.HTMLURL() + return c.Issue.HTMLURL(ctx) } // CommentHashTag returns unique hash tag for comment id. diff --git a/models/issues/issue.go b/models/issues/issue.go index ef651359ab..053b96dceb 100644 --- a/models/issues/issue.go +++ b/models/issues/issue.go @@ -405,14 +405,14 @@ func (issue *Issue) APIURL(ctx context.Context) string { } // HTMLURL returns the absolute URL to this issue. -func (issue *Issue) HTMLURL() string { +func (issue *Issue) HTMLURL(ctx context.Context) string { var path string if issue.IsPull { path = "pulls" } else { path = "issues" } - return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index) + return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(ctx), path, issue.Index) } // Link returns the issue's relative URL. diff --git a/models/migrations/base/tests.go b/models/migrations/base/tests.go index 33fd1df707..3b52a5e7c7 100644 --- a/models/migrations/base/tests.go +++ b/models/migrations/base/tests.go @@ -4,7 +4,6 @@ package base import ( - "context" "fmt" "os" "path/filepath" @@ -124,7 +123,7 @@ func MainTest(m *testing.M) { setting.AppDataPath = tmpDataPath unittest.InitSettingsForTesting() - if err = git.InitFull(context.Background()); err != nil { + if err = git.InitFull(); err != nil { testlogger.Fatalf("Unable to InitFull: %v\n", err) } setting.LoadDBSetting() diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 4f899453b5..a8e2970fa3 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -501,7 +501,7 @@ Please try upgrading to a lower version first (suggested v1.6.4), then upgrade t // Some migration tasks depend on the git command if git.DefaultContext == nil { - if err = git.InitSimple(context.Background()); err != nil { + if err = git.InitSimple(); err != nil { return err } } diff --git a/models/organization/org.go b/models/organization/org.go index 5eba004d69..9ece044d6c 100644 --- a/models/organization/org.go +++ b/models/organization/org.go @@ -159,8 +159,8 @@ func (org *Organization) AvatarLink(ctx context.Context) string { } // HTMLURL returns the organization's full link. -func (org *Organization) HTMLURL() string { - return org.AsUser().HTMLURL() +func (org *Organization) HTMLURL(ctx context.Context) string { + return org.AsUser().HTMLURL(ctx) } // OrganisationLink returns the organization sub page link. diff --git a/models/packages/descriptor.go b/models/packages/descriptor.go index 2d43dc3046..ea0e0d5e73 100644 --- a/models/packages/descriptor.go +++ b/models/packages/descriptor.go @@ -83,13 +83,13 @@ func (pd *PackageDescriptor) VersionWebLink() string { } // PackageHTMLURL returns the absolute package HTML URL -func (pd *PackageDescriptor) PackageHTMLURL() string { - return fmt.Sprintf("%s/-/packages/%s/%s", pd.Owner.HTMLURL(), string(pd.Package.Type), url.PathEscape(pd.Package.LowerName)) +func (pd *PackageDescriptor) PackageHTMLURL(ctx context.Context) string { + return fmt.Sprintf("%s/-/packages/%s/%s", pd.Owner.HTMLURL(ctx), string(pd.Package.Type), url.PathEscape(pd.Package.LowerName)) } // VersionHTMLURL returns the absolute package version HTML URL -func (pd *PackageDescriptor) VersionHTMLURL() string { - return fmt.Sprintf("%s/%s", pd.PackageHTMLURL(), url.PathEscape(pd.Version.LowerVersion)) +func (pd *PackageDescriptor) VersionHTMLURL(ctx context.Context) string { + return fmt.Sprintf("%s/%s", pd.PackageHTMLURL(ctx), url.PathEscape(pd.Version.LowerVersion)) } // CalculateBlobSize returns the total blobs size in bytes diff --git a/models/repo/repo.go b/models/repo/repo.go index 2403b3b40b..73c7e304d2 100644 --- a/models/repo/repo.go +++ b/models/repo/repo.go @@ -363,10 +363,8 @@ func (repo *Repository) FullName() string { // HTMLURL returns the repository HTML URL func (repo *Repository) HTMLURL(ctxs ...context.Context) string { - ctx := context.TODO() - if len(ctxs) > 0 { - ctx = ctxs[0] - } + // FIXME: this HTMLURL is still used in mail templates, so the "ctx" is not provided. + ctx := util.OptionalArg(ctxs, context.TODO()) return httplib.MakeAbsoluteURL(ctx, repo.Link()) } diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go index cb60cf5f85..4611a079ec 100644 --- a/models/unittest/testdb.go +++ b/models/unittest/testdb.go @@ -141,7 +141,7 @@ func MainTest(m *testing.M, testOptsArg ...*TestOptions) { fatalTestError("util.SyncDirs: %v\n", err) } - if err = git.InitFull(context.Background()); err != nil { + if err = git.InitFull(); err != nil { fatalTestError("git.Init: %v\n", err) } diff --git a/models/user/user.go b/models/user/user.go index 9cad1cc7c9..ae500f3a1f 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -27,6 +27,7 @@ import ( "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/container" "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/httplib" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/optional" "code.gitea.io/gitea/modules/setting" @@ -303,8 +304,8 @@ func (u *User) HomeLink() string { } // HTMLURL returns the user or organization's full link. -func (u *User) HTMLURL() string { - return setting.AppURL + url.PathEscape(u.Name) +func (u *User) HTMLURL(ctx context.Context) string { + return httplib.MakeAbsoluteURL(ctx, u.HomeLink()) } // OrganisationLink returns the organization sub page link. diff --git a/modules/git/attribute/main_test.go b/modules/git/attribute/main_test.go index df8241bfb0..1f1d80ec0a 100644 --- a/modules/git/attribute/main_test.go +++ b/modules/git/attribute/main_test.go @@ -4,7 +4,6 @@ package attribute import ( - "context" "fmt" "os" "testing" @@ -22,7 +21,7 @@ func testRun(m *testing.M) error { defer util.RemoveAll(gitHomePath) setting.Git.HomePath = gitHomePath - if err = git.InitFull(context.Background()); err != nil { + if err = git.InitFull(); err != nil { return fmt.Errorf("failed to call Init: %w", err) } diff --git a/modules/git/git.go b/modules/git/git.go index a2ffd6d289..f45d8c234e 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -53,7 +53,7 @@ func DefaultFeatures() *Features { if !setting.IsProd || setting.IsInTesting { log.Warn("git.DefaultFeatures is called before git.InitXxx, initializing with default values") } - if err := InitSimple(context.Background()); err != nil { + if err := InitSimple(); err != nil { log.Fatal("git.InitSimple failed: %v", err) } } @@ -158,7 +158,7 @@ func HomeDir() string { // InitSimple initializes git module with a very simple step, no config changes, no global command arguments. // This method doesn't change anything to filesystem. At the moment, it is only used by some Gitea sub-commands. -func InitSimple(ctx context.Context) error { +func InitSimple() error { if setting.Git.HomePath == "" { return errors.New("unable to init Git's HomeDir, incorrect initialization of the setting and git modules") } @@ -167,7 +167,8 @@ func InitSimple(ctx context.Context) error { log.Warn("git module has been initialized already, duplicate init may work but it's better to fix it") } - DefaultContext = ctx + // FIXME: git context is used across the application, so it should use the global default context, this design is not right but it's hard to change now. + DefaultContext = context.Background() globalCommandArgs = nil if setting.Git.Timeout.Default > 0 { @@ -196,8 +197,8 @@ func InitSimple(ctx context.Context) error { // InitFull initializes git module with version check and change global variables, sync gitconfig. // It should only be called once at the beginning of the program initialization (TestMain/GlobalInitInstalled) as this code makes unsynchronized changes to variables. -func InitFull(ctx context.Context) (err error) { - if err = InitSimple(ctx); err != nil { +func InitFull() (err error) { + if err = InitSimple(); err != nil { return err } diff --git a/modules/git/git_test.go b/modules/git/git_test.go index 58ba01cabc..7a8ca74b01 100644 --- a/modules/git/git_test.go +++ b/modules/git/git_test.go @@ -4,7 +4,6 @@ package git import ( - "context" "fmt" "os" "testing" @@ -25,7 +24,7 @@ func testRun(m *testing.M) error { setting.Git.HomePath = gitHomePath - if err = InitFull(context.Background()); err != nil { + if err = InitFull(); err != nil { return fmt.Errorf("failed to call Init: %w", err) } diff --git a/modules/git/languagestats/main_test.go b/modules/git/languagestats/main_test.go index 707d268c81..b8f9ded005 100644 --- a/modules/git/languagestats/main_test.go +++ b/modules/git/languagestats/main_test.go @@ -4,7 +4,6 @@ package languagestats import ( - "context" "fmt" "os" "testing" @@ -22,7 +21,7 @@ func testRun(m *testing.M) error { defer util.RemoveAll(gitHomePath) setting.Git.HomePath = gitHomePath - if err = git.InitFull(context.Background()); err != nil { + if err = git.InitFull(); err != nil { return fmt.Errorf("failed to call Init: %w", err) } diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 433e8c4c27..ee1872b999 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -47,12 +47,19 @@ var ( // GetManager returns the Manager func GetManager() *Manager { - InitManager(context.Background()) + initManager(context.Background()) return manager } // InitManager creates the graceful manager in the provided context func InitManager(ctx context.Context) { + if manager != nil { + log.Error("graceful.InitManager called more than once") + } + initManager(ctx) // FIXME: this design is not right, it conflicts with the "Background" context used in GetManager +} + +func initManager(ctx context.Context) { initOnce.Do(func() { manager = newGracefulManager(ctx) diff --git a/modules/httplib/url.go b/modules/httplib/url.go index f51506ac3b..2a1376b8d4 100644 --- a/modules/httplib/url.go +++ b/modules/httplib/url.go @@ -19,7 +19,7 @@ type RequestContextKeyStruct struct{} var RequestContextKey = RequestContextKeyStruct{} func urlIsRelative(s string, u *url.URL) bool { - // Unfortunately browsers consider a redirect Location with preceding "//", "\\", "/\" and "\/" as meaning redirect to "http(s)://REST_OF_PATH" + // Unfortunately, browsers consider a redirect Location with preceding "//", "\\", "/\" and "\/" as meaning redirect to "http(s)://REST_OF_PATH" // Therefore we should ignore these redirect locations to prevent open redirects if len(s) > 1 && (s[0] == '/' || s[0] == '\\') && (s[1] == '/' || s[1] == '\\') { return false diff --git a/routers/api/v1/activitypub/person.go b/routers/api/v1/activitypub/person.go index 0b0db011c6..f2ba2baf7f 100644 --- a/routers/api/v1/activitypub/person.go +++ b/routers/api/v1/activitypub/person.go @@ -52,7 +52,7 @@ func Person(ctx *context.APIContext) { return } - person.URL = ap.IRI(ctx.ContextUser.HTMLURL()) + person.URL = ap.IRI(ctx.ContextUser.HTMLURL(ctx)) person.Icon = ap.Image{ Type: ap.ImageType, diff --git a/routers/init.go b/routers/init.go index 744feee2f0..2281260a6f 100644 --- a/routers/init.go +++ b/routers/init.go @@ -111,9 +111,9 @@ func InitWebInstallPage(ctx context.Context) { mustInit(svg.Init) } -// InitWebInstalled is for global installed configuration. +// InitWebInstalled is for the global configuration of an installed instance func InitWebInstalled(ctx context.Context) { - mustInitCtx(ctx, git.InitFull) + mustInit(git.InitFull) log.Info("Git version: %s (home: %s)", git.DefaultFeatures().VersionInfo(), git.HomeDir()) if !git.DefaultFeatures().SupportHashSha256 { log.Warn("sha256 hash support is disabled - requires Git >= 2.42." + util.Iif(git.DefaultFeatures().UsingGogit, " Gogit is currently unsupported.", "")) diff --git a/routers/web/admin/auths.go b/routers/web/admin/auths.go index 60ca7f0048..fb1a7d9524 100644 --- a/routers/web/admin/auths.go +++ b/routers/web/admin/auths.go @@ -97,7 +97,7 @@ func NewAuthSource(ctx *context.Context) { ctx.Data["AuthSources"] = authSources ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SMTPAuths"] = smtp.Authenticators - oauth2providers := oauth2.GetSupportedOAuth2ProvidersWithContext(ctx) + oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx) ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["SSPIAutoCreateUsers"] = true @@ -242,7 +242,7 @@ func NewAuthSourcePost(ctx *context.Context) { ctx.Data["AuthSources"] = authSources ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SMTPAuths"] = smtp.Authenticators - oauth2providers := oauth2.GetSupportedOAuth2ProvidersWithContext(ctx) + oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx) ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["SSPIAutoCreateUsers"] = true @@ -334,7 +334,7 @@ func EditAuthSource(ctx *context.Context) { ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SMTPAuths"] = smtp.Authenticators - oauth2providers := oauth2.GetSupportedOAuth2Providers() + oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx) ctx.Data["OAuth2Providers"] = oauth2providers source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid")) @@ -368,7 +368,7 @@ func EditAuthSourcePost(ctx *context.Context) { ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["SMTPAuths"] = smtp.Authenticators - oauth2providers := oauth2.GetSupportedOAuth2Providers() + oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx) ctx.Data["OAuth2Providers"] = oauth2providers source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid")) diff --git a/routers/web/auth/oauth_test.go b/routers/web/auth/oauth_test.go index 8d9365fab4..4571a70b72 100644 --- a/routers/web/auth/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -67,7 +67,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { oidcToken = createAndParseToken(t, grants[0]) assert.Equal(t, user.DisplayName(), oidcToken.Name) assert.Equal(t, user.Name, oidcToken.PreferredUsername) - assert.Equal(t, user.HTMLURL(), oidcToken.Profile) + assert.Equal(t, user.HTMLURL(t.Context()), oidcToken.Profile) assert.Equal(t, user.AvatarLink(db.DefaultContext), oidcToken.Picture) assert.Equal(t, user.Website, oidcToken.Website) assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt) diff --git a/routers/web/explore/user.go b/routers/web/explore/user.go index af48e6fb79..3774be033d 100644 --- a/routers/web/explore/user.go +++ b/routers/web/explore/user.go @@ -103,7 +103,7 @@ func RenderUserSearch(ctx *context.Context, opts user_model.SearchUserOptions, t if isSitemap { m := sitemap.NewSitemap() for _, item := range users { - m.Add(sitemap.URL{URL: item.HTMLURL(), LastMod: item.UpdatedUnix.AsTimePtr()}) + m.Add(sitemap.URL{URL: item.HTMLURL(ctx), LastMod: item.UpdatedUnix.AsTimePtr()}) } ctx.Resp.Header().Set("Content-Type", "text/xml") if _, err := m.WriteTo(ctx.Resp); err != nil { diff --git a/routers/web/feed/profile.go b/routers/web/feed/profile.go index cecf9d409a..3ca4890e35 100644 --- a/routers/web/feed/profile.go +++ b/routers/web/feed/profile.go @@ -54,7 +54,7 @@ func showUserFeed(ctx *context.Context, formatType string) { return } - rctx := renderhelper.NewRenderContextSimpleDocument(ctx, ctx.ContextUser.HTMLURL()) + rctx := renderhelper.NewRenderContextSimpleDocument(ctx, ctx.ContextUser.HTMLURL(ctx)) ctxUserDescription, err := markdown.RenderString(rctx, ctx.ContextUser.Description) if err != nil { @@ -64,7 +64,7 @@ func showUserFeed(ctx *context.Context, formatType string) { feed := &feeds.Feed{ Title: ctx.Locale.TrString("home.feed_of", ctx.ContextUser.DisplayName()), - Link: &feeds.Link{Href: ctx.ContextUser.HTMLURL()}, + Link: &feeds.Link{Href: ctx.ContextUser.HTMLURL(ctx)}, Description: string(ctxUserDescription), Created: time.Now(), } diff --git a/routers/web/webfinger.go b/routers/web/webfinger.go index a4c9bf902b..9d65b48ac7 100644 --- a/routers/web/webfinger.go +++ b/routers/web/webfinger.go @@ -85,7 +85,7 @@ func WebfingerQuery(ctx *context.Context) { } aliases := []string{ - u.HTMLURL(), + u.HTMLURL(ctx), appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(u.ID, 10), } if !u.KeepEmailPrivate { @@ -96,7 +96,7 @@ func WebfingerQuery(ctx *context.Context) { { Rel: "http://webfinger.net/rel/profile-page", Type: "text/html", - Href: u.HTMLURL(), + Href: u.HTMLURL(ctx), }, { Rel: "http://webfinger.net/rel/avatar", diff --git a/services/auth/source/oauth2/providers.go b/services/auth/source/oauth2/providers.go index c97b8c8e1c..bb21cb53fe 100644 --- a/services/auth/source/oauth2/providers.go +++ b/services/auth/source/oauth2/providers.go @@ -108,17 +108,12 @@ func getExistingAzureADAuthSources(ctx context.Context) ([]string, error) { return existingAzureProviders, nil } -// GetSupportedOAuth2Providers returns the map of unconfigured OAuth2 providers +// GetSupportedOAuth2Providers returns the list of supported OAuth2 providers with context for filtering // key is used as technical name (like in the callbackURL) // values to display // Note: Azure AD providers (azuread, microsoftonline, azureadv2) are filtered out // unless they already exist in the system to encourage use of OpenID Connect -func GetSupportedOAuth2Providers() []Provider { - return GetSupportedOAuth2ProvidersWithContext(context.Background()) -} - -// GetSupportedOAuth2ProvidersWithContext returns the list of supported OAuth2 providers with context for filtering -func GetSupportedOAuth2ProvidersWithContext(ctx context.Context) []Provider { +func GetSupportedOAuth2Providers(ctx context.Context) []Provider { providers := make([]Provider, 0, len(gothProviders)) existingAzureSources, err := getExistingAzureADAuthSources(ctx) if err != nil { diff --git a/services/convert/issue.go b/services/convert/issue.go index 7f386e6293..ecb3b93af1 100644 --- a/services/convert/issue.go +++ b/services/convert/issue.go @@ -66,7 +66,7 @@ func toIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Iss return &api.Issue{} } apiIssue.URL = issue.APIURL(ctx) - apiIssue.HTMLURL = issue.HTMLURL() + apiIssue.HTMLURL = issue.HTMLURL(ctx) if err := issue.LoadLabels(ctx); err != nil { return &api.Issue{} } @@ -112,7 +112,7 @@ func toIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Iss apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr() } // Add pr's html url - apiIssue.PullRequest.HTMLURL = issue.HTMLURL() + apiIssue.PullRequest.HTMLURL = issue.HTMLURL(ctx) } } if issue.DeadlineUnix != 0 { diff --git a/services/convert/notification.go b/services/convert/notification.go index 41063cf399..69470638be 100644 --- a/services/convert/notification.go +++ b/services/convert/notification.go @@ -40,7 +40,7 @@ func ToNotificationThread(ctx context.Context, n *activities_model.Notification) if n.Issue != nil { result.Subject.Title = n.Issue.Title result.Subject.URL = n.Issue.APIURL(ctx) - result.Subject.HTMLURL = n.Issue.HTMLURL() + result.Subject.HTMLURL = n.Issue.HTMLURL(ctx) result.Subject.State = n.Issue.State() comment, err := n.Issue.GetLastComment(ctx) if err == nil && comment != nil { @@ -53,7 +53,7 @@ func ToNotificationThread(ctx context.Context, n *activities_model.Notification) if n.Issue != nil { result.Subject.Title = n.Issue.Title result.Subject.URL = n.Issue.APIURL(ctx) - result.Subject.HTMLURL = n.Issue.HTMLURL() + result.Subject.HTMLURL = n.Issue.HTMLURL(ctx) result.Subject.State = n.Issue.State() comment, err := n.Issue.GetLastComment(ctx) if err == nil && comment != nil { diff --git a/services/convert/package.go b/services/convert/package.go index b27992bea9..08310dd7f6 100644 --- a/services/convert/package.go +++ b/services/convert/package.go @@ -35,7 +35,7 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m Name: pd.Package.Name, Version: pd.Version.Version, CreatedAt: pd.Version.CreatedUnix.AsTime(), - HTMLURL: pd.VersionHTMLURL(), + HTMLURL: pd.VersionHTMLURL(ctx), }, nil } diff --git a/services/convert/pull.go b/services/convert/pull.go index 4acbd880dc..82ab0125d5 100644 --- a/services/convert/pull.go +++ b/services/convert/pull.go @@ -73,7 +73,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u apiPullRequest := &api.PullRequest{ ID: pr.ID, - URL: pr.Issue.HTMLURL(), + URL: pr.Issue.HTMLURL(ctx), Index: pr.Index, Poster: apiIssue.Poster, Title: apiIssue.Title, @@ -87,7 +87,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u IsLocked: apiIssue.IsLocked, Comments: apiIssue.Comments, ReviewComments: pr.GetReviewCommentsCount(ctx), - HTMLURL: pr.Issue.HTMLURL(), + HTMLURL: pr.Issue.HTMLURL(ctx), DiffURL: pr.Issue.DiffURL(), PatchURL: pr.Issue.PatchURL(), HasMerged: pr.HasMerged, @@ -348,7 +348,7 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs apiPullRequest := &api.PullRequest{ ID: pr.ID, - URL: pr.Issue.HTMLURL(), + URL: pr.Issue.HTMLURL(ctx), Index: pr.Index, Poster: apiIssue.Poster, Title: apiIssue.Title, @@ -362,7 +362,7 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs IsLocked: apiIssue.IsLocked, Comments: apiIssue.Comments, ReviewComments: reviewCounts[pr.IssueID], - HTMLURL: pr.Issue.HTMLURL(), + HTMLURL: pr.Issue.HTMLURL(ctx), DiffURL: pr.Issue.DiffURL(), PatchURL: pr.Issue.PatchURL(), HasMerged: pr.HasMerged, diff --git a/services/convert/pull_review.go b/services/convert/pull_review.go index 29a5ab7466..574f34fa17 100644 --- a/services/convert/pull_review.go +++ b/services/convert/pull_review.go @@ -34,7 +34,7 @@ func ToPullReview(ctx context.Context, r *issues_model.Review, doer *user_model. Submitted: r.CreatedUnix.AsTime(), Updated: r.UpdatedUnix.AsTime(), HTMLURL: r.HTMLURL(ctx), - HTMLPullURL: r.Issue.HTMLURL(), + HTMLPullURL: r.Issue.HTMLURL(ctx), } if r.ReviewerTeam != nil { @@ -105,7 +105,7 @@ func ToPullReviewCommentList(ctx context.Context, review *issues_model.Review, d OrigCommitID: comment.OldRef, DiffHunk: patch2diff(comment.Patch), HTMLURL: comment.HTMLURL(ctx), - HTMLPullURL: review.Issue.HTMLURL(), + HTMLPullURL: review.Issue.HTMLURL(ctx), } if comment.Line < 0 { diff --git a/services/convert/user.go b/services/convert/user.go index 90bcf35cf6..cee4de5091 100644 --- a/services/convert/user.go +++ b/services/convert/user.go @@ -53,7 +53,7 @@ func toUser(ctx context.Context, user *user_model.User, signed, authed bool) *ap FullName: user.FullName, Email: user.GetPlaceholderEmail(), AvatarURL: user.AvatarLink(ctx), - HTMLURL: user.HTMLURL(), + HTMLURL: user.HTMLURL(ctx), Created: user.CreatedUnix.AsTime(), Restricted: user.IsRestricted, Location: user.Location, diff --git a/services/doctor/doctor.go b/services/doctor/doctor.go index c6810a5fa0..e7fe29d8ee 100644 --- a/services/doctor/doctor.go +++ b/services/doctor/doctor.go @@ -36,7 +36,7 @@ func initDBSkipLogger(ctx context.Context) error { return fmt.Errorf("db.InitEngine: %w", err) } // some doctor sub-commands need to use git command - if err := git.InitFull(ctx); err != nil { + if err := git.InitFull(); err != nil { return fmt.Errorf("git.InitFull: %w", err) } return nil diff --git a/services/mailer/mail_issue_common.go b/services/mailer/mail_issue_common.go index a34d8a68c9..f5190ce8a1 100644 --- a/services/mailer/mail_issue_common.go +++ b/services/mailer/mail_issue_common.go @@ -56,9 +56,9 @@ func composeIssueCommentMessages(ctx context.Context, comment *mailComment, lang commentType := issues_model.CommentTypeComment if comment.Comment != nil { commentType = comment.Comment.Type - link = comment.Issue.HTMLURL() + "#" + comment.Comment.HashTag() + link = comment.Issue.HTMLURL(ctx) + "#" + comment.Comment.HashTag() } else { - link = comment.Issue.HTMLURL() + link = comment.Issue.HTMLURL(ctx) } reviewType := issues_model.ReviewTypeComment @@ -175,7 +175,7 @@ func composeIssueCommentMessages(ctx context.Context, comment *mailComment, lang msg.SetHeader("In-Reply-To", reference) references := []string{reference} - listUnsubscribe := []string{"<" + comment.Issue.HTMLURL() + ">"} + listUnsubscribe := []string{"<" + comment.Issue.HTMLURL(ctx) + ">"} if setting.IncomingEmail.Enabled { if replyPayload != nil { @@ -313,7 +313,7 @@ func generateAdditionalHeadersForIssue(ctx *mailComment, reason string, recipien maps.Copy(headers, generateReasonHeaders(reason)) headers["X-Gitea-Issue-ID"] = issueID - headers["X-Gitea-Issue-Link"] = ctx.Issue.HTMLURL() + headers["X-Gitea-Issue-Link"] = ctx.Issue.HTMLURL(context.TODO()) // FIXME: use proper context headers["X-GitLab-Issue-IID"] = issueID return headers diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index 24f5d39d50..ce1ebe03a1 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -150,12 +150,12 @@ func TestComposeIssueComment(t *testing.T) { assert.NoError(t, err) // text/plain - assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, doer.HTMLURL())) - assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, issue.HTMLURL())) + assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, doer.HTMLURL(t.Context()))) + assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, issue.HTMLURL(t.Context()))) // text/html - assert.Contains(t, string(b), fmt.Sprintf(`href="%s"`, doer.HTMLURL())) - assert.Contains(t, string(b), fmt.Sprintf(`href="%s"`, issue.HTMLURL())) + assert.Contains(t, string(b), fmt.Sprintf(`href="%s"`, doer.HTMLURL(t.Context()))) + assert.Contains(t, string(b), fmt.Sprintf(`href="%s"`, issue.HTMLURL(t.Context()))) } func TestMailMentionsComment(t *testing.T) { diff --git a/services/mailer/notify.go b/services/mailer/notify.go index a7df0052bc..5921021ce8 100644 --- a/services/mailer/notify.go +++ b/services/mailer/notify.go @@ -128,7 +128,7 @@ func (m *mailNotifier) IssueChangeAssignee(ctx context.Context, doer *user_model func (m *mailNotifier) PullRequestReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { if isRequest && doer.ID != reviewer.ID && reviewer.EmailNotificationsPreference != user_model.EmailNotificationsDisabled { - ct := fmt.Sprintf("Requested to review %s.", issue.HTMLURL()) + ct := fmt.Sprintf("Requested to review %s.", issue.HTMLURL(ctx)) if err := SendIssueAssignedMail(ctx, issue, doer, ct, comment, []*user_model.User{reviewer}); err != nil { log.Error("Error in SendIssueAssignedMail for issue[%d] to reviewer[%d]: %v", issue.ID, reviewer.ID, err) } diff --git a/services/oauth2_provider/access_token.go b/services/oauth2_provider/access_token.go index 5a190d8616..dce4ac765b 100644 --- a/services/oauth2_provider/access_token.go +++ b/services/oauth2_provider/access_token.go @@ -196,7 +196,7 @@ func NewAccessTokenResponse(ctx context.Context, grant *auth.OAuth2Grant, server if grant.ScopeContains("profile") { idToken.Name = user.DisplayName() idToken.PreferredUsername = user.Name - idToken.Profile = user.HTMLURL() + idToken.Profile = user.HTMLURL(ctx) idToken.Picture = user.AvatarLink(ctx) idToken.Website = user.Website idToken.Locale = user.Language diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index e9526818e3..62bc625bda 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -18,9 +18,9 @@ {{end}} - {{template "base/head_script" .}} {{template "base/head_opengraph" .}} {{template "base/head_style" .}} + {{template "base/head_script" .}} {{template "custom/header" .}} diff --git a/templates/base/head_opengraph.tmpl b/templates/base/head_opengraph.tmpl index f1f38999d2..cb96fb6d6d 100644 --- a/templates/base/head_opengraph.tmpl +++ b/templates/base/head_opengraph.tmpl @@ -3,14 +3,14 @@ - + {{if .ContextUser.Description}} {{end}} {{else if .Repository}} {{if .Issue}} - + {{if .Issue.Content}} {{end}} @@ -26,7 +26,7 @@ {{end}} {{else}} - + {{if .Repository.Description}} {{end}} diff --git a/templates/shared/user/blocked_users.tmpl b/templates/shared/user/blocked_users.tmpl index a4c74c46ac..c0b1a8a7a4 100644 --- a/templates/shared/user/blocked_users.tmpl +++ b/templates/shared/user/blocked_users.tmpl @@ -39,7 +39,7 @@
{{if .Note}}
diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index 1fc65ddea8..a6dab1d40a 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -43,7 +43,7 @@ func TestAPIPullReview(t *testing.T) { require.Len(t, reviews, 8) for _, r := range reviews { - assert.Equal(t, pullIssue.HTMLURL(), r.HTMLPullURL) + assert.Equal(t, pullIssue.HTMLURL(t.Context()), r.HTMLPullURL) } assert.EqualValues(t, 8, reviews[3].ID) assert.EqualValues(t, "APPROVED", reviews[3].State) diff --git a/tests/integration/migration-test/migration_test.go b/tests/integration/migration-test/migration_test.go index 0fc8a6e24d..ee326b2ada 100644 --- a/tests/integration/migration-test/migration_test.go +++ b/tests/integration/migration-test/migration_test.go @@ -56,7 +56,7 @@ func initMigrationTest(t *testing.T) func() { assert.NotEmpty(t, setting.RepoRootPath) assert.NoError(t, unittest.SyncDirs(filepath.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath)) - assert.NoError(t, git.InitFull(t.Context())) + assert.NoError(t, git.InitFull()) setting.LoadDBSetting() setting.InitLoggersForTest() diff --git a/tests/integration/webfinger_test.go b/tests/integration/webfinger_test.go index 757d442cd2..6efc44e603 100644 --- a/tests/integration/webfinger_test.go +++ b/tests/integration/webfinger_test.go @@ -50,7 +50,7 @@ func TestWebfinger(t *testing.T) { var jrd webfingerJRD DecodeJSON(t, resp, &jrd) assert.Equal(t, "acct:user2@"+appURL.Host, jrd.Subject) - assert.ElementsMatch(t, []string{user.HTMLURL(), appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(user.ID, 10)}, jrd.Aliases) + assert.ElementsMatch(t, []string{user.HTMLURL(t.Context()), appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(user.ID, 10)}, jrd.Aliases) req = NewRequest(t, "GET", fmt.Sprintf("/.well-known/webfinger?resource=acct:%s@%s", user.LowerName, "unknown.host")) MakeRequest(t, req, http.StatusBadRequest) diff --git a/tests/test_utils.go b/tests/test_utils.go index ad692058a6..eda00c9c78 100644 --- a/tests/test_utils.go +++ b/tests/test_utils.go @@ -4,7 +4,6 @@ package tests import ( - "context" "database/sql" "fmt" "os" @@ -68,7 +67,7 @@ func InitTest(requireGitea bool) { unittest.InitSettingsForTesting() setting.Repository.DefaultBranch = "master" // many test code still assume that default branch is called "master" - if err := git.InitFull(context.Background()); err != nil { + if err := git.InitFull(); err != nil { log.Fatal("git.InitOnceWithSync: %v", err) }