Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parseDuration function to templates #3816

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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