"""Teach the upstream cheatsheet parser to read wrapper-generated Niri KDL."""
from pathlib import Path
import sys
path = Path(sys.argv[1])
text = path.read_text()
replacements = [
(
'filePath = pluginApi?.pluginSettings?.niriConfigPath || (homeDir + "/.config/niri/config.kdl");',
'filePath = pluginApi?.pluginSettings?.niriConfigPath || (homeDir + "/.config/niri/keybind-cheatsheet.kdl");\n'
' if (filePath === "~/.config/niri/config.kdl") filePath = "~/.config/niri/keybind-cheatsheet.kdl";',
),
(
'line.startsWith("binds") && line.includes("{")',
'/^"?binds"?\\s*\\{/.test(line)',
),
(
'line.match(/^"?([A-Za-z0-9_+]+)"?\\s*((?:[a-z\\-]+=(?:"[^"]*"|[1-9][0-9]*|true|false)\\s*)*)\\{(.*)$/)',
'line.match(/^"?([A-Za-z0-9_+]+)"?\\s*([^{}]*)\\{(.*)$/)',
),
(
'currentBindAttributes.match(/hotkey-overlay-title="([^"]+)"/)',
'currentBindAttributes.match(/"?hotkey-overlay-title"?\\s*=\\s*"([^"]+)"/)',
),
(
'var action = currentBindAction.trim().replace(/;$/, "").trim();',
'var action = currentBindAction.trim().replace(/;$/, "").trim()\n .replace(/^"([A-Za-z0-9_-]+)"/, "$1");',
),
]
for before, after in replacements:
if text.count(before) != 1:
raise SystemExit(f"expected one occurrence of {before!r}, found {text.count(before)}")
text = text.replace(before, after)
path.write_text(text)