Fix context usages (#35348)

This commit is contained in:
wxiaoguang
2025-08-27 19:00:01 +08:00
committed by GitHub
parent da5ce5c8e7
commit e837c998b7
48 changed files with 98 additions and 100 deletions

View File

@ -100,7 +100,7 @@ func runRepoSyncReleases(ctx context.Context, _ *cli.Command) error {
return err return err
} }
if err := git.InitSimple(ctx); err != nil { if err := git.InitSimple(); err != nil {
return err return err
} }

View File

@ -128,7 +128,7 @@ func runRecreateTable(ctx context.Context, cmd *cli.Command) error {
} }
recreateTables := migrate_base.RecreateTables(beans...) 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 { if err := migrations.EnsureUpToDate(ctx, x); err != nil {
return err return err
} }

View File

@ -90,7 +90,7 @@ func runDumpRepository(ctx context.Context, cmd *cli.Command) error {
} }
// migrations.GiteaLocalUploader depends on git module // migrations.GiteaLocalUploader depends on git module
if err := git.InitSimple(context.Background()); err != nil { if err := git.InitSimple(); err != nil {
return err return err
} }
@ -179,7 +179,7 @@ func runDumpRepository(ctx context.Context, cmd *cli.Command) error {
} }
if err := migrations.DumpRepository( if err := migrations.DumpRepository(
context.Background(), ctx,
repoDir, repoDir,
cmd.String("owner_name"), cmd.String("owner_name"),
opts, opts,

View File

@ -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) _ = fail(ctx, "Unable to access repository path", "Unable to access repository path %q, err: %v", setting.RepoRootPath, err)
return 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) _ = fail(ctx, "Failed to init git", "Failed to init git, err: %v", err)
} }
} }

View File

@ -236,15 +236,16 @@ func serveInstalled(c *cli.Command) error {
} }
func servePprof() { func servePprof() {
// FIXME: it shouldn't use the global DefaultServeMux, and it should use a proper context
http.DefaultServeMux.Handle("/debug/fgprof", fgprof.Handler()) http.DefaultServeMux.Handle("/debug/fgprof", fgprof.Handler())
_, _, finished := process.GetManager().AddTypedContext(context.Background(), "Web: PProf Server", process.SystemProcessType, true) _, _, 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 to introduce a configurable option for it. // 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("Starting pprof server on localhost:6060")
log.Info("Stopped pprof server: %v", http.ListenAndServe("localhost:6060", nil)) log.Info("Stopped pprof server: %v", http.ListenAndServe("localhost:6060", nil))
finished() finished()
} }
func runWeb(_ context.Context, cmd *cli.Command) error { func runWeb(ctx context.Context, cmd *cli.Command) error {
defer func() { defer func() {
if panicked := recover(); panicked != nil { if panicked := recover(); panicked != nil {
log.Fatal("PANIC: %v\n%s", panicked, log.Stack(2)) 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) return fmt.Errorf("unknown command: %s", subCmdName)
} }
managerCtx, cancel := context.WithCancel(context.Background()) managerCtx, cancel := context.WithCancel(ctx)
graceful.InitManager(managerCtx) graceful.InitManager(managerCtx)
defer cancel() defer cancel()

View File

@ -320,7 +320,7 @@ func (a *Action) GetCommentHTMLURL(ctx context.Context) string {
return "#" return "#"
} }
return a.Issue.HTMLURL() return a.Issue.HTMLURL(ctx)
} }
// GetCommentLink returns link to action comment. // GetCommentLink returns link to action comment.

View File

@ -280,11 +280,11 @@ func (n *Notification) HTMLURL(ctx context.Context) string {
if n.Comment != nil { if n.Comment != nil {
return n.Comment.HTMLURL(ctx) return n.Comment.HTMLURL(ctx)
} }
return n.Issue.HTMLURL() return n.Issue.HTMLURL(ctx)
case NotificationSourceCommit: case NotificationSourceCommit:
return n.Repository.HTMLURL() + "/commit/" + url.PathEscape(n.CommitID) return n.Repository.HTMLURL(ctx) + "/commit/" + url.PathEscape(n.CommitID)
case NotificationSourceRepository: case NotificationSourceRepository:
return n.Repository.HTMLURL() return n.Repository.HTMLURL(ctx)
} }
return "" return ""
} }

View File

