Files
rz01_v2/scripts/replace_snippet.py

82 lines
2.4 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import sys
from pathlib import Path
# This script replaces the content between start_marker end end_marker
# in every .html file of this project. The markers themselves remain intact.
def replace_between_markers(root_dir: str, start_marker: str, end_marker: str, replacement_file: str, encoding="utf-8"):
with open(replacement_file, "r", encoding=encoding) as f:
replacement = f.read()
start_len = len(start_marker)
changed = 0
total_html = 0
unchanged_files = [] # NEU
for dirpath, _, filenames in os.walk(root_dir):
for fn in filenames:
if not fn.lower().endswith(".html"):
continue
total_html += 1
path = os.path.join(dirpath, fn)
with open(path, "r", encoding=encoding) as f:
original = f.read()
out = original
i = 0
file_changed = False
while True:
s = out.find(start_marker, i)
if s == -1:
break
e = out.find(end_marker, s + start_len)
if e == -1:
break
before = out[:s + start_len]
after = out[e:]
out_new = before + "\n" + replacement + "\n" + after
if out_new != out:
out = out_new
file_changed = True
i = s + start_len + len(replacement)
else:
i = s + start_len + len(replacement)
if file_changed and out != original:
with open(path, "w", encoding=encoding) as f:
f.write(out)
changed += 1
else:
unchanged_files.append(path)
return changed, total_html, unchanged_files
def main():
script_dir = Path(__file__).resolve().parent
root_dir = str(script_dir.parent)
start_marker = "<!--INCLUDE-START-->"
end_marker = "<!--INCLUDE-END-->"
replacement_file = str(script_dir) + "/snippet.txt"
print(replacement_file)
changed, total, unchanged_files = replace_between_markers(
root_dir, start_marker, end_marker, replacement_file
)
print(f"Changed: {changed} of {total} HTML files")
print("\nNo changes have been made in the following files:")
for p in unchanged_files:
print(p)
if __name__ == "__main__":
main()