use anyhow::{bail, Context, Result};
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use std::sync::LazyLock;
use crate::model::Scan;
use crate::parse;
use crate::walk;
static PROJECTPATH_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!("^{}$", crate::marker::PROJECTPATH)).expect("project path regex")
});
pub struct Workspace {
pub root: PathBuf,
pub projects: Vec<ProjectRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectRef {
pub key: String,
pub dir: PathBuf,
pub external: bool,
}
pub struct LawScans {
pub own: String,
pub scans: BTreeMap<String, Scan>,
}
const LOCAL_GIT_ENV: [&str; 15] = [
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_CONFIG",
"GIT_CONFIG_PARAMETERS",
"GIT_CONFIG_COUNT",
"GIT_OBJECT_DIRECTORY",
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_IMPLICIT_WORK_TREE",
"GIT_GRAFT_FILE",
"GIT_INDEX_FILE",
"GIT_NO_REPLACE_OBJECTS",
"GIT_REPLACE_REF_BASE",
"GIT_PREFIX",
"GIT_SHALLOW_FILE",
"GIT_COMMON_DIR",
];
static OWN_REPO: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
let cwd = std::env::current_dir().ok()?;
std::fs::canonicalize(root_of(&cwd)).ok()
});
pub fn blob_id(bytes: &[u8]) -> String {
let mut sha = sha1_smol::Sha1::new();
sha.update(format!("blob {}\0", bytes.len()).as_bytes());
sha.update(bytes);
sha.digest().to_string()
}
pub fn git(dir: &Path) -> std::process::Command {
let mut cmd = std::process::Command::new("git");
cmd.current_dir(dir);
let repo = std::fs::canonicalize(root_of(dir)).ok();
if repo.is_none() || repo != *OWN_REPO {
for var in LOCAL_GIT_ENV {
cmd.env_remove(var);
}
}
cmd
}
pub fn root_of(start: &Path) -> PathBuf {
start
.ancestors()
.find(|dir| dir.join(".git").exists())
.unwrap_or(start)
.to_path_buf()
}
impl Workspace {
pub fn discover(start: &Path) -> Result<Self> {
Self::at(root_of(start))
}
pub fn at(root: PathBuf) -> Result<Self> {
let mut projects = Vec::new();
collect_projects(&root, &root, false, &mut projects)?;
projects.sort_by(|a, b| a.key.cmp(&b.key));
Ok(Self { root, projects })
}
pub fn get(&self, key: &str) -> Option<&ProjectRef> {
self.projects.iter().find(|project| project.key == key)
}
pub fn enclosing(&self, dir: &Path) -> Option<&ProjectRef> {
dir.ancestors()
.take_while(|d| d.starts_with(&self.root))
.find_map(|d| self.projects.iter().find(|project| project.dir == d))
}
pub fn require(&self, dir: &Path) -> Result<&ProjectRef> {
let Some(project) = self.enclosing(dir) else {
bail!(
"{} is in no Silcrow project. Projects: {}. Run from a project, or pass `--all` where the verb takes it.",
dir.display(),
self.list()
);
};
if project.external {
bail!(
"project `{}` is behind a nested `.git`: it is read for resolution, never checked or written",
project.key
);
}
Ok(project)
}
pub fn local(&self) -> Vec<&ProjectRef> {
self.projects
.iter()
.filter(|project| !project.external)
.collect()
}
pub fn base_ref(&self, on_integration: &str) -> Result<Option<String>> {
let dirs: Vec<&Path> = self.local().iter().map(|p| p.dir.as_path()).collect();
crate::published::base_ref(&self.root, &dirs, on_integration)
}
pub fn frozen(&self, dir: &Path, ids: &BTreeSet<String>) -> Result<BTreeSet<String>> {
let dirs: Vec<&Path> = self.local().iter().map(|p| p.dir.as_path()).collect();
crate::published::frozen(&self.root, &dirs, dir, ids)
}
pub fn held_letters(&self, dir: &Path) -> Result<BTreeMap<String, BTreeSet<String>>> {
let dirs: Vec<&Path> = self.local().iter().map(|p| p.dir.as_path()).collect();
let tip = crate::published::tip(&self.root, &dirs)?;
crate::published::held_letters(dir, &tip)
}
pub fn list(&self) -> String {
if self.projects.is_empty() {
return "none".to_string();
}
self.projects
.iter()
.map(|project| format!("`{}`", project.key))
.collect::<Vec<_>>()
.join(", ")
}
pub fn law_scans(&self, own: &str) -> Result<LawScans> {
self.law_scans_of(own, |_| true)
}
pub fn law_scans_of(&self, own: &str, read: impl Fn(&str) -> bool) -> Result<LawScans> {
let mut scans = BTreeMap::new();
for project in self.projects.iter().filter(|project| project.key != own) {
let scan = match read(&project.key) {
true => scan_laws(&project.dir)?,
false => Scan::default(),
};
scans.insert(project.key.clone(), scan);
}
Ok(LawScans {
own: own.to_string(),
scans,
})
}
}
pub fn in_workspace(key: &str, rel: &Path) -> PathBuf {
if key == "." {
rel.to_path_buf()
} else {
Path::new(key).join(rel)
}
}
fn scan_laws(dir: &Path) -> Result<Scan> {
let mut notes = Vec::new();
for path in walk::decision_files(dir)? {
let text =
std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
notes.push((PathBuf::from(parse::display_path(&path, dir)), text));
}
Ok(parse::scan_notes(¬es))
}
fn collect_projects(
root: &Path,
dir: &Path,
external: bool,
out: &mut Vec<ProjectRef>,
) -> Result<()> {
if walk::is_project(dir) {
out.push(ProjectRef {
key: project_key(root, dir)?,
dir: dir.to_path_buf(),
external,
});
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if !entry.file_type()?.is_dir() {
continue;
}
let path = entry.path();
if walk::skips_dir(&path)? {
continue;
}
let nested_repo = path.join(".git").exists();
if nested_repo && !PROJECTPATH_RE.is_match(&relative_key(root, &path)?) {
continue;
}
collect_projects(root, &path, external || nested_repo, out)?;
}
Ok(())
}
fn project_key(root: &Path, dir: &Path) -> Result<String> {
let key = relative_key(root, dir)?;
if !PROJECTPATH_RE.is_match(&key) {
bail!(
"project `{key}` has a path a qualified reference cannot name: segments are `[A-Za-z0-9_-][A-Za-z0-9._-]*`"
);
}
Ok(key)
}
fn relative_key(root: &Path, dir: &Path) -> Result<String> {
let rel = dir.strip_prefix(root).unwrap_or(dir);
let mut parts = Vec::new();
for comp in rel.components() {
match comp {
Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
_ => bail!("project {} is not below the workspace root", dir.display()),
}
}
Ok(if parts.is_empty() {
".".to_string()
} else {
parts.join("/")
})
}
#[cfg(test)]
mod tests {
use super::*;
const BLOCK: &str = "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n";
#[test]
fn projects_are_keyed_by_path_and_external_behind_a_nested_repository() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::write(root.join("AGENTS.md"), BLOCK).unwrap();
std::fs::create_dir_all(root.join("packages/billing/async")).unwrap();
std::fs::write(root.join("packages/billing/AGENTS.md"), BLOCK).unwrap();
std::fs::write(root.join("packages/billing/async/AGENTS.md"), BLOCK).unwrap();
std::fs::create_dir_all(root.join("vendor/lib/.git")).unwrap();
std::fs::write(root.join("vendor/lib/AGENTS.md"), BLOCK).unwrap();
let ws = Workspace::discover(&root.join("packages/billing/async")).unwrap();
assert_eq!(ws.root, root);
let keys: Vec<_> = ws
.projects
.iter()
.map(|h| (h.key.as_str(), h.external))
.collect();
assert_eq!(
keys,
vec![
(".", false),
("packages/billing", false),
("packages/billing/async", false),
("vendor/lib", true),
]
);
let near = ws.enclosing(&root.join("packages/billing/src")).unwrap();
assert_eq!(near.key, "packages/billing");
assert!(ws.require(&root.join("vendor/lib")).is_err());
}
#[test]
fn a_dir_in_no_project_lists_the_projects() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::write(root.join("a/AGENTS.md"), BLOCK).unwrap();
let ws = Workspace::discover(root).unwrap();
let err = ws.require(root).unwrap_err().to_string();
assert!(err.contains("`a`"), "{err}");
}
}