Search code examples
pythongitpython

gitpython: determine the remote associated to a (tracking) branch


I would like to determine the remote branch, that is associated to the current (tracking branch)

The solution, that I found is working, but it feels strange, that I have to parse the configuration to achieve what I want.

Is there any more elegant solution?

repo = git.Repo(path) 
branch = repo.active_branch
cfg =  branch.config_reader().config  
# hand crafting the section name in next line just seems clumsy
remote= cfg.get(f'branch "{branch.name}"', "remote") 

Solution

  • Perhaps git.Head.tracking_branch() and git.Reference.remote_name can give you what you're looking for?

    e.g.

    repo = git.Repo(path) 
    branch = repo.active_branch
    remote_name = branch.tracking_branch().remote_name