parser.go 5.4 KB

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