Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

7.8 KB
Raw Blame
// ©AngelaMos | 2026
// layout.rs

use std::path::{Path, PathBuf};

use lisdex_ingest::detect::BuildSystem;

pub const VARIANT_AFL: &str = "afl";
pub const VARIANT_CMPLOG: &str = "cmplog";
pub const VARIANT_BENCH: &str = "bench";
pub const BUILD_DIR_PREFIX: &str = "build";
pub const INSTALL_DIR: &str = "install";
pub const TOOLCHAIN_DIR: &str = "toolchain";
pub const SHADOW_DIR: &str = "shadow";
pub const LOGS_DIR: &str = "logs";
pub const ARTIFACTS_DIR: &str = "artifacts";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildLayout {
    pub source: PathBuf,
    pub work: PathBuf,
}

#[derive(Debug, thiserror::Error)]
pub enum LayoutError {
    #[error(
        "the work directory {work} sits inside the source tree {tree}, so every build \
         directory would test as in-tree: no tier would reset its build directory, tier N+1 \
         would reconfigure on tier N's cache, and artifact discovery would sweep every tier's \
         output into one measurement. Use a work directory outside the source, or exactly the \
         source for a genuine in-tree build"
    )]
    NestedWork { tree: PathBuf, work: PathBuf },
}

fn lexically_absolute(path: &Path) -> PathBuf {
    std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}

impl BuildLayout {
    #[must_use]
    pub fn new(source: impl Into<PathBuf>, work: impl Into<PathBuf>) -> Self {
        Self {
            source: source.into(),
            work: work.into(),
        }
    }

    pub fn validated(
        source: impl Into<PathBuf>,
        work: impl Into<PathBuf>,
    ) -> Result<Self, LayoutError> {
        let layout = Self::new(source, work);
        let source = lexically_absolute(&layout.source);
        let work = lexically_absolute(&layout.work);
        if work != source && work.starts_with(&source) {
            return Err(LayoutError::NestedWork { tree: source, work });
        }
        Ok(layout)
    }

    #[must_use]
    pub fn build_dir(&self, system: BuildSystem, variant: &str) -> PathBuf {
        self.work
            .join(format!("{BUILD_DIR_PREFIX}-{}-{variant}", system.as_str()))
    }

    #[must_use]
    pub fn install_dir(&self, variant: &str) -> PathBuf {
        self.work.join(format!("{INSTALL_DIR}-{variant}"))
    }

    #[must_use]
    pub fn toolchain_dir(&self) -> PathBuf {
        self.work.join(TOOLCHAIN_DIR)
    }

    #[must_use]
    pub fn shadow_dir(&self, variant: &str) -> PathBuf {
        self.work.join(format!("{SHADOW_DIR}-{variant}"))
    }

    #[must_use]
    pub fn logs_dir(&self) -> PathBuf {
        self.work.join(LOGS_DIR)
    }

    #[must_use]
    pub fn artifacts_dir(&self, variant: &str) -> PathBuf {
        self.work.join(format!("{ARTIFACTS_DIR}-{variant}"))
    }

    pub fn prepare(&self) -> std::io::Result<()> {
        std::fs::create_dir_all(&self.work)?;
        std::fs::create_dir_all(self.toolchain_dir())?;
        std::fs::create_dir_all(self.logs_dir())
    }

    pub fn reset_dir(&self, dir: &Path) -> std::io::Result<()> {
        if dir.exists() {
            std::fs::remove_dir_all(dir)?;
        }
        std::fs::create_dir_all(dir)
    }

