use anyhow::{bail, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use crate::hash;
use crate::model::Law;
use crate::parse;
use crate::walk;
pub struct Published {
laws: Vec<Law>,
}
pub fn branch(projects: &[&Path]) -> Result<String> {
let mut named: Vec<(PathBuf, String)> = Vec::new();
for dir in projects {
let path = dir.join("AGENTS.md");
let text = std::fs::read_to_string(&path).unwrap_or_default();
let Some(branch) = crate::scheme::attr_from_agents(&text, "default-branch") else {
bail!(
"{}: the Silcrow block names no `default-branch`. Run `silcrow install --write` to write it.",
path.display()
);
};
named.push((path, branch));
}
let Some((_, first)) = named.first() else {
bail!("no project names a `default-branch`. Run `silcrow install --write`.");
};
if named.iter().any(|(_, branch)| branch != first) {
let list: Vec<String> = named
.iter()
.map(|(path, branch)| format!("{} names `{branch}`", path.display()))
.collect();
bail!(
"the projects of one workspace name different default branches: {}",
list.join(", ")
);
}
Ok(first.clone())
}
pub fn default_branch(root: &Path) -> Result<String> {
if let Ok(remote) = git(
root,
&[
"symbolic-ref",
"--quiet",
"--short",
"refs/remotes/origin/HEAD",
],
) {
if let Some(branch) = remote.strip_prefix("origin/") {
return Ok(branch.to_string());
}
}
match git(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]) {
Ok(branch) => Ok(branch),
Err(_) => bail!(
"cannot name the default branch: `origin/HEAD` is not set and `HEAD` is detached. Run `git remote set-head origin --auto` or check out the default branch, then `silcrow install --write`."
),
}
}
pub fn base_ref(root: &Path, projects: &[&Path], on_integration: &str) -> Result<Option<String>> {
if git(root, &["rev-parse", "--is-inside-work-tree"]).is_err() {
bail!("silcrow compares against git history: not a git repository");
}
if git(root, &["rev-parse", "--verify", "HEAD"]).is_err() {
return Ok(None);
}
let published = held_branch(root, projects)?.name;
if git(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok() == Some(published.clone()) {
return git(root, &["rev-parse", on_integration]).map(Some);
}
let target = branch_ref(root, &published)?;
git(root, &["merge-base", &target, "HEAD"]).map(Some)
}
#[derive(Debug, PartialEq, Eq)]
pub enum MergeTarget {
Branch { var: &'static str, name: String },
Commit { var: &'static str, sha: String },
}
const TARGET_BRANCHES: [&str; 6] = [
"CI_MERGE_REQUEST_TARGET_BRANCH_NAME",
"BITBUCKET_PR_DESTINATION_BRANCH",
"SYSTEM_PULLREQUEST_TARGETBRANCH",
"CHANGE_TARGET",
"BUILDKITE_PULL_REQUEST_BASE_BRANCH",
"CI_COMMIT_TARGET_BRANCH",
];
pub fn merge_target(env: impl Fn(&str) -> Option<String>) -> Option<MergeTarget> {
let read = |var: &str| {
env(var)
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
};
let branch = |var: &'static str, name: String| MergeTarget::Branch {
var,
name: name
.strip_prefix("refs/heads/")
.map(str::to_string)
.unwrap_or(name),
};
if let Some(name) = read("GITHUB_BASE_REF") {
return Some(branch("GITHUB_BASE_REF", name));
}
let var = "CI_MERGE_REQUEST_DIFF_BASE_SHA";
if let Some(sha) = read(var) {
return Some(MergeTarget::Commit { var, sha });
}
TARGET_BRANCHES
.into_iter()
.find_map(|var| read(var).map(|name| branch(var, name)))
}
pub fn merge_point(root: &Path, target: &MergeTarget) -> Result<String> {
match target {
MergeTarget::Commit { var, sha } => {
git(root, &["rev-parse", "--verify", "--quiet", &format!("{sha}^{{commit}}")])
.map_err(|_| {
anyhow::anyhow!(
"`{var}` names the merge-base {sha}, and this clone does not hold it. Fetch it, `git fetch origin {sha}`, then run `silcrow check` again."
)
})
}
MergeTarget::Branch { var, name } => {
let remote = format!("origin/{name}");
let held = format!("refs/remotes/{remote}");
if git(root, &["rev-parse", "--verify", "--quiet", &held]).is_err() {
bail!(
"`{var}` names the merge target `{name}`, and this clone does not hold `{remote}`. Fetch it, `git fetch origin {name}`, or the whole history, `fetch-depth: 0` for actions/checkout, then run `silcrow check` again."
);
}
git(root, &["merge-base", &remote, "HEAD"]).map_err(|_| {
anyhow::anyhow!(
"`{remote}` and `HEAD` share no commit this clone holds, since it is shallow. Fetch the history, `git fetch --unshallow origin {name}`, or `fetch-depth: 0` for actions/checkout, then run `silcrow check` again."
)
})
}
}
}
pub struct Held {
pub name: String,
pub rewritten: Option<(String, String)>,
}
pub fn held_branch(root: &Path, projects: &[&Path]) -> Result<Held> {
let named = branch(projects)?;
require_history(root)?;
let head = git(root, &["rev-parse", "--verify", "-q", "HEAD"]).ok();
let mut held: Option<(String, String)> = None;
for dir in projects {
let Some((before, at)) = unlanded(dir, head.as_deref())? else {
continue;
};
if let Some((other, _)) = held.as_ref().filter(|(other, _)| *other != before) {
bail!(
"the projects of one workspace were published to different branches before `default-branch` changed: `{other}` and `{before}`"
);
}
held = Some((before, at));
}
Ok(match held {
Some((name, at)) => Held {
name,
rewritten: Some((named, at)),
},
None => Held {
name: named,
rewritten: None,
},
})
}
fn unlanded(dir: &Path, head: Option<&str>) -> Result<Option<(String, String)>> {
let now = std::fs::read_to_string(dir.join("AGENTS.md"))
.ok()
.and_then(|text| crate::scheme::attr_from_agents(&text, "default-branch"));
let kept = head.and_then(|head| {
crate::cache::memo(dir, head, &"default-branch history", || {
branch_history(dir).ok()
})
});
let (at_head, commits) = match kept {
Some(history) => history,
None => branch_history(dir)?,
};
let mut changes = vec![(None, at_head, now)];
for (commit, before, after) in commits {
changes.push((Some(commit), before, after));
}
let mut found = None;
for (commit, before, after) in changes {
let Some(before) = before.filter(|before| Some(before) != after.as_ref()) else {
continue;
};
let landed = match (commit.as_deref(), find_branch_ref(dir, &before)?) {
(Some(commit), Some(target)) => {
git(dir, &["merge-base", "--is-ancestor", commit, &target]).is_ok()
}
_ => false,
};
if !landed {
let at = commit.map_or("the worktree".to_string(), |c| short(&c).to_string());
found = Some((before, at));
}
}
Ok(found)
}
fn branch_history(dir: &Path) -> Result<BranchHistory> {
let mut batch = Batch::start(dir)?;
let mut value_at = |rev: &str| -> Result<Option<String>> {
Ok(match batch.read(&format!("{rev}:./AGENTS.md"))? {
Some(object) if object.kind == "blob" => crate::scheme::attr_from_agents(
&crate::scheme::at_commit(&String::from_utf8_lossy(&object.body)),
"default-branch",
),
_ => None,
})
};
let at_head = value_at("HEAD")?;
let log = git(
dir,
&[
"log",
"--first-parent",
"--format=%H",
"HEAD",
"--",
"AGENTS.md",
],
)?;
let mut commits = Vec::new();
for commit in log.lines().filter(|l| !l.is_empty()) {
let after = value_at(commit)?;
let before = value_at(&format!("{commit}^1"))?;
commits.push((commit.to_string(), before, after));
}
batch.finish()?;
Ok((at_head, commits))
}
type BranchHistory = (
Option<String>,
Vec<(String, Option<String>, Option<String>)>,
);
pub fn require_history(root: &Path) -> Result<()> {
if git(root, &["rev-parse", "--is-shallow-repository"])? == "true" {
bail!(
"this clone is shallow: silcrow reads the history of the repository, for the default branch, the ids removed laws carried, the letters it wrote and the age and counts of each law, and a shallow clone cuts it. Fetch the whole history: `git fetch --unshallow`, or `fetch-depth: 0` for actions/checkout."
);
}
Ok(())
}
pub fn written_last(root: &Path, paths: &[PathBuf], pin: &str) -> Result<bool> {
let mut args = vec![
"--literal-pathspecs".to_string(),
"log".into(),
"-1".into(),
"--format=%H %P".into(),
"HEAD".into(),
"--".into(),
];
args.extend(paths.iter().map(|p| p.to_string_lossy().into_owned()));
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let last = git(root, &args)?;
let mut commits = last.split_whitespace();
let Some(commit) = commits.next() else {
return Ok(false);
};
if commits.count() > 1 {
return Ok(false);
}
let patch = git(
root,
&[
"show",
"--format=",
"--no-color",
"--no-ext-diff",
"--find-renames",
"-U0",
commit,
],
)?;
Ok(patch
.lines()
.any(|line| line.starts_with('+') && !line.starts_with("+++") && line.contains(pin)))
}
pub fn unshared(root: &Path, projects: &[&Path]) -> Result<Option<String>> {
let Ok(current) = git(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]) else {
return Ok(None);
};
let default = branch(projects)?;
if current == default {
return Ok(None);
}
let remotes = git(
root,
&["for-each-ref", "--format=%(refname)", "refs/remotes"],
)?;
let tracked = remotes.lines().any(|name| {
name.strip_prefix("refs/remotes/")
.and_then(|rest| rest.split_once('/'))
.is_some_and(|(_, branch)| branch == current)
});
Ok((!tracked).then_some(current))
}
fn branch_ref(root: &Path, published: &str) -> Result<String> {
match find_branch_ref(root, published)? {
Some(target) => Ok(target),
None => bail!(
"the default branch `{published}` is neither a local branch nor `origin/{published}`: fetch it, or name the published tree yourself with `silcrow check --base <ref>` or `silcrow diff <ref>`"
),
}
}
fn find_branch_ref(root: &Path, name: &str) -> Result<Option<String>> {
let local = format!("refs/heads/{name}");
let remote = format!("refs/remotes/origin/{name}");
let exists = |r: &str| git(root, &["rev-parse", "--verify", "--quiet", r]).is_ok();
let holds = |a: &str, b: &str| git(root, &["merge-base", "--is-ancestor", b, a]).is_ok();
Ok(match (exists(&local), exists(&remote)) {
(true, true) if holds(&local, &remote) => Some(local),
(true, true) if holds(&remote, &local) => Some(remote),
(true, true) => bail!(
"the default branch `{name}` and `origin/{name}` have diverged, and neither holds the other: pull or push `{name}` so one holds the other, or name the published tree yourself with `silcrow check --base <ref>` or `silcrow diff <ref>`"
),
(true, false) => Some(local),
(false, true) => Some(remote),
(false, false) => None,
})
}
pub fn frozen(
root: &Path,
projects: &[&Path],
dir: &Path,
ids: &BTreeSet<String>,
) -> Result<BTreeSet<String>> {
if ids.is_empty() {
return Ok(BTreeSet::new());
}
if git(root, &["rev-parse", "--is-inside-work-tree"]).is_err()
|| git(root, &["rev-parse", "--verify", "HEAD"]).is_err()
{
return Ok(BTreeSet::new());
}
let head = declared_at(dir, "HEAD")?;
let ids: BTreeSet<String> = ids.difference(&head).cloned().collect();
if ids.is_empty() {
return Ok(ids);
}
let tip = branch_ref(root, &held_branch(root, projects)?.name)?;
removed_at(dir, &tip, &ids)
}
pub fn removed_at(dir: &Path, tip: &str, ids: &BTreeSet<String>) -> Result<BTreeSet<String>> {
require_history(dir)?;
let declared = declared_at(dir, tip)?;
let ids: Vec<&String> = ids.iter().filter(|id| !declared.contains(*id)).collect();
if ids.is_empty() {
return Ok(BTreeSet::new());
}
let lists = note_lists(dir, tip)?;
let dirs = note_pathspecs(&lists);
let mut out = BTreeSet::new();
for id in ids {
let pickaxe = format!("-S{id}");
let mut args = vec![
"log",
"--first-parent",
"--diff-merges=first-parent",
&pickaxe,
"--name-only",
"--format=",
tip,
"--",
];
args.extend(dirs.iter().map(String::as_str));
if git(dir, &args)?
.lines()
.any(|rel| held_by(&lists, Path::new(rel.trim())))
{
out.insert(id.clone());
}
}
Ok(out)
}
fn note_pathspecs(lists: &[(PathBuf, walk::Notes)]) -> BTreeSet<String> {
lists
.iter()
.flat_map(|(project, notes)| notes.roots().into_iter().map(|root| project.join(root)))
.map(|path| match path.to_string_lossy() {
path if path.is_empty() => ":(top)".to_string(),
path => format!(":(top){path}"),
})
.collect()
}
fn held_by(lists: &[(PathBuf, walk::Notes)], rel: &Path) -> bool {
lists
.iter()
.any(|(project, notes)| rel.strip_prefix(project).is_ok_and(|rel| notes.holds(rel)))
}
fn declared_at(dir: &Path, rev: &str) -> Result<BTreeSet<String>> {
Ok(at(dir, rev)?
.laws
.iter()
.flat_map(|law| std::iter::once(&law.id).chain(&law.aliases))
.cloned()
.collect())
}
fn note_lists(dir: &Path, tip: &str) -> Result<Vec<(PathBuf, walk::Notes)>> {
let prefix = git(dir, &["rev-parse", "--show-prefix"])?;
let mut versions = vec![(tip.to_string(), format!("{prefix}AGENTS.md"))];
for rev in [tip, "HEAD"] {
if git(
dir,
&[
"rev-parse",
"--verify",
"--quiet",
&format!("{rev}^{{commit}}"),
],
)
.is_err()
{
continue;
}
let log = git(
dir,
&[
"log",
"--first-parent",
"--follow",
"--name-only",
"--format=%x00%H",
rev,
"--",
"AGENTS.md",
],
)?;
for entry in log.split('\0') {
let mut lines = entry.lines().map(str::trim).filter(|l| !l.is_empty());
if let (Some(commit), Some(path)) = (lines.next(), lines.next()) {
versions.push((commit.to_string(), path.to_string()));
}
}
}
let mut batch = Batch::start(dir)?;
let mut out = Vec::new();
for (rev, path) in versions {
let agents = match batch.read(&format!("{rev}:{path}"))? {
Some(object) if object.kind == "blob" => Some(String::from_utf8(object.body)?),
_ => None,
};
let Ok(notes) = walk::Notes::at_commit(agents.as_deref()) else {
continue;
};
let project = Path::new(&path)
.parent()
.unwrap_or(Path::new(""))
.to_path_buf();
out.push((project, notes));
}
batch.finish()?;
Ok(out)
}
pub fn held_letters(dir: &Path, tip: &str) -> Result<BTreeMap<String, BTreeSet<String>>> {
require_history(dir)?;
let lists = note_lists(dir, tip)?;
let dirs = note_pathspecs(&lists);
let mut args = vec![
"log",
"--first-parent",
"--diff-merges=first-parent",
"--name-only",
"--format=%x00%H",
tip,
"--",
];
args.extend(dirs.iter().map(String::as_str));
let log = git(dir, &args)?;
let mut batch = Batch::start(dir)?;
let mut read = BTreeSet::new();
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for entry in log.split('\0').filter(|e| !e.trim().is_empty()) {
let mut lines = entry.lines().map(str::trim).filter(|l| !l.is_empty());
let Some(commit) = lines.next() else {
continue;
};
for rel in lines {
let path = Path::new(rel);
if !held_by(&lists, path) {
continue;
}
let Some(object) = batch.read(&format!("{commit}:{rel}"))? else {
continue;
};
if object.kind != "blob" || !read.insert(object.id) {
continue;
}
let text = String::from_utf8(object.body)?;
for law in parse::scan_text(path, &text).laws {
let letters: BTreeSet<String> = law
.clauses
.iter()
.filter_map(|c| c.letter.clone())
.collect();
for id in std::iter::once(&law.id).chain(&law.aliases) {
out.entry(id.clone())
.or_default()
.extend(letters.iter().cloned());
}
}
}
}
batch.finish()?;
Ok(out)
}
pub fn tip(root: &Path, projects: &[&Path]) -> Result<String> {
branch_ref(root, &held_branch(root, projects)?.name)
}
pub fn at(root: &Path, base: &str) -> Result<Published> {
let notes = notes_at(root, base)?;
Ok(Published {
laws: parse::scan_notes(¬es).laws,
})
}
pub fn notes_at(root: &Path, base: &str) -> Result<Vec<(PathBuf, String)>> {
let mut git = Batch::start(root)?;
if git.read(&format!("{base}^{{tree}}"))?.is_none() {
bail!("`{base}` names no tree: name a commit, a branch or a tag");
}
let agents = match git.read(&format!("{base}:./AGENTS.md"))? {
Some(object) if object.kind == "blob" => Some(String::from_utf8(object.body)?),
Some(object) => bail!("{base}:AGENTS.md is not a blob: {}", object.kind),
None => None,
};
let mut notes = Vec::new();
let list = walk::Notes::at_commit(agents.as_deref())
.map_err(|e| anyhow::anyhow!("{base}:AGENTS.md: {e}"))?;
for dir in list.roots() {
let spec = format!("{base}:./{}", dir.to_string_lossy());
if let Some(object) = git.read(&spec)? {
collect_notes(&mut git, object, dir, &list, &mut notes)?;
}
}
git.finish()?;
Ok(notes)
}
pub fn files_at(root: &Path, rev: &str) -> Result<BTreeSet<PathBuf>> {
let listed = git(
root,
&["ls-tree", "-r", "-z", "--name-only", rev, "--", "."],
)?;
Ok(listed
.split('\0')
.filter(|p| !p.is_empty())
.map(PathBuf::from)
.collect())
}
pub fn projects_at(root: &Path, rev: &str) -> Result<Vec<PathBuf>> {
let listed = git(
root,
&["ls-tree", "-r", "-z", "--name-only", rev, "--", "."],
)?;
let mut git = Batch::start(root)?;
let mut out = Vec::new();
for path in listed.split('\0').filter(|p| !p.is_empty()).map(Path::new) {
let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) else {
continue;
};
if path.file_name().is_none_or(|name| name != "AGENTS.md") {
continue;
}
let Some(object) = git.read(&format!("{rev}:./{}", path.to_string_lossy()))? else {
bail!(
"git ls-tree listed {} at {rev}, cat-file finds none",
path.display()
);
};
if object.kind == "blob" && crate::scheme::has_block(&String::from_utf8_lossy(&object.body))
{
out.push(dir.to_path_buf());
}
}
git.finish()?;
Ok(out)
}
pub fn write_tree(root: &Path, rev: &str, dest: &Path) -> Result<()> {
let mut git = Batch::start(root)?;
let Some(tree) = git.read(&format!("{rev}^{{tree}}"))? else {
bail!("`{rev}` names no tree");
};
write_object(&mut git, tree, dest)?;
git.finish()
}
fn write_object(git: &mut Batch, tree: Object, dest: &Path) -> Result<()> {
std::fs::create_dir_all(dest)?;
let id_len = tree.id.len() / 2;
let mut rest = tree.body.as_slice();
while !rest.is_empty() {
let (Some(sp), Some(nul)) = (
rest.iter().position(|&b| b == b' '),
rest.iter().position(|&b| b == 0),
) else {
bail!("git cat-file --batch: malformed tree {}", tree.id);
};
let Some(raw) = rest.get(nul + 1..nul + 1 + id_len) else {
bail!("git cat-file --batch: truncated tree {}", tree.id);
};
let mode = std::str::from_utf8(&rest[..sp])?.to_string();
let name = std::str::from_utf8(&rest[sp + 1..nul])?.to_string();
let id: String = raw.iter().map(|b| format!("{b:02x}")).collect();
rest = &rest[nul + 1 + id_len..];
if mode == "160000" {
continue;
}
let Some(object) = git.read(&id)? else {
bail!("git cat-file --batch: {id} is missing");
};
let path = dest.join(&name);
match (mode.as_str(), object.kind.as_str()) {
(_, "tree") => write_object(git, object, &path)?,
#[cfg(unix)]
("120000", "blob") => {
std::os::unix::fs::symlink(std::str::from_utf8(&object.body)?, &path)?
}
(_, "blob") if name == "AGENTS.md" => match std::str::from_utf8(&object.body) {
Ok(text) => std::fs::write(&path, crate::scheme::at_commit(text).as_bytes())?,
Err(_) => std::fs::write(&path, &object.body)?,
},
(_, "blob") => std::fs::write(&path, &object.body)?,
(_, kind) => bail!("git cat-file --batch: {} is a {kind}", path.display()),
}
}
Ok(())
}
fn collect_notes(
git: &mut Batch,
object: Object,
path: PathBuf,
list: &walk::Notes,
notes: &mut Vec<(PathBuf, String)>,
) -> Result<()> {
if object.kind != "tree" {
let name = path.to_string_lossy();
if !list.holds(&path) {
return Ok(());
}
if object.kind != "blob" {
bail!(
"git cat-file --batch: {name} is not a blob: {}",
object.kind
);
}
notes.push((path, String::from_utf8(object.body)?.trim().to_string()));
return Ok(());
}
let id_len = object.id.len() / 2;
let mut rest = object.body.as_slice();
let mut entries = Vec::new();
while !rest.is_empty() {
let (Some(sp), Some(nul)) = (
rest.iter().position(|&b| b == b' '),
rest.iter().position(|&b| b == 0),
) else {
bail!("git cat-file --batch: malformed tree {}", object.id);
};
let Some(raw) = rest.get(nul + 1..nul + 1 + id_len) else {
bail!("git cat-file --batch: truncated tree {}", object.id);
};
let mode = std::str::from_utf8(&rest[..sp])?.to_string();
let name = std::str::from_utf8(&rest[sp + 1..nul])?.to_string();
let id: String = raw.iter().map(|b| format!("{b:02x}")).collect();
rest = &rest[nul + 1 + id_len..];
entries.push((mode, name, id));
}
if !path.as_os_str().is_empty() {
for (mode, name, id) in &entries {
if name != "AGENTS.md" || mode == "160000" {
continue;
}
if let Some(agents) = git.read(id)? {
if agents.kind == "blob"
&& crate::scheme::has_block(&String::from_utf8_lossy(&agents.body))
{
return Ok(());
}
}
}
}
for (mode, name, id) in entries {
let child = path.join(&name);
if mode == "160000" {
if list.holds(&child) {
bail!(
"git cat-file --batch: {} is not a blob: commit",
child.display()
);
}
continue;
}
let Some(object) = git.read(&id)? else {
bail!("git cat-file --batch: {id} is missing");
};
collect_notes(git, object, child, list, notes)?;
}
Ok(())
}
pub fn pinned_at(
root: &Path,
base: &str,
) -> Result<BTreeMap<crate::marker::MarkerAddr, BTreeMap<String, Vec<PathBuf>>>> {
let out = crate::workspace::git(root)
.args([
"-c",
"grep.fullName=false",
"grep",
"-I",
"-l",
"-z",
"-F",
"--no-color",
"§",
base,
"--",
".",
])
.output()?;
match out.status.code() {
Some(0) => {}
Some(1) => return Ok(BTreeMap::new()),
_ => bail!(
"git grep at {base} failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
),
}
let project = walk::Project::at(root)?;
let nested = projects_at(root, base)?;
let prefix = format!("{base}:");
let mut pins: BTreeMap<crate::marker::MarkerAddr, BTreeMap<String, Vec<PathBuf>>> =
BTreeMap::new();
let mut git = Batch::start(root)?;
for path in String::from_utf8(out.stdout)?.split_terminator('\0') {
let Some(rel) = path.strip_prefix(&prefix) else {
bail!("git grep at {base}: {path} is not under {base}");
};
let rel = Path::new(rel);
if nested.iter().any(|dir| rel.starts_with(dir))
|| walk::in_checked_nested_project(&project, rel)
|| !project.holds_code(rel)
{
continue;
}
let Some(object) = git.read(&format!("{base}:./{}", rel.to_string_lossy()))? else {
bail!("git cat-file at {base}: {} is missing", rel.display());
};
let text = String::from_utf8_lossy(&object.body);
for row in crate::span::marker_rows(rel, &text, None) {
for pin in row.markers {
if let Some((addr, digest)) = pin.split_digest() {
pins.entry(addr)
.or_default()
.entry(digest)
.or_default()
.push(rel.to_path_buf());
}
}
}
}
git.finish()?;
Ok(pins)
}
struct Object {
id: String,
kind: String,
body: Vec<u8>,
}
struct Batch {
child: std::process::Child,
stdin: std::process::ChildStdin,
stdout: std::io::BufReader<std::process::ChildStdout>,
}
impl Batch {
fn start(root: &Path) -> Result<Self> {
let mut child = crate::workspace::git(root)
.args(["cat-file", "--batch"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdin = child.stdin.take().expect("piped stdin");
let stdout = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
Ok(Self {
child,
stdin,
stdout,
})
}
fn read(&mut self, spec: &str) -> Result<Option<Object>> {
use std::io::{BufRead, Read};
if spec.contains('\n') {
bail!("git cat-file --batch: object name spans lines: {spec:?}");
}
let sent = writeln!(self.stdin, "{spec}").and_then(|()| self.stdin.flush());
let mut header = String::new();
if sent.is_ok() {
self.stdout.read_line(&mut header)?;
}
let header = header.trim_end_matches('\n');
if header.is_empty() {
let mut err = String::new();
if let Some(stderr) = self.child.stderr.as_mut() {
stderr.read_to_string(&mut err)?;
}
bail!("git cat-file --batch failed: {}", err.trim());
}
if header == format!("{spec} missing") {
return Ok(None);
}
let (id, kind, size) = match header.split(' ').collect::<Vec<_>>()[..] {
[id, kind, size] => (id, kind, size.parse::<usize>()?),
_ => bail!("git cat-file --batch: {spec}: {header}"),
};
let mut body = vec![0; size + 1];
self.stdout.read_exact(&mut body)?;
if body.pop() != Some(b'\n') {
bail!("git cat-file --batch: {spec} is not terminated");
}
Ok(Some(Object {
id: id.to_string(),
kind: kind.to_string(),
body,
}))
}
fn finish(self) -> Result<()> {
drop(self.stdin);
let out = self.child.wait_with_output()?;
if !out.status.success() {
bail!(
"git cat-file --batch failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(())
}
}
impl Published {
pub fn laws(&self) -> &[Law] {
&self.laws
}
pub fn keys(&self) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for law in &self.laws {
out.insert(law.id.clone());
for al in &law.clauses {
if let Some(letter) = &al.letter {
out.insert(format!("{}.{letter}", law.id));
}
}
}
out
}
pub fn letters_of(&self, law: &Law) -> Option<BTreeSet<String>> {
Some(
self.law_of(law)?
.clauses
.iter()
.filter_map(|al| al.letter.clone())
.collect(),
)
}
pub fn law_of(&self, law: &Law) -> Option<&Law> {
let published = || self.laws.iter().filter(|b| !hash::is_provisional_id(&b.id));
published()
.find(|b| b.id == law.id)
.or_else(|| published().find(|b| law.aliases.contains(&b.id)))
}
}
pub fn short(rev: &str) -> &str {
let full = matches!(rev.len(), 40 | 64) && rev.bytes().all(|b| b.is_ascii_hexdigit());
if full {
&rev[..9]
} else {
rev
}
}
pub const BLOCK_ATTRS: [&str; 7] = [
"notes",
"default-branch",
"code",
"docs",
"tests",
"test-markers",
"note-words",
];
pub fn block_changes(
old: Option<&str>,
new: Option<&str>,
) -> Vec<(&'static str, Option<String>, Option<String>)> {
let (Some(old), Some(new)) = (
old.filter(|t| crate::scheme::has_block(t)),
new.filter(|t| crate::scheme::has_block(t)),
) else {
return Vec::new();
};
let value = |text: &str, attr: &str| {
crate::scheme::attr_from_agents(&crate::scheme::at_commit(text), attr)
.map(|v| v.split_whitespace().collect::<Vec<_>>().join(" "))
};
BLOCK_ATTRS
.into_iter()
.map(|attr| (attr, value(old, attr), value(new, attr)))
.filter(|(_, old, new)| old != new)
.collect()
}
pub fn agents_at(dir: &Path, rev: &str) -> Result<Option<String>> {
Ok(blobs_at(dir, rev, &[PathBuf::from("AGENTS.md")])?
.pop()
.flatten())
}
pub fn blobs_at(root: &Path, rev: &str, rels: &[PathBuf]) -> Result<Vec<Option<String>>> {
let mut git = Batch::start(root)?;
let mut out = Vec::new();
for rel in rels {
out.push(
match git.read(&format!("{rev}:./{}", rel.to_string_lossy()))? {
Some(object) if object.kind == "blob" => {
Some(String::from_utf8_lossy(&object.body).into_owned())
}
_ => None,
},
);
}
git.finish()?;
Ok(out)
}
fn git(root: &Path, args: &[&str]) -> Result<String> {
let out = crate::workspace::git(root).args(args).output()?;
if !out.status.success() {
bail!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8(out.stdout)?.trim().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn project(published: Option<&str>) -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
let attr = published.map_or(String::new(), |b| format!(" default-branch=\"{b}\""));
std::fs::write(
dir.path().join("AGENTS.md"),
format!("<silcrow{attr}>\n</silcrow>\n"),
)
.unwrap();
dir
}
#[test]
fn write_tree_keeps_an_export_ignored_file() {
let dir = project(Some("main"));
let run = |args: &[&str]| {
let out = crate::test_git()
.args(args)
.current_dir(dir.path())
.output()
.unwrap();
assert!(
out.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
};
std::fs::create_dir_all(dir.path().join("src")).unwrap();
std::fs::write(
dir.path().join(".gitattributes"),
"src/x.rs export-ignore\n",
)
.unwrap();
std::fs::write(dir.path().join("src/x.rs"), "fn f() {}\r\n").unwrap();
run(&["init", "-q", "-b", "main"]);
run(&["add", "-A"]);
run(&[
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-q",
"--no-verify",
"-m",
"x",
]);
let head = tempfile::tempdir().unwrap();
write_tree(dir.path(), "HEAD", head.path()).unwrap();
assert_eq!(
std::fs::read(head.path().join("src/x.rs")).unwrap(),
b"fn f() {}\r\n",
"the blob, byte for byte"
);
assert!(head.path().join("AGENTS.md").is_file());
}
#[test]
fn short_cuts_only_a_full_commit_id() {
let sha = "1199022b52b84041b485c718fb89e2e409245985";
assert_eq!(short(sha), "1199022b5");
assert_eq!(short("origin/main"), "origin/main");
assert_eq!(short("refs/heads/release-2026"), "refs/heads/release-2026");
assert_eq!(short("HEAD^1"), "HEAD^1");
}
#[test]
fn default_branch_is_required_and_shared_by_every_project() {
let main = project(Some("main"));
let also_main = project(Some("main"));
let trunk = project(Some("trunk"));
let none = project(None);
assert_eq!(branch(&[main.path(), also_main.path()]).unwrap(), "main");
let err = branch(&[main.path(), none.path()]).unwrap_err().to_string();
assert!(err.contains("silcrow install --write"), "{err}");
let err = branch(&[main.path(), trunk.path()])
.unwrap_err()
.to_string();
assert!(err.contains("different default branches"), "{err}");
}
}