markupwright 0.1.3

Template-driven workspace documentation generator
Documentation
use std::{
    io::Write as _,
    path::{Path, PathBuf},
};

const CONFIG_TEMPLATE: &str = r#"version = 1

[workspace]
name = __WORKSPACE_NAME__

[render]
templates = ".markupwright/templates"
header = "header.md.j2"
navigation = "README.md"
source-suffix = ".in"

[domains]

[[documents]]
include = ["README.md.in"]
template = "readme-root.md.j2"

[[documents]]
include = ["**/*.md.in"]
template = "document.md.j2"
"#;

const GITIGNORE: &str = "cache/\n";

#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
    #[error("unsafe Markupwright layout: {source}")]
    UnsafeLayout {
        #[source]
        source: crate::fs::tool_layout::Error,
    },

    #[error("{} already exists; refusing to replace it", path.display())]
    Existing { path: PathBuf },

    #[error("failed to create {}: {source}", path.display())]
    CreateDirectory {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("failed to write {}: {source}", path.display())]
    Write {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

pub(crate) fn initialize(root: &Path) -> Result<(), Error> {
    crate::fs::tool_layout::ensure_safe(root).map_err(|source| Error::UnsafeLayout { source })?;

    let directory = root.join(crate::layout::DIRECTORY);
    let config = root.join(crate::layout::CONFIG);
    let gitignore = root.join(crate::layout::GITIGNORE);

    ensure_absent(&config)?;
    ensure_absent(&gitignore)?;
    let templates = root.join(crate::layout::TEMPLATES);
    let mut created = Vec::new();
    let result = (|| {
        create_directory(&directory, &mut created)?;
        create_directory(&templates, &mut created)?;
        create_file(&gitignore, GITIGNORE)?;
        created.push(Created::File(gitignore));
        create_file(&config, &config_source(root))?;
        created.push(Created::File(config));

        Ok(())
    })();

    if result.is_err() {
        rollback(&created);
    }

    result
}

#[derive(Debug)]
enum Created {
    Directory(PathBuf),
    File(PathBuf),
}

fn config_source(root: &Path) -> String {
    let name = root
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("workspace");
    let name = toml::Value::String(name.to_owned()).to_string();

    CONFIG_TEMPLATE.replace("__WORKSPACE_NAME__", &name)
}

fn ensure_absent(path: &Path) -> Result<(), Error> {
    match crate::fs::symlink_metadata(path) {
        Ok(_) => Err(Error::Existing {
            path: path.to_path_buf(),
        }),

        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),

        Err(source) => Err(Error::Write {
            path: path.to_path_buf(),
            source,
        }),
    }
}

fn create_directory(path: &Path, created: &mut Vec<Created>) -> Result<(), Error> {
    if path.is_dir() {
        return Ok(());
    }

    crate::fs::create_dir_all(path).map_err(|source| Error::CreateDirectory {
        path: path.to_path_buf(),
        source,
    })?;
    created.push(Created::Directory(path.to_path_buf()));

    Ok(())
}

fn create_file(path: &Path, contents: &str) -> Result<(), Error> {
    let Some(parent) = path.parent() else {
        return Err(Error::Write {
            path: path.to_path_buf(),
            source: std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "destination has no parent",
            ),
        });
    };
    let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|source| Error::Write {
        path: path.to_path_buf(),
        source,
    })?;

    temporary
        .write_all(contents.as_bytes())
        .map_err(|source| Error::Write {
            path: path.to_path_buf(),
            source,
        })?;
    temporary.flush().map_err(|source| Error::Write {
        path: path.to_path_buf(),
        source,
    })?;
    temporary
        .as_file()
        .sync_all()
        .map_err(|source| Error::Write {
            path: path.to_path_buf(),
            source,
        })?;
    temporary
        .persist_noclobber(path)
        .map_err(|error| Error::Write {
            path: path.to_path_buf(),
            source: error.error,
        })?;

    Ok(())
}

fn rollback(created: &[Created]) {
    for entry in created.iter().rev() {
        match entry {
            Created::Directory(path) => {
                let _result = crate::fs::remove_dir(path);
            }

            Created::File(path) => {
                let _result = crate::fs::remove_file(path);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use googletest::prelude::*;

    use super::*;

    #[gtest]
    fn creates_complete_layout() -> Result<()> {
        let directory = tempfile::tempdir().or_fail()?;

        initialize(directory.path()).or_fail()?;
        let config_path = directory.path().join(crate::layout::CONFIG);
        let source = fs::read_to_string(&config_path).or_fail()?;

        crate::config::Config::parse(&source, &config_path).or_fail()?;

        verify_eq!(
            fs::read_to_string(directory.path().join(crate::layout::CONFIG)).or_fail()?,
            config_source(directory.path())
        )?;
        verify_eq!(
            fs::read_to_string(directory.path().join(crate::layout::GITIGNORE)).or_fail()?,
            GITIGNORE
        )?;
        verify_true!(directory.path().join(".markupwright/templates").is_dir())
    }

    #[gtest]
    fn refuses_to_replace_existing_configuration() -> Result<()> {
        let directory = tempfile::tempdir().or_fail()?;
        let tool_directory = directory.path().join(".markupwright");

        fs::create_dir(&tool_directory).or_fail()?;
        fs::write(tool_directory.join("config.toml"), "existing\n").or_fail()?;

        let error = initialize(directory.path()).expect_err("existing config must be rejected");

        verify_that!(error, matches_pattern!(Error::Existing { .. }))?;
        verify_false!(tool_directory.join(".gitignore").exists())
    }
}