"""What a cut says as each step finishes: on stderr, and in a file of the run's own, so the steps outlast the terminal.""" import datetime import pathlib import typing from failure import Failure # Says that one step of a cut finished, as `saying` makes it. Say = typing.Callable[[str], None] Clock = typing.Callable[[], datetime.datetime] def trace_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Path: """The folder each cut keeps its trace in, under the state folder as run-heavy finds it.""" state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state") return pathlib.Path(state) / "deploy-release" def run_name(began: datetime.datetime, pid: int) -> str: """The name of the files one run keeps, which sorts by when it began.""" return f"{began:%Y-%m-%dT%H-%M-%S}-{pid}" def stamped(at: datetime.datetime, line: str) -> str: return f"{at.isoformat(timespec='seconds')} {line}\n" def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure: """A new trace, /.log, whose first line is command; a Failure where it can't be written.""" file = folder / f"{name}.log" try: folder.mkdir(parents=True, exist_ok=True) file.write_text(stamped(now(), command), encoding="utf-8") except OSError as failure: return Failure(f"the trace {file} could not be started: {failure}") return file def kept(trace: pathlib.Path | None, line: str, now: Clock, out: typing.TextIO) -> None: """Append line with its time to trace, where there is one. A trace that can't be written only warns on out, since the cut's own steps count.""" if trace is None: return try: with trace.open("a", encoding="utf-8") as file: file.write(stamped(now(), line)) except OSError as failure: print(f"deploy-release: warning: the trace {trace} could not be written: {failure}", file=out) def saying(trace: pathlib.Path | None, now: Clock, out: typing.TextIO) -> Say: """Says each step on out, so the human sees how far the cut got before the changelog fills the screen, and keeps it in trace.""" def say(step: str) -> None: print(f"deploy-release: {step}", file=out) kept(trace, step, now, out) return say