Search code examples
gitgithubatlassian-sourcetreebranching-and-merginggit-detached-head

Fix Git Branching with Detached Head and Unrelated Histories


I need to fix a Git repository that has a detached head and 2 consecutive branches with unrelated histories. I have to use SourceTree at work, but I can use command lines too if needed. What I have to do is to reconcile the current [Head] (3 on the image) with the [origin/master][origin/head][master] (2) without loosing the commits in between. I would also like to merge (or re-attach) the 2 branches (pink and blue). (I only want 1 branch in total). I am not sure in which order it would be best to proceed: reconciling the [Head] and [origin/master] or re-attaching the 2 branches.

Git Repository Image

I had to hide all the names and comments as this is for work and the content I am allowed sharing is restricted. And sorry if this question is not up to the best standards, it is my first question on any kind of forum.


Solution

  • Once you create a branch label at HEAD, then you will be free to checkout other branches without losing any of your commit history (Ofcourse later you can still retrieve the commit histories provided you know the SHA-IDs, but that's difficult to keep track of)

    So first thing first, create a local branch at where your HEAD is

    git branch develop

    (develop is some branch name, you can give any other name as you wish)

    Now if you see your source tree, you will see both HEAD and develop (or whatever name you gave in the above git command). You are now free to checkout master branch.

    git checkout master

    Once you do, your HEAD will now be at master. Remember: HEAD tells you which snapshot (or which commit) your current code is in.

    Next if you want to get the commits of your develop branch (branch which you just created above) in the master as well, all you need to do is merge

    Assuming you are in master branch (If you are not, then checkout master)

    git merge develop

    (This brings develop branch commits in local master)

    git push origin master

    (This pushes those changes to remote/master)

    Tip: Instead of merge, there is a better option rebase available in git. But I assume you are new to git, so its better for you to go through some online material and study about it to understand the difference between merge and rebase. (Or you can ask your peers to explain you)