2

I've done several changes on my local files in a parallel branch. I used git stash to save my changes and to get other changes into master without having to push online. So I had to solve some merge conflicts about files redudants files. Step by step, this is my code on git bash:

git stash
git pull origin master
git stash pop
git mergetool

I solved conflict about one file myFile.py using meld as mergetool. My problem is that I forgot a huge part of code in the remote file (myFile_remote_7572.py) during the merge step. Right now, I'm not able to find the file anywhere on my laptop. I want to restore it in order to find my last code without restarting merge step. Thanks...

2 Answers 2

3

While git mergetool likes to call some files local and others remote, it's really using a very bad set of names here. Everything in Git is local!

Importantly, the file you want is in a commit that is going to be hard to find, as it was also entirely local, despite git mergetool calling it "remote". I'm afraid this answer is going to be fairly long, too. Here's the TL;DR:

  • git stash pop is just git stash apply && git stash drop. If the apply step fails with a merge conflict, this omits the drop step, which is good.
  • The file you want was / is stored in a stash commit.
  • If you still have the stash commit, you can get the entire file from there. Since there was a merge conflict, git stash pop will not have dropped the stash on its own, so you may be in luck there.
  • You may also be able to get the conflict back into the index (aka staging area), as long as you have not committed the result.
  • If not, you may be able to dig out the stash commit, even if you have explicitly git stash droped it.

If the file is in an index staging slot, you can use git show to retrieve it:

git show :3:path/to/file.ext > /tmp/file.ext.recovered

This extracts the slot-3 version of path/to/file.ext to standard output, which here I redirect to a temporary file.

Or, if you find the w commit from the stash, you can use git show <hash>:<path> to view the saved file. For instance, if refs/stash itself still refers to the w commit, you can easily run:

git stash show stash:path/to/file.ext > /tmp/file.ext.recovered

to get it back.

Read on to see what the w commit is and how to find it, if necessary, if you cannot get the file you want straight from the index.

Long

First, let me note that git stash just makes and uses commits. When you run:

git stash        # aka "git stash save" or "git stash push"
...
git stash pop

you are creating a commit—well, two commits, really—at the save / push step, and then using that commit (one of the two) to perform a merge operation at the pop step.

Because the merge had conflicts, you need to know how merge really works. Using git mergetool lets you defer learning some of the details for a while, but it's time to dig into them.

Now, each commit in Git records a complete snapshot of the entire source tree. That's true of all regular commits, and also of the special commits that git stash makes. In fact, the main thing that is special about the stash commits is that they are on no branch.

How branches grow, and what it means to be on a branch

In normal operation in Git, you are "on" some branch such as master or develop. But what precisely does this mean? Well, let's sit down for a moment and imagine we are starting a new, completely empty repository, with no commits at all. We are on the branch master, but there are no commits. So we create some files, run git add on them, and run git commit, which creates the very first commit. It gets some big, ugly, seemingly-random hash ID, but for short let's just call it commit A. Now we can draw out the existing situation:

A   <-- master

Commit A holds the full snapshot of all of our files. Meanwhile the name master holds the hash ID of commit A, so we say that the name points to the commit.

To make a new commit, we make some changes to some file(s), run git add, and run git commit again. Git now makes a new commit, with a new, unique, big ugly apparently-random ID. This new commit B holds a full snapshot of all files—including files you did not change. It also holds the big ugly hash ID of commit A. So commit B now points to commit A.

Crucially, just after creating commit B, Git changes our name master to hold the ID of commit B. So now master points to B, and B points to A:

A <-B   <-- master

This notion, that a branch name points to the last commit on a branch, gives us the name for that commit. Git calls this the tip of the branch. The branch name always simply identifies the last commit on the branch.

Once a commit is made, it can never be changed in any way. (At most, you can decide you don't like B, and stop using it and start using a new commit that you prefer, that points back to, say, commit A. If you make the name master point to the replacement for B, Git seems to have changed B, but in fact, there's just a different tip commit, with a new and different hash ID.) So these internal arrows always go backwards and never change, so we can get away with just drawing lines. That's more convenient for the case where we actually start branching our commits:

A--B--C--D--E--F   <-- master
          \
           G--H   <-- develop

