parser.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 5 or 6 fields.
  20. // (second) (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 sixth 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. // parseDescriptor returns a pre-defined schedule for the expression, or panics
  136. // if none matches.
  137. func parseDescriptor(spec string) Schedule {
  138. switch spec {
  139. case "@yearly", "@annually":
  140. return &SpecSchedule{
  141. Second: 1 << seconds.min,
  142. Minute: 1 << minutes.min,
  143. Hour: 1 << hours.min,
  144. Dom: 1 << dom.min,
  145. Month: 1 << months.min,
  146. Dow: all(dow),
  147. }
  148. case "@monthly":
  149. return &SpecSchedule{
  150. Second: 1 << seconds.min,
  151. Minute: 1 << minutes.min,
  152. Hour: 1 << hours.min,
  153. Dom: 1 << dom.min,
  154. Month: all(months),
  155. Dow: all(dow),
  156. }
  157. case "@weekly":
  158. return &SpecSchedule{
  159. Second: 1 << seconds.min,
  160. Minute: 1 << minutes.min,
  161. Hour: 1 << hours.min,
  162. Dom: all(dom),
  163. Month: all(months),
  164. Dow: 1 << dow.min,
  165. }
  166. case "@daily", "@midnight":
  167. return &SpecSchedule{
  168. Second: 1 << seconds.min,
  169. Minute: 1 << minutes.min,
  170. Hour: 1 << hours.min,
  171. Dom: all(dom),
  172. Month: all(months),
  173. Dow: all(dow),
  174. }
  175. case "@hourly":
  176. return &SpecSchedule{
  177. Second: 1 << seconds.min,
  178. Minute: 1 << minutes.min,
  179. Hour: all(hours),
  180. Dom: all(dom),
  181. Month: all(months),
  182. Dow: all(dow),
  183. }
  184. }
  185. const every = "@every "
  186. if strings.HasPrefix(spec, every) {
  187. duration, err := time.ParseDuration(spec[len(every):])
  188. if err != nil {
  189. log.Panicf("Failed to parse duration %s: %s", spec, err)
  190. }
  191. return Every(duration)
  192. }
  193. log.Panicf("Unrecognized descriptor: %s", spec)
  194. return nil
  195. }