geolith-cli 0.4.2

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
Documentation
#![allow(clippy::unwrap_used)] // tests and benches may unwrap (AGENTS.md).

//! Three AGENTS.md rules are about the file tree, not about code, so they are
//! tests here instead of script guards: no `.mjs`/`.cjs`/`.mts`/`.cts` files
//! (`package.json` is `"type": "module"`, so `.js` is ESM and `.ts` runs under
//! Node's type stripping), no `wrangler*` files (Worker config lives in
//! code; the build writes `wrangler.json` into gitignored output), and one data
//! layout under the git-ignored `.data/`.
//!
//! Every list includes untracked files that git does not ignore, so a new file
//! fails the check before it is committed.

use std::path::Path;
use std::process::Command;

/// The repository root. `git ls-files` lists only the current directory's
/// subtree, so the root is where the tree checks have to run.
fn root() -> String {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .output()
        .expect("run git rev-parse");
    assert!(output.status.success(), "git rev-parse failed");
    String::from_utf8(output.stdout)
        .expect("git rev-parse output is UTF-8")
        .trim()
        .to_owned()
}

/// Tracked files plus untracked files git does not ignore, relative to the
/// repository root.
fn files() -> Vec<String> {
    let output = Command::new("git")
        .args([
            "ls-files",
            "--cached",
            "--others",
            "--exclude-standard",
            "-z",
        ])
        .current_dir(root())
        .output()
        .expect("run git ls-files");
    assert!(output.status.success(), "git ls-files failed");
    String::from_utf8(output.stdout)
        .expect("git ls-files output is UTF-8")
        .split('\0')
        .filter(|file| !file.is_empty())
        .map(str::to_owned)
        .collect()
}

#[test]
fn no_module_specific_extensions() {
    let banned: Vec<String> = files()
        .into_iter()
        .filter(|file| {
            [".mjs", ".cjs", ".mts", ".cts"]
                .iter()
                .any(|ends| file.ends_with(ends))
        })
        .collect();
    assert!(
        banned.is_empty(),
        "tracked .mjs/.cjs/.mts/.cts files are not allowed; use .ts or .js: {banned:?}"
    );
}

#[test]
fn no_wrangler_files() {
    let banned: Vec<String> = files()
        .into_iter()
        .filter(|file| {
            Path::new(file)
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name.to_ascii_lowercase().starts_with("wrangler"))
        })
        .collect();
    assert!(
        banned.is_empty(),
        "wrangler* files are not allowed; configure the Worker in code: {banned:?}"
    );
}

/// The folders of the one data layout under the git-ignored `.data/` (README,
/// "Data layout"). Every `.data/` path starts with one of them.
const DATA_FOLDERS: [&str; 7] = [
    "inputs", "bin", "tiles", "search", "routing", "datasets", "qa",
];

/// A character of a path as the layout writes them.
fn path_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-' | '$' | '{' | '}' | '~')
}

/// The files whose `data/…` paths are read from the repository root: documents,
/// scripts and the JSON they read, all of them run from the root or telling a
/// reader to. In source code the same text is relative to the module or the
/// manifest (`include_str!("data/…")`, `CARGO_MANIFEST_DIR`), so only the
/// anchored forms count there.
fn reads_from_the_repo_root(file: &str) -> bool {
    let extension = Path::new(file)
        .extension()
        .and_then(|extension| extension.to_str());
    extension.is_none_or(|extension| {
        [
            "md", "sh", "py", "txt", "yml", "yaml", "toml", "json", "jsonc", "example",
        ]
        .contains(&extension)
    })
}

/// The `.data/` paths of `text` that sit outside the layout. A bare `.data/`
/// names the root itself and is allowed.
fn data_paths_outside_the_layout(text: &str) -> Vec<String> {
    let mut bad = Vec::new();
    let mut rest = text;
    while let Some(at) = rest.find(".data/") {
        let tail = &rest[at + ".data/".len()..];
        let path: String = tail.chars().take_while(|c| path_char(*c)).collect();
        let first = path.split('/').next().unwrap_or("");
        if !first.is_empty() && !DATA_FOLDERS.contains(&first) {
            // Built from parts, so the message of the guard is not a path it forbids.
            bad.push(format!("{}data/{path}", '.'));
        }
        rest = tail;
    }
    bad
}

