"""Enable Jinja2 'do' extension in sourcehut Flask app. Upstream fix: https://lists.sr.ht/~sircmpwn/sr.ht-dev/patches/39036 """ import glob candidates = glob.glob("/usr/lib/python3.*/site-packages/srht/flask.py") if not candidates: raise FileNotFoundError("Cannot find srht/flask.py") source_file = candidates[0] with open(source_file) as f: content = f.read() target = "self.jinja_loader = ChoiceLoader" patch = ' self.jinja_env.add_extension("jinja2.ext.do")' if "jinja2.ext.do" not in content: lines = content.split("\n") patched = False for i, line in enumerate(lines): if target in line: lines.insert(i + 1, patch) patched = True break if not patched: raise RuntimeError(f"Could not find '{target}' in {source_file}") with open(source_file, "w") as f: f.write("\n".join(lines)) print(f"Patched {source_file}: enabled jinja2.ext.do") else: print(f"Already patched: {source_file}")