58 lines
2.3 KiB
Python
58 lines
2.3 KiB
Python
"""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 pathlib
|
|
import time
|
|
import typing
|
|
|
|
from failure import Failure
|
|
from text_files import utc_stamp
|
|
|
|
# Says that one step of a cut finished, as `saying` makes it.
|
|
Say = typing.Callable[[str], None]
|
|
# The time now, in seconds since the epoch, as time.time gives it.
|
|
Clock = typing.Callable[[], float]
|
|
|
|
|
|
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: float, pid: int) -> str:
|
|
"""The name of the files one run keeps, which sorts by when it began: that time in UTC, with no colon, so the name is valid on every disk."""
|
|
return f"{time.strftime('%Y-%m-%dT%H-%M-%SZ', time.gmtime(began))}-{pid}"
|
|
|
|
|
|
def stamped(at: float, line: str) -> str:
|
|
return f"{utc_stamp.utc(at)} {line}\n"
|
|
|
|
|
|
def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure:
|
|
"""A new trace, <folder>/<name>.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, in UTC, 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
|