_stub.py
Language Python1.4 KB46 lines
"""Frontmatter helpers shared by the client-enrich write-back scripts.Frontmatter is edited as text, one key at a time, so every line the scripts donot own stays byte-identical. Not run directly."""import reimport sysdef split_frontmatter(text):m = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)if not m:sys.exit("ERROR: no YAML frontmatter found at top of stub.")return m.group(1), text[m.end() :]def fm_get(fm, key):m = re.search(rf"(?m)^{re.escape(key)}:[ \t]*(.*)$", fm)return m.group(1).strip() if m else Nonedef fm_is_empty(val):if val is None:return Truev = val.strip().strip('"').strip("'").strip()return v == "" or v == "[TBD]"def fm_set(fm, key, value, force, literal=True):"""Fill `key` only if it is empty or "[TBD]" (any value with force). Never adds a key.re.sub reads backslashes in the replacement as escapes, so literal=Truedoubles them and the value lands exactly as given. patch_research.py passesliteral=False, which keeps its established handling of a backslash."""cur = fm_get(fm, key)if cur is None:return fm, Falseif not force and not fm_is_empty(cur):return fm, Falseif literal:value = value.replace("\\", "\\\\")return re.sub(rf"(?m)^{re.escape(key)}:[ \t]*.*$", f'{key}: "{value}"', fm, count=1), True