use anyhow::Result;
use crate::harness;
use crate::workspace::Workspace;
fn dry_run_notes(ws: &Workspace) {
if let Some(line) = published_rewrite(ws) {
println!("{line}\n");
}
let Some(home) = std::env::var_os("HOME") else {
println!("HOME is unset, so no home skill directory was read.\n");
return;
};
let shadows = harness::home_skills(std::path::Path::new(&home), &ws.root);
if shadows.is_empty() {
return;
}
for dir in &shadows {
println!(
" {} is a home skill named silcrow, which may load in place of the repo pointer",
dir.display()
);
}
println!("\nRemove it unless you mean it to override the repo pointer.\n");
}
fn published_rewrite(ws: &Workspace) -> Option<String> {
let dirs: Vec<&std::path::Path> = ws.local().iter().map(|p| p.dir.as_path()).collect();
let born = crate::workspace::git(&ws.root)
.args(["rev-parse", "--verify", "--quiet", "HEAD"])
.output()
.is_ok_and(|out| out.status.success());
if dirs.is_empty() || !born {
return None;
}
match crate::published::held_branch(&ws.root, &dirs) {
Ok(held) => held.rewritten.map(|(named, at)| {
let name = held.name;
format!(
"The Silcrow block names `{named}` in `default-branch`, a change made at {at} while `{name}` was the default branch, and `{name}` does not hold it: every comparison reads `{name}` as the default branch until the change lands there. If `{name}` is no longer the default branch, let it hold the change and keep it, local or as `origin/{name}`: a branch this clone lacks holds no change."
)
}),
Err(e) => Some(format!("The default branch cannot be read: {e}")),
}
}
pub fn install(dry_run: bool) -> Result<()> {
let cwd = std::env::current_dir()?;
let ws = Workspace::discover(&cwd)?;
if !ws.root.join(".git").exists() {
anyhow::bail!("no git repository here. `silcrow install` writes into the git root.");
}
let project = ws
.enclosing(&cwd)
.map_or_else(|| cwd.clone(), |project| project.dir.clone());
if let Some(enclosing) = ws.enclosing(&cwd).filter(|project| project.dir != cwd) {
eprintln!(
"install writes the block of project `{}`, the nearest that encloses this directory. A nested project starts as an `AGENTS.md` with a Silcrow block in its own directory.",
enclosing.key
);
}
if let Err(e) = crate::policy::ProjectPolicy::from_root(&project) {
anyhow::bail!("{e} `install` writes no file while the block reads otherwise.");
}
if dry_run {
dry_run_notes(&ws);
}
harness::install_skill(&ws.root, dry_run)?;
harness::install_block_and_hooks(&ws.root, &project, dry_run)
}