Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to checkout to a new branch with Pygithub?

This is what I have learned,

g = Github("user", "pass")
repoName = "apiTest"
print "Get all repos:"
for repo in g.get_user().get_repos():
print "\t%s" % repo.name

print "<--------------------------------------------------->"

print "Get all branches in repo %s:" % repoName
for branch in g.get_user().get_repo(repoName).get_branches():
print "\t%s" % branch.name

print "<--------------------------------------------------->"

print "Get last commit message in repo %s:" % repoName
branch = g.get_user().get_repo(repoName).get_branch("dev")
lastCommit = branch._commit.value.commit
print "\t%s" % lastCommit._message.value
print "\t%s"

print "<--------------------------------------------------->"
fc = repo.update_file("/README.md", "testing PyGithub", "test commit", fc.sha)
print fc

but I 'd like to know how to checkout to a new branch. I didn't find any example online. Thank you very much.

like image 984
ypeng Avatar asked Sep 08 '17 15:09

ypeng


People also ask

How do I checkout to a new branch?

New Branches The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.

Can I git checkout create a branch?

The easiest way to create a Git branch is to use the “git checkout” command with the “-b” option for a new branch. Next, you just have to specify the name for the branch you want to create. To achieve that, you will run the “git checkout” command with the “-b” option and add “feature” as the branch name.


1 Answers

You can use the PyGithub create_git_ref function to create a new branch. Using your above example:

g = Github("user", "pass")
repoName = "apiTest"
source_branch = 'master'
target_branch = 'newfeature'

repo = g.get_user().get_repo(repoName)
sb = repo.get_branch(source_branch)
repo.create_git_ref(ref='refs/heads/' + target_branch, sha=sb.commit.sha)
like image 153
Andy Fraley Avatar answered Nov 03 '22 00:11

Andy Fraley