#!/usr/bin/env python3 """Keymap Cheat Sheet helper: watch a keyboard config repo and turn its keymap into JSON. keymap.py '{"op": "load", "repo": "xnmrph/corne"}' cached sheet, no network keymap.py '{"op": "check", "repo": "xnmrph/corne"}' ls-remote; fetch + parse on change keymap.py '{"op": "check", ..., "force": true}' fetch + parse even if unchanged Change detection is `git ls-remote` (no GitHub API, so no rate limit; private repos work with your git credentials). The repo is kept as a shallow clone in ~/.cache/glassMxrph/keymap//repo. Sources, first found wins (or the "path" setting): 1. keymap-drawer YAML (`keymap parse` output; the file with the most layers) 2. ZMK *.keymap 3. QMK keymap.json Prints one JSON object: {"ok": true, "changed": bool, "sheet": {...}} or {"ok": false, "error": "..."}. """ import json import os import re import subprocess import sys import time CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "glassMxrph", "keymap") GIT_ENV = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_ASKPASS="true", SSH_ASKPASS="true", GIT_SSH_COMMAND=os.environ.get("GIT_SSH_COMMAND", "ssh -o BatchMode=yes -o ConnectTimeout=10")) # --------------------------------------------------------------------------- yaml # A small reader for the YAML keymap-drawer writes (PyYAML is not always # installed): block mappings and sequences, flow {..} and [..], quoted and plain # scalars, comments, | and > block scalars. def _strip_comment(line): quote = None for i, c in enumerate(line): if quote: if c == quote: quote = None elif c in "'\"" and (i == 0 or line[i - 1] in " \t-:[{,"): quote = c elif c == "#" and (i == 0 or line[i - 1] in " \t"): return line[:i].rstrip() return line.rstrip() def _find_colon(text): """Index of the mapping colon in a block line ('key: value' / 'key:'), or -1.""" depth, quote = 0, None i = 0 while i < len(text): c = text[i] if quote: if c == quote: if quote == "'" and text[i + 1:i + 2] == "'": i += 1 else: quote = None elif c == "\\" and quote == '"': i += 1 elif c in "'\"" and (i == 0 or text[i - 1] in " ,[{"): quote = c elif c in "[{": depth += 1 elif c in "]}": depth -= 1 elif c == ":" and depth == 0 and (i + 1 == len(text) or text[i + 1] in " \t"): return i i += 1 return -1 def _plain(text): if re.fullmatch(r"[-+]?\d+", text): return int(text) if text in ("true", "True"): return True if text in ("false", "False"): return False if text in ("null", "~", ""): return None return text def _quoted(text, i): q = text[i] out = [] i += 1 while i < len(text): c = text[i] if q == "'" and c == "'": if text[i + 1:i + 2] == "'": out.append("'") i += 2 continue return "".join(out), i + 1 if q == '"' and c == "\\": nxt = text[i + 1:i + 2] out.append({"n": "\n", "t": "\t", "\\": "\\", '"': '"', "/": "/"}.get(nxt, nxt)) i += 2 continue if q == '"' and c == '"': return "".join(out), i + 1 out.append(c) i += 1 raise ValueError("unterminated string") def _flow(text, i=0, stops=""): """Parse a flow value starting at text[i]; returns (value, next index).""" while i < len(text) and text[i] in " \t": i += 1 if i >= len(text): return None, i c = text[i] if c == "{": out = {} i += 1 while True: while i < len(text) and text[i] in " \t,": i += 1 if i >= len(text): raise ValueError("unterminated mapping") if text[i] == "}": return out, i + 1 key, i = _flow(text, i, ":,}") while i < len(text) and text[i] in " \t": i += 1 value = None if i < len(text) and text[i] == ":": value, i = _flow(text, i + 1, ",}") out[str(key)] = value if c == "[": out = [] i += 1 while True: while i < len(text) and text[i] in " \t,": i += 1 if i >= len(text): raise ValueError("unterminated list") if text[i] == "]": return out, i + 1 value, i = _flow(text, i, ",]") out.append(value) if c in "'\"": return _quoted(text, i) j = i while j < len(text): if text[j] in stops and (text[j] != ":" or j + 1 == len(text) or text[j + 1] in " \t,}"): break j += 1 return _plain(text[i:j].strip()), j def _scalar(text): text = text.strip() if not text: return None if text[0] in "{['\"": value, _ = _flow(text) return value return _plain(text) def load_yaml(source): lines = [] raw = source.split("\n") for line in raw: if line.strip() in ("---", "..."): continue stripped = _strip_comment(line.replace("\t", " ")) if stripped.strip(): lines.append([len(stripped) - len(stripped.lstrip()), stripped.strip(), line]) pos = [0] def block_scalar(indent, style): out = [] while pos[0] < len(lines) and lines[pos[0]][0] > indent: original = lines[pos[0]][2] out.append(original) pos[0] += 1 if not out: return "" cut = min(len(l) - len(l.lstrip()) for l in out if l.strip()) body = [l[cut:] for l in out] return ("\n" if style == "|" else " ").join(body) + "\n" def value_after(text, indent): if text in ("|", "|-", ">", ">-"): return block_scalar(indent, text[0]) if text: return _scalar(text) if pos[0] < len(lines): child_indent, child = lines[pos[0]][0], lines[pos[0]][1] if child_indent > indent or (child_indent == indent and (child == "-" or child.startswith("- "))): return parse(child_indent) return None def parse(indent): if pos[0] >= len(lines): return None first = lines[pos[0]][1] if first == "-" or first.startswith("- "): out = [] while pos[0] < len(lines) and lines[pos[0]][0] == indent and (lines[pos[0]][1] == "-" or lines[pos[0]][1].startswith("- ")): rest = lines[pos[0]][1][1:].strip() if not rest: pos[0] += 1 out.append(value_after("", indent)) elif rest[0] not in "{[" and _find_colon(rest) >= 0: # "- key: value" starts a mapping indented past the dash. lines[pos[0]][0] = indent + 2 lines[pos[0]][1] = rest out.append(parse(indent + 2)) else: pos[0] += 1 out.append(_scalar(rest)) return out out = {} while pos[0] < len(lines) and lines[pos[0]][0] == indent: text = lines[pos[0]][1] if text == "-" or text.startswith("- "): break colon = _find_colon(text) if colon < 0: raise ValueError("expected 'key: value': " + text) key = _scalar(text[:colon]) pos[0] += 1 out[str(key)] = value_after(text[colon + 1:].strip(), indent) return out if not lines: return None return parse(lines[0][0]) # --------------------------------------------------------------------------- keys def pretty(legend): """Unmapped ZMK behaviours ('&smart_shift') read as words ('Smart shift').""" legend = str(legend) if legend.startswith("&") and len(legend) > 1: words = legend[1:].replace("_", " ").split() return " ".join(words)[:1].upper() + " ".join(words)[1:] return legend def key_from_drawer(key): """One keymap-drawer key -> {t, s, h, type}.""" if key is None: return {"t": "", "type": "blank"} if not isinstance(key, dict): return {"t": pretty(key)} out = {} for name in ("t", "s", "h", "tl", "tr", "bl", "br"): value = key.get(name) if value is not None and str(value) != "": if isinstance(value, dict): # nested legend, keep its tap value = value.get("t", "") out[name] = pretty(value) kind = str(key.get("type") or "") if "trans" in kind.split(): out["type"] = "trans" elif "held" in kind.split(): out["type"] = "held" elif "ghost" in kind.split() or "blank" in kind.split(): out["type"] = "blank" if not out.get("t") else "ghost" out.setdefault("t", "") return out def parse_drawer(text): data = load_yaml(text) if not isinstance(data, dict) or not isinstance(data.get("layers"), dict): raise ValueError("no layers in the keymap-drawer file") layers = [] for name, keys in data["layers"].items(): if isinstance(keys, list): layers.append({"name": str(name), "keys": [key_from_drawer(k) for k in _flatten(keys)]}) names = [l["name"] for l in layers] combos = [] for combo in data.get("combos") or []: if not isinstance(combo, dict) or not isinstance(combo.get("p"), list): continue k = combo.get("k") legend = k.get("t", "") if isinstance(k, dict) else ("" if k is None else str(k)) only = [str(l) for l in combo.get("l") or [] if str(l) in names] combos.append({"keys": [int(p) for p in combo["p"] if isinstance(p, int)], "legend": legend, "layers": only}) layout = data.get("layout") if isinstance(data.get("layout"), dict) else {} keyboard = str(layout.get("zmk_keyboard") or layout.get("qmk_keyboard") or "") return {"layers": layers, "combos": combos, "keyboard": keyboard, "layerCombos": []} def _flatten(keys): out = [] for k in keys: if isinstance(k, list): # keymap-drawer also allows rows as lists out.extend(k) else: out.append(k) return out KEYCODES = { "EXCLAMATION": "!", "EXCL": "!", "AT_SIGN": "@", "AT": "@", "HASH": "#", "POUND": "#", "DOLLAR": "$", "DLLR": "$", "PERCENT": "%", "PRCNT": "%", "CARET": "^", "AMPERSAND": "&", "AMPS": "&", "ASTERISK": "*", "ASTRK": "*", "STAR": "*", "LEFT_PARENTHESIS": "(", "LPAR": "(", "RIGHT_PARENTHESIS": ")", "RPAR": ")", "EQUAL": "=", "PLUS": "+", "MINUS": "-", "UNDERSCORE": "_", "UNDER": "_", "SLASH": "/", "FSLH": "/", "QUESTION": "?", "QMARK": "?", "BACKSLASH": "\\", "BSLH": "\\", "PIPE": "|", "PIPE2": "|", "NON_US_BACKSLASH": "\\", "NUBS": "\\", "SEMICOLON": ";", "SEMI": ";", "COLON": ":", "SINGLE_QUOTE": "'", "SQT": "'", "APOSTROPHE": "'", "APOS": "'", "DOUBLE_QUOTES": '"', "DQT": '"', "COMMA": ",", "LESS_THAN": "<", "LT": "<", "PERIOD": ".", "DOT": ".", "GREATER_THAN": ">", "GT": ">", "LEFT_BRACKET": "[", "LBKT": "[", "RIGHT_BRACKET": "]", "RBKT": "]", "LEFT_BRACE": "{", "LBRC": "{", "RIGHT_BRACE": "}", "RBRC": "}", "GRAVE": "`", "TILDE": "~", "TILDE2": "~", "NON_US_HASH": "#", "NUHS": "#", "BACKSPACE": "Bspc", "BSPC": "Bspc", "ESCAPE": "Esc", "ESC": "Esc", "RETURN": "Enter", "RET": "Enter", "ENTER": "Enter", "RETURN2": "Enter", "RET2": "Enter", "SPACE": "Space", "SPC": "Space", "TAB": "Tab", "DELETE": "Del", "DEL": "Del", "INSERT": "Ins", "INS": "Ins", "HOME": "Home", "END": "End", "PAGE_UP": "PgUp", "PG_UP": "PgUp", "PGUP": "PgUp", "PAGE_DOWN": "PgDn", "PG_DN": "PgDn", "PGDN": "PgDn", "UP": "↑", "UP_ARROW": "↑", "DOWN": "↓", "DOWN_ARROW": "↓", "LEFT": "←", "LEFT_ARROW": "←", "RIGHT": "→", "RIGHT_ARROW": "→", "CAPSLOCK": "Caps", "CAPS": "Caps", "CAPS_LOCK": "Caps", "PRINTSCREEN": "PrtSc", "PSCRN": "PrtSc", "SCROLLLOCK": "ScrLk", "PAUSE_BREAK": "Pause", "LEFT_SHIFT": "Shift", "LSHIFT": "Shift", "LSHFT": "Shift", "LSFT": "Shift", "RIGHT_SHIFT": "Shift", "RSHIFT": "Shift", "RSHFT": "Shift", "RSFT": "Shift", "LEFT_CONTROL": "Ctrl", "LCTRL": "Ctrl", "LCTL": "Ctrl", "RIGHT_CONTROL": "Ctrl", "RCTRL": "Ctrl", "RCTL": "Ctrl", "LEFT_ALT": "Alt", "LALT": "Alt", "LOPT": "Alt", "RIGHT_ALT": "AltGr", "RALT": "AltGr", "ROPT": "AltGr", "ALGR": "AltGr", "LEFT_GUI": "Gui", "LGUI": "Gui", "LCMD": "Gui", "LWIN": "Gui", "LMETA": "Gui", "RIGHT_GUI": "Gui", "RGUI": "Gui", "RCMD": "Gui", "RWIN": "Gui", "RMETA": "Gui", "C_VOLUME_UP": "Vol+", "C_VOL_UP": "Vol+", "KC_VOLU": "Vol+", "VOLU": "Vol+", "C_VOLUME_DOWN": "Vol−", "C_VOL_DN": "Vol−", "VOLD": "Vol−", "C_MUTE": "Mute", "MUTE": "Mute", "C_PLAY_PAUSE": "Play", "C_PP": "Play", "MPLY": "Play", "C_NEXT": "Next", "MNXT": "Next", "C_PREVIOUS": "Prev", "C_PREV": "Prev", "MPRV": "Prev", "C_BRIGHTNESS_INC": "Bri+", "C_BRI_UP": "Bri+", "C_BRIGHTNESS_DEC": "Bri−", "C_BRI_DN": "Bri−", "KP_NUMLOCK": "Num", "KP_MINUS": "-", "KP_PLUS": "+", "KP_MULTIPLY": "*", "KP_SLASH": "/", "KP_ENTER": "Enter", "KP_DOT": ".", } MODS = {"LS": "Shift", "RS": "Shift", "LC": "Ctrl", "RC": "Ctrl", "LA": "Alt", "RA": "AltGr", "LG": "❖", "RG": "❖", "LSFT": "Shift", "RSFT": "Shift", "LCTL": "Ctrl", "RCTL": "Ctrl", "LALT": "Alt", "RALT": "AltGr", "LGUI": "❖", "RGUI": "❖", "S": "Shift", "C": "Ctrl", "A": "Alt", "G": "❖", "MOD_LSFT": "Shift", "MOD_LCTL": "Ctrl", "MOD_LALT": "Alt", "MOD_LGUI": "Gui", "MOD_RSFT": "Shift", "MOD_RCTL": "Ctrl", "MOD_RALT": "AltGr", "MOD_RGUI": "Gui"} def keycode(code): """ZMK / QMK keycode -> legend ('LG(N1)' -> '❖1', 'KC_A' -> 'A').""" code = code.strip() m = re.fullmatch(r"([A-Z_]+)\((.*)\)", code) if m and m.group(1) in MODS: mod = MODS[m.group(1)] inner = keycode(m.group(2)) if mod == "Shift" and len(inner) == 1 and inner.isalpha(): return inner.upper() return mod + inner if mod == "❖" else f"{mod} {inner}" if code.startswith("KC_"): code = code[3:] if code in KEYCODES: return KEYCODES[code] m = re.fullmatch(r"(?:N|NUMBER_|KP_N|KP_NUMBER_|P)(\d)", code) if m: return m.group(1) if re.fullmatch(r"F\d{1,2}", code): return code if len(code) == 1: return code.upper() return code.replace("_", " ").title() # --------------------------------------------------------------------------- zmk def _strip_c(text): text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S) return re.sub(r"//[^\n]*", " ", text) def _nodes(body): """Direct child nodes of a devicetree body: [(name, content)].""" out = [] i = 0 while True: m = re.compile(r"([\w@-]+)(?:\s*:\s*[\w@-]+)?\s*\{").search(body, i) if not m: return out depth, j = 1, m.end() while j < len(body) and depth: depth += {"{": 1, "}": -1}.get(body[j], 0) j += 1 out.append((m.group(1), body[m.end():j - 1])) i = j def _block(text, compatible): m = re.search(r'compatible\s*=\s*"' + re.escape(compatible) + r'"\s*;', text) if not m: return "" start = text.rfind("{", 0, m.start()) depth, j = 1, start + 1 while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 return text[start + 1:j - 1] def _prop(content, name): m = re.search(r"(?= 2: return {"t": keycode(" ".join(args[1:])), "h": layer(args[0])} if behavior == "mt" and len(args) >= 2: return {"t": keycode(" ".join(args[1:])), "h": keycode(args[0])} if behavior == "sk" and args: return {"t": keycode(" ".join(args)), "s": "sticky"} if behavior == "bt" and args: if args[0] == "BT_SEL" and len(args) > 1 and args[1].isdigit(): return {"t": f"BT {int(args[1]) + 1}"} return {"t": {"BT_CLR": "BT✕", "BT_CLR_ALL": "All✕", "BT_NXT": "BT→", "BT_PRV": "BT←"}.get(args[0], args[0])} if behavior == "bootloader": return {"t": "Boot"} if behavior == "sys_reset": return {"t": "Reset"} if behavior == "caps_word": return {"t": "Caps"} if behavior == "key_repeat": return {"t": "Repeat"} if behavior in ("mkp", "mmv", "msc") and args: a = args[0] return {"t": {"LCLK": "L-clk", "RCLK": "R-clk", "MCLK": "M-clk", "MOVE_UP": "↑", "MOVE_DOWN": "↓", "MOVE_LEFT": "←", "MOVE_RIGHT": "→", "SCRL_UP": "⇡", "SCRL_DOWN": "⇣", "SCRL_LEFT": "⇠", "SCRL_RIGHT": "⇢"}.get(a, a)} label = behavior.replace("_", " ") return {"t": label if len(label) <= 6 else label[:1].upper() + label[1:]} def _bindings(value): value = (value or "").replace("<", " ").replace(">", " ").replace(",", " ") return [" ".join(b.split()) for b in value.split("&")[1:] if b.strip()] def parse_zmk(text): text = _strip_c(text) keymap = _block(text, "zmk,keymap") if not keymap: raise ValueError("no zmk,keymap node") nodes = [(name, content) for name, content in _nodes(keymap) if _prop(content, "bindings") is not None] names = [] for name, content in nodes: label = _prop(content, "display-name") or _prop(content, "label") names.append(label.strip('"') if label else name) layers = [] for (name, content), label in zip(nodes, names): layers.append({"name": label, "keys": [zmk_binding(b, names) for b in _bindings(_prop(content, "bindings"))]}) combos = [] for name, content in _nodes(_block(text, "zmk,combos")): positions = _cells(_prop(content, "key-positions")) bindings = _bindings(_prop(content, "bindings")) if not positions or not bindings: continue only = [names[int(n)] for n in _cells(_prop(content, "layers")) if int(n) < len(names)] combos.append({"keys": [int(p) for p in positions], "legend": zmk_binding(bindings[0], names)["t"], "layers": only}) return {"layers": layers, "combos": combos, "keyboard": "", "layerCombos": zmk_conditional(text, names)} def zmk_conditional(text, names): out = [] for name, content in _nodes(_block(_strip_c(text), "zmk,conditional-layers")): ifs = [int(n) for n in _cells(_prop(content, "if-layers"))] then = _cells(_prop(content, "then-layer")) if ifs and then and all(n < len(names) for n in ifs) and int(then[0]) < len(names): out.append({"hold": [names[n] for n in ifs], "layer": names[int(then[0])]}) return out # --------------------------------------------------------------------------- qmk def qmk_key(code, count): code = code.strip() layer = lambda n: f"L{n}" if code in ("_______", "KC_TRNS", "KC_TRANSPARENT", "_____"): return {"t": "", "type": "trans"} if code in ("XXXXXXX", "KC_NO"): return {"t": "", "type": "blank"} m = re.fullmatch(r"(MO|TG|TO|OSL|TT|DF)\((\d+)\)", code) if m: return {"t": layer(m.group(2)), "layer": layer(m.group(2))} m = re.fullmatch(r"LT\((\d+),\s*(.+)\)", code) if m: return {"t": keycode(m.group(2)), "h": layer(m.group(1))} m = re.fullmatch(r"MT\(([^,]+),\s*(.+)\)", code) if m: return {"t": keycode(m.group(2)), "h": " ".join(MODS.get(x.strip(), x.strip()) for x in m.group(1).split("|"))} m = re.fullmatch(r"([LR]?(?:SFT|CTL|ALT|GUI|SHIFT|CTRL|OPT|CMD|WIN))_T\((.+)\)", code) if m: return {"t": keycode(m.group(2)), "h": keycode(m.group(1).replace("SHIFT", "SFT").replace("CTRL", "CTL"))} return {"t": keycode(code)} def parse_qmk(text): data = json.loads(text) raw = data.get("layers") if isinstance(data, dict) else None if not isinstance(raw, list): raise ValueError("no layers in keymap.json") layers = [{"name": f"L{i}", "keys": [qmk_key(str(c), len(raw)) for c in keys]} for i, keys in enumerate(raw)] return {"layers": layers, "combos": [], "keyboard": str(data.get("keyboard") or ""), "layerCombos": []} # --------------------------------------------------------------------------- layout def _corne_like(cols, thumbs): """Split 3xN with a column stagger and a fanned thumb cluster; x,y in key units.""" stagger = [0.35, 0.35, 0.12, 0.0, 0.12, 0.24][-cols:] half_gap = 1.1 width = cols + half_gap # one half plus half the gap keys = [] for row in range(3): for c in range(cols): keys.append({"x": c, "y": row + stagger[c], "r": 0}) for c in range(cols): mirror = cols - 1 - c keys.append({"x": 2 * width - 1 - mirror, "y": row + stagger[mirror], "r": 0}) if thumbs == 6: fan = [(cols - 2.55, 3.32, 0), (cols - 1.5, 3.42, 8), (cols - 0.42, 3.62, 16)] else: fan = [(cols - 1.55, 3.36, 4), (cols - 0.45, 3.56, 12)] for x, y, r in fan: keys.append({"x": x, "y": y, "r": r, "thumb": True}) for x, y, r in reversed(fan): keys.append({"x": 2 * width - 1 - x, "y": y, "r": -r, "thumb": True}) return keys def layout_for(count, keyboard=""): """Physical key positions for a key count; split boards are guessed from common sizes.""" split = {42: (6, 6), 36: (5, 6), 34: (5, 4), 40: (6, 4)} if count in split: cols, thumbs = split[count] return {"split": True, "keys": _corne_like(cols, thumbs)} per_row = 12 if count % 12 == 0 or count > 40 else 10 return {"split": False, "keys": [{"x": i % per_row, "y": i // per_row, "r": 0} for i in range(count)]} # --------------------------------------------------------------------------- repo def repo_url(repo): repo = repo.strip() if re.fullmatch(r"[\w.-]+/[\w.-]+", repo): return f"https://github.com/{repo.removesuffix('.git')}.git" if repo.startswith("github.com/"): return "https://" + repo return repo def repo_name(repo): m = re.search(r"([\w.-]+/[\w.-]+?)(?:\.git)?/?$", repo.strip()) return m.group(1) if m else repo def web_url(repo): url = repo_url(repo) m = re.match(r"(?:https://|git@)(github\.com|gitlab\.com|codeberg\.org)[/:](.+?)(?:\.git)?$", url) return f"https://{m.group(1)}/{m.group(2)}" if m else "" def git(args, cwd=None, timeout=60): p = subprocess.run(["git"] + args, cwd=cwd, env=GIT_ENV, capture_output=True, text=True, timeout=timeout) if p.returncode: lines = [l for l in (p.stderr or p.stdout).strip().splitlines() if l.strip()] raise RuntimeError(lines[-1] if lines else "git " + args[0] + " failed") return p.stdout def remote_sha(url, branch): ref = f"refs/heads/{branch}" if branch else "HEAD" out = git(["ls-remote", url, ref], timeout=25) for line in out.splitlines(): sha, _, name = line.partition("\t") if name == ref: return sha raise RuntimeError(f"branch {branch} not found" if branch else "the repository is empty") def slug(url, branch): return re.sub(r"[^\w.-]+", "_", url.split("://", 1)[-1].removesuffix(".git")) + (f"@{branch}" if branch else "") def sync(url, branch, folder): ref = branch or "HEAD" if not os.path.isdir(os.path.join(folder, ".git")): os.makedirs(os.path.dirname(folder), exist_ok=True) git(["init", "-q", folder]) git(["remote", "add", "origin", url], cwd=folder) else: git(["remote", "set-url", "origin", url], cwd=folder) git(["fetch", "-q", "--depth", "2", "--no-tags", "origin", ref], cwd=folder, timeout=120) git(["checkout", "-qf", "--detach", "FETCH_HEAD"], cwd=folder) SKIP_DIRS = {".git", ".github", "node_modules", "build", ".cache"} def files(folder): for root, dirs, names in os.walk(folder): dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS) for name in sorted(names): yield os.path.relpath(os.path.join(root, name), folder) def read(folder, rel): with open(os.path.join(folder, rel), encoding="utf-8", errors="replace") as f: return f.read() def parse_file(folder, rel): text = read(folder, rel) if rel.endswith(".keymap"): return parse_zmk(text), "zmk" if rel.endswith(".json"): return parse_qmk(text), "qmk" return parse_drawer(text), "keymap-drawer" def find_source(folder, path): if path: if not os.path.isfile(os.path.join(folder, path)): raise RuntimeError(f"{path} is not in the repository") return path all_files = list(files(folder)) best, most = None, 0 for rel in all_files: if not rel.endswith((".yaml", ".yml")) or "config" in os.path.basename(rel) or rel.count(os.sep) > 3: continue try: text = read(folder, rel) if not re.search(r"^layers:", text, re.M): continue data = parse_drawer(text) except Exception: continue n = sum(1 for l in data["layers"] if any(k.get("t") for k in l["keys"])) if n > most: best, most = rel, n if best: return best keymaps = sorted((r for r in all_files if r.endswith(".keymap")), key=lambda r: (not r.startswith("config"), len(r))) if keymaps: return keymaps[0] for rel in all_files: if os.path.basename(rel) == "keymap.json": return rel raise RuntimeError("no keymap found (keymap-drawer YAML, ZMK .keymap or QMK keymap.json)") def pending_redraw(folder, source): """The last commit changed the .keymap but not the drawn YAML, and CI redraws it.""" if not source.endswith((".yaml", ".yml")): return False try: changed = git(["diff", "--name-only", "HEAD~1", "HEAD"], cwd=folder).split() except RuntimeError: return False if not any(f.endswith(".keymap") for f in changed) or source in changed: return False workflows = os.path.join(folder, ".github", "workflows") if not os.path.isdir(workflows): return False for name in os.listdir(workflows): try: if "keymap-drawer" in read(workflows, name) or re.search(r"\bkeymap\b.*\bdraw\b", read(workflows, name)): return True except OSError: pass return False def build(folder, url, branch, path, repo): source = find_source(folder, path) sheet, kind = parse_file(folder, source) keymaps = [r for r in files(folder) if r.endswith(".keymap")] if not sheet["layerCombos"] and keymaps: try: names = [l["name"] for l in sheet["layers"]] zmk = parse_zmk(read(folder, keymaps[0])) zmk_names = [l["name"] for l in zmk["layers"]] sheet["layerCombos"] = [c for c in zmk_conditional(read(folder, keymaps[0]), zmk_names) if c["layer"] in names and all(h in names for h in c["hold"])] except Exception: pass count = max((len(l["keys"]) for l in sheet["layers"]), default=0) if not count: raise RuntimeError(f"{source} has no keys") for layer in sheet["layers"]: layer["keys"] += [{"t": "", "type": "blank"}] * (count - len(layer["keys"])) log = git(["log", "-1", "--format=%H%x00%ct%x00%s"], cwd=folder).strip().split("\x00") sheet.update({ "repo": repo_name(repo), "web": web_url(repo), "branch": branch, "source": source, "format": kind, "sha": log[0], "committed": int(log[1]) if len(log) > 1 and log[1].isdigit() else 0, "subject": log[2] if len(log) > 2 else "", "fetched": int(time.time()), "pending": pending_redraw(folder, source), "layout": layout_for(count, sheet.get("keyboard", "")), }) return sheet def main(request): repo = str(request.get("repo") or "").strip() if not repo: return {"ok": False, "error": "Set a keymap repository in the widget settings"} branch = str(request.get("branch") or "").strip() path = str(request.get("path") or "").strip().lstrip("/") url = repo_url(repo) base = os.path.join(CACHE, slug(url, branch)) cached_path = os.path.join(base, "sheet.json") cached = None try: with open(cached_path, encoding="utf-8") as f: cached = json.load(f) if cached.get("path", "") != path: cached = None except (OSError, ValueError): pass if request.get("op") == "load": return {"ok": True, "changed": False, "sheet": cached} sha = remote_sha(url, branch) if cached and cached.get("sha") == sha and not request.get("force"): cached["checked"] = int(time.time()) return {"ok": True, "changed": False, "sheet": cached} folder = os.path.join(base, "repo") sync(url, branch, folder) sheet = build(folder, url, branch, path, repo) sheet["path"] = path sheet["checked"] = int(time.time()) os.makedirs(base, exist_ok=True) tmp = cached_path + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(sheet, f, ensure_ascii=False) os.replace(tmp, cached_path) changed = not cached or cached.get("sha") != sheet["sha"] or json.dumps(cached.get("layers")) != json.dumps(sheet["layers"]) return {"ok": True, "changed": changed, "sheet": sheet} if __name__ == "__main__": try: result = main(json.loads(sys.argv[1]) if len(sys.argv) > 1 else {}) except subprocess.TimeoutExpired: result = {"ok": False, "error": "The repository did not answer in time"} except Exception as e: # reported in the panel, never a traceback result = {"ok": False, "error": str(e) or type(e).__name__} print(json.dumps(result, ensure_ascii=False))