    #[must_use]
    pub fn is_out_of_tree(&self, build_dir: &Path) -> bool {
        !build_dir.starts_with(&self.source)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn layout() -> BuildLayout {
        BuildLayout::new("/work/src/libpng", "/work/build/libpng")
    }

    #[test]
    fn build_dirs_are_namespaced_by_system_and_variant() {
        assert_eq!(
            layout().build_dir(BuildSystem::CMake, VARIANT_AFL),
            PathBuf::from("/work/build/libpng/build-cmake-afl")
        );
        assert_eq!(
            layout().build_dir(BuildSystem::Autotools, VARIANT_CMPLOG),
            PathBuf::from("/work/build/libpng/build-autotools-cmplog")
        );
    }

    #[test]
    fn the_two_variants_never_share_a_build_dir() {
        let afl = layout().build_dir(BuildSystem::CMake, VARIANT_AFL);
        let cmplog = layout().build_dir(BuildSystem::CMake, VARIANT_CMPLOG);
        assert_ne!(afl, cmplog);
    }

    #[test]
    fn trying_a_second_build_system_does_not_reuse_the_first_ones_directory() {
        let cmake = layout().build_dir(BuildSystem::CMake, VARIANT_AFL);
        let autotools = layout().build_dir(BuildSystem::Autotools, VARIANT_AFL);
        assert_ne!(cmake, autotools);
    }

    #[test]
    fn builds_live_outside_the_source_tree() {
        let layout = layout();
        let build = layout.build_dir(BuildSystem::CMake, VARIANT_AFL);
        assert!(layout.is_out_of_tree(&build));
    }

    #[test]
    fn a_work_directory_nested_in_the_source_is_rejected() {
        assert!(matches!(
            BuildLayout::validated("/work/src/libpng", "/work/src/libpng/work/builds/libpng"),
            Err(LayoutError::NestedWork { .. })
        ));
    }

    #[test]
    fn a_work_directory_equal_to_the_source_is_a_legitimate_in_tree_build() {
        assert!(BuildLayout::validated("/work/src/lua", "/work/src/lua").is_ok());
    }

    #[test]
    fn a_work_directory_beside_the_source_is_accepted() {
        assert!(BuildLayout::validated("/work/src/libpng", "/work/build/libpng").is_ok());
    }

    #[test]
    fn a_sibling_whose_name_merely_starts_with_the_source_name_is_accepted() {
        assert!(BuildLayout::validated("/work/src/png", "/work/src/png-build").is_ok());
    }

    #[test]
    fn a_relative_work_directory_is_compared_lexically_absolute() {
        let source = std::env::current_dir().unwrap();
        assert!(matches!(
            BuildLayout::validated(&source, "nested/builds"),
            Err(LayoutError::NestedWork { .. })
        ));
    }

    #[test]
    fn an_in_tree_build_dir_is_reported_as_such() {
        let layout = BuildLayout::new("/work/src/lua", "/work/src/lua");
        let build = layout.build_dir(BuildSystem::Make, VARIANT_AFL);
        assert!(!layout.is_out_of_tree(&build));
    }

    #[test]
    fn install_and_artifact_dirs_are_variant_scoped() {
        assert_eq!(
            layout().install_dir(VARIANT_AFL),
            PathBuf::from("/work/build/libpng/install-afl")
        );
        assert_eq!(
            layout().artifacts_dir(VARIANT_CMPLOG),
            PathBuf::from("/work/build/libpng/artifacts-cmplog")
        );
    }

    #[test]
    fn prepare_creates_the_scratch_tree() {
        let work = lisdex_core::scratch::path("layout-prepare");
        let _ = std::fs::remove_dir_all(&work);
        let layout = BuildLayout::new("/src", &work);
        layout.prepare().unwrap();
        assert!(layout.toolchain_dir().is_dir());
        assert!(layout.logs_dir().is_dir());
    }

    #[test]
    fn resetting_a_build_dir_clears_stale_state() {
        let work = lisdex_core::scratch::path("layout-reset");
        let _ = std::fs::remove_dir_all(&work);
        let layout = BuildLayout::new("/src", &work);
        layout.prepare().unwrap();
        let dir = layout.build_dir(BuildSystem::CMake, VARIANT_AFL);
        layout.reset_dir(&dir).unwrap();
        std::fs::write(dir.join("CMakeCache.txt"), "stale").unwrap();
        layout.reset_dir(&dir).unwrap();
        assert!(!dir.join("CMakeCache.txt").exists());
    }

    #[test]
    fn a_prepass_directory_is_reset_by_its_own_path_not_a_reparsed_name() {
        let work = lisdex_core::scratch::path("layout-prepass");
        let _ = std::fs::remove_dir_all(&work);
        let layout = BuildLayout::new("/src", &work);
        layout.prepare().unwrap();
        let prepass = layout.build_dir(BuildSystem::CMake, "afl-prepass");
        assert!(prepass.ends_with("build-cmake-afl-prepass"));
        layout.reset_dir(&prepass).unwrap();
        std::fs::write(prepass.join("CMakeCache.txt"), "stale").unwrap();
        layout.reset_dir(&prepass).unwrap();
        assert!(!prepass.join("CMakeCache.txt").exists());
        assert!(!layout.build_dir(BuildSystem::CMake, "prepass").exists());
    }
}