237 lines
9.9 KiB
Python
237 lines
9.9 KiB
Python
#!/usr/bin/env python3
|
|||
|
|
"""Refresh automations-calendar.html from scheduled entries in the workflows tab."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import argparse
|
||
|
|
import html
|
||
|
|
import json
|
||
|
|
import re
|
||
|
|
import shutil
|
||
|
|
import tempfile
|
||
|
|
import xml.etree.ElementTree as ET
|
||
|
|
import zipfile
|
||
|
|
from datetime import datetime, timezone
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
|
||
|
|
ROOT = Path(__file__).resolve().parent.parent
|
||
|
|
DEFAULT_WORKBOOK = ROOT / "local/workflows.xlsx"
|
||
|
|
DEFAULT_HTML = ROOT / "output/automations-calendar.html"
|
||
|
|
DEFAULT_STATUS = ROOT / "examples/status.example.json"
|
||
|
|
DEFAULT_TEMPLATE = ROOT / "templates/automations-calendar.template.html"
|
||
|
|
DAYS = ("Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||
|
|
NS = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
|
||
|
|
REL_NS = {"r": "http://schemas.openxmlformats.org/package/2006/relationships"}
|
||
|
|
DOC_REL = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
|
||
|
|
|
||
|
|
|
||
|
|
def normalize(value: str) -> str:
|
||
|
|
return re.sub(r"[^a-z0-9]+", "", value.casefold())
|
||
|
|
|
||
|
|
|
||
|
|
def column_index(reference: str) -> int:
|
||
|
|
letters = re.match(r"[A-Z]+", reference.upper()).group(0)
|
||
|
|
result = 0
|
||
|
|
for letter in letters:
|
||
|
|
result = result * 26 + ord(letter) - 64
|
||
|
|
return result - 1
|
||
|
|
|
||
|
|
|
||
|
|
def column_letters(index: int) -> str:
|
||
|
|
result = ""
|
||
|
|
number = index + 1
|
||
|
|
while number:
|
||
|
|
number, remainder = divmod(number - 1, 26)
|
||
|
|
result = chr(65 + remainder) + result
|
||
|
|
return result
|
||
|
|
|
||
|
|
|
||
|
|
def shared_strings(archive: zipfile.ZipFile) -> list[str]:
|
||
|
|
try:
|
||
|
|
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
|
||
|
|
except KeyError:
|
||
|
|
return []
|
||
|
|
return ["".join(node.text or "" for node in item.findall(".//m:t", NS)) for item in root.findall("m:si", NS)]
|
||
|
|
|
||
|
|
|
||
|
|
def sheet_path(archive: zipfile.ZipFile, sheet_name: str) -> str:
|
||
|
|
workbook = ET.fromstring(archive.read("xl/workbook.xml"))
|
||
|
|
relation_id = None
|
||
|
|
for sheet in workbook.findall(".//m:sheet", NS):
|
||
|
|
if sheet.attrib.get("name", "").casefold() == sheet_name.casefold():
|
||
|
|
relation_id = sheet.attrib[DOC_REL]
|
||
|
|
break
|
||
|
|
if not relation_id:
|
||
|
|
raise ValueError(f"Worksheet not found: {sheet_name}")
|
||
|
|
rels = ET.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
|
||
|
|
target = next(rel.attrib["Target"] for rel in rels.findall("r:Relationship", REL_NS) if rel.attrib["Id"] == relation_id)
|
||
|
|
target = target.lstrip("/")
|
||
|
|
return target if target.startswith("xl/") else f"xl/{target}"
|
||
|
|
|
||
|
|
|
||
|
|
def cell_value(cell: ET.Element, strings: list[str]):
|
||
|
|
cell_type = cell.attrib.get("t")
|
||
|
|
if cell_type == "inlineStr":
|
||
|
|
return "".join(node.text or "" for node in cell.findall(".//m:t", NS))
|
||
|
|
value_node = cell.find("m:v", NS)
|
||
|
|
if value_node is None or value_node.text is None:
|
||
|
|
return None
|
||
|
|
raw = value_node.text
|
||
|
|
if cell_type == "s":
|
||
|
|
return strings[int(raw)]
|
||
|
|
if cell_type in {"str", "e"}:
|
||
|
|
return raw
|
||
|
|
if cell_type == "b":
|
||
|
|
return raw == "1"
|
||
|
|
try:
|
||
|
|
number = float(raw)
|
||
|
|
return int(number) if number.is_integer() else number
|
||
|
|
except ValueError:
|
||
|
|
return raw
|
||
|
|
|
||
|
|
|
||
|
|
WORKSHEET_NAME = "workflows"
|
||
|
|
|
||
|
|
|
||
|
|
def read_workflow_rows(workbook_path: Path) -> tuple[list[dict], str]:
|
||
|
|
with zipfile.ZipFile(workbook_path) as archive:
|
||
|
|
strings = shared_strings(archive)
|
||
|
|
root = ET.fromstring(archive.read(sheet_path(archive, WORKSHEET_NAME)))
|
||
|
|
matrix: list[list] = []
|
||
|
|
for row in root.findall(".//m:sheetData/m:row", NS):
|
||
|
|
values: list = []
|
||
|
|
for cell in row.findall("m:c", NS):
|
||
|
|
index = column_index(cell.attrib["r"])
|
||
|
|
while len(values) <= index:
|
||
|
|
values.append(None)
|
||
|
|
values[index] = cell_value(cell, strings)
|
||
|
|
matrix.append(values)
|
||
|
|
|
||
|
|
if not matrix:
|
||
|
|
return [], "A1:A1"
|
||
|
|
headers = [str(value or "").strip() for value in matrix[0]]
|
||
|
|
header_map = {name.casefold(): index for index, name in enumerate(headers) if name}
|
||
|
|
if not header_map:
|
||
|
|
raise ValueError("workflows worksheet has no column headers")
|
||
|
|
last_header_column = max(header_map.values())
|
||
|
|
last_data_row = max(
|
||
|
|
(row_number for row_number, row in enumerate(matrix, start=1) if any(value not in (None, "") for value in row[: last_header_column + 1])),
|
||
|
|
default=1,
|
||
|
|
)
|
||
|
|
used_range = f"A1:{column_letters(last_header_column)}{last_data_row}"
|
||
|
|
required = ["name", "machine", "project", "ops segment", "mon", "tues", "wed", "thu", "fri", "sat", "sun", "other", "notes"]
|
||
|
|
missing = [name for name in required if name not in header_map]
|
||
|
|
if missing:
|
||
|
|
raise ValueError(f"{WORKSHEET_NAME} tab is missing required columns: {', '.join(missing)}")
|
||
|
|
|
||
|
|
records = []
|
||
|
|
for source_row, row in enumerate(matrix[1:], start=2):
|
||
|
|
def get(*names: str):
|
||
|
|
for name in names:
|
||
|
|
index = header_map.get(name)
|
||
|
|
if index is not None:
|
||
|
|
return row[index] if index < len(row) else None
|
||
|
|
return None
|
||
|
|
|
||
|
|
name = str(get("name") or "").strip()
|
||
|
|
if not name or name.casefold().startswith("do not edit"):
|
||
|
|
continue
|
||
|
|
schedule = {}
|
||
|
|
for day in DAYS:
|
||
|
|
raw = get(day.casefold())
|
||
|
|
minutes = None
|
||
|
|
cadence = ""
|
||
|
|
if isinstance(raw, (int, float)):
|
||
|
|
minutes = round((float(raw) % 1) * 24 * 60) % 1440
|
||
|
|
elif raw is not None and str(raw).strip():
|
||
|
|
cadence = str(raw).strip()
|
||
|
|
schedule[day] = {"raw": raw, "minutes": minutes, "cadence": cadence}
|
||
|
|
if not any(slot["raw"] not in (None, "") for slot in schedule.values()):
|
||
|
|
continue
|
||
|
|
records.append({
|
||
|
|
"id": source_row,
|
||
|
|
"name": name,
|
||
|
|
"machine": str(get("machine") or "Unspecified").strip(),
|
||
|
|
"project": str(get("project") or "Unspecified").strip(),
|
||
|
|
"location": str(get("operator", "location") or "Unspecified").strip(),
|
||
|
|
"opsSegment": str(get("ops segment") or "Unsorted").strip(),
|
||
|
|
"status": str(get("operational", "status") or "Active").strip(),
|
||
|
|
"other": str(get("other") or "").strip(),
|
||
|
|
"notes": str(get("notes") or "").strip(),
|
||
|
|
"schedule": schedule,
|
||
|
|
})
|
||
|
|
records.sort(key=lambda item: (item["opsSegment"].casefold(), item["project"].casefold(), item["name"].casefold()))
|
||
|
|
return records, used_range
|
||
|
|
|
||
|
|
|
||
|
|
def read_statuses(path: Path) -> dict[str, dict]:
|
||
|
|
if not path.exists():
|
||
|
|
return {}
|
||
|
|
payload = json.loads(path.read_text(encoding="utf-8-sig"))
|
||
|
|
records = payload.get("records", payload) if isinstance(payload, dict) else payload
|
||
|
|
result = {}
|
||
|
|
if isinstance(records, dict):
|
||
|
|
records = [{"name": name, **value} for name, value in records.items()]
|
||
|
|
for record in records or []:
|
||
|
|
if isinstance(record, dict) and record.get("name"):
|
||
|
|
names = [record["name"], *(record.get("aliases") or [])]
|
||
|
|
for name in names:
|
||
|
|
result[normalize(str(name))] = record
|
||
|
|
return result
|
||
|
|
|
||
|
|
|
||
|
|
def attach_statuses(records: list[dict], statuses: dict[str, dict]) -> None:
|
||
|
|
for item in records:
|
||
|
|
found = statuses.get(normalize(item["name"]))
|
||
|
|
if found:
|
||
|
|
outcome = str(found.get("outcome", "unknown")).casefold()
|
||
|
|
if outcome not in {"success", "failure", "unknown"}:
|
||
|
|
outcome = "unknown"
|
||
|
|
item["run"] = {
|
||
|
|
"outcome": outcome,
|
||
|
|
"lastRun": found.get("lastRun") or found.get("last_run"),
|
||
|
|
"detail": found.get("detail") or found.get("message") or "",
|
||
|
|
"source": found.get("source") or "status registry",
|
||
|
|
}
|
||
|
|
else:
|
||
|
|
item["run"] = {"outcome": "unknown", "lastRun": None, "detail": "No verifiable run result was collected.", "source": "none"}
|
||
|
|
|
||
|
|
|
||
|
|
def update_html(html_path: Path, records: list[dict], used_range: str, workbook_path: Path, template_path: Path = DEFAULT_TEMPLATE) -> None:
|
||
|
|
html_path.parent.mkdir(parents=True, exist_ok=True)
|
||
|
|
document = template_path.read_text(encoding="utf-8")
|
||
|
|
payload = json.dumps(records, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
|
||
|
|
document, replacements = re.subn(r" const automations = .*?;\r?\n const days =", lambda _: f" const automations = {payload};\n const days =", document, count=1, flags=re.S)
|
||
|
|
if replacements != 1:
|
||
|
|
raise ValueError("Could not locate the embedded automations data block in the HTML template")
|
||
|
|
generated = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
|
||
|
|
source_line = f"Source: configured workbook · {WORKSHEET_NAME}!{used_range} · Generated {generated}"
|
||
|
|
document, replacements = re.subn(r"Source: .*? · (?:cron|workflows)![^<]+", lambda _: html.escape(source_line), document, count=1)
|
||
|
|
if replacements != 1:
|
||
|
|
raise ValueError("Could not update the HTML source stamp")
|
||
|
|
with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False, dir=html_path.parent, suffix=".tmp") as handle:
|
||
|
|
handle.write(document)
|
||
|
|
temp_path = Path(handle.name)
|
||
|
|
shutil.move(temp_path, html_path)
|
||
|
|
|
||
|
|
|
||
|
|
def main() -> None:
|
||
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
||
|
|
parser.add_argument("--workbook", type=Path, default=DEFAULT_WORKBOOK)
|
||
|
|
parser.add_argument("--html", type=Path, default=DEFAULT_HTML)
|
||
|
|
parser.add_argument("--template", type=Path, default=DEFAULT_TEMPLATE)
|
||
|
|
parser.add_argument("--status", type=Path, default=DEFAULT_STATUS)
|
||
|
|
args = parser.parse_args()
|
||
|
|
if not args.workbook.is_file():
|
||
|
|
parser.error(f"Workbook not found: {args.workbook}")
|
||
|
|
if not args.template.is_file():
|
||
|
|
parser.error(f"HTML template not found: {args.template}")
|
||
|
|
records, used_range = read_workflow_rows(args.workbook)
|
||
|
|
attach_statuses(records, read_statuses(args.status))
|
||
|
|
update_html(args.html, records, used_range, args.workbook.resolve(), args.template)
|
||
|
|
print(f"Updated {args.html.resolve()} with {len(records)} automations from {WORKSHEET_NAME}!{used_range}")
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|