简体   繁体   中英

go back to previous commit make changes and push to the branch

i recently ran into an issue while resolving conflicts after git pull. i couldn't resolve conflict properly as i am fairly new to git. ihave following branches:

  • pmp101
  • staging
  • master

i was working on staging branch. before git pull i had already commited my code, so i decided to revert everything i was trying to do when trying to resolve conflicts.

so i did git log and did git checkout [shaofmylastcommit] . now i got my code back so the other developer whose code was the reason for conflict, he gave me his files which i replaced with mine and add my codes to it which i copied before replacing the file.

now i commited my code again but when i tried to git push it gave me an error saying you are at detached head which i didn't understand. so i thought i needed to be on my branch again to push the code, so i did git checkout staging

but now again all my changes were gone, which freaked me out. but i got a meaage saying "this is a good time to keep your changes to new branch as you are trying to switch branch" or something like that. so i did exactly and ai got a new branch with name "promotion".

now i did git checkout promotion and got my changes back(thank god! phew!)...

but now i have this new branch and i am supposed to work on branch "staging" so what should i do and if i run into similar problem in future what should i do, i am guessing there was no need for me to create a new branch i could have pushed those changes from branch "staging", but i was on detached head which i don't know what means exaclty.

If you have checked out the right commit, and see the right content, but the wrong branch, you can reset your staging branch to that commit:

git checkout staging
git reset --hard <yourCommit>

However, if the git push entails a --force , that might not be a good idea.

An alternative approach is to:

  • reset your staging branch to origin/staging (that way, any new commit done on that branch will be simply pushed, without --force)

     git checkout staging git reset --hard origin/staging 
  • replay your commit (or two commits) on top of that branch:

     git cherry-pick <one-commit> git cherry-pick <second-commit> 

Then you can push normally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM