Search code examples
gitbranch

how to delete old git branches on localhost with remote/origin in name


I have seen a good deal on deleting an old branch however my confusion is deleting an old branch with remote/origin/feature in the name.

Here are few of the branches I want to delete locally but not remotely:

remotes/origin/feature/ghost-user-view2
remotes/origin/feature/ghosting-records-handling
remotes/origin/feature/profile-sync-fix

I tried git branch -D feature/profile-sync-fix

That didn't work. I am nervious to try to much and delete something I can not get back. What is the proper way to handle it locally without effecting the remote branch?


Solution

  • As you may know: In git everything is local. Your history is local, your tags are local, your branches are local. This is even true for remote branches, although I understand your insecurity on the topic.

    As any branch in git the remote branches are just references onto specific commits. Git just considers this branches to be different due to their naming. Usually all local branches can be found in your .git directory in refs/heads, remote branches on the other hand rest in refs/remotes (and tags in refs/tags). Otherwise the concept is no different from "usual" branches.

    Edit: As Jubobs suggested in the comments: the term remote-tracking branch is less confusing and should imply why such branches are local. They are merely tracking a remote branch and are not on the remote itself.

    Now you should understand that although git branch -r lists the remote branches, the branches are still completly local.


    But how does git know where to put the branches/changes from the remote?

    Well, that's simple, it's all in your repository configuration you can find in .git/config; here you can find the configuration for your remote (if you have one) which should look quite similar to this:

    [remote "origin"]
        url = /this/is/the/url/to/my/remote
        fetch = +refs/heads/*:refs/remotes/origin/*
    

    The interesting part is this little text snippet: fetch = +refs/heads/*:refs/remotes/origin/*

    What does it do?

    It tells git to take all branches of the remote repository from refs/heads (which contain all local branches) and to "map" all these branches onto branches in refs/remotes/origin (in our local repository).


    TL;DR: git branch -rd will only delete a local branch. The local counterpart of the branch in the remote repository.