Search code examples
gitbranchreverthead

Make git master HEAD point to current HEAD of branch


I have to admit that I haven't played with gits advanced features but on my current project I had to.

The situation: Someone tried to implement some features and comitted them to the master, now I was called to do what this other person tried to do (but failed), therefore, the first thing I did was

git checkout -b clean_start HASH

Hash is a correct SHA1 hash of about 20 commits before the current master and that worked. I now made some changes to this branch and am now at a point where I'd like to change the current master branch of remote repository (that has the changes made by the other person) to my local branch.

In other words, I'd like to move the head of the master 20 commits back and then merge my new clean branch into it.

Is that exactly what I have to do? With revert HEAD~20 etc. or is there a command that makes exactly such a head move?


Solution

  • You can do this, if the remote repository accepts forced pushes:

    git push --force origin clean_start:master
    

    Note that if anyone else has the repository cloned, a push from them could potentially undo this. If you want to merge your local master branch and the remote master branch, but keep the file tree from your branch (discarding the file tree of origin's master), you can do so like this:

    git merge -s ours --no-commit origin/master
    git commit  # Separate step so that you can use your own commit message.
    git checkout master
    git merge clean_start  # Fast-forward
    git push origin master
    

    This will create a merge commit with both branches (your master and origin's master) as its parent, but the tree will be identical to your current branch tip. In other words, it will create a symbolic merge where no actual code merge occurred.

    If you don't mind that other people working in the repo will be interrupted, you can use the first approach. But if you work with other people who already have these commits, the second approach will be more fool-proof and will keep history.