"""Take the first code block from the `result` field of uitkomst.json, verbatim. Usage: python3 eerste-codeblok.py uitkomst.json index.html Rule from the demo-brief: the `result` field counts, and from it the content of the first fenced code block, letter for letter. A fence is three or more backticks or tildes at the start of a line (up to three spaces in), optionally followed by a language name. The block ends at the first line with the same character, at least as long, and nothing else. The content is every line in between, each with its newline. Exit codes, which count as a technical error and allow one more run: 2 is_error is true in uitkomst.json 3 there is no code block 4 the code block is never closed """ import hashlib import json import re import sys OPEN = re.compile(r"^ {0,3}(`{3,}|~{3,})[^`]*$") def first_block(text: str) -> str: lines = text.split("\n") for i, line in enumerate(lines): m = OPEN.match(line) if not m: continue fence = m.group(1) close = re.compile(r"^ {0,3}" + re.escape(fence[0]) + "{" + str(len(fence)) + r",}[ \t]*$") for j in range(i + 1, len(lines)): if close.match(lines[j]): return "".join(f"{body}\n" for body in lines[i + 1:j]) sys.exit(4) sys.exit(3) def main(src: str, dst: str) -> None: with open(src, encoding="utf-8") as fh: data = json.load(fh) if data.get("is_error"): sys.exit(2) block = first_block(data["result"]).encode("utf-8") with open(dst, "wb") as fh: fh.write(block) print(f"{dst}: {len(block)} bytes, sha256 {hashlib.sha256(block).hexdigest()}") if __name__ == "__main__": main(sys.argv[1], sys.argv[2])