parent
f9886bde77
commit
c451110a0c
2 changed files with 337 additions and 0 deletions
@ -0,0 +1,131 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
"""Read vor.txt and generate vor.md, inserting dates if missing. |
||||||
|
|
||||||
|
Port of the PHP 5.4 script: on PHP < 7 the date is produced by |
||||||
|
strftime('%A, %d.%m.%Y ') with the de_DE locale, i.e. day and month are |
||||||
|
zero-padded ("Dienstag, 04.11.2026 "). |
||||||
|
""" |
||||||
|
|
||||||
|
from datetime import date, datetime, timedelta, timezone |
||||||
|
|
||||||
|
FILE_TXT = 'vor.txt' |
||||||
|
FILE_MD = 'vor.md' |
||||||
|
|
||||||
|
TUESDAY = 1 # date.weekday(): Monday == 0 |
||||||
|
WEDNESDAY = 2 |
||||||
|
|
||||||
|
|
||||||
|
def last_sunday(year, month): |
||||||
|
"""Last Sunday of a 31-day month (March / October).""" |
||||||
|
d = date(year, month, 31) |
||||||
|
return d - timedelta(days=(d.weekday() + 1) % 7) |
||||||
|
|
||||||
|
|
||||||
|
def cet_today(): |
||||||
|
"""Today's date in PHP's "CET" zone (= CET/CEST with EU summer time). |
||||||
|
|
||||||
|
Python 3.6 has no zoneinfo. EU summer time runs from the last Sunday of |
||||||
|
March to the last Sunday of October, switching at 01:00 UTC. |
||||||
|
""" |
||||||
|
now = datetime.now(timezone.utc).replace(tzinfo=None) |
||||||
|
start = datetime(now.year, 3, last_sunday(now.year, 3).day, 1, 0) |
||||||
|
end = datetime(now.year, 10, last_sunday(now.year, 10).day, 1, 0) |
||||||
|
offset = 2 if start <= now < end else 1 |
||||||
|
return (now + timedelta(hours=offset)).date() |
||||||
|
|
||||||
|
|
||||||
|
def nth_weekday(first_of_month, weekday, n): |
||||||
|
"""n-th (1-based) given weekday counted from the first of the month. |
||||||
|
|
||||||
|
Like PHP's "fourth tuesday of this month": if n is too large for the |
||||||
|
month, the result overflows into the next month. |
||||||
|
""" |
||||||
|
offset = (weekday - first_of_month.weekday()) % 7 |
||||||
|
return first_of_month + timedelta(days=offset + 7 * (n - 1)) |
||||||
|
|
||||||
|
|
||||||
|
def add_month(d): |
||||||
|
"""First-of-month date -> first day of the following month.""" |
||||||
|
if d.month == 12: |
||||||
|
return date(d.year + 1, 1, 1) |
||||||
|
return date(d.year, d.month + 1, 1) |
||||||
|
|
||||||
|
|
||||||
|
def get_tuesday(first_of_month): |
||||||
|
"""Fourth Tuesday of the month, like strftime('%A, %d.%m.%Y ') in de_DE.""" |
||||||
|
t = nth_weekday(first_of_month, TUESDAY, 4) |
||||||
|
# Always a Tuesday, so no locale needed for the weekday name. |
||||||
|
return 'Dienstag, {:d}.{:d}.{:4d} '.format(t.day, t.month, t.year) |
||||||
|
|
||||||
|
|
||||||
|
def generate(lines, today): |
||||||
|
"""Return the lines of vor.md for the content `lines` of vor.txt.""" |
||||||
|
# Header |
||||||
|
arr = ['| | | |', '|:------|:------|:------|'] |
||||||
|
|
||||||
|
first_day = today.replace(day=1) |
||||||
|
ts = first_day |
||||||
|
|
||||||
|
first_wedn = nth_weekday(first_day, WEDNESDAY, 1) |
||||||
|
number = 4 |
||||||
|
# Treat March differently |
||||||
|
if (first_wedn.month, first_wedn.day) == (3, 1): |
||||||
|
number = 5 |
||||||
|
|
||||||
|
tues_date = nth_weekday(first_day, TUESDAY, number) |
||||||
|
wed_date = tues_date + timedelta(days=1) |
||||||
|
|
||||||
|
cond = True |
||||||
|
if first_day.month in (2, 3): |
||||||
|
cond = (first_day != first_wedn |
||||||
|
and (tues_date.month, tues_date.day) != (3, 22)) |
||||||
|
|
||||||
|
# Are we past the fourth Tuesday of this month? |
||||||
|
if today >= wed_date and cond: |
||||||
|
ts = add_month(ts) |
||||||
|
|
||||||
|
for line in lines: |
||||||
|
# Skip empty lines |
||||||
|
if not line: |
||||||
|
continue |
||||||
|
# Remove empty fields too (PHP's array_filter also drops "0") |
||||||
|
fields = [x for x in line.split('|') if x not in ('', '0')] |
||||||
|
# Get next Tuesday independent of PHP version |
||||||
|
tuesday = get_tuesday(ts) |
||||||
|
if len(fields) == 2: |
||||||
|
# Date missing, insert |
||||||
|
fields.insert(0, tuesday) |
||||||
|
ts = add_month(ts) |
||||||
|
li = '|'.join(fields) |
||||||
|
# Insert leading and trailing spaces if required |
||||||
|
if li[:1] != ' ': |
||||||
|
li = ' ' + li |
||||||
|
if li[-1:] != ' ': |
||||||
|
li = li + ' ' |
||||||
|
arr.append('|' + li + '|') |
||||||
|
return arr |
||||||
|
|
||||||
|
|
||||||
|
def read_lines(path): |
||||||
|
"""Like PHP file($path, FILE_IGNORE_NEW_LINES): split on \\n only.""" |
||||||
|
with open(path, encoding='utf-8', errors='surrogateescape', |
||||||
|
newline='\n') as f: |
||||||
|
lines = [] |
||||||
|
for line in f: |
||||||
|
if line.endswith('\n'): |
||||||
|
line = line[:-1] |
||||||
|
if line.endswith('\r'): |
||||||
|
line = line[:-1] |
||||||
|
lines.append(line) |
||||||
|
return lines |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
arr = generate(read_lines(FILE_TXT), cet_today()) |
||||||
|
with open(FILE_MD, 'w', encoding='utf-8', errors='surrogateescape', |
||||||
|
newline='\n') as f: |
||||||
|
f.write('\n'.join(arr) + '\n') |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': |
||||||
|
main() |
||||||
@ -0,0 +1,206 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
"""Shift the entry of the last fourth Tuesday from vor.md to past.md. |
||||||
|
|
||||||
|
Port of the PHP 5.4 script. Creates vor.txt along the way. Exit code 1 |
||||||
|
signals the calling script that files were changed (e.g. to commit them to |
||||||
|
git), 0 means nothing changed. |
||||||
|
""" |
||||||
|
|
||||||
|
import os |
||||||
|
import re |
||||||
|
import shutil |
||||||
|
import sys |
||||||
|
from collections import OrderedDict |
||||||
|
from datetime import date, datetime, timedelta, timezone |
||||||
|
|
||||||
|
def print_stderr(msg): |
||||||
|
"""Print error message and exit.""" |
||||||
|
sys.stderr.write(msg + '\n') |
||||||
|
sys.exit(-1) |
||||||
|
|
||||||
|
class ShiftPres: |
||||||
|
TUESDAY = 1 # date.weekday(): Monday == 0 |
||||||
|
|
||||||
|
# Characters PHP's trim() strips by default (str.strip() would also strip |
||||||
|
# Unicode spaces such as NBSP, which trim() leaves alone) |
||||||
|
PHP_TRIM = ' \t\n\r\0\x0b' |
||||||
|
|
||||||
|
# For German date matching (re.ASCII so \d matches only 0-9, like PHP's PCRE) |
||||||
|
PREG = re.compile(r'^(0?[1-9]|[12][0-9]|3[01])\.(0?[1-9]|1[0-2])\.([1-9]\d{3})$', |
||||||
|
re.ASCII) |
||||||
|
|
||||||
|
def __init__(self, vor='vor.md', past='past.md'): |
||||||
|
"""Read "past.md" and "vor.md" into lists and set up new vor.txt.""" |
||||||
|
self.vor = vor |
||||||
|
self.vor_md = self.read_lines(vor) |
||||||
|
# PHP basename($vor, '.md'): strips the suffix only if present |
||||||
|
vor_base = os.path.basename(vor) |
||||||
|
if vor_base.endswith('.md') and vor_base != '.md': |
||||||
|
vor_base = vor_base[:-3] |
||||||
|
self.vor_t = vor_base + '.txt' |
||||||
|
self.vor_txt = [] |
||||||
|
self.past_t = past |
||||||
|
self.past_md = self.read_lines(past) |
||||||
|
self.exit = 0 # Default return value |
||||||
|
|
||||||
|
# ------------------------------------------------------------------ |
||||||
|
# Static helpers |
||||||
|
# ------------------------------------------------------------------ |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def read_lines(path): |
||||||
|
"""Like PHP file($path, FILE_IGNORE_NEW_LINES): split on \\n only.""" |
||||||
|
with open(path, encoding='utf-8', errors='surrogateescape', |
||||||
|
newline='\n') as f: |
||||||
|
lines = [] |
||||||
|
for line in f: |
||||||
|
if line.endswith('\n'): |
||||||
|
line = line[:-1] |
||||||
|
if line.endswith('\r'): |
||||||
|
line = line[:-1] |
||||||
|
lines.append(line) |
||||||
|
return lines |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def write_text(path, text): |
||||||
|
with open(path, 'w', encoding='utf-8', errors='surrogateescape', |
||||||
|
newline='\n') as f: |
||||||
|
f.write(text) |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def last_sunday(year, month): |
||||||
|
"""Last Sunday of a 31-day month (March / October).""" |
||||||
|
d = date(year, month, 31) |
||||||
|
return d - timedelta(days=(d.weekday() + 1) % 7) |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def berlin_today(): |
||||||
|
"""Today's date in Europe/Berlin (no zoneinfo before Python 3.9). |
||||||
|
|
||||||
|
EU summer time runs from the last Sunday of March to the last Sunday |
||||||
|
of October, switching at 01:00 UTC. |
||||||
|
""" |
||||||
|
now = datetime.now(timezone.utc).replace(tzinfo=None) |
||||||
|
start = datetime(now.year, 3, ShiftPres.last_sunday(now.year, 3).day, 1, 0) |
||||||
|
end = datetime(now.year, 10, ShiftPres.last_sunday(now.year, 10).day, 1, 0) |
||||||
|
offset = 2 if start <= now < end else 1 |
||||||
|
return (now + timedelta(hours=offset)).date() |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def parse_german(dat): |
||||||
|
"""'dd.mm.yyyy' -> date. Overflowing days roll over like PHP (31.02. -> 03.03.).""" |
||||||
|
m = ShiftPres.PREG.match(dat) |
||||||
|
day, month, year = int(m.group(1)), int(m.group(2)), int(m.group(3)) |
||||||
|
return date(year, month, 1) + timedelta(days=day - 1) |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def nth_weekday(first_of_month, weekday, n): |
||||||
|
"""n-th (1-based) weekday counted from the first of the month.""" |
||||||
|
offset = (weekday - first_of_month.weekday()) % 7 |
||||||
|
return first_of_month + timedelta(days=offset + 7 * (n - 1)) |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def php_filter(line): |
||||||
|
"""explode('|') + array_filter: drop '' and '0' but keep the original keys. |
||||||
|
|
||||||
|
OrderedDict because dict ordering is only guaranteed from Python 3.7. |
||||||
|
""" |
||||||
|
return OrderedDict((i, f) for i, f in enumerate(line.split('|')) |
||||||
|
if f not in ('', '0')) |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def date_of_first_field(line): |
||||||
|
"""Return the 'dd.mm.yyyy' string of the first field if valid, else None.""" |
||||||
|
fields = ShiftPres.php_filter(line) |
||||||
|
ff = fields.get(1, '').split(', ') |
||||||
|
if len(ff) > 1: |
||||||
|
dat = ff[1].strip(ShiftPres.PHP_TRIM) |
||||||
|
if ShiftPres.PREG.match(dat): |
||||||
|
return dat |
||||||
|
return None |
||||||
|
|
||||||
|
@staticmethod |
||||||
|
def get_4tuesday(dat): |
||||||
|
first_day = ShiftPres.parse_german(dat).replace(day=1) |
||||||
|
return ShiftPres.nth_weekday(first_day, ShiftPres.TUESDAY, 4) |
||||||
|
|
||||||
|
# ------------------------------------------------------------------ |
||||||
|
# Instance methods |
||||||
|
# ------------------------------------------------------------------ |
||||||
|
|
||||||
|
def save(self): |
||||||
|
"""Save "vor.txt" and "past.md" before leaving.""" |
||||||
|
# Backup files first (PHP's copy() only warns if the source is missing) |
||||||
|
for path in (self.vor_t, self.past_t): |
||||||
|
try: |
||||||
|
shutil.copyfile(path, path + '.bak') |
||||||
|
except OSError as e: |
||||||
|
print_stderr('Warning: backup of {} failed: {}\n'.format(path, e)) |
||||||
|
self.write_text(self.vor_t, '\n'.join(self.vor_txt) + '\n') |
||||||
|
self.write_text(self.past_t, '\n'.join(self.past_md) + '\n') |
||||||
|
# Signal to calling bash script to put files into git |
||||||
|
self.exit = 1 |
||||||
|
|
||||||
|
def shift(self): |
||||||
|
"""Shift from "vor.md" to "past.md", creating "vor.txt" along the way.""" |
||||||
|
yester = self.berlin_today() - timedelta(days=1) |
||||||
|
# For correct insertion into past list |
||||||
|
past = self.find_past() |
||||||
|
if past < 0: |
||||||
|
print_stderr("Can't locate insert position in {}, exiting".format(self.past_t)) |
||||||
|
|
||||||
|
# Loop through "vor.md" and check if yesterday is 4th Tuesday => shift to "past.md" |
||||||
|
# Otherwise copy to "vor.txt", including custom date if found (as in: not 4th Tuesday) |
||||||
|
for line in self.vor_md: |
||||||
|
dat = self.date_of_first_field(line) |
||||||
|
if dat: |
||||||
|
values = list(self.php_filter(line).values()) |
||||||
|
dp = self.parse_german(dat) |
||||||
|
# if we are not invoked on the morning of the 4th Wednesday, copy to "vor.txt" |
||||||
|
if dp != yester: |
||||||
|
# If manually set date doesn't equal fourth Tuesday, copy |
||||||
|
if dp != self.get_4tuesday(dat): |
||||||
|
str0 = '|' + '|'.join(values) + '|' |
||||||
|
else: |
||||||
|
# Otherwise, only copy text |
||||||
|
str0 = '|' + '|'.join(values[1:]) + '|' |
||||||
|
self.vor_txt.append(str0) |
||||||
|
else: |
||||||
|
# Shift to "past.md" |
||||||
|
self.past_md.insert(past, line) |
||||||
|
else: |
||||||
|
self.vor_txt.append(line) |
||||||
|
|
||||||
|
def check_save(self): |
||||||
|
"""True if "vor.txt" and "past.md" need saving (a line was shifted).""" |
||||||
|
# Take header of "vor.md" into account |
||||||
|
return len(self.vor_txt) != len(self.vor_md) - 2 |
||||||
|
|
||||||
|
def get_exit(self): |
||||||
|
return self.exit |
||||||
|
|
||||||
|
def find_past(self): |
||||||
|
"""Find first entry in PAST.""" |
||||||
|
for i, line in enumerate(self.past_md): |
||||||
|
if self.date_of_first_field(line) is not None: |
||||||
|
return i |
||||||
|
return -1 |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
try: |
||||||
|
shift = ShiftPres() |
||||||
|
shift.shift() |
||||||
|
if shift.check_save(): |
||||||
|
shift.save() |
||||||
|
except Exception: |
||||||
|
# Unexpected failure (e.g. missing input file). Exit like a PHP fatal |
||||||
|
# error (255): an uncaught Python exception would exit with 1, which |
||||||
|
# the calling script reads as "files changed, commit them". |
||||||
|
sys.exit(255) |
||||||
|
# Signal to calling bash script |
||||||
|
sys.exit(shift.get_exit()) |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': |
||||||
|
main() |
||||||
Loading…
Reference in new issue