Skip to content

Commit

Permalink
Add parseDuration function to templates
Browse files Browse the repository at this point in the history
Signed-off-by: Vadim Aleksandrov <valeksandrov@me.com>
  • Loading branch information
verdel committed Jun 14, 2024
1 parent 7e2cd80 commit cf28754
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,4 @@ templating.
| tz | string, time.Time | Returns the time in the timezone. For example, Europe/Paris. |
| since | time.Time | [time.Duration](https://pkg.go.dev/time#Since), returns the duration of how much time passed from the provided time till the current system time. |
| humanizeDuration | number or string | Returns a human-readable string representing the duration, and the error if it happened. |
| parseDuration | string | Returns the time.Duration representation of a passed string. |
4 changes: 4 additions & 0 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ var DefaultFuncs = FuncMap{
},
"since": time.Since,
"humanizeDuration": commonTemplates.HumanizeDuration,
// parseDuration returns the time.Duration representation of a passed string
"parseDuration": func(text string) (time.Duration, error) {
return time.ParseDuration(text)
},
}

// Pair is a key/value string pair.
Expand Down
8 changes: 8 additions & 0 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,14 @@ func TestTemplateFuncs(t *testing.T) {
in: "{{ . | since | humanizeDuration }}",
data: time.Now().Add(-1 * time.Hour),
exp: "1h 0m 0s",
}, {
title: "Template using duration",
in: `{{ "60s" | parseDuration | printf "%d" }}`,
exp: "60000000000",
}, {
title: "Template using invalid duration",
in: `{{ "60k" | parseDuration | printf "%d" }}`,
expErr: "template: :1:11: executing \"\" at <parseDuration>: error calling parseDuration: time: unknown unit \"k\" in duration \"60k\"",
}} {
tc := tc
t.Run(tc.title, func(t *testing.T) {
Expand Down

0 comments on commit cf28754

Please sign in to comment.