Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Welcome to Brei

Brei is a small workflow system. This is the Rust version of Brei, which was written in Python; it reads the same workflows, with a few differences. The primary reason for creating Brei is to replace GNU Make, in order to be compatible on systems that are naturally deprived of this wonder of human ingenuity. In a nutshell:

[[task]]
description = "Greet the Globe"
stdout = "hello.txt"
script = "echo 'Hello, World!'"
  • No new syntax: programmable workflows in TOML, YAML or JSON files.
  • Efficient: Runs tasks lazily and in parallel.
  • Feature complete: Supports templates, variables, includes and configurable runners.
  • No dependencies: Brei is a single executable.
  • Small codebase: Brei is around 2000 lines of Rust, written as a literate program. This book is the source code.

Why

Why yet another workflow tool? This tool was developed as part of the Entangled project, but can be used on its own. Brei is meant to perform small scale automisations for literate programming in Entangled, like generating figures, and performing computations locally. It requires no setup to work with and workflows are easy to understand by novice users. If you have any more serious needs than that, we’d recommend to use a more tried and proven system, of which there are too many to count.

When to use

You’re running a project, there’s lots of odds and ends that need automisation. You’d use a Makefile but your friend is on Windows and doesn’t have GNU Make installed. You try to ship a product that needs this, but don’t want to confront people trying it for the first time with a tonne of stuff they’ve never heard of.

Running

Install Brei with Cargo:

cargo install --git https://github.com/entangled/brei.rs

Then brei should be available as a command-line executable. Without -i, it reads brei.toml, brei.yaml, brei.yml, or the [tool.brei] section of pyproject.toml, whichever it finds first.

brei --help
Build one of the configured targets

Usage: brei [OPTIONS] [TARGETS]...

Arguments:
  [TARGETS]...  Names of the tasks to run, or other targets: files, or variables as `var(name)`

Options:
  -i, --input-file <INPUT_FILE>  Brei TOML, YAML or JSON file; use a `[...]` suffix to indicate a section
  -B, --force-run                Rebuild all dependencies
  -j, --jobs <JOBS>              Number of jobs to run at the same time [default: number of CPUs]
  -k, --keep-going               Keep going after a failure, building everything that doesn't depend on it
  -v, --version                  Print the version number and exit
      --list-runners             Show the default runners and exit
      --debug                    More verbose logging
  -h, --help                     Print help

How it works

You give Brei a list of tasks that may depend on one another. Brei will run these when input files are newer than the target, or when the script that creates the target changed since the last run (Brei keeps a history in .brei_history). Execution is lazy and in parallel.

Tasks

Tasks are the elemental units of work in Brei. A task is the single execution of a given script, and can be indicated to depend on previous tasks by explicitly listing targets and dependencies.

#| file: examples/tasks.toml
[[task]]
creates = ["hello.txt"]
runner = "bash"
script = "echo 'Hello, World!' > hello.txt"

[[task]]
name = "all"
requires = ["hello.txt"]

[[task]]
name = "clean"
script = "rm hello.txt"

This defines to named tasks all and clean, where all depends on the creation of a file hello.txt. Giving a name to a task is similar to creating a ‘phony’ target in Make.

Templates

We can use patterns to create reusable items. Variables are written like in many scripting languages: ${var_name} (or $var_name) substitutes for the contents of the var_name variable. Use two dollar signs $$ to make a $ literal. Any other dollar sign is left alone, so scripts can use things like $(pwd) or $1 without escaping them.

#| file: examples/rot13.toml
[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[template.echo]
stdout = "${stdout}"
script = "echo ${text}"

[template.rot13]
stdout = "${stdout}"
stdin = "${stdin}"
script = "tr a-zA-Z n-za-mN-ZA-M"

[[call]]
template = "echo"
  [call.args]
  stdout = "${dir}/secret.txt"
  text = "Uryyb, Jbeyq!"

[[call]]
template = "rot13"
  [call.args]
  stdin = "${dir}/secret.txt"
  stdout = "${dir}/msg.txt"

[[task]]
name = "all"
requires = ["${dir}/msg.txt"]
script = "cat ${dir}/msg.txt"
brei -i examples/rot13.toml all
Creating temporary directory
creating `/tmp/tmp.Jr9fybXRHx/secret.txt`
creating `/tmp/tmp.Jr9fybXRHx/msg.txt`
#all
#all Hello, World!

Multiplexing

You can call templates with lists of arguments to create many tasks. There are two ways to combine multiple arguments: inner and outer, configured with the join argument. The inner product takes the first item of each list, then the second, and so on, while outer takes every combination. The default is inner.

#| file: examples/template_multiplexing.toml
[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[template.touch]
description = "${pre} ${a} ${b}"
creates = ["${dir}/${pre}-${a}-${b}"]
script = "touch '${dir}/${pre}-${a}-${b}'"

[[call]]
template = "touch"
collect = "inner"
  [call.args]
  pre = "inner"
  a = ["x", "y", "z"]
  b = ["1", "2", "3"]

[[call]]
template = "touch"
collect = "outer"
join = "outer"
  [call.args]
  pre = "outer"
  a = ["x", "y"]
  b = ["1", "2"]

[[task]]
name = "all"
requires = ["#inner", "#outer"]

The collect argument creates a collection phony task containing all items in the call.

brei -i examples/template_multiplexing.toml all
Creating temporary directory
inner y 2
outer x 1
inner z 3
outer y 1
inner x 1
outer y 2
outer x 2

Variables

You may write the output of a command to the contents of a variable, by using "var(name)" as a target. For instance, in many science applications its desirable to know which version of a software generated some output.

#| file: examples/versioned_output.toml
[environment]
data_dir = "./data"
output_dir = "./output/${commit}"

[[task]]
stdout = "var(commit)"
script = "git rev-parse HEAD"

[[task]]
creates = ["${output_dir}/data.h5"]
requires = ["${data_dir}/input.h5", "#prepare"]
runner = "python"
path = "scripts/run.py"

[[task]]
name = "prepare"
script = """
mkdir -p ${output_dir}
ln -sf ${output_dir} output/latest
"""

[[task]]
name = "all"
requires = ["${output_dir}/data.h5"]

Also note the following:

  • Instead of listing a script you can give a path to an existing script.
  • Named (phony) targets are referenced with a hash symbol #.
  • Tasks with no targets are always run, and so are tasks that write to a variable.
  • The [environment] item lists global variables.
  • All string substitution is done lazily.

List variables

A task can also write its output to a list variable, by using "listvar(name)" as stdout. Each line of the output becomes an element of the list; empty lines are skipped. You can then use "splice(name)" as an element of a list in the arguments of a template call, to create a task for each element, or in requires, to depend on all of them. For instance, to copy all figures to the website:

#| file: examples/list_variables.toml
[[task]]
description = "Listing figures"
stdout = "listvar(figures)"
runner = "python"
script = """
from pathlib import Path
for p in sorted(Path("docs/fig").glob("*.svg")):
    print(p.name)
"""

[template.copy]
description = "copy `${name}`"
requires = ["docs/fig/${name}"]
creates = ["docs/site/fig/${name}"]
runner = "python"
script = """
import shutil
shutil.copy("docs/fig/${name}", "docs/site/fig/${name}")
"""

[[call]]
template = "copy"
collect = "figures"
args = { name = ["splice(figures)"] }

[[task]]
name = "all"
requires = ["#figures"]

The task that lists the figures has no file targets, so it runs every time, and new figures are found. Each copy task only runs when its figure changed.

List variables are kept simple on purpose:

  • listvar(name) can only be used as stdout of a task.
  • splice(name) can only be a whole element of a list in requires or in template call arguments, not part of a string.
  • A list variable can’t be used in a string with ${name}.
  • In an inner join, all lists should have the same length.

Brei has no functions to work on file names. Instead, have the listing print what the template needs, like the file names above. For anything more involved, generate a workflow and include it, see the next section.

Includes

You can include parts of a workflow from other files, in TOML, YAML or JSON.

#| file: examples/echo.toml
[template.echo]
stdout = "${stdout}"
script = "echo '${text}'"
#| file: examples/hello-includes.toml
include = [
    "./echo.toml"
]

[[call]]
template = "echo"
  [call.args]
  stdout = "hello.txt"
  text = "Hello, World!"

[[task]]
name = "all"
requires = ["hello.txt"]

It is even possible to include files that still need to be generated. The following generates a file with ten tasks, includes that file and runs those tasks.

#| file: examples/include-gen.toml
include = [
    "${dir}/gen.json"
]

[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[[task]]
description = "Generating workflow"
stdout = "${dir}/gen.json"
runner = "python"
script = """
import json
tasks = [
    {"stdout": f"${dir}/out{i}.dat",
     "script": f"echo '{i}'"} for i in range(10)
]
tasks.append({"name": "write-outs", "requires": [
    f"${dir}/out{i}.dat" for i in range(10)
]})
print(json.dumps({"task": tasks}))
"""

[[task]]
name = "all"
requires = ["#write-outs"]
brei -i examples/include-gen.toml all
Creating temporary directory
Generating workflow
creating `/tmp/tmp.qJTuIRn8mx/out7.dat`
creating `/tmp/tmp.qJTuIRn8mx/out1.dat`
creating `/tmp/tmp.qJTuIRn8mx/out8.dat`
creating `/tmp/tmp.qJTuIRn8mx/out6.dat`
creating `/tmp/tmp.qJTuIRn8mx/out5.dat`
creating `/tmp/tmp.qJTuIRn8mx/out4.dat`
creating `/tmp/tmp.qJTuIRn8mx/out3.dat`
creating `/tmp/tmp.qJTuIRn8mx/out2.dat`
creating `/tmp/tmp.qJTuIRn8mx/out0.dat`
creating `/tmp/tmp.qJTuIRn8mx/out9.dat`

Custom Runner

By default, the contents of script is split in lines, each line is split into arguments like a Unix shell would, and run as a command directly, without a shell. What that means is that the script will perform the same operations on all platforms, but there are no pipes, redirections or shell variables. However, you can choose to have the script run by any other means by providing the runner argument.

#| file: examples/custom-runner.toml
[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[runner.lua]
command = "lua"
args = ["${script}"]

[[task]]
runner = "lua"
stdout = "${dir}/hello.txt"
script = """
function fact (n)
  if n == 0 then
    return 1
  else
    return n * fact(n-1)
  end
end

print("10! = ", fact(10))
"""

[[task]]
name = "all"
requires = ["${dir}/hello.txt"]
script = "cat ${dir}/hello.txt"
brei -i examples/custom-runner.toml all
Creating temporary directory
creating `/tmp/tmp.0va1Atp7uz/hello.txt`
#all
#all 10! = 	3628800

There are a number of runners configured by default.

brei --list-runners
bash       bash ${script}
python     python ${script}

Forcing a rerun

Sometimes you want to always rerun a task no matter what. Brei measures its own test coverage this way, with this brei.toml. The tests run every time, also when no source file changed: they use other programs too, like bash and python, and Brei can’t see when those change. The other tasks run whenever there is a new profile.

The LLVM tools that read the profiles have to be the same version as the LLVM in rustc, so we use the ones that come with it (install them with rustup component add llvm-tools). Every process that runs during the tests (the test binaries, and the brei binary that some of them run) writes a raw profile of its own, and these are merged into one.

#| file: brei.toml
[environment]
ignore = "/.cargo/registry|/lib/rustlib/"

[[task]]
name = "coverage"
description = "Coverage report"
requires = ["docs/src/coverage/index.html"]
script = "${llvm_bin}/llvm-cov report --ignore-filename-regex=${ignore} --instr-profile=cov/brei.profdata ${objects}"

[[task]]
description = "Finding the LLVM tools"
stdout = "var(llvm_bin)"
runner = "bash"
script = '''echo "$(rustc --print sysroot)/lib/rustlib/$(rustc -vV | sed -n 's/^host: //p')/bin"'''

[[task]]
description = "Running tests with coverage"
creates = ["cov/brei.profdata"]
force = true
runner = "bash"
script = '''
set -e
rm -rf cov/profraw
LLVM_PROFILE_FILE="$(pwd)/cov/profraw/%p-%m.profraw" RUSTFLAGS="-C instrument-coverage" cargo test
${llvm_bin}/llvm-profdata merge -sparse cov/profraw/*.profraw -o cov/brei.profdata
'''

[[task]]
description = "Listing instrumented executables"
stdout = "var(objects)"
requires = ["cov/brei.profdata"]
runner = "bash"
script = '''
LLVM_PROFILE_FILE=/dev/null RUSTFLAGS="-C instrument-coverage" cargo test --no-run --message-format=json \
    | jq -j 'select(.reason == "compiler-artifact" and .executable != null) | "-object \(.executable) "'
'''

[[task]]
description = "Writing HTML report"
requires = ["cov/brei.profdata"]
creates = ["docs/src/coverage/index.html"]
script = "${llvm_bin}/llvm-cov show --format=html --project-title=Brei --output-dir=docs/src/coverage --ignore-filename-regex=${ignore} --instr-profile=cov/brei.profdata ${objects}"

[[task]]
name = "clean"
script = "rm -rf cov docs/src/coverage"

The HTML report goes into the source of this book, so that it becomes part of the coverage chapter.

To pass the executables to llvm-cov, we list them by building the tests again, which is quick because they are already built. Build scripts of dependencies may still run in this step, and would leave profiles of their own in the current directory, so those go to /dev/null.

brei coverage

Remarks

  • If you need your workflows also execute on a Windows machine, it is advised to write scripts for the default runner (lists of commands) or in a language like Python.
  • Brei is not meant for building programs, so it doesn’t have the same feature set as GNU Make. If you need more complex logic, you can write a Brei generator. The generator creates tasks, writes them to JSON and then Brei can include the result from your generator task.
  • TOML is nice but not ideal: it can be tricky to see the difference beteween single [...] and double [[...]] square brackets. Sometimes TOML syntax will lead to very verbose notation, however, current alternatives are all worse.
  • Many modern programming languages that we like (Python, Rust, Julia) have their project settings in a TOML file. This way your Brei workflow can piggy-back on project files that are already there.

License

Copyright 2023 Netherlands eScience Center, Licensed under the Apache License, Version 2.0, see LICENSE.

Use of generative AI

Significant parts of this port from Python to Rust were done by Claude Opus 5.5, a large language model by Anthropic, working in Claude Code. It worked under the direction of the author, who set the design and the conventions. The first version of the task engine (noodles), the template strings, and the literate setup of the project were written by hand. Claude wrote most of the rest: the engine’s memoization, cancellation and cycle detection; the Brei rules, variables, templates and program resolution; the program loader and the command-line interface; the tests ported from Python Brei; and this book’s tooling for coverage and running examples. Most of the prose in this book was written by Claude as well. Commits with Claude’s work are marked Co-Authored-By: Claude in the Git history.

Workflow Reference

This chapter lists everything that can go in a Brei workflow file. The introduction shows the same features by example; the Programs and Brei chapters explain how they work.

Files

A workflow is a TOML, YAML (.yaml or .yml) or JSON file; the extension decides which. brei reads, in this order:

  1. the file given with -i, for example -i workflow.toml;
  2. brei.toml in the current directory;
  3. brei.yaml or brei.yml in the current directory;
  4. the [tool.brei] section of pyproject.toml.

A workflow can also be a section of a bigger file. On the command line, the section goes in brackets after the file name, with dots between the keys: -i pyproject.toml[tool.brei]. Included files are always read as a whole.

Paths in a workflow, including those of includes, are relative to the directory brei runs in. Unknown keys and values of the wrong type are errors, so that typos don’t go unnoticed.

Top-level keys

All keys are optional.

KeyTypeMeaning
tasklist of tasksThe tasks, written [[task]] in TOML.
environmenttable of stringsVariables with a fixed value.
templatetable of tasksTemplates, by name.
calllist of callsUses of templates, written [[call]] in TOML.
includelist of stringsOther workflow files to include.
runnertable of runnersExtra runners, by name.

The same workflow in TOML, YAML and JSON:

[environment]
greeting = "Hello"

[[task]]
name = "all"
stdout = "hello.txt"
script = "echo '${greeting}, World!'"
environment:
  greeting: Hello
task:
  - name: all
    stdout: hello.txt
    script: "echo '${greeting}, World!'"
{
  "environment": { "greeting": "Hello" },
  "task": [
    { "name": "all", "stdout": "hello.txt", "script": "echo '${greeting}, World!'" }
  ]
}

Targets

Everything a task creates or requires is a target, written as a string:

Written asTarget
#nameA phony target: a name for a task that doesn’t create a file.
var(name)A scalar variable: a string, computed by a task.
listvar(name)A list variable: a list of strings, computed by a task.
splice(name)The elements of the list variable name, as separate targets. Only in requires and call arguments.
anything elseA path to a file. A leading ./ is ignored: ./a.txt is a.txt.

Variable names can’t contain white space or parentheses. var(x) and listvar(x) are the same variable, so using a variable both ways is an error.

Template strings

Almost every string in a workflow is a template string. ${name} (or $name) is replaced with the value of the scalar variable name. A variable gets its value from the environment, from a task with var(name) as stdout, or from the arguments of a call.

$$ is a literal dollar sign. Any other dollar sign is left alone, so scripts can use things like $(pwd), $1 or ${#array[@]} without escaping them. A name starts with a letter or underscore, followed by letters, digits and underscores.

Values are filled in lazily: a task that uses a variable waits for the task that computes it.

Tasks

A task runs a script to create its targets from its dependencies. All keys are optional.

KeyTypeMeaning
createslist of targetsWhat the task creates.
requireslist of targetsWhat the task needs before it can run.
namestringMakes the task available as the phony target #name.
descriptionstringShown in the log when the task runs.
scriptstringWhat to run. Without a runner, every line is a command.
runnerstringThe runner that runs script or path.
pathstringA script file to run, instead of script. Needs a runner, and is a dependency of the task.
stdintargetStandard input: a file or a scalar variable.
stdouttargetStandard output: a file, var(name) or listvar(name). It is also a target of the task.
forcebooleanAlways run the task. Default false.

Scripts

Without a runner, every non-empty line of script is a command. A line is split into arguments like a Unix shell would (with quotes and backslashes), but it doesn’t go through a shell: there are no pipes, redirections or shell variables. Programs are looked up on the PATH, like a shell does, and commands run in the directory brei runs in.

With a runner, the script is written to a temporary file, and the runner runs that file. A task with neither script nor path doesn’t run anything; it only waits for its dependencies, which is useful with name.

A command that doesn’t read stdin gets empty input, not the terminal. Output that doesn’t go to stdout (and all of standard error) goes to the log.

Output to variables

With stdout = "var(name)", the output of the script, without white space at the start and end, is the value of name. With stdout = "listvar(name)", every non-empty line of the output is an element of the list name.

When a task runs

A task runs when it is needed for the targets on the command line, and:

  • it creates no files (only phony targets or variables);
  • it writes its stdout to a variable;
  • force is true, or brei runs with -B;
  • one of the files it creates is missing, or older than one of the files it requires;
  • or its script changed since the files were made. Brei keeps track of this in .brei_history.

After running, every file in creates should exist and be up to date; otherwise the task failed.

Rules for tasks

These are errors:

  • two tasks that create the same target;
  • both script and path; path without runner; runner without script or path;
  • stdin that is a phony target or a list variable; stdout that is a phony target;
  • stdin on a script of more than one line without a runner (use a runner instead);
  • listvar(...) anywhere but stdout; splice(...) anywhere but requires;
  • variables in creates, stdout or name, unless they can be computed before running anything else (see Variables in targets).

Variables in targets

The targets of a task can use variables, as long as Brei can compute those first: the variables must come from the environment, or from tasks whose targets have no variables themselves. These tasks run while the workflow is read, once:

[[task]]
stdout = "var(dir)"
script = "mktemp -d"

[[task]]
name = "all"
stdout = "${dir}/hello.txt"
script = "echo hello"

Environment

[environment] gives variables a value. The values are template strings, and can use other variables:

[environment]
data_dir = "./data"
output_dir = "${data_dir}/output"

Templates

A template is a task with variables, that is filled in by a call. It has the same keys as a task. Templates are defined by name, under [template.name]; when two have the same name, the last one counts.

[template.echo]
stdout = "${stdout}"
script = "echo ${text}"

Calls

A call fills in a template.

KeyTypeMeaning
templatestringThe name of the template. Required.
argstable of strings or lists of stringsThe values of the template’s variables. Required.
collectstringA phony target #collect that requires all targets of the call.
join"inner" or "outer"How to combine list arguments. Default "inner".

The arguments are template strings themselves, so they can use variables from the environment. Variables of the template that aren’t in args keep their meaning: they come from the environment or from tasks.

When arguments are lists, the template is filled in several times:

  • inner: the first element of every list, then the second, and so on. All lists must have the same length.
  • outer: every combination of elements.

An element splice(name) in an argument list is replaced by the elements of the list variable name. A string argument splice(name) becomes that list.

[[call]]
template = "echo"
collect = "greetings"
args = { stdout = ["hello.txt", "bye.txt"], text = ["Hello", "Bye"] }

The template can also come from an include.

Includes

include lists other workflow files, in TOML, YAML or JSON, whose contents are added to this one. Include paths are template strings, and an included file can be created by a task in the including workflow: Brei runs that task first.

include = ["${dir}/generated.json"]

Includes are read after the tasks and calls of the workflow that includes them, so a call can use a template from an include.

Runners

A runner is a command that runs a script file.

KeyTypeMeaning
commandstringThe program to run.
argslist of stringsIts arguments. ${script} is the path of the script file. Other variables are an error.

Brei comes with two runners, bash and python, both called with ${script} as their only argument. A runner with the same name replaces it. brei --list-runners shows them.

[runner.lua]
command = "lua"
args = ["${script}"]

Differences with Python Brei

Brei.rs reads the same workflows as Python Brei. The few differences are listed in the Compatibility chapter.

Architecture

This project is developed in a style of literate programming using Entangled. All sources to the working program are present in this documentation.

Brei started out as a Python script supporting the use of Entangled by providing a simple and cheap workflow engine. The Python version uses Asyncio futures to perform the lazy evaluation of the tasks in a workflow. When porting to Rust, I found that it was easier to write a kernel that walks the dependency tree explicitly. This kernel design is still at the core of Brei (see the engine implementation), called Noodles after an earlier brainchild of mine by the same name.

This design was finalized and made working by Claude Opus 5.5, who also implemented all of the layering on top of the engine.

Main Module
The CLI, logging and end-to-end testing
Program Loader
Data structures for program input
Engine
Core task machine
Brei Rules
Layer on top of the engine
Programs
State machine around the tasks
Template Strings
Run-time string interpolation
Compatibility
Ensuring compatibility with the older Python implementation
Coverage
Test coverage report

Main Module

The crate consists of a library and a binary. The binary is the brei command. The library is meant for other front ends, like the Python package: they can define a program, from a file or in code, and run it. The modules that make up Brei are private; the library exports only what is needed for that.

  • A program is a Program, made of RuleTemplates (tasks and templates), Calls and Runners. These have public fields, and can be deserialized with serde from anything that looks like the workflow format. read_program reads one from a file.
  • run resolves a program and builds targets, with Options for the directory, the number of jobs, and so on. It fails with an Error, whose message is meant for people.
  • kill_all kills the commands that are running, for when the front end is interrupted. default_runners gives the runners that come with Brei.

The library logs through the log crate; the front end decides how to show it.

The library

The crate documentation, the modules, and what is exported.

#![allow(unused)]
fn main() {
//| file: src/lib.rs
//! Brei is a small but versatile workflow system. Workflows are written in TOML, YAML or JSON:
//! a list of tasks, which create targets from other targets by running a script. Tasks run
//! lazily and in parallel. See the [book](https://entangled.github.io/brei.rs) for the details.
//!
//! This library is for front ends: define a [`Program`], or read one with [`read_program`],
//! and [`run`] it. Brei logs through the [`log`](https://docs.rs/log) crate.
//!
//! ```no_run
//! use brei::{read_program, run, Options};
//!
//! let options = Options::default();
//! let program = read_program(&options.root, Some("brei.toml")).unwrap();
//! run(program, &["all"], &options).unwrap();
//! ```

#![warn(missing_docs)]

mod template_strings;
mod noodles;
mod tasks;
mod loader;

use std::fmt;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::Arc;
use noodles::kernel::Kernel;
use noodles::task::Error as EngineError;
use noodles::worker_pool::WorkerPool;
use tasks::{Job, Key, Target, TargetId, TaskDb, HISTORY_FILE};

pub use loader::{read_program, LoadError};
pub use tasks::{Program, Call, Argument, Join, RuleTemplate, Runner, default_runners, kill_all};

<<lib-options>>
<<lib-error>>
<<lib-targets>>
<<lib-run>>

#[cfg(test)]
mod tests {
    use super::*;

    <<lib-tests>>
}
}

Options

The options of run are those of the command line.

#![allow(unused)]
fn main() {
//| id: lib-options
/// How to run a program.
#[derive(Clone, Debug)]
pub struct Options {
    /// The directory to run in. Paths in the program, and the history file, are relative to it.
    pub root: PathBuf,
    /// The number of jobs to run at the same time; by default, the number of CPUs.
    pub jobs: Option<NonZeroUsize>,
    /// Run all tasks, also those that are up to date.
    pub force_run: bool,
    /// Keep going after a failure, building everything that doesn't depend on it.
    pub keep_going: bool,
}

impl Default for Options {
    fn default() -> Self {
        Options { root: PathBuf::from("."), jobs: None, force_run: false, keep_going: false }
    }
}
}

Errors

Errors carry a message, so that the types behind them can stay private. Failures are listed one per line. A cycle is shown as the chain of targets that wait for each other.

#![allow(unused)]
fn main() {
//| id: lib-error
/// Why running a program failed. Each kind carries a message for people.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// The history file can't be read or written.
    History(String),
    /// The program is wrong: a mistake in a task, a missing template or include, and so on.
    Program(String),
    /// A target to build isn't valid.
    Target(String),
    /// Some tasks failed, or wait for each other.
    Build(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::History(msg) | Error::Program(msg) | Error::Target(msg) | Error::Build(msg) => write!(f, "{msg}"),
        }
    }
}

impl std::error::Error for Error {}

fn describe(db: &TaskDb, error: EngineError<Job>) -> Error {
    Error::Build(match error {
        EngineError::Jobs(failures) => {
            let lines: Vec<String> = failures.iter().map(|f| format!("  - {f}")).collect();
            format!("some jobs have failed:\n{}", lines.join("\n"))
        }
        EngineError::Cycle(keys) => {
            let targets: Vec<String> = keys.iter().filter_map(|k| match k {
                Key::Target(id) => Some(format!("`{}`", db.targets.get(*id))),
                Key::Local(_) => None,
            }).collect();
            format!("cycle in dependencies: {}", targets.join(" -> "))
        }
        EngineError::Internal(e) => format!("internal error: {e}"),
    })
}
}

Targets

Targets to build are usually the names of rules: all builds #all. A name that isn’t the name of a rule is read as any other target, so output.csv builds a file, and var(x) computes a variable.

#![allow(unused)]
fn main() {
//| id: lib-targets
fn target(db: &TaskDb, name: &str) -> Result<TargetId, Error> {
    let phony = Target::Phony(name.to_string());
    let target = if db.creates(&phony) {
        phony
    } else {
        name.parse().map_err(|_| Error::Target("empty target name".into()))?
    };
    db.targets.intern(&target).map_err(|e| Error::Target(e.to_string()))
}
}

Running a program

The history is loaded before resolving the program, since resolving may already run rules. It is saved afterwards, also when something failed: rules that succeeded don’t need to run again. Resolving and building use the same kernel, so that what was computed during resolution is not computed again.

#![allow(unused)]
fn main() {
//| id: lib-run
/// Resolve `program`, and build `targets`: names of tasks, or other targets, like files or `var(name)`.
pub fn run(program: Program, targets: &[impl AsRef<str>], options: &Options) -> Result<(), Error> {
    let mut db = TaskDb::new(&options.root);
    db.force_run = options.force_run;
    let db = Arc::new(db);
    db.load_history(HISTORY_FILE).map_err(|e| Error::History(format!("can't read history: {e}")))?;

    let worker = match options.jobs {
        Some(jobs) => WorkerPool::new(jobs.get()),
        None => WorkerPool::with_available_parallelism(),
    };
    let mut kernel = Kernel::new();
    if options.keep_going {
        kernel = kernel.keep_going();
    }

    let result = tasks::resolve(&db, &mut kernel, &worker, program, &loader::load_include)
        .map_err(|e| Error::Program(e.to_string()))
        .and_then(|()| targets.iter().map(|t| target(&db, t.as_ref())).collect::<Result<Vec<_>, _>>())
        .and_then(|ids| tasks::build_all(&db, &mut kernel, &worker, &ids).map_err(|e| describe(&db, e)));

    let saved = db.save_history(HISTORY_FILE).map_err(|e| Error::History(format!("can't write history: {e}")));
    result.and(saved)
}
}

A program can be defined in code, without a file.

#![allow(unused)]
fn main() {
//| id: lib-tests
fn hello() -> Program {
    let task = RuleTemplate {
        name: Some("hello".into()),
        stdout: Some("hello.txt".into()),
        script: Some("echo hello".into()),
        ..Default::default()
    };
    Program { task: vec![task], ..Default::default() }
}

#[test]
fn run_program() {
    let dir = tempfile::TempDir::new().unwrap();
    let options = Options { root: dir.path().into(), ..Default::default() };
    run(hello(), &["hello"], &options).unwrap();
    assert_eq!(std::fs::read_to_string(dir.path().join("hello.txt")).unwrap(), "hello\n");
    assert!(dir.path().join(HISTORY_FILE).exists());

    assert!(matches!(run(hello(), &["nothere"], &options), Err(Error::Build(_))));
    assert!(matches!(run(hello(), &[""], &options), Err(Error::Target(_))));
    let broken = Program { include: vec!["nothere.toml".into()], ..Default::default() };
    assert_eq!(run(broken, &["hello"], &options), Err(Error::Program("include `nothere.toml` not found".into())));
}
}

The command line

The binary is the brei command-line program, on top of the library. It follows the options of the Python version, and adds -k, to keep going after a failure, like make -k.

#![allow(unused)]
fn main() {
//| file: src/main.rs
use std::io::IsTerminal;
use std::num::NonZeroUsize;
use std::path::Path;
use std::process::ExitCode;
use clap::Parser;
use brei::{default_runners, kill_all, read_program, run, Options};

/// Build one of the configured targets.
#[derive(Parser)]
#[command(name = "brei", disable_version_flag = true)]
struct Args {
    /// Names of the tasks to run, or other targets: files, or variables as `var(name)`.
    targets: Vec<String>,

    /// Brei TOML, YAML or JSON file; use a `[...]` suffix to indicate a section.
    #[arg(short, long)]
    input_file: Option<String>,

    /// Rebuild all dependencies.
    #[arg(short = 'B', long)]
    force_run: bool,

    /// Number of jobs to run at the same time [default: number of CPUs].
    #[arg(short, long)]
    jobs: Option<NonZeroUsize>,

    /// Keep going after a failure, building everything that doesn't depend on it.
    #[arg(short, long)]
    keep_going: bool,

    /// Print the version number and exit.
    #[arg(short, long)]
    version: bool,

    /// Show the default runners and exit.
    #[arg(long)]
    list_runners: bool,

    /// More verbose logging.
    #[arg(long)]
    debug: bool,
}

<<main-logger>>
<<main-run>>
}

Logging

The library logs through the log crate, and this is where the log is shown, on standard error. When a rule runs, its note is shown in green. Every line of output of a command is shown with the note of its rule in yellow (the library passes it as the key-value pair note). Anything between backticks is shown in bold. Without --debug, debug messages are hidden. Colours are only used on a terminal, and not when NO_COLOR is set.

#![allow(unused)]
fn main() {
//| id: main-logger
struct Logger {
    level: log::LevelFilter,
    color: bool,
}

impl Logger {
    fn paint(&self, code: &str, text: &str) -> String {
        match self.color {
            true => format!("\x1b[{code}m{text}\x1b[0m"),
            false => text.to_string(),
        }
    }

    /// Show text in backticks in bold.
    fn highlight(&self, text: &str) -> String {
        let parts: Vec<&str> = text.split('`').collect();
        if !self.color || parts.len().is_multiple_of(2) {
            return text.to_string();
        }
        parts.iter().enumerate().map(|(i, part)| match i % 2 {
            1 => format!("\x1b[1m`{part}`\x1b[22m"),
            _ => part.to_string(),
        }).collect()
    }
}

impl log::Log for Logger {
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        metadata.level() <= self.level && metadata.target().starts_with("brei")
    }

    fn log(&self, record: &log::Record) {
        use log::Level;
        if !self.enabled(record.metadata()) {
            return;
        }
        let message = record.args().to_string();
        let line = match (record.level(), record.target()) {
            (Level::Info, "brei::rule") => self.paint("32", &message),
            (Level::Info, "brei::output") => {
                let note = record.key_values().get(log::kv::Key::from_str("note")).map(|v| v.to_string()).unwrap_or_default();
                format!("{} {message}", self.paint("33", &note))
            }
            (Level::Info, _) => self.highlight(&message),
            (Level::Debug | Level::Trace, _) => self.paint("2", &format!("debug: {message}")),
            (Level::Warn, _) => format!("{} {}", self.paint("33", "warning:"), self.highlight(&message)),
            (Level::Error, _) => format!("{} {}", self.paint("1;31", "error:"), self.highlight(&message)),
        };
        eprintln!("{line}");
    }

    fn flush(&self) {}
}

fn init_logger(debug: bool) {
    let level = if debug { log::LevelFilter::Debug } else { log::LevelFilter::Info };
    let color = std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none();
    if log::set_logger(Box::leak(Box::new(Logger { level, color }))).is_ok() {
        log::set_max_level(level);
    }
}
}

Main

Programs are read relative to the current directory, and so is the history. When Brei is interrupted (Ctrl-C, or SIGTERM), it kills the commands that are running, which run in process groups of their own and wouldn’t stop otherwise, and exits with code 130. The history isn’t saved then.

//| id: main-run
fn list_runners() {
    let runners = default_runners();
    let mut names: Vec<&String> = runners.keys().collect();
    names.sort();
    for name in names {
        let runner = &runners[name];
        println!("{name:10} {} {}", runner.command, runner.args.join(" "));
    }
}

fn main() -> ExitCode {
    let args = Args::parse();
    if args.version {
        println!("Brei {}", env!("CARGO_PKG_VERSION"));
        return ExitCode::SUCCESS;
    }
    if args.list_runners {
        list_runners();
        return ExitCode::SUCCESS;
    }
    init_logger(args.debug);
    let interrupted = ctrlc::set_handler(|| {
        kill_all();
        log::error!("interrupted");
        std::process::exit(130);
    });
    if let Err(e) = interrupted {
        log::warn!("can't handle interrupts: {e}");
    }
    let options = Options { root: ".".into(), jobs: args.jobs, force_run: args.force_run, keep_going: args.keep_going };
    let result = read_program(Path::new("."), args.input_file.as_deref())
        .map_err(|e| e.to_string())
        .and_then(|program| run(program, &args.targets, &options).map_err(|e| e.to_string()));
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(msg) => {
            log::error!("{msg}");
            ExitCode::FAILURE
        }
    }
}

Tests

These tests run the brei binary in a temporary directory.

#![allow(unused)]
fn main() {
//| file: tests/cli.rs
use std::fs;
use std::path::Path;
use std::process::{Command, Output};
use tempfile::TempDir;

fn brei(dir: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_brei")).args(args).current_dir(dir).output().unwrap()
}

fn setup(program: &str) -> TempDir {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("brei.toml"), program).unwrap();
    dir
}

fn read(dir: &TempDir, path: &str) -> String {
    fs::read_to_string(dir.path().join(path)).unwrap()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

<<cli-tests>>
}

Building targets by name, or as a file. The second time, nothing runs, thanks to the history; with -B everything runs again.

#![allow(unused)]
fn main() {
//| id: cli-tests
const HELLO: &str = r#"
[[task]]
name = "hello"
creates = ["hello.txt"]
runner = "bash"
script = "echo run >> log.txt; echo hello > hello.txt"
"#;

#[test]
fn build() {
    let dir = setup(HELLO);
    assert!(brei(dir.path(), &["hello"]).status.success());
    assert_eq!(read(&dir, "hello.txt"), "hello\n");
    assert!(dir.path().join(".brei_history").exists());

    assert!(brei(dir.path(), &["hello.txt"]).status.success());
    assert_eq!(read(&dir, "log.txt"), "run\n");

    assert!(brei(dir.path(), &["-B", "hello"]).status.success());
    assert_eq!(read(&dir, "log.txt"), "run\nrun\n");
}
}

A failure gives an error message and exit code. With -k, the other targets are still built.

#![allow(unused)]
fn main() {
//| id: cli-tests
const FAILING: &str = r#"
[[task]]
name = "fail"
script = "false"

[[task]]
creates = ["ok.txt"]
script = "touch ok.txt"
"#;

#[test]
fn failure() {
    let dir = setup(FAILING);
    let output = brei(dir.path(), &["-k", "-j", "1", "fail", "ok.txt"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("`false` failed with exit code 1"), "{}", stderr(&output));
    assert!(dir.path().join("ok.txt").exists());

    let output = brei(dir.path(), &["nothere"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("missing dependency: `nothere`"), "{}", stderr(&output));
}
}

The output of commands is logged, with the note of the rule. With --debug, we also see which commands run.

#![allow(unused)]
fn main() {
//| id: cli-tests
#[test]
fn logging() {
    let dir = setup(r#"
        [[task]]
        name = "greet"
        script = "echo hello"

        [[task]]
        name = "complain"
        description = "complaining"
        runner = "bash"
        script = "echo oops >&2"
    "#);
    let output = brei(dir.path(), &["greet", "--debug"]);
    let log = stderr(&output);
    assert!(log.starts_with("#greet\n") && log.contains("#greet hello\n"), "{log}");
    assert!(log.contains("debug: #greet: running `echo hello`"), "{log}");
    assert!(output.stdout.is_empty());

    let output = brei(dir.path(), &["complain"]);
    assert!(stderr(&output).contains("complaining oops"), "{}", stderr(&output));
}
}

Input files, with a section, and errors in reading them.

#![allow(unused)]
fn main() {
//| id: cli-tests
#[test]
fn input_file() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("workflow.toml"), format!("[brei]\n{}", HELLO.replace("[[task]]", "[[brei.task]]"))).unwrap();
    assert!(brei(dir.path(), &["-i", "workflow.toml[brei]", "hello"]).status.success());
    assert_eq!(read(&dir, "hello.txt"), "hello\n");

    let output = brei(dir.path(), &["hello"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("no input file given"), "{}", stderr(&output));
}

#[test]
fn info() {
    let dir = TempDir::new().unwrap();
    let output = brei(dir.path(), &["--list-runners"]);
    assert!(String::from_utf8_lossy(&output.stdout).contains("bash"));
    let output = brei(dir.path(), &["-v"]);
    assert!(String::from_utf8_lossy(&output.stdout).starts_with("Brei "));
}
}

Program Loader

A Brei program is read from a TOML, YAML (.yaml or .yml) or JSON file, depending on its extension. It can also be a section of a bigger file: a Python project can keep its workflow in pyproject.toml, under [tool.brei]. Sections are written with dots, tool.brei.

On the command line, a section is given in brackets after the file name: pyproject.toml[tool.brei]. Without an input file, Brei looks for brei.toml, then for brei.yaml and brei.yml, and then for a [tool.brei] section in pyproject.toml.

#![allow(unused)]
fn main() {
//| file: src/loader.rs
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use serde::de::DeserializeOwned;
use crate::tasks::Program;

<<loader-error>>
<<loader-read>>
<<loader-program>>

#[cfg(test)]
mod tests {
    <<loader-tests>>
}
}

Errors

#![allow(unused)]
fn main() {
//| id: loader-error
/// Why a program can't be read.
#[derive(Debug)]
pub enum LoadError {
    /// The file can't be read.
    Io(PathBuf, String),
    /// The extension isn't `.toml`, `.yaml`, `.yml` or `.json`.
    UnknownFormat(PathBuf),
    /// The file isn't a valid program.
    Invalid(PathBuf, String),
    /// The file doesn't have the given section.
    MissingSection(PathBuf, String),
    /// No input file was given, and none was found.
    NoInput,
}

impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LoadError::Io(path, msg) => write!(f, "can't read `{}`: {msg}", path.display()),
            LoadError::UnknownFormat(path) => write!(f, "unknown file format: `{}`, use `.toml`, `.yaml` or `.json`", path.display()),
            LoadError::Invalid(path, msg) => write!(f, "in `{}`: {msg}", path.display()),
            LoadError::MissingSection(path, section) => write!(f, "`{}` should contain a section `{section}`", path.display()),
            LoadError::NoInput => write!(f,
                "no input file given, and no `brei.toml`, `brei.yaml`, `brei.yml`, or `pyproject.toml` with a `[tool.brei]` section, was found"),
        }
    }
}
}

