use std::path::Path;
use crate::scheme;
use crate::walk::Patterns;
pub const DEFAULT_CODE: &str = "**/*";
pub const DEFAULT_NOTE_WORDS: usize = 3000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NoteWords {
pub limit: usize,
pub warn: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Verdict {
Error,
Warn,
Allow,
}
impl Verdict {
fn read(value: &str) -> Option<Self> {
match value {
"error" => Some(Self::Error),
"warn" => Some(Self::Warn),
"allow" => Some(Self::Allow),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TestMarkers {
default: Verdict,
rules: Vec<(String, Patterns, Verdict)>,
attr: String,
}
impl TestMarkers {
pub fn at(&self, rel: &Path) -> (Verdict, Option<&str>) {
self.rules
.iter()
.rev()
.find(|(_, glob, _)| glob.matches(rel))
.map_or((self.default, None), |(rule, _, verdict)| {
(*verdict, Some(rule.as_str()))
})
}
pub fn attr(&self) -> &str {
&self.attr
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TestPaths {
list: Option<Patterns>,
}
impl TestPaths {
pub fn conventions() -> Self {
Self { list: None }
}
pub fn at(root: &Path) -> anyhow::Result<Self> {
ProjectPolicy::from_root(root)
.map(|policy| policy.tests)
.map_err(anyhow::Error::msg)
}
pub fn holds(&self, rel: &Path) -> bool {
match &self.list {
Some(list) => list.matches(rel),
None => by_convention(rel),
}
}
}
fn by_convention(rel: &Path) -> bool {
let dirs: Vec<&str> = rel
.parent()
.into_iter()
.flat_map(Path::components)
.filter_map(|c| c.as_os_str().to_str())
.collect();
let name = rel.file_name().and_then(|n| n.to_str()).unwrap_or_default();
let ext = rel.extension().and_then(|e| e.to_str()).unwrap_or_default();
let script = matches!(
ext,
"js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts"
);
dirs.contains(&"tests")
|| (ext == "go" && name.ends_with("_test.go"))
|| (ext == "py" && (name.starts_with("test_") || name.ends_with("_test.py")))
|| (script
&& (dirs.contains(&"__tests__")
|| name
.split('.')
.skip(1)
.any(|part| part == "test" || part == "spec")))
|| (matches!(ext, "java" | "kt" | "kts") && dirs.windows(2).any(|w| w == ["src", "test"]))
}
#[derive(Clone, Debug)]
pub struct ProjectPolicy {
pub code: Patterns,
pub docs: Patterns,
pub tests: TestPaths,
pub test_markers: TestMarkers,
pub note_words: NoteWords,
note_words_attr: String,
code_list: String,
docs_list: String,
tests_list: String,
}
impl ProjectPolicy {
pub fn defaults() -> Self {
Self::of(DEFAULT_CODE, "").expect("the default lists are valid")
}
pub fn from_root(root: &Path) -> Result<Self, String> {
let text = std::fs::read_to_string(root.join("AGENTS.md")).ok();
Self::from_agents(text.as_deref())
}
pub fn explicit_at(root: &Path) -> Result<Self, String> {
let text = std::fs::read_to_string(root.join("AGENTS.md")).ok();
let policy = Self::from_agents(text.as_deref())?;
if let Some(text) = &text {
let written = scheme::attr_names(text);
let omitted: Vec<String> = crate::published::BLOCK_ATTRS
.iter()
.filter(|attr| !written.iter().any(|w| w == *attr))
.map(|attr| format!("`{attr}`"))
.collect();
if !omitted.is_empty() {
return Err(format!(
"AGENTS.md: the Silcrow block omits {}, and a project writes each attribute of its block. Run `silcrow install`, which writes each one at its default and keeps the values you set.",
omitted.join(", ")
));
}
}
Ok(policy)
}
pub fn from_agents(text: Option<&str>) -> Result<Self, String> {
let Some(text) = text else {
return Ok(Self::defaults());
};
let unknown: Vec<String> = scheme::attr_names(text)
.into_iter()
.filter(|attr| !crate::published::BLOCK_ATTRS.contains(&attr.as_str()))
.collect();
if !unknown.is_empty() {
return Err(unknown_attrs(&unknown));
}
crate::walk::Notes::from_agents(Some(text)).map_err(|e| format!("AGENTS.md: {e}"))?;
let code = scheme::attr_from_agents(text, "code");
let docs = scheme::attr_from_agents(text, "docs");
let code = code.unwrap_or_else(|| DEFAULT_CODE.to_string());
if code.split_whitespace().next().is_none() {
return Err(format!(
"AGENTS.md: the `code` list is empty, so no marker could pay a law's code duty. Name the code, or write `code=\"{DEFAULT_CODE}\"` for every file."
));
}
let note_words_attr = scheme::attr_from_agents(text, "note-words");
let note_words = note_words(note_words_attr.as_deref())?;
let tests = tests(scheme::attr_from_agents(text, "tests").as_deref())?;
let test_markers = test_markers(scheme::attr_from_agents(text, "test-markers").as_deref())?;
let policy = Self::of(&code, docs.as_deref().unwrap_or(""))
.map_err(|e| format!("AGENTS.md: {e}"))?;
let tests_list = scheme::attr_from_agents(text, "tests")
.map(|v| v.split_whitespace().collect::<Vec<_>>().join(" "))
.unwrap_or_default();
Ok(Self {
note_words,
note_words_attr: note_words_attr
.map(|v| v.trim().to_string())
.unwrap_or_default(),
tests,
test_markers,
tests_list,
..policy
})
}
fn of(code: &str, docs: &str) -> anyhow::Result<Self> {
let words = |list: &str| list.split_whitespace().collect::<Vec<_>>().join(" ");
Ok(Self {
code: Patterns::parse("code", code)?,
docs: Patterns::parse("docs", docs)?,
note_words: NoteWords {
limit: DEFAULT_NOTE_WORDS,
warn: false,
},
note_words_attr: String::new(),
tests: TestPaths::conventions(),
test_markers: test_markers(None).map_err(anyhow::Error::msg)?,
code_list: words(code),
docs_list: words(docs),
tests_list: String::new(),
})
}
pub fn code_attr(&self) -> &str {
&self.code_list
}
pub fn docs_attr(&self) -> &str {
&self.docs_list
}
pub fn note_words_attr(&self) -> String {
match self.note_words_attr.is_empty() {
true => format!("error:{DEFAULT_NOTE_WORDS}"),
false => self.note_words_attr.clone(),
}
}
pub fn tests_attr(&self) -> String {
match self.tests.list {
Some(_) => self.tests_list.clone(),
None => TESTS_CONVENTIONS.to_string(),
}
}
}
const TESTS_CONVENTIONS: &str = "conventions";
fn tests(value: Option<&str>) -> Result<TestPaths, String> {
let Some(value) = value.filter(|v| v.trim() != TESTS_CONVENTIONS) else {
return Ok(TestPaths::conventions());
};
let list = Patterns::parse("tests", value).map_err(|e| format!("AGENTS.md: {e}"))?;
if list.is_empty() {
return Err("AGENTS.md: the `tests` list is empty. Name the test code, such as `tests=\"spec/**\"`, or write `tests=\"conventions\"` for the convention of each language.".to_string());
}
Ok(TestPaths { list: Some(list) })
}
fn test_markers(value: Option<&str>) -> Result<TestMarkers, String> {
let value = value.unwrap_or("error");
let (first, rest) = value.split_once(char::is_whitespace).unwrap_or((value, ""));
let Some(default) = Verdict::read(first) else {
return Err(format!(
"AGENTS.md: `test-markers=\"{first}\"` is neither `error`, `warn` nor `allow`. Write `test-markers=\"allow\"` where a test carries a law the tree decides nowhere else, `test-markers=\"warn\"` to warn on a marker in test code, or `test-markers=\"error\"` to fail it."
));
};
let mut rules = Vec::new();
for rule in rest.split_whitespace() {
let read = rule.rsplit_once(':').and_then(|(glob, verdict)| {
Some((
Patterns::parse("test-markers", glob).ok()?,
Verdict::read(verdict)?,
))
});
let Some((glob, verdict)) = read.filter(|(glob, _)| !glob.is_empty()) else {
return Err(format!(
"AGENTS.md: the `test-markers` rule `{rule}` is not `<glob>:<value>`, a glob of the project and a value of `error`, `warn` or `allow`, such as `tests/conformance/**:allow`."
));
};
rules.push((rule.to_string(), glob, verdict));
}
Ok(TestMarkers {
default,
rules,
attr: value.split_whitespace().collect::<Vec<_>>().join(" "),
})
}
fn note_words(value: Option<&str>) -> Result<NoteWords, String> {
let Some(value) = value else {
return Ok(NoteWords {
limit: DEFAULT_NOTE_WORDS,
warn: false,
});
};
let written = value.trim();
let (warn, count) = match written.split_once(':') {
Some(("error", count)) => (false, Some(count)),
Some(("warn", count)) => (true, Some(count)),
_ => (false, None),
};
let limit = count
.filter(|count| count.bytes().all(|b| b.is_ascii_digit()))
.and_then(|count| count.parse::<usize>().ok());
match limit {
Some(limit) if limit > 0 => Ok(NoteWords { limit, warn }),
_ => Err(format!(
"AGENTS.md: `note-words=\"{value}\"` is not a positive integer after `error:` or `warn:`. Write `note-words=\"error:{DEFAULT_NOTE_WORDS}\"` to fail a note past {DEFAULT_NOTE_WORDS} words, or `note-words=\"warn:{DEFAULT_NOTE_WORDS}\"` to warn on it."
)),
}
}
fn unknown_attrs(attrs: &[String]) -> String {
let known =
"The block reads `notes`, `default-branch`, `code`, `docs`, `tests`, `test-markers` and `note-words`";
let names: Vec<String> = attrs.iter().map(|attr| format!("`{attr}`")).collect();
match names.as_slice() {
[one] => format!("AGENTS.md: {one} is not an attribute of the block. {known}."),
[rest @ .., last] => format!(
"AGENTS.md: {} and {last} are not attributes of the block. {known}.",
rest.join(", ")
),
[] => unreachable!("an unknown attribute is named"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn omitted_attrs_use_defaults() {
let policy = ProjectPolicy::from_agents(Some("<silcrow>\n</silcrow>\n")).unwrap();
assert!(policy.code.matches(Path::new("src/a.rs")));
assert!(policy.code.matches(Path::new("a.py")));
assert!(policy.docs.is_empty());
assert_eq!((policy.code_attr(), policy.docs_attr()), ("**/*", ""));
}
#[test]
fn code_and_docs_are_lists_of_patterns() {
let policy = ProjectPolicy::from_agents(Some(
"<silcrow code=\"src/** !src/gen/**\" docs=\"website/docs/**/*.html README.md\">\n</silcrow>\n",
))
.unwrap();
assert!(policy.code.matches(Path::new("src/a.rs")));
assert!(!policy.code.matches(Path::new("src/gen/a.rs")));
assert!(!policy.code.matches(Path::new("lib/a.rs")));
assert!(policy.docs.matches(Path::new("website/docs/a/b.html")));
assert!(policy.docs.matches(Path::new("README.md")));
assert!(!policy.docs.matches(Path::new("docs/arch.md")));
assert_eq!(policy.docs_attr(), "website/docs/**/*.html README.md");
}
#[test]
fn an_empty_code_list_or_an_invalid_glob_is_a_defect() {
let err =
ProjectPolicy::from_agents(Some("<silcrow code=\"\">\n</silcrow>\n")).unwrap_err();
assert!(err.contains("`code` list is empty"), "{err}");
let err =
ProjectPolicy::from_agents(Some("<silcrow docs=\"web/[\">\n</silcrow>\n")).unwrap_err();
assert!(err.contains("is not a glob"), "{err}");
let err = ProjectPolicy::from_agents(Some("<silcrow code=\"!src/**\">\n</silcrow>\n"))
.unwrap_err();
assert!(err.contains("includes no path"), "{err}");
}
#[test]
fn note_words_is_a_positive_integer_after_a_severity() {
let policy = ProjectPolicy::from_agents(Some("<silcrow>\n</silcrow>\n")).unwrap();
let fail = |limit| NoteWords { limit, warn: false };
assert_eq!(policy.note_words, fail(DEFAULT_NOTE_WORDS));
for (value, words) in [
("error:1", fail(1)),
("error:4000", fail(4000)),
(" error:120 ", fail(120)),
("error:3000", fail(3000)),
(
"warn:3000",
NoteWords {
limit: 3000,
warn: true,
},
),
] {
let policy = ProjectPolicy::from_agents(Some(&format!(
"<silcrow note-words=\"{value}\">\n</silcrow>\n"
)))
.unwrap();
assert_eq!(policy.note_words, words, "{value}");
}
for value in [
"1",
"3000",
" 120 ",
"0",
"-3",
"+3",
"3.5",
"abc",
"",
"3000 words",
"warn:",
"warn:0",
"info:3000",
"warn:+3",
"Warn:3000",
"warn: 3000",
"error:warn:3000",
] {
let err = ProjectPolicy::from_agents(Some(&format!(
"<silcrow note-words=\"{value}\">\n</silcrow>\n"
)))
.unwrap_err();
assert!(
err.contains("is not a positive integer after `error:` or `warn:`")
&& err.contains("`note-words=\"error:3000\"`")
&& err.contains("`note-words=\"warn:3000\"`"),
"{value}: {err}"
);
}
}
#[test]
fn test_code_is_each_language_convention_unless_the_tests_list_names_it() {
let conventions = TestPaths::conventions();
for (path, test) in [
("tests/it.rs", true),
("crates/a/tests/it.rs", true),
("src/lib.rs", false),
("pkg/pay_test.go", true),
("pkg/pay.go", false),
("app/test_pay.py", true),
("app/pay_test.py", true),
("app/testing.py", false),
("web/pay.test.ts", true),
("web/pay.spec.jsx", true),
("web/__tests__/pay.js", true),
("web/test.ts", false),
("web/pay.ts", false),
("svc/src/test/java/PayTest.java", true),
("svc/src/test/kotlin/PayTest.kt", true),
("svc/src/main/java/Pay.java", false),
] {
assert_eq!(conventions.holds(Path::new(path)), test, "{path}");
}
let policy = ProjectPolicy::from_agents(Some(
"<silcrow tests=\"spec/** !spec/fixtures/**\">\n</silcrow>\n",
))
.unwrap();
assert!(policy.tests.holds(Path::new("spec/pay.rb")));
assert!(!policy.tests.holds(Path::new("spec/fixtures/a.rb")));
assert!(!policy.tests.holds(Path::new("tests/it.rs")));
assert_eq!(policy.tests_attr(), "spec/** !spec/fixtures/**");
assert_eq!(ProjectPolicy::defaults().tests_attr(), "conventions");
let written =
ProjectPolicy::from_agents(Some("<silcrow tests=\"conventions\">\n</silcrow>\n"))
.unwrap();
assert!(written.tests.holds(Path::new("tests/it.rs")));
assert!(!written.tests.holds(Path::new("conventions")));
assert_eq!(written.tests_attr(), "conventions");
let err =
ProjectPolicy::from_agents(Some("<silcrow tests=\"\">\n</silcrow>\n")).unwrap_err();
assert!(err.contains("the `tests` list is empty"), "{err}");
}
#[test]
fn test_markers_is_error_warn_or_allow_and_error_when_omitted() {
let read = |attrs: &str| {
ProjectPolicy::from_agents(Some(&format!("<silcrow{attrs}>\n</silcrow>\n")))
};
let test = Path::new("tests/unit.rs");
for (attrs, verdict) in [
("", Verdict::Error),
(" test-markers=\"error\"", Verdict::Error),
(" test-markers=\"warn\"", Verdict::Warn),
(" test-markers=\"allow\"", Verdict::Allow),
] {
assert_eq!(
read(attrs).unwrap().test_markers.at(test),
(verdict, None),
"{attrs}"
);
}
for value in ["", "yes", "true", "false", "Warn", " warn"] {
let err = read(&format!(" test-markers=\"{value}\"")).unwrap_err();
assert!(
err.contains("is neither `error`, `warn` nor `allow`"),
"{value}: {err}"
);
}
}
#[test]
fn a_test_markers_rule_sets_the_value_of_the_files_its_glob_matches_and_the_last_wins() {
let markers = test_markers(Some(
"error tests/conformance/**:allow tests/conformance/flaky/**:warn",
))
.unwrap();
assert_eq!(
markers.attr(),
"error tests/conformance/**:allow tests/conformance/flaky/**:warn"
);
for (rel, verdict, rule) in [
("tests/unit.rs", Verdict::Error, None),
(
"tests/conformance/a.rs",
Verdict::Allow,
Some("tests/conformance/**:allow"),
),
(
"tests/conformance/flaky/b.rs",
Verdict::Warn,
Some("tests/conformance/flaky/**:warn"),
),
] {
assert_eq!(markers.at(Path::new(rel)), (verdict, rule), "{rel}");
}
for value in [
"error tests/**",
"error tests/**:maybe",
"error :allow",
"error !tests/**:allow",
"error /abs/**:allow",
] {
let err = test_markers(Some(value)).unwrap_err();
assert!(err.contains("is not `<glob>:<value>`"), "{value}: {err}");
}
}
#[test]
fn an_unknown_attribute_fails_naming_the_known_ones() {
let err =
ProjectPolicy::from_agents(Some("<silcrow color=\"red\">\n</silcrow>\n")).unwrap_err();
assert!(err.contains("`color` is not an attribute"), "{err}");
}
#[test]
fn an_invalid_decisions_glob_is_a_defect() {
let err = ProjectPolicy::from_agents(Some("<silcrow notes=\"docs/[\">\n</silcrow>\n"))
.unwrap_err();
assert!(err.contains("is not a glob"), "{err}");
}
}