use std::path::{Path, PathBuf};
pub(crate) fn rs_files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
walk(dir, &mut out);
out
}
pub(crate) fn rs_files_in(rel: &str) -> Vec<PathBuf> {
rs_files(&Path::new(env!("CARGO_MANIFEST_DIR")).join(rel))
}
pub(crate) fn production_code(source: &str) -> String {
source
.lines()
.filter(|line| !line.trim_start().starts_with("//"))
.take_while(|line| !line.trim_start().starts_with("#[cfg(test)]"))
.collect::<Vec<_>>()
.join("\n")
}
pub(crate) fn calls<'a>(code: &'a str, opener: &str) -> Vec<&'a str> {
let mut out = Vec::new();
let mut from = 0;
while let Some(found) = code[from..].find(opener) {
let start = from + found;
let end = start + call_len(&code[start..]);
out.push(&code[start..end]);
from = end.max(start + 1);
}
out
}
fn call_len(call: &str) -> usize {
let bytes = call.as_bytes();
let mut depth = 0usize;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'(' => depth += 1,
b')' => {
depth = depth.saturating_sub(1);
if depth == 0 {
return i + 1;
}
}
b'"' => i = string_end(bytes, i, None),
b'r' => {
if let Some(hashes) = raw_string_hashes(bytes, i) {
i = string_end(bytes, i + 1 + hashes, Some(hashes));
}
}
b'\'' => {
if bytes.get(i + 1) == Some(&b'\\') {
i = bytes[i + 2..]
.iter()
.position(|&b| b == b'\'')
.map_or(bytes.len(), |n| i + 2 + n);
} else if bytes.get(i + 2) == Some(&b'\'') {
i += 2;
}
}
_ => {}
}
i += 1;
}
bytes.len()
}
fn string_end(bytes: &[u8], open: usize, raw: Option<usize>) -> usize {
let hashes = raw.unwrap_or(0);
let mut i = open + 1;
while i < bytes.len() {
if raw.is_none() && bytes[i] == b'\\' {
i += 2;
continue;
}
if bytes[i] == b'"' && bytes[i + 1..].iter().take(hashes).all(|&b| b == b'#') {
return i + hashes;
}
i += 1;
}
bytes.len()
}
fn raw_string_hashes(bytes: &[u8], at: usize) -> Option<usize> {
if at > 0 && (bytes[at - 1].is_ascii_alphanumeric() || bytes[at - 1] == b'_') {
return None;
}
let hashes = bytes[at + 1..].iter().take_while(|&&b| b == b'#').count();
(bytes.get(at + 1 + hashes) == Some(&b'"')).then_some(hashes)
}
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).expect("a readable source directory") {
let path = entry.expect("a readable directory entry").path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
#[cfg(test)]
mod tests {
use crate::vendor::VendorId;
use std::collections::BTreeMap;
#[test]
fn no_changelog_entry_appears_under_two_versions() {
let Some(changelog) = changelog() else { return };
let mut seen: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
let mut version = "<before any version heading>";
for line in changelog.lines() {
if let Some(rest) = line.strip_prefix("## ") {
version = rest.trim();
} else if let Some(entry) = line.strip_prefix("- ") {
let entry = entry.trim();
if entry.len() > 24 {
seen.entry(entry).or_default().push(version);
}
}
}
let duplicated: Vec<_> = seen
.iter()
.filter(|(_, versions)| {
let mut distinct = versions.to_vec();
distinct.sort_unstable();
distinct.dedup();
distinct.len() > 1
})
.map(|(entry, versions)| format!("{versions:?}: {}…", &entry[..40.min(entry.len())]))
.collect();
assert!(
duplicated.is_empty(),
"these entries appear under more than one version — an [Unreleased] \\
note has merged into a released section:\n{}",
duplicated.join("\n")
);
}
#[test]
fn no_changelog_section_repeats_a_category() {
let Some(changelog) = changelog() else { return };
let mut offenders = Vec::new();
let mut version = "<before any version heading>";
let mut categories: Vec<&str> = Vec::new();
let mut flush = |version: &str, categories: &mut Vec<&str>| {
let mut sorted = categories.clone();
sorted.sort_unstable();
let before = sorted.len();
sorted.dedup();
if sorted.len() != before {
offenders.push(version.to_string());
}
categories.clear();
};
for line in changelog.lines() {
if let Some(rest) = line.strip_prefix("## ") {
flush(version, &mut categories);
version = rest.trim();
} else if let Some(rest) = line.strip_prefix("### ") {
categories.push(rest.trim());
}
}
flush(version, &mut categories);
const SHIPPED_THIS_WAY: [&str; 2] = ["[1.8.0] — 2026-08-28", "[0.14.0] — 2026-07-20"];
offenders.retain(|version| !SHIPPED_THIS_WAY.contains(&version.as_str()));
assert!(
offenders.is_empty(),
"these versions carry the same category heading twice, which hides \
whatever is under the second one from the release's version \
decision: {offenders:?}"
);
}
fn changelog() -> Option<String> {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("CHANGELOG.md");
std::fs::read_to_string(&path).ok()
}
#[derive(Debug)]
enum MacosMirror {
Slot(&'static str),
Generic(&'static [&'static str]),
}
fn macos_mirror(id: VendorId) -> MacosMirror {
const CORE: &[&str] = &["plan", "vendor_short", "session_pct", "weekly_pct"];
match id {
VendorId::AnthropicApi => MacosMirror::Slot("aapi_headline"),
VendorId::Antigravity => MacosMirror::Slot("scoped_model"),
VendorId::CommandCode => MacosMirror::Slot("cc_monthly_pct"),
VendorId::Copilot => MacosMirror::Slot("copilot_completions_pct"),
VendorId::Cursor => MacosMirror::Slot("cursor_total_pct"),
VendorId::Deepinfra => MacosMirror::Slot("dif_balance"),
VendorId::Deepseek => MacosMirror::Slot("ds_balance"),
VendorId::Devin => MacosMirror::Slot("devin_daily_pct"),
VendorId::Grok => MacosMirror::Slot("grok_balance"),
VendorId::Kilo => MacosMirror::Slot("kilo_balance"),
VendorId::Lyceum => MacosMirror::Slot("lyceum_balance"),
VendorId::Minimax => MacosMirror::Slot("minimax_video_pct"),
VendorId::Moonshot => MacosMirror::Slot("km_balance"),
VendorId::Novita => MacosMirror::Slot("nv_balance"),
VendorId::Ollama => MacosMirror::Slot("oll_monthly_pct"),
VendorId::OpenCodeGo => MacosMirror::Slot("ocg_monthly_pct"),
VendorId::Openrouter => MacosMirror::Slot("or_balance"),
VendorId::Supergrok => MacosMirror::Slot("sgk_period"),
VendorId::Zai => MacosMirror::Slot("zai_mcp_pct"),
VendorId::Anthropic => MacosMirror::Generic(CORE),
VendorId::Openai => MacosMirror::Generic(CORE),
VendorId::Kimi => MacosMirror::Generic(CORE),
VendorId::Kiro => MacosMirror::Generic(CORE),
VendorId::ModelStudio => MacosMirror::Generic(CORE),
VendorId::NousResearch => MacosMirror::Generic(CORE),
VendorId::OrcaRouter => MacosMirror::Generic(CORE),
VendorId::Grokbot => MacosMirror::Generic(&["plan", "vendor_short", "weekly_pct"]),
}
}
fn rust_placeholder_keys() -> std::collections::BTreeSet<String> {
let mut out = std::collections::BTreeSet::new();
let mut files = super::rs_files_in("src");
files.sort();
for file in files {
let Ok(source) = std::fs::read_to_string(&file) else {
continue;
};
let code = super::production_code(&source);
for (idx, _) in code.match_indices('"') {
let rest = &code[idx + 1..];
let Some(close) = rest.find('"') else { break };
let key = &rest[..close];
if key.is_empty()
|| !key
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
{
continue;
}
let before = code[..idx].trim_end();
let after = rest[close + 1..].trim_start();
let opens_tuple = before.ends_with('(') && after.starts_with(',');
let is_insert = before.ends_with(".insert(");
if opens_tuple || is_insert {
out.insert(key.to_string());
}
}
}
out
}
#[test]
fn macos_format_mirrors_every_vendor_placeholder_family() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("macos/ai-usagebar-menubar.swift");
let Ok(swift) = std::fs::read_to_string(&path) else {
return;
};
let format = match swift.split_once("let FORMAT = ") {
Some((_, rest)) => rest.split("__aiub_end__").next().unwrap_or(rest),
None => panic!("macOS menubar FORMAT string not found"),
};
let emitted = rust_placeholder_keys();
assert!(
emitted.len() > 100,
"the placeholder scan found only {} keys — the scan broke, not the mirror",
emitted.len()
);
for &id in VendorId::all() {
let tokens: Vec<&str> = match macos_mirror(id) {
MacosMirror::Slot(token) => vec![token],
MacosMirror::Generic(tokens) => {
assert!(
!tokens.is_empty(),
"{id:?} claims the generic placeholders but names none — \
list the tokens it renders through, or give it a slot"
);
tokens.to_vec()
}
};
for token in tokens {
assert!(
format.contains(&format!("{{{token}}}")),
"macOS FORMAT is missing {{{token}}} for {id:?} — append its slot \
(never insert: the Swift side reads fields by index)"
);
assert!(
emitted.contains(token),
"{id:?} is mirrored through {{{token}}}, but no Rust code emits that \
placeholder any more — it was renamed on one side only"
);
}
}
}
#[test]
fn aur_checksum_arrays_match_source_arrays() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let aur_dir = root.join("packaging/aur");
if !aur_dir.exists() {
return;
}
for filename in ["PKGBUILD", "PKGBUILD-bin"] {
let path = aur_dir.join(filename);
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => continue,
};
let sources = count_pkgbuild_arrays(&content, "source");
let checksums = count_pkgbuild_arrays(&content, "sha256sums");
assert!(
!sources.is_empty(),
"{filename} must declare at least one source array"
);
for (src_var, src_len) in &sources {
let suffix = src_var.strip_prefix("source").unwrap_or("");
let sha_var = format!("sha256sums{suffix}");
let sha_len = checksums.get(&sha_var).copied().unwrap_or(0);
assert_eq!(
*src_len, sha_len,
"{filename}: {src_var} ({src_len} elements) and \
{sha_var} ({sha_len} elements) differ in length"
);
}
for sha_var in checksums.keys() {
let suffix = sha_var.strip_prefix("sha256sums").unwrap_or("");
let src_var = format!("source{suffix}");
assert!(
sources.contains_key(&src_var),
"{filename}: {sha_var} declared without corresponding {src_var}"
);
}
}
for filename in [".SRCINFO", ".SRCINFO-bin"] {
let path = aur_dir.join(filename);
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => continue,
};
let sources = count_srcinfo_lines(&content, "source");
let checksums = count_srcinfo_lines(&content, "sha256sums");
assert!(
!sources.is_empty(),
"{filename} must declare at least one source entry"
);
for (src_key, src_len) in &sources {
let suffix = src_key.strip_prefix("source").unwrap_or("");
let sha_key = format!("sha256sums{suffix}");
let sha_len = checksums.get(&sha_key).copied().unwrap_or(0);
assert_eq!(
*src_len, sha_len,
"{filename}: {src_key} ({src_len} lines) and \
{sha_key} ({sha_len} lines) differ in count"
);
}
for sha_key in checksums.keys() {
let suffix = sha_key.strip_prefix("sha256sums").unwrap_or("");
let src_key = format!("source{suffix}");
assert!(
sources.contains_key(&src_key),
"{filename}: {sha_key} declared without corresponding {src_key}"
);
}
}
}
fn count_pkgbuild_arrays(content: &str, prefix: &str) -> BTreeMap<String, usize> {
let mut results = BTreeMap::new();
let mut in_array: Option<(String, usize)> = None;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') {
continue;
}
if let Some((name, count)) = in_array.as_mut() {
let part = trimmed.split('#').next().unwrap_or("").trim();
*count += count_quoted_items(part);
if part.contains(')') {
results.insert(name.clone(), *count);
in_array = None;
}
} else if let Some((var_name, rest)) = trimmed.split_once("=(") {
let var_name = var_name.trim();
if var_name.starts_with(prefix) {
let part = rest.split('#').next().unwrap_or("").trim();
let count = count_quoted_items(part);
if part.contains(')') {
results.insert(var_name.to_string(), count);
} else {
in_array = Some((var_name.to_string(), count));
}
}
}
}
results
}
fn count_quoted_items(s: &str) -> usize {
let mut count = 0;
let mut in_single = false;
let mut in_double = false;
let mut in_word = false;
for c in s.chars() {
if in_single {
if c == '\'' {
in_single = false;
count += 1;
}
} else if in_double {
if c == '"' {
in_double = false;
count += 1;
}
} else if c == '\'' {
in_single = true;
in_word = false;
} else if c == '"' {
in_double = true;
in_word = false;
} else if c == '(' || c == ')' || c.is_whitespace() {
if in_word {
count += 1;
in_word = false;
}
} else {
in_word = true;
}
}
if in_word {
count += 1;
}
count
}
fn count_srcinfo_lines(content: &str, prefix: &str) -> BTreeMap<String, usize> {
let mut counts = BTreeMap::new();
for line in content.lines() {
let trimmed = line.trim();
if let Some((key, _)) = trimmed.split_once('=') {
let key = key.trim();
if key.starts_with(prefix) {
*counts.entry(key.to_string()).or_insert(0) += 1;
}
}
}
counts
}
#[test]
fn calls_ignore_parens_inside_literals() {
let code =
r##"println!("step 1) {}", path.display()); other(); println!(r#"a ) "b" "#, x);"##;
let found = super::calls(code, "println!(");
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].ends_with("path.display())"), "{}", found[0]);
assert!(found[1].ends_with("x)"), "{}", found[1]);
}
#[test]
fn calls_handle_char_literals_lifetimes_and_escapes() {
let code = r#"print!("{}", f(')', '"', "\"", &'a str)); tail()"#;
let found = super::calls(code, "print!(");
assert_eq!(found, [r#"print!("{}", f(')', '"', "\"", &'a str))"#]);
}
#[test]
fn calls_visit_each_macro_once_and_survive_an_unclosed_call() {
let code = "eprintln!(\"a\"); println!(\"b\"); println!(\"c\"";
let found = super::calls(code, "println!(");
assert_eq!(
found,
["println!(\"a\")", "println!(\"b\")", "println!(\"c\""]
);
}
}