Alex
Alex

Reputation: 44395

How to add/commit and push a repository via git-python?

I am trying to use git-python to add, commit and push to a repository. Following the incomplete documentation and an example here I tried it the following way:

myrepo = Repo('Repos/hello-world/.git')
# make changes to README.md
myrepo.index.add('README.md')
myrepo.index.commit("Updating copyright year")
myrepo.git.push("origin", "copyright_updater")   ###

I checked out the repository hello_world and put it under a folder Repos. I did change a single file, the README.md. But with that code I get an error

git.exc.GitCommandError: Cmd('git') failed due to: exit code(1)
   cmdline: git push origin copyright_updater
   stderr: 'error: src refspec copyright_updater does not match any.
 error: failed to push some refs to '[email protected]:alex4200/hello-world.git''

in the marked line.

How can I fix it, in order to push the changes to a new branch and to create a pull request on GitHub?

Upvotes: 5

Views: 8884

Answers (1)

Alex
Alex

Reputation: 44395

What you need to do is to use git directly. This is explained at the end of the gitpython tutorial.

Basically, when you have a repo object, you can call every git function like

repo.git.function(param1, param2, param3, ...) 

so for example, to call the git command

git push --set-upstream origin testbranch

you do

repo.git.push("--set-upstream", "origin", "testbranch")

Special rules concerning '-' applies.

So the full sequence, in order to create a new branch and push it to github, becomes

repo = Repo('Repos/hello-world/.git')
# make changes to README.md
repo.index.add('README.md')
repo.index.commit("My commit message")
repo.git.checkout("-b", "new_branch")
repo.git.push("--set-upstream","origin","new_branch")

How you create a pull request on github for the new branch, is some different magic I do not master yet...

Upvotes: 6

Related Questions