crates/korp-map-build-thing/tests/clean_text.rs
//! **The repository's prose stays public-ready.** Every tracked text file
//! (Rust sources, manifests, Markdown, the emitted `.nornir` files) is scanned
//! for wording that does not belong in a public repository: rude or emotional
//! words, quotes of people, notes about internal work streams and task ids,
//! machine names, private paths and addresses, and credentials.
//!
//! A hit names the file, the line and the rule. Rewrite the line in plain,
//! neutral English that keeps the technical meaning; do not weaken a rule to
//! make a hit go away unless the word is a real technical term (then add the
//! phrase to [`ALLOWED`]).
use std::path::{Path, PathBuf};
use korp_map_build_thing::emit::repo_root;
use regex::Regex;
/// One rule: a name for the report and a case-insensitive pattern.
struct Rule {
name: &'static str,
pattern: &'static str,
}
const RULES: &[Rule] = &[
Rule {
name: "rude or emotional word",
pattern: r"\b(fuck\w*|shit\w*|damn\w*|crap|crappy|wtf|bullshit|stupid\w*|idiot\w*|dumb|moron\w*|garbage|rubbish|sucks?|insane\w*|ridiculous\w*|nonsense|horrible|terrible|awful|stinky|stink\w*|lying|liars?|cheat\w*)\b",
},
Rule {
name: "rude or emotional word",
pattern: r"\b(a|the|is a) lie\b",
},
Rule {
name: "emotional punctuation",
pattern: r"[a-z](!!|\?\?|\?!|!\?)",
},
Rule {
name: "quote of a person",
pattern: r"\b(owner|owner's|verbatim)\b",
},
Rule {
name: "quote of a person",
pattern: r"\b(och|att|inte|ska|vill|nukad|raderar)\b",
},
Rule {
name: "internal work-stream note",
pattern: r"\b(lanes?|agents?|stinky)\b",
},
Rule {
name: "internal task id",
pattern: r"\b(seam|netlod|netwhole|korpui|korpmap|mapwire|mapread|mapdrive|kalm|hus3d|map-dead)-\d|katana-doc-stale|\b(root )?law \d|\broot law\b",
},
Rule {
name: "machine name",
pattern: r"\b(loki|oden|dwarf|t14s?|x14)\b",
},
Rule {
name: "private path or address",
pattern: r"/home/rickard|\brickard\b|/mnt/|~/work\b|192\.168\.|\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",
},
Rule {
name: "email address",
pattern: r"[a-z0-9._%+-]+@[a-z0-9-]+\.[a-z]{2,}",
},
Rule {
name: "credential",
pattern: r"\bghp_[a-z0-9]{20,}|\bglpat-|\bxox[abp]-|-----begin [a-z ]*private key",
},
];
/// Technical phrases that contain a ruled word: removed from a line before
/// the rules run. Keep each entry as specific as the term itself.
const ALLOWED: &[&str] = &[
// A dependency's type name (the HTTP client of the quality harness).
"ureq::agent",
// The cell grid's owner stamp: which tile a slice belongs to.
"owner stamp",
"owner cell",
"let owner",
"= owner;",
"owner is the covering tile",
// The code table's owner (`errcode.rs`).
"owner of the table",
// A job nobody holds; the boot that owns the chain.
"with no owner",
"boot-owner",
];
/// The copyright holder, allowed exactly as written and only on a `Copyright` or
/// `SPDX-FileCopyrightText` line (lower-cased, as the scan compares).
const COPYRIGHT_HOLDER: &str = "ignalina aps (rickard ernst björn lundin)";
/// Files that are not prose: licence texts, locks, data.
fn skipped(rel: &Path) -> bool {
let s = rel.to_string_lossy();
s.starts_with("LICENSES/")
|| s == "LICENSE"
|| s == "LICENSE-MIT"
|| s == "LICENSE-APACHE"
// A published crate carries its own copies of the licence texts.
|| s.ends_with("/LICENSE")
|| s.ends_with("/LICENSE-MIT")
|| s.ends_with("/LICENSE-APACHE")
|| s.ends_with("Cargo.lock")
|| s.ends_with(".poly")
// This file spells the rules out.
|| s.ends_with("korp-map-build-thing/tests/clean_text.rs")
}
fn scanned(rel: &Path) -> bool {
matches!(
rel.extension().and_then(|e| e.to_str()),
Some("rs" | "md" | "toml" | "txt" | "proto" | "yml" | "yaml" | "json")
) || rel
.file_name()
.is_some_and(|n| n == ".gitignore" || n == "README")
}
fn walk(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for e in entries.flatten() {
let p = e.path();
let name = e.file_name();
let name = name.to_string_lossy();
if p.is_dir() {
if name == "target" || name == ".git" || name == ".claude" {
continue;
}
walk(root, &p, out);
} else if let Ok(rel) = p.strip_prefix(root) {
if scanned(rel) && !skipped(rel) {
out.push(rel.to_path_buf());
}
}
}
}
/// Every hit as `file:line: rule: text`.
fn scan(root: &Path) -> (usize, Vec<String>) {
let rules: Vec<(&str, Regex)> = RULES
.iter()
.map(|r| {
(
r.name,
Regex::new(&format!("(?i){}", r.pattern)).expect("rule compiles"),
)
})
.collect();
let mut files = Vec::new();
walk(root, root, &mut files);
files.sort();
let mut hits = Vec::new();
for rel in &files {
let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
continue;
};
for (n, line) in text.lines().enumerate() {
let mut l = line.to_lowercase();
if l.contains("copyright") || l.contains("spdx-filecopyrighttext") {
l = l.replace(COPYRIGHT_HOLDER, " ");
}
for a in ALLOWED {
l = l.replace(a, " ");
}
for (name, re) in &rules {
if re.is_match(&l) {
hits.push(format!(
"{}:{}: {name}: {}",
rel.display(),
n + 1,
line.trim()
));
}
}
}
}
(files.len(), hits)
}
#[test]
fn every_tracked_text_reads_public_ready() {
let root = repo_root();
let (files, hits) = scan(&root);
assert!(
files > 40,
"the scan reached only {files} files under {}",
root.display()
);
assert!(
hits.is_empty(),
"{} line(s) need neutral wording:\n{}",
hits.len(),
hits.join("\n")
);
}
#[test]
fn the_rules_catch_what_they_name() {
let dir = std::env::temp_dir().join(format!("korp-map-clean-text-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
let bad = [
"// this is stupid",
"// works now!!",
"// as the owner said",
"// lane GG #20",
"// see seam-24",
"// measured on loki",
"// cache in /home/rickard/x",
"// host 192.168.1.9",
"// mail someone@example.org",
"// Rickard Ernst Björn Lundin wrote this",
"// Copyright (c) 2026 Rickard Lundin",
];
let good = [
"// the owner stamp of a cell",
"// x lies inside the box",
"let y = f()??;",
"// Copyright (c) 2026 Ignalina ApS (Rickard Ernst Björn Lundin)",
"// SPDX-FileCopyrightText: 2026 Ignalina ApS (Rickard Ernst Björn Lundin)",
];
let text: Vec<&str> = bad.iter().chain(good.iter()).copied().collect();
std::fs::write(dir.join("src/a.rs"), text.join("\n")).unwrap();
let (_, hits) = scan(&dir);
std::fs::remove_dir_all(&dir).ok();
for (i, b) in bad.iter().enumerate() {
assert!(
hits.iter()
.any(|h| h.starts_with(&format!("src/a.rs:{}:", i + 1))),
"missed {b:?}"
);
}
for (i, g) in good.iter().enumerate() {
let line = bad.len() + i + 1;
assert!(
!hits
.iter()
.any(|h| h.starts_with(&format!("src/a.rs:{line}:"))),
"false hit on {g:?}: {hits:?}"
);
}
}