parser.go 6.7 KB

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