parser.go 6.5 KB

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