diff --git a/models/actions/schedule_spec_test.go b/models/actions/schedule_spec_test.go index 0c26fce4b2c5e..57221461dfec5 100644 --- a/models/actions/schedule_spec_test.go +++ b/models/actions/schedule_spec_test.go @@ -7,19 +7,17 @@ import ( "testing" "time" + "code.gitea.io/gitea/modules/test" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestActionScheduleSpec_Parse(t *testing.T) { // Mock the local timezone is not UTC - local := time.Local tz, err := time.LoadLocation("Asia/Shanghai") require.NoError(t, err) - defer func() { - time.Local = local - }() - time.Local = tz + defer test.MockVariableValue(&time.Local, tz)() now, err := time.Parse(time.RFC3339, "2024-07-31T15:47:55+08:00") require.NoError(t, err) diff --git a/models/issues/milestone.go b/models/issues/milestone.go index db0312adf0057..4c9bae58f7d40 100644 --- a/models/issues/milestone.go +++ b/models/issues/milestone.go @@ -84,10 +84,9 @@ func (m *Milestone) BeforeUpdate() { // this object. func (m *Milestone) AfterLoad() { m.NumOpenIssues = m.NumIssues - m.NumClosedIssues - if m.DeadlineUnix.Year() == 9999 { + if m.DeadlineUnix == 0 { return } - m.DeadlineString = m.DeadlineUnix.FormatDate() if m.IsClosed { m.IsOverdue = m.ClosedDateUnix >= m.DeadlineUnix diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index ddf20d9542cfe..41f337b838ad6 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -364,6 +364,7 @@ func prepareMigrationTasks() []*migration { newMigration(304, "Add index for release sha1", v1_23.AddIndexForReleaseSha1), newMigration(305, "Add Repository Licenses", v1_23.AddRepositoryLicenses), newMigration(306, "Add BlockAdminMergeOverride to ProtectedBranch", v1_23.AddBlockAdminMergeOverrideBranchProtection), + newMigration(307, "Fix milestone deadline_unix when there is no due date", v1_23.FixMilestoneNoDueDate), } return preparedMigrations } diff --git a/models/migrations/v1_23/v307.go b/models/migrations/v1_23/v307.go new file mode 100644 index 0000000000000..ef7f5f2c3f486 --- /dev/null +++ b/models/migrations/v1_23/v307.go @@ -0,0 +1,21 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package v1_23 //nolint + +import ( + "code.gitea.io/gitea/modules/timeutil" + + "xorm.io/xorm" +) + +func FixMilestoneNoDueDate(x *xorm.Engine) error { + type Milestone struct { + DeadlineUnix timeutil.TimeStamp + } + // Wednesday, December 1, 9999 12:00:00 AM GMT+00:00 + _, err := x.Table("milestone").Where("deadline_unix > 253399622400"). + Cols("deadline_unix"). + Update(&Milestone{DeadlineUnix: 0}) + return err +} diff --git a/models/repo/user_repo.go b/models/repo/user_repo.go index c305603e02070..ecc9216950738 100644 --- a/models/repo/user_repo.go +++ b/models/repo/user_repo.go @@ -110,26 +110,28 @@ func GetRepoAssignees(ctx context.Context, repo *Repository) (_ []*user_model.Us return nil, err } - additionalUserIDs := make([]int64, 0, 10) - if err = e.Table("team_user"). - Join("INNER", "team_repo", "`team_repo`.team_id = `team_user`.team_id"). - Join("INNER", "team_unit", "`team_unit`.team_id = `team_user`.team_id"). - Where("`team_repo`.repo_id = ? AND (`team_unit`.access_mode >= ? OR (`team_unit`.access_mode = ? AND `team_unit`.`type` = ?))", - repo.ID, perm.AccessModeWrite, perm.AccessModeRead, unit.TypePullRequests). - Distinct("`team_user`.uid"). - Select("`team_user`.uid"). - Find(&additionalUserIDs); err != nil { - return nil, err - } - uniqueUserIDs := make(container.Set[int64]) uniqueUserIDs.AddMultiple(userIDs...) - uniqueUserIDs.AddMultiple(additionalUserIDs...) + + if repo.Owner.IsOrganization() { + additionalUserIDs := make([]int64, 0, 10) + if err = e.Table("team_user"). + Join("INNER", "team_repo", "`team_repo`.team_id = `team_user`.team_id"). + Join("INNER", "team_unit", "`team_unit`.team_id = `team_user`.team_id"). + Where("`team_repo`.repo_id = ? AND (`team_unit`.access_mode >= ? OR (`team_unit`.access_mode = ? AND `team_unit`.`type` = ?))", + repo.ID, perm.AccessModeWrite, perm.AccessModeRead, unit.TypePullRequests). + Distinct("`team_user`.uid"). + Select("`team_user`.uid"). + Find(&additionalUserIDs); err != nil { + return nil, err + } + uniqueUserIDs.AddMultiple(additionalUserIDs...) + } // Leave a seat for owner itself to append later, but if owner is an organization // and just waste 1 unit is cheaper than re-allocate memory once. users := make([]*user_model.User, 0, len(uniqueUserIDs)+1) - if len(userIDs) > 0 { + if len(uniqueUserIDs) > 0 { if err = e.In("id", uniqueUserIDs.Values()). Where(builder.Eq{"`user`.is_active": true}). OrderBy(user_model.GetOrderByName()). diff --git a/modules/gitgraph/graph.go b/modules/gitgraph/graph.go index 331ad6b218de9..7e12be030fb35 100644 --- a/modules/gitgraph/graph.go +++ b/modules/gitgraph/graph.go @@ -32,7 +32,7 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo graphCmd.AddArguments("--all") } - graphCmd.AddArguments("-C", "-M", "--date=iso"). + graphCmd.AddArguments("-C", "-M", "--date=iso-strict"). AddOptionFormat("-n %d", setting.UI.GraphMaxCommitNum*page). AddOptionFormat("--pretty=format:%s", format) diff --git a/modules/gitgraph/graph_models.go b/modules/gitgraph/graph_models.go index e48fef8b9d0cc..191b0b3afce9b 100644 --- a/modules/gitgraph/graph_models.go +++ b/modules/gitgraph/graph_models.go @@ -8,6 +8,7 @@ import ( "context" "fmt" "strings" + "time" asymkey_model "code.gitea.io/gitea/models/asymkey" "code.gitea.io/gitea/models/db" @@ -192,6 +193,14 @@ var RelationCommit = &Commit{ Row: -1, } +func parseGitTime(timeStr string) time.Time { + t, err := time.Parse(time.RFC3339, timeStr) + if err != nil { + return time.Unix(0, 0) + } + return t +} + // NewCommit creates a new commit from a provided line func NewCommit(row, column int, line []byte) (*Commit, error) { data := bytes.SplitN(line, []byte("|"), 5) @@ -206,7 +215,7 @@ func NewCommit(row, column int, line []byte) (*Commit, error) { // 1 matches git log --pretty=format:%H => commit hash Rev: string(data[1]), // 2 matches git log --pretty=format:%ad => author date (format respects --date= option) - Date: string(data[2]), + Date: parseGitTime(string(data[2])), // 3 matches git log --pretty=format:%h => abbreviated commit hash ShortRev: string(data[3]), // 4 matches git log --pretty=format:%s => subject @@ -245,7 +254,7 @@ type Commit struct { Column int Refs []git.Reference Rev string - Date string + Date time.Time ShortRev string Subject string } diff --git a/modules/templates/helper.go b/modules/templates/helper.go index a01aad06a173e..efaa10624bd87 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -73,11 +73,6 @@ func NewFuncMap() template.FuncMap { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" }, - // for backward compatibility only, do not use them anymore - "TimeSince": timeSinceLegacy, - "TimeSinceUnix": timeSinceLegacy, - "DateTime": dateTimeLegacy, - // ----------------------------------------------------------------- // setting "AppName": func() string { @@ -156,18 +151,8 @@ func NewFuncMap() template.FuncMap { // ----------------------------------------------------------------- // render - "RenderCommitMessage": RenderCommitMessage, - "RenderCommitMessageLinkSubject": renderCommitMessageLinkSubject, - - "RenderCommitBody": renderCommitBody, - "RenderCodeBlock": renderCodeBlock, - "RenderIssueTitle": renderIssueTitle, - "RenderEmoji": renderEmoji, - "ReactionToEmoji": reactionToEmoji, - - "RenderMarkdownToHtml": RenderMarkdownToHtml, - "RenderLabel": renderLabel, - "RenderLabels": RenderLabels, + "RenderCodeBlock": renderCodeBlock, + "ReactionToEmoji": reactionToEmoji, // ----------------------------------------------------------------- // misc @@ -179,6 +164,22 @@ func NewFuncMap() template.FuncMap { "FilenameIsImage": filenameIsImage, "TabSizeClass": tabSizeClass, + + // for backward compatibility only, do not use them anymore + "TimeSince": timeSinceLegacy, + "TimeSinceUnix": timeSinceLegacy, + "DateTime": dateTimeLegacy, + + "RenderEmoji": renderEmojiLegacy, + "RenderLabel": renderLabelLegacy, + "RenderLabels": renderLabelsLegacy, + "RenderIssueTitle": renderIssueTitleLegacy, + + "RenderMarkdownToHtml": renderMarkdownToHtmlLegacy, + + "RenderCommitMessage": renderCommitMessageLegacy, + "RenderCommitMessageLinkSubject": renderCommitMessageLinkSubjectLegacy, + "RenderCommitBody": renderCommitBodyLegacy, } } @@ -296,3 +297,9 @@ func userThemeName(user *user_model.User) string { } return setting.UI.DefaultTheme } + +func panicIfDevOrTesting() { + if !setting.IsProd || setting.IsInTesting { + panic("legacy template functions are for backward compatibility only, do not use them in new code") + } +} diff --git a/modules/templates/util_date.go b/modules/templates/util_date.go index b9e04401f15f5..66f83d23fe5c2 100644 --- a/modules/templates/util_date.go +++ b/modules/templates/util_date.go @@ -12,7 +12,6 @@ import ( "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" - "code.gitea.io/gitea/modules/translation" ) type DateUtils struct{} @@ -28,7 +27,7 @@ func (du *DateUtils) AbsoluteShort(time any) template.HTML { // AbsoluteLong renders in "January 01, 2006" format func (du *DateUtils) AbsoluteLong(time any) template.HTML { - return dateTimeFormat("short", time) + return dateTimeFormat("long", time) } // FullTime renders in "Jan 01, 2006 20:33:44" format @@ -54,23 +53,6 @@ func parseLegacy(datetime string) time.Time { return t } -func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML { - if !setting.IsProd || setting.IsInTesting { - panic("dateTimeLegacy is for backward compatibility only, do not use it in new code") - } - if s, ok := datetime.(string); ok { - datetime = parseLegacy(s) - } - return dateTimeFormat(format, datetime) -} - -func timeSinceLegacy(time any, _ translation.Locale) template.HTML { - if !setting.IsProd || setting.IsInTesting { - panic("timeSinceLegacy is for backward compatibility only, do not use it in new code") - } - return TimeSince(time) -} - func anyToTime(any any) (t time.Time, isZero bool) { switch v := any.(type) { case nil: diff --git a/modules/templates/util_date_legacy.go b/modules/templates/util_date_legacy.go new file mode 100644 index 0000000000000..ceefb0044717a --- /dev/null +++ b/modules/templates/util_date_legacy.go @@ -0,0 +1,23 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package templates + +import ( + "html/template" + + "code.gitea.io/gitea/modules/translation" +) + +func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML { + panicIfDevOrTesting() + if s, ok := datetime.(string); ok { + datetime = parseLegacy(s) + } + return dateTimeFormat(format, datetime) +} + +func timeSinceLegacy(time any, _ translation.Locale) template.HTML { + panicIfDevOrTesting() + return TimeSince(time) +} diff --git a/modules/templates/util_render.go b/modules/templates/util_render.go index 6eee007f34683..1201828345715 100644 --- a/modules/templates/util_render.go +++ b/modules/templates/util_render.go @@ -24,13 +24,21 @@ import ( "code.gitea.io/gitea/modules/util" ) +type RenderUtils struct { + ctx context.Context +} + +func NewRenderUtils(ctx context.Context) *RenderUtils { + return &RenderUtils{ctx: ctx} +} + // RenderCommitMessage renders commit message with XSS-safe and special links. -func RenderCommitMessage(ctx context.Context, msg string, metas map[string]string) template.HTML { +func (ut *RenderUtils) RenderCommitMessage(msg string, metas map[string]string) template.HTML { cleanMsg := template.HTMLEscapeString(msg) // we can safely assume that it will not return any error, since there // shouldn't be any special HTML. fullMessage, err := markup.RenderCommitMessage(&markup.RenderContext{ - Ctx: ctx, + Ctx: ut.ctx, Metas: metas, }, cleanMsg) if err != nil { @@ -44,9 +52,9 @@ func RenderCommitMessage(ctx context.Context, msg string, metas map[string]strin return renderCodeBlock(template.HTML(msgLines[0])) } -// renderCommitMessageLinkSubject renders commit message as a XSS-safe link to +// RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to // the provided default url, handling for special links without email to links. -func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML { +func (ut *RenderUtils) RenderCommitMessageLinkSubject(msg, urlDefault string, metas map[string]string) template.HTML { msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace) lineEnd := strings.IndexByte(msgLine, '\n') if lineEnd > 0 { @@ -60,7 +68,7 @@ func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, // we can safely assume that it will not return any error, since there // shouldn't be any special HTML. renderedMessage, err := markup.RenderCommitMessageSubject(&markup.RenderContext{ - Ctx: ctx, + Ctx: ut.ctx, DefaultLink: urlDefault, Metas: metas, }, template.HTMLEscapeString(msgLine)) @@ -71,8 +79,8 @@ func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, return renderCodeBlock(template.HTML(renderedMessage)) } -// renderCommitBody extracts the body of a commit message without its title. -func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML { +// RenderCommitBody extracts the body of a commit message without its title. +func (ut *RenderUtils) RenderCommitBody(msg string, metas map[string]string) template.HTML { msgLine := strings.TrimSpace(msg) lineEnd := strings.IndexByte(msgLine, '\n') if lineEnd > 0 { @@ -86,7 +94,7 @@ func renderCommitBody(ctx context.Context, msg string, metas map[string]string) } renderedMessage, err := markup.RenderCommitMessage(&markup.RenderContext{ - Ctx: ctx, + Ctx: ut.ctx, Metas: metas, }, template.HTMLEscapeString(msgLine)) if err != nil { @@ -105,22 +113,22 @@ func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML { return template.HTML(htmlWithCodeTags) } -// renderIssueTitle renders issue/pull title with defined post processors -func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML { +// RenderIssueTitle renders issue/pull title with defined post processors +func (ut *RenderUtils) RenderIssueTitle(text string, metas map[string]string) template.HTML { renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{ - Ctx: ctx, + Ctx: ut.ctx, Metas: metas, }, template.HTMLEscapeString(text)) if err != nil { log.Error("RenderIssueTitle: %v", err) - return template.HTML("") + return "" } return template.HTML(renderedText) } -// renderLabel renders a label -// locale is needed due to an import cycle with our context providing the `Tr` function -func renderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML { +// RenderLabel renders a label +func (ut *RenderUtils) RenderLabel(label *issues_model.Label) template.HTML { + locale := ut.ctx.Value(translation.ContextKey).(translation.Locale) var extraCSSClasses string textColor := util.ContrastColor(label.Color) labelScope := label.ExclusiveScope() @@ -134,12 +142,12 @@ func renderLabel(ctx context.Context, locale translation.Locale, label *issues_m if labelScope == "" { // Regular label return HTMLFormat(`
%s
`, - extraCSSClasses, textColor, label.Color, descriptionText, renderEmoji(ctx, label.Name)) + extraCSSClasses, textColor, label.Color, descriptionText, ut.RenderEmoji(label.Name)) } // Scoped label - scopeHTML := renderEmoji(ctx, labelScope) - itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:]) + scopeHTML := ut.RenderEmoji(labelScope) + itemHTML := ut.RenderEmoji(label.Name[len(labelScope)+1:]) // Make scope and item background colors slightly darker and lighter respectively. // More contrast needed with higher luminance, empirically tweaked. @@ -176,13 +184,12 @@ func renderLabel(ctx context.Context, locale translation.Locale, label *issues_m textColor, itemColor, itemHTML) } -// renderEmoji renders html text with emoji post processors -func renderEmoji(ctx context.Context, text string) template.HTML { - renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx}, - template.HTMLEscapeString(text)) +// RenderEmoji renders html text with emoji post processors +func (ut *RenderUtils) RenderEmoji(text string) template.HTML { + renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ut.ctx}, template.HTMLEscapeString(text)) if err != nil { log.Error("RenderEmoji: %v", err) - return template.HTML("") + return "" } return template.HTML(renderedText) } @@ -200,9 +207,9 @@ func reactionToEmoji(reaction string) template.HTML { return template.HTML(fmt.Sprintf(`:%s:`, reaction, setting.StaticURLPrefix, url.PathEscape(reaction))) } -func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //nolint:revive +func (ut *RenderUtils) MarkdownToHtml(input string) template.HTML { //nolint:revive output, err := markdown.RenderString(&markup.RenderContext{ - Ctx: ctx, + Ctx: ut.ctx, Metas: map[string]string{"mode": "document"}, }, input) if err != nil { @@ -211,7 +218,7 @@ func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //n return output } -func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML { +func (ut *RenderUtils) RenderLabels(labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML { isPullRequest := issue != nil && issue.IsPull baseLink := fmt.Sprintf("%s/%s", repoLink, util.Iif(isPullRequest, "pulls", "issues")) htmlCode := `` @@ -220,7 +227,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu if label == nil { continue } - htmlCode += fmt.Sprintf(`%s`, baseLink, label.ID, renderLabel(ctx, locale, label)) + htmlCode += fmt.Sprintf(`%s`, baseLink, label.ID, ut.RenderLabel(label)) } htmlCode += "" return template.HTML(htmlCode) diff --git a/modules/templates/util_render_legacy.go b/modules/templates/util_render_legacy.go new file mode 100644 index 0000000000000..994f2fa064cb5 --- /dev/null +++ b/modules/templates/util_render_legacy.go @@ -0,0 +1,52 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package templates + +import ( + "context" + "html/template" + + issues_model "code.gitea.io/gitea/models/issues" + "code.gitea.io/gitea/modules/translation" +) + +func renderEmojiLegacy(ctx context.Context, text string) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderEmoji(text) +} + +func renderLabelLegacy(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderLabel(label) +} + +func renderLabelsLegacy(ctx context.Context, locale translation.Locale, labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderLabels(labels, repoLink, issue) +} + +func renderMarkdownToHtmlLegacy(ctx context.Context, input string) template.HTML { //nolint:revive + panicIfDevOrTesting() + return NewRenderUtils(ctx).MarkdownToHtml(input) +} + +func renderCommitMessageLegacy(ctx context.Context, msg string, metas map[string]string) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderCommitMessage(msg, metas) +} + +func renderCommitMessageLinkSubjectLegacy(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderCommitMessageLinkSubject(msg, urlDefault, metas) +} + +func renderIssueTitleLegacy(ctx context.Context, text string, metas map[string]string) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderIssueTitle(text, metas) +} + +func renderCommitBodyLegacy(ctx context.Context, msg string, metas map[string]string) template.HTML { + panicIfDevOrTesting() + return NewRenderUtils(ctx).RenderCommitBody(msg, metas) +} diff --git a/modules/templates/util_render_test.go b/modules/templates/util_render_test.go index ba47c34efc193..3e4ea04c63191 100644 --- a/modules/templates/util_render_test.go +++ b/modules/templates/util_render_test.go @@ -65,9 +65,14 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } +func newTestRenderUtils() *RenderUtils { + ctx := context.Background() + ctx = context.WithValue(ctx, translation.ContextKey, &translation.MockLocale{}) + return NewRenderUtils(ctx) +} + func TestRenderCommitBody(t *testing.T) { type args struct { - ctx context.Context msg string metas map[string]string } @@ -79,7 +84,6 @@ func TestRenderCommitBody(t *testing.T) { { name: "multiple lines", args: args{ - ctx: context.Background(), msg: "first line\nsecond line", }, want: "second line", @@ -87,7 +91,6 @@ func TestRenderCommitBody(t *testing.T) { { name: "multiple lines with leading newlines", args: args{ - ctx: context.Background(), msg: "\n\n\n\nfirst line\nsecond line", }, want: "second line", @@ -95,15 +98,15 @@ func TestRenderCommitBody(t *testing.T) { { name: "multiple lines with trailing newlines", args: args{ - ctx: context.Background(), msg: "first line\nsecond line\n\n\n", }, want: "second line", }, } + ut := newTestRenderUtils() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assert.Equalf(t, tt.want, renderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas) + assert.Equalf(t, tt.want, ut.RenderCommitBody(tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v)", tt.args.msg, tt.args.metas) }) } @@ -127,19 +130,19 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit #123 space` - assert.EqualValues(t, expected, renderCommitBody(context.Background(), testInput(), testMetas)) + assert.EqualValues(t, expected, newTestRenderUtils().RenderCommitBody(testInput(), testMetas)) } func TestRenderCommitMessage(t *testing.T) { expected := `space @mention-user ` - assert.EqualValues(t, expected, RenderCommitMessage(context.Background(), testInput(), testMetas)) + assert.EqualValues(t, expected, newTestRenderUtils().RenderCommitMessage(testInput(), testMetas)) } func TestRenderCommitMessageLinkSubject(t *testing.T) { expected := `space @mention-user` - assert.EqualValues(t, expected, renderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas)) + assert.EqualValues(t, expected, newTestRenderUtils().RenderCommitMessageLinkSubject(testInput(), "https://example.com/link", testMetas)) } func TestRenderIssueTitle(t *testing.T) { @@ -165,7 +168,7 @@ mail@domain.com space ` expected = strings.ReplaceAll(expected, "", " ") - assert.EqualValues(t, expected, renderIssueTitle(context.Background(), testInput(), testMetas)) + assert.EqualValues(t, expected, newTestRenderUtils().RenderIssueTitle(testInput(), testMetas)) } func TestRenderMarkdownToHtml(t *testing.T) { @@ -190,25 +193,23 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit #123 space

` - assert.Equal(t, expected, string(RenderMarkdownToHtml(context.Background(), testInput()))) + assert.Equal(t, expected, string(newTestRenderUtils().MarkdownToHtml(testInput()))) } func TestRenderLabels(t *testing.T) { - ctx := context.Background() - locale := &translation.MockLocale{} - + ut := newTestRenderUtils() label := &issues.Label{ID: 123, Name: "label-name", Color: "label-color"} issue := &issues.Issue{} expected := `/owner/repo/issues?labels=123` - assert.Contains(t, RenderLabels(ctx, locale, []*issues.Label{label}, "/owner/repo", issue), expected) + assert.Contains(t, ut.RenderLabels([]*issues.Label{label}, "/owner/repo", issue), expected) label = &issues.Label{ID: 123, Name: "label-name", Color: "label-color"} issue = &issues.Issue{IsPull: true} expected = `/owner/repo/pulls?labels=123` - assert.Contains(t, RenderLabels(ctx, locale, []*issues.Label{label}, "/owner/repo", issue), expected) + assert.Contains(t, ut.RenderLabels([]*issues.Label{label}, "/owner/repo", issue), expected) } func TestUserMention(t *testing.T) { - rendered := RenderMarkdownToHtml(context.Background(), "@no-such-user @mention-user @mention-user") + rendered := newTestRenderUtils().MarkdownToHtml("@no-such-user @mention-user @mention-user") assert.EqualValues(t, `

@no-such-user @mention-user @mention-user

`, strings.TrimSpace(string(rendered))) } diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 97f7a49390543..05650cc9bed23 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -56,12 +56,12 @@ func GetRawFile(ctx *context.APIContext) { // required: true // - name: filepath // in: path - // description: filepath of the file to get + // description: path of the file to get, it should be "{ref}/{filepath}". If there is no ref could be inferred, it will be treated as the default branch // type: string // required: true // - name: ref // in: query - // description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)" + // description: "The name of the commit/branch/tag. Default the repository’s default branch" // type: string // required: false // responses: @@ -109,12 +109,12 @@ func GetRawFileOrLFS(ctx *context.APIContext) { // required: true // - name: filepath // in: path - // description: filepath of the file to get + // description: path of the file to get, it should be "{ref}/{filepath}". If there is no ref could be inferred, it will be treated as the default branch // type: string // required: true // - name: ref // in: query - // description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)" + // description: "The name of the commit/branch/tag. Default the repository’s default branch" // type: string // required: false // responses: diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index e86fb3ccb1c52..cbe709c030db4 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/api/v1/utils" + "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/services/context" "code.gitea.io/gitea/services/convert" issue_service "code.gitea.io/gitea/services/issue" @@ -1046,18 +1047,11 @@ func UpdateIssueDeadline(ctx *context.APIContext) { return } - var deadlineUnix timeutil.TimeStamp - var deadline time.Time - if form.Deadline != nil && !form.Deadline.IsZero() { - deadline = time.Date(form.Deadline.Year(), form.Deadline.Month(), form.Deadline.Day(), - 23, 59, 59, 0, time.Local) - deadlineUnix = timeutil.TimeStamp(deadline.Unix()) - } - + deadlineUnix, _ := common.ParseAPIDeadlineToEndOfDay(form.Deadline) if err := issues_model.UpdateIssueDeadline(ctx, issue, deadlineUnix, ctx.Doer); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err) return } - ctx.JSON(http.StatusCreated, api.IssueDeadline{Deadline: &deadline}) + ctx.JSON(http.StatusCreated, api.IssueDeadline{Deadline: deadlineUnix.AsTimePtr()}) } diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index abe9e4006a8e4..78907c85a5847 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -7,7 +7,6 @@ package repo import ( "net/http" "strconv" - "time" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" @@ -16,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/api/v1/utils" + "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/services/context" "code.gitea.io/gitea/services/convert" ) @@ -155,16 +155,16 @@ func CreateMilestone(ctx *context.APIContext) { // "$ref": "#/responses/notFound" form := web.GetForm(ctx).(*api.CreateMilestoneOption) - if form.Deadline == nil { - defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local) - form.Deadline = &defaultDeadline + var deadlineUnix int64 + if form.Deadline != nil { + deadlineUnix = form.Deadline.Unix() } milestone := &issues_model.Milestone{ RepoID: ctx.Repo.Repository.ID, Name: form.Title, Content: form.Description, - DeadlineUnix: timeutil.TimeStamp(form.Deadline.Unix()), + DeadlineUnix: timeutil.TimeStamp(deadlineUnix), } if form.State == "closed" { @@ -225,9 +225,7 @@ func EditMilestone(ctx *context.APIContext) { if form.Description != nil { milestone.Content = *form.Description } - if form.Deadline != nil && !form.Deadline.IsZero() { - milestone.DeadlineUnix = timeutil.TimeStamp(form.Deadline.Unix()) - } + milestone.DeadlineUnix, _ = common.ParseAPIDeadlineToEndOfDay(form.Deadline) oldIsClosed := milestone.IsClosed if form.State != nil { diff --git a/routers/common/deadline.go b/routers/common/deadline.go new file mode 100644 index 0000000000000..152e94597bc6a --- /dev/null +++ b/routers/common/deadline.go @@ -0,0 +1,31 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package common + +import ( + "time" + + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/timeutil" +) + +func ParseDeadlineDateToEndOfDay(date string) (timeutil.TimeStamp, error) { + if date == "" { + return 0, nil + } + deadline, err := time.ParseInLocation("2006-01-02", date, setting.DefaultUILocation) + if err != nil { + return 0, err + } + deadline = time.Date(deadline.Year(), deadline.Month(), deadline.Day(), 23, 59, 59, 0, deadline.Location()) + return timeutil.TimeStamp(deadline.Unix()), nil +} + +func ParseAPIDeadlineToEndOfDay(t *time.Time) (timeutil.TimeStamp, error) { + if t == nil || t.IsZero() || t.Unix() == 0 { + return 0, nil + } + deadline := time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, setting.DefaultUILocation) + return timeutil.TimeStamp(deadline.Unix()), nil +} diff --git a/routers/web/feed/convert.go b/routers/web/feed/convert.go index 774644e29ae21..3f33e9933a2ea 100644 --- a/routers/web/feed/convert.go +++ b/routers/web/feed/convert.go @@ -71,6 +71,7 @@ func renderMarkdown(ctx *context.Context, act *activities_model.Action, content // feedActionsToFeedItems convert gitea's Action feed to feeds Item func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) { + renderUtils := templates.NewRenderUtils(ctx) for _, act := range actions { act.LoadActUser(ctx) @@ -215,7 +216,7 @@ func feedActionsToFeedItems(ctx *context.Context, actions activities_model.Actio desc += fmt.Sprintf("%s\n%s", html.EscapeString(fmt.Sprintf("%s/commit/%s", act.GetRepoAbsoluteLink(ctx), commit.Sha1)), commit.Sha1, - templates.RenderCommitMessage(ctx, commit.Message, nil), + renderUtils.RenderCommitMessage(commit.Message, nil), ) } diff --git a/routers/web/goget.go b/routers/web/goget.go index 8d5612ebfe970..3714dd8eb0fc1 100644 --- a/routers/web/goget.go +++ b/routers/web/goget.go @@ -65,7 +65,7 @@ func goGet(ctx *context.Context) { insecure = "--insecure " } - goGetImport := context.ComposeGoGetImport(ownerName, trimmedRepoName) + goGetImport := context.ComposeGoGetImport(ctx, ownerName, trimmedRepoName) var cloneURL string if setting.Repository.GoGetCloneURLProtocol == "ssh" { diff --git a/routers/web/org/projects.go b/routers/web/org/projects.go index 2a5434b4147f6..6dfefbf68d243 100644 --- a/routers/web/org/projects.go +++ b/routers/web/org/projects.go @@ -103,9 +103,9 @@ func Projects(ctx *context.Context) { } else { ctx.Data["State"] = "open" } - + renderUtils := templates.NewRenderUtils(ctx) for _, project := range projects { - project.RenderedContent = templates.RenderMarkdownToHtml(ctx, project.Description) + project.RenderedContent = renderUtils.MarkdownToHtml(project.Description) } err = shared_user.LoadHeaderCount(ctx) @@ -435,7 +435,7 @@ func ViewProject(ctx *context.Context) { ctx.Data["SelectLabels"] = selectLabels ctx.Data["AssigneeID"] = assigneeID - project.RenderedContent = templates.RenderMarkdownToHtml(ctx, project.Description) + project.RenderedContent = templates.NewRenderUtils(ctx).MarkdownToHtml(project.Description) ctx.Data["LinkedPRs"] = linkedPrsMap ctx.Data["PageIsViewProjects"] = true ctx.Data["CanWriteProjects"] = canWriteProjects(ctx) diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 507b5af9d904a..1ee6e98afbd3d 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -17,7 +17,6 @@ import ( "sort" "strconv" "strings" - "time" activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/db" @@ -45,9 +44,9 @@ import ( api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/templates/vars" - "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/routers/utils" shared_user "code.gitea.io/gitea/routers/web/shared/user" asymkey_service "code.gitea.io/gitea/services/asymkey" @@ -2215,7 +2214,7 @@ func GetIssueInfo(ctx *context.Context) { ctx.JSON(http.StatusOK, map[string]any{ "convertedIssue": convert.ToIssue(ctx, ctx.Doer, issue), - "renderedLabels": templates.RenderLabels(ctx, ctx.Locale, issue.Labels, ctx.Repo.RepoLink, issue), + "renderedLabels": templates.NewRenderUtils(ctx).RenderLabels(issue.Labels, ctx.Repo.RepoLink, issue), }) } @@ -2329,7 +2328,6 @@ func UpdateIssueContent(ctx *context.Context) { // UpdateIssueDeadline updates an issue deadline func UpdateIssueDeadline(ctx *context.Context) { - form := web.GetForm(ctx).(*api.EditDeadlineOption) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index")) if err != nil { if issues_model.IsErrIssueNotExist(err) { @@ -2345,20 +2343,13 @@ func UpdateIssueDeadline(ctx *context.Context) { return } - var deadlineUnix timeutil.TimeStamp - var deadline time.Time - if form.Deadline != nil && !form.Deadline.IsZero() { - deadline = time.Date(form.Deadline.Year(), form.Deadline.Month(), form.Deadline.Day(), - 23, 59, 59, 0, time.Local) - deadlineUnix = timeutil.TimeStamp(deadline.Unix()) - } - + deadlineUnix, _ := common.ParseDeadlineDateToEndOfDay(ctx.FormString("deadline")) if err := issues_model.UpdateIssueDeadline(ctx, issue, deadlineUnix, ctx.Doer); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err.Error()) return } - ctx.JSON(http.StatusCreated, api.IssueDeadline{Deadline: &deadline}) + ctx.JSONRedirect("") } // UpdateIssueMilestone change issue's milestone diff --git a/routers/web/repo/milestone.go b/routers/web/repo/milestone.go index e4ee025875ef6..5c0972188cecf 100644 --- a/routers/web/repo/milestone.go +++ b/routers/web/repo/milestone.go @@ -7,7 +7,6 @@ import ( "fmt" "net/http" "net/url" - "time" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" @@ -16,8 +15,8 @@ import ( "code.gitea.io/gitea/modules/markup/markdown" "code.gitea.io/gitea/modules/optional" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/services/context" "code.gitea.io/gitea/services/forms" "code.gitea.io/gitea/services/issue" @@ -134,22 +133,18 @@ func NewMilestonePost(ctx *context.Context) { return } - if len(form.Deadline) == 0 { - form.Deadline = "9999-12-31" - } - deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) + deadlineUnix, err := common.ParseDeadlineDateToEndOfDay(form.Deadline) if err != nil { ctx.Data["Err_Deadline"] = true ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form) return } - deadline = time.Date(deadline.Year(), deadline.Month(), deadline.Day(), 23, 59, 59, 0, deadline.Location()) - if err = issues_model.NewMilestone(ctx, &issues_model.Milestone{ + if err := issues_model.NewMilestone(ctx, &issues_model.Milestone{ RepoID: ctx.Repo.Repository.ID, Name: form.Title, Content: form.Content, - DeadlineUnix: timeutil.TimeStamp(deadline.Unix()), + DeadlineUnix: deadlineUnix, }); err != nil { ctx.ServerError("NewMilestone", err) return @@ -194,17 +189,13 @@ func EditMilestonePost(ctx *context.Context) { return } - if len(form.Deadline) == 0 { - form.Deadline = "9999-12-31" - } - deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) + deadlineUnix, err := common.ParseDeadlineDateToEndOfDay(form.Deadline) if err != nil { ctx.Data["Err_Deadline"] = true ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form) return } - deadline = time.Date(deadline.Year(), deadline.Month(), deadline.Day(), 23, 59, 59, 0, deadline.Location()) m, err := issues_model.GetMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":id")) if err != nil { if issues_model.IsErrMilestoneNotExist(err) { @@ -216,7 +207,7 @@ func EditMilestonePost(ctx *context.Context) { } m.Name = form.Title m.Content = form.Content - m.DeadlineUnix = timeutil.TimeStamp(deadline.Unix()) + m.DeadlineUnix = deadlineUnix if err = issues_model.UpdateMilestone(ctx, m, m.IsClosed); err != nil { ctx.ServerError("UpdateMilestone", err) return diff --git a/routers/web/web.go b/routers/web/web.go index 83d116babd769..29dd8a8edcb66 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -1208,7 +1208,7 @@ func registerRoutes(m *web.Router) { m.Group("/{index}", func() { m.Post("/title", repo.UpdateIssueTitle) m.Post("/content", repo.UpdateIssueContent) - m.Post("/deadline", web.Bind(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline) + m.Post("/deadline", repo.UpdateIssueDeadline) m.Post("/watch", repo.IssueWatch) m.Post("/ref", repo.UpdateIssueRef) m.Post("/pin", reqRepoAdmin, repo.IssuePinOrUnpin) @@ -1323,7 +1323,7 @@ func registerRoutes(m *web.Router) { m.Get(".rss", feedEnabled, repo.TagsListFeedRSS) m.Get(".atom", feedEnabled, repo.TagsListFeedAtom) }, ctxDataSet("EnableFeed", setting.Other.EnableFeed), - repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, true)) + repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, context.RepoRefByTypeOptions{IgnoreNotExistErr: true})) m.Post("/tags/delete", repo.DeleteTag, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef()) }, ignSignIn, context.RepoAssignment, reqRepoCodeReader) @@ -1337,7 +1337,7 @@ func registerRoutes(m *web.Router) { m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS) m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom) }, ctxDataSet("EnableFeed", setting.Other.EnableFeed), - repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, true)) + repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, context.RepoRefByTypeOptions{IgnoreNotExistErr: true})) m.Get("/releases/attachments/{uuid}", repo.MustBeNotEmpty, repo.GetAttachment) m.Get("/releases/download/{vTag}/{fileName}", repo.MustBeNotEmpty, repo.RedirectDownload) m.Group("/releases", func() { @@ -1535,7 +1535,7 @@ func registerRoutes(m *web.Router) { m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS) m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS) // "/*" route is deprecated, and kept for backward compatibility - m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS) + m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.SingleDownloadOrLFS) }, repo.MustBeNotEmpty) m.Group("/raw", func() { @@ -1544,7 +1544,7 @@ func registerRoutes(m *web.Router) { m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload) m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID) // "/*" route is deprecated, and kept for backward compatibility - m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload) + m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.SingleDownload) }, repo.MustBeNotEmpty) m.Group("/render", func() { @@ -1559,7 +1559,7 @@ func registerRoutes(m *web.Router) { m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits) m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits) // "/*" route is deprecated, and kept for backward compatibility - m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits) + m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.RefCommits) }, repo.MustBeNotEmpty) m.Group("/blame", func() { @@ -1582,7 +1582,7 @@ func registerRoutes(m *web.Router) { m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home) m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home) m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home) - m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home) // "/*" route is deprecated, and kept for backward compatibility + m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.Home) // "/*" route is deprecated, and kept for backward compatibility }, repo.SetEditorconfigIfExists) m.Get("/forks", context.RepoRef(), repo.Forks) diff --git a/services/context/api.go b/services/context/api.go index 00cfd6afd92dd..b45e80a329789 100644 --- a/services/context/api.go +++ b/services/context/api.go @@ -14,7 +14,6 @@ import ( "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/cache" - "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" @@ -306,24 +305,8 @@ func RepoRefForAPI(next http.Handler) http.Handler { return } - if ref := ctx.FormTrim("ref"); len(ref) > 0 { - commit, err := ctx.Repo.GitRepo.GetCommit(ref) - if err != nil { - if git.IsErrNotExist(err) { - ctx.NotFound() - } else { - ctx.Error(http.StatusInternalServerError, "GetCommit", err) - } - return - } - ctx.Repo.Commit = commit - ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() - ctx.Repo.TreePath = ctx.PathParam("*") - next.ServeHTTP(w, req) - return - } - - refName := getRefName(ctx.Base, ctx.Repo, RepoRefAny) + // NOTICE: the "ref" here for internal usage only (e.g. woodpecker) + refName, _ := getRefNameLegacy(ctx.Base, ctx.Repo, ctx.FormTrim("ref")) var err error if ctx.Repo.GitRepo.IsBranchExist(refName) { diff --git a/services/context/context.go b/services/context/context.go index 42f7c3d9d1d8a..6c7128ef6866c 100644 --- a/services/context/context.go +++ b/services/context/context.go @@ -100,6 +100,7 @@ func NewTemplateContextForWeb(ctx *Context) TemplateContext { tmplCtx := NewTemplateContext(ctx) tmplCtx["Locale"] = ctx.Base.Locale tmplCtx["AvatarUtils"] = templates.NewAvatarUtils(ctx) + tmplCtx["RenderUtils"] = templates.NewRenderUtils(ctx) tmplCtx["RootData"] = ctx.Data tmplCtx["Consts"] = map[string]any{ "RepoUnitTypeCode": unit.TypeCode, @@ -154,7 +155,9 @@ func Contexter() func(next http.Handler) http.Handler { ctx := NewWebContext(base, rnd, session.GetContextSession(req)) ctx.Data.MergeFrom(middleware.CommonTemplateContextData()) - ctx.Data["Context"] = ctx // TODO: use "ctx" in template and remove this + if setting.IsProd && !setting.IsInTesting { + ctx.Data["Context"] = ctx // TODO: use "ctx" in template and remove this + } ctx.Data["CurrentURL"] = setting.AppSubURL + req.URL.RequestURI() ctx.Data["Link"] = ctx.Link diff --git a/services/context/repo.go b/services/context/repo.go index 2df2b7ea40387..e7b32d62832d4 100644 --- a/services/context/repo.go +++ b/services/context/repo.go @@ -25,6 +25,7 @@ import ( "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/httplib" code_indexer "code.gitea.io/gitea/modules/indexer/code" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/optional" @@ -306,11 +307,9 @@ func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository) { } // ComposeGoGetImport returns go-get-import meta content. -func ComposeGoGetImport(owner, repo string) string { - /// setting.AppUrl is guaranteed to be parse as url - appURL, _ := url.Parse(setting.AppURL) - - return path.Join(appURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo)) +func ComposeGoGetImport(ctx context.Context, owner, repo string) string { + curAppURL, _ := url.Parse(httplib.GuessCurrentAppURL(ctx)) + return path.Join(curAppURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo)) } // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200 @@ -332,7 +331,7 @@ func EarlyResponseForGoGetMeta(ctx *Context) { } else { cloneURL = repo_model.ComposeHTTPSCloneURL(username, reponame) } - goImportContent := fmt.Sprintf("%s git %s", ComposeGoGetImport(username, reponame), cloneURL) + goImportContent := fmt.Sprintf("%s git %s", ComposeGoGetImport(ctx, username, reponame), cloneURL) htmlMeta := fmt.Sprintf(``, html.EscapeString(goImportContent)) ctx.PlainText(http.StatusOK, htmlMeta) } @@ -744,7 +743,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { } if ctx.FormString("go-get") == "1" { - ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name) + ctx.Data["GoGetImport"] = ComposeGoGetImport(ctx, owner.Name, repo.Name) fullURLPrefix := repo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(ctx.Repo.BranchName) ctx.Data["GoDocDirectory"] = fullURLPrefix + "{/dir}" ctx.Data["GoDocFile"] = fullURLPrefix + "{/dir}/{file}#L{line}" @@ -756,19 +755,11 @@ func RepoAssignment(ctx *Context) context.CancelFunc { type RepoRefType int const ( - // RepoRefLegacy unknown type, make educated guess and redirect. - // for backward compatibility with previous URL scheme - RepoRefLegacy RepoRefType = iota - // RepoRefAny is for usage where educated guess is needed - // but redirect can not be made - RepoRefAny - // RepoRefBranch branch + // RepoRefUnknown is for legacy support, makes the code to "guess" the ref type + RepoRefUnknown RepoRefType = iota RepoRefBranch - // RepoRefTag tag RepoRefTag - // RepoRefCommit commit RepoRefCommit - // RepoRefBlob blob RepoRefBlob ) @@ -781,22 +772,6 @@ func RepoRef() func(*Context) context.CancelFunc { return RepoRefByType(RepoRefBranch) } -// RefTypeIncludesBranches returns true if ref type can be a branch -func (rt RepoRefType) RefTypeIncludesBranches() bool { - if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch { - return true - } - return false -} - -// RefTypeIncludesTags returns true if ref type can be a tag -func (rt RepoRefType) RefTypeIncludesTags() bool { - if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag { - return true - } - return false -} - func getRefNameFromPath(repo *Repository, path string, isExist func(string) bool) string { refName := "" parts := strings.Split(path, "/") @@ -810,28 +785,50 @@ func getRefNameFromPath(repo *Repository, path string, isExist func(string) bool return "" } +func isStringLikelyCommitID(objFmt git.ObjectFormat, s string, minLength ...int) bool { + minLen := util.OptionalArg(minLength, objFmt.FullLength()) + if len(s) < minLen || len(s) > objFmt.FullLength() { + return false + } + for _, c := range s { + isHex := (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') + if !isHex { + return false + } + } + return true +} + +func getRefNameLegacy(ctx *Base, repo *Repository, optionalExtraRef ...string) (string, RepoRefType) { + extraRef := util.OptionalArg(optionalExtraRef) + reqPath := ctx.PathParam("*") + reqPath = path.Join(extraRef, reqPath) + + if refName := getRefName(ctx, repo, RepoRefBranch); refName != "" { + return refName, RepoRefBranch + } + if refName := getRefName(ctx, repo, RepoRefTag); refName != "" { + return refName, RepoRefTag + } + + // For legacy support only full commit sha + parts := strings.Split(reqPath, "/") + if isStringLikelyCommitID(git.ObjectFormatFromName(repo.Repository.ObjectFormatName), parts[0]) { + // FIXME: this logic is different from other types. Ideally, it should also try to GetCommit to check if it exists + repo.TreePath = strings.Join(parts[1:], "/") + return parts[0], RepoRefCommit + } + + if refName := getRefName(ctx, repo, RepoRefBlob); len(refName) > 0 { + return refName, RepoRefBlob + } + repo.TreePath = reqPath + return repo.Repository.DefaultBranch, RepoRefBranch +} + func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string { path := ctx.PathParam("*") switch pathType { - case RepoRefLegacy, RepoRefAny: - if refName := getRefName(ctx, repo, RepoRefBranch); len(refName) > 0 { - return refName - } - if refName := getRefName(ctx, repo, RepoRefTag); len(refName) > 0 { - return refName - } - // For legacy and API support only full commit sha - parts := strings.Split(path, "/") - - if len(parts) > 0 && len(parts[0]) == git.ObjectFormatFromName(repo.Repository.ObjectFormatName).FullLength() { - repo.TreePath = strings.Join(parts[1:], "/") - return parts[0] - } - if refName := getRefName(ctx, repo, RepoRefBlob); len(refName) > 0 { - return refName - } - repo.TreePath = path - return repo.Repository.DefaultBranch case RepoRefBranch: ref := getRefNameFromPath(repo, path, repo.GitRepo.IsBranchExist) if len(ref) == 0 { @@ -866,13 +863,13 @@ func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string { return getRefNameFromPath(repo, path, repo.GitRepo.IsTagExist) case RepoRefCommit: parts := strings.Split(path, "/") - - if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= repo.GetObjectFormat().FullLength() { + if isStringLikelyCommitID(repo.GetObjectFormat(), parts[0], 7) { + // FIXME: this logic is different from other types. Ideally, it should also try to GetCommit to check if it exists repo.TreePath = strings.Join(parts[1:], "/") return parts[0] } - if len(parts) > 0 && parts[0] == headRefName { + if parts[0] == headRefName { // HEAD ref points to last default branch commit commit, err := repo.GitRepo.GetBranchCommit(repo.Repository.DefaultBranch) if err != nil { @@ -888,15 +885,21 @@ func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string { } return path default: - log.Error("Unrecognized path type: %v", path) + panic(fmt.Sprintf("Unrecognized path type: %v", pathType)) } return "" } +type RepoRefByTypeOptions struct { + IgnoreNotExistErr bool +} + // RepoRefByType handles repository reference name for a specific type // of repository reference -func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context) context.CancelFunc { +func RepoRefByType(detectRefType RepoRefType, opts ...RepoRefByTypeOptions) func(*Context) context.CancelFunc { + opt := util.OptionalArg(opts) return func(ctx *Context) (cancel context.CancelFunc) { + refType := detectRefType // Empty repository does not have reference information. if ctx.Repo.Repository.IsEmpty { // assume the user is viewing the (non-existent) default branch @@ -956,7 +959,12 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context } ctx.Repo.IsViewBranch = true } else { - refName = getRefName(ctx.Base, ctx.Repo, refType) + guessLegacyPath := refType == RepoRefUnknown + if guessLegacyPath { + refName, refType = getRefNameLegacy(ctx.Base, ctx.Repo) + } else { + refName = getRefName(ctx.Base, ctx.Repo, refType) + } ctx.Repo.RefName = refName isRenamedBranch, has := ctx.Data["IsRenamedBranch"].(bool) if isRenamedBranch && has { @@ -967,7 +975,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context return cancel } - if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) { + if refType == RepoRefBranch && ctx.Repo.GitRepo.IsBranchExist(refName) { ctx.Repo.IsViewBranch = true ctx.Repo.BranchName = refName @@ -977,7 +985,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context return cancel } ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() - } else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) { + } else if refType == RepoRefTag && ctx.Repo.GitRepo.IsTagExist(refName) { ctx.Repo.IsViewTag = true ctx.Repo.TagName = refName @@ -991,7 +999,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context return cancel } ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() - } else if len(refName) >= 7 && len(refName) <= ctx.Repo.GetObjectFormat().FullLength() { + } else if isStringLikelyCommitID(ctx.Repo.GetObjectFormat(), refName, 7) { ctx.Repo.IsViewCommit = true ctx.Repo.CommitID = refName @@ -1002,18 +1010,18 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context } // If short commit ID add canonical link header if len(refName) < ctx.Repo.GetObjectFormat().FullLength() { - ctx.RespHeader().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"", - util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), util.PathEscapeSegments(refName), url.PathEscape(ctx.Repo.Commit.ID.String()), 1)))) + canonicalURL := util.URLJoin(httplib.GuessCurrentAppURL(ctx), strings.Replace(ctx.Req.URL.RequestURI(), util.PathEscapeSegments(refName), url.PathEscape(ctx.Repo.Commit.ID.String()), 1)) + ctx.RespHeader().Set("Link", fmt.Sprintf(`<%s>; rel="canonical"`, canonicalURL)) } } else { - if len(ignoreNotExistErr) > 0 && ignoreNotExistErr[0] { + if opt.IgnoreNotExistErr { return cancel } ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName)) return cancel } - if refType == RepoRefLegacy { + if guessLegacyPath { // redirect from old URL scheme to new URL scheme prefix := strings.TrimPrefix(setting.AppSubURL+strings.ToLower(strings.TrimSuffix(ctx.Req.URL.Path, ctx.PathParam("*"))), strings.ToLower(ctx.Repo.RepoLink)) redirect := path.Join( diff --git a/services/convert/issue.go b/services/convert/issue.go index f514dc431351e..e3124efd6402e 100644 --- a/services/convert/issue.go +++ b/services/convert/issue.go @@ -260,7 +260,7 @@ func ToAPIMilestone(m *issues_model.Milestone) *api.Milestone { if m.IsClosed { apiMilestone.Closed = m.ClosedDateUnix.AsTimePtr() } - if m.DeadlineUnix.Year() < 9999 { + if m.DeadlineUnix > 0 { apiMilestone.Deadline = m.DeadlineUnix.AsTimePtr() } return apiMilestone diff --git a/templates/base/head_script.tmpl b/templates/base/head_script.tmpl index 22e08e9c8f69c..c0c7235e3b02e 100644 --- a/templates/base/head_script.tmpl +++ b/templates/base/head_script.tmpl @@ -21,10 +21,10 @@ If you introduce mistakes in it, Gitea JavaScript code wouldn't run correctly. {{if or .Participants .Assignees .MentionableTeams}} mentionValues: Array.from(new Map([ {{- range .Participants -}} - ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink $.Context}}'}], + ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink ctx}}'}], {{- end -}} {{- range .Assignees -}} - ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink $.Context}}'}], + ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink ctx}}'}], {{- end -}} {{- range .MentionableTeams -}} ['{{$.MentionableTeamsOrg}}/{{.Name}}', {key: '{{$.MentionableTeamsOrg}}/{{.Name}}', value: '{{$.MentionableTeamsOrg}}/{{.Name}}', name: '{{$.MentionableTeamsOrg}}/{{.Name}}', avatar: '{{$.MentionableTeamsOrgAvatar}}'}], diff --git a/templates/explore/repo_list.tmpl b/templates/explore/repo_list.tmpl index 742e83834d06f..219b1255c0a12 100644 --- a/templates/explore/repo_list.tmpl +++ b/templates/explore/repo_list.tmpl @@ -49,7 +49,7 @@ - {{$description := .DescriptionHTML $.Context}} + {{$description := .DescriptionHTML ctx}} {{if $description}}
{{$description}}
{{end}} diff --git a/templates/org/team/new.tmpl b/templates/org/team/new.tmpl index 9608eac154ef3..410a3c4b62fb7 100644 --- a/templates/org/team/new.tmpl +++ b/templates/org/team/new.tmpl @@ -99,17 +99,17 @@
- +
- +
- +
@@ -121,7 +121,7 @@ {{if lt $unit.MaxPerm 2}}
- + {{ctx.Locale.Tr $unit.DescKey}}
diff --git a/templates/org/team/sidebar.tmpl b/templates/org/team/sidebar.tmpl index ac41cda71641d..c4acd8da24568 100644 --- a/templates/org/team/sidebar.tmpl +++ b/templates/org/team/sidebar.tmpl @@ -61,11 +61,11 @@ {{if (not $unit.Type.UnitGlobalDisabled)}} {{ctx.Locale.Tr $unit.NameKey}} - {{if eq ($.Team.UnitAccessMode $.Context $unit.Type) 0 -}} + {{if eq ($.Team.UnitAccessMode ctx $unit.Type) 0 -}} {{ctx.Locale.Tr "org.teams.none_access"}} - {{- else if or (eq $.Team.ID 0) (eq ($.Team.UnitAccessMode $.Context $unit.Type) 1) -}} + {{- else if or (eq $.Team.ID 0) (eq ($.Team.UnitAccessMode ctx $unit.Type) 1) -}} {{ctx.Locale.Tr "org.teams.read_access"}} - {{- else if eq ($.Team.UnitAccessMode $.Context $unit.Type) 2 -}} + {{- else if eq ($.Team.UnitAccessMode ctx $unit.Type) 2 -}} {{ctx.Locale.Tr "org.teams.write_access"}} {{- end}} diff --git a/templates/package/content/cargo.tmpl b/templates/package/content/cargo.tmpl index 7fd88a284a296..8b51074af44f5 100644 --- a/templates/package/content/cargo.tmpl +++ b/templates/package/content/cargo.tmpl @@ -27,7 +27,7 @@ git-fetch-with-cli = true
{{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.Readme}}

{{ctx.Locale.Tr "packages.about"}}

{{if .PackageDescriptor.Metadata.Description}}
{{.PackageDescriptor.Metadata.Description}}
{{end}} - {{if .PackageDescriptor.Metadata.Readme}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}} + {{if .PackageDescriptor.Metadata.Readme}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}} {{end}} {{if .PackageDescriptor.Metadata.Dependencies}} diff --git a/templates/package/content/chef.tmpl b/templates/package/content/chef.tmpl index 03ce9f852bde8..b3713808f659b 100644 --- a/templates/package/content/chef.tmpl +++ b/templates/package/content/chef.tmpl @@ -20,7 +20,7 @@

