forked from jakub/ansible
63 lines
2.3 KiB
Python
63 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Conservatively set BepInEx ValheimWebMap settings without removing other keys."""
|
|
import os
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
path = Path(sys.argv[1])
|
|
port = sys.argv[2]
|
|
if not port.isdigit() or not 1 <= int(port) <= 65535:
|
|
raise SystemExit("Invalid port")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
original = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
if "\x00" in original:
|
|
raise SystemExit("Unexpected NUL in config")
|
|
lines = original.splitlines(keepends=True)
|
|
sections = {}
|
|
section = None
|
|
for ix, line in enumerate(lines):
|
|
m = re.match(r"^\s*\[([^\]]+)\]\s*$", line.strip())
|
|
if m:
|
|
section = m.group(1).casefold()
|
|
if section in sections:
|
|
raise SystemExit("Duplicate section; refusing to edit")
|
|
sections[section] = ix
|
|
|
|
settings = {"web": {"Port": port, "Host": "*"},
|
|
"history": {"TrackSessions": "false", "TrackDeaths": "false"}}
|
|
for name, options in settings.items():
|
|
if name not in sections:
|
|
if lines and not lines[-1].endswith("\n"):
|
|
lines[-1] += "\n"
|
|
lines.extend([f"\n[{name.capitalize()}]\n"] + [f"{key} = {value}\n" for key, value in options.items()])
|
|
continue
|
|
start = sections[name]
|
|
end = next((ix for ix in sorted(sections.values()) if ix > start), len(lines))
|
|
region = lines[start + 1:end]
|
|
for key, value in options.items():
|
|
matches = [ix for ix, line in enumerate(region) if re.match(rf"^\s*{re.escape(key)}\s*=", line, flags=re.I)]
|
|
if len(matches) > 1:
|
|
raise SystemExit(f"Duplicate setting {name}.{key}; refusing to edit")
|
|
if matches:
|
|
region[matches[0]] = f"{key} = {value}\n"
|
|
else:
|
|
region.append(f"{key} = {value}\n")
|
|
lines[start + 1:end] = region
|
|
# positions after this section have moved; recalculate before next section
|
|
sections = {}
|
|
for ix, line in enumerate(lines):
|
|
m = re.match(r"^\s*\[([^\]]+)\]\s*$", line.strip())
|
|
if m:
|
|
sections[m.group(1).casefold()] = ix
|
|
result = "".join(lines)
|
|
if result != original:
|
|
tmp = path.with_name(path.name + ".ansible-tmp")
|
|
with tmp.open("w", encoding="utf-8") as f:
|
|
f.write(result)
|
|
f.flush()
|
|
os.fsync(f.fileno())
|
|
os.chmod(tmp, 0o640)
|
|
os.replace(tmp, path)
|
|
print("changed" if result != original else "unchanged")
|