Files
buryan-infra/ops/work/tools/reconcile.py
T

135 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Сверка источников совместимости Yealink.
Правило владельца: официальный источник — истина; при расхождении
вариант не рассматриваем (помечаем conflict и исключаем из подбора).
Источники:
matrix/*.yaml — матрица Yealink (21 хост × 42 аксессуара), новее
yealink/*.yaml — из PDF-руководств (MeetingEye 400/600/800), 2022
Выход: ops/work/compat/reconciled.yaml + отчёт
"""
import glob
import os
import re
import sys
BASE = "/opt/work-hub/compat"
OUT = BASE
def load(kind):
"""kind: matrix | yealink"""
out = {}
for f in glob.glob(os.path.join(BASE, kind, "*.yaml")):
if os.path.basename(f).startswith("_"):
continue
try:
import yaml
d = yaml.safe_load(open(f, encoding="utf-8"))
except Exception:
continue
c = (d or {}).get("compatibility") or {}
host = (c.get("device") or "").strip()
if not host:
continue
accs = {}
for a in c.get("accessories") or []:
model = (a.get("model") or "").strip()
if not model:
continue
# derive_supported: в PDF-источниках поля supported нет,
# оно выводится из max_qty (0 = Nonsupport)
if "supported" in a and a["supported"] is not None:
sup = bool(a["supported"])
else:
q = a.get("max_qty")
sup = not (q == 0)
accs[model.lower()] = {
"model": model,
"supported": sup,
"max_qty": a.get("max_qty"),
"note": a.get("note"),
"role": a.get("role"),
"origin": kind,
}
out[host.lower()] = {"host": host, "accessories": accs, "origin": kind}
return out
def norm(s):
return re.sub(r"[^a-z0-9]", "", s.lower())
def main():
import yaml
matrix = load("matrix")
pdf = load("yealink")
print("хостов в матрице: %d | в PDF-руководствах: %d" % (len(matrix), len(pdf)))
merged = {}
report = {"agree": [], "conflict": [], "matrix_only": [], "pdf_only": []}
for hkey, m in matrix.items():
merged[hkey] = {"host": m["host"], "accessories": dict(m["accessories"]),
"sources": ["matrix"]}
for hkey, p in pdf.items():
if hkey not in merged:
merged[hkey] = {"host": p["host"], "accessories": dict(p["accessories"]),
"sources": ["pedf"]}
continue
target = merged[hkey]
target["sources"].append("pdf")
for akey, pa in p["accessories"].items():
matched = None
for k in target["accessories"]:
if norm(k) == norm(akey):
matched = k
break
if matched is None:
target["accessories"][akey] = pa
report["pdf_only"].append((p["host"], pa["model"]))
continue
ma = target["accessories"][matched]
if ma["supported"] != pa["supported"]:
# конфликт: матрица новее — она истина, вариант исключаем
report["conflict"].append({
"host": p["host"], "accessory": ma["model"],
"matrix": ma["supported"], "pdf": pa["supported"],
"resolved": ma["supported"], "rule": "matrix (новее)",
})
ma["conflict"] = True
ma["pdf_supported"] = pa["supported"]
ma["usable"] = False # ← не рассматриваем
else:
report["agree"].append((p["host"], ma["model"]))
# всё, что без конфликта — пригодно
for h in merged.values():
for a in h["accessories"].values():
a.setdefault("usable", not a.get("conflict", False))
path = os.path.join(OUT, "reconciled.yaml")
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump({"hosts": [{"host": h["host"], "sources": h["sources"],
"accessories": list(h["accessories"].values())}
for h in merged.values()]},
f, allow_unicode=True, sort_keys=False, width=200)
print("\n=== СВЕРКА ===")
print(" совпало: %d" % len(report["agree"]))
print(" КОНФЛИКТОВ: %d ← исключены из подбора" % len(report["conflict"]))
print(" только в матрице: %d" % len(report["matrix_only"]))
print(" только в PDF: %d" % len(report["pdf_only"]))
print("\nконфликты (первые 10):")
for c in report["conflict"][:10]:
print(" %-18s %-12s матрица=%s pdf=%s → берём матрицу"
% (c["host"][:18], c["accessory"][:12],
"√" if c["matrix"] else "×", "√" if c["pdf"] else "×"))
print("\nсохранено:", path)
return 0
if __name__ == "__main__":
sys.exit(main())