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 👇

28.8 KB
Raw Blame
// ©AngelaMos | 2026
// headers.rs

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

use crate::extract::MIN_PROJECT_STEM;

pub const HEADER_EXTENSIONS: &[&str] = &["h", "hpp", "hh", "hxx"];
pub const INCLUDE_DIR: &str = "include";
pub const MAX_DEPTH: usize = 12;
pub const NESTED_INCLUDE_DEPTH: usize = 3;

// A directory whose name begins with this is a test directory, and naming the variants
// one at a time missed libarchive's `test_utils`, whose header declared four helpers that
// ranked as library entry points. Censused across the six validation trees: `test`, `tests`,
// `testing`, `test_utils`, `testpngs`, `testdata`, `test_cmake`, `test_cmake_no_target` -
// every match is genuinely a test directory, no false positives. This can never exclude the
// tree the user points at, because the walk only ever tests the names of CHILD directories.
pub const TEST_DIR_PREFIX: &str = "test";

pub const EXCLUDED_DIRS: &[&str] = &[
    "contrib",
    "example",
    "examples",
    "fuzz",
    "fuzzing",
    "fuzzers",
    "build",
    "doc",
    "docs",
    "third_party",
    "thirdparty",
    "3rdparty",
    "vendor",
    "vendored",
    "external",
    "externals",
    "deps",
    "subprojects",
    "tools",
    "programs",
    "imageio",
    "xmlwf",
    "bin",
    "enc",
    ".git",
];

#[derive(Debug, thiserror::Error)]
pub enum HeaderError {
    #[error("{0} is not a directory")]
    NotADirectory(PathBuf),
    #[error("no public headers found under {0}")]
    NoHeaders(PathBuf),
    #[error("io error reading {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum HeaderOrigin {
    Installed,
    IncludeDir,
    SourceRoot,
    Tree,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct HeaderSet {
    pub root: PathBuf,
    pub origin: HeaderOrigin,
    pub headers: Vec<PathBuf>,
}

pub const PRIVATE_MARKERS: &[&str] = &["priv", "internal", "impl", "iop"];
pub const PRIVATE_SUFFIXES: &[&str] = &["_p", "-p", "_int"];
pub const LICENSE_STEMS: &[&str] = &["license", "licence", "copying", "copyright", "notice"];
pub const GENERATOR_SUFFIXES: &[&str] = &["in", "cmake", "prebuilt", "tmpl", "template"];

#[must_use]
pub fn is_private_header(path: &Path) -> bool {
    let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
        return false;
    };
    let lowered = stem.to_lowercase();
    PRIVATE_MARKERS
        .iter()
        .any(|marker| lowered.contains(marker))
        || PRIVATE_SUFFIXES
            .iter()
            .any(|suffix| lowered.ends_with(suffix))
}

#[must_use]
pub fn is_header(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| HEADER_EXTENSIONS.contains(&extension.to_lowercase().as_str()))
}

#[must_use]
pub fn is_excluded(name: &str) -> bool {
    let lowered = name.to_lowercase();
    lowered.starts_with(TEST_DIR_PREFIX) || EXCLUDED_DIRS.contains(&lowered.as_str())
}

#[must_use]
pub fn project_token(name: &str) -> String {
    let lowered = name.to_lowercase();
    let trimmed = lowered.strip_prefix("lib").unwrap_or(&lowered);
    trimmed
        .chars()
        .filter(char::is_ascii_alphanumeric)
        .collect()
}

fn kin(one: &str, other: &str) -> bool {
    !one.is_empty() && !other.is_empty() && (one.starts_with(other) || other.starts_with(one))
}

fn carries_own_licence(dir: &Path) -> bool {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return false;
    };
    entries.flatten().any(|entry| {
        entry.file_type().is_ok_and(|kind| kind.is_file())
            && entry
                .path()
                .file_stem()
                .and_then(|stem| stem.to_str())
                .is_some_and(|stem| LICENSE_STEMS.contains(&stem.to_lowercase().as_str()))
    })
}

fn names_itself_after(dir: &Path, project: &str) -> bool {
    if dir
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| kin(&project_token(name), project))
    {
        return true;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return false;
    };
    entries.flatten().any(|entry| {
        let path = entry.path();
        is_header(&path)
            && path
                .file_stem()
                .and_then(|stem| stem.to_str())
                .is_some_and(|stem| kin(&project_token(stem), project))
    })
}

