parser.go 9.3 KB

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