diff --git a/src/commands/branch.rs b/src/commands/branch.rs index ddaa51f..bd4e5b2 100644 --- a/src/commands/branch.rs +++ b/src/commands/branch.rs @@ -2,6 +2,7 @@ use anyhow::{bail, Result}; use crate::cli::BranchCommands; use crate::context::Ctx; +use crate::stash; use crate::state::BranchEntry; use crate::ui; use crate::validate; @@ -51,7 +52,7 @@ fn create(ctx: &Ctx, name: &str) -> Result<()> { }); ctx.save_stack(&stack)?; - ctx.git.checkout(name)?; + stash::checkout_with_stash(ctx, name)?; ui::success(&format!("Added '{name}' to stack '{}'", stack.name)); ui::info(&format!("Child of '{current}'")); diff --git a/src/commands/switch.rs b/src/commands/switch.rs index 8305fd4..405f8ba 100644 --- a/src/commands/switch.rs +++ b/src/commands/switch.rs @@ -4,6 +4,7 @@ use console::{Key, Term}; use std::collections::HashSet; use crate::context::Ctx; +use crate::stash; use crate::ui; struct PickerItem { @@ -48,7 +49,7 @@ pub fn run(branch: Option, ctx: &Ctx) -> Result<()> { ui::info("Already on that branch."); return Ok(()); } - ctx.git.checkout(&target)?; + stash::checkout_with_stash(ctx, &target)?; ui::success(&format!("Switched to {target}")); return Ok(()); } @@ -177,7 +178,7 @@ pub fn run(branch: Option, ctx: &Ctx) -> Result<()> { if *target == current { ui::info("Already on that branch."); } else { - ctx.git.checkout(target)?; + stash::checkout_with_stash(ctx, target)?; ui::success(&format!("Switched to {target}")); } } diff --git a/src/git.rs b/src/git.rs index 8550310..5200d1e 100644 --- a/src/git.rs +++ b/src/git.rs @@ -287,6 +287,70 @@ impl Git { Ok(()) } + /// Stash working tree changes with a message tag. + /// Uses --include-untracked to capture new files. + pub fn stash_push(&self, message: &str) -> Result<()> { + self.run(&["stash", "push", "--include-untracked", "-m", message])?; + Ok(()) + } + + /// List stash entries whose message matches the given string exactly. + /// Returns a vec of stash indices (e.g. 0, 2, 5) for matching entries, + /// ordered from most recent to oldest. + pub fn stash_list_matching(&self, message: &str) -> Result> { + let output = self.run_raw(&["stash", "list", "--format=%gd %gs"])?; + let stdout = String::from_utf8(output.stdout) + .context("git stash list output was not valid UTF-8")?; + + if stdout.trim().is_empty() { + return Ok(vec![]); + } + + let mut matches = vec![]; + for line in stdout.trim().lines() { + // Lines look like: "stash@{0} On branch-name: gw:feature-a" + // The %gd is "stash@{N}" and %gs is the stash subject + let Some((gd, gs)) = line.split_once(' ') else { + continue; + }; + // Check if the stash subject ends with our exact message. + // git prepends "On : " to the message, so we match the suffix. + if gs.ends_with(message) { + // Parse the index from stash@{N} + if let Some(idx_str) = gd.strip_prefix("stash@{").and_then(|s| s.strip_suffix('}')) + { + if let Ok(idx) = idx_str.parse::() { + matches.push(idx); + } + } + } + } + Ok(matches) + } + + /// Pop a stash entry by index. Returns whether conflicts occurred. + /// On clean pop, the stash entry is removed. On conflict, the stash + /// entry remains and conflict markers are left in the working tree. + pub fn stash_pop(&self, index: usize) -> Result { + let output = self.run_raw(&["stash", "pop", &format!("stash@{{{index}}}")])?; + + if output.status.success() { + return Ok(false); + } + + // Check if this was a conflict (stash applied with merge conflicts) + // vs an actual error (bad stash index, etc.) + if self.has_unresolved_conflicts()? { + return Ok(true); + } + + let stderr = String::from_utf8_lossy(&output.stderr); + Err(anyhow!( + "git stash pop failed: {}", + stderr.trim() + )) + } + /// Atomically update multiple refs using git update-ref --stdin. /// Each entry is (branch_name, target_sha). pub fn update_ref_transaction(&self, updates: &[(String, String)]) -> Result<()> { diff --git a/src/lib.rs b/src/lib.rs index de46887..267ae17 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod context; pub mod gh; pub mod git; pub mod propagation; +pub mod stash; pub mod state; pub mod ui; pub mod validate; diff --git a/src/stash.rs b/src/stash.rs new file mode 100644 index 0000000..f99776a --- /dev/null +++ b/src/stash.rs @@ -0,0 +1,69 @@ +use anyhow::Result; + +use crate::context::Ctx; +use crate::ui; + +const STASH_PREFIX: &str = "gw:"; + +fn stash_message(branch: &str) -> String { + format!("{STASH_PREFIX}{branch}") +} + +/// Auto-stash dirty work on current branch, checkout target, +/// auto-unstash if target has a tagged stash. +/// +/// If checkout fails after stashing, restores the stash before returning +/// the error (safety invariant: never lose uncommitted work). +/// +/// During active propagation, skips auto-stash/unstash and falls back +/// to a plain checkout. +pub fn checkout_with_stash(ctx: &Ctx, target: &str) -> Result<()> { + // Skip auto-stash during active propagation to avoid stashing + // conflict markers or interfering with the rebase cascade. + if ctx.propagation_state()?.is_some() { + ctx.git.checkout(target)?; + return Ok(()); + } + + let current = ctx.git.current_branch()?; + let dirty = !ctx.git.is_working_tree_clean()?; + + // Stash if dirty + if dirty { + ctx.git.stash_push(&stash_message(¤t))?; + ui::info(&format!("Stashed changes for {current}")); + } + + // Checkout with rollback on failure + if let Err(e) = ctx.git.checkout(target) { + if dirty { + // Restore the stash we just pushed so the user doesn't lose work + let _ = ctx.git.stash_pop(0); + } + return Err(e); + } + + // Unstash if target has a tagged stash + let matches = ctx.git.stash_list_matching(&stash_message(target))?; + if !matches.is_empty() { + let index = matches[0]; // Most recent match + let had_conflicts = ctx.git.stash_pop(index)?; + if had_conflicts { + ui::warn(&format!( + "Restored stashed changes for {target} (with conflicts)" + )); + ui::warn("Resolve conflict markers in your working tree."); + ui::warn("The stash was not dropped. Run `git stash drop` after resolving."); + } else { + ui::info(&format!("Restored stashed changes for {target}")); + } + if matches.len() > 1 { + ui::warn(&format!( + "Note: {} additional gw stash(es) exist for {target}", + matches.len() - 1 + )); + } + } + + Ok(()) +} diff --git a/tests/branch_test.rs b/tests/branch_test.rs index 035a428..c602f77 100644 --- a/tests/branch_test.rs +++ b/tests/branch_test.rs @@ -346,3 +346,62 @@ fn full_branch_lifecycle() { .success() .stdout(predicate::str::contains("No stacks")); } + +// ============================================================ +// Auto-stash on branch create +// ============================================================ + +#[test] +fn branch_create_auto_stashes_dirty_work() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "auth work"); + + // Create dirty work on auth + std::fs::write(repo.path.join("dirty.txt"), "wip").unwrap(); + + // Branch create should auto-stash the dirty work + gw_cmd(&repo.path) + .args(["branch", "create", "auth-tests"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed changes for auth")) + .stdout(predicate::str::contains("Added 'auth-tests' to stack 'auth'")); + + // Should be on the new branch with a clean working tree + assert_eq!(repo.current_branch(), "auth-tests"); + assert!(!repo.path.join("dirty.txt").exists()); + + // Switch back to auth - should restore the stashed work + gw_cmd(&repo.path) + .args(["switch", "auth"]) + .assert() + .success() + .stdout(predicate::str::contains("Restored stashed changes for auth")); + + assert!(repo.path.join("dirty.txt").exists()); + assert_eq!(std::fs::read_to_string(repo.path.join("dirty.txt")).unwrap(), "wip"); +} + +#[test] +fn branch_create_clean_tree_no_stash() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "auth work"); + + // Branch create with clean tree - no stash messages + gw_cmd(&repo.path) + .args(["branch", "create", "auth-tests"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed").not()) + .stdout(predicate::str::contains("Added 'auth-tests'")); +} diff --git a/tests/switch_test.rs b/tests/switch_test.rs index 64e910a..bc70e03 100644 --- a/tests/switch_test.rs +++ b/tests/switch_test.rs @@ -183,3 +183,238 @@ fn switch_to_base_branch() { assert_eq!(repo.current_branch(), main_branch); } + +// --- Auto-stash tests --- + +#[test] +fn switch_auto_stashes_dirty_work() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "auth work"); + + gw_cmd(&repo.path) + .args(["branch", "create", "auth-tests"]) + .assert() + .success(); + repo.commit_file("b.txt", "b", "tests work"); + + // Create dirty work on auth-tests + std::fs::write(repo.path.join("dirty.txt"), "wip").unwrap(); + + // Switch to auth - should auto-stash + gw_cmd(&repo.path) + .args(["switch", "auth"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed changes for auth-tests")) + .stdout(predicate::str::contains("Switched to auth")); + + // dirty.txt should not be on auth + assert!(!repo.path.join("dirty.txt").exists()); + + // Switch back to auth-tests - should auto-unstash + gw_cmd(&repo.path) + .args(["switch", "auth-tests"]) + .assert() + .success() + .stdout(predicate::str::contains("Restored stashed changes for auth-tests")) + .stdout(predicate::str::contains("Switched to auth-tests")); + + // dirty.txt should be back + assert!(repo.path.join("dirty.txt").exists()); + assert_eq!(std::fs::read_to_string(repo.path.join("dirty.txt")).unwrap(), "wip"); +} + +#[test] +fn switch_clean_branch_no_stash_messages() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "auth work"); + + gw_cmd(&repo.path) + .args(["branch", "create", "auth-tests"]) + .assert() + .success(); + + // Switch with clean working tree - no stash messages + gw_cmd(&repo.path) + .args(["switch", "auth"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed").not()) + .stdout(predicate::str::contains("Restored").not()); +} + +#[test] +fn switch_same_branch_dirty_no_stash() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + + // Create dirty work + std::fs::write(repo.path.join("dirty.txt"), "wip").unwrap(); + + // Switch to same branch - should be no-op, no stash + gw_cmd(&repo.path) + .args(["switch", "auth"]) + .assert() + .success() + .stdout(predicate::str::contains("Already on that branch")) + .stdout(predicate::str::contains("Stashed").not()); + + // dirty.txt should still be there + assert!(repo.path.join("dirty.txt").exists()); +} + +#[test] +fn switch_stashes_untracked_files() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "auth work"); + + gw_cmd(&repo.path) + .args(["branch", "create", "auth-tests"]) + .assert() + .success(); + + // Create an untracked file (not git-added) + std::fs::write(repo.path.join("new-file.txt"), "new stuff").unwrap(); + + // Switch away - should stash the untracked file + gw_cmd(&repo.path) + .args(["switch", "auth"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed changes for auth-tests")); + + assert!(!repo.path.join("new-file.txt").exists()); + + // Switch back - should restore + gw_cmd(&repo.path) + .args(["switch", "auth-tests"]) + .assert() + .success() + .stdout(predicate::str::contains("Restored stashed changes for auth-tests")); + + assert!(repo.path.join("new-file.txt").exists()); + assert_eq!( + std::fs::read_to_string(repo.path.join("new-file.txt")).unwrap(), + "new stuff" + ); +} + +#[test] +fn switch_exact_branch_name_matching() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "features"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "work"); + + gw_cmd(&repo.path) + .args(["branch", "create", "feature-v2"]) + .assert() + .success(); + repo.commit_file("b.txt", "b", "v2 work"); + + gw_cmd(&repo.path) + .args(["branch", "create", "feature-v2-hotfix"]) + .assert() + .success(); + + // Create dirty work on feature-v2-hotfix + std::fs::write(repo.path.join("hotfix.txt"), "fix").unwrap(); + + // Switch to feature-v2 + gw_cmd(&repo.path) + .args(["switch", "feature-v2"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed changes for feature-v2-hotfix")); + + // Now create dirty work on feature-v2 + std::fs::write(repo.path.join("v2.txt"), "v2 wip").unwrap(); + + // Switch to features (root) + gw_cmd(&repo.path) + .args(["switch", "features"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed changes for feature-v2")); + + // Switch back to feature-v2 - should only restore feature-v2's stash, not feature-v2-hotfix's + gw_cmd(&repo.path) + .args(["switch", "feature-v2"]) + .assert() + .success() + .stdout(predicate::str::contains("Restored stashed changes for feature-v2")); + + assert!(repo.path.join("v2.txt").exists()); + assert!(!repo.path.join("hotfix.txt").exists()); // Should NOT be restored here + + // Switch to feature-v2-hotfix - should restore its own stash + gw_cmd(&repo.path) + .args(["switch", "feature-v2-hotfix"]) + .assert() + .success() + .stdout(predicate::str::contains("Restored stashed changes for feature-v2-hotfix")); + + assert!(repo.path.join("hotfix.txt").exists()); +} + +#[test] +fn switch_during_propagation_skips_auto_stash() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["stack", "create", "auth"]) + .assert() + .success(); + repo.commit_file("a.txt", "a", "auth work"); + + gw_cmd(&repo.path) + .args(["branch", "create", "auth-tests"]) + .assert() + .success(); + + // Create dirty work + std::fs::write(repo.path.join("dirty.txt"), "wip").unwrap(); + + // Simulate active propagation + repo.write_state_toml( + r#" +operation = "rebase" +stack = "auth" +started_at = "12345" +original_branch = "auth" +original_refs = [] +completed = [] +remaining = [] +"#, + ); + + // Switch should work but NOT auto-stash (git checkout will carry untracked files) + gw_cmd(&repo.path) + .args(["switch", "auth"]) + .assert() + .success() + .stdout(predicate::str::contains("Stashed").not()) + .stdout(predicate::str::contains("Switched to auth")); +} \ No newline at end of file