Search code examples
gittagsbranch

Find branch of a tag on remote git repository


I'm trying to automate buildsteps with a gui and want to create a json-file with all available tags and branch-heads for selection. I can already list all branches and tags in a repository by using

git ls-remote --tags/heads url-of-repo

Now I want to know, which tag belongs to a branch. I could do something like

git branch --contains tags/<tag>

But I want to avoid checking out all repositories locally to just get this information. Maybe there's a command to directly show all tags of a branch?


Solution

  • Make a clone, a bare one,

    git clone --bare url-of-repo
    

    Every time you want to list the branches, update the branches and tags first,

    cd path-to-the-bare-repo
    git fetch origin +refs/heads/*:refs/heads/* +refs/tags/*:refs/tags/*
    

    and then run

    git branch --contains tags/<tag>
    

    I'd recommend git for-each-ref, which allows to format the output and is more script-friendly. For example,

    git for-each-ref refs/heads --contains tags/<tag> --format="%(refname:lstrip=2)"
    

    If you don't want to use cd in the script, you could also export GIT_DIR and unset it.

    export GIT_DIR=path-to-the-bare-repo
    git fetch origin +refs/heads/*:refs/heads/* +refs/tags/*:refs/tags/*
    git for-each-ref refs/heads --contains tags/<tag> --format="%(refname:lstrip=2)"
    unset GIT_DIR
    

    or simply

    GIT_DIR=path-to-the-bare-repo git fetch origin +refs/heads/*:refs/heads/* +refs/tags/*:refs/tags/*
    GIT_DIR=path-to-the-bare-repo git for-each-ref refs/heads --contains tags/<tag> --format="%(refname:lstrip=2)"
    

    If you don't want to make a local clone, and you have access to the hosting server. Another option is to run a web service to query the branches in the repository hosted in the server. You could use django to write and run such a service in several minutes.