{{ctx.Locale.Tr "packages.about"}}

{{if .PackageDescriptor.Metadata.Description}}

{{.PackageDescriptor.Metadata.Description}}

{{end}} - {{if .PackageDescriptor.Metadata.LongDescription}}{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.LongDescription}}{{end}} + {{if .PackageDescriptor.Metadata.LongDescription}}{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.LongDescription}}{{end}}
{{end}} diff --git a/templates/package/content/composer.tmpl b/templates/package/content/composer.tmpl index 8d48e6c95d5ee..45698208696ba 100644 --- a/templates/package/content/composer.tmpl +++ b/templates/package/content/composer.tmpl @@ -25,7 +25,7 @@ {{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.Comments}}

{{ctx.Locale.Tr "packages.about"}}

{{if .PackageDescriptor.Metadata.Description}}
{{.PackageDescriptor.Metadata.Description}}
{{end}} - {{if .PackageDescriptor.Metadata.Readme}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}} + {{if .PackageDescriptor.Metadata.Readme}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}} {{if .PackageDescriptor.Metadata.Comments}}
{{StringUtils.Join .PackageDescriptor.Metadata.Comments " "}}
{{end}} {{end}} diff --git a/templates/package/content/npm.tmpl b/templates/package/content/npm.tmpl index 01298a664c734..bb024348d07f3 100644 --- a/templates/package/content/npm.tmpl +++ b/templates/package/content/npm.tmpl @@ -25,7 +25,7 @@
{{if .PackageDescriptor.Metadata.Readme}}
- {{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}} + {{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{else if .PackageDescriptor.Metadata.Description}} {{.PackageDescriptor.Metadata.Description}} diff --git a/templates/package/content/nuget.tmpl b/templates/package/content/nuget.tmpl index f1fe420c0ba24..5bb98a86ddf9e 100644 --- a/templates/package/content/nuget.tmpl +++ b/templates/package/content/nuget.tmpl @@ -18,9 +18,9 @@ {{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.ReleaseNotes .PackageDescriptor.Metadata.Readme}}

{{ctx.Locale.Tr "packages.about"}}

- {{if .PackageDescriptor.Metadata.Description}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Description}}
{{end}} - {{if .PackageDescriptor.Metadata.Readme}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}} - {{if .PackageDescriptor.Metadata.ReleaseNotes}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.ReleaseNotes}}
{{end}} + {{if .PackageDescriptor.Metadata.Description}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Description}}
{{end}} + {{if .PackageDescriptor.Metadata.Readme}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}} + {{if .PackageDescriptor.Metadata.ReleaseNotes}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.ReleaseNotes}}
{{end}} {{end}} {{if .PackageDescriptor.Metadata.Dependencies}} diff --git a/templates/package/content/pub.tmpl b/templates/package/content/pub.tmpl index f2c7ac938faad..2f63cde3a639c 100644 --- a/templates/package/content/pub.tmpl +++ b/templates/package/content/pub.tmpl @@ -14,6 +14,6 @@ {{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.Readme}}

