use std::path::{Path, PathBuf};
use crate::workspace::Workspace;
pub(super) use crate::fs_faults::FailAtWrite;
pub(super) use crate::identity::Minter;
pub(super) use prov_graph::exec::block_on;
pub(super) use prov_graph::fs::StdFs;
use prov_store::fs::Storage;
pub(super) use prov_store::index::FileIndex;
pub(super) fn write(dir: &Path, rel: &str, text: &str) {
let p = dir.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
pub(super) fn read(dir: &Path, rel: &str) -> String {
std::fs::read_to_string(dir.join(rel)).unwrap()
}
pub(super) fn tempdir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("prov-mutate-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
pub(super) fn ws(dir: &Path) -> Workspace<StdFs> {
Workspace::builder(StdFs).root(dir).build()
}
pub(super) fn id_ws(dir: &Path) -> Workspace<StdFs, Minter, FileIndex> {
Workspace::builder(StdFs)
.root(dir)
.identity(Minter::lazy(42))
.index(FileIndex::new(fig::Format::Yaml))
.build()
}
pub(super) fn hosted_registry_ws<FS: Storage>(
dir: &Path,
fs: FS,
) -> Workspace<FS, Minter, FileIndex> {
let host = "registry.yaml";
if !dir.join(host).exists() {
write(dir, host, "title: ID registry\n");
}
let text = std::fs::read_to_string(dir.join(host)).unwrap();
Workspace::builder(fs)
.root(dir)
.identity(Minter::eager(7))
.index(FileIndex::parse(Path::new(host), &text).unwrap())
.build()
}
pub(super) fn snapshot(dir: &Path) -> Vec<(String, String)> {
fn walk(dir: &Path, base: &Path, out: &mut Vec<(String, String)>) {
let mut entries: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap())
.collect();
entries.sort_by_key(std::fs::DirEntry::path);
for entry in entries {
let path = entry.path();
if path.is_dir() {
walk(&path, base, out);
} else {
out.push((
path.strip_prefix(base)
.unwrap()
.to_string_lossy()
.into_owned(),
std::fs::read_to_string(&path).unwrap_or_default(),
));
}
}
}
let mut out = Vec::new();
walk(dir, dir, &mut out);
out
}
pub(super) fn failing_ws(dir: &Path, fail_at: usize) -> Workspace<FailAtWrite> {
Workspace::builder(FailAtWrite::nth(fail_at))
.root(dir)
.build()
}
pub(super) fn linked_tree(tag: &str) -> PathBuf {
let dir = tempdir(tag);
write(
&dir,
"index.md",
"---\ntitle: Root\ncontents:\n- a.md\n- b.md\n---\nbody\n",
);
write(
&dir,
"a.md",
"---\ntitle: A\npart_of: index.md\n---\nsee [[b]]\n",
);
write(
&dir,
"b.md",
"---\ntitle: B\npart_of: index.md\nlinks:\n- a.md\n---\nbody\n",
);
dir
}