File size: 1,732 Bytes
0b13d3c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | """Block-scoped replace for multi-block stores (erosion pass 131 installation form).
A replace inside a store of repeated blocks gets block scope: slice from the
target header to the next header, replace inside the slice, reassemble.
'First match' in a global replace is a property of the file, not of your intent.
"""
import re
def block_replace(path: str, header_prefix: str, old: str, new: str,
header_re: str = r"^## ") -> dict:
"""Replace `old` with `new` ONLY inside the block that starts with the line
beginning `header_prefix`. Returns {'ok': bool, 'replacements': int, 'why': str}."""
txt = open(path, encoding="utf-8").read()
lines = txt.splitlines(keepends=True)
# find target header (case-insensitive: store headers are mixed-case families)
hi = None
hp_low = header_prefix.lower()
for i, l in enumerate(lines):
if l.lower().startswith(hp_low):
hi = i
break
if hi is None:
return {"ok": False, "replacements": 0, "why": "target header not found"}
# find next header after target
nj = len(lines)
for j in range(hi + 1, len(lines)):
if re.match(header_re, lines[j]):
nj = j
break
block = "".join(lines[hi:nj])
n = block.count(old)
if n == 0:
return {"ok": False, "replacements": 0, "why": "old string absent in target block"}
if n > 1:
return {"ok": False, "replacements": 0, "why": f"old string non-unique in block (n={n})"}
block2 = block.replace(old, new)
out = "".join(lines[:hi]) + block2 + "".join(lines[nj:])
open(path, "w", encoding="utf-8").write(out)
return {"ok": True, "replacements": 1, "why": "replaced in block scope"}
|