flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
Documentation
//! A Rust library's launcher is built from the files Cargo compiles for it:
//! a test, a benchmark or a document is none of them, while a compiled
//! source, a new module a source names and a local path dependency's
//! compiled source are.
mod common;
use flow_start::Spawn as _;
use std::fs;
use std::path::Path;
use std::process::{Command, Output};

/// A Rust library's `flow.toml`.
const FLOW_TOML: &str =
    "[process]\ncommand = \"flow-toolkit-rust serve\"\nextract = \"flow-toolkit-rust extract\"\n";

fn write(path: &Path, text: &str) {
    fs::create_dir_all(path.parent().expect("a file has a directory"))
        .expect("the fixture directory is created");
    fs::write(path, text).expect("the fixture file is written");
}

/// `extract` for the library at `root`.
fn extract(root: &Path) -> Command {
    let mut command = common::toolkit(common::rust_toolkit());
    command
        .args(["extract", "--library"])
        .arg(root)
        .arg("--out")
        .arg(root.with_file_name("contract-out"))
        .arg("--depfile")
        .arg(root.with_file_name("deps"));
    command
}

/// `extract` where Cargo cannot be found, so that only a launcher that is
/// current serves the answer.
fn extract_without_cargo(root: &Path) -> Output {
    let empty = root.join("target/no-cargo");
    fs::create_dir_all(&empty).expect("the directory is created");
    extract(root)
        .env("PATH", empty)
        .locked_output()
        .expect("the command runs")
}

