Implementation
This architecture documentation is very much a work in progress.
brei --versionBrei 0.3.2, Copyright (c) 2023 Netherlands eScience Center.
Licensed under the Apache License, Version 2.0.Test coverage
| Name | Stmts | Miss | Cover |
|---|---|---|---|
| brei/__init__.py | 7 | 0 | 100% |
| brei/async_timer.py | 12 | 0 | 100% |
| brei/cli.py | 88 | 56 | 36% |
| brei/construct.py | 30 | 10 | 67% |
| brei/errors.py | 20 | 3 | 85% |
| brei/lazy.py | 112 | 13 | 88% |
| brei/logging.py | 13 | 6 | 54% |
| brei/program.py | 139 | 14 | 90% |
| brei/result.py | 21 | 2 | 90% |
| brei/runner.py | 3 | 0 | 100% |
| brei/task.py | 318 | 18 | 94% |
| brei/template_strings.py | 42 | 0 | 100% |
| brei/utility.py | 21 | 0 | 100% |
| brei/version.py | 2 | 0 | 100% |
| TOTAL | 828 | 122 | 85% |
Python module
from importlib import metadata
__version__ = metadata.version("brei")"""
Welcome to Brei's API documentation. There are two ways to use Brei: from the
command-line (in which case we refer to the homepage for documentation), or
straight from Python. The easiest function to work with is `brei()`, which
links to the command-line app one-to-one.
## Program
If you want to read the `Program` yourself, there are several ways to do so:
1. Use `Program.read()`. You give it a `Path` to a TOML or JSON file and a
section, this last bit giving a object path into the data. For instance:
`Program.read(Path("pyproject.toml"), "tool.brei")`.
2. Read your own data format into JSON compatible data, then
`construct(Program, data)`. The `construct` function uses `msgspec` to validate
the input data against the type annotations of the program's classes.
After reading the data, you'll want to resolve all tasks, i.e. perform includes
and run any necessary task to resolve the targets of all other tasks.
program = Program.read(Path("brei.toml"))
db: TaskDB = await resolve_tasks(program)
await db.run(Phony("all"))
There are three kinds of targets: `pathlib.Path`, `Phony` and `Variable`.
## API
"""
from .program import Program, resolve_tasks, TemplateCall
from .construct import construct
from .lazy import Lazy, LazyDB
from .task import Task, TaskDB, Phony, Variable, TaskProxy
from .runner import Runner
from .cli import brei
__all__ = [
"brei",
"Lazy", "LazyDB", "Phony", "Program", "Runner", "Task", "TaskDB",
"TaskProxy", "TemplateCall", "Variable", "construct",
"resolve_tasks",
]Logging
Logging is formatted by the rich module.
import logging
import sys
from rich.highlighter import RegexHighlighter
from rich.logging import RichHandler
def logger():
return logging.getLogger("brei")
def configure_logger(debug: bool, rich: bool = True):
class BackTickHighlighter(RegexHighlighter):
highlights = [r"`(?P<bold>[^`]*)`"]
if rich:
FORMAT = "%(message)s"
logging.basicConfig(
level=logging.DEBUG if debug else logging.INFO,
format=FORMAT,
datefmt="[%X]",
handlers=[RichHandler(show_path=debug, highlighter=BackTickHighlighter())],
)
else:
logging.basicConfig(
level=logging.DEBUG if debug else logging.INFO,
handlers=[logging.StreamHandler(sys.stdout)]
)Command-line interface
from pathlib import Path
import re
import sys
import textwrap
import tomllib
from typing import Optional, Any
import asyncio
import rich_click as click
from rich.console import Console
from rich.table import Table
from .runner import DEFAULT_RUNNERS
from .errors import HelpfulUserError, InputError, UserError
from .lazy import Phony
from .utility import construct, read_from_file
from .program import Program, resolve_tasks
from .logging import logger, configure_logger
from .version import __version__
from .result import Result
log = logger()
async def main(
program: Program, target_strs: list[str], force_run: bool, throttle: Optional[int]
):
db = await resolve_tasks(program, history_path=Path(".brei_history"))
if throttle:
db.throttle = asyncio.Semaphore(throttle)
db.force_run = force_run
with db.persistent_history():
results: list[Result[Any]] = await asyncio.gather(*(db.run(Phony(t), db=db) for t in target_strs))
if not all(results):
log.error("Some jobs have failed:")
for r in results:
if not r:
msg = textwrap.indent(str(r), "| ")
log.error(msg)
def read_program(input_file: Optional[str]) -> Program:
if input_file is not None:
if m := re.match(r"([^\[\]]+)\[([^\[\]\s]+)\]", input_file):
input_path = Path(m.group(1))
section = m.group(2)
else:
input_path = Path(input_file)
section = None
return read_from_file(Program, input_path, section)
elif Path("brei.toml").exists():
return read_from_file(Program, Path("brei.toml"))
elif Path("pyproject.toml").exists():
with open("pyproject.toml", "rb") as f_in:
data = tomllib.load(f_in)
try:
for s in ["tool", "brei"]:
data = data[s]
except KeyError as e:
raise HelpfulUserError(
f"With out the `-i` argument, Brei looks for `brei.toml` first, then for "
f"a `[tool.brei]` section in `pyproject.toml`. A `pyproject.toml` file was "
f"found, but contained no `[tool.brei]` section."
) from e
return construct(Program, data)
else:
raise HelpfulUserError(
"No input file given, no `brei.toml` found and no `pyproject.toml` found."
)
@click.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.argument("targets", nargs=-1)
@click.option(
"-i",
"--input-file",
help="Brei TOML or JSON file, use a `[...]` suffix to indicate a subsection.",
)
@click.option("-B", "--force-run", is_flag=True, help="rebuild all dependencies")
@click.option("-j", "--jobs", type=int, help="limit number of concurrent jobs")
@click.option("-v", "--version", is_flag=True, help="print version number and exit")
@click.option("--list-runners", is_flag=True, help="show default configured runners")
@click.option("--debug", is_flag=True, help="more verbose logging")
def brei(
targets: tuple[str, ...],
*,
input_file: Optional[str] = None,
force_run: bool = False,
jobs: Optional[int] = None,
version: bool = False,
list_runners: bool = False,
debug: bool = False
):
"""Build one of the configured targets.
TARGETS are the names of tasks to run.
"""
if version:
print(f"Brei {__version__}, Copyright (c) 2023 Netherlands eScience Center.")
print("Licensed under the Apache License, Version 2.0.")
sys.exit(0)
if list_runners:
t = Table(title="Default Runners", header_style="italic green", show_edge=False)
t.add_column("runner", style="bold yellow")
t.add_column("executable")
t.add_column("arguments")
for r, c in DEFAULT_RUNNERS.items():
t.add_row(r, c.command, f"{c.args}")
console = Console()
console.print(t)
sys.exit(0)
try:
program = read_program(input_file)
except (HelpfulUserError, InputError) as e:
raise click.ClickException(str(e)) from e
configure_logger(debug)
try:
asyncio.run(main(program, list(targets), force_run, jobs))
except UserError as e:
log.error(f"Failed: {e}")
def cli():
brei()
if __name__ == "__main__":
cli()Laziness
Brei executes workflows in Asyncio, through lazy evaluation and
memoization. The first time a Lazy task is requested, the
LazyDB starts it as an asyncio.Task and stores
that future on the task object. When multiple tasks ask for the result
of the same dependent task, they all await the same future, so the
computation is performed only once.
A task waiting for one of its dependencies is recorded in its
_awaiting list. Before a task starts waiting on a
dependency, we check that the dependency isn’t (indirectly) waiting on
the task already. Because asyncio is single threaded, the task that
would close a cycle always finds it, no matter in which order the tasks
were started.
Results
One common problem when using workflow systems in Python, is that
errors are not tracable to their source. It is quite common to get a
stack-trace that leads to the internals of the workflow system, but not
to the cause of the error. The way around this, is not to use Python’s
exception system (at least not in the outer layer), but rather signify
errors by returning Failure objects.
from brei.result import Failure, TaskFailure, Ok
from hypothesis import given
from hypothesis.strategies import builds, booleans, text, integers
results = builds(lambda b, t, i: Ok(i) if b else TaskFailure(t),
booleans(), text(min_size=1), integers())
@given(results)
def test_result(r):
assert (r and hasattr(r, "value")) or (not r and isinstance(r, Failure))from dataclasses import dataclass
class Failure(Exception):
def __bool__(self):
return False
@dataclass
class MissingFailure[T](Failure):
target: T
def __str__(self):
return f"Missing dependency: {self.target}"
@dataclass
class TaskFailure(Failure):
message: str
def __post_init__(self):
Exception.__init__(self, self.message)
@dataclass
class DependencyFailure[T](Failure):
dependencies: dict[T, Failure]
def __str__(self):
return "\n".join(f"{key} -> {fail}" for key, fail in self.dependencies.items())
@dataclass
class Ok[R]:
value: R
def __bool__(self):
return True
type Result[R] = Failure | Ok[R]Lazy evaluation
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional, Any
import asyncio
from .errors import CyclicWorkflowError
from .logging import logger
from .result import Failure, Result, Ok, DependencyFailure, MissingFailure
log = logger()
@dataclass
class Phony:
name: str
@classmethod
def from_str(cls, s: str) -> Phony:
if s[0] == "#":
return Phony(s[1:])
raise ValueError("A phony target should start with a `#` character.")
def __str__(self):
return f"#{self.name}"
def __hash__(self):
return hash(str(self))
@dataclass
class Lazy[T, R]:
"""Base class for tasks that are tagged with type `T` (usually `str` or
`Path`) and representing values of type `R`.
To implement a specific task, you need to implement the asynchronous
`run` method, which should return a value of `R` or throw `TaskFailure`.
If `run` returns another `Lazy` object, that is run in turn, and its
result is the result of this task.
Attributes:
creates: list of target identifiers, for instance paths that are
generated by running a particular task.
requires: list of dependency identifiers. All of these need to
be realized before the task can run.
result (property): value of the result, once the task was run. This
throws an exception if accessed before the task is complete.
"""
creates: list[T]
requires: list[T]
_future: Optional[asyncio.Future[R]] = field(default=None, init=False)
_awaiting: list[Lazy] = field(default_factory=list, init=False)
def __bool__(self):
return self._future is not None and self._future.done() \
and not self._future.cancelled() and self._future.exception() is None
@property
def result(self) -> R:
if self._future is None or not self._future.done():
raise ValueError("Task has not run yet.")
if not self:
raise ValueError("Task has failed.")
return self._future.result()
async def run(self, *, db) -> R:
raise NotImplementedError()
def reset(self):
self._future = None
self._awaiting = []
class MissingDependency(Exception):
pass
@dataclass
class LazyDB[T, TaskT: Lazy]:
"""Collect tasks and coordinate running a task from a task identifier."""
tasks: list[TaskT] = field(default_factory=list)
index: dict[T, TaskT] = field(default_factory=dict)
async def run(self, t: T, **kwargs) -> Result[Any]:
"""Run the task that creates `t`, if it hasn't run yet. Keyword
arguments are passed on to `Lazy.run`. Returns `Ok` with the value of
the task, or a `Failure`."""
try:
return Ok(await self._start(self._get_task(t), **kwargs))
except Failure as f:
return f
def _get_task(self, t: T) -> Lazy:
if t in self.index:
return self.index[t]
try:
return self.on_missing(t)
except MissingDependency:
raise MissingFailure(t)
def _start(self, task: Lazy, **kwargs) -> asyncio.Future:
if task._future is None:
task._future = asyncio.ensure_future(self._run(task, **kwargs))
return task._future
async def _run(self, task: Lazy, **kwargs) -> Any:
current = task
while True:
await self._run_deps(task, current.requires, **kwargs)
value = await current.run(**kwargs)
if not isinstance(value, Lazy):
return value
current = value
async def _run_deps(self, waiter: Lazy, requires: list[T], **kwargs):
"""Run the dependencies of `waiter`. Failures are collected into a
`DependencyFailure`, other exceptions are passed on."""
def start(t: T) -> asyncio.Future:
try:
dep = self._get_task(t)
except MissingFailure as f:
future = asyncio.get_running_loop().create_future()
future.set_exception(f)
return future
self._check_cycle(waiter, dep)
waiter._awaiting.append(dep)
return self._start(dep, **kwargs)
results = await asyncio.gather(*map(start, requires), return_exceptions=True)
for r in results:
if isinstance(r, BaseException) and not isinstance(r, Failure):
raise r
failed = {t: r for t, r in zip(requires, results) if isinstance(r, Failure)}
if failed:
raise DependencyFailure(failed)
def _check_cycle(self, waiter: Lazy, dep: Lazy):
"""Raise `CyclicWorkflowError` if `dep` is (indirectly) waiting on `waiter`."""
paths = [[dep]]
seen: set[int] = set()
while paths:
path = paths.pop()
if path[-1] is waiter:
raise CyclicWorkflowError([t.creates[0] for t in [waiter, *path] if t.creates])
if id(path[-1]) in seen:
continue
seen.add(id(path[-1]))
paths.extend(path + [d] for d in path[-1]._awaiting)
def on_missing(self, t: T) -> TaskT:
raise MissingDependency()
def add(self, task: TaskT):
"""Add a task to the DB."""
log.debug(f"adding task ===\n{task}")
self.tasks.append(task)
for target in task.creates:
self.index[target] = task
def clean(self):
self.tasks = []
self.index = {}
def reset(self):
for t in self.tasks:
t.reset()Template strings
The goal is to have more flexible templates in Brei. I’ve looked into
Jinja as a way to expand templates, but this is rejected due to large
mostly unneeded complexity and ditto dependencies. A better alternative
is to use Python’s string.Template to do variable
substition. Evaluation needs to be lazy, and I would like to be able to
pipe standard output of a task to the contents of a variable.
Considering this last point, we want to differentiate between writing
output to the contents of a variable, and writing output to the file
pointed to by the variable.
To assign the output of a command to a variable, we can have the following:
[[task]]
stdout = "var(commit)"
language = "Bash"
script = "git rev-parse HEAD"To use it, refer using Python’s string.Template syntax,
which is similar to Bash, Make, Perl etc, i.e. either
$commit or ${commit}.
[[task]]
targets = ["output/${commit}/run.h5"]
dependencies = ["build/bin/model", "data/input.csv"]
language = "Bash"
script = "model run"The system should infer that the use of $commit creates
an implicit dependency on running git rev-parse HEAD.
However, there may be steps in between:
[environment]
output_path = "output/${commit}"
[[task]]
targets = ["${output_path}/run.h5"]
... etc ...We can trace these variable substitutions using the same lazy evaluation strategy as the workflow itself.
from dataclasses import dataclass, is_dataclass, fields
from string import Template
from typing import Any, Mapping
from functools import singledispatch
from msgspec import Struct, structs
from .lazy import Lazy
def substitute[T](template: T, env: Mapping[str, str]) -> T:
return _substitute(template, env)
def _fields(obj: Any) -> list[str] | None:
"""Names of the fields to recurse into, or None if `obj` is a leaf."""
if is_dataclass(obj) and not isinstance(obj, type):
return [f.name for f in fields(obj) if f.name[0] != "_"]
if isinstance(obj, Struct):
return list(obj.__struct_fields__)
return None
def _rebuild(obj: Any, values: dict[str, Any]) -> Any:
if isinstance(obj, Struct):
return structs.replace(obj, **values)
return type(obj)(**values)
@singledispatch
def _substitute(template: Any, env: Mapping[str, str]) -> Any:
names = _fields(template)
if names is None:
return template
return _rebuild(template, {n: substitute(getattr(template, n), env) for n in names})
@_substitute.register
def _(template: str, env: Mapping[str, str]) -> str:
return Template(template).safe_substitute(env)
@_substitute.register
def _(template: list, env: Mapping[str, str]) -> list:
return [substitute(x, env) for x in template]
@singledispatch
def gather_args(template: Any) -> set[str]:
names = _fields(template)
if names is None:
return set()
return set().union(*(gather_args(getattr(template, n)) for n in names))
@gather_args.register
def _(template: str) -> set[str]:
return set(Template(template).get_identifiers())
@gather_args.register
def _(template: list) -> set[str]:
return set().union(*map(gather_args, template))from dataclasses import dataclass
from typing import Iterable, Optional
import pytest
from brei.task import TemplateVariable, Variable
from brei.template_strings import gather_args, substitute
from brei.lazy import LazyDB
class Environment(LazyDB[Variable, TemplateVariable]):
def __setitem__(self, k: str, v: str):
self.add(TemplateVariable([Variable(k)], [], v))
def __getitem__(self, k: str) -> str:
return self.index[Variable(k)].result
def __contains__(self, k: str) -> bool:
return Variable(k) in self.index
def items(self) -> Iterable[str]:
return (k.name for k in self.index if isinstance(k, Variable))
@property
def environment(self):
return self
@pytest.mark.asyncio
async def test_template_string():
env = Environment()
env["x"] = "Hello, ${y}!"
env["y"] = "World"
env["z"] = "print('${x}')"
await env.run(Variable("z"), db=env)
assert env["x"] == "Hello, World!"
assert env["z"] == "print('Hello, World!')"
@dataclass
class MyData:
some_list: list[str]
some_prop: str
some_none: Optional[str] = None
def test_template_dtype():
data = MyData(
some_list = ["${x} bar", "bar ${x} bar"],
some_prop = "bar ${x}"
)
assert gather_args(data) == set("x")
subst = substitute(data, {"x": "foo"})
assert subst.some_list == ["foo bar", "bar foo bar"]
assert subst.some_prop == "bar foo"
assert subst.some_none is NoneTasks
from msgspec import Struct
class Runner(Struct, forbid_unknown_fields=True):
command: str
args: list[str]
DEFAULT_RUNNERS: dict[str, Runner] = {
"python": Runner("python", ["${script}"]),
"bash": Runner("bash", ["${script}"]),
}from __future__ import annotations
import asyncio
from collections import defaultdict
from collections.abc import Iterator, Mapping
from contextlib import contextmanager, nullcontext
from copy import copy
from dataclasses import dataclass, field
from pathlib import Path
import re
import string
import json
from tempfile import NamedTemporaryFile
from typing import Any, DefaultDict, Optional
from asyncio import create_subprocess_exec
from textwrap import indent
import shlex
import hashlib
from .errors import HelpfulUserError
from .result import TaskFailure
from .lazy import MissingDependency, Lazy, LazyDB, Phony
from .utility import stat
from .logging import logger
from .template_strings import gather_args, substitute
from .runner import Runner, DEFAULT_RUNNERS
from msgspec import Struct, field as struct_field
from rich.markup import escape
log = logger()
@dataclass
class Variable:
name: str
def __hash__(self):
return hash(f"var({self.name})")
def __str__(self):
return f"var({self.name})"
# `listvar(name)` as `stdout` stores the output, split into lines, as a list.
# `splice(name)` as an element of a list inserts the elements of that list.
LIST_VARIABLE = re.compile(r"listvar\(([^\s\(\)]+)\)")
SPLICE = re.compile(r"splice\(([^\s\(\)]+)\)")
def splice_name(s: str) -> str | None:
"""The name of the list variable in `splice(name)`, or `None`."""
return m.group(1) if (m := SPLICE.fullmatch(s)) else None
def str_to_target(s: str) -> Path | Phony | Variable:
if s[0] == "#":
return Phony(s[1:])
elif m := re.match(r"var\(([^\s\(\)]+)\)", s):
return Variable(m.group(1))
elif m := LIST_VARIABLE.fullmatch(s):
return Variable(m.group(1))
else:
return Path(s)
def is_oneliner(s: str) -> bool:
return len(s.splitlines()) == 1
@dataclass
class Task(Lazy[Path | Phony | Variable, str | list[str] | None]):
name: Optional[str] = None
runner: Optional[str] = None
path: Optional[Path] = None
script: Optional[str] = None
stdin: Optional[Path | Variable] = None
stdout: Optional[Path | Variable] = None
description: Optional[str] = None
force: bool = False
list_output: bool = False
@property
def target_paths(self):
return (p for p in self.creates if isinstance(p, Path))
@property
def dependency_paths(self):
return (p for p in self.requires if isinstance(p, Path))
@property
def digest(self) -> str | None:
if self.script is None:
return None
return hashlib.md5(self.script.encode()).hexdigest()
def __str__(self):
tgts = ", ".join(str(t) for t in self.creates)
deps = ", ".join(str(t) for t in self.requires)
if self.script is not None:
src = indent(self.script, prefix=" ▎ ", predicate=lambda _: True)
elif self.path is not None:
src = str(self.path)
else:
src = " - "
name = f"{self.name}: " if self.name else ""
return name + f"[{tgts}] <- [{deps}]\n" + src
def __post_init__(self):
if self.name and Phony(self.name) not in self.creates:
self.creates.append(Phony(self.name))
if self.stdin and self.stdin not in self.requires:
self.requires.append(self.stdin)
if self.path and self.path not in self.requires:
self.requires.append(self.path)
if self.stdout and self.stdout not in self.creates:
self.creates.append(self.stdout)
def always_run(self) -> bool:
return self.force or len(list(self.target_paths)) == 0
def needs_run(self, db: TaskDB) -> bool:
if any(not p.exists() for p in self.target_paths):
return True
target_stats = [stat(p) for p in self.target_paths]
dep_stats = [stat(p) for p in self.dependency_paths]
if any(t < d for t in target_stats for d in dep_stats):
return True
if any(self.digest != db.history.get(p, None) for p in self.target_paths):
return True
return False
@contextmanager
def get_script_path(self):
if self.path is not None:
tmpfile = None
path = self.path
elif self.script is not None:
# On Windows, a file can't be opened by another process while we
# still have it open, so we close it before running the script.
with NamedTemporaryFile("w", delete=False) as tmpfile:
tmpfile.write(self.script)
path = Path(tmpfile.name)
else:
raise ValueError("A `Rule` can have either `path` or `script` defined.")
try:
yield path
finally:
if tmpfile is not None:
path.unlink(missing_ok=True)
@contextmanager
def get_stdin(self, db: TaskDB):
"""Yields the `stdin` argument for the subprocess, and the data to
send to it."""
match self.stdin:
case Variable(x):
yield asyncio.subprocess.PIPE, db.environment[x].encode()
case x if isinstance(x, Path):
with open(x, "r") as stdin:
yield stdin, None
case _:
yield None, None
@contextmanager
def get_stdout(self):
match self.stdout:
case Variable(x):
yield asyncio.subprocess.PIPE
case x if isinstance(x, Path):
with open(x, "w") as stdout:
yield stdout
case _:
yield None
@contextmanager
def get_commands(self, db: TaskDB):
"""Yields the list of commands to run. Without a runner, each line
of the script is a command; with a runner, the script is written to a
file (if needed) and passed to the runner."""
if self.runner is None:
assert self.script is not None
if not is_oneliner(self.script):
assert self.stdin is None
yield [shlex.split(line) for line in self.script.splitlines()]
return
runner = db.runners[self.runner]
with self.get_script_path() as path:
args = [string.Template(arg).substitute(script=path) for arg in runner.args]
yield [[runner.command, *args]]
def check_return_code(self, returncode: int | None, db: TaskDB):
"""A failing command fails the task. Its targets may be written
partially, so we forget them, and they are built again next time."""
if returncode == 0:
return
for p in self.target_paths:
db.history.pop(p, None)
raise TaskFailure(f"Command failed with exit code {returncode}.")
async def _exec(self, db: TaskDB, short_note: str, command: list[str],
stdin, input_data: bytes | None, stdout) -> bytes:
"""Run a single command, returning its standard output if it was captured.
Standard error, and standard output if it doesn't go to a file or
variable, is forwarded to the log line by line while the command runs."""
async def write_stdin():
if input_data is None or proc.stdin is None:
return
try:
proc.stdin.write(input_data)
await proc.stdin.drain()
proc.stdin.close()
except (BrokenPipeError, ConnectionResetError):
pass # the command exited without reading all of its input
async def forward(stream: asyncio.StreamReader | None):
if stream is None:
return
async for line in stream:
log.info(f"[gold1]{short_note}[/] %s", escape(line.decode().rstrip()),
extra={"markup": True})
async def read_stdout() -> bytes:
if stdout is asyncio.subprocess.PIPE and proc.stdout is not None:
return await proc.stdout.read()
await forward(proc.stdout)
return b""
async with db.throttle or nullcontext():
proc = await create_subprocess_exec(
*command,
stdin=stdin,
stdout=asyncio.subprocess.PIPE if stdout is None else stdout,
stderr=asyncio.subprocess.PIPE,
)
stdout_data, *_ = await asyncio.gather(
read_stdout(), forward(proc.stderr), write_stdin())
await proc.wait()
log.debug(f"return-code {proc.returncode}")
self.check_return_code(proc.returncode, db)
return stdout_data
async def run(self, *, db: TaskDB):
if not self.always_run() and not self.needs_run(db) and not db.force_run:
tgts = " ".join(f"`{t}`" for t in self.target_paths)
log.debug(f"Targets {tgts} already up-to-date.")
return
log.debug(f"{self}")
if self.runner is None and self.script is None:
return
targets = " ".join(f"`{t}`" for t in self.creates)
short_note = self.description or (f"#{self.name}" if self.name else None) \
or f"creating {targets}"
log.info(f"[green]{short_note}[/]", extra={'markup': True})
stdout_data = b""
with self.get_commands(db) as commands, \
self.get_stdin(db) as (stdin, input_data), \
self.get_stdout() as stdout:
for command in commands:
stdout_data += await self._exec(db, short_note, command, stdin, input_data, stdout)
for p in self.target_paths:
db.history[p] = self.digest
if self.needs_run(db):
raise TaskFailure("Task didn't achieve goals.")
if self.list_output:
return [line for line in stdout_data.decode().splitlines() if line]
return stdout_data.decode().strip() if stdout_data else None
class TaskProxy(Struct, forbid_unknown_fields=True):
"""Input to create an actual Task.
An actual `Task` has no template variables remaining and untyped strings
are replaced with `Path` `Variable` or `Phony` objects.
"""
creates: list[str] = struct_field(default_factory=list)
requires: list[str] = struct_field(default_factory=list)
name: Optional[str] = None
runner: Optional[str] = None
path: Optional[str] = None
script: Optional[str] = None
stdin: Optional[str] = None
stdout: Optional[str] = None
description: Optional[str] = None
force: bool = False
@property
def all_targets(self):
return (
self.creates
+ ([self.stdout] if self.stdout else [])
+ ([f"#{self.name}"] if self.name else [])
)
@property
def all_dependencies(self):
return (
self.requires
+ ([self.stdin] if self.stdin else [])
+ ([self.path] if self.path else [])
)
@dataclass
class TemplateVariable(Lazy[Variable, str]):
template: str
def __post_init__(self):
self.requires += [Variable(arg) for arg in gather_args(self.template)]
async def run(self, *, db) -> str:
return substitute(self.template, db.environment)
@dataclass
class TemplateTask(Lazy[Path | Phony | Variable, Task]):
template: TaskProxy
def __post_init__(self):
assert not gather_args(self.template.creates)
check_list_syntax(self.template)
self.creates += [str_to_target(t) for t in self.template.all_targets]
self.requires += [Variable(arg) for arg in gather_args(self.template)]
self.requires += [Variable(n) for t in self.template.requires if (n := splice_name(t))]
async def run(self, *, db):
proxy = substitute(self.template, db.environment)
tgts = [str_to_target(t) for t in proxy.all_targets]
deps = [str_to_target(t) for t in db.splice(proxy.all_dependencies)]
path = Path(proxy.path) if proxy.path else None
stdin = str_to_target(proxy.stdin) if proxy.stdin else None
stdout = str_to_target(proxy.stdout) if proxy.stdout else None
assert not isinstance(stdin, Phony) and not isinstance(stdout, Phony)
task = Task(
tgts,
deps,
proxy.name,
proxy.runner,
path,
proxy.script,
stdin,
stdout,
proxy.description,
proxy.force,
list_output=proxy.stdout is not None and LIST_VARIABLE.fullmatch(proxy.stdout) is not None,
)
return task
def check_list_syntax(proxy: TaskProxy):
"""`listvar(name)` can only be used as `stdout`, `splice(name)` only in
`requires`."""
for t in [*proxy.creates, *proxy.all_dependencies]:
if LIST_VARIABLE.fullmatch(t):
raise HelpfulUserError(f"`{t}` can only be used as `stdout` of a task.")
for t in [*proxy.all_targets, *(x for x in (proxy.stdin, proxy.path) if x)]:
if SPLICE.fullmatch(t):
raise HelpfulUserError(f"`{t}` can only be used in `requires` or template call arguments.")
@dataclass
class TaskDB(LazyDB[Path | Variable | Phony, Task | TemplateTask | TemplateVariable]):
runners: dict[str, Runner] = field(default_factory=lambda: copy(DEFAULT_RUNNERS))
throttle: Optional[asyncio.Semaphore] = None
force_run: bool = False
history_path: Path | None = None
history: dict[Path, str | None] = field(default_factory=dict)
@contextmanager
def persistent_history(self):
if not self.history_path:
yield
else:
self.read_history(self.history_path)
yield
self.write_history(self.history_path)
def read_history(self, history_path: Path):
if not history_path.exists():
return
with open(history_path, "r") as f_in:
data = json.load(f_in)
for k, v in data.items():
self.history[Path(k)] = v
def write_history(self, history_path: Path):
with open(history_path, "w") as f_out:
json.dump({str(k): v for k, v in self.history.items()}, f_out, indent=2)
def on_missing(self, t: Path | Phony | Variable):
if isinstance(t, Path) and t.exists():
return Task([t], [])
raise MissingDependency()
def is_resolvable(self, s: Any) -> bool:
return all(v in self.index for v in map(Variable, gather_args(s)))
async def resolve_object(self, s: Any) -> Any:
vars = gather_args(s)
await asyncio.gather(*(self.run(Variable(v), db=self) for v in vars))
result = substitute(s, self.environment)
log.debug(f"substituting {s} => {result}")
return result
@property
def environment(self):
return Environment(self)
def list_variable(self, name: str) -> list[str]:
"""The value of list variable `name`, which should be computed already."""
if Variable(name) not in self.index:
raise HelpfulUserError(f"List variable `{name}` is not defined.")
value = self.index[Variable(name)].result
if not isinstance(value, list):
raise HelpfulUserError(
f"`splice({name})` needs a list variable; use `listvar({name})` as `stdout`.")
return value
def splice(self, items: list[str]) -> list[str]:
"""Replace each `splice(name)` in `items` with the elements of the list
variable `name`."""
result: list[str] = []
for item in items:
name = splice_name(item)
result.extend(self.list_variable(name) if name else [item])
return result
class Environment(Mapping[str, str]):
def __init__(self, db):
self.db = db
def __contains__(self, k: object):
return isinstance(k, str) and Variable(k) in self.db.index
def __iter__(self) -> Iterator[str]:
return (k.name for k in self.db.index if isinstance(k, Variable))
def __len__(self) -> int:
return sum(1 for _ in self)
def __getitem__(self, k: str) -> str:
value = self.db.index[Variable(k)].result
if isinstance(value, list):
raise HelpfulUserError(
f"`{k}` is a list variable, it can only be used as `splice({k})`.")
return valuePrograms
from __future__ import annotations
import asyncio
from collections.abc import Iterator
from copy import copy
from itertools import chain, product, repeat
from dataclasses import dataclass
from enum import Enum
import json
from pathlib import Path
from typing import cast
import tomllib
from msgspec import Struct, field
from msgspec.structs import replace
from .template_strings import gather_args, substitute
from .logging import logger
from .errors import HelpfulUserError, UserError
from .utility import construct, read_from_file
from .task import (
splice_name,
Variable,
TaskDB,
Runner,
TaskProxy,
TemplateTask,
TemplateVariable,
)
log = logger()
@dataclass
class MissingInclude(UserError):
path: Path
def __str__(self):
return f"Include `{self.path}` not found."
@dataclass
class MissingTemplate(UserError):
name: str
def __str__(self):
return f"Template `{self.name}` not found."
class Join(Enum):
INNER = "inner"
OUTER = "outer"
class TemplateCall(Struct, forbid_unknown_fields=True):
"""Calls a template with a set of arguments.
Members:
- template: name of the template.
- args: arguments to the call.
- collect: name of the phony target by which to collect all generated targets.
- join: `inner` or `outer` join.
"""
template: str
args: dict[str, str | list[str]]
collect: str | None = None
join: Join = Join.INNER
@property
def all_args(self) -> Iterator[dict[str, str]]:
if all(isinstance(v, str) for v in self.args.values()):
yield cast(dict[str, str], self.args)
return
if self.join == Join.INNER:
# Lists may be computed with `splice`, so a difference in length
# is an error, instead of silently dropping items.
lengths = {k: len(v) for k, v in self.args.items() if not isinstance(v, str)}
if len(set(lengths.values())) > 1:
raise HelpfulUserError(
f"Template `{self.template}`: the arguments of an inner join should "
"have the same length, got " + ", ".join(f"{k}: {n}" for k, n in lengths.items()))
for v in zip(
*map(
lambda x: repeat(x) if isinstance(x, str) else x,
self.args.values(),
)
):
yield dict(zip(self.args.keys(), v))
else: # cartesian product
for v in product(
*map(lambda x: [x] if isinstance(x, str) else x, self.args.values())
):
yield dict(zip(self.args.keys(), v))
class Program(Struct, forbid_unknown_fields=True):
"""A Brei program.
Members:
- task: list of tasks.
- environment: variables.
- template: set of templates; these are tasks with template variables
that are substituted by a `TemplateCall`.
- call: list of calls to templates.
- include: list of includes.
- runner: extra configured task runners.
"""
task: list[TaskProxy] = field(default_factory=list)
environment: dict[str, str] = field(default_factory=dict)
template: dict[str, TaskProxy] = field(default_factory=dict)
call: list[TemplateCall] = field(default_factory=list)
include: list[str] = field(default_factory=list)
runner: dict[str, Runner] = field(default_factory=dict)
@staticmethod
def read(path: Path, section: str | None = None) -> Program:
return read_from_file(Program, path, section)
def call_splices(call: TemplateCall) -> list[str]:
"""Names of the list variables spliced into the arguments of `call`."""
return [n for v in call.args.values() for item in ([v] if isinstance(v, str) else v)
if (n := splice_name(item))]
async def expand_splices(db: TaskDB, call: TemplateCall) -> TemplateCall:
"""Compute the list variables spliced into the arguments of `call`, and
insert their elements."""
names = call_splices(call)
results = await asyncio.gather(*(db.run(Variable(n), db=db) for n in names))
for n, r in zip(names, results):
if not r:
raise HelpfulUserError(f"Could not compute list variable `{n}`: {r}")
def expand(v: str | list[str]) -> str | list[str]:
if isinstance(v, str):
return db.splice([v]) if splice_name(v) else v
return db.splice(v)
return replace(call, args={k: expand(v) for k, v in call.args.items()})
def tasks_from_call(template: TaskProxy, call: TemplateCall) -> list[TaskProxy]:
tasks = [substitute(template, args) for args in call.all_args]
if call.collect:
targets = list(chain.from_iterable(t.all_targets for t in tasks))
collection = TaskProxy([], targets, name=call.collect)
return tasks + [collection]
else:
return tasks
async def resolve_delayed(db: TaskDB, tasks: list[TaskProxy]) -> list[TaskProxy]:
"""Resolve `tasks` (substituting variables in targets).
Returns: list of unresolvable tasks.
"""
async def resolve(task: TaskProxy) -> TaskProxy | None:
if not db.is_resolvable(task.all_targets):
return task
tt = await db.resolve_object(task)
db.add(TemplateTask([], [], tt))
return None
return [t for t in await asyncio.gather(*map(resolve, tasks)) if t]
async def resolve_tasks(program: Program, history_path: Path | None = None) -> TaskDB:
"""Resolve a program. A resolved program has all of its includes and
template calls done, so that only tasks remains. In order to resolve
a program, some tasks may need to be run. Variables that appear in
the `creates` field of a task (aka targets), will be resolved eagerly.
Returns: TaskDB instance.
"""
db = TaskDB(history_path = history_path)
template_index = dict()
async def go(program: Program):
for var, template in program.environment.items():
db.add(TemplateVariable([Variable(var)], [], template))
task_templates = copy(program.task)
template_index.update(program.template)
delayed_calls: list[TemplateCall] = []
delayed_templates: list[TaskProxy] = []
db.runners.update(program.runner)
for c in program.call:
if c.template not in template_index:
log.debug(
"template `%s` not available, waiting for includes to resolve",
c.template,
)
delayed_calls.append(c)
continue
if call_splices(c):
log.debug("call to `%s` splices list variables, waiting for tasks", c.template)
delayed_calls.append(c)
continue
task_templates.extend(tasks_from_call(template_index[c.template], c))
for tt in task_templates:
# we could check for resolvability here, but I don't like the
# idea that order then matters. this way the rule is:
# > if a task has a templated target, those variables should be
# > resolvable after all other tasks were added, seeing that the
# > task to resolve these variables can't have templated targets
# > themselves.
if gather_args(tt.all_targets):
delayed_templates.append(tt)
else:
db.add(TemplateTask([], [], tt))
delayed_templates = await resolve_delayed(db, delayed_templates)
for inc in program.include:
incp = Path(await db.resolve_object(inc))
if incp in db.index:
await db.run(incp, db=db)
if not incp.exists():
raise MissingInclude(incp)
prg = Program.read(incp)
await go(prg)
for c in delayed_calls:
if c.template not in template_index:
log.debug(
"template `%s` still not available, now this is an error", c.template
)
raise MissingTemplate(c.template)
c = await expand_splices(db, c)
for tt in tasks_from_call(template_index[c.template], c):
if gather_args(tt.creates):
delayed_templates.append(tt)
else:
db.add(TemplateTask([], [], tt))
delayed_templates = await resolve_delayed(db, delayed_templates)
if delayed_templates:
unresolvable = [p for t in delayed_templates for p in t.creates if not db.is_resolvable(p)]
raise UserError(f"Task has unresolvable targets: {unresolvable}")
return db
with db.persistent_history():
await go(program)
return dbUtils
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from datetime import datetime
import os
from .construct import construct, read_from_file
def normal_relative(path: Path) -> Path:
return path.resolve() # .relative_to(Path.cwd())
@dataclass
class FileStat:
path: Path
modified: datetime
@staticmethod
def from_path(path: Path):
stat = os.stat(path)
return FileStat(path, datetime.fromtimestamp(stat.st_mtime))
def __lt__(self, other: FileStat) -> bool:
return self.modified < other.modified
def stat(path: Path) -> FileStat:
path = normal_relative(path)
return FileStat.from_path(path)from dataclasses import dataclass
import time
from contextlib import asynccontextmanager
@dataclass
class Elapsed:
elapsed: float | None = None
@asynccontextmanager
async def timer():
e = Elapsed()
t = time.perf_counter()
yield e
e.elapsed = time.perf_counter() - tfrom typing import Any, Optional
import tomllib
import json
from pathlib import Path
import msgspec
from .errors import HelpfulUserError, InputError
def construct[T](annot: type[T], data: Any) -> T:
"""Construct an object of type `annot` from JSON compatible `data`, using
`msgspec` for validation. Raises an `InputError` if the data doesn't match
the type."""
try:
return msgspec.convert(data, type=annot)
except msgspec.ValidationError as e:
raise InputError(annot.__name__, str(e)) from e
def read_from_file[T](data_type: type[T], path: Path, section: Optional[str] = None) -> T:
"""Read a config from given `path` in given `section`. The path should refer to
a TOML or JSON file that should decode to a `Config` object. If `section` is given, only
that section is decoded to a `Config` object. The `section` string may contain
periods to indicate deeper nesting.
Example:
```python
read_from_file(Config, Path("./pyproject.toml"), "tool.loom")
```
"""
if not path.exists():
raise HelpfulUserError(f"File not found: {path}")
with open(path, "rb") as f:
if path.suffix == ".toml":
data: Any = tomllib.load(f)
elif path.suffix == ".json":
data = json.load(f)
else:
raise HelpfulUserError(f"Unrecognized file format: {path}")
try:
if section is not None:
for s in section.split("."):
data = data[s]
except KeyError as e:
raise HelpfulUserError(
f"Data file `{path}` should contain section `{section}`."
) from e
try:
return construct(data_type, data)
except InputError as e:
raise HelpfulUserError(f"In `{path}`: {e}") from e