Explorar o código

Add method capable of parsing standard cron spec

Currently Parse method accepts 5 or 6 entries, where the first field
denotes seconds. ParseStandard method follows standard cron spec
requiring to pass exactly 5 entries where the first is minute and last
is day of week. See https://en.wikipedia.org/wiki/Cron.
Maciej Szulik %!s(int64=9) %!d(string=hai) anos
pai
achega
b43eae7392
Modificáronse 2 ficheiros con 60 adicións e 0 borrados
  1. 40 0
      parser.go
  2. 20 0
      parser_test.go

+ 40 - 0
parser.go

@@ -9,6 +9,46 @@ import (
 	"time"
 )
 
+// ParseStandard returns a new crontab schedule representing the given standardSpec
+// (https://en.wikipedia.org/wiki/Cron). It differs from Parse requiring to always
+// pass 5 entries representing: minute, hour, day of month, month and day of week,
+// in that order. It returns a descriptive error if the spec is not valid.
+//
+// It accepts
+//   - Standard crontab specs, e.g. "* * * * ?"
+//   - Descriptors, e.g. "@midnight", "@every 1h30m"
+func ParseStandard(standardSpec string) (_ Schedule, err error) {
+	// Convert panics into errors
+	defer func() {
+		if recovered := recover(); recovered != nil {
+			err = fmt.Errorf("%v", recovered)
+		}
+	}()
+
+	if standardSpec[0] == '@' {
+		return parseDescriptor(standardSpec), nil
+	}
+
+	// Split on whitespace.  We require exactly 5 fields.
+	// (minute) (hour) (day of month) (month) (day of week)
+	fields := strings.Fields(standardSpec)
+	if len(fields) != 5 {
+		log.Panicf("Expected exactly 5, found %d: %s", len(fields), standardSpec)
+	}
+
+	schedule := &SpecSchedule{
+		Second: 1 << seconds.min,
+		Minute: getField(fields[0], minutes),
+		Hour:   getField(fields[1], hours),
+		Dom:    getField(fields[2], dom),
+		Month:  getField(fields[3], months),
+		Dow:    getField(fields[4], dow),
+	}
+
+	return schedule, nil
+
+}
+
 // Parse returns a new crontab schedule representing the given spec.
 // It returns a descriptive error if the spec is not valid.
 //

+ 20 - 0
parser_test.go

@@ -115,3 +115,23 @@ func TestSpecSchedule(t *testing.T) {
 		}
 	}
 }
+
+func TestStandardSpecSchedule(t *testing.T) {
+	entries := []struct {
+		expr     string
+		expected Schedule
+	}{
+		{"5 * * * *", &SpecSchedule{1 << seconds.min, 1 << 5, all(hours), all(dom), all(months), all(dow)}},
+		{"@every 5m", ConstantDelaySchedule{time.Duration(5) * time.Minute}},
+	}
+
+	for _, c := range entries {
+		actual, err := ParseStandard(c.expr)
+		if err != nil {
+			t.Error(err)
+		}
+		if !reflect.DeepEqual(actual, c.expected) {
+			t.Errorf("%s => (expected) %b != %b (actual)", c.expr, c.expected, actual)
+		}
+	}
+}