#!/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()