#[must_use]
pub fn is_vendored_tree(dir: &Path, project: &str) -> bool {
    // A name list never ends: libjpeg-turbo vendors a whole PNG decoder at src/spng and
    // ranked eight spng_* functions in its own top 20. But a licence file alone is not the
    // signal - lz4 ships lib/LICENSE and libexpat ships expat/COPYING over their OWN api,
    // and excluding those made both libraries un-analysable. A tree is vendored only when
    // it carries its own licence AND nothing in it is named after the project.
    carries_own_licence(dir) && !names_itself_after(dir, project)
}

fn collect(
    root: &Path,
    project: &str,
    depth: usize,
    found: &mut Vec<PathBuf>,
) -> Result<(), HeaderError> {
    if depth > MAX_DEPTH {
        return Ok(());
    }
    let entries = std::fs::read_dir(root).map_err(|source| HeaderError::Io {
        path: root.to_path_buf(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| HeaderError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();
        if path.is_dir() {
            if !is_excluded(&name) && !is_vendored_tree(&path, project) {
                collect(&path, project, depth + 1, found)?;
            }
        } else if is_header(&path) && !is_private_header(&path) {
            found.push(path);
        }
    }
    Ok(())
}

fn collect_shallow(root: &Path) -> Result<Vec<PathBuf>, HeaderError> {
    let entries = std::fs::read_dir(root).map_err(|source| HeaderError::Io {
        path: root.to_path_buf(),
        source,
    })?;
    let mut found = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|source| HeaderError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        if path.is_file() && is_header(&path) && !is_private_header(&path) {
            found.push(path);
        }
    }
    Ok(found)
}

// A tree shipping `jconfig.h.in` is telling you its build GENERATES `jconfig.h`, so a
// jconfig.h resolving from anywhere else is the wrong library's. This is the dominant B30
// shape and the one no name rule catches: pnglibconf.h and expat_config.h carry the project
// token, but jconfig.h, tiffconf.h and opj_config.h do not. Stripping the generator suffix
// yields the path the build would produce, which the ownership test already understands.
// Stacked on purpose. cmake's own convention is `<name>.h.cmake.in`, two generator
// suffixes deep, and stripping only one leaves `opj_config.h.cmake`, which is not a header
// - so openjpeg's generated config header was invisible both to B26's detection and to the
// OWNED set the foreign-include refusal is built on.
fn strip_generator(path: &Path) -> Option<PathBuf> {
    let mut generated = path.to_path_buf();
    let mut stripped = false;
    while let Some(suffix) = generated
        .extension()
        .and_then(|suffix| suffix.to_str())
        .map(str::to_lowercase)
    {
        if !GENERATOR_SUFFIXES.contains(&suffix.as_str()) {
            break;
        }
        generated = generated.with_extension("");
        stripped = true;
    }
    (stripped && is_header(&generated)).then_some(generated)
}

fn collect_generated(dir: &Path, project: &str, depth: usize, found: &mut Vec<PathBuf>) {
    if depth > MAX_DEPTH {
        return;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().to_lowercase();
        if path.is_dir() {
            if !is_excluded(&name) && !is_vendored_tree(&path, project) {
                collect_generated(&path, project, depth + 1, found);
            }
        } else if let Some(generated) = strip_generator(&path) {
            found.push(generated);
        }
    }
}

// A header the build GENERATES and that nothing has generated yet. The template is the
// tree's own statement that the file is produced rather than shipped, so this is a
// structural fact about the checkout and never a guess read off a compiler diagnostic.
#[must_use]
pub fn missing_generated(source: &Path, includes: &[PathBuf]) -> Vec<PathBuf> {
    generated_headers(source)
        .into_iter()
        .filter(|generated| {
            if generated.is_file() {
                return false;
            }
            let Some(name) = generated.file_name() else {
                return false;
            };
            !includes.iter().any(|dir| dir.join(name).is_file())
        })
        .collect()
}

#[must_use]
pub fn generated_headers(source: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    collect_generated(source, &project_of(source), 0, &mut found);
    found.sort();
    found.dedup();
    found
}

fn holds_a_directory_named_after(dir: &Path, project: &str) -> bool {
    // `kin` is a bare prefix test, and this decision redirects the WHOLE analysis to a new
    // header root, so a short stem here is the B61 hazard with a bigger blast radius: zlib
    // cloned as `libz` tokenises to `z`, and every `include/z*/` in the tree would answer to it.
    if project.len() < MIN_PROJECT_STEM {
        return false;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return false;
    };
    entries.flatten().any(|entry| {
        entry.file_type().is_ok_and(|kind| kind.is_dir())
            && entry
                .file_name()
                .to_str()
                .is_some_and(|name| kin(&project_token(name), project))
    })
}

// brotli keeps its public API in `c/include/brotli/`, so the `<source>/include` probe misses
// it, the tree walk parses `c/common/constants.h` without `-I c/include`, and every header
// is refused: brotli was the one clone of eight that could not be analysed at all. The
// project-named subdirectory is what makes this safe to search for - openjpeg ships
// `thirdparty/include` and libarchive `contrib/android/include`, and both hold nothing named
// after their project, so neither is mistaken for a public API root.
fn nested_include_root(dir: &Path, project: &str, depth: usize) -> Option<PathBuf> {
    if depth > NESTED_INCLUDE_DEPTH {
        return None;
    }
    let mut found = Vec::new();
    for entry in std::fs::read_dir(dir).ok()?.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_lowercase();
        if is_excluded(&name) || is_vendored_tree(&path, project) {
            continue;
        }
        if name == INCLUDE_DIR && holds_a_directory_named_after(&path, project) {
            found.push(path);
        } else if let Some(nested) = nested_include_root(&path, project, depth + 1) {
            found.push(nested);
        }
    }
    found.sort();
    found.into_iter().next()
}

