Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the current state of my staging area?

Tags:

git

Question:
I added some files to my staging area. I want to temporarily save this information. How to?

Background:
Sometimes I perform some bigger refactorings. It only really makes sense to commit the complete result.
During this refactoring, I also make some unrelated changes which I would like to commit independently.
For example, the refactoring renamed a method. The unrelated change fixed a spelling error on one parameter of another method in the same class.
Now, assume I already added most of the files to the staging area when I realize that I forgot to commit one of the unrelated changes beforehand.
Adding the files to the staging area takes time, because I check every single file to make sure that I really only commit what I want to. So, simply removing them all from the staging area is not the solution.
What I would like to do instead:

  1. Save the current state of the staging area
  2. Remove all staged files
  3. Stage the unrelated change
  4. Commit the unrelated change
  5. Re-apply the saved state to the staging area.

Is this somehow possible?

An alternate solution would be the possibility of multiple staging areas, but I don't think that's possible.

like image 835
Daniel Hilgarth Avatar asked Feb 22 '13 08:02

Daniel Hilgarth


2 Answers

The following chain of commands should do the trick

git commit -m "temporary" # save current stage are as an actual commit
git commit unrelated_files -m "The other feature"
git stash # hide the rest
git rebase -i HEAD~2 # change the order of two last commits
git reset HEAD^ # rollback the "temporary" commit
git add . # add everything from that commit back to staging
git stash pop # and return back all initially unstaged stuff
like image 109
aragaer Avatar answered Sep 28 '22 05:09

aragaer


You definitely need git stash

This will save your current work, and leave your directory as if you did a reset to HEAD. You can now switch branches, do some work on another topic.

When you're ready to work on your feature again, re-apply your stashed changes with git stash apply

You can combine multiple stashes, git stash list will list them, then you can select wich one to apply, such as git stash apply @{1}

Edit :

As @nevik-rehnel said in the comments, you can also use interactive adding.

Unstage everything, use git add -p to stage the unrelated changes, commit, then restage everything.

like image 30
Intrepidd Avatar answered Sep 28 '22 05:09

Intrepidd