#![allow(clippy::unwrap_used)]
use std::path::Path;
use std::process::Command;
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()
}
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:?}"
);
}
const DATA_FOLDERS: [&str; 7] = [
"inputs", "bin", "tiles", "search", "routing", "datasets", "qa",
];
fn path_char(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-' | '$' | '{' | '}' | '~')
}
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)
})
}
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) {
bad.push(format!("{}data/{path}", '.'));
}
rest = tail;
}
bad
}
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
}
#[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:?}"
);
}
#[test]
fn no_file_names_the_per_user_settings_folder() {
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:?}"
);
}
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()))
}
fn names_a_home_folder(text: &str) -> bool {
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"
})
}
#[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);
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());
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()
);
}