Debian Codegraph @

cron_descriptor/ExpressionParser.py

raw
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
23 import re
24 from typing import ClassVar
25
26 from .Exception import FormatError, MissingFieldError
27 from .Options import Options
28
29
30 class ExpressionParser:
31 _expression = ""
32 _options: Options
33
34 _cron_days: ClassVar[dict[int, str]] = {
35 0: "SUN",
36 1: "MON",
37 2: "TUE",
38 3: "WED",
39 4: "THU",
40 5: "FRI",
41 6: "SAT",
42 }
43
44 _cron_months: ClassVar[dict[int, str]] = {
45 1: "JAN",
46 2: "FEB",
47 3: "MAR",
48 4: "APR",
49 5: "MAY",
50 6: "JUN",
51 7: "JUL",
52 8: "AUG",
53 9: "SEP",
54 10: "OCT",
55 11: "NOV",
56 12: "DEC",
57 }
58
59 def __init__(self, expression: str, options: Options) -> None:
60 """Initializes a new instance of the ExpressionParser class
61 Args:
62 expression: The cron expression string
63 options: Parsing options
64
65 """
66 self._expression = expression
67 self._options = options
68
69 def parse(self) -> list[str]:
70 """Parses the cron expression string
71 Returns:
72 A 7 part string array, one part for each component of the cron expression (seconds, minutes, etc.)
73
74 Raises:
75 MissingFieldException: if _expression is empty or None
76 FormatException: if _expression has wrong format
77
78 """
79 # Initialize all elements of parsed array to empty strings
80 parsed = ["", "", "", "", "", "", ""]
81
82 if not self._expression:
83 msg = "ExpressionDescriptor.expression"
84 raise MissingFieldError(msg)
85
86 expression_parts_temp = self._expression.split()
87 expression_parts_temp_length = len(expression_parts_temp)
88 if expression_parts_temp_length < 5:
89 msg = f"Error: Expression only has {expression_parts_temp_length} parts. At least 5 part are required."
90 raise FormatError(msg)
91 if expression_parts_temp_length == 5:
92 # 5 part cron so shift array past seconds element
93 for i, expression_part_temp in enumerate(expression_parts_temp):
94 parsed[i + 1] = expression_part_temp
95 elif expression_parts_temp_length == 6:
96 # We will detect if this 6 part expression has a year specified and if so we will shift the parts and treat the
97 # first part as a minute part rather than a second part.
98 # Ways we detect:
99 # 1. Last part is a literal year (i.e. 2020)
100 # 2. 3rd or 5th part is specified as "?" (DOM or DOW)
101 year_regex = re.compile(r"\d{4}$")
102 is_year_with_no_seconds_part = bool(year_regex.search(expression_parts_temp[5])) or "?" in [expression_parts_temp[4], expression_parts_temp[2]]
103 for i, expression_part_temp in enumerate(expression_parts_temp):
104 if is_year_with_no_seconds_part:
105 # Shift parts over by one
106 parsed[i + 1] = expression_part_temp
107 else:
108 parsed[i] = expression_part_temp
109
110 elif expression_parts_temp_length == 7:
111 parsed = expression_parts_temp
112 else:
113 msg = f"Error: Expression has too many parts ({expression_parts_temp_length}). Expression must not have more than 7 parts."
114 raise FormatError(msg)
115 self.normalize_expression(parsed)
116
117 return parsed
118
119 def normalize_expression(self, expression_parts: list[str]) -> None:
120 """Converts cron expression components into consistent, predictable formats.
121
122 Args:
123 expression_parts: A 7 part string array, one part for each component of the cron expression
124 Returns:
125 None
126
127 """
128 # convert ? to * only for DOM and DOW
129 expression_parts[3] = expression_parts[3].replace("?", "*")
130 expression_parts[5] = expression_parts[5].replace("?", "*")
131
132 # convert 0/, 1/ to */
133 if expression_parts[0].startswith("0/"):
134 expression_parts[0] = expression_parts[0].replace("0/", "*/") # seconds
135
136 if expression_parts[1].startswith("0/"):
137 expression_parts[1] = expression_parts[1].replace("0/", "*/") # minutes
138
139 if expression_parts[2].startswith("0/"):
140 expression_parts[2] = expression_parts[2].replace("0/", "*/") # hours
141
142 if expression_parts[3].startswith("1/"):
143 expression_parts[3] = expression_parts[3].replace("1/", "*/") # DOM
144
145 if expression_parts[4].startswith("1/"):
146 expression_parts[4] = expression_parts[4].replace("1/", "*/") # Month
147
148 if expression_parts[5].startswith("1/"):
149 expression_parts[5] = expression_parts[5].replace("1/", "*/") # DOW
150
151 if expression_parts[6].startswith("1/"):
152 expression_parts[6] = expression_parts[6].replace("1/", "*/") # Years
153
154 # Adjust DOW based on dayOfWeekStartIndexZero option
155 def digit_replace(match: re.Match[str]) -> str:
156 match_value = match.group()
157 dow_digits = re.sub(r"\D", "", match_value)
158 dow_digits_adjusted = dow_digits
159 if self._options.day_of_week_start_index_zero:
160 if dow_digits == "7":
161 dow_digits_adjusted = "0"
162 else:
163 dow_digits_adjusted = str(int(dow_digits) - 1)
164
165 return match_value.replace(dow_digits, dow_digits_adjusted)
166
167 expression_parts[5] = re.sub(r"(^\d)|([^#/\s]\d)", digit_replace, expression_parts[5])
168
169 # Convert DOM '?' to '*'
170 if expression_parts[3] == "?":
171 expression_parts[3] = "*"
172
173 # convert SUN-SAT format to 0-6 format
174 for day_number in self._cron_days:
175 expression_parts[5] = expression_parts[5].upper().replace(self._cron_days[day_number], str(day_number))
176
177 # convert JAN-DEC format to 1-12 format
178 for month_number in self._cron_months:
179 expression_parts[4] = expression_parts[4].upper().replace(
180 self._cron_months[month_number], str(month_number))
181
182 # convert 0 second to (empty)
183 if expression_parts[0] == "0":
184 expression_parts[0] = ""
185
186 # If time interval is specified for seconds or minutes and next time part is single item, make it a "self-range" so
187 # the expression can be interpreted as an interval 'between' range.
188 # For example:
189 # 0-20/3 9 * * * => 0-20/3 9-9 * * * (9 => 9-9)
190 # */5 3 * * * => */5 3-3 * * * (3 => 3-3)
191 star_and_slash = ["*", "/"]
192 has_part_zero_star_and_slash = any(ext in expression_parts[0] for ext in star_and_slash)
193 has_part_one_star_and_slash = any(ext in expression_parts[1] for ext in star_and_slash)
194 has_part_two_special_chars = any(ext in expression_parts[2] for ext in ["*", "-", ",", "/"])
195 if not has_part_two_special_chars and (has_part_zero_star_and_slash or has_part_one_star_and_slash):
196 expression_parts[2] += f"-{expression_parts[2]}"
197
198 # Loop through all parts and apply global normalization
199 length = len(expression_parts)
200 for i in range(length):
201
202 # convert all '*/1' to '*'
203 if expression_parts[i] == "*/1":
204 expression_parts[i] = "*"
205
206 """
207 Convert Month,DOW,Year step values with a starting value (i.e. not '*') to between expressions.
208 This allows us to reuse the between expression handling for step values.
209
210 For Example:
211 - month part '3/2' will be converted to '3-12/2' (every 2 months between March and December)
212 - DOW part '3/2' will be converted to '3-6/2' (every 2 days between Tuesday and Saturday)
213 """
214
215 if "/" in expression_parts[i] and not any(exp in expression_parts[i] for exp in ["*", "-", ","]):
216 choices = {
217 4: "12",
218 5: "6",
219 6: "9999",
220 }
221
222 step_range_through = choices.get(i)
223
224 if step_range_through is not None:
225 parts = expression_parts[i].split("/")
226 expression_parts[i] = f"{parts[0]}-{step_range_through}/{parts[1]}"