Reading a file

Without a section, we deserialize the file directly, so that error messages point at the right line. To read a section, we first parse the file into a generic value, and look up the section in there. YAML has no generic value type of its own here: we read it into a JSON value, and from there it’s the same as JSON.

#![allow(unused)]
fn main() {
//| id: loader-read
/// Read a TOML, YAML or JSON file, or a section of it (`a.b` for nested sections).
pub fn read_from_file<T: DeserializeOwned>(path: &Path, section: Option<&str>) -> Result<T, LoadError> {
    let text = fs::read_to_string(path).map_err(|e| LoadError::Io(path.into(), e.to_string()))?;
    let invalid = |msg: String| LoadError::Invalid(path.into(), msg);
    let missing = || LoadError::MissingSection(path.into(), section.unwrap_or("").into());
    let keys = || section.into_iter().flat_map(|s| s.split('.'));
    let json = |mut value: serde_json::Value| {
        for key in keys() {
            value = value.get_mut(key).ok_or_else(missing)?.take();
        }
        serde_json::from_value(value).map_err(|e| invalid(e.to_string()))
    };

    match path.extension().and_then(|e| e.to_str()) {
        Some("toml") if section.is_none() => toml::from_str(&text).map_err(|e| invalid(e.to_string())),
        Some("toml") => {
            let mut value: toml::Value = toml::from_str(&text).map_err(|e| invalid(e.to_string()))?;
            for key in keys() {
                value = value.get_mut(key).ok_or_else(missing)?.clone();
            }
            value.try_into().map_err(|e: toml::de::Error| invalid(e.to_string()))
        }
        Some("json") => json(serde_json::from_str(&text).map_err(|e| invalid(e.to_string()))?),
        Some("yaml" | "yml") if section.is_none() => serde_saphyr::from_str(&text).map_err(|e| invalid(e.to_string())),
        Some("yaml" | "yml") => json(serde_saphyr::from_str(&text).map_err(|e| invalid(e.to_string()))?),
        _ => Err(LoadError::UnknownFormat(path.into())),
    }
}
}

Finding the program

The input is relative to the directory dir. Included programs are read without a section; load_include is the function to pass to tasks::resolve.

#![allow(unused)]
fn main() {
//| id: loader-program
/// Split `file[section]` into the file and the section.
fn split_input(input: &str) -> (&str, Option<&str>) {
    match input.strip_suffix(']').and_then(|s| s.split_once('[')) {
        Some((file, section)) if !file.is_empty() && !section.is_empty() => (file, Some(section)),
        _ => (input, None),
    }
}

/// Read the program given on the command line, or find one in `dir`.
pub fn read_program(dir: &Path, input: Option<&str>) -> Result<Program, LoadError> {
    if let Some(input) = input {
        let (file, section) = split_input(input);
        return read_from_file(&dir.join(file), section);
    }
    for name in ["brei.toml", "brei.yaml", "brei.yml"] {
        let brei = dir.join(name);
        if brei.exists() {
            return read_from_file(&brei, None);
        }
    }
    let pyproject = dir.join("pyproject.toml");
    if pyproject.exists() {
        return match read_from_file(&pyproject, Some("tool.brei")) {
            Err(LoadError::MissingSection(..)) => Err(LoadError::NoInput),
            result => result,
        };
    }
    Err(LoadError::NoInput)
}

/// Read an included program.
pub fn load_include(path: &Path) -> Result<Program, String> {
    read_from_file(path, None).map_err(|e| e.to_string())
}
}

Tests

#![allow(unused)]
fn main() {
//| id: loader-tests
use std::fs;
use std::sync::Arc;
use tempfile::TempDir;
use crate::noodles::kernel::Kernel;
use crate::noodles::single_worker::SingleWorker;
use crate::tasks::{TaskDb, Argument, Join, Value, resolve, build};
use super::*;

const SAMPLE: &str = r#"
    [environment]
    dir = "out"

    [[task]]
    description = "Creating output directory"
    creates = ["out/.keep"]
    script = "mkdir -p out\ntouch out/.keep"
    runner = "bash"

    [template.echo]
    stdout = "${stdout}"
    requires = ["out/.keep"]
    script = "echo ${text}"

    [template.rot13]
    stdout = "${stdout}"
    stdin = "${stdin}"
    script = "tr a-zA-Z n-za-mN-ZA-M"

    [[call]]
    template = "echo"
        [call.args]
        stdout = "${dir}/secret.txt"
        text = "Uryyb, Jbeyq!"

    [[call]]
    template = "rot13"
    join = "outer"
        [call.args]
        stdin = "${dir}/secret.txt"
        stdout = "var(message)"

    [runner.sh]
    command = "sh"
    args = ["${script}"]
"#;

fn write(dir: &TempDir, path: &str, text: &str) {
    fs::write(dir.path().join(path), text).unwrap();
}
}

A sample program, with all the parts of a program. It also runs.

#![allow(unused)]
fn main() {
//| id: loader-tests
#[test]
fn sample() {
    let dir = TempDir::new().unwrap();
    write(&dir, "brei.toml", SAMPLE);
    let program = read_program(dir.path(), None).unwrap();
    assert_eq!(program.task[0].description.as_deref(), Some("Creating output directory"));
    assert_eq!(program.call[1].join, Join::Outer);
    assert_eq!(program.call[0].args["text"], Argument::Single("Uryyb, Jbeyq!".into()));
    assert_eq!(program.runner["sh"].command, "sh");

    let db = Arc::new(TaskDb::new(dir.path()));
    let (mut kernel, worker) = (Kernel::new(), SingleWorker::new());
    resolve(&db, &mut kernel, &worker, program, &load_include).unwrap();
    let id = db.targets.lookup(&"var(message)".parse().unwrap()).unwrap();
    assert_eq!(build(&db, &mut kernel, &worker, id).unwrap(), Value::Scalar("Hello, World!".into()));
}
}

The same parts of a program in YAML.

#![allow(unused)]
fn main() {
//| id: loader-tests
#[test]
fn yaml() {
    let dir = TempDir::new().unwrap();
    write(&dir, "workflow.yaml", r#"
environment:
  name: World
task:
  - stdout: var(greeting)
    script: echo Hello
template:
  echo:
    stdout: ${out}
    script: echo ${greeting}, ${name}!
call:
  - template: echo
    args: { out: "var(message)" }
"#);
    let program = read_program(dir.path(), Some("workflow.yaml")).unwrap();
    let db = Arc::new(TaskDb::new(dir.path()));
    let (mut kernel, worker) = (Kernel::new(), SingleWorker::new());
    resolve(&db, &mut kernel, &worker, program, &load_include).unwrap();
    let id = db.targets.lookup(&"var(message)".parse().unwrap()).unwrap();
    assert_eq!(build(&db, &mut kernel, &worker, id).unwrap(), Value::Scalar("Hello, World!".into()));
}
}

Unknown fields and wrong types are errors, with the file name in the message.

#![allow(unused)]
fn main() {
//| id: loader-tests
#[test]
fn invalid() {
    let dir = TempDir::new().unwrap();
    write(&dir, "typo.toml", "[[task]]\nscirpt = \"echo\"\n");
    write(&dir, "join.toml", "[[call]]\ntemplate = \"t\"\nargs = {}\njoin = \"left\"\n");
    write(&dir, "list.json", r#"{"task": [{"creates": "a.txt"}]}"#);
    write(&dir, "typo.yaml", "task:\n  - scirpt: echo\n");
    write(&dir, "brei.ini", "");
    for file in ["typo.toml", "join.toml", "list.json", "typo.yaml"] {
        let err = read_program(dir.path(), Some(file)).unwrap_err();
        assert!(matches!(err, LoadError::Invalid(..)), "{file}: {err}");
        assert!(err.to_string().starts_with(&format!("in `{}", dir.path().join(file).display())));
    }
    assert!(matches!(read_program(dir.path(), Some("brei.ini")), Err(LoadError::UnknownFormat(_))));
    assert!(matches!(read_program(dir.path(), Some("nothere.toml")), Err(LoadError::Io(..))));
}
}

Programs can be in a section of a file, also in JSON and YAML. Without an input file, brei.toml comes first, then brei.yaml and brei.yml, then pyproject.toml.

#![allow(unused)]
fn main() {
//| id: loader-tests
#[test]
fn sections() {
    let dir = TempDir::new().unwrap();
    assert!(matches!(read_program(dir.path(), None), Err(LoadError::NoInput)));
    write(&dir, "pyproject.toml", "[project]\nname = \"test\"\n");
    assert!(matches!(read_program(dir.path(), None), Err(LoadError::NoInput)));

    write(&dir, "pyproject.toml", "[tool.brei]\ninclude = [\"pyproject\"]\n");
    assert_eq!(read_program(dir.path(), None).unwrap().include, ["pyproject"]);
    write(&dir, "brei.yml", "include: [yml]\n");
    assert_eq!(read_program(dir.path(), None).unwrap().include, ["yml"]);
    write(&dir, "brei.yaml", "include: [yaml]\n");
    assert_eq!(read_program(dir.path(), None).unwrap().include, ["yaml"]);
    write(&dir, "brei.toml", "include = [\"brei\"]\n");
    assert_eq!(read_program(dir.path(), None).unwrap().include, ["brei"]);

    write(&dir, "workflow.json", r#"{"a": {"b": {"include": ["json"]}}}"#);
    assert_eq!(read_program(dir.path(), Some("workflow.json[a.b]")).unwrap().include, ["json"]);
    assert!(matches!(read_program(dir.path(), Some("workflow.json[a.c]")), Err(LoadError::MissingSection(..))));
    write(&dir, "workflow.yml", "a:\n  b:\n    include: [yaml]\n");
    assert_eq!(read_program(dir.path(), Some("workflow.yml[a.b]")).unwrap().include, ["yaml"]);
    assert!(matches!(read_program(dir.path(), Some("workflow.yml[a.c]")), Err(LoadError::MissingSection(..))));
    assert_eq!(read_program(dir.path(), Some("pyproject.toml[tool.brei]")).unwrap().include, ["pyproject"]);
    assert_eq!(split_input("a[b]c"), ("a[b]c", None));
}
}

Errors in rules say which rule they come from.

#![allow(unused)]
fn main() {
//| id: loader-tests
#[test]
fn rule_errors() {
    let dir = TempDir::new().unwrap();
    write(&dir, "brei.toml", r#"
        [[task]]
        stdout = "listvar(x)"
        script = "true"

        [[task]]
        creates = ["b.txt"]
        script = "echo ${x}"
    "#);
    let program = read_program(dir.path(), None).unwrap();
    let db = Arc::new(TaskDb::new(dir.path()));
    let err = resolve(&db, &mut Kernel::new(), &SingleWorker::new(), program, &load_include).unwrap_err();
    assert_eq!(err.to_string(), "in rule for `b.txt`: `x` is a list variable, it can only be used as `splice(x)`");
}
}

Engine

The engine sends out tasks to get responses. A response is one of: a result, a continuation, or an error. The continuation should contain a promise, that is a graph of dependent tasks the root of which gives a new response, closing the recursive loop.

Every time a task is complete, its key is looked up in an inverse dependency map, and the result value maybe associated with a dependent task. If that task has all dependencies fulfilled, it may report ready.

#![allow(unused)]
fn main() {
//| file: src/noodles/mod.rs
pub mod task;
pub mod kernel;
pub mod worker_pool;

#[cfg(test)]
pub mod single_worker;
#[cfg(test)]
mod mock;
}
#![allow(unused)]
fn main() {
//| file: src/noodles/task.rs
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::iter::Iterator;
use std::hash::Hash;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};


pub trait Task: Sized {
    type Value: Clone;
    type Key: Copy + Hash + Eq;
    type Error: Clone;

    fn key(&self) -> Self::Key;
    fn dependencies(&self) -> impl Iterator<Item=Self::Key>;
    fn memoize(&self) -> bool;
    fn run(self, cancel: &CancelToken) -> Response<Self>;
    fn assoc(&mut self, key: Self::Key, value: Self::Value);
    fn ready(&self) -> bool;
}

pub enum Response<T: Task> {
    Value(T::Value),
    Continuation(Box<Promise<T>>),
    Error(T::Error)
}

#[derive(Debug)]
pub enum InternalError {
    SendError(String),
    NoResult
}

impl std::fmt::Display for InternalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InternalError::SendError(msg) => write!(f, "can't send a task to a worker: {msg}"),
            InternalError::NoResult => write!(f, "the kernel stopped without a result"),
        }
    }
}

pub enum Error<T: Task> {
    Jobs(Vec<T::Error>),
    Cycle(Vec<T::Key>),
    Internal(InternalError)
}

impl<T: Task> From<InternalError> for Error<T> {
    fn from(e: InternalError) -> Self {
        Error::Internal(e)
    }
}

impl<T: Task> fmt::Debug for Error<T> where T::Error: fmt::Debug, T::Key: fmt::Debug {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Jobs(e) => f.debug_tuple("Jobs").field(e).finish(),
            Error::Cycle(c) => f.debug_tuple("Cycle").field(c).finish(),
            Error::Internal(e) => f.debug_tuple("Internal").field(e).finish(),
        }
    }
}

pub struct Promise<T: Task> {
    pub root: T::Key,
    pub tasks: HashMap<T::Key, T>,
    pub inverse_deps: HashMap<T::Key, HashSet<T::Key>>
}

impl<T: Task> Promise<T> {
    pub fn new(root: T::Key, tasks: impl IntoIterator<Item=T>) -> Self {
        let mut inverse_deps: HashMap<T::Key, HashSet<T::Key>> = HashMap::new();
        let tasks: HashMap<T::Key, T> = tasks.into_iter().map(|t| (t.key(), t)).collect();
        for (key, task) in &tasks {
            for dep in task.dependencies() {
                inverse_deps.entry(dep).or_default().insert(*key);
            }
        }
        Promise { root, tasks, inverse_deps }
    }

    /// A cycle of tasks in this promise that wait for each other, if there is one. Each task in the cycle waits for the next, and the last waits for the first.
    pub fn cycle(&self) -> Option<Vec<T::Key>> {
        enum Mark { Active, Done }
        // Only tasks that aren't ready yet wait for anything.
        let waits_for = |key: &T::Key| -> Vec<T::Key> {
            match self.tasks.get(key) {
                Some(task) if !task.ready() => task.dependencies().filter(|d| self.tasks.contains_key(d)).collect(),
                _ => Vec::new(),
            }
        };

        // A single task can only wait for itself; this saves some work in loops of tail calls.
        if self.tasks.len() == 1 {
            let key = self.tasks.keys().next().unwrap();
            return waits_for(key).contains(key).then(|| vec![*key]);
        }

        let mut marks: HashMap<T::Key, Mark> = HashMap::new();
        for start in self.tasks.keys() {
            if marks.contains_key(start) {
                continue;
            }
            marks.insert(*start, Mark::Active);
            let mut path = vec![*start];
            let mut todo = vec![waits_for(start).into_iter()];
            while let Some(deps) = todo.last_mut() {
                match deps.next() {
                    Some(dep) => match marks.get(&dep) {
                        Some(Mark::Active) => {
                            let i = path.iter().position(|k| *k == dep).unwrap();
                            return Some(path.split_off(i));
                        }
                        Some(Mark::Done) => {}
                        None => {
                            marks.insert(dep, Mark::Active);
                            path.push(dep);
                            todo.push(waits_for(&dep).into_iter());
                        }
                    },
                    None => {
                        marks.insert(path.pop().unwrap(), Mark::Done);
                        todo.pop();
                    }
                }
            }
        }
        None
    }
}

pub trait Worker<T: Task> {
    fn submit(&self, frame_id: u64, task: T) -> Result<(), InternalError>;
    fn listen(&self) -> impl Iterator<Item=(u64, T::Key, Response<T>)>;
    fn cancel(&self);
}

<<cancel-token>>
}

Tasks are given a CancelToken when they are run. A task that takes a long time, like running an external program, should check it every now and then, and stop when it is cancelled. What a cancelled task returns doesn’t matter, as the response will be thrown away.

#![allow(unused)]
fn main() {
//| id: cancel-token
#[derive(Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);

impl CancelToken {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn cancel(&self) {
        self.0.store(true, Ordering::Relaxed);
    }

    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Relaxed)
    }
}
}

The kernel keeps a stack of frames, although it is not really a stack but a tree: every promise that is being evaluated lives in its own frame. A frame remembers where its result should go: the frame and key of the task that gave the continuation, or nothing if it is the top-level frame.

A task is run only once, so as soon as it is ready the kernel takes it out of its frame and hands it to the worker.

When a task that is not the root of its frame gives a continuation, the new frame gets that task as parent. When the root of a frame gives a continuation, the new frame replaces the old one and inherits its parent. This is the equivalent of tail-call optimisation: a chain of tail calls doesn’t build up frames.

Memoization

Most keys only need to be unique within a frame: they name intermediate steps in a computation. Some tasks however have an identity that is shared by the entire graph. In Brei these are the targets: if two rules depend on the same file, that file should be built only once. A task says it is one of these by returning true from memoize(), and its key must then be unique among all memoized tasks.

