简体   繁体   中英

Git push (force) after merging commits into another branch

We use git with different branches. A colleague made a mistake and committed (+ pushed) a few different commits to the wrong branch (dev branch).

The branch he committed to should be merged into 'master' anyway. I wonder if these steps would be safe:

  • Merge changes from dev branch into master
  • Push all changes to origin/master
  • In dev branch - revert so all commits are dropped
  • Push (force) to make sure the remote repository is in sync (eg: drops all wrong commits)

Will these pose any issues in the repository later on ? (eg: with the merge commit and the fact that the original commits were removed) ?

The original commits will not be removed. They are still in the master branchs history, just not anymore in the dev branch history. You shouldn't get any issues except for the rewritten history of the dev branch that will force everyone who got that "wrong" state of the dev branch already and based work onto it to rebase their local branches like described in the help of git rebase .

The steps you're proposing would surely do what you expect. Just one clarification: git revert actually creates a new commit (which un-does what the commit we're reverting did). Consequently, in the last step, you will not need to force in order to be able to push .

Note that if you're willing to force push (I assume you know the consequences) you may do something easier:

  • let your colleague reset his dev branch so that it doesn't not contain the commits you don't want (eg: git reset --hard <sha1 of commit before he merged>
  • let him push force, to actually drop the wrong commits ( git push -f origin dev )

and now he is back to where he was before the wrong merge, so he can start again, using the correct branch.


More precisions: let's say you had the following commits

-- A -- B
        \- dev
-- C -- D
        \- master

and the your colleague added commit E to the wrong branch. Then, with the steps you're proposing, you'll have:

-- A -- B -- E -- E'
             \     \-- dev
-- C -- D ----F
               \-- master

where F is just a merge commit, and where E' is the revert.

As we can see: as far as code is concerned, each branch will be in the expected state. However commit E will not, topologically, be removed from dev .

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