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 👇

21.7 KB
Raw Blame
// ©AngelaMos | 2026
// detect.rs

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

pub const MESON_BUILD: &str = "meson.build";
pub const BAZEL_WORKSPACE: [&str; 3] = ["WORKSPACE", "WORKSPACE.bazel", "MODULE.bazel"];
pub const BAZEL_BUILD: [&str; 2] = ["BUILD", "BUILD.bazel"];
pub const CMAKE_LISTS: &str = "CMakeLists.txt";
pub const CMAKE_PRESETS: &str = "CMakePresets.json";
pub const CONFIGURE_AC: [&str; 2] = ["configure.ac", "configure.in"];
pub const AUTOGEN: [&str; 3] = ["autogen.sh", "bootstrap", "buildconf"];
pub const CONFIGURE_SCRIPT: &str = "configure";
pub const MAKEFILE_AM: &str = "Makefile.am";
pub const MAKEFILE_IN: &str = "Makefile.in";
pub const SCONS_SCRIPT: &str = "SConstruct";
pub const WAF_SCRIPT: &str = "wscript";
pub const MAKEFILE: [&str; 3] = ["GNUmakefile", "Makefile", "makefile"];

pub const VENDORED_DIRS: [&str; 18] = [
    "contrib",
    "third_party",
    "thirdparty",
    "3rdparty",
    "external",
    "externals",
    "deps",
    "dependencies",
    "vendor",
    "subprojects",
    "debian",
    "test",
    "tests",
    "example",
    "examples",
    "doc",
    "docs",
    "node_modules",
];

pub const NESTED_SEARCH_MAX_DEPTH: usize = 4;

pub const PRECEDENCE: [BuildSystem; 7] = [
    BuildSystem::Meson,
    BuildSystem::Bazel,
    BuildSystem::CMake,
    BuildSystem::Autotools,
    BuildSystem::Scons,
    BuildSystem::Waf,
    BuildSystem::Make,
];