The kernel keeps a memo of memoized keys. When a memoized task is ready, the kernel looks up its key:

  • not present: the task is submitted, and the key is marked as pending, owned by this frame;
  • pending: the frame is added to the list of waiters, and nothing is submitted;
  • done (or failed): the outcome is delivered to the frame right away.

When the owner of a memoized key gets its final value (possibly after a continuation was resolved), the value is stored in the memo and delivered to all waiters. Because the owner needs to see that final value, a memoized root that gives a continuation doesn’t get tail-call optimisation: its frame stays alive until the continuation is done.

Only memoized keys are stored, so a loop of local tail calls still runs in constant memory. The size of the memo is bounded by the number of distinct memoized tasks, which in Brei is the number of targets. Computed values survive between calls to run, so a second run can reuse earlier results. Everything else (pending and failed entries) is removed at the end of a run, so a failed task will be tried again next time.

Failure

By default the kernel stops at the first error: the error is returned, and all tasks that are still running are cancelled. For a build system it is often more useful to do as much as possible, and only skip what depends on a failure, like make -k. A kernel created with .keep_going() does that:

  • a task that gives an error is marked as failed, and the error is stored;
  • a task that depends on a failed task fails as well, without being run. If that task is the root of its frame, the failure is passed on to the parent. The frame itself is kept, because other tasks in it may still be running and their results may be needed elsewhere, through the memo;
  • a failed memoized key is stored in the memo as failed, so that all frames waiting for it fail too.

The run ends when the top-level frame has a value, or when no work is left. If any task failed, the result is Error::Jobs with all errors, in the order they happened.

Cycles

A memoized task that, through its continuation, ends up waiting for itself would never finish. Every frame knows its enclosing memoized key: the closest memoized task on the way up its chain of parents, whose result the frame is helping to compute. If a frame owns or waits for key K, then its enclosing key waits for K. The kernel keeps these edges in a graph. Before adding a waiter, it checks whether K already (indirectly) waits for the enclosing key. If it does, adding the edge would close a loop, so the run stops with Error::Cycle. The cycle lists the keys in order: each waits for the next, and the last waits for the first.

Edges for a memoized key are removed once its value is known, so the graph only contains the computations that are still running.

Tasks within a single promise can also wait for each other in a loop. Those tasks would never be ready, so the kernel checks every promise it adds, with a depth-first search over the dependencies between its tasks. A loop is reported as Error::Cycle too. Tasks that are ready don’t wait for anything, so they can’t be part of a loop.

Implementation

Delivering a value may cause other values to be delivered: the root of a frame finishing will deliver its value to the parent, and a memoized key will deliver to its waiters. Instead of recursing, the kernel keeps a queue of deliveries (frame, key, outcome) that is drained after every response from the worker.

#![allow(unused)]
fn main() {
//| file: src/noodles/kernel.rs
use std::boxed::Box;
use std::collections::{HashMap, HashSet, VecDeque};
use super::task::{Task, Promise, Worker, InternalError, Error, Response};

struct Frame<T: Task> {
    parent: Option<(u64, T::Key)>,
    enclosing: Option<T::Key>,
    promise: Box<Promise<T>>,
}

enum State<T: Task> {
    Pending { owner: u64, waiters: Vec<u64> },
    Done(T::Value),
    Failed,
}

enum Outcome<T: Task> {
    Value(T::Value),
    Failed,
}

impl<T: Task> Clone for Outcome<T> {
    fn clone(&self) -> Self {
        match self {
            Outcome::Value(v) => Outcome::Value(v.clone()),
            Outcome::Failed => Outcome::Failed,
        }
    }
}

pub struct Kernel<T: Task> {
    keep_going: bool,
    frame_no: u64,
    frames: HashMap<u64, Frame<T>>,
    memo: HashMap<T::Key, State<T>>,
    waits_for: HashMap<T::Key, Vec<T::Key>>,
    queue: VecDeque<(u64, T::Key, Outcome<T>)>,
    errors: Vec<T::Error>,
}

impl<T: Task> Default for Kernel<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Task> Kernel<T> {
    pub fn new() -> Self {
        Self {
            keep_going: false,
            frame_no: 1,
            frames: HashMap::new(),
            memo: HashMap::new(),
            waits_for: HashMap::new(),
            queue: VecDeque::new(),
            errors: Vec::new(),
        }
    }

    /// Don't stop at the first error, but run everything that doesn't depend on a failed task.
    pub fn keep_going(mut self) -> Self {
        self.keep_going = true;
        self
    }

    /// Number of entries in the memo.
    #[cfg(test)]
    pub fn memo_count(&self) -> usize {
        self.memo.len()
    }

    /// Whether `frame_id` is responsible for computing the memoized `key`.
    fn owns(&self, frame_id: u64, key: T::Key) -> bool {
        matches!(self.memo.get(&key), Some(State::Pending { owner, .. }) if *owner == frame_id)
    }

    /// A path from `from` to `to` in the waits-for graph, if there is one.
    fn find_path(&self, from: T::Key, to: T::Key) -> Option<Vec<T::Key>> {
        let mut previous: HashMap<T::Key, T::Key> = HashMap::new();
        let mut seen = HashSet::from([from]);
        let mut todo = VecDeque::from([from]);
        while let Some(key) = todo.pop_front() {
            if key == to {
                let mut path = vec![to];
                while let Some(k) = previous.get(path.last().unwrap()) {
                    path.push(*k);
                }
                path.reverse();
                return Some(path);
            }
            for next in self.waits_for.get(&key).into_iter().flatten() {
                if seen.insert(*next) {
                    previous.insert(*next, key);
                    todo.push_back(*next);
                }
            }
        }
        None
    }

    fn add<W: Worker<T>>(&mut self, worker: &W, parent: Option<(u64, T::Key)>, mut promise: Box<Promise<T>>) -> Result<(), Error<T>> {
        let frame_id = self.frame_no;
        self.frame_no += 1;

        if let Some(cycle) = promise.cycle() {
            return Err(Error::Cycle(cycle));
        }

        let enclosing = match parent {
            Some((p, k)) if self.owns(p, k) => Some(k),
            Some((p, _)) => self.frames.get(&p).and_then(|f| f.enclosing),
            None => None,
        };

        let ready: Vec<T::Key> = promise.tasks.iter()
            .filter(|(_, task)| task.ready())
            .map(|(key, _)| *key)
            .collect();
        let ready: Vec<T> = ready.iter().map(|key| promise.tasks.remove(key).unwrap()).collect();

        self.frames.insert(frame_id, Frame { parent, enclosing, promise });
        for task in ready {
            self.schedule(worker, frame_id, task)?;
        }
        Ok(())
    }

    /// Submit a ready task, unless its result is (or will be) available from the memo.
    fn schedule<W: Worker<T>>(&mut self, worker: &W, frame_id: u64, task: T) -> Result<(), Error<T>> {
        if !task.memoize() {
            return Ok(worker.submit(frame_id, task)?);
        }

        let key = task.key();
        let enclosing = self.frames.get(&frame_id).and_then(|f| f.enclosing);
        match self.memo.get_mut(&key) {
            Some(State::Done(v)) => {
                let v = v.clone();
                self.queue.push_back((frame_id, key, Outcome::Value(v)));
            }
            Some(State::Failed) => {
                self.queue.push_back((frame_id, key, Outcome::Failed));
            }
            Some(State::Pending { waiters, .. }) => {
                waiters.push(frame_id);
                if let Some(outer) = enclosing {
                    if let Some(cycle) = self.find_path(key, outer) {
                        return Err(Error::Cycle(cycle));
                    }
                    self.waits_for.entry(outer).or_default().push(key);
                }
            }
            None => {
                self.memo.insert(key, State::Pending { owner: frame_id, waiters: Vec::new() });
                if let Some(outer) = enclosing {
                    self.waits_for.entry(outer).or_default().push(key);
                }
                worker.submit(frame_id, task)?;
            }
        }
        Ok(())
    }

    /// Handle a response from the worker.
    fn respond<W: Worker<T>>(&mut self, worker: &W, frame_id: u64, key: T::Key, response: Response<T>) -> Result<(), Error<T>> {
        // Results for frames that were already discarded are ignored, unless the memo still needs them.
        if !self.frames.contains_key(&frame_id) && !self.owns(frame_id, key) {
            return Ok(());
        }

        match response {
            Response::Value(v) => {
                self.queue.push_back((frame_id, key, Outcome::Value(v)));
            }
            Response::Continuation(c) => {
                let tail_call = !self.owns(frame_id, key)
                    && self.frames.get(&frame_id).is_some_and(|f| f.promise.root == key);
                if tail_call {
                    let parent = self.frames.remove(&frame_id).unwrap().parent;
                    self.add(worker, parent, c)?;
                } else {
                    self.add(worker, Some((frame_id, key)), c)?;
                }
            }
            Response::Error(e) => {
                if !self.keep_going {
                    return Err(Error::Jobs(vec![e]));
                }
                self.errors.push(e);
                self.queue.push_back((frame_id, key, Outcome::Failed));
            }
        }
        Ok(())
    }

    /// Deliver the outcome of `key` in frame `frame_id`. Returns the value of the top-level frame, once known.
    fn deliver<W: Worker<T>>(&mut self, worker: &W, frame_id: u64, key: T::Key, outcome: Outcome<T>) -> Result<Option<T::Value>, Error<T>> {
        if self.owns(frame_id, key) {
            let state = match &outcome {
                Outcome::Value(v) => State::Done(v.clone()),
                Outcome::Failed => State::Failed,
            };
            if let Some(State::Pending { waiters, .. }) = self.memo.insert(key, state) {
                for w in waiters {
                    self.queue.push_back((w, key, outcome.clone()));
                }
            }
            self.waits_for.remove(&key);
        }

        let Some(frame) = self.frames.get_mut(&frame_id) else { return Ok(None) };

        // The root of a frame reports to the parent; other tasks report to their own frame.
        if key == frame.promise.root {
            let parent = frame.parent;
            match outcome {
                Outcome::Value(v) => {
                    self.frames.remove(&frame_id);
                    match parent {
                        None => return Ok(Some(v)),
                        Some((p, pk)) => self.queue.push_back((p, pk, Outcome::Value(v))),
                    }
                }
                // The frame is kept, since other tasks in it may still be running.
                Outcome::Failed => {
                    if let Some((p, pk)) = parent {
                        self.queue.push_back((p, pk, Outcome::Failed));
                    }
                }
            }
            return Ok(None);
        }

        let mut ready = Vec::new();
        if let Some(dependents) = frame.promise.inverse_deps.get(&key) {
            for dep in dependents {
                match &outcome {
                    Outcome::Value(v) => {
                        let Some(task) = frame.promise.tasks.get_mut(dep) else { continue };
                        task.assoc(key, v.clone());
                        if task.ready() {
                            ready.push(frame.promise.tasks.remove(dep).unwrap());
                        }
                    }
                    // A task that depends on a failed task fails as well, without being run.
                    Outcome::Failed => {
                        if frame.promise.tasks.remove(dep).is_some() {
                            self.queue.push_back((frame_id, *dep, Outcome::Failed));
                        }
                    }
                }
            }
        }
        for task in ready {
            self.schedule(worker, frame_id, task)?;
        }
        Ok(None)
    }

    fn drain<W: Worker<T>>(&mut self, worker: &W) -> Result<Option<T::Value>, Error<T>> {
        while let Some((frame_id, key, outcome)) = self.queue.pop_front() {
            if let Some(result) = self.deliver(worker, frame_id, key, outcome)? {
                return Ok(Some(result));
            }
        }
        Ok(None)
    }

    fn run_frames<W: Worker<T>>(&mut self, worker: &W, promise: Box<Promise<T>>) -> Result<T::Value, Error<T>> {
        self.add(worker, None, promise)?;
        if let Some(result) = self.drain(worker)? {
            return Ok(result);
        }

        for (frame_id, key, response) in worker.listen() {
            self.respond(worker, frame_id, key, response)?;
            if let Some(result) = self.drain(worker)? {
                return Ok(result);
            }
        }

        Err(Error::Internal(InternalError::NoResult))
    }

    pub fn run<W: Worker<T>>(&mut self, worker: &W, promise: Box<Promise<T>>) -> Result<T::Value, Error<T>> {
        let result = self.run_frames(worker, promise);
        let errors = std::mem::take(&mut self.errors);
        let result = match result {
            Ok(_) | Err(Error::Internal(InternalError::NoResult)) if !errors.is_empty() => Err(Error::Jobs(errors)),
            result => result,
        };

        // Whatever is still running is no longer needed.
        worker.cancel();
        self.frames.clear();
        self.queue.clear();
        self.waits_for.clear();
        self.memo.retain(|_, state| matches!(state, State::Done(_)));
        result
    }
}
}

Single Worker

The single worker has a single sender-receiver pair. When tasks are submitted they are immediately executed and the result is push on the channel. Since all work happens inside submit, listen doesn’t need to block: if the channel is empty, nothing is left to do and the kernel can report that no result was found. Tasks are never running while the kernel is busy, so there is nothing to cancel: cancelling only throws away results that weren’t read yet.

#![allow(unused)]
fn main() {
//| file: src/noodles/single_worker.rs
use super::task::{Task, Response, Worker, InternalError, CancelToken};
use crossbeam_channel::{Sender, Receiver, unbounded};

pub struct SingleWorker<T: Task> {
    sender: Sender<(u64, T::Key, Response<T>)>,
    receiver: Receiver<(u64, T::Key, Response<T>)>,
    token: CancelToken,
}

impl<T: Task> SingleWorker<T> {
    pub fn new() -> Self {
        let (sender, receiver) = unbounded();
        SingleWorker{ sender, receiver, token: CancelToken::new() }
    }
}

impl<T: Task> Default for SingleWorker<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Task> Worker<T> for SingleWorker<T> {
    fn submit(&self, frame_id: u64, task: T) -> Result<(), InternalError> {
        let key = task.key();
        self.sender.send((frame_id, key, task.run(&self.token))).map_err(|e| InternalError::SendError(e.to_string()))
    }

    fn listen(&self) -> impl Iterator<Item=(u64, T::Key, Response<T>)> {
        self.receiver.try_iter()
    }

    fn cancel(&self) {
        while self.receiver.try_recv().is_ok() {}
    }
}
}

Worker Pool

The worker pool runs tasks on a fixed number of threads. Submitted tasks go into a shared channel, from which each thread takes the next task to run; responses come back through a second channel. Tasks, keys, values and errors now need to be Send, since they cross between threads.

The kernel needs to know when nothing is left to do, otherwise a graph that can’t complete would block forever. The pool counts the number of tasks in flight: submit increments it, and receiving a response decrements it. When the count is zero the iterator returned by listen ends, just like the single worker.

If a task panics, the thread catches the panic and sends it back with the response. The panic is then resumed on the thread that called listen, so a panicking task has the same effect as with the single worker.

Every task is sent along with the cancel token that was current when it was submitted. To cancel, the pool triggers that token and replaces it with a fresh one for later tasks. Tasks that are still waiting in the channel are skipped when a thread picks them up; tasks that are running are told to stop through the token. Cancelling waits until every task in flight has reported back, and throws the responses away (including panics), so the next run starts clean. A task that never looks at its token will hold this up until it finishes.

When the pool is dropped, all tasks are cancelled, and the threads stop.

#![allow(unused)]
fn main() {
//| file: src/noodles/worker_pool.rs
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::panic::{self, AssertUnwindSafe};
use std::thread::{self, JoinHandle};
use super::task::{Task, Response, Worker, InternalError, CancelToken};
use crossbeam_channel::{Sender, Receiver, unbounded};

enum Outcome<T: Task> {
    Response(Response<T>),
    Panic(Box<dyn Any + Send>),
    Skipped,
}

type Message<T> = (u64, <T as Task>::Key, Outcome<T>);

pub struct WorkerPool<T: Task> {
    tasks: Option<Sender<(u64, T, CancelToken)>>,
    results: Receiver<Message<T>>,
    in_flight: Cell<usize>,
    token: RefCell<CancelToken>,
    threads: Vec<JoinHandle<()>>,
}

impl<T> WorkerPool<T>
where T: Task + Send + 'static, T::Key: Send, T::Value: Send, T::Error: Send
{
    pub fn new(n_threads: usize) -> Self {
        let (task_sender, task_receiver) = unbounded::<(u64, T, CancelToken)>();
        let (result_sender, result_receiver) = unbounded::<Message<T>>();

        let threads = (0..n_threads.max(1)).map(|_| {
            let tasks = task_receiver.clone();
            let results = result_sender.clone();
            thread::spawn(move || {
                for (frame_id, task, token) in tasks.iter() {
                    let key = task.key();
                    let outcome = if token.is_cancelled() {
                        Outcome::Skipped
                    } else {
                        match panic::catch_unwind(AssertUnwindSafe(|| task.run(&token))) {
                            Ok(response) => Outcome::Response(response),
                            Err(payload) => Outcome::Panic(payload),
                        }
                    };
                    if results.send((frame_id, key, outcome)).is_err() {
                        break;
                    }
                }
            })
        }).collect();

        WorkerPool {
            tasks: Some(task_sender),
            results: result_receiver,
            in_flight: Cell::new(0),
            token: RefCell::new(CancelToken::new()),
            threads,
        }
    }

    /// A pool with as many threads as the machine can run in parallel.
    pub fn with_available_parallelism() -> Self {
        Self::new(thread::available_parallelism().map_or(1, |n| n.get()))
    }
}

impl<T> Worker<T> for WorkerPool<T>
where T: Task + Send + 'static, T::Key: Send, T::Value: Send, T::Error: Send
{
    fn submit(&self, frame_id: u64, task: T) -> Result<(), InternalError> {
        let sender = self.tasks.as_ref().ok_or(InternalError::SendError("worker pool is shut down".into()))?;
        let token = self.token.borrow().clone();
        sender.send((frame_id, task, token)).map_err(|e| InternalError::SendError(e.to_string()))?;
        self.in_flight.set(self.in_flight.get() + 1);
        Ok(())
    }

    fn listen(&self) -> impl Iterator<Item=(u64, T::Key, Response<T>)> {
        std::iter::from_fn(move || loop {
            if self.in_flight.get() == 0 {
                return None;
            }
            let (frame_id, key, outcome) = self.results.recv().ok()?;
            self.in_flight.set(self.in_flight.get() - 1);
            match outcome {
                Outcome::Response(response) => return Some((frame_id, key, response)),
                Outcome::Panic(payload) => panic::resume_unwind(payload),
                Outcome::Skipped => continue,
            }
        })
    }

    fn cancel(&self) {
        self.token.replace(CancelToken::new()).cancel();
        while self.in_flight.get() > 0 && self.results.recv().is_ok() {
            self.in_flight.set(self.in_flight.get() - 1);
        }
    }
}

impl<T: Task> Drop for WorkerPool<T> {
    fn drop(&mut self) {
        self.token.borrow().cancel();
        self.tasks.take();
        for thread in self.threads.drain(..) {
            let _ = thread.join();
        }
    }
}
}

Mock tasks

To test the engine, we have a mock task that computes on integers. Each task has a u64 key, a list of dependencies and a function that takes the values of its dependencies (in order) and gives a Response. Since the function may return a continuation, we can have recursion. Tasks are not memoized, unless built with .memoized(). Tasks that want to look at the cancel token are built with Mock::cancellable.

#![allow(unused)]
fn main() {
//| file: src/noodles/mock.rs
use std::collections::HashMap;
use std::sync::{Arc, Barrier};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use super::task::{Task, Promise, Response, Error, InternalError, CancelToken};
use super::kernel::Kernel;
use super::single_worker::SingleWorker;
use super::worker_pool::WorkerPool;

type Func = Arc<dyn Fn(&[i64], &CancelToken) -> Response<Mock> + Send + Sync>;

struct Mock {
    key: u64,
    deps: Vec<u64>,
    args: HashMap<u64, i64>,
    memoize: bool,
    func: Func,
}

impl Mock {
    fn new(key: u64, deps: &[u64], func: impl Fn(&[i64]) -> Response<Mock> + Send + Sync + 'static) -> Self {
        Self::cancellable(key, deps, move |x, _| func(x))
    }

    fn cancellable(key: u64, deps: &[u64], func: impl Fn(&[i64], &CancelToken) -> Response<Mock> + Send + Sync + 'static) -> Self {
        Mock { key, deps: deps.to_vec(), args: HashMap::new(), memoize: false, func: Arc::new(func) }
    }

    fn memoized(mut self) -> Self {
        self.memoize = true;
        self
    }
}

impl Task for Mock {
    type Value = i64;
    type Key = u64;
    type Error = String;

    fn key(&self) -> u64 { self.key }

    fn dependencies(&self) -> impl Iterator<Item=u64> {
        self.deps.iter().copied()
    }

    fn memoize(&self) -> bool { self.memoize }

    fn run(self, cancel: &CancelToken) -> Response<Self> {
        let args: Vec<i64> = self.deps.iter().map(|k| self.args[k]).collect();
        (self.func)(&args, cancel)
    }

    fn assoc(&mut self, key: u64, value: i64) {
        self.args.insert(key, value);
    }

    fn ready(&self) -> bool {
        self.deps.iter().all(|k| self.args.contains_key(k))
    }
}

<<mock-helpers>>
<<mock-recursion>>
<<mock-memo>>

#[cfg(test)]
mod tests {
    use super::*;

    fn eval(p: Box<Promise<Mock>>) -> Result<i64, Error<Mock>> {
        let worker = SingleWorker::new();
        let mut kernel = Kernel::new();
        kernel.run(&worker, p)
    }

    <<mock-tests>>
}
}

Some shorthands for building promises and tasks.

#![allow(unused)]
fn main() {
//| id: mock-helpers
fn promise(root: u64, tasks: Vec<Mock>) -> Box<Promise<Mock>> {
    Box::new(Promise::new(root, tasks))
}

fn constant(key: u64, value: i64) -> Mock {
    Mock::new(key, &[], move |_| Response::Value(value))
}

fn binop(key: u64, a: u64, b: u64, f: fn(i64, i64) -> i64) -> Mock {
    Mock::new(key, &[a, b], move |x| Response::Value(f(x[0], x[1])))
}
}

Primitive computations

A diamond shaped graph: (2 + 3) * (2 * 3).

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn diamond() {
    let p = promise(5, vec![
        constant(1, 2),
        constant(2, 3),
        binop(3, 1, 2, |a, b| a + b),
        binop(4, 1, 2, |a, b| a * b),
        binop(5, 3, 4, |a, b| a * b),
    ]);
    assert_eq!(eval(p).unwrap(), 30);
}
}

Errors are propagated to the caller.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn error() {
    let p = promise(3, vec![
        constant(1, 1),
        constant(2, 0),
        Mock::new(3, &[1, 2], |x| if x[1] == 0 {
            Response::Error("division by zero".into())
        } else {
            Response::Value(x[0] / x[1])
        }),
    ]);
    assert!(matches!(eval(p), Err(Error::Jobs(e)) if e == ["division by zero"]));
}
}

If the graph can never complete, because the root depends on a task that doesn’t exist, the single worker runs dry and we get NoResult.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn missing_dependency() {
    let p = promise(2, vec![binop(2, 1, 3, |a, b| a + b), constant(1, 1)]);
    assert!(matches!(eval(p), Err(Error::Internal(InternalError::NoResult))));
}
}

Recursion

The factorial is computed by having factorial(n) return a continuation: a promise to compute n * factorial(n - 1). The task for factorial(n - 1) is not the root of the new frame, so its result is fed into the multiplication. Note that every frame reuses the keys 1 and 2.

#![allow(unused)]
fn main() {
//| id: mock-recursion
fn factorial(key: u64, n: i64) -> Mock {
    Mock::new(key, &[], move |_| {
        if n <= 1 {
            return Response::Value(1);
        }
        Response::Continuation(promise(2, vec![
            factorial(1, n - 1),
            Mock::new(2, &[1], move |x| Response::Value(n * x[0])),
        ]))
    })
}
}

The tail-recursive version passes an accumulator. Here the continuation consists of only a root task, so the kernel replaces frames instead of nesting them.

#![allow(unused)]
fn main() {
//| id: mock-recursion
fn factorial_acc(key: u64, n: i64, acc: i64) -> Mock {
    Mock::new(key, &[], move |_| {
        if n <= 1 {
            return Response::Value(acc);
        }
        Response::Continuation(promise(1, vec![factorial_acc(1, n - 1, acc * n)]))
    })
}
}

Fibonacci has two recursive calls in each continuation.

#![allow(unused)]
fn main() {
//| id: mock-recursion
fn fibonacci(key: u64, n: i64) -> Mock {
    Mock::new(key, &[], move |_| {
        if n < 2 {
            return Response::Value(n);
        }
        Response::Continuation(promise(3, vec![
            fibonacci(1, n - 1),
            fibonacci(2, n - 2),
            binop(3, 1, 2, |a, b| a + b),
        ]))
    })
}

fn sum_to(key: u64, n: i64) -> Mock {
    Mock::new(key, &[], move |_| {
        if n == 0 {
            return Response::Value(0);
        }
        Response::Continuation(promise(2, vec![
            sum_to(1, n - 1),
            Mock::new(2, &[1], move |x| Response::Value(n + x[0])),
        ]))
    })
}
}
#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn recursion() {
    for (n, f) in [(0, 1), (1, 1), (5, 120), (20, 2432902008176640000)] {
        assert_eq!(eval(promise(0, vec![factorial(0, n)])).unwrap(), f);
        assert_eq!(eval(promise(0, vec![factorial_acc(0, n, 1)])).unwrap(), f);
    }
    assert_eq!(eval(promise(0, vec![fibonacci(0, 20)])).unwrap(), 6765);
}
}

Recursion doesn’t use the Rust stack, so we can go very deep without overflowing.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn deep_recursion() {
    let n = 100_000;
    assert_eq!(eval(promise(0, vec![sum_to(0, n)])).unwrap(), n * (n + 1) / 2);
}
}

Memoization

Fibonacci again, but now with memoized tasks: fibonacci_memo(n) has key n. The addition is a local task, so it gets a key that doesn’t clash. A counter keeps track of how many times a Fibonacci task was actually run.

#![allow(unused)]
fn main() {
//| id: mock-memo
const SUM: u64 = u64::MAX;

fn fibonacci_memo(n: u64, runs: Arc<AtomicUsize>) -> Mock {
    Mock::new(n, &[], move |_| {
        runs.fetch_add(1, Ordering::Relaxed);
        if n < 2 {
            return Response::Value(n as i64);
        }
        Response::Continuation(promise(SUM, vec![
            fibonacci_memo(n - 1, runs.clone()),
            fibonacci_memo(n - 2, runs.clone()),
            binop(SUM, n - 1, n - 2, |a, b| a + b),
        ]))
    }).memoized()
}

fn sum_acc(key: u64, n: i64, acc: i64) -> Mock {
    Mock::new(key, &[], move |_| {
        if n == 0 {
            return Response::Value(acc);
        }
        Response::Continuation(promise(1, vec![sum_acc(1, n - 1, acc + n)]))
    })
}
}

Each Fibonacci number is computed exactly once. Running again with the same kernel takes the answer from the memo.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn memoization() {
    let runs = Arc::new(AtomicUsize::new(0));
    let worker = SingleWorker::new();
    let mut kernel = Kernel::new();
    let fib50 = 12_586_269_025;

    assert_eq!(kernel.run(&worker, promise(50, vec![fibonacci_memo(50, runs.clone())])).unwrap(), fib50);
    assert_eq!(runs.load(Ordering::Relaxed), 51);
    assert_eq!(kernel.memo_count(), 51);

    assert_eq!(kernel.run(&worker, promise(50, vec![fibonacci_memo(50, runs.clone())])).unwrap(), fib50);
    assert_eq!(runs.load(Ordering::Relaxed), 51);
}
}

A loop of local tail calls leaves nothing behind.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn local_loop() {
    let worker = SingleWorker::new();
    let mut kernel = Kernel::new();
    let n = 1_000_000;
    assert_eq!(kernel.run(&worker, promise(0, vec![sum_acc(0, n, 0)])).unwrap(), n * (n + 1) / 2);
    assert_eq!(kernel.memo_count(), 0);
}
}

A memoized task that waits for itself is a cycle.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn cycle() {
    let looping = Mock::new(1, &[], |_| Response::Continuation(promise(2, vec![
        Mock::new(1, &[], |_| Response::Value(0)).memoized(),
        Mock::new(2, &[1], |x| Response::Value(x[0])),
    ]))).memoized();
    assert!(matches!(eval(promise(1, vec![looping])), Err(Error::Cycle(c)) if c == [1]));
}
}

A cycle can also go through several memoized tasks: here task 1 needs 2, which needs 1 again.

#![allow(unused)]
fn main() {
//| id: mock-memo
fn needs(key: u64, dep: u64) -> Mock {
    Mock::new(key, &[], move |_| Response::Continuation(promise(SUM, vec![
        needs(dep, key),
        Mock::new(SUM, &[dep], |x| Response::Value(x[0])),
    ]))).memoized()
}
}
#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn indirect_cycle() {
    assert!(matches!(eval(promise(1, vec![needs(1, 2)])), Err(Error::Cycle(c)) if c == [1, 2]));
}
}

