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