#![allow(
dead_code,
unreachable_pub,
reason = "shared by several test binaries, each using part of it"
)]
use flow_start::Spawn as _;
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Output;
use flow_testing::{Outside, Project};
pub fn rust_toolkit() -> &'static str {
flow_testing::rust_toolkit()
.to_str()
.expect("the build directory is UTF-8")
}
pub fn extract(
crate_name: &str,
root: Option<&Path>,
functions: &[flow_toolkit::__bridge::Function],
) -> Result<BTreeMap<flow_types::Segments, String>, flow_toolkit::ContractError> {
flow_toolkit::__bridge::extract(crate_name, root, functions).map(|modules| {
modules
.into_iter()
.map(|(path, module)| (path, flow_abi::contract::print(&module)))
.collect()
})
}
pub fn own(path: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join(path)
}
pub fn outside() -> &'static Outside {
let dir = option_env!("CARGO_TARGET_TMPDIR").map_or_else(
|| std::env::temp_dir().join("flow-toolkit-rust-units"),
PathBuf::from,
);
Outside::of(&dir)
}
pub fn flow(args: &[&str]) -> Output {
Project::new(outside(), &[], &[]).flow(args)
}
pub fn said(output: &Output) -> String {
format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)
}
pub fn flow_fmt(text: &str) -> String {
let project = Project::new(outside(), &[("contract.flow", text)], &[]);
let formatted = project.flow(&["fmt", "contract.flow"]);
assert!(formatted.status.success(), "{}", said(&formatted));
std::fs::read_to_string(project.path().join("contract.flow"))
.expect("the formatted text is read")
}
pub fn stage_contract(
dir: &Path,
contracts: &BTreeMap<flow_types::Segments, String>,
serve: &str,
program: &str,
) -> PathBuf {
let library = dir.join("lib");
std::fs::create_dir_all(library.join("contract")).expect("the library directory is created");
std::fs::write(
library.join("flow.toml"),
format!("[process]\ncommand = '{serve}'\n"),
)
.expect("flow.toml is written");
let mut imports = String::new();
let mut bound = std::collections::BTreeSet::new();
for (module, text) in contracts {
let module = module.as_str();
let file = if module.is_empty() {
library.join("contract/lib.flow")
} else {
library.join("contract").join(format!("{module}.flow"))
};
std::fs::create_dir_all(file.parent().expect("a contract file has a directory"))
.expect("the contract directory is created");
std::fs::write(&file, text).expect("the contract module is written");
let natural = module.rsplit('/').next().filter(|last| !last.is_empty());
match natural {
None if bound.insert("lib".to_owned()) => imports.push_str("use \"./lib\"\n"),
Some(last) if bound.insert(last.to_owned()) => {
writeln!(imports, "use \"./lib/{module}\"").expect("a String takes text");
}
_ => {
let alias = format!("lib_{}", module.replace('/', "_"));
bound.insert(alias.clone());
writeln!(imports, "use \"./lib/{module}\" as {alias}")
.expect("a String takes text");
}
}
}
let main = dir.join("main.flow");
std::fs::write(&main, format!("{imports}{program}")).expect("the program is written");
main
}
pub fn listing(contracts: &BTreeMap<flow_types::Segments, String>, program: &str) -> Vec<u8> {
let project = Project::new(outside(), &[], &[]);
stage_contract(
project.path(),
contracts,
"sh -c \"cp $2 ../listing\" record",
program,
);
let bound = project.flow(&["run", "main.flow"]);
std::fs::read(project.path().join("listing")).unwrap_or_else(|error| {
panic!(
"the host hands the library a listing ({error}): {}",
said(&bound)
)
})
}
pub fn referring(tools: &[&str]) -> String {
let mut main = String::from("pub flow main() -> Int = {\n");
for tool in tools {
writeln!(main, " let _ = {tool}").expect("a String takes text");
}
main.push_str(" 1\n}\n");
main
}
pub fn listed(
contracts: &BTreeMap<flow_types::Segments, String>,
program: &str,
) -> Vec<(flow_abi::description::Identity, flow_abi::TypeSpec)> {
flow_abi::read_listing(&listing(contracts, program))
.expect("the host writes a valid contract file")
.into_iter()
.flat_map(|program| program.tools)
.collect()
}
pub fn modules(out: &Path) -> BTreeMap<flow_types::Segments, String> {
let bytes = std::fs::read(out).expect("the contract file is read");
let contract =
flow_abi::contract::Contract::decode(&bytes).expect("extract writes one contract");
contract
.modules
.into_iter()
.map(|module| {
let path = flow_types::Segments::from_names(module.path.iter().map(String::as_str))
.expect("a contract module's path is a module path");
(path, flow_abi::contract::print(&module.module))
})
.collect()
}
pub fn depfile(path: &Path) -> Vec<PathBuf> {
let text = std::fs::read_to_string(path).expect("the depfile is read");
assert!(
text.is_empty() || text.ends_with('\n'),
"every line ends with a line feed: {text:?}"
);
text.lines().map(PathBuf::from).collect()
}
pub fn catalog(decls: Vec<flow_types::Decl>) -> flow_abi::Catalog {
flow_abi::Catalog::std(decls).expect("regular test declarations")
}
pub fn std_result() -> flow_types::Decl {
use flow_types::{Constructor, EnumShape, Payload};
flow_types::Decl {
lexical_ordinal: 1,
identity: flow_types::Identity {
origin: flow_types::ModulePath::new(
flow_types::Tree::Std,
None,
"result"
.parse::<flow_types::Segments>()
.expect("a test path is a path"),
),
version: Some("v1".into()),
name: "Result".into(),
},
doc: None,
members: Vec::new(),
params: vec!["T".into(), "E".into()],
opaque: false,
body: flow_types::Body::Enum(
EnumShape::new(
"Result",
[
Constructor::new("Ok", Payload::Positional(1)),
Constructor::new("Err", Payload::Positional(1)),
],
),
vec![
vec![flow_types::Type::Param(0)],
vec![flow_types::Type::Param(1)],
],
),
}
}
pub fn bound_call(bound: flow_types::Type, decls: Vec<flow_types::Decl>) -> flow_toolkit::Context {
let catalog = catalog(decls);
let signature = flow_abi::Signature {
params: Vec::new(),
result: flow_types::Type::Text,
generic: vec!["T".into()],
};
let spec = flow_abi::TypeSpec::from_catalog(&catalog, &signature).expect("a served type");
let generic = flow_abi::call_views(&catalog, &signature, &[bound]).expect("the call's views");
flow_toolkit::Context::try_new(
"7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
.parse()
.expect("a call key"),
&spec,
Some(&generic),
flow_toolkit::Cancellation::default(),
)
.expect("the views fit the declaration")
}
pub fn written_at<T: flow_toolkit::Shaped>(
value: &T,
ty: &flow_types::Type,
decls: Vec<flow_types::Decl>,
) -> Option<Vec<u8>> {
let catalog = catalog(decls);
let mut bytes = Vec::new();
flow_abi::write_shaped(&mut bytes, &catalog, ty, value).ok()?;
Some(bytes)
}
pub fn raw(text: &str) -> flow_toolkit::JsonValue {
use flow_toolkit::{Json, JsonValue};
fn of(json: &Json) -> JsonValue {
match json {
Json::Null => JsonValue::Null,
Json::Bool(flag) => JsonValue::Bool(*flag),
Json::Number(number) => JsonValue::Number(number.clone()),
Json::String(text) => JsonValue::Text(text.clone()),
Json::Array(items) => JsonValue::List(items.iter().map(of).collect()),
Json::Object(members) => JsonValue::Object(
members
.iter()
.map(|(name, member)| (name.clone(), of(member)))
.collect(),
),
}
}
of(&flow_toolkit::parse_json(text).expect("JSON"))
}
pub fn names_std(
listed: &[(flow_abi::description::Identity, flow_abi::TypeSpec)],
module: &str,
name: &str,
) -> bool {
listed.iter().any(|(_, spec)| {
spec.catalog().decls().any(|(_, decl)| {
decl.identity.name == name
&& *decl.identity.origin.tree() == flow_types::Tree::Std
&& *decl.identity.origin.segments() == module
})
})
}
pub fn tool_names(listed: &[(flow_abi::description::Identity, flow_abi::TypeSpec)]) -> Vec<&str> {
let mut names: Vec<&str> = listed
.iter()
.filter(|(identity, _)| {
identity
.library
.as_ref()
.is_none_or(|library| library.address != "std")
})
.map(|(identity, _)| identity.name.as_str())
.collect();
names.sort_unstable();
names
}
pub fn local(name: &str, params: &[&str], body: flow_types::Body) -> flow_types::Decl {
flow_types::Decl {
lexical_ordinal: 1,
identity: flow_types::Identity {
origin: flow_types::ModulePath::new(
flow_types::Tree::Local,
None,
"main"
.parse::<flow_types::Segments>()
.expect("a test path is a path"),
),
version: None,
name: name.into(),
},
doc: None,
members: Vec::new(),
params: params.iter().map(|param| (*param).to_owned()).collect(),
opaque: false,
body,
}
}
pub fn runtime_bytes(catalog: &flow_abi::Catalog, ty: &flow_types::Type, json: &str) -> Vec<u8> {
let limits = flow_abi::Limits::default();
let json = flow_abi::parse(json, &limits).expect("JSON");
let value = flow_abi::decode(catalog, ty, &json, flow_abi::Mode::Rebuild, &limits)
.expect("the runtime reads the JSON form");
flow_abi::encode_bytes(catalog, ty, &value).expect("the runtime writes the value")
}
pub fn reread<T: flow_toolkit::Shaped>(
catalog: &flow_abi::Catalog,
ty: &flow_types::Type,
bytes: &[u8],
) -> (T, Vec<u8>) {
let mut reader = flow_abi::primitives::Reader::new(bytes);
let value: T = flow_abi::read_shaped(
&mut reader,
catalog,
ty,
flow_abi::Mode::Rebuild,
&flow_abi::Limits::default(),
)
.expect("one of the Rust type's");
assert!(reader.is_empty(), "the bytes are one whole value");
let mut out = Vec::new();
flow_abi::write_shaped(&mut out, catalog, ty, &value).expect("it is written");
(value, out)
}
pub fn stage_native_conformance(project: &Path, executable: &str) -> String {
let native = project.join("tools");
std::fs::create_dir(&native).expect("the fixture directory is created");
for file in ["tools.rs", "sample.rs"] {
std::fs::copy(own(&format!("tests/conformance/{file}")), native.join(file))
.expect("the fixture file is copied");
}
std::fs::write(native.join("flow.toml"), flow_toml(executable)).expect("flow.toml is written");
toolkit_consumer(
&native,
"staged-native-conformance",
"[lib]\npath=\"tools.rs\"\n",
);
"./tools".into()
}
pub fn flow_toml(executable: &str) -> String {
format!("[process]\ncommand = '\"{executable}\" serve'\nextract = '\"{executable}\" extract'\n")
}
pub fn new_library(executable: &str, root: &Path) {
let made = toolkit(executable)
.arg("new")
.arg(root)
.locked_output()
.expect("the toolkit runs");
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
std::fs::write(root.join("flow.toml"), flow_toml(executable)).expect("flow.toml is written");
}
pub fn cache_home() -> PathBuf {
std::env::temp_dir().join("flow-toolkit-rust-tests")
}
pub fn toolkit(executable: &str) -> std::process::Command {
let mut command = std::process::Command::new(executable);
command.env("XDG_CACHE_HOME", cache_home());
command
}
pub fn launcher_cache(root: &Path) -> PathBuf {
use sha2::Digest as _;
let root = root.canonicalize().expect("the path exists");
let digest = sha2::Sha256::digest(root.as_os_str().as_encoded_bytes());
let key = digest.iter().fold(String::new(), |mut key, byte| {
use std::fmt::Write as _;
let _ = write!(key, "{byte:02x}");
key
});
cache_home()
.join("flow-toolkit-rust/libraries")
.join(&key[..32])
.join("build")
}
pub fn toolkit_consumer(root: &Path, name: &str, extra: &str) {
let sdk = own("")
.canonicalize()
.expect("the toolkit's directory exists");
let manifest = format!(
"[package]\nname={name:?}\nversion=\"0.0.0\"\nedition=\"2024\"\n[workspace]\n[dependencies]\nflow-toolkit={{path={}}}\n{extra}",
flow_abi::Json::String(sdk.to_str().expect("a UTF-8 path").into()).canonical()
);
std::fs::write(root.join("Cargo.toml"), manifest).expect("Cargo.toml is written");
flow_testing::lock_from_repository(root);
}
pub fn echo_contract() -> Vec<u8> {
use flow_abi::contract;
let text = || contract::TypeRef::named("Text");
let echo = contract::FlowDeclaration {
name: "echo".to_owned(),
generics: Vec::new(),
params: vec![contract::Param {
name: "value".to_owned(),
ty: text(),
default: None,
}],
result: contract::TypeRef::applied("Result", vec![text(), text()]),
};
contract::Contract {
modules: vec![contract::Module {
path: Vec::new(),
module: contract::ContractModule {
generated_from: "rust module fixture".to_owned(),
imports: Vec::new(),
items: vec![contract::Item {
docs: String::new(),
origin: None,
declaration: contract::Declaration::Flow(echo),
}],
},
}],
}
.bytes()
}
pub fn printf_format(bytes: &[u8]) -> String {
bytes.iter().fold(String::new(), |mut out, byte| {
let _ = write!(out, "\\{byte:03o}");
out
})
}