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 the type annotations in dataclasses to validate the input data.

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 the type annotations
16in dataclasses to validate the input data.
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, Template
34from .runner import Runner
35from .cli import brei
36
37__all__ = [
38    "brei",
39
40    "Lazy", "LazyDB", "Phony", "Program", "Runner", "Task", "TaskDB",
41    "TaskProxy", "Template", "TemplateCall", "Variable", "construct",
42    "resolve_tasks",
43]
44# ~/~ end
brei = <RichCommand brei>
@dataclass
class Lazy(typing.Generic[~T, ~R]):
 37@dataclass
 38class Lazy(Generic[T, R]):
 39    """Base class for tasks that are tagged with type `T` (usually `str` or
 40    `Path`) and representing values of type `R`.
 41
 42    To implement a specific task, you need to implement the asynchronous
 43    `run` method, which should return a value of `R` or throw `TaskFailure`.
 44
 45    Attributes:
 46        targets: list of target identifiers, for instance paths that are
 47            generated by running a particular task.
 48        dependencies: list of dependency identifiers. All of these need to
 49            be realized before the task can run.
 50        result (property): value of the result, once the task was run. This
 51            throws an exception if accessed before the task is complete.
 52    """
 53
 54    creates: list[T]
 55    requires: list[T]
 56
 57    _lock: asyncio.Lock = field(default_factory=asyncio.Lock, init=False)
 58    _result: Optional[Result[R]] = field(default=None, init=False)
 59
 60    @property
 61    def real_requirements(self) -> list[T]:
 62        return [d for d in self.requires if not isinstance(d, Phony)]
 63
 64    def __bool__(self):
 65        return self._result is not None and bool(self._result)
 66
 67    @property
 68    def result(self) -> R:
 69        if self._result is None:
 70            raise ValueError("Task has not run yet.")
 71        if not self._result:
 72            raise ValueError("Task has failed.")
 73        assert isinstance(self._result, Ok)
 74        if isinstance(self._result.value, Lazy):
 75            return self._result.value.result
 76        return self._result.value
 77
 78    async def run(self, *, db) -> R:
 79        raise NotImplementedError()
 80
 81    async def run_after_deps(self, recurse, visited: dict[T, None], **kwargs) -> Result[R]:
 82        dep_res = await asyncio.gather(
 83            *(recurse(dep, copy(visited), **kwargs) for dep in self.requires)
 84        )
 85        if not all(dep_res):
 86            return DependencyFailure(
 87                {k: v for (k, v) in zip(self.requires, dep_res) if not v}
 88            )
 89        try:
 90            return Ok(await self.run(**kwargs))
 91        except TaskFailure as f:
 92            return f
 93
 94    async def run_cached(self, recurse, visited: dict[T, None], **kwargs) -> Result[R]:
 95        async with self._lock:
 96            if self._result is not None:
 97                return self._result
 98            self._result = await self.run_after_deps(recurse, visited, **kwargs)
 99            return self._result
100
101    def reset(self):
102        self._result = None
103
104    def fields(self):
105        return {f.name: getattr(self, f.name) for f in fields(self) if f.name[0] != "_"}

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.