fn assert_current(root: &Path, why: &str) {
    let output = extract_without_cargo(root);
    assert!(
        output.status.success(),
        "{why}: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn assert_stale(root: &Path, why: &str) {
    let output = extract_without_cargo(root);
    assert_eq!(
        output.status.code(),
        Some(2),
        "{why}: the launcher is rebuilt"
    );
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("cargo was not found"),
        "{why}: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn assert_built(root: &Path) {
    let output = extract(root).locked_output().expect("the command runs");
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn recorded(root: &Path) -> Vec<String> {
    fs::read_to_string(common::launcher_cache(root).join("sources"))
        .expect("the build recorded its sources")
        .lines()
        .filter(|line| !Path::new(line).is_absolute())
        .map(str::to_owned)
        .collect()
}

#[test]
fn a_launcher_is_rebuilt_for_a_compiled_file_and_not_for_a_test() {
    let files = tempfile::TempDir::with_prefix("rust-compiled-inputs").expect("a directory");
    let base = files.path().canonicalize().expect("the path exists");
    let root = base.join("tools");
    write(&root.join("flow.toml"), FLOW_TOML);
    write(
        &root.join("src/lib.rs"),
        "#[flow_toolkit::tool] pub fn echo(value:String)->String{shared::same(value)}\n",
    );
    write(&root.join("tests/plain.rs"), "#[test] fn plain() {}\n");
    write(&root.join("README.md"), "A fixture.\n");
    write(
        &base.join("shared/Cargo.toml"),
        "[package]\nname=\"shared\"\nversion=\"0.0.0\"\nedition=\"2024\"\n",
    );
    write(
        &base.join("shared/src/lib.rs"),
        "pub fn same(value:String)->String{value}\n",
    );
    write(
        &base.join("shared/tests/shared.rs"),
        "#[test] fn shared() {}\n",
    );
    common::toolkit_consumer(&root, "compiled-inputs", "shared={path=\"../shared\"}\n");
    assert_built(&root);
    let sources = recorded(&root);
    for compiled in ["src/lib.rs", "../shared/src/lib.rs"] {
        assert!(
            sources.iter().any(|source| source == compiled),
            "{compiled}: {sources:?}"
        );
    }
    assert!(
        !sources.iter().any(|source| source.contains("tests/")),
        "{sources:?}"
    );
    assert_current(&root, "a fresh launcher");

    write(&root.join("tests/plain.rs"), "#[test] fn edited() {}\n");
    write(&root.join("tests/added.rs"), "#[test] fn added() {}\n");
    write(&root.join("README.md"), "An edited fixture.\n");
    write(
        &base.join("shared/tests/shared.rs"),
        "#[test] fn edited() {}\n",
    );
    assert_current(&root, "tests and documents are not compiled");

    write(
        &base.join("shared/src/lib.rs"),
        "pub fn same(value:String)->String{ value }\n",
    );
    assert_stale(&root, "a local path dependency's compiled source changed");
    assert_built(&root);

    write(
        &root.join("src/lib.rs"),
        "mod helper;\n#[flow_toolkit::tool] pub fn echo(value:String)->String{helper::same(value)}\n",
    );
    write(
        &root.join("src/helper.rs"),
        "pub fn same(value:String)->String{shared::same(value)}\n",
    );
    assert_stale(&root, "a compiled source changed");
    assert_built(&root);
    assert!(
        recorded(&root)
            .iter()
            .any(|source| source == "src/helper.rs"),
        "a module a source names is compiled"
    );
    write(
        &root.join("src/helper.rs"),
        "pub fn same(value:String)->String{ shared::same(value) }\n",
    );
    assert_stale(&root, "the new module changed");
}

#[test]
fn a_dependency_s_contract_directory_is_source_the_build_may_read() {
    let files = tempfile::TempDir::with_prefix("rust-dependency-contract").expect("a directory");
    let base = files.path().canonicalize().expect("the path exists");
    let root = base.join("tools");
    write(&root.join("flow.toml"), FLOW_TOML);
    write(
        &root.join("src/lib.rs"),
        "#[flow_toolkit::tool] pub fn word()->String{shared::WORD.into()}\n",
    );
    write(
        &base.join("shared/Cargo.toml"),
        "[package]\nname=\"shared\"\nversion=\"0.0.0\"\nedition=\"2024\"\n",
    );
    write(
        &base.join("shared/src/lib.rs"),
        "pub const WORD: &str = include_str!(\"../contract/word.txt\");\n",
    );
    write(&base.join("shared/contract/word.txt"), "one");
    common::toolkit_consumer(
        &root,
        "dependency-contract",
        "shared={path=\"../shared\"}\n",
    );
    assert_built(&root);
    assert_current(&root, "a fresh launcher");
    write(&base.join("shared/contract/word.txt"), "two");
    assert_stale(
        &root,
        "a file in the dependency's contract directory changed",
    );
}

#[test]
fn a_build_script_may_watch_a_directory_and_a_path_that_does_not_exist_yet() {
    let files = tempfile::TempDir::with_prefix("rust-watched-inputs").expect("a directory");
    let root = files
        .path()
        .canonicalize()
        .expect("the path exists")
        .join("tools");
    write(&root.join("flow.toml"), FLOW_TOML);
    write(
        &root.join("build.rs"),
        "fn main() { println!(\"cargo::rerun-if-changed=assets\"); println!(\"cargo::rerun-if-changed=generated.txt\"); }\n",
    );
    write(&root.join("assets/one.txt"), "one\n");
    write(
        &root.join("src/lib.rs"),
        "#[flow_toolkit::tool] pub fn echo(value:String)->String{value}\n",
    );
    common::toolkit_consumer(&root, "watched-inputs", "");
    assert_built(&root);
    let sources = recorded(&root);
    for watched in ["assets", "generated.txt"] {
        assert!(
            sources.iter().any(|source| source == watched),
            "{watched}: {sources:?}"
        );
    }
    assert_current(&root, "a watched path that does not exist yet stays absent");
    write(&root.join("assets/nested/two.txt"), "two\n");
    assert_stale(&root, "a file added to a watched directory");
    assert_built(&root);
    assert_current(&root, "the rebuilt launcher");
    write(&root.join("generated.txt"), "now here\n");
    assert_stale(&root, "a watched path appeared");
    assert_built(&root);
    assert_current(&root, "the rebuilt launcher");
}

#[test]
fn a_build_clears_what_an_earlier_extraction_left_unfinished() {
    let files = tempfile::TempDir::with_prefix("rust-leftover-extraction").expect("a directory");
    let root = files
        .path()
        .canonicalize()
        .expect("the path exists")
        .join("tools");
    write(&root.join("flow.toml"), FLOW_TOML);
    write(
        &root.join("src/lib.rs"),
        "#[flow_toolkit::tool] pub fn echo(value:String)->String{value}\n",
    );
    common::toolkit_consumer(&root, "leftover", "");
    write(
        &common::launcher_cache(&root).join("contracts.new/stale.flow"),
        "a module a failed extraction left\n",
    );
    assert_built(&root);
    assert!(
        !root
            .with_file_name("contract-out")
            .join("stale.flow")
            .exists(),
        "a module left by an earlier extraction is not part of the contract"
    );
}

#[test]
fn the_depfile_lists_each_directory_of_a_nested_module_so_a_file_added_there_regenerates_the_contract()
 {
    let files = tempfile::TempDir::with_prefix("rust-nested-inputs").expect("a directory");
    let root = files
        .path()
        .canonicalize()
        .expect("the path exists")
        .join("tools");
    write(&root.join("flow.toml"), FLOW_TOML);
    write(&root.join("src/lib.rs"), "pub mod ledger;\n");
    write(&root.join("src/ledger.rs"), "pub mod entries;\n");
    write(
        &root.join("src/ledger/entries/mod.rs"),
        "#[flow_toolkit::tool] pub fn echo(value:String)->String{value}\n",
    );
    common::toolkit_consumer(&root, "nested-inputs", "");
    assert_built(&root);
    let listed = common::depfile(&root.with_file_name("deps"));
    for directory in ["", "src", "src/ledger", "src/ledger/entries"] {
        assert!(
            listed.contains(&root.join(directory)),
            "the depfile lists the directory {directory:?}: {listed:?}"
        );
    }
    assert!(listed.contains(&root.join("src/ledger/entries/mod.rs")));
    assert!(
        !root.join("target").exists(),
        "nothing is written into the library"
    );
    assert!(
        !listed
            .iter()
            .any(|path| path.starts_with(root.join("target"))),
        "build output is never an input: {listed:?}"
    );
    assert_eq!(
        common::modules(&root.with_file_name("contract-out"))
            .into_keys()
            .collect::<Vec<_>>(),
        ["ledger/entries"]
    );
}