21

I have cloned a repository with GitPython, now I would like to checkout a branch and update the local repository's working tree with the contents of that branch. Ideally, I'd also be able to check if the branch exists before doing this. This is what I have so far:

import git

repo_clone_url = "git@github.com:mygithubuser/myrepo.git"
local_repo = "mytestproject"
test_branch = "test-branch"
repo = git.Repo.clone_from(repo_clone_url, local_repo)
# Check out branch test_branch somehow
# write to file in working directory
repo.index.add(["test.txt"])
commit = repo.index.commit("Commit test")

I am not sure what to put in the place of the comments above. The documentation seems to give an example of how to detach the HEAD, but not how to checkout an named branch.

Alex Spurling
  • 47,884
  • 23
  • 63
  • 71

1 Answers1

33

If the branch exists:

repo.git.checkout('branchename')

If not:

repo.git.checkout('-b', 'branchename')

Basically, with GitPython, if you know how to do it within command line, but not within the API, just use repo.git.action("your command without leading 'git' and 'action'"), example: git log --reverse => repo.git.log('--reverse')

Arount
  • 7,881
  • 1
  • 23
  • 37
  • Thanks, do you know how to check if a local branch exists? – Alex Spurling Dec 18 '17 at 16:46
  • Yes. I even know two of them! And I surelly can imagine even more with some minutes! But, they are all not that good because all based on the same thing. GitPython only compute and forward git command lines to OS and parse result. The best you can is to `try` something and expect a `git.exc.GitCommandError`. If it happen the branch does not exists OR you messed your code.. What to check: `repo.git.checkout('branchename')` or `repo.git.rev_parse('--verify', 'branchname')`. It does not make the same git thing, but gives you the exact same result. – Arount Dec 18 '17 at 19:13
  • @Arount I am applying the first command you list, and while I am not getting an error. It does not appear that the repo is switching over the branch? What might I be missing? – Kyle Swanson Apr 10 '19 at 22:28
  • @Arount wrote up my question here -> https://stackoverflow.com/questions/55622824/how-to-query-the-log-of-a-specific-git-repo-branch-using-gitpython – Kyle Swanson Apr 11 '19 at 00:10
  • 1
    I can't say this enough, but thank you. The last part of your answer finally made me understand this package. I'm trying to understand this 2 days straight. Should be the first thing in the GitPython documentation. – Daniel Lavedonio de Lima Jun 17 '20 at 17:46