Attributes: targets: list of target identifiers, for instance paths that are generated by running a particular task. dependencies: 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]
real_requirements: list[~T]
60    @property
61    def real_requirements(self) -> list[T]:
62        return [d for d in self.requires if not isinstance(d, Phony)]
result: ~R
67    @property
68    def result(self) -> R:
69        if self._result is None:
70            raise ValueError("Task has not run yet.")
71        if not self._result:
72            raise ValueError("Task has failed.")
73        assert isinstance(self._result, Ok)
74        if isinstance(self._result.value, Lazy):
75            return self._result.value.result
76        return self._result.value
async def run(self, *, db) -> ~R:
78    async def run(self, *, db) -> R:
79        raise NotImplementedError()
async def run_after_deps( self, recurse, visited: dict[~T, None], **kwargs) -> brei.result.Failure | brei.result.Ok[~R]:
81    async def run_after_deps(self, recurse, visited: dict[T, None], **kwargs) -> Result[R]:
82        dep_res = await asyncio.gather(
83            *(recurse(dep, copy(visited), **kwargs) for dep in self.requires)
84        )
85        if not all(dep_res):
86            return DependencyFailure(
87                {k: v for (k, v) in zip(self.requires, dep_res) if not v}
88            )
89        try:
90            return Ok(await self.run(**kwargs))
91        except TaskFailure as f:
92            return f
async def run_cached( self, recurse, visited: dict[~T, None], **kwargs) -> brei.result.Failure | brei.result.Ok[~R]:
94    async def run_cached(self, recurse, visited: dict[T, None], **kwargs) -> Result[R]:
95        async with self._lock:
96            if self._result is not None:
97                return self._result
98            self._result = await self.run_after_deps(recurse, visited, **kwargs)
99            return self._result
def reset(self):
101    def reset(self):
102        self._result = None
def fields(self):
104    def fields(self):
105        return {f.name: getattr(self, f.name) for f in fields(self) if f.name[0] != "_"}
@dataclass
class LazyDB(typing.Generic[~T, ~TaskT]):
114@dataclass
115class LazyDB(Generic[T, TaskT]):
116    """Collect tasks and coordinate running a task from a task identifier."""
117
118    tasks: list[TaskT] = field(default_factory=list)
119    index: dict[T, TaskT] = field(default_factory=dict)
120
121    async def run(self, t: T, visited: dict[T, None] | None = None, **kwargs) -> Result[Any]:
122        visited = visited or dict()
123        if t in visited:
124            raise CyclicWorkflowError(list(visited.keys()))
125        visited[t] = None
126
127        if t not in self.index:
128            try:
129                task = self.on_missing(t)
130            except MissingDependency:
131                return MissingFailure(t)
132        else:
133            task = self.index[t]
134
135        while True:
136            match (result := await task.run_cached(self.run, visited, **kwargs)):
137                case Ok(x) if isinstance(x, Lazy):
138                    task = cast(TaskT, x)
139                case _:
140                    return result
141
142    def on_missing(self, _: T) -> TaskT:
143        raise MissingDependency()
144
145    def add(self, task: TaskT):
146        """Add a task to the DB."""
147        log.debug(f"adding task ===\n{task}")
148        self.tasks.append(task)
149        for target in task.creates:
150            self.index[target] = task
151
152    def clean(self):
153        self.tasks = []
154        self.index = {}
155
156    def reset(self):
157        for t in self.tasks:
158            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, visited: dict[~T, None] | None = None, **kwargs) -> brei.result.Failure | brei.result.Ok[Any]:
121    async def run(self, t: T, visited: dict[T, None] | None = None, **kwargs) -> Result[Any]:
122        visited = visited or dict()
123        if t in visited:
124            raise CyclicWorkflowError(list(visited.keys()))
125        visited[t] = None
126
127        if t not in self.index:
128            try:
129                task = self.on_missing(t)
130            except MissingDependency:
131                return MissingFailure(t)
132        else:
133            task = self.index[t]
134
135        while True:
136            match (result := await task.run_cached(self.run, visited, **kwargs)):
137                case Ok(x) if isinstance(x, Lazy):
138                    task = cast(TaskT, x)
139                case _:
140                    return result
def on_missing(self, _: ~T) -> ~TaskT:
142    def on_missing(self, _: T) -> TaskT:
143        raise MissingDependency()
def add(self, task: ~TaskT):
145    def add(self, task: TaskT):
146        """Add a task to the DB."""
147        log.debug(f"adding task ===\n{task}")
148        self.tasks.append(task)
149        for target in task.creates:
150            self.index[target] = task

Add a task to the DB.

def clean(self):
152    def clean(self):
153        self.tasks = []
154        self.index = {}
def reset(self):
156    def reset(self):
157        for t in self.tasks:
158            t.reset()
@dataclass
class Phony(brei.construct.FromStr):
20@dataclass
21class Phony(FromStr):
22    name: str
23
24    @classmethod
25    def from_str(cls, s: str) -> Phony:
26        if s[0] == "#":
27            return Phony(s[1:])
28        raise ValueError("A phony target should start with a `#` character.")
29
30    def __str__(self):
31        return f"#{self.name}"
32
33    def __hash__(self):
34        return hash(str(self))
Phony(name: str)
name: str
@classmethod
def from_str(cls, s: str) -> Phony:
24    @classmethod
25    def from_str(cls, s: str) -> Phony:
26        if s[0] == "#":
27            return Phony(s[1:])
28        raise ValueError("A phony target should start with a `#` character.")
@dataclass
class Program:
101@dataclass
102class Program:
103    """A Brei program.
104
105    Members:
106
107      - task: list of tasks.
108      - environment: variables.
109      - template: set of templates.
110      - call: list of calls to templates.
111      - include: list of includes.
112      - runner: extra configured task runners.
113    """
114    task: list[TaskProxy] = field(default_factory=list)
115    environment: dict[str, str] = field(default_factory=dict)
116    template: dict[str, Template] = field(default_factory=dict)
117    call: list[TemplateCall] = field(default_factory=list)
118    include: list[str] = field(default_factory=list)
119    runner: dict[str, Runner] = field(default_factory=dict)
120
121    @staticmethod
122    def read(path: Path, section: str | None = None) -> Program:
123        return read_from_file(Program, path, section)

