Debian Codegraph @

tpl/time/time.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package time provides template functions for measuring and displaying time.
15 package time
16
17 import (
18 "fmt"
19 "time"
20
21 "github.com/gohugoio/hugo/cache/dynacache"
22 "github.com/gohugoio/hugo/common/htime"
23 "github.com/gohugoio/hugo/deps"
24
25 "github.com/spf13/cast"
26 )
27
28 // New returns a new instance of the time-namespaced template functions.
29 func New(timeFormatter htime.TimeFormatter, location *time.Location, deps *deps.Deps) *Namespace {
30 if deps.MemCache == nil {
31 panic("must provide MemCache")
32 }
33
34 return &Namespace{
35 timeFormatter: timeFormatter,
36 location: location,
37 deps: deps,
38 cacheIn: dynacache.GetOrCreatePartition[string, *time.Location](
39 deps.MemCache,
40 "/tmpl/time/in",
41 dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearNever},
42 ),
43 }
44 }
45
46 // Namespace provides template functions for the "time" namespace.
47 type Namespace struct {
48 timeFormatter htime.TimeFormatter
49 location *time.Location
50 deps *deps.Deps
51 cacheIn *dynacache.Partition[string, *time.Location]
52 }
53
54 // AsTime converts the textual representation of the datetime string into
55 // a time.Time interface.
56 func (ns *Namespace) AsTime(v any, args ...any) (any, error) {
57 loc := ns.location
58 if len(args) > 0 {
59 locStr, err := cast.ToStringE(args[0])
60 if err != nil {
61 return nil, err
62 }
63 loc, err = time.LoadLocation(locStr)
64 if err != nil {
65 return nil, err
66 }
67 }
68
69 return htime.ToTimeInDefaultLocationE(v, loc)
70 }
71
72 // Format converts the textual representation of the datetime string in v into
73 // time.Time if needed and formats it with the given layout.
74 func (ns *Namespace) Format(layout string, v any) (string, error) {
75 t, err := htime.ToTimeInDefaultLocationE(v, ns.location)
76 if err != nil {
77 return "", err
78 }
79
80 return ns.timeFormatter.Format(t, layout), nil
81 }
82
83 // Now returns the current local time or `clock` time
84 func (ns *Namespace) Now() time.Time {
85 return htime.Now()
86 }
87
88 // In returns the time t in the IANA time zone specified by timeZoneName.
89 // If timeZoneName is "" or "UTC", the time is returned in UTC.
90 // If timeZoneName is "Local", the time is returned in the system's local time zone.
91 // Otherwise, timeZoneName must be a valid IANA location name (e.g., "Europe/Oslo").
92 func (ns *Namespace) In(timeZoneName string, t time.Time) (time.Time, error) {
93 location, err := ns.cacheIn.GetOrCreate(dynacache.CleanKey(timeZoneName), func(string) (*time.Location, error) {
94 return time.LoadLocation(timeZoneName)
95 })
96 if err != nil {
97 return time.Time{}, err
98 }
99
100 return t.In(location), nil
101 }
102
103 // ParseDuration parses the duration string s.
104 // A duration string is a possibly signed sequence of
105 // decimal numbers, each with optional fraction and a unit suffix,
106 // such as "300ms", "-1.5h" or "2h45m".
107 // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
108 // See https://golang.org/pkg/time/#ParseDuration
109 func (ns *Namespace) ParseDuration(s any) (time.Duration, error) {
110 ss, err := cast.ToStringE(s)
111 if err != nil {
112 return 0, err
113 }
114
115 return time.ParseDuration(ss)
116 }
117
118 var durationUnits = map[string]time.Duration{
119 "nanosecond": time.Nanosecond,
120 "ns": time.Nanosecond,
121 "microsecond": time.Microsecond,
122 "us": time.Microsecond,
123 "µs": time.Microsecond,
124 "millisecond": time.Millisecond,
125 "ms": time.Millisecond,
126 "second": time.Second,
127 "s": time.Second,
128 "minute": time.Minute,
129 "m": time.Minute,
130 "hour": time.Hour,
131 "h": time.Hour,
132 }
133
134 // Duration converts the given number to a time.Duration.
135 // Unit is one of nanosecond/ns, microsecond/us/µs, millisecond/ms, second/s, minute/m or hour/h.
136 func (ns *Namespace) Duration(unit any, number any) (time.Duration, error) {
137 unitStr, err := cast.ToStringE(unit)
138 if err != nil {
139 return 0, err
140 }
141 unitDuration, found := durationUnits[unitStr]
142 if !found {
143 return 0, fmt.Errorf("%q is not a valid duration unit", unit)
144 }
145 n, err := cast.ToInt64E(number)
146 if err != nil {
147 return 0, err
148 }
149 return time.Duration(n) * unitDuration, nil
150 }