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
//! `flow-toolkit-rust new DIR`: a Rust Tool library with its `flow.toml`,
//! `Cargo.toml`, `Cargo.lock`, one `#[tool]` with a native test, and the
//! contract `extract` writes, built by the same code. Here, where the
//! toolkit's launcher is built, the library is built for real.

mod common;

use flow_start::Spawn as _;
use std::path::Path;

use common::flow;
use tempfile::TempDir;

/// Every file under `dir`, relative to it, in order.
fn files(dir: &Path) -> Vec<String> {
    fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
        for entry in std::fs::read_dir(dir).expect("a directory").flatten() {
            let path = entry.path();
            if path.is_dir() {
                walk(root, &path, out);
            } else {
                let relative = path.strip_prefix(root).expect("under the root");
                out.push(relative.to_string_lossy().into_owned());
            }
        }
    }
    let mut out = Vec::new();
    walk(dir, dir, &mut out);
    out.sort();
    out
}

/// Writes a library at `root` with `flow-toolkit-rust new`.
fn new(root: &Path) -> std::process::Output {
    common::toolkit(common::rust_toolkit())
        .arg("new")
        .arg(root)
        .locked_output()
        .expect("the toolkit runs")
}

/// Each registry or git package `lock` locks: its name, version, source
/// and checksum.
fn locked(lock: &str) -> Vec<[Option<String>; 4]> {
    let table = lock.parse::<toml::Table>().expect("a lock");
    table["package"]
        .as_array()
        .expect("a list of packages")
        .iter()
        .map(|package| {
            ["name", "version", "source", "checksum"].map(|key| {
                package
                    .get(key)
                    .and_then(toml::Value::as_str)
                    .map(str::to_owned)
            })
        })
        .filter(|[_, _, source, _]| source.is_some())
        .collect()
}

#[test]
fn a_new_rust_library_holds_its_contract_and_passes_its_own_test() {
    let project = TempDir::with_prefix("flow-new-rust").expect("a directory");
    let root = project.path().join("ledger");
    let made = new(&root);
    assert!(
        made.status.success(),
        "{}",
        String::from_utf8_lossy(&made.stderr)
    );
    let expected = [
        ".gitignore",
        "Cargo.lock",
        "Cargo.toml",
        "contract/lib.flow",
        "flow.toml",
        "src/lib.rs",
    ];
    assert_eq!(files(&root), expected);
    assert_eq!(
        String::from_utf8(made.stdout)
            .expect("UTF-8")
            .lines()
            .map(str::to_owned)
            .collect::<Vec<_>>(),
        expected
            .iter()
            .map(|file| format!("{}/{file}", root.display()))
            .collect::<Vec<_>>(),
        "new names every file it wrote"
    );
    assert_eq!(
        std::fs::read_dir(project.path()).unwrap().count(),
        1,
        "no staging directory is left beside the library"
    );
    assert_eq!(
        std::fs::read_to_string(root.join("flow.toml")).unwrap(),
        "[process]\ncommand = \"flow-toolkit-rust serve\"\nextract = \"flow-toolkit-rust extract\"\n"
    );
    let manifest = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(manifest.contains("name = \"ledger\""), "{manifest}");
    assert!(
        manifest.contains(&format!(
            "flow-toolkit = {{ path = {:?} }}",
            common::own("").canonicalize().unwrap()
        )),
        "{manifest}"
    );
    assert!(
        std::fs::read_to_string(root.join("contract/lib.flow"))
            .unwrap()
            .contains("pub flow greet(name: Name) -> Greeting"),
    );
    // A checkout's toolkit carries the repository's lock (`seed.rs`).
    let carried = locked(
        &std::fs::read_to_string(flow_testing::repository_root().join("Cargo.lock")).unwrap(),
    );
    for package in locked(&std::fs::read_to_string(root.join("Cargo.lock")).unwrap()) {
        assert!(
            carried.contains(&package),
            "the new library locks {package:?}, which the toolkit's lock does not"
        );
    }

    let again = new(&root);
    assert_eq!(again.status.code(), Some(2));
    assert!(
        String::from_utf8_lossy(&again.stderr).contains("exists"),
        "{}",
        String::from_utf8_lossy(&again.stderr)
    );
    assert_eq!(files(&root), expected, "a refused new writes over nothing");

    let tested = std::process::Command::new(env!("CARGO"))
        .args(["test", "--quiet", "--offline"])
        .current_dir(&root)
        .env("CARGO_TARGET_DIR", project.path().join("target"))
        .locked_output()
        .expect("cargo runs");
    assert!(
        tested.status.success(),
        "{}",
        String::from_utf8_lossy(&tested.stderr)
    );
}

#[test]
fn a_new_rust_library_builds_and_serves_a_program_through_flow() {
    let project = TempDir::with_prefix("flow-new-rust").expect("a directory");
    let root = project.path().join("ledger");
    let made = new(&root);
    assert!(
        made.status.success(),
        "{}",
        String::from_utf8_lossy(&made.stderr)
    );
    std::fs::write(
        root.join("flow.toml"),
        common::flow_toml(common::rust_toolkit()),
    )
    .expect("flow.toml is written");
    let shown = root.to_str().expect("a UTF-8 path");
    let checked = flow(&["build", "--check", shown]);
    assert_eq!(
        checked.status.code(),
        Some(0),
        "the contract is current: {}",
        common::said(&checked)
    );
    let program = project.path().join("main.flow");
    std::fs::write(
        &program,
        "use \"./ledger\"\n\
         pub flow main() -> Result<Text, ToolProblem> = {\n    \
             let greeting = ledger.greet(ledger.Name(\"Ada\"))?\n    \
             Ok(greeting.message)\n}\n",
    )
    .unwrap();
    let run = flow(&["run", program.to_str().unwrap()]);
    assert_eq!(run.status.code(), Some(0), "{}", common::said(&run));
    assert!(
        String::from_utf8_lossy(&run.stdout).contains("Hello, Ada!"),
        "{}",
        common::said(&run)
    );
}