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 program outside the repository importing a remote Rust library
//! (`guides/cli.md`, *Approve a repository's native code*): it runs only
//! once its commit is approved, and the toolkit builds it on demand into its
//! own cache, keyed by the fetched library's root, and serves it from there;
//! a later run reuses that build; `flow check` never builds, approved or
//! not; the fetched tree is never written. A library whose build fails is
//! refused before anything is recorded, naming what Cargo said.
//!
//! The repository here keeps its `Cargo.lock` at its workspace root, as
//! Flow's own libraries do, and is fetched over `file://`. The launcher is
//! built for real, which is slow, so the tests are few.

#![cfg(unix)]

mod common;

use flow_start::Spawn as _;
use flow_testing::{Project, Rerun, rerun};
use std::path::{Path, PathBuf};
use std::process::Output;

/// The program, outside the repository, using the library at `v1`.
const MAIN: &str = "use \"github.com/acme/tools@v1/ledger\"\n\
pub flow main() -> Result<Text, ToolProblem> = {\n    \
    let greeting = ledger.greet(ledger.Name(\"Ada\"))?\n    \
    Ok(greeting.message)\n}\n";

/// Runs `git` in `dir`, apart from the user's and the system's
/// configuration, and returns what it printed.
fn git(dir: &Path, args: &[&str]) -> String {
    let mut command = std::process::Command::new("git");
    let output = flow_testing::without_git_configuration(&mut command)
        .current_dir(dir)
        .args(["-c", "init.defaultBranch=main", "-c", "tag.gpgSign=false"])
        .args(args)
        .env("GIT_AUTHOR_NAME", "Flow Test")
        .env("GIT_AUTHOR_EMAIL", "test@example.com")
        .env("GIT_COMMITTER_NAME", "Flow Test")
        .env("GIT_COMMITTER_EMAIL", "test@example.com")
        .env("GIT_TERMINAL_PROMPT", "0")
        .locked_output()
        .expect("git runs");
    assert!(
        output.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout)
        .expect("UTF-8")
        .trim()
        .to_owned()
}

/// Every file under `dir`, relative to it, in order, with its bytes.
fn files(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
    fn walk(root: &Path, dir: &Path, out: &mut Vec<(PathBuf, Vec<u8>)>) {
        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_owned(),
                    std::fs::read(&path).expect("a file is read"),
                ));
            }
        }
    }
    let mut out = Vec::new();
    walk(dir, dir, &mut out);
    out.sort();
    out
}

/// A project holding a repository with the Rust library `ledger`, a cache,
/// a program using it and, in the project's Flow home, the program's runs.
struct Remote {
    project: Project,
    commit: String,
}

impl Remote {
    /// The repository released at `v1`, its library made by
    /// `flow-toolkit-rust new` and moved into a workspace whose lock is at the repository's
    /// root, with its `src/lib.rs` replaced by `source` when given.
    fn released(source: Option<&str>) -> Remote {
        let project = Project::new(common::outside(), &[("program/main.flow", MAIN)], &[]);
        let repository = project.path().join("repository");
        let library = repository.join("ledger");
        std::fs::create_dir(&repository).expect("the repository's directory");
        common::new_library(common::rust_toolkit(), &library);
        // One workspace for the repository, as Flow's own libraries keep:
        // the library joins it, and its lock moves to the workspace's root.
        let manifest = library.join("Cargo.toml");
        let own = std::fs::read_to_string(&manifest).expect("Cargo.toml");
        let joined = own
            .replace(
                "# A workspace of its own; remove this table to join an enclosing one.\n",
                "",
            )
            .replace("[workspace]\n", "");
        assert_ne!(joined, own, "the library had a workspace of its own");
        std::fs::write(&manifest, joined).expect("Cargo.toml is written");
        std::fs::write(
            repository.join("Cargo.toml"),
            "[workspace]\nmembers = [\"ledger\"]\nresolver = \"3\"\n",
        )
        .expect("the workspace");
        std::fs::rename(library.join("Cargo.lock"), repository.join("Cargo.lock"))
            .expect("the lock moves to the workspace root");
        if let Some(source) = source {
            std::fs::write(library.join("src/lib.rs"), source).expect("the source");
        }
        git(&repository, &["init", "-q"]);
        git(&repository, &["add", "-A"]);
        git(&repository, &["commit", "-q", "-m", "ledger"]);
        git(&repository, &["tag", "v1"]);
        let commit = git(&repository, &["rev-parse", "HEAD"]);
        Remote { project, commit }
    }

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