Tasks in one promise that wait for each other are a cycle too, whether they are memoized or not. The cycle is found when the promise is added, also when it comes from a continuation. Tasks outside the cycle that depend on it are not part of it.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn local_cycle() {
    let looping = || vec![
        Mock::new(1, &[2], |x| Response::Value(x[0])),
        Mock::new(2, &[3], |x| Response::Value(x[0])),
        Mock::new(3, &[2], |x| Response::Value(x[0])).memoized(),
        Mock::new(4, &[4], |x| Response::Value(x[0])),
    ];
    let is_cycle = |c: &[u64]| c == [2, 3] || c == [3, 2] || c == [4];
    assert!(matches!(eval(promise(1, looping())), Err(Error::Cycle(c)) if is_cycle(&c)));

    let continued = Mock::new(0, &[], move |_| Response::Continuation(promise(1, looping())));
    assert!(matches!(eval_pool(promise(0, vec![continued])), Err(Error::Cycle(c)) if is_cycle(&c)));

    let add = |key, a, b| binop(key, a, b, |x, y| x + y);
    let diamond = vec![constant(1, 1), add(2, 1, 1), add(3, 1, 2), add(4, 2, 3)];
    assert_eq!(eval(promise(4, diamond)).unwrap(), 5);
}
}

Worker pool

The same computations give the same answers on a worker pool. Memoization still runs every Fibonacci task only once, even though tasks now run concurrently: the memo is managed by the kernel, which runs on a single thread.

#![allow(unused)]
fn main() {
//| id: mock-tests
fn eval_pool(p: Box<Promise<Mock>>) -> Result<i64, Error<Mock>> {
    let worker = WorkerPool::new(4);
    let mut kernel = Kernel::new();
    kernel.run(&worker, p)
}

#[test]
fn pool_computations() {
    let p = promise(3, vec![constant(1, 2), constant(2, 3), binop(3, 1, 2, |a, b| a * b)]);
    assert_eq!(eval_pool(p).unwrap(), 6);
    assert_eq!(eval_pool(promise(0, vec![factorial(0, 20)])).unwrap(), 2432902008176640000);
    assert_eq!(eval_pool(promise(0, vec![factorial_acc(0, 20, 1)])).unwrap(), 2432902008176640000);
    assert_eq!(eval_pool(promise(0, vec![fibonacci(0, 20)])).unwrap(), 6765);
    assert_eq!(eval_pool(promise(0, vec![sum_to(0, 10_000)])).unwrap(), 50_005_000);
}

#[test]
fn pool_memoization() {
    let runs = Arc::new(AtomicUsize::new(0));
    assert_eq!(eval_pool(promise(50, vec![fibonacci_memo(50, runs.clone())])).unwrap(), 12_586_269_025);
    assert_eq!(runs.load(Ordering::Relaxed), 51);
}

#[test]
fn pool_error() {
    let p = promise(2, vec![
        Mock::new(1, &[], |_| Response::Error("failed".into())),
        Mock::new(2, &[1], |x| Response::Value(x[0])),
    ]);
    assert!(matches!(eval_pool(p), Err(Error::Jobs(e)) if e == ["failed"]));
    assert!(matches!(eval_pool(promise(2, vec![binop(2, 1, 3, |a, b| a + b)])), Err(Error::Internal(InternalError::NoResult))));
}
}

To show that tasks really run in parallel, four tasks wait on a barrier for four threads. This can only finish if all four run at the same time; on the single worker it would block forever.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn pool_parallel() {
    let barrier = Arc::new(std::sync::Barrier::new(4));
    let mut tasks: Vec<Mock> = (1..=4).map(|k| {
        let barrier = barrier.clone();
        Mock::new(k, &[], move |_| {
            barrier.wait();
            Response::Value(k as i64)
        })
    }).collect();
    tasks.push(Mock::new(5, &[1, 2, 3, 4], |x| Response::Value(x.iter().sum())));
    assert_eq!(eval_pool(promise(5, tasks)).unwrap(), 10);
}
}

A panic in a task is passed on to the caller.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
#[should_panic(expected = "boom")]
fn pool_panic() {
    let _ = eval_pool(promise(1, vec![Mock::new(1, &[], |_| panic!("boom"))]));
}
}

Failure and cancellation

When a task fails, the kernel stops by default. Here an error happens next to a memoized Fibonacci computation. When we keep going, the Fibonacci numbers are still computed and end up in the memo, even though the run as a whole fails. Without keeping going, the run stops before that.

#![allow(unused)]
fn main() {
//| id: mock-tests
fn failing_next_to_fibonacci() -> Box<Promise<Mock>> {
    promise(SUM, vec![
        Mock::new(100, &[], |_| Response::Error("failed".into())),
        fibonacci_memo(10, Arc::new(AtomicUsize::new(0))),
        binop(SUM, 100, 10, |a, b| a + b),
    ])
}

#[test]
fn keep_going() {
    let worker = SingleWorker::new();
    let mut kernel = Kernel::new().keep_going();
    assert!(matches!(kernel.run(&worker, failing_next_to_fibonacci()), Err(Error::Jobs(e)) if e == ["failed"]));
    assert_eq!(kernel.memo_count(), 11);

    let mut kernel = Kernel::new();
    assert!(matches!(kernel.run(&worker, failing_next_to_fibonacci()), Err(Error::Jobs(e)) if e == ["failed"]));
    assert!(kernel.memo_count() < 11);
}
}

All errors are collected, also when they happen deep down in a continuation.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn keep_going_collects_errors() {
    let deep_error = Mock::new(2, &[], |_| Response::Continuation(promise(1, vec![
        Mock::new(1, &[], |_| Response::Error("deep".into())),
    ])));
    let p = promise(3, vec![
        Mock::new(1, &[], |_| Response::Error("shallow".into())),
        deep_error,
        binop(3, 1, 2, |a, b| a + b),
    ]);
    let worker = SingleWorker::new();
    let mut kernel = Kernel::new().keep_going();
    let Err(Error::Jobs(mut errors)) = kernel.run(&worker, p) else { panic!("expected errors") };
    errors.sort();
    assert_eq!(errors, ["deep", "shallow"]);
}
}

On the worker pool, an error cancels the tasks that are still running. Task 2 would run for ten seconds, unless it notices it is cancelled. The barrier makes sure that task 2 is already running when task 1 fails.

#![allow(unused)]
fn main() {
//| id: mock-tests
#[test]
fn pool_cancel() {
    let barrier = Arc::new(Barrier::new(2));
    let cancelled = Arc::new(AtomicBool::new(false));
    let p = {
        let (b1, b2) = (barrier.clone(), barrier.clone());
        let cancelled = cancelled.clone();
        promise(3, vec![
            Mock::new(1, &[], move |_| {
                b1.wait();
                Response::Error("failed".into())
            }),
            Mock::cancellable(2, &[], move |_, token| {
                b2.wait();
                let start = Instant::now();
                while start.elapsed() < Duration::from_secs(10) {
                    if token.is_cancelled() {
                        cancelled.store(true, Ordering::Relaxed);
                        break;
                    }
                    thread::sleep(Duration::from_millis(1));
                }
                Response::Value(0)
            }),
            binop(3, 1, 2, |a, b| a + b),
        ])
    };

    let start = Instant::now();
    assert!(matches!(eval_pool(p), Err(Error::Jobs(e)) if e == ["failed"]));
    assert!(cancelled.load(Ordering::Relaxed));
    assert!(start.elapsed() < Duration::from_secs(5));
}
}

Brei

This chapter builds Brei on top of the engine: the tasks that Brei runs, what they produce, and how they find each other. The code lives in the tasks module.

#![allow(unused)]
fn main() {
//| file: src/tasks/mod.rs
//! Brei tasks, running on the engine in `noodles`.

mod target;
mod rule;
mod db;
mod template;
mod history;
mod program;
mod exec;
mod group;
mod job;

#[cfg(test)]
mod tests;

pub use target::{Target, TargetId, Key};
pub use rule::{Runner, default_runners};
pub use db::TaskDb;
pub use template::RuleTemplate;
pub use history::HISTORY_FILE;
pub use group::kill_all;
pub use program::{Program, Call, Argument, Join, resolve};
pub use job::{Job, build_all};

#[cfg(test)]
pub(crate) use {rule::{Rule, RuleError, Value, Failure}, job::build};
}

Targets

Everything a task creates or requires is a target. There are three kinds of target:

  • a path, a file on disk, written as the path itself: data/output.csv;
  • a phony target, a name for a task that doesn’t create a file, written with a hash: #all;
  • a variable, a value computed by a task. A variable has a type, which is one of:
    • a scalar, a single string, written as var(name). It can be used in templates as ${name};
    • a list of strings, written as listvar(name). The output of a task with listvar(name) as stdout is split into lines. A list can’t be used in a template directly; instead splice(name) inserts its elements into a list of dependencies or call arguments.

Scalar and list variables share the same name space: var(x) and listvar(x) refer to the same variable, used in two incompatible ways. That is an error, which is caught when targets are interned.

#![allow(unused)]
fn main() {
//| file: src/tasks/target.rs
use std::collections::HashMap;
use std::fmt;
use std::path::{Component, Path, PathBuf};
use std::str::FromStr;
use std::sync::RwLock;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VarType {
    Scalar,
    List,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Target {
    Path(PathBuf),
    Phony(String),
    Variable(String, VarType),
}

<<target-parse>>
<<target-intern>>
<<target-key>>

#[cfg(test)]
mod tests {
    use super::*;

    <<target-tests>>
}
}

Parsing

Targets are written as strings in a Brei program. A string that doesn’t look like any of the other kinds is a path. Variable names can’t contain white space or parentheses.

Paths are normalized a little bit, so that ./data.csv and data.csv are the same target. We only remove . components; .. is left alone, since a/../b is not the same as b when a is a symbolic link. The separator is always /, also on Windows (which accepts both), so that targets, and the history, look the same on every platform.

#![allow(unused)]
fn main() {
//| id: target-parse
pub(super) fn wrapped<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
    let name = s.strip_prefix(prefix)?.strip_prefix('(')?.strip_suffix(')')?;
    let valid = !name.is_empty() && !name.contains(|c: char| c.is_whitespace() || c == '(' || c == ')');
    valid.then_some(name)
}

fn normalize(path: &Path) -> PathBuf {
    let mut normal = String::new();
    let mut separate = false;
    for component in path.components() {
        let part = component.as_os_str().to_string_lossy();
        match component {
            Component::CurDir => continue,
            Component::Prefix(_) => normal.push_str(&part),
            Component::RootDir => normal.push('/'),
            Component::ParentDir | Component::Normal(_) => {
                if separate {
                    normal.push('/');
                }
                normal.push_str(&part);
            }
        }
        separate = matches!(component, Component::ParentDir | Component::Normal(_));
    }
    if normal.is_empty() { PathBuf::from(".") } else { PathBuf::from(normal) }
}

impl Target {
    /// A path target, normalized.
    pub fn path(path: impl AsRef<Path>) -> Self {
        Target::Path(normalize(path.as_ref()))
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct EmptyTarget;

impl FromStr for Target {
    type Err = EmptyTarget;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(EmptyTarget);
        }
        Ok(if let Some(name) = s.strip_prefix('#') {
            Target::Phony(name.to_string())
        } else if let Some(name) = wrapped(s, "var") {
            Target::Variable(name.to_string(), VarType::Scalar)
        } else if let Some(name) = wrapped(s, "listvar") {
            Target::Variable(name.to_string(), VarType::List)
        } else {
            Target::path(s)
        })
    }
}

impl fmt::Display for Target {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Target::Path(p) => write!(f, "{}", p.display()),
            Target::Phony(name) => write!(f, "#{}", name),
            Target::Variable(name, VarType::Scalar) => write!(f, "var({})", name),
            Target::Variable(name, VarType::List) => write!(f, "listvar({})", name),
        }
    }
}
}
#![allow(unused)]
fn main() {
//| id: target-tests
fn target(s: &str) -> Target {
    s.parse().unwrap()
}

#[test]
fn parse() {
    assert_eq!(target("data/output.csv"), Target::Path("data/output.csv".into()));
    assert_eq!(target("#all"), Target::Phony("all".into()));
    assert_eq!(target("var(name)"), Target::Variable("name".into(), VarType::Scalar));
    assert_eq!(target("listvar(files)"), Target::Variable("files".into(), VarType::List));
    assert_eq!("".parse::<Target>(), Err(EmptyTarget));
}

#[test]
fn parse_edge_cases() {
    // not a valid variable name, so these are paths
    assert_eq!(target("var(a b)"), Target::Path("var(a b)".into()));
    assert_eq!(target("var()"), Target::Path("var()".into()));
    assert_eq!(target("variable(x)"), Target::Path("variable(x)".into()));
    // normalization
    assert_eq!(target("./data.csv"), target("data.csv"));
    assert_eq!(target("data//output.csv"), target("data/output.csv"));
    assert_eq!(target("data/./output.csv"), target("data/output.csv"));
    assert_ne!(target("a/../b"), target("b"));
    assert_eq!(target("./"), Target::Path(".".into()));
}

#[test]
fn display_round_trip() {
    for s in ["data/output.csv", "#all", "var(name)", "listvar(files)"] {
        assert_eq!(target(s).to_string(), s);
    }
}
}

Interning

The engine wants keys that are Copy, and they get copied a lot: into the memo, the waits-for graph and the delivery queue. A Target holds a string, so it isn’t Copy. Instead, every target gets a number, a TargetId, from a table that is shared by all tasks. Looking up the same target twice gives the same id.

New targets can appear while the workflow is running, for instance when a list variable is spliced into a list of dependencies. Those tasks run on worker threads, so the table is behind a RwLock. Most of the time we are only reading.

The table indexes targets by their name, which for a variable leaves out the type. So var(x) and listvar(x) get the same id, and when a variable comes in with a different type than the one that is already in the table, intern gives a TypeMismatch. The type that is stored is the one that was seen first.

#![allow(unused)]
fn main() {
//| id: target-intern
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TargetId(u32);

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Name {
    Path(PathBuf),
    Phony(String),
    Variable(String),
}

impl From<&Target> for Name {
    fn from(target: &Target) -> Self {
        match target {
            Target::Path(p) => Name::Path(p.clone()),
            Target::Phony(n) => Name::Phony(n.clone()),
            Target::Variable(n, _) => Name::Variable(n.clone()),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct TypeMismatch {
    pub name: String,
    pub known: VarType,
    pub found: VarType,
}

impl fmt::Display for TypeMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.known {
            VarType::List => write!(f, "`{}` is a list variable, it can only be used as `splice({})`", self.name, self.name),
            VarType::Scalar => write!(f, "`{}` is not a list variable, use `${{{}}}` instead", self.name, self.name),
        }
    }
}

#[derive(Default)]
struct Table {
    targets: Vec<Target>,
    index: HashMap<Name, TargetId>,
}

impl Table {
    /// Check that `target` agrees with the target that is known under `id`.
    fn check(&self, id: TargetId, target: &Target) -> Result<TargetId, TypeMismatch> {
        match (&self.targets[id.0 as usize], target) {
            (Target::Variable(name, known), Target::Variable(_, found)) if known != found =>
                Err(TypeMismatch { name: name.clone(), known: *known, found: *found }),
            _ => Ok(id),
        }
    }
}

#[derive(Default)]
pub struct Targets {
    table: RwLock<Table>,
}

impl Targets {
    pub fn new() -> Self {
        Self::default()
    }

    /// The id of `target`, adding it to the table if it is new.
    pub fn intern(&self, target: &Target) -> Result<TargetId, TypeMismatch> {
        let name = Name::from(target);
        {
            let table = self.table.read().unwrap();
            if let Some(id) = table.index.get(&name) {
                return table.check(*id, target);
            }
        }
        let mut table = self.table.write().unwrap();
        // Another thread may have added it in the mean time.
        if let Some(id) = table.index.get(&name) {
            return table.check(*id, target);
        }
        let id = TargetId(table.targets.len().try_into().expect("too many targets"));
        table.targets.push(target.clone());
        table.index.insert(name, id);
        Ok(id)
    }

    /// The id of `target`, if it is known (with the same type).
    pub fn lookup(&self, target: &Target) -> Option<TargetId> {
        let table = self.table.read().unwrap();
        let id = *table.index.get(&Name::from(target))?;
        table.check(id, target).ok()
    }

    pub fn get(&self, id: TargetId) -> Target {
        self.table.read().unwrap().targets[id.0 as usize].clone()
    }

    #[cfg(test)]
    pub fn len(&self) -> usize {
        self.table.read().unwrap().targets.len()
    }
}
}
#![allow(unused)]
fn main() {
//| id: target-tests
#[test]
fn interning() {
    let targets = Targets::new();
    let a = targets.intern(&target("a.txt")).unwrap();
    let b = targets.intern(&target("#b")).unwrap();
    assert_ne!(a, b);
    assert_eq!(targets.intern(&target("./a.txt")), Ok(a));
    assert_eq!(targets.lookup(&target("var(c)")), None);
    assert_eq!(targets.get(b), target("#b"));
    assert_eq!(targets.len(), 2);
}

#[test]
fn interning_from_threads() {
    let targets = std::sync::Arc::new(Targets::new());
    let handles: Vec<_> = (0..8).map(|_| {
        let targets = targets.clone();
        std::thread::spawn(move || {
            (0..100).map(|i| targets.intern(&target(&format!("file{i}.txt"))).unwrap()).collect::<Vec<_>>()
        })
    }).collect();
    let ids: Vec<Vec<TargetId>> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    assert!(ids.iter().all(|v| *v == ids[0]));
    assert_eq!(targets.len(), 100);
}

#[test]
fn variable_types() {
    let targets = Targets::new();
    let files = targets.intern(&target("listvar(files)")).unwrap();
    assert_eq!(targets.intern(&target("listvar(files)")), Ok(files));
    assert_eq!(targets.lookup(&target("var(files)")), None);

    let err = targets.intern(&target("var(files)")).unwrap_err();
    assert_eq!(err, TypeMismatch { name: "files".into(), known: VarType::List, found: VarType::Scalar });
    assert_eq!(err.to_string(), "`files` is a list variable, it can only be used as `splice(files)`");

    targets.intern(&target("var(name)")).unwrap();
    let err = targets.intern(&target("listvar(name)")).unwrap_err();
    assert_eq!(err.to_string(), "`name` is not a list variable, use `${name}` instead");
    assert_eq!(targets.len(), 2);
}
}

Engine keys

Not every task in the engine is a target. Running a Brei task takes a few steps: first its dependencies need to be there, then we check whether the targets are out of date, and only then do we run the script. These intermediate steps live inside a single continuation, and get a local key. Targets are global: their tasks are memoized, so that every target is built at most once, and they can be shared between frames. Local keys are only unique within their frame.

#![allow(unused)]
fn main() {
//| id: target-key
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
    Target(TargetId),
    Local(u32),
}

impl Key {
    /// Whether tasks with this key should be memoized by the engine.
    pub fn is_global(&self) -> bool {
        matches!(self, Key::Target(_))
    }
}

impl From<TargetId> for Key {
    fn from(id: TargetId) -> Self {
        Key::Target(id)
    }
}
}
#![allow(unused)]
fn main() {
//| id: target-tests
#[test]
fn keys() {
    let targets = Targets::new();
    let key: Key = targets.intern(&target("a.txt")).unwrap().into();
    assert!(key.is_global());
    assert!(!Key::Local(0).is_global());
}
}

Rules

A rule says how to create a set of targets from a set of dependencies. This is what the Python version calls a Task; here that name is taken by the engine. A rule has:

  • creates, the targets it creates, and requires, the targets it needs;
  • optionally a name, which makes the rule available as the phony target #name;
  • something to run: a script, optionally with a runner, or a path to a script file, which needs a runner. Without a runner, every line of the script is a command. With a runner, the script is written to a file, and the runner is called with that file;
  • optionally stdin and stdout, which redirect standard input and output to a file or variable. Standard input can only come from a file or a scalar variable; standard output can go to a file, a scalar variable or a list variable;
  • a description, used for logging, and force, to always run the rule.

The targets in stdout and name, and the dependencies in stdin and path, are added to creates and requires when the rule is added to the database. A rule that doesn’t create any file is always run, so that is the case for rules that only have phony or variable targets. A rule that writes its standard output to a variable is always run as well, even when it also creates files: the value of a variable only lives in memory, so the rule has to run to give it.

#![allow(unused)]
fn main() {
//| file: src/tasks/rule.rs
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::PathBuf;
use serde::Deserialize;
use super::target::{Target, VarType, TypeMismatch};

<<rule-value>>
<<rule-failure>>
<<rule-runner>>
<<rule-rule>>
}

Values

The engine passes values from one task to the next. For a file or phony target there’s nothing to pass: whatever a rule produced is on disk. Variables carry a string or a list of strings.

#![allow(unused)]
fn main() {
//| id: rule-value
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Value {
    Nothing,
    Scalar(String),
    List(Vec<String>),
}
}

Failures

When a rule fails, the engine collects the error. These need to be Clone, so we store messages instead of the original errors. A failure in running a rule is wrapped in Failure::Rule, with the note that identifies the rule in the log.

#![allow(unused)]
fn main() {
//| id: rule-failure
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Failure {
    Missing(Target),
    UnknownRunner(String),
    InvalidScript(String),
    Template(String),
    Io(String),
    Command { command: String, code: Option<i32> },
    NotAchieved(Vec<Target>),
    Cancelled,
    Rule(String, Box<Failure>),
}

impl From<std::io::Error> for Failure {
    fn from(e: std::io::Error) -> Self {
        Failure::Io(e.to_string())
    }
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Failure::Missing(t) => write!(f, "missing dependency: `{t}`"),
            Failure::UnknownRunner(r) => write!(f, "unknown runner: `{r}`"),
            Failure::InvalidScript(line) => write!(f, "can't parse command: `{line}`"),
            Failure::Template(msg) => write!(f, "error in template: {msg}"),
            Failure::Io(msg) => write!(f, "{msg}"),
            Failure::Command { command, code: Some(code) } => write!(f, "`{command}` failed with exit code {code}"),
            Failure::Command { command, code: None } => write!(f, "`{command}` was killed"),
            Failure::NotAchieved(targets) => {
                let targets: Vec<String> = targets.iter().map(|t| format!("`{t}`")).collect();
                write!(f, "rule didn't create {}", targets.join(", "))
            }
            Failure::Cancelled => write!(f, "cancelled"),
            Failure::Rule(note, failure) => write!(f, "{note}: {failure}"),
        }
    }
}
}

Runners

A runner is a command that runs a script. Its arguments are template strings, where ${script} is replaced with the path of the script. That is the only variable they can use: other variables are an error, which is found when the runner is added. Brei comes with runners for Python and Bash; a program can add more.

#![allow(unused)]
fn main() {
//| id: rule-runner
/// A command that runs a script file.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Runner {
    /// The program to run.
    pub command: String,
    /// Its arguments, where `${script}` is the path of the script file.
    pub args: Vec<String>,
}

/// The runners that come with Brei, by name: `bash` and `python`.
pub fn default_runners() -> HashMap<String, Runner> {
    let runner = |command: &str| Runner { command: command.into(), args: vec!["${script}".into()] };
    HashMap::from([
        ("python".into(), runner("python")),
        ("bash".into(), runner("bash")),
    ])
}
}

The rule

The digest of a rule is a hash of its script. It is stored in the history after the rule was run, so that we notice when the script changed. We use MD5, like the Python version, to be able to read the same history files. Rules that run a script file don’t have a digest; for those, the script file is a dependency.

#![allow(unused)]
fn main() {
//| id: rule-rule
#[derive(Clone, Debug, Default)]
pub struct Rule {
    pub creates: Vec<Target>,
    pub requires: Vec<Target>,
    pub name: Option<String>,
    pub runner: Option<String>,
    pub path: Option<PathBuf>,
    pub script: Option<String>,
    pub stdin: Option<Target>,
    pub stdout: Option<Target>,
    pub description: Option<String>,
    pub force: bool,
}

#[derive(Debug, PartialEq, Eq)]
pub enum RuleError {
    TypeMismatch(TypeMismatch),
    Duplicate(Target),
    Invalid(String),
}

impl From<TypeMismatch> for RuleError {
    fn from(e: TypeMismatch) -> Self {
        RuleError::TypeMismatch(e)
    }
}

impl fmt::Display for RuleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RuleError::TypeMismatch(e) => write!(f, "{e}"),
            RuleError::Duplicate(t) => write!(f, "`{t}` is created by more than one rule"),
            RuleError::Invalid(msg) => write!(f, "{msg}"),
        }
    }
}

fn dedup(targets: &mut Vec<Target>) {
    let mut seen = HashSet::new();
    targets.retain(|t| seen.insert(t.clone()));
}

impl Rule {
    pub fn target_paths(&self) -> impl Iterator<Item=&PathBuf> {
        self.creates.iter().filter_map(|t| match t { Target::Path(p) => Some(p), _ => None })
    }

    pub fn dependency_paths(&self) -> impl Iterator<Item=&PathBuf> {
        self.requires.iter().filter_map(|t| match t { Target::Path(p) => Some(p), _ => None })
    }

    pub fn digest(&self) -> Option<String> {
        self.script.as_ref().map(|s| format!("{:x}", md5::compute(s)))
    }

    /// A short note on the rule, for the log: its description, its name, or its targets.
    pub fn note(&self) -> String {
        if let Some(description) = &self.description {
            return description.clone();
        }
        if let Some(name) = &self.name {
            return format!("#{name}");
        }
        let targets: Vec<String> = self.creates.iter().map(|t| format!("`{t}`")).collect();
        format!("creating {}", targets.join(" "))
    }

    pub fn always_run(&self) -> bool {
        self.force || self.target_paths().next().is_none() || matches!(self.stdout, Some(Target::Variable(..)))
    }

    /// Add implied targets and dependencies, and check that the rule makes sense.
    pub(super) fn complete(mut self) -> Result<Rule, RuleError> {
        if let Some(name) = &self.name {
            self.creates.push(Target::Phony(name.clone()));
        }
        if let Some(stdin) = &self.stdin {
            self.requires.push(stdin.clone());
        }
        if let Some(path) = &self.path {
            self.requires.push(Target::path(path));
        }
        if let Some(stdout) = &self.stdout {
            self.creates.push(stdout.clone());
        }
        dedup(&mut self.creates);
        dedup(&mut self.requires);

        let invalid = |msg: String| Err(RuleError::Invalid(msg));
        match &self.stdin {
            None | Some(Target::Path(_)) | Some(Target::Variable(_, VarType::Scalar)) => {}
            Some(t) => return invalid(format!("`stdin` can't be `{t}`")),
        }
        if let Some(t @ Target::Phony(_)) = &self.stdout {
            return invalid(format!("`stdout` can't be `{t}`"));
        }
        match (&self.runner, &self.script, &self.path) {
            (_, Some(_), Some(_)) => invalid("a rule can't have both `script` and `path`".into()),
            (None, None, Some(_)) => invalid("a rule with a `path` needs a `runner`".into()),
            (Some(_), None, None) => invalid("a rule with a `runner` needs a `script` or `path`".into()),
            (None, Some(script), None) if script.lines().count() > 1 && self.stdin.is_some() =>
                invalid("a script of more than one line can't have `stdin`, use a runner".into()),
            _ => Ok(self),
        }
    }
}
}

The task database

The task database holds everything the tasks share while running: the table of targets, the recipes, and which recipe creates which target. Commands run in the root directory, and paths are relative to it.

A recipe is anything that creates targets. There are three kinds:

  • a rule, ready to run;
  • a template: a rule that uses variables. It is expanded into a rule once the values of those variables are known;
  • a variable from the environment, whose value is a template string.

Each recipe knows the targets it creates, and what it requires before it can be used. For a rule, those are its dependencies. For a template or an environment variable, they are only the variables it uses: the dependencies of a template rule are only known once it is expanded.

A rule is stored as an Entry, with its targets interned. Entries are shared through an Arc, because rules that are expanded from a template don’t live in the database, only in the jobs that run them.

The history remembers the digest of the rule that last created each file. It is shared by all tasks, which may run on different threads, so it is behind a Mutex. It is a BTreeMap, so that it is written to disk in a stable order.

The database is shared with the tasks through an Arc. Recipes and runners can still be added while it is shared: reading a program needs to run some tasks before all recipes are known, for instance to compute the name of a file to include. So these are behind a RwLock, and recipes themselves are behind an Arc, so that a job can hold on to one. A target can only be created by one recipe.