#[derive(Debug, thiserror::Error)]
pub enum DetectError {
    #[error("io error reading {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("{0} is not a directory")]
    NotADirectory(PathBuf),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuildSystem {
    Meson,
    Bazel,
    CMake,
    Autotools,
    Scons,
    Waf,
    Make,
}

impl BuildSystem {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            BuildSystem::Meson => "meson",
            BuildSystem::Bazel => "bazel",
            BuildSystem::CMake => "cmake",
            BuildSystem::Autotools => "autotools",
            BuildSystem::Scons => "scons",
            BuildSystem::Waf => "waf",
            BuildSystem::Make => "make",
        }
    }

    #[must_use]
    pub fn is_supported(self) -> bool {
        matches!(
            self,
            BuildSystem::CMake | BuildSystem::Meson | BuildSystem::Autotools | BuildSystem::Make
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Marker {
    MesonBuild,
    BazelWorkspace,
    BazelBuild,
    CMakeLists,
    CMakePresets,
    ConfigureAc,
    Autogen,
    ConfigureScript,
    MakefileAm,
    MakefileIn,
    SconsScript,
    WafScript,
    Makefile,
}

impl Marker {
    #[must_use]
    pub fn system(self) -> BuildSystem {
        match self {
            Marker::MesonBuild => BuildSystem::Meson,
            Marker::BazelWorkspace | Marker::BazelBuild => BuildSystem::Bazel,
            Marker::CMakeLists | Marker::CMakePresets => BuildSystem::CMake,
            Marker::ConfigureAc
            | Marker::Autogen
            | Marker::ConfigureScript
            | Marker::MakefileAm
            | Marker::MakefileIn => BuildSystem::Autotools,
            Marker::SconsScript => BuildSystem::Scons,
            Marker::WafScript => BuildSystem::Waf,
            Marker::Makefile => BuildSystem::Make,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Evidence {
    pub marker: Marker,
    pub file: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Bootstrap {
    Autogen(String),
    Autoreconf,
    None,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Detection {
    pub root: PathBuf,
    pub evidence: Vec<Evidence>,
    pub candidates: Vec<BuildSystem>,
}

impl Detection {
    #[must_use]
    pub fn has(&self, marker: Marker) -> bool {
        self.evidence.iter().any(|found| found.marker == marker)
    }

    #[must_use]
    pub fn file_for(&self, marker: Marker) -> Option<&str> {
        self.evidence
            .iter()
            .find(|found| found.marker == marker)
            .map(|found| found.file.as_str())
    }

    #[must_use]
    pub fn primary(&self) -> Option<BuildSystem> {
        self.candidates.first().copied()
    }

    #[must_use]
    pub fn supported(&self) -> Vec<BuildSystem> {
        self.candidates
            .iter()
            .copied()
            .filter(|system| system.is_supported())
            .collect()
    }

    #[must_use]
    pub fn unsupported(&self) -> Vec<BuildSystem> {
        self.candidates
            .iter()
            .copied()
            .filter(|system| !system.is_supported())
            .collect()
    }

    #[must_use]
    pub fn bootstrap(&self) -> Bootstrap {
        if let Some(script) = self.file_for(Marker::Autogen) {
            Bootstrap::Autogen(script.to_owned())
        } else if self.has(Marker::ConfigureAc) {
            Bootstrap::Autoreconf
        } else {
            Bootstrap::None
        }
    }

    #[must_use]
    pub fn has_generated_configure(&self) -> bool {
        self.has(Marker::ConfigureScript)
    }
}

fn marker_for(name: &str) -> Option<Marker> {
    if name == MESON_BUILD {
        return Some(Marker::MesonBuild);
    }
    if BAZEL_WORKSPACE.contains(&name) {
        return Some(Marker::BazelWorkspace);
    }
    if BAZEL_BUILD.contains(&name) {
        return Some(Marker::BazelBuild);
    }
    if name == CMAKE_LISTS {
        return Some(Marker::CMakeLists);
    }
    if name == CMAKE_PRESETS {
        return Some(Marker::CMakePresets);
    }
    if CONFIGURE_AC.contains(&name) {
        return Some(Marker::ConfigureAc);
    }
    if AUTOGEN.contains(&name) {
        return Some(Marker::Autogen);
    }
    if name == CONFIGURE_SCRIPT {
        return Some(Marker::ConfigureScript);
    }
    if name == MAKEFILE_AM {
        return Some(Marker::MakefileAm);
    }
    if name == MAKEFILE_IN {
        return Some(Marker::MakefileIn);
    }
    if name == SCONS_SCRIPT {
        return Some(Marker::SconsScript);
    }
    if name == WAF_SCRIPT {
        return Some(Marker::WafScript);
    }
    if MAKEFILE.contains(&name) {
        return Some(Marker::Makefile);
    }
    None
}

fn scan(root: &Path) -> Result<Vec<Evidence>, DetectError> {
    let entries = std::fs::read_dir(root).map_err(|source| DetectError::Io {
        path: root.to_path_buf(),
        source,
    })?;

    let mut names = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|source| DetectError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let file_type = entry.file_type().map_err(|source| DetectError::Io {
            path: entry.path(),
            source,
        })?;
        if file_type.is_dir() {
            continue;
        }
        names.push(entry.file_name().to_string_lossy().into_owned());
    }
    names.sort();

    let mut evidence = Vec::new();
    for name in names {
        if let Some(marker) = marker_for(&name) {
            evidence.push(Evidence { marker, file: name });
        }
    }
    Ok(evidence)
}

fn rank(evidence: &[Evidence]) -> Vec<BuildSystem> {
    PRECEDENCE
        .into_iter()
        .filter(|system| {
            evidence
                .iter()
                .any(|found| found.marker.system() == *system)
        })
        .collect()
}

fn is_searchable_dir(name: &str) -> bool {
    !name.starts_with('.')
        && !VENDORED_DIRS
            .iter()
            .any(|skipped| name.eq_ignore_ascii_case(skipped))
}

fn subdirectories(dir: &Path) -> Result<Vec<PathBuf>, DetectError> {
    let entries = std::fs::read_dir(dir).map_err(|source| DetectError::Io {
        path: dir.to_path_buf(),
        source,
    })?;

    let mut found = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|source| DetectError::Io {
            path: dir.to_path_buf(),
            source,
        })?;
        let file_type = entry.file_type().map_err(|source| DetectError::Io {
            path: entry.path(),
            source,
        })?;
        if !file_type.is_dir() {
            continue;
        }
        if !is_searchable_dir(&entry.file_name().to_string_lossy()) {
            continue;
        }
        found.push(entry.path());
    }
    found.sort();
    Ok(found)
}

fn supported_precedence(evidence: &[Evidence]) -> Option<usize> {
    rank(evidence)
        .into_iter()
        .filter(|system| system.is_supported())
        .filter_map(|system| PRECEDENCE.iter().position(|known| *known == system))
        .min()
}

fn nested_build_root(root: &Path) -> Result<Option<(PathBuf, Vec<Evidence>)>, DetectError> {
    let mut frontier = vec![root.to_path_buf()];
    for _ in 0..NESTED_SEARCH_MAX_DEPTH {
        let mut next = Vec::new();
        let mut qualifying: Vec<(usize, PathBuf, Vec<Evidence>)> = Vec::new();
        for dir in &frontier {
            for child in subdirectories(dir)? {
                let evidence = scan(&child)?;
                match supported_precedence(&evidence) {
                    Some(precedence) => qualifying.push((precedence, child, evidence)),
                    None => next.push(child),
                }
            }
        }
        if let Some(best) = qualifying
            .iter()
            .map(|(precedence, _, _)| *precedence)
            .min()
        {
            let mut tied = qualifying
                .into_iter()
                .filter(|(precedence, _, _)| *precedence == best);
            let winner = tied.next();
            if tied.next().is_some() {
                return Ok(None);
            }
            return Ok(winner.map(|(_, path, evidence)| (path, evidence)));
        }
        if next.is_empty() {
            break;
        }
        frontier = next;
    }
    Ok(None)
}

fn sole_subdirectory(root: &Path) -> Result<Option<PathBuf>, DetectError> {
    let entries = std::fs::read_dir(root).map_err(|source| DetectError::Io {
        path: root.to_path_buf(),
        source,
    })?;

    let mut found = None;
    for entry in entries {
        let entry = entry.map_err(|source| DetectError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let file_type = entry.file_type().map_err(|source| DetectError::Io {
            path: entry.path(),
            source,
        })?;
        if !file_type.is_dir() {
            continue;
        }
        if entry.file_name().to_string_lossy().starts_with('.') {
            continue;
        }
        if found.is_some() {
            return Ok(None);
        }
        found = Some(entry.path());
    }
    Ok(found)
}

pub fn detect(root: &Path) -> Result<Detection, DetectError> {
    if !root.is_dir() {
        return Err(DetectError::NotADirectory(root.to_path_buf()));
    }

    let evidence = scan(root)?;
    if evidence.is_empty() {
        if let Some(nested) = sole_subdirectory(root)? {
            let nested_evidence = scan(&nested)?;
            if !nested_evidence.is_empty() {
                let candidates = rank(&nested_evidence);
                return Ok(Detection {
                    root: nested,
                    evidence: nested_evidence,
                    candidates,
                });
            }
        }
        if let Some((nested, nested_evidence)) = nested_build_root(root)? {
            let candidates = rank(&nested_evidence);
            return Ok(Detection {
                root: nested,
                evidence: nested_evidence,
                candidates,
            });
        }
    }

    let candidates = rank(&evidence);
    Ok(Detection {
        root: root.to_path_buf(),
        evidence,
        candidates,
    })
}

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

    struct Fixture {
        root: PathBuf,
    }

    impl Fixture {
        fn new(name: &str) -> Self {
            let root = lisdex_core::scratch::path(&format!("detect-{name}"));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).unwrap();
            Self { root }
        }

        fn file(self, name: &str) -> Self {
            let path = self.root.join(name);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(path, "").unwrap();
            self
        }

        fn dir(self, name: &str) -> Self {
            std::fs::create_dir_all(self.root.join(name)).unwrap();
            self
        }

        fn detect(&self) -> Detection {
            detect(&self.root).unwrap()
        }
    }

    #[test]
    fn cmake_project_is_detected() {
        let found = Fixture::new("cmake").file(CMAKE_LISTS).detect();
        assert_eq!(found.primary(), Some(BuildSystem::CMake));
    }

    #[test]
    fn meson_outranks_cmake() {
        let found = Fixture::new("meson-cmake")
            .file(MESON_BUILD)
            .file(CMAKE_LISTS)
            .detect();
        assert_eq!(found.primary(), Some(BuildSystem::Meson));
        assert_eq!(
            found.candidates,
            vec![BuildSystem::Meson, BuildSystem::CMake]
        );
    }

    #[test]
    fn cmake_outranks_a_bare_makefile_wrapper() {
        let found = Fixture::new("cmake-make")
            .file(CMAKE_LISTS)
            .file("Makefile")
            .detect();
        assert_eq!(found.primary(), Some(BuildSystem::CMake));
    }

    #[test]
    fn dual_cmake_and_autotools_keeps_both_candidates_in_order() {
        let found = Fixture::new("libpng-shape")
            .file(CMAKE_LISTS)
            .file("configure.ac")
            .file("Makefile.am")
            .detect();
        assert_eq!(
            found.candidates,
            vec![BuildSystem::CMake, BuildSystem::Autotools]
        );
    }

    #[test]
    fn generated_autotools_files_do_not_promote_raw_make() {
        let found = Fixture::new("autotools-built")
            .file("configure.ac")
            .file("configure")
            .file("Makefile.am")
            .file("Makefile.in")
            .file("Makefile")
            .detect();
        assert_eq!(found.primary(), Some(BuildSystem::Autotools));
        assert_eq!(
            found.candidates,
            vec![BuildSystem::Autotools, BuildSystem::Make]
        );
    }

    #[test]
    fn configure_backup_file_is_not_a_marker() {
        let found = Fixture::new("configure-backup").file("configure~").detect();
        assert!(found.evidence.is_empty());
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn autogen_script_is_preferred_over_autoreconf() {
        let found = Fixture::new("autogen")
            .file("autogen.sh")
            .file("configure.ac")
            .detect();
        assert_eq!(
            found.bootstrap(),
            Bootstrap::Autogen("autogen.sh".to_owned())
        );
    }

    #[test]
    fn configure_ac_without_autogen_bootstraps_with_autoreconf() {
        let found = Fixture::new("autoreconf").file("configure.ac").detect();
        assert_eq!(found.bootstrap(), Bootstrap::Autoreconf);
        assert!(!found.has_generated_configure());
    }

    #[test]
    fn pre_generated_configure_needs_no_bootstrap() {
        let found = Fixture::new("pregenerated").file("configure").detect();
        assert_eq!(found.primary(), Some(BuildSystem::Autotools));
        assert_eq!(found.bootstrap(), Bootstrap::None);
        assert!(found.has_generated_configure());
    }

    #[test]
    fn configure_in_is_recognised_as_configure_ac() {
        let found = Fixture::new("configure-in").file("configure.in").detect();
        assert!(found.has(Marker::ConfigureAc));
        assert_eq!(found.bootstrap(), Bootstrap::Autoreconf);
    }

    #[test]
    fn raw_makefile_project_falls_through_to_make() {
        let found = Fixture::new("raw-make").file("Makefile").detect();
        assert_eq!(found.primary(), Some(BuildSystem::Make));
    }

    #[test]
    fn bazel_is_detected_but_reported_unsupported() {
        let found = Fixture::new("bazel")
            .file("WORKSPACE")
            .file("BUILD.bazel")
            .detect();
        assert_eq!(found.primary(), Some(BuildSystem::Bazel));
        assert!(found.supported().is_empty());
        assert_eq!(found.unsupported(), vec![BuildSystem::Bazel]);
    }

    #[test]
    fn scons_and_waf_are_detected_but_unsupported() {
        let found = Fixture::new("scons-waf")
            .file(SCONS_SCRIPT)
            .file(WAF_SCRIPT)
            .detect();
        assert_eq!(
            found.unsupported(),
            vec![BuildSystem::Scons, BuildSystem::Waf]
        );
    }

    #[test]
    fn unknown_tree_yields_no_candidates() {
        let found = Fixture::new("unknown").file("README.md").detect();
        assert!(found.candidates.is_empty());
        assert_eq!(found.primary(), None);
    }

    #[test]
    fn a_directory_named_like_a_marker_is_ignored() {
        let found = Fixture::new("marker-dir").dir(CMAKE_LISTS).detect();
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn a_tarball_with_one_prefixed_directory_is_descended_into() {
        let fixture = Fixture::new("tarball").file("libpng-1.6.37/configure.ac");
        let found = fixture.detect();
        assert_eq!(found.primary(), Some(BuildSystem::Autotools));
        assert!(found.root.ends_with("libpng-1.6.37"));
    }

    #[test]
    fn descent_does_not_happen_when_the_root_itself_has_markers() {
        let fixture = Fixture::new("no-descend")
            .file(CMAKE_LISTS)
            .file("subproject/meson.build");
        let found = fixture.detect();
        assert_eq!(found.primary(), Some(BuildSystem::CMake));
        assert_eq!(found.root, fixture.root);
    }

    #[test]
    fn descent_does_not_happen_with_multiple_subdirectories() {
        let fixture = Fixture::new("two-subdirs")
            .file("one/CMakeLists.txt")
            .file("two/CMakeLists.txt");
        let found = fixture.detect();
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn detecting_a_missing_directory_is_an_error() {
        let missing = lisdex_core::scratch::path("detect-does-not-exist");
        let _ = std::fs::remove_dir_all(&missing);
        assert!(matches!(
            detect(&missing),
            Err(DetectError::NotADirectory(_))
        ));
    }

    #[test]
    fn every_supported_system_has_a_stable_name() {
        for system in PRECEDENCE {
            assert!(!system.as_str().is_empty());
        }
        assert!(BuildSystem::CMake.is_supported());
        assert!(BuildSystem::Meson.is_supported());
        assert!(BuildSystem::Autotools.is_supported());
        assert!(BuildSystem::Make.is_supported());
        assert!(!BuildSystem::Bazel.is_supported());
    }

    #[test]
    fn a_build_root_nested_under_many_subdirectories_is_found() {
        let fixture = Fixture::new("nested-many")
            .file("Project/CMake/CMakeLists.txt")
            .file("Project/GNU/Library/configure.ac")
            .file("Source/MediaInfo/File__Analyze.cpp")
            .dir("Release");
        let found = fixture.detect();
        assert_eq!(found.primary(), Some(BuildSystem::CMake));
        assert_eq!(found.root, fixture.root.join("Project/CMake"));
    }

    #[test]
    fn a_shallower_build_root_outranks_a_deeper_vendored_copy() {
        let fixture = Fixture::new("nested-shallower")
            .file("Project/CMake/CMakeLists.txt")
            .file("Project/zlib/projects/GNU/configure.ac")
            .file("Project/zlib/projects/GNU/Makefile.am");
        let found = fixture.detect();
        assert_eq!(found.root, fixture.root.join("Project/CMake"));
    }

    #[test]
    fn a_marker_inside_a_vendored_directory_is_not_a_build_root() {
        let found = Fixture::new("nested-vendored")
            .file("contrib/zlib/CMakeLists.txt")
            .file("third_party/brotli/configure.ac")
            .file("tests/harness/Makefile.am")
            .detect();
        assert!(found.candidates.is_empty());
        assert_eq!(found.primary(), None);
    }

    #[test]
    fn a_tree_with_no_markers_at_any_depth_stays_empty() {
        let found = Fixture::new("nested-none")
            .file("Source/MediaInfo/File__Analyze.cpp")
            .file("Project/notes.txt")
            .dir("Release")
            .detect();
        assert!(found.evidence.is_empty());
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn a_root_marker_is_never_overridden_by_a_nested_one() {
        let fixture = Fixture::new("nested-root-wins")
            .file(CONFIGURE_AC[0])
            .file("Project/CMake/CMakeLists.txt")
            .dir("Source");
        let found = fixture.detect();
        assert_eq!(found.primary(), Some(BuildSystem::Autotools));
        assert_eq!(found.root, fixture.root);
    }

    #[test]
    fn a_build_root_deeper_than_the_search_bound_is_not_found() {
        let found = Fixture::new("nested-too-deep")
            .file("a/b/c/d/e/CMakeLists.txt")
            .dir("Source")
            .detect();
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn an_unsupported_nested_build_system_is_not_a_build_root() {
        let found = Fixture::new("nested-unsupported")
            .file("Project/bazel/WORKSPACE")
            .dir("Source")
            .detect();
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn two_nested_build_roots_tied_at_the_same_depth_are_refused() {
        let found = Fixture::new("nested-ambiguous")
            .file("Project/one/CMakeLists.txt")
            .file("Project/two/CMakeLists.txt")
            .dir("Source")
            .detect();
        assert!(found.candidates.is_empty());
    }

    #[test]
    fn a_stronger_build_system_breaks_a_same_depth_tie() {
        let fixture = Fixture::new("nested-tiebreak")
            .file("Project/cmake/CMakeLists.txt")
            .file("Project/autotools/configure.ac")
            .dir("Source");
        let found = fixture.detect();
        assert_eq!(found.primary(), Some(BuildSystem::CMake));
        assert_eq!(found.root, fixture.root.join("Project/cmake"));
    }
}