feat(config): Accept durations given in days (e.g. "7d") (#12579)

This commit is contained in:
Sven Rebhan 2023-02-16 18:10:18 +01:00 committed by GitHub
parent 8896538f5d
commit 9dfbbb29ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 7 deletions

View File

@ -1,12 +1,18 @@
package config package config
import ( import (
"fmt"
"regexp"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/alecthomas/units" "github.com/alecthomas/units"
) )
// Regexp for day specifications in durations
var durationDayRe = regexp.MustCompile(`(\d+(?:\.\d+)?)d`)
// Duration is a time.Duration // Duration is a time.Duration
type Duration time.Duration type Duration time.Duration
@ -36,13 +42,18 @@ func (d *Duration) UnmarshalText(b []byte) error {
// Finally, try value is a TOML string (e.g. "3s", 3s) or literal (e.g. '3s') // Finally, try value is a TOML string (e.g. "3s", 3s) or literal (e.g. '3s')
if durStr == "" { if durStr == "" {
durStr = "0s" *d = Duration(0)
return nil
} }
// special case: logging interval had a default of 0d, which silently
// failed, but in order to prevent issues with default configs that had // Handle "day" intervals and replace them with the "hours" equivalent
// uncommented the option, change it from zero days to zero hours. for _, m := range durationDayRe.FindAllStringSubmatch(durStr, -1) {
if durStr == "0d" { days, err := strconv.ParseFloat(m[1], 64)
durStr = "0h" if err != nil {
return fmt.Errorf("converting %q to hours failed: %w", durStr, err)
}
hours := strconv.FormatFloat(days*24, 'f', -1, 64) + "h"
durStr = strings.Replace(durStr, m[0], hours, 1)
} }
dur, err := time.ParseDuration(durStr) dur, err := time.ParseDuration(durStr)

View File

@ -91,7 +91,12 @@ func TestTOMLParsingStringDurations(t *testing.T) {
"42m", "42m",
"100ms", "100ms",
"100us", "100us",
"100ns" "100ns",
"1d",
"7.5d",
"7d8h15m",
"3d7d",
"15m8h3.5d"
] ]
`) `)
@ -107,6 +112,11 @@ func TestTOMLParsingStringDurations(t *testing.T) {
100 * time.Millisecond, 100 * time.Millisecond,
100 * time.Microsecond, 100 * time.Microsecond,
100 * time.Nanosecond, 100 * time.Nanosecond,
24 * time.Hour,
7*24*time.Hour + 12*time.Hour,
7*24*time.Hour + 8*time.Hour + 15*time.Minute,
10 * 24 * time.Hour,
3*24*time.Hour + 12*time.Hour + 8*time.Hour + 15*time.Minute,
} }
// Load the data // Load the data