#![allow(unused)]
fn main() {
//| file: src/tasks/db.rs
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use super::rule::{Rule, RuleError, Runner, default_runners};
use super::target::{Target, TargetId, Targets};
use super::template::{variables, RuleTemplate};

pub struct Entry {
    pub(super) rule: Rule,
    pub(super) creates: Vec<TargetId>,
    pub(super) requires: Vec<TargetId>,
    pub(super) stdin: Option<TargetId>,
}

impl Entry {
    pub(super) fn new(rule: Rule, targets: &Targets) -> Result<Self, RuleError> {
        let rule = rule.complete()?;
        let intern = |ts: &[Target]| ts.iter().map(|t| targets.intern(t)).collect::<Result<Vec<_>, _>>();
        let creates = intern(&rule.creates)?;
        let requires = intern(&rule.requires)?;
        let stdin = match &rule.stdin {
            Some(t @ Target::Variable(..)) => targets.lookup(t),
            _ => None,
        };
        Ok(Entry { rule, creates, requires, stdin })
    }
}

pub enum Kind {
    Rule(Arc<Entry>),
    Template(RuleTemplate),
    Variable(String),
}

pub struct Recipe {
    pub(super) creates: Vec<TargetId>,
    pub(super) requires: Vec<TargetId>,
    pub(super) kind: Kind,
}

pub struct TaskDb {
    pub root: PathBuf,
    pub targets: Targets,
    pub force_run: bool,
    runners: RwLock<HashMap<String, Runner>>,
    recipes: RwLock<HashMap<TargetId, Arc<Recipe>>>,
    pub(super) history: Mutex<BTreeMap<PathBuf, String>>,
}

impl TaskDb {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        TaskDb {
            root: root.into(),
            targets: Targets::new(),
            force_run: false,
            runners: RwLock::new(default_runners()),
            recipes: RwLock::new(HashMap::new()),
            history: Mutex::new(BTreeMap::new()),
        }
    }

    pub fn add(&self, rule: Rule) -> Result<(), RuleError> {
        let entry = Entry::new(rule, &self.targets)?;
        self.insert(Recipe { creates: entry.creates.clone(), requires: entry.requires.clone(), kind: Kind::Rule(Arc::new(entry)) })
    }

    pub(super) fn insert(&self, recipe: Recipe) -> Result<(), RuleError> {
        let mut recipes = self.recipes.write().unwrap();
        if let Some(id) = recipe.creates.iter().find(|id| recipes.contains_key(id)) {
            return Err(RuleError::Duplicate(self.targets.get(*id)));
        }
        let recipe = Arc::new(recipe);
        for id in &recipe.creates {
            recipes.insert(*id, recipe.clone());
        }
        Ok(())
    }

    pub(super) fn recipe_for(&self, target: TargetId) -> Option<Arc<Recipe>> {
        self.recipes.read().unwrap().get(&target).cloned()
    }

    /// Whether some recipe creates `target`.
    pub fn creates(&self, target: &Target) -> bool {
        self.targets.lookup(target).and_then(|id| self.recipe_for(id)).is_some()
    }

    /// Add a runner. Its arguments can only use the variable `script`.
    pub fn add_runner(&self, name: &str, runner: Runner) -> Result<(), RuleError> {
        if let Some(var) = runner.args.iter().flat_map(|arg| variables(arg)).find(|v| *v != "script") {
            return Err(RuleError::Invalid(format!("its arguments use `${{{var}}}`, but only `${{script}}` can be used")));
        }
        self.runners.write().unwrap().insert(name.to_string(), runner);
        Ok(())
    }

    pub fn runner(&self, name: &str) -> Option<Runner> {
        self.runners.read().unwrap().get(name).cloned()
    }
}
}

Persistent history

The history is kept between runs in a JSON file, by default .brei_history in the root directory, that maps each path to its digest. A missing file is an empty history. Loading adds to the history in memory, so that loading twice does no harm.

The history should be saved after every run, also when the run failed: targets of failed rules have been forgotten, so they are built again next time, while the rules that did succeed don’t need to. We write to a temporary file first and then rename it, so an interrupted write can’t leave a broken history behind.

#![allow(unused)]
fn main() {
//| file: src/tasks/history.rs
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;
use super::db::TaskDb;

pub const HISTORY_FILE: &str = ".brei_history";

impl TaskDb {
    /// Read the history from a file, relative to the root.
    pub fn load_history(&self, path: impl AsRef<Path>) -> io::Result<()> {
        let file = match File::open(self.root.join(path)) {
            Ok(file) => file,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(e),
        };
        let data: BTreeMap<PathBuf, String> = serde_json::from_reader(BufReader::new(file))?;
        self.history.lock().unwrap().extend(data);
        Ok(())
    }

    /// Write the history to a file, relative to the root.
    pub fn save_history(&self, path: impl AsRef<Path>) -> io::Result<()> {
        let path = self.root.join(path);
        let dir = path.parent().unwrap_or(&self.root);
        let mut tmp = NamedTempFile::new_in(dir)?;
        {
            let mut out = BufWriter::new(tmp.as_file_mut());
            serde_json::to_writer_pretty(&mut out, &*self.history.lock().unwrap())?;
            writeln!(out)?;
            out.flush()?;
        }
        tmp.persist(path)?;
        Ok(())
    }
}
}

Templates

A rule in a Brei program is written with strings, which may contain variables: ${name} is replaced with the value of the scalar variable var(name). Additionally, splice(name) in requires is replaced with the elements of the list variable listvar(name). Such a rule is a RuleTemplate, the Python TaskProxy. A template depends on the variables it uses. Once their values are known, it is expanded into a Rule, which then has its own dependencies.

A template string uses the dollar syntax. $$ is a literal dollar sign, also in a template that doesn’t use any variables, so every template is expanded, even if it has no variables. One that has no variables and doesn’t splice anything is expanded right away, and added as a rule. Otherwise it is added as a recipe of its own.

The targets of a template (creates, stdout and name) are fixed: we need to know which recipe creates a target before we can build it. Templates with variables in their targets are resolved in an earlier stage, when reading the program. List variables have their own place: listvar(name) can only be used as stdout, and splice(name) only in requires.

#![allow(unused)]
fn main() {
//| file: src/tasks/template.rs
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;
use serde::Deserialize;
use crate::template_strings::{dollar, Env, Error, Format, Item};
use super::db::{Kind, Recipe, TaskDb};
use super::rule::{Failure, Rule, RuleError};
use super::target::{wrapped, Target, VarType};

/// A task, or a template, as written in a program. All strings are template strings.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RuleTemplate {
    /// The targets the task creates.
    pub creates: Vec<String>,
    /// The targets the task needs; `splice(name)` adds the elements of a list variable.
    pub requires: Vec<String>,
    /// Makes the task available as the phony target `#name`.
    pub name: Option<String>,
    /// The runner of the script; without one, every line of the script is a command.
    pub runner: Option<String>,
    /// A script file to run instead of `script`; needs a runner.
    pub path: Option<String>,
    /// The script to run.
    pub script: Option<String>,
    /// Standard input: a file, or a scalar variable `var(name)`.
    pub stdin: Option<String>,
    /// Standard output: a file, `var(name)` or `listvar(name)`.
    pub stdout: Option<String>,
    /// Shown in the log when the task runs.
    pub description: Option<String>,
    /// Always run the task.
    pub force: bool,
}

/// The values of list variables, by name.
pub(super) type Lists = HashMap<String, Vec<String>>;

/// Names of the variables in a template string.
pub(super) fn variables(s: &str) -> impl Iterator<Item=&str> {
    dollar(s).filter_map(|item| match item {
        Ok(Item::Variable(name)) => Some(name),
        _ => None,
    })
}

pub(super) fn substitute(s: &str, env: &Env) -> Result<String, Failure> {
    dollar(s).format(env).map_err(|e| Failure::Template(match e {
        Error::MissingVariable(name) => format!("variable `{name}` has no value"),
        Error::InvalidTemplate(msg) => msg,
    }))
}

/// Substitute the variables in `env`, and leave the others. The values in `env` are template strings themselves, and so is the result.
pub(super) fn fill(s: &str, env: &Env) -> String {
    dollar(s).flatten().map(|item| match item {
        Item::Variable(name) => env.get(name).cloned().unwrap_or_else(|| format!("${{{name}}}")),
        Item::Literal(text) => escape(text),
    }).collect()
}

/// A template string for the literal text `s`.
pub(super) fn escape(s: &str) -> String {
    s.replace('$', "$$")
}

pub(super) fn splice_name(s: &str) -> Option<&str> {
    wrapped(s, "splice")
}

fn parse(s: String) -> Result<Target, Failure> {
    s.parse().map_err(|_| Failure::Template("empty target".into()))
}

impl RuleTemplate {
    /// The targets: `creates`, `stdout` and the phony target `#name`.
    pub(super) fn targets(&self) -> Vec<String> {
        self.creates.iter().cloned()
            .chain(self.stdout.clone())
            .chain(self.name.as_ref().map(|n| format!("#{n}")))
            .collect()
    }

    fn strings(&self) -> impl Iterator<Item=&String> {
        let fields = [&self.name, &self.runner, &self.path, &self.script, &self.stdin, &self.stdout, &self.description];
        self.creates.iter().chain(&self.requires).chain(fields.into_iter().flatten())
    }

    /// Names of the variables used in the template.
    pub fn variables(&self) -> BTreeSet<&str> {
        self.strings().flat_map(|s| variables(s)).collect()
    }

    /// A short description of the rule, for error messages.
    pub fn label(&self) -> String {
        let targets = self.targets();
        if let Some(name) = &self.name {
            format!("rule `#{name}`")
        } else if !targets.is_empty() {
            let targets: Vec<String> = targets.iter().map(|t| format!("`{t}`")).collect();
            format!("rule for {}", targets.join(", "))
        } else if let Some(description) = &self.description {
            format!("rule \"{description}\"")
        } else {
            "rule without targets".to_string()
        }
    }

    /// Names of the variables used in the targets.
    pub fn target_variables(&self) -> BTreeSet<&str> {
        let fields = [&self.name, &self.stdout];
        self.creates.iter().chain(fields.into_iter().flatten()).flat_map(|s| variables(s)).collect()
    }

    fn map(&self, target: impl Fn(&str) -> String, other: impl Fn(&str) -> String) -> RuleTemplate {
        RuleTemplate {
            creates: self.creates.iter().map(|s| target(s)).collect(),
            requires: self.requires.iter().map(|s| other(s)).collect(),
            name: self.name.as_deref().map(&target),
            runner: self.runner.as_deref().map(&other),
            path: self.path.as_deref().map(&other),
            script: self.script.as_deref().map(&other),
            stdin: self.stdin.as_deref().map(&other),
            stdout: self.stdout.as_deref().map(&target),
            description: self.description.as_deref().map(&other),
            force: self.force,
        }
    }

    /// Substitute the variables in `env` in all fields, leaving the others (see `fill`).
    pub(super) fn fill(&self, env: &Env) -> RuleTemplate {
        self.map(|s| fill(s, env), |s| fill(s, env))
    }

    /// Substitute the variables in `env` in the targets only.
    pub(super) fn fill_targets(&self, env: &Env) -> RuleTemplate {
        self.map(|s| fill(s, env), str::to_string)
    }

    /// Names of the list variables spliced into `requires`.
    pub fn splices(&self) -> BTreeSet<&str> {
        self.requires.iter().filter_map(|s| splice_name(s)).collect()
    }

    fn check(&self) -> Result<(), RuleError> {
        let invalid = |msg: String| Err(RuleError::Invalid(msg));
        let targets = self.targets();
        if let Some(t) = targets.iter().find(|t| variables(t).next().is_some()) {
            return invalid(format!("the targets of a rule can't contain variables, found `{t}`"));
        }
        let inputs = || self.stdin.iter().chain(&self.path);
        if let Some(s) = self.creates.iter().chain(&self.requires).chain(inputs()).find(|s| wrapped(s, "listvar").is_some()) {
            return invalid(format!("`{s}` can only be used as `stdout` of a rule"));
        }
        if let Some(s) = targets.iter().chain(inputs()).find(|s| splice_name(s).is_some()) {
            return invalid(format!("`{s}` can only be used in `requires`"));
        }
        Ok(())
    }

    /// Substitute variables and splice lists, giving a rule.
    pub(super) fn expand(&self, env: &Env, lists: &Lists) -> Result<Rule, Failure> {
        let sub = |s: &Option<String>| s.as_deref().map(|s| substitute(s, env)).transpose();
        let target = |s: &str| parse(substitute(s, env)?);

        let mut requires = Vec::new();
        for s in &self.requires {
            match splice_name(s) {
                Some(name) => {
                    let items = lists.get(name)
                        .ok_or_else(|| Failure::Template(format!("list variable `{name}` has no value")))?;
                    for item in items {
                        requires.push(parse(item.clone())?);
                    }
                }
                None => requires.push(target(s)?),
            }
        }

        Ok(Rule {
            creates: self.creates.iter().map(|s| target(s)).collect::<Result<_, _>>()?,
            requires,
            name: sub(&self.name)?,
            runner: sub(&self.runner)?,
            path: sub(&self.path)?.map(PathBuf::from),
            script: sub(&self.script)?,
            stdin: sub(&self.stdin)?.map(parse).transpose()?,
            stdout: sub(&self.stdout)?.map(parse).transpose()?,
            description: sub(&self.description)?,
            force: self.force,
        })
    }
}

fn scalar(name: &str) -> Target {
    Target::Variable(name.to_string(), VarType::Scalar)
}

impl TaskDb {
    /// Add a rule that may use variables.
    pub fn add_template(&self, template: RuleTemplate) -> Result<(), RuleError> {
        template.check()?;
        let invalid = |f: Failure| RuleError::Invalid(f.to_string());
        let (vars, lists) = (template.variables(), template.splices());
        if vars.is_empty() && lists.is_empty() {
            let rule = template.expand(&Env::new(), &Lists::new()).map_err(invalid)?;
            return self.add(rule);
        }

        let requires = vars.iter().map(|v| scalar(v))
            .chain(lists.iter().map(|v| Target::Variable(v.to_string(), VarType::List)))
            .map(|t| self.targets.intern(&t))
            .collect::<Result<Vec<_>, _>>()?;
        let mut creates = Vec::new();
        for t in template.targets() {
            let t = parse(substitute(&t, &Env::new()).map_err(invalid)?).map_err(invalid)?;
            creates.push(self.targets.intern(&t)?);
        }
        self.insert(Recipe { creates, requires, kind: Kind::Template(template) })
    }

    /// Add a variable whose value is a template string.
    pub fn add_variable(&self, name: &str, template: &str) -> Result<(), RuleError> {
        let creates = vec![self.targets.intern(&scalar(name))?];
        let requires = variables(template).map(|v| self.targets.intern(&scalar(v))).collect::<Result<Vec<_>, _>>()?;
        self.insert(Recipe { creates, requires, kind: Kind::Variable(template.to_string()) })
    }
}
}

Running a rule

Is a rule out of date?

A rule needs to run when one of its target files is missing, is older than one of the files it depends on, or was created by a different version of the script (according to the history).

#![allow(unused)]
fn main() {
//| file: src/tasks/exec.rs
use std::env;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, SystemTime};
use tempfile::{NamedTempFile, TempPath};
use crate::noodles::task::CancelToken;
use crate::template_strings::Env;
use super::db::TaskDb;
use super::group;
use super::rule::{Rule, Value, Failure};
use super::target::{Target, VarType};
use super::template::substitute;

impl TaskDb {
    fn modified(&self, path: &Path) -> Result<SystemTime, Failure> {
        Ok(fs::metadata(self.root.join(path))?.modified()?)
    }

    pub fn needs_run(&self, rule: &Rule) -> Result<bool, Failure> {
        if rule.target_paths().any(|p| !self.root.join(p).exists()) {
            return Ok(true);
        }
        let targets = rule.target_paths().map(|p| self.modified(p)).collect::<Result<Vec<_>, _>>()?;
        let deps = rule.dependency_paths().map(|p| self.modified(p)).collect::<Result<Vec<_>, _>>()?;
        if targets.iter().any(|t| deps.iter().any(|d| t < d)) {
            return Ok(true);
        }
        let digest = rule.digest();
        let history = self.history.lock().unwrap();
        Ok(rule.target_paths().any(|p| history.get(p) != digest.as_ref()))
    }

    fn remember(&self, rule: &Rule) {
        let mut history = self.history.lock().unwrap();
        for p in rule.target_paths() {
            match rule.digest() {
                Some(digest) => history.insert(p.clone(), digest),
                None => history.remove(p),
            };
        }
    }

    /// Targets of a rule that failed may be written partially, so we forget them, and they are built again next time.
    fn forget(&self, rule: &Rule) {
        let mut history = self.history.lock().unwrap();
        for p in rule.target_paths() {
            history.remove(p);
        }
    }

    <<exec-commands>>
    <<exec-execute>>
}

<<exec-find-program>>
<<exec-run-command>>
}

Commands

Without a runner, each line of the script is a command, split into arguments like a shell would. Note that this is not a shell: there are no pipes, redirections or variables. With a runner, the script is written to a temporary file (unless the rule has a path), and there is a single command: the runner with its arguments. The temporary file is kept until the rule is done.

#![allow(unused)]
fn main() {
//| id: exec-commands
fn commands(&self, rule: &Rule, script_file: &mut Option<TempPath>) -> Result<Vec<Vec<String>>, Failure> {
    let Some(name) = &rule.runner else {
        let script = rule.script.as_deref().unwrap_or("");
        return script.lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| shlex::split(line).ok_or_else(|| Failure::InvalidScript(line.to_string())))
            .collect();
    };

    let runner = self.runner(name).ok_or_else(|| Failure::UnknownRunner(name.clone()))?;
    let path: PathBuf = match (&rule.path, &rule.script) {
        (Some(path), _) => self.root.join(path),
        (None, Some(script)) => {
            let mut file = NamedTempFile::new()?;
            file.write_all(script.as_bytes())?;
            // Close the file, so that it can be opened by the runner on any platform.
            let temp = file.into_temp_path();
            let path = temp.to_path_buf();
            *script_file = Some(temp);
            path
        }
        (None, None) => return Err(Failure::InvalidScript(String::new())),
    };

    let mut env = Env::new();
    env.insert("script".into(), path.to_string_lossy().into_owned());
    let args = runner.args.iter()
        .map(|arg| substitute(arg, &env))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(vec![std::iter::once(runner.command.clone()).chain(args).collect()])
}
}

Executing

To execute a rule, we first check if it needs to run at all. A rule without a script (only dependencies) is done once its dependencies are.

Standard input comes from a file, from the value of a variable, or is empty. Unlike the Python version, a command never reads from the terminal: with many commands running at the same time that would be confusing. Standard output goes to a file, is captured into a variable, or goes to the log. Standard error always goes to the log. If there are several commands, they share the same input and output files.

The log uses the log crate. Every rule that runs logs its note, and every line of output is logged with the note attached as the key-value pair note, so that output from rules that run at the same time can be told apart. The program that uses the library decides how to show this.

After running, we store the digest in the history, and check that the rule actually did what it promised: if it still needs to run, something is wrong. The value of a rule is its standard output, if it was captured: trimmed for a scalar, and split into non-empty lines for a list.

#![allow(unused)]
fn main() {
//| id: exec-execute
pub(super) fn execute(&self, rule: &Rule, input: Option<&str>, cancel: &CancelToken) -> Result<Value, Failure> {
    if !(self.force_run || rule.always_run()) && !self.needs_run(rule)? {
        log::debug!("{} is up to date", rule.note());
        return Ok(Value::Nothing);
    }
    if rule.runner.is_none() && rule.script.is_none() {
        return Ok(Value::Nothing);
    }
    let note = rule.note();
    log::info!(target: "brei::rule", "{note}");

    let mut script_file = None;
    let commands = self.commands(rule, &mut script_file)?;
    let stdin = match &rule.stdin {
        Some(Target::Path(p)) => Some(File::open(self.root.join(p))?),
        _ => None,
    };
    let stdout = match &rule.stdout {
        Some(Target::Path(p)) => Some(File::create(self.root.join(p))?),
        _ => None,
    };
    let capture = matches!(rule.stdout, Some(Target::Variable(..)));

    let mut output = Vec::new();
    for command in &commands {
        let display = command.join(" ");
        let Some(program) = find_program(&command[0]) else {
            self.forget(rule);
            return Err(Failure::Io(format!("can't run `{display}`: command not found")));
        };
        let mut cmd = Command::new(program);
        cmd.args(&command[1..]).current_dir(&self.root).stderr(Stdio::piped());
        cmd.stdin(match &stdin {
            Some(file) => Stdio::from(file.try_clone()?),
            None if input.is_some() => Stdio::piped(),
            None => Stdio::null(),
        });
        cmd.stdout(match &stdout {
            Some(file) => Stdio::from(file.try_clone()?),
            None => Stdio::piped(),
        });
        log::debug!("{note}: running `{display}`");
        match run_command(cmd, &display, input, capture, &note, cancel) {
            Ok(out) => output.extend(out),
            Err(failure) => {
                self.forget(rule);
                return Err(failure);
            }
        }
    }
    drop(script_file);

    self.remember(rule);
    if self.needs_run(rule)? {
        return Err(Failure::NotAchieved(rule.creates.clone()));
    }

    let text = String::from_utf8_lossy(&output);
    Ok(match &rule.stdout {
        Some(Target::Variable(_, VarType::List)) =>
            Value::List(text.lines().filter(|l| !l.is_empty()).map(String::from).collect()),
        Some(Target::Variable(_, VarType::Scalar)) => Value::Scalar(text.trim().to_string()),
        _ => Value::Nothing,
    })
}
}

Finding a program

A command is looked up on the PATH, the way a shell does it, before it runs. Command can do this by itself, but on Windows it looks in the system directories first. There, bash.exe starts the Windows Subsystem for Linux, while the user means the bash on their path, for instance from Git for Windows. On Windows, a program can leave out its extension: we try those in PATHEXT. A command with a directory in it is used as it is.

#![allow(unused)]
fn main() {
//| id: exec-find-program
fn find_program(name: &str) -> Option<PathBuf> {
    if name.contains(['/', '\\']) {
        return Some(PathBuf::from(name));
    }
    let mut extensions = vec![String::new()];
    if cfg!(windows) {
        let pathext = env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
        if Path::new(name).extension().is_none() {
            extensions.clear();
        }
        extensions.extend(pathext.split(';').filter(|e| !e.is_empty()).map(str::to_lowercase));
    }
    env::split_paths(&env::var_os("PATH")?)
        .flat_map(|dir| extensions.iter().map(move |ext| dir.join(format!("{name}{ext}"))))
        .find(|path| is_executable(path))
}

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}

#[cfg(not(unix))]
fn is_executable(path: &Path) -> bool {
    path.is_file()
}
}

Running a command

Input and output go through pipes. Each pipe gets its own thread, so that a command that writes a lot of output before reading its input can’t block. Output is either captured, or forwarded to the log line by line. Meanwhile, we poll the command to see if it has finished, and check the cancel token. A cancelled command is killed.

A command can start processes of its own, like a runner script that calls other programs. Killing only the command would leave those running, so commands run in a process group of their own, which is killed as a whole.

#![allow(unused)]
fn main() {
//| id: exec-run-command
fn forward(stream: impl Read + Send + 'static, note: &str) -> thread::JoinHandle<std::io::Result<Vec<u8>>> {
    let note = note.to_string();
    thread::spawn(move || {
        let mut reader = BufReader::new(stream);
        let mut line = Vec::new();
        while reader.read_until(b'\n', &mut line)? > 0 {
            log::info!(target: "brei::output", note = note.as_str(); "{}", String::from_utf8_lossy(&line).trim_end());
            line.clear();
        }
        Ok(Vec::new())
    })
}

fn run_command(mut cmd: Command, display: &str, input: Option<&str>, capture: bool, note: &str, cancel: &CancelToken) -> Result<Vec<u8>, Failure> {
    let mut child = group::spawn(&mut cmd).map_err(|e| Failure::Io(format!("can't run `{display}`: {e}")))?;

    let writer = match (child.stdin.take(), input) {
        (Some(mut stdin), Some(data)) => {
            let data = data.as_bytes().to_vec();
            // The command may exit without reading all of its input; that's fine.
            Some(thread::spawn(move || { let _ = stdin.write_all(&data); }))
        }
        _ => None,
    };
    let reader = child.stdout.take().map(|mut stdout| match capture {
        true => thread::spawn(move || {
            let mut buffer = Vec::new();
            stdout.read_to_end(&mut buffer).map(|_| buffer)
        }),
        false => forward(stdout, note),
    });
    let errors = child.stderr.take().map(|stderr| forward(stderr, note));

    let status = loop {
        if let Some(status) = child.try_wait()? {
            group::done(&child);
            break status;
        }
        if cancel.is_cancelled() {
            group::kill(&mut child);
            let _ = child.wait();
            group::done(&child);
            return Err(Failure::Cancelled);
        }
        thread::sleep(Duration::from_millis(10));
    };

    if let Some(writer) = writer {
        let _ = writer.join();
    }
    if let Some(errors) = errors {
        errors.join().expect("reader thread panicked")?;
    }
    let output = match reader {
        Some(reader) => reader.join().expect("reader thread panicked")?,
        None => Vec::new(),
    };
    if !status.success() {
        return Err(Failure::Command { command: display.to_string(), code: status.code() });
    }
    Ok(output)
}
}

Process groups

On Unix, every command runs in a process group of its own, whose id is the process id of the command. Killing the group kills the command and everything it started (unless those started groups of their own). Before the command is waited for, its process id can’t be reused, so it is safe to kill the group then.

There is a catch. When you press Ctrl-C, the terminal sends SIGINT to the foreground process group, which is the group of brei. Commands in their own group don’t get it, so they would keep running after brei stops. That’s why we keep track of the groups that are running: kill_all kills them all, and is meant to be called when Brei is interrupted. After that, no new commands start. Starting a command and adding it to the list happens while holding the lock, so a command can’t slip through.

On other platforms, commands are killed with Child::kill, and kill_all doesn’t do anything. On Windows, Ctrl-C reaches every process in the console anyway.

#![allow(unused)]
fn main() {
//| file: src/tasks/group.rs
use std::collections::BTreeSet;
use std::io;
use std::process::{Child, Command};
use std::sync::Mutex;

struct Running {
    stopping: bool,
    groups: BTreeSet<u32>,
}

static RUNNING: Mutex<Running> = Mutex::new(Running { stopping: false, groups: BTreeSet::new() });

/// Start a command in a process group of its own.
pub(super) fn spawn(cmd: &mut Command) -> io::Result<Child> {
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(cmd, 0);
    let mut running = RUNNING.lock().unwrap();
    if running.stopping {
        return Err(io::Error::new(io::ErrorKind::Interrupted, "Brei is stopping"));
    }
    let child = cmd.spawn()?;
    running.groups.insert(child.id());
    Ok(child)
}

/// Forget about a command, after waiting for it.
pub(super) fn done(child: &Child) {
    RUNNING.lock().unwrap().groups.remove(&child.id());
}

/// Kill a command, and everything it started. Do this before waiting for it.
pub(super) fn kill(child: &mut Child) {
    #[cfg(unix)]
    kill_group(child.id());
    let _ = child.kill();
}

#[cfg(unix)]
fn kill_group(id: u32) {
    // SAFETY: `kill` only sends a signal; it has no memory safety requirements.
    unsafe {
        libc::kill(-(id as libc::pid_t), libc::SIGKILL);
    }
}

/// Kill all running commands, and don't start new ones. For when Brei is interrupted.
pub fn kill_all() {
    let mut running = RUNNING.lock().unwrap();
    running.stopping = true;
    #[cfg(unix)]
    for id in &running.groups {
        kill_group(*id);
    }
}
}

Engine tasks

Now we can put rules on the engine. There are five kinds of jobs:

  • Build a target, with the target as its key. This job is memoized, so every target is built at most once. If no recipe creates the target, it should be a file that already exists. Otherwise, the result is a continuation: building each dependency of the recipe, followed by running the rule, or expanding the template;
  • Expand a template or an environment variable, once the variables it uses are built. A variable gives its value right away. A template gives a rule, so the result is again a continuation: building the dependencies of that rule, followed by running it;
  • Run a rule, once its dependencies are built. This has a local key, and receives the values of all dependencies. The only value it uses is that of a variable on stdin;
  • Alias a target to another. A recipe can create several targets, but we want to use it only once. So the first target is the main one: building any other target of the recipe gives a continuation that builds the main target, followed by an alias that passes on its value;
  • All waits for several targets, so that we can build them in one go. Its value is Nothing.
