Skip to content

Instantly share code, notes, and snippets.

@lucaswerkmeister
Created October 28, 2016 11:37
Show Gist options
  • Save lucaswerkmeister/566f35d8b332d646b3ca20e123d1878d to your computer and use it in GitHub Desktop.
Save lucaswerkmeister/566f35d8b332d646b3ca20e123d1878d to your computer and use it in GitHub Desktop.
Rough sketch on how to turn a Git branch into an orphan branch
branch=... # the branch you want to turn into an orphan branch
base=master # the branch which $branch is based on and shouldn’t be anymore
firstCommit=... # the first commit on $branch that’s not on $base
# rename $branch to $branch-bak
git checkout $branch
git checkout -b $branch-bak
git branch -d $branch
# new orphan $branch
git checkout --orphan $branch
git rm -rf .
# create a first commit that we can rebase on (git rebase --onto refuses to operate on the orphan branch)
git cherry-pick $firstCommit
# move all the other commits over
git rebase --onto $branch $(git merge-base $branch-bak $base) $branch-bak
# that leaves us on a detached head for whatever reason, so change $branch to point to that commit
branchSha=$(git show --no-patch --pretty=format:%H)
git checkout $branch
git reset --hard $branchSha
@BenBE
Copy link

BenBE commented Oct 28, 2016

Line 6+7 could read
git checkout -f -b "$branch-bak" "$branch"

Line 8 should be
git branch -D "$branch"
to force deletion if unmerged (which $branch likely is)

Not sure on the git rebase --onto= site of things, why it doesn't update $branch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment