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 'git@github.com: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?

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

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

Alex
  • 41,580
  • 88
  • 260
  • 469
  • 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. – torek May 27 '21 at 00:15