2018-01-07 20:00:56 +00:00
|
|
|
package duration
|
2017-01-29 17:30:08 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
2018-01-02 08:50:00 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2017-01-29 17:30:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Duration is a TOML datatype
|
|
|
|
// A duration string is a possibly signed sequence of
|
|
|
|
// decimal numbers and a unit suffix,
|
|
|
|
// such as "300s", "1.5h" or "5d".
|
|
|
|
// Valid time units are "s", "m", "h", "d", "w".
|
|
|
|
type Duration struct {
|
|
|
|
time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalTOML parses a duration string.
|
2017-04-10 16:54:12 +00:00
|
|
|
func (d *Duration) UnmarshalTOML(dataInterface interface{}) error {
|
|
|
|
var data string
|
|
|
|
switch dataInterface.(type) {
|
|
|
|
case string:
|
|
|
|
data = dataInterface.(string)
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid duration: \"%s\"", dataInterface)
|
|
|
|
}
|
2017-01-29 17:30:08 +00:00
|
|
|
// " + int + unit + "
|
2017-04-10 16:54:12 +00:00
|
|
|
if len(data) < 2 {
|
|
|
|
return fmt.Errorf("invalid duration: \"%s\"", data)
|
2017-01-29 17:30:08 +00:00
|
|
|
}
|
|
|
|
|
2017-04-10 16:54:12 +00:00
|
|
|
unit := data[len(data)-1]
|
|
|
|
value, err := strconv.Atoi(string(data[:len(data)-1]))
|
2017-01-29 17:30:08 +00:00
|
|
|
if err != nil {
|
2018-01-02 08:50:00 +00:00
|
|
|
return errors.Wrapf(err, "unable to parse duration \"%s\"", data)
|
2017-01-29 17:30:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
switch unit {
|
|
|
|
case 's':
|
|
|
|
d.Duration = time.Duration(value) * time.Second
|
|
|
|
case 'm':
|
|
|
|
d.Duration = time.Duration(value) * time.Minute
|
|
|
|
case 'h':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour
|
|
|
|
case 'd':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour * 24
|
|
|
|
case 'w':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour * 24 * 7
|
|
|
|
case 'y':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour * 24 * 365
|
|
|
|
default:
|
2018-01-02 08:50:00 +00:00
|
|
|
return fmt.Errorf("invalid duration unit \"%s\"", string(unit))
|
2017-01-29 17:30:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|