use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
use super::{WorkspaceFile, WorkspaceIndex};
#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
#[error("workspace discovery failed: {0}")]
Discovery(Box<str>),
#[error("workspace loading failed: {0}")]
Files(Box<str>),
#[error("workspace metadata failed: {0}")]
Metadata(#[source] crate::domain::Error),
#[error("workspace checksum failed: {0}")]
Checksum(#[source] crate::fs::checksum::Error),
#[error(transparent)]
Config(#[from] crate::config::Error),
}
#[derive(Debug)]
pub(crate) struct Files {
root: PathBuf,
entries: Vec<WorkspaceFile>,
checksums: BTreeMap<PathBuf, crate::fs::checksum::FileChecksum>,
checksum: crate::fs::checksum::Checksum,
config: crate::config::Config,
}
impl Files {
#[must_use]
pub(crate) const fn checksum(&self) -> crate::fs::checksum::Checksum {
self.checksum
}
pub(crate) fn into_workspace(self) -> Result<Loaded, Error> {
let workspace = WorkspaceIndex::try_new(self.root.clone(), self.entries, self.config)
.map_err(Error::Metadata)?;
Ok(Loaded {
workspace,
root: self.root,
checksums: self.checksums,
})
}
}
#[derive(Debug)]
pub(crate) struct Loaded {
pub(crate) workspace: WorkspaceIndex,
root: PathBuf,
checksums: BTreeMap<PathBuf, crate::fs::checksum::FileChecksum>,
}
impl Loaded {
pub(crate) fn checksum_with(
&self,
replacements: &[(PathBuf, crate::fs::checksum::FileChecksum)],
) -> Result<crate::fs::checksum::Checksum, crate::fs::checksum::Error> {
let mut checksums = self.checksums.clone();
checksums.extend(replacements.iter().cloned());
crate::fs::checksum::tree_map(&self.root, &checksums)
}
}
#[derive(Debug, thiserror::Error)]
#[error("{}: failed to read: {source}", path.display())]
struct FileError {
path: PathBuf,
#[source]
source: std::io::Error,
}
#[cfg(test)]
fn load(root: &Path) -> Result<(Loaded, Vec<PathBuf>), Error> {
let paths = discover(root)?;
let workspace = read_paths(root, &paths)?.into_workspace()?;
Ok((workspace, paths))
}
pub(crate) fn discover(root: &Path) -> Result<Vec<PathBuf>, Error> {
let (mut paths, failures) = crate::fs::walk::workspace_source_files(root).into_parts();
if !failures.is_empty() {
let mut failures = failures
.into_iter()
.map(|error| format!("walk error: {error}"))
.collect::<Vec<_>>();
failures.sort_unstable();
failures.dedup();
return Err(Error::Discovery(failures.join("; ").into_boxed_str()));
}
let config = root.join(crate::layout::CONFIG);
match crate::fs::symlink_metadata(&config) {
Ok(_) if !paths.contains(&config) => paths.push(config),
Ok(_) => {}
Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
Err(source) => {
return Err(Error::Discovery(
format!("failed to inspect {}: {source}", config.display()).into_boxed_str(),
));
}
}
paths.sort();
Ok(paths)
}
pub(crate) fn read_paths(root: &Path, paths: &[PathBuf]) -> Result<Files, Error> {
let mut entries = Vec::new();
let mut checksums = BTreeMap::new();
let mut failures = Vec::new();
for path in paths {
match load_file(path.clone(), root) {
Ok((file, checksum)) => {
checksums.insert(file.path.clone(), checksum);
entries.push(file);
}
Err(error) => failures.push(error.to_string()),
}
}
if !failures.is_empty() {
failures.sort_unstable();
failures.dedup();
return Err(Error::Files(failures.join("; ").into_boxed_str()));
}
let checksum = crate::fs::checksum::tree_map(root, &checksums).map_err(Error::Checksum)?;
let config_path = root.join(crate::layout::CONFIG);
let config_file = entries.iter().find(|entry| entry.path == config_path);
let config = crate::config::Config::indexed(
&config_path,
config_file.and_then(|entry| entry.contents.as_deref()),
config_file.is_some(),
)?;
Ok(Files {
root: root.to_path_buf(),
entries,
checksums,
checksum,
config,
})
}
fn load_file(
path: PathBuf,
root: &Path,
) -> Result<(WorkspaceFile, crate::fs::checksum::FileChecksum), FileError> {
let bytes = crate::fs::read(&path).map_err(|source| FileError {
path: path.strip_prefix(root).unwrap_or(&path).to_path_buf(),
source,
})?;
let checksum = crate::fs::checksum::contents(&bytes);
let contents = String::from_utf8(bytes).ok().map(String::into_boxed_str);
Ok((WorkspaceFile { path, contents }, checksum))
}
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
#[gtest]
fn binary_files_remain_indexed_without_text_contents() -> Result<()> {
let directory = tempfile::tempdir().or_fail()?;
let path = directory.path().join("image.png");
std::fs::create_dir(directory.path().join(".markupwright")).or_fail()?;
std::fs::write(
directory.path().join(".markupwright/config.toml"),
r#"version = 1
[workspace]
[render]
templates = ".markupwright/templates"
header = "header.md.j2"
navigation = "README.md"
source-suffix = ".in"
[domains]
[[documents]]
include = ["*.md.in"]
template = "document.md.j2"
"#,
)
.or_fail()?;
std::fs::write(&path, [0xff]).or_fail()?;
let (loaded, _) = load(directory.path()).or_fail()?;
verify_true!(loaded.workspace.contains(&path))?;
verify_eq!(loaded.workspace.contents(&path), None)
}
#[gtest]
fn workspace_file_read_errors_are_contextual() -> Result<()> {
let directory = tempfile::tempdir().or_fail()?;
let path = directory.path().join("missing.md.in");
let error = load_file(path, directory.path()).unwrap_err().to_string();
verify_that!(
error.as_str(),
starts_with("missing.md.in: failed to read:")
)
}
}