Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/commands/branch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}'"));
Expand Down
5 changes: 3 additions & 2 deletions src/commands/switch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use console::{Key, Term};
use std::collections::HashSet;

use crate::context::Ctx;
use crate::stash;
use crate::ui;

struct PickerItem {
Expand Down Expand Up @@ -48,7 +49,7 @@ pub fn run(branch: Option<String>, 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(());
}
Expand Down Expand Up @@ -177,7 +178,7 @@ pub fn run(branch: Option<String>, 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}"));
}
}
Expand Down
64 changes: 64 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<usize>> {
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 <branch>: " 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::<usize>() {
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<bool> {
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<()> {
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
69 changes: 69 additions & 0 deletions src/stash.rs
Original file line number Diff line number Diff line change
@@ -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(&current))?;
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(())
}
59 changes: 59 additions & 0 deletions tests/branch_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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'"));
}
Loading