Now that we have two branch names, with two branch tips, we need a way to know which branch we're using. This is where the special name HEAD comes in: Git attaches the word HEAD to one of our various branches:

A--B--C--D--E--F   <-- master
          \
           G--H   <-- develop (HEAD)

This is what it means for us to be "on branch develop": if we make a new commit now, new commit I will point back to existing commit H, and Git will change develop—not master—to point to new commit I.

This also helps us figure out which commits are on which branch(es): commit H is on develop because it's the tip of develop, and commit F is on master because it's the tip of master. But commit G is also on develop because, by starting at H and working backwards, we can reach commit G. Likewise, commit E is on master because we can start at F and work backwards to get to E.

Interestingly, commits D and earlier are on both branches! We can start at either tip and work backwards and get there. Hence:

  • Some commits are on more than one branch. You find out by using the names to get to the tip commits, and then working backwards.

  • The name HEAD identifies which branch we're on, by being attached to one of the branch names.

For (much) more about this, I suggest reading and working through the web site, Think Like (a) Git.

Note that like everything else about a commit, the snapshot contained inside each commit is completely read-only. Nothing and no one can change any of these snapshot files. Moreover, files inside snapshots are in a special, compressed, Git-only format. This means you need an area in which you can work on / with your files, and that area is called the work-tree (or some minor spelling variant).

The files that you see, when you check out a commit, are in your work-tree. Here, they have their ordinary uncompressed form, and you can read them, and write on them to change them. These work-tree files are not stored in Git: they are only in your work-tree. That's why you must be careful with, e.g., git reset --hard, which will overwrite your work-tree files.

The index, also called the staging area and the cache

It's easy to see the point of commits—they hold every saved version of every file forever, so that you can always go back and see what you saved—and it's equally easy to see the need for the work-tree, since the commits are read-only. But Git has this strange thing halfway between commit and work-tree, which Git calls, variously, the index, the staging area, or sometimes the cache (depending on which bit of Git is doing the calling).

The best short description of the index is that it's where you build the next commit you will make. It contains a copy of every file, starting with the copies extracted from the current commit. That is, you git checkout some branch name, and Git extracts the commit to which that branch-name points. But it really puts the commit into the index first. The files in the index are still in the special, Git-only, compressed form. Then Git expands those files into the work-tree into their usable form. The key difference between the index copy and the committed copy is that you can overwrite the index copy.

This is what git add does: it just copies the work-tree version of a file into the index. If the file was there before, that throws away the old version and stores the new one, compressed and ready to go into a new commit. Until you run git commit, though, you can keep on replacing the file. It's only when you run git commit that Git freezes the index versions into a commit. (This is also how Git is so fast, compared to other systems that do not use this "index" idea.)

You might think you could get away without knowing about the index. It's almost possible! If you use git commit -a a lot, you can often pretend there's no index. But in fact, the index takes on an expanded role during merges, so you do have to know about it.

Merges

At this point it's pretty easy to see how a regular git merge works. Let's say you have the same graph as above, except that you run git checkout master to switch to the master branch:

A--B--C--D--E--F   <-- master (HEAD)
          \
           G--H   <-- develop

Now you'd like to incorporate work done on develop into master, so you run git merge develop. What Git does at this point is not to just copy commit H. If it did that, you would lose any changes you made in commits E and F. Instead, Git reads back through the graph—starting at H and working backwards, and simultaneously, starting at F and working backwards—to find the best common commit. Here, it's quite obvious which one is both shared (on both branches) and best, and that's commit D.

So at this point, Git runs, in effect, two separate git diff commands, to compare the snapshot in D against the two snapshots in F—what you've done, or changed since D, on branch master—and in H, what they have done on branch develop:

git diff --find-renames <hash-of-D> <hash-of-F>   # what we changed
git diff --find-renames <hash-of-D> <hash-of-H>   # what they changed

Git can now combine these changes, and apply the combined changes to the snapshot taken from commit D. This combining of changes, from some common starting point, is the action part of git merge. I like to say that this is the to merge verb: Git does the verb, the to merge, by comparing the common starting commit to the two ending commits, and combining the changes.