#![allow(unused)]
fn main() {
//| file: src/tasks/job.rs
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::noodles::task::{Task, Response, Promise, CancelToken, Error, Worker};
use crate::noodles::kernel::Kernel;
use crate::template_strings::Env;
use super::db::{Entry, Kind, Recipe, TaskDb};
use super::rule::{Value, Failure};
use super::target::{Target, TargetId, Key};
use super::template::{substitute, Lists};

pub enum Job {
    Build { db: Arc<TaskDb>, target: TargetId },
    Expand { db: Arc<TaskDb>, recipe: Arc<Recipe>, args: HashMap<TargetId, Value> },
    Run { db: Arc<TaskDb>, entry: Arc<Entry>, args: HashMap<TargetId, Value> },
    Alias { target: TargetId, value: Option<Value> },
    All { targets: Vec<TargetId>, done: HashSet<TargetId> },
}

impl Job {
    pub fn build(db: &Arc<TaskDb>, target: TargetId) -> Self {
        Job::Build { db: db.clone(), target }
    }
}

/// Build the dependencies, then `last`.
fn after(db: &Arc<TaskDb>, deps: &[TargetId], last: Job) -> Response<Job> {
    let tasks = deps.iter().map(|dep| Job::build(db, *dep)).chain([last]);
    Response::Continuation(Box::new(Promise::new(Key::Local(0), tasks)))
}

fn build_target(db: Arc<TaskDb>, target: TargetId) -> Response<Job> {
    let Some(recipe) = db.recipe_for(target) else {
        return match db.targets.get(target) {
            Target::Path(p) if db.root.join(&p).exists() => Response::Value(Value::Nothing),
            t => Response::Error(Failure::Missing(t)),
        };
    };

    let main = recipe.creates[0];
    if main != target {
        return after(&db, &[main], Job::Alias { target: main, value: None });
    }
    let last = match &recipe.kind {
        Kind::Rule(entry) => Job::Run { db: db.clone(), entry: entry.clone(), args: HashMap::new() },
        Kind::Template(_) | Kind::Variable(_) => Job::Expand { db: db.clone(), recipe: recipe.clone(), args: HashMap::new() },
    };
    after(&db, &recipe.requires, last)
}

<<job-expand-run>>
}

To expand a template, we collect the values of the variables it uses. Variables that have no value (because the rule that creates them didn’t need to run) are left out, so using them gives an error. The rule that comes out of a template is interned at run time; its dependencies may be new targets, for instance paths from a list variable.

#![allow(unused)]
fn main() {
//| id: job-expand-run
fn expand(db: Arc<TaskDb>, recipe: Arc<Recipe>, args: HashMap<TargetId, Value>) -> Response<Job> {
    let mut env = Env::new();
    let mut lists = Lists::new();
    for (id, value) in args {
        let Target::Variable(name, _) = db.targets.get(id) else { continue };
        match value {
            Value::Scalar(s) => { env.insert(name, s); }
            Value::List(l) => { lists.insert(name, l); }
            Value::Nothing => {}
        }
    }

    let label = match &recipe.kind {
        Kind::Template(template) => template.label(),
        _ => format!("`{}`", db.targets.get(recipe.creates[0])),
    };
    let result = match &recipe.kind {
        Kind::Variable(template) => substitute(template, &env).map(|s| Response::Value(Value::Scalar(s))),
        Kind::Template(template) => template.expand(&env, &lists)
            .and_then(|rule| Entry::new(rule, &db.targets).map_err(|e| Failure::Template(e.to_string())))
            .map(|entry| {
                let entry = Arc::new(entry);
                after(&db, &entry.requires, Job::Run { db: db.clone(), entry: entry.clone(), args: HashMap::new() })
            }),
        Kind::Rule(_) => unreachable!("rules are not expanded"),
    };
    result.unwrap_or_else(|failure| Response::Error(Failure::Rule(label, Box::new(failure))))
}

fn run_rule(db: Arc<TaskDb>, entry: Arc<Entry>, args: HashMap<TargetId, Value>, cancel: &CancelToken) -> Response<Job> {
    let input = entry.stdin.map(|id| match args.get(&id) {
        Some(Value::Scalar(s)) => s.as_str(),
        _ => "",
    });
    match db.execute(&entry.rule, input, cancel) {
        Ok(value) => Response::Value(value),
        Err(Failure::Cancelled) => Response::Error(Failure::Cancelled),
        Err(failure) => Response::Error(Failure::Rule(entry.rule.note(), Box::new(failure))),
    }
}

impl Task for Job {
    type Value = Value;
    type Key = Key;
    type Error = Failure;

    fn key(&self) -> Key {
        match self {
            Job::Build { target, .. } => Key::Target(*target),
            Job::Expand { .. } | Job::Run { .. } | Job::Alias { .. } | Job::All { .. } => Key::Local(0),
        }
    }

    fn dependencies(&self) -> impl Iterator<Item=Key> {
        let deps: Vec<TargetId> = match self {
            Job::Build { .. } => Vec::new(),
            Job::Expand { recipe, .. } => recipe.requires.clone(),
            Job::Run { entry, .. } => entry.requires.clone(),
            Job::Alias { target, .. } => vec![*target],
            Job::All { targets, .. } => targets.clone(),
        };
        deps.into_iter().map(Key::Target)
    }

    fn memoize(&self) -> bool {
        self.key().is_global()
    }

    fn run(self, cancel: &CancelToken) -> Response<Self> {
        match self {
            Job::Build { db, target } => build_target(db, target),
            Job::Expand { db, recipe, args } => expand(db, recipe, args),
            Job::Run { db, entry, args } => run_rule(db, entry, args, cancel),
            Job::Alias { value, .. } => Response::Value(value.expect("alias is ready")),
            Job::All { .. } => Response::Value(Value::Nothing),
        }
    }

    fn assoc(&mut self, key: Key, value: Value) {
        match (self, key) {
            (Job::Expand { args, .. } | Job::Run { args, .. }, Key::Target(id)) => { args.insert(id, value); }
            (Job::Alias { value: v, .. }, _) => *v = Some(value),
            (Job::All { done, .. }, Key::Target(id)) => { done.insert(id); }
            _ => {}
        }
    }

    fn ready(&self) -> bool {
        match self {
            Job::Build { .. } => true,
            Job::Expand { recipe, args, .. } => args.len() == recipe.requires.len(),
            Job::Run { entry, args, .. } => args.len() == entry.requires.len(),
            Job::Alias { value, .. } => value.is_some(),
            Job::All { targets, done } => done.len() == targets.len(),
        }
    }
}

/// Build a target, giving its value.
pub fn build<W: Worker<Job>>(db: &Arc<TaskDb>, kernel: &mut Kernel<Job>, worker: &W, target: TargetId) -> Result<Value, Error<Job>> {
    kernel.run(worker, Box::new(Promise::new(Key::Target(target), [Job::build(db, target)])))
}

/// Build several targets at once.
pub fn build_all<W: Worker<Job>>(db: &Arc<TaskDb>, kernel: &mut Kernel<Job>, worker: &W, targets: &[TargetId]) -> Result<(), Error<Job>> {
    let mut targets = targets.to_vec();
    targets.sort();
    targets.dedup();
    let mut jobs: Vec<Job> = targets.iter().map(|t| Job::build(db, *t)).collect();
    jobs.push(Job::All { targets, done: HashSet::new() });
    kernel.run(worker, Box::new(Promise::new(Key::Local(0), jobs))).map(|_| ())
}
}

Tests

The tests run real commands in a temporary directory, so they need bash, cat, tr and a few other common Unix tools.

#![allow(unused)]
fn main() {
//| file: src/tasks/tests.rs
use std::fs;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use tempfile::TempDir;
use crate::noodles::kernel::Kernel;
use crate::noodles::single_worker::SingleWorker;
use crate::noodles::worker_pool::WorkerPool;
use crate::noodles::task::Error;
use super::*;

fn target(s: &str) -> Target {
    s.parse().unwrap()
}

fn targets(ts: &[&str]) -> Vec<Target> {
    ts.iter().map(|t| target(t)).collect()
}

fn rule(creates: &[&str], requires: &[&str], script: &str) -> Rule {
    Rule { creates: targets(creates), requires: targets(requires), script: Some(script.into()), ..Default::default() }
}

fn bash(creates: &[&str], requires: &[&str], script: &str) -> Rule {
    Rule { runner: Some("bash".into()), ..rule(creates, requires, script) }
}

fn run(db: &Arc<TaskDb>, t: &str) -> Result<Value, Error<Job>> {
    let id = db.targets.intern(&target(t)).unwrap();
    build(db, &mut Kernel::new(), &SingleWorker::new(), id)
}

fn read(dir: &TempDir, path: &str) -> String {
    fs::read_to_string(dir.path().join(path)).unwrap()
}

fn in_rule(note: &str, failure: Failure) -> Failure {
    Failure::Rule(note.into(), Box::new(failure))
}

fn failures(result: Result<Value, Error<Job>>) -> Vec<Failure> {
    match result {
        Err(Error::Jobs(failures)) => failures,
        Err(e) => panic!("expected failures, got {e:?}"),
        Ok(v) => panic!("expected failures, got {v:?}"),
    }
}

<<task-tests>>
}

A simple rule, and a chain of rules. The second time, nothing needs to be done. When a dependency changes, only the rules that depend on it run again.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn hello() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(Rule { stdout: Some(target("hello.txt")), ..rule(&[], &[], "echo hello") }).unwrap();
    assert_eq!(run(&Arc::new(db), "hello.txt").unwrap(), Value::Nothing);
    assert_eq!(read(&dir, "hello.txt"), "hello\n");
}

#[test]
fn up_to_date() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(bash(&["a.txt"], &[], "echo a >> log.txt; echo a > a.txt")).unwrap();
    db.add(bash(&["b.txt"], &["a.txt"], "echo b >> log.txt; cat a.txt > b.txt")).unwrap();
    let db = Arc::new(db);

    run(&db, "b.txt").unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\nb\n");
    assert_eq!(read(&dir, "b.txt"), "a\n");

    run(&db, "b.txt").unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\nb\n");

    // make `b.txt` older than `a.txt`
    let earlier = SystemTime::now() - Duration::from_secs(10);
    fs::File::options().write(true).open(dir.path().join("b.txt")).unwrap().set_modified(earlier).unwrap();
    run(&db, "b.txt").unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\nb\nb\n");
}
}

Variables pass values between rules, through standard output and input.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn variables() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(Rule { stdout: Some(target("var(greeting)")), ..rule(&[], &[], "echo hello world") }).unwrap();
    db.add(Rule {
        stdin: Some(target("var(greeting)")),
        stdout: Some(target("shout.txt")),
        ..rule(&[], &[], "tr a-z A-Z")
    }).unwrap();
    db.add(Rule { stdout: Some(target("listvar(files)")), ..rule(&[], &[], r"printf 'a\nb\n\nc\n'") }).unwrap();
    let db = Arc::new(db);

    assert_eq!(run(&db, "var(greeting)").unwrap(), Value::Scalar("hello world".into()));
    run(&db, "shout.txt").unwrap();
    assert_eq!(read(&dir, "shout.txt"), "HELLO WORLD");
    assert_eq!(run(&db, "listvar(files)").unwrap(), Value::List(vec!["a".into(), "b".into(), "c".into()]));
}
}

A rule that writes to a variable and also creates a file runs every time, so that the variable has a value, even when the file is up to date.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn variable_and_file() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(Rule { stdout: Some(target("var(x)")), ..bash(&["x.txt"], &[], "touch x.txt; echo x") }).unwrap();
    let db = Arc::new(db);

    assert_eq!(run(&db, "var(x)").unwrap(), Value::Scalar("x".into()));
    assert_eq!(run(&db, "var(x)").unwrap(), Value::Scalar("x".into()));
}
}

A rule that creates several targets runs once, even when its targets are built in parallel. Its value can be reached through any of its targets.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn several_targets() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(bash(&["a.txt", "b.txt", "c.txt"], &[], "echo run >> log.txt; touch a.txt b.txt c.txt")).unwrap();
    db.add(Rule { name: Some("all".into()), requires: targets(&["a.txt", "b.txt", "c.txt"]), ..Default::default() }).unwrap();
    db.add(Rule { name: Some("answer".into()), stdout: Some(target("var(answer)")), ..rule(&[], &[], "echo 42") }).unwrap();
    let db = Arc::new(db);

    let id = db.targets.lookup(&target("#all")).unwrap();
    build(&db, &mut Kernel::new(), &WorkerPool::new(4), id).unwrap();
    assert_eq!(read(&dir, "log.txt"), "run\n");

    // `#answer` is the main target, `var(answer)` is an alias.
    assert_eq!(run(&db, "var(answer)").unwrap(), Value::Scalar("42".into()));
}
}

Dependencies that are files without a rule are fine, as long as they exist.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn missing_dependency() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("input.txt"), "data").unwrap();
    let db = TaskDb::new(dir.path());
    db.add(rule(&["copy.txt"], &["input.txt"], "cp input.txt copy.txt")).unwrap();
    db.add(rule(&["other.txt"], &["nothere.txt"], "touch other.txt")).unwrap();
    let db = Arc::new(db);

    run(&db, "copy.txt").unwrap();
    assert_eq!(read(&dir, "copy.txt"), "data");
    assert_eq!(failures(run(&db, "other.txt")), [Failure::Missing(target("nothere.txt"))]);
    assert_eq!(failures(run(&db, "#nothing")), [Failure::Missing(target("#nothing"))]);
}
}

A failing command fails the rule, and so does a rule that doesn’t create its targets. Failures say which rule they come from.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn failing_rules() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(rule(&["x.txt"], &[], "false")).unwrap();
    db.add(rule(&["y.txt"], &[], "true")).unwrap();
    db.add(rule(&["z.txt"], &[], "no-such-command")).unwrap();
    let db = Arc::new(db);

    assert_eq!(failures(run(&db, "x.txt")), [in_rule("creating `x.txt`", Failure::Command { command: "false".into(), code: Some(1) })]);
    assert_eq!(failures(run(&db, "y.txt")), [in_rule("creating `y.txt`", Failure::NotAchieved(targets(&["y.txt"])))]);
    let z = failures(run(&db, "z.txt"));
    assert!(matches!(&z[..], [Failure::Rule(_, f)] if matches!(&**f, Failure::Io(msg) if msg.contains("no-such-command"))));
    assert_eq!(z[0].to_string(), "creating `z.txt`: can't run `no-such-command`: command not found");
}
}

When one rule fails, a slow command that runs in parallel is killed.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn cancel() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(rule(&["slow.txt"], &[], "sleep 10")).unwrap();
    db.add(rule(&["fail.txt"], &[], "false")).unwrap();
    db.add(Rule { name: Some("all".into()), requires: targets(&["slow.txt", "fail.txt"]), ..Default::default() }).unwrap();
    let db = Arc::new(db);

    let start = Instant::now();
    let id = db.targets.lookup(&target("#all")).unwrap();
    assert!(build(&db, &mut Kernel::new(), &WorkerPool::new(2), id).is_err());
    assert!(start.elapsed() < Duration::from_secs(5));
}
}

A cancelled command is killed with everything it started. Here the runner, bash, starts sleep, which should be killed as well. To see if sleep is still running, we look in /proc, so this test only runs on Linux. A killed process may still be around for a moment, as a zombie, until it is cleaned up.

#![allow(unused)]
fn main() {
//| id: task-tests
#[cfg(target_os = "linux")]
#[test]
fn kill_group() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(bash(&["slow.txt"], &[], "sleep 30 & echo $! > sleep.pid; wait")).unwrap();
    db.add(bash(&["fail.txt"], &[], "while [ ! -s sleep.pid ]; do sleep 0.01; done; false")).unwrap();
    db.add(Rule { name: Some("all".into()), requires: targets(&["slow.txt", "fail.txt"]), ..Default::default() }).unwrap();
    let db = Arc::new(db);

    let id = db.targets.lookup(&target("#all")).unwrap();
    assert!(build(&db, &mut Kernel::new(), &WorkerPool::new(2), id).is_err());
    let pid = read(&dir, "sleep.pid");
    let alive = || fs::read_to_string(format!("/proc/{}/stat", pid.trim()))
        .is_ok_and(|stat| stat.rsplit(") ").next().is_some_and(|rest| !rest.starts_with('Z')));
    let start = Instant::now();
    while alive() && start.elapsed() < Duration::from_secs(2) {
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(!alive(), "`sleep` is still running");
}
}

Mistakes in rules are found when they are added.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn invalid_rules() {
    let db = TaskDb::new(".");
    db.add(rule(&["a.txt"], &[], "true")).unwrap();
    assert_eq!(db.add(rule(&["a.txt"], &[], "true")), Err(RuleError::Duplicate(target("a.txt"))));

    db.add(Rule { stdout: Some(target("listvar(x)")), ..rule(&[], &[], "true") }).unwrap();
    assert!(matches!(db.add(Rule { stdin: Some(target("var(x)")), ..rule(&["b.txt"], &[], "cat") }),
        Err(RuleError::TypeMismatch(_))));

    let invalid = [
        Rule { stdin: Some(target("#a")), ..rule(&["c.txt"], &[], "cat") },
        Rule { stdout: Some(target("#a")), ..rule(&[], &[], "true") },
        Rule { path: Some("script.py".into()), ..Rule::default() },
        Rule { runner: Some("bash".into()), ..Rule::default() },
        Rule { stdin: Some(target("in.txt")), ..rule(&["d.txt"], &[], "cat\ncat") },
    ];
    for r in invalid {
        assert!(matches!(db.add(r), Err(RuleError::Invalid(_))));
    }
}
}

Runners can only use ${script} in their arguments.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn runner_arguments() {
    let db = TaskDb::new(".");
    let runner = |args: &[&str]| Runner { command: "lua".into(), args: args.iter().map(|a| a.to_string()).collect() };
    db.add_runner("lua", runner(&["-W", "${script}"])).unwrap();
    assert_eq!(db.add_runner("lua", runner(&["${script}", "${other}"])),
        Err(RuleError::Invalid("its arguments use `${other}`, but only `${script}` can be used".into())));
}
}

The history carries over to a new database, through the history file. A rule whose script changed runs again, and so does a rule that failed last time.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn persistent_history() {
    let dir = TempDir::new().unwrap();
    let rules = |script: &str| {
        let db = TaskDb::new(dir.path());
        db.add(bash(&["a.txt"], &[], &format!("echo {script} >> log.txt; echo {script} > a.txt"))).unwrap();
        db.add(bash(&["b.txt"], &[], "echo b >> log.txt; [ -e ok ] && touch b.txt")).unwrap();
        db.load_history(HISTORY_FILE).unwrap();
        Arc::new(db)
    };

    let db = rules("a");
    run(&db, "a.txt").unwrap();
    assert!(run(&db, "b.txt").is_err());
    db.save_history(HISTORY_FILE).unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\nb\n");

    // `a.txt` is up to date, `b.txt` failed so it runs again.
    fs::write(dir.path().join("ok"), "").unwrap();
    let db = rules("a");
    run(&db, "a.txt").unwrap();
    run(&db, "b.txt").unwrap();
    db.save_history(HISTORY_FILE).unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\nb\nb\n");

    // a different script for `a.txt`
    let db = rules("A");
    run(&db, "a.txt").unwrap();
    run(&db, "b.txt").unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\nb\nb\nA\n");

    fs::write(dir.path().join(HISTORY_FILE), "not json").unwrap();
    assert!(TaskDb::new(dir.path()).load_history(HISTORY_FILE).is_err());
}
}

Several targets are built in one run, in parallel, sharing their dependencies. Naming a target twice is fine. With keep_going, a failing target doesn’t stop the others.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn build_several() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add(bash(&["a.txt"], &[], "echo a >> log.txt; touch a.txt")).unwrap();
    db.add(bash(&["b.txt"], &["a.txt"], "touch b.txt")).unwrap();
    db.add(bash(&["c.txt"], &["a.txt"], "touch c.txt")).unwrap();
    db.add(rule(&["x.txt"], &[], "false")).unwrap();
    let db = Arc::new(db);
    let ids = |ts: &[&str]| ts.iter().map(|t| db.targets.lookup(&target(t)).unwrap()).collect::<Vec<_>>();

    build_all(&db, &mut Kernel::new(), &WorkerPool::new(4), &ids(&["b.txt", "c.txt", "b.txt"])).unwrap();
    assert_eq!(read(&dir, "log.txt"), "a\n");
    assert!(dir.path().join("b.txt").exists() && dir.path().join("c.txt").exists());
    build_all(&db, &mut Kernel::new(), &SingleWorker::new(), &[]).unwrap();

    fs::remove_file(dir.path().join("b.txt")).unwrap();
    fs::remove_file(dir.path().join("c.txt")).unwrap();
    let result = build_all(&db, &mut Kernel::new().keep_going(), &SingleWorker::new(), &ids(&["x.txt", "b.txt", "c.txt"]));
    assert_eq!(failures(result.map(|_| Value::Nothing)), [in_rule("creating `x.txt`", Failure::Command { command: "false".into(), code: Some(1) })]);
    assert!(dir.path().join("b.txt").exists() && dir.path().join("c.txt").exists());
}
}

Templates

A variable from the environment is a template string, which may use other variables. Templates use variables in any field, and are expanded when they run.

#![allow(unused)]
fn main() {
//| id: task-tests
fn template(creates: &[&str], requires: &[&str], script: &str) -> RuleTemplate {
    let strings = |ts: &[&str]| ts.iter().map(|t| t.to_string()).collect();
    RuleTemplate { creates: strings(creates), requires: strings(requires), script: Some(script.into()), ..Default::default() }
}

#[test]
fn environment() {
    let dir = TempDir::new().unwrap();
    fs::create_dir(dir.path().join("data")).unwrap();
    fs::write(dir.path().join("data/input.txt"), "hello").unwrap();
    let db = TaskDb::new(dir.path());
    db.add_variable("dir", "data").unwrap();
    db.add_variable("input", "${dir}/input.txt").unwrap();
    db.add(Rule { stdout: Some(target("var(output)")), ..rule(&[], &[], "echo output.txt") }).unwrap();
    db.add_template(template(&["output.txt"], &["${input}"], "cp ${input} ${output}")).unwrap();
    let db = Arc::new(db);

    assert_eq!(run(&db, "var(input)").unwrap(), Value::Scalar("data/input.txt".into()));
    run(&db, "output.txt").unwrap();
    assert_eq!(read(&dir, "output.txt"), "hello");
}
}

The output of a template rule can go to a variable, and the values of variables are substituted in stdin too. A literal dollar sign is written $$, also in a rule without variables, and a dollar sign that doesn’t start a variable stays as it is.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn template_variables() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add_variable("name", "greeting").unwrap();
    db.add(Rule { stdout: Some(target("var(greeting)")), ..rule(&[], &[], "echo hello") }).unwrap();
    db.add_template(RuleTemplate {
        stdin: Some("var(${name})".into()), stdout: Some("var(shout)".into()), ..template(&[], &[], "tr a-z A-Z")
    }).unwrap();
    db.add_template(RuleTemplate { stdout: Some("var(dollars)".into()), ..template(&[], &[], "echo $$1 $1 $(x)") }).unwrap();
    let db = Arc::new(db);

    assert_eq!(run(&db, "var(shout)").unwrap(), Value::Scalar("HELLO".into()));
    assert_eq!(run(&db, "var(dollars)").unwrap(), Value::Scalar("$1 $1 $(x)".into()));
}
}

Splicing a list variable into requires makes all its elements dependencies. These targets are only known at run time.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn splice() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("c.txt"), "c\n").unwrap();
    let db = TaskDb::new(dir.path());
    db.add(Rule { stdout: Some(target("listvar(files)")), ..rule(&[], &[], r"printf 'a.txt\nb.txt\nc.txt\n'") }).unwrap();
    db.add(bash(&["a.txt"], &[], "echo a > a.txt")).unwrap();
    db.add(bash(&["b.txt"], &[], "echo b > b.txt")).unwrap();
    db.add_template(RuleTemplate {
        runner: Some("bash".into()),
        ..template(&["all.txt"], &["splice(files)"], "cat a.txt b.txt c.txt > all.txt")
    }).unwrap();
    db.add_template(template(&["d.txt"], &["splice(files)", "nothere.txt"], "touch d.txt")).unwrap();
    let db = Arc::new(db);

    run(&db, "all.txt").unwrap();
    assert_eq!(read(&dir, "all.txt"), "a\nb\nc\n");
    assert_eq!(failures(run(&db, "d.txt")), [Failure::Missing(target("nothere.txt"))]);
}
}

Templates fail when the variables they use are missing. Mistakes are found when a template is added, where possible: variables in targets, list variables in the wrong places, or a variable that is used both as a scalar and as a list.

#![allow(unused)]
fn main() {
//| id: task-tests
#[test]
fn invalid_templates() {
    let dir = TempDir::new().unwrap();
    let db = TaskDb::new(dir.path());
    db.add_template(template(&["a.txt"], &[], "touch ${unknown}")).unwrap();
    db.add_variable("x", "${y}").unwrap();
    assert_eq!(db.add_variable("x", "1"), Err(RuleError::Duplicate(target("var(x)"))));
    db.add(Rule { stdout: Some(target("listvar(list)")), ..rule(&[], &[], "true") }).unwrap();
    assert!(matches!(db.add_template(template(&["b.txt"], &[], "echo ${list}")), Err(RuleError::TypeMismatch(_))));
    assert!(matches!(db.add_template(template(&["b.txt"], &["splice(x)"], "true")), Err(RuleError::TypeMismatch(_))));

    let invalid = [
        template(&["${x}.txt"], &[], "true"),
        RuleTemplate { name: Some("${x}".into()), ..template(&[], &[], "true") },
        template(&["c.txt"], &["listvar(list)"], "true"),
        template(&["listvar(list)"], &[], "true"),
        template(&["splice(list)"], &[], "true"),
        RuleTemplate { stdin: Some("splice(list)".into()), ..template(&["c.txt"], &[], "cat") },
    ];
    for t in invalid {
        assert!(matches!(db.add_template(t), Err(RuleError::Invalid(_))));
    }

    let db = Arc::new(db);
    assert_eq!(failures(run(&db, "a.txt")), [Failure::Missing(target("var(unknown)"))]);
    assert_eq!(failures(run(&db, "var(x)")), [Failure::Missing(target("var(y)"))]);
}
}

Programs

A Brei program is more than a list of rules. It also has:

  • an environment of variables, whose values are template strings;
  • templates: rules with variables, that are filled in by a call;
  • includes of other programs, which may have to be built by a rule first;
  • extra runners.

Before we can build anything, these have to be resolved into recipes in the task database. This is the Python resolve_tasks. Programs are read from TOML or JSON by the loader; here, included programs are read by a function that is passed in, so that resolution doesn’t depend on a file format.

Programs are deserialized with serde. Unknown fields are an error, so that a typo doesn’t silently get ignored. The fields of a rule are those of RuleTemplate, and those of a runner are command and args.

#![allow(unused)]
fn main() {
//| file: src/tasks/program.rs
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde::Deserialize;
use crate::noodles::kernel::Kernel;
use crate::noodles::task::{Error, Worker};
use crate::template_strings::Env;
use super::db::TaskDb;
use super::job::{Job, build, build_all};
use super::rule::{RuleError, Runner, Value};
use super::target::{Target, TypeMismatch, VarType};
use super::template::{RuleTemplate, escape, splice_name, substitute, variables};

<<program-types>>
<<program-error>>
<<program-call>>
<<program-resolve>>

#[cfg(test)]
mod tests {
    <<program-tests>>
}
}

The program

A call fills in a template with arguments. An argument is a string or a list of strings. With lists, the template is filled in once for each element. If there are several lists, they are either zipped (an inner join, the default), or every combination is used (an outer join). collect names a phony target that requires all targets of the call.

#![allow(unused)]
fn main() {
//| id: program-types
/// A Brei program: the contents of a workflow file.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Program {
    /// The tasks.
    pub task: Vec<RuleTemplate>,
    /// Variables with a fixed value, a template string.
    pub environment: BTreeMap<String, String>,
    /// Templates, by name, to be filled in by calls.
    pub template: HashMap<String, RuleTemplate>,
    /// Calls of templates.
    pub call: Vec<Call>,
    /// Paths of other programs to include, template strings.
    pub include: Vec<String>,
    /// Extra runners, by name.
    pub runner: HashMap<String, Runner>,
}

/// How a call combines arguments that are lists.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Join {
    /// The first elements of all lists, then the second, and so on.
    #[default]
    Inner,
    /// Every combination of elements.
    Outer,
}

/// An argument of a call.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum Argument {
    /// A single value.
    Single(String),
    /// A list of values: the template is filled in for each.
    Multiple(Vec<String>),
}

/// A call of a template.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Call {
    /// The name of the template.
    pub template: String,
    /// The values of the variables of the template.
    pub args: BTreeMap<String, Argument>,
    /// The name of a phony target that requires all targets of the call.
    #[serde(default)]
    pub collect: Option<String>,
    /// How to combine arguments that are lists.
    #[serde(default)]
    pub join: Join,
}
}

Errors

Resolving a program can fail in many ways: a rule can be wrong, a template or include can be missing, or a rule that computes a variable we need can fail. When a rule is wrong, the error says which one, using RuleTemplate::label.