A Brei program.

Members:

  • task: list of tasks.
  • environment: variables.
  • template: set of templates.
  • call: list of calls to templates.
  • include: list of includes.
  • runner: extra configured task runners.
Program( task: list[TaskProxy] = <factory>, environment: dict[str, str] = <factory>, template: dict[str, Template] = <factory>, call: list[TemplateCall] = <factory>, include: list[str] = <factory>, runner: dict[str, Runner] = <factory>)
task: list[TaskProxy]
environment: dict[str, str]
template: dict[str, Template]
call: list[TemplateCall]
include: list[str]
runner: dict[str, Runner]
@staticmethod
def read(path: pathlib.Path, section: str | None = None) -> Program:
121    @staticmethod
122    def read(path: Path, section: str | None = None) -> Program:
123        return read_from_file(Program, path, section)
@dataclass
class Runner:
6@dataclass
7class Runner:
8    command: str
9    args: list[str]
Runner(command: str, args: list[str])
command: str
args: list[str]
 69@dataclass
 70class Task(Lazy[Path | Phony | Variable, str | list[str] | None]):
 71    name: Optional[str] = None
 72    runner: Optional[str] = None
 73    path: Optional[Path] = None
 74    script: Optional[str] = None
 75    stdin: Optional[Path | Variable] = None
 76    stdout: Optional[Path | Variable] = None
 77    description: Optional[str] = None
 78    force: bool = False
 79    list_output: bool = False
 80
 81    @property
 82    def target_paths(self):
 83        return (p for p in self.creates if isinstance(p, Path))
 84
 85    @property
 86    def dependency_paths(self):
 87        return (p for p in self.requires if isinstance(p, Path))
 88
 89    @property
 90    def digest(self) -> str | None:
 91        if self.script is None:
 92            return None
 93        return hashlib.md5(self.script.encode()).hexdigest()
 94
 95    def __str__(self):
 96        tgts = ", ".join(str(t) for t in self.creates)
 97        deps = ", ".join(str(t) for t in self.requires)
 98        if self.script is not None:
 99            src = indent(self.script, prefix=" â–Ž ", predicate=lambda _: True)
