79215670

Date: 2024-11-22 15:50:28
Score: 0.5
Natty:
Report link

Even though the question is already over 6 years old, I want to add my answer here for people like me, that are confused by the git documentation on this and then land here from a Google search.

The answer of torek works and is probably the workflow as it is intended to be described in the git documentation. What's important to understand, is that when using the --keep-index option, the index will be kept (as the name suggests) but will still be stored in the stash itself. So you do the following:

# Assuming you have some changes in the index, that you
# want to do tests on, and then some more changes in
# your working directory.

$ git stash --keep-index

# Now do your tests.

$ git reset --hard
$ git stash pop --index

# Now the original situation is restored and you can
# commit.

Basically, after you're done testing you want to completely clean your index and working directory to have no uncommited changes and then reapply the stash. It will recover both the index and your unstaged changes.

There's a variation on this, that I have to use. I'm using a pre-commit hook to verify that code is properly formatted and documentation is complete. Now I have some changes that I want to commit and therefore I stage them but some other changes too that I not only want gone for the sake of testing but also would make me unable to commit. Then I do this:

# Assuming same situation again: There's some stuff
# in the index that you want to commit and also
# some other changes.

$ git stash --keep-index

# After testing:
$ git commit

$ git checkout HEAD~1 . # Note the "."
$ git stash pop
$ git reset .

# Now all your uncommited changes are in your
# working directory again.

The command git checkout HEAD~1 . basically means: "Make all my files be the same as they were one commit ago, but don't change the branch or anything." The "." at the end is crucial. Without it, you would just move the HEAD to the previous commit and be in a detached HEAD state. After that your files are the same as they were on the commit on which you made the stash. That's why you can just apply the stash here. And after that, you have some staged changes from the checkout command and some unstaged changes from applying the stash. The last command git reset . just serves to clean this up.

My problem with both of these workflows is what to do, when you learn you have to make changes during the testing phase. It seems to me the only good way is to recover all your changes with a reset and stash pop as in the 1st workflow, then make your changes, then add these changes too and then go back to the testing state again. With the 2nd workflow you can also just do the changes and commit and then at the end of it make sure they will not be overwritten again with your next commit.

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Timo