greengate_runtime/pushed_tree.rs
1//! Run a pre-push check against what is being PUSHED.
2//!
3//! `rust-test` and `run-tests-js` take their file set from the pushed refs —
4//! correct — and then run the suite with `current_dir` set to the developer's
5//! working tree. So the suite can pass on an uncommitted fix, or fail on an
6//! uncommitted experiment, and in neither case has it tested the commits being
7//! pushed. Same gap as the pre-commit one, from the other end.
8//!
9//! ## Why not the stash
10//!
11//! Holding unstaged changes aside is the pre-commit answer, and it is the wrong
12//! instrument here. A push is not a staging operation: the difference that
13//! matters is not tree-versus-index but tree-versus-the-commit-you-are-sending,
14//! and that includes everything staged-but-uncommitted too. Setting all of it
15//! aside for the length of a test suite would leave the developer looking at a
16//! tree that is not theirs for minutes at a time.
17//!
18//! ## What it costs, which is the whole question
19//!
20//! `git worktree add --detach <tip>` materialises the pushed commit somewhere
21//! else and the suite runs there. The tree is untouched, and an interrupted run
22//! leaves a worktree rather than a mangled checkout.
23//!
24//! The cost is real: a second checkout, and a build that cannot reuse the
25//! primary tree's `target/` cache, so the first push after this lands is a cold
26//! build. That is why it is opt-in — `git config greengate.testPushedTree true`
27//! — rather than the default. The default keeps today's behaviour and now SAYS
28//! what it is testing, which was the actual bug: not that it used the tree, but
29//! that nobody knew it did.
30
31use std::path::{Path, PathBuf};
32
33use crate::hooks::common::unique_name;
34use crate::ui::warning_sign;
35
36/// Whether the user asked for the accurate-but-slower answer.
37///
38/// Read through [`crate::config`], so `on`, `yes` and every capitalisation work
39/// exactly as git-config(1) says they do — and a value git cannot parse takes
40/// the default while SAYING so, rather than reading as a quiet "no".
41pub fn enabled(settings: &crate::config::Settings) -> bool {
42 crate::config::boolean_or(settings, "greengate.testPushedTree", false)
43}
44
45/// The escape hatch: a command to run inside a fresh snapshot before any
46/// suite does, after amont's own preparation (see [`crate::snapshot_prep`]:
47/// `greengate.snapshotCarry`, then the JavaScript dependencies).
48///
49/// A checkout is not a workspace, and most of what makes one is now
50/// amont's: `npm ci` / `pnpm install --frozen-lockfile` per lockfile, and
51/// the untracked files the repository names. What is left is per-repository
52/// knowledge amont cannot have — a code generator, a database client, a
53/// build step:
54///
55/// ```sh
56/// git config greengate.snapshotPrepare "pnpm prisma generate"
57/// ```
58///
59/// When it is set it OWNS the dependencies — amont's own install step stands
60/// down, so a repository that already installs here does not install twice.
61/// Runs through the shell, in the snapshot, before the gate, and a failure
62/// is the snapshot's failure: no suite runs on a tree that was never made
63/// runnable. Used by both snapshot consumers — `greengate.testPushedTree` at
64/// push time and the background rehearsal — so the two cannot drift. It gets
65/// `GREENGATE_SOURCE_WORKTREE`: the working tree the snapshot was taken from.
66const PREPARE: &str = "greengate.snapshotPrepare";
67
68/// The environment variable naming the source working tree (see PREPARE).
69pub const SOURCE_WORKTREE_ENV: &str = "GREENGATE_SOURCE_WORKTREE";
70
71/// Set to `1` on what a snapshot runs to prepare itself — the dependency
72/// install and `greengate.snapshotPrepare` — for a custom `prepare` script that
73/// wants to know. INFORMATION, not the guard: the guard is `MARKER`, a file
74/// in the snapshot's git dir, which cannot leak into another repository the
75/// way an inherited variable does.
76pub const SNAPSHOT_ENV: &str = "GREENGATE_SNAPSHOT";
77
78/// The file a push snapshot carries in its OWN git admin dir
79/// (`<common>/worktrees/<name>/`), which `amont init` reads before baking.
80///
81/// Why it exists: the snapshot is a linked worktree, so it shares the
82/// repository's hooks directory, and its dependency install runs `prepare` —
83/// `amont init` — which baked every hook to a binary inside the snapshot,
84/// deleted minutes later. Why a file there and not an environment variable:
85/// that admin dir is the snapshot's alone and dies with it, so every process
86/// run inside the snapshot sees it (the install, `snapshotPrepare`, an
87/// install a gate runs itself) and a fixture repository amont's own suite
88/// creates does not. `GREENGATE_REHEARSAL` could not serve: it is removed before
89/// any gate spawns (`rehearsal::in_snapshot`), deliberately.
90///
91/// Both halves must be a version carrying this: an older runner writes no
92/// marker, and an older pinned `init` does not read one.
93const MARKER: &str = "greengate-snapshot";
94
95/// Where `dir`'s snapshot marker lives, absolute. `Err` carries git's own
96/// reason when it would not say. The `GIT_*` environment is stripped: a
97/// hook's `GIT_DIR` names the repository the hook runs for, not the
98/// snapshot being asked about.
99fn snapshot_marker_path(dir: &Path) -> std::io::Result<PathBuf> {
100 let mut cmd = std::process::Command::new("git");
101 cmd.arg("-C")
102 .arg(dir)
103 .args(["rev-parse", "--path-format=absolute", "--git-path", MARKER])
104 .stdin(std::process::Stdio::null());
105 crate::hooks::common::strip_git_env(&mut cmd);
106 let out = cmd.output()?;
107 if !out.status.success() {
108 let why = String::from_utf8_lossy(&out.stderr);
109 let why = why
110 .lines()
111 .find(|l| !l.trim().is_empty())
112 .unwrap_or("no reason given");
113 return Err(std::io::Error::other(format!(
114 "git would not say where the snapshot marker lives: {}",
115 crate::ui::sanitize(why)
116 )));
117 }
118 let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
119 if p.is_empty() {
120 return Err(std::io::Error::other(
121 "git gave an empty path for the snapshot marker",
122 ));
123 }
124 let p = PathBuf::from(p);
125 Ok(if p.is_absolute() { p } else { dir.join(p) })
126}
127
128/// Is the marker at `path`? Three answers, not two: `Path::exists` folds
129/// "cannot look" into "absent", and absent is the answer that bakes.
130pub fn probe_marker(path: &Path) -> std::io::Result<bool> {
131 match std::fs::symlink_metadata(path) {
132 Ok(_) => Ok(true),
133 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
134 Err(e) => Err(e),
135 }
136}
137
138/// Is `dir` inside a greengate push snapshot? `Err` when that cannot be told —
139/// which the caller must treat as "do not write", never as "no".
140pub fn in_push_snapshot(dir: &Path) -> std::io::Result<bool> {
141 probe_marker(&snapshot_marker_path(dir)?)
142}
143
144/// Mark the snapshot at `dir` as one. Resolving the path is part of the
145/// mark: a snapshot whose marker could not even be located is unmarked.
146fn mark_snapshot(dir: &Path) -> std::io::Result<()> {
147 std::fs::write(snapshot_marker_path(dir)?, b"")
148}
149
150pub fn prepare_command(settings: &crate::config::Settings) -> Option<String> {
151 crate::config::string_value(settings, PREPARE).filter(|s| !s.trim().is_empty())
152}
153
154/// A checkout of the pushed commit, removed when it goes out of scope.
155pub struct PushedTree {
156 path: PathBuf,
157 repo: PathBuf,
158 /// The commit checked out — what preparation scopes the push by.
159 tip: String,
160}
161
162impl PushedTree {
163 /// Materialise `tip`, or `None` when that is not possible — in which case
164 /// the caller falls back to the working tree and says so.
165 /// Takes the repository explicitly rather than relying on the working
166 /// directory: `set_current_dir` is process-global, so a test that changed
167 /// it would race every other test in the binary.
168 ///
169 /// Checkout AND preparation, for the push-time caller: a snapshot that
170 /// could not be prepared is no snapshot, said once, here.
171 pub fn create(
172 settings: &crate::config::Settings,
173 repo: &Path,
174 tip: &str,
175 ) -> Option<PushedTree> {
176 let tree = Self::checkout(repo, tip)?;
177 match tree.prepare(settings) {
178 Ok(()) => Some(tree),
179 Err(why) => {
180 // `Drop` removes the worktree; the caller hears `None` and
181 // says what it is doing instead.
182 println!("{} could not prepare the snapshot: {why}", warning_sign());
183 None
184 }
185 }
186 }
187
188 /// The checkout alone. The rehearsal registers itself between this and
189 /// [`PushedTree::prepare`], so an install that takes minutes is visible —
190 /// to `--status`, to a push that would otherwise start over, and to a
191 /// newer commit that must cancel it.
192 pub fn checkout(repo: &Path, tip: &str) -> Option<PushedTree> {
193 let base = std::env::temp_dir().join(unique_name("greengate-push"));
194 Self::checkout_at(base, repo, tip)
195 }
196
197 /// The actual work, over an explicit path — split out so a test can hand
198 /// it a path it controls, since `create`'s own path is unpredictable BY
199 /// DESIGN and cannot be aimed at a fixture.
200 ///
201 /// `create_dir`, not a `remove_dir_all` before creating: that deleted
202 /// whatever was already at this path BEFORE this process had established
203 /// it owned it — an unpredictable name makes landing on an existing path
204 /// unlikely, not impossible, and "unlikely" is not the bar for a delete.
205 /// `create_dir` is exclusive: it fails loudly on anything already there
206 /// instead of removing it, and git's own `worktree add` is content to
207 /// receive a directory that already exists as long as it is empty —
208 /// which this one, having just been created, provably is.
209 fn checkout_at(base: PathBuf, repo: &Path, tip: &str) -> Option<PushedTree> {
210 Self::checkout_at_with(base, repo, tip, &mark_snapshot)
211 }
212
213 /// [`checkout_at`] with the marker writer passed in — a parameter, not a
214 /// global switch, so a test can make it fail without racing the other
215 /// tests in the binary.
216 fn checkout_at_with(
217 base: PathBuf,
218 repo: &Path,
219 tip: &str,
220 mark: &dyn Fn(&Path) -> std::io::Result<()>,
221 ) -> Option<PushedTree> {
222 std::fs::create_dir(&base).ok()?;
223 let ok = crate::git::succeeds(&[
224 "-C",
225 repo.to_str()?,
226 "worktree",
227 "add",
228 "--detach",
229 "--quiet",
230 base.to_str()?,
231 tip,
232 ]);
233 if !ok {
234 // Ours to clean up: we created it moments ago, so nothing else
235 // could have raced in ahead of us to make this delete unsafe.
236 let _ = std::fs::remove_dir_all(&base);
237 return None;
238 }
239 let tree = PushedTree {
240 path: base,
241 repo: repo.to_path_buf(),
242 tip: tip.to_string(),
243 };
244 // Fail closed: an unmarked snapshot is one whose install re-bakes the
245 // repository's hooks to itself. `Drop` unregisters the worktree git
246 // has already recorded and removes the directory.
247 if let Err(e) = mark(&tree.path) {
248 println!("{} could not mark the snapshot: {e}", warning_sign());
249 return None;
250 }
251 Some(tree)
252 }
253
254 /// Make the checkout runnable: carry, dependencies, then
255 /// `greengate.snapshotPrepare`. `Err` says why, in one line.
256 pub fn prepare(&self, settings: &crate::config::Settings) -> Result<(), String> {
257 let script = prepare_command(settings);
258 crate::snapshot_prep::run(
259 settings,
260 &self.repo,
261 &self.path,
262 &self.tip,
263 script.is_some(),
264 )?;
265 let Some(script) = script else {
266 return Ok(());
267 };
268 println!("preparing the snapshot: {script}");
269 #[cfg(unix)]
270 let mut cmd = {
271 let mut c = std::process::Command::new("sh");
272 c.arg("-c").arg(&script);
273 c
274 };
275 #[cfg(not(unix))]
276 let mut cmd = {
277 let mut c = std::process::Command::new("cmd");
278 c.arg("/C").arg(&script);
279 c
280 };
281 cmd.current_dir(&self.path)
282 .stdin(std::process::Stdio::null());
283 crate::hooks::common::strip_git_env(&mut cmd);
284 // the working tree the snapshot was taken FROM — where an installed
285 // workspace already lives (see PREPARE)
286 cmd.env(SOURCE_WORKTREE_ENV, &self.repo);
287 cmd.env(SNAPSHOT_ENV, "1");
288 if crate::hooks::common::bounded_success(settings, &mut cmd, PREPARE) {
289 Ok(())
290 } else {
291 Err(format!("{PREPARE} failed in the snapshot"))
292 }
293 }
294
295 pub fn path(&self) -> &Path {
296 &self.path
297 }
298}
299
300impl Drop for PushedTree {
301 fn drop(&mut self) {
302 // `--force`: the suite may have written into it, and a build artefact
303 // must not be a reason to leave a worktree registered forever.
304 let _ = crate::git::succeeds(&[
305 "-C",
306 self.repo.to_str().unwrap_or_default(),
307 "worktree",
308 "remove",
309 "--force",
310 self.path.to_str().unwrap_or_default(),
311 ]);
312 let _ = std::fs::remove_dir_all(&self.path);
313 }
314}
315
316/// `(gate, tip)` pairs whose suite ACTUALLY ran in a checkout of `tip` —
317/// what happened, per check, as opposed to what `enabled()` says was asked
318/// for.
319///
320/// Read by `dispatch::stamp_tips`. It used to decide from the CONFIG plus a
321/// per-tip "the snapshot could not be made" set, which answers for the
322/// checks that asked for a snapshot and says nothing about one that never
323/// did: a declared `amont.conf` gate ran in the working tree, passed on an
324/// uncommitted fix, and was stamped onto a tip that had never been tested —
325/// so the next push of that tip skipped it. A stamp is a claim about one
326/// gate and one tree, and the record it is made from has to be that fine.
327///
328/// A `Mutex` because pre-push checks run concurrently and each loops over its
329/// own refs; a poisoned lock reads as "did not run there", which costs a
330/// redundant gate run and never a false stamp.
331static SNAPSHOTTED: std::sync::OnceLock<
332 std::sync::Mutex<std::collections::HashSet<(String, String)>>,
333> = std::sync::OnceLock::new();
334
335fn snapshotted() -> &'static std::sync::Mutex<std::collections::HashSet<(String, String)>> {
336 SNAPSHOTTED.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
337}
338
339fn note_snapshot(gate: &str, tip: &str) {
340 if let Ok(mut set) = snapshotted().lock() {
341 set.insert((gate.to_string(), tip.to_string()));
342 }
343}
344
345/// Did `gate` run in a checkout of `tip` — the pushed content itself, not
346/// whatever the working tree held?
347///
348/// `false` also when the lock is poisoned: a stamp is a claim that the gate
349/// ran on exactly this content, and a claim we cannot check is one we do not
350/// make.
351pub fn ran_on_tip(gate: &str, tip: &str) -> bool {
352 match snapshotted().lock() {
353 Ok(set) => set.contains(&(gate.to_string(), tip.to_string())),
354 Err(_) => false,
355 }
356}
357
358/// Where a pre-push suite should run, and whether that is the honest answer.
359///
360/// Takes ONE commit, not the whole ref list: a push can carry several refs
361/// (`git push origin a b`), each with its own tip, and a caller that checked
362/// out only the first one and ran every ref's tests against it would test
363/// the second ref's code against the first ref's tree. Callers loop over
364/// their own refs and pass each one's tip in turn.
365///
366/// `gate` is the check's id (`Check::name`) — what a stamp names, and what
367/// [`ran_on_tip`] is asked about when `dispatch::stamp_tips` decides whether
368/// this gate may vouch for this tip. A check that runs a suite anywhere
369/// else than the directory returned here is answering about content no
370/// stamp may claim.
371///
372/// Returns the directory plus the guard that owns it — dropping the guard
373/// removes the worktree, so the caller must hold it for the length of the run.
374pub fn where_to_run(
375 settings: &crate::config::Settings,
376 tip: &str,
377 fallback: &str,
378 gate: &str,
379) -> (PathBuf, Option<PushedTree>) {
380 // Inside a rehearsal the working tree IS a snapshot of the tip: a
381 // second checkout would test the same content twice, and the warning
382 // below would be false.
383 if crate::rehearsal::in_snapshot() {
384 return (PathBuf::from(fallback), None);
385 }
386 if !enabled(settings) {
387 // Today's behaviour, but no longer silent about it. NOT a fallback:
388 // nobody asked for a snapshot, and `stamp_tips` already knows to
389 // vouch for the working tree only when it IS the tip.
390 //
391 // Once per process: every gate in the push asks this, and one line
392 // says it — the fourth repetition would teach the reader to skip it.
393 static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
394 if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
395 println!(
396 "{} testing the WORKING TREE, not the pushed commits \
397 (`git config greengate.testPushedTree true` to test what you are pushing)",
398 warning_sign()
399 );
400 }
401 return (PathBuf::from(fallback), None);
402 }
403 match PushedTree::create(settings, Path::new(fallback), tip) {
404 Some(tree) => {
405 // Recorded, not inferred. `stamp_tips` used to read `enabled()`
406 // and conclude "the suite ran on the tip itself" — for every
407 // gate, including ones that never came here. Only a gate that
408 // was handed this checkout can be said to have run in it.
409 note_snapshot(gate, tip);
410 let path = tree.path().to_path_buf();
411 (path, Some(tree))
412 }
413 None => {
414 // Not recorded, and that IS the record: the gate passed on a
415 // possibly-dirty working tree, and stamping the tip anyway —
416 // which reading the config would do — let the next push of that
417 // tree (a retry after a dropped connection, or a tag on the
418 // merged commit) skip a gate nobody had run on its content.
419 // `gate_stamp`'s own promise is that no path here can let an
420 // unchecked commit through.
421 println!(
422 "{} could not check out {tip} to test it; testing the working tree instead \
423 (nothing will be stamped for it)",
424 warning_sign()
425 );
426 (PathBuf::from(fallback), None)
427 }
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434
435 fn test_settings() -> crate::config::Settings {
436 crate::config::Settings::default()
437 }
438
439 /// The whole point: two calls must not name the same path, or a
440 /// predictable name is right back to being predictable.
441 #[test]
442 fn unique_name_does_not_repeat() {
443 let first_name = unique_name("greengate-push");
444 let second_name = unique_name("greengate-push");
445 assert_ne!(first_name, second_name);
446 assert!(first_name.starts_with("greengate-push-"));
447 }
448
449 /// The point of the whole fix: something already at the target path is
450 /// left ALONE, not deleted to make way. `create_at` fails closed
451 /// (`None`) instead of the old `remove_dir_all`-first shape, which would
452 /// have destroyed `sentinel.txt` here to clear the path for a worktree
453 /// that was never going to use it anyway (the repo below is fake).
454 #[test]
455 fn an_existing_path_is_left_alone_not_cleared() {
456 let base = std::env::temp_dir().join(format!("pushed-collision-{}", std::process::id()));
457 let _ = std::fs::remove_dir_all(&base);
458 std::fs::create_dir_all(&base).unwrap();
459 std::fs::write(base.join("sentinel.txt"), "do not delete me").unwrap();
460
461 let got = PushedTree::checkout_at(base.clone(), Path::new("/does/not/matter"), "HEAD");
462 assert!(
463 got.is_none(),
464 "must refuse rather than reuse a path it did not create"
465 );
466 assert_eq!(
467 std::fs::read_to_string(base.join("sentinel.txt")).unwrap(),
468 "do not delete me",
469 "an existing path must never be cleared to make room"
470 );
471 let _ = std::fs::remove_dir_all(&base);
472 }
473
474 fn repo(name: &str) -> PathBuf {
475 let d = std::env::temp_dir().join(format!("pushed-{name}-{}", std::process::id()));
476 let _ = std::fs::remove_dir_all(&d);
477 std::fs::create_dir_all(&d).unwrap();
478 for args in [
479 vec!["init", "-q", "--template=", "."],
480 vec!["config", "user.email", "t@t.test"],
481 vec!["config", "user.name", "t"],
482 // Git for Windows rewrites line endings on checkout; a byte
483 // comparison would otherwise assert git's newline policy.
484 vec!["config", "core.autocrlf", "false"],
485 ] {
486 std::process::Command::new("git")
487 .args(&args)
488 .current_dir(&d)
489 .output()
490 .expect("git");
491 }
492 d
493 }
494
495 /// The point: the checkout holds the COMMIT, not whatever the developer
496 /// has open.
497 #[test]
498 fn the_worktree_holds_the_committed_content() {
499 let d = repo("tree");
500 let git = |args: &[&str]| {
501 std::process::Command::new("git")
502 .args(args)
503 .current_dir(&d)
504 .output()
505 .expect("git")
506 };
507 std::fs::write(d.join("a.txt"), "committed\n").unwrap();
508 git(&["add", "-A"]);
509 git(&["commit", "-qm", "seed"]);
510 let head = String::from_utf8_lossy(&git(&["rev-parse", "HEAD"]).stdout)
511 .trim()
512 .to_string();
513 // Uncommitted, and it must not travel.
514 std::fs::write(d.join("a.txt"), "dirty, not pushed\n").unwrap();
515
516 let tree = PushedTree::create(&test_settings(), &d, &head).expect("worktree");
517 let seen = std::fs::read_to_string(tree.path().join("a.txt")).unwrap();
518 let at = tree.path().to_path_buf();
519 drop(tree);
520
521 assert_eq!(seen, "committed\n", "the worktree saw the dirty tree");
522 assert!(!at.exists(), "the worktree outlived its guard");
523 let _ = std::fs::remove_dir_all(&d);
524 }
525
526 fn seeded(name: &str) -> (PathBuf, String) {
527 let d = repo(name);
528 let git = |args: &[&str]| {
529 std::process::Command::new("git")
530 .args(args)
531 .current_dir(&d)
532 .output()
533 .expect("git")
534 };
535 git(&["commit", "--allow-empty", "-qm", "seed"]);
536 let head = String::from_utf8_lossy(&git(&["rev-parse", "HEAD"]).stdout)
537 .trim()
538 .to_string();
539 (d, head)
540 }
541
542 /// The snapshot carries the marker in its own admin dir; the repository
543 /// it was taken from does not — the marker is per-worktree, not shared.
544 #[test]
545 fn a_snapshot_is_marked_and_its_source_is_not() {
546 let (d, head) = seeded("marked");
547 let tree = PushedTree::checkout(&d, &head).expect("worktree");
548 assert!(in_push_snapshot(tree.path()).expect("probe"));
549 assert!(!in_push_snapshot(&d).expect("probe"));
550 drop(tree);
551 let _ = std::fs::remove_dir_all(&d);
552 }
553
554 /// Fail closed: a snapshot that could not be marked would re-bake the
555 /// repository's hooks to itself, so it is no snapshot — and git's
556 /// registration of it is undone, not just the directory.
557 #[test]
558 fn an_unmarkable_snapshot_is_no_snapshot() {
559 let (d, head) = seeded("unmarkable");
560 let base = std::env::temp_dir().join(unique_name("greengate-push-unmarkable"));
561 let name = base.file_name().unwrap().to_string_lossy().into_owned();
562 let got = PushedTree::checkout_at_with(base.clone(), &d, &head, &|_| {
563 Err(std::io::Error::other("cannot mark"))
564 });
565 assert!(got.is_none(), "an unmarked snapshot was handed out");
566 assert!(
567 !base.exists(),
568 "the snapshot directory outlived the refusal"
569 );
570 let list = std::process::Command::new("git")
571 .args(["worktree", "list", "--porcelain"])
572 .current_dir(&d)
573 .output()
574 .expect("git");
575 let list = String::from_utf8_lossy(&list.stdout);
576 assert!(!list.contains(&name), "still registered:\n{list}");
577 let _ = std::fs::remove_dir_all(&d);
578 }
579
580 #[cfg(unix)]
581 fn is_root() -> bool {
582 std::process::Command::new("id")
583 .arg("-u")
584 .output()
585 .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "0")
586 .unwrap_or(false)
587 }
588
589 /// Three answers, not two. A marker that cannot be looked at is an
590 /// error — `Path::exists` would have said "absent", which bakes.
591 #[cfg(unix)]
592 #[test]
593 fn a_marker_that_cannot_be_looked_at_is_an_error_not_absent() {
594 use std::os::unix::fs::PermissionsExt;
595 if is_root() {
596 eprintln!("skipped: root ignores directory permissions");
597 return;
598 }
599 struct Restore(PathBuf);
600 impl Drop for Restore {
601 fn drop(&mut self) {
602 let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755));
603 if let Some(parent) = self.0.parent() {
604 let _ = std::fs::remove_dir_all(parent);
605 }
606 }
607 }
608 let probe_dir = std::env::temp_dir().join(unique_name("greengate-probe"));
609 let locked = probe_dir.join("locked");
610 std::fs::create_dir_all(&locked).expect("mkdir");
611 let marker = locked.join(MARKER);
612 std::fs::write(&marker, "").expect("marker");
613 assert!(probe_marker(&marker).expect("readable"), "present");
614 assert!(
615 !probe_marker(&locked.join("nope")).expect("readable"),
616 "absent"
617 );
618
619 let _guard = Restore(locked.clone());
620 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).expect("chmod");
621 let got = probe_marker(&marker);
622 assert_eq!(
623 got.expect_err("a locked directory is not an absent marker")
624 .kind(),
625 std::io::ErrorKind::PermissionDenied
626 );
627 }
628}