fn gathered(root: &Path, project: &str) -> Result<Vec<PathBuf>, HeaderError> {
    let mut found = Vec::new();
    collect(root, project, 0, &mut found)?;
    found.sort();
    Ok(found)
}

#[must_use]
pub fn project_of(source: &Path) -> String {
    source
        .file_name()
        .and_then(|name| name.to_str())
        .map(project_token)
        .unwrap_or_default()
}

// B68. Every candidate header root, most authoritative first, rather than the first one that
// holds a file. Discovery cannot tell whether a header DECLARES anything without parsing it,
// and one that declares nothing is not a surface - libtiff ships an `placeholder.h` at its
// root whose entire contents are "This file is intentionally empty", put there so pre-3.11
// CMake would accept an `add_library()` call. It has no `include/` directory and its public
// headers live in `libtiff/`, so the shallow-root rule matched that one empty file and made it
// the whole header set, and the library read as having no API at all.
//
// The caller parses each in turn and stops at the first that yields a declaration, so a tree
// that works today is unaffected by construction: its first candidate already declares
// something and no later one is ever reached.
pub fn candidates(source: &Path, install: Option<&Path>) -> Result<Vec<HeaderSet>, HeaderError> {
    if !source.is_dir() {
        return Err(HeaderError::NotADirectory(source.to_path_buf()));
    }

    let project = project_of(source);
    let mut found = Vec::new();

    if let Some(install) = install
        && install.is_dir()
    {
        let headers = gathered(install, &project)?;
        if !headers.is_empty() {
            found.push(HeaderSet {
                root: install.to_path_buf(),
                origin: HeaderOrigin::Installed,
                headers,
            });
        }
    }

    let include = source.join(INCLUDE_DIR);
    if include.is_dir() {
        let headers = gathered(&include, &project)?;
        if !headers.is_empty() {
            found.push(HeaderSet {
                root: include,
                origin: HeaderOrigin::IncludeDir,
                headers,
            });
        }
    }

    if let Some(nested) = nested_include_root(source, &project, 0) {
        let headers = gathered(&nested, &project)?;
        if !headers.is_empty() {
            found.push(HeaderSet {
                root: nested,
                origin: HeaderOrigin::IncludeDir,
                headers,
            });
        }
    }

    let mut shallow = collect_shallow(source)?;
    shallow.sort();
    if !shallow.is_empty() {
        found.push(HeaderSet {
            root: source.to_path_buf(),
            origin: HeaderOrigin::SourceRoot,
            headers: shallow,
        });
    }

    let headers = gathered(source, &project)?;
    if !headers.is_empty() {
        found.push(HeaderSet {
            root: source.to_path_buf(),
            origin: HeaderOrigin::Tree,
            headers,
        });
    }

    if found.is_empty() {
        return Err(HeaderError::NoHeaders(source.to_path_buf()));
    }
    Ok(found)
}