@ -414,7 +414,7 @@ func (c *Comment) HTMLURL(ctx context.Context) string {
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" 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 // 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) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" return ""
} }
return c.Issue.HTMLURL() return c.Issue.HTMLURL(ctx)
} }
// PRURL formats a URL-string to the pull-request // 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 { if !c.Issue.IsPull {
return "" return ""
} }
return c.Issue.HTMLURL() return c.Issue.HTMLURL(ctx)
} }
// CommentHashTag returns unique hash tag for comment id. // CommentHashTag returns unique hash tag for comment id.

View File

@ -405,14 +405,14 @@ func (issue *Issue) APIURL(ctx context.Context) string {
} }
// HTMLURL returns the absolute URL to this issue. // HTMLURL returns the absolute URL to this issue.
func (issue *Issue) HTMLURL() string { func (issue *Issue) HTMLURL(ctx context.Context) string {
var path string var path string
if issue.IsPull { if issue.IsPull {
path = "pulls" path = "pulls"
} else { } else {
path = "issues" 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. // Link returns the issue's relative URL.

View File

@ -4,7 +4,6 @@
package base package base
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@ -124,7 +123,7 @@ func MainTest(m *testing.M) {
setting.AppDataPath = tmpDataPath setting.AppDataPath = tmpDataPath
unittest.InitSettingsForTesting() unittest.InitSettingsForTesting()
if err = git.InitFull(context.Background()); err != nil { if err = git.InitFull(); err != nil {
testlogger.Fatalf("Unable to InitFull: %v\n", err) testlogger.Fatalf("Unable to InitFull: %v\n", err)
} }
setting.LoadDBSetting() setting.LoadDBSetting()

View File

@ -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 // Some migration tasks depend on the git command
if git.DefaultContext == nil { if git.DefaultContext == nil {
if err = git.InitSimple(context.Background()); err != nil { if err = git.InitSimple(); err != nil {
return err return err
} }
} }

View File

@ -159,8 +159,8 @@ func (org *Organization) AvatarLink(ctx context.Context) string {
} }
// HTMLURL returns the organization's full link. // HTMLURL returns the organization's full link.
func (org *Organization) HTMLURL() string { func (org *Organization) HTMLURL(ctx context.Context) string {
return org.AsUser().HTMLURL() return org.AsUser().HTMLURL(ctx)
} }
// OrganisationLink returns the organization sub page link. // OrganisationLink returns the organization sub page link.

View File

@ -83,13 +83,13 @@ func (pd *PackageDescriptor) VersionWebLink() string {
} }
// PackageHTMLURL returns the absolute package HTML URL // PackageHTMLURL returns the absolute package HTML URL
func (pd *PackageDescriptor) PackageHTMLURL() string { func (pd *PackageDescriptor) PackageHTMLURL(ctx context.Context) string {
return fmt.Sprintf("%s/-/packages/%s/%s", pd.Owner.HTMLURL(), string(pd.Package.Type), url.PathEscape(pd.Package.LowerName)) 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 // VersionHTMLURL returns the absolute package version HTML URL
func (pd *PackageDescriptor) VersionHTMLURL() string { func (pd *PackageDescriptor) VersionHTMLURL(ctx context.Context) string {
return fmt.Sprintf("%s/%s", pd.PackageHTMLURL(), url.PathEscape(pd.Version.LowerVersion)) return fmt.Sprintf("%s/%s", pd.PackageHTMLURL(ctx), url.PathEscape(pd.Version.LowerVersion))
} }
// CalculateBlobSize returns the total blobs size in bytes // CalculateBlobSize returns the total blobs size in bytes

View File

@ -363,10 +363,8 @@ func (repo *Repository) FullName() string {
// HTMLURL returns the repository HTML URL // HTMLURL returns the repository HTML URL
func (repo *Repository) HTMLURL(ctxs ...context.Context) string { func (repo *Repository) HTMLURL(ctxs ...context.Context) string {
ctx := context.TODO() // FIXME: this HTMLURL is still used in mail templates, so the "ctx" is not provided.
if len(ctxs) > 0 { ctx := util.OptionalArg(ctxs, context.TODO())
ctx = ctxs[0]
}
return httplib.MakeAbsoluteURL(ctx, repo.Link()) return httplib.MakeAbsoluteURL(ctx, repo.Link())
} }

View File

@ -141,7 +141,7 @@ func MainTest(m *testing.M, testOptsArg ...*TestOptions) {
fatalTestError("util.SyncDirs: %v\n", err) 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) fatalTestError("git.Init: %v\n", err)
} }

View File

@ -27,6 +27,7 @@ import (
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/container" "code.gitea.io/gitea/modules/container"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/optional" "code.gitea.io/gitea/modules/optional"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -303,8 +304,8 @@ func (u *User) HomeLink() string {
} }
// HTMLURL returns the user or organization's full link. // HTMLURL returns the user or organization's full link.
func (u *User) HTMLURL() string { func (u *User) HTMLURL(ctx context.Context) string {
return setting.AppURL + url.PathEscape(u.Name) return httplib.MakeAbsoluteURL(ctx, u.HomeLink())
} }
// OrganisationLink returns the organization sub page link. // OrganisationLink returns the organization sub page link.

View File

@ -4,7 +4,6 @@
package attribute package attribute
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -22,7 +21,7 @@ func testRun(m *testing.M) error {
defer util.RemoveAll(gitHomePath) defer util.RemoveAll(gitHomePath)
setting.Git.HomePath = 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) return fmt.Errorf("failed to call Init: %w", err)
} }

View File

@ -53,7 +53,7 @@ func DefaultFeatures() *Features {
if !setting.IsProd || setting.IsInTesting { if !setting.IsProd || setting.IsInTesting {
log.Warn("git.DefaultFeatures is called before git.InitXxx, initializing with default values") 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) 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. // 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. // 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 == "" { if setting.Git.HomePath == "" {
return errors.New("unable to init Git's HomeDir, incorrect initialization of the setting and git modules") 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") 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 globalCommandArgs = nil
if setting.Git.Timeout.Default > 0 { 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. // 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. // 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) { func InitFull() (err error) {
if err = InitSimple(ctx); err != nil { if err = InitSimple(); err != nil {
return err return err
} }

View File

@ -4,7 +4,6 @@
package git package git
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -25,7 +24,7 @@ func testRun(m *testing.M) error {
setting.Git.HomePath = gitHomePath 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) return fmt.Errorf("failed to call Init: %w", err)
} }

View File

@ -4,7 +4,6 @@
package languagestats package languagestats
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -22,7 +21,7 @@ func testRun(m *testing.M) error {
defer util.RemoveAll(gitHomePath) defer util.RemoveAll(gitHomePath)
setting.Git.HomePath = 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) return fmt.Errorf("failed to call Init: %w", err)
} }

View File

@ -47,12 +47,19 @@ var (
// GetManager returns the Manager // GetManager returns the Manager
func GetManager() *Manager { func GetManager() *Manager {
InitManager(context.Background()) initManager(context.Background())
return manager return manager
} }
// InitManager creates the graceful manager in the provided context // InitManager creates the graceful manager in the provided context
func InitManager(ctx context.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() { initOnce.Do(func() {
manager = newGracefulManager(ctx) manager = newGracefulManager(ctx)

View File

@ -19,7 +19,7 @@ type RequestContextKeyStruct struct{}
var RequestContextKey = RequestContextKeyStruct{} var RequestContextKey = RequestContextKeyStruct{}
func urlIsRelative(s string, u *url.URL) bool { 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 // Therefore we should ignore these redirect locations to prevent open redirects
if len(s) > 1 && (s[0] == '/' || s[0] == '\\') && (s[1] == '/' || s[1] == '\\') { if len(s) > 1 && (s[0] == '/' || s[0] == '\\') && (s[1] == '/' || s[1] == '\\') {
return false return false

View File

@ -52,7 +52,7 @@ func Person(ctx *context.APIContext) {
return return
} }
person.URL = ap.IRI(ctx.ContextUser.HTMLURL()) person.URL = ap.IRI(ctx.ContextUser.HTMLURL(ctx))
person.Icon = ap.Image{ person.Icon = ap.Image{
Type: ap.ImageType, Type: ap.ImageType,

View File

@ -111,9 +111,9 @@ func InitWebInstallPage(ctx context.Context) {
mustInit(svg.Init) mustInit(svg.Init)
} }
// InitWebInstalled is for global installed configuration. // InitWebInstalled is for the global configuration of an installed instance
func InitWebInstalled(ctx context.Context) { func InitWebInstalled(ctx context.Context) {
mustInitCtx(ctx, git.InitFull) mustInit(git.InitFull)
log.Info("Git version: %s (home: %s)", git.DefaultFeatures().VersionInfo(), git.HomeDir()) log.Info("Git version: %s (home: %s)", git.DefaultFeatures().VersionInfo(), git.HomeDir())
if !git.DefaultFeatures().SupportHashSha256 { if !git.DefaultFeatures().SupportHashSha256 {
log.Warn("sha256 hash support is disabled - requires Git >= 2.42." + util.Iif(git.DefaultFeatures().UsingGogit, " Gogit is currently unsupported.", "")) log.Warn("sha256 hash support is disabled - requires Git >= 2.42." + util.Iif(git.DefaultFeatures().UsingGogit, " Gogit is currently unsupported.", ""))

View File

@ -97,7 +97,7 @@ func NewAuthSource(ctx *context.Context) {
ctx.Data["AuthSources"] = authSources ctx.Data["AuthSources"] = authSources
ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = smtp.Authenticators ctx.Data["SMTPAuths"] = smtp.Authenticators
oauth2providers := oauth2.GetSupportedOAuth2ProvidersWithContext(ctx) oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx)
ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["OAuth2Providers"] = oauth2providers
ctx.Data["SSPIAutoCreateUsers"] = true ctx.Data["SSPIAutoCreateUsers"] = true
@ -242,7 +242,7 @@ func NewAuthSourcePost(ctx *context.Context) {
ctx.Data["AuthSources"] = authSources ctx.Data["AuthSources"] = authSources
ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = smtp.Authenticators ctx.Data["SMTPAuths"] = smtp.Authenticators
oauth2providers := oauth2.GetSupportedOAuth2ProvidersWithContext(ctx) oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx)
ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["OAuth2Providers"] = oauth2providers
ctx.Data["SSPIAutoCreateUsers"] = true ctx.Data["SSPIAutoCreateUsers"] = true
@ -334,7 +334,7 @@ func EditAuthSource(ctx *context.Context) {
ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = smtp.Authenticators ctx.Data["SMTPAuths"] = smtp.Authenticators
oauth2providers := oauth2.GetSupportedOAuth2Providers() oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx)
ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["OAuth2Providers"] = oauth2providers
source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid")) source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid"))
@ -368,7 +368,7 @@ func EditAuthSourcePost(ctx *context.Context) {
ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["SMTPAuths"] = smtp.Authenticators ctx.Data["SMTPAuths"] = smtp.Authenticators
oauth2providers := oauth2.GetSupportedOAuth2Providers() oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx)
ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["OAuth2Providers"] = oauth2providers
source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid")) source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid"))

View File

@ -67,7 +67,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
oidcToken = createAndParseToken(t, grants[0]) oidcToken = createAndParseToken(t, grants[0])
assert.Equal(t, user.DisplayName(), oidcToken.Name) assert.Equal(t, user.DisplayName(), oidcToken.Name)
assert.Equal(t, user.Name, oidcToken.PreferredUsername) 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.AvatarLink(db.DefaultContext), oidcToken.Picture)
assert.Equal(t, user.Website, oidcToken.Website) assert.Equal(t, user.Website, oidcToken.Website)
assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt) assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt)

View File

@ -103,7 +103,7 @@ func RenderUserSearch(ctx *context.Context, opts user_model.SearchUserOptions, t
if isSitemap { if isSitemap {
m := sitemap.NewSitemap() m := sitemap.NewSitemap()
for _, item := range users { 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") ctx.Resp.Header().Set("Content-Type", "text/xml")
if _, err := m.WriteTo(ctx.Resp); err != nil { if _, err := m.WriteTo(ctx.Resp); err != nil {

View File

@ -54,7 +54,7 @@ func showUserFeed(ctx *context.Context, formatType string) {
return return
} }
rctx := renderhelper.NewRenderContextSimpleDocument(ctx, ctx.ContextUser.HTMLURL()) rctx := renderhelper.NewRenderContextSimpleDocument(ctx, ctx.ContextUser.HTMLURL(ctx))
ctxUserDescription, err := markdown.RenderString(rctx, ctxUserDescription, err := markdown.RenderString(rctx,
ctx.ContextUser.Description) ctx.ContextUser.Description)
if err != nil { if err != nil {
@ -64,7 +64,7 @@ func showUserFeed(ctx *context.Context, formatType string) {
feed := &feeds.Feed{ feed := &feeds.Feed{
Title: ctx.Locale.TrString("home.feed_of", ctx.ContextUser.DisplayName()), 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), Description: string(ctxUserDescription),
Created: time.Now(), Created: time.Now(),
} }

View File

@ -85,7 +85,7 @@ func WebfingerQuery(ctx *context.Context) {
} }
aliases := []string{ aliases := []string{
u.HTMLURL(), u.HTMLURL(ctx),
appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(u.ID, 10), appURL.String() + "api/v1/activitypub/user-id/" + strconv.FormatInt(u.ID, 10),
} }
if !u.KeepEmailPrivate { if !u.KeepEmailPrivate {
@ -96,7 +96,7 @@ func WebfingerQuery(ctx *context.Context) {
{ {
Rel: "http://webfinger.net/rel/profile-page", Rel: "http://webfinger.net/rel/profile-page",
Type: "text/html", Type: "text/html",
Href: u.HTMLURL(), Href: u.HTMLURL(ctx),
}, },
{ {
Rel: "http://webfinger.net/rel/avatar", Rel: "http://webfinger.net/rel/avatar",

View File

@ -108,17 +108,12 @@ func getExistingAzureADAuthSources(ctx context.Context) ([]string, error) {
return existingAzureProviders, nil 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) // key is used as technical name (like in the callbackURL)
// values to display // values to display
// Note: Azure AD providers (azuread, microsoftonline, azureadv2) are filtered out // Note: Azure AD providers (azuread, microsoftonline, azureadv2) are filtered out
// unless they already exist in the system to encourage use of OpenID Connect // unless they already exist in the system to encourage use of OpenID Connect
func GetSupportedOAuth2Providers() []Provider { func GetSupportedOAuth2Providers(ctx context.Context) []Provider {
return GetSupportedOAuth2ProvidersWithContext(context.Background())
}
// GetSupportedOAuth2ProvidersWithContext returns the list of supported OAuth2 providers with context for filtering
func GetSupportedOAuth2ProvidersWithContext(ctx context.Context) []Provider {
providers := make([]Provider, 0, len(gothProviders)) providers := make([]Provider, 0, len(gothProviders))
existingAzureSources, err := getExistingAzureADAuthSources(ctx) existingAzureSources, err := getExistingAzureADAuthSources(ctx)
if err != nil { if err != nil {

View File

@ -66,7 +66,7 @@ func toIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Iss
return &api.Issue{} return &api.Issue{}
} }
apiIssue.URL = issue.APIURL(ctx) apiIssue.URL = issue.APIURL(ctx)
apiIssue.HTMLURL = issue.HTMLURL() apiIssue.HTMLURL = issue.HTMLURL(ctx)
if err := issue.LoadLabels(ctx); err != nil { if err := issue.LoadLabels(ctx); err != nil {
return &api.Issue{} 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() apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
} }
// Add pr's html url // Add pr's html url
apiIssue.PullRequest.HTMLURL = issue.HTMLURL() apiIssue.PullRequest.HTMLURL = issue.HTMLURL(ctx)
} }
} }
if issue.DeadlineUnix != 0 { if issue.DeadlineUnix != 0 {

View File

@ -40,7 +40,7 @@ func ToNotificationThread(ctx context.Context, n *activities_model.Notification)
if n.Issue != nil { if n.Issue != nil {
result.Subject.Title = n.Issue.Title result.Subject.Title = n.Issue.Title
result.Subject.URL = n.Issue.APIURL(ctx) 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() result.Subject.State = n.Issue.State()
comment, err := n.Issue.GetLastComment(ctx) comment, err := n.Issue.GetLastComment(ctx)
if err == nil && comment != nil { if err == nil && comment != nil {
@ -53,7 +53,7 @@ func ToNotificationThread(ctx context.Context, n *activities_model.Notification)
if n.Issue != nil { if n.Issue != nil {
result.Subject.Title = n.Issue.Title result.Subject.Title = n.Issue.Title
result.Subject.URL = n.Issue.APIURL(ctx) 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() result.Subject.State = n.Issue.State()
comment, err := n.Issue.GetLastComment(ctx) comment, err := n.Issue.GetLastComment(ctx)
if err == nil && comment != nil { if err == nil && comment != nil {

View File

@ -35,7 +35,7 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m
Name: pd.Package.Name, Name: pd.Package.Name,
Version: pd.Version.Version, Version: pd.Version.Version,
CreatedAt: pd.Version.CreatedUnix.AsTime(), CreatedAt: pd.Version.CreatedUnix.AsTime(),
HTMLURL: pd.VersionHTMLURL(), HTMLURL: pd.VersionHTMLURL(ctx),
}, nil }, nil
} }

View File

@ -73,7 +73,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
apiPullRequest := &api.PullRequest{ apiPullRequest := &api.PullRequest{
ID: pr.ID, ID: pr.ID,
URL: pr.Issue.HTMLURL(), URL: pr.Issue.HTMLURL(ctx),
Index: pr.Index, Index: pr.Index,
Poster: apiIssue.Poster, Poster: apiIssue.Poster,
Title: apiIssue.Title, Title: apiIssue.Title,
@ -87,7 +87,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
IsLocked: apiIssue.IsLocked, IsLocked: apiIssue.IsLocked,
Comments: apiIssue.Comments, Comments: apiIssue.Comments,
ReviewComments: pr.GetReviewCommentsCount(ctx), ReviewComments: pr.GetReviewCommentsCount(ctx),
HTMLURL: pr.Issue.HTMLURL(), HTMLURL: pr.Issue.HTMLURL(ctx),
DiffURL: pr.Issue.DiffURL(), DiffURL: pr.Issue.DiffURL(),
PatchURL: pr.Issue.PatchURL(), PatchURL: pr.Issue.PatchURL(),
HasMerged: pr.HasMerged, HasMerged: pr.HasMerged,
@ -348,7 +348,7 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs
apiPullRequest := &api.PullRequest{ apiPullRequest := &api.PullRequest{
ID: pr.ID, ID: pr.ID,
URL: pr.Issue.HTMLURL(), URL: pr.Issue.HTMLURL(ctx),
Index: pr.Index, Index: pr.Index,
Poster: apiIssue.Poster, Poster: apiIssue.Poster,
Title: apiIssue.Title, Title: apiIssue.Title,
@ -362,7 +362,7 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs
IsLocked: apiIssue.IsLocked, IsLocked: apiIssue.IsLocked,
Comments: apiIssue.Comments, Comments: apiIssue.Comments,
ReviewComments: reviewCounts[pr.IssueID], ReviewComments: reviewCounts[pr.IssueID],
HTMLURL: pr.Issue.HTMLURL(), HTMLURL: pr.Issue.HTMLURL(ctx),
DiffURL: pr.Issue.DiffURL(), DiffURL: pr.Issue.DiffURL(),
PatchURL: pr.Issue.PatchURL(), PatchURL: pr.Issue.PatchURL(),
HasMerged: pr.HasMerged, HasMerged: pr.HasMerged,

View File

@ -34,7 +34,7 @@ func ToPullReview(ctx context.Context, r *issues_model.Review, doer *user_model.
Submitted: r.CreatedUnix.AsTime(), Submitted: r.CreatedUnix.AsTime(),
Updated: r.UpdatedUnix.AsTime(), Updated: r.UpdatedUnix.AsTime(),
HTMLURL: r.HTMLURL(ctx), HTMLURL: r.HTMLURL(ctx),
HTMLPullURL: r.Issue.HTMLURL(), HTMLPullURL: r.Issue.HTMLURL(ctx),
} }
if r.ReviewerTeam != nil { if r.ReviewerTeam != nil {
@ -105,7 +105,7 @@ func ToPullReviewCommentList(ctx context.Context, review *issues_model.Review, d
OrigCommitID: comment.OldRef, OrigCommitID: comment.OldRef,
DiffHunk: patch2diff(comment.Patch), DiffHunk: patch2diff(comment.Patch),
HTMLURL: comment.HTMLURL(ctx), HTMLURL: comment.HTMLURL(ctx),
HTMLPullURL: review.Issue.HTMLURL(), HTMLPullURL: review.Issue.HTMLURL(ctx),
} }
if comment.Line < 0 { if comment.Line < 0 {

View File

@ -53,7 +53,7 @@ func toUser(ctx context.Context, user *user_model.User, signed, authed bool) *ap
FullName: user.FullName, FullName: user.FullName,
Email: user.GetPlaceholderEmail(), Email: user.GetPlaceholderEmail(),
AvatarURL: user.AvatarLink(ctx), AvatarURL: user.AvatarLink(ctx),
HTMLURL: user.HTMLURL(), HTMLURL: user.HTMLURL(ctx),
Created: user.CreatedUnix.AsTime(), Created: user.CreatedUnix.AsTime(),
Restricted: user.IsRestricted, Restricted: user.IsRestricted,
Location: user.Location, Location: user.Location,

View File

@ -36,7 +36,7 @@ func initDBSkipLogger(ctx context.Context) error {
return fmt.Errorf("db.InitEngine: %w", err) return fmt.Errorf("db.InitEngine: %w", err)
} }
// some doctor sub-commands need to use git command // 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 fmt.Errorf("git.InitFull: %w", err)
} }
return nil return nil

View File

@ -56,9 +56,9 @@ func composeIssueCommentMessages(ctx context.Context, comment *mailComment, lang
commentType := issues_model.CommentTypeComment commentType := issues_model.CommentTypeComment
if comment.Comment != nil { if comment.Comment != nil {
commentType = comment.Comment.Type commentType = comment.Comment.Type
link = comment.Issue.HTMLURL() + "#" + comment.Comment.HashTag() link = comment.Issue.HTMLURL(ctx) + "#" + comment.Comment.HashTag()
} else { } else {
link = comment.Issue.HTMLURL() link = comment.Issue.HTMLURL(ctx)
} }
reviewType := issues_model.ReviewTypeComment reviewType := issues_model.ReviewTypeComment
@ -175,7 +175,7 @@ func composeIssueCommentMessages(ctx context.Context, comment *mailComment, lang
msg.SetHeader("In-Reply-To", reference) msg.SetHeader("In-Reply-To", reference)
references := []string{reference} references := []string{reference}
listUnsubscribe := []string{"<" + comment.Issue.HTMLURL() + ">"} listUnsubscribe := []string{"<" + comment.Issue.HTMLURL(ctx) + ">"}
if setting.IncomingEmail.Enabled { if setting.IncomingEmail.Enabled {
if replyPayload != nil { if replyPayload != nil {
@ -313,7 +313,7 @@ func generateAdditionalHeadersForIssue(ctx *mailComment, reason string, recipien
maps.Copy(headers, generateReasonHeaders(reason)) maps.Copy(headers, generateReasonHeaders(reason))
headers["X-Gitea-Issue-ID"] = issueID 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 headers["X-GitLab-Issue-IID"] = issueID
return headers return headers

View File

@ -150,12 +150,12 @@ func TestComposeIssueComment(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
// text/plain // text/plain
assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, doer.HTMLURL())) assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, doer.HTMLURL(t.Context())))
assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, issue.HTMLURL())) assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, issue.HTMLURL(t.Context())))
// text/html // text/html
assert.Contains(t, string(b), fmt.Sprintf(`href="%s"`, doer.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())) assert.Contains(t, string(b), fmt.Sprintf(`href="%s"`, issue.HTMLURL(t.Context())))
} }
func TestMailMentionsComment(t *testing.T) { func TestMailMentionsComment(t *testing.T) {

View File

@ -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) { 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 { 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 { 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) log.Error("Error in SendIssueAssignedMail for issue[%d] to reviewer[%d]: %v", issue.ID, reviewer.ID, err)
} }

View File

@ -196,7 +196,7 @@ func NewAccessTokenResponse(ctx context.Context, grant *auth.OAuth2Grant, server
if grant.ScopeContains("profile") { if grant.ScopeContains("profile") {
idToken.Name = user.DisplayName() idToken.Name = user.DisplayName()
idToken.PreferredUsername = user.Name idToken.PreferredUsername = user.Name
idToken.Profile = user.HTMLURL() idToken.Profile = user.HTMLURL(ctx)
idToken.Picture = user.AvatarLink(ctx) idToken.Picture = user.AvatarLink(ctx)
idToken.Website = user.Website idToken.Website = user.Website
idToken.Locale = user.Language idToken.Locale = user.Language

View File

@ -18,9 +18,9 @@
{{end}} {{end}}
<link rel="icon" href="{{AssetUrlPrefix}}/img/favicon.svg" type="image/svg+xml"> <link rel="icon" href="{{AssetUrlPrefix}}/img/favicon.svg" type="image/svg+xml">
<link rel="alternate icon" href="{{AssetUrlPrefix}}/img/favicon.png" type="image/png"> <link rel="alternate icon" href="{{AssetUrlPrefix}}/img/favicon.png" type="image/png">
{{template "base/head_script" .}}
{{template "base/head_opengraph" .}} {{template "base/head_opengraph" .}}
{{template "base/head_style" .}} {{template "base/head_style" .}}
{{template "base/head_script" .}}
{{template "custom/header" .}} {{template "custom/header" .}}
</head> </head>
<body hx-headers='{"x-csrf-token": "{{.CsrfToken}}"}' hx-swap="outerHTML" hx-ext="morph" hx-push-url="false"> <body hx-headers='{"x-csrf-token": "{{.CsrfToken}}"}' hx-swap="outerHTML" hx-ext="morph" hx-push-url="false">

View File

@ -3,14 +3,14 @@
<meta property="og:title" content="{{.ContextUser.DisplayName}}"> <meta property="og:title" content="{{.ContextUser.DisplayName}}">
<meta property="og:type" content="profile"> <meta property="og:type" content="profile">
<meta property="og:image" content="{{.ContextUser.AvatarLink ctx}}"> <meta property="og:image" content="{{.ContextUser.AvatarLink ctx}}">
<meta property="og:url" content="{{.ContextUser.HTMLURL}}"> <meta property="og:url" content="{{.ContextUser.HTMLURL ctx}}">
{{if .ContextUser.Description}} {{if .ContextUser.Description}}
<meta property="og:description" content="{{StringUtils.EllipsisString .ContextUser.Description 300}}"> <meta property="og:description" content="{{StringUtils.EllipsisString .ContextUser.Description 300}}">
{{end}} {{end}}
{{else if .Repository}} {{else if .Repository}}
{{if .Issue}} {{if .Issue}}
<meta property="og:title" content="{{.Issue.Title}}"> <meta property="og:title" content="{{.Issue.Title}}">
<meta property="og:url" content="{{.Issue.HTMLURL}}"> <meta property="og:url" content="{{.Issue.HTMLURL ctx}}">
{{if .Issue.Content}} {{if .Issue.Content}}
<meta property="og:description" content="{{StringUtils.EllipsisString .Issue.Content 300}}"> <meta property="og:description" content="{{StringUtils.EllipsisString .Issue.Content 300}}">
{{end}} {{end}}
@ -26,7 +26,7 @@
{{end}} {{end}}
{{else}} {{else}}
<meta property="og:title" content="{{.Repository.Name}}"> <meta property="og:title" content="{{.Repository.Name}}">
<meta property="og:url" content="{{.Repository.HTMLURL}}"> <meta property="og:url" content="{{.Repository.HTMLURL ctx}}">
{{if .Repository.Description}} {{if .Repository.Description}}
<meta property="og:description" content="{{StringUtils.EllipsisString .Repository.Description 300}}"> <meta property="og:description" content="{{StringUtils.EllipsisString .Repository.Description 300}}">
{{end}} {{end}}

View File

@ -39,7 +39,7 @@
</div> </div>
<div class="flex-item-main"> <div class="flex-item-main">
<div class="flex-item-title"> <div class="flex-item-title">
<a class="item" href="{{.Blockee.HTMLURL}}">{{.Blockee.GetDisplayName}}</a> <a class="item" href="{{.Blockee.HomeLink}}">{{.Blockee.GetDisplayName}}</a>
</div> </div>
{{if .Note}} {{if .Note}}
<div class="flex-item-body"> <div class="flex-item-body">

View File

@ -43,7 +43,7 @@ func TestAPIPullReview(t *testing.T) {
require.Len(t, reviews, 8) require.Len(t, reviews, 8)
for _, r := range reviews { 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, 8, reviews[3].ID)
assert.EqualValues(t, "APPROVED", reviews[3].State) assert.EqualValues(t, "APPROVED", reviews[3].State)

View File

@ -56,7 +56,7 @@ func initMigrationTest(t *testing.T) func() {
assert.NotEmpty(t, setting.RepoRootPath) 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, 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.LoadDBSetting()
setting.InitLoggersForTest() setting.InitLoggersForTest()

View File

@ -50,7 +50,7 @@ func TestWebfinger(t *testing.T) {
var jrd webfingerJRD var jrd webfingerJRD
DecodeJSON(t, resp, &jrd) DecodeJSON(t, resp, &jrd)
assert.Equal(t, "acct:user2@"+appURL.Host, jrd.Subject) 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")) req = NewRequest(t, "GET", fmt.Sprintf("/.well-known/webfinger?resource=acct:%s@%s", user.LowerName, "unknown.host"))
MakeRequest(t, req, http.StatusBadRequest) MakeRequest(t, req, http.StatusBadRequest)

View File

@ -4,7 +4,6 @@
package tests package tests
import ( import (
"context"
"database/sql" "database/sql"
"fmt" "fmt"
"os" "os"
@ -68,7 +67,7 @@ func InitTest(requireGitea bool) {
unittest.InitSettingsForTesting() unittest.InitSettingsForTesting()
setting.Repository.DefaultBranch = "master" // many test code still assume that default branch is called "master" 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) log.Fatal("git.InitOnceWithSync: %v", err)
} }