Skip to content
This repository has been archived by the owner on Jan 11, 2019. It is now read-only.

Commit

Permalink
Implement UnmarshalYAML
Browse files Browse the repository at this point in the history
  • Loading branch information
jianli committed Aug 16, 2018
1 parent 88b0669 commit cc9f595
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
19 changes: 19 additions & 0 deletions cronexpr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]])
Expand Down Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions cronexpr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ package cronexpr
import (
"testing"
"time"

yaml "gopkg.in/yaml.v2"
)

/******************************************************************************/
Expand Down Expand Up @@ -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",
Expand Down

0 comments on commit cc9f595

Please sign in to comment.