]> source.dussan.org Git - gitea.git/commitdiff
Replace DateTime with proper functions (#32402)
authorwxiaoguang <wxiaoguang@gmail.com>
Sat, 2 Nov 2024 21:04:53 +0000 (05:04 +0800)
committerGitHub <noreply@github.com>
Sat, 2 Nov 2024 21:04:53 +0000 (21:04 +0000)
Follow #32383

This PR cleans up the "Deadline" usages in templates, make them call
`ParseLegacy` first to get a `Time` struct then display by `DateUtils`.

Now it should be pretty clear how "deadline string" works, it makes it
possible to do further refactoring and correcting.

modules/templates/helper.go
modules/templates/util_date.go
modules/templates/util_date_test.go [new file with mode: 0644]
modules/timeutil/datetime.go
modules/timeutil/datetime_test.go [deleted file]
templates/repo/issue/milestone_issues.tmpl
templates/repo/issue/milestones.tmpl
templates/repo/issue/view_content/comments.tmpl
templates/user/dashboard/milestones.tmpl

index 5038e8a1327b9d79026b6919b4431a1cd824e0b3..a5168541d8b01be2fe384efe9452ff8c0c588284 100644 (file)
@@ -54,7 +54,7 @@ func NewFuncMap() template.FuncMap {
                "StringUtils": NewStringUtils,
                "SliceUtils":  NewSliceUtils,
                "JsonUtils":   NewJsonUtils,
-               "DateUtils":   NewDateUtils, // TODO: to be replaced by DateUtils
+               "DateUtils":   NewDateUtils,
 
                // -----------------------------------------------------------------
                // svg / avatar / icon / color
@@ -71,7 +71,7 @@ func NewFuncMap() template.FuncMap {
                "CountFmt":      base.FormatNumberSI,
                "TimeSince":     timeutil.TimeSince,
                "TimeSinceUnix": timeutil.TimeSinceUnix,
-               "DateTime":      timeutil.DateTime,
+               "DateTime":      dateTimeLegacy, // for backward compatibility only, do not use it anymore
                "Sec2Time":      util.SecToTime,
                "LoadTimes": func(startTime time.Time) string {
                        return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
index ec48a7e4beba359b2b3bf33445136d5587e81446..45dd8da02f19e618c4996b3912dd0cecffd11600 100644 (file)
@@ -6,7 +6,9 @@ package templates
 import (
        "context"
        "html/template"
+       "time"
 
+       "code.gitea.io/gitea/modules/setting"
        "code.gitea.io/gitea/modules/timeutil"
 )
 
@@ -32,3 +34,27 @@ func (du *DateUtils) AbsoluteLong(time any) template.HTML {
 func (du *DateUtils) FullTime(time any) template.HTML {
        return timeutil.DateTime("full", time)
 }
+
+// ParseLegacy parses the datetime in legacy format, eg: "2016-01-02" in server's timezone.
+// It shouldn't be used in new code. New code should use Time or TimeStamp as much as possible.
+func (du *DateUtils) ParseLegacy(datetime string) time.Time {
+       return parseLegacy(datetime)
+}
+
+func parseLegacy(datetime string) time.Time {
+       t, err := time.Parse(time.RFC3339, datetime)
+       if err != nil {
+               t, _ = time.ParseInLocation(time.DateOnly, datetime, setting.DefaultUILocation)
+       }
+       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 timeutil.DateTime(format, datetime)
+}
diff --git a/modules/templates/util_date_test.go b/modules/templates/util_date_test.go
new file mode 100644 (file)
index 0000000..96c3776
--- /dev/null
@@ -0,0 +1,51 @@
+// Copyright 2023 The Gitea Authors. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+package templates
+
+import (
+       "testing"
+       "time"
+
+       "code.gitea.io/gitea/modules/setting"
+       "code.gitea.io/gitea/modules/test"
+       "code.gitea.io/gitea/modules/timeutil"
+
+       "github.com/stretchr/testify/assert"
+)
+
+func TestDateTime(t *testing.T) {
+       testTz, _ := time.LoadLocation("America/New_York")
+       defer test.MockVariableValue(&setting.DefaultUILocation, testTz)()
+       defer test.MockVariableValue(&setting.IsInTesting, false)()
+
+       du := NewDateUtils(nil)
+
+       refTimeStr := "2018-01-01T00:00:00Z"
+       refDateStr := "2018-01-01"
+       refTime, _ := time.Parse(time.RFC3339, refTimeStr)
+       refTimeStamp := timeutil.TimeStamp(refTime.Unix())
+
+       assert.EqualValues(t, "-", du.AbsoluteShort(nil))
+       assert.EqualValues(t, "-", du.AbsoluteShort(0))
+       assert.EqualValues(t, "-", du.AbsoluteShort(time.Time{}))
+       assert.EqualValues(t, "-", du.AbsoluteShort(timeutil.TimeStamp(0)))
+
+       actual := dateTimeLegacy("short", "invalid")
+       assert.EqualValues(t, `-`, actual)
+
+       actual = dateTimeLegacy("short", refTimeStr)
+       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2018-01-01T00:00:00Z">2018-01-01</absolute-date>`, actual)
+
+       actual = du.AbsoluteShort(refTime)
+       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2018-01-01T00:00:00Z">2018-01-01</absolute-date>`, actual)
+
+       actual = dateTimeLegacy("short", refDateStr)
+       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2018-01-01T00:00:00-05:00">2018-01-01</absolute-date>`, actual)
+
+       actual = du.AbsoluteShort(refTimeStamp)
+       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2017-12-31T19:00:00-05:00">2017-12-31</absolute-date>`, actual)
+
+       actual = du.FullTime(refTimeStamp)
+       assert.EqualValues(t, `<relative-time weekday="" year="numeric" format="datetime" month="short" day="numeric" hour="numeric" minute="numeric" second="numeric" data-tooltip-content data-tooltip-interactive="true" datetime="2017-12-31T19:00:00-05:00">2017-12-31 19:00:00 -05:00</relative-time>`, actual)
+}
index c089173560b48e813902db8b3ead32dc6867627c..664e0320b03ff6733ad97614dc0a101d405d6618 100644 (file)
@@ -12,9 +12,7 @@ import (
 )
 
 // DateTime renders an absolute time HTML element by datetime.
-func DateTime(format string, datetime any, extraAttrs ...string) template.HTML {
-       // TODO: remove the extraAttrs argument, it's not used in any call to DateTime
-
+func DateTime(format string, datetime any) template.HTML {
        if p, ok := datetime.(*time.Time); ok {
                datetime = *p
        }
@@ -34,9 +32,6 @@ func DateTime(format string, datetime any, extraAttrs ...string) template.HTML {
        switch v := datetime.(type) {
        case nil:
                return "-"
-       case string:
-               datetimeEscaped = html.EscapeString(v)
-               textEscaped = datetimeEscaped
        case time.Time:
                if v.IsZero() || v.Unix() == 0 {
                        return "-"
@@ -51,10 +46,7 @@ func DateTime(format string, datetime any, extraAttrs ...string) template.HTML {
                panic(fmt.Sprintf("Unsupported time type %T", datetime))
        }
 
-       attrs := make([]string, 0, 10+len(extraAttrs))
-       attrs = append(attrs, extraAttrs...)
-       attrs = append(attrs, `weekday=""`, `year="numeric"`)
-
+       attrs := []string{`weekday=""`, `year="numeric"`}
        switch format {
        case "short", "long": // date only
                attrs = append(attrs, `month="`+format+`"`, `day="numeric"`)
diff --git a/modules/timeutil/datetime_test.go b/modules/timeutil/datetime_test.go
deleted file mode 100644 (file)
index ac2ce35..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2023 The Gitea Authors. All rights reserved.
-// SPDX-License-Identifier: MIT
-
-package timeutil
-
-import (
-       "testing"
-       "time"
-
-       "code.gitea.io/gitea/modules/setting"
-       "code.gitea.io/gitea/modules/test"
-
-       "github.com/stretchr/testify/assert"
-)
-
-func TestDateTime(t *testing.T) {
-       testTz, _ := time.LoadLocation("America/New_York")
-       defer test.MockVariableValue(&setting.DefaultUILocation, testTz)()
-
-       refTimeStr := "2018-01-01T00:00:00Z"
-       refDateStr := "2018-01-01"
-       refTime, _ := time.Parse(time.RFC3339, refTimeStr)
-       refTimeStamp := TimeStamp(refTime.Unix())
-
-       assert.EqualValues(t, "-", DateTime("short", nil))
-       assert.EqualValues(t, "-", DateTime("short", 0))
-       assert.EqualValues(t, "-", DateTime("short", time.Time{}))
-       assert.EqualValues(t, "-", DateTime("short", TimeStamp(0)))
-
-       actual := DateTime("short", "invalid")
-       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="invalid">invalid</absolute-date>`, actual)
-
-       actual = DateTime("short", refTimeStr)
-       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2018-01-01T00:00:00Z">2018-01-01T00:00:00Z</absolute-date>`, actual)
-
-       actual = DateTime("short", refTime)
-       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2018-01-01T00:00:00Z">2018-01-01</absolute-date>`, actual)
-
-       actual = DateTime("short", refDateStr)
-       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2018-01-01">2018-01-01</absolute-date>`, actual)
-
-       actual = DateTime("short", refTimeStamp)
-       assert.EqualValues(t, `<absolute-date weekday="" year="numeric" month="short" day="numeric" date="2017-12-31T19:00:00-05:00">2017-12-31</absolute-date>`, actual)
-
-       actual = DateTime("full", refTimeStamp)
-       assert.EqualValues(t, `<relative-time weekday="" year="numeric" format="datetime" month="short" day="numeric" hour="numeric" minute="numeric" second="numeric" data-tooltip-content data-tooltip-interactive="true" datetime="2017-12-31T19:00:00-05:00">2017-12-31 19:00:00 -05:00</relative-time>`, actual)
-}
index 5bae6fc6d585ed2b88b1373c11534c6707a5434e..01bd944f46b4176c9efae2950d8551413f60b70c 100644 (file)
@@ -38,7 +38,7 @@
                                                {{if .Milestone.DeadlineString}}
                                                        <span{{if .IsOverdue}} class="text red"{{end}}>
                                                                {{svg "octicon-calendar"}}
-                                                               {{DateTime "short" .Milestone.DeadlineString}}
+                                                               {{ctx.DateUtils.AbsoluteShort (.Milestone.DeadlineString|ctx.DateUtils.ParseLegacy)}}
                                                        </span>
                                                {{else}}
                                                        {{svg "octicon-calendar"}}
index bce7ad871719a7e83d7ecbe98d9ff34f61839a48..8b84659d10894bd79d6de8af23aa01aaafada497 100644 (file)
@@ -59,7 +59,7 @@
                                                                        {{if .DeadlineString}}
                                                                                <span class="flex-text-inline {{if .IsOverdue}}text red{{end}}">
                                                                                        {{svg "octicon-calendar" 14}}
-                                                                                       {{DateTime "short" .DeadlineString}}
+                                                                                       {{ctx.DateUtils.AbsoluteShort (.DeadlineString|ctx.DateUtils.ParseLegacy)}}
                                                                                </span>
                                                                        {{else}}
                                                                                {{svg "octicon-calendar" 14}}
index 57abbeb8f79605edf99ba9292325f40fe2ed2e17..9324959bedd60c30f986a65e68ff951c2eb63b72 100644 (file)
                                {{template "shared/user/avatarlink" dict "user" .Poster}}
                                <span class="text grey muted-links">
                                        {{template "shared/user/authorlink" .Poster}}
-                                       {{ctx.Locale.Tr "repo.issues.due_date_added" (DateTime "long" .Content) $createdStr}}
+                                       {{$dueDate := ctx.DateUtils.AbsoluteLong (.Content|ctx.DateUtils.ParseLegacy)}}
+                                       {{ctx.Locale.Tr "repo.issues.due_date_added" $dueDate $createdStr}}
                                </span>
                        </div>
                {{else if eq .Type 17}}
                                        {{template "shared/user/authorlink" .Poster}}
                                        {{$parsedDeadline := StringUtils.Split .Content "|"}}
                                        {{if eq (len $parsedDeadline) 2}}
-                                               {{$from := DateTime "long" (index $parsedDeadline 1)}}
-                                               {{$to := DateTime "long" (index $parsedDeadline 0)}}
+                                               {{$to := ctx.DateUtils.AbsoluteLong ((index $parsedDeadline 0)|ctx.DateUtils.ParseLegacy)}}
+                                               {{$from := ctx.DateUtils.AbsoluteLong ((index $parsedDeadline 1)|ctx.DateUtils.ParseLegacy)}}
                                                {{ctx.Locale.Tr "repo.issues.due_date_modified" $to $from $createdStr}}
                                        {{end}}
                                </span>
                                {{template "shared/user/avatarlink" dict "user" .Poster}}
                                <span class="text grey muted-links">
                                        {{template "shared/user/authorlink" .Poster}}
-                                       {{ctx.Locale.Tr "repo.issues.due_date_remove" (DateTime "long" .Content) $createdStr}}
+                                       {{$dueDate := ctx.DateUtils.AbsoluteLong (.Content|ctx.DateUtils.ParseLegacy)}}
+                                       {{ctx.Locale.Tr "repo.issues.due_date_remove" $dueDate $createdStr}}
                                </span>
                        </div>
                {{else if eq .Type 19}}
index 71ff8dba3f4e777ccd978f916c8a26f0f318c93d..e01eca7c7431c1018c6a25e2779680a5dd3d0ad6 100644 (file)
                                                                                        {{if .DeadlineString}}
                                                                                                <span{{if .IsOverdue}} class="text red"{{end}}>
                                                                                                        {{svg "octicon-calendar" 14}}
-                                                                                                       {{DateTime "short" .DeadlineString}}
+                                                                                                       {{ctx.DateUtils.AbsoluteShort (.DeadlineString|ctx.DateUtils.ParseLegacy)}}
                                                                                                </span>
                                                                                        {{else}}
                                                                                                {{svg "octicon-calendar" 14}}