13

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 ?

codegeek
  • 32,236
  • 12
  • 63
  • 63
Nicolas BOISSINOT
  • 131
  • 1
  • 1
  • 3
  • 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 ` is the correct format, but you should also know that you should `git fetch` first, and `git pull origin refs/tags/` after. – Inbar Rose Nov 19 '13 at 14:20

4 Answers4

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')
lev
  • 2,877
  • 23
  • 22
  • 9
    AttributeError: 'Git' object has no attribute 'checkout' – Jon Skarpeteig Dec 02 '15 at 13:24
  • 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). – lev Dec 02 '15 at 15:21
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.
""" 
stefanbo
  • 51
  • 1
0
git.Repo().git.checkout('tag')
johnson
  • 3,729
  • 3
  • 31
  • 32
-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()