diff options
author | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2021-07-05 10:13:41 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2021-07-05 10:23:29 +0200 |
commit | e31b1d194655ac3a38fe903ff3995806b129b88a (patch) | |
tree | 8ffac9e39952c9f547b7b4e92620c1c05c84bfc5 /common/types | |
parent | 43a23239b2e3ad602c06d9af0b648e0304fc8744 (diff) |
commands: Make the --poll flag a duration
So you can do:
```
hugo server --poll 700ms
```
See #8720
Diffstat (limited to 'common/types')
-rw-r--r-- | common/types/convert.go | 20 | ||||
-rw-r--r-- | common/types/convert_test.go | 11 |
2 files changed, 31 insertions, 0 deletions
diff --git a/common/types/convert.go b/common/types/convert.go index 7beb3404e..0560eda0d 100644 --- a/common/types/convert.go +++ b/common/types/convert.go @@ -18,10 +18,30 @@ import ( "fmt" "html/template" "reflect" + "time" "github.com/spf13/cast" ) +// ToDuration converts v to time.Duration. +// See ToDurationE if you need to handle errors. +func ToDuration(v interface{}) time.Duration { + d, _ := ToDurationE(v) + return d +} + +// ToDurationE converts v to time.Duration. +func ToDurationE(v interface{}) (time.Duration, error) { + if n := cast.ToInt(v); n > 0 { + return time.Duration(n) * time.Millisecond, nil + } + d, err := time.ParseDuration(cast.ToString(v)) + if err != nil { + return 0, fmt.Errorf("cannot convert %v to time.Duration", v) + } + return d, nil +} + // ToStringSlicePreserveString is the same as ToStringSlicePreserveStringE, // but it never fails. func ToStringSlicePreserveString(v interface{}) []string { diff --git a/common/types/convert_test.go b/common/types/convert_test.go index 364228f41..88b303604 100644 --- a/common/types/convert_test.go +++ b/common/types/convert_test.go @@ -16,6 +16,7 @@ package types import ( "encoding/json" "testing" + "time" qt "github.com/frankban/quicktest" ) @@ -36,3 +37,13 @@ func TestToString(t *testing.T) { c.Assert(ToString([]byte("Hugo")), qt.Equals, "Hugo") c.Assert(ToString(json.RawMessage("Hugo")), qt.Equals, "Hugo") } + +func TestToDuration(t *testing.T) { + c := qt.New(t) + + c.Assert(ToDuration("200ms"), qt.Equals, 200*time.Millisecond) + c.Assert(ToDuration("200"), qt.Equals, 200*time.Millisecond) + c.Assert(ToDuration("4m"), qt.Equals, 4*time.Minute) + c.Assert(ToDuration("asdfadf"), qt.Equals, time.Duration(0)) + +} |