gitsw automatically manages your uncommitted changes using Git’s stash feature. When you switch branches, it saves your work and automatically restores it when you come back.
How It Works
The auto-stash feature follows a simple three-step workflow:Leaving a Branch
When you switch away from a branch with uncommitted changes, The stash is created with the flag
gitsw prompts you to stash them:INCLUDE_UNTRACKED, meaning both staged and unstaged files are saved. Each stash is tagged with the branch name: git-switch: branch-name.Working on Another Branch
Switch freely between branches.
gitsw tracks which stash belongs to which branch in .git/git-switch.json:Stash Creation
When leaving a branch,gitsw detects uncommitted changes using Git’s status API:
- Staged changes: Files added with
git add - Modified files: Changes to tracked files
- Untracked files: New files not yet added to Git
src/git.rs:128-134:
The stash OID (Object ID) is stored in the branch state so
gitsw can identify and restore the correct stash later.Auto-Restore on Return
When you switch back to a branch,gitsw checks if there’s a stash associated with it (src/main.rs:457-500):
git2::Repository::stash_apply(), which attempts to merge the stashed changes with the current working tree.
Conflict Handling
If applying the stash causes conflicts (e.g., the branch has diverged significantly),gitsw prompts you with options:
- Apply
- Skip
- Abort
The stash is applied with conflict markers in the affected files. You’ll need to resolve them manually:The stash is preserved so you don’t lose your work.
When conflicts occur,
gitsw preserves the stash. This prevents data loss even if the automatic restore fails.Disabling Auto-Stash
You can disable automatic stashing with the--no-stash flag:
- You want to manually manage stashes
- You’re sure there are no conflicts
- You’re switching temporarily and will return immediately
Viewing Stashed Branches
See all branches with active stashes:Stash Lifecycle
The complete lifecycle of a stash ingitsw:
- Created: When leaving a branch with uncommitted changes (
src/main.rs:388-409) - Stored: The stash OID is saved in
.git/git-switch.json(src/state.rs:75-83) - Applied: When returning to the branch (
src/main.rs:465-472) - Dropped: Automatically removed after successful application (
src/git.rs:143-148) - Cleared: Removed from state tracking (
src/state.rs:112-116)
Implementation Details
State Tracking
Each branch’s state is tracked in.git/git-switch.json:
Stash Operations
TheGitRepo wrapper in src/git.rs provides three key operations:
stash_save(): Creates a stash with untracked filesstash_apply(): Restores stash contents to working treestash_drop(): Removes stash from Git’s stash list
Finding Stashes
gitsw uses the stash OID to find the exact stash, even if you’ve manually created other stashes:
gitsw only manages its own stashes and doesn’t interfere with your manual stash workflow.