"""The board's facet families: how a task is categorised, computed from what it is.
Every value is derived, never typed by hand: from the task's ``command`` (through the
same deterministic reading the run plans use, :mod:`openloops.command_risk`), its
``org``, its ``minutes`` and its open ``blocked_by`` edges. The page draws its filter
from :data:`FAMILIES` (labels, help, value labels, order) and from each task's
``facets``, so a family added here appears on the board with no page change.
Families, in the order the page shows them:
* ``presence``: runs without you, or needs you at the terminal (a login, 2FA, a paste,
a browser): the split the owner launches by.
* ``ready``: every prerequisite done, waiting on an open issue, or unknown (the edges
could not be read: never rounded into either).
* ``where``: the Mac, the twb server, the iqb server.
* ``risk``: the floor's level (run, show, discuss, refuse).
* ``touches``: what it changes (deploy, publish, secret, money, server, GitHub, deletes,
exposure, local files).
* ``org``: whose repository the task is in.
* ``time``: the estimate's bucket.
A task without a command gets ``presence: by-hand`` and no command-derived values.
Pure: no I/O.
"""
from __future__ import annotations
import re
from collections.abc import Mapping
from typing import Any
from openloops.command_risk import interactive_reasons, risk_floor
__all__ = ["FAMILIES", "task_facets", "families_payload"]
#: (key, label, help, ((value, label), ...)). Values not listed (an org) are shown as is.
FAMILIES: tuple[tuple[str, str, str, tuple[tuple[str, str], ...]], ...] = (
(
"presence",
"You needed",
"Whether a step needs you at the terminal: a login, 2FA, a paste, a browser.",
(
("unattended", "Without you"),
("attended", "Needs you"),
("by-hand", "No command"),
),
),
(
"ready",
"Ready",
"Waiting means an issue it depends on is still open.",
(
("ready", "Ready"),
("waiting", "Waiting on another"),
("unknown", "Not read"),
),
),
(
"where",
"Runs on",
"The machine the command acts on.",
(("mac", "Mac"), ("twb", "twb server"), ("iqb", "iqb server")),
),
(
"risk",
"Risk",
"Shows first and Asks you by name wait for your yes.",
(
("run", "Runs"),
("show", "Shows first"),
("discuss", "Asks you by name"),
("refuse", "Won't run"),
),
),
(
"touches",
"Changes",
"What the command changes.",
(
("deploy", "A deploy"),
("publish", "A publish"),
("secret", "A secret"),
("money", "Money"),
("server", "A server"),
("github", "GitHub"),
("deletes", "Deletes"),
("exposure", "Makes public"),
("local", "Local only"),
),
),
("org", "Org", "Whose repository the task is in.", ()),
(
"time",
"Time",
"The estimate.",
(("short", "Under 5 min"), ("medium", "5 to 15 min"), ("long", "Over 15 min")),
),
)
#: A risk reason's prefix (``command_risk``'s wording) to the ``touches`` value it means.
_TOUCHES: tuple[tuple[str, str], ...] = (
("production: deploy", "deploy"),
("production: service restart", "deploy"),
("production: edits server files", "server"),
("publication:", "publish"),
("credentials:", "secret"),
("writes: gh secret", "secret"),
("money:", "money"),
("writes on another machine", "server"),
("merges a pull request", "github"),
("pushes git commits", "github"),
("starts a CI workflow", "github"),
("changes GitHub settings", "github"),
("irreversible:", "deletes"),
("exposure:", "exposure"),
)
_SSH = re.compile(r"\bssh\b(?:\s+-\S+(?:\s+\S+)?)*?\s+(?:\S+@)?(twb?|iqb?)\b")
_DEPLOY = re.compile(r"\bdeploy\.py\b|\bdeploy_from_tw\b")
def _where(command: str) -> list[str]:
hosts = {"tw": "twb", "twb": "twb", "iq": "iqb", "iqb": "iqb"}
out = {hosts[m] for m in _SSH.findall(command)}
if _DEPLOY.search(command):
out.add("twb")
if not out or re.search(r"(^|[;&|]\s*)(cd|git|npm|python|uv)\b", command):
out.add("mac")
return [v for v in ("mac", "twb", "iqb") if v in out]
def _touches(reasons: list[str]) -> list[str]:
out = [v for prefix, v in _TOUCHES for r in reasons if r.startswith(prefix)]
seen = list(dict.fromkeys(out))
return seen or ["local"]
def _time(minutes: Any) -> list[str]:
if not isinstance(minutes, (int, float)) or isinstance(minutes, bool):
return []
return ["short" if minutes < 5 else "medium" if minutes <= 15 else "long"]
[docs]
def task_facets(task: Mapping[str, Any]) -> dict[str, list[str]]:
"""Each family's values for one task record (lists: a task can run on two machines).
>>> f = task_facets({'command': "ssh tw 'python3 x.py --apply'", 'org': 'acme',
... 'minutes': 3, 'blocked_by': []})
>>> f['presence'], f['where'], f['ready'], f['time'], f['org']
(['unattended'], ['twb'], ['ready'], ['short'], ['acme'])
>>> task_facets({'command': 'npm login && npm publish', 'blocked_by': None})['presence']
['attended']
>>> task_facets({'command': None, 'blocked_by': ['o/r#2']})['ready']
['waiting']
"""
command = task.get("command") or ""
blocked_by = task.get("blocked_by")
out: dict[str, list[str]] = {
"ready": (
["unknown"]
if blocked_by is None
else (["waiting"] if blocked_by else ["ready"])
),
"org": [task["org"]] if task.get("org") else [],
"time": _time(task.get("minutes")),
}
if not command.strip():
return {"presence": ["by-hand"], **out}
level, reasons = risk_floor(command)
hands = interactive_reasons(command)
return {
"presence": ["attended" if hands else "unattended"],
**out,
"where": _where(command),
"risk": [level],
"touches": _touches(reasons + hands),
}
[docs]
def families_payload() -> list[dict[str, Any]]:
""":data:`FAMILIES` as JSON for the page: ``[{key, label, help, values: [{value, label}]}]``."""
return [
{
"key": key,
"label": label,
"help": help_,
"values": [{"value": v, "label": lab} for v, lab in values],
}
for key, label, help_, values in FAMILIES
]