If some changes are added to the index and there are some changes that are not added to the index, how do I swap this two sets of changes?
Charles Bailey has a more complete solution involving commits and managing potential conflict resolution.
I am trying to use only git stash
, except what I initially overlooked was that git stash
save will save both the index and the private files (which is inconvenient when you want to swap the index content with the private files content)
You could:
git commit
-m "temp commit" (create a commit for the current index)git stash
(stashing obviously what is not yet added to the index)git reset --soft HEAD^
(preserve the files previously committed)git stash
againgit drop stash@{1}
(applying not what you just stashed, but what you stashed before, i.e the initial changes that weren't yet added to the index)git add -A
At the end:
- what was initially in the index ends up being stashed
- what was not added to the index is now added.
It think that this is easiest to do with temporary commits. When you have staged and unstaged commits, you have the possibility of conflicts when trying to reorder the changes.
Make a commit with the staged changes, create a branch for later use:
git commit -m "Saved staged"
git branch save-staged
Make a commit with the unstaged changes (if the unstaged changes include new files you may need to explicitly git add
them first):
git commit -a -m "Unstaged changes"
Rebase the unstaged changes onto the original HEAD (may involve conflict resolution):
git rebase --onto HEAD^^ HEAD^
Rebase the staged changes onto the unstaged changes (may involve conflict resolution):
git reset --hard save-staged
git rebase --onto HEAD@{1} HEAD^
Finally, reset the index to the (originally) unstaged changes:
git reset HEAD^
And move the branch pointer back to the original HEAD:
git reset --soft HEAD^
Removed temporary branch:
git branch -D save-staged
The way with patches:
Save patches for both staged and unstaged states
git diff >> unstaged.patch
git diff --cached >> staged.patch
Apply originally unstaged changes
git reset --hard
git apply unstaged.patch
Stage this changes except the patch files
git add -A
git reset -- staged.patch unstaged.patch
Apply originally staged changes
git apply staged.patch
Remove patch files
rm staged.patch unstaged.patch