    /// Runs `flow` with `args` in the project, fetching
    /// `github.com/acme/tools` from the repository, through git's own
    /// `url.<base>.insteadOf`, into the project's cache, and with the
    /// toolkit building in the tests' [`common::cache_home`].
    fn flow(&self, args: &[&str]) -> Output {
        let mut command = self.project.command();
        flow_testing::without_git_configuration(&mut command)
            .env("FLOW_CACHE", self.path("cache"))
            .env_remove("FLOW_OFFLINE")
            .env("XDG_CACHE_HOME", common::cache_home())
            .env("GIT_CONFIG_COUNT", "1")
            .env(
                "GIT_CONFIG_KEY_0",
                format!("url.file://{}.insteadOf", self.path("repository").display()),
            )
            .env("GIT_CONFIG_VALUE_0", "https://github.com/acme/tools")
            .args(args)
            .locked_output()
            .expect("flow runs")
    }

    fn program(&self) -> String {
        self.path("program/main.flow")
            .to_str()
            .expect("UTF-8")
            .to_owned()
    }

    fn run(&self) -> Output {
        self.flow(&["run", &self.program()])
    }

    fn approve(&self) {
        let approved = self.flow(&["approve", &self.program(), "--yes"]);
        assert_eq!(
            approved.status.code(),
            Some(0),
            "{}",
            common::said(&approved)
        );
    }

    /// The fetched tree of the commit.
    fn tree(&self) -> PathBuf {
        std::fs::canonicalize(self.path("cache/trees/github.com%2Facme%2Ftools"))
            .expect("the repository's trees")
            .join(&self.commit)
    }

    /// Where the toolkit keeps the library's build: its directory in the
    /// cache, keyed by the fetched library's canonical root.
    fn slot(&self) -> PathBuf {
        common::launcher_cache(&self.tree().join("ledger"))
            .parent()
            .expect("a build is in its library's directory")
            .to_owned()
    }

    fn runs_recorded(&self) -> usize {
        std::fs::read_dir(self.project.home().join("runs")).map_or(0, Iterator::count)
    }
}

/// Whether to run the test's body here: in a child process of this test
/// with no Rust flags of its own; otherwise it runs that child and says so.
///
/// The library's build is its own, not this test's: flags a coverage run
/// gives this process, such as `-C instrument-coverage`, would reach the
/// nested Cargo build through the environment, and on Linux they make its
/// dependencies' build scripts fail. Without `git` the test fails.
fn apart_from_the_test_s_rustflags<T: Fn()>(test: T) -> bool {
    let Rerun::Parent(mut child) = rerun(test) else {
        return true;
    };
    flow_testing::require_program("git");
    // Every way Cargo is handed Rust flags: `RUSTFLAGS`, its encoded and
    // `build.` forms and each `target.<triple>.rustflags`; and the wrapper a
    // coverage run puts around `rustc`, which is cargo-llvm-cov's own, in
    // place of the one there was before it (sccache, say).
    let removed: Vec<std::ffi::OsString> = std::env::vars_os()
        .map(|(key, _)| key)
        .filter(|key| {
            key.to_str().is_some_and(|key| {
                key.ends_with("RUSTFLAGS")
                    || key == "RUSTC_WORKSPACE_WRAPPER"
                    || key.starts_with("__CARGO_LLVM_COV")
            })
        })
        .collect();
    for key in &removed {
        child.env_remove(key);
    }
    if std::env::var_os("__CARGO_LLVM_COV_RUSTC_WRAPPER").is_some() {
        match std::env::var_os("__CARGO_LLVM_COV_RUSTC_WRAPPER_PRE_EXISTING")
            .filter(|wrapper| !wrapper.is_empty())
        {
            Some(wrapper) => child.env("RUSTC_WRAPPER", wrapper),
            None => child.env_remove("RUSTC_WRAPPER"),
        };
    }
    let child = child.locked_output().expect("the test runs as a child");
    let names: Vec<String> = std::env::vars_os()
        .filter_map(|(key, _)| key.into_string().ok())
        .filter(|key| {
            key.contains("RUST") || key.starts_with("CARGO_LLVM") || key.starts_with("CARGO_TARGET")
        })
        .collect();
    assert!(
        child.status.success(),
        "{}{}\n(removed {removed:?}; variables named for Rust here: {names:?})",
        String::from_utf8_lossy(&child.stdout),
        String::from_utf8_lossy(&child.stderr)
    );
    false
}

