Implement UnmarshalYAML
This commit is contained in:
parent
88b0669f7d
commit
cc9f59582a
19
cronexpr.go
19
cronexpr.go
|
@ -44,6 +44,10 @@ type Expression struct {
|
|||
yearList []int
|
||||
}
|
||||
|
||||
func (expr Expression) String() string {
|
||||
return fmt.Sprintf("(%s)", expr.expression)
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
|
||||
// MustParse returns a new Expression pointer. It expects a well-formed cron
|
||||
|
@ -85,6 +89,7 @@ func Parse(cronLine string) (*Expression, error) {
|
|||
var field = 0
|
||||
var err error
|
||||
|
||||
expr.expression = cronLine
|
||||
// second field (optional)
|
||||
if fieldCount == 7 {
|
||||
err = expr.secondFieldHandler(cron[indices[field][0]:indices[field][1]])
|
||||
|
@ -144,6 +149,20 @@ func Parse(cronLine string) (*Expression, error) {
|
|||
return &expr, nil
|
||||
}
|
||||
|
||||
func (expr *Expression) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||
var cronLine string
|
||||
if err := unmarshal(&cronLine); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
expression, err := Parse(cronLine)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*expr = *expression
|
||||
return nil
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
|
||||
// Next returns the closest time instant immediately following `fromTime` which
|
||||
|
|
|
@ -17,6 +17,8 @@ package cronexpr
|
|||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
/******************************************************************************/
|
||||
|
@ -236,6 +238,28 @@ func TestZero(t *testing.T) {
|
|||
|
||||
/******************************************************************************/
|
||||
|
||||
type Config struct {
|
||||
Expression Expression `yaml:"Expression"`
|
||||
}
|
||||
|
||||
func TestUnmarshaler(t *testing.T) {
|
||||
var config Config
|
||||
err := yaml.Unmarshal([]byte(`Expression: "* * * * *"`), &config)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error while unmarshaling")
|
||||
}
|
||||
if config.Expression.String() != "(* * * * *)" {
|
||||
t.Errorf("Unexpected value when unmarshaled")
|
||||
}
|
||||
|
||||
err = yaml.Unmarshal([]byte(`Expression: * * * * *`), &config)
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error")
|
||||
}
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
|
||||
func TestNextN(t *testing.T) {
|
||||
expected := []string{
|
||||
"Sat, 30 Nov 2013 00:00:00",
|
||||
|
|
Loading…
Reference in New Issue