100        elif self.path is not None:
101            src = str(self.path)
102        else:
103            src = " - "
104        name = f"{self.name}: " if self.name else ""
105        return name + f"[{tgts}] <- [{deps}]\n" + src
106
107    def __post_init__(self):
108        if self.name and Phony(self.name) not in self.creates:
109            self.creates.append(Phony(self.name))
110        if self.stdin and self.stdin not in self.requires:
111            self.requires.append(self.stdin)
112        if self.path and self.path not in self.requires:
113            self.requires.append(self.path)
114        if self.stdout and self.stdout not in self.creates:
115            self.creates.append(self.stdout)
116
117    def always_run(self) -> bool:
118        return self.force or len(list(self.target_paths)) == 0
119
120    def needs_run(self, db: TaskDB) -> bool:
121        if any(not p.exists() for p in self.target_paths):
122            return True
123        target_stats = [stat(p) for p in self.target_paths]
124        dep_stats = [stat(p) for p in self.dependency_paths]
125        if any(t < d for t in target_stats for d in dep_stats):
126            return True
127        if any(self.digest != db.history.get(p, None) for p in self.target_paths):
128            return True
129        return False
130
131    @contextmanager
132    def get_script_path(self):
133        if self.path is not None:
134            tmpfile = None
135            path = self.path
136        elif self.script is not None:
137            # On Windows, a file can't be opened by another process while we
138            # still have it open, so we close it before running the script.
139            with NamedTemporaryFile("w", delete=False) as tmpfile:
140                tmpfile.write(self.script)
141            path = Path(tmpfile.name)
142        else:
143            raise ValueError("A `Rule` can have either `path` or `script` defined.")
144
145        try:
146            yield path
147        finally:
148            if tmpfile is not None:
149                path.unlink(missing_ok=True)
150
151    @contextmanager
152    def get_stdout(self):
153        match self.stdout:
154            case Variable(x):
155                yield asyncio.subprocess.PIPE
156            case x if isinstance(x, Path):
157                stdout = open(x, "w")
158                yield stdout
159                stdout.close()
160            case _:
161                yield None
162
163    def check_return_code(self, returncode: int | None, db: TaskDB):
164        """A failing command fails the task. Its targets may be written
165        partially, so we forget them, and they are built again next time."""
166        if returncode == 0:
167            return
168        for p in self.target_paths:
169            db.history.pop(p, None)
170        raise TaskFailure(f"Command failed with exit code {returncode}.")
171
172    async def run(self, *, db: TaskDB):
173        if not self.always_run() and not self.needs_run(db) and not db.force_run:
174            tgts = " ".join(f"`{t}`" for t in self.target_paths)
175            log.debug(f"Targets {tgts} already up-to-date.")
176            return
177
178        log.debug(f"{self}")
179        if (self.path is None and self.script is None):
180            return
181
182        targets = " ".join(f"`{t}`" for t in self.creates)
183        short_note = self.description or (f"#{self.name}" if self.name else None) \
184            or f"creating {targets}"
185        log.info(f"[green]{short_note}[/]", extra={'markup': True})
186
187        stdin: TextIO | int | None = None
188        match self.stdin:
189            case Variable(x):
190                stdin = asyncio.subprocess.PIPE
191                input_data = db.environment[x].encode()
192            case x if isinstance(x, Path):
193                stdin = open(x, "r")
194                input_data = None
195            case _:
196                stdin = None
197                input_data = None
198
199        if self.runner is None and self.script is not None:
200            if not is_oneliner(self.script):
201                assert self.stdin is None
202
203
204            with self.get_stdout() as stdout:
205                stdout_data = b""
206                for line in self.script.splitlines():
207                    async with db.throttle or nullcontext():
208                        proc = await create_subprocess_exec(
209                            *shlex.split(line),
210                            stdin=stdin,
211                            stdout=stdout,
212                            stderr=asyncio.subprocess.PIPE,
213                        )
214                        stdout_data_part, stderr_data = await proc.communicate(input_data)
215                        log.debug(f"return-code {proc.returncode}")
216                    if stdout_data_part:
217                        stdout_data += stdout_data_part
218                    if stderr_data:
219                        log.info(f"[gold1]{short_note}[/] %s", stderr_data.decode().rstrip(), extra={"markup": True})
220                    self.check_return_code(proc.returncode, db)
221
222        elif self.runner is not None:
223            with self.get_script_path() as path, self.get_stdout() as stdout:
224                runner = db.runners[self.runner]
225                args = [string.Template(arg).substitute(script=path) for arg in runner.args]
226                async with db.throttle or nullcontext():
227                    proc = await create_subprocess_exec(
228                        runner.command,
229                        *args,
230                        stdin=stdin,
231                        stdout=stdout,
232                        stderr=asyncio.subprocess.PIPE,
233                    )
234                    stdout_data, stderr_data = await proc.communicate(input_data)
235                    log.debug(f"return-code {proc.returncode}")
236
237            if stderr_data:
238                log.info(f"[gold1]{short_note}[/] %s", stderr_data.decode().rstrip(), extra={"markup": True})
239            self.check_return_code(proc.returncode, db)
240
241        else:
242            return
243
244        for p in self.target_paths:
245            db.history[p] = self.digest
246
247        if self.needs_run(db):
248            raise TaskFailure("Task didn't achieve goals.")
249
250        if self.list_output:
251            return [line for line in stdout_data.decode().splitlines() if line] if stdout_data else []
252        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
81    @property
82    def target_paths(self):
83        return (p for p in self.creates if isinstance(p, Path))
dependency_paths
85    @property
86    def dependency_paths(self):
87        return (p for p in self.requires if isinstance(p, Path))
digest: str | None
89    @property
90    def digest(self) -> str | None:
91        if self.script is None:
92            return None
93        return hashlib.md5(self.script.encode()).hexdigest()
def always_run(self) -> bool:
117    def always_run(self) -> bool:
118        return self.force or len(list(self.target_paths)) == 0
def needs_run(self, db: TaskDB) -> bool:
120    def needs_run(self, db: TaskDB) -> bool:
121        if any(not p.exists() for p in self.target_paths):
122            return True
123        target_stats = [stat(p) for p in self.target_paths]
124        dep_stats = [stat(p) for p in self.dependency_paths]
125        if any(t < d for t in target_stats for d in dep_stats):
126            return True
127        if any(self.digest != db.history.get(p, None) for p in self.target_paths):
128            return True
129        return False
@contextmanager
def get_script_path(self):
131    @contextmanager
132    def get_script_path(self):
133        if self.path is not None:
134            tmpfile = None
135            path = self.path
136        elif self.script is not None:
137            # On Windows, a file can't be opened by another process while we
138            # still have it open, so we close it before running the script.
139            with NamedTemporaryFile("w", delete=False) as tmpfile:
140                tmpfile.write(self.script)
141            path = Path(tmpfile.name)
142        else:
143            raise ValueError("A `Rule` can have either `path` or `script` defined.")
144
145        try:
146            yield path
147        finally:
148            if tmpfile is not None:
149                path.unlink(missing_ok=True)
@contextmanager
def get_stdout(self):
151    @contextmanager
152    def get_stdout(self):
153        match self.stdout:
154            case Variable(x):
155                yield asyncio.subprocess.PIPE
156            case x if isinstance(x, Path):
157                stdout = open(x, "w")
158                yield stdout
159                stdout.close()
160            case _:
161                yield None
def check_return_code(self, returncode: int | None, db: TaskDB):
163    def check_return_code(self, returncode: int | None, db: TaskDB):
164        """A failing command fails the task. Its targets may be written
165        partially, so we forget them, and they are built again next time."""
166        if returncode == 0:
167            return
168        for p in self.target_paths:
169            db.history.pop(p, None)
170        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):
172    async def run(self, *, db: TaskDB):
173        if not self.always_run() and not self.needs_run(db) and not db.force_run:
174            tgts = " ".join(f"`{t}`" for t in self.target_paths)
175            log.debug(f"Targets {tgts} already up-to-date.")
176            return
177
178        log.debug(f"{self}")
179        if (self.path is None and self.script is None):
180            return
181
182        targets = " ".join(f"`{t}`" for t in self.creates)
183        short_note = self.description or (f"#{self.name}" if self.name else None) \
184            or f"creating {targets}"
185        log.info(f"[green]{short_note}[/]", extra={'markup': True})
186
187        stdin: TextIO | int | None = None
188        match self.stdin:
189            case Variable(x):
190                stdin = asyncio.subprocess.PIPE
191                input_data = db.environment[x].encode()
192            case x if isinstance(x, Path):
193                stdin = open(x, "r")
194                input_data = None
195            case _:
196                stdin = None
197                input_data = None
198
199        if self.runner is None and self.script is not None:
200            if not is_oneliner(self.script):
201                assert self.stdin is None
202
203
204            with self.get_stdout() as stdout:
205                stdout_data = b""
206                for line in self.script.splitlines():
207                    async with db.throttle or nullcontext():
208                        proc = await create_subprocess_exec(
209                            *shlex.split(line),
210                            stdin=stdin,
211                            stdout=stdout,
212                            stderr=asyncio.subprocess.PIPE,
213                        )
214                        stdout_data_part, stderr_data = await proc.communicate(input_data)
215                        log.debug(f"return-code {proc.returncode}")
216                    if stdout_data_part:
217                        stdout_data += stdout_data_part
218                    if stderr_data:
219                        log.info(f"[gold1]{short_note}[/] %s", stderr_data.decode().rstrip(), extra={"markup": True})
220                    self.check_return_code(proc.returncode, db)
221
222        elif self.runner is not None:
223            with self.get_script_path() as path, self.get_stdout() as stdout:
224                runner = db.runners[self.runner]
225                args = [string.Template(arg).substitute(script=path) for arg in runner.args]
226                async with db.throttle or nullcontext():
227                    proc = await create_subprocess_exec(
228                        runner.command,
229                        *args,
230                        stdin=stdin,
231                        stdout=stdout,
232                        stderr=asyncio.subprocess.PIPE,
233                    )
234                    stdout_data, stderr_data = await proc.communicate(input_data)
235                    log.debug(f"return-code {proc.returncode}")
236
237            if stderr_data:
238                log.info(f"[gold1]{short_note}[/] %s", stderr_data.decode().rstrip(), extra={"markup": True})
239            self.check_return_code(proc.returncode, db)
240
241        else:
242            return
243
244        for p in self.target_paths:
245            db.history[p] = self.digest
246
247        if self.needs_run(db):
248            raise TaskFailure("Task didn't achieve goals.")
249
250        if self.list_output:
251            return [line for line in stdout_data.decode().splitlines() if line] if stdout_data else []
252        return stdout_data.decode().strip() if stdout_data else None
347@dataclass
348class TaskDB(LazyDB[Path | Variable | Phony, Task | TemplateTask | TemplateVariable]):
349    runners: dict[str, Runner] = field(default_factory=lambda: copy(DEFAULT_RUNNERS))
350    throttle: Optional[asyncio.Semaphore] = None
351    force_run: bool = False
352    history_path: Path | None = None
353    history: dict[Path, str | None] = field(default_factory=dict)
354
355    @contextmanager
356    def persistent_history(self):
357        if not self.history_path:
358            yield
359        else:
360            self.read_history(self.history_path)
361            yield
362            self.write_history(self.history_path)
363
364    def read_history(self, history_path: Path):
365        if not history_path.exists():
366            return
367
368        with open(history_path, "r") as f_in:
369            data = json.load(f_in)
370            for k, v in data.items():
371                self.history[Path(k)] = v
372
373    def write_history(self, history_path: Path):
374        with open(history_path, "w") as f_out:
375            json.dump({str(k): v for k, v in self.history.items()}, f_out, indent=2)
376
377    def on_missing(self, t: Path | Phony | Variable):
378        if isinstance(t, Path) and t.exists():
379            return Task([t], [])
380        raise MissingDependency()
381
382    def is_resolvable(self, s: Any) -> bool:
383        return all(v in self.index for v in map(Variable, gather_args(s)))
384
385    async def resolve_object(self, s: Any) -> Any:
386        vars = gather_args(s)
387        await asyncio.gather(*(self.run(Variable(v), db=self) for v in vars))
388        result = substitute(s, self.environment)
389        log.debug(f"substituting {s} => {result}")
390        return result
391
392    @property
393    def environment(self):
394        return Environment(self)
395
396    def list_variable(self, name: str) -> list[str]:
397        """The value of list variable `name`, which should be computed already."""
398        if Variable(name) not in self.index:
399            raise HelpfulUserError(f"List variable `{name}` is not defined.")
400        value = self.index[Variable(name)].result
401        if not isinstance(value, list):
402            raise HelpfulUserError(
403                f"`splice({name})` needs a list variable; use `listvar({name})` as `stdout`.")
404        return value
405
406    def splice(self, items: list[str]) -> list[str]:
407        """Replace each `splice(name)` in `items` with the elements of the list
408        variable `name`."""
409        result: list[str] = []
410        for item in items:
411            name = splice_name(item)
412            result.extend(self.list_variable(name) if name else [item])
413        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):
355    @contextmanager
356    def persistent_history(self):
357        if not self.history_path:
358            yield
359        else:
360            self.read_history(self.history_path)
361            yield
362            self.write_history(self.history_path)
def read_history(self, history_path: pathlib.Path):
364    def read_history(self, history_path: Path):
365        if not history_path.exists():
366            return
367
368        with open(history_path, "r") as f_in:
369            data = json.load(f_in)
370            for k, v in data.items():
371                self.history[Path(k)] = v
def write_history(self, history_path: pathlib.Path):
373    def write_history(self, history_path: Path):
374        with open(history_path, "w") as f_out:
375            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):
377    def on_missing(self, t: Path | Phony | Variable):
378        if isinstance(t, Path) and t.exists():
379            return Task([t], [])
380        raise MissingDependency()
def is_resolvable(self, s: Any) -> bool:
382    def is_resolvable(self, s: Any) -> bool:
383        return all(v in self.index for v in map(Variable, gather_args(s)))
async def resolve_object(self, s: Any) -> Any:
385    async def resolve_object(self, s: Any) -> Any:
386        vars = gather_args(s)
387        await asyncio.gather(*(self.run(Variable(v), db=self) for v in vars))
388        result = substitute(s, self.environment)
389        log.debug(f"substituting {s} => {result}")
390        return result
environment
392    @property
393    def environment(self):
394        return Environment(self)
def list_variable(self, name: str) -> list[str]:
396    def list_variable(self, name: str) -> list[str]:
397        """The value of list variable `name`, which should be computed already."""
398        if Variable(name) not in self.index:
399            raise HelpfulUserError(f"List variable `{name}` is not defined.")
400        value = self.index[Variable(name)].result
401        if not isinstance(value, list):
402            raise HelpfulUserError(
403                f"`splice({name})` needs a list variable; use `listvar({name})` as `stdout`.")
404        return value

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

