2018-01-07 21:00:56 +01:00
|
|
|
package duration
|
2017-01-29 18:30:08 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
2018-01-02 09:50:00 +01:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2017-01-29 18:30:08 +01: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.
|
2018-01-13 14:57:10 +01:00
|
|
|
func (d *Duration) UnmarshalText(data []byte) error {
|
|
|
|
|
2017-01-29 18:30:08 +01:00
|
|
|
// " + int + unit + "
|
2017-04-10 18:54:12 +02:00
|
|
|
if len(data) < 2 {
|
|
|
|
return fmt.Errorf("invalid duration: \"%s\"", data)
|
2017-01-29 18:30:08 +01:00
|
|
|
}
|
|
|
|
|
2017-04-10 18:54:12 +02:00
|
|
|
unit := data[len(data)-1]
|
|
|
|
value, err := strconv.Atoi(string(data[:len(data)-1]))
|
2017-01-29 18:30:08 +01:00
|
|
|
if err != nil {
|
2018-01-02 09:50:00 +01:00
|
|
|
return errors.Wrapf(err, "unable to parse duration \"%s\"", data)
|
2017-01-29 18:30:08 +01: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 09:50:00 +01:00
|
|
|
return fmt.Errorf("invalid duration unit \"%s\"", string(unit))
|
2017-01-29 18:30:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|