#![allow(unused)]
fn main() {
//| id: program-error
#[derive(Debug)]
pub enum ProgramError {
    Rule(String, RuleError),
    TypeMismatch(TypeMismatch),
    MissingTemplate(String),
    MissingInclude(PathBuf),
    Load(PathBuf, String),
    Call(String, String),
    NoValue(Target),
    Unresolvable(Vec<String>),
    Build(Error<Job>),
}

impl From<TypeMismatch> for ProgramError {
    fn from(e: TypeMismatch) -> Self {
        ProgramError::TypeMismatch(e)
    }
}

impl From<Error<Job>> for ProgramError {
    fn from(e: Error<Job>) -> Self {
        ProgramError::Build(e)
    }
}

impl fmt::Display for ProgramError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProgramError::Rule(rule, e) => write!(f, "in {rule}: {e}"),
            ProgramError::TypeMismatch(e) => write!(f, "{e}"),
            ProgramError::MissingTemplate(name) => write!(f, "template `{name}` not found"),
            ProgramError::MissingInclude(path) => write!(f, "include `{}` not found", path.display()),
            ProgramError::Load(path, msg) => write!(f, "can't read `{}`: {msg}", path.display()),
            ProgramError::Call(name, msg) => write!(f, "in call to template `{name}`: {msg}"),
            ProgramError::NoValue(t) => write!(f, "`{t}` has no value"),
            ProgramError::Unresolvable(targets) => write!(f, "rules have unresolvable targets: {}", targets.join(", ")),
            ProgramError::Build(Error::Jobs(failures)) => {
                let failures: Vec<String> = failures.iter().map(|e| e.to_string()).collect();
                write!(f, "{}", failures.join("; "))
            }
            ProgramError::Build(e) => write!(f, "{e:?}"),
        }
    }
}
}

Calls

The arguments of a call are template strings themselves. For instance, an argument "${dir}/output.txt" uses the environment variable dir. So we fill in the arguments with RuleTemplate::fill, which leaves the other variables for later.

An inner join of lists with different lengths is an error. Lists can come from list variables, so silently dropping elements would hide mistakes.

#![allow(unused)]
fn main() {
//| id: program-call
impl Call {
    /// The arguments for each time the template is filled in.
    fn instances(&self) -> Result<Vec<Env>, ProgramError> {
        let mut single = Env::new();
        let mut lists = Vec::new();
        for (key, arg) in &self.args {
            match arg {
                Argument::Single(s) => { single.insert(key.clone(), s.clone()); }
                Argument::Multiple(l) => lists.push((key, l)),
            }
        }

        match self.join {
            Join::Inner => {
                let lengths: BTreeSet<usize> = lists.iter().map(|(_, l)| l.len()).collect();
                if lengths.len() > 1 {
                    let lengths: Vec<String> = lists.iter().map(|(k, l)| format!("{k}: {}", l.len())).collect();
                    let msg = format!("the arguments of an inner join should have the same length, got {}", lengths.join(", "));
                    return Err(ProgramError::Call(self.template.clone(), msg));
                }
                let n = lengths.first().copied().unwrap_or(1);
                Ok((0..n).map(|i| {
                    let mut env = single.clone();
                    env.extend(lists.iter().map(|(k, l)| (k.to_string(), l[i].clone())));
                    env
                }).collect())
            }
            Join::Outer => {
                let mut envs = vec![single];
                for (key, list) in lists {
                    envs = envs.into_iter().flat_map(|env| list.iter().map(move |v| {
                        let mut env = env.clone();
                        env.insert(key.clone(), v.clone());
                        env
                    })).collect();
                }
                Ok(envs)
            }
        }
    }

    /// Names of the list variables spliced into the arguments.
    fn splices(&self) -> BTreeSet<&str> {
        self.args.values().flat_map(|arg| match arg {
            Argument::Single(s) => std::slice::from_ref(s),
            Argument::Multiple(l) => l.as_slice(),
        }).filter_map(|s| splice_name(s)).collect()
    }

    /// The rules from filling in `template`, plus the collecting rule.
    fn expand(&self, template: &RuleTemplate) -> Result<Vec<RuleTemplate>, ProgramError> {
        let mut rules: Vec<RuleTemplate> = self.instances()?.iter().map(|env| template.fill(env)).collect();
        if let Some(name) = &self.collect {
            let requires = rules.iter().flat_map(|r| r.targets()).collect();
            rules.push(RuleTemplate { name: Some(name.clone()), requires, ..Default::default() });
        }
        Ok(rules)
    }
}
}

Resolving

Resolving a program needs to run tasks, so the resolver holds a kernel and a worker. The kernel remembers the values it computed, so when the same kernel is used to build the targets afterwards, the rules that were run during resolution aren’t run again. That matters: a rule like mktemp -d gives a different value every time.

The order of resolution follows the Python version:

  1. Add the environment and the runners.
  2. Fill in the calls. A call has to wait if its template isn’t known yet (it may be in an include), or if it splices list variables.
  3. Add the rules. A rule with variables in its targets has to wait: we can’t know what it creates before we know the values of those variables.
  4. Resolve the waiting rules whose target variables are created by a known recipe. These variables are computed, the values are filled in, and the rule is added.
  5. Read the includes, and resolve them in turn. An include can be built by a rule.
  6. Fill in the calls that had to wait, and add or delay their rules.
  7. Resolve the waiting rules again. Any rule that is still waiting is an error.

The variables in the targets of a delayed rule should be computable from rules that don’t have variables in their targets themselves. That way, the order of the rules doesn’t matter.

#![allow(unused)]
fn main() {
//| id: program-resolve
struct Resolver<'a, W: Worker<Job>> {
    db: &'a Arc<TaskDb>,
    kernel: &'a mut Kernel<Job>,
    worker: &'a W,
    load: &'a dyn Fn(&Path) -> Result<Program, String>,
    templates: HashMap<String, RuleTemplate>,
}

fn scalar(name: &str) -> Target {
    Target::Variable(name.to_string(), VarType::Scalar)
}

/// Add the recipes of `program` to the database. Included programs are read with `load`.
pub fn resolve<W: Worker<Job>>(
    db: &Arc<TaskDb>, kernel: &mut Kernel<Job>, worker: &W, program: Program,
    load: &dyn Fn(&Path) -> Result<Program, String>,
) -> Result<(), ProgramError> {
    Resolver { db, kernel, worker, load, templates: HashMap::new() }.resolve(program)
}

impl<'a, W: Worker<Job>> Resolver<'a, W> {
    <<resolver-values>>
    <<resolver-resolve>>
}
}

To get the values of variables, we build them all at once, and then ask for them one by one. The second time, the values come straight from the memo of the kernel. Rules that write to a variable always run, so every variable that comes out of a rule has a value.

#![allow(unused)]
fn main() {
//| id: resolver-values
fn values(&mut self, targets: &[Target]) -> Result<Vec<Value>, ProgramError> {
    let ids = targets.iter().map(|t| self.db.targets.intern(t)).collect::<Result<Vec<_>, _>>()?;
    build_all(self.db, self.kernel, self.worker, &ids)?;
    ids.iter().map(|id| Ok(build(self.db, self.kernel, self.worker, *id)?)).collect()
}

/// The values of scalar variables.
fn env<'s>(&mut self, names: impl IntoIterator<Item=&'s str>) -> Result<Env, ProgramError> {
    let targets: Vec<Target> = names.into_iter().map(scalar).collect();
    let values = self.values(&targets)?;
    targets.into_iter().zip(values).map(|(t, v)| match (t, v) {
        (Target::Variable(name, _), Value::Scalar(s)) => Ok((name, s)),
        (t, _) => Err(ProgramError::NoValue(t)),
    }).collect()
}

/// The values of list variables.
fn lists<'s>(&mut self, names: impl IntoIterator<Item=&'s str>) -> Result<HashMap<String, Vec<String>>, ProgramError> {
    let targets: Vec<Target> = names.into_iter().map(|n| Target::Variable(n.to_string(), VarType::List)).collect();
    let values = self.values(&targets)?;
    targets.into_iter().zip(values).map(|(t, v)| match (t, v) {
        (Target::Variable(name, _), Value::List(l)) => Ok((name, l)),
        (t, _) => Err(ProgramError::NoValue(t)),
    }).collect()
}
}

The values of variables are literal strings, but filling them into a rule gives a template again, so they are escaped.

#![allow(unused)]
fn main() {
//| id: resolver-resolve
/// Whether the variables in the targets of `rule` can be computed.
fn resolvable(&self, rule: &RuleTemplate) -> bool {
    rule.target_variables().into_iter().all(|v| self.db.creates(&scalar(v)))
}

/// Add the rules with resolvable targets, and give back the others.
fn resolve_delayed(&mut self, delayed: Vec<RuleTemplate>) -> Result<Vec<RuleTemplate>, ProgramError> {
    let (ready, waiting): (Vec<_>, Vec<_>) = delayed.into_iter().partition(|r| self.resolvable(r));
    let names: BTreeSet<String> = ready.iter().flat_map(|r| r.target_variables()).map(String::from).collect();
    let env: Env = self.env(names.iter().map(String::as_str))?.into_iter().map(|(k, v)| (k, escape(&v))).collect();
    for rule in ready {
        let rule = rule.fill_targets(&env);
        log::debug!("resolved the targets of {}", rule.label());
        self.add_rule(rule)?;
    }
    Ok(waiting)
}

fn add_rule(&self, rule: RuleTemplate) -> Result<(), ProgramError> {
    let label = rule.label();
    self.db.add_template(rule).map_err(|e| ProgramError::Rule(label, e))
}

/// Add rules, or delay them if their targets have variables.
fn add(&mut self, rules: Vec<RuleTemplate>, delayed: &mut Vec<RuleTemplate>) -> Result<(), ProgramError> {
    for rule in rules {
        if rule.target_variables().is_empty() {
            self.add_rule(rule)?;
        } else {
            delayed.push(rule);
        }
    }
    Ok(())
}

/// Replace `splice(name)` in the arguments with the elements of the list variable.
fn splice(&mut self, call: Call) -> Result<Call, ProgramError> {
    let lists = self.lists(call.splices())?;
    let expand = |s: &String| match splice_name(s) {
        Some(name) => lists[name].clone(),
        None => vec![s.clone()],
    };
    let args = call.args.iter().map(|(k, arg)| (k.clone(), match arg {
        Argument::Single(s) if splice_name(s).is_some() => Argument::Multiple(expand(s)),
        Argument::Single(s) => Argument::Single(s.clone()),
        Argument::Multiple(l) => Argument::Multiple(l.iter().flat_map(expand).collect()),
    })).collect();
    Ok(Call { args, ..call })
}

fn include(&mut self, include: &str) -> Result<(), ProgramError> {
    let env = self.env(variables(include))?;
    let path = PathBuf::from(substitute(include, &env).expect("all variables are known"));
    let target = Target::path(&path);
    if self.db.creates(&target) {
        self.values(&[target])?;
    }
    log::debug!("including `{}`", path.display());
    let full = self.db.root.join(&path);
    if !full.exists() {
        return Err(ProgramError::MissingInclude(path));
    }
    let program = (self.load)(&full).map_err(|e| ProgramError::Load(path, e))?;
    self.resolve(program)
}

fn resolve(&mut self, program: Program) -> Result<(), ProgramError> {
    for (name, template) in &program.environment {
        self.db.add_variable(name, template)
            .map_err(|e| ProgramError::Rule(format!("environment variable `{name}`"), e))?;
    }
    for (name, runner) in program.runner {
        self.db.add_runner(&name, runner)
            .map_err(|e| ProgramError::Rule(format!("runner `{name}`"), e))?;
    }
    self.templates.extend(program.template);

    let mut rules = program.task;
    let mut delayed_calls = Vec::new();
    for call in program.call {
        match self.templates.get(&call.template) {
            Some(template) if call.splices().is_empty() => rules.extend(call.expand(template)?),
            _ => {
                log::debug!("call to `{}` waits for includes or list variables", call.template);
                delayed_calls.push(call);
            }
        }
    }
    let mut delayed = Vec::new();
    self.add(rules, &mut delayed)?;
    delayed = self.resolve_delayed(delayed)?;

    for include in &program.include {
        self.include(include)?;
    }

    for call in delayed_calls {
        let Some(template) = self.templates.get(&call.template).cloned() else {
            return Err(ProgramError::MissingTemplate(call.template));
        };
        let rules = self.splice(call)?.expand(&template)?;
        self.add(rules, &mut delayed)?;
    }

    delayed = self.resolve_delayed(delayed)?;
    if !delayed.is_empty() {
        let targets = delayed.iter().flat_map(|r| r.targets()).collect();
        return Err(ProgramError::Unresolvable(targets));
    }
    Ok(())
}
}

Tests

#![allow(unused)]
fn main() {
//| id: program-tests
use std::fs;
use std::path::Path;
use std::sync::Arc;
use tempfile::TempDir;
use crate::noodles::kernel::Kernel;
use crate::noodles::single_worker::SingleWorker;
use crate::tasks::{TaskDb, RuleTemplate, Value, build_all, build};
use super::*;

fn strings(ss: &[&str]) -> Vec<String> {
    ss.iter().map(|s| s.to_string()).collect()
}

fn rule(creates: &[&str], requires: &[&str], script: &str) -> RuleTemplate {
    RuleTemplate { creates: strings(creates), requires: strings(requires), script: Some(script.into()), ..Default::default() }
}

fn bash(creates: &[&str], requires: &[&str], script: &str) -> RuleTemplate {
    RuleTemplate { runner: Some("bash".into()), ..rule(creates, requires, script) }
}

fn call(template: &str, args: &[(&str, Argument)]) -> Call {
    let args = args.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
    Call { template: template.into(), args, ..Default::default() }
}

fn single(s: &str) -> Argument {
    Argument::Single(s.into())
}

fn multiple(ss: &[&str]) -> Argument {
    Argument::Multiple(strings(ss))
}

fn no_includes(path: &Path) -> Result<Program, String> {
    Err(format!("unexpected include {}", path.display()))
}

struct Setup {
    dir: TempDir,
    db: Arc<TaskDb>,
    kernel: Kernel<Job>,
    worker: SingleWorker<Job>,
}

impl Setup {
    fn new() -> Self {
        let dir = TempDir::new().unwrap();
        let db = Arc::new(TaskDb::new(dir.path()));
        Setup { dir, db, kernel: Kernel::new(), worker: SingleWorker::new() }
    }

    fn resolve(&mut self, program: Program, load: &dyn Fn(&Path) -> Result<Program, String>) -> Result<(), ProgramError> {
        resolve(&self.db, &mut self.kernel, &self.worker, program, load)
    }

    fn build(&mut self, targets: &[&str]) {
        let ids: Vec<_> = targets.iter().map(|t| self.db.targets.lookup(&t.parse().unwrap()).unwrap()).collect();
        build_all(&self.db, &mut self.kernel, &self.worker, &ids).unwrap();
    }

    fn value(&mut self, target: &str) -> Value {
        let id = self.db.targets.lookup(&target.parse().unwrap()).unwrap();
        build(&self.db, &mut self.kernel, &self.worker, id).unwrap()
    }

    fn read(&self, path: &str) -> String {
        fs::read_to_string(self.dir.path().join(path)).unwrap()
    }
}
}

Calls fill in templates. Arguments can use variables from the environment, and lists give a rule for each element. With collect, a phony target builds them all.

#![allow(unused)]
fn main() {
//| id: program-tests
#[test]
fn calls() {
    let mut s = Setup::new();
    let program = Program {
        environment: [("ext".to_string(), "txt".to_string())].into(),
        template: [("write".to_string(), rule(&["${name}.${ext}"], &[], "touch ${name}.${ext}"))].into(),
        call: vec![
            Call { collect: Some("letters".into()), ..call("write", &[("name", multiple(&["a", "b"]))]) },
            call("write", &[("name", single("c"))]),
        ],
        ..Default::default()
    };
    s.resolve(program, &no_includes).unwrap();
    s.build(&["#letters", "c.txt"]);
    for f in ["a.txt", "b.txt", "c.txt"] {
        assert!(s.dir.path().join(f).exists());
    }
}

#[test]
fn joins() {
    let args = [("x", multiple(&["1", "2"])), ("y", multiple(&["a", "b"])), ("z", single("-"))];
    let inner = call("t", &args).instances().unwrap();
    let pairs: Vec<String> = inner.iter().map(|e| format!("{}{}{}", e["x"], e["y"], e["z"])).collect();
    assert_eq!(pairs, ["1a-", "2b-"]);

    let outer = Call { join: Join::Outer, ..call("t", &args) }.instances().unwrap();
    let pairs: Vec<String> = outer.iter().map(|e| format!("{}{}", e["x"], e["y"])).collect();
    assert_eq!(pairs, ["1a", "1b", "2a", "2b"]);

    let uneven = call("t", &[("x", multiple(&["1", "2"])), ("y", multiple(&["a"]))]);
    assert!(matches!(uneven.instances(), Err(ProgramError::Call(..))));
}
}

A rule with a variable in its targets waits until the variable is known. The rule that computes the variable runs only once, also when its value is needed again to build the targets.

#![allow(unused)]
fn main() {
//| id: program-tests
#[test]
fn delayed_targets() {
    let mut s = Setup::new();
    let program = Program {
        task: vec![
            RuleTemplate { stdout: Some("var(dir)".into()), ..bash(&[], &[], "echo run >> log.txt; mkdir -p out; echo out") },
            RuleTemplate { name: Some("all".into()), ..rule(&[], &["${dir}/msg.txt"], "") },
        ],
        template: [("echo".to_string(), RuleTemplate { stdout: Some("${out}".into()), ..rule(&[], &[], "echo ${text}") })].into(),
        call: vec![call("echo", &[("out", single("${dir}/msg.txt")), ("text", single("$$hello"))])],
        ..Default::default()
    };
    s.resolve(program, &no_includes).unwrap();
    s.build(&["#all"]);
    assert_eq!(s.read("out/msg.txt"), "$hello\n");
    assert_eq!(s.read("log.txt"), "run\n");
    assert_eq!(s.value("var(dir)"), Value::Scalar("out".into()));
}
}

Includes can be built by a rule, and their name can use variables. A call can use a template from an include.

#![allow(unused)]
fn main() {
//| id: program-tests
#[test]
fn includes() {
    let mut s = Setup::new();
    let program = Program {
        environment: [("name".to_string(), "generated".to_string())].into(),
        task: vec![RuleTemplate { stdout: Some("generated.txt".into()), ..rule(&[], &[], "echo hello") }],
        include: vec!["${name}.txt".into()],
        call: vec![call("greet", &[("who", single("world"))])],
        ..Default::default()
    };
    let load = |path: &Path| -> Result<Program, String> {
        let greeting = fs::read_to_string(path).map_err(|e| e.to_string())?;
        let greet = RuleTemplate { stdout: Some("var(greeting)".into()), ..rule(&[], &[], &format!("echo {} ${{who}}", greeting.trim())) };
        Ok(Program { template: [("greet".to_string(), greet)].into(), ..Default::default() })
    };
    s.resolve(program, &load).unwrap();
    assert_eq!(s.value("var(greeting)"), Value::Scalar("hello world".into()));
}
}

A call can splice list variables into its arguments.

#![allow(unused)]
fn main() {
//| id: program-tests
#[test]
fn splice_arguments() {
    let mut s = Setup::new();
    let program = Program {
        task: vec![RuleTemplate { stdout: Some("listvar(names)".into()), ..rule(&[], &[], r"printf 'a\nb\n'") }],
        template: [("touch".to_string(), rule(&["${name}.txt"], &[], "touch ${name}.txt"))].into(),
        call: vec![Call {
            collect: Some("all".into()),
            ..call("touch", &[("name", multiple(&["splice(names)", "c"]))])
        }],
        ..Default::default()
    };
    s.resolve(program, &no_includes).unwrap();
    s.build(&["#all"]);
    for f in ["a.txt", "b.txt", "c.txt"] {
        assert!(s.dir.path().join(f).exists());
    }
}
}

Missing templates, missing includes and targets that can’t be resolved are errors.

#![allow(unused)]
fn main() {
//| id: program-tests
#[test]
fn errors() {
    let missing_template = Program { call: vec![call("nothere", &[])], ..Default::default() };
    assert!(matches!(Setup::new().resolve(missing_template, &no_includes), Err(ProgramError::MissingTemplate(t)) if t == "nothere"));

    let missing_include = Program { include: vec!["nothere.toml".into()], ..Default::default() };
    assert!(matches!(Setup::new().resolve(missing_include, &no_includes), Err(ProgramError::MissingInclude(_))));

    let unresolvable = Program { task: vec![rule(&["${x}.txt"], &[], "true")], ..Default::default() };
    let err = Setup::new().resolve(unresolvable, &no_includes).unwrap_err();
    assert_eq!(err.to_string(), "rules have unresolvable targets: ${x}.txt");

    let failing = Program {
        task: vec![
            RuleTemplate { stdout: Some("var(x)".into()), ..rule(&[], &[], "false") },
            rule(&["${x}.txt"], &[], "true"),
        ],
        ..Default::default()
    };
    let err = Setup::new().resolve(failing, &no_includes).unwrap_err();
    assert_eq!(err.to_string(), "creating `var(x)`: `false` failed with exit code 1");
}
}

Template Strings

Brei supports template strings that expand variables that are written in a Bash-like syntax ${name} or $name. Most string formatting in Rust is done compile time, so here’s a small library that provides run-time template strings.

The reason we chose dollar signs over curly braces, is that we think this will require fewer character escapes in task definitions.

Some end-to-end tests:

#![allow(unused)]
fn main() {
//| id: end-to-end-test
#[test]
fn test_format() {
    let mut env = Env::new();
    env.insert(String::from("name"), String::from("Sara"));

    assert_eq!(
        dollar("Hallo, ${name}!").format(&env).unwrap(),
        "Hallo, Sara!");
    assert_eq!(
        dollar("Hallo, $name!").format(&env).unwrap(),
        "Hallo, Sara!");
    assert_eq!(
        dollar("$${${name}}").format(&env).unwrap(),
        "${Sara}");
    assert_eq!(
        dollar("${name{").format(&env).unwrap(),
        "${name{");
    assert!(matches!(
        dollar("${number}").format(&env),
        Err(Error::MissingVariable(n)) if n == "number"));
}
}

For this submodule we define a specialized error and result type:

#![allow(unused)]
fn main() {
//| file: src/template_strings/result.rs
#[derive(Debug)]
pub enum Error {
    InvalidTemplate(String),
    MissingVariable(String)
}

pub type Result<T> = core::result::Result<T, Error>;
}

We define a Format trait that provides the format method on implemented types. We need to pass an environment containing the string replacements.

#![allow(unused)]
fn main() {
//| file: src/template_strings/format.rs
use std::collections::HashMap;
use super::result::Result;

/// The `Env` type is used for passing variable bindings to the
/// `format` method.
pub type Env = HashMap<String, String>;

pub trait Format<'a> {
    type Output;

    fn format(self, env: &'a Env) -> Result<Self::Output>;
}
}

First, we decompose a given string into Items, being either a Literal or Variable part.

#![allow(unused)]
fn main() {
//| file: src/template_strings/item.rs
use super::result::{Result, Error};
use super::format::{Format, Env};

/// An `Item` refers to either a string literal or a variable
/// reference. `Item` implements the `Format` trait, with a `str`
/// output.
///
/// Any type that implements an iterator over `Item`
/// also implements the `Format` trait with a `String` output.
#[derive(Debug, PartialEq, Eq)]
pub enum Item<'a> {
    Literal(&'a str),
    Variable(&'a str)
}

<<format-item>>
}

We implement the Format trait for both Item and Iterator<Item=Result<Item>>>.

#![allow(unused)]
fn main() {
//| id: format-item
impl<'a> Format<'a> for &Item<'a> {
    type Output = &'a str;
    fn format(self, env: &'a Env) -> Result<Self::Output> {
        use Item::{Literal, Variable};
        use Error::MissingVariable;

        match *self {
            Literal(x) => Ok(x),
            Variable(n) => env.get(&n.to_string()).map(String::as_str)
                .ok_or(MissingVariable(n.to_string()))
        }
    }
}

impl<'a, T: Iterator<Item=Result<Item<'a>>>> Format<'a> for T {
    type Output = String;
    fn format(self, env: &'a Env) -> Result<Self::Output> {
        let mut result = String::new();
        for i in self {
            result.push_str(i?.format(env)?);
        }
        Ok(result)
    }
}
}

Now, all we need to do is write parsers that turn a string into an iterator of items. We have an implementation for curly brace syntax that is similar to many modern programming languages, and the dollar sign syntax for Brei. We leave the curly-brace syntax in for possible later use.

Curly (rust) syntax

#![allow(unused)]
fn main() {
//| file: src/template_strings/curly.rs
use std::iter::Iterator;
use super::result::{Result, Error};
use super::item::Item;

pub struct Curly<'a> {
    template: &'a str
}

pub fn curly<'a, S>(s: S) -> Curly<'a> where S: Into<&'a str> {
    Curly { template: s.into() }
}

impl<'a> Curly<'a> {
    fn flush(&mut self) -> &'a str {
        let (result, end) = self.template.split_at(self.template.len());
        self.template = end;
        result
    }

    fn error<T>(&mut self, msg: T) -> Result<Item<'a>>
    where T: ToString {
        self.flush();
        Err(Error::InvalidTemplate(msg.to_string()))
    }
}

impl<'a> Iterator for Curly<'a> {
    type Item = Result<Item<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        use Item::{Literal,Variable};

        if self.template.is_empty() {
            return None;
        }

        if self.template.get(..2) == Some("{{") {
            let (_, rest) = self.template.split_at(2);
            self.template = rest;
            return Some(Ok(Literal("{")));
        }

        if self.template.get(..2) == Some("}}") {
            let (_, rest) = self.template.split_at(2);
            self.template = rest;
            return Some(Ok(Literal("}")));
        }

        let (first, rest) = self.template.split_at(1);
        if first == "{" {
            if let Some((name, rest)) = rest.split_once('}') {
                self.template = rest;
                return Some(Ok(Variable(name)));
            }
            return Some(self.error("unterminated '{...'"));
        }

        if first == "}" {
            return Some(self.error("unexpected '}'"));
        }

        let idx = self.template.find(['{', '}'])
            .unwrap_or(self.template.len());
        let (result, rest) = self.template.split_at(idx);
        self.template = rest;
        Some(Ok(Literal(result)))
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use super::super::format::{Format, Env};
    use Item::{Literal, Variable};

    #[test]
    fn test_iterator() {
        let it1 = curly("Hello");
        let re1: Result<Vec<Item>> = it1.collect();
        assert_eq!(re1.unwrap(), vec![Literal("Hello")]);

        let it2 = curly("Hello, {name}!");
        let re2: Result<Vec<Item>> = it2.collect();
        assert_eq!(re2.unwrap(), vec![Literal("Hello, "), Variable("name"), Literal("!")]);

        let it3 = curly("Hello, }name{");
        let re3: Result<Vec<Item>> = it3.collect();
        assert!(matches!(re3, Err(Error::InvalidTemplate(_))));

        let it4 = curly("Hell, {name");
        let re4: Result<Vec<Item>> = it4.collect();
        assert!(matches!(re4, Err(Error::InvalidTemplate(_))));

        let it5 = curly("}} Literal {{");
        let re5: Result<Vec<Item>> = it5.collect();
        assert_eq!(re5.unwrap(), vec![Literal("}"), Literal(" Literal "), Literal("{")]);
    }

    #[test]
    fn test_format() {
        let mut env = Env::new();
        env.insert(String::from("name"), String::from("Sara"));

        assert_eq!(
            curly("Hallo, {name}!").format(&env).unwrap(),
            "Hallo, Sara!");
        assert_eq!(
            curly("{{{name}}}").format(&env).unwrap(),
            "{Sara}");
        assert!(matches!(
            curly("{{name}").format(&env),
            Err(Error::InvalidTemplate(_))));
        assert!(matches!(
            curly("{number}").format(&env),
            Err(Error::MissingVariable(_))));
    }
}
}

Dollar syntax

The dollar syntax follows Python’s string.Template, as used by the Python version of Brei. A variable is written $name or ${name}, where a name starts with a letter or underscore, followed by letters, digits and underscores. $$ is a literal dollar sign. Any other dollar sign is left alone, like Python’s safe_substitute does. That way, scripts can contain things like $(pwd), $1 or ${#array[@]}, which are not Brei variables, without escaping them. So parsing a dollar template never fails.

#![allow(unused)]
fn main() {
//| file: src/template_strings/dollar.rs
use std::iter::Iterator;
use super::result::Result;
use super::item::Item;

/// Iterates `Item` from a `&str` reference using a `${...}` type
/// string template.
pub struct Dollar<'a> {
    template: &'a str
}

/// Create an `Item` iterator for a given dollar-templated string.
pub fn dollar<'a, S>(s: S) -> Dollar<'a> where S: Into<&'a str> {
    Dollar {template: s.into()}
}

/// The length of the identifier at the start of `s`, if there is one.
fn identifier(s: &str) -> Option<usize> {
    let first = s.chars().next()?;
    if !(first.is_ascii_alphabetic() || first == '_') {
        return None;
    }
    Some(s.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(s.len()))
}

impl<'a> Iterator for Dollar<'a> {
    type Item = Result<Item<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        use Item::{Literal,Variable};

        if self.template.is_empty() {
            return None;
        }

        let Some(rest) = self.template.strip_prefix('$') else {
            let idx = self.template.find('$').unwrap_or(self.template.len());
            let (result, rest) = self.template.split_at(idx);
            self.template = rest;
            return Some(Ok(Literal(result)));
        };

        if let Some(rest) = rest.strip_prefix('$') {
            self.template = rest;
            return Some(Ok(Literal("$")));
        }