def splice(self, items: list[str]) -> list[str]:
406    def splice(self, items: list[str]) -> list[str]:
407        """Replace each `splice(name)` in `items` with the elements of the list
408        variable `name`."""
409        result: list[str] = []
410        for item in items:
411            name = splice_name(item)
412            result.extend(self.list_variable(name) if name else [item])
413        return result

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

@dataclass
class TaskProxy:
255@dataclass
256class TaskProxy:
257    """Input to create an actual Task.
258
259    An actual `Task` has no template variables remaining and untyped strings
260    are replaced with `Path` `Variable` or `Phony` objects.
261    """
262    creates: list[str] = field(default_factory=list)
263    requires: list[str] = field(default_factory=list)
264    name: Optional[str] = None
265    runner: Optional[str] = None
266    path: Optional[str] = None
267    script: Optional[str] = None
268    stdin: Optional[str] = None
269    stdout: Optional[str] = None
270    description: Optional[str] = None
271    force: bool = False
272
273    @property
274    def all_targets(self):
275        return (
276            self.creates
277            + ([self.stdout] if self.stdout else [])
278            + ([f"#{self.name}"] if self.name else [])
279        )
280
281    @property
282    def all_dependencies(self):
283        return (
284            self.requires
285            + ([self.stdin] if self.stdin else [])
286            + ([self.path] if self.path else [])
287        )

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.

