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