GitPython create and push tags

Viewed 10930

In a python script, I try to create and push a tag to origin on a git repository. I use gitpython-1.0.2.

I an able to checkout anexisting tag but no way to find how to push a new tag to remote.

Many thanks

5 Answers

To create a new tag using gitpython:

from git import Repo
obj = Repo("directory_name")
obj.create_tag("tag_name")

To push to remote

obj.remote.origin.push("tagname")
tag = repo.create_tag(tagName, message=mesg)
repo.remote.origin.push(tag.path)

tag.name may be conflict with your local branch name, use tag.path here.

I used the below snippet code to create a tag and push it to remote. You may need to handle exceptions by adding try ... catch block on each git operation.

repo = git.Repo(os.path.abspath(repo_path)
repo.git.tag('-a', tagname, commit, '-m', '')
repo.git.push('origin', tagname)

Git supports two types of tags: lightweight and annotated. So in GitPython we also can created both types:

# create repository
repo = Repo(path)
# annotated
ref_an = repo.create_tag(tag_name, message=message))
# lightweight 
ref_lw = repo.create_tag(tag_name))

To push lightweight tag u need specify reference to tag repo.remote('origin').push(ref_lw ), but in annotated u can just use:

repo.remote('origin').push()

if configuration push.followTags = true. To set configuration programmatically

repo.config_writer().set_value('push', 'followTags', 'true').release()

Additional information about pushing commits & tags simultaneously

Related