Is there any way to force the stash override on the current modifications?

Asked

Viewed 133 times

2

When I use the remote git stash to hide the changes, sometimes you need to change that same file, while it is already hidden by Stash.

When I try to apply one git stash pop, but at the same time one of the files that is saved by stash has a modification in the current branch, an error message appears, informing about this modification.

I made a small code as an example below

Example:

>> mkdir test_repo 

>> cd test_repo

>> git init

>> echo "Arquivo A" > a.txt

>> git add a.txt

>>git commit -m "Criando o arquivo A"

>> echo "Arquivo A modificado para fazer um teste com Stash" > a.txt
git stash

>> echo "Arquivo A modificado mais uma vez" > a.txt

>> git stash pop

When I do this, the following error is issued:

error: Local changes of the following files will be overwritten during merge: a.txt.

Confirm your changes or wait for them before merging. Aborting

Is there any way to force git stash pop overwrites the file in the current job, whether or not it has modifications?

  • Have you tried git stash apply?

  • 1

    If you want to actually overwrite the files, you could use the git checkout stash -- ., No? What would your branch files in the current directory look like in the stash version...

  • 1

    @Felipeavelar this second option works, the first failed to try.

1 answer

2


To overwrite the files with what is in stash, it is necessary to perform a checkout with the stash files, just use the command:

git checkout stash -- .

This command will take all the stash commits, as per @Wallace Maxsters, it is possible to choose only one of the commits of the stash, for that, just list the commits with:

git stash list

and select your target, as exemplified by the following command for the recent stash commit:

git checkout stash{0} -- .

If you want misdirect the files, you can use:

git merge --squash stash

That will take all commits that are in stash and will begin the process of merging with the current branch.

If you just want to overwrite the files that are in the stash and keep the modifications made to the current branch, you need to add the merge resolution option --strategy-option=theirs, with the command as follows:

git merge --squash --strategy-option=theirs stash

It is important to remember that this does not clear your stash, to remove the last login you need to use the git stash drop.

  • Important the last remark. The git stash pop usually remove the applied stash (at least with me, when there are conflicts it is still stored, even with the pop).

  • 1

    Observing: It would be nice to include in your reply that you have how to checkout a specific Stash (because you may have several). In case, using git checkout stash@{0} -- file.txt. The 0 is the most recent stash.

  • 1

    @Wallacemaxters, I edited the answer. (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.