Skip to main content

greengate_runtime/
staged_only.rs

1//! Make the checks see what is being committed.
2//!
3//! `staged_files()` asks the index for the PATH LIST, which is right, and then
4//! hands those paths to tools that open them from the WORKING TREE. Eleven of
5//! the fifteen pre-commit checks do this. So `git add -p` half a file, commit,
6//! and prettier reads the whole working-tree file: it fails on lines you did not
7//! stage, or passes on lines you did.
8//!
9//! `pre-commit` fixes this for everyone by stashing the unstaged changes for the
10//! duration of the run, and their wording names both directions:
11//!
12//! > Running hooks on unstaged changes can lead to both false-positives and
13//! > false-negatives during committing.
14//!
15//! ## This is the most dangerous code in the repository
16//!
17//! A stash taken and not restored loses uncommitted work. That is worse than
18//! either failure that overwrote tracked files, because there is nothing on disk
19//! to recover from. Hence, in order of how likely each is to bite:
20//!
21//! 1. **Nothing to stash → nothing happens.** The common case never touches the
22//!    tree.
23//! 2. **Restore on a SIGNAL.** `Drop` runs on unwind and on early return; it
24//!    does NOT run when Ctrl-C kills the process, and interrupting a slow
25//!    pre-commit is the most probable route to an orphaned stash, not the least.
26//! 3. **Restore in `Drop`** for panics and early returns.
27//! 4. **Never mid-operation.** A merge or rebase in progress means the tree is
28//!    already holding somebody else's work — `GitState` (PR 2) answers this.
29//! 5. **Restore failure is loud and fatal**, and prints the store's path, so
30//!    the work is findable on disk rather than silently gone. (Not `git stash
31//!    list`: nothing here is a stash ref — see the `impl` comment below for
32//!    why byte-exact copies beat both `stash --keep-index` and a patch.)
33//! 6. **`amont restore`** for when even the handler was interrupted.
34//!
35//! The store describes itself in an `index` file, and every repo-controlled
36//! path lives under `files/`. Both because the store used to encode its
37//! metadata in the payload FILENAMES, which a repository is allowed to collide
38//! with — and did, deleting a tracked file and planting a symlink outside the
39//! worktree. See [`Held`].
40
41use crate::names::BIN;
42use std::path::Path;
43use std::sync::atomic::{AtomicBool, Ordering};
44// Only the unix signal path keeps integer statics (the self-pipe fd and the
45// pending signal); Windows hands its handler a fresh thread and needs
46// neither, so an unconditional import is an unused one there.
47#[cfg(unix)]
48use std::sync::atomic::AtomicI32;
49use std::sync::Mutex;
50
51use crate::ui::{error_sign, warning_sign};
52
53/// Whether this process is holding a patch. Global because a signal handler
54/// cannot be handed a reference, and because there is at most one per process.
55static HELD: AtomicBool = AtomicBool::new(false);
56
57/// Guards `checkout` through `HELD.store(true, ..)` in `enter()` against a
58/// `restore()` racing in concurrently from the signal-watcher thread.
59///
60/// Without this, a signal landing mid-`checkout` lets `restore()` read `HELD`
61/// as still `false`, no-op, and kill the process — while `checkout`'s child
62/// keeps running, ORPHANED, and eventually finishes writing the tree anyway.
63/// The parked files are never put back and nothing said so. This is not
64/// hypothetical: it is what running the checkout-then-signal race a dozen
65/// times over actually produced, once `restore()` moved off the interrupted
66/// call stack and onto a thread of its own — see `install_signal_handler`.
67/// `restore()` blocking here until `enter()` finishes is exactly the fix: by
68/// the time it can read `HELD`, `checkout` has definitely either succeeded
69/// (and it restores) or never called (and it no-ops), never "maybe".
70static ENTER_LOCK: Mutex<()> = Mutex::new(());
71
72/// Where the unstaged changes are parked. Inside `$GIT_DIR` so they are never
73/// committed, never seen by a check, and findable by hand.
74pub const STORE: &str = crate::names::HELD_STORE;
75
76/// Our metadata, beside the payloads rather than encoded into their names.
77const INDEX: &str = "index";
78
79/// Everything repo-controlled lives under here. See [`Held`].
80const FILES: &str = "files";
81
82/// The index's first field. Present so an older or newer store is recognised
83/// as such instead of being half-understood.
84const FORMAT: &str = crate::names::HELD_FORMAT;
85
86/// What each held path's ON-DISK content looked like right after `enter()`'s
87/// checkout — i.e. the index content the checks were meant to see. `rel NUL
88/// hex NUL` pairs. Absent (an older store, a crash before the write) means no
89/// mid-check-edit protection, exactly as before the file existed.
90const EXPECTED: &str = "expected";
91
92/// Where a file the user edited MID-CHECK parks the held copy instead of
93/// clobbering the edit. Beside the store, not inside it: the store is deleted
94/// on a clean restore and this must survive to be read.
95const PRESERVED: &str = crate::names::PRESERVED_STORE;
96
97/// FNV-1a over the content. Not a security boundary — the question is "did
98/// an editor save land here while the checks ran", and an accidental
99/// collision needs an accidental 64-bit fixed point.
100fn content_hash(bytes: &[u8]) -> u64 {
101    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
102    for &b in bytes {
103        h ^= u64::from(b);
104        h = h.wrapping_mul(0x0000_0100_0000_01b3);
105    }
106    h
107}
108
109/// One parked path, and what it was.
110///
111/// This used to be encoded in the FILENAME — `<name>.amont-absent` and
112/// `<name>.amont-symlink` beside the payload copies — and a repository is
113/// allowed to contain files with those names. It cost exactly what you would
114/// expect: a repo tracking `notes` and `notes.amont-absent`, with the second
115/// modified, had `notes` DELETED from the working tree on restore, because the
116/// suffix strip turned one file's payload into a statement about another. The
117/// symlink form was worse: the repo chose both the link name and an arbitrary
118/// ABSOLUTE target, so committing in it planted a symlink pointing anywhere on
119/// the machine, and anything that later wrote that path wrote through it.
120///
121/// Marker-by-name cannot be made safe by escaping, because the store is also
122/// read by `amont restore` from a later process that has only the filenames
123/// to go on. So the metadata moved out of band, and every repo-controlled path
124/// moved under `files/`, where it cannot collide with `index` no matter what it
125/// is called.
126#[derive(Debug, Clone, PartialEq, Eq)]
127enum Held {
128    /// Content differs from the index. The bytes are at `files/<rel>`.
129    ///
130    /// `mode` is the working tree's, captured before `checkout` resets it.
131    /// `git diff --name-only` lists a pure `chmod +x` with IDENTICAL content,
132    /// so without this a `chmod +x deploy.sh` you had not staged came back
133    /// non-executable and nothing said so — invisible to every content-based
134    /// assertion, which is why it survived so long.
135    Modified { rel: String, mode: Option<u32> },
136    /// Deleted in the tree but not staged. Restore deletes it again.
137    Absent { rel: String },
138    /// A symlink, and where it pointed. No payload file is written at all.
139    Symlink { rel: String, target: String },
140}
141
142/// A repo-relative path that cannot escape the tree it came from.
143///
144/// Applied on the way OUT of the store as well as in: the index is a file on
145/// disk that a later `amont restore` trusts, so `..`, an absolute path or a
146/// drive prefix must not survive being written into it by any route.
147fn safe_rel(rel: &str) -> Option<std::path::PathBuf> {
148    use std::path::Component;
149    if rel.is_empty() {
150        return None;
151    }
152    let mut out = std::path::PathBuf::new();
153    for c in Path::new(rel).components() {
154        match c {
155            Component::Normal(part) => out.push(part),
156            // RootDir, Prefix, ParentDir, CurDir: all of them mean this path
157            // is not a plain location inside the worktree.
158            _ => return None,
159        }
160    }
161    (!out.as_os_str().is_empty()).then_some(out)
162}
163
164fn push_field(out: &mut Vec<u8>, s: &str) {
165    out.extend_from_slice(s.as_bytes());
166    out.push(0);
167}
168
169/// NUL-delimited, for the reason `git.rs` gives for `-z`: a path may contain a
170/// newline, a tab, a quote or a backslash, and may not contain a NUL. There is
171/// no escaping here to get wrong, which is the point.
172fn encode_index(entries: &[Held]) -> Vec<u8> {
173    let mut out = Vec::new();
174    push_field(&mut out, FORMAT);
175    for e in entries {
176        match e {
177            Held::Modified { rel, mode } => {
178                push_field(&mut out, "file");
179                push_field(&mut out, rel);
180                push_field(&mut out, &mode.map(|m| m.to_string()).unwrap_or_default());
181            }
182            Held::Absent { rel } => {
183                push_field(&mut out, "absent");
184                push_field(&mut out, rel);
185            }
186            Held::Symlink { rel, target } => {
187                push_field(&mut out, "symlink");
188                push_field(&mut out, rel);
189                push_field(&mut out, target);
190            }
191        }
192    }
193    out
194}
195
196/// Parse, or say why not. A store we cannot read in full is never partially
197/// applied: the caller keeps it and tells the user where it is.
198fn parse_index(raw: &[u8]) -> Result<Vec<Held>, String> {
199    let mut fields: Vec<&[u8]> = raw.split(|b| *b == 0).collect();
200    // Every field is NUL-TERMINATED, so a well-formed store leaves exactly one
201    // trailing empty slice. Any other empty field is a truncation.
202    if fields.last().is_some_and(|f| f.is_empty()) {
203        fields.pop();
204    }
205    let text = |f: &[u8]| -> Result<String, String> {
206        std::str::from_utf8(f)
207            .map(|s| s.to_string())
208            .map_err(|_| "held store index is not valid UTF-8".to_string())
209    };
210
211    let header = fields
212        .first()
213        .ok_or_else(|| "held store index is empty".to_string())?;
214    // greengate 3.x's store keeps its own header: `restore` puts one back.
215    if *header != FORMAT.as_bytes() && *header != crate::names::old::HELD_FORMAT.as_bytes() {
216        return Err(format!(
217            "held store index is not {FORMAT} — refusing to guess at its shape"
218        ));
219    }
220
221    let mut out = Vec::new();
222    let mut i = 1;
223    let take = |i: &mut usize, what: &str| -> Result<String, String> {
224        let f = fields
225            .get(*i)
226            .ok_or_else(|| format!("held store index ends mid-record, expected {what}"))?;
227        *i += 1;
228        text(f)
229    };
230    while i < fields.len() {
231        let kind = take(&mut i, "a record kind")?;
232        match kind.as_str() {
233            "file" => {
234                let rel = take(&mut i, "a path")?;
235                let mode = take(&mut i, "a mode")?;
236                let mode = if mode.is_empty() {
237                    None
238                } else {
239                    Some(
240                        mode.parse::<u32>()
241                            .map_err(|_| format!("held store index has a bad mode: {mode:?}"))?,
242                    )
243                };
244                out.push(Held::Modified { rel, mode });
245            }
246            "absent" => out.push(Held::Absent {
247                rel: take(&mut i, "a path")?,
248            }),
249            "symlink" => {
250                let rel = take(&mut i, "a path")?;
251                let target = take(&mut i, "a link target")?;
252                out.push(Held::Symlink { rel, target });
253            }
254            other => return Err(format!("held store index has an unknown record: {other:?}")),
255        }
256    }
257    Ok(out)
258}
259
260#[cfg(unix)]
261fn mode_of(meta: &std::fs::Metadata) -> Option<u32> {
262    use std::os::unix::fs::PermissionsExt;
263    Some(meta.permissions().mode())
264}
265
266#[cfg(not(unix))]
267fn mode_of(_meta: &std::fs::Metadata) -> Option<u32> {
268    None // No execute bit to lose.
269}
270
271#[cfg(unix)]
272fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> {
273    use std::os::unix::fs::PermissionsExt;
274    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
275}
276
277#[cfg(not(unix))]
278fn set_mode(_path: &Path, _mode: u32) -> std::io::Result<()> {
279    Ok(())
280}
281
282/// Unstaged changes, set aside for the duration of a stage.
283pub struct StagedOnly {
284    held: bool,
285}
286
287/// `greengate.fix`, read the moment a restore needs it and not before.
288///
289/// `Drop` and the signal watcher both restore, and neither can hold a borrow
290/// of the process's `Settings`. Reading through a config-only `Settings` is
291/// EXACT here, not an approximation: `greengate.fix` is not in
292/// [`crate::manifest::SETTABLE`], so no policy can set it and the answer is
293/// git config's alone. Lazy on purpose — the spawn budget counts every read
294/// on the happy path, and a restore is the unhappy one.
295fn fixing_from_config() -> bool {
296    crate::hooks::common::fixing_requested(&crate::config::Settings::default())
297}
298
299/// Why COPIES and not `git stash --keep-index`, and not a patch either.
300///
301/// Saving is the easy half; restoring is the whole problem.
302///
303/// `stash pop` MERGES into a tree that already holds the staged content, so it
304/// writes conflict markers into the user's file. Measured on the first attempt.
305///
306/// `git diff` + `git apply` is deterministic on Unix and is what `pre-commit`
307/// does — but it applies PATCH semantics to text, and Git for Windows converts
308/// line endings by default. Measured on the second attempt: every restore test
309/// failed on Windows and passed everywhere else, which is the worst possible
310/// shape for the one routine in this codebase that can lose somebody's work.
311///
312/// So: byte-exact copies. Read the file, put it back. No patch to apply, no
313/// newline policy to agree about, and binary files need no special case. It
314/// costs a temporary copy of only the files that have unstaged changes.
315impl StagedOnly {
316    /// The three early exits, and THE ORDER IS THE DESIGN.
317    ///
318    /// Both of the first two used to return "nothing held" with NO OUTPUT,
319    /// which meant the checks silently judged the working tree — the exact
320    /// failure this module exists to prevent, announced as a clean run.
321    /// `docs/index-fidelity-and-run-modes.md` §1 says conflicted paths ABORT
322    /// the stage; they did not.
323    ///
324    /// 1. **Conflicts first**, and they are an `Err`: a conflicted path has no
325    ///    staged and unstaged halves to separate, so there is nothing this can
326    ///    honestly do. `pre_commit` turns the `Err` into a printed message and
327    ///    `Verdict::Block`. Safe by construction: git itself refuses a commit
328    ///    with unmerged entries, so nothing that would have succeeded now
329    ///    fails.
330    /// 2. **Nothing unstaged** ⇒ nothing held, SILENTLY. The common case must
331    ///    stay free, and it is not a degraded run: there is no unstaged content
332    ///    for a check to be confused by.
333    /// 3. **Mid-operation LAST**, and only when there IS unstaged content, with
334    ///    one printed line. Checked after the conflict test rather than before
335    ///    it, deliberately: the other order made the ordinary conflicted-merge
336    ///    case take the mid-operation branch and warn instead of aborting.
337    ///    Checked after the emptiness test because with a clean tree fidelity
338    ///    is not actually off, and `registry.rs:64-67` calls out on purpose
339    ///    that a resolution commit still runs its checks.
340    pub fn enter() -> Result<StagedOnly, String> {
341        // Conflicted paths cannot be split into staged and unstaged halves.
342        let conflicted: Vec<String> =
343            crate::git::stdout_paths(&["diff", "--name-only", "--diff-filter=U"])
344                .unwrap_or_default();
345        if !conflicted.is_empty() {
346            return Err(format!(
347                "{} unmerged paths — resolve and stage them first:\n    {}",
348                error_sign(),
349                conflicted.join("\n    ")
350            ));
351        }
352        // Tracked files only: an untracked file is not part of this commit and
353        // moving it would surprise everyone.
354        let changed: Vec<String> =
355            crate::git::stdout_paths(&["diff", "--name-only"]).unwrap_or_default();
356        if changed.is_empty() {
357            return Ok(StagedOnly { held: false });
358        }
359        // A tree mid-merge is already holding work that is not the author's,
360        // so taking a copy of it would be the wrong instrument entirely — but
361        // the checks are then reading the tree, and that has to be said.
362        let in_progress = crate::git_states_in_progress();
363        if !in_progress.is_empty() {
364            println!(
365                "{} {} in progress — checks see the working tree, not just the index",
366                warning_sign(),
367                in_progress
368                    .iter()
369                    .map(|s| s.as_str())
370                    .collect::<Vec<_>>()
371                    .join(" and ")
372            );
373            return Ok(StagedOnly { held: false });
374        }
375
376        let Some(store) = store_dir() else {
377            return Ok(StagedOnly { held: false });
378        };
379        // A stash left behind by an interrupted restore still holds work
380        // nobody has recovered — point 5 in the module doc. Clearing it to
381        // make room for a new one would be exactly the loss this module
382        // exists to prevent, so refuse instead of silently deleting it.
383        if has_contents(&store) {
384            return Err(format!(
385                "{} a previous stash was left behind at {} — recover it with \
386                 `{BIN} restore`, then retry",
387                error_sign(),
388                store.display()
389            ));
390        }
391        let root = crate::hooks::common::repo_root();
392        let root = Path::new(&root);
393
394        // Explicitly, because a run whose every entry is a deletion or a
395        // symlink writes no payload file and so would otherwise never create
396        // the directory the index goes in.
397        if std::fs::create_dir_all(&store).is_err() {
398            return Err(held_nothing(&store));
399        }
400
401        let mut entries: Vec<Held> = Vec::with_capacity(changed.len());
402        for rel in &changed {
403            // git gave us this path, but it is repo-controlled and it is about
404            // to be joined onto a root, so it is checked like anything else.
405            let Some(relp) = safe_rel(rel) else {
406                return Err(held_nothing(&store));
407            };
408            let from = root.join(&relp);
409
410            // A symlink must be read as a link, not opened: `fs::read` follows
411            // it, which copies the TARGET's bytes instead of the link, and
412            // silently mistakes a dangling link (a normal mid-edit state) for
413            // a deleted file — restore would then delete the link rather than
414            // put it back.
415            match std::fs::symlink_metadata(&from) {
416                Ok(meta) if meta.file_type().is_symlink() => match std::fs::read_link(&from) {
417                    Ok(target) => entries.push(Held::Symlink {
418                        rel: rel.clone(),
419                        target: target.to_string_lossy().into_owned(),
420                    }),
421                    Err(_) => return Err(held_nothing(&store)),
422                },
423                Ok(meta) => {
424                    // It exists, so we must be able to reproduce it. Failing to
425                    // read it now means failing to restore it later, and the
426                    // one thing this module may not do is park work it cannot
427                    // put back.
428                    let Ok(bytes) = std::fs::read(&from) else {
429                        return Err(held_nothing(&store));
430                    };
431                    let to = store.join(FILES).join(&relp);
432                    if let Some(parent) = to.parent() {
433                        if std::fs::create_dir_all(parent).is_err() {
434                            return Err(held_nothing(&store));
435                        }
436                    }
437                    if std::fs::write(&to, bytes).is_err() {
438                        return Err(held_nothing(&store));
439                    }
440                    entries.push(Held::Modified {
441                        rel: rel.clone(),
442                        mode: mode_of(&meta),
443                    });
444                }
445                // Deleted in the tree but not staged: record the absence, so
446                // the restore deletes it again rather than resurrecting it.
447                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
448                    entries.push(Held::Absent { rel: rel.clone() })
449                }
450                // Something else is wrong with the path. Do not guess.
451                Err(_) => return Err(held_nothing(&store)),
452            }
453        }
454
455        // The index lands BEFORE the tree is touched, so a store can never be
456        // half-described while the working tree has already moved.
457        if std::fs::write(store.join(INDEX), encode_index(&entries)).is_err() {
458            return Err(held_nothing(&store));
459        }
460
461        // Tree := index, for exactly the paths being parked. Scoped, not
462        // `checkout -- .`: the repo-wide form makes git traverse and lstat
463        // the entire working tree to reset the handful of files just
464        // enumerated — seconds on a large tree, on every dirty commit — and
465        // the pathspec list is BY CONSTRUCTION the complete set of tracked
466        // paths that differ. `:(literal)` per path, because a path is data
467        // here and `*`/`:` are pathspec syntax. Locked against a concurrent
468        // `restore()` — see `ENTER_LOCK`.
469        {
470            let _guard = ENTER_LOCK.lock().unwrap_or_else(|p| p.into_inner());
471            let mut spec = String::new();
472            for p in &changed {
473                spec.push_str(":(literal)");
474                spec.push_str(p);
475                spec.push('\0');
476            }
477            if crate::git::stdout_piped_raw(
478                &["checkout", "--pathspec-from-file=-", "--pathspec-file-nul"],
479                &spec,
480            )
481            .is_none()
482            {
483                let _ = std::fs::remove_dir_all(&store);
484                return Err(format!(
485                    "{} could not set the unstaged changes aside; nothing was changed",
486                    error_sign()
487                ));
488            }
489            // What the checks will see, recorded so `put_back` can tell an
490            // editor save made MID-CHECK apart from its own checkout — the
491            // clobber this module used to commit silently. Best-effort: a
492            // failure to record only means the old unconditional restore.
493            let mut expected = String::new();
494            for e in &entries {
495                if let Held::Modified { rel, .. } = e {
496                    if let Some(relp) = safe_rel(rel) {
497                        if let Ok(bytes) = std::fs::read(root.join(&relp)) {
498                            expected.push_str(rel);
499                            expected.push('\0');
500                            expected.push_str(&format!("{:016x}", content_hash(&bytes)));
501                            expected.push('\0');
502                        }
503                    }
504                }
505            }
506            let _ = std::fs::write(store.join(EXPECTED), expected);
507            HELD.store(true, Ordering::SeqCst);
508        }
509        Ok(StagedOnly { held: true })
510    }
511
512    /// Put them back. Idempotent, and safe to call from the watcher thread
513    /// `install_signal_handler` starts — never from the signal handler itself.
514    /// `fixing` rather than the whole configuration: this runs from `Drop` and
515    /// from the signal thread, neither of which can hold a borrow.
516    pub fn restore(fixing: bool) {
517        // Blocks until `enter()` has definitely finished its own checkout —
518        // see `ENTER_LOCK`. The common case (no `enter()` active) is
519        // uncontended.
520        let _guard = ENTER_LOCK.lock().unwrap_or_else(|p| p.into_inner());
521        if !HELD.swap(false, Ordering::SeqCst) {
522            return;
523        }
524        let Some(store) = store_dir() else {
525            return;
526        };
527        if !store.is_dir() {
528            return;
529        }
530        let root = crate::hooks::common::repo_root();
531        match put_back(fixing, &store, Path::new(&root)) {
532            Ok(()) => {
533                let _ = std::fs::remove_dir_all(&store);
534            }
535            Err(_) => {
536                // The one message in this codebase that must never be swallowed.
537                eprintln!(
538                    "{} YOUR UNSTAGED CHANGES COULD NOT BE PUT BACK AUTOMATICALLY.",
539                    error_sign()
540                );
541                eprintln!("    They are safe, in: {}", store.display());
542                eprintln!("    Recover them with: {BIN} restore");
543            }
544        }
545    }
546}
547
548/// Whether `dir` exists and holds at least one entry.
549fn has_contents(dir: &Path) -> bool {
550    std::fs::read_dir(dir)
551        .map(|mut entries| entries.next().is_some())
552        .unwrap_or(false)
553}
554
555fn held_nothing(store: &Path) -> String {
556    let _ = std::fs::remove_dir_all(store);
557    format!(
558        "{} could not hold the unstaged changes aside; nothing was changed",
559        error_sign()
560    )
561}
562
563/// Put every held path back over the tree.
564///
565/// Dispatches on the index: a store written by this version describes itself,
566/// and one left behind by an older binary mid-upgrade is still recoverable
567/// through [`put_back_legacy`]. Nobody's work is stranded by the format change.
568fn put_back(fixing: bool, store: &Path, root: &Path) -> std::io::Result<()> {
569    match std::fs::read(store.join(INDEX)) {
570        Ok(raw) => {
571            let entries = parse_index(&raw).map_err(std::io::Error::other)?;
572            put_back_v1(fixing, store, root, &entries)
573        }
574        Err(e) if e.kind() == std::io::ErrorKind::NotFound => put_back_legacy(store, root),
575        Err(e) => Err(e),
576    }
577}
578
579fn put_back_v1(fixing: bool, store: &Path, root: &Path, entries: &[Held]) -> std::io::Result<()> {
580    let expected = read_expected(store);
581    // The guard stands down when fixing is ON: a repo-wide fixer (`prettier
582    // --write .`) legitimately rewrites held files mid-run, and telling its
583    // writes apart from an editor save is not possible from here. `greengate.fix`
584    // is an explicit opt-in whose documented contract has always been "the
585    // tree returns to your unstaged version"; the guard protects the default
586    // population, which is everyone else.
587    let guard = !fixing;
588    let mut preserved: Vec<(String, std::path::PathBuf)> = Vec::new();
589    let escapes = |rel: &str| {
590        std::io::Error::other(format!(
591            "held store names a path outside the worktree: {rel:?}"
592        ))
593    };
594    for e in entries {
595        match e {
596            Held::Absent { rel } => {
597                let relp = safe_rel(rel).ok_or_else(|| escapes(rel))?;
598                // It was deleted in the tree; `checkout` brought it back.
599                let _ = std::fs::remove_file(root.join(relp));
600            }
601            Held::Symlink { rel, target } => {
602                let relp = safe_rel(rel).ok_or_else(|| escapes(rel))?;
603                let link = root.join(relp);
604                // `checkout` put the staged content there — a regular file,
605                // or a link of its own; replace it, don't merge with it.
606                let _ = remove_link(&link);
607                create_symlink(target, &link)?;
608            }
609            Held::Modified { rel, mode } => {
610                let relp = safe_rel(rel).ok_or_else(|| escapes(rel))?;
611                let target = root.join(&relp);
612                if let Some(parent) = target.parent() {
613                    std::fs::create_dir_all(parent)?;
614                }
615                let held = std::fs::read(store.join(FILES).join(&relp))?;
616                // What `checkout` put here may be a SYMLINK: the staged content
617                // of a path whose unstaged version is a regular file. Both
618                // `fs::read` below and `fs::write` FOLLOW a link, so restoring
619                // through it would compare against, and then overwrite, the
620                // link's TARGET — a file anywhere on the machine, outside the
621                // worktree included, that this module was never asked to
622                // touch. The link is the index's content, not the author's;
623                // the author's is the regular file in the store. Remove the
624                // link so the write lands on the path itself.
625                if is_symlink(&target) {
626                    remove_link(&target)?;
627                }
628                // The clobber guard. If the file on disk no longer holds what
629                // `enter()`'s checkout put there, somebody wrote it while the
630                // checks ran — an editor save is WORK, and this write used to
631                // destroy it silently. Keep the newer file; park the held
632                // copy where the warning says.
633                if guard
634                    && expected.get(rel.as_str()).is_some_and(|want| {
635                        std::fs::read(&target)
636                            .is_ok_and(|now| content_hash(&now) != *want && now != held)
637                    })
638                {
639                    let kept = preserve(store, &relp, &held)?;
640                    preserved.push((rel.clone(), kept));
641                    continue;
642                }
643                std::fs::write(&target, held)?;
644                // AFTER the write: a recorded mode without `u+w` applied first
645                // would make writing the content fail.
646                if let Some(m) = mode {
647                    set_mode(&target, *m)?;
648                }
649            }
650        }
651    }
652    if !preserved.is_empty() {
653        eprintln!(
654            "{} {} file(s) changed while the checks ran — the newer content was KEPT.",
655            crate::ui::warning_sign(),
656            preserved.len()
657        );
658        eprintln!("    The unstaged version each held before the commit is parked at:");
659        for (rel, kept) in &preserved {
660            eprintln!("      {} -> {}", crate::ui::sanitize(rel), kept.display());
661        }
662        eprintln!("    Compare and merge by hand; the parked copies are yours to delete.");
663    }
664    Ok(())
665}
666
667/// Park `held` beside the store, never inside it — the store is deleted on a
668/// clean restore and this must survive to be read. A previous incident's copy
669/// is not overwritten; the name grows a counter instead.
670fn preserve(store: &Path, relp: &Path, held: &[u8]) -> std::io::Result<std::path::PathBuf> {
671    let base = store
672        .parent()
673        .map(|p| p.join(PRESERVED))
674        .ok_or_else(|| std::io::Error::other("store has no parent"))?;
675    let mut to = base.join(relp);
676    let mut n = 0;
677    while to.exists() {
678        n += 1;
679        to = base.join(relp).with_extension(format!("kept-{n}"));
680    }
681    if let Some(parent) = to.parent() {
682        std::fs::create_dir_all(parent)?;
683    }
684    std::fs::write(&to, held)?;
685    Ok(to)
686}
687
688/// The `EXPECTED` record, or empty when it is absent or unreadable — which
689/// simply disables the clobber guard, the pre-existing behaviour.
690fn read_expected(store: &Path) -> std::collections::HashMap<String, u64> {
691    let Ok(raw) = std::fs::read_to_string(store.join(EXPECTED)) else {
692        return Default::default();
693    };
694    let mut map = std::collections::HashMap::new();
695    let mut it = raw.split('\0');
696    while let (Some(rel), Some(hex)) = (it.next(), it.next()) {
697        if rel.is_empty() {
698            break;
699        }
700        if let Ok(h) = u64::from_str_radix(hex, 16) {
701            map.insert(rel.to_string(), h);
702        }
703    }
704    map
705}
706
707/// A store from before the index existed, where the kind of each entry was
708/// encoded in its file NAME.
709///
710/// Kept only so that upgrading mid-hold cannot strand somebody's work. The
711/// ambiguity that made this format unsafe — a repository may contain files
712/// called `x.amont-absent` — is not fixable at recovery time: by the time we
713/// are reading it, the statement and the payload are already indistinguishable.
714/// This is a best-effort read of a format we no longer write.
715fn put_back_legacy(store: &Path, root: &Path) -> std::io::Result<()> {
716    for entry in walk(store)? {
717        let rel = entry.strip_prefix(store).unwrap_or(&entry).to_path_buf();
718        let rel_str = rel.to_string_lossy().to_string();
719        let escapes = || {
720            std::io::Error::other(format!(
721                "held store names a path outside the worktree: {rel_str:?}"
722            ))
723        };
724        if let Some(original) = rel_str.strip_suffix(".amont-absent") {
725            let relp = safe_rel(original).ok_or_else(escapes)?;
726            let _ = std::fs::remove_file(root.join(relp));
727            continue;
728        }
729        if let Some(original) = rel_str.strip_suffix(".amont-symlink") {
730            let link_target = std::fs::read_to_string(&entry)?;
731            let relp = safe_rel(original).ok_or_else(escapes)?;
732            let link_path = root.join(relp);
733            let _ = std::fs::remove_file(&link_path);
734            create_symlink(&link_target, &link_path)?;
735            continue;
736        }
737        let relp = safe_rel(&rel_str).ok_or_else(escapes)?;
738        let target = root.join(&relp);
739        if let Some(parent) = target.parent() {
740            std::fs::create_dir_all(parent)?;
741        }
742        std::fs::write(&target, std::fs::read(&entry)?)?;
743    }
744    Ok(())
745}
746
747#[cfg(unix)]
748fn create_symlink(target: &str, link: &Path) -> std::io::Result<()> {
749    std::os::unix::fs::symlink(target, link)
750}
751
752/// Windows distinguishes file and directory symlinks at creation time. The
753/// target usually still exists (it was the staged content `checkout` left
754/// behind, untouched by this whole dance), so ask it; a dangling link falls
755/// back to `symlink_file`, the more common case.
756#[cfg(windows)]
757fn create_symlink(target: &str, link: &Path) -> std::io::Result<()> {
758    let resolved = link
759        .parent()
760        .map(|parent| parent.join(target))
761        .unwrap_or_else(|| Path::new(target).to_path_buf());
762    if resolved.is_dir() {
763        std::os::windows::fs::symlink_dir(target, link)
764    } else {
765        std::os::windows::fs::symlink_file(target, link)
766    }
767}
768
769/// Is the path itself a symlink? `symlink_metadata`, never `metadata`: the
770/// latter follows the link and answers about whatever it points at.
771fn is_symlink(path: &Path) -> bool {
772    std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink())
773}
774
775/// Remove a symlink — the LINK, never its target. On Windows a link to a
776/// directory is removed with `remove_dir`, and `remove_file` refuses it; on
777/// unix `remove_file` unlinks either kind.
778fn remove_link(link: &Path) -> std::io::Result<()> {
779    match std::fs::remove_file(link) {
780        Ok(()) => Ok(()),
781        Err(first) => match std::fs::remove_dir(link) {
782            Ok(()) => Ok(()),
783            Err(_) => Err(first),
784        },
785    }
786}
787
788#[cfg(not(any(unix, windows)))]
789fn create_symlink(target: &str, link: &Path) -> std::io::Result<()> {
790    Err(std::io::Error::other(format!(
791        "no symlink support on this platform: {} -> {target}",
792        link.display()
793    )))
794}
795
796fn walk(dir: &Path) -> std::io::Result<Vec<std::path::PathBuf>> {
797    let mut out = Vec::new();
798    for entry in std::fs::read_dir(dir)? {
799        let path = entry?.path();
800        if path.is_dir() {
801            out.extend(walk(&path)?);
802        } else {
803            out.push(path);
804        }
805    }
806    Ok(out)
807}
808
809/// Where the store lives, agreeing with [`StagedOnly::restore`] and
810/// [`restore_command`] BY CONSTRUCTION — all three call this one function
811/// rather than each asking git their own way. That used to be
812/// `hooks_dir.parent()` in `enter()` against `git rev-parse --git-dir`
813/// everywhere else: correct for the main worktree, where `.git/hooks`'s
814/// parent IS `$GIT_DIR`, but wrong for a LINKED worktree, where hooks
815/// dispatch from the COMMON directory's shared `hooks/` while `--git-dir`
816/// names the worktree's own PRIVATE gitdir. The mismatch parked files in one
817/// directory and looked for them in the other — silently, since a missing
818/// store reads as "nothing to do" — which is how a real commit in a real
819/// worktree lost real unstaged content. Sharing one function instead of one
820/// convention makes that class of drift impossible rather than merely fixed.
821fn store_dir() -> Option<std::path::PathBuf> {
822    let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
823    Some(Path::new(&dir).join(STORE))
824}
825
826impl Drop for StagedOnly {
827    fn drop(&mut self) {
828        if self.held {
829            StagedOnly::restore(fixing_from_config());
830        }
831    }
832}
833
834/// Set while the signal watcher cancels cluster Jobs: a second signal then
835/// ends amont at once instead of queueing behind the cancel.
836static LEAVE_ON_SIGNAL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
837
838/// Holds [`LEAVE_ON_SIGNAL`] set; a second signal queues again, as before the
839/// cancel, once it is dropped — on every exit path, a panic included.
840#[must_use = "the flag is cleared when the guard drops"]
841pub(crate) struct LeaveOnSecondSignal(());
842
843impl Drop for LeaveOnSecondSignal {
844    fn drop(&mut self) {
845        LEAVE_ON_SIGNAL.store(false, std::sync::atomic::Ordering::SeqCst);
846    }
847}
848
849/// From now on a second signal ends amont at once ([`LEAVE_ON_SIGNAL`]), for
850/// as long as the guard lives; [`crate::cluster::cancel_live`] holds it over
851/// its deletes.
852pub(crate) fn leave_on_second_signal() -> LeaveOnSecondSignal {
853    LEAVE_ON_SIGNAL.store(true, std::sync::atomic::Ordering::SeqCst);
854    LeaveOnSecondSignal(())
855}
856
857/// Put back files this tool parked, from a later invocation.
858///
859/// For when even the signal handler was interrupted.
860pub fn restore_command(settings: &crate::config::Settings) -> Result<(), String> {
861    let store = store_dir().ok_or_else(|| "not inside a git repository".to_string())?;
862    // A store greengate 3.x parked is put back from where 3.x left it: the
863    // migration refuses to move it, and asks for this command.
864    let store = match store
865        .parent()
866        .and_then(crate::migrate::old_held_store)
867        .filter(|_| !store.is_dir())
868    {
869        Some(old) => old,
870        None => store,
871    };
872    if !store.is_dir() {
873        println!("{} nothing of ours to restore", warning_sign());
874        return Ok(());
875    }
876    // `store_dir()` already established we are in a repository, so this cannot
877    // fail here — asked the checked way anyway, because `repo_root()`'s "."
878    // would make `put_back` write held files relative to the current directory
879    // rather than the work tree, and a restore that lands in the wrong place is
880    // the failure this whole module exists to prevent.
881    let root = crate::hooks::common::repo_root_checked()?;
882    put_back(
883        crate::hooks::common::fixing_requested(settings),
884        &store,
885        Path::new(&root),
886    )
887    .map_err(|e| format!("could not put {} back: {e}", store.display()))?;
888    let _ = std::fs::remove_dir_all(&store);
889    println!("restored your unstaged changes");
890    Ok(())
891}
892
893/// Restore before dying on a signal.
894///
895/// `Drop` does not run when the process is killed, and Ctrl-C during a slow
896/// pre-commit is the most likely way to reach an orphaned stash. Installed only
897/// when a stash is actually held.
898///
899/// The handler itself does almost nothing. `restore()` runs `git`, walks the
900/// filesystem, writes files and prints — none of that is async-signal-safe,
901/// and running it IN the handler risks a deadlock: if the thread the signal
902/// interrupted already held a lock the handler's own code would then wait on
903/// forever (the allocator's, or stdio's), the process hangs instead of
904/// exiting, which is worse than either failure `restore` exists to prevent.
905///
906/// So the handler only records which signal arrived and writes one byte down
907/// a pipe — both on POSIX's async-signal-safe list — and a plain background
908/// thread, blocked reading that pipe, does the actual restore once it wakes,
909/// in ordinary thread context where none of those restrictions apply. This is
910/// the standard "self-pipe" pattern for getting work out of a signal handler.
911#[cfg(unix)]
912pub fn install_signal_handler() {
913    // Once per process: `tree_run` arms it before every gate it spawns, and a
914    // second call would open another pipe, start another watcher and leave
915    // the first one blocked forever.
916    static INSTALLED: std::sync::Once = std::sync::Once::new();
917    INSTALLED.call_once(install_signal_handler_once);
918}
919
920#[cfg(unix)]
921fn install_signal_handler_once() {
922    let mut fds = [-1i32; 2];
923    if unsafe { libc_pipe(fds.as_mut_ptr()) } != 0 {
924        // No pipe, no watcher, no handler: Ctrl-C falls back to the default
925        // action. Losing the safety net is better than building it on a
926        // primitive that just failed us.
927        return;
928    }
929    let (read_fd, write_fd) = (fds[0], fds[1]);
930    SIGNAL_PIPE_WRITE.store(write_fd, Ordering::SeqCst);
931
932    std::thread::spawn(move || loop {
933        let mut byte = 0u8;
934        let n = unsafe { libc_read(read_fd, &mut byte as *mut u8, 1) };
935        if n <= 0 {
936            return; // pipe closed, or a real error: nothing left to watch for
937        }
938        // Gates first: they run in their own process groups, so the signal
939        // that is killing amont never reached them (amont#302).
940        crate::tree_run::reap_live();
941        StagedOnly::restore(fixing_from_config());
942        // A gate Job on the cluster: asked to go, not waited for (ADR-0016).
943        // After the restore, so a second signal that cuts this short can
944        // only leave a Job to its deadline, never the index parked.
945        crate::cluster::cancel_live();
946        // Re-raise with the default handler so the exit status is honest
947        // about having been killed.
948        let sig = PENDING_SIGNAL.load(Ordering::SeqCst);
949        if sig != 0 {
950            unsafe {
951                libc_signal(sig, 0); // SIG_DFL
952                libc_raise(sig);
953            }
954        }
955    });
956
957    extern "C" fn on_signal(sig: i32) {
958        // Before anything else: the signal may have killed a child (Ctrl-C
959        // reaches the whole foreground group) whose death unblocks code that
960        // would otherwise fall back to a local run before the watcher runs.
961        crate::tree_run::mark_dying();
962        // A second signal while the cluster Jobs are being cancelled: leave
963        // them, and die now. `signal` and `raise` are async-signal-safe.
964        if LEAVE_ON_SIGNAL.load(Ordering::SeqCst) {
965            unsafe {
966                libc_signal(sig, 0); // SIG_DFL
967                libc_raise(sig);
968            }
969            return;
970        }
971        PENDING_SIGNAL.store(sig, Ordering::SeqCst);
972        let fd = SIGNAL_PIPE_WRITE.load(Ordering::SeqCst);
973        if fd >= 0 {
974            let byte = 1u8;
975            unsafe {
976                libc_write(fd, &byte as *const u8, 1);
977            }
978        }
979    }
980    // Numeric literals rather than a `libc` import: this module deliberately
981    // ships dependency-free (see the `extern` block below and
982    // `scripts/check-no-deps.sh`), and unlike `sigset_t`-based APIs these four
983    // numbers are fixed by POSIX on every platform this runs on.
984    //
985    // SIGHUP was missing and is at least as likely as Ctrl-C: it is the
986    // terminal-closed and SSH-connection-dropped case, and a pre-commit
987    // interrupted that way orphaned the held store with nothing said. SIGQUIT
988    // is the Ctrl-\ sibling of SIGINT.
989    const SIGHUP: i32 = 1;
990    const SIGINT: i32 = 2;
991    const SIGQUIT: i32 = 3;
992    const SIGTERM: i32 = 15;
993    unsafe {
994        for sig in [SIGHUP, SIGINT, SIGQUIT, SIGTERM] {
995            libc_signal(sig, on_signal as *const () as usize);
996        }
997    }
998}
999
1000/// The Windows twin: `SetConsoleCtrlHandler` instead of `signal(2)`. The
1001/// system already runs the handler on a fresh thread, so there is no
1002/// self-pipe dance — `restore()` is called directly (its `ENTER_LOCK`
1003/// synchronisation against a mid-`enter()` signal is the same on both
1004/// platforms), and returning FALSE hands the event to the default handler,
1005/// which terminates the process: the exit stays honest about being killed.
1006/// Before this, Ctrl-C mid-check on Windows orphaned the held patch and the
1007/// recovery was "your next commit is blocked, run `amont restore`" — the
1008/// platform with the fewest git-hooks veterans got the scariest failure.
1009///
1010/// Raw FFI rather than a crate for the same reason as the unix externs
1011/// below: this binary ships dependency-free, and this is one kernel32 call
1012/// with a stable signature. Covers Ctrl-C, Ctrl-Break, and console-closed.
1013#[cfg(windows)]
1014pub fn install_signal_handler() {
1015    extern "system" fn on_ctrl(_event: u32) -> i32 {
1016        StagedOnly::restore(fixing_from_config());
1017        0 // FALSE: pass to the default handler, which terminates
1018    }
1019    #[link(name = "kernel32")]
1020    extern "system" {
1021        fn SetConsoleCtrlHandler(handler: extern "system" fn(u32) -> i32, add: i32) -> i32;
1022    }
1023    // Once per process, as on unix: `tree_run` arms it before every gate, and
1024    // each extra registration would run the restore again.
1025    static INSTALLED: std::sync::Once = std::sync::Once::new();
1026    INSTALLED.call_once(|| unsafe {
1027        SetConsoleCtrlHandler(on_ctrl, 1);
1028    });
1029}
1030
1031#[cfg(not(any(unix, windows)))]
1032pub fn install_signal_handler() {}
1033
1034/// The write end of the self-pipe a signal handler wakes the watcher thread
1035/// through. `-1` until `install_signal_handler` has run.
1036#[cfg(unix)]
1037static SIGNAL_PIPE_WRITE: AtomicI32 = AtomicI32::new(-1);
1038
1039/// Which signal woke the watcher, so it can re-raise the right one.
1040#[cfg(unix)]
1041static PENDING_SIGNAL: AtomicI32 = AtomicI32::new(0);
1042
1043// Externs rather than a dependency: `scripts/check-no-deps.sh` keeps this
1044// binary crate-free, and these are five libc calls with stable signatures —
1045// `pipe`/`read`/`write` need nothing beyond plain integers and byte pointers,
1046// so unlike `sigset_t`-based APIs there is no opaque, platform-varying struct
1047// layout to get wrong by hand.
1048#[cfg(unix)]
1049extern "C" {
1050    #[link_name = "signal"]
1051    fn libc_signal_raw(sig: i32, handler: usize) -> usize;
1052    #[link_name = "raise"]
1053    fn libc_raise_raw(sig: i32) -> i32;
1054    #[link_name = "pipe"]
1055    fn libc_pipe_raw(fds: *mut i32) -> i32;
1056    #[link_name = "read"]
1057    fn libc_read_raw(fd: i32, buf: *mut u8, count: usize) -> isize;
1058    #[link_name = "write"]
1059    fn libc_write_raw(fd: i32, buf: *const u8, count: usize) -> isize;
1060}
1061
1062#[cfg(unix)]
1063unsafe fn libc_signal(sig: i32, handler: usize) {
1064    unsafe {
1065        libc_signal_raw(sig, handler);
1066    }
1067}
1068
1069#[cfg(unix)]
1070unsafe fn libc_raise(sig: i32) {
1071    unsafe {
1072        libc_raise_raw(sig);
1073    }
1074}
1075
1076#[cfg(unix)]
1077unsafe fn libc_pipe(fds: *mut i32) -> i32 {
1078    unsafe { libc_pipe_raw(fds) }
1079}
1080
1081#[cfg(unix)]
1082unsafe fn libc_read(fd: i32, buf: *mut u8, count: usize) -> isize {
1083    unsafe { libc_read_raw(fd, buf, count) }
1084}
1085
1086#[cfg(unix)]
1087unsafe fn libc_write(fd: i32, buf: *const u8, count: usize) -> isize {
1088    unsafe { libc_write_raw(fd, buf, count) }
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use super::*;
1094
1095    fn modified(rel: &str) -> Held {
1096        Held::Modified {
1097            rel: rel.to_string(),
1098            mode: Some(0o100_644),
1099        }
1100    }
1101
1102    /// The store has to survive names a repository is allowed to choose, and
1103    /// those include every character a filename may hold except NUL — which is
1104    /// exactly why the index is NUL-delimited rather than line-based.
1105    #[test]
1106    fn the_index_round_trips_hostile_names() {
1107        let entries = vec![
1108            modified("a\nb.txt"),
1109            modified("a\tb"),
1110            modified("a\\b"),
1111            modified("é.json"),
1112            modified("quote\"and'apostrophe"),
1113            // The names that used to BE the metadata.
1114            modified("notes.amont-absent"),
1115            Held::Absent {
1116                rel: "gone.amont-symlink".to_string(),
1117            },
1118            Held::Symlink {
1119                rel: "link\nname".to_string(),
1120                target: "target\nwith\nnewlines".to_string(),
1121            },
1122        ];
1123        let raw = encode_index(&entries);
1124        assert_eq!(parse_index(&raw).expect("round trip"), entries);
1125    }
1126
1127    #[test]
1128    fn an_empty_index_round_trips() {
1129        let raw = encode_index(&[]);
1130        assert_eq!(parse_index(&raw).expect("round trip"), Vec::<Held>::new());
1131    }
1132
1133    /// A store we do not recognise is never half-understood.
1134    #[test]
1135    fn parse_index_rejects_a_foreign_header() {
1136        let err = parse_index(b"greengate-held-v99\0file\0a\0\0").expect_err("must refuse");
1137        assert!(err.contains("greengate-held-v1"), "{err}");
1138    }
1139
1140    /// greengate 3.x's store is still read, so `restore` can put it back.
1141    #[test]
1142    fn parse_index_reads_a_3x_store() {
1143        assert_eq!(
1144            parse_index(format!("{}\0", crate::names::old::HELD_FORMAT).as_bytes())
1145                .expect("a 3.x header"),
1146            Vec::<Held>::new()
1147        );
1148    }
1149
1150    #[test]
1151    fn parse_index_rejects_a_truncated_record() {
1152        // A `file` record promises a path and a mode.
1153        let raw = b"greengate-held-v1\0file\0a.txt\0";
1154        let err = parse_index(raw).expect_err("must refuse");
1155        assert!(err.contains("ends mid-record"), "{err}");
1156    }
1157
1158    #[test]
1159    fn parse_index_rejects_an_unknown_record_kind() {
1160        let raw = b"greengate-held-v1\0execute\0rm -rf\0";
1161        assert!(parse_index(raw).is_err());
1162    }
1163
1164    /// The guard that makes the store unable to name anything outside the
1165    /// worktree, applied on the way out as well as in.
1166    #[test]
1167    fn safe_rel_refuses_anything_that_leaves_the_tree() {
1168        for bad in [
1169            "",
1170            "..",
1171            "../x",
1172            "a/../../b",
1173            "/etc/passwd",
1174            "/",
1175            ".",
1176            "./a",
1177        ] {
1178            assert!(safe_rel(bad).is_none(), "{bad:?} must be refused");
1179        }
1180        for good in ["a", "a/b.txt", "é.json", "a\nb", "notes.amont-absent"] {
1181            assert!(safe_rel(good).is_some(), "{good:?} should be allowed");
1182        }
1183    }
1184
1185    /// Windows drive-qualified paths are absolute even when they do not start
1186    /// with a separator, and `Path::join` honours them.
1187    #[cfg(windows)]
1188    #[test]
1189    fn safe_rel_refuses_a_drive_prefix() {
1190        assert!(safe_rel("C:\\Windows\\System32").is_none());
1191        assert!(safe_rel("C:x").is_none());
1192    }
1193
1194    /// The flag a second signal reads is armed only while the guard lives:
1195    /// an early return or a panic cannot leave it armed.
1196    #[test]
1197    fn the_second_signal_flag_is_disarmed_when_the_guard_drops() {
1198        let armed = || LEAVE_ON_SIGNAL.load(Ordering::SeqCst);
1199        {
1200            let _guard = leave_on_second_signal();
1201            assert!(armed());
1202        }
1203        assert!(!armed());
1204        let panicked = std::panic::catch_unwind(|| {
1205            let _guard = leave_on_second_signal();
1206            panic!("a cancel that panics");
1207        });
1208        assert!(panicked.is_err());
1209        assert!(!armed());
1210    }
1211}