geolith-cli 0.4.1

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

//! Two 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), and no `wrangler*` files (Worker config lives in
//! code; the build writes `wrangler.json` into gitignored output).
//!
//! Both lists include 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:?}"
    );
}

/// 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")));
}