How to checkout a tag with GitPython
Asked Answered
V

4

14

In a python script, I try to checkout a tag after cloning a git repository. I use GitPython 0.3.2.

#!/usr/bin/env python
import git
g = git.Git()
g.clone("user@host:repos")
g = git.Git(repos)
g.execute(["git", "checkout", "tag_name"])

With this code I have an error:

g.execute(["git", "checkout", "tag_name"])
File "/usr/lib/python2.6/site-packages/git/cmd.py", line 377, in execute
raise GitCommandError(command, status, stderr_value)
GitCommandError: 'git checkout tag_name' returned exit status 1: error: pathspec 'tag_name' did not match any file(s) known to git.

If I replace the tag name with a branch name, I have no problem. I didn't find informations in GitPython documentation. And if I try to checkout the same tag in a shell, I have non problem.

Do you know how can I checkout a git tag in python ?

Volga answered 19/11, 2013 at 14:15 Comment(1)
I hope this is just for the example, but your error says you are actually using the string "tag_name" and that is why the error happens. Regardless, git checkout <tag> is the correct format, but you should also know that you should git fetch first, and git pull origin refs/tags/<tag> after.Nathanielnathanil
N
10

Assuming you cloned the repository in 'path/to/repo', just try this:

from git import Git

g = Git('path/to/repo')

g.checkout('tag_name')
Necrose answered 8/1, 2015 at 13:34 Comment(2)
AttributeError: 'Git' object has no attribute 'checkout'Palanquin
I've just tried the sequence: [1] from git import Git [2] g = Git('GooglePlayAppsCrawler') [3] g.checkout(). It works (GooglePlayAppsCrawler is the git repo I have in the current working directory).Necrose
U
2
git.Repo().git.checkout('tag')
Unstop answered 25/10, 2022 at 9:39 Comment(0)
M
1
from git import Git
g = Git(repo_path)
g.init()
g.checkout(version_tag)

Like cmd.py Class Git comments say

"""
The Git class manages communication with the Git binary.

It provides a convenient interface to calling the Git binary, such as in::

 g = Git( git_dir )
 g.init()                   # calls 'git init' program
 rval = g.ls_files()        # calls 'git ls-files' program

``Debugging``
    Set the GIT_PYTHON_TRACE environment variable print each invocation
    of the command to stdout.
    Set its value to 'full' to see details about the returned values.
""" 
Malaco answered 29/12, 2016 at 9:51 Comment(0)
I
-1

This worked for me, and I think it's closer to the intended API usage:

from git import Repo

repo = Repo.clone_from("https://url_here", "local_path")
repo.heads['tag-name'].checkout()
Igraine answered 19/11, 2018 at 21:46 Comment(2)
not work for me: AttributeError: 'IterableList' object has no attribute tag-nameGrapevine
This did work for me - I believe this matches the most up-to-date release of gitpython (GitPython==3.1.7 for me)Trainload

© 2022 - 2024 — McMap. All rights reserved.