{{ctx.Locale.Tr "packages.about"}}

{{if .PackageDescriptor.Metadata.Description}}
{{.PackageDescriptor.Metadata.Description}}
{{end}} - {{if .PackageDescriptor.Metadata.Readme}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}} + {{if .PackageDescriptor.Metadata.Readme}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}} {{end}} {{end}} diff --git a/templates/package/content/pypi.tmpl b/templates/package/content/pypi.tmpl index 817fced97b960..2a22a6ed71ba6 100644 --- a/templates/package/content/pypi.tmpl +++ b/templates/package/content/pypi.tmpl @@ -16,9 +16,9 @@

{{if .PackageDescriptor.Metadata.Summary}}{{.PackageDescriptor.Metadata.Summary}}{{end}}

{{if .PackageDescriptor.Metadata.LongDescription}} - {{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.LongDescription}} + {{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.LongDescription}} {{else if .PackageDescriptor.Metadata.Description}} - {{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Description}} + {{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Description}} {{end}}
{{end}} diff --git a/templates/projects/view.tmpl b/templates/projects/view.tmpl index f5c1bb76703c4..71f9d059adb9b 100644 --- a/templates/projects/view.tmpl +++ b/templates/projects/view.tmpl @@ -49,7 +49,7 @@ {{svg "octicon-check"}} {{end}} {{end}} - {{RenderLabel $.Context ctx.Locale .}} + {{ctx.RenderUtils.RenderLabel .}}

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

