Skip to content

Commit 9b0047f

Browse files
authored
Fix intent-to-add stash restore (#2143)
Closes #2142
1 parent 00b2520 commit 9b0047f

2 files changed

Lines changed: 93 additions & 36 deletions

File tree

‎crates/prek/src/cli/run/keeper.rs‎

Lines changed: 27 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::path::{Path, PathBuf};
22
use std::process::Command;
3-
use std::sync::Mutex;
3+
use std::sync::{Arc, Mutex};
44

55
use anstream::eprintln;
66
use anyhow::Result;
@@ -14,10 +14,8 @@ use crate::fs::Simplified;
1414
use crate::git::{self, GIT, git_cmd};
1515
use crate::store::Store;
1616

17-
static RESTORE_WORKTREE: Mutex<Option<WorkTreeKeeper>> = Mutex::new(None);
18-
19-
struct IntentToAddKeeper(Vec<PathBuf>);
20-
struct WorkingTreeKeeper {
17+
struct IntentToAddRestorer(Vec<PathBuf>);
18+
struct UnstagedChangesRestorer {
2119
root: PathBuf,
2220
patch: Option<PathBuf>,
2321
}
@@ -37,7 +35,7 @@ fn ensure_patches_dir(path: &Path) -> Result<()> {
3735
Ok(())
3836
}
3937

40-
impl IntentToAddKeeper {
38+
impl IntentToAddRestorer {
4139
async fn clean(root: &Path) -> Result<Self> {
4240
let files = git::intent_to_add_files(root).await?;
4341
if files.is_empty() {
@@ -76,7 +74,7 @@ impl IntentToAddKeeper {
7674
}
7775
}
7876

79-
impl Drop for IntentToAddKeeper {
77+
impl Drop for IntentToAddRestorer {
8078
fn drop(&mut self) {
8179
if let Err(err) = self.restore() {
8280
eprintln!(
@@ -87,7 +85,7 @@ impl Drop for IntentToAddKeeper {
8785
}
8886
}
8987

90-
impl WorkingTreeKeeper {
88+
impl UnstagedChangesRestorer {
9189
async fn clean(root: &Path, patch_dir: &Path) -> Result<Self> {
9290
let tree = git::write_tree().await?;
9391

@@ -222,7 +220,7 @@ impl WorkingTreeKeeper {
222220
}
223221
}
224222

225-
impl Drop for WorkingTreeKeeper {
223+
impl Drop for UnstagedChangesRestorer {
226224
fn drop(&mut self) {
227225
if let Err(err) = self.restore() {
228226
eprintln!(
@@ -235,48 +233,41 @@ impl Drop for WorkingTreeKeeper {
235233

236234
/// Clean Git intent-to-add files and working tree changes, and restore them when dropped.
237235
pub struct WorkTreeKeeper {
238-
intent_to_add: Option<IntentToAddKeeper>,
239-
working_tree: Option<WorkingTreeKeeper>,
236+
state: Arc<Mutex<Option<WorkTreeState>>>,
240237
}
241238

242-
#[derive(Default)]
243-
pub struct RestoreGuard {
244-
_guard: (),
239+
struct WorkTreeState {
240+
// Drop order matters: restore file contents before re-adding intent-to-add entries.
241+
unstaged_changes: UnstagedChangesRestorer,
242+
intent_to_add: IntentToAddRestorer,
245243
}
246244

247-
impl Drop for RestoreGuard {
245+
impl Drop for WorkTreeKeeper {
248246
fn drop(&mut self) {
249-
if let Some(mut keeper) = RESTORE_WORKTREE.lock().unwrap().take() {
250-
keeper.restore();
251-
}
247+
let mut state = self.state.lock().unwrap();
248+
drop(state.take());
252249
}
253250
}
254251

255252
impl WorkTreeKeeper {
256253
/// Clear intent-to-add changes from the index and clear the non-staged changes from the working directory.
257254
/// Restore them when the instance is dropped.
258-
pub async fn clean(store: &Store, root: &Path) -> Result<RestoreGuard> {
259-
let cleaner = Self {
260-
intent_to_add: Some(IntentToAddKeeper::clean(root).await?),
261-
working_tree: Some(WorkingTreeKeeper::clean(root, &store.patches_dir()).await?),
255+
pub async fn clean(store: &Store, root: &Path) -> Result<Self> {
256+
let intent_to_add = IntentToAddRestorer::clean(root).await?;
257+
let unstaged_changes = UnstagedChangesRestorer::clean(root, &store.patches_dir()).await?;
258+
let state = WorkTreeState {
259+
unstaged_changes,
260+
intent_to_add,
262261
};
263-
264-
// Set to the global for the cleanup hook.
265-
*RESTORE_WORKTREE.lock().unwrap() = Some(cleaner);
262+
let state = Arc::new(Mutex::new(Some(state)));
266263

267264
// Make sure restoration when ctrl-c is pressed.
268-
add_cleanup(|| {
269-
if let Some(guard) = &mut *RESTORE_WORKTREE.lock().unwrap() {
270-
guard.restore();
271-
}
265+
let cleanup_state = Arc::clone(&state);
266+
add_cleanup(move || {
267+
let mut state = cleanup_state.lock().unwrap();
268+
drop(state.take());
272269
});
273270

274-
Ok(RestoreGuard::default())
275-
}
276-
277-
/// Restore the intent-to-add changes and non-staged changes.
278-
fn restore(&mut self) {
279-
self.intent_to_add.take();
280-
self.working_tree.take();
271+
Ok(Self { state })
281272
}
282273
}

‎crates/prek/tests/run.rs‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1491,6 +1491,72 @@ fn staged_files_only() -> Result<()> {
14911491
Ok(())
14921492
}
14931493

1494+
#[test]
1495+
fn intent_to_add_file_survives_conflicted_stash_restore() -> Result<()> {
1496+
let context = TestContext::new();
1497+
context.init_project();
1498+
context.write_pre_commit_config(indoc::indoc! {r#"
1499+
repos:
1500+
- repo: local
1501+
hooks:
1502+
- id: rewrite-python
1503+
name: rewrite-python
1504+
language: system
1505+
entry: python3 -c 'open("test.py", "w").write("a = 1\n")'
1506+
files: ^test\.py$
1507+
"#});
1508+
1509+
let cwd = context.work_dir();
1510+
context.git_add(PRE_COMMIT_CONFIG_YAML);
1511+
1512+
cwd.child("intent.txt").write_str("preserve me\n")?;
1513+
git_cmd(cwd)
1514+
.arg("add")
1515+
.arg("--intent-to-add")
1516+
.arg("intent.txt")
1517+
.assert()
1518+
.success();
1519+
1520+
cwd.child("test.py").write_str("a=1\n")?;
1521+
context.git_add("test.py");
1522+
cwd.child("test.py").write_str("a=1\nb = 2\n")?;
1523+
1524+
let filters: Vec<_> = context
1525+
.filters()
1526+
.into_iter()
1527+
.chain([(r"/\d+-\d+.patch", "/[TIME]-[PID].patch")])
1528+
.collect();
1529+
1530+
cmd_snapshot!(filters, context.run(), @r"
1531+
success: false
1532+
exit_code: 1
1533+
----- stdout -----
1534+
rewrite-python...........................................................Failed
1535+
- hook id: rewrite-python
1536+
- files were modified by this hook
1537+
1538+
----- stderr -----
1539+
Unstaged changes detected, stashing unstaged changes to `[HOME]/patches/[TIME]-[PID].patch`
1540+
Stashed changes conflicted with changes made by hook, rolling back the hook changes
1541+
Restored working tree changes from `[HOME]/patches/[TIME]-[PID].patch`
1542+
");
1543+
1544+
assert_eq!(context.read("intent.txt"), "preserve me\n");
1545+
assert_eq!(context.read("test.py"), "a=1\nb = 2\n");
1546+
1547+
let output = git_cmd(cwd)
1548+
.arg("diff")
1549+
.arg("--diff-filter=A")
1550+
.arg("--name-only")
1551+
.arg("--")
1552+
.arg("intent.txt")
1553+
.output()?;
1554+
assert!(output.status.success(), "{output:?}");
1555+
assert_eq!(String::from_utf8(output.stdout)?, "intent.txt\n");
1556+
1557+
Ok(())
1558+
}
1559+
14941560
#[cfg(unix)]
14951561
#[test]
14961562
fn restore_on_interrupt() -> Result<()> {

0 commit comments

Comments
 (0)