Skip to content

Commit

Permalink
Clarify expression alias logic
Browse files Browse the repository at this point in the history
Instead of using tuple indexing use a namedtuple mapped from the
expression aliases. This makes readability / understanding of this logic
a little easier.
  • Loading branch information
evanpurkhiser committed Oct 30, 2024
1 parent fcf5ff8 commit dc080ae
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions src/croniter/croniter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from __future__ import absolute_import, print_function, division

from collections import namedtuple
import traceback as _traceback
import copy
import math
Expand Down Expand Up @@ -79,6 +80,19 @@ def is_32bit():
'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}
DOW_ALPHAS = {'sun': 0, 'mon': 1, 'tue': 2, 'wed': 3, 'thu': 4, 'fri': 5, 'sat': 6}

ExpressionAlias = namedtuple('ExpressionAlias', 'regular, hashed')

# Non-standard expression aliases
EXPR_ALIASES = {
'@midnight': ExpressionAlias('0 0 * * *', 'h h(0-2) * * * h'),
'@hourly': ExpressionAlias('0 * * * *', 'h * * * * h'),
'@daily': ExpressionAlias('0 0 * * *', 'h h * * * h'),
'@weekly': ExpressionAlias('0 0 * * 0', 'h h * * h h'),
'@monthly': ExpressionAlias('0 0 1 * *', 'h h h * * h'),
'@yearly': ExpressionAlias('0 0 1 1 *', 'h h h h * h'),
'@annually': ExpressionAlias('0 0 1 1 *', 'h h h h * h'),
}

step_search_re = re.compile(r'^([^-]+)-([^-/]+)(/(\d+))?$')
only_int_re = re.compile(r'^\d+$')

Expand Down Expand Up @@ -797,22 +811,14 @@ def _expand(cls, expr_format, hash_id=None, second_at_beginning=False, from_time
# Split the expression in components, and normalize L -> l, MON -> mon,
# etc. Keep expr_format untouched so we can use it in the exception
# messages.
expr_aliases = {
'@midnight': ('0 0 * * *', 'h h(0-2) * * * h'),
'@hourly': ('0 * * * *', 'h * * * * h'),
'@daily': ('0 0 * * *', 'h h * * * h'),
'@weekly': ('0 0 * * 0', 'h h * * h h'),
'@monthly': ('0 0 1 * *', 'h h h * * h'),
'@yearly': ('0 0 1 1 *', 'h h h h * h'),
'@annually': ('0 0 1 1 *', 'h h h h * h'),
}

efl = expr_format.lower()
hash_id_expr = hash_id is not None and 1 or 0
try:
efl = expr_aliases[efl][hash_id_expr]
except KeyError:
pass

# Expand expression aliases like `@midnight`
if efl in EXPR_ALIASES:
if hash_id is None:
efl = EXPR_ALIASES[efl].regular
else:
efl = EXPR_ALIASES[efl].hashed

expressions = efl.split()

Expand Down

0 comments on commit dc080ae

Please sign in to comment.