From 93edd930a64d5993df13f40b635c39be02c711fb Mon Sep 17 00:00:00 2001 From: Brian Brazil Date: Thu, 26 Feb 2015 17:17:04 +0000 Subject: [PATCH] Better handling of edge conditions in humanizeDuration --- templates/templates.go | 10 +++++----- templates/templates_test.go | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/templates/templates.go b/templates/templates.go index a990de63b..ca7946d87 100644 --- a/templates/templates.go +++ b/templates/templates.go @@ -188,22 +188,22 @@ func NewTemplateExpander(text string, name string, data interface{}, timestamp c sign = "-" v = -v } - seconds := math.Mod(v, 60) + seconds := int64(v) % 60 minutes := (int64(v) / 60) % 60 hours := (int64(v) / 60 / 60) % 24 days := (int64(v) / 60 / 60 / 24) // For days to minutes, we display seconds as an integer. if days != 0 { - return fmt.Sprintf("%s%dd %dh %dm %.0fs", sign, days, hours, minutes, seconds) + return fmt.Sprintf("%s%dd %dh %dm %ds", sign, days, hours, minutes, seconds) } if hours != 0 { - return fmt.Sprintf("%s%dh %dm %.0fs", sign, hours, minutes, seconds) + return fmt.Sprintf("%s%dh %dm %ds", sign, hours, minutes, seconds) } if minutes != 0 { - return fmt.Sprintf("%s%dm %.0fs", sign, minutes, seconds) + return fmt.Sprintf("%s%dm %ds", sign, minutes, seconds) } // For seconds, we display 4 significant digts. - return fmt.Sprintf("%s%.4gs", sign, math.Floor(seconds*1000+.5)/1000) + return fmt.Sprintf("%s%.4gs", sign, v) } prefix := "" for _, p := range []string{"m", "u", "n", "p", "f", "a", "z", "y"} { diff --git a/templates/templates_test.go b/templates/templates_test.go index 262699526..2800d30db 100644 --- a/templates/templates_test.go +++ b/templates/templates_test.go @@ -113,14 +113,14 @@ func TestTemplateExpansion(t *testing.T) { { // HumanizeDuration - seconds. text: "{{ range . }}{{ humanizeDuration . }}:{{ end }}", - input: []float64{0, 1, 60, 3600, 86400, 86400 + 3600, -(86400*2 + 3600*3 + 60*4 + 5)}, - output: "0s:1s:1m 0s:1h 0m 0s:1d 0h 0m 0s:1d 1h 0m 0s:-2d 3h 4m 5s:", + input: []float64{0, 1, 60, 3600, 86400, 86400 + 3600, -(86400*2 + 3600*3 + 60*4 + 5), 899.99}, + output: "0s:1s:1m 0s:1h 0m 0s:1d 0h 0m 0s:1d 1h 0m 0s:-2d 3h 4m 5s:14m 59s:", }, { // HumanizeDuration - subsecond and fractional seconds. text: "{{ range . }}{{ humanizeDuration . }}:{{ end }}", input: []float64{.1, .0001, .12345, 60.1, 60.5, 1.2345, 12.345}, - output: "100ms:100us:123.5ms:1m 0s:1m 0s:1.235s:12.35s:", + output: "100ms:100us:123.5ms:1m 0s:1m 0s:1.234s:12.35s:", }, { // Title.