If all goes well—if there are no conflicts and Git thinks it has combined these two sets of changes correctly—Git will go ahead and make a new commit, using the combined changes. The new commit adds on to the current branch, but unlike a regular commit, it points back to both of its two input commits. The third input—the merge base—is implied: it's always going to be commit D since any future lookup starting from F and H will also find D. This new commit is a merge commit, which uses the word merge as an adjective. Git sometimes abbreviates this to just a merge, using the word merge as a noun:

A--B--C--D--E--F--I   <-- master (HEAD)
          \      /
           G----H   <-- develop

Now merge commit I points back to both F and H, while the name master points to merge commit I, and the merge is complete.

Resolving conflicts, index staging slots, and how git mergetool works

If the merge goes wrong, though, Git stops in the middle of the merge! In this case, Git leaves, for each conflicted file, all three copies of the file in the index. The way this works is that Git has four staging slots per file name. So if README.txt has a merge conflict, Git puts the base version of README.txt—from commit D—into staging slot 1, the --ours version of README.txt from commit F into staging slot 2, and the --theirs version of README.txt from commit H into staging slot 3. Staging slot zero is reserved for files that didn't have a merge conflict, so Git removes anything from slot zero.

Git also puts its best effort at combining the three versions of README.txt into the work-tree. You can edit this file in your own favorite editor (e.g., vim README.txt) and fix things up, if you like. If you do that, you can then run git add README.txt as usual. This tells Git to copy the work-tree version of README.txt into the index as usual; but this time, Git removes the three higher-stage entries, leaving you with just the stage-zero README.txt. This is how Git knows that you have resolved the conflict.

Until you resolve the conflict, the higher stages remain in the index. This is how Git knows that you haven't resolved the conflict. So the index controls which files Git considers successfully merged.

If you like git mergetool, you can use it. (I don't, and don't.) What it does is look through the index1 for these unmerged files. Upon finding them, it extracts all three of the index entries into three temporary files, which it calls:

  • base: for the merge base version from index slot 1
  • local: for the --ours version from index slot 2
  • remote: for the --theirs version from index slot 3

In an ordinary conflicted git merge style merge, these three copies are also available in the three commits, two of which have easy names: HEAD refers to the current branch, and MERGE_HEAD (which git merge writes out during the conflict) refers to the other commit—the one that git mergetool is calling remote even though it's a local commit.

So if this were an ordinary git merge, that would be where you could go to find your files. But this is not git merge, this is git stash pop, and now we're finally ready to look at where these are and go.


1As I just found out yesterday or so, git mergetool interacts with git rerere to ignore unmerged files that git rerere has resolved, even though those retain their higher-stage entries. If you don't use git rerere, this is not something to worry about.


Stashes

When git stash save or git stash push makes its commits—it normally makes two, one for the index and one for the work-tree—they work a lot like any ordinary commit. The main thing that is special about them, as we already noted, is that they are on no branches. But they do, just like any ordinary commit, point back to other commits. In fact, the index commit is an ordinary commit, and if the branch to which HEAD is attached were to advance as usual, HEAD would point to this index commit that I will call i:

...--J--K   <-- branch (HEAD)
         \
          i

The commit that git stash save or git stash push makes to hold the work-tree, which I call w, has the form of a merge commit because it has not one but two parents: it points back to commit K as its first parent, but to commit i as its second. So we can draw this as:

...--J--K   <-- branch (HEAD)
        |\
        i-w   <-- refs/stash

Git uses the special (not-a-branch) name refs/stash to remember commit w. Commit w remembers both commits i and (in this case) K. So the stash knows which commit it was on. It does not know, or care, which branch it was on—branch names don't really matter much in Git, after all—but it remembers which commit it was on, because commits matter. (In a sense, commits are all that matter, in Git!)

It's when you run git stash apply or git stash pop that Git decides whether to use commit i. Without --index, Git simply throws away commit i entirely, even though it carefully made it when you saved the stash. It does this partly so that you can make the keep-or-discard-index decision later; but perhaps more because it's very easy, and in practice pretty much necessary, to make the i commit first while building the stash. So we can kind of ignore the i commit here, since we're not going to use it.

Now that we have made the stash, now we might bring in some new commits. Let's say that after commit K, we bring in more commits with a "fast forward" from git pull:

