use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
#[derive(Debug, Clone)]
pub struct RenderedFile {
pub bytes: Vec<u8>,
pub media_type: String,
}
#[derive(Debug)]
pub struct RenderedSite {
pub(super) page_count: usize,
pub(super) files: BTreeMap<String, RenderedFile>,
pub(super) redirects: BTreeMap<String, String>,
}
impl RenderedSite {
pub fn page_count(&self) -> usize {
self.page_count
}
pub fn files(&self) -> &BTreeMap<String, RenderedFile> {
&self.files
}
pub fn redirects(&self) -> &BTreeMap<String, String> {
&self.redirects
}
pub fn publish(&self, output: &Path) -> Result<(), crate::site::SiteError> {
self.publish_reported(output, &crate::reporting::Reporting::default())
}
pub(crate) fn publish_reported(
&self,
output: &Path,
reporting: &crate::reporting::Reporting,
) -> Result<(), crate::site::SiteError> {
use crate::site::SiteError;
let mut progress = reporting.stage("Publishing site", Some(self.files.len()));
let parent = output
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
if let Ok(metadata) = fs::symlink_metadata(output) {
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(SiteError::UnownedOutput);
}
if fs::read_dir(output)?.next().is_some() && !output.join(".diplodocus-site").is_file()
{
return Err(SiteError::UnownedOutput);
}
}
let stage = tempfile::Builder::new()
.prefix(".diplodocus-site-")
.tempdir_in(parent)?;
for (path, file) in &self.files {
progress.item(path);
let path = stage.path().join(path);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, &file.bytes)?;
progress.advance();
}
fs::write(
stage.path().join(".diplodocus-site"),
b"diplodocus-site-v1\n",
)?;
if output.exists() {
#[cfg(target_os = "linux")]
rustix::fs::renameat_with(
rustix::fs::CWD,
stage.path(),
rustix::fs::CWD,
output,
rustix::fs::RenameFlags::EXCHANGE,
)
.map_err(std::io::Error::from)?;
#[cfg(not(target_os = "linux"))]
{
let backup = tempfile::Builder::new()
.prefix(".diplodocus-old-")
.tempdir_in(parent)?;
let old = backup.path().join("site");
fs::rename(output, &old)?;
if let Err(error) = fs::rename(stage.path(), output) {
fs::rename(old, output)?;
return Err(error.into());
}
}
} else {
fs::rename(stage.path(), output)?;
}
progress.finish();
Ok(())
}
}