ExpressionDescriptor.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2016 Adam Schubert
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import re
  23. import datetime
  24. import calendar
  25. from .GetText import GetText
  26. from .CasingTypeEnum import CasingTypeEnum
  27. from .DescriptionTypeEnum import DescriptionTypeEnum
  28. from .ExpressionParser import ExpressionParser
  29. from .Options import Options
  30. from .StringBuilder import StringBuilder
  31. from .Exception import FormatException, WrongArgumentException
  32. class ExpressionDescriptor:
  33. """
  34. Converts a Cron Expression into a human readable string
  35. """
  36. _special_characters = ['/', '-', ',', '*']
  37. _expression = ''
  38. _options = None
  39. _expression_parts = []
  40. def __init__(self, expression, options=None, **kwargs):
  41. """Initializes a new instance of the ExpressionDescriptor
  42. Args:
  43. expression: The cron expression string
  44. options: Options to control the output description
  45. Raises:
  46. WrongArgumentException: if kwarg is unknown
  47. """
  48. if options is None:
  49. options = Options()
  50. self._expression = expression
  51. self._options = options
  52. self._expression_parts = []
  53. # if kwargs in _options, overwrite it, if not raise exception
  54. for kwarg in kwargs:
  55. if hasattr(self._options, kwarg):
  56. setattr(self._options, kwarg, kwargs[kwarg])
  57. else:
  58. raise WrongArgumentException("Unknown {} configuration argument".format(kwarg))
  59. # Initializes localization
  60. self.get_text = GetText(options.locale_code, options.locale_location)
  61. # Parse expression
  62. parser = ExpressionParser(self._expression, self._options)
  63. self._expression_parts = parser.parse()
  64. def _(self, message):
  65. return self.get_text.trans.gettext(message)
  66. def get_description(self, description_type=DescriptionTypeEnum.FULL):
  67. """Generates a humanreadable string for the Cron Expression
  68. Args:
  69. description_type: Which part(s) of the expression to describe
  70. Returns:
  71. The cron expression description
  72. Raises:
  73. Exception:
  74. """
  75. choices = {
  76. DescriptionTypeEnum.FULL: self.get_full_description,
  77. DescriptionTypeEnum.TIMEOFDAY: self.get_time_of_day_description,
  78. DescriptionTypeEnum.HOURS: self.get_hours_description,
  79. DescriptionTypeEnum.MINUTES: self.get_minutes_description,
  80. DescriptionTypeEnum.SECONDS: self.get_seconds_description,
  81. DescriptionTypeEnum.DAYOFMONTH: self.get_day_of_month_description,
  82. DescriptionTypeEnum.MONTH: self.get_month_description,
  83. DescriptionTypeEnum.DAYOFWEEK: self.get_day_of_week_description,
  84. DescriptionTypeEnum.YEAR: self.get_year_description,
  85. }
  86. return choices.get(description_type, self.get_seconds_description)()
  87. def get_full_description(self):
  88. """Generates the FULL description
  89. Returns:
  90. The FULL description
  91. Raises:
  92. FormatException: if formatting fails
  93. """
  94. try:
  95. time_segment = self.get_time_of_day_description()
  96. day_of_month_desc = self.get_day_of_month_description()
  97. month_desc = self.get_month_description()
  98. day_of_week_desc = self.get_day_of_week_description()
  99. year_desc = self.get_year_description()
  100. description = "{0}{1}{2}{3}{4}".format(
  101. time_segment,
  102. day_of_month_desc,
  103. day_of_week_desc,
  104. month_desc,
  105. year_desc)
  106. description = self.transform_verbosity(description, self._options.verbose)
  107. description = ExpressionDescriptor.transform_case(description, self._options.casing_type)
  108. except Exception:
  109. description = self._(
  110. "An error occurred when generating the expression description. Check the cron expression syntax."
  111. )
  112. raise FormatException(description)
  113. return description
  114. def get_time_of_day_description(self):
  115. """Generates a description for only the TIMEOFDAY portion of the expression
  116. Returns:
  117. The TIMEOFDAY description
  118. """
  119. seconds_expression = self._expression_parts[0]
  120. minute_expression = self._expression_parts[1]
  121. hour_expression = self._expression_parts[2]
  122. description = StringBuilder()
  123. # handle special cases first
  124. if any(exp in minute_expression for exp in self._special_characters) is False and \
  125. any(exp in hour_expression for exp in self._special_characters) is False and \
  126. any(exp in seconds_expression for exp in self._special_characters) is False:
  127. # specific time of day (i.e. 10 14)
  128. description.append(self._("At "))
  129. description.append(
  130. self.format_time(
  131. hour_expression,
  132. minute_expression,
  133. seconds_expression))
  134. elif seconds_expression == "" and "-" in minute_expression and \
  135. "," not in minute_expression and \
  136. any(exp in hour_expression for exp in self._special_characters) is False:
  137. # minute range in single hour (i.e. 0-10 11)
  138. minute_parts = minute_expression.split('-')
  139. description.append(self._("Every minute between {0} and {1}").format(
  140. self.format_time(hour_expression, minute_parts[0]), self.format_time(hour_expression, minute_parts[1])))
  141. elif seconds_expression == "" and "," in hour_expression and "-" not in hour_expression and \
  142. any(exp in minute_expression for exp in self._special_characters) is False:
  143. # hours list with single minute (o.e. 30 6,14,16)
  144. hour_parts = hour_expression.split(',')
  145. description.append(self._("At"))
  146. for i, hour_part in enumerate(hour_parts):
  147. description.append(" ")
  148. description.append(self.format_time(hour_part, minute_expression))
  149. if i < (len(hour_parts) - 2):
  150. description.append(",")
  151. if i == len(hour_parts) - 2:
  152. description.append(self._(" and"))
  153. else:
  154. # default time description
  155. seconds_description = self.get_seconds_description()
  156. minutes_description = self.get_minutes_description()
  157. hours_description = self.get_hours_description()
  158. description.append(seconds_description)
  159. if description and minutes_description:
  160. description.append(", ")
  161. description.append(minutes_description)
  162. if description and hours_description:
  163. description.append(", ")
  164. description.append(hours_description)
  165. return str(description)
  166. def get_seconds_description(self):
  167. """Generates a description for only the SECONDS portion of the expression
  168. Returns:
  169. The SECONDS description
  170. """
  171. def get_description_format(s):
  172. if s == "0":
  173. return ""
  174. try:
  175. if int(s) < 20:
  176. return self._("at {0} seconds past the minute")
  177. else:
  178. return self._("at {0} seconds past the minute [grThen20]") or self._("at {0} seconds past the minute")
  179. except ValueError:
  180. return self._("at {0} seconds past the minute")
  181. return self.get_segment_description(
  182. self._expression_parts[0],
  183. self._("every second"),
  184. lambda s: s,
  185. lambda s: self._("every {0} seconds").format(s),
  186. lambda s: self._("seconds {0} through {1} past the minute"),
  187. get_description_format,
  188. lambda s: self._(", second {0} through second {1}") or self._(", {0} through {1}")
  189. )
  190. def get_minutes_description(self):
  191. """Generates a description for only the MINUTE portion of the expression
  192. Returns:
  193. The MINUTE description
  194. """
  195. seconds_expression = self._expression_parts[0]
  196. def get_description_format(s):
  197. if s == "0" and seconds_expression == "":
  198. return ""
  199. try:
  200. if int(s) < 20:
  201. return self._("at {0} minutes past the hour")
  202. else:
  203. return self._("at {0} minutes past the hour [grThen20]") or self._("at {0} minutes past the hour")
  204. except ValueError:
  205. return self._("at {0} minutes past the hour")
  206. return self.get_segment_description(
  207. self._expression_parts[1],
  208. self._("every minute"),
  209. lambda s: s,
  210. lambda s: self._("every {0} minutes").format(s),
  211. lambda s: self._("minutes {0} through {1} past the hour"),
  212. get_description_format,
  213. lambda s: self._(", minute {0} through minute {1}") or self._(", {0} through {1}")
  214. )
  215. def get_hours_description(self):
  216. """Generates a description for only the HOUR portion of the expression
  217. Returns:
  218. The HOUR description
  219. """
  220. expression = self._expression_parts[2]
  221. return self.get_segment_description(
  222. expression,
  223. self._("every hour"),
  224. lambda s: self.format_time(s, "0"),
  225. lambda s: self._("every {0} hours").format(s),
  226. lambda s: self._("between {0} and {1}"),
  227. lambda s: self._("at {0}"),
  228. lambda s: self._(", hour {0} through hour {1}") or self._(", {0} through {1}")
  229. )
  230. def get_day_of_week_description(self):
  231. """Generates a description for only the DAYOFWEEK portion of the expression
  232. Returns:
  233. The DAYOFWEEK description
  234. """
  235. if self._expression_parts[5] == "*":
  236. # DOW is specified as * so we will not generate a description and defer to DOM part.
  237. # Otherwise, we could get a contradiction like "on day 1 of the month, every day"
  238. # or a dupe description like "every day, every day".
  239. return ""
  240. def get_day_name(s):
  241. exp = s
  242. if "#" in s:
  243. exp, _ = s.split("#", 2)
  244. elif "L" in s:
  245. exp = exp.replace("L", '')
  246. return ExpressionDescriptor.number_to_day(int(exp))
  247. def get_format(s):
  248. if "#" in s:
  249. day_of_week_of_month = s[s.find("#") + 1:]
  250. try:
  251. day_of_week_of_month_number = int(day_of_week_of_month)
  252. choices = {
  253. 1: self._("first"),
  254. 2: self._("second"),
  255. 3: self._("third"),
  256. 4: self._("fourth"),
  257. 5: self._("fifth"),
  258. }
  259. day_of_week_of_month_description = choices.get(day_of_week_of_month_number, '')
  260. except ValueError:
  261. day_of_week_of_month_description = ''
  262. formatted = "{}{}{}".format(self._(", on the "), day_of_week_of_month_description, self._(" {0} of the month"))
  263. elif "L" in s:
  264. formatted = self._(", on the last {0} of the month")
  265. else:
  266. formatted = self._(", only on {0}")
  267. return formatted
  268. return self.get_segment_description(
  269. self._expression_parts[5],
  270. self._(", every day"),
  271. lambda s: get_day_name(s),
  272. lambda s: self._(", every {0} days of the week").format(s),
  273. lambda s: self._(", {0} through {1}"),
  274. lambda s: get_format(s),
  275. lambda s: self._(", {0} through {1}")
  276. )
  277. def get_month_description(self):
  278. """Generates a description for only the MONTH portion of the expression
  279. Returns:
  280. The MONTH description
  281. """
  282. return self.get_segment_description(
  283. self._expression_parts[4],
  284. '',
  285. lambda s: datetime.date(datetime.date.today().year, int(s), 1).strftime("%B"),
  286. lambda s: self._(", every {0} months").format(s),
  287. lambda s: self._(", month {0} through month {1}") or self._(", {0} through {1}"),
  288. lambda s: self._(", only in {0}"),
  289. lambda s: self._(", month {0} through month {1}") or self._(", {0} through {1}")
  290. )
  291. def get_day_of_month_description(self):
  292. """Generates a description for only the DAYOFMONTH portion of the expression
  293. Returns:
  294. The DAYOFMONTH description
  295. """
  296. expression = self._expression_parts[3]
  297. if expression == "L":
  298. description = self._(", on the last day of the month")
  299. elif expression == "LW" or expression == "WL":
  300. description = self._(", on the last weekday of the month")
  301. else:
  302. regex = re.compile(r"(\d{1,2}W)|(W\d{1,2})")
  303. m = regex.match(expression)
  304. if m: # if matches
  305. day_number = int(m.group().replace("W", ""))
  306. day_string = self._("first weekday") if day_number == 1 else self._("weekday nearest day {0}").format(day_number)
  307. description = self._(", on the {0} of the month").format(day_string)
  308. else:
  309. # Handle "last day offset"(i.e.L - 5: "5 days before the last day of the month")
  310. regex = re.compile(r"L-(\d{1,2})")
  311. m = regex.match(expression)
  312. if m: # if matches
  313. off_set_days = m.group(1)
  314. description = self._(", {0} days before the last day of the month").format(off_set_days)
  315. else:
  316. description = self.get_segment_description(
  317. expression,
  318. self._(", every day"),
  319. lambda s: s,
  320. lambda s: self._(", every day") if s == "1" else self._(", every {0} days"),
  321. lambda s: self._(", between day {0} and {1} of the month"),
  322. lambda s: self._(", on day {0} of the month"),
  323. lambda s: self._(", {0} through {1}")
  324. )
  325. return description
  326. def get_year_description(self):
  327. """Generates a description for only the YEAR portion of the expression
  328. Returns:
  329. The YEAR description
  330. """
  331. def format_year(s):
  332. regex = re.compile(r"^\d+$")
  333. if regex.match(s):
  334. year_int = int(s)
  335. if year_int < 1900:
  336. return year_int
  337. return datetime.date(year_int, 1, 1).strftime("%Y")
  338. else:
  339. return s
  340. return self.get_segment_description(
  341. self._expression_parts[6],
  342. '',
  343. lambda s: format_year(s),
  344. lambda s: self._(", every {0} years").format(s),
  345. lambda s: self._(", year {0} through year {1}") or self._(", {0} through {1}"),
  346. lambda s: self._(", only in {0}"),
  347. lambda s: self._(", year {0} through year {1}") or self._(", {0} through {1}")
  348. )
  349. def get_segment_description(
  350. self,
  351. expression,
  352. all_description,
  353. get_single_item_description,
  354. get_interval_description_format,
  355. get_between_description_format,
  356. get_description_format,
  357. get_range_format
  358. ):
  359. """Returns segment description
  360. Args:
  361. expression: Segment to descript
  362. all_description: *
  363. get_single_item_description: 1
  364. get_interval_description_format: 1/2
  365. get_between_description_format: 1-2
  366. get_description_format: format get_single_item_description
  367. get_range_format: function that formats range expressions depending on cron parts
  368. Returns:
  369. segment description
  370. """
  371. description = None
  372. if expression is None or expression == '':
  373. description = ''
  374. elif expression == "*":
  375. description = all_description
  376. elif any(ext in expression for ext in ['/', '-', ',']) is False:
  377. description = get_description_format(expression).format(get_single_item_description(expression))
  378. elif "/" in expression:
  379. segments = expression.split('/')
  380. description = get_interval_description_format(segments[1]).format(get_single_item_description(segments[1]))
  381. # interval contains 'between' piece (i.e. 2-59/3 )
  382. if "-" in segments[0]:
  383. between_segment_description = self.generate_between_segment_description(
  384. segments[0],
  385. get_between_description_format,
  386. get_single_item_description
  387. )
  388. if not between_segment_description.startswith(", "):
  389. description += ", "
  390. description += between_segment_description
  391. elif any(ext in segments[0] for ext in ['*', ',']) is False:
  392. range_item_description = get_description_format(segments[0]).format(
  393. get_single_item_description(segments[0])
  394. )
  395. range_item_description = range_item_description.replace(", ", "")
  396. description += self._(", starting {0}").format(range_item_description)
  397. elif "," in expression:
  398. segments = expression.split(',')
  399. description_content = ''
  400. for i, segment in enumerate(segments):
  401. if i > 0 and len(segments) > 2:
  402. description_content += ","
  403. if i < len(segments) - 1:
  404. description_content += " "
  405. if i > 0 and len(segments) > 1 and (i == len(segments) - 1 or len(segments) == 2):
  406. description_content += self._(" and ")
  407. if "-" in segment:
  408. between_segment_description = self.generate_between_segment_description(
  409. segment,
  410. get_range_format,
  411. get_single_item_description
  412. )
  413. between_segment_description = between_segment_description.replace(", ", "")
  414. description_content += between_segment_description
  415. else:
  416. description_content += get_single_item_description(segment)
  417. description = get_description_format(expression).format(description_content)
  418. elif "-" in expression:
  419. description = self.generate_between_segment_description(
  420. expression,
  421. get_between_description_format,
  422. get_single_item_description
  423. )
  424. return description
  425. def generate_between_segment_description(
  426. self,
  427. between_expression,
  428. get_between_description_format,
  429. get_single_item_description
  430. ):
  431. """
  432. Generates the between segment description
  433. :param between_expression:
  434. :param get_between_description_format:
  435. :param get_single_item_description:
  436. :return: The between segment description
  437. """
  438. description = ""
  439. between_segments = between_expression.split('-')
  440. between_segment_1_description = get_single_item_description(between_segments[0])
  441. between_segment_2_description = get_single_item_description(between_segments[1])
  442. between_segment_2_description = between_segment_2_description.replace(":00", ":59")
  443. between_description_format = get_between_description_format(between_expression)
  444. description += between_description_format.format(between_segment_1_description, between_segment_2_description)
  445. return description
  446. def format_time(
  447. self,
  448. hour_expression,
  449. minute_expression,
  450. second_expression=''
  451. ):
  452. """Given time parts, will construct a formatted time description
  453. Args:
  454. hour_expression: Hours part
  455. minute_expression: Minutes part
  456. second_expression: Seconds part
  457. Returns:
  458. Formatted time description
  459. """
  460. hour = int(hour_expression)
  461. period = ''
  462. if self._options.use_24hour_time_format is False:
  463. period = self._("PM") if (hour >= 12) else self._("AM")
  464. if period:
  465. # add preceding space
  466. period = " " + period
  467. if hour > 12:
  468. hour -= 12
  469. if hour == 0:
  470. hour = 12
  471. minute = str(int(minute_expression)) # Removes leading zero if any
  472. second = ''
  473. if second_expression is not None and second_expression:
  474. second = "{}{}".format(":", str(int(second_expression)).zfill(2))
  475. return "{0}:{1}{2}{3}".format(str(hour).zfill(2), minute.zfill(2), second, period)
  476. def transform_verbosity(self, description, use_verbose_format):
  477. """Transforms the verbosity of the expression description by stripping verbosity from original description
  478. Args:
  479. description: The description to transform
  480. use_verbose_format: If True, will leave description as it, if False, will strip verbose parts
  481. Returns:
  482. The transformed description with proper verbosity
  483. """
  484. if use_verbose_format is False:
  485. description = description.replace(self._(", every minute"), '')
  486. description = description.replace(self._(", every hour"), '')
  487. description = description.replace(self._(", every day"), '')
  488. description = re.sub(r', ?$', '', description)
  489. return description
  490. @staticmethod
  491. def transform_case(description, case_type):
  492. """Transforms the case of the expression description, based on options
  493. Args:
  494. description: The description to transform
  495. case_type: The casing type that controls the output casing
  496. Returns:
  497. The transformed description with proper casing
  498. """
  499. if case_type == CasingTypeEnum.Sentence:
  500. description = "{}{}".format(
  501. description[0].upper(),
  502. description[1:])
  503. elif case_type == CasingTypeEnum.Title:
  504. description = description.title()
  505. else:
  506. description = description.lower()
  507. return description
  508. @staticmethod
  509. def number_to_day(day_number):
  510. """Returns localized day name by its CRON number
  511. Args:
  512. day_number: Number of a day
  513. Returns:
  514. Day corresponding to day_number
  515. Raises:
  516. IndexError: When day_number is not found
  517. """
  518. try:
  519. return [
  520. calendar.day_name[6],
  521. calendar.day_name[0],
  522. calendar.day_name[1],
  523. calendar.day_name[2],
  524. calendar.day_name[3],
  525. calendar.day_name[4],
  526. calendar.day_name[5]
  527. ][day_number]
  528. except IndexError:
  529. raise IndexError("Day {} is out of range!".format(day_number))
  530. def __str__(self):
  531. return self.get_description()
  532. def __repr__(self):
  533. return self.get_description()
  534. def get_description(expression, options=None):
  535. """Generates a human readable string for the Cron Expression
  536. Args:
  537. expression: The cron expression string
  538. options: Options to control the output description
  539. Returns:
  540. The cron expression description
  541. """
  542. descriptor = ExpressionDescriptor(expression, options)
  543. return descriptor.get_description(DescriptionTypeEnum.FULL)