/// The repo-root `data/` references of `text`. A reference is anchored at the
/// repository root by `./` or by a shell variable that holds the root, or — in a file
/// that is read from the root — starts a token and is path-shaped (a `/` or an
/// extension after `data/`). The dataset configs of
/// `packages/dataset-builder/data/datasets` are package-relative, a path with a
/// folder in front belongs to that folder, an absolute `/data/…` is a made-up
/// test path, and a bare word after `data/` is prose.
fn root_data_paths(text: &str, reads_from_root: bool) -> Vec<String> {
    let mut bad = Vec::new();
    for (at, _) in text.match_indices("data/") {
        let before: String = text[..at]
            .chars()
            .rev()
            .take_while(|c| path_char(*c))
            .collect::<String>()
            .chars()
            .rev()
            .collect();
        let tail = &text[at + "data/".len()..];
        let path: String = tail.chars().take_while(|c| path_char(*c)).collect();
        if path == "datasets" || path.starts_with("datasets/") {
            continue;
        }
        let anchored = before == "./" || (before.starts_with('$') && before.ends_with('/'));
        let starts_the_token = reads_from_root && before.is_empty();
        let last = path.rsplit('/').next().unwrap_or("");
        let path_shaped = path.contains('/') || last.contains('.');
        if anchored || (starts_the_token && (path.is_empty() || path_shaped)) {
            bad.push(format!("{before}data/{path}"));
        }
    }
    bad
}

/// One data layout: no repo-root `data/` folder, and no `.data/` path outside
/// the layout of the README. The orchestrator moves files between the folders of
/// the layout; a script or a doc that names an old path breaks the next run.
#[test]
fn one_data_layout_under_dot_data() {
    let root = root();
    let mut offenders: Vec<String> = Vec::new();
    for file in files() {
        if file.starts_with("data/") {
            offenders.push(format!("{file}: a repo-root data/ folder"));
        }
        let Ok(bytes) = std::fs::read(Path::new(&root).join(&file)) else {
            continue;
        };
        let text = String::from_utf8_lossy(&bytes);
        let from_root = reads_from_the_repo_root(&file);
        offenders.extend(
            root_data_paths(&text, from_root)
                .into_iter()
                .map(|path| format!("{file}: {path}")),
        );
        offenders.extend(
            data_paths_outside_the_layout(&text)
                .into_iter()
                .map(|path| format!("{file}: {path}")),
        );
    }
    assert!(
        offenders.is_empty(),
        "keep one data layout under the git-ignored .data/ (README, \"Data layout\"): {offenders:?}"
    );
}

/// No file names the per-user settings folder: configuration and secrets live
/// in the git-ignored `.env` (see `.env.example`), never under `~/.config`.
#[test]
fn no_file_names_the_per_user_settings_folder() {
    // Built from parts so this file does not name it itself.
    let needle = [".config", "/geolith"].concat();
    let root = root();
    let offenders: Vec<String> = files()
        .into_iter()
        .filter(|file| {
            std::fs::read(Path::new(&root).join(file)).is_ok_and(|bytes| {
                bytes
                    .windows(needle.len())
                    .any(|window| window == needle.as_bytes())
            })
        })
        .collect();
    assert!(
        offenders.is_empty(),
        "keep settings in .env, not under ~/{needle}: {offenders:?}"
    );
}

/// True when `line` holds a run of exactly 32 hex digits, the shape of a
/// Cloudflare account ID.
fn has_hex32(line: &str) -> bool {
    line.split(|c: char| !c.is_ascii_alphanumeric())
        .any(|token| token.len() == 32 && token.chars().all(|c| c.is_ascii_hexdigit()))
}

