| 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 |
from __future__ import annotations |
| 23 |
|
| 24 |
import calendar |
| 25 |
import datetime |
| 26 |
import re |
| 27 |
from typing import Callable, TypedDict |
| 28 |
|
| 29 |
from typing_extensions import Unpack |
| 30 |
|
| 31 |
from .CasingTypeEnum import CasingTypeEnum |
| 32 |
from .DescriptionTypeEnum import DescriptionTypeEnum |
| 33 |
from .Exception import FormatError, WrongArgumentError |
| 34 |
from .ExpressionParser import ExpressionParser |
| 35 |
from .GetText import GetText |
| 36 |
from .Options import Options |
| 37 |
from .StringBuilder import StringBuilder |
| 38 |
|
| 39 |
|
| 40 |
class OptionsKwargs(TypedDict, total=False): |
| 41 |
use_24hour_time_format: bool |
| 42 |
locale_code: str |
| 43 |
casing_type: CasingTypeEnum |
| 44 |
verbose: bool |
| 45 |
day_of_week_start_index_zero: bool |
| 46 |
locale_location: str | None |
| 47 |
|
| 48 |
class ExpressionDescriptor: |
| 49 |
"""Converts a Cron Expression into a human readable string |
| 50 |
""" |
| 51 |
|
| 52 |
_special_characters = ("/", "-", ",", "*") |
| 53 |
|
| 54 |
_expression = "" |
| 55 |
_options: Options |
| 56 |
_expression_parts: list[str] |
| 57 |
|
| 58 |
def __init__(self, expression: str, options: Options | None=None, **kwargs: Unpack[OptionsKwargs]) -> None: |
| 59 |
"""Initializes a new instance of the ExpressionDescriptor |
| 60 |
|
| 61 |
Args: |
| 62 |
expression: The cron expression string |
| 63 |
options: Options to control the output description |
| 64 |
Raises: |
| 65 |
WrongArgumentException: if kwarg is unknown |
| 66 |
|
| 67 |
""" |
| 68 |
if options is None: |
| 69 |
options = Options() |
| 70 |
self._expression = expression |
| 71 |
self._options = options |
| 72 |
self._expression_parts = [] |
| 73 |
|
| 74 |
# if kwargs in _options, overwrite it, if not raise exception |
| 75 |
for kwarg, value in kwargs.items(): |
| 76 |
if hasattr(self._options, kwarg): |
| 77 |
setattr(self._options, kwarg, value) |
| 78 |
else: |
| 79 |
msg = f"Unknown {kwarg} configuration argument" |
| 80 |
raise WrongArgumentError(msg) |
| 81 |
|
| 82 |
# Initializes localization |
| 83 |
self.get_text = GetText(options.locale_code, options.locale_location) |
| 84 |
|
| 85 |
# Parse expression |
| 86 |
parser = ExpressionParser(self._expression, self._options) |
| 87 |
self._expression_parts = parser.parse() |
| 88 |
|
| 89 |
def translate(self, message: str) -> str: |
| 90 |
return self.get_text.trans.gettext(message) |
| 91 |
|
| 92 |
def get_description(self, description_type: DescriptionTypeEnum = DescriptionTypeEnum.FULL) -> str: |
| 93 |
"""Generates a humanreadable string for the Cron Expression |
| 94 |
|
| 95 |
Args: |
| 96 |
description_type: Which part(s) of the expression to describe |
| 97 |
Returns: |
| 98 |
The cron expression description |
| 99 |
Raises: |
| 100 |
Exception: |
| 101 |
|
| 102 |
""" |
| 103 |
choices = { |
| 104 |
DescriptionTypeEnum.FULL: self.get_full_description, |
| 105 |
DescriptionTypeEnum.TIMEOFDAY: self.get_time_of_day_description, |
| 106 |
DescriptionTypeEnum.HOURS: self.get_hours_description, |
| 107 |
DescriptionTypeEnum.MINUTES: self.get_minutes_description, |
| 108 |
DescriptionTypeEnum.SECONDS: self.get_seconds_description, |
| 109 |
DescriptionTypeEnum.DAYOFMONTH: self.get_day_of_month_description, |
| 110 |
DescriptionTypeEnum.MONTH: self.get_month_description, |
| 111 |
DescriptionTypeEnum.DAYOFWEEK: self.get_day_of_week_description, |
| 112 |
DescriptionTypeEnum.YEAR: self.get_year_description, |
| 113 |
} |
| 114 |
|
| 115 |
return choices.get(description_type, self.get_seconds_description)() |
| 116 |
|
| 117 |
def get_full_description(self) -> str: |
| 118 |
"""Generates the FULL description |
| 119 |
|
| 120 |
Returns: |
| 121 |
The FULL description |
| 122 |
Raises: |
| 123 |
FormatException: if formatting fails |
| 124 |
|
| 125 |
""" |
| 126 |
try: |
| 127 |
time_segment = self.get_time_of_day_description() |
| 128 |
day_of_month_desc = self.get_day_of_month_description() |
| 129 |
month_desc = self.get_month_description() |
| 130 |
day_of_week_desc = self.get_day_of_week_description() |
| 131 |
year_desc = self.get_year_description() |
| 132 |
|
| 133 |
description = f"{time_segment}{day_of_month_desc}{day_of_week_desc}{month_desc}{year_desc}" |
| 134 |
|
| 135 |
description = self.transform_verbosity(description, use_verbose_format=self._options.verbose) |
| 136 |
description = ExpressionDescriptor.transform_case(description, self._options.casing_type) |
| 137 |
except Exception as e: |
| 138 |
description = self.translate( |
| 139 |
"An error occurred when generating the expression description. Check the cron expression syntax.", |
| 140 |
) |
| 141 |
raise FormatError(description) from e |
| 142 |
|
| 143 |
return description |
| 144 |
|
| 145 |
def get_time_of_day_description(self) -> str: |
| 146 |
"""Generates a description for only the TIMEOFDAY portion of the expression |
| 147 |
|
| 148 |
Returns: |
| 149 |
The TIMEOFDAY description |
| 150 |
|
| 151 |
""" |
| 152 |
seconds_expression = self._expression_parts[0] |
| 153 |
minute_expression = self._expression_parts[1] |
| 154 |
hour_expression = self._expression_parts[2] |
| 155 |
|
| 156 |
description = StringBuilder() |
| 157 |
|
| 158 |
# handle special cases first |
| 159 |
if any(exp in minute_expression for exp in self._special_characters) is False and \ |
| 160 |
any(exp in hour_expression for exp in self._special_characters) is False and \ |
| 161 |
any(exp in seconds_expression for exp in self._special_characters) is False: |
| 162 |
# specific time of day (i.e. 10 14) |
| 163 |
description.append(self.translate("At ")) |
| 164 |
description.append( |
| 165 |
self.format_time( |
| 166 |
hour_expression, |
| 167 |
minute_expression, |
| 168 |
seconds_expression)) |
| 169 |
elif seconds_expression == "" and "-" in minute_expression and \ |
| 170 |
"," not in minute_expression and \ |
| 171 |
any(exp in hour_expression for exp in self._special_characters) is False: |
| 172 |
# minute range in single hour (i.e. 0-10 11) |
| 173 |
minute_parts = minute_expression.split("-") |
| 174 |
description.append(self.translate("Every minute between {0} and {1}").format( |
| 175 |
self.format_time(hour_expression, minute_parts[0]), self.format_time(hour_expression, minute_parts[1]))) |
| 176 |
elif seconds_expression == "" and "," in hour_expression and "-" not in hour_expression and \ |
| 177 |
any(exp in minute_expression for exp in self._special_characters) is False: |
| 178 |
# hours list with single minute (o.e. 30 6,14,16) |
| 179 |
hour_parts = hour_expression.split(",") |
| 180 |
description.append(self.translate("At")) |
| 181 |
for i, hour_part in enumerate(hour_parts): |
| 182 |
description.append(" ") |
| 183 |
description.append(self.format_time(hour_part, minute_expression)) |
| 184 |
|
| 185 |
if i < (len(hour_parts) - 2): |
| 186 |
description.append(",") |
| 187 |
|
| 188 |
if i == len(hour_parts) - 2: |
| 189 |
description.append(self.translate(" and")) |
| 190 |
else: |
| 191 |
# default time description |
| 192 |
seconds_description = self.get_seconds_description() |
| 193 |
minutes_description = self.get_minutes_description() |
| 194 |
hours_description = self.get_hours_description() |
| 195 |
|
| 196 |
description.append(seconds_description) |
| 197 |
|
| 198 |
if description and minutes_description: |
| 199 |
description.append(", ") |
| 200 |
|
| 201 |
description.append(minutes_description) |
| 202 |
|
| 203 |
if description and hours_description: |
| 204 |
description.append(", ") |
| 205 |
|
| 206 |
description.append(hours_description) |
| 207 |
return str(description) |
| 208 |
|
| 209 |
def get_seconds_description(self) -> str: |
| 210 |
"""Generates a description for only the SECONDS portion of the expression |
| 211 |
|
| 212 |
Returns: |
| 213 |
The SECONDS description |
| 214 |
|
| 215 |
""" |
| 216 |
|
| 217 |
def get_description_format(s: str) -> str: |
| 218 |
if s == "0": |
| 219 |
return "" |
| 220 |
|
| 221 |
try: |
| 222 |
if int(s) < 20: |
| 223 |
return self.translate("at {0} seconds past the minute") |
| 224 |
|
| 225 |
return self.translate("at {0} seconds past the minute [grThen20]") or self.translate("at {0} seconds past the minute") |
| 226 |
except ValueError: |
| 227 |
return self.translate("at {0} seconds past the minute") |
| 228 |
|
| 229 |
return self.get_segment_description( |
| 230 |
self._expression_parts[0], |
| 231 |
self.translate("every second"), |
| 232 |
lambda s: s, |
| 233 |
lambda s: self.translate("every {0} seconds").format(s), |
| 234 |
lambda _: self.translate("seconds {0} through {1} past the minute"), |
| 235 |
get_description_format, |
| 236 |
lambda _: self.translate(", second {0} through second {1}") or self.translate(", {0} through {1}"), |
| 237 |
) |
| 238 |
|
| 239 |
def get_minutes_description(self) -> str: |
| 240 |
"""Generates a description for only the MINUTE portion of the expression |
| 241 |
|
| 242 |
Returns: |
| 243 |
The MINUTE description |
| 244 |
|
| 245 |
""" |
| 246 |
seconds_expression = self._expression_parts[0] |
| 247 |
|
| 248 |
def get_description_format(s: str) -> str: |
| 249 |
if s == "0" and seconds_expression == "": |
| 250 |
return "" |
| 251 |
|
| 252 |
try: |
| 253 |
if int(s) < 20: |
| 254 |
return self.translate("at {0} minutes past the hour") |
| 255 |
|
| 256 |
return self.translate("at {0} minutes past the hour [grThen20]") or self.translate("at {0} minutes past the hour") |
| 257 |
except ValueError: |
| 258 |
return self.translate("at {0} minutes past the hour") |
| 259 |
|
| 260 |
return self.get_segment_description( |
| 261 |
self._expression_parts[1], |
| 262 |
self.translate("every minute"), |
| 263 |
lambda s: s, |
| 264 |
lambda s: self.translate("every {0} minutes").format(s), |
| 265 |
lambda _: self.translate("minutes {0} through {1} past the hour"), |
| 266 |
get_description_format, |
| 267 |
lambda _: self.translate(", minute {0} through minute {1}") or self.translate(", {0} through {1}"), |
| 268 |
) |
| 269 |
|
| 270 |
def get_hours_description(self) -> str: |
| 271 |
"""Generates a description for only the HOUR portion of the expression |
| 272 |
|
| 273 |
Returns: |
| 274 |
The HOUR description |
| 275 |
|
| 276 |
""" |
| 277 |
expression = self._expression_parts[2] |
| 278 |
return self.get_segment_description( |
| 279 |
expression, |
| 280 |
self.translate("every hour"), |
| 281 |
lambda s: self.format_time(s, "0"), |
| 282 |
lambda s: self.translate("every {0} hours").format(s), |
| 283 |
lambda _: self.translate("between {0} and {1}"), |
| 284 |
lambda _: self.translate("at {0}"), |
| 285 |
lambda _: self.translate(", hour {0} through hour {1}") or self.translate(", {0} through {1}"), |
| 286 |
) |
| 287 |
|
| 288 |
def get_day_of_week_description(self) -> str: |
| 289 |
"""Generates a description for only the DAYOFWEEK portion of the expression |
| 290 |
|
| 291 |
Returns: |
| 292 |
The DAYOFWEEK description |
| 293 |
|
| 294 |
""" |
| 295 |
if self._expression_parts[5] == "*": |
| 296 |
# DOW is specified as * so we will not generate a description and defer to DOM part. |
| 297 |
# Otherwise, we could get a contradiction like "on day 1 of the month, every day" |
| 298 |
# or a dupe description like "every day, every day". |
| 299 |
return "" |
| 300 |
|
| 301 |
def get_day_name(s: str) -> str: |
| 302 |
exp = s |
| 303 |
if "#" in s: |
| 304 |
exp, _ = s.split("#", 2) |
| 305 |
elif "L" in s: |
| 306 |
exp = exp.replace("L", "") |
| 307 |
return ExpressionDescriptor.number_to_day(int(exp)) |
| 308 |
|
| 309 |
def get_format(s: str) -> str: |
| 310 |
if "#" in s: |
| 311 |
day_of_week_of_month = s[s.find("#") + 1:] |
| 312 |
|
| 313 |
try: |
| 314 |
day_of_week_of_month_number = int(day_of_week_of_month) |
| 315 |
choices = { |
| 316 |
1: self.translate("first"), |
| 317 |
2: self.translate("second"), |
| 318 |
3: self.translate("third"), |
| 319 |
4: self.translate("fourth"), |
| 320 |
5: self.translate("fifth"), |
| 321 |
} |
| 322 |
day_of_week_of_month_description = choices.get(day_of_week_of_month_number, "") |
| 323 |
except ValueError: |
| 324 |
day_of_week_of_month_description = "" |
| 325 |
|
| 326 |
formatted = "{}{}{}".format(self.translate(", on the "), day_of_week_of_month_description, self.translate(" {0} of the month")) |
| 327 |
elif "L" in s: |
| 328 |
formatted = self.translate(", on the last {0} of the month") |
| 329 |
elif self._expression_parts[3] != "*": |
| 330 |
# When day-of-month is also restricted, cron fires on either match (OR), so prefer |
| 331 |
# "or on"; locales lacking that translation keep their existing "only on" wording. |
| 332 |
formatted = self.translate(", or on {0}") or self.translate(", only on {0}") |
| 333 |
else: |
| 334 |
formatted = self.translate(", only on {0}") |
| 335 |
|
| 336 |
return formatted |
| 337 |
|
| 338 |
# A DOW step on specific days describes a weekly cadence ("every 2 weeks, only on Friday") |
| 339 |
# rather than a within-week one ("every 2 days of the week, Monday through Friday"): a day |
| 340 |
# list always, or a range whose step is >= its size (so at most one day per range fires). |
| 341 |
dow_expression = self._expression_parts[5] |
| 342 |
if "/" in dow_expression: |
| 343 |
base, step = dow_expression.split("/", 1) |
| 344 |
day_description = None |
| 345 |
if "," in base: |
| 346 |
day_description = self.get_segment_description( |
| 347 |
base, |
| 348 |
"", |
| 349 |
get_day_name, |
| 350 |
lambda s: self.translate(", every {0} days of the week").format(s), |
| 351 |
lambda _: self.translate(", {0} through {1}"), |
| 352 |
lambda _: self.translate(", only on {0}"), |
| 353 |
lambda _: self.translate(", {0} through {1}"), |
| 354 |
) |
| 355 |
elif "-" in base: |
| 356 |
range_start, range_end = base.split("-") |
| 357 |
if int(step) >= int(range_end) - int(range_start) + 1: |
| 358 |
if int(range_end) == 6: |
| 359 |
# A single day with a step normalises to <day>-6 (e.g. FRI/2 -> 5-6/2), so an |
| 360 |
# end of 6 means a single day, not a real range; show the start day alone |
| 361 |
# rather than "<day> through Saturday". |
| 362 |
day_description = self.translate(", only on {0}").format(get_day_name(range_start)) |
| 363 |
else: |
| 364 |
day_description = self.generate_between_segment_description( |
| 365 |
base, |
| 366 |
lambda _: self.translate(", {0} through {1}"), |
| 367 |
get_day_name, |
| 368 |
) |
| 369 |
|
| 370 |
if day_description is not None: |
| 371 |
interval_description = ( |
| 372 |
self.translate(", every {0} weeks") or self.translate(", every {0} days of the week") |
| 373 |
).format(step) |
| 374 |
return interval_description + day_description |
| 375 |
|
| 376 |
return self.get_segment_description( |
| 377 |
self._expression_parts[5], |
| 378 |
self.translate(", every day"), |
| 379 |
get_day_name, |
| 380 |
lambda s: self.translate(", every {0} days of the week").format(s), |
| 381 |
lambda _: self.translate(", {0} through {1}"), |
| 382 |
get_format, |
| 383 |
lambda _: self.translate(", {0} through {1}"), |
| 384 |
) |
| 385 |
|
| 386 |
def get_month_description(self) -> str: |
| 387 |
"""Generates a description for only the MONTH portion of the expression |
| 388 |
|
| 389 |
Returns: |
| 390 |
The MONTH description |
| 391 |
|
| 392 |
""" |
| 393 |
return self.get_segment_description( |
| 394 |
self._expression_parts[4], |
| 395 |
"", |
| 396 |
lambda s: datetime.date(datetime.datetime.now(tz=datetime.timezone.utc).date().year, int(s), 1).strftime("%B"), |
| 397 |
lambda s: self.translate(", every {0} months").format(s), |
| 398 |
lambda _: self.translate(", month {0} through month {1}") or self.translate(", {0} through {1}"), |
| 399 |
lambda _: self.translate(", only in {0}"), |
| 400 |
lambda _: self.translate(", month {0} through month {1}") or self.translate(", {0} through {1}"), |
| 401 |
) |
| 402 |
|
| 403 |
def get_day_of_month_description(self) -> str: |
| 404 |
"""Generates a description for only the DAYOFMONTH portion of the expression |
| 405 |
|
| 406 |
Returns: |
| 407 |
The DAYOFMONTH description |
| 408 |
|
| 409 |
""" |
| 410 |
expression = self._expression_parts[3] |
| 411 |
|
| 412 |
if expression == "L": |
| 413 |
description = self.translate(", on the last day of the month") |
| 414 |
elif expression in ("LW", "WL"): |
| 415 |
description = self.translate(", on the last weekday of the month") |
| 416 |
else: |
| 417 |
regex = re.compile(r"(\d{1,2}W)|(W\d{1,2})") |
| 418 |
m = regex.match(expression) |
| 419 |
if m: # if matches |
| 420 |
day_number = int(m.group().replace("W", "")) |
| 421 |
|
| 422 |
day_string = self.translate("first weekday") if day_number == 1 else self.translate("weekday nearest day {0}").format(day_number) |
| 423 |
description = self.translate(", on the {0} of the month").format(day_string) |
| 424 |
elif expression == "*" and self._expression_parts[5] != "*": |
| 425 |
# DOW is specified, but DOM is *, so do not generate DOM description. |
| 426 |
# Otherwise, we could get a contradiction like "every day, on Tuesday" |
| 427 |
description = "" |
| 428 |
else: |
| 429 |
# Handle "last day offset"(i.e.L - 5: "5 days before the last day of the month") |
| 430 |
regex = re.compile(r"L-(\d{1,2})") |
| 431 |
m = regex.match(expression) |
| 432 |
if m: # if matches |
| 433 |
off_set_days = m.group(1) |
| 434 |
description = self.translate(", {0} days before the last day of the month").format(off_set_days) |
| 435 |
else: |
| 436 |
description = self.get_segment_description( |
| 437 |
expression, |
| 438 |
self.translate(", every day"), |
| 439 |
lambda s: s, |
| 440 |
lambda s: self.translate(", every day") if s == "1" else self.translate(", every {0} days"), |
| 441 |
lambda _: self.translate(", between day {0} and {1} of the month"), |
| 442 |
lambda _: self.translate(", on day {0} of the month"), |
| 443 |
lambda _: self.translate(", {0} through {1}"), |
| 444 |
) |
| 445 |
|
| 446 |
return description |
| 447 |
|
| 448 |
def get_year_description(self) -> str: |
| 449 |
"""Generates a description for only the YEAR portion of the expression |
| 450 |
|
| 451 |
Returns: |
| 452 |
The YEAR description |
| 453 |
|
| 454 |
""" |
| 455 |
|
| 456 |
def format_year(s: str) -> str: |
| 457 |
regex = re.compile(r"^\d+$") |
| 458 |
if regex.match(s): |
| 459 |
year_int = int(s) |
| 460 |
if year_int < 1900: |
| 461 |
return str(year_int) |
| 462 |
return datetime.date(year_int, 1, 1).strftime("%Y") |
| 463 |
|
| 464 |
return s |
| 465 |
|
| 466 |
return self.get_segment_description( |
| 467 |
self._expression_parts[6], |
| 468 |
"", |
| 469 |
format_year, |
| 470 |
lambda s: self.translate(", every {0} years").format(s), |
| 471 |
lambda _: self.translate(", year {0} through year {1}") or self.translate(", {0} through {1}"), |
| 472 |
lambda _: self.translate(", only in {0}"), |
| 473 |
lambda _: self.translate(", year {0} through year {1}") or self.translate(", {0} through {1}"), |
| 474 |
) |
| 475 |
|
| 476 |
def get_segment_description( |
| 477 |
self, |
| 478 |
expression: str, |
| 479 |
all_description: str, |
| 480 |
get_single_item_description: Callable[[str], str], |
| 481 |
get_interval_description_format: Callable[[str], str], |
| 482 |
get_between_description_format: Callable[[str], str], |
| 483 |
get_description_format: Callable[[str], str], |
| 484 |
get_range_format: Callable[[str], str], |
| 485 |
) -> str: |
| 486 |
"""Returns segment description |
| 487 |
Args: |
| 488 |
expression: Segment to descript |
| 489 |
all_description: * |
| 490 |
get_single_item_description: 1 |
| 491 |
get_interval_description_format: 1/2 |
| 492 |
get_between_description_format: 1-2 |
| 493 |
get_description_format: format get_single_item_description |
| 494 |
get_range_format: function that formats range expressions depending on cron parts |
| 495 |
Returns: |
| 496 |
segment description |
| 497 |
|
| 498 |
""" |
| 499 |
if not expression: |
| 500 |
return "" |
| 501 |
|
| 502 |
if expression == "*": |
| 503 |
return all_description |
| 504 |
|
| 505 |
if not any(ext in expression for ext in ["/", "-", ","]): |
| 506 |
return get_description_format(expression).format(get_single_item_description(expression)) |
| 507 |
|
| 508 |
if "," in expression: |
| 509 |
segments = expression.split(",") |
| 510 |
|
| 511 |
description_content = "" |
| 512 |
for i, segment in enumerate(segments): |
| 513 |
if i > 0 and len(segments) > 2: |
| 514 |
description_content += "," |
| 515 |
|
| 516 |
if i < len(segments) - 1: |
| 517 |
description_content += " " |
| 518 |
|
| 519 |
if i > 0 and len(segments) > 1 and (i == len(segments) - 1 or len(segments) == 2): |
| 520 |
description_content += self.translate(" and ") |
| 521 |
|
| 522 |
if "/" in segment: |
| 523 |
description_content += self._describe_step_in_comma( |
| 524 |
segment, get_interval_description_format, get_range_format, get_single_item_description, |
| 525 |
) |
| 526 |
elif "-" in segment: |
| 527 |
between_segment_description = self.generate_between_segment_description( |
| 528 |
segment, |
| 529 |
get_range_format, |
| 530 |
get_single_item_description, |
| 531 |
) |
| 532 |
|
| 533 |
between_segment_description = between_segment_description.replace(", ", "") |
| 534 |
|
| 535 |
description_content += between_segment_description |
| 536 |
else: |
| 537 |
description_content += get_single_item_description(segment) |
| 538 |
|
| 539 |
return get_description_format(expression).format(description_content) |
| 540 |
|
| 541 |
if "/" in expression: |
| 542 |
segments = expression.split("/") |
| 543 |
description = get_interval_description_format(segments[1]).format(segments[1]) |
| 544 |
|
| 545 |
# interval contains 'between' piece (i.e. 2-59/3 ) |
| 546 |
if "-" in segments[0]: |
| 547 |
between_segment_description = self.generate_between_segment_description( |
| 548 |
segments[0], |
| 549 |
get_between_description_format, |
| 550 |
get_single_item_description, |
| 551 |
) |
| 552 |
if not between_segment_description.startswith(", "): |
| 553 |
description += ", " |
| 554 |
|
| 555 |
description += between_segment_description |
| 556 |
elif not any(ext in segments[0] for ext in ["*", ","]): |
| 557 |
range_item_description = get_description_format(segments[0]).format( |
| 558 |
get_single_item_description(segments[0]), |
| 559 |
) |
| 560 |
range_item_description = range_item_description.replace(", ", "") |
| 561 |
|
| 562 |
description += self.translate(", starting {0}").format(range_item_description) |
| 563 |
return description |
| 564 |
|
| 565 |
if "-" in expression: |
| 566 |
return self.generate_between_segment_description( |
| 567 |
expression, |
| 568 |
get_between_description_format, |
| 569 |
get_single_item_description, |
| 570 |
) |
| 571 |
|
| 572 |
return "?" |
| 573 |
|
| 574 |
def generate_between_segment_description( |
| 575 |
self, |
| 576 |
between_expression: str, |
| 577 |
get_between_description_format: Callable[[str], str], |
| 578 |
get_single_item_description: Callable[[str], str], |
| 579 |
) -> str: |
| 580 |
"""Generates the between segment description |
| 581 |
:param between_expression: |
| 582 |
:param get_between_description_format: |
| 583 |
:param get_single_item_description: |
| 584 |
:return: The between segment description |
| 585 |
""" |
| 586 |
description = "" |
| 587 |
between_segments = between_expression.split("-") |
| 588 |
between_segment_1_description = get_single_item_description(between_segments[0]) |
| 589 |
between_segment_2_description = get_single_item_description(between_segments[1]) |
| 590 |
between_segment_2_description = between_segment_2_description.replace(":00", ":59") |
| 591 |
|
| 592 |
between_description_format = get_between_description_format(between_expression) |
| 593 |
description += between_description_format.format(between_segment_1_description, between_segment_2_description) |
| 594 |
|
| 595 |
return description |
| 596 |
|
| 597 |
def _describe_step_in_comma( |
| 598 |
self, |
| 599 |
segment: str, |
| 600 |
get_interval_description_format: Callable[[str], str], |
| 601 |
get_range_format: Callable[[str], str], |
| 602 |
get_single_item_description: Callable[[str], str], |
| 603 |
) -> str: |
| 604 |
"""Describes a step expression that appears inside a comma-separated list. |
| 605 |
|
| 606 |
For example, given "6-23/2" from the expression "0,6-23/2", this produces |
| 607 |
"every 2 hours, 06:00 AM through 11:59 PM". |
| 608 |
""" |
| 609 |
sub_segments = segment.split("/") |
| 610 |
step_description = get_interval_description_format(sub_segments[1]).format(sub_segments[1]) |
| 611 |
if "-" in sub_segments[0]: |
| 612 |
between_desc = self.generate_between_segment_description( |
| 613 |
sub_segments[0], get_range_format, get_single_item_description, |
| 614 |
) |
| 615 |
between_desc = between_desc.replace(", ", "") |
| 616 |
step_description += ", " + between_desc |
| 617 |
elif sub_segments[0] != "*": |
| 618 |
range_item = get_single_item_description(sub_segments[0]) |
| 619 |
step_description += ", " + self.translate("starting {0}").format(range_item) |
| 620 |
return step_description |
| 621 |
|
| 622 |
def format_time( |
| 623 |
self, |
| 624 |
hour_expression: str, |
| 625 |
minute_expression: str, |
| 626 |
second_expression: str | None=None, |
| 627 |
) -> str: |
| 628 |
"""Given time parts, will construct a formatted time description |
| 629 |
Args: |
| 630 |
hour_expression: Hours part |
| 631 |
minute_expression: Minutes part |
| 632 |
second_expression: Seconds part |
| 633 |
Returns: |
| 634 |
Formatted time description |
| 635 |
|
| 636 |
""" |
| 637 |
hour = int(hour_expression) |
| 638 |
|
| 639 |
period = "" |
| 640 |
if self._options.use_24hour_time_format is False: |
| 641 |
period = self.translate("PM") if (hour >= 12) else self.translate("AM") |
| 642 |
if period: |
| 643 |
# add preceding space |
| 644 |
period = " " + period |
| 645 |
|
| 646 |
if hour > 12: |
| 647 |
hour -= 12 |
| 648 |
|
| 649 |
if hour == 0: |
| 650 |
hour = 12 |
| 651 |
|
| 652 |
minute = str(int(minute_expression)) # Removes leading zero if any |
| 653 |
second = "" |
| 654 |
if second_expression is not None and second_expression: |
| 655 |
second = "{}{}".format(":", str(int(second_expression)).zfill(2)) |
| 656 |
|
| 657 |
return f"{str(hour).zfill(2)}:{minute.zfill(2)}{second}{period}" |
| 658 |
|
| 659 |
def transform_verbosity(self, description: str, *, use_verbose_format: bool = False) -> str: |
| 660 |
"""Transforms the verbosity of the expression description by stripping verbosity from original description |
| 661 |
Args: |
| 662 |
description: The description to transform |
| 663 |
use_verbose_format: If True, will leave description as it, if False, will strip verbose parts |
| 664 |
Returns: |
| 665 |
The transformed description with proper verbosity |
| 666 |
|
| 667 |
""" |
| 668 |
if not use_verbose_format: |
| 669 |
description = description.replace(self.translate(", every minute"), "") |
| 670 |
description = description.replace(self.translate(", every hour"), "") |
| 671 |
description = description.replace(self.translate(", every day"), "") |
| 672 |
description = re.sub(r", ?$", "", description) |
| 673 |
return description |
| 674 |
|
| 675 |
@staticmethod |
| 676 |
def transform_case(description: str, case_type: CasingTypeEnum) -> str: |
| 677 |
"""Transforms the case of the expression description, based on options |
| 678 |
Args: |
| 679 |
description: The description to transform |
| 680 |
case_type: The casing type that controls the output casing |
| 681 |
Returns: |
| 682 |
The transformed description with proper casing |
| 683 |
""" |
| 684 |
if case_type == CasingTypeEnum.Sentence: |
| 685 |
description = f"{description[0].upper()}{description[1:]}" |
| 686 |
elif case_type == CasingTypeEnum.Title: |
| 687 |
description = description.title() |
| 688 |
else: |
| 689 |
description = description.lower() |
| 690 |
return description |
| 691 |
|
| 692 |
@staticmethod |
| 693 |
def number_to_day(day_number: int) -> str: |
| 694 |
"""Returns localized day name by its CRON number |
| 695 |
|
| 696 |
Args: |
| 697 |
day_number: Number of a day |
| 698 |
Returns: |
| 699 |
Day corresponding to day_number |
| 700 |
Raises: |
| 701 |
IndexError: When day_number is not found |
| 702 |
|
| 703 |
""" |
| 704 |
try: |
| 705 |
return [ |
| 706 |
calendar.day_name[6], |
| 707 |
calendar.day_name[0], |
| 708 |
calendar.day_name[1], |
| 709 |
calendar.day_name[2], |
| 710 |
calendar.day_name[3], |
| 711 |
calendar.day_name[4], |
| 712 |
calendar.day_name[5], |
| 713 |
][day_number] |
| 714 |
except IndexError as e: |
| 715 |
msg = f"Day {day_number} is out of range!" |
| 716 |
raise IndexError(msg) from e |
| 717 |
|
| 718 |
def __str__(self) -> str: |
| 719 |
return self.get_description() |
| 720 |
|
| 721 |
def __repr__(self) -> str: |
| 722 |
return self.get_description() |
| 723 |
|
| 724 |
|
| 725 |
def get_description(expression: str, options: Options | None=None) -> str: |
| 726 |
"""Generates a human readable string for the Cron Expression |
| 727 |
Args: |
| 728 |
expression: The cron expression string |
| 729 |
options: Options to control the output description |
| 730 |
Returns: |
| 731 |
The cron expression description |
| 732 |
|
| 733 |
""" |
| 734 |
descriptor = ExpressionDescriptor(expression, options) |
| 735 |
return descriptor.get_description(DescriptionTypeEnum.FULL) |