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

1

5

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?

Jeanniejeannine answered 26/5, 2021 at 14:7 Comment(0)
J
6

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...

Jeanniejeannine answered 26/5, 2021 at 16:12 Comment(1)
Pull requests are not part of Git. Pull requests on GitHub use GitHub URLs and sequences; pull requests on Bitbucket use bitbucket URLs and sequences (different from those on GitHub); and so on.Flamingo

© 2022 - 2024 — McMap. All rights reserved.