Why does git stash creates 2 commit objects? Seems like 1 was adequate


When doing git stash 2 commits are created. One is referenced by the stash ref and has 2 parent commits. One parent is the index of where we did the stash. The other parent has the actual contents of what we stashed.
Why are 2 commits needed for the stash? It seems to me that only 1 was sufficient. I.e. just make stash ref to the commit that has the actual contents.
Would this not work?

Show source
| git   | git-stash   | git-commit   2017-01-03 11:01 1 Answers

Answers ( 1 )

  1. 2017-01-03 11:01

    git stash will, in fact, make up to three commits. The two that you have observed are the default two: one for the index state—remember that in Git, the index, also called the staging area, contains the next commit to write, and is updated every time you git add new contents—and one for the work-tree state. These may differ from each other and/or from the HEAD commit at the time you create the stash.

    The fundamental issue is that git stash is not meant only to save your current work-tree, nor only to save your current index state, nor only to save some combination of the two. If you intended to save the current index state, you could simply make an ordinary commit. If you intended to save a combination of the two, you could simply run git commit -a.

    Instead, git stash defaults to saving both the index state and the work-tree state, separately. This allows you to retrieve both separate states again later, if that's what you mean to do. It allows you to retrieve a mashed-together version of both states, if that's what you mean to do. And, if you use -u or -a, so that git stash makes its third commit containing untracked or untracked-and-ignored files, it allows you recover all those various states.

    You express your final intent not at the time you save the stash, but rather at the time you recover it.1 This may not be the best possible design, since (a) sometimes it's not possible to recover your intended state, and (b) if you use git stash pop without --index when you had intended to use --index, this destroys the separated state and then discards both commits, making it exceedingly difficult to recover. In general, though, deferring decisions is usually a good approach.

    1If you use --keep-index at the time you save the stash, you are in fact asserting at least some intent at save-time. But that's another matter entirely. Moreover, there's a long-standing bug in git stash that makes keeping both index and work-tree state separate problematic. See here for details.

◀ Go back