343 lines
12 KiB
Rust
343 lines
12 KiB
Rust
//! The `i18n` audit command: walks `crates/ui-egui/src` and `apps/*/src`,
|
|
//! reports hardcoded user-facing string literals (SPEC §12) and the still
|
|
//! un-migrated `mod strings` table entries.
|
|
//!
|
|
//! Non-failing by default: exit 0 normally, exit 1 with `--strict` when any
|
|
//! non-table literal is found. `--json` prints a machine-readable report.
|
|
|
|
use std::ffi::OsStr;
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use crate::rules;
|
|
|
|
/// How many sample offenders are printed at most.
|
|
const MAX_SAMPLES: usize = 5;
|
|
|
|
/// Per-file audit result.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct FileStat {
|
|
/// Workspace-relative path.
|
|
pub path: String,
|
|
/// Hardcoded user-facing literals found in the file.
|
|
pub literals: usize,
|
|
/// `mod strings` literals still pending migration.
|
|
pub pending_tables: usize,
|
|
}
|
|
|
|
/// Sums over all scanned files.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
pub struct Totals {
|
|
/// Sum of per-file literal counts.
|
|
pub literals: usize,
|
|
/// Sum of per-file pending table counts.
|
|
pub pending_tables: usize,
|
|
}
|
|
|
|
/// Whole-workspace audit report.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
pub struct Report {
|
|
/// One entry per scanned file, in sorted path order.
|
|
pub files: Vec<FileStat>,
|
|
/// Totals over all files.
|
|
pub totals: Totals,
|
|
/// First [`MAX_SAMPLES`] offenders shown as `path:line: "text"`.
|
|
pub samples: Vec<String>,
|
|
}
|
|
|
|
/// Source directories the audit scans.
|
|
fn source_roots(ws: &Path) -> Vec<PathBuf> {
|
|
let mut roots = vec![ws.join("crates").join("ui-egui").join("src")];
|
|
if let Ok(entries) = fs::read_dir(ws.join("apps")) {
|
|
for entry in entries.flatten() {
|
|
let src = entry.path().join("src");
|
|
if src.is_dir() {
|
|
roots.push(src);
|
|
}
|
|
}
|
|
}
|
|
roots
|
|
}
|
|
|
|
/// Whether a directory should not be descended into.
|
|
fn skipped_dir(name: &str) -> bool {
|
|
name == "tests" || name == "examples" || name == "target"
|
|
}
|
|
|
|
/// Whether a file is a scanned source (not a test helper).
|
|
fn is_source(path: &Path) -> bool {
|
|
if path.extension() != Some(OsStr::new("rs")) {
|
|
return false;
|
|
}
|
|
let name = path.file_name().and_then(|os| os.to_str()).unwrap_or_default();
|
|
!(name.ends_with("_tests.rs") || name == "testsupport.rs")
|
|
}
|
|
|
|
/// Iterative (stack-based, depth-bounded by the folder tree) walk for `.rs`
|
|
/// files below the roots, skipping test and example directories.
|
|
fn collect_files(roots: &[PathBuf]) -> Vec<PathBuf> {
|
|
let mut out: Vec<PathBuf> = Vec::new();
|
|
let mut stack: Vec<PathBuf> = roots.to_vec();
|
|
while let Some(dir) = stack.pop() {
|
|
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
let name = path.file_name().and_then(|os| os.to_str()).unwrap_or_default();
|
|
if path.is_dir() && !skipped_dir(name) {
|
|
stack.push(path);
|
|
} else if is_source(&path) {
|
|
out.push(path);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Workspace-relative sort key for stable, portable output.
|
|
fn rel_path<'a>(ws: &'a Path, path: &'a Path) -> &'a Path {
|
|
path.strip_prefix(ws).unwrap_or(path)
|
|
}
|
|
|
|
/// Audits every source file under the workspace roots.
|
|
///
|
|
/// # Errors
|
|
/// Returns an error string when a root directory cannot be read, which for
|
|
/// a mislaid workspace layout surfaces instead of a silently empty report.
|
|
pub fn audit(ws: &Path) -> Result<Report, String> {
|
|
let roots = source_roots(ws);
|
|
if !roots.iter().any(|root| root.is_dir()) {
|
|
return Err(String::from("no ui-egui/src or apps/*/src directories found — run from the workspace root"));
|
|
}
|
|
let mut files = collect_files(&roots);
|
|
files.sort_by(|x, y| rel_path(ws, x).cmp(rel_path(ws, y)));
|
|
let mut report = Report::default();
|
|
for path in &files {
|
|
let rel = rel_path(ws, path);
|
|
let Ok(source) = fs::read_to_string(path) else {
|
|
eprintln!("i18n: skipping unreadable file {}", rel.display());
|
|
continue;
|
|
};
|
|
let scan = rules::scan(&source);
|
|
report.files.push(FileStat { path: rel.display().to_string(), literals: scan.offenders.len(), pending_tables: scan.pending });
|
|
for offender in &scan.offenders {
|
|
if report.samples.len() == MAX_SAMPLES {
|
|
break;
|
|
}
|
|
report.samples.push(format!("{}:{}: {:?}", rel.display(), offender.line, offender.text));
|
|
}
|
|
report.totals.literals += scan.offenders.len();
|
|
report.totals.pending_tables += scan.pending;
|
|
}
|
|
Ok(report)
|
|
}
|
|
|
|
/// Human-readable report text.
|
|
fn render_text(report: &Report, scanned: usize) -> String {
|
|
use std::fmt::Write;
|
|
let mut text = String::new();
|
|
let _ = writeln!(text, "i18n audit (SPEC §12): hardcoded user strings — scanned {scanned} files");
|
|
for stat in &report.files {
|
|
let _ = writeln!(text, " {:<52} literals={} pending_tables={}", stat.path, stat.literals, stat.pending_tables);
|
|
}
|
|
let _ = writeln!(text, "\nfirst offenders ({} of {}):", report.samples.len(), report.totals.literals);
|
|
for sample in &report.samples {
|
|
let _ = writeln!(text, " {sample}");
|
|
}
|
|
let _ = writeln!(
|
|
text,
|
|
"\ntotal: {} hardcoded literal(s) in {} file(s), {} pending table entr{}; add `// i18n-ok` for justified literals, migrate `mod strings` to the i18n crate.",
|
|
report.totals.literals,
|
|
report.files.iter().filter(|f| f.literals > 0).count(),
|
|
report.totals.pending_tables,
|
|
if report.totals.pending_tables == 1 { "y" } else { "ies" }
|
|
);
|
|
text
|
|
}
|
|
|
|
/// JSON report (`--json`).
|
|
fn render_json(report: &Report) -> String {
|
|
let files: Vec<serde_json::Value> = report
|
|
.files
|
|
.iter()
|
|
.map(|stat| {
|
|
serde_json::json!({
|
|
"path": stat.path,
|
|
"literals": stat.literals,
|
|
"pending_tables": stat.pending_tables,
|
|
})
|
|
})
|
|
.collect();
|
|
let json = serde_json::json!({
|
|
"files": files,
|
|
"totals": {
|
|
"literals": report.totals.literals,
|
|
"pending_tables": report.totals.pending_tables,
|
|
},
|
|
});
|
|
serde_json::to_string(&json).unwrap_or_else(|_| String::from("{\"files\":[]}"))
|
|
}
|
|
|
|
/// Runs `cargo xtask i18n [--strict] [--json]`.
|
|
///
|
|
/// # Errors
|
|
/// Returns an error for unknown flags or, with `--strict`, when any
|
|
/// hardcoded literal is found (which fails the command).
|
|
pub fn run(args: &[String]) -> Result<(), String> {
|
|
let mut strict = false;
|
|
let mut json = false;
|
|
for arg in args {
|
|
match arg.as_str() {
|
|
"--strict" => strict = true,
|
|
"--json" => json = true,
|
|
other => return Err(format!("unknown flag `{other}` for i18n")),
|
|
}
|
|
}
|
|
let report = audit(&crate::root())?;
|
|
let scanned = report.files.len();
|
|
let line = if json { render_json(&report) } else { render_text(&report, scanned) };
|
|
println!("{line}");
|
|
finish(&report, strict)
|
|
}
|
|
|
|
/// Applies the `--strict` decision to a built report.
|
|
///
|
|
/// # Errors
|
|
/// Returns an error when `--strict` is set and any non-table literal was
|
|
/// found.
|
|
fn finish(report: &Report, strict: bool) -> Result<(), String> {
|
|
if strict && report.totals.literals > 0 {
|
|
return Err(format!("{} hardcoded user string(s) found (--strict)", report.totals.literals));
|
|
}
|
|
Ok(())
|
|
}
|
|
/// Scratch workspace fixture for the golden audit test; removes itself.
|
|
#[cfg(test)]
|
|
struct Fixture {
|
|
/// Root of the temporary tree.
|
|
root: PathBuf,
|
|
}
|
|
|
|
#[cfg(test)]
|
|
impl Fixture {
|
|
/// Creates a scratch workspace with ui-egui and two app sources.
|
|
fn build() -> Option<Fixture> {
|
|
use std::sync::atomic::{AtomicU32, Ordering};
|
|
static NONCE: AtomicU32 = AtomicU32::new(0);
|
|
let pid = std::process::id();
|
|
let count = NONCE.fetch_add(1, Ordering::Relaxed);
|
|
let dir = std::env::temp_dir().join(format!("xtask-i18n-golden-{pid:08}-{count}"));
|
|
let ui = dir.join("crates/ui-egui/src");
|
|
let app = dir.join("apps/notescraft/src");
|
|
let cli = dir.join("apps/notescraft-cli/src");
|
|
fs::create_dir_all(&ui).ok()?;
|
|
fs::create_dir_all(&app).ok()?;
|
|
fs::create_dir_all(&cli).ok()?;
|
|
let app_rs = "\
|
|
mod strings {
|
|
pub const TITLE: &str = \"App title\";
|
|
pub const SUBTITLE: &str = \"App subtitle\";
|
|
}
|
|
|
|
ui.button(\"Real one\");
|
|
let id = Id::new(\"app.panel\");
|
|
ui.heading(\"Real two\");
|
|
";
|
|
fs::write(ui.join("app.rs"), app_rs).ok()?;
|
|
fs::write(app.join("main.rs"), "ui.heading(\"App heading\");\n").ok()?;
|
|
fs::write(cli.join("main.rs"), "let v = 1;\n").ok()?;
|
|
fs::write(ui.join("app_tests.rs"), "ui.button(\"Test strings\");\n").ok()?;
|
|
fs::create_dir_all(ui.join("tests/inner")).ok()?;
|
|
fs::write(ui.join("tests/inner/deep.rs"), "ui.button(\"Deep\");\n").ok()?;
|
|
fs::write(ui.join("example_tests.rs"), "ui.button(\"Examples\");\n").ok()?;
|
|
Some(Fixture { root: dir })
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
impl Drop for Fixture {
|
|
/// Removes the whole scratch tree when the test ends.
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.root);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::Report;
|
|
use super::{Fixture, audit, finish, render_json, run};
|
|
use crate::root;
|
|
|
|
fn fixture() -> Fixture {
|
|
Fixture::build().expect("fixture build")
|
|
}
|
|
|
|
#[test]
|
|
fn golden_audit_shape() {
|
|
let fx = fixture();
|
|
let report = audit(&fx.root).unwrap_or_default();
|
|
let paths: Vec<String> = report.files.iter().map(|f| f.path.clone()).collect();
|
|
assert_eq!(paths, ["apps/notescraft/src/main.rs", "apps/notescraft-cli/src/main.rs", "crates/ui-egui/src/app.rs",]);
|
|
assert_eq!(report.totals.literals, 3);
|
|
assert_eq!(report.totals.pending_tables, 2);
|
|
assert_eq!(report.samples.len(), 3);
|
|
}
|
|
|
|
#[test]
|
|
fn golden_samples_carry_path_line_text() {
|
|
let fx = fixture();
|
|
let report = audit(&fx.root).unwrap_or_default();
|
|
let real_one = report.samples.first().cloned().unwrap_or_default();
|
|
assert_eq!(real_one, "apps/notescraft/src/main.rs:1: \"App heading\"");
|
|
let real_two = report.samples.last().cloned().unwrap_or_default();
|
|
assert_eq!(real_two, "crates/ui-egui/src/app.rs:8: \"Real two\"");
|
|
}
|
|
|
|
#[test]
|
|
fn skipped_names_and_dirs_are_not_scanned() {
|
|
let fx = fixture();
|
|
let report = audit(&fx.root).unwrap_or_default();
|
|
let joined = report.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>().join("|");
|
|
assert!(!joined.contains("_tests.rs"));
|
|
assert!(!joined.contains("tests/"));
|
|
assert_eq!(report.totals.literals, 3); // no "Test strings", "Deep", "Examples"
|
|
}
|
|
|
|
#[test]
|
|
fn json_render_has_files_and_totals() {
|
|
let fx = fixture();
|
|
let report = audit(&fx.root).unwrap_or_default();
|
|
let parsed: serde_json::Value = serde_json::from_str(&render_json(&report)).unwrap_or_default();
|
|
let ui_entry = parsed
|
|
.get("files")
|
|
.and_then(serde_json::Value::as_array)
|
|
.unwrap_or(&Vec::new())
|
|
.iter()
|
|
.find(|file| file.get("path").and_then(serde_json::Value::as_str) == Some("crates/ui-egui/src/app.rs"))
|
|
.cloned()
|
|
.unwrap_or_default();
|
|
assert_eq!(ui_entry.get("literals").and_then(serde_json::Value::as_u64), Some(2));
|
|
assert_eq!(ui_entry.get("pending_tables").and_then(serde_json::Value::as_u64), Some(2));
|
|
assert_eq!(parsed.get("totals").and_then(|totals| totals.get("literals")).and_then(serde_json::Value::as_u64), Some(3));
|
|
assert_eq!(parsed.get("totals").and_then(|totals| totals.get("pending_tables")).and_then(serde_json::Value::as_u64), Some(2));
|
|
}
|
|
|
|
#[test]
|
|
fn strict_fails_only_with_findings() {
|
|
let findings = Report { totals: super::Totals { literals: 2, pending_tables: 0 }, ..Report::default() };
|
|
assert!(finish(&findings, true).is_err());
|
|
assert!(finish(&findings, false).is_ok());
|
|
assert!(finish(&Report::default(), true).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_flag_is_rejected() {
|
|
let args = vec![String::from("--bogus")];
|
|
assert!(run(&args).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn root_points_at_workspace() {
|
|
assert!(root().join("crates/ui-egui/src").is_dir());
|
|
}
|
|
}
|