{{end}} diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl index 6e2a5570c712a..5484024ff8197 100644 --- a/templates/repo/branch/list.tmpl +++ b/templates/repo/branch/list.tmpl @@ -27,7 +27,7 @@ {{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DefaultBranchBranch.DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DefaultBranchBranch.DBBranch.CommitID)}}
-

{{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DefaultBranchBranch.DBBranch.CommitMessage (.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DefaultBranchBranch.DBBranch.CommitTime}}{{if .DefaultBranchBranch.DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}

+

{{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}} · {{ctx.RenderUtils.RenderCommitMessage .DefaultBranchBranch.DBBranch.CommitMessage (.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DefaultBranchBranch.DBBranch.CommitTime}}{{if .DefaultBranchBranch.DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}

{{if and $.IsWriter (not $.Repository.IsArchived) (not .IsDeleted)}} @@ -102,7 +102,7 @@ {{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DBBranch.CommitID)}} -

{{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DBBranch.CommitMessage ($.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DBBranch.CommitTime}}{{if .DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}}  {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}

+

{{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DBBranch.CommitID}} · {{ctx.RenderUtils.RenderCommitMessage .DBBranch.CommitMessage ($.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DBBranch.CommitTime}}{{if .DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}}  {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}

{{end}} diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl index 975d57324543a..b9d71917a1d1c 100644 --- a/templates/repo/commit_page.tmpl +++ b/templates/repo/commit_page.tmpl @@ -19,7 +19,7 @@ {{end}}
-

{{RenderCommitMessage $.Context .Commit.Message ($.Repository.ComposeMetas ctx)}}{{template "repo/commit_statuses" dict "Status" .CommitStatus "Statuses" .CommitStatuses}}

+

{{ctx.RenderUtils.RenderCommitMessage .Commit.Message ($.Repository.ComposeMetas ctx)}}{{template "repo/commit_statuses" dict "Status" .CommitStatus "Statuses" .CommitStatuses}}

{{if not $.PageIsWiki}} {{if IsMultilineCommitMessage .Commit.Message}} -
{{RenderCommitBody $.Context .Commit.Message ($.Repository.ComposeMetas ctx)}}
+
{{ctx.RenderUtils.RenderCommitBody .Commit.Message ($.Repository.ComposeMetas ctx)}}
{{end}} {{template "repo/commit_load_branches_and_tags" .}}
diff --git a/templates/repo/commits_list.tmpl b/templates/repo/commits_list.tmpl index b8d10eb1aa454..50b754cc234b6 100644 --- a/templates/repo/commits_list.tmpl +++ b/templates/repo/commits_list.tmpl @@ -59,10 +59,10 @@ {{if $.PageIsWiki}} - {{.Summary | RenderEmoji $.Context}} + {{.Summary | ctx.RenderUtils.RenderEmoji}} {{else}} {{$commitLink:= printf "%s/commit/%s" $commitRepoLink (PathEscape .ID.String)}} - {{RenderCommitMessageLinkSubject $.Context .Message $commitLink ($.Repository.ComposeMetas ctx)}} + {{ctx.RenderUtils.RenderCommitMessageLinkSubject .Message $commitLink ($.Repository.ComposeMetas ctx)}} {{end}} {{if IsMultilineCommitMessage .Message}} @@ -70,7 +70,7 @@ {{end}} {{template "repo/commit_statuses" dict "Status" .Status "Statuses" .Statuses}} {{if IsMultilineCommitMessage .Message}} -
{{RenderCommitBody $.Context .Message ($.Repository.ComposeMetas ctx)}}
+
{{ctx.RenderUtils.RenderCommitBody .Message ($.Repository.ComposeMetas ctx)}}
{{end}} {{if $.CommitsTagsMap}} {{range (index $.CommitsTagsMap .ID.String)}} diff --git a/templates/repo/commits_list_small.tmpl b/templates/repo/commits_list_small.tmpl index 4c67319b8c05a..0657eaba1d3bd 100644 --- a/templates/repo/commits_list_small.tmpl +++ b/templates/repo/commits_list_small.tmpl @@ -14,7 +14,7 @@ {{$commitLink:= printf "%s/commit/%s" $.comment.Issue.PullRequest.BaseRepo.Link (PathEscape .ID.String)}} - {{- RenderCommitMessageLinkSubject $.root.Context .Message $commitLink ($.comment.Issue.PullRequest.BaseRepo.ComposeMetas ctx) -}} + {{- ctx.RenderUtils.RenderCommitMessageLinkSubject .Message $commitLink ($.comment.Issue.PullRequest.BaseRepo.ComposeMetas ctx) -}} {{if IsMultilineCommitMessage .Message}} @@ -48,7 +48,7 @@
{{if IsMultilineCommitMessage .Message}}
-		{{- RenderCommitBody $.root.Context .Message ($.comment.Issue.PullRequest.BaseRepo.ComposeMetas ctx) -}}
+		{{- ctx.RenderUtils.RenderCommitBody .Message ($.comment.Issue.PullRequest.BaseRepo.ComposeMetas ctx) -}}
 	
{{end}} {{end}} diff --git a/templates/repo/diff/compare.tmpl b/templates/repo/diff/compare.tmpl index 5ac6013ed50c2..28419a34628b1 100644 --- a/templates/repo/diff/compare.tmpl +++ b/templates/repo/diff/compare.tmpl @@ -187,7 +187,7 @@
{{template "shared/issueicon" .}}
- {{RenderIssueTitle $.Context .PullRequest.Issue.Title ($.Repository.ComposeMetas ctx) | RenderCodeBlock}} + {{ctx.RenderUtils.RenderIssueTitle .PullRequest.Issue.Title ($.Repository.ComposeMetas ctx) | RenderCodeBlock}} #{{.PullRequest.Issue.Index}}
diff --git a/templates/repo/graph/commits.tmpl b/templates/repo/graph/commits.tmpl index 1691fb8d45084..f1d0e62330274 100644 --- a/templates/repo/graph/commits.tmpl +++ b/templates/repo/graph/commits.tmpl @@ -29,7 +29,7 @@ - {{RenderCommitMessage $.Context $commit.Subject ($.Repository.ComposeMetas ctx)}} + {{ctx.RenderUtils.RenderCommitMessage $commit.Subject ($.Repository.ComposeMetas ctx)}} {{range $commit.Refs}} @@ -37,7 +37,7 @@ {{if eq $refGroup "pull"}} {{if or (not $.HidePRRefs) (SliceUtils.Contains $.SelectedBranches .Name)}} - + {{svg "octicon-git-pull-request"}} #{{.ShortName}} {{end}} @@ -56,7 +56,7 @@ {{end}} {{end}} - + {{$userName := $commit.Commit.Author.Name}} {{if $commit.User}} {{if and $commit.User.FullName DefaultShowFullName}} diff --git a/templates/repo/header.tmpl b/templates/repo/header.tmpl index b023b28b62475..c3ae697f31fbf 100644 --- a/templates/repo/header.tmpl +++ b/templates/repo/header.tmpl @@ -177,7 +177,7 @@ {{end}} - {{$projectsUnit := .Repository.MustGetUnit $.Context ctx.Consts.RepoUnitTypeProjects}} + {{$projectsUnit := .Repository.MustGetUnit ctx ctx.Consts.RepoUnitTypeProjects}} {{if and (not ctx.Consts.RepoUnitTypeProjects.UnitGlobalDisabled) (.Permission.CanRead ctx.Consts.RepoUnitTypeProjects) ($projectsUnit.ProjectsConfig.IsProjectsAllowed "repo")}} {{svg "octicon-project"}} {{ctx.Locale.Tr "repo.projects"}} @@ -203,7 +203,7 @@ {{end}} {{if .Permission.CanRead ctx.Consts.RepoUnitTypeExternalWiki}} - + {{svg "octicon-link-external"}} {{ctx.Locale.Tr "repo.wiki"}} {{end}} diff --git a/templates/repo/issue/card.tmpl b/templates/repo/issue/card.tmpl index 916d52446b4ef..6c24419b467a3 100644 --- a/templates/repo/issue/card.tmpl +++ b/templates/repo/issue/card.tmpl @@ -14,7 +14,7 @@
{{template "shared/issueicon" .}}
- {{.Title | RenderEmoji ctx | RenderCodeBlock}} + {{.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{if and $.isPinnedIssueCard $.Page.IsRepoAdmin}} {{svg "octicon-x" 16}} @@ -65,7 +65,7 @@
diff --git a/templates/repo/issue/fields/checkboxes.tmpl b/templates/repo/issue/fields/checkboxes.tmpl index 531f401fb7ca6..6134c326b6b43 100644 --- a/templates/repo/issue/fields/checkboxes.tmpl +++ b/templates/repo/issue/fields/checkboxes.tmpl @@ -4,7 +4,7 @@
- +
{{if $opt.required}} diff --git a/templates/repo/issue/fields/header.tmpl b/templates/repo/issue/fields/header.tmpl index 06c41af6b9902..bcd0ffbd350e9 100644 --- a/templates/repo/issue/fields/header.tmpl +++ b/templates/repo/issue/fields/header.tmpl @@ -2,5 +2,5 @@

{{.item.Attributes.label}}{{if .item.Validations.required}}{{end}}

{{end}} {{if .item.Attributes.description}} - {{RenderMarkdownToHtml .Context .item.Attributes.description}} + {{ctx.RenderUtils.MarkdownToHtml .item.Attributes.description}} {{end}} diff --git a/templates/repo/issue/fields/markdown.tmpl b/templates/repo/issue/fields/markdown.tmpl index 934699ed058ce..f6995328dd4d8 100644 --- a/templates/repo/issue/fields/markdown.tmpl +++ b/templates/repo/issue/fields/markdown.tmpl @@ -1,3 +1,3 @@
-
{{RenderMarkdownToHtml .Context .item.Attributes.value}}
+
{{ctx.RenderUtils.MarkdownToHtml .item.Attributes.value}}
diff --git a/templates/repo/issue/filter_actions.tmpl b/templates/repo/issue/filter_actions.tmpl index 831ab17bea2c6..4cdad7a7480df 100644 --- a/templates/repo/issue/filter_actions.tmpl +++ b/templates/repo/issue/filter_actions.tmpl @@ -30,7 +30,7 @@ {{end}} {{$previousExclusiveScope = $exclusiveScope}}
- {{if SliceUtils.Contains $.SelLabelIDs .ID}}{{svg (Iif $exclusiveScope "octicon-dot-fill" "octicon-check")}}{{end}} {{RenderLabel $.Context ctx.Locale .}} + {{if SliceUtils.Contains $.SelLabelIDs .ID}}{{svg (Iif $exclusiveScope "octicon-dot-fill" "octicon-check")}}{{end}} {{ctx.RenderUtils.RenderLabel .}} {{template "repo/issue/labels/label_archived" .}}
{{end}} diff --git a/templates/repo/issue/filter_list.tmpl b/templates/repo/issue/filter_list.tmpl index c6de4977dc5dd..d48af5b1506f8 100644 --- a/templates/repo/issue/filter_list.tmpl +++ b/templates/repo/issue/filter_list.tmpl @@ -42,7 +42,7 @@ {{svg "octicon-check"}} {{end}} {{end}} - {{RenderLabel $.Context ctx.Locale .}} + {{ctx.RenderUtils.RenderLabel .}}

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

{{end}} diff --git a/templates/repo/issue/labels/label.tmpl b/templates/repo/issue/labels/label.tmpl index 3651ba118feea..f40c792da706e 100644 --- a/templates/repo/issue/labels/label.tmpl +++ b/templates/repo/issue/labels/label.tmpl @@ -3,5 +3,5 @@ id="label_{{.label.ID}}" href="{{.root.RepoLink}}/{{if or .root.IsPull .root.Issue.IsPull}}pulls{{else}}issues{{end}}?labels={{.label.ID}}"{{/* FIXME: use .root.Issue.Link or create .root.Link */}} > - {{- RenderLabel $.Context ctx.Locale .label -}} + {{- ctx.RenderUtils.RenderLabel .label -}} diff --git a/templates/repo/issue/labels/label_list.tmpl b/templates/repo/issue/labels/label_list.tmpl index 413d6405b22d2..07a548a8afd05 100644 --- a/templates/repo/issue/labels/label_list.tmpl +++ b/templates/repo/issue/labels/label_list.tmpl @@ -30,8 +30,8 @@ {{range .Labels}}
  • - {{RenderLabel $.Context ctx.Locale .}} - {{if .Description}}
    {{.Description | RenderEmoji $.Context}}{{end}} + {{ctx.RenderUtils.RenderLabel .}} + {{if .Description}}
    {{.Description | ctx.RenderUtils.RenderEmoji}}{{end}}
    {{if $.PageIsOrgSettingsLabels}} @@ -70,8 +70,8 @@ {{range .OrgLabels}}
  • - {{RenderLabel $.Context ctx.Locale .}} - {{if .Description}}
    {{.Description | RenderEmoji $.Context}}{{end}} + {{ctx.RenderUtils.RenderLabel .}} + {{if .Description}}
    {{.Description | ctx.RenderUtils.RenderEmoji}}{{end}}
    {{svg "octicon-issue-opened"}} {{ctx.Locale.Tr "repo.issues.label_open_issues" .NumOpenRepoIssues}} diff --git a/templates/repo/issue/labels/labels_selector_field.tmpl b/templates/repo/issue/labels/labels_selector_field.tmpl index 3d65a7d8cd542..96fb65866401e 100644 --- a/templates/repo/issue/labels/labels_selector_field.tmpl +++ b/templates/repo/issue/labels/labels_selector_field.tmpl @@ -21,8 +21,8 @@
    {{end}} {{$previousExclusiveScope = $exclusiveScope}} - {{svg (Iif $exclusiveScope "octicon-dot-fill" "octicon-check")}}  {{RenderLabel $.Context ctx.Locale .}} - {{if .Description}}
    {{.Description | RenderEmoji $.Context}}{{end}} +
    {{svg (Iif $exclusiveScope "octicon-dot-fill" "octicon-check")}}  {{ctx.RenderUtils.RenderLabel .}} + {{if .Description}}
    {{.Description | ctx.RenderUtils.RenderEmoji}}{{end}}

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

    {{end}} @@ -34,8 +34,8 @@
    {{end}} {{$previousExclusiveScope = $exclusiveScope}} - {{svg (Iif $exclusiveScope "octicon-dot-fill" "octicon-check")}}  {{RenderLabel $.Context ctx.Locale .}} - {{if .Description}}
    {{.Description | RenderEmoji $.Context}}{{end}} +
    {{svg (Iif $exclusiveScope "octicon-dot-fill" "octicon-check")}}  {{ctx.RenderUtils.RenderLabel .}} + {{if .Description}}
    {{.Description | ctx.RenderUtils.RenderEmoji}}{{end}}

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

    {{end}} diff --git a/templates/repo/issue/milestone_new.tmpl b/templates/repo/issue/milestone_new.tmpl index 9f32df00e39f0..736a75d73a1b3 100644 --- a/templates/repo/issue/milestone_new.tmpl +++ b/templates/repo/issue/milestone_new.tmpl @@ -30,9 +30,9 @@
    - +
    diff --git a/templates/repo/issue/new_form.tmpl b/templates/repo/issue/new_form.tmpl index e56d1b9ecc7bd..6f1bebc0329a9 100644 --- a/templates/repo/issue/new_form.tmpl +++ b/templates/repo/issue/new_form.tmpl @@ -18,15 +18,15 @@ {{range .Fields}} {{if eq .Type "input"}} - {{template "repo/issue/fields/input" dict "Context" $.Context "item" .}} + {{template "repo/issue/fields/input" "item" .}} {{else if eq .Type "markdown"}} - {{template "repo/issue/fields/markdown" dict "Context" $.Context "item" .}} + {{template "repo/issue/fields/markdown" "item" .}} {{else if eq .Type "textarea"}} - {{template "repo/issue/fields/textarea" dict "Context" $.Context "item" . "root" $}} + {{template "repo/issue/fields/textarea" "item" . "root" $}} {{else if eq .Type "dropdown"}} - {{template "repo/issue/fields/dropdown" dict "Context" $.Context "item" .}} + {{template "repo/issue/fields/dropdown" "item" .}} {{else if eq .Type "checkboxes"}} - {{template "repo/issue/fields/checkboxes" dict "Context" $.Context "item" .}} + {{template "repo/issue/fields/checkboxes" "item" .}} {{end}} {{end}} {{else}} diff --git a/templates/repo/issue/view_content/comments.tmpl b/templates/repo/issue/view_content/comments.tmpl index f42968ca9272a..30475331544cf 100644 --- a/templates/repo/issue/view_content/comments.tmpl +++ b/templates/repo/issue/view_content/comments.tmpl @@ -173,11 +173,11 @@ {{template "shared/user/authorlink" .Poster}} {{if and .AddedLabels (not .RemovedLabels)}} - {{ctx.Locale.TrN (len .AddedLabels) "repo.issues.add_label" "repo.issues.add_labels" (RenderLabels ctx ctx.Locale .AddedLabels $.RepoLink .Issue) $createdStr}} + {{ctx.Locale.TrN (len .AddedLabels) "repo.issues.add_label" "repo.issues.add_labels" (ctx.RenderUtils.RenderLabels .AddedLabels $.RepoLink .Issue) $createdStr}} {{else if and (not .AddedLabels) .RemovedLabels}} - {{ctx.Locale.TrN (len .RemovedLabels) "repo.issues.remove_label" "repo.issues.remove_labels" (RenderLabels ctx ctx.Locale .RemovedLabels $.RepoLink .Issue) $createdStr}} + {{ctx.Locale.TrN (len .RemovedLabels) "repo.issues.remove_label" "repo.issues.remove_labels" (ctx.RenderUtils.RenderLabels .RemovedLabels $.RepoLink .Issue) $createdStr}} {{else}} - {{ctx.Locale.Tr "repo.issues.add_remove_labels" (RenderLabels ctx ctx.Locale .AddedLabels $.RepoLink .Issue) (RenderLabels ctx ctx.Locale .RemovedLabels $.RepoLink .Issue) $createdStr}} + {{ctx.Locale.Tr "repo.issues.add_remove_labels" (ctx.RenderUtils.RenderLabels .AddedLabels $.RepoLink .Issue) (ctx.RenderUtils.RenderLabels .RemovedLabels $.RepoLink .Issue) $createdStr}} {{end}}
    @@ -222,7 +222,7 @@ {{template "shared/user/avatarlink" dict "user" .Poster}} {{template "shared/user/authorlink" .Poster}} - {{ctx.Locale.Tr "repo.issues.change_title_at" (.OldTitle|RenderEmoji $.Context) (.NewTitle|RenderEmoji $.Context) $createdStr}} + {{ctx.Locale.Tr "repo.issues.change_title_at" (.OldTitle|ctx.RenderUtils.RenderEmoji) (.NewTitle|ctx.RenderUtils.RenderEmoji) $createdStr}}
    {{else if eq .Type 11}} @@ -626,7 +626,7 @@
    - + {{svg "octicon-x" 16}} diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 08f9c63a290c9..d117bfbc51a63 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -202,7 +202,7 @@ {{end}} {{if .AllowMerge}} {{/* user is allowed to merge */}} - {{$prUnit := .Repository.MustGetUnit $.Context ctx.Consts.RepoUnitTypePullRequests}} + {{$prUnit := .Repository.MustGetUnit ctx ctx.Consts.RepoUnitTypePullRequests}} {{if or $prUnit.PullRequestsConfig.AllowMerge $prUnit.PullRequestsConfig.AllowRebase $prUnit.PullRequestsConfig.AllowRebaseMerge $prUnit.PullRequestsConfig.AllowSquash $prUnit.PullRequestsConfig.AllowFastForwardOnly}} {{$hasPendingPullRequestMergeTip := ""}} {{if .HasPendingPullRequestMerge}} diff --git a/templates/repo/issue/view_content/sidebar.tmpl b/templates/repo/issue/view_content/sidebar.tmpl index c168e98785eda..9c1acae0cfb0e 100644 --- a/templates/repo/issue/view_content/sidebar.tmpl +++ b/templates/repo/issue/view_content/sidebar.tmpl @@ -280,7 +280,7 @@
    {{end}} - {{if .Repository.IsTimetrackerEnabled $.Context}} + {{if .Repository.IsTimetrackerEnabled ctx}} {{if and .CanUseTimetracker (not .Repository.IsArchived)}}
    @@ -358,48 +358,35 @@
    {{ctx.Locale.Tr "repo.issues.due_date"}} -
    -
    - {{svg "octicon-x" 16 "close icon"}} - {{ctx.Locale.Tr "repo.issues.due_date_invalid"}} -
    - {{if ne .Issue.DeadlineUnix 0}} -

    -

    -
    - {{svg "octicon-calendar" 16 "tw-mr-2"}} - {{DateUtils.AbsoluteLong .Issue.DeadlineUnix}} -
    -
    - {{if and .HasIssuesOrPullsWritePermission (not .Repository.IsArchived)}} - {{svg "octicon-pencil" 16 "tw-mr-1"}} - {{svg "octicon-trash"}} - {{end}} -
    +
    + {{if .Issue.DeadlineUnix}} +
    +
    + {{svg "octicon-calendar"}} {{DateUtils.AbsoluteLong .Issue.DeadlineUnix}} +
    +
    + {{if and .HasIssuesOrPullsWritePermission (not .Repository.IsArchived)}} + {{svg "octicon-pencil"}} + {{svg "octicon-trash"}} + {{end}}
    -

    +
    {{else}} -

    {{ctx.Locale.Tr "repo.issues.due_date_not_set"}}

    + {{ctx.Locale.Tr "repo.issues.due_date_not_set"}} {{end}} {{if and .HasIssuesOrPullsWritePermission (not .Repository.IsArchived)}} -
    -
    - {{$.CsrfTokenHtml}} - - -
    -
    +
    + {{$.CsrfTokenHtml}} + + +
    {{end}}
    - {{if .Repository.IsDependenciesEnabled $.Context}} + {{if .Repository.IsDependenciesEnabled ctx}}
    @@ -423,8 +410,8 @@ {{range .BlockingDependencies}}
    - - #{{.Issue.Index}} {{.Issue.Title | RenderEmoji $.Context}} + + #{{.Issue.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji}}
    {{.Repository.OwnerName}}/{{.Repository.Name}} @@ -455,8 +442,8 @@ {{range .BlockedByDependencies}}
    - - #{{.Issue.Index}} {{.Issue.Title | RenderEmoji $.Context}} + + #{{.Issue.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji}}
    {{.Repository.OwnerName}}/{{.Repository.Name}} @@ -477,8 +464,8 @@
    {{svg "octicon-lock" 16}} - - #{{.Issue.Index}} {{.Issue.Title | RenderEmoji $.Context}} + + #{{.Issue.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji}}
    diff --git a/templates/repo/issue/view_title.tmpl b/templates/repo/issue/view_title.tmpl index 45c19d1977983..0f796ce9bf754 100644 --- a/templates/repo/issue/view_title.tmpl +++ b/templates/repo/issue/view_title.tmpl @@ -7,7 +7,7 @@ {{$canEditIssueTitle := and (or .HasIssuesOrPullsWritePermission .IsIssuePoster) (not .Repository.IsArchived)}}

    - {{RenderIssueTitle $.Context .Issue.Title ($.Repository.ComposeMetas ctx) | RenderCodeBlock}} + {{ctx.RenderUtils.RenderIssueTitle .Issue.Title ($.Repository.ComposeMetas ctx) | RenderCodeBlock}} #{{.Issue.Index}}

    diff --git a/templates/repo/latest_commit.tmpl b/templates/repo/latest_commit.tmpl index 8bacb427bf324..9d718d7197a41 100644 --- a/templates/repo/latest_commit.tmpl +++ b/templates/repo/latest_commit.tmpl @@ -22,10 +22,10 @@ {{template "repo/commit_statuses" dict "Status" .LatestCommitStatus "Statuses" .LatestCommitStatuses}} {{$commitLink:= printf "%s/commit/%s" .RepoLink (PathEscape .LatestCommit.ID.String)}} - {{RenderCommitMessageLinkSubject $.Context .LatestCommit.Message $commitLink ($.Repository.ComposeMetas ctx)}} + {{ctx.RenderUtils.RenderCommitMessageLinkSubject .LatestCommit.Message $commitLink ($.Repository.ComposeMetas ctx)}} {{if IsMultilineCommitMessage .LatestCommit.Message}} -
    {{RenderCommitBody $.Context .LatestCommit.Message ($.Repository.ComposeMetas ctx)}}
    +
    {{ctx.RenderUtils.RenderCommitBody .LatestCommit.Message ($.Repository.ComposeMetas ctx)}}
    {{end}}
    {{end}} diff --git a/templates/repo/pulse.tmpl b/templates/repo/pulse.tmpl index 5a75740573cd9..1d7923b2f2f7f 100644 --- a/templates/repo/pulse.tmpl +++ b/templates/repo/pulse.tmpl @@ -125,7 +125,7 @@ {{ctx.Locale.Tr "repo.activity.published_release_label"}} {{.TagName}} {{if not .IsTag}} - {{.Title | RenderEmoji $.Context | RenderCodeBlock}} + {{.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{end}} {{DateUtils.TimeSince .CreatedUnix}}

    @@ -145,7 +145,7 @@ {{range .Activity.MergedPRs}}

    {{ctx.Locale.Tr "repo.activity.merged_prs_label"}} - #{{.Index}} {{.Issue.Title | RenderEmoji $.Context | RenderCodeBlock}} + #{{.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{DateUtils.TimeSince .MergedUnix}}

    {{end}} @@ -164,7 +164,7 @@ {{range .Activity.OpenedPRs}}

    {{ctx.Locale.Tr "repo.activity.opened_prs_label"}} - #{{.Index}} {{.Issue.Title | RenderEmoji $.Context | RenderCodeBlock}} + #{{.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{DateUtils.TimeSince .Issue.CreatedUnix}}

    {{end}} @@ -183,7 +183,7 @@ {{range .Activity.ClosedIssues}}

    {{ctx.Locale.Tr "repo.activity.closed_issue_label"}} - #{{.Index}} {{.Title | RenderEmoji $.Context | RenderCodeBlock}} + #{{.Index}} {{.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{DateUtils.TimeSince .ClosedUnix}}

    {{end}} @@ -202,7 +202,7 @@ {{range .Activity.OpenedIssues}}

    {{ctx.Locale.Tr "repo.activity.new_issue_label"}} - #{{.Index}} {{.Title | RenderEmoji $.Context | RenderCodeBlock}} + #{{.Index}} {{.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{DateUtils.TimeSince .CreatedUnix}}

    {{end}} @@ -220,9 +220,9 @@ {{ctx.Locale.Tr "repo.activity.unresolved_conv_label"}} #{{.Index}} {{if .IsPull}} - {{.Title | RenderEmoji $.Context | RenderCodeBlock}} + {{.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{else}} - {{.Title | RenderEmoji $.Context | RenderCodeBlock}} + {{.Title | ctx.RenderUtils.RenderEmoji | RenderCodeBlock}} {{end}} {{DateUtils.TimeSince .UpdatedUnix}}

    diff --git a/templates/repo/settings/collaboration.tmpl b/templates/repo/settings/collaboration.tmpl index dcf070f6ac491..9f90f0a2b9614 100644 --- a/templates/repo/settings/collaboration.tmpl +++ b/templates/repo/settings/collaboration.tmpl @@ -69,7 +69,7 @@ {{if or (eq .AccessMode 1) (eq .AccessMode 2)}} {{$first := true}}
    - Sections: {{range $u, $unit := $.Units}}{{if and ($.Repo.UnitEnabled $.Context $unit.Type) ($team.UnitEnabled $.Context $unit.Type)}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{ctx.Locale.Tr $unit.NameKey}}{{end}}{{end}} {{if $first}}None{{end}} + Sections: {{range $u, $unit := $.Units}}{{if and ($.Repo.UnitEnabled ctx $unit.Type) ($team.UnitEnabled ctx $unit.Type)}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{ctx.Locale.Tr $unit.NameKey}}{{end}}{{end}} {{if $first}}None{{end}}
    {{end}}
    diff --git a/templates/repo/settings/lfs_file_find.tmpl b/templates/repo/settings/lfs_file_find.tmpl index 4c6943618e430..59f1bb10cfdcf 100644 --- a/templates/repo/settings/lfs_file_find.tmpl +++ b/templates/repo/settings/lfs_file_find.tmpl @@ -15,7 +15,7 @@ - {{.Summary | RenderEmoji $.Context}} + {{.Summary | ctx.RenderUtils.RenderEmoji}} diff --git a/templates/repo/settings/navbar.tmpl b/templates/repo/settings/navbar.tmpl index e46273aff055f..3e127ccbb3517 100644 --- a/templates/repo/settings/navbar.tmpl +++ b/templates/repo/settings/navbar.tmpl @@ -12,7 +12,7 @@ {{ctx.Locale.Tr "repo.settings.hooks"}} {{end}} - {{if .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeCode}} + {{if .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeCode}} {{ctx.Locale.Tr "repo.settings.branches"}} diff --git a/templates/repo/settings/options.tmpl b/templates/repo/settings/options.tmpl index 6fc994ce9b2fd..1a7884bde29e0 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -53,7 +53,7 @@ {{/* These variables exist to make the logic in the Settings window easier to comprehend and are not used later on. */}} {{$newMirrorsPartiallyEnabled := or (not .DisableNewPullMirrors) (not .DisableNewPushMirrors)}} {{/* .Repository.IsMirror is not always reliable if the repository is not actively acting as a mirror because of errors. */}} - {{$showMirrorSettings := and (.Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeCode) (or $newMirrorsPartiallyEnabled .Repository.IsMirror .PullMirror .PushMirrors)}} + {{$showMirrorSettings := and (.Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeCode) (or $newMirrorsPartiallyEnabled .Repository.IsMirror .PullMirror .PushMirrors)}} {{$newMirrorsEntirelyEnabled := and (not .DisableNewPullMirrors) (not .DisableNewPushMirrors)}} {{$onlyNewPushMirrorsEnabled := and (not .DisableNewPushMirrors) .DisableNewPullMirrors}} {{$onlyNewPullMirrorsEnabled := and .DisableNewPushMirrors (not .DisableNewPullMirrors)}} @@ -143,7 +143,7 @@
    - {{$address := MirrorRemoteAddress $.Context .Repository .PullMirror.GetRemoteName}} + {{$address := MirrorRemoteAddress ctx .Repository .PullMirror.GetRemoteName}}
    @@ -294,7 +294,7 @@ {{.CsrfTokenHtml}} - {{$isCodeEnabled := .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeCode}} + {{$isCodeEnabled := .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeCode}} {{$isCodeGlobalDisabled := ctx.Consts.RepoUnitTypeCode.UnitGlobalDisabled}}
    @@ -348,14 +348,14 @@
    - +

    {{ctx.Locale.Tr "repo.settings.external_wiki_url_desc"}}

    - {{$isIssuesEnabled := or (.Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeIssues) (.Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeExternalTracker)}} + {{$isIssuesEnabled := or (.Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeIssues) (.Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeExternalTracker)}} {{$isIssuesGlobalDisabled := ctx.Consts.RepoUnitTypeIssues.UnitGlobalDisabled}} {{$isExternalTrackerGlobalDisabled := ctx.Consts.RepoUnitTypeExternalTracker.UnitGlobalDisabled}} {{$isIssuesAndExternalGlobalDisabled := and $isIssuesGlobalDisabled $isExternalTrackerGlobalDisabled}} @@ -369,28 +369,28 @@
    - +
    -
    +
    {{if .Repository.CanEnableTimetracker}}
    - +
    -
    +
    - +
    {{end}}
    - +
    @@ -401,26 +401,26 @@
    - +
    -
    +
    - +

    {{ctx.Locale.Tr "repo.settings.external_tracker_url_desc"}}

    - +

    {{ctx.Locale.Tr "repo.settings.tracker_url_format_desc"}}

    - {{$externalTracker := (.Repository.MustGetUnit $.Context ctx.Consts.RepoUnitTypeExternalTracker)}} + {{$externalTracker := (.Repository.MustGetUnit ctx ctx.Consts.RepoUnitTypeExternalTracker)}} {{$externalTrackerStyle := $externalTracker.ExternalTrackerConfig.ExternalTrackerStyle}} @@ -441,7 +441,7 @@
    - +

    {{ctx.Locale.Tr "repo.settings.tracker_issue_style.regexp_pattern_desc"}}

    @@ -449,9 +449,9 @@
    - {{$isProjectsEnabled := .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeProjects}} + {{$isProjectsEnabled := .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeProjects}} {{$isProjectsGlobalDisabled := ctx.Consts.RepoUnitTypeProjects.UnitGlobalDisabled}} - {{$projectsUnit := .Repository.MustGetUnit $.Context ctx.Consts.RepoUnitTypeProjects}} + {{$projectsUnit := .Repository.MustGetUnit ctx ctx.Consts.RepoUnitTypeProjects}}
    @@ -491,7 +491,7 @@
    - {{$isReleasesEnabled := .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeReleases}} + {{$isReleasesEnabled := .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeReleases}} {{$isReleasesGlobalDisabled := ctx.Consts.RepoUnitTypeReleases.UnitGlobalDisabled}}
    @@ -501,7 +501,7 @@
    - {{$isPackagesEnabled := .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypePackages}} + {{$isPackagesEnabled := .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypePackages}} {{$isPackagesGlobalDisabled := ctx.Consts.RepoUnitTypePackages.UnitGlobalDisabled}}
    @@ -512,7 +512,7 @@
    {{if .EnableActions}} - {{$isActionsEnabled := .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeActions}} + {{$isActionsEnabled := .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeActions}} {{$isActionsGlobalDisabled := ctx.Consts.RepoUnitTypeActions.UnitGlobalDisabled}}
    @@ -525,9 +525,9 @@ {{if not .IsMirror}}
    - {{$pullRequestEnabled := .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypePullRequests}} + {{$pullRequestEnabled := .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypePullRequests}} {{$pullRequestGlobalDisabled := ctx.Consts.RepoUnitTypePullRequests.UnitGlobalDisabled}} - {{$prUnit := .Repository.MustGetUnit $.Context ctx.Consts.RepoUnitTypePullRequests}} + {{$prUnit := .Repository.MustGetUnit ctx ctx.Consts.RepoUnitTypePullRequests}}
    @@ -1048,7 +1048,7 @@
    {{end}} - {{if .Repository.UnitEnabled $.Context ctx.Consts.RepoUnitTypeWiki}} + {{if .Repository.UnitEnabled ctx ctx.Consts.RepoUnitTypeWiki}}