TaskProxy( creates: list[str] = <factory>, requires: list[str] = <factory>, name: str | None = None, runner: str | None = None, path: str | None = None, script: str | None = None, stdin: str | None = None, stdout: str | None = None, description: str | None = None, force: bool = False)
creates: list[str]
requires: list[str]
name: str | None = None
runner: str | None = None
path: str | None = None
script: str | None = None
stdin: str | None = None
stdout: str | None = None
description: str | None = None
force: bool = False
all_targets
273    @property
274    def all_targets(self):
275        return (
276            self.creates
277            + ([self.stdout] if self.stdout else [])
278            + ([f"#{self.name}"] if self.name else [])
279        )
all_dependencies
281    @property
282    def all_dependencies(self):
283        return (
284            self.requires
285            + ([self.stdin] if self.stdin else [])
286            + ([self.path] if self.path else [])
287        )
class Template(brei.TaskProxy):
434class Template(TaskProxy):
435    """A `Template` can receive the same arguments as a TaskProxy. The difference is
436    that any template variables in the Template can be substituted with a `TemplateCall`."""
437    def call(self, args: dict[str, Any]) -> TaskProxy:
438        return substitute(self, args)

A Template can receive the same arguments as a TaskProxy. The difference is that any template variables in the Template can be substituted with a TemplateCall.

