parser.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package cron
  2. import (
  3. "fmt"
  4. "log"
  5. "math"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. // Parse returns a new crontab schedule representing the given spec.
  11. // It returns a descriptive error if the spec is not valid.
  12. //
  13. // It accepts
  14. // - Full crontab specs, e.g. "* * * * * ?"
  15. // - Descriptors, e.g. "@midnight", "@every 1h30m"
  16. func Parse(spec string) (_ Schedule, err error) {
  17. // Convert panics into errors
  18. defer func() {
  19. if recovered := recover(); recovered != nil {
  20. err = fmt.Errorf("%v", recovered)
  21. }
  22. }()
  23. if spec[0] == '@' {
  24. return parseDescriptor(spec), nil
  25. }
  26. // Split on whitespace. We require 5 or 6 fields.
  27. // (second) (minute) (hour) (day of month) (month) (day of week, optional)
  28. fields := strings.Fields(spec)
  29. if len(fields) != 5 && len(fields) != 6 {
  30. log.Panicf("Expected 5 or 6 fields, found %d: %s", len(fields), spec)
  31. }
  32. // If a sixth field is not provided (DayOfWeek), then it is equivalent to star.
  33. if len(fields) == 5 {
  34. fields = append(fields, "*")
  35. }
  36. schedule := &SpecSchedule{
  37. Second: getField(fields[0], seconds),
  38. Minute: getField(fields[1], minutes),
  39. Hour: getField(fields[2], hours),
  40. Dom: getField(fields[3], dom),
  41. Month: getField(fields[4], months),
  42. Dow: getField(fields[5], dow),
  43. }
  44. return schedule, nil
  45. }
  46. // getField returns an Int with the bits set representing all of the times that
  47. // the field represents. A "field" is a comma-separated list of "ranges".
  48. func getField(field string, r bounds) uint64 {
  49. // list = range {"," range}
  50. var bits uint64
  51. ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' })
  52. for _, expr := range ranges {
  53. bits |= getRange(expr, r)
  54. }
  55. return bits
  56. }
  57. // getRange returns the bits indicated by the given expression:
  58. // number | number "-" number [ "/" number ]
  59. func getRange(expr string, r bounds) uint64 {
  60. var (
  61. start, end, step uint
  62. rangeAndStep = strings.Split(expr, "/")
  63. lowAndHigh = strings.Split(rangeAndStep[0], "-")
  64. singleDigit = len(lowAndHigh) == 1
  65. )
  66. var extra_star uint64
  67. if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" {
  68. start = r.min
  69. end = r.max
  70. extra_star = starBit
  71. } else {
  72. start = parseIntOrName(lowAndHigh[0], r.names)
  73. switch len(lowAndHigh) {
  74. case 1:
  75. end = start
  76. case 2:
  77. end = parseIntOrName(lowAndHigh[1], r.names)
  78. default:
  79. log.Panicf("Too many hyphens: %s", expr)
  80. }
  81. }
  82. switch len(rangeAndStep) {
  83. case 1:
  84. step = 1
  85. case 2:
  86. step = mustParseInt(rangeAndStep[1])
  87. // Special handling: "N/step" means "N-max/step".
  88. if singleDigit {
  89. end = r.max
  90. }
  91. default:
  92. log.Panicf("Too many slashes: %s", expr)
  93. }
  94. if start < r.min {
  95. log.Panicf("Beginning of range (%d) below minimum (%d): %s", start, r.min, expr)
  96. }
  97. if end > r.max {
  98. log.Panicf("End of range (%d) above maximum (%d): %s", end, r.max, expr)
  99. }
  100. if start > end {
  101. log.Panicf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr)
  102. }
  103. if step == 0 {
  104. log.Panicf("Step of range should be a positive number: %s", expr)
  105. }
  106. return getBits(start, end, step) | extra_star
  107. }
  108. // parseIntOrName returns the (possibly-named) integer contained in expr.
  109. func parseIntOrName(expr string, names map[string]uint) uint {
  110. if names != nil {
  111. if namedInt, ok := names[strings.ToLower(expr)]; ok {
  112. return namedInt
  113. }
  114. }
  115. return mustParseInt(expr)
  116. }
  117. // mustParseInt parses the given expression as an int or panics.
  118. func mustParseInt(expr string) uint {
  119. num, err := strconv.Atoi(expr)
  120. if err != nil {
  121. log.Panicf("Failed to parse int from %s: %s", expr, err)
  122. }
  123. if num < 0 {
  124. log.Panicf("Negative number (%d) not allowed: %s", num, expr)
  125. }
  126. return uint(num)
  127. }
  128. // getBits sets all bits in the range [min, max], modulo the given step size.
  129. func getBits(min, max, step uint) uint64 {
  130. var bits uint64
  131. // If step is 1, use shifts.
  132. if step == 1 {
  133. return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)
  134. }
  135. // Else, use a simple loop.
  136. for i := min; i <= max; i += step {
  137. bits |= 1 << i
  138. }
  139. return bits
  140. }
  141. // all returns all bits within the given bounds. (plus the star bit)
  142. func all(r bounds) uint64 {
  143. return getBits(r.min, r.max, 1) | starBit
  144. }
  145. // parseDescriptor returns a pre-defined schedule for the expression, or panics
  146. // if none matches.
  147. func parseDescriptor(spec string) Schedule {
  148. switch spec {
  149. case "@yearly", "@annually":
  150. return &SpecSchedule{
  151. Second: 1 << seconds.min,
  152. Minute: 1 << minutes.min,
  153. Hour: 1 << hours.min,
  154. Dom: 1 << dom.min,
  155. Month: 1 << months.min,
  156. Dow: all(dow),
  157. }
  158. case "@monthly":
  159. return &SpecSchedule{
  160. Second: 1 << seconds.min,
  161. Minute: 1 << minutes.min,
  162. Hour: 1 << hours.min,
  163. Dom: 1 << dom.min,
  164. Month: all(months),
  165. Dow: all(dow),
  166. }
  167. case "@weekly":
  168. return &SpecSchedule{
  169. Second: 1 << seconds.min,
  170. Minute: 1 << minutes.min,
  171. Hour: 1 << hours.min,
  172. Dom: all(dom),
  173. Month: all(months),
  174. Dow: 1 << dow.min,
  175. }
  176. case "@daily", "@midnight":
  177. return &SpecSchedule{
  178. Second: 1 << seconds.min,
  179. Minute: 1 << minutes.min,
  180. Hour: 1 << hours.min,
  181. Dom: all(dom),
  182. Month: all(months),
  183. Dow: all(dow),
  184. }
  185. case "@hourly":
  186. return &SpecSchedule{
  187. Second: 1 << seconds.min,
  188. Minute: 1 << minutes.min,
  189. Hour: all(hours),
  190. Dom: all(dom),
  191. Month: all(months),
  192. Dow: all(dow),
  193. }
  194. }
  195. const every = "@every "
  196. if strings.HasPrefix(spec, every) {
  197. duration, err := time.ParseDuration(spec[len(every):])
  198. if err != nil {
  199. log.Panicf("Failed to parse duration %s: %s", spec, err)
  200. }
  201. return Every(duration)
  202. }
  203. log.Panicf("Unrecognized descriptor: %s", spec)
  204. return nil
  205. }