/// True when `text` names a home folder under the macOS users directory other
/// than the made-up `test` user of the fixtures.
fn names_a_home_folder(text: &str) -> bool {
    // Built from parts so this file does not name it itself.
    let needle = ["/Us", "ers/"].concat();
    text.match_indices(&needle).any(|(at, _)| {
        let user: String = text[at + needle.len()..]
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == '.' || *c == '_' || *c == '-')
            .collect();
        !user.is_empty() && user != "test" && user != "Shared"
    })
}

/// No file names a Cloudflare account ID or a personal home folder: scripts
/// read the account from `CLOUDFLARE_ACCOUNT_ID` in the git-ignored `.env`.
#[test]
fn no_file_names_an_account_id_or_a_home_folder() {
    let root = root();
    let offenders: Vec<String> = files()
        .into_iter()
        .filter(|file| {
            std::fs::read(Path::new(&root).join(file)).is_ok_and(|bytes| {
                let text = String::from_utf8_lossy(&bytes);
                names_a_home_folder(&text)
                    || text.lines().any(|line| {
                        line.to_ascii_lowercase().contains("account") && has_hex32(line)
                    })
            })
        })
        .collect();
    assert!(
        offenders.is_empty(),
        "remove account IDs and home-folder paths; read them from .env: {offenders:?}"
    );
}

#[test]
fn the_tree_guards_catch_what_they_name() {
    let id = ["0123456789abcdef", "0123456789abcdef"].concat();
    assert!(has_hex32(&format!("account_id = \"{id}\"")));
    assert!(!has_hex32(&format!("account_id = \"{id}0\"")));
    let home = ["/Us", "ers/"].concat();
    assert!(names_a_home_folder(&format!("{home}someone/dev")));
    assert!(!names_a_home_folder(&format!("{home}test/.data")));

    let one = |text: &str| root_data_paths(text, true);
    // Built from parts, so this file never names a data path itself.
    let data = |rest: &str| ["da", "ta/", rest].concat();
    let path = |rest: &str| [".", "da", "ta/", rest].concat();
    let at = |rest: &str| format!("./{}", data(rest));
    assert_eq!(one(&at("overture")), [at("overture")]);
    assert_eq!(one(&format!("--data {}", at("tmp"))), [at("tmp")]);
    assert_eq!(
        one(&format!("$R/{}", data("tmp"))),
        [format!("$R/{}", data("tmp"))]
    );
    assert_eq!(
        one(&format!("writes {}", data("india-boundary.geojson"))),
        [data("india-boundary.geojson")]
    );
    assert_eq!(
        one(&format!("`{}", data("region-tiles.sh"))),
        [data("region-tiles.sh")]
    );
    assert_eq!(one(&format!("a bare {} folder", data(""))), [data("")]);
    assert!(one(&format!("join(\"{}datasets/rainfall.json\")", data(""))).is_empty());
    assert!(one(&format!("packages/dataset-builder/{}", data("datasets"))).is_empty());
    assert!(one(&format!("input {}expectations", data(""))).is_empty());
    assert!(one(&format!("\"/{}\"", data("overture"))).is_empty());
    assert!(one("https://example.com/data/{country}").is_empty());
    assert!(one(&format!("bench-{}", data("x"))).is_empty());
    // In source code a bare `data/` is relative to the module, not to the root.
    let include = format!("include_str!(\"{}refresh/in.txt\")", data(""));
    assert!(root_data_paths(&include, false).is_empty());
    assert_eq!(root_data_paths(&include, true), [data("refresh/in.txt")]);
    assert!(reads_from_the_repo_root("README.md"));
    assert!(reads_from_the_repo_root("scripts/planet.sh"));
    assert!(!reads_from_the_repo_root(
        "geolith/tests/dataset_refresh_plan.rs"
    ));

    assert_eq!(
        data_paths_outside_the_layout(&format!("the run folder {}planet-2026-11-27/x", path(""))),
        [path("planet-2026-11-27/x")]
    );
    assert_eq!(
        data_paths_outside_the_layout(&format!("{}inputs/osm/planet.osm.pbf", path(""))),
        Vec::<String>::new()
    );
    assert_eq!(
        data_paths_outside_the_layout(&format!("`/{}` is ignored", path(""))),
        Vec::<String>::new()
    );
}