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 010b321 commit dd01378
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 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 @@ -83,6 +84,20 @@ def is_32bit():
for i in M_ALPHAS, DOW_ALPHAS:
ALPHAS.update(i)
del i

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 @@ -811,22 +826,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 dd01378

Please sign in to comment.