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

Implement UnmarshalYAML #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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