        if let Some(inner) = rest.strip_prefix('{') {
            if let Some(n) = identifier(inner) && inner[n..].starts_with('}') {
                self.template = &inner[n + 1..];
                return Some(Ok(Variable(&inner[..n])));
            }
        } else if let Some(n) = identifier(rest) {
            self.template = &rest[n..];
            return Some(Ok(Variable(&rest[..n])));
        }

        // not a variable, so a literal dollar sign
        self.template = rest;
        Some(Ok(Literal("$")))
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use super::super::format::{Format, Env};
    use super::super::result::Error;
    use Item::{Literal, Variable};

    #[test]
    fn test_iterator() {
        let it1 = dollar("Hello");
        let re1: Result<Vec<Item>> = it1.collect();
        assert_eq!(re1.unwrap(), vec![Literal("Hello")]);

        let it2 = dollar("Hello, ${name}!");
        let re2: Result<Vec<Item>> = it2.collect();
        assert_eq!(re2.unwrap(), vec![Literal("Hello, "), Variable("name"), Literal("!")]);

        let it3 = dollar("$1 $(pwd) ${a b} ${#x[@]} ${name 5$");
        let re3: Result<Vec<Item>> = it3.collect();
        let text: String = re3.unwrap().iter().map(|i| match i { Literal(s) => *s, Variable(_) => panic!() }).collect();
        assert_eq!(text, "$1 $(pwd) ${a b} ${#x[@]} ${name 5$");

        let it4 = dollar("$a1_b-c ${_x}y");
        let re4: Result<Vec<Item>> = it4.collect();
        assert_eq!(re4.unwrap(), vec![Variable("a1_b"), Literal("-c "), Variable("_x"), Literal("y")]);

        let it5 = dollar("$$ Literal $$");
        let re5: Result<Vec<Item>> = it5.collect();
        assert_eq!(re5.unwrap(), vec![Literal("$"), Literal(" Literal "), Literal("$")]);
    }

    <<end-to-end-test>>
}
}

Top-level module

#![allow(unused)]
fn main() {
//| file: src/template_strings/mod.rs
//! Run-time processing of template strings
//!

mod result;
mod format;
pub mod item;
// Brei uses the dollar syntax; the curly syntax is kept for later use.
#[allow(dead_code)]
mod curly;
mod dollar;

pub use result::*;
pub use item::*;
pub use format::*;
pub use dollar::*;
}

Compatibility with Python Brei

This chapter ports the tests of the Python version (test/ in its repository), and the examples from its documentation, to check that we behave the same. The tests run the brei binary on a workflow in a temporary directory, so they test everything from reading the program to running commands. Many workflows use the python runner, so these tests need Python, and also git and lua for some of the examples.

Tests of the Python internals, like the lazy evaluation in test_lazy.py, have their counterparts in the engine and Brei chapters instead. The template string tests are in Template Strings.

Differences

These differences from the Python version are deliberate:

  • Exit code: when something fails, brei exits with code 1.
  • Standard input: a command without stdin reads from /dev/null, not from the terminal.
  • Dollar escapes: $$ stays a literal dollar sign through calls of templates. In Python, every substitution turns $$ into $, so $$ in a template that is called ends up as a variable.
  • Error messages are worded differently. For example, splicing a scalar variable says that it is not a list variable, where Python says that splice needs a list variable.
  • Empty variables: a scalar variable with empty output is "", where Python gives None.
  • Variable rules: a rule that writes to a variable always runs, also when the files it creates are up to date. Python skips it, and the variable has no value.
  • History: the history file is always used. The Python library can also run without one.
  • YAML: workflows can also be written in YAML (.yaml or .yml). Python Brei only reads TOML and JSON.

Setup

A Workflow is a temporary directory with a brei.toml. Some examples create a temporary directory with mktemp -d; we set TMPDIR so that it ends up in the test directory too.

#![allow(unused)]
fn main() {
//| file: tests/python.rs
use std::fs;
use std::path::Path;
use std::process::{Command, Output};
use std::thread;
use std::time::{Duration, Instant, SystemTime};
use tempfile::TempDir;

struct Workflow {
    dir: TempDir,
}

impl Workflow {
    fn new(program: &str) -> Self {
        let workflow = Workflow { dir: TempDir::new().unwrap() };
        workflow.write("brei.toml", program);
        workflow
    }

    fn path(&self, path: &str) -> std::path::PathBuf {
        self.dir.path().join(path)
    }

    fn write(&self, path: &str, text: &str) {
        let path = self.path(path);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, text).unwrap();
    }

    fn read(&self, path: &str) -> String {
        fs::read_to_string(self.path(path)).unwrap()
    }

    fn exists(&self, path: &str) -> bool {
        self.path(path).exists()
    }

    fn modified(&self, path: &str) -> SystemTime {
        fs::metadata(self.path(path)).unwrap().modified().unwrap()
    }

    fn brei(&self, args: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_brei"))
            .args(args).current_dir(self.dir.path()).env("TMPDIR", self.dir.path()).env("NO_COLOR", "1")
            .output().unwrap()
    }

    /// Run `brei`, which should succeed; gives the log.
    fn run(&self, args: &[&str]) -> String {
        let output = self.brei(args);
        let log = String::from_utf8_lossy(&output.stderr).into_owned();
        assert!(output.status.success(), "brei {args:?} failed:\n{log}");
        log
    }

    /// Run `brei`, which should fail; gives the log.
    fn fail(&self, args: &[&str]) -> String {
        let output = self.brei(args);
        let log = String::from_utf8_lossy(&output.stderr).into_owned();
        assert!(!output.status.success(), "brei {args:?} should fail:\n{log}");
        log
    }

    /// Check the contents of files, ignoring white space around them.
    fn check(&self, files: &[(&str, &str)]) {
        for (path, content) in files {
            assert!(self.exists(path), "`{path}` doesn't exist");
            assert_eq!(self.read(path).trim(), content.trim(), "contents of `{path}`");
        }
    }
}

/// Give file modification times a chance to differ.
fn tick() {
    thread::sleep(Duration::from_millis(20));
}

<<python-tests>>
}

Workflows

From test_program.py: workflows that build #all, with the files they should create.

#![allow(unused)]
fn main() {
//| id: python-tests
const HELLO_WORLD: &str = r##"
[[task]]
name = "all"
requires = ["hello.txt"]

[[task]]
stdout = "hello.txt"
script = "echo 'Hello, World'"
"##;

const INCLUDE: &str = r##"
include = [
    "generated_wf.toml"
]

[[task]]
stdout = "generated_wf.toml"
runner = "python"
script = '''
print("""
[[task]]
stdout = "hello.txt"
script = "echo 'Hello, World'"
""")
'''

[[task]]
name = "all"
requires = ["hello.txt"]
"##;

const TEMPLATE: &str = r##"
[template.echo]
stdout = "${stdout}"
runner = "python"
script = '''
print("${text}")
'''

[[task]]
name = "all"
requires = ["hello.txt"]

[[call]]
template = "echo"
args = { stdout = "hello.txt", text = "Hello, World" }
"##;

const ROT_13: &str = r##"
[[task]]
stdout = "secret.txt"
runner = "python"
script = """
print("Uryyb, Jbeyq!")
"""

[template.rot13]
stdout = "${stdout}"
stdin = "${stdin}"
script = "tr a-zA-Z n-za-mN-ZA-M"

[[call]]
template = "rot13"
  [call.args]
  stdin = "secret.txt"
  stdout = "hello.txt"

[[task]]
name = "all"
requires = ["hello.txt"]
"##;

const TEMPLATED_TASK: &str = r##"
[environment]
msg = "Hello, World!"

[[task]]
stdout = "hello.txt"
script = "echo '${msg}'"

[[task]]
name = "all"
requires = ["hello.txt"]
"##;

const VARIABLE_STDOUT: &str = r##"
[template.echo]
script = "echo '${text}'"
stdout = "${stdout}"

[[call]]
template = "echo"
  [call.args]
  text = "Hello, World!"
  stdout = "var(msg)"

[[task]]
script = "cat"
stdin = "var(msg)"
stdout = "hello.txt"

[[call]]
template = "echo"
  [call.args]
  text = "goodbye.txt"
  stdout = "var(file_name)"

[[task]]
script = "cat"
stdin = "var(msg)"
stdout = "${file_name}"

[[task]]
name = "all"
requires = ["hello.txt", "${file_name}"]
"##;

const ARRAY_CALL: &str = r##"
[template.echo]
script = "echo '${a}${b}'"
stdout = "${pre}-${a}-${b}"

[[call]]
template = "echo"
collect = "inner"
  [call.args]
  pre = "zip"
  a = ["1", "2", "3"]
  b = ["a", "b", "c"]

[[call]]
template = "echo"
join = "outer"
collect = "outer"
  [call.args]
  pre = "prod"
  a = ["1", "2"]
  b = ["a", "b"]

[[task]]
name = "all"
requires = ["#inner", "#outer"]
"##;

#[test]
fn workflows() {
    let hello: &[(&str, &str)] = &[("hello.txt", "Hello, World")];
    let cases: &[(&str, &[(&str, &str)])] = &[
        (HELLO_WORLD, hello),
        (INCLUDE, hello),
        (TEMPLATE, hello),
        (ROT_13, &[("hello.txt", "Hello, World!")]),
        (TEMPLATED_TASK, &[("hello.txt", "Hello, World!")]),
        (VARIABLE_STDOUT, &[("hello.txt", "Hello, World!"), ("goodbye.txt", "Hello, World!")]),
        (ARRAY_CALL, &[("zip-1-a", "1a"), ("zip-2-b", "2b"), ("zip-3-c", "3c"),
                       ("prod-1-a", "1a"), ("prod-1-b", "1b"), ("prod-2-a", "2a"), ("prod-2-b", "2b")]),
    ];
    for (program, files) in cases {
        let workflow = Workflow::new(program);
        workflow.run(&["all"]);
        workflow.check(files);
    }
}
}

A rule with force always runs, also when its targets are up to date.

#![allow(unused)]
fn main() {
//| id: python-tests
const FORCE_RUN: &str = r##"
[[task]]
name = "forced"
force = true
creates = ["forced.txt"]
script = "touch forced.txt"

[[task]]
name = "unforced"
force = false
creates = ["unforced.txt"]
script = "touch unforced.txt"

[[task]]
name = "all"
requires = ["#forced", "#unforced"]
"##;

#[test]
fn forcing() {
    let workflow = Workflow::new(FORCE_RUN);
    workflow.run(&["all"]);
    let (forced, unforced) = (workflow.modified("forced.txt"), workflow.modified("unforced.txt"));
    tick();
    workflow.run(&["all"]);
    assert!(workflow.modified("forced.txt") > forced);
    assert_eq!(workflow.modified("unforced.txt"), unforced);
}
}

A failing command fails, also when it wrote some output. Its target may be written partially, so it shouldn’t be in the history.

#![allow(unused)]
fn main() {
//| id: python-tests
const FAILING: &str = r##"
[[task]]
stdout = "runner.txt"
runner = "python"
script = '''
import sys
print("partial output")
sys.exit(3)
'''

[[task]]
stdout = "oneliner.txt"
script = "python -c 'import sys; sys.exit(4)'"
"##;

#[test]
fn failing_command() {
    for (target, code) in [("runner.txt", 3), ("oneliner.txt", 4)] {
        let workflow = Workflow::new(FAILING);
        let log = workflow.fail(&[target]);
        assert!(log.contains(&format!("failed with exit code {code}")), "{log}");
        assert!(!workflow.read(".brei_history").contains(target));
    }
}
}

List variables

A call can splice a list variable into its arguments. Empty lines are not part of the list.

#![allow(unused)]
fn main() {
//| id: python-tests
const LIST_NAMES: &str = r##"
[[task]]
stdout = "listvar(names)"
script = '''python -c 'print("a"); print(""); print("b")' '''
"##;

const SPLICE_CALL: &str = r##"
[template.write]
stdout = "out-${name}.txt"
script = '''python -c 'print("${name}")' '''

[[call]]
template = "write"
collect = "outs"
args = { name = ["splice(names)", "c"] }

[[task]]
name = "all"
requires = ["#outs"]
"##;

#[test]
fn splice_call() {
    let workflow = Workflow::new(&format!("{LIST_NAMES}{SPLICE_CALL}"));
    workflow.run(&["all"]);
    workflow.check(&[("out-a.txt", "a"), ("out-b.txt", "b"), ("out-c.txt", "c")]);
    assert!(!workflow.exists("out-.txt"));
}
}

A rule can splice a list variable into its dependencies. When one of them changes, the rule runs again.

#![allow(unused)]
fn main() {
//| id: python-tests
const SPLICE_REQUIRES: &str = r##"
[[task]]
stdout = "listvar(inputs)"
script = '''python -c 'print("in-1.txt"); print("in-2.txt")' '''

[[task]]
stdout = "summary.txt"
requires = ["splice(inputs)"]
script = '''python -c 'print(open("in-1.txt").read() + open("in-2.txt").read())' '''
"##;

#[test]
fn splice_requires() {
    let workflow = Workflow::new(SPLICE_REQUIRES);
    workflow.write("in-1.txt", "1");
    workflow.write("in-2.txt", "2");
    workflow.run(&["summary.txt"]);
    workflow.check(&[("summary.txt", "12")]);

    tick();
    workflow.write("in-2.txt", "3");
    workflow.run(&["summary.txt"]);
    workflow.check(&[("summary.txt", "13")]);
}

#[test]
fn splice_empty_list() {
    let workflow = Workflow::new(r##"
[[task]]
stdout = "listvar(nothing)"
script = "python -c 'pass'"

[template.write]
stdout = "out-${name}.txt"
script = "python -c 'pass'"

[[call]]
template = "write"
collect = "outs"
args = { name = ["splice(nothing)"] }
"##);
    workflow.run(&["outs"]);
    assert!(!fs::read_dir(workflow.dir.path()).unwrap().any(|e| e.unwrap().file_name().to_string_lossy().starts_with("out-")));
}
}

List variables used in the wrong way are errors.

#![allow(unused)]
fn main() {
//| id: python-tests
#[test]
fn list_variable_errors() {
    let cases = [
        (format!("{LIST_NAMES}{}", r##"
[[task]]
stdout = "x.txt"
script = "python -c 'print(\"${names}\")'"
"##), "list variable"),
        (format!("{LIST_NAMES}{}", r##"
[[task]]
stdout = "x.txt"
requires = ["listvar(names)"]
script = "python -c 'pass'"
"##), "can only be used as `stdout`"),
        (r##"
[[task]]
stdout = "var(name)"
script = "python -c 'print(1)'"

[template.write]
stdout = "out-${name}.txt"
script = "python -c 'pass'"

[[call]]
template = "write"
args = { name = ["splice(name)"] }
"##.to_string(), "is not a list variable"),
        (format!("{LIST_NAMES}{}", r##"
[template.write]
stdout = "out-${a}-${b}.txt"
script = "python -c 'pass'"

[[call]]
template = "write"
args = { a = ["splice(names)"], b = ["1", "2", "3"] }
"##), "same length"),
    ];
    for (program, message) in cases {
        let log = Workflow::new(&program).fail(&["x.txt"]);
        assert!(log.contains(message), "expected `{message}` in:\n{log}");
    }
}
}

History

From test_history.py. With the history, a rule that is up to date doesn’t run, until its script changes. Without the history (here: when we remove it), it always runs, because we can’t know which script created the target.

#![allow(unused)]
fn main() {
//| id: python-tests
const WF1: &str = r##"{"task": [{"stdout": "x", "script": "echo 'hello'"}, {"name": "all", "requires": ["x"]}]}"##;
const WF2: &str = r##"{"task": [{"stdout": "x", "script": "echo 'goodbye'"}, {"name": "all", "requires": ["x"]}]}"##;

#[test]
fn history() {
    let workflow = Workflow::new("");
    workflow.write("wf1.json", WF1);
    workflow.write("wf2.json", WF2);

    workflow.run(&["-i", "wf1.json", "all"]);
    let s1 = workflow.modified("x");
    tick();
    workflow.run(&["-i", "wf1.json", "all"]);
    let s2 = workflow.modified("x");
    tick();
    workflow.run(&["-i", "wf2.json", "all"]);
    let s3 = workflow.modified("x");
    assert_eq!(workflow.read("x").trim(), "goodbye");
    assert_eq!(s1, s2);
    assert!(s3 > s2);

    fs::remove_file(workflow.path(".brei_history")).unwrap();
    tick();
    workflow.run(&["-i", "wf2.json", "all"]);
    assert!(workflow.modified("x") > s3);
}
}

Rules and programs

From test_lazy.py: rules run in parallel, and a change in an input file rebuilds what depends on it.

#![allow(unused)]
fn main() {
//| id: python-tests
#[test]
fn runtime() {
    let mut program = String::new();
    for a in 0..4 {
        program += &format!("[[task]]\nname = \"sleep{a}\"\nrunner = \"python\"\nscript = \"import time; time.sleep(0.2)\"\n\n");
    }
    program += "[[task]]\nname = \"all\"\nrequires = [\"#sleep0\", \"#sleep1\", \"#sleep2\", \"#sleep3\"]\n";
    let workflow = Workflow::new(&program);
    let start = Instant::now();
    workflow.run(&["-j", "4", "all"]);
    let elapsed = start.elapsed();
    // One after another would take 0.8 seconds.
    assert!(elapsed > Duration::from_millis(200) && elapsed < Duration::from_millis(800), "{elapsed:?}");
}

const REBUILD: &str = r##"
[[task]]
stdout = "a"
requires = ["i1"]
runner = "python"
script = "print(int(open('i1','r').read()) + 1)"

[[task]]
stdout = "b"
requires = ["a", "i2"]
runner = "python"
script = "print(int(open('a','r').read()) * int(open('i2','r').read()))"

[[task]]
stdout = "c"
requires = ["a", "b"]
runner = "python"
script = "print(int(open('b','r').read()) * int(open('a','r').read()))"
"##;

#[test]
fn rebuild() {
    let workflow = Workflow::new(REBUILD);
    workflow.write("i1", "1\n");
    workflow.write("i2", "3\n");
    workflow.run(&["c"]);
    workflow.check(&[("a", "2"), ("b", "6"), ("c", "12")]);
    let a = workflow.modified("a");

    tick();
    workflow.write("i2", "4\n");
    workflow.run(&["c"]);
    assert_eq!(workflow.modified("a"), a);
    workflow.check(&[("a", "2"), ("b", "8"), ("c", "16")]);
}
}

From test_construct.py: programs with mistakes in them. Unknown fields are errors.

#![allow(unused)]
fn main() {
//| id: python-tests
#[test]
fn construct_errors() {
    let workflow = Workflow::new("");
    let cases = [
        (r##"{"task": [{"creates": "hello.txt"}]}"##, "invalid type"),
        (r##"{"call": [{"template": "t", "args": {}, "join": "sideways"}]}"##, "unknown variant"),
        (r##"{"tasks": []}"##, "unknown field"),
        (r##"{"task": [{"creates": ["x"], "requries": ["y"]}]}"##, "unknown field"),
        (r##"{"template": {"t": {"creates": ["${x}"], "bogus": 1}}}"##, "unknown field"),
        (r##"{"call": [{"template": "t", "args": {}, "jion": "outer"}]}"##, "unknown field"),
        (r##"{"runner": {"r": {"command": "r", "args": [], "env": {}}}}"##, "unknown field"),
    ];
    for (program, message) in cases {
        workflow.write("program.json", program);
        let log = workflow.fail(&["-i", "program.json"]);
        assert!(log.contains(message), "expected `{message}` in:\n{log}");
    }
}
}

Examples

The examples from the documentation of the Python version.

#![allow(unused)]
fn main() {
//| id: python-tests
const ROT13_EXAMPLE: &str = r##"
[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[template.echo]
stdout = "${stdout}"
script = "echo ${text}"

[template.rot13]
stdout = "${stdout}"
stdin = "${stdin}"
script = "tr a-zA-Z n-za-mN-ZA-M"

[[call]]
template = "echo"
  [call.args]
  stdout = "${dir}/secret.txt"
  text = "Uryyb, Jbeyq!"

[[call]]
template = "rot13"
  [call.args]
  stdin = "${dir}/secret.txt"
  stdout = "${dir}/msg.txt"

[[task]]
name = "all"
requires = ["${dir}/msg.txt"]
script = "cat ${dir}/msg.txt"
"##;

const TASKS_EXAMPLE: &str = r##"
[[task]]
creates = ["hello.txt"]
runner = "bash"
script = "echo 'Hello, World!' > hello.txt"

[[task]]
name = "all"
requires = ["hello.txt"]

[[task]]
name = "clean"
script = "rm hello.txt"
"##;

#[test]
fn example_tasks() {
    let workflow = Workflow::new(TASKS_EXAMPLE);
    workflow.run(&["all"]);
    workflow.check(&[("hello.txt", "Hello, World!")]);
    workflow.run(&["clean"]);
    assert!(!workflow.exists("hello.txt"));
}

#[cfg_attr(windows, ignore = "`mktemp` in Git Bash gives a Unix path")]
#[test]
fn example_rot13() {
    let log = Workflow::new(ROT13_EXAMPLE).run(&["all"]);
    assert!(log.contains("#all Hello, World!"), "{log}");
}
}

Templates can be called with lists, which are joined, or combined in every way. The targets of the template are in a temporary directory; which tasks ran, we see from their descriptions in the log. (Where mktemp -d puts the directory differs between platforms.)

#![allow(unused)]
fn main() {
//| id: python-tests
const MULTIPLEXING_EXAMPLE: &str = r##"
[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[template.touch]
description = "${pre} ${a} ${b}"
creates = ["${dir}/${pre}-${a}-${b}"]
script = "touch '${dir}/${pre}-${a}-${b}'"

[[call]]
template = "touch"
collect = "inner"
  [call.args]
  pre = "inner"
  a = ["x", "y", "z"]
  b = ["1", "2", "3"]

[[call]]
template = "touch"
collect = "outer"
join = "outer"
  [call.args]
  pre = "outer"
  a = ["x", "y"]
  b = ["1", "2"]

[[task]]
name = "all"
requires = ["#inner", "#outer"]
"##;

#[cfg_attr(windows, ignore = "`mktemp` in Git Bash gives a Unix path")]
#[test]
fn example_template_multiplexing() {
    let log = Workflow::new(MULTIPLEXING_EXAMPLE).run(&["all"]);
    let mut notes: Vec<&str> = log.lines().filter(|l| l.starts_with("inner ") || l.starts_with("outer ")).collect();
    notes.sort();
    assert_eq!(notes, ["inner x 1", "inner y 2", "inner z 3", "outer x 1", "outer x 2", "outer y 1", "outer y 2"]);
}
}

Includes can be static files, or generated by a rule. Here, a Python script generates a workflow in JSON.

#![allow(unused)]
fn main() {
//| id: python-tests
const ECHO_EXAMPLE: &str = r##"
[template.echo]
stdout = "${stdout}"
script = "echo '${text}'"
"##;

const HELLO_INCLUDES_EXAMPLE: &str = r##"
include = [
    "./echo.toml"
]

[[call]]
template = "echo"
  [call.args]
  stdout = "hello.txt"
  text = "Hello, World!"

[[task]]
name = "all"
requires = ["hello.txt"]
"##;

const INCLUDE_GEN_EXAMPLE: &str = r##"
include = [
    "${dir}/gen.json"
]

[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[[task]]
description = "Generating workflow"
stdout = "${dir}/gen.json"
runner = "python"
script = """
import json
tasks = [
    {"stdout": f"${dir}/out{i}.dat",
     "script": f"echo '{i}'"} for i in range(10)
]
tasks.append({"name": "write-outs", "requires": [
    f"${dir}/out{i}.dat" for i in range(10)
]})
print(json.dumps({"task": tasks}))
"""

[[task]]
name = "all"
requires = ["#write-outs"]
"##;

#[cfg_attr(windows, ignore = "`mktemp` in Git Bash gives a Unix path")]
#[test]
fn example_includes() {
    let workflow = Workflow::new(HELLO_INCLUDES_EXAMPLE);
    workflow.write("echo.toml", ECHO_EXAMPLE);
    workflow.run(&["all"]);
    workflow.check(&[("hello.txt", "Hello, World!")]);

    let workflow = Workflow::new(INCLUDE_GEN_EXAMPLE);
    let log = workflow.run(&["all"]);
    let count = log.lines().filter(|l| l.starts_with("creating `") && l.ends_with(".dat`")).count();
    assert_eq!(count, 10, "{log}");
}
}

A list variable gives the files to copy.

#![allow(unused)]
fn main() {
//| id: python-tests
const LIST_VARIABLES_EXAMPLE: &str = r##"
[[task]]
description = "Listing figures"
stdout = "listvar(figures)"
runner = "python"
script = """
from pathlib import Path
for p in sorted(Path("docs/fig").glob("*.svg")):
    print(p.name)
"""

[template.copy]
description = "copy `${name}`"
requires = ["docs/fig/${name}"]
creates = ["docs/site/fig/${name}"]
runner = "python"
script = """
import shutil
shutil.copy("docs/fig/${name}", "docs/site/fig/${name}")
"""

[[call]]
template = "copy"
collect = "figures"
args = { name = ["splice(figures)"] }

[[task]]
name = "all"
requires = ["#figures"]
"##;

#[test]
fn example_list_variables() {
    let workflow = Workflow::new(LIST_VARIABLES_EXAMPLE);
    workflow.write("docs/fig/a.svg", "<svg>a</svg>");
    workflow.write("docs/fig/b.svg", "<svg>b</svg>");
    workflow.write("docs/site/fig/.keep", "");
    workflow.run(&["all"]);
    workflow.check(&[("docs/site/fig/a.svg", "<svg>a</svg>"), ("docs/site/fig/b.svg", "<svg>b</svg>")]);
}
}

The output directory depends on the current git commit. The script scripts/run.py is not part of the example, so we write one. Note that the link output/latest in this example is broken: ln -sf ./output/<commit> output/latest makes a relative link, which points to output/output/<commit>. So our script writes to the output directory directly.

#![allow(unused)]
fn main() {
//| id: python-tests
const VERSIONED_OUTPUT_EXAMPLE: &str = r##"
[environment]
data_dir = "./data"
output_dir = "./output/${commit}"

[[task]]
stdout = "var(commit)"
script = "git rev-parse HEAD"

[[task]]
creates = ["${output_dir}/data.h5"]
requires = ["${data_dir}/input.h5", "#prepare"]
runner = "python"
path = "scripts/run.py"

[[task]]
name = "prepare"
script = """
mkdir -p ${output_dir}
ln -sf ${output_dir} output/latest
"""

[[task]]
name = "all"
requires = ["${output_dir}/data.h5"]
"##;

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git").args(args).current_dir(dir)
        .env("GIT_AUTHOR_NAME", "test").env("GIT_AUTHOR_EMAIL", "test@example.com")
        .env("GIT_COMMITTER_NAME", "test").env("GIT_COMMITTER_EMAIL", "test@example.com")
        .status().unwrap();
    assert!(status.success());
}

#[cfg_attr(windows, ignore = "`ln -s` in Git Bash can't make symbolic links")]
#[test]
fn example_versioned_output() {
    let workflow = Workflow::new(VERSIONED_OUTPUT_EXAMPLE);
    workflow.write("data/input.h5", "data");
    workflow.write("scripts/run.py", concat!(
        "import shutil, subprocess\n",
        "commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()\n",
        "shutil.copy('data/input.h5', f'output/{commit}/data.h5')\n"));
    git(workflow.dir.path(), &["init", "-q"]);
    git(workflow.dir.path(), &["commit", "-q", "--allow-empty", "-m", "test"]);
    let commit = String::from_utf8(Command::new("git").args(["rev-parse", "HEAD"]).current_dir(workflow.dir.path())
        .output().unwrap().stdout).unwrap();

    workflow.run(&["all"]);
    workflow.check(&[(&format!("output/{}/data.h5", commit.trim()), "data")]);
}
}

A custom runner, for Lua. This test is skipped when Lua isn’t installed.

#![allow(unused)]
fn main() {
//| id: python-tests
const CUSTOM_RUNNER_EXAMPLE: &str = r##"
[[task]]
description = "Creating temporary directory"
stdout = "var(dir)"
script = "mktemp -d"

[runner.lua]
command = "lua"
args = ["${script}"]

[[task]]
runner = "lua"
stdout = "${dir}/hello.txt"
script = """
function fact (n)
  if n == 0 then
    return 1
  else
    return n * fact(n-1)
  end
end

print("10! = ", fact(10))
"""

[[task]]
name = "all"
requires = ["${dir}/hello.txt"]
script = "cat ${dir}/hello.txt"
"##;

#[test]
fn example_custom_runner() {
    if Command::new("lua").arg("-v").output().is_err() {
        eprintln!("skipped: lua is not installed");
        return;
    }
    let log = Workflow::new(CUSTOM_RUNNER_EXAMPLE).run(&["all"]);
    assert!(log.contains("#all 10! = \t3628800"), "{log}");
}
}

Coverage

This is the test coverage of Brei, as of the last time the book was built after running brei coverage (see Forcing a rerun). If there is no report below, coverage hasn’t been measured. You can also open the report on its own.