Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor: multi-dimensional simplifications (hook_filter, RAII stash) (#403)

Maximilian Roose7ee53f09032
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 93b1f8e9b..3633f89ae 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -17,7 +17,7 @@
//! This ensures approval happens exactly once at the command entry point,
//! eliminating the need to thread `auto_trust` through execution layers.
-use super::hooks::{HookSource, ParsedFilter};
+use super::hook_filter::{HookSource, ParsedFilter};
use super::project_config::{HookCommand, collect_commands_for_hooks};
use crate::output;
use anyhow::Context;
diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rs
new file mode 100644
index 000000000..1cceed8be
--- /dev/null
+++ b/src/commands/hook_filter.rs
@@ -0,0 +1,56 @@
+//! Hook filter types for command filtering by source and name.
+//!
+//! These types are shared between `hooks.rs` (command preparation/execution)
+//! and `command_approval.rs` (approval flow). Re-exported from `hooks.rs`
+//! for backward compatibility.
+
+/// Distinguishes between user hooks and project hooks for command preparation.
+///
+/// Approval for project hooks is handled at the gate (command entry point),
+/// not during hook execution.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display)]
+#[strum(serialize_all = "kebab-case")]
+pub enum HookSource {
+ /// User hooks from ~/.config/worktrunk/config.toml (no approval required)
+ User,
+ /// Project hooks from .worktrunk.toml (approval handled at gate)
+ Project,
+}
+
+/// A parsed name filter, optionally scoped to a specific source.
+///
+/// Supports formats:
+/// - `"foo"` - matches commands named "foo" from any source
+/// - `"user:foo"` - matches only user's command named "foo"
+/// - `"project:foo"` - matches only project's command named "foo"
+/// - `"user:"` or `"project:"` - matches all commands from that source
+pub struct ParsedFilter<'a> {
+ pub source: Option<HookSource>,
+ pub name: &'a str,
+}
+
+impl<'a> ParsedFilter<'a> {
+ pub fn parse(filter: &'a str) -> Self {
+ if let Some(name) = filter.strip_prefix("user:") {
+ Self {
+ source: Some(HookSource::User),
+ name,
+ }
+ } else if let Some(name) = filter.strip_prefix("project:") {
+ Self {
+ source: Some(HookSource::Project),
+ name,
+ }
+ } else {
+ Self {
+ source: None,
+ name: filter,
+ }
+ }
+ }
+
+ /// Check if this filter matches the given source.
+ pub(crate) fn matches_source(&self, source: HookSource) -> bool {
+ self.source.is_none() || self.source == Some(source)
+ }
+}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index ad04836f7..1d1406a23 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -62,56 +62,8 @@ pub enum HookFailureStrategy {
Warn,
}
-/// Distinguishes between user hooks and project hooks for command preparation.
-///
-/// Approval for project hooks is handled at the gate (command entry point),
-/// not during hook execution.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display)]
-#[strum(serialize_all = "kebab-case")]
-pub enum HookSource {
- /// User hooks from ~/.config/worktrunk/config.toml (no approval required)
- User,
- /// Project hooks from .worktrunk.toml (approval handled at gate)
- Project,
-}
-
-/// A parsed name filter, optionally scoped to a specific source.
-///
-/// Supports formats:
-/// - `"foo"` - matches commands named "foo" from any source
-/// - `"user:foo"` - matches only user's command named "foo"
-/// - `"project:foo"` - matches only project's command named "foo"
-/// - `"user:"` or `"project:"` - matches all commands from that source
-pub struct ParsedFilter<'a> {
- pub source: Option<HookSource>,
- pub name: &'a str,
-}
-
-impl<'a> ParsedFilter<'a> {
- pub fn parse(filter: &'a str) -> Self {
- if let Some(name) = filter.strip_prefix("user:") {
- Self {
- source: Some(HookSource::User),
- name,
- }
- } else if let Some(name) = filter.strip_prefix("project:") {
- Self {
- source: Some(HookSource::Project),
- name,
- }
- } else {
- Self {
- source: None,
- name: filter,
- }
- }
- }
-
- /// Check if this filter matches the given source.
- fn matches_source(&self, source: HookSource) -> bool {
- self.source.is_none() || self.source == Some(source)
- }
-}
+// Re-export for backward compatibility with existing imports
+pub use super::hook_filter::{HookSource, ParsedFilter};
/// Prepare hook commands from both user and project configs.
///
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 4eabce64f..142c902bc 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -7,6 +7,7 @@ pub mod configure_shell;
pub mod context;
mod for_each;
mod hook_commands;
+mod hook_filter;
mod hooks;
pub mod init;
pub mod list;
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 650e71d37..2e3a7c015 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -323,39 +323,72 @@ fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {
Ok(())
}
+/// Stash guard that auto-restores on drop.
+///
+/// Created by `prepare_target_worktree()` when the target worktree has changes
+/// that don't conflict with the push. Automatically restores the stash when
+/// dropped, ensuring cleanup happens in both success and error paths.
+#[must_use = "stash guard restores immediately if dropped; hold it until push completes"]
pub(crate) struct TargetWorktreeStash {
+ /// Inner data wrapped in Option so we can take() in Drop.
+ /// None means already restored (or disarmed).
+ inner: Option<StashData>,
+}
+
+struct StashData {
repo: Repository,
path: PathBuf,
stash_ref: String,
}
-impl TargetWorktreeStash {
- pub(crate) fn new(path: &Path, stash_ref: String) -> Self {
- Self {
- repo: Repository::at(path),
- path: path.to_path_buf(),
- stash_ref,
- }
- }
-
- pub(crate) fn restore(self) -> anyhow::Result<()> {
- crate::output::print(progress_message(cformat!(
+impl StashData {
+ /// Restore the stash, printing progress and warning on failure.
+ fn restore(self) {
+ let _ = crate::output::print(progress_message(cformat!(
"Restoring stashed changes in <bold>{}</>...",
format_path_for_display(&self.path)
- )))?;
+ )));
if let Err(_e) = self
.repo
.run_command(&["stash", "pop", "--quiet", &self.stash_ref])
{
- crate::output::print(warning_message(cformat!(
+ let _ = crate::output::print(warning_message(cformat!(
"Failed to restore stash <bold>{stash_ref}</> - run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",
stash_ref = self.stash_ref,
path = format_path_for_display(&self.path),
- )))?;
+ )));
+ }
+ }
+}
+
+impl Drop for TargetWorktreeStash {
+ fn drop(&mut self) {
+ if let Some(data) = self.inner.take() {
+ data.restore();
+ }
+ }
+}
+
+impl TargetWorktreeStash {
+ pub(crate) fn new(path: &Path, stash_ref: String) -> Self {
+ Self {
+ inner: Some(StashData {
+ repo: Repository::at(path),
+ path: path.to_path_buf(),
+ stash_ref,
+ }),
}
+ }
- Ok(())
+ /// Explicitly restore the stash now, preventing Drop from restoring again.
+ ///
+ /// Use this when you need the restore to happen at a specific point
+ /// (e.g., before a success message). Drop handles errors/early returns.
+ pub(crate) fn restore_now(&mut self) {
+ if let Some(data) = self.inner.take() {
+ data.restore();
+ }
}
}
@@ -510,4 +543,35 @@ mod tests {
// All files are tracked (modified, staged, etc.)
assert!(parse_untracked_files(" M file1.txt\0M file2.txt\0").is_empty());
}
+
+ #[test]
+ fn test_stash_guard_restore_now_clears_inner() {
+ // Create a guard - note: this doesn't actually create a stash since we're not
+ // in a real git repo with that stash ref. We're just testing the state machine.
+ let mut guard = TargetWorktreeStash::new(std::path::Path::new("/tmp"), "stash@{0}".into());
+
+ // Inner should be populated
+ assert!(guard.inner.is_some());
+
+ // restore_now() should clear inner (the restore itself will fail since no real repo,
+ // but that's expected - we're testing the state transition)
+ guard.restore_now();
+
+ // Inner should now be None
+ assert!(guard.inner.is_none());
+
+ // Calling restore_now() again is a no-op
+ guard.restore_now();
+ assert!(guard.inner.is_none());
+ }
+
+ #[test]
+ fn test_stash_guard_drop_clears_inner() {
+ // Test that Drop also consumes the inner
+ let guard = TargetWorktreeStash::new(std::path::Path::new("/tmp"), "stash@{0}".into());
+
+ // Just drop it - the restore will fail (no real repo) but Drop shouldn't panic
+ drop(guard);
+ // If we get here, Drop worked without panicking
+ }
}
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index c936a5377..b2ad48911 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -924,7 +924,8 @@ pub fn handle_push(
}
// Check for conflicting changes in target worktree (auto-stash safe changes)
- let mut target_worktree_stash =
+ // The stash guard auto-restores on drop (error paths), or explicitly via restore_now()
+ let mut stash_guard =
repo.prepare_target_worktree(target_worktree_path.as_ref(), &target_branch)?;
// Count commits and show what will be pushed
@@ -998,28 +999,26 @@ pub fn handle_push(
// Get git common dir for the push
let git_common_dir = repo.git_common_dir()?;
- // Perform the push
+ // Perform the push - stash guard will auto-restore on any exit path
// Use --receive-pack to pass config to the receiving end without permanently mutating repo config
let push_target = format!("HEAD:{}", target_branch);
- if let Err(e) = repo.run_command(&[
+ repo.run_command(&[
"push",
"--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",
git_common_dir.to_str().unwrap(),
&push_target,
- ]) {
- if let Some(stash) = target_worktree_stash.take() {
- stash.restore()?;
- }
+ ])
+ .map_err(|e| {
// CommandFailed contains raw git output, wrap in PushFailed for proper formatting
- return Err(GitError::PushFailed {
+ GitError::PushFailed {
target_branch: target_branch.clone(),
error: e.to_string(),
}
- .into());
- }
+ })?;
- if let Some(stash) = target_worktree_stash.take() {
- stash.restore()?;
+ // Restore stash before success message (Drop handles error paths automatically)
+ if let Some(guard) = stash_guard.as_mut() {
+ guard.restore_now();
}
// Show success message after push completes