...--J--K--...--L   <-- branch (HEAD)
        |\
        i-w   <-- refs/stash

It's now time to git stash apply the w commit.

The way Git handles this is to run the to merge part of git merge!

One of the two main inputs to pretty much any merge is always the HEAD commit, which is now commit L. The other main input is commit w. Git uses w's parent, commit K, as the merge base.2 So Git runs, in effect, two git diff commands as usual:

git diff --find-renames <hash-of-K> <hash-of-L>   # what "we" did
git diff --find-renames <hash-of-K> <hash-of-w>   # what "they" did

Git now attempts to combine the two sets of changes and apply them to the snapshot from commit K. If all goes well—of course it didn't, but if it had—Git would consider the "apply" complete, and discard (pop) the stash. Git does not make a commit at this point, no matter what; that's always up to you. The combining would and does happen in the index, though, using the work-tree to store Git's best effort in the case of conflicts.

If the combining doesn't go well, Git does it in the index, just like for git merge, and writes its best effort to the work-tree, just like for git merge. It then stops—avoids git stash drop—and leaves you to clean up the mess. If you choose to use git mergetool, that extracts the three versions from the three index staging slots as before.

If you still have the stash, the files are still there in the stash—in the w commit to which refs/stash points. Hence git show stash:<path> will access it directly.

If git mergetool has not marked the file resolved (by moving a work-tree copy into stage-zero and wiping out the stage-1-through-3 entries), there is a copy in the index right now, and git show :3:<path> will get the --theirs copy out. You can also use git checkout --theirs <path> to place that in the work-tree in its usual path (overwriting anything already there, so be careful).

You can even use git checkout -m <path> to re-create the merge conflict. This is generally possible up until you commit the merged result.


2This is the natural and correct merge base, although git stash apply forces it anyway.


If you have dropped or cleared the stash

If you finished the to-merge verb action and ran git stash drop or git stash clear, you may be somewhat out of luck. The only reference to commit w is now gone. Git can garbage collect (git gc) the stash commit, typically once it's 14 days old, at this point. However, you may be able to find it using git fsck --lost-found: see the recipe at the end of the git stash documentation.

3
  • Hi @Torek, thank you a lot for your help. To be honest, I've only read your TL;DR version above (thanks anyway for the long one, I'll have a look after). As I mentioned in my post the merge conflict was solved via Meld. So git stash drop have been runned on background as you mentionned. I'm not sure to find the ` index staging slot` you're talking about and I didn't do any commit yet. When I rerun git mergetool the terminal says No files need merging. It will be helpful if you can give me step by step instruction in this specific case as I'm real beginner on git. Thanks ! Aug 24, 2018 at 17:05
  • I've also a file in my directory. The name of this file is myFile.py.ORIG, I've seen some code into it. What does mean this file ? Aug 24, 2018 at 17:15
  • I'm not sure precisely what mergetool does with meld, nor what meld itself does. The .ORIG file is a backup that git mergetool makes, to hold a copy of the work-tree file before the merge tool itself runs. You can view the entire index (including all staging slots) with git ls-files --stage but it's not user-oriented: it's meant more for working on Git than working with Git. As for whether the stash is still there, use git stash list to see all stashes...
    – torek
    Aug 24, 2018 at 18:30
0

It is not possible to restore the code without restarting merge step (in this scenario)

However, If you re-start the merge step, you will get to the desired state with the following steps:

If myFile_remote_7572.py was in the stashed changes

  1. To return to master: git checkout master
  2. To pull latest changes: git fetch upstream; git merge upstream/master
  3. To correct my new branch: git checkout new-branch; git rebase master
  4. To apply the correct stashed changes: git stash apply

Git is smart enough not to drop a stash if it doesn't apply cleanly.


If myFile_remote_7572.py was on the remote

  1. Pull the latest changes: git fetch
  2. Checkout file from the remote: git checkout origin/master -- path/to/file/myFile_remote_7572.py

The fetch will download all the recent changes, but it will not put it in your current checked out code (working area).

The checkout will update the working tree with the particular file from the downloaded changes (origin/master).

1
  • That is, unfortunately, going to be the wrong file. The file labeled "remote" during the git mergetool run is the one that was in the stash.
    – torek
    Aug 23, 2018 at 1:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.