|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Firmware regression gate: diff two `esphome config` dumps. |
| 3 | +
|
| 4 | +Compiling proves the YAML is valid. It does not prove the firmware still DOES |
| 5 | +what it did. This runs two independent diffs: |
| 6 | +
|
| 7 | + ENTITY GATE -- every user-facing entity (domain, name, category). |
| 8 | + Catches dropped/renamed/added entities, which break |
| 9 | + Home Assistant entity_ids. |
| 10 | +
|
| 11 | + BEHAVIOUR GATE -- the automation bodies attached to those entities |
| 12 | + (on_stall, on_press, script bodies, on_boot, intervals, |
| 13 | + *_action, lambdas). Catches an entity that survived by |
| 14 | + name while its behaviour was silently replaced. |
| 15 | +
|
| 16 | +The behaviour gate exists because of the v2.7.0 homing regression: the entity |
| 17 | +gate passed clean while `on_stall` had been swapped for valar-core's default, |
| 18 | +which zeroed the cover's position on every stall. Entity names alone cannot see |
| 19 | +that class of bug. |
| 20 | +
|
| 21 | +Usage: |
| 22 | + python gate.py OLD.yaml NEW.yaml # human-readable report |
| 23 | + python gate.py OLD.yaml NEW.yaml --detail ANCHOR_SUBSTRING |
| 24 | +
|
| 25 | +Exit code is 0 if both gates are clean, 1 if either reports a difference. |
| 26 | +Differences are not automatically failures -- intended changes must be reviewed |
| 27 | +and called out. The gate's job is to make sure nothing changes UNNOTICED. |
| 28 | +""" |
| 29 | +import argparse, json, sys, yaml |
| 30 | + |
| 31 | +# --- shared loader ----------------------------------------------------------- |
| 32 | + |
| 33 | +DOMAINS = [ |
| 34 | + "binary_sensor", "sensor", "text_sensor", "switch", "number", "select", |
| 35 | + "button", "cover", "light", "datetime", "text", "fan", "lock", "climate", |
| 36 | + "valve", "event", "update", "stepper", "output", "alarm_control_panel", |
| 37 | + "media_player", |
| 38 | +] |
| 39 | + |
| 40 | + |
| 41 | +class Loader(yaml.SafeLoader): |
| 42 | + """SafeLoader that tolerates ESPHome's custom tags (!lambda, !secret, ...).""" |
| 43 | + |
| 44 | + |
| 45 | +def _passthrough(loader, tag_suffix, node): |
| 46 | + if isinstance(node, yaml.ScalarNode): |
| 47 | + return loader.construct_scalar(node) |
| 48 | + if isinstance(node, yaml.SequenceNode): |
| 49 | + return loader.construct_sequence(node) |
| 50 | + return loader.construct_mapping(node) |
| 51 | + |
| 52 | + |
| 53 | +Loader.add_multi_constructor("!", _passthrough) |
| 54 | + |
| 55 | + |
| 56 | +def load(path): |
| 57 | + with open(path, "r", encoding="utf-8") as fh: |
| 58 | + return yaml.load(fh, Loader=Loader) |
| 59 | + |
| 60 | + |
| 61 | +# --- entity gate ------------------------------------------------------------- |
| 62 | + |
| 63 | +def entities(cfg): |
| 64 | + rows = set() |
| 65 | + for domain in DOMAINS: |
| 66 | + block = cfg.get(domain) |
| 67 | + if not isinstance(block, list): |
| 68 | + continue |
| 69 | + for item in block: |
| 70 | + if not isinstance(item, dict): |
| 71 | + continue |
| 72 | + if item.get("name") is not None: |
| 73 | + rows.add(f"{domain}\t{item['name']}\t{item.get('entity_category') or ''}") |
| 74 | + # Multi-entity platforms (wifi_info, ...) nest one sub-entity per key. |
| 75 | + for sub in item.values(): |
| 76 | + if isinstance(sub, dict) and "name" in sub: |
| 77 | + rows.add(f"{domain}\t{sub['name']}\t{sub.get('entity_category') or ''}") |
| 78 | + return rows |
| 79 | + |
| 80 | + |
| 81 | +# --- behaviour gate ---------------------------------------------------------- |
| 82 | + |
| 83 | +def is_behaviour_key(key): |
| 84 | + return key.startswith("on_") or key.endswith("_action") or key in ( |
| 85 | + "lambda", "then", "condition") |
| 86 | + |
| 87 | + |
| 88 | +def strip_comments(text): |
| 89 | + """Drop whole-line C++ comments. Only lines that START with // are removed -- |
| 90 | + a trailing-comment rule would truncate URLs like https://... in literals.""" |
| 91 | + return "\n".join( |
| 92 | + ln for ln in text.splitlines() if not ln.lstrip().startswith("//")) |
| 93 | + |
| 94 | + |
| 95 | +def canon(obj): |
| 96 | + """Whitespace- and comment-insensitive, so reformatting or a reworded |
| 97 | + comment is not reported as a behaviour change.""" |
| 98 | + if isinstance(obj, str): |
| 99 | + return " ".join(strip_comments(obj).split()) |
| 100 | + if isinstance(obj, list): |
| 101 | + return [canon(v) for v in obj] |
| 102 | + if isinstance(obj, dict): |
| 103 | + return {k: canon(v) for k, v in sorted(obj.items())} |
| 104 | + return obj |
| 105 | + |
| 106 | + |
| 107 | +def behaviours(cfg): |
| 108 | + """anchor -> body. Anchors are stable identities (entity name, script id, |
| 109 | + boot priority) rather than list positions, so a reordered package merge |
| 110 | + does not look like a change.""" |
| 111 | + out = {} |
| 112 | + |
| 113 | + def put(anchor, key, body): |
| 114 | + out[(anchor, key)] = json.dumps(canon(body), sort_keys=True) |
| 115 | + |
| 116 | + for boot in (cfg.get("esphome") or {}).get("on_boot") or []: |
| 117 | + if isinstance(boot, dict): |
| 118 | + put("esphome:on_boot", str(boot.get("priority", "?")), boot.get("then")) |
| 119 | + |
| 120 | + for scr in cfg.get("script") or []: |
| 121 | + if isinstance(scr, dict): |
| 122 | + put(f"script:{scr.get('id','?')}", "then", scr.get("then")) |
| 123 | + |
| 124 | + for iv in cfg.get("interval") or []: |
| 125 | + if isinstance(iv, dict): |
| 126 | + put(f"interval:{iv.get('interval','?')}", "then", iv.get("then")) |
| 127 | + |
| 128 | + for domain in DOMAINS: |
| 129 | + block = cfg.get(domain) |
| 130 | + if not isinstance(block, list): |
| 131 | + continue |
| 132 | + for item in block: |
| 133 | + if not isinstance(item, dict): |
| 134 | + continue |
| 135 | + anchor = f"{domain}:{item.get('name') or item.get('id') or '?'}" |
| 136 | + for key, val in sorted(item.items()): |
| 137 | + if is_behaviour_key(key): |
| 138 | + put(anchor, key, val) |
| 139 | + elif isinstance(val, dict): |
| 140 | + for k2, v2 in sorted(val.items()): |
| 141 | + if is_behaviour_key(k2): |
| 142 | + put(f"{anchor}.{key}", k2, v2) |
| 143 | + return out |
| 144 | + |
| 145 | + |
| 146 | +# --- reporting --------------------------------------------------------------- |
| 147 | + |
| 148 | +def report_entities(old, new): |
| 149 | + removed, added = sorted(old - new), sorted(new - old) |
| 150 | + print("=" * 72) |
| 151 | + print("ENTITY GATE") |
| 152 | + print("=" * 72) |
| 153 | + if not removed and not added: |
| 154 | + print(" clean - entity lists identical\n") |
| 155 | + return True |
| 156 | + for row in removed: |
| 157 | + print(f" REMOVED {row}") |
| 158 | + for row in added: |
| 159 | + print(f" ADDED {row}") |
| 160 | + print(f"\n {len(removed)} removed, {len(added)} added -- each must be intended and called out.\n") |
| 161 | + return False |
| 162 | + |
| 163 | + |
| 164 | +def report_behaviours(old, new): |
| 165 | + changed = sorted(k for k in set(old) & set(new) if old[k] != new[k]) |
| 166 | + dropped = sorted(set(old) - set(new)) |
| 167 | + gained = sorted(set(new) - set(old)) |
| 168 | + print("=" * 72) |
| 169 | + print("BEHAVIOUR GATE") |
| 170 | + print("=" * 72) |
| 171 | + if not changed and not dropped and not gained: |
| 172 | + print(" clean - all automation bodies identical\n") |
| 173 | + return True |
| 174 | + for k in changed: |
| 175 | + print(f" CHANGED {k[0]} :: {k[1]}") |
| 176 | + for k in dropped: |
| 177 | + print(f" DROPPED {k[0]} :: {k[1]}") |
| 178 | + for k in gained: |
| 179 | + print(f" NEW {k[0]} :: {k[1]}") |
| 180 | + print(f"\n {len(changed)} changed, {len(dropped)} dropped, {len(gained)} new.") |
| 181 | + print(" Re-run with --detail <anchor> to see the bodies side by side.\n") |
| 182 | + return False |
| 183 | + |
| 184 | + |
| 185 | +def detail(old, new, needle): |
| 186 | + for key in sorted(set(old) | set(new)): |
| 187 | + if needle.lower() not in f"{key[0]} {key[1]}".lower(): |
| 188 | + continue |
| 189 | + o, n = old.get(key), new.get(key) |
| 190 | + if o == n: |
| 191 | + continue |
| 192 | + print("=" * 72) |
| 193 | + print(f"{key[0]} :: {key[1]}") |
| 194 | + print("-" * 30 + " OLD " + "-" * 30) |
| 195 | + print(json.dumps(json.loads(o), indent=2) if o else "(absent)") |
| 196 | + print("-" * 30 + " NEW " + "-" * 30) |
| 197 | + print(json.dumps(json.loads(n), indent=2) if n else "(absent)") |
| 198 | + |
| 199 | + |
| 200 | +def main(): |
| 201 | + ap = argparse.ArgumentParser() |
| 202 | + ap.add_argument("old") |
| 203 | + ap.add_argument("new") |
| 204 | + ap.add_argument("--detail", help="show bodies for anchors matching this substring") |
| 205 | + args = ap.parse_args() |
| 206 | + |
| 207 | + old_cfg, new_cfg = load(args.old), load(args.new) |
| 208 | + old_b, new_b = behaviours(old_cfg), behaviours(new_cfg) |
| 209 | + |
| 210 | + if args.detail: |
| 211 | + detail(old_b, new_b, args.detail) |
| 212 | + return 0 |
| 213 | + |
| 214 | + ok_e = report_entities(entities(old_cfg), entities(new_cfg)) |
| 215 | + ok_b = report_behaviours(old_b, new_b) |
| 216 | + return 0 if (ok_e and ok_b) else 1 |
| 217 | + |
| 218 | + |
| 219 | +if __name__ == "__main__": |
| 220 | + sys.exit(main()) |
0 commit comments