def call(self, args: dict[str, typing.Any]) -> TaskProxy:
437    def call(self, args: dict[str, Any]) -> TaskProxy:
438        return substitute(self, args)
@dataclass
class TemplateCall:
56@dataclass
57class TemplateCall:
58    """Calls a template with a set of arguments.
59
60    Members:
61
62      - template: name of the template.
63      - args: arguments to the call.
64      - collect: name of the phony target by which to collect all generated targets.
65      - join: `inner` or `outer` join.
66    """
67    template: str
68    args: dict[str, str | list[str]]
69    collect: str | None = None
70    join: Join = Join.INNER
71
72    @property
73    def all_args(self):
74        if all(isinstance(v, str) for v in self.args.values()):
75            yield self.args
76            return
77
78        if self.join == Join.INNER:
79            # Lists may be computed with `splice`, so a difference in length
80            # is an error, instead of silently dropping items.
81            lengths = {k: len(v) for k, v in self.args.items() if not isinstance(v, str)}
82            if len(set(lengths.values())) > 1:
83                raise HelpfulUserError(
84                    f"Template `{self.template}`: the arguments of an inner join should "
85                    "have the same length, got " + ", ".join(f"{k}: {n}" for k, n in lengths.items()))
86            for v in zip(
87                *map(
88                    lambda x: repeat(x) if isinstance(x, str) else x,
89                    self.args.values(),
90                )
91            ):
92                yield dict(zip(self.args.keys(), v))
93
94        else:  # cartesian product
95            for v in product(
96                *map(lambda x: [x] if isinstance(x, str) else x, self.args.values())
97            ):
98                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.
TemplateCall( template: str, args: dict[str, str | list[str]], collect: str | None = None, join: brei.program.Join = <Join.INNER: 1>)
template: str
args: dict[str, str | list[str]]
collect: str | None = None
join: brei.program.Join = <Join.INNER: 1>
all_args
72    @property
73    def all_args(self):
74        if all(isinstance(v, str) for v in self.args.values()):
75            yield self.args
76            return
77
78        if self.join == Join.INNER:
79            # Lists may be computed with `splice`, so a difference in length
80            # is an error, instead of silently dropping items.
81            lengths = {k: len(v) for k, v in self.args.items() if not isinstance(v, str)}
82            if len(set(lengths.values())) > 1:
83                raise HelpfulUserError(
84                    f"Template `{self.template}`: the arguments of an inner join should "
85                    "have the same length, got " + ", ".join(f"{k}: {n}" for k, n in lengths.items()))
86            for v in zip(
87                *map(
88                    lambda x: repeat(x) if isinstance(x, str) else x,
89                    self.args.values(),
90                )
91            ):
92                yield dict(zip(self.args.keys(), v))
93
94        else:  # cartesian product
95            for v in product(
96                *map(lambda x: [x] if isinstance(x, str) else x, self.args.values())
97            ):
98                yield dict(zip(self.args.keys(), v))
@dataclass
class Variable:
32@dataclass
33class Variable:
34    name: str
35
36    def __hash__(self):
37        return hash(f"var({self.name})")
38
39    def __str__(self):
40        return f"var({self.name})"
Variable(name: str)
name: str
def construct(annot: Any, json: Any) -> Any:
29def construct(annot: Any, json: Any) -> Any:
30    try:
31        return _construct(annot, json)
32    except (AssertionError, ValueError) as e:
33        raise InputError(annot, json) from e
async def resolve_tasks( program: Program, history_path: pathlib.Path | None = None) -> TaskDB:
174async def resolve_tasks(program: Program, history_path: Path | None = None) -> TaskDB:
175    """Resolve a program. A resolved program has all of its includes and
176    template calls done, so that only tasks remains. In order to resolve
177    a program, some tasks may need to be run. Variables that appear in
178    the `creates` field of a task (aka targets), will be resolved eagerly.
179
180    Returns: TaskDB instance.
181    """
182    db = TaskDB(history_path = history_path)
183    template_index = dict()
184
185    async def go(program: Program):
186        for var, template in program.environment.items():
187            db.add(TemplateVariable([Variable(var)], [], template))
188
189        task_templates = copy(program.task)
190        template_index.update(program.template)
191        delayed_calls: list[TemplateCall] = []
192        delayed_templates: list[TaskProxy] = []
193
194        db.runners.update(program.runner)
195
196        for c in program.call:
197            if c.template not in template_index:
198                log.debug(
199                    "template `%s` not available, waiting for includes to resolve",
200                    c.template,
201                )
202                delayed_calls.append(c)
203                continue
204            if call_splices(c):
205                log.debug("call to `%s` splices list variables, waiting for tasks", c.template)
206                delayed_calls.append(c)
207                continue
208
209            task_templates.extend(tasks_from_call(template_index[c.template], c))
210
211        for tt in task_templates:
212            # we could check for resolvability here, but I don't like the
213            # idea that order then matters. this way the rule is:
214            # > if a task has a templated target, those variables should be
215            # > resolvable after all other tasks were added, seeing that the
216            # > task to resolve these variables can't have templated targets
217            # > themselves.
218            if gather_args(tt.all_targets):
219                delayed_templates.append(tt)
220            else:
221                db.add(TemplateTask([], [], tt))
222
223        delayed_templates = await resolve_delayed(db, delayed_templates)
224
225        for inc in program.include:
226            incp = Path(await db.resolve_object(inc))
227            if incp in db.index:
228                await db.run(incp, db=db)
229            if not incp.exists():
230                raise MissingInclude(incp)
231
232            prg = Program.read(incp)
233            await go(prg)
234
235        for c in delayed_calls:
236            if c.template not in template_index:
237                log.debug(
238                    "template `%s` still not available, now this is an error", c.template
239                )
240                raise MissingTemplate(c.template)
241
242            c = await expand_splices(db, c)
243            for tt in tasks_from_call(template_index[c.template], c):
244                if gather_args(tt.creates):
245                    delayed_templates.append(tt)
246                else:
247                    db.add(TemplateTask([], [], tt))
248
249        delayed_templates = await resolve_delayed(db, delayed_templates)
250        if delayed_templates:
251            unresolvable = [p for t in delayed_templates for p in t.creates if not db.is_resolvable(p)]
252            raise UserError(f"Task has unresolvable targets: {unresolvable}")
253
254        return db
255
256    with db.persistent_history():
257        await go(program)
258
259    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.