0

I'm writing a script that will delete remote branches that are already merged into the default remote branch, but I'm having trouble determining the remote default branch because it isn't always set.

I know if I clone a repo, then I get a tracking branch to remotes/origin/HEAD

However, if I add the remote to an existing repository and fetch, then I won't get this remote tracking branch.

This related question asks why it isn't there, but I want to know how to add it.

Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
  • Why do you want to set the remote's HEAD? There's some options for setting the remote HEAD in this question: http://stackoverflow.com/questions/1485578/change-a-git-remote-head-to-point-to-something-besides-master – alexbclay Sep 08 '16 at 17:16
  • @Alex, I'm not trying to set it, I'm trying to fetch it. – Jeff Puckett Sep 08 '16 at 19:09
  • Gotcha. How about this one then: http://stackoverflow.com/questions/8839958/how-does-origin-head-get-set The second answer works in my limited test case. – alexbclay Sep 08 '16 at 19:31

1 Answers1

2

As alexbclay implied in a comment, there seems to be no real use for this, but there are several ways to find it:

  • If your Git is new enough (and the one on the server is as well), git ls-remote --symref will print it out (plus everything else, so you might want to add more options to limit the output):

    $ git ls-remote --symref
    ...
    ref: refs/heads/master  HEAD
    ...
    

    Once you have this, you can create the reference locally with git symbolic-ref (in this case, assuming remote foo, using git symbolic-ref refs/remotes/foo/HEAD refs/remotes/foo/master: follow the usual renaming, using git config --get-all remote.foo.fetch to figure out the renaming, if it's non-standard).

  • If that fails, you can fall back on the method git clone uses: read the remote heads (with git ls-remote again) and see if there is a unique match on the ID for HEAD against all the actual branch heads. If it's unique, you know which one it is. If not, you can pick the first alphabetically as git clone does, or pick one at random. (I'm not sure off-hand what git clone does if the remote's HEAD is detached and thus does not match any of the remote's branches. It might be interesting to find out.)

  • Slow but simple: make a new clone, see what you get for refs/remotes/origin/HEAD. :-) That's basically the previous two methods glommed together. (Use --reference to speed up the network interaction, perhaps.)

Community
  • 1
  • 1
torek
  • 448,244
  • 59
  • 642
  • 775
  • Thanks torek, `git ls-remote --symref ` is exactly what I was looking for. I have updated my question to provide a hint about why I needed this. – Jeff Puckett Sep 08 '16 at 20:12