How to check a branch using GitPython

I cloned the repository with GitPython, now I want to check the branch and update the working local repository tree with the contents of this branch. Ideally, I can also 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 place of the comments above. the documentation seems to give an example of how to detach a HEAD, but not how to check a named branch.

+5
source share
1 answer

If the branch exists:

 repo.git.checkout('branchename') 

If not:

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

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

+4
source

Source: https://habr.com/ru/post/1274158/


All Articles