Stash to do changes in another branch and go back

Viewed 1425

I was working on a branch and there was a need to fix something in the master branch. I was not ready to commit so I stashed my changes to try to go back. The pipeline of command that I used were:

git stash
git checkout master
git pull
==> fixed code in file file.py
==> made changes in file2.py that I don't want to keep
git add file.py
git commit -m'fixed stuff'
git push
git checkout initial_branch
git stash apply stash@{0}

Which gave me the error:

error: Your local changes to the following files would be overwritten by merge:
        file2.py
Please, commit your changes or stash them before you can merge.
Aborting

I wonder what I did wrong what I should do in this case in the future.

2 Answers

Most likely what happened is that during the following step you also changed one or more files besides file.py:

==> fixed code in file file.py

This would have left your working directory with some other changes. Then, when you tried to apply the stash, Git refused to do it, because the changes in the stash would have resulted in irreconcilable merge conflicts.

To remedy your current situation, you should have run git status after committing the hotfix in the master branch. Ideally, you should have seen a message saying something like "working directory clean, nothing to commit." If you had seen that message, then applying the stash should not have been a problem.

By the way, if you want to just apply the stash on the top of the stack, you may simplify to:

git stash apply

Edit:

Based on the update to your question, the offending file is file2.py. If you don't want the changes to that file, then you should reset it:

git checkout -- file2.py

After doing this, git status should be clean, and there should be no problems with applying the stash.

Another way to proceed would be to commit for later

git commit -am "temp - do not push"

Then you'll be able to change branch / merge without problems.

And when you want to get back to your previous work, from your branch,

git reset HEAD^

will just undo the commit but keep your changes in the working tree (actual files).

Main advantage is : your unfinished work isn't "wandering" in the stash list (which can also have many other irrelevant things), it stays on the relevant branch.


Additionnally, to make all this more practical to use, make aliases

git config --global alias.save 'git commit -am "saved work - do not push"'

git config --global alias.reload 'git reset HEAD^'

Then a work interruption could be scenarized as

# at this point you're working on branch feature-XYZ

# you need to quickly let this aside and work on hotfix-ABC
git save
git checkout hotfix-ABC

# work on the branch, commit, push, anything

# then the fire is put up, you can get back to your previous dev
git checkout feature-XYZ
git reload
Related