extend Go's time.ParseDuration to support days, weeks and years (#4116)
This commit is contained in:
+200
@@ -0,0 +1,200 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the https://go.dev/LICENSE file.
|
||||
//
|
||||
// Code is borrowed directly from pkg/time.ParseDuration under
|
||||
// Go's BSD-style license, extended with changes to support
|
||||
// days, weeks and year as time Duration units.
|
||||
|
||||
// Package cmd provides extended time.Duration implementation
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Duration is a standard unit of time.
|
||||
type Duration time.Duration
|
||||
|
||||
// Days returns the duration as a floating point number of days.
|
||||
func (d Duration) Days() float64 {
|
||||
hour := d / Hour
|
||||
nsec := d % Hour
|
||||
return float64(hour) + float64(nsec)*(1e-9/60/60/24)
|
||||
}
|
||||
|
||||
// Standard unit of time.
|
||||
var (
|
||||
Nanosecond = Duration(time.Nanosecond)
|
||||
Microsecond = Duration(time.Microsecond)
|
||||
Millisecond = Duration(time.Millisecond)
|
||||
Second = Duration(time.Second)
|
||||
Minute = Duration(time.Minute)
|
||||
Hour = Duration(time.Hour)
|
||||
Day = Hour * 24
|
||||
Week = Day * 7
|
||||
Fortnight = Week * 2
|
||||
Month = Day * 30 // Approximation
|
||||
Year = Day * 365 // Approximation
|
||||
Decade = Year * 10 // Approximation
|
||||
Century = Year * 100 // Approximation
|
||||
Millennium = Year * 1000 // Approximation
|
||||
)
|
||||
|
||||
// leadingInt consumes the leading [0-9]* from s.
|
||||
// this function is directly copied from
|
||||
// https://cs.opensource.google/go/go/+/refs/tags/go1.18.3:src/time/format.go;drc=55590f3a2b89f001bcadf0df6eb2dde62618302b;l=1455
|
||||
// only changes the "error string that's being returned"
|
||||
func leadingInt(s string) (x int64, rem string, err error) {
|
||||
errLeadingInt := errors.New("bad [0-9]*")
|
||||
|
||||
i := 0
|
||||
for ; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c < '0' || c > '9' {
|
||||
break
|
||||
}
|
||||
if x > (1<<63-1)/10 {
|
||||
// overflow
|
||||
return 0, "", errLeadingInt
|
||||
}
|
||||
x = x*10 + int64(c) - '0'
|
||||
if x < 0 {
|
||||
// overflow
|
||||
return 0, "", errLeadingInt
|
||||
}
|
||||
}
|
||||
return x, s[i:], nil
|
||||
}
|
||||
|
||||
// unitMap defines 'unit' to 'actual-value'
|
||||
// translates for calculating duration.
|
||||
var unitMap = map[string]int64{
|
||||
"ns": int64(Nanosecond),
|
||||
"us": int64(Microsecond),
|
||||
"µs": int64(Microsecond), // U+00B5 = micro symbol
|
||||
"μs": int64(Microsecond), // U+03BC = Greek letter mu
|
||||
"ms": int64(Millisecond),
|
||||
"s": int64(Second),
|
||||
"m": int64(Minute),
|
||||
"h": int64(Hour),
|
||||
"d": int64(Day),
|
||||
"w": int64(Week),
|
||||
"y": int64(Year), // Approximation
|
||||
}
|
||||
|
||||
// ParseDuration parses a duration string.
|
||||
// This implementation is similar to Go's
|
||||
// https://cs.opensource.google/go/go/+/refs/tags/go1.18.3:src/time/format.go;l=1546;bpv=1;bpt=1
|
||||
// extends it to parse days, weeks and years..
|
||||
//
|
||||
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d", "w", "y".
|
||||
func ParseDuration(s string) (Duration, error) {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return 0, errors.New("invalid empty duration")
|
||||
}
|
||||
|
||||
// [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
|
||||
orig := s
|
||||
var d int64
|
||||
neg := false
|
||||
|
||||
// Consume [-+]?
|
||||
if s != "" {
|
||||
c := s[0]
|
||||
if c == '-' || c == '+' {
|
||||
neg = c == '-'
|
||||
s = s[1:]
|
||||
}
|
||||
}
|
||||
// Special case: if all that is left is "0", this is zero.
|
||||
if s == "0" {
|
||||
return 0, nil
|
||||
}
|
||||
if s == "" {
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
for s != "" {
|
||||
var (
|
||||
v, f int64 // integers before, after decimal point
|
||||
scale float64 = 1 // value = v + f/scale
|
||||
)
|
||||
|
||||
var err error
|
||||
|
||||
// The next character must be [0-9.]
|
||||
if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') {
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
// Consume [0-9]*
|
||||
pl := len(s)
|
||||
v, s, err = leadingInt(s)
|
||||
if err != nil {
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
pre := pl != len(s) // whether we consumed anything before a period
|
||||
|
||||
// Consume (\.[0-9]*)?
|
||||
post := false
|
||||
if s != "" && s[0] == '.' {
|
||||
s = s[1:]
|
||||
pl := len(s)
|
||||
f, s, err = leadingInt(s)
|
||||
if err != nil {
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
for n := pl - len(s); n > 0; n-- {
|
||||
scale *= 10
|
||||
}
|
||||
post = pl != len(s)
|
||||
}
|
||||
if !pre && !post {
|
||||
// no digits (e.g. ".s" or "-.s")
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
|
||||
// Consume unit.
|
||||
i := 0
|
||||
for ; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c == '.' || '0' <= c && c <= '9' {
|
||||
break
|
||||
}
|
||||
}
|
||||
if i == 0 {
|
||||
return 0, errors.New("missing unit in duration " + orig)
|
||||
}
|
||||
u := s[:i]
|
||||
s = s[i:]
|
||||
unit, ok := unitMap[u]
|
||||
if !ok {
|
||||
return 0, errors.New("unknown unit " + u + " in duration " + orig)
|
||||
}
|
||||
if v > (1<<63-1)/unit {
|
||||
// overflow
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
v *= unit
|
||||
if f > 0 {
|
||||
// float64 is needed to be nanosecond accurate for fractions of hours.
|
||||
// v >= 0 && (f*unit/scale) <= 3.6e+12 (ns/h, h is the largest unit)
|
||||
v += int64(float64(f) * (float64(unit) / scale))
|
||||
if v < 0 {
|
||||
// overflow
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
}
|
||||
d += v
|
||||
if d < 0 {
|
||||
// overflow
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
}
|
||||
|
||||
if neg {
|
||||
d = -d
|
||||
}
|
||||
return Duration(d), nil
|
||||
}
|
||||
+1
-2
@@ -27,7 +27,6 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"maze.io/x/duration"
|
||||
)
|
||||
|
||||
// ls specific flags.
|
||||
@@ -140,7 +139,7 @@ func parseRewindFlag(rewind string) (timeRef time.Time) {
|
||||
|
||||
if timeRef.IsZero() {
|
||||
// rewind is not parsed, check if it is a duration instead
|
||||
if duration, e := duration.ParseDuration(rewind); e == nil {
|
||||
if duration, e := ParseDuration(rewind); e == nil {
|
||||
if duration < 0 {
|
||||
fatalIf(probe.NewError(errors.New("negative duration is not supported")),
|
||||
"Unable to parse --rewind argument")
|
||||
|
||||
+101
-13
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -19,20 +19,105 @@ package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"maze.io/x/duration"
|
||||
)
|
||||
|
||||
var parseDurationTests = []struct {
|
||||
in string
|
||||
ok bool
|
||||
want Duration
|
||||
}{
|
||||
// simple
|
||||
{"0", true, 0},
|
||||
{"5s", true, 5 * Second},
|
||||
{"30s", true, 30 * Second},
|
||||
{"1478s", true, 1478 * Second},
|
||||
// sign
|
||||
{"-5s", true, -5 * Second},
|
||||
{"+5s", true, 5 * Second},
|
||||
{"-0", true, 0},
|
||||
{"+0", true, 0},
|
||||
// decimal
|
||||
{"5.0s", true, 5 * Second},
|
||||
{"5.6s", true, 5*Second + 600*Millisecond},
|
||||
{"5.s", true, 5 * Second},
|
||||
{".5s", true, 500 * Millisecond},
|
||||
{"1.0s", true, 1 * Second},
|
||||
{"1.00s", true, 1 * Second},
|
||||
{"1.004s", true, 1*Second + 4*Millisecond},
|
||||
{"1.0040s", true, 1*Second + 4*Millisecond},
|
||||
{"100.00100s", true, 100*Second + 1*Millisecond},
|
||||
// different units
|
||||
{"10ns", true, 10 * Nanosecond},
|
||||
{"11us", true, 11 * Microsecond},
|
||||
{"12µs", true, 12 * Microsecond}, // U+00B5
|
||||
{"12μs", true, 12 * Microsecond}, // U+03BC
|
||||
{"13ms", true, 13 * Millisecond},
|
||||
{"14s", true, 14 * Second},
|
||||
{"15m", true, 15 * Minute},
|
||||
{"16h", true, 16 * Hour},
|
||||
{"12d", true, 12 * Day},
|
||||
{"3w", true, 3 * Week},
|
||||
// composite durations
|
||||
{"3h30m", true, 3*Hour + 30*Minute},
|
||||
{"10.5s4m", true, 4*Minute + 10*Second + 500*Millisecond},
|
||||
{"-2m3.4s", true, -(2*Minute + 3*Second + 400*Millisecond)},
|
||||
{"1h2m3s4ms5us6ns", true, 1*Hour + 2*Minute + 3*Second + 4*Millisecond + 5*Microsecond + 6*Nanosecond},
|
||||
{"39h9m14.425s", true, 39*Hour + 9*Minute + 14*Second + 425*Millisecond},
|
||||
{"2w3d12h", true, 2*Week + 3*Day + 12*Hour},
|
||||
// large value
|
||||
{"52763797000ns", true, 52763797000 * Nanosecond},
|
||||
// more than 9 digits after decimal point, see https://golang.org/issue/6617
|
||||
{"0.3333333333333333333h", true, 20 * Minute},
|
||||
// 9007199254740993 = 1<<53+1 cannot be stored precisely in a float64
|
||||
{"9007199254740993ns", true, (1<<53 + 1) * Nanosecond},
|
||||
// largest duration that can be represented by int64 in nanoseconds
|
||||
{"9223372036854775807ns", true, (1<<63 - 1) * Nanosecond},
|
||||
{"9223372036854775.807us", true, (1<<63 - 1) * Nanosecond},
|
||||
{"9223372036s854ms775us807ns", true, (1<<63 - 1) * Nanosecond},
|
||||
// large negative value
|
||||
{"-9223372036854775807ns", true, -1<<63 + 1*Nanosecond},
|
||||
|
||||
// errors
|
||||
{"", false, 0},
|
||||
{"3", false, 0},
|
||||
{"-", false, 0},
|
||||
{"s", false, 0},
|
||||
{".", false, 0},
|
||||
{"-.", false, 0},
|
||||
{".s", false, 0},
|
||||
{"+.s", false, 0},
|
||||
{"3000000h", false, 0}, // overflow
|
||||
{"9223372036854775808ns", false, 0}, // overflow
|
||||
{"9223372036854775.808us", false, 0}, // overflow
|
||||
{"9223372036854ms775us808ns", false, 0}, // overflow
|
||||
// largest negative value of type int64 in nanoseconds should fail
|
||||
// see https://go-review.googlesource.com/#/c/2461/
|
||||
{"-9223372036854775808ns", false, 0},
|
||||
}
|
||||
|
||||
func TestParseDuration(t *testing.T) {
|
||||
for _, tc := range parseDurationTests {
|
||||
t.Run(tc.in, func(t *testing.T) {
|
||||
d, err := ParseDuration(tc.in)
|
||||
if tc.ok && (err != nil || d != tc.want) {
|
||||
t.Errorf("ParseDuration(%q) = %v, %v, want %v, nil", tc.in, d, err, tc.want)
|
||||
} else if !tc.ok && err == nil {
|
||||
t.Errorf("ParseDuration(%q) = _, nil, want _, non-nil", tc.in)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Test for ParseDurationTime. Validates the returned value
|
||||
// for given time value in days, hours and minute format.
|
||||
func TestParseDurationTime(t *testing.T) {
|
||||
testCases := []struct {
|
||||
timeValue string
|
||||
expected duration.Duration
|
||||
expected Duration
|
||||
err string
|
||||
}{
|
||||
// Test 1: empty string as input
|
||||
{"", 0, "time: invalid duration "},
|
||||
{"", 0, "invalid empty duration"},
|
||||
// Test 2: Input string contains 4 day, 10 hour and 3 minutes
|
||||
{"4d10h3m", 381780000000000, ""},
|
||||
// Test 3: Input string contains 10 day and 3 hours
|
||||
@@ -40,7 +125,7 @@ func TestParseDurationTime(t *testing.T) {
|
||||
// Test 4: Input string contains minutes and days
|
||||
{"3m7d", 604980000000000, ""},
|
||||
// Test 5: Input string contains unknown unit
|
||||
{"4a3d", 0, "time: unknown unit a in duration 4a3d"},
|
||||
{"4a3d", 0, "unknown unit a in duration 4a3d"},
|
||||
// Test 6: Input string contains fractional day
|
||||
{"1.5d", 129600000000000, ""},
|
||||
// Test 6: Input string contains fractional day and hour
|
||||
@@ -50,12 +135,15 @@ func TestParseDurationTime(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
myVal, err := duration.ParseDuration(testCase.timeValue)
|
||||
if err != nil && err.Error() != testCase.err {
|
||||
t.Error()
|
||||
}
|
||||
if myVal != testCase.expected {
|
||||
t.Error()
|
||||
}
|
||||
testCase := testCase
|
||||
t.Run("", func(t *testing.T) {
|
||||
myVal, err := ParseDuration(testCase.timeValue)
|
||||
if err != nil && err.Error() != testCase.err {
|
||||
t.Error()
|
||||
}
|
||||
if myVal != testCase.expected {
|
||||
t.Errorf("Expected %v, got %v", testCase.expected, myVal)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/replication"
|
||||
"github.com/minio/pkg/console"
|
||||
"maze.io/x/duration"
|
||||
)
|
||||
|
||||
var replicateResyncStartFlags = []cli.Flag{
|
||||
@@ -119,7 +118,7 @@ func mainReplicateResyncStart(cliCtx *cli.Context) error {
|
||||
if cliCtx.IsSet("older-than") {
|
||||
olderThanStr = cliCtx.String("older-than")
|
||||
if olderThanStr != "" {
|
||||
days, e := duration.ParseDuration(olderThanStr)
|
||||
days, e := ParseDuration(olderThanStr)
|
||||
if e != nil || !strings.ContainsAny(olderThanStr, "dwy") {
|
||||
fatalIf(probe.NewError(e), "Unable to parse older-than=`"+olderThanStr+"`.")
|
||||
}
|
||||
|
||||
@@ -154,15 +154,15 @@ func (m *traceUI) View() string {
|
||||
m.apiStatsMap[res.Trace.FuncName] = traceSt
|
||||
}
|
||||
|
||||
table.SetHeader([]string{"API", "RX", "TX", "N"})
|
||||
table.SetHeader([]string{"API", "CALLS", "RX", "TX"})
|
||||
data := make([][]string, 0, len(m.apiStatsMap))
|
||||
|
||||
for k, stats := range m.apiStatsMap {
|
||||
data = append(data, []string{
|
||||
k,
|
||||
whiteStyle.Render(fmt.Sprintf("%d", stats.loadAPICall())),
|
||||
whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesRX())),
|
||||
whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesTX())),
|
||||
whiteStyle.Render(fmt.Sprintf("%d", stats.loadAPICall())),
|
||||
})
|
||||
}
|
||||
sort.Slice(data, func(i, j int) bool {
|
||||
@@ -185,7 +185,7 @@ func (m *traceUI) View() string {
|
||||
totalTX += stats.loadAPIBytesTX()
|
||||
totalCalls += stats.loadAPICall()
|
||||
}
|
||||
msg := fmt.Sprintf("\n========\nTotal: %d Calls, %s RX, %s TX - in %.02fs",
|
||||
msg := fmt.Sprintf("\n========\nTotal: %d CALLS, %s RX, %s TX - in %.02fs",
|
||||
totalCalls,
|
||||
humanize.IBytes(totalRX),
|
||||
humanize.IBytes(totalTX),
|
||||
|
||||
+2
-3
@@ -38,7 +38,6 @@ import (
|
||||
"github.com/minio/madmin-go"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
"maze.io/x/duration"
|
||||
|
||||
jwtgo "github.com/golang-jwt/jwt/v4"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
@@ -177,7 +176,7 @@ func isOlder(ti time.Time, olderRef string) bool {
|
||||
return false
|
||||
}
|
||||
objectAge := time.Since(ti)
|
||||
olderThan, e := duration.ParseDuration(olderRef)
|
||||
olderThan, e := ParseDuration(olderRef)
|
||||
fatalIf(probe.NewError(e), "Unable to parse olderThan=`"+olderRef+"`.")
|
||||
return objectAge < time.Duration(olderThan)
|
||||
}
|
||||
@@ -189,7 +188,7 @@ func isNewer(ti time.Time, newerRef string) bool {
|
||||
}
|
||||
|
||||
objectAge := time.Since(ti)
|
||||
newerThan, e := duration.ParseDuration(newerRef)
|
||||
newerThan, e := ParseDuration(newerRef)
|
||||
fatalIf(probe.NewError(e), "Unable to parse newerThan=`"+newerRef+"`.")
|
||||
return objectAge >= time.Duration(newerThan)
|
||||
}
|
||||
|
||||
@@ -41,7 +41,6 @@ require (
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b
|
||||
gopkg.in/h2non/filetype.v1 v1.0.5
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
maze.io/x/duration v0.0.0-20160924141736-faac084b6075
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@@ -954,8 +954,6 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh
|
||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
maze.io/x/duration v0.0.0-20160924141736-faac084b6075 h1:4zVed9rL46683x3koxOYLzh8FlLFjnRrzTo2uvgA5D4=
|
||||
maze.io/x/duration v0.0.0-20160924141736-faac084b6075/go.mod h1:1kfR2ph3CIvtfIQ8D8JhmAgePmnAUnR+AWYWUBo+l08=
|
||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
||||
|
||||
Reference in New Issue
Block a user