`git ls-remote` in GitPython
Asked Answered
S

3

5

In my python program, I want to check whether a ref exists on my remote. I can check the remote with git ls-remote, but I would like to avoid parsing the output myself.

I found git.remote.Remote in GitPython, but that only refers to a remote of a local repository.

Does GitPython have an equivalent command which allows me to look at remote refs without cloning the repository?

Sphygmograph answered 23/2, 2016 at 18:21 Comment(0)
S
22

GitPython does not support ls-remote, but you can use git.cmd to run any git command and then parse the output manually:

import git
def lsremote(url):
    remote_refs = {}
    g = git.cmd.Git()
    for ref in g.ls_remote(url).split('\n'):
        hash_ref_list = ref.split('\t')
        remote_refs[hash_ref_list[1]] = hash_ref_list[0]
    return remote_refs

Example:

In [3]: refs = lsremote('https://github.com/gitpython-developers/GitPython.git')
In [4]: refs['HEAD']
Out[4]: u'9f4af7c6db25c5bbec7fdc8dfc0ea6803350d94c'
Sphygmograph answered 23/2, 2016 at 18:54 Comment(0)
C
2

Case without cloning:

import git

url = "git://github.com/git/git.git"
g = git.cmd.Git()
g.ls_remote("--tags", url).split('\n')

I left a parsing of output for you, but I have some example

>>> test = g.ls_remote("--tags", url).split('\n')
>>> print(test[0])
d5aef6e4d58cfe1549adef5b436f3ace984e8c86    refs/tags/gitgui-0.10.0
Churr answered 16/4, 2020 at 10:39 Comment(0)
R
1

This works as well.

from git import Repo
repo = Repo('path to source')
repo.git.ls_remote("--heads", "origin", "release/10.0.0.2")

Output will be something like:

'9e5ca005c2d320a4904e88e25df1efa6fb26b396\trefs/heads/release/10.0.0.2'

Repulsion answered 18/3, 2020 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.