//! OxygenFlow's cheap checks as one WASI module (#96): what //! `.flow/jobs/{layout,todos,size,summary}.sh` did in an Alpine microVM, so //! that any runner offering the WASM tier (a phone, plex, windows-1) can take //! them. The job's files are preopened as `/src`, which is also the current //! directory, so every path here is relative to the workspace. //! //! - `layout PATH...`: each path is a file; fails naming the first missing. //! - `todos DIR...`: the lines holding a note marker, counted, the first 20 //! listed; never fails. //! - `size DIR`: lines of Rust in each crate directory under DIR. //! - `summary`: one line naming `$PROJECT`. //! - `changelog FILE [MANIFEST]`: the changelog's shape: `## Unreleased` //! first if at all, then `## X.Y.Z (YYYY-MM-DD)` sections, newest first, //! none empty; with a manifest (`Cargo.toml`, `*.properties`, //! `package.json`), its version has a section, as a release needs. use std::fs; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode; /// The note markers, spelt in pieces so this file does not count itself. const MARKERS: [&str; 3] = [concat!("TO", "DO"), concat!("FIX", "ME"), concat!("X", "XX")]; /// How many noted lines `todos` lists. const LISTED: usize = 20; const USAGE: &str = "usage: flow-checks layout PATH... | todos DIR... | size DIR | summary | changelog FILE [MANIFEST]"; fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); let root = Path::new("."); let mut out = io::stdout().lock(); let done = match args.split_first() { Some((cmd, rest)) => match cmd.as_str() { "layout" => layout(root, rest, &mut out), "todos" => todos(root, rest, &mut out), "size" => match rest { [dir] => size(root, dir, &mut out), _ => Err(USAGE.to_string()), }, "summary" => summary(std::env::var("PROJECT").ok().as_deref(), &mut out), "changelog" => match rest { [file] => changelog(root, file, None, &mut out), [file, manifest] => changelog(root, file, Some(manifest), &mut out), _ => Err(USAGE.to_string()), }, _ => Err(USAGE.to_string()), }, None => Err(USAGE.to_string()), }; match done { Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("{e}"); ExitCode::FAILURE } } } type Done = Result<(), String>; fn emit(out: &mut impl Write, line: &str) -> Done { writeln!(out, "{line}").map_err(|e| format!("write: {e}")) } /// The workspace has the files it should. fn layout(root: &Path, paths: &[String], out: &mut impl Write) -> Done { if paths.is_empty() { return Err(USAGE.to_string()); } for p in paths { if !root.join(p).is_file() { return Err(format!("missing: {p}")); } emit(out, &format!("found {p}"))?; } Ok(()) } /// Notes left in the code, for the log. fn todos(root: &Path, dirs: &[String], out: &mut impl Write) -> Done { if dirs.is_empty() { return Err(USAGE.to_string()); } let mut noted = Vec::new(); for d in dirs { for file in files(&root.join(d))? { // Text only, as grep reports a binary file rather than its lines. let Ok(text) = fs::read_to_string(&file) else { continue }; let name = shown(root, &file); for (i, line) in text.lines().enumerate() { if MARKERS.iter().any(|m| line.contains(m)) { noted.push(format!("{name}:{}:{line}", i + 1)); } } } } emit(out, &format!("{} {} notes in {}", noted.len(), MARKERS.join("/"), shown_dirs(dirs)))?; for line in noted.iter().take(LISTED) { emit(out, line)?; } Ok(()) } /// Lines of Rust per crate: each directory directly under `dir`. fn size(root: &Path, dir: &str, out: &mut impl Write) -> Done { for krate in entries(&root.join(dir))?.into_iter().filter(|p| p.is_dir()) { let mut lines = 0; for file in files(&krate)?.into_iter().filter(|f| f.extension().is_some_and(|e| e == "rs")) { let bytes = fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?; lines += bytes.iter().filter(|&&b| b == b'\n').count(); } emit(out, &format!("{:<24} {lines:>6} lines", format!("{}/", shown(root, &krate))))?; } Ok(()) } fn summary(project: Option<&str>, out: &mut impl Write) -> Done { emit(out, &format!("{}: every check passed on this state.", project.unwrap_or("This project"))) } /// A directory's entries, sorted by name so every runner prints the same. /// A version as three numbers, or `None`. fn version(s: &str) -> Option<(u64, u64, u64)> { let mut parts = s.split('.').map(|p| p.parse::().ok()); let v = (parts.next()??, parts.next()??, parts.next()??); parts.next().is_none().then_some(v) } /// A `YYYY-MM-DD` date with a real month and day. fn is_date(s: &str) -> bool { let b = s.as_bytes(); b.len() == 10 && b[4] == b'-' && b[7] == b'-' && s[..4].parse::().is_ok() && s[5..7].parse::().is_ok_and(|m| (1..=12).contains(&m)) && s[8..].parse::().is_ok_and(|d| (1..=31).contains(&d)) } /// The version a manifest declares: `version = "…"` in `Cargo.toml`'s /// `[package]` or `[workspace.package]`, a `….version=` key of a /// `.properties` file, or `"version"` in a `package.json`. fn manifest_version(path: &str, text: &str) -> Option { let unquote = |v: &str| v.trim().trim_matches('"').trim_end_matches(',').trim_matches('"').to_string(); if path.ends_with(".properties") { return text.lines().find_map(|l| { let (k, v) = l.split_once('=')?; (k.trim() == "version" || k.trim().ends_with(".version")).then(|| v.trim().to_string()) }); } if path.ends_with(".json") { return text.lines().find_map(|l| l.trim().strip_prefix("\"version\":").map(unquote)); } let mut section = ""; for l in text.lines() { let l = l.trim(); if l.starts_with('[') { section = l; } else if matches!(section, "[package]" | "[workspace.package]") { if let Some(v) = l.strip_prefix("version").and_then(|r| r.trim_start().strip_prefix('=')) { return Some(unquote(v)); } } } None } /// The changelog's shape, and the manifest's version in it. fn changelog(root: &Path, file: &str, manifest: Option<&String>, out: &mut impl Write) -> Done { let text = fs::read_to_string(root.join(file)).map_err(|e| format!("{file}: {e}"))?; let mut sections: Vec<(usize, String, usize)> = Vec::new(); // (line, heading, entries) for (i, line) in text.lines().enumerate() { if let Some(h) = line.strip_prefix("## ") { sections.push((i + 1, h.trim().to_string(), 0)); } else if let Some(last) = sections.last_mut() { if line.trim_start().starts_with("- ") || line.trim_start().starts_with("* ") { last.2 += 1; } } } let mut problems = Vec::new(); let mut last: Option<(u64, u64, u64)> = None; let mut released = Vec::new(); for (k, (line, h, n)) in sections.iter().enumerate() { if h == "Unreleased" { if k != 0 { problems.push(format!("{file}:{line}: ## Unreleased comes first")); } continue; } let (v, rest) = h.split_once(' ').unwrap_or((h.as_str(), "")); let date = rest.trim().strip_prefix('(').and_then(|r| r.strip_suffix(')')); match (version(v), date) { (Some(ver), Some(d)) if is_date(d) => { if last.is_some_and(|l| ver >= l) { problems.push(format!("{file}:{line}: {v} is not older than the section above it")); } last = Some(ver); released.push(v.to_string()); if *n == 0 { problems.push(format!("{file}:{line}: ## {h} has no entries")); } } _ => problems.push(format!("{file}:{line}: \"## {h}\" is not \"## X.Y.Z (YYYY-MM-DD)\" or \"## Unreleased\"")), } } let mut said = format!("changelog: {} released section{}", released.len(), if released.len() == 1 { "" } else { "s" }); if let Some(m) = manifest { let mtext = fs::read_to_string(root.join(m)).map_err(|e| format!("{m}: {e}"))?; match manifest_version(m, &mtext) { Some(v) if released.contains(&v) => said.push_str(&format!(", {m} at {v} has its section")), Some(v) => problems.push(format!( "{m} says version {v}, but {file} has no \"## {v} (YYYY-MM-DD)\" section: a release of it would have no notes" )), None => problems.push(format!("{m}: no version found")), } } if problems.is_empty() { return emit(out, &said); } Err(problems.join("\n")) } fn entries(dir: &Path) -> Result, String> { let read = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let mut all = read.map(|e| e.map(|e| e.path())).collect::, _>>().map_err(|e| format!("{}: {e}", dir.display()))?; all.sort(); Ok(all) } /// Every file under `dir`, depth first, in name order; links are not followed. fn files(dir: &Path) -> Result, String> { let mut found = Vec::new(); for p in entries(dir)? { let kind = fs::symlink_metadata(&p).map_err(|e| format!("{}: {e}", p.display()))?.file_type(); if kind.is_dir() { found.extend(files(&p)?); } else if kind.is_file() { found.push(p); } } Ok(found) } /// A path as the workspace names it, with `/` between its parts. fn shown(root: &Path, p: &Path) -> String { let rel = p.strip_prefix(root).unwrap_or(p); rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/") } fn shown_dirs(dirs: &[String]) -> String { dirs.iter().map(|d| format!("{}/", d.trim_end_matches('/'))).collect::>().join(" ") } #[cfg(test)] mod tests { use super::*; fn tree(files: &[(&str, &str)]) -> tempfile::TempDir { let dir = tempfile::tempdir().unwrap(); for (path, text) in files { let p = dir.path().join(path); fs::create_dir_all(p.parent().unwrap()).unwrap(); fs::write(p, text).unwrap(); } dir } fn run(f: impl FnOnce(&mut Vec) -> Done) -> (Done, String) { let mut out = Vec::new(); let done = f(&mut out); (done, String::from_utf8(out).unwrap()) } fn args(a: &[&str]) -> Vec { a.iter().map(|s| s.to_string()).collect() } #[test] fn changelog_shape_and_the_manifest_version() { let good = "# Changelog\n\nIntro.\n\n## Unreleased\n\n## 0.2.0 (2026-11-03)\n\n- **New.**\n\n## 0.1.9 (2026-10-01)\n\n- Old.\n"; let dir = tree(&[ ("CHANGELOG.md", good), ("Cargo.toml", "[workspace]\nmembers = []\n\n[workspace.package]\nversion = \"0.2.0\"\n"), ("gradle.properties", "android.useAndroidX=true\noxygenhub.version=0.1.9\n"), ("package.json", "{\n \"name\": \"x\",\n \"version\": \"0.3.0\",\n}\n"), ]); let r = |m: Option<&str>| run(|o| changelog(dir.path(), "CHANGELOG.md", m.map(String::from).as_ref(), o)); let (done, out) = r(None); assert_eq!((done, out.trim()), (Ok(()), "changelog: 2 released sections")); assert!(r(Some("Cargo.toml")).1.contains("Cargo.toml at 0.2.0 has its section")); assert!(r(Some("gradle.properties")).0.is_ok(), "an older release's section counts"); let e = r(Some("package.json")).0.unwrap_err(); assert!(e.contains("version 0.3.0") && e.contains("no \"## 0.3.0 (YYYY-MM-DD)\""), "{e}"); let bad = "## 0.1.0 (2026-10-01)\n\n- a\n\n## Unreleased\n\n## 0.2.0 (2026-13-01)\n\n- b\n\n## 0.0.9 (2026-09-01)\n\n## v1\n"; let dir = tree(&[("CHANGELOG.md", bad)]); let e = run(|o| changelog(dir.path(), "CHANGELOG.md", None, o)).0.unwrap_err(); assert!(e.contains(":5: ## Unreleased comes first"), "{e}"); assert!(e.contains(":7: \"## 0.2.0 (2026-13-01)\" is not"), "a month 13: {e}"); assert!(e.contains(":11: ## 0.0.9 (2026-09-01) has no entries"), "{e}"); assert!(e.contains(":13: \"## v1\""), "{e}"); let order = "## 0.1.0 (2026-10-01)\n\n- a\n\n## 0.2.0 (2026-11-01)\n\n- b\n"; let dir = tree(&[("CHANGELOG.md", order)]); let e = run(|o| changelog(dir.path(), "CHANGELOG.md", None, o)).0.unwrap_err(); assert!(e.contains("0.2.0 is not older than the section above it"), "{e}"); } #[test] fn layout_lists_what_it_found_and_fails_on_the_first_missing() { let t = tree(&[("Cargo.toml", ""), ("docs/m0.md", "")]); let (done, out) = run(|o| layout(t.path(), &args(&["Cargo.toml", "docs/m0.md"]), o)); assert_eq!(done, Ok(())); assert_eq!(out, "found Cargo.toml\nfound docs/m0.md\n"); let (done, out) = run(|o| layout(t.path(), &args(&["Cargo.toml", "nope.rs", "docs/m0.md"]), o)); assert_eq!(done, Err("missing: nope.rs".to_string())); assert_eq!(out, "found Cargo.toml\n"); // A directory is not the file asked for. assert!(layout(t.path(), &args(&["docs"]), &mut Vec::new()).is_err()); } #[test] fn todos_counts_every_marked_line_and_lists_the_first_twenty() { let marker = MARKERS[0]; let many: String = (0..25).map(|i| format!("// {marker} {i}\n")).collect(); let t = tree(&[ ("crates/a/src/lib.rs", &format!("fn a() {{}}\n// {} later\n", MARKERS[1])), ("crates/b/src/many.rs", &many), ("crates/b/blob.bin", "\u{0}"), ]); // Invalid UTF-8 is skipped, as grep skips a binary file's lines. fs::write(t.path().join("crates/b/blob.bin"), [0xff, 0xfe, b'T']).unwrap(); let (done, out) = run(|o| todos(t.path(), &args(&["crates"]), o)); assert_eq!(done, Ok(())); let lines: Vec<&str> = out.lines().collect(); assert_eq!(lines[0], format!("26 {} notes in crates/", MARKERS.join("/"))); assert_eq!(lines[1], format!("crates/a/src/lib.rs:2:// {} later", MARKERS[1])); assert_eq!(lines[2], format!("crates/b/src/many.rs:1:// {marker} 0")); assert_eq!(lines.len(), 1 + LISTED); } #[test] fn size_counts_rust_lines_per_crate_in_name_order() { let t = tree(&[ ("crates/zeta/src/main.rs", "a\nb\nc\n"), ("crates/alpha/src/lib.rs", "a\n"), ("crates/alpha/src/deep/mod.rs", "a\nb\n"), ("crates/alpha/README.md", "not rust\n"), ("crates/loose.txt", "a file, not a crate\n"), ]); let (done, out) = run(|o| size(t.path(), "crates", o)); assert_eq!(done, Ok(())); assert_eq!(out, format!("{:<24} {:>6} lines\n{:<24} {:>6} lines\n", "crates/alpha/", 3, "crates/zeta/", 3)); } #[test] fn summary_names_the_project() { let (_, out) = run(|o| summary(Some("OxygenFlow"), o)); assert_eq!(out, "OxygenFlow: every check passed on this state.\n"); } }