Search code examples
gitworkflowgithooksgit-stash

Git stash keeping index conflict


I need to create pre-commit hook to do some 'sanity tests' of project (mainly check whether the deployment will go without problems). Because I need to tests only changes that are about to be commited, I need to stash non-staged changes before running the tests and pop stashed changes after doing this. But there's a problem because there is possibility of the conflict between stash and index in following case:

Let's say I have the file named testfile with following content:

first line
second line
third line

Now i'll add a line between second and third

first line
second line
second and a half line
third line

and run git add so it will become staged.

Now I'll add next line after previous one so the file looks like that

first line
second line
second and a half line
second and three quarters line
third line

So now first and second lines are commited, second and a half is staged, second and three quarters is unstaged and third is commited.

Let's get straight to the point. Now when I run git stash --keep-index, then perform my tests and try to run git stash pop, the result is following:

Auto-merging testfile
CONFLICT (content): Merge conflict in testfile

and file contents look like this:

first line
second line
second and a half line
<<<<<<< Updated upstream
=======
second and three quarters line
>>>>>>> Stashed changes
third line

I have no idea how to reapply stashed changes and avoid this type of conflict after running my tests. I'd be grateful for pointing me right direction with this.


Solution

  • You basically want git checkout --theirs then (for the files in conflict), if you want to have the version in the stash (--theirs refers to it).

    Then git reset HEAD to remove changes from the index (added there because of the conflict), and git stash drop in the end.

    It would be nice if there was an option for git-stash pop to handle this better, because this is usually what you want.