parser.go 7.9 KB

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