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

自古美人都是妖i 提交于 2021-02-07 13:57:23

问题


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?


回答1:


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



回答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)



回答3:


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)


来源:https://stackoverflow.com/questions/15909962/how-to-get-a-list-of-tags-and-create-new-tags-with-python-and-dulwich-in-git

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!