Files

114 lines
4.5 KiB
Python

"""The Baseline of a Change request (ADR-0006).
A Change request is an Execution that starts from the Deliverables of a completed
Execution of the same Customer case. That Execution is its Baseline. It is read from
its files under the Customer case, through its manifest, so it does not depend on a
checkpoint and survives a restart. It is only ever read: a Baseline is never modified.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
from execution_engine.states.execution_state import (
UNASSIGNED_CASE,
case_dir,
execution_dir,
)
MANIFEST_FILENAME = "execution.json"
COMPLETED = "completed"
WORKING_FILENAME = "working.json"
_EXECUTION_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
class BaselineError(ValueError):
"""The Execution named as a Baseline cannot be one; the message says why."""
def load_baseline(
output_root: Path, customer_case: str, execution_id: str
) -> dict[str, Any]:
"""The Baseline as plain data: its id, its request and every Deliverable.
Raises BaselineError when the Execution does not exist, belongs to another
Customer case, or did not complete.
"""
if not isinstance(execution_id, str) or not _EXECUTION_ID.match(execution_id):
raise BaselineError(f"baseline {execution_id!r} is not an Execution id")
if customer_case == UNASSIGNED_CASE:
raise BaselineError(
"a Change request needs a customer_case: a Baseline is a completed "
"Execution of the same Customer case"
)
folder = execution_dir(output_root, execution_id, customer_case)
manifest_path = folder / MANIFEST_FILENAME
if not manifest_path.is_file():
elsewhere = [
path.parent.parent.parent.name
for path in case_dir(output_root, "x").parent.glob(
f"*/executions/{execution_id}/{MANIFEST_FILENAME}"
)
]
if elsewhere:
# Never say which: one case must learn nothing about another.
raise BaselineError(
f"baseline {execution_id} belongs to another Customer case"
)
raise BaselineError(
f"baseline {execution_id} is not an Execution of Customer case "
f"{customer_case} with files on record"
)
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except ValueError as exc:
raise BaselineError(f"baseline {execution_id} has no readable record") from exc
if manifest.get("customer_case") not in (None, customer_case):
raise BaselineError(f"baseline {execution_id} belongs to another Customer case")
if manifest.get("status", COMPLETED) != COMPLETED:
raise BaselineError(
f"baseline {execution_id} did not complete ({manifest.get('status')}); "
"a Change request starts from a completed Execution"
)
deliverables: dict[str, dict[str, Any]] = {}
for kind, entry in (manifest.get("deliverables") or {}).items():
document = folder / str(entry.get("document", ""))
if not document.is_file():
raise BaselineError(f"baseline {execution_id} is missing its {kind} file")
attachments = {}
for name in entry.get("attachments") or ():
path = folder / name
if not path.is_file():
raise BaselineError(f"baseline {execution_id} is missing {name}")
attachments[name] = path.read_text(encoding="utf-8")
deliverables[kind] = {
"content": document.read_text(encoding="utf-8"),
"attachments": attachments,
}
if not deliverables:
raise BaselineError(f"baseline {execution_id} holds no Deliverables")
working_path = folder / WORKING_FILENAME
working: dict[str, Any] = {}
if working_path.is_file():
try:
loaded = json.loads(working_path.read_text(encoding="utf-8"))
except ValueError:
loaded = {}
if isinstance(loaded, dict):
working = loaded
return {
"execution_id": execution_id,
"customer_case": customer_case,
"workflow_request": manifest.get("workflow_request", ""),
"baseline": manifest.get("baseline"), # what it was itself changed from
# The choices made for it; a Change request follows them unless told otherwise.
"options": dict(manifest.get("options") or {}),
"deliverables": deliverables,
# Working material worth starting from again, such as pillar advice.
"working": working,
}