Home > Software engineering >  If commits are snapshots, then why does `git stash pop` retain your changes from after the stash?
If commits are snapshots, then why does `git stash pop` retain your changes from after the stash?

Time:04-06

In my quest to understand git a little bit better, I am learning that:

  1. Commits are not changes/deltas, they are snapshots
  2. Stashes are commits

I had assumed for years that commits were deltas but they are actually snapshots. Got it.

Now I do this:

  1. Type some text in file A
  2. Stash
  3. Type some text in file B
  4. Commit
  5. Stash pop

I am expecting that stash pop will delete the text in file B, because it is applying a snapshot of the project from before this text was added. But this is not the case, it applies the stash as if it is a delta, not a snapshot.

So what am I missing here? What does it really mean for commits to be snapshots?

CodePudding user response:

it applies the stash as if it is a delta, not a snapshot

Correct. It is in itself a snapshot, but "apply" is a form of merge and is enacted as a diff from the HEAD off which it was formed. The stash commit did not remove the text in file B in relation to the HEAD commit that preceded it, so applying it does not remove the text.

If you don't understand merge logic, you might want to read my https://www.biteinteractive.com/understanding-git-merge/. Not only merge itself but revert, cherry pick, rebase, and your "apply" all use merge logic. (This is why any of them, including applying a stash, can fail due to a merge conflict.)

  •  Tags:  
  • git
  • Related