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

 1# ~/~ begin <<docs/implementation.md#brei/__init__.py>>[init]
 2"""
 3Welcome to Brei's API documentation. There are two ways to use Brei: from the
 4command-line (in which case we refer to the homepage for documentation), or
 5straight from Python. The easiest function to work with is `brei()`, which
 6links to the command-line app one-to-one.
 7
 8## Program
 9If you want to read the `Program` yourself, there are several ways to do so:
10
111. Use `Program.read()`. You give it a `Path` to a TOML or JSON file and a
12section, this last bit giving a object path into the data. For instance:
13`Program.read(Path("pyproject.toml"), "tool.brei")`.
142. Read your own data format into JSON compatible data, then
15`construct(Program, data)`. The `construct` function uses `msgspec` to validate
16the input data against the type annotations of the program's classes.
17
18After reading the data, you'll want to resolve all tasks, i.e. perform includes
19and run any necessary task to resolve the targets of all other tasks.
20
21    program = Program.read(Path("brei.toml"))
22    db: TaskDB = await resolve_tasks(program)
23    await db.run(Phony("all"))
24
25There are three kinds of targets: `pathlib.Path`, `Phony` and `Variable`.
26
27## API
28"""
29
30from .program import Program, resolve_tasks, TemplateCall
31from .construct import construct
32from .lazy import Lazy, LazyDB
33from .task import Task, TaskDB, Phony, Variable, TaskProxy
34from .runner import Runner
35from .cli import brei
36
37__all__ = [
38    "brei",
39
40    "Lazy", "LazyDB", "Phony", "Program", "Runner", "Task", "TaskDB",
41    "TaskProxy", "TemplateCall", "Variable", "construct",
42    "resolve_tasks",
43]
44# ~/~ end
brei = <RichCommand brei>
@dataclass
class Lazy(typing.Generic[T, R]):
32@dataclass
33class Lazy[T, R]:
34    """Base class for tasks that are tagged with type `T` (usually `str` or
35    `Path`) and representing values of type `R`.
36
37    To implement a specific task, you need to implement the asynchronous
38    `run` method, which should return a value of `R` or throw `TaskFailure`.
39    If `run` returns another `Lazy` object, that is run in turn, and its
40    result is the result of this task.
41
42    Attributes:
43        creates: list of target identifiers, for instance paths that are
44            generated by running a particular task.
45        requires: list of dependency identifiers. All of these need to
46            be realized before the task can run.
47        result (property): value of the result, once the task was run. This
48            throws an exception if accessed before the task is complete.
49    """
50
51    creates: list[T]
52    requires: list[T]
53
54    _future: asyncio.Future[R] | None = field(default=None, init=False)
55    _awaiting: list[Lazy] = field(default_factory=list, init=False)
56
57    def __bool__(self):
58        return self._future is not None and self._future.done() \
59            and not self._future.cancelled() and self._future.exception() is None
60
61    @property
62    def result(self) -> R:
63        if self._future is None or not self._future.done():
64            raise ValueError("Task has not run yet.")
65        if not self:
66            raise ValueError("Task has failed.")
67        return self._future.result()
68
69    async def run(self, *, db) -> R:
70        raise NotImplementedError()
71
72    def reset(self):
73        self._future = None
74        self._awaiting = []

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.

Lazy(creates: 'list[T]', requires: 'list[T]')
creates: 'list[T]'
requires: 'list[T]'
result: 'R'
61    @property
62    def result(self) -> R:
63        if self._future is None or not self._future.done():
64            raise ValueError("Task has not run yet.")
65        if not self:
66            raise ValueError("Task has failed.")
67        return self._future.result()
async def run(self, *, db) -> 'R':
69    async def run(self, *, db) -> R:
70        raise NotImplementedError()
def reset(self):
72    def reset(self):
73        self._future = None
74        self._awaiting = []
@dataclass
class LazyDB(typing.Generic[T, TaskT]):
 81@dataclass
 82class LazyDB[T, TaskT: Lazy]:
 83    """Collect tasks and coordinate running a task from a task identifier."""
 84
 85    tasks: list[TaskT] = field(default_factory=list)
 86    index: dict[T, TaskT] = field(default_factory=dict)
 87
 88    async def run(self, t: T, **kwargs) -> Result[Any]:
 89        """Run the task that creates `t`, if it hasn't run yet. Keyword
 90        arguments are passed on to `Lazy.run`. Returns `Ok` with the value of
 91        the task, or a `Failure`."""
 92        try:
 93            return Ok(await self._start(self._get_task(t), **kwargs))
 94        except Failure as f:
 95            return f
 96
 97    def _get_task(self, t: T) -> Lazy:
 98        if t in self.index:
 99            return self.index[t]
