use std::path::{Path, PathBuf};
use std::process::Command;
use crate::hookfile::{self, HookFile, Refuse, Staged, SwapFailure};
use crate::names::{BIN, FLEET_BIN, OLD_BIN, OLD_FLEET_BIN};
use crate::ui::{error_sign, highlight, valid_sign, warning_sign};
pub const PLACEHOLDER: &str = "__GREENGATE_BIN__";
pub const SHIM: &str = include_str!("../templates/hooks/pre-commit");
pub use crate::hookfile::{is_our_shim, SHIM_MARKER};
pub const DISPATCHERS: [&str; 6] = [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TemplateDir {
Unresolvable,
NoGit,
IsCheckout,
InsideCheckout,
Safe,
}
fn git_ok(dir: &Path, args: &[&str]) -> bool {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
pub fn classify_dir(dir: &Path) -> TemplateDir {
let Ok(real) = dir.canonicalize() else {
return TemplateDir::Unresolvable;
};
if Command::new("git").arg("--version").output().is_err() {
return TemplateDir::NoGit;
}
if git_ok(&real, &["ls-files", "--error-unmatch", "."]) {
return TemplateDir::IsCheckout;
}
if git_ok(&real, &["rev-parse", "--git-dir"]) {
return TemplateDir::InsideCheckout;
}
TemplateDir::Safe
}
pub fn bake(shim: &str, bin: &str) -> String {
shim.replace(PLACEHOLDER, bin)
}
pub fn is_bakeable(bin: &str) -> bool {
if bin.is_empty() || bin == PLACEHOLDER {
return false;
}
let b = bin.as_bytes();
if b[0] == b'/' {
return true;
}
b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
}
fn absolute(p: &Path) -> PathBuf {
if p.is_absolute() {
return p.to_path_buf();
}
match std::env::current_dir() {
Ok(cwd) => cwd.join(p),
Err(_) => p.to_path_buf(),
}
}
fn unbaked_lookup_dir() -> PathBuf {
home().join(".local").join("bin")
}
fn warn_if_unbaked_cannot_resolve(binary: &str) {
let looked = unbaked_lookup_dir();
let placed = Path::new(binary).parent();
let reachable = placed.is_some_and(|p| {
matches!(
(p.canonicalize(), looked.canonicalize()),
(Ok(a), Ok(b)) if a == b
)
});
if reachable {
return;
}
eprintln!();
eprintln!(
"{} the binary is at {}, which an unbaked shim will not find.",
warning_sign(),
highlight(binary)
);
eprintln!(
" Shims here keep the placeholder, and they look only in {}.",
looked.display()
);
eprintln!(" Either link it where they look:");
eprintln!(" ln -s {} {}", binary, looked.join(BIN).display());
eprintln!(" or set GIT_HOOKS_BIN in the environment git runs hooks with:");
eprintln!(" export GIT_HOOKS_BIN={binary}");
}
pub fn bin_dir() -> PathBuf {
if let Some(d) = std::env::var_os("GREENGATE_BIN_DIR") {
return PathBuf::from(d);
}
home().join(".local").join("bin")
}
pub fn template_hooks_dir() -> PathBuf {
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home().join(".config"));
base.join("git")
.join("git-templates")
.join("templates")
.join("hooks")
}
fn home() -> PathBuf {
std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
}
fn installed_name() -> String {
match std::env::current_exe() {
Ok(p) => name_for(&p, BIN),
Err(_) => BIN.to_string(),
}
}
fn name_for(exe: &Path, name: &str) -> String {
match exe.extension().and_then(|e| e.to_str()) {
Some(e) if !e.is_empty() => format!("{name}.{e}"),
_ => name.to_string(),
}
}
fn replace_atomically(from: &Path, target: &Path) -> std::io::Result<()> {
let dir = target.parent().unwrap_or_else(|| Path::new("."));
let file = target
.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default();
let staged_copy = dir.join(format!(".{file}.tmp.{}", std::process::id()));
if let Err(e) = stage_copy(from, &staged_copy) {
let _ = std::fs::remove_file(&staged_copy); return Err(e);
}
if cfg!(windows) && target.exists() {
let aside = target.with_extension("old.exe");
let _ = std::fs::remove_file(&aside); if let Err(e) = std::fs::rename(target, &aside) {
let _ = std::fs::remove_file(&staged_copy); return Err(e);
}
}
let renamed = std::fs::rename(&staged_copy, target);
if renamed.is_err() {
let _ = std::fs::remove_file(&staged_copy); if cfg!(windows) {
let _ = std::fs::rename(target.with_extension("old.exe"), target); }
}
renamed
}
fn stage_copy(from: &Path, staged: &Path) -> std::io::Result<()> {
let mut source = std::fs::File::open(from)?;
let mut file = std::fs::File::create(staged)?;
std::io::copy(&mut source, &mut file)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o755))?;
}
file.sync_all()
}
const LEFTOVER_AGE: std::time::Duration = std::time::Duration::from_secs(600);
fn sweep_install_leftovers(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let ours = [BIN, OLD_BIN]
.iter()
.any(|n| name.starts_with(&format!(".{n}")) && name.contains(".tmp."));
let aside = [BIN, FLEET_BIN, OLD_BIN, OLD_FLEET_BIN]
.iter()
.any(|n| name == format!("{n}.old.exe"));
let stale = entry
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age >= LEFTOVER_AGE);
if (ours || aside) && stale {
let _ = std::fs::remove_file(entry.path()); }
}
}
fn write_aliases(binary: &Path) -> Result<Vec<&'static str>, String> {
let dir = binary.parent().unwrap_or_else(|| Path::new("."));
let pairs = [(BIN, OLD_BIN), (FLEET_BIN, OLD_FLEET_BIN)];
let mut written = Vec::new();
for (new, old) in pairs {
let from = dir.join(name_for(binary, new));
if !from.is_file() {
continue;
}
let alias = dir.join(name_for(binary, old));
replace_atomically(&from, &alias).map_err(|e| {
format!(
"installed {}, but cannot write its old name {}: {e}\n hooks baked to the old name keep running the build that was there;\n run `{BIN} install` again, or delete {}",
from.display(),
alias.display(),
alias.display()
)
})?;
written.push(old);
}
Ok(written)
}
fn foreign_hooks(dir: &Path) -> Vec<(&'static str, HookFile)> {
DISPATCHERS
.into_iter()
.map(|name| (name, hookfile::classify(&dir.join(name))))
.filter(|(_, what)| !matches!(what, HookFile::Absent | HookFile::Ours))
.collect()
}
#[derive(Debug)]
pub struct Written {
pub path: PathBuf,
pub replaced: HookFile,
}
#[derive(Debug)]
pub enum ShimWriteError {
Refused(Vec<Refuse>),
Preflight { at: PathBuf, error: std::io::Error },
Swap(SwapFailure),
}
impl std::fmt::Display for ShimWriteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ShimWriteError::Refused(refusals) => {
writeln!(f, "refusing to write {} hooks:", refusals.len())?;
for (i, r) in refusals.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, " {}", r.explain())?;
}
Ok(())
}
ShimWriteError::Preflight { at, error } => {
write!(f, "cannot prepare {}: {error}", at.display())
}
ShimWriteError::Swap(s) => write!(f, "{s}"),
}
}
}
fn write_shims(dir: &Path, bin: &str, force: bool) -> Result<Vec<Written>, ShimWriteError> {
if !is_bakeable(bin) {
return Err(ShimWriteError::Preflight {
at: dir.to_path_buf(),
error: std::io::Error::other(format!(
"refusing to bake {bin:?}: the shim takes an absolute path only"
)),
});
}
let baked = bake(SHIM, bin);
let mut allowed: Vec<(PathBuf, HookFile)> = Vec::new();
let mut refusals: Vec<Refuse> = Vec::new();
for name in DISPATCHERS {
let path = dir.join(name);
match hookfile::guard_write(&path, force) {
Ok(what) => allowed.push((path, what)),
Err(r) => refusals.push(r),
}
}
if !refusals.is_empty() {
return Err(ShimWriteError::Refused(refusals));
}
let mut staged: Vec<Staged> = Vec::new();
for (path, _) in &allowed {
match hookfile::stage(path, &baked, true) {
Ok(s) => staged.push(s),
Err(error) => {
return Err(ShimWriteError::Preflight {
at: path.clone(),
error,
});
}
}
}
hookfile::commit_all(staged).map_err(ShimWriteError::Swap)?;
Ok(allowed
.into_iter()
.map(|(path, replaced)| Written { path, replaced })
.collect())
}
pub fn run(settings: &crate::config::Settings, force: bool) -> Result<(), String> {
let binary = install_binary()?;
populate_template_dir(&binary, force)?;
bake_repo_hooks(&binary, force)?;
offer_trust();
offer_agents_md(settings);
point_at_setup(settings);
Ok(())
}
pub fn enroll(conventions: Option<&str>) -> Result<(), String> {
match conventions {
None | Some("declared") | Some("everywhere") => {}
Some(other) => {
return Err(format!(
"{BIN} enroll --conventions takes `declared` or `everywhere`, not {other:?}"
));
}
}
let binary = install_binary()?;
populate_template_dir(&binary, false)?;
let hooks = template_hooks_dir();
let templates = hooks
.parent()
.ok_or_else(|| "template hooks dir has no parent".to_string())?
.to_path_buf();
point_template_dir_at(&templates)?;
match conventions {
Some(word) => {
if !crate::git::succeeds(&["config", "--global", "greengate.conventions", word]) {
return Err(
"could not write greengate.conventions to the global git config".into(),
);
}
eprintln!(
"{} greengate.conventions = {} (global)",
valid_sign(),
highlight(word)
);
if word == "declared" {
eprintln!(" House rules run only in repositories that commit a greengate.conf;");
eprintln!(" the safety net (conflicts, secrets, size, debug leftovers) runs");
eprintln!(" everywhere.");
}
}
None => {
eprintln!(
"{} conventions currently apply everywhere. On a machine that also",
warning_sign()
);
eprintln!(" clones other people's projects, consider:");
eprintln!(
" {}",
highlight(concat!(crate::bin!(), " enroll --conventions declared"))
);
}
}
eprintln!();
eprintln!("Enrolled. Every future `git clone` and `git init` gets the hooks.");
eprintln!("Repositories cloned before now are untouched — wire them with");
eprintln!(
" {} (one repository)",
highlight(concat!(crate::bin!(), " init"))
);
eprintln!(
" {} (every repository under a root)",
highlight(concat!(crate::fleet_bin!(), " install --root <dir>"))
);
eprintln!(
"Undo with {}.",
highlight("git config --global --unset init.templateDir")
);
Ok(())
}
fn point_template_dir_at(templates: &std::path::Path) -> Result<(), String> {
let want = templates.to_string_lossy().into_owned();
let current = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
.filter(|s| !s.is_empty());
match current {
None => {
if !crate::git::succeeds(&["config", "--global", "init.templateDir", &want]) {
return Err("could not write init.templateDir to the global git config".into());
}
eprintln!(
"{} init.templateDir = {} (global)",
valid_sign(),
highlight(&want)
);
Ok(())
}
Some(existing) if same_dir(&existing, &want) => {
eprintln!(
"{} init.templateDir already points here ({})",
valid_sign(),
highlight(&existing)
);
Ok(())
}
Some(existing) => Err(format!(
"init.templateDir is already set to {existing} — something else installs
hooks on this machine. Overwriting it would silently disable that.
Decide which one wins, then either unset it
(git config --global --unset init.templateDir) and re-run
`{BIN} enroll`, or leave enrollment to it."
)),
}
}
fn same_dir(a: &str, b: &str) -> bool {
if a == b {
return true;
}
match (
std::path::Path::new(a).canonicalize(),
std::path::Path::new(b).canonicalize(),
) {
(Ok(x), Ok(y)) => x == y,
_ => false,
}
}
pub fn init() -> Result<(), String> {
init_with(
std::env::current_exe(),
Path::new("."),
&crate::pushed_tree::in_push_snapshot,
)
}
fn init_with(
me: std::io::Result<PathBuf>,
dir: &Path,
in_snapshot: &dyn Fn(&Path) -> std::io::Result<bool>,
) -> Result<(), String> {
let rh = repo_hooks_in(dir);
if matches!(rh, RepoHooks::Nowhere) {
return Ok(());
}
match in_snapshot(dir) {
Ok(true) => {
eprintln!(
"{BIN} init: inside a {BIN} push snapshot — the repository's hooks are left as they are"
);
return Ok(());
}
Ok(false) => {}
Err(_) if matches!(rh, RepoHooks::Unanswerable { .. }) => {}
Err(e) => {
return Err(format!(
"{} cannot tell whether this is a {BIN} push snapshot — {e}\n \
Hooks were NOT installed.",
error_sign()
))
}
}
let hooks = match rh {
RepoHooks::Own(dir) => dir,
RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
return Err(redirected_message(&to, &own))
}
RepoHooks::Redirected { to, .. } => to,
RepoHooks::Nowhere => return Ok(()),
RepoHooks::Unanswerable { why } => {
return Err(format!(
"{} git would not say where this repository's hooks live —\n {}\n \
Hooks were NOT installed.",
error_sign(),
crate::ui::sanitize(&why)
))
}
};
let me = me.map_err(|e| format!("cannot locate the running binary: {e}"))?;
let binary = absolute(&me);
let binary = binary.to_string_lossy().into_owned();
if !is_bakeable(&binary) {
return Err(format!(
"{} cannot bake {binary:?} — the shim takes an absolute path only",
error_sign()
));
}
std::fs::create_dir_all(&hooks)
.map_err(|e| format!("cannot create {}: {e}", hooks.display()))?;
let written = write_shims(&hooks, &binary, false)
.map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
eprintln!(
"{} {BIN}: {} hooks in {}",
valid_sign(),
written.len(),
hooks.display()
);
Ok(())
}
fn point_at_setup(settings: &crate::config::Settings) {
let s = crate::commit_style::Style::resolve(settings);
eprintln!(
" commit style: gitmoji {}, subject ≤{}, description ≤{} — `{BIN} setup` to change",
s.gitmoji.as_str(),
s.subject_max,
s.description_max
);
}
fn offer_trust() {
let Ok(root) = crate::hooks::common::repo_root_checked() else {
return;
};
let root = Path::new(&root);
let state = crate::trust::state(root);
if matches!(
state,
crate::trust::State::NoManifest | crate::trust::State::Trusted
) {
return;
}
eprintln!();
eprintln!(
"{} {} declares checks and policy that would apply to your commits:",
warning_sign(),
crate::manifest::manifest_name(root)
);
let manifest_file = crate::manifest::manifest_name(root);
let manifest = root.join(manifest_file);
let Ok(source) = std::fs::read(&manifest) else {
eprintln!("{} could not read {manifest_file}", warning_sign());
return;
};
eprint!(
"{}",
crate::trust::describe_source(&String::from_utf8_lossy(&source))
);
let Some(fp) = crate::trust::fingerprint_bytes(root, &source) else {
eprintln!("{} could not hash {manifest_file}", warning_sign());
return;
};
if crate::trust::confirm(" Trust them? (y/N) ") {
match crate::trust::record_verified(root, &fp) {
Ok(()) => eprintln!("{} trusted ({fp})", valid_sign()),
Err(e) => eprintln!("{} {e}", warning_sign()),
}
} else {
eprintln!(" Left untrusted. The built-ins still run; these do not.");
eprintln!(" Change your mind with `{BIN} trust`.");
}
}
fn offer_agents_md(settings: &crate::config::Settings) {
let Ok(root) = crate::hooks::common::repo_root_checked() else {
return;
};
let path = Path::new(&root).join("AGENTS.md");
match crate::agents_md::check(settings, &path) {
Ok(crate::agents_md::CheckResult::MatchesGenerated) => return,
Ok(_) => {}
Err(_) => return,
}
eprintln!();
eprintln!(
"{} AGENTS.md can point coding agents at `greengate list --json` \
instead of leaving them to discover these checks the hard way:",
warning_sign()
);
if crate::trust::confirm(" Add it? (y/N) ") {
match crate::agents_md::write(settings, &path) {
Ok(()) => eprintln!("{} wrote {}", valid_sign(), path.display()),
Err(e) => eprintln!("{} {e}", warning_sign()),
}
} else {
eprintln!(" Left as-is. Change your mind with `{BIN} agents-md`.");
}
}
fn on_path_already(me: &Path) -> Option<PathBuf> {
let me_real = me.canonicalize().ok()?;
let name = installed_name();
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path)
.map(|dir| dir.join(&name))
.filter(|cand| !in_a_build_dir(cand))
.find(|cand| cand.canonicalize().is_ok_and(|real| real == me_real))
.map(|cand| absolute(&cand))
.filter(|abs| is_bakeable(&abs.to_string_lossy()))
}
fn in_a_build_dir(p: &Path) -> bool {
p.ancestors()
.skip(1)
.take(4)
.any(|dir| dir.join("CACHEDIR.TAG").is_file())
}
fn install_binary() -> Result<String, String> {
let me =
std::env::current_exe().map_err(|e| format!("cannot locate the running binary: {e}"))?;
if std::env::var_os("GREENGATE_BIN_DIR").is_none() {
if let Some(stable) = on_path_already(&me) {
let shown = stable.to_string_lossy().into_owned();
eprintln!("{} using {}", valid_sign(), highlight(&shown));
eprintln!(" already on PATH, so nothing was copied — an upgrade there");
eprintln!(" reaches every repository without reinstalling.");
return Ok(shown);
}
}
let dir = bin_dir();
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
let target = absolute(&dir.join(installed_name()));
let already_there = matches!(
(me.canonicalize(), target.canonicalize()),
(Ok(a), Ok(b)) if a == b
);
sweep_install_leftovers(&dir);
if !already_there {
replace_atomically(&me, &target)
.map_err(|e| format!("cannot install to {}: {e}", target.display()))?;
}
let aliases = write_aliases(&target)?;
let installed = target.to_string_lossy().into_owned();
eprintln!("{} installed {}", valid_sign(), highlight(&installed));
if !aliases.is_empty() {
eprintln!(
" also as {}: hooks baked to the old name keep working",
aliases.join(" and ")
);
}
Ok(installed)
}
fn populate_template_dir(binary: &str, force: bool) -> Result<(), String> {
let dir = template_hooks_dir();
let _ = std::fs::create_dir_all(&dir);
let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
let shown = shown.display();
match classify_dir(&dir) {
TemplateDir::IsCheckout => {
eprintln!(
"{} template dir IS the checkout ({shown}) — nothing to install.",
warning_sign()
);
eprintln!(" Its shims keep the placeholder deliberately and resolve");
eprintln!(" {binary} at run time. This is the intended setup.");
warn_if_unbaked_cannot_resolve(binary);
}
TemplateDir::InsideCheckout => {
eprintln!(
"{} {shown} is inside a git checkout — leaving it alone.",
warning_sign()
);
warn_if_unbaked_cannot_resolve(binary);
}
TemplateDir::NoGit => eprintln!(
"{} git is not on PATH — refusing to delete anything.",
warning_sign()
),
TemplateDir::Unresolvable => {
eprintln!("{} cannot resolve {shown} — skipping.", warning_sign())
}
TemplateDir::Safe => {
let written = write_shims(&dir, binary, force)
.map_err(|e| format!("cannot write shims to {shown}: {e}"))?;
eprintln!("{} wrote {} shims to {shown}", valid_sign(), written.len());
report_overwrites(&written);
}
}
Ok(())
}
fn report_overwrites(written: &[Written]) {
for w in written {
if matches!(w.replaced, HookFile::Absent | HookFile::Ours) {
continue;
}
eprintln!(
"{} overwrote {} — it was {}",
warning_sign(),
w.path.display(),
w.replaced.describe()
);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepoHooks {
Own(PathBuf),
Redirected { to: PathBuf, own: PathBuf },
Nowhere,
Unanswerable { why: String },
}
pub fn repo_hooks() -> RepoHooks {
repo_hooks_in(Path::new("."))
}
pub fn repo_hooks_in(dir: &Path) -> RepoHooks {
let Some(out) = crate::git::output_in(
dir,
&[
"rev-parse",
"--path-format=absolute",
"--git-path",
"hooks",
"--git-common-dir",
],
) else {
return RepoHooks::Unanswerable {
why: "could not run git".to_string(),
};
};
if out.code != 0 {
if out.stderr.contains("not a git repository") {
return RepoHooks::Nowhere;
}
let why = out
.stderr
.lines()
.find(|l| l.starts_with("fatal:"))
.or_else(|| out.stderr.lines().find(|l| !l.trim().is_empty()))
.unwrap_or("git gave no reason")
.to_string();
return RepoHooks::Unanswerable { why };
}
let mut lines = out.stdout.lines();
let (Some(dispatched), Some(common)) = (lines.next(), lines.next()) else {
return RepoHooks::Nowhere;
};
let dispatched = PathBuf::from(dispatched);
let own = PathBuf::from(common).join("hooks");
if crate::hookfile::resolve_lexical(&dispatched) == crate::hookfile::resolve_lexical(&own) {
RepoHooks::Own(own)
} else {
RepoHooks::Redirected {
to: dispatched,
own,
}
}
}
pub fn redirect_culprit(to: &Path) -> Option<&'static str> {
let s = to.to_string_lossy().replace('\\', "/");
if s.contains("/.husky") {
return Some("husky");
}
if s.contains("/.lefthook") || s.contains("lefthook") {
return Some("lefthook");
}
None
}
pub fn holds_our_shims(dir: &Path) -> bool {
DISPATCHERS
.iter()
.any(|name| matches!(hookfile::classify(&dir.join(name)), HookFile::Ours))
}
pub fn redirect_is_hostile(to: &Path, own: &Path) -> bool {
redirect_culprit(to).is_some() || (holds_our_shims(own) && !holds_our_shims(to))
}
pub fn redirected_message(to: &Path, own: &Path) -> String {
let mut msg = format!(
"{} git dispatches hooks from {}, not {}",
error_sign(),
highlight(&to.display().to_string()),
own.display()
);
match redirect_culprit(to) {
Some(tool) => msg.push_str(&format!(
"\n `core.hooksPath` is set, so {tool} owns the hooks here. Shims\n \
written to either directory would be overwritten or never run."
)),
None => msg.push_str(
"\n `core.hooksPath` is set, so another tool owns the hooks here.\n \
Shims written to either directory would be overwritten or never run.",
),
}
msg.push_str(&format!(
"\n Hand dispatch back first: {}",
highlight("git config --unset core.hooksPath")
));
if redirect_culprit(to).is_none() && holds_our_shims(own) {
msg.push_str(&format!(
"\n Or, if the redirect is deliberate, clear our stale shims from {}\n \
first: {}",
own.display(),
highlight(concat!(crate::bin!(), " uninstall"))
));
}
msg
}
fn bake_repo_hooks(binary: &str, force: bool) -> Result<(), String> {
let hooks = match repo_hooks() {
RepoHooks::Own(dir) => dir,
RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
return Err(redirected_message(&to, &own))
}
RepoHooks::Redirected { to, .. } => to,
RepoHooks::Nowhere => {
eprintln!(
"{} not inside a git repository — no repo hooks written.",
warning_sign()
);
return Ok(());
}
RepoHooks::Unanswerable { why } => {
return Err(format!(
"{} git would not say where this repository's hooks live —\n {}",
error_sign(),
crate::ui::sanitize(&why)
))
}
};
let _ = std::fs::create_dir_all(&hooks);
let foreign = foreign_hooks(&hooks);
if !foreign.is_empty() && !force {
let mut msg = format!(
"{} {} already has hooks that are not ours:",
error_sign(),
hooks.display()
);
for (name, what) in &foreign {
msg.push_str(&format!("\n {name} — {}", what.describe()));
}
msg.push_str(concat!(
"\n Look at them first, then `",
crate::bin!(),
" install --force`."
));
return Err(msg);
}
let written = write_shims(&hooks, binary, force)
.map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
eprintln!(
"{} baked {} shims into {}",
valid_sign(),
written.len(),
hooks.display()
);
report_overwrites(&written);
Ok(())
}
pub fn uninstall(remove_binary: bool) -> Result<(), String> {
uninstall_template_dir()?;
uninstall_repo_hooks()?;
if remove_binary {
let me = std::env::current_exe().unwrap_or_else(|_| PathBuf::from(BIN));
for name in [BIN, OLD_BIN] {
let target = bin_dir().join(name_for(&me, name));
match std::fs::remove_file(&target) {
Ok(()) => eprintln!(
"{} removed {}",
valid_sign(),
highlight(&target.to_string_lossy())
),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("cannot remove {}: {e}", target.display())),
}
}
}
report_global_template_dir();
eprintln!(" hook.skip and greengate.severity were not touched.");
Ok(())
}
pub fn uninstall_repo() -> Result<(), String> {
uninstall_repo_hooks()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstalledState {
Present,
Absent,
Partial,
Unknown,
}
impl InstalledState {
pub fn as_str(self) -> &'static str {
match self {
InstalledState::Present => "present",
InstalledState::Absent => "absent",
InstalledState::Partial => "partial",
InstalledState::Unknown => "unknown",
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Installed {
pub state: InstalledState,
pub hooks_dir: Option<PathBuf>,
pub shims: Vec<(&'static str, Option<String>)>,
}
impl Installed {
fn unknown() -> Installed {
Installed {
state: InstalledState::Unknown,
hooks_dir: None,
shims: Vec::new(),
}
}
pub fn to_json(&self) -> String {
let shims: Vec<String> = self
.shims
.iter()
.map(|(name, bin)| {
crate::json::object(&[
crate::json::string_field("name", name),
crate::json::opt_string_field("binary", bin.as_deref()),
])
})
.collect();
let dir = self.hooks_dir.as_ref().map(|d| d.display().to_string());
crate::json::object(&[
crate::json::string_field("state", self.state.as_str()),
crate::json::opt_string_field("hooks_dir", dir.as_deref()),
format!("\"shims\":{}", crate::json::array(&shims)),
])
}
}
pub fn installed_in(dir: &Path) -> Installed {
let mut shims = Vec::new();
let mut unreadable = false;
for name in DISPATCHERS {
let path = dir.join(name);
match hookfile::classify(&path) {
HookFile::Ours => shims.push((name, baked_binary(&path))),
HookFile::Unknown { .. }
| HookFile::Foreign(hookfile::ForeignWhy::Unreadable { .. }) => unreadable = true,
HookFile::Absent
| HookFile::Symlink { .. }
| HookFile::NotARegularFile
| HookFile::Foreign(
hookfile::ForeignWhy::HandWritten | hookfile::ForeignWhy::NotUtf8,
) => {}
#[cfg(unix)]
HookFile::Foreign(hookfile::ForeignWhy::MultiplyLinked { .. }) => {}
}
}
let state = match (shims.len(), unreadable) {
(n, _) if n == DISPATCHERS.len() => InstalledState::Present,
(_, true) => InstalledState::Unknown,
(0, false) => InstalledState::Absent,
_ => InstalledState::Partial,
};
Installed {
state,
hooks_dir: Some(dir.to_path_buf()),
shims,
}
}
pub fn installed_here() -> Installed {
match repo_hooks() {
RepoHooks::Own(dir) | RepoHooks::Redirected { to: dir, .. } => installed_in(&dir),
RepoHooks::Nowhere | RepoHooks::Unanswerable { .. } => Installed::unknown(),
}
}
pub fn installed_in_template_dir() -> Installed {
installed_in(&template_hooks_dir())
}
fn baked_binary(path: &Path) -> Option<String> {
let text = std::fs::read_to_string(path).ok()?;
text.lines().find_map(|l| {
let v = l.strip_prefix("BAKED=\"")?.strip_suffix('"')?;
(!v.is_empty() && v != PLACEHOLDER).then(|| v.to_string())
})
}
pub fn forget_bookkeeping_in(repo: &Path) -> Vec<&'static str> {
let mut gone = Vec::new();
if crate::gate_stamp::forget_in(repo) {
gone.push("gate stamps");
}
if crate::attest::forget_in(repo) {
gone.push("attestations");
}
if crate::bypass::forget_in(repo) {
gone.push("bypass ledger");
}
if crate::downgrade::forget_in(repo) {
gone.push("downgrade ledger");
}
if crate::skew::forget_in(repo) {
gone.push("version-skew marker");
}
if crate::git::succeeds_in(repo, &["config", "--unset-all", "greengate.knownIdentity"]) {
gone.push("known-identity memo");
}
if !crate::trust::recorded(repo).is_empty() && crate::trust::revoke(repo).is_ok() {
gone.push("greengate.conf trust");
}
gone
}
fn uninstall_repo_hooks() -> Result<(), String> {
let dirs: Vec<PathBuf> = match repo_hooks() {
RepoHooks::Own(dir) => vec![dir],
RepoHooks::Redirected { to, own } => vec![to, own],
RepoHooks::Nowhere => {
eprintln!(
"{} not inside a git repository — no repo hooks removed.",
warning_sign()
);
return Ok(());
}
RepoHooks::Unanswerable { why } => {
eprintln!(
"{} git would not answer here — no repo hooks removed ({})",
warning_sign(),
crate::ui::sanitize(&why)
);
return Ok(());
}
};
for hooks in &dirs {
let mut removed = 0usize;
let mut left: Vec<String> = Vec::new();
for name in DISPATCHERS {
let path = hooks.join(name);
match hookfile::classify(&path) {
HookFile::Absent => {}
HookFile::Ours => match hookfile::guard_remove(&path, true) {
Ok(()) => {
hookfile::remove_regular(&path)
.map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
removed += 1;
}
Err(r) => left.push(r.explain()),
},
what => left.push(format!("{name} — {}", what.describe())),
}
}
if removed > 0 || !left.is_empty() || dirs.len() == 1 {
eprintln!(
"{} removed {removed} shims from {}",
valid_sign(),
hooks.display()
);
}
for reason in &left {
eprintln!("{} left alone: {reason}", warning_sign());
}
}
if let Ok(root) = crate::hooks::common::repo_root_checked() {
let gone = forget_bookkeeping_in(Path::new(&root));
if !gone.is_empty() {
eprintln!("{} forgot {}", valid_sign(), gone.join(", "));
}
}
Ok(())
}
fn uninstall_template_dir() -> Result<(), String> {
let dir = template_hooks_dir();
let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
let shown = shown.display();
match classify_dir(&dir) {
TemplateDir::IsCheckout | TemplateDir::InsideCheckout => {
eprintln!(
"{} template dir is a git checkout ({shown}) — deleting NOTHING there.",
warning_sign()
);
eprintln!(" Those shims are tracked files belonging to that checkout,");
eprintln!(" not something this install put there. Remove them with git,");
eprintln!(" or point init.templateDir somewhere else.");
}
TemplateDir::NoGit => eprintln!(
"{} git is not on PATH — cannot tell whether {shown} is a checkout, deleting nothing.",
warning_sign()
),
TemplateDir::Unresolvable => eprintln!(
"{} no template dir at {shown} — nothing to remove.",
warning_sign()
),
TemplateDir::Safe => {
let mut removed = 0usize;
let mut left: Vec<String> = Vec::new();
for name in DISPATCHERS {
let path = dir.join(name);
match hookfile::classify(&path) {
HookFile::Absent => {}
HookFile::Ours => match hookfile::guard_remove(&path, true) {
Ok(()) => {
hookfile::remove_regular(&path)
.map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
removed += 1;
}
Err(r) => left.push(r.explain()),
},
what => left.push(format!("{name} — {}", what.describe())),
}
}
eprintln!("{} removed {removed} shims from {shown}", valid_sign());
for reason in &left {
eprintln!("{} left alone: {reason}", warning_sign());
}
}
}
Ok(())
}
fn report_global_template_dir() {
let Some(configured) = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
.filter(|s| !s.is_empty())
else {
return;
};
eprintln!();
eprintln!(
"{} init.templateDir is still set: {}",
warning_sign(),
highlight(&configured)
);
eprintln!(" Every `git clone` and `git init` still copies hooks from there");
eprintln!(" into the new repository. Uninstalling this repo did not change that.");
eprintln!(" Undo it with:");
eprintln!(
" {}",
highlight("git config --global --unset init.templateDir")
);
}
#[cfg(test)]
mod tests {
use super::*;
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("gh-install-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).expect("mkdir");
d
}
fn git(dir: &Path, args: &[&str]) {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.expect("git");
}
#[test]
fn shims_on_disk_match_the_embedded_one() {
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
if !Path::new(dir).is_dir() {
println!(
"! no repository checkout here — nothing to compare the embedded shim against"
);
return;
}
for name in DISPATCHERS {
let disk = std::fs::read_to_string(Path::new(dir).join(name))
.unwrap_or_else(|e| panic!("read {name}: {e}"));
assert_eq!(disk, SHIM, "{name} differs from the embedded shim");
}
}
#[test]
fn the_embedded_shim_carries_no_carriage_return() {
assert!(
!SHIM.contains('\r'),
"the embedded shim has CRLF line endings: this binary would \
install `#!/bin/sh\\r` as a POSIX sh hook. `.gitattributes` \
declares templates/hooks/* as eol=lf — has it been removed, or \
is this checkout stale?"
);
}
#[test]
fn a_directory_holding_tracked_files_is_never_safe() {
let d = tmp("tracked");
git(&d, &["init", "-q", "--template=", "."]);
git(&d, &["config", "user.email", "t@t.test"]);
git(&d, &["config", "user.name", "t"]);
std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
git(&d, &["add", "-A"]);
git(&d, &["commit", "-qm", "seed"]);
assert_eq!(classify_dir(&d), TemplateDir::IsCheckout);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_worktree_is_recognised_even_though_its_path_differs() {
let d = tmp("wt-main");
git(&d, &["init", "-q", "--template=", "."]);
git(&d, &["config", "user.email", "t@t.test"]);
git(&d, &["config", "user.name", "t"]);
std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
git(&d, &["add", "-A"]);
git(&d, &["commit", "-qm", "seed"]);
let wt = d.with_extension("wt");
let _ = std::fs::remove_dir_all(&wt);
git(&d, &["worktree", "add", "-q", wt.to_str().unwrap()]);
assert!(
wt.join("kept.txt").is_file(),
"worktree did not materialise"
);
assert_ne!(d.canonicalize().ok(), wt.canonicalize().ok());
assert_eq!(
classify_dir(&wt),
TemplateDir::IsCheckout,
"a worktree must be refused exactly like the main checkout"
);
let _ = std::fs::remove_dir_all(&wt);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn an_untracked_directory_inside_a_checkout_is_refused() {
let d = tmp("inside");
git(&d, &["init", "-q", "--template=", "."]);
let sub = d.join("scratch");
std::fs::create_dir_all(&sub).expect("mkdir");
assert_eq!(classify_dir(&sub), TemplateDir::InsideCheckout);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn an_ordinary_directory_is_safe() {
let d = tmp("plain");
assert_eq!(classify_dir(&d), TemplateDir::Safe);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_missing_directory_is_unresolvable_not_safe() {
assert_eq!(
classify_dir(Path::new("/nonexistent-install-c8f2/hooks")),
TemplateDir::Unresolvable
);
}
#[test]
fn baking_is_total_and_idempotent() {
let once = bake(SHIM, "/opt/amont");
assert!(!once.contains(PLACEHOLDER), "a token survived baking");
assert!(once.contains("/opt/amont"));
assert_eq!(bake(&once, "/other"), once, "re-baking must be a no-op");
}
#[test]
fn baking_does_not_rewrite_the_comment_explaining_it() {
for line in bake(SHIM, "/opt/amont").lines() {
if line.trim_start().starts_with('#') {
assert!(
!line.contains("/opt/amont"),
"baking rewrote a comment: {line}"
);
}
}
}
#[test]
fn only_an_absolute_path_is_bakeable() {
for good in [
"/opt/amont",
"/home/u/.local/bin/amont",
"C:/Users/u/amont.exe",
"C:\\Users\\u\\amont.exe",
] {
assert!(is_bakeable(good), "{good} should be bakeable");
}
for bad in [
"",
PLACEHOLDER,
"amont",
"./amont",
"../amont",
"target/debug/amont",
"C:amont.exe",
] {
assert!(!is_bakeable(bad), "{bad:?} must not be bakeable");
}
}
#[test]
fn the_shim_never_tests_the_placeholder_as_a_path() {
assert!(
!SHIM.contains(&format!("[ -x \"{PLACEHOLDER}\" ]")),
"the shim tests the raw token as a path"
);
assert!(
SHIM.contains("case \"$BAKED\" in"),
"the shim lost its absoluteness guard"
);
}
#[test]
fn write_shims_refuses_a_relative_binary_path() {
let d = tmp("relative");
let err = write_shims(&d, "target/debug/amont", false).expect_err("must refuse");
assert!(err.to_string().contains("absolute"), "{err}");
for name in DISPATCHERS {
assert!(!d.join(name).exists(), "{name} was written anyway");
}
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn writing_shims_covers_every_dispatcher() {
let d = tmp("write");
let written = write_shims(&d, "/opt/amont", false).expect("write");
assert_eq!(written.len(), DISPATCHERS.len());
for name in DISPATCHERS {
let got = std::fs::read_to_string(d.join(name)).expect("read");
assert!(!got.contains(PLACEHOLDER), "{name} was written unbaked");
assert!(got.contains("/opt/amont"), "{name} has no path");
}
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn one_refusal_writes_nothing_at_all() {
let d = tmp("all-or-nothing");
let theirs = d.join("prepare-commit-msg");
std::fs::write(&theirs, "#!/bin/sh\necho MINE\n").expect("write");
let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
assert!(
matches!(err, ShimWriteError::Refused(ref rs) if rs.len() == 1),
"{err}"
);
for name in ["commit-msg", "pre-commit", "pre-push"] {
assert!(
!d.join(name).exists(),
"{name} was written despite a refusal elsewhere"
);
}
assert_eq!(
std::fs::read_to_string(&theirs).expect("read"),
"#!/bin/sh\necho MINE\n"
);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_refusal_names_the_reason_for_each_hook() {
let d = tmp("named");
std::fs::write(d.join("commit-msg"), [0x7f, b'E', b'L', b'F', 0xff]).expect("write");
std::fs::write(d.join("pre-commit"), "#!/bin/sh\necho mine\n").expect("write");
let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
let text = err.to_string();
assert!(text.contains("not valid UTF-8"), "{text}");
assert!(text.contains("commit-msg"), "{text}");
assert!(text.contains("pre-commit"), "{text}");
let foreign = foreign_hooks(&d);
assert_eq!(foreign.len(), 2, "{foreign:?}");
assert!(foreign
.iter()
.any(|(n, w)| *n == "commit-msg" && matches!(w, HookFile::Foreign(_))));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn force_reports_what_each_write_replaced() {
let d = tmp("force-report");
std::fs::write(d.join("commit-msg"), "#!/bin/sh\necho mine\n").expect("write");
let written = write_shims(&d, "/opt/amont", true).expect("force must write");
let replaced: Vec<_> = written
.iter()
.filter(|w| !matches!(w.replaced, HookFile::Absent))
.collect();
assert_eq!(replaced.len(), 1, "{written:?}");
assert!(replaced[0].path.ends_with("commit-msg"));
assert!(matches!(replaced[0].replaced, HookFile::Foreign(_)));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_installed_name_keeps_the_platform_suffix() {
assert_eq!(
name_for(Path::new("/w/target/release/greengate.exe"), BIN),
"greengate.exe"
);
assert_eq!(
name_for(Path::new("/w/target/release/greengate.exe"), OLD_BIN),
"amont.exe"
);
assert_eq!(
name_for(Path::new("/u/target/release/greengate"), BIN),
"greengate"
);
assert_eq!(name_for(Path::new("/some.dir/greengate"), OLD_BIN), "amont");
}
#[cfg(unix)]
#[test]
fn an_install_replaces_by_rename_and_writes_the_alias_as_a_copy() {
use std::os::unix::fs::MetadataExt;
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0); }
}
let dir = std::env::temp_dir().join(format!("greengate-install-{}", std::process::id()));
let _cleanup = Cleanup(dir.clone());
std::fs::create_dir_all(&dir).unwrap();
let src = dir.join("built");
std::fs::write(&src, "new build").unwrap();
let target = dir.join(BIN);
std::fs::write(&target, "old build").unwrap();
let before = std::fs::metadata(&target).unwrap().ino();
let stale = dir.join(format!(".{BIN}.tmp.1"));
std::fs::write(&stale, "x").unwrap();
let aged = std::process::Command::new("touch")
.args(["-t", "200001010000"])
.arg(&stale)
.status()
.unwrap();
assert!(aged.success(), "touch -t could not age the leftover");
let old_source = dir.join("old-source");
std::fs::write(&old_source, "y").unwrap();
std::process::Command::new("touch")
.args(["-t", "200001010000"])
.arg(&old_source)
.status()
.unwrap();
let young = dir.join(format!(".{BIN}.tmp.2"));
stage_copy(&old_source, &young).unwrap();
std::fs::write(dir.join(OLD_BIN), "2.x binary").unwrap();
sweep_install_leftovers(&dir);
replace_atomically(&src, &target).unwrap();
assert_eq!(write_aliases(&target).unwrap(), vec![OLD_BIN]);
assert_eq!(std::fs::read_to_string(&target).unwrap(), "new build");
assert_ne!(std::fs::metadata(&target).unwrap().ino(), before);
let alias = dir.join(OLD_BIN);
assert_eq!(std::fs::read_to_string(&alias).unwrap(), "new build");
assert!(!std::fs::symlink_metadata(&alias)
.unwrap()
.file_type()
.is_symlink());
assert_ne!(
std::fs::metadata(&alias).unwrap().ino(),
std::fs::metadata(&target).unwrap().ino(),
"the alias is a copy, not a hard link"
);
assert!(!stale.exists(), "a stale leftover was not swept");
assert!(
young.exists(),
"a young temporary, maybe another install's, was swept"
);
assert!(!dir.join(OLD_FLEET_BIN).exists());
std::fs::write(&alias, "2.3.1 overwrite").unwrap();
assert_eq!(std::fs::read_to_string(&target).unwrap(), "new build");
}
fn hook_bytes(dir: &Path) -> Vec<(String, Vec<u8>)> {
let mut v: Vec<_> = std::fs::read_dir(dir)
.expect("hooks dir")
.filter_map(|e| e.ok())
.map(|e| {
(
e.file_name().to_string_lossy().into_owned(),
std::fs::read(e.path()).unwrap_or_default(),
)
})
.collect();
v.sort();
v
}
#[test]
fn init_fails_closed_when_the_snapshot_probe_cannot_answer() {
let d = tmp("probe-err");
git(&d, &["init", "-q", "--template=", "."]);
let hooks = d.join(".git").join("hooks");
std::fs::create_dir_all(&hooks).expect("mkdir");
write_shims(&hooks, "/sentinel/A/amont", false).expect("seed");
let before = hook_bytes(&hooks);
let b = || Ok(PathBuf::from("/sentinel/B/amont"));
let got = init_with(b(), &d, &|_| Err(std::io::Error::other("probe broke")));
let why = got.expect_err("a probe that cannot answer must fail init");
assert!(why.contains("cannot tell"), "{why}");
assert_eq!(before, hook_bytes(&hooks), "init wrote on doubt");
init_with(b(), &d, &|_| Ok(false)).expect("not a snapshot: bakes");
assert_ne!(before, hook_bytes(&hooks), "the control could not fail");
let _ = std::fs::remove_dir_all(&d);
}
}