#[test]
fn an_approved_remote_rust_library_is_built_once_into_the_cache_and_served_from_it() {
    if !apart_from_the_test_s_rustflags(
        an_approved_remote_rust_library_is_built_once_into_the_cache_and_served_from_it,
    ) {
        return;
    }
    let remote = Remote::released(None);

    // Not approved: refused, and nothing is built.
    let refused = remote.run();
    let said = common::said(&refused);
    assert_ne!(refused.status.code(), Some(0), "{said}");
    assert!(said.contains("implementation-not-approved"), "{said}");
    assert!(!remote.slot().exists(), "an unapproved library was built");
    assert_eq!(remote.runs_recorded(), 0, "a refused run recorded nothing");
    let fetched = files(&remote.tree());

    // Approved: the first run builds it into its slot and runs.
    remote.approve();
    // Checking the program never builds it, approved or not: only a run
    // that binds it does.
    let checked = remote.flow(&["check", &remote.program()]);
    assert_eq!(checked.status.code(), Some(0), "{}", common::said(&checked));
    assert!(!remote.slot().exists(), "`flow check` built the library");
    let ran = remote.run();
    assert_eq!(ran.status.code(), Some(0), "{}", common::said(&ran));
    assert!(
        String::from_utf8_lossy(&ran.stdout).contains("Hello, Ada!"),
        "{}",
        common::said(&ran)
    );
    assert!(
        remote.slot().is_dir(),
        "the toolkit built it into its cache"
    );
    assert_eq!(
        files(&remote.tree()),
        fetched,
        "the fetched tree is never written"
    );

    // A later run reuses the build.
    let again = remote.run();
    assert_eq!(again.status.code(), Some(0), "{}", common::said(&again));
    assert!(
        String::from_utf8_lossy(&again.stdout).contains("Hello, Ada!"),
        "{}",
        common::said(&again)
    );
}

#[test]
fn a_remote_rust_library_that_does_not_build_is_refused_naming_it_and_cargo_s_cause() {
    if !apart_from_the_test_s_rustflags(
        a_remote_rust_library_that_does_not_build_is_refused_naming_it_and_cargo_s_cause,
    ) {
        return;
    }
    let remote = Remote::released(Some(
        "use flow_toolkit::{Flow, tool};\n\
         #[derive(Flow, Debug, PartialEq)]\npub struct Name(pub String);\n\
         #[derive(Flow, Debug, PartialEq)]\npub struct Greeting { pub message: String }\n\
         #[tool]\npub fn greet(name: Name) -> Greeting { Greeting { message: missing_value } }\n",
    ));
    remote.approve();
    let refused = remote.run();
    assert_ne!(refused.status.code(), Some(0), "{}", common::said(&refused));
    // As one line: the human report wraps its message.
    let said = common::said(&refused)
        .split_whitespace()
        .filter(|word| *word != "│")
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        said.contains("error[E0425]: cannot find value `missing_value` in this scope"),
        "Cargo's cause: {said}"
    );
    assert_eq!(remote.runs_recorded(), 0, "a refused run recorded nothing");
    assert!(
        !remote.tree().join("ledger/target").exists() && !remote.tree().join("target").exists(),
        "nothing is built into the fetched tree"
    );
}