100        try:
101            return self.on_missing(t)
102        except MissingDependency:
103            raise MissingFailure(t)
104
105    def _start(self, task: Lazy, **kwargs) -> asyncio.Future:
106        if task._future is None:
107            task._future = asyncio.ensure_future(self._run(task, **kwargs))
108        return task._future
109
110    async def _run(self, task: Lazy, **kwargs) -> Any:
111        current = task
112        while True:
113            await self._run_deps(task, current.requires, **kwargs)
114            value = await current.run(**kwargs)
115            if not isinstance(value, Lazy):
116                return value
117            current = value
118
119    async def _run_deps(self, waiter: Lazy, requires: list[T], **kwargs):
120        """Run the dependencies of `waiter`. Failures are collected into a
121        `DependencyFailure`, other exceptions are passed on."""
122        def start(t: T) -> asyncio.Future:
123            try:
124                dep = self._get_task(t)
125            except MissingFailure as f:
126                future = asyncio.get_running_loop().create_future()
127                future.set_exception(f)
128                return future
129            self._check_cycle(waiter, dep)
130            waiter._awaiting.append(dep)
131            return self._start(dep, **kwargs)
132
133        results = await asyncio.gather(*map(start, requires), return_exceptions=True)
134        for r in results:
135            if isinstance(r, BaseException) and not isinstance(r, Failure):
136                raise r
137        failed = {t: r for t, r in zip(requires, results) if isinstance(r, Failure)}
138        if failed:
139            raise DependencyFailure(failed)
140
141    def _check_cycle(self, waiter: Lazy, dep: Lazy):
142        """Raise `CyclicWorkflowError` if `dep` is (indirectly) waiting on `waiter`."""
143        paths = [[dep]]
144        seen: set[int] = set()
145        while paths:
146            path = paths.pop()
147            if path[-1] is waiter:
148                raise CyclicWorkflowError([t.creates[0] for t in [waiter, *path] if t.creates])
149            if id(path[-1]) in seen:
150                continue
151            seen.add(id(path[-1]))
152            paths.extend(path + [d] for d in path[-1]._awaiting)
153
154    def on_missing(self, t: T) -> TaskT:
155        raise MissingDependency()
156
157    def add(self, task: TaskT):
158        """Add a task to the DB."""
159        log.debug(f"adding task ===\n{task}")
160        self.tasks.append(task)
161        for target in task.creates:
162            self.index[target] = task
163
164    def clean(self):
165        self.tasks = []
166        self.index = {}
167
168    def reset(self):
169        for t in self.tasks:
170            t.reset()

Collect tasks and coordinate running a task from a task identifier.

LazyDB( tasks: 'list[TaskT]' = <factory>, index: 'dict[T, TaskT]' = <factory>)
tasks: 'list[TaskT]'
index: 'dict[T, TaskT]'
async def run(self, t: 'T', **kwargs) -> Result[typing.Any]:
88    async def run(self, t: T, **kwargs) -> Result[Any]:
89        """Run the task that creates `t`, if it hasn't run yet. Keyword
90        arguments are passed on to `Lazy.run`. Returns `Ok` with the value of
91        the task, or a `Failure`."""
92        try:
93            return Ok(await self._start(self._get_task(t), **kwargs))
94        except Failure as f:
95            return f

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.

def on_missing(self, t: 'T') -> 'TaskT':
154    def on_missing(self, t: T) -> TaskT:
155        raise MissingDependency()
def add(self, task: 'TaskT'):
157    def add(self, task: TaskT):
158        """Add a task to the DB."""
159        log.debug(f"adding task ===\n{task}")
160        self.tasks.append(task)
161        for target in task.creates:
162            self.index[target] = task

Add a task to the DB.

def clean(self):
164    def clean(self):
165        self.tasks = []
166        self.index = {}
def reset(self):
168    def reset(self):
169        for t in self.tasks:
170            t.reset()
@dataclass
class Phony:
15@dataclass
16class Phony:
17    name: str
18
19    @classmethod
20    def from_str(cls, s: str) -> Phony:
21        if s[0] == "#":
22            return Phony(s[1:])
23        raise ValueError("A phony target should start with a `#` character.")
24
25    def __str__(self):
26        return f"#{self.name}"
27
28    def __hash__(self):
29        return hash(str(self))
Phony(name: str)
name: str
@classmethod
def from_str(cls, s: str) -> Phony:
19    @classmethod
20    def from_str(cls, s: str) -> Phony:
21        if s[0] == "#":
22            return Phony(s[1:])
23        raise ValueError("A phony target should start with a `#` character.")
class Program(msgspec.Struct):
103class Program(Struct, forbid_unknown_fields=True):
104    """A Brei program.
105
106    Members:
107
108      - task: list of tasks.
109      - environment: variables.
110      - template: set of templates; these are tasks with template variables
111        that are substituted by a `TemplateCall`.
112      - call: list of calls to templates.
113      - include: list of includes.
114      - runner: extra configured task runners.
115    """
116    task: list[TaskProxy] = field(default_factory=list)
117    environment: dict[str, str] = field(default_factory=dict)
118    template: dict[str, TaskProxy] = field(default_factory=dict)
119    call: list[TemplateCall] = field(default_factory=list)
120    include: list[str] = field(default_factory=list)
121    runner: dict[str, Runner] = field(default_factory=dict)
122
123    @staticmethod
124    def read(path: Path, section: str | None = None) -> Program:
125        return read_from_file(Program, path, section)

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]
environment: dict[str, str]
template: dict[str, TaskProxy]
call: list[TemplateCall]
include: list[str]
runner: dict[str, Runner]
@staticmethod
def read(path: pathlib.Path, section: str | None = None) -> Program:
123    @staticmethod
124    def read(path: Path, section: str | None = None) -> Program:
125        return read_from_file(Program, path, section)
class Runner(msgspec.Struct):
6class Runner(Struct, forbid_unknown_fields=True):
7    command: str
8    args: list[str]

