gitpre-commitunstage

How to undo a "git add" keeping the previously staged version? (Does the index have history?)


I have a question that's similar to How to undo 'git add' before commit?, but with an important difference:

background:

I'm running some code that's generating files which I'll add to my repository when complete. The code that's generating the files is new code, and in flux, so I'm sometimes running it more than once, with changes.

Along the way, I'm adding the generated files to the index, so they'll be ready for one big commit at the end. This also allows me to check to see if my changes to the code create changes in the output, and if so, what those changes are. But... I accidentally ran another git add on a file that had showed up both in the Changes to be committed section (as a new file) and the Changes not staged for commit section (as modified). I meant to run a git diff on it, but I slipped and re-added it, so now I don't have a way to diff it (that I know of), so...

the question:

Is there a way to undo just the last staging operation, such that a previously-added version will still/again be in the index, and the modified file will again be in my working tree, so that I can diff it?

None of this is committed or anything, as the goal is to commit it all together when I'm done with this little round of development. I just really like that git can normally show me changes to new files, before they're committed... but... I missed a chance at that, and am now wondering if there's a way to get it back. ?

The things I've looked up so far seem to be able to get me back to the last commit (no file) or the current state of the file (which I have anyway), but not the in-between of going to a previous version from the index, that's never been part of a commit. Any hints on even whether or not this is possible (even a solid answer that it's not, preferably with an explanation of why this is the case) would be appreciated.


Solution

  • There's no direct way to get to the last staged version of a file. There's no versioning of the index file, that's what you are supposed to use commit for. In future you could consider making temporary commits more often (e.g. with commit --amend) and then at least your previous versions would be in your reflog (e.g. git log -g).

    However, all staged versions of all files will have been added to the git object database. You should be able to find them with git fsck --lost-found. This will write out all "dangling" blobs into .git/lost-found/other. Unfortunately they won't be in any particular order or have their original file name but any lost blob should be in there somewhere.