commands: Make the --poll flag a duration

So you can do:

```
hugo server --poll 700ms
```

See #8720
This commit is contained in:
Bjørn Erik Pedersen
2021-07-05 10:13:41 +02:00
parent 43a23239b2
commit e31b1d1946
9 changed files with 56 additions and 18 deletions

View File

@@ -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 {

View File

@@ -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))
}