use crate::common;
use common::output_retrying_etxtbsy;
use std::path::{Path, PathBuf};
use std::process::Command;
struct Sandbox(PathBuf);
impl Sandbox {
fn new(name: &str) -> Self {
let d = std::env::temp_dir().join(format!("gh-inst-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).expect("mkdir");
Sandbox(d)
}
fn path(&self, rel: &str) -> PathBuf {
rel.split('/').fold(self.0.clone(), |p, c| p.join(c))
}
fn install(&self, cwd: &Path) -> (i32, String) {
let mut cmd = crate::common::amont_cmd();
cmd.arg("install")
.current_dir(cwd)
.env("HOME", &self.0)
.env("USERPROFILE", &self.0)
.env("XDG_CONFIG_HOME", self.path(".config"));
let out = output_retrying_etxtbsy(&mut cmd).expect("run amont install");
(
out.status.code().unwrap_or(-1),
format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
),
)
}
}
impl Drop for Sandbox {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn git(dir: &Path, args: &[&str]) {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.expect("git");
}
fn init_repo(dir: &Path) {
std::fs::create_dir_all(dir).expect("mkdir");
git(dir, &["init", "-q", "--template=", "."]);
git(dir, &["config", "user.email", "t@t.test"]);
git(dir, &["config", "user.name", "t"]);
}
#[test]
fn a_symlinked_checkout_is_refused_and_left_untouched() {
let s = Sandbox::new("symlink");
let checkout = s.path("checkout");
init_repo(&checkout);
let hooks = checkout.join("templates/hooks");
std::fs::create_dir_all(&hooks).expect("mkdir");
std::fs::write(hooks.join("pre-commit"), "precious __AMONT_BIN__\n").expect("write");
git(&checkout, &["add", "-A"]);
git(&checkout, &["commit", "-qm", "seed"]);
let cfg = s.path(".config/git");
std::fs::create_dir_all(&cfg).expect("mkdir");
#[cfg(unix)]
std::os::unix::fs::symlink(&checkout, cfg.join("git-templates")).expect("symlink");
#[cfg(windows)]
{
if std::os::windows::fs::symlink_dir(&checkout, cfg.join("git-templates")).is_err() {
return;
}
}
let before = std::fs::read_to_string(hooks.join("pre-commit")).expect("read");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = s.install(&repo);
assert_eq!(code, 0, "refusing is not an error:\n{out}");
assert!(
out.contains("IS the checkout"),
"the refusal must be explained:\n{out}"
);
let after = std::fs::read_to_string(hooks.join("pre-commit")).expect("read");
assert_eq!(before, after, "TRACKED FILE WAS REWRITTEN");
assert!(
after.contains("__AMONT_BIN__"),
"the tracked placeholder was baked away"
);
}
#[cfg(unix)]
#[test]
fn a_template_dir_it_cannot_write_fails_the_install() {
use std::os::unix::fs::PermissionsExt;
if unsafe { libc_geteuid() } == 0 {
return;
}
let s = Sandbox::new("readonly");
let repo = s.path("repo");
init_repo(&repo);
let tpl = s.path(".config/git/git-templates/templates/hooks");
std::fs::create_dir_all(&tpl).expect("mkdir");
std::fs::set_permissions(&tpl, std::fs::Permissions::from_mode(0o555)).expect("chmod");
let (code, out) = s.install(&repo);
let _ = std::fs::set_permissions(&tpl, std::fs::Permissions::from_mode(0o755));
assert_ne!(code, 0, "a failed write reported success:\n{out}");
assert!(
out.contains("cannot write shims"),
"and did not say what failed:\n{out}"
);
}
#[cfg(unix)]
unsafe fn libc_geteuid() -> u32 {
extern "C" {
fn geteuid() -> u32;
}
unsafe { geteuid() }
}
fn run_verb(s: &Sandbox, cwd: &Path, args: &[&str]) -> (i32, String) {
let out = crate::common::amont_cmd()
.args(args)
.current_dir(cwd)
.env("HOME", &s.0)
.env("USERPROFILE", &s.0)
.env("XDG_CONFIG_HOME", s.path(".config"))
.output()
.expect("run amont");
(
out.status.code().unwrap_or(-1),
format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
),
)
}
#[test]
fn install_refuses_to_overwrite_a_hook_it_did_not_write() {
let s = Sandbox::new("foreign");
let repo = s.path("repo");
init_repo(&repo);
let mine = repo.join(".git/hooks/commit-msg");
std::fs::create_dir_all(repo.join(".git/hooks")).expect("mkdir");
std::fs::write(&mine, "#!/bin/sh\necho MY OWN HOOK\n").expect("write");
let (code, out) = s.install(&repo);
assert_ne!(code, 0, "a silent overwrite reported success:\n{out}");
assert!(out.contains("commit-msg"), "must name the file:\n{out}");
assert_eq!(
std::fs::read_to_string(&mine).expect("read"),
"#!/bin/sh\necho MY OWN HOOK\n",
"THEIR HOOK WAS OVERWRITTEN"
);
let (code, out) = run_verb(&s, &repo, &["install", "--force"]);
assert_eq!(code, 0, "{out}");
assert!(std::fs::read_to_string(&mine)
.expect("read")
.contains("amont"));
}
#[test]
fn a_hook_it_cannot_decode_is_refused_and_left_byte_identical() {
let s = Sandbox::new("binary-hook");
let repo = s.path("repo");
init_repo(&repo);
std::fs::create_dir_all(repo.join(".git/hooks")).expect("mkdir");
let theirs = repo.join(".git/hooks/pre-commit");
let bytes: Vec<u8> = vec![
0x7f, b'E', b'L', b'F', 0x02, 0x01, 0x01, 0x00, 0xff, 0xfe, 0x00,
];
std::fs::write(&theirs, &bytes).expect("write");
let (code, out) = s.install(&repo);
assert_ne!(code, 0, "a silent overwrite reported success:\n{out}");
assert!(
out.contains("not valid UTF-8"),
"the refusal must say what it could not read:\n{out}"
);
assert_eq!(
std::fs::read(&theirs).expect("read"),
bytes,
"THEIR COMPILED HOOK WAS OVERWRITTEN"
);
}
#[cfg(unix)]
#[test]
fn force_replaces_a_symlinked_hook_and_never_the_file_it_pointed_at() {
let s = Sandbox::new("write-through");
let repo = s.path("repo");
init_repo(&repo);
let dev = repo.join("devhooks");
std::fs::create_dir_all(&dev).expect("mkdir");
std::fs::create_dir_all(repo.join(".git/hooks")).expect("mkdir");
let names = [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
];
for name in names {
let target = dev.join(name);
std::fs::write(&target, format!("#!/bin/sh\n# PRECIOUS {name}\n")).expect("write");
std::os::unix::fs::symlink(&target, repo.join(".git/hooks").join(name)).expect("symlink");
}
git(&repo, &["add", "-A"]);
git(&repo, &["commit", "-qm", "seed"]);
let before: Vec<String> = names
.iter()
.map(|n| std::fs::read_to_string(dev.join(n)).expect("read"))
.collect();
let (code, out) = s.install(&repo);
assert_ne!(
code, 0,
"a write through a symlink reported success:\n{out}"
);
assert!(out.contains("symlink"), "the refusal must name it:\n{out}");
let (code, out) = run_verb(&s, &repo, &["install", "--force"]);
assert_eq!(code, 0, "{out}");
for (i, name) in names.iter().enumerate() {
assert_eq!(
std::fs::read_to_string(dev.join(name)).expect("read"),
before[i],
"THE WRITE WENT THROUGH THE LINK for {name}"
);
let hook = repo.join(".git/hooks").join(name);
assert!(
!std::fs::symlink_metadata(&hook)
.expect("stat")
.file_type()
.is_symlink(),
"{name} is still a symlink after --force"
);
assert!(
std::fs::read_to_string(&hook)
.expect("read")
.contains("amont"),
"{name} was not replaced with a shim"
);
}
}
#[test]
fn a_tracked_hooks_directory_is_refused_even_with_force() {
let s = Sandbox::new("tracked-hooks");
let repo = s.path("repo");
init_repo(&repo);
let dev = repo.join("devhooks");
std::fs::create_dir_all(&dev).expect("mkdir");
for name in [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
] {
std::fs::write(dev.join(name), format!("#!/bin/sh\n# tracked {name}\n")).expect("write");
}
git(&repo, &["add", "-A"]);
git(&repo, &["commit", "-qm", "seed"]);
git(&repo, &["config", "core.hooksPath", "devhooks"]);
let before = std::fs::read_to_string(dev.join("pre-commit")).expect("read");
for args in [&["install"][..], &["install", "--force"][..]] {
let (code, out) = run_verb(&s, &repo, args);
assert_ne!(code, 0, "{args:?} rewrote tracked source:\n{out}");
assert!(
out.contains("TRACKED") || out.contains("not ours") || out.contains("core.hooksPath"),
"{args:?} must say why:\n{out}"
);
assert_eq!(
std::fs::read_to_string(dev.join("pre-commit")).expect("read"),
before,
"TRACKED FILE WAS REWRITTEN by {args:?}"
);
}
}
#[test]
fn an_untracked_redirect_is_refused_and_names_the_remedy() {
let s = Sandbox::new("husky-redirect");
let repo = s.path("repo");
init_repo(&repo);
let husky = repo.join(".husky/_");
std::fs::create_dir_all(&husky).expect("mkdir");
std::fs::write(
husky.join("pre-commit"),
"#!/usr/bin/env sh\n. \"$(dirname \"$0\")/h\"\n",
)
.expect("write");
let before = std::fs::read_to_string(husky.join("pre-commit")).expect("read");
git(&repo, &["config", "core.hooksPath", ".husky/_"]);
for args in [&["install"][..], &["install", "--force"][..]] {
let (code, out) = run_verb(&s, &repo, args);
assert_ne!(
code, 0,
"{args:?} wrote into a redirected hooks dir:\n{out}"
);
assert!(
out.contains("core.hooksPath"),
"{args:?} must name the setting:\n{out}"
);
assert!(
out.contains("git config --unset core.hooksPath"),
"{args:?} must name the remedy:\n{out}"
);
assert!(out.contains("husky"), "{args:?} must name husky:\n{out}");
assert_eq!(
std::fs::read_to_string(husky.join("pre-commit")).expect("read"),
before,
"{args:?} overwrote husky's own hook"
);
assert!(
!repo.join(".git/hooks/pre-commit").exists(),
"{args:?} wrote a shim git would never dispatch"
);
}
}
#[test]
fn a_deliberate_redirect_with_stale_leftovers_is_still_installed() {
let s = Sandbox::new("benign-redirect-leftovers");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "setup install failed:\n{out}");
let tooling = repo.join("tooling/hooks");
std::fs::create_dir_all(&tooling).expect("mkdir");
for name in [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
] {
let shim = std::fs::read_to_string(repo.join(".git/hooks").join(name)).expect("read");
std::fs::write(tooling.join(name), shim).expect("write");
}
git(&repo, &["config", "core.hooksPath", "tooling/hooks"]);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(
code, 0,
"a deliberate redirect was refused over leftovers:\n{out}"
);
}
#[test]
fn a_redirect_with_only_stranded_shims_names_the_cleanup() {
let s = Sandbox::new("stranded-remedy");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "setup install failed:\n{out}");
let tooling = repo.join("tooling/hooks");
std::fs::create_dir_all(&tooling).expect("mkdir");
git(&repo, &["config", "core.hooksPath", "tooling/hooks"]);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_ne!(code, 0, "stranded shims must still refuse:\n{out}");
assert!(
out.contains("greengate uninstall"),
"the message must offer the stale-shim cleanup path:\n{out}"
);
assert!(
out.contains("git config --unset core.hooksPath"),
"and still name the dispatch remedy:\n{out}"
);
}
#[test]
fn uninstall_reaches_shims_left_in_a_redirected_dir() {
let s = Sandbox::new("uninstall-redirect");
let repo = s.path("repo");
init_repo(&repo);
let husky = repo.join(".husky/_");
std::fs::create_dir_all(&husky).expect("mkdir");
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "setup install failed:\n{out}");
let shim = std::fs::read_to_string(repo.join(".git/hooks/pre-commit")).expect("read");
std::fs::write(husky.join("pre-commit"), &shim).expect("write");
git(&repo, &["config", "core.hooksPath", ".husky/_"]);
let (code, out) = run_verb(&s, &repo, &["uninstall"]);
assert_eq!(code, 0, "uninstall failed:\n{out}");
assert!(
!husky.join("pre-commit").exists(),
"our shim was left behind in the redirected dir:\n{out}"
);
assert!(
!repo.join(".git/hooks/pre-commit").exists(),
"our shim was left behind in the repo's own dir:\n{out}"
);
}
#[cfg(unix)]
#[test]
fn a_write_that_cannot_happen_leaves_no_dispatchers_at_all() {
use std::os::unix::fs::PermissionsExt;
if unsafe { libc_geteuid() } == 0 {
return;
}
let s = Sandbox::new("halfwritten");
let repo = s.path("repo");
init_repo(&repo);
let hooks = repo.join(".git/hooks");
std::fs::create_dir_all(&hooks).expect("mkdir");
std::fs::set_permissions(&hooks, std::fs::Permissions::from_mode(0o555)).expect("chmod");
let (code, out) = s.install(&repo);
let _ = std::fs::set_permissions(&hooks, std::fs::Permissions::from_mode(0o755));
assert_ne!(code, 0, "a failed write reported success:\n{out}");
for name in [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
] {
assert!(
!hooks.join(name).exists(),
"{name} landed despite the install failing:\n{out}"
);
}
let leftovers: Vec<_> = std::fs::read_dir(&hooks)
.expect("readdir")
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(".amont-tmp-"))
.collect();
assert!(
leftovers.is_empty(),
"staging litter left behind: {leftovers:?}"
);
}
#[test]
fn force_names_what_it_overwrote() {
let s = Sandbox::new("force-names");
let repo = s.path("repo");
init_repo(&repo);
std::fs::create_dir_all(repo.join(".git/hooks")).expect("mkdir");
std::fs::write(
repo.join(".git/hooks/commit-msg"),
"#!/bin/sh\necho MY OWN HOOK\n",
)
.expect("write");
let (code, out) = run_verb(&s, &repo, &["install", "--force"]);
assert_eq!(code, 0, "{out}");
assert!(
out.contains("overwrote") && out.contains("commit-msg"),
"--force must say what it took:\n{out}"
);
assert_eq!(
out.matches("overwrote").count(),
1,
"--force reported overwrites that did not happen:\n{out}"
);
}
#[cfg(unix)]
#[test]
fn uninstall_refuses_a_template_dir_that_is_a_checkout() {
let s = Sandbox::new("uninstall-checkout");
let checkout = s.path("checkout");
init_repo(&checkout);
let hooks = checkout.join("templates/hooks");
std::fs::create_dir_all(&hooks).expect("mkdir");
for name in [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
] {
std::fs::write(
hooks.join(name),
"#!/bin/sh\n# git-templates hook shim.\nexec amont __AMONT_BIN__\n",
)
.expect("write");
}
git(&checkout, &["add", "-A"]);
git(&checkout, &["commit", "-qm", "seed"]);
let cfg = s.path(".config/git");
std::fs::create_dir_all(&cfg).expect("mkdir");
std::os::unix::fs::symlink(&checkout, cfg.join("git-templates")).expect("symlink");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["uninstall"]);
assert_eq!(code, 0, "refusing is not an error:\n{out}");
assert!(
out.contains("checkout") && out.contains("NOTHING"),
"the refusal must be explained:\n{out}"
);
assert!(
out.contains(
&checkout
.canonicalize()
.expect("canon")
.display()
.to_string()
),
"and must name the RESOLVED path, not the symlink:\n{out}"
);
for name in [
"commit-msg",
"post-commit",
"post-rewrite",
"pre-commit",
"pre-push",
"prepare-commit-msg",
] {
assert!(
hooks.join(name).is_file(),
"TRACKED FILE {name} WAS DELETED:\n{out}"
);
}
}
fn install_with_bin_dir(s: &Sandbox, cwd: &Path, bin_dir: &Path) -> (i32, String) {
let out = crate::common::amont_cmd()
.arg("install")
.current_dir(cwd)
.env("HOME", &s.0)
.env("USERPROFILE", &s.0)
.env("XDG_CONFIG_HOME", s.path(".config"))
.env("GREENGATE_BIN_DIR", bin_dir)
.output()
.expect("run amont install");
(
out.status.code().unwrap_or(-1),
format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
),
)
}
#[cfg(unix)]
fn checkout_template_dir(s: &Sandbox) -> Option<std::path::PathBuf> {
let checkout = s.path("checkout");
init_repo(&checkout);
let hooks = checkout.join("templates/hooks");
std::fs::create_dir_all(&hooks).expect("mkdir");
std::fs::write(hooks.join("pre-commit"), "precious __AMONT_BIN__\n").expect("write");
git(&checkout, &["add", "-A"]);
git(&checkout, &["commit", "-qm", "seed"]);
let cfg = s.path(".config/git");
std::fs::create_dir_all(&cfg).expect("mkdir");
std::os::unix::fs::symlink(&checkout, cfg.join("git-templates")).ok()?;
Some(checkout)
}
#[cfg(unix)]
#[test]
fn a_binary_an_unbaked_shim_cannot_find_is_named() {
let s = Sandbox::new("binhint");
if checkout_template_dir(&s).is_none() {
println!(" ! symlinks unavailable — skipping");
return;
}
let repo = s.path("repo");
init_repo(&repo);
let elsewhere = s.path("opt/tools");
std::fs::create_dir_all(&elsewhere).expect("mkdir");
let (code, out) = install_with_bin_dir(&s, &repo, &elsewhere);
assert_eq!(code, 0, "the install itself should still succeed:\n{out}");
assert!(
out.contains("unbaked shim will not find"),
"the unreachable binary was not flagged:\n{out}"
);
assert!(
out.contains("opt/tools"),
"did not name where it went:\n{out}"
);
assert!(
out.contains(".local/bin"),
"did not name where shims look:\n{out}"
);
assert!(out.contains("ln -s"), "offered no link:\n{out}");
assert!(
out.contains("GIT_HOOKS_BIN"),
"did not name the runtime override:\n{out}"
);
}
#[cfg(unix)]
#[test]
fn the_default_bin_dir_is_not_flagged() {
let s = Sandbox::new("binhint-default");
if checkout_template_dir(&s).is_none() {
println!(" ! symlinks unavailable — skipping");
return;
}
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = s.install(&repo);
assert_eq!(code, 0, "{out}");
assert!(
!out.contains("unbaked shim will not find"),
"warned about the default layout, which is the whole fleet:\n{out}"
);
}
fn install_on_path(s: &Sandbox, cwd: &Path, path: &str) -> (i32, String) {
let out = crate::common::amont_cmd()
.arg("install")
.current_dir(cwd)
.env("HOME", &s.0)
.env("USERPROFILE", &s.0)
.env("XDG_CONFIG_HOME", s.path(".config"))
.env_remove("GREENGATE_BIN_DIR")
.env("PATH", path)
.output()
.expect("run amont install");
(
out.status.code().unwrap_or(-1),
format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
),
)
}
fn baked_in(repo: &Path) -> String {
let shim = std::fs::read_to_string(repo.join(".git/hooks/pre-commit")).expect("read shim");
shim.lines()
.find_map(|l| l.trim().strip_prefix("BAKED=\""))
.and_then(|l| l.strip_suffix('"'))
.map(str::to_string)
.unwrap_or_else(|| panic!("no baked path in the shim:\n{shim}"))
}
#[test]
fn a_binary_already_on_path_is_not_copied() {
let s = Sandbox::new("onpath");
let repo = s.path("repo");
init_repo(&repo);
let pkg = s.path("pkg/bin");
std::fs::create_dir_all(&pkg).expect("mkdir");
let placed = pkg.join(if cfg!(windows) {
"greengate.exe"
} else {
"greengate"
});
std::fs::copy(env!("CARGO_BIN_EXE_greengate"), &placed).expect("copy");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&placed, std::fs::Permissions::from_mode(0o755)).expect("chmod");
}
let (code, out) = run_from(&s, &placed, &repo, &pkg.to_string_lossy());
assert_eq!(code, 0, "{out}");
let baked = baked_in(&repo);
assert_eq!(
std::path::Path::new(&baked).canonicalize().ok(),
placed.canonicalize().ok(),
"did not bake the binary where it already was (baked {baked}):\n{out}"
);
assert!(
!s.path(".local/bin/greengate").exists() && !s.path(".local/bin/amont").exists(),
"made a second copy the package manager will never update:\n{out}"
);
assert!(
out.contains("nothing was copied"),
"did not say it skipped the copy:\n{out}"
);
}
#[cfg(unix)]
#[test]
fn a_symlink_on_path_bakes_the_link_not_its_versioned_target() {
let s = Sandbox::new("brewshape");
let repo = s.path("repo");
init_repo(&repo);
let cellar = s.path("cellar/1.0.0/bin");
let bin = s.path("brew/bin");
std::fs::create_dir_all(&cellar).expect("mkdir");
std::fs::create_dir_all(&bin).expect("mkdir");
let real = cellar.join("greengate");
std::fs::copy(env!("CARGO_BIN_EXE_greengate"), &real).expect("copy");
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o755)).expect("chmod");
}
let link = bin.join("greengate");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
let (code, out) = run_from(&s, &link, &repo, &bin.to_string_lossy());
assert_eq!(code, 0, "{out}");
let baked = baked_in(&repo);
assert!(
!baked.contains("/1.0.0/"),
"baked the VERSIONED path, which the next upgrade deletes: {baked}"
);
assert!(
baked.ends_with("brew/bin/greengate"),
"expected the PATH entry, got {baked}"
);
}
#[test]
fn a_binary_not_on_path_is_still_copied() {
let s = Sandbox::new("notonpath");
let repo = s.path("repo");
init_repo(&repo);
let inherited = std::env::var("PATH").unwrap_or_default();
let (code, out) = install_on_path(&s, &repo, &inherited);
assert_eq!(code, 0, "{out}");
let copied = s.path(".local/bin/greengate");
assert!(
copied.exists() || s.path(".local/bin/greengate.exe").exists(),
"a binary that is not on PATH must still be copied somewhere stable:\n{out}"
);
let alias = s.path(".local/bin/amont");
assert!(
alias.exists() || s.path(".local/bin/amont.exe").exists(),
"the amont alias was not written beside it:\n{out}"
);
}
#[test]
fn amont_bin_dir_still_forces_a_copy() {
let s = Sandbox::new("forcedcopy");
let repo = s.path("repo");
init_repo(&repo);
let elsewhere = s.path("opt/bin");
std::fs::create_dir_all(&elsewhere).expect("mkdir");
let (code, out) = install_with_bin_dir(&s, &repo, &elsewhere);
assert_eq!(code, 0, "{out}");
assert!(
elsewhere.join("greengate").exists() || elsewhere.join("greengate.exe").exists(),
"GREENGATE_BIN_DIR was ignored:\n{out}"
);
}
fn run_from(s: &Sandbox, exe: &Path, cwd: &Path, dir: &str) -> (i32, String) {
let mut cmd = Command::new(exe);
cmd.arg("install")
.current_dir(cwd)
.env("HOME", &s.0)
.env("USERPROFILE", &s.0)
.env("XDG_CONFIG_HOME", s.path(".config"))
.env_remove("GREENGATE_BIN_DIR")
.env("PATH", path_with(dir));
let out = output_retrying_etxtbsy(&mut cmd).expect("run amont install");
(
out.status.code().unwrap_or(-1),
format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
),
)
}
#[test]
fn a_build_directory_on_path_is_not_baked() {
let s = Sandbox::new("builddir");
let repo = s.path("repo");
init_repo(&repo);
let build = s.path("proj/target/debug");
std::fs::create_dir_all(&build).expect("mkdir");
std::fs::write(
s.path("proj/target/CACHEDIR.TAG"),
"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.expect("write tag");
let placed = build.join(if cfg!(windows) {
"greengate.exe"
} else {
"greengate"
});
std::fs::copy(env!("CARGO_BIN_EXE_greengate"), &placed).expect("copy");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&placed, std::fs::Permissions::from_mode(0o755)).expect("chmod");
}
let (code, out) = run_from(&s, &placed, &repo, &build.to_string_lossy());
assert_eq!(code, 0, "{out}");
let baked = baked_in(&repo);
assert!(
!baked.contains("target"),
"baked a build directory, which the next rebuild empties: {baked}"
);
assert!(
s.path(".local/bin/greengate").exists() || s.path(".local/bin/greengate.exe").exists(),
"and did not copy it somewhere durable instead:\n{out}"
);
}
fn path_with(dir: &str) -> std::ffi::OsString {
let inherited = std::env::var_os("PATH").unwrap_or_default();
let mut dirs = vec![std::path::PathBuf::from(dir)];
dirs.extend(std::env::split_paths(&inherited));
std::env::join_paths(dirs).expect("join PATH")
}
fn snapshot(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir(dir) else {
return out;
};
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
out.extend(snapshot(&p));
} else {
out.push((p.clone(), std::fs::read(&p).expect("read")));
}
}
out.sort();
out
}
fn template_hooks_dir(s: &Sandbox, repo: &Path) -> PathBuf {
let (code, out) = run_verb(s, repo, &["list", "--json"]);
assert_eq!(code, 0, "list --json failed:\n{out}");
let tail = out
.split("\"template_dir\":")
.nth(1)
.expect("template_dir field");
let dir = tail.split("\"hooks_dir\":\"").nth(1).expect("hooks_dir");
PathBuf::from(dir.split('"').next().expect("closing quote"))
}
#[test]
fn uninstall_repo_leaves_the_template_dir_and_global_config_untouched() {
let s = Sandbox::new("uninstall-repo");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "setup install failed:\n{out}");
let gitconfig = s.path(".gitconfig");
let config_before = std::fs::read(&gitconfig).ok();
let templates = template_hooks_dir(&s, &repo);
let before = snapshot(&templates);
assert!(
!before.is_empty(),
"install filled no template dir at {}",
templates.display()
);
let (code, out) = run_verb(&s, &repo, &["uninstall", "--repo"]);
assert_eq!(code, 0, "uninstall --repo failed:\n{out}");
assert!(
!repo.join(".git/hooks/pre-commit").exists(),
"the repo shim survived:\n{out}"
);
assert_eq!(
snapshot(&templates),
before,
"the template dir changed:\n{out}"
);
assert_eq!(
std::fs::read(&gitconfig).ok(),
config_before,
"the global git config changed"
);
}
#[test]
fn uninstall_repo_without_a_template_dir_creates_none() {
let s = Sandbox::new("uninstall-repo-none");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "setup install failed:\n{out}");
let templates = template_hooks_dir(&s, &repo);
std::fs::remove_dir_all(&templates).expect("remove template dir");
let (code, out) = run_verb(&s, &repo, &["uninstall", "--repo"]);
assert_eq!(code, 0, "uninstall --repo failed:\n{out}");
assert!(
!templates.exists(),
"uninstall --repo created {}",
templates.display()
);
assert!(!repo.join(".git/hooks/pre-commit").exists());
}
#[test]
fn uninstall_repo_and_binary_together_are_a_usage_error() {
let s = Sandbox::new("uninstall-repo-binary");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["uninstall", "--repo", "--binary"]);
assert_eq!(code, 2, "{out}");
assert!(out.contains("mutually exclusive"), "{out}");
}
#[test]
fn list_json_reports_the_installed_shims() {
let s = Sandbox::new("list-installed");
let repo = s.path("repo");
init_repo(&repo);
let state = |cwd: &Path| {
let (code, out) = run_verb(&s, cwd, &["list", "--json"]);
let tail = out
.split("\"installed\":{\"state\":\"")
.nth(1)
.map(str::to_string);
(
code,
tail.and_then(|t| t.split('"').next().map(str::to_string)),
out,
)
};
let (_, st, out) = state(&repo);
assert_eq!(st.as_deref(), Some("absent"), "{out}");
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "install failed:\n{out}");
let (_, st, out) = state(&repo);
assert_eq!(st.as_deref(), Some("present"), "{out}");
let installed = out
.split("\"template_dir\":")
.next()
.expect("installed part");
let binaries: Vec<String> = installed
.split("\"binary\":")
.skip(1)
.map(|rest| {
let value = rest.strip_prefix('"').expect("a string, not null");
value[..value.find('"').expect("closing quote")].replace("\\\\", "\\")
})
.collect();
assert_eq!(binaries.len(), 6, "{out}");
for binary in &binaries {
assert!(
Path::new(binary).is_absolute(),
"{binary} is not absolute:\n{out}"
);
}
std::fs::remove_file(repo.join(".git/hooks/post-commit")).expect("remove one shim");
let (_, st, out) = state(&repo);
assert_eq!(st.as_deref(), Some("partial"), "{out}");
let outside = s.path("plain");
std::fs::create_dir_all(&outside).expect("mkdir");
let (_, st, out) = state(&outside);
assert_eq!(st.as_deref(), Some("unknown"), "{out}");
}
#[cfg(unix)]
#[test]
fn an_unreadable_hook_reports_unknown() {
use std::os::unix::fs::PermissionsExt;
if unsafe { libc_geteuid() } == 0 {
return; }
let s = Sandbox::new("list-unreadable");
let repo = s.path("repo");
init_repo(&repo);
let (code, out) = run_verb(&s, &repo, &["install"]);
assert_eq!(code, 0, "install failed:\n{out}");
let hook = repo.join(".git/hooks/pre-commit");
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o000)).expect("chmod");
let (_, out) = run_verb(&s, &repo, &["list", "--json"]);
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).expect("chmod back");
assert!(
out.contains("\"installed\":{\"state\":\"unknown\""),
"{out}"
);
}