use anyhow::{bail, Context, Result};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
static READ_ONLY: AtomicBool = AtomicBool::new(false);
type Listing = Option<HashSet<PathBuf>>;
type Listings = Mutex<HashMap<(PathBuf, Vec<String>), Listing>>;
fn listings() -> &'static Listings {
static CACHE: OnceLock<Listings> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
type Slot = Arc<Mutex<Option<Vec<PathBuf>>>>;
type Walks = Mutex<HashMap<(&'static str, PathBuf), Slot>>;
fn walks() -> &'static Walks {
static CACHE: OnceLock<Walks> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
pub fn read_only_run() {
READ_ONLY.store(true, Ordering::Relaxed);
}
pub fn forget() {
listings().lock().expect("listing cache").clear();
walks().lock().expect("walk cache").clear();
}
fn walked(
kind: &'static str,
root: &Path,
walk: impl Fn() -> Result<Vec<PathBuf>>,
) -> Result<Vec<PathBuf>> {
if !READ_ONLY.load(Ordering::Relaxed) {
return walk();
}
let slot = Arc::clone(
walks()
.lock()
.expect("walk cache")
.entry((kind, root.to_path_buf()))
.or_default(),
);
let mut slot = slot.lock().expect("walk slot");
if let Some(found) = slot.as_ref() {
return Ok(found.clone());
}
let found = walk()?;
*slot = Some(found.clone());
Ok(found)
}
#[cfg_attr(not(test), allow(dead_code))]
pub const CODE_EXTS: &[&str] = &[
"rs",
"ts",
"mts",
"cts",
"tsx",
"js",
"jsx",
"mjs",
"cjs",
"py",
"html",
"htm",
"css",
"hcl",
"tf",
"tfvars",
"sh",
"bash",
"yaml",
"yml",
"cedar",
"dockerfile",
"containerfile",
"prisma",
"jsonc",
"md",
];
const SKIP_EXTS: &[&str] = &[
"png",
"jpg",
"jpeg",
"gif",
"webp",
"ico",
"bmp",
"tif",
"tiff",
"heic",
"avif",
"psd",
"pdf",
"zip",
"gz",
"tgz",
"bz2",
"xz",
"zst",
"7z",
"rar",
"tar",
"wasm",
"so",
"dylib",
"a",
"o",
"rlib",
"rmeta",
"bin",
"exe",
"dll",
"class",
"jar",
"pyc",
"pyo",
"woff",
"woff2",
"ttf",
"otf",
"eot",
"mp3",
"mp4",
"wav",
"flac",
"ogg",
"m4a",
"mov",
"mkv",
"avi",
"webm",
"lock",
"sock",
"npy",
"npz",
"pkl",
"parquet",
"feather",
"arrow",
"avro",
"h5",
"hdf5",
"onnx",
"pt",
"pth",
"safetensors",
"sqlite",
"sqlite3",
"db",
"xlsx",
"xls",
"docx",
"pptx",
];
const SKIP_DIRS: &[&str] = &["target", "node_modules", ".cargo"];
pub fn skips_dir(path: &Path) -> Result<bool> {
let name = path.file_name().unwrap_or_default();
if name == ".git" {
return Ok(true);
}
if !SKIP_DIRS.iter().any(|skip| name == *skip) {
return Ok(false);
}
match git_listed(path)? {
Some(listed) => Ok(listed.is_empty()),
None => Ok(!crate::workspace::root_of(path).join(".git").exists()),
}
}
pub fn is_project(dir: &Path) -> bool {
std::fs::read_to_string(dir.join("AGENTS.md")).is_ok_and(|text| crate::scheme::has_block(&text))
}
fn is_boundary(dir: &Path) -> bool {
dir.join(".git").exists() || is_project(dir)
}
pub struct Project {
pub root: PathBuf,
pub notes: Notes,
pub docs: Patterns,
}
impl Project {
pub fn at(root: &Path) -> Result<Self> {
let agents = std::fs::read_to_string(root.join("AGENTS.md")).ok();
Ok(Self {
root: root.to_path_buf(),
notes: Notes::from_agents(agents.as_deref())
.map_err(|e| anyhow::anyhow!("{}: {e}", root.join("AGENTS.md").display()))?,
docs: crate::policy::ProjectPolicy::from_agents(agents.as_deref())
.map_err(anyhow::Error::msg)?
.docs,
})
}
pub fn is_doc(&self, rel: &Path) -> bool {
!self.is_note(rel) && self.docs.matches(rel)
}
pub fn is_note(&self, rel: &Path) -> bool {
self.notes.holds(rel)
}
pub fn holds_code(&self, rel: &Path) -> bool {
let Some(ext) = rel.extension().and_then(|e| e.to_str()) else {
return crate::span_lang::lang_for_path(rel).is_some();
};
!SKIP_EXTS.contains(&ext) && !self.is_note(rel)
}
}
pub const DEFAULT_NOTES: &str = "docs/decisions/**/*.md";
#[derive(Clone, Debug, Default)]
pub struct Patterns {
patterns: Vec<(bool, String, globset::GlobMatcher)>,
}
impl PartialEq for Patterns {
fn eq(&self, other: &Self) -> bool {
let key = |p: &Self| -> Vec<(bool, String)> {
p.patterns.iter().map(|(b, s, _)| (*b, s.clone())).collect()
};
key(self) == key(other)
}
}
impl Patterns {
pub fn parse(attr: &str, list: &str) -> Result<Self> {
let mut patterns = Vec::new();
for raw in list.split_whitespace() {
let (include, body) = match raw.strip_prefix('!') {
Some(rest) => (false, rest),
None => (true, raw),
};
if body.starts_with(['/', '\\']) || Path::new(body).is_absolute() {
bail!("the `{attr}` pattern `{raw}` is an absolute path: write it relative to the project");
}
let segments: Vec<&str> = body
.split(['/', '\\'])
.filter(|s| !s.is_empty() && *s != ".")
.collect();
if segments.contains(&"..") {
bail!("the `{attr}` pattern `{raw}` leaves the project through `..`: write it inside the project");
}
if segments.is_empty() {
bail!("the `{attr}` pattern `{raw}` names no path");
}
let glob = segments.join("/");
let matcher = globset::GlobBuilder::new(&glob)
.literal_separator(true)
.backslash_escape(true)
.build()
.map_err(|e| anyhow::anyhow!("the `{attr}` pattern `{raw}` is not a glob: {e}"))?
.compile_matcher();
patterns.push((include, glob, matcher));
}
if !patterns.is_empty() && !patterns.iter().any(|(include, ..)| *include) {
bail!("the `{attr}` list `{list}` includes no path");
}
Ok(Self { patterns })
}
pub fn is_empty(&self) -> bool {
self.patterns.is_empty()
}
pub fn matches(&self, rel: &Path) -> bool {
let rel = rel.to_string_lossy().replace('\\', "/");
let rel = Path::new(&rel);
self.patterns
.iter()
.rev()
.find(|(_, _, glob)| {
rel.ancestors()
.any(|p| !p.as_os_str().is_empty() && glob.is_match(p))
})
.is_some_and(|(include, ..)| *include)
}
}
#[derive(Clone, Debug)]
pub struct Notes {
patterns: Patterns,
}
impl Notes {
pub fn from_agents(agents: Option<&str>) -> Result<Self> {
match agents.and_then(|text| crate::scheme::attr_from_agents(text, "notes")) {
Some(list) => Self::parse(&list),
None => Self::parse(DEFAULT_NOTES),
}
}
pub fn at_commit(agents: Option<&str>) -> Result<Self> {
Self::from_agents(agents.map(crate::scheme::at_commit).as_deref())
}
pub fn parse(list: &str) -> Result<Self> {
let patterns = Patterns::parse("notes", list)?;
if patterns.is_empty() {
bail!("the `notes` list `{list}` includes no path: name the decision notes, or omit the attribute for `{DEFAULT_NOTES}`");
}
Ok(Self { patterns })
}
pub fn holds(&self, rel: &Path) -> bool {
rel.extension().and_then(|e| e.to_str()) == Some("md") && self.patterns.matches(rel)
}
pub fn roots(&self) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = self
.patterns
.patterns
.iter()
.filter(|(include, ..)| *include)
.map(|(_, glob, _)| {
glob.split('/')
.take_while(|s| !s.contains(['*', '?', '[', '{', '\\']))
.collect()
})
.collect();
out.sort();
out.dedup();
let all = out.clone();
out.retain(|dir| {
!all.iter()
.any(|other| other != dir && dir.starts_with(other))
});
out
}
}
pub fn is_note_in(root: &Path, rel: &Path) -> Result<bool> {
for dir in rel.ancestors().skip(1) {
let at = root.join(dir);
if is_project(&at) {
let project = Project::at(&at)?;
return Ok(rel.strip_prefix(dir).is_ok_and(|rel| project.is_note(rel)));
}
}
Ok(false)
}
pub fn decision_files(root: &Path) -> Result<Vec<PathBuf>> {
walked("notes", root, || {
let project = Project::at(root)?;
let mut out = Vec::new();
walk(root, &mut out, &|path| {
project.is_note(path.strip_prefix(&project.root).unwrap_or(path))
})?;
Ok(out)
})
}
pub fn doc_files(root: &Path) -> Result<Vec<PathBuf>> {
let project = Project::at(root)?;
Ok(code_files(root)?
.into_iter()
.filter(|path| project.is_doc(path.strip_prefix(&project.root).unwrap_or(path)))
.collect())
}
pub fn code_files(root: &Path) -> Result<Vec<PathBuf>> {
walked("code", root, || {
read_each(code_candidates(root)?, ReadAs::Text)
})
}
pub fn skipped_files(root: &Path) -> Result<Vec<PathBuf>> {
read_each(code_candidates(root)?, ReadAs::Foreign)
}
fn read_each(paths: Vec<PathBuf>, want: ReadAs) -> Result<Vec<PathBuf>> {
let read = crate::par::map_many(paths, |path| read_as(&path).map(|read| (path, read)));
let mut out = Vec::new();
for found in read {
let (path, read) = found?;
if read == want {
out.push(path);
}
}
Ok(out)
}
fn code_candidates(root: &Path) -> Result<Vec<PathBuf>> {
walked("candidates", root, || {
let project = Project::at(root)?;
let mut out = Vec::new();
walk(root, &mut out, &|path| {
project.holds_code(path.strip_prefix(&project.root).unwrap_or(path))
})?;
Ok(out)
})
}
#[derive(Debug, PartialEq, Eq)]
enum ReadAs {
Text,
Binary,
Foreign,
}
fn read_as(path: &Path) -> Result<ReadAs> {
let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
if std::str::from_utf8(&bytes).is_ok() {
return Ok(ReadAs::Text);
}
if is_binary(&bytes) {
return Ok(ReadAs::Binary);
}
let shown = path
.ancestors()
.skip(1)
.find(|dir| dir.join(".git").exists())
.and_then(|root| path.strip_prefix(root).ok())
.unwrap_or(path)
.display();
if crate::span_lang::lang_for_path(path).is_some() {
bail!("{shown} is not UTF-8 text, and Silcrow parses its extension: save it as UTF-8");
}
if holds_marker_shape(&bytes) {
bail!(
"{shown} is not UTF-8 text, and a line of it is shaped as a marker Silcrow cannot read: save it as UTF-8, or stop tracking it"
);
}
Ok(ReadAs::Foreign)
}
fn is_binary(bytes: &[u8]) -> bool {
bytes.contains(&0)
}
fn holds_marker_shape(bytes: &[u8]) -> bool {
let text: String = bytes.iter().map(|&b| char::from(b)).collect();
text.replace("\u{c2}§", "§")
.trim_start_matches("\u{ef}\u{bb}\u{bf}")
.lines()
.any(crate::marker::shaped_as_marker)
}
pub fn files_outside_projects(root: &Path) -> Result<Vec<PathBuf>> {
let mut found = Vec::new();
if is_project(root) {
return Ok(found);
}
walk(root, &mut found, &|path| {
path.extension()
.and_then(|e| e.to_str())
.is_none_or(|ext| !SKIP_EXTS.contains(&ext))
})?;
let mut out = Vec::new();
for path in found {
if read_as(&path)? == ReadAs::Text {
out.push(path);
}
}
Ok(out)
}
pub fn walks_to(project: &Project, rel: &Path) -> bool {
let mut dir = rel.parent();
while let Some(d) = dir.filter(|d| !d.as_os_str().is_empty()) {
if is_boundary(&project.root.join(d)) {
return false;
}
dir = d.parent();
}
project.holds_code(rel)
}
pub fn in_checked_nested_project(project: &Project, rel: &Path) -> bool {
!behind_nested_repo(&project.root, rel)
&& dirs_of(rel).any(|d| is_project(&project.root.join(d)))
}
pub fn behind_nested_repo(root: &Path, rel: &Path) -> bool {
dirs_of(rel).any(|d| root.join(d).join(".git").exists())
}
fn dirs_of(rel: &Path) -> impl Iterator<Item = &Path> {
rel.ancestors()
.skip(1)
.filter(|d| !d.as_os_str().is_empty())
}
fn walk(dir: &Path, out: &mut Vec<PathBuf>, keep: &dyn Fn(&Path) -> bool) -> Result<()> {
if !dir.is_dir() {
return Ok(());
}
let listed = git_listed(dir)?;
descend(dir, out, &|path| {
keep(path) && listed.as_ref().is_none_or(|files| files.contains(path))
})?;
out.sort();
Ok(())
}
fn git_listed(dir: &Path) -> Result<Option<HashSet<PathBuf>>> {
git_ls_files(dir, &["--cached", "--others", "--exclude-standard"])
}
pub fn untracked_files(dir: &Path) -> Result<BTreeSet<PathBuf>> {
let listed = git_ls_files(dir, &["--others", "--exclude-standard"])?;
Ok(listed.into_iter().flatten().collect())
}
fn git_ls_files(dir: &Path, which: &[&str]) -> Result<Option<HashSet<PathBuf>>> {
if !READ_ONLY.load(Ordering::Relaxed) {
return list_files(dir, which);
}
let key = (
dir.to_path_buf(),
which.iter().map(|w| w.to_string()).collect(),
);
if let Some(found) = listings().lock().expect("listing cache").get(&key) {
return Ok(found.clone());
}
let found = list_files(dir, which)?;
listings()
.lock()
.expect("listing cache")
.insert(key, found.clone());
Ok(found)
}
fn list_files(dir: &Path, which: &[&str]) -> Result<Option<HashSet<PathBuf>>> {
let root = crate::workspace::root_of(dir);
let dot_git = root.join(".git");
if !dot_git.exists() {
return Ok(None);
}
let link = std::fs::read_to_string(&dot_git).unwrap_or_default();
if link
.trim()
.strip_prefix("gitdir: ")
.is_some_and(|git_dir| root.starts_with(git_dir))
{
return Ok(None);
}
let out = crate::workspace::git(&root)
.args(["ls-files", "-z"])
.args(which)
.args(["--full-name", "--"])
.arg(match dir.strip_prefix(&root) {
Ok(rel) if !rel.as_os_str().is_empty() => rel.to_path_buf(),
_ => PathBuf::from("."),
})
.output()?;
if !out.status.success() {
bail!(
"git ls-files in {}: {}",
dir.display(),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(Some(
out.stdout
.split(|&b| b == 0)
.filter(|rel| !rel.is_empty())
.map(|rel| root.join(String::from_utf8_lossy(rel).as_ref()))
.collect(),
))
}
fn descend(dir: &Path, out: &mut Vec<PathBuf>, keep: &dyn Fn(&Path) -> bool) -> Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if entry.file_name() == ".git" {
continue;
}
let kind = entry.file_type()?;
if kind.is_symlink() {
continue;
}
if kind.is_dir() {
if is_boundary(&path) || skips_dir(&path)? {
continue;
}
descend(&path, out, keep)?;
} else if kind.is_file() && keep(&path) {
out.push(path);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_decisions_pattern_outside_the_project_or_not_a_glob_is_refused() {
for list in [
"/abs/docs/**",
"../docs/**",
"docs/../../x",
"docs/[",
"!docs/archive/**",
"",
"!",
] {
assert!(Notes::parse(list).is_err(), "{list:?}");
}
let block = "<silcrow notes=\"\">\n</silcrow>\n";
assert!(Notes::from_agents(Some(block)).is_err());
}
#[test]
fn the_default_decisions_list_is_docs_decisions_and_only_when_omitted() {
let notes = Notes::from_agents(Some("<silcrow>\n</silcrow>\n")).unwrap();
assert!(notes.holds(Path::new("docs/decisions/x.md")));
assert!(notes.holds(Path::new("docs/decisions/cli/x.md")));
assert!(!notes.holds(Path::new("docs/guide.md")));
assert!(!notes.holds(Path::new("docs/decisions/x.rs")));
assert!(!notes.holds(Path::new("src/docs/decisions/x.md")));
assert_eq!(notes.roots(), [PathBuf::from("docs/decisions")]);
let explicit =
Notes::from_agents(Some("<silcrow notes=\"notes/*.md\">\n</silcrow>\n")).unwrap();
assert!(!explicit.holds(Path::new("docs/decisions/x.md")));
}
#[test]
fn a_custom_decisions_list_excludes_with_a_later_negation() {
let notes =
Notes::parse("./docs/**/*.md !docs/archive/** docs/archive/keep.md rules").unwrap();
assert!(notes.holds(Path::new("docs/x.md")));
assert!(notes.holds(Path::new("docs/a/b/x.md")));
assert!(!notes.holds(Path::new("docs/archive/old.md")));
assert!(!notes.holds(Path::new("docs/archive/deep/old.md")));
assert!(notes.holds(Path::new("docs/archive/keep.md")));
assert!(
notes.holds(Path::new("rules/pay.md")),
"a directory covers its files"
);
assert!(!notes.holds(Path::new("readme.md")));
assert_eq!(
notes.roots(),
[PathBuf::from("docs"), PathBuf::from("rules")]
);
let star = Notes::parse("*.md").unwrap();
assert!(star.holds(Path::new("x.md")));
assert!(!star.holds(Path::new("docs/x.md")), "`*` stops at a `/`");
assert_eq!(star.roots(), [PathBuf::new()]);
}
#[test]
fn documentation_is_what_the_docs_list_matches_outside_the_notes() {
let dir = tempfile::tempdir().unwrap();
for sub in ["docs/decisions", "docs/archive", "docs/ideation", "notes"] {
std::fs::create_dir_all(dir.path().join(sub)).unwrap();
}
for (rel, text) in [
("docs/guide.md", "guide"),
("docs/decisions/x.md", "law"),
("docs/archive/old.md", "old"),
("docs/ideation/idea.md", "idea"),
("notes/n.md", "note"),
] {
std::fs::write(dir.path().join(rel), text).unwrap();
}
let rels = |files: Vec<PathBuf>| -> Vec<String> {
files
.iter()
.map(|p| {
p.strip_prefix(dir.path())
.unwrap()
.to_string_lossy()
.replace('\\', "/")
})
.collect()
};
std::fs::write(dir.path().join("AGENTS.md"), "<silcrow>\n</silcrow>\n").unwrap();
assert!(doc_files(dir.path()).unwrap().is_empty());
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow docs=\"docs/**/*.md notes/**\">\n</silcrow>\n",
)
.unwrap();
assert_eq!(
rels(decision_files(dir.path()).unwrap()),
["docs/decisions/x.md"]
);
let docs = rels(doc_files(dir.path()).unwrap());
for kept in [
"docs/archive/old.md",
"docs/ideation/idea.md",
"docs/guide.md",
"notes/n.md",
] {
assert!(docs.contains(&kept.to_string()), "{kept}: {docs:?}");
}
assert!(
!docs.contains(&"docs/decisions/x.md".to_string()),
"{docs:?}"
);
let code = rels(code_files(dir.path()).unwrap());
assert!(
code.contains(&"docs/archive/old.md".to_string()),
"{code:?}"
);
assert!(
!code.contains(&"docs/decisions/x.md".to_string()),
"{code:?}"
);
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"notes/**/*.md docs/**/*.md !docs/guide.md\" docs=\"**/*.md\">\n</silcrow>\n",
)
.unwrap();
assert_eq!(
rels(decision_files(dir.path()).unwrap()),
[
"docs/archive/old.md",
"docs/decisions/x.md",
"docs/ideation/idea.md",
"notes/n.md"
]
);
assert_eq!(
rels(doc_files(dir.path()).unwrap()),
["AGENTS.md", "docs/guide.md"]
);
}
#[cfg(unix)]
#[test]
fn the_walk_skips_a_symlinked_file_and_directory() {
let outside = tempfile::tempdir().unwrap();
std::fs::write(outside.path().join("lib.py"), "def fee():\n return 1\n").unwrap();
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("app.py"), "import lib\n").unwrap();
std::os::unix::fs::symlink(outside.path().join("lib.py"), dir.path().join("lib.py"))
.unwrap();
std::os::unix::fs::symlink(outside.path(), dir.path().join("vendor")).unwrap();
let files = code_files(dir.path()).unwrap();
assert_eq!(files, vec![dir.path().join("app.py")]);
}
#[test]
fn walk_stops_at_a_nested_project_and_a_nested_repository() {
let dir = tempfile::tempdir().unwrap();
let block = "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n";
std::fs::write(dir.path().join("AGENTS.md"), block).unwrap();
std::fs::create_dir_all(dir.path().join("pkg/src")).unwrap();
std::fs::write(dir.path().join("pkg/AGENTS.md"), block).unwrap();
std::fs::write(dir.path().join("pkg/src/lib.rs"), "").unwrap();
std::fs::create_dir_all(dir.path().join("vendor/x/.git")).unwrap();
std::fs::write(dir.path().join("vendor/x/lib.rs"), "").unwrap();
std::fs::create_dir_all(dir.path().join("plain")).unwrap();
std::fs::write(dir.path().join("plain/AGENTS.md"), "# no block\n").unwrap();
std::fs::write(dir.path().join("plain/lib.rs"), "").unwrap();
let files = code_files(dir.path()).unwrap();
let rels: Vec<_> = files
.iter()
.map(|p| {
p.strip_prefix(dir.path())
.unwrap()
.to_string_lossy()
.into_owned()
})
.collect();
assert!(rels.contains(&"plain/lib.rs".to_string()), "{rels:?}");
assert!(!rels.iter().any(|r| r.starts_with("pkg/")), "{rels:?}");
assert!(!rels.iter().any(|r| r.starts_with("vendor/")), "{rels:?}");
}
#[test]
fn in_git_the_walk_reads_tracked_and_unignored_untracked_files_only() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let git = |args: &[&str]| {
let status = crate::test_git()
.args(args)
.current_dir(root)
.output()
.unwrap()
.status;
assert!(status.success(), "git {args:?}");
};
git(&["init", "-q"]);
std::fs::write(
root.join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\" docs=\"*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(root.join(".gitignore"), ".venv/\nlocal.py\nnotes.md\n").unwrap();
std::fs::create_dir_all(root.join(".venv/lib")).unwrap();
std::fs::create_dir_all(root.join("docs/decisions")).unwrap();
for (rel, text) in [
("tracked.py", "x = 1\n"),
("new.py", "x = 2\n"),
("local.py", "x = 3\n"),
(".venv/lib/util.py", "x = 4\n"),
("forced.py", "x = 5\n"),
("guide.md", "# Guide\n"),
("notes.md", "# Notes\n"),
("docs/decisions/x.md", "# X\n"),
] {
std::fs::write(root.join(rel), text).unwrap();
}
git(&["add", "tracked.py", "AGENTS.md", ".gitignore"]);
git(&["add", "-f", "forced.py"]);
std::fs::write(
root.join(".gitignore"),
".venv/\nlocal.py\nnotes.md\nforced.py\n",
)
.unwrap();
let rels = |files: Vec<PathBuf>| -> Vec<String> {
files
.iter()
.map(|p| p.strip_prefix(root).unwrap().to_string_lossy().into_owned())
.collect()
};
let code = rels(code_files(root).unwrap());
for kept in ["tracked.py", "new.py", "forced.py"] {
assert!(code.contains(&kept.to_string()), "{kept}: {code:?}");
}
for dropped in ["local.py", ".venv/lib/util.py"] {
assert!(!code.contains(&dropped.to_string()), "{dropped}: {code:?}");
}
let docs = rels(doc_files(root).unwrap());
assert!(docs.contains(&"guide.md".to_string()), "{docs:?}");
assert!(!docs.contains(&"notes.md".to_string()), "{docs:?}");
assert_eq!(rels(decision_files(root).unwrap()), ["docs/decisions/x.md"]);
}
#[test]
fn in_git_a_build_directory_name_skips_only_what_git_does_not_list() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let git = |args: &[&str]| {
let status = crate::test_git()
.args(args)
.current_dir(root)
.output()
.unwrap()
.status;
assert!(status.success(), "git {args:?}");
};
std::fs::write(
root.join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(root.join(".gitignore"), "/target/\n").unwrap();
for rel in [
"app/target/rules.py",
"web/node_modules/lib.js",
"target/debug/out.rs",
] {
std::fs::create_dir_all(root.join(rel).parent().unwrap()).unwrap();
std::fs::write(root.join(rel), "x = 1\n").unwrap();
}
let rels = || -> Vec<String> {
code_files(root)
.unwrap()
.iter()
.map(|p| p.strip_prefix(root).unwrap().to_string_lossy().into_owned())
.collect()
};
let outside = rels();
for dropped in ["app/target/rules.py", "web/node_modules/lib.js"] {
assert!(!outside.contains(&dropped.to_string()), "{outside:?}");
}
git(&["init", "-q"]);
git(&["add", "app/target/rules.py"]);
let code = rels();
for kept in ["app/target/rules.py", "web/node_modules/lib.js"] {
assert!(code.contains(&kept.to_string()), "{kept}: {code:?}");
}
assert!(!code.iter().any(|r| r.starts_with("target/")), "{code:?}");
let project = Project::at(root).unwrap();
assert!(walks_to(&project, Path::new("app/target/rules.py")));
}
#[test]
fn the_index_tree_inside_the_git_directory_reads_every_file() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let status = crate::test_git()
.args(["init", "-q"])
.current_dir(root)
.status()
.unwrap();
assert!(status.success());
let git_dir = root.join(".git").canonicalize().unwrap();
let tree = git_dir.join("silcrow-index");
std::fs::create_dir_all(&tree).unwrap();
std::fs::write(
tree.join(".git"),
format!("gitdir: {}\n", git_dir.display()),
)
.unwrap();
std::fs::write(
tree.join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(tree.join("staged.py"), "x = 1\n").unwrap();
let code = code_files(&tree).unwrap();
assert!(code.contains(&tree.join("staged.py")), "{code:?}");
}
#[test]
fn code_files_include_fallback_exts_and_skip_binaries() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n",
)
.unwrap();
std::fs::write(dir.path().join("main.go"), "package main\n").unwrap();
std::fs::write(dir.path().join("pic.png"), []).unwrap();
let files = code_files(dir.path()).unwrap();
let names: Vec<_> = files
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert!(names.contains(&"main.go".to_string()));
assert!(names.contains(&"AGENTS.md".to_string()));
assert!(!names.contains(&"pic.png".to_string()));
}
#[test]
fn a_file_that_is_not_utf8_is_skipped_only_when_it_can_carry_no_marker() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n",
)
.unwrap();
std::fs::write(root.join("data.csv"), b"caf\xe9;1\n").unwrap();
std::fs::write(
root.join("law.csv"),
b"Art. \xa7 3;# \xa7 abc\n-- \xa7 Gesetzbuch\n",
)
.unwrap();
std::fs::write(
root.join("statement.csv"),
b"\x00GITCRYPT\x00\x8f# \xa7 abcdefgh1.a\n\xe9",
)
.unwrap();
std::fs::write(root.join("model.npy"), b"\x93NUMPY\xa7\xff").unwrap();
std::fs::write(root.join("blob"), b"\xff\xfe\x00").unwrap();
std::fs::write(root.join("ok.py"), "x = 1\n").unwrap();
let names = |files: Vec<PathBuf>| -> Vec<String> {
files
.iter()
.map(|p| p.strip_prefix(root).unwrap().display().to_string())
.collect()
};
assert_eq!(names(code_files(root).unwrap()), ["AGENTS.md", "ok.py"]);
assert_eq!(names(skipped_files(root).unwrap()), ["data.csv", "law.csv"]);
for (name, bytes, why) in [
(
"bad.py",
&b"x = '\xe9'\n"[..],
"Silcrow parses its extension",
),
(
"latin1.txt",
&b"caf\xe9\n# \xa7 abcdefgh1.a\n"[..],
"shaped as a marker",
),
(
"utf8.txt",
&b"x \xff\n// \xc2\xa7 one +draft\n"[..],
"shaped as a marker",
),
] {
std::fs::write(root.join(name), bytes).unwrap();
let err = format!("{:#}", code_files(root).unwrap_err());
assert!(
err.contains(&root.join(name).display().to_string()),
"{err}"
);
assert!(err.contains(why), "{err}");
assert!(skipped_files(root).is_err());
std::fs::remove_file(root.join(name)).unwrap();
}
let ws = tempfile::tempdir().unwrap();
std::fs::create_dir(ws.path().join("app")).unwrap();
std::fs::write(
ws.path().join("app/AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(ws.path().join("data.csv"), b"caf\xe9;1\n").unwrap();
std::fs::create_dir_all(ws.path().join("finance/bank")).unwrap();
std::fs::write(
ws.path().join("finance/bank/s.csv"),
b"\x00GITCRYPT\x00\xa7",
)
.unwrap();
let outside = files_outside_projects(ws.path()).unwrap();
assert!(outside.is_empty(), "{outside:?}");
std::fs::write(ws.path().join("stray.py"), b"# \xa7 x\n\xff").unwrap();
let err = format!("{:#}", files_outside_projects(ws.path()).unwrap_err());
assert!(err.contains("stray.py"), "{err}");
}
}