How to get a list of tags and create new tags with python and dulwich in git?
Asked Answered
A

3

6

I am having problems to retrieve the following information of a git repo using python:

  1. I would like to get a list of all tags of this repository.
  2. I would like to checkout another branch and also create a new branch for staging.
  3. I would like to tag a commit with an annotated tag.

I have looked into the dulwich's documentation and the way it works seems very bare-bones. Are there also alternatives which are easier to use?

Abisia answered 9/4, 2013 at 18:40 Comment(0)
T
6

The simplest way to get all tags using Dulwich is:

from dulwich.repo import Repo
r = Repo("/path/to/repo")
tags = r.refs.as_dict("refs/tags")

tags is now a dictionary mapping tags to commit SHA1s.

Checking out another branch:

r.refs.set_symbolic_ref("HEAD", "refs/heads/foo")
r.reset_index()

Creating a branch:

r.refs["refs/heads/foo"] = head_sha1_of_new_branch
Terence answered 19/5, 2013 at 21:54 Comment(3)
hi @jelmer, thanks for the project :) Any chance of an example of how to a.add tag b.push tags to remote?Higgler
Great it's useful! Please ask a new question about that, I think that's a different topic.Terence
Sure, done @Terence #60140228Higgler
R
2

Now you can also get an alphabetically sorted list of tag labels.

from dulwich.repo import Repo
from dulwich.porcelain import tag_list

repo = Repo('.')
tag_labels = tag_list(repo)
Rawalpindi answered 13/2, 2015 at 19:50 Comment(1)
Great! Seems like no way to get the SHA1 part from porcelain thoughHiggler
B
1

Call git via subprocess. From one of my own programs:

def gitcmd(cmds, output=False):
    """Run the specified git command.

    Arguments:
    cmds   -- command string or list of strings of command and arguments
    output -- wether the output should be captured and returned, or
              just the return value
    """
    if isinstance(cmds, str):
        if ' ' in cmds:
            raise ValueError('No spaces in single command allowed.')
        cmds = [cmds] # make it into a list.
    # at this point we'll assume cmds was a list.
    cmds = ['git'] + cmds # prepend with git
    if output: # should the output be captured?
        rv = subprocess.check_output(cmds, stderr=subprocess.STDOUT).decode()
    else:
        with open(os.devnull, 'w') as bb:
            rv = subprocess.call(cmds, stdout=bb, stderr=bb)
    return rv

Some examples:

rv = gitcmd(['gc', '--auto', '--quiet',])
outp = gitcmd('status', True)
Bypass answered 9/4, 2013 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.