markupwright 0.1.3

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

#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
    #[error("tool path {} must not be a symbolic link", path.display())]
    Symlink { path: PathBuf },
    #[error("failed to inspect tool path {}: {source}", path.display())]
    Inspect {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

pub(crate) fn ensure_safe(root: &Path) -> Result<(), Error> {
    for relative in [
        crate::layout::DIRECTORY,
        crate::layout::CONFIG,
        crate::layout::GITIGNORE,
        crate::layout::TEMPLATES,
        crate::layout::CACHE,
        crate::layout::CACHE_STATE,
    ] {
        let path = root.join(relative);

        match std::fs::symlink_metadata(&path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(Error::Symlink { path });
            }

            Ok(_) => {}

            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}

            Err(source) => return Err(Error::Inspect { path, source }),
        }
    }

    Ok(())
}

#[cfg(all(test, unix))]
mod tests {
    use std::os::unix::fs::symlink;

    use googletest::prelude::*;

    use super::*;

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

        symlink(
            outside.path(),
            repository.path().join(crate::layout::DIRECTORY),
        )
        .or_fail()?;

        verify_that!(
            ensure_safe(repository.path()),
            err(matches_pattern!(Error::Symlink { .. }))
        )
    }
}