A base class for defining efficient serializable objects.

Fields are defined using type annotations. Fields may optionally have default values, which result in keyword parameters to the constructor.

Structs automatically define __init__, __eq__, __repr__, and __copy__ methods. Additional methods can be defined on the class as needed. Note that __init__/__new__ cannot be overridden, but other methods can. A tuple of the field names is available on the class via the __struct_fields__ attribute if needed.

Additional class options can be enabled by passing keywords to the class definition (see example below). These configuration options may also be inspected at runtime through the __struct_config__ attribute.

Configuration

frozen: bool, default False Whether instances of this type are pseudo-immutable. If true, attribute assignment is disabled and a corresponding __hash__ is defined. order: bool, default False If True, __lt__, `__le__,__gt__, and__ge__methods will be generated for this type. eq: bool, default True If True (the default), an__eq__method will be generated for this type. Set to False to compare based on instance identity alone. kw_only: bool, default False If True, all fields will be treated as keyword-only arguments in the generated__init__method. Default is False. omit_defaults: bool, default False Whether fields should be omitted from encoding if the corresponding value is the default for that field. Enabling this may reduce message size, and often also improve encoding & decoding performance. forbid_unknown_fields: bool, default False If True, an error is raised if an unknown field is encountered while decoding structs of this type. If False (the default), no error is raised and the unknown field is skipped. tag: str, int, bool, callable, or None, default None Used along withtag_fieldfor configuring tagged union support. If either are non-None, then the struct is considered "tagged". In this case, an extra field (thetag_field) and value (thetag``) are added to the encoded message, which can be used to differentiate message types during decoding.

Set tag=True to enable the default tagged configuration (tag_field is "type", tag is the class name). Alternatively, you can provide a string (or less commonly int) value directly to be used as the tag (e.g. tag="my-tag-value").tag can also be passed a callable that takes the class qualname and returns a valid tag value (e.g. tag=str.lower). See the docs for more information. tag_field: str or None, default None The field name to use for tagged union support. If tag is non-None, then this defaults to "type". See the tag docs above for more information. rename: str, mapping, callable, or None, default None Controls renaming the field names used when encoding/decoding the struct. May be one of "lower", "upper", "camel", "pascal", or "kebab" to rename in lowercase, UPPERCASE, camelCase, PascalCase, or kebab-case respectively. May also be a mapping from field names to the renamed names (missing fields are not renamed). Alternatively, may be a callable that takes the field name and returns a new name or None to not rename that field. Default is None for no field renaming. repr_omit_defaults: bool, default False Whether fields should be omitted from the generated repr if the corresponding value is the default for that field. array_like: bool, default False If True, this struct type will be treated as an array-like type during encoding/decoding, rather than a dict-like type (the default). This may improve performance, at the cost of a more inscrutable message encoding. gc: bool, default True Whether garbage collection is enabled for this type. Disabling this may help reduce GC pressure, but will prevent reference cycles composed of only gc=False from being collected. It is the user's responsibility to ensure that reference cycles don't occur when setting gc=False. weakref: bool, default False Whether instances of this type support weak references. Defaults to False. dict: bool, default False Whether instances of this type will include a __dict__. Setting this to True will allow adding additional undeclared attributes to a struct instance, which may be useful for holding private runtime state. Defaults to False. cache_hash: bool, default False If enabled, the hash of a frozen struct instance will be computed at most once, and then cached on the instance for further reuse. For expensive hash values this can improve performance at the cost of a small amount of memory usage.

Examples

Here we define a new Struct type for describing a dog. It has three fields; two required and one optional.

>>> class Dog(Struct):
...     name: str
...     breed: str
...     is_good_boy: bool = True
...
>>> Dog('snickers', breed='corgi')
Dog(name='snickers', breed='corgi', is_good_boy=True)

Additional struct options can be set as part of the class definition. Here we define a new Struct type for a frozen Point object.

>>> class Point(Struct, frozen=True):
...     x: float
...     y: float
...
>>> {Point(1.5, 2.0): 1}  # frozen structs are hashable
{Point(x=1.5, y=2.0): 1}
command: str
args: list[str]
 73@dataclass
 74class Task(Lazy[Path | Phony | Variable, str | list[str] | None]):
 75    name: str | None = None
 76    runner: str | None = None
 77    path: Path | None = None
 78    script: str | None = None
 79    stdin: Path | Variable | None = None
 80    stdout: Path | Variable | None = None
 81    description: str | None = None
 82    force: bool = False
 83    list_output: bool = False
 84
 85    @property
 86    def target_paths(self):
 87        return (p for p in self.creates if isinstance(p, Path))
 88
 89    @property
 90    def dependency_paths(self):
 91        return (p for p in self.requires if isinstance(p, Path))
 92
 93    @property
 94    def digest(self) -> str | None:
 95        if self.script is None:
 96            return None
 97        return hashlib.md5(self.script.encode()).hexdigest()
 98
 99    def __str__(self):
100        tgts = ", ".join(str(t) for t in self.creates)
101        deps = ", ".join(str(t) for t in self.requires)
102        if self.script is not None:
103            src = indent(self.script, prefix=" â–Ž ", predicate=lambda _: True)
104        elif self.path is not None:
105            src = str(self.path)
106        else:
107            src = " - "
108        name = f"{self.name}: " if self.name else ""
109        return name + f"[{tgts}] <- [{deps}]\n" + src
110
111    def __post_init__(self):
112        if self.name and Phony(self.name) not in self.creates:
113            self.creates.append(Phony(self.name))
114        if self.stdin and self.stdin not in self.requires:
115            self.requires.append(self.stdin)
116        if self.path and self.path not in self.requires:
117            self.requires.append(self.path)
118        if self.stdout and self.stdout not in self.creates:
119            self.creates.append(self.stdout)
120
121    def always_run(self) -> bool:
122        return self.force or len(list(self.target_paths)) == 0
123
124    def needs_run(self, db: TaskDB) -> bool:
125        if any(not p.exists() for p in self.target_paths):
126            return True
127        target_stats = [stat(p) for p in self.target_paths]
128        dep_stats = [stat(p) for p in self.dependency_paths]
129        if any(t < d for t in target_stats for d in dep_stats):
130            return True
131        if any(self.digest != db.history.get(p, None) for p in self.target_paths):
132            return True
133        return False
134
135    @contextmanager
136    def get_script_path(self):
137        if self.path is not None:
138            tmpfile = None
139            path = self.path
140        elif self.script is not None:
141            # On Windows, a file can't be opened by another process while we
142            # still have it open, so we close it before running the script.
143            with NamedTemporaryFile("w", delete=False) as tmpfile:
144                tmpfile.write(self.script)
145            path = Path(tmpfile.name)
146        else:
147            raise ValueError("A `Rule` can have either `path` or `script` defined.")
148
149        try:
150            yield path
151        finally:
152            if tmpfile is not None:
153                path.unlink(missing_ok=True)
154
155    @contextmanager
156    def get_stdin(self, db: TaskDB):
157        """Yields the `stdin` argument for the subprocess, and the data to
158        send to it."""
159        match self.stdin:
160            case Variable(x):
161                yield asyncio.subprocess.PIPE, db.environment[x].encode()
162            case x if isinstance(x, Path):
163                with open(x, "r") as stdin:
164                    yield stdin, None
165            case _:
166                yield None, None
167
168    @contextmanager
169    def get_stdout(self):
170        match self.stdout:
171            case Variable(x):
172                yield asyncio.subprocess.PIPE
173            case x if isinstance(x, Path):
174                with open(x, "w") as stdout:
175                    yield stdout
176            case _:
177                yield None
178
179    @contextmanager
180    def get_commands(self, db: TaskDB):
181        """Yields the list of commands to run. Without a runner, each line
182        of the script is a command; with a runner, the script is written to a
183        file (if needed) and passed to the runner."""
184        if self.runner is None:
185            assert self.script is not None
186            if not is_oneliner(self.script):
187                assert self.stdin is None
188            yield [shlex.split(line) for line in self.script.splitlines()]
189            return
190
191        runner = db.runners[self.runner]
192        with self.get_script_path() as path:
193            args = [string.Template(arg).substitute(script=path) for arg in runner.args]
194            yield [[runner.command, *args]]
195
196    def check_return_code(self, returncode: int | None, db: TaskDB):
197        """A failing command fails the task. Its targets may be written
198        partially, so we forget them, and they are built again next time."""
199        if returncode == 0:
200            return
201        for p in self.target_paths:
202            db.history.pop(p, None)
203        raise TaskFailure(f"Command failed with exit code {returncode}.")
204
205    async def _exec(self, db: TaskDB, short_note: str, command: list[str],
206                    stdin, input_data: bytes | None, stdout) -> bytes:
207        """Run a single command, returning its standard output if it was captured.
208        Standard error, and standard output if it doesn't go to a file or
209        variable, is forwarded to the log line by line while the command runs."""
210        async def write_stdin():
211            if input_data is None or proc.stdin is None:
212                return
213            try:
214                proc.stdin.write(input_data)
215                await proc.stdin.drain()
216                proc.stdin.close()
217            except (BrokenPipeError, ConnectionResetError):
218                pass  # the command exited without reading all of its input
219
220        async def forward(stream: asyncio.StreamReader | None):
221            if stream is None:
222                return
223            async for line in stream:
224                log.info(f"[gold1]{short_note}[/] %s", escape(line.decode().rstrip()),
225                         extra={"markup": True})
226
227        async def read_stdout() -> bytes:
228            if stdout is asyncio.subprocess.PIPE and proc.stdout is not None:
229                return await proc.stdout.read()
230            await forward(proc.stdout)
231            return b""
232
233        async with db.throttle or nullcontext():
234            proc = await create_subprocess_exec(
235                *command,
236                stdin=stdin,
237                stdout=asyncio.subprocess.PIPE if stdout is None else stdout,
238                stderr=asyncio.subprocess.PIPE,
239            )
240            stdout_data, *_ = await asyncio.gather(
241                read_stdout(), forward(proc.stderr), write_stdin())
242            await proc.wait()
243            log.debug(f"return-code {proc.returncode}")
244        self.check_return_code(proc.returncode, db)
245        return stdout_data
246
247    async def run(self, *, db: TaskDB):
248        if not self.always_run() and not self.needs_run(db) and not db.force_run:
249            tgts = " ".join(f"`{t}`" for t in self.target_paths)
250            log.debug(f"Targets {tgts} already up-to-date.")
251            return
252
253        log.debug(f"{self}")
254        if self.runner is None and self.script is None:
255            return
256
257        targets = " ".join(f"`{t}`" for t in self.creates)
258        short_note = self.description or (f"#{self.name}" if self.name else None) \
259            or f"creating {targets}"
260        log.info(f"[green]{short_note}[/]", extra={'markup': True})
261
262        stdout_data = b""
263        with self.get_commands(db) as commands, \
264                self.get_stdin(db) as (stdin, input_data), \
265                self.get_stdout() as stdout:
266            for command in commands:
267                stdout_data += await self._exec(db, short_note, command, stdin, input_data, stdout)
268
269        for p in self.target_paths:
270            db.history[p] = self.digest
271
272        if self.needs_run(db):
273            raise TaskFailure("Task didn't achieve goals.")
274
275        if self.list_output:
276            return [line for line in stdout_data.decode().splitlines() if line]
277        return stdout_data.decode().strip() if stdout_data else None
Task( creates: 'list[T]', requires: 'list[T]', name: str | None = None, runner: str | None = None, path: pathlib.Path | None = None, script: str | None = None, stdin: pathlib.Path | Variable | None = None, stdout: pathlib.Path | Variable | None = None, description: str | None = None, force: bool = False, list_output: bool = False)
name: str | None = None
runner: str | None = None
path: pathlib.Path | None = None
script: str | None = None
stdin: pathlib.Path | Variable | None = None
stdout: pathlib.Path | Variable | None = None
description: str | None = None
force: bool = False
list_output: bool = False
target_paths
85    @property
86    def target_paths(self):
87        return (p for p in self.creates if isinstance(p, Path))
dependency_paths
89    @property
90    def dependency_paths(self):
91        return (p for p in self.requires if isinstance(p, Path))
digest: str | None
93    @property
94    def digest(self) -> str | None:
95        if self.script is None:
96            return None
97        return hashlib.md5(self.script.encode()).hexdigest()
def always_run(self) -> bool:
121    def always_run(self) -> bool:
122        return self.force or len(list(self.target_paths)) == 0
def needs_run(self, db: TaskDB) -> bool:
124    def needs_run(self, db: TaskDB) -> bool:
125        if any(not p.exists() for p in self.target_paths):
126            return True
127        target_stats = [stat(p) for p in self.target_paths]
128        dep_stats = [stat(p) for p in self.dependency_paths]
129        if any(t < d for t in target_stats for d in dep_stats):
130            return True
131        if any(self.digest != db.history.get(p, None) for p in self.target_paths):
132            return True
133        return False
@contextmanager
def get_script_path(self):
135    @contextmanager
136    def get_script_path(self):
137        if self.path is not None:
138            tmpfile = None
139            path = self.path
140        elif self.script is not None:
141            # On Windows, a file can't be opened by another process while we
142            # still have it open, so we close it before running the script.
143            with NamedTemporaryFile("w", delete=False) as tmpfile:
144                tmpfile.write(self.script)
145            path = Path(tmpfile.name)
146        else:
147            raise ValueError("A `Rule` can have either `path` or `script` defined.")
148
149        try:
150            yield path
151        finally:
152            if tmpfile is not None:
153                path.unlink(missing_ok=True)
@contextmanager
def get_stdin(self, db: TaskDB):
155    @contextmanager
156    def get_stdin(self, db: TaskDB):
157        """Yields the `stdin` argument for the subprocess, and the data to
158        send to it."""
159        match self.stdin:
160            case Variable(x):
161                yield asyncio.subprocess.PIPE, db.environment[x].encode()
162            case x if isinstance(x, Path):
163                with open(x, "r") as stdin:
164                    yield stdin, None
165            case _:
166                yield None, None

Yields the stdin argument for the subprocess, and the data to send to it.

@contextmanager
def get_stdout(self):
168    @contextmanager
169    def get_stdout(self):
170        match self.stdout:
171            case Variable(x):
172                yield asyncio.subprocess.PIPE
173            case x if isinstance(x, Path):
174                with open(x, "w") as stdout:
175                    yield stdout
176            case _:
177                yield None
@contextmanager
def get_commands(self, db: TaskDB):
179    @contextmanager
180    def get_commands(self, db: TaskDB):
181        """Yields the list of commands to run. Without a runner, each line
182        of the script is a command; with a runner, the script is written to a
183        file (if needed) and passed to the runner."""
184        if self.runner is None:
185            assert self.script is not None
186            if not is_oneliner(self.script):
187                assert self.stdin is None
188            yield [shlex.split(line) for line in self.script.splitlines()]
189            return
190
191        runner = db.runners[self.runner]
192        with self.get_script_path() as path:
193            args = [string.Template(arg).substitute(script=path) for arg in runner.args]
194            yield [[runner.command, *args]]

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.

def check_return_code(self, returncode: int | None, db: TaskDB):
196    def check_return_code(self, returncode: int | None, db: TaskDB):
197        """A failing command fails the task. Its targets may be written
198        partially, so we forget them, and they are built again next time."""
199        if returncode == 0:
200            return
201        for p in self.target_paths:
202            db.history.pop(p, None)
203        raise TaskFailure(f"Command failed with exit code {returncode}.")

A failing command fails the task. Its targets may be written partially, so we forget them, and they are built again next time.

async def run(self, *, db: TaskDB):
247    async def run(self, *, db: TaskDB):
248        if not self.always_run() and not self.needs_run(db) and not db.force_run:
249            tgts = " ".join(f"`{t}`" for t in self.target_paths)
250            log.debug(f"Targets {tgts} already up-to-date.")
251            return
252
253        log.debug(f"{self}")
254        if self.runner is None and self.script is None:
255            return
256
257        targets = " ".join(f"`{t}`" for t in self.creates)
258        short_note = self.description or (f"#{self.name}" if self.name else None) \
259            or f"creating {targets}"
260        log.info(f"[green]{short_note}[/]", extra={'markup': True})
261
262        stdout_data = b""
263        with self.get_commands(db) as commands, \
264                self.get_stdin(db) as (stdin, input_data), \
265                self.get_stdout() as stdout:
266            for command in commands:
267                stdout_data += await self._exec(db, short_note, command, stdin, input_data, stdout)
268
269        for p in self.target_paths:
270            db.history[p] = self.digest
271
272        if self.needs_run(db):
273            raise TaskFailure("Task didn't achieve goals.")
274
275        if self.list_output:
276            return [line for line in stdout_data.decode().splitlines() if line]
277        return stdout_data.decode().strip() if stdout_data else None
371@dataclass
372class TaskDB(LazyDB[Path | Variable | Phony, Task | TemplateTask | TemplateVariable]):
373    runners: dict[str, Runner] = field(default_factory=lambda: copy(DEFAULT_RUNNERS))
374    throttle: asyncio.Semaphore | None = None
375    force_run: bool = False
376    history_path: Path | None = None
377    history: dict[Path, str | None] = field(default_factory=dict)
378
379    @contextmanager
380    def persistent_history(self):
381        if not self.history_path:
382            yield
383        else:
384            self.read_history(self.history_path)
385            yield
386            self.write_history(self.history_path)
387
388    def read_history(self, history_path: Path):
389        if not history_path.exists():
390            return
391
392        with open(history_path, "r") as f_in:
393            data = json.load(f_in)
394            for k, v in data.items():
395                self.history[Path(k)] = v
396
397    def write_history(self, history_path: Path):
398        with open(history_path, "w") as f_out:
399            json.dump({str(k): v for k, v in self.history.items()}, f_out, indent=2)
400
401    def on_missing(self, t: Path | Phony | Variable):
402        if isinstance(t, Path) and t.exists():
403            return Task([t], [])
404        raise MissingDependency()
405
406    def is_resolvable(self, s: Any) -> bool:
407        return all(v in self.index for v in map(Variable, gather_args(s)))
408
409    async def resolve_object(self, s: Any) -> Any:
410        vars = gather_args(s)
411        await asyncio.gather(*(self.run(Variable(v), db=self) for v in vars))
412        result = substitute(s, self.environment)
413        log.debug(f"substituting {s} => {result}")
414        return result
415
416    @property
417    def environment(self):
418        return Environment(self)
419
420    def list_variable(self, name: str) -> list[str]:
421        """The value of list variable `name`, which should be computed already."""
422        if Variable(name) not in self.index:
423            raise HelpfulUserError(f"List variable `{name}` is not defined.")
424        value = self.index[Variable(name)].result
425        if not isinstance(value, list):
426            raise HelpfulUserError(
427                f"`splice({name})` needs a list variable; use `listvar({name})` as `stdout`.")
428        return value
429
430    def splice(self, items: list[str]) -> list[str]:
431        """Replace each `splice(name)` in `items` with the elements of the list
432        variable `name`."""
433        result: list[str] = []
434        for item in items:
435            name = splice_name(item)
436            result.extend(self.list_variable(name) if name else [item])
437        return result
TaskDB( tasks: 'list[TaskT]' = <factory>, index: 'dict[T, TaskT]' = <factory>, runners: dict[str, Runner] = <factory>, throttle: asyncio.locks.Semaphore | None = None, force_run: bool = False, history_path: pathlib.Path | None = None, history: dict[pathlib.Path, str | None] = <factory>)
runners: dict[str, Runner]
throttle: asyncio.locks.Semaphore | None = None
force_run: bool = False
history_path: pathlib.Path | None = None
history: dict[pathlib.Path, str | None]
@contextmanager
def persistent_history(self):
379    @contextmanager
380    def persistent_history(self):
381        if not self.history_path:
382            yield
383        else:
384            self.read_history(self.history_path)
385            yield
386            self.write_history(self.history_path)
def read_history(self, history_path: pathlib.Path):
388    def read_history(self, history_path: Path):
389        if not history_path.exists():
390            return
391
392        with open(history_path, "r") as f_in:
393            data = json.load(f_in)
394            for k, v in data.items():
395                self.history[Path(k)] = v
def write_history(self, history_path: pathlib.Path):
397    def write_history(self, history_path: Path):
398        with open(history_path, "w") as f_out:
399            json.dump({str(k): v for k, v in self.history.items()}, f_out, indent=2)
def on_missing(self, t: pathlib.Path | Phony | Variable):
401    def on_missing(self, t: Path | Phony | Variable):
402        if isinstance(t, Path) and t.exists():
403            return Task([t], [])
404        raise MissingDependency()
def is_resolvable(self, s: Any) -> bool:
406    def is_resolvable(self, s: Any) -> bool:
407        return all(v in self.index for v in map(Variable, gather_args(s)))
async def resolve_object(self, s: Any) -> Any:
409    async def resolve_object(self, s: Any) -> Any:
410        vars = gather_args(s)
411        await asyncio.gather(*(self.run(Variable(v), db=self) for v in vars))
412        result = substitute(s, self.environment)
413        log.debug(f"substituting {s} => {result}")
414        return result
environment
416    @property
417    def environment(self):
418        return Environment(self)
def list_variable(self, name: str) -> list[str]:
420    def list_variable(self, name: str) -> list[str]:
421        """The value of list variable `name`, which should be computed already."""
422        if Variable(name) not in self.index:
423            raise HelpfulUserError(f"List variable `{name}` is not defined.")
424        value = self.index[Variable(name)].result
425        if not isinstance(value, list):
426            raise HelpfulUserError(
427                f"`splice({name})` needs a list variable; use `listvar({name})` as `stdout`.")
428        return value

The value of list variable name, which should be computed already.

def splice(self, items: list[str]) -> list[str]:
430    def splice(self, items: list[str]) -> list[str]:
431        """Replace each `splice(name)` in `items` with the elements of the list
432        variable `name`."""
433        result: list[str] = []
434        for item in items:
435            name = splice_name(item)
436            result.extend(self.list_variable(name) if name else [item])
437        return result

Replace each splice(name) in items with the elements of the list variable name.

class TaskProxy(msgspec.Struct):
280class TaskProxy(Struct, forbid_unknown_fields=True):
281    """Input to create an actual Task.
282
283    An actual `Task` has no template variables remaining and untyped strings
284    are replaced with `Path` `Variable` or `Phony` objects.
285    """
286    creates: list[str] = struct_field(default_factory=list)
287    requires: list[str] = struct_field(default_factory=list)
288    name: str | None = None
289    runner: str | None = None
290    path: str | None = None
291    script: str | None = None
292    stdin: str | None = None
293    stdout: str | None = None
294    description: str | None = None
295    force: bool = False
296
297    @property
298    def all_targets(self):
299        return (
300            self.creates
301            + ([self.stdout] if self.stdout else [])
302            + ([f"#{self.name}"] if self.name else [])
303        )
304
305    @property
306    def all_dependencies(self):
307        return (
308            self.requires
309            + ([self.stdin] if self.stdin else [])
310            + ([self.path] if self.path else [])
311        )

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]
requires: list[str]
name: str | None
runner: str | None
path: str | None
script: str | None
stdin: str | None
stdout: str | None
description: str | None
force: bool
all_targets
297    @property
298    def all_targets(self):
299        return (
300            self.creates
301            + ([self.stdout] if self.stdout else [])
302            + ([f"#{self.name}"] if self.name else [])
303        )
all_dependencies
305    @property
306    def all_dependencies(self):
307        return (
308            self.requires
309            + ([self.stdin] if self.stdin else [])
310            + ([self.path] if self.path else [])
311        )
class TemplateCall(msgspec.Struct):
 59class TemplateCall(Struct, forbid_unknown_fields=True):
 60    """Calls a template with a set of arguments.
 61
 62    Members:
 63
 64      - template: name of the template.
 65      - args: arguments to the call.
 66      - collect: name of the phony target by which to collect all generated targets.
 67      - join: `inner` or `outer` join.
 68    """
 69    template: str
 70    args: dict[str, str | list[str]]
 71    collect: str | None = None
 72    join: Join = Join.INNER
 73
 74    @property
 75    def all_args(self) -> Iterator[dict[str, str]]:
 76        if all(isinstance(v, str) for v in self.args.values()):
 77            yield cast(dict[str, str], self.args)
 78            return
 79
 80        if self.join == Join.INNER:
 81            # Lists may be computed with `splice`, so a difference in length
 82            # is an error, instead of silently dropping items.
 83            lengths = {k: len(v) for k, v in self.args.items() if not isinstance(v, str)}
 84            if len(set(lengths.values())) > 1:
 85                raise HelpfulUserError(
 86                    f"Template `{self.template}`: the arguments of an inner join should "
 87                    "have the same length, got " + ", ".join(f"{k}: {n}" for k, n in lengths.items()))
 88            for v in zip(
 89                *map(
 90                    lambda x: repeat(x) if isinstance(x, str) else x,
 91                    self.args.values(),
 92                )
 93            ):
 94                yield dict(zip(self.args.keys(), v))
 95
 96        else:  # cartesian product
 97            for v in product(
 98                *map(lambda x: [x] if isinstance(x, str) else x, self.args.values())
 99            ):
100                yield dict(zip(self.args.keys(), v))

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
join: brei.program.Join
all_args: Iterator[dict[str, str]]
 74    @property
 75    def all_args(self) -> Iterator[dict[str, str]]:
 76        if all(isinstance(v, str) for v in self.args.values()):
 77            yield cast(dict[str, str], self.args)
 78            return
 79
 80        if self.join == Join.INNER:
 81            # Lists may be computed with `splice`, so a difference in length
 82            # is an error, instead of silently dropping items.
 83            lengths = {k: len(v) for k, v in self.args.items() if not isinstance(v, str)}
 84            if len(set(lengths.values())) > 1:
 85                raise HelpfulUserError(
 86                    f"Template `{self.template}`: the arguments of an inner join should "
 87                    "have the same length, got " + ", ".join(f"{k}: {n}" for k, n in lengths.items()))
 88            for v in zip(
 89                *map(
 90                    lambda x: repeat(x) if isinstance(x, str) else x,
 91                    self.args.values(),
 92                )
 93            ):
 94                yield dict(zip(self.args.keys(), v))
 95
 96        else:  # cartesian product
 97            for v in product(
 98                *map(lambda x: [x] if isinstance(x, str) else x, self.args.values())
 99            ):
100                yield dict(zip(self.args.keys(), v))
@dataclass
class Variable:
36@dataclass
37class Variable:
38    name: str
39
40    def __hash__(self):
41        return hash(f"var({self.name})")
42
43    def __str__(self):
44        return f"var({self.name})"
Variable(name: str)
name: str
def construct(annot: type[T], data: Any) -> T:
14def construct[T](annot: type[T], data: Any) -> T:
15    """Construct an object of type `annot` from JSON compatible `data`, using
16    `msgspec` for validation. Raises an `InputError` if the data doesn't match
17    the type."""
18    try:
19        return msgspec.convert(data, type=annot)
20    except msgspec.ValidationError as e:
21        raise InputError(annot.__name__, str(e)) from e

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.

async def resolve_tasks( program: Program, history_path: pathlib.Path | None = None) -> TaskDB:
176async def resolve_tasks(program: Program, history_path: Path | None = None) -> TaskDB:
177    """Resolve a program. A resolved program has all of its includes and
178    template calls done, so that only tasks remains. In order to resolve
179    a program, some tasks may need to be run. Variables that appear in
180    the `creates` field of a task (aka targets), will be resolved eagerly.
181
182    Returns: TaskDB instance.
183    """
184    db = TaskDB(history_path = history_path)
185    template_index = dict()
186
187    async def go(program: Program):
188        for var, template in program.environment.items():
189            db.add(TemplateVariable([Variable(var)], [], template))
190
191        task_templates = copy(program.task)
192        template_index.update(program.template)
193        delayed_calls: list[TemplateCall] = []
194        delayed_templates: list[TaskProxy] = []
195
196        db.runners.update(program.runner)
197
198        for c in program.call:
199            if c.template not in template_index:
200                log.debug(
201                    "template `%s` not available, waiting for includes to resolve",
202                    c.template,
203                )
204                delayed_calls.append(c)
205                continue
206            if call_splices(c):
207                log.debug("call to `%s` splices list variables, waiting for tasks", c.template)
208                delayed_calls.append(c)
209                continue
210
211            task_templates.extend(tasks_from_call(template_index[c.template], c))
212
213        for tt in task_templates:
214            # we could check for resolvability here, but I don't like the
215            # idea that order then matters. this way the rule is:
216            # > if a task has a templated target, those variables should be
217            # > resolvable after all other tasks were added, seeing that the
218            # > task to resolve these variables can't have templated targets
219            # > themselves.
220            if gather_args(tt.all_targets):
221                delayed_templates.append(tt)
222            else:
223                db.add(TemplateTask([], [], tt))
224
225        delayed_templates = await resolve_delayed(db, delayed_templates)
226
227        for inc in program.include:
228            incp = Path(await db.resolve_object(inc))
229            if incp in db.index:
230                await db.run(incp, db=db)
231            if not incp.exists():
232                raise MissingInclude(incp)
233
234            prg = Program.read(incp)
235            await go(prg)
236
237        for c in delayed_calls:
238            if c.template not in template_index:
239                log.debug(
240                    "template `%s` still not available, now this is an error", c.template
241                )
242                raise MissingTemplate(c.template)
243
244            c = await expand_splices(db, c)
245            for tt in tasks_from_call(template_index[c.template], c):
246                if gather_args(tt.creates):
247                    delayed_templates.append(tt)
248                else:
249                    db.add(TemplateTask([], [], tt))
250
251        delayed_templates = await resolve_delayed(db, delayed_templates)
252        if delayed_templates:
253            unresolvable = [p for t in delayed_templates for p in t.creates if not db.is_resolvable(p)]
254            raise UserError(f"Task has unresolvable targets: {unresolvable}")
255
256        return db
257
258    with db.persistent_history():
259        await go(program)
260
261    return db

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.