use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::rules::{self, Ruleset};
use crate::walk::{Options, Root};
use crate::{Output, code};
const WORDS: &str = "kept # a vague participle\nheld except lib/vendored/ # a vague participle\n\
made allow made_up # a vague participle\n";
fn ruleset() -> Ruleset {
Ruleset {
name: "test@1".into(),
identifiers: Some(WORDS.into()),
docs: None,
strings: None,
identifiers_advice: "Rename it.\n".into(),
strings_advice: String::new(),
}
}
struct Tree(PathBuf);
impl Tree {
fn new(files: &[(&str, &str)]) -> Tree {
let tree = Tree::plain(files);
for args in [&["init", "-q"][..], &["add", "-A"]] {
assert!(Command::new("git").args(args).current_dir(&tree.0).status().unwrap().success());
}
tree
}
fn plain(files: &[(&str, &str)]) -> Tree {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let name = format!("prosecop-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
let tree = Tree(std::env::temp_dir().join(name));
std::fs::create_dir_all(&tree.0).unwrap();
for (path, text) in files {
let path = tree.0.join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
tree
}
fn try_run(&self, args: &[&str]) -> Result<Output, String> {
crate::run(&Root::at(self.0.clone()), &args.iter().map(|a| a.to_string()).collect::<Vec<_>>())
}
fn run(&self, args: &[&str]) -> Output {
self.try_run(args).unwrap()
}
fn code(&self, args: &[&str]) -> Output {
self.code_in(&self.0, args)
}
fn code_in(&self, dir: &std::path::Path, args: &[&str]) -> Output {
let options = Options::parse(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>()).unwrap();
code::run(&ruleset(), &Root::at(dir.to_path_buf()), &options).unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn code(path: &str, text: &str) -> Vec<String> {
Tree::new(&[(path, text)]).code(&[]).stdout.lines().map(String::from).collect()
}
fn docs(path: &str, text: &str) -> Vec<String> {
let tree = Tree::new(&[(path, text)]);
let out = tree.run(&["claude@5/docs.txt", tree.0.join(path).to_str().unwrap()]).stdout;
let rule = |l: &str| l.splitn(5, ": ").take(3).collect::<Vec<_>>().join(": ");
out.lines().map(|l| rule(l.strip_prefix(path).unwrap().strip_prefix(':').unwrap())).collect()
}
fn strings(path: &str, text: &str) -> Vec<String> {
let tree = Tree::new(&[(path, text)]);
let out = tree.run(&["claude@5/strings.txt", tree.0.join(path).to_str().unwrap()]).stdout;
let rule = |l: &str| {
let fields: Vec<&str> = l.splitn(4, ": ").collect();
format!("{}: {}", fields[0].rsplit(':').next().unwrap(), fields[2])
};
out.lines().map(rule).collect()
}
#[test]
fn code_finds_forbidden_words_in_identifiers_and_file_names() {
let found = code("desk/kept_file.rs", "fn main() {\n let heldValue = 1;\n}\n");
assert_eq!(found, ["desk/kept_file.rs:1: kept in kept_file.rs", "desk/kept_file.rs:2: held in heldValue"]);
}
#[test]
fn code_allows_a_word_under_its_paths_and_in_its_compounds() {
assert!(code("lib/vendored/x.rs", "fn held() {}\n").is_empty());
assert_eq!(code("desk/x.py", "made_up = 1\nmade = 2\n"), ["desk/x.py:2: made in made"]);
}
#[test]
fn code_skips_comments_strings_and_tests() {
let rust = "// kept\n/* a /* kept */ kept */\nfn f() { \"kept\"; r#\"kept\"#; 'k'; }\n#[test]\nfn kept() {}\n\
#[tokio::test]\nasync fn kept_async() {}\n";
assert!(code("desk/x.rs", rust).is_empty());
assert!(code("desk/x.py", "# kept\ns = 'kept'\ndef test_kept():\n \"\"\"kept\"\"\"\n").is_empty());
assert!(code("desk/x.ts", "// kept\nconst s = `kept ${1}`; /* kept */\n").is_empty());
}
#[test]
fn code_exempts_a_function_inside_a_macro_that_makes_tests() {
let rust = "macro_rules! cases {\n ($n:ident) => { #[test] fn $n() {} };\n}\ncases! { fn kept() {} }\n\
other! { fn kept() {} }\n";
assert_eq!(code("desk/x.rs", rust), ["desk/x.rs:5: kept in kept"]);
}
#[test]
fn code_checks_the_named_directories_outside_excludes_and_prints_the_identifiers_advice() {
let tree = Tree::new(&[("a/kept.rs", "fn f() {}\n"), ("a/vendor/kept.rs", ""), ("b/kept.rs", "")]);
let out = tree.code(&["a", "--exclude", "a/vendor"]);
assert_eq!(out.stdout, "a/kept.rs:1: kept in kept.rs\n");
assert!(out.failed && out.stderr.contains("of test@1") && out.stderr.ends_with("Rename it.\n"));
}
#[test]
fn the_built_in_ruleset_parses_every_word_with_a_reason() {
let (claude, _) = rules::resolve("claude@5").unwrap();
let lines = claude.identifiers.as_deref().unwrap().lines().filter(|l| !l.trim().is_empty());
assert!(lines.clone().count() > 0 && lines.clone().all(|l| l.contains(" # ")));
assert!(!Tree::new(&[("a/x.rs", "/// One.\nfn f() {}\n")]).run(&["claude@5"]).failed);
}
#[test]
fn docs_checks_the_shape_of_a_rust_doc() {
let long = "/// Line.\n///\n".repeat(20) + "fn f() {}\n";
assert!(docs("x.rs", &long).is_empty());
assert_eq!(docs("x.rs", "/// One. Two.\nfn f() {}\n"), ["1: reject: summary"]);
assert_eq!(docs("x.rs", "/// The test.\n#[test]\nfn f() {}\n"), ["1: reject: test doc"]);
assert_eq!(docs("tests/x.rs", "//! A test module.\n"), ["1: reject: test module doc"]);
let each = "/// One.\n///\n/// It reads each row and each column.\nfn f() {}\n";
assert_eq!(docs("x.rs", each), ["3: reject: each chain"]);
let words = "/// One.\n///\n/// It".to_string() + &" reads".repeat(30) + ".\nfn f() {}\n";
assert_eq!(docs("x.rs", &words), ["3: reject: long sentence"]);
}
#[test]
fn docs_finds_each_rule_by_pattern() {
let cases = [
("It is no parser.", "no-negation"),
("A value that nothing reads.", "negative relative"),
("It is the file a request writes.", "object relative"),
("It is a name, as the user spells it.", "as clause"),
("It shows what is typed.", "vague what"),
("It joined a file of it.", "verbed of it"),
("It is beside the point.", "banned word"),
("The row's owner's map.", "possessive chain"),
];
for (doc, rule) in cases {
let found = docs("x.rs", &format!("/// {doc}\nfn f() {{}}\n"));
assert!(found.contains(&format!("1: reject: {rule}")), "{doc}: {found:?}");
}
assert_eq!(docs("x.rs", "/// One.\n///\n/// The key: name of it.\nfn f() {}\n"), ["3: warn: colon fragment"]);
assert_eq!(docs("x.rs", "/// It is made here.\nfn f() {}\n"), ["1: reject: banned word"]);
assert!(docs("x.rs", "/// A made-up name.\nfn f() {}\n").is_empty());
}
#[test]
fn docs_reads_markdown_without_code_tables_or_headings() {
assert!(docs("x.md", "# What is it\n\n what is code\n\n| what is |\n\n`what is` here.\n").is_empty());
}
#[test]
fn docs_checks_python_docstrings() {
let wide = format!("def f():\n \"\"\"{}.\"\"\"\n", "a".repeat(200));
assert!(docs("pylib/python/x.py", &wide).is_empty());
let test = "\"\"\"A test module.\"\"\"\n";
assert_eq!(docs("pylib/python/tests/test_x.py", test), ["1: reject: test module doc"]);
let class = "class C:\n x: int\n \"\"\"It is what is given.\"\"\"\n\n def f(self):\n \
'''One.\n\n Parameters:\n v: what is it.\n\n References:\n \
What is.\n '''\n";
assert_eq!(docs("pylib/python/x.py", class), ["3: reject: vague what", "9: reject: vague what"]);
}
#[test]
fn docs_lists_files_by_suffix_outside_excludes_and_skips_suffixes_that_match_nothing() {
let bad = "/// One. Two.\nfn f() {}\n";
let tree = Tree::new(&[("a/x.rs", bad), ("vendor/y.rs", bad), ("notes.txt", bad)]);
let out = tree.run(&["claude@5/docs.txt", "--ext", ".rs,.md,py", "--exclude=vendor"]);
assert_eq!(out.stdout.lines().map(|l| l.split(':').next().unwrap()).collect::<Vec<_>>(), ["a/x.rs"]);
assert!(out.failed);
}
#[test]
fn each_kind_rejects_an_unknown_option_and_a_suffix_it_cannot_read() {
let tree = Tree::new(&[]);
let error = |args: &[&str]| tree.try_run(args).err().unwrap();
for ruleset in ["claude@5", "claude@5/identifiers.txt", "claude@5/docs.txt", "claude@5/strings.txt"] {
assert!(error(&[ruleset, "--all"]).starts_with("unknown option --all"));
}
assert!(error(&["claude@5/docs.txt", "--ext", ".ts"]).contains("cannot read .ts"));
assert!(error(&["claude@5/identifiers.txt", "--ext=md"]).contains("cannot read .md"));
assert!(error(&["claude@5/strings.txt", "--ext=md"]).contains("cannot read .md"));
assert!(error(&["claude@5/docs.txt", "--forbid", "near"]).contains("only to identifiers"));
}
#[test]
fn the_first_argument_names_a_built_in_ruleset_or_a_path_and_may_pick_one_kind() {
let tree = Tree::new(&[("a/kept.rs", "/// One. Two.\nfn f() {}\n"), ("notes.md", "It shows what is typed.\n")]);
let lines = |out: Output| {
out.stdout.lines().map(|l| l.splitn(4, ": ").take(2).collect::<Vec<_>>().join(": ")).collect::<Vec<_>>()
};
assert_eq!(lines(tree.run(&["claude@5", "a"])), ["a/kept.rs:1: kept in kept.rs", "a/kept.rs:1: reject"]);
assert_eq!(lines(tree.run(&["claude@5/identifiers.txt", "a"])), ["a/kept.rs:1: kept in kept.rs"]);
assert_eq!(lines(tree.run(&["claude@5/docs.txt", "a"])), ["a/kept.rs:1: reject"]);
assert_eq!(lines(tree.run(&["claude@5/identifiers", "a"])), ["a/kept.rs:1: kept in kept.rs"]);
assert_eq!(lines(tree.run(&["claude@5/docs", "a"])), ["a/kept.rs:1: reject"]);
let rules = tree.0.join("rules/house");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(rules.join("identifiers.txt"), "kept # a vague participle\n").unwrap();
let out = tree.run(&[rules.to_str().unwrap(), "a", "notes.md"]);
assert_eq!(out.stdout, "a/kept.rs:1: kept in kept.rs\n");
assert!(out.stderr.contains("rules/house found:"));
let out = tree.run(&[rules.join("identifiers").to_str().unwrap(), "a"]);
assert_eq!(out.stdout, "a/kept.rs:1: kept in kept.rs\n");
let docs = rules.join("docs.txt");
assert!(tree.try_run(&[docs.to_str().unwrap()]).err().unwrap().contains("has no docs.txt"));
let error = |args: &[&str]| tree.try_run(args).err().unwrap();
assert!(error(&["claude@9"]).contains("neither a built-in ruleset, which are claude@5, nor a path"));
let kinds = "a rules file is identifiers.txt, docs.txt or strings.txt";
assert!(error(&["claude@5/messages.txt"]).contains(kinds));
assert!(error(&["claude@5/messages"]).contains(kinds));
assert!(error(&["--ext", ".rs"]).starts_with("usage:"));
}
#[test]
fn docs_rules_report_an_error_with_its_line_or_rule() {
let parse = |text: &str| crate::docs::DocRules::parse(text, "docs.txt").err().unwrap();
assert_eq!(parse("verdict = reject\n"), "docs.txt:1: a field must follow a `[NAME]`");
assert_eq!(parse("[a]\npattern = {verbs}\n"), "docs.txt:2: {verbs} is not defined");
assert_eq!(parse("[a]\nverdict = maybe\n"), "docs.txt:2: unknown field or value: verdict = maybe");
assert!(parse("[a]\npattern = (\nwords = x\n").starts_with("docs.txt: [a]: "));
assert_eq!(parse("[a]\nwords = x\n"), "docs.txt: [a]: a rule needs a pattern and words");
}
#[test]
fn docs_reads_plain_text_as_prose() {
assert_eq!(docs("x.txt", "word # It shows what is typed.\n"), ["1: reject: vague what"]);
}
#[test]
fn code_checks_untracked_files_outside_gitignore() {
let tree = Tree::new(&[(".gitignore", "ignored/\n"), ("a.rs", "")]);
for path in ["untracked/kept.rs", "ignored/kept.rs"] {
std::fs::create_dir_all(tree.0.join(path).parent().unwrap()).unwrap();
std::fs::write(tree.0.join(path), "").unwrap();
}
assert_eq!(tree.code(&[]).stdout, "untracked/kept.rs:1: kept in kept.rs\n");
}
#[test]
fn code_runs_from_a_subdirectory_with_the_gitignore_above_it() {
let tree = Tree::new(&[(".gitignore", "ignored/\n"), ("sub/kept.rs", ""), ("sub/ignored/kept.rs", "")]);
assert_eq!(tree.code_in(&tree.0.join("sub"), &[]).stdout, "kept.rs:1: kept in kept.rs\n");
}
#[test]
fn code_runs_outside_a_git_work_tree_without_its_gitignore() {
let tree = Tree::plain(&[(".gitignore", "ignored/\n"), ("ignored/kept.rs", "")]);
assert_eq!(tree.code(&[]).stdout, "ignored/kept.rs:1: kept in kept.rs\n");
}
#[test]
fn code_reports_a_path_outside_the_root_as_it_was_named() {
let tree = Tree::plain(&[("a/kept.rs", ""), ("b/x.rs", "")]);
let b = tree.0.join("b");
assert_eq!(tree.code_in(&b, &["../a"]).stdout, "../a/kept.rs:1: kept in kept.rs\n");
let a = tree.0.join("a");
let absolute = format!("{}/kept.rs:1: kept in kept.rs\n", a.display()).replace('\\', "/");
assert_eq!(tree.code_in(&b, &[a.to_str().unwrap()]).stdout, absolute);
assert_eq!(tree.code_in(&b, &[a.join("kept.rs").to_str().unwrap()]).stdout, absolute);
}
#[test]
fn code_takes_more_forbidden_words_and_allowed_words_or_compounds() {
let tree = Tree::new(&[("desk/a.rs", "fn kept_near() {}\nfn made_least() {}\nfn held_kib() {}\n")]);
let out = tree.code(&["--forbid", "near,least", "--allow=kept,least", "--allow", "held_kib"]);
assert_eq!(out.stdout, "desk/a.rs:1: near in kept_near\ndesk/a.rs:2: made in made_least\n");
assert!(out.stderr.contains("near: The word is forbidden by --forbid."));
}
#[test]
fn strings_finds_each_rule_in_a_message_and_stays_silent_on_a_sound_one() {
let cases = [
("U+{c}, which a click copies", &["which subject", "narrated input"][..]),
("the lists must all have one length, which `{text}` might not", &["which subject"]),
("a `skip` may not name `{arch}`, which pycc does not compile for", &["which subject"]),
("`{n}` is a list, which may not be called", &["restated which"]),
("2**63 is no int64", &["noun negation"]),
("`object.__init__` sets no field", &["noun negation"]),
("There is no name here to rename", &["noun negation", "pronoun opener"]),
("`{program}` wrote what is not text: {e}", &["vague what"]),
("It is over {} MB", &["pronoun opener"]),
("the file was saved successfully", &["filler"]),
("Something went wrong with the file", &["empty failure"]),
("a dict's key is a string literal", &["generic statement"]),
("an alias's type parameter takes a default, not a bound", &["generic statement"]),
("a parameter's name is interned", &["generic statement"]),
("an answer's arrays are in memory", &["generic statement"]),
("the value is set. Each row's value has its own type", &["generic statement"]),
("`x` is a list, not an `np.ndarray`", &[]),
("`{short}` takes a 1D array of at least 1 element", &[]),
("takes {x}, but a list's index is an int", &["generic statement"]),
("takes {x}, not a list's index", &[]),
("index {k} is past the end of {name}, which has {n} items", &[]),
("`{c}` is a frozen dataclass, which raises `FrozenInstanceError`", &[]),
("`{n}` may declare only its keys, since it is a `TypedDict`", &[]),
("What is the name of the file?", &[]),
("Could not show `{path}`: unreadable font", &[]),
];
for (message, rules) in cases {
let found = strings("x.rs", &format!("fn f() {{ g(\"{message}\"); }}\n"));
let expected: Vec<String> = rules.iter().map(|rule| format!("1: {rule}")).collect();
assert_eq!(found, expected, "{message}");
}
}
#[test]
fn strings_checks_only_literals_shaped_like_sentences_outside_tests() {
let rust = "fn f() {\n g(\"It is\");\n g(\"It_is_not_here\");\n g(\"red green blue\");\n \
g(\"x = It is not here\");\n g(\"It is not here\");\n}\n#[cfg(test)]\nmod tests {\n \
fn t() { g(\"It is not here\"); }\n}\n";
assert_eq!(strings("src/x.rs", rust), ["6: pronoun opener"]);
assert!(strings("src/tests.rs", rust).is_empty());
assert!(strings("src/x.test.ts", "g('It is not here');\n").is_empty());
assert_eq!(strings("src/x.ts", "g(`It is not ${here} now`);\n"), ["1: pronoun opener"]);
}
#[test]
fn strings_skips_python_docstrings_but_reads_a_message_on_a_line_of_its_own() {
let python = "\"\"\"It is a module.\"\"\"\n\nLIMIT = 3\n\"\"\"It is the limit of the run.\"\"\"\n\n\
def f():\n \"\"\"It is a function.\"\"\"\n raise ValueError(\n \
\"It is over the limit of %d\" % LIMIT\n )\n";
assert_eq!(strings("x.py", python), ["9: pronoun opener"]);
}
#[test]
fn strings_prints_the_advice_of_each_rule_found_and_the_strings_advice() {
let tree = Tree::new(&[("x.rs", "fn f() { g(\"It is not here\"); }\n")]);
let out = tree.run(&["claude@5/strings"]);
assert!(out.failed && out.stderr.starts_with("Strings of claude@5 found:\n pronoun opener: Start with"));
assert!(out.stderr.contains("decide who reads it"), "{}", out.stderr);
}