#![cfg(unix)]
mod common;
use flow_start::Spawn as _;
use flow_testing::{Project, Rerun, rerun};
use std::path::{Path, PathBuf};
use std::process::Output;
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";
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()
}
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
}
struct Remote {
project: Project,
commit: String,
}
impl Remote {
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);
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)
}
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)
);
}
fn tree(&self) -> PathBuf {
std::fs::canonicalize(self.path("cache/trees/github.com%2Facme%2Ftools"))
.expect("the repository's trees")
.join(&self.commit)
}
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)
}
}
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");
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);
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());
remote.approve();
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"
);
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));
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"
);
}