pub fn discover(source: &Path, install: Option<&Path>) -> Result<HeaderSet, HeaderError> {
    candidates(source, install).map(|mut found| found.remove(0))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::{Path, PathBuf};

    fn fixture(label: &str, files: &[&str]) -> PathBuf {
        let root = lisdex_core::scratch::path(&format!("headers-{label}"));
        let _ = std::fs::remove_dir_all(&root);
        for file in files {
            let path = root.join(file);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "int f(void);\n").unwrap();
        }
        root
    }

    // The tree has to sit in a PROJECT-NAMED directory, because that is what project_of
    // reads. Renaming to a sibling of the fixture put it at a fixed, PID-free path in the
    // shared temp dir - so `cargo test` deleted a real /tmp/lz4, and two concurrent runs
    // fought over the same directory. Rename inside a per-process box instead.
    fn named_as_project(root: &Path, project: &str) -> PathBuf {
        let mut boxed = root.file_name().unwrap().to_os_string();
        boxed.push("-box");
        let box_dir = root.with_file_name(boxed);
        let _ = std::fs::remove_dir_all(&box_dir);
        std::fs::create_dir_all(&box_dir).unwrap();
        let renamed = box_dir.join(project);
        std::fs::rename(root, &renamed).unwrap();
        renamed
    }

    fn names(set: &HeaderSet) -> Vec<String> {
        let mut found: Vec<String> = set
            .headers
            .iter()
            .map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        found.sort();
        found
    }

    #[test]
    fn an_installed_include_tree_is_the_authoritative_public_api() {
        let root = fixture(
            "installed",
            &["src/png.h", "src/pngpriv.h", "install/include/png.h"],
        );
        let set = discover(&root.join("src"), Some(&root.join("install"))).unwrap();
        assert_eq!(set.origin, HeaderOrigin::Installed);
        assert_eq!(names(&set), vec!["png.h"]);
    }

    #[test]
    fn a_subdirectory_carrying_its_own_licence_is_a_vendored_tree() {
        let root = fixture(
            "vendored",
            &[
                "LICENSE.md",
                "include/turbojpeg.h",
                "include/spng/LICENSE",
                "include/spng/spng.h",
            ],
        );
        let renamed = named_as_project(&root, "libjpeg-turbo-vendored");
        let set = discover(&renamed, None).unwrap();
        assert_eq!(
            names(&set),
            vec!["turbojpeg.h"],
            "libjpeg-turbo ranked eight spng_* functions from a vendored PNG decoder"
        );
    }

    #[test]
    fn a_generated_header_counts_as_missing_only_until_something_produces_it() {
        let root = fixture(
            "missinggen",
            &[
                "lib/opj_config.h.cmake.in",
                "lib/already.h.in",
                "lib/already.h",
            ],
        );
        let missing: Vec<String> = missing_generated(&root, &[])
            .iter()
            .filter_map(|path| path.file_name())
            .map(|name| name.to_string_lossy().into_owned())
            .collect();
        assert_eq!(
            missing,
            vec!["opj_config.h".to_owned()],
            "already.h exists in the tree, so nothing needs to generate it"
        );

        let elsewhere = fixture("missinggendir", &["opj_config.h"]);
        assert!(
            missing_generated(&root, std::slice::from_ref(&elsewhere)).is_empty(),
            "a header supplied on the include path is not missing either"
        );
    }

    #[test]
    fn generated_headers_strip_the_generator_suffix_and_ignore_everything_else() {
        let root = fixture(
            "generators",
            &[
                "src/jconfig.h.in",
                "expat_config.h.cmake",
                "scripts/pnglibconf.h.prebuilt",
                "config.h",
                "Makefile.in",
                "src/real.h",
                // cmake's own convention, two generator suffixes deep. Stripping one
                // leaves opj_config.h.cmake, which is not a header, so openjpeg's
                // generated config header used to be invisible here.
                "lib/opj_config.h.cmake.in",
            ],
        );
        let found: Vec<String> = generated_headers(&root)
            .iter()
            .map(|path| {
                path.strip_prefix(&root)
                    .unwrap_or(path)
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        assert_eq!(
            found,
            vec![
                "expat_config.h".to_owned(),
                "lib/opj_config.h".to_owned(),
                "scripts/pnglibconf.h".to_owned(),
                "src/jconfig.h".to_owned(),
            ],
            "Makefile.in is not a header and config.h is not a generator"
        );
    }

    #[test]
    fn a_licence_over_the_projects_own_api_excludes_nothing() {
        // lz4 ships lib/LICENSE and libexpat ships expat/COPYING over their own headers.
        // Treating a licence file as proof of vendoring made both un-analysable.
        let root = fixture("own_licence", &["include/COPYING", "include/own_licence.h"]);
        let set = discover(&root, None).unwrap();
        assert_eq!(names(&set), vec!["own_licence.h"]);
    }

    #[test]
    fn a_licenced_subdirectory_named_after_the_project_is_kept() {
        let root = fixture(
            "lz4shape",
            &["lib/LICENSE", "lib/lz4frame.h", "ossfuzz/x.h"],
        );
        let renamed = named_as_project(&root, "lz4");
        let set = discover(&renamed, None).unwrap();
        assert!(
            names(&set).contains(&"lz4frame.h".to_owned()),
            "lib/ carries lz4's own api and lz4frame.h is named after the project"
        );
    }

    #[test]
    fn a_licenced_subdirectory_named_after_nothing_local_is_vendored() {
        let root = fixture(
            "turboshape",
            &[
                "LICENSE.md",
                "src/turbojpeg.h",
                "src/spng/LICENSE",
                "src/spng/spng.h",
            ],
        );
        let renamed = named_as_project(&root, "libjpeg-turbo");
        let set = discover(&renamed, None).unwrap();
        assert_eq!(names(&set), vec!["turbojpeg.h"]);
    }

    #[test]
    fn a_project_token_drops_the_lib_prefix_and_punctuation() {
        assert_eq!(project_token("libexpat"), "expat");
        assert_eq!(project_token("libjpeg-turbo"), "jpegturbo");
        assert_eq!(project_token("lz4"), "lz4");
    }

    #[test]
    fn a_licence_like_name_that_is_not_a_licence_does_not_exclude_a_tree() {
        let root = fixture(
            "licence_prefix",
            &["include/lib/libpng-LICENSE.txt", "include/lib/png.h"],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(names(&set), vec!["png.h"]);
    }

    #[test]
    fn an_include_directory_is_used_when_nothing_was_installed() {
        let root = fixture("includedir", &["include/tiff.h", "libtiff/tif_dir.c"]);
        let set = discover(&root, None).unwrap();
        assert_eq!(set.origin, HeaderOrigin::IncludeDir);
        assert_eq!(names(&set), vec!["tiff.h"]);
    }

    #[test]
    fn headers_at_the_source_root_are_collected_when_there_is_no_include_dir() {
        let root = fixture("sourceroot", &["png.h", "pngconf.h", "png.c"]);
        let set = discover(&root, None).unwrap();
        assert_eq!(set.origin, HeaderOrigin::SourceRoot);
        assert_eq!(names(&set), vec!["png.h", "pngconf.h"]);
    }

    #[test]
    fn test_and_contrib_trees_are_never_part_of_the_public_surface() {
        let root = fixture(
            "excluded",
            &[
                "include/archive.h",
                "include/tests/helper.h",
                "include/test_utils/test_utils.h",
                "include/contrib/oss-fuzz/harness.h",
                "include/examples/demo.h",
                "include/fuzz/driver.h",
            ],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(
            names(&set),
            vec!["archive.h"],
            "libarchive's test_utils declared four helpers that ranked as library entry \
             points, because the exclusion list named test directories one variant at a time"
        );
    }

    #[test]
    fn a_directory_named_for_tests_is_excluded_however_it_is_spelled() {
        for name in ["test", "tests", "testing", "test_utils", "testdata"] {
            assert!(is_excluded(name), "{name}");
        }
    }

    #[test]
    fn the_tree_the_user_points_at_is_never_excluded_by_its_own_name() {
        let root = fixture("testu01", &["include/unif01.h", "src/unif01.c"]);
        let set = discover(&root, None).unwrap();
        assert_eq!(
            names(&set),
            vec!["unif01.h"],
            "the walk only ever judges the names of child directories, so a library whose \
             own name begins with test still analyses"
        );
    }

    #[test]
    fn nested_headers_under_the_include_root_are_found() {
        let root = fixture(
            "nested",
            &["include/openjpeg.h", "include/opj/opj_stdint.h"],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(names(&set), vec!["openjpeg.h", "opj_stdint.h"]);
    }

    #[test]
    fn cpp_header_extensions_are_included_and_sources_are_not() {
        let root = fixture(
            "extensions",
            &[
                "include/a.h",
                "include/b.hpp",
                "include/c.hh",
                "include/d.c",
                "include/e.cpp",
                "include/f.txt",
            ],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(names(&set), vec!["a.h", "b.hpp", "c.hh"]);
    }

    #[test]
    fn headers_that_name_themselves_private_are_not_public_api() {
        let root = fixture(
            "private",
            &[
                "png.h",
                "pngconf.h",
                "pngpriv.h",
                "tiffiop.h",
                "zlib_internal.h",
                "codec_impl.h",
                "thing_p.h",
            ],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(names(&set), vec!["png.h", "pngconf.h"], "{:?}", names(&set));
    }

    #[test]
    fn a_project_keeping_its_public_header_in_a_named_subdirectory_is_still_found() {
        let root = fixture(
            "subdir",
            &[
                "libarchive/archive.h",
                "libarchive/archive_entry.h",
                "libarchive/archive_read_private.h",
                "README.md",
            ],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(set.origin, HeaderOrigin::Tree);
        assert_eq!(names(&set), vec!["archive.h", "archive_entry.h"]);
    }

    #[test]
    fn a_vendored_dependency_is_never_mistaken_for_the_project_surface() {
        let root = fixture(
            "vendored_thirdparty",
            &[
                "src/lib/openjp2/openjpeg.h",
                "thirdparty/libpng/png.h",
                "thirdparty/libtiff/tiffio.h",
                "subprojects/zlib/zlib.h",
            ],
        );
        let set = discover(&root, None).unwrap();
        assert_eq!(names(&set), vec!["openjpeg.h"], "{:?}", names(&set));
    }

    #[test]
    fn a_root_header_still_wins_over_a_deeper_one() {
        let root = fixture("rootwins", &["png.h", "src/internals/helper.h"]);
        let set = discover(&root, None).unwrap();
        assert_eq!(set.origin, HeaderOrigin::SourceRoot);
        assert_eq!(names(&set), vec!["png.h"]);
    }

    #[test]
    fn a_tree_with_no_headers_reports_that_rather_than_guessing() {
        let root = fixture("empty", &["src/main.c", "README.md"]);
        let error = discover(&root, None).unwrap_err();
        assert!(matches!(error, HeaderError::NoHeaders(_)), "{error:?}");
    }

    #[test]
    fn a_missing_source_tree_is_an_error() {
        let missing = Path::new("/nonexistent/lisdex/surface/tree");
        let error = discover(missing, None).unwrap_err();
        assert!(matches!(error, HeaderError::NotADirectory(_)), "{error:?}");
    }

    #[test]
    fn an_include_root_nested_one_level_down_is_still_the_public_api() {
        let root = fixture(
            "nestedinclude",
            &[
                "c/include/brotli/decode.h",
                "c/include/brotli/port.h",
                "c/common/constants.h",
            ],
        );
        let renamed = named_as_project(&root, "brotli");
        let set = discover(&renamed, None).unwrap();
        assert_eq!(set.origin, HeaderOrigin::IncludeDir);
        assert_eq!(
            set.root,
            renamed.join("c/include"),
            "brotli's public API lives at c/include, so the tree walk parsed \
             c/common/constants.h without -I c/include and refused every header"
        );
        assert_eq!(names(&set), vec!["decode.h", "port.h"]);
    }

    // The isolating control. A rule that took ANY nested include directory would pass the
    // test above and still be wrong: openjpeg ships thirdparty/include and libarchive ships
    // contrib/android/include. The project-named subdirectory is the whole discriminator.
    #[test]
    fn a_nested_include_holding_nothing_named_after_the_project_is_not_the_api() {
        let root = fixture(
            "foreignnested",
            &["src/include/lcms2/lcms2.h", "src/openjpeg/openjpeg.h"],
        );
        let renamed = named_as_project(&root, "openjpeg");
        let set = discover(&renamed, None).unwrap();
        assert_eq!(
            set.origin,
            HeaderOrigin::Tree,
            "src/include holds lcms2, not openjpeg, so it is a dependency's headers"
        );
    }

    #[test]
    fn a_project_stem_too_short_to_be_evidence_claims_no_nested_include() {
        let root = fixture(
            "shortstem",
            &["src/include/zoo/zoo.h", "src/zlib/deflate.h"],
        );
        let renamed = named_as_project(&root, "libz");
        let set = discover(&renamed, None).unwrap();
        assert_ne!(
            set.origin,
            HeaderOrigin::IncludeDir,
            "libz tokenises to `z`, and a bare prefix test would hand the whole \
             analysis to any include/z*/ in the tree"
        );
    }

    #[test]
    fn an_install_tree_without_headers_falls_back_to_the_source() {
        let root = fixture("installempty", &["install/lib/libpng.a", "include/png.h"]);
        let set = discover(&root, Some(&root.join("install"))).unwrap();
        assert_eq!(set.origin, HeaderOrigin::IncludeDir);
        assert_eq!(names(&set), vec!["png.h"]);
    }
}