parser.go 7.6 KB

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