如何通过 git-python 添加/提交和推送存储库?

问题描述

我正在尝试使用 git-python 添加、提交和推送到存储库。按照不完整的文档和示例 here 我尝试了以下方式:

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")   ###

我检查了存储库 hello_world 并将其放在文件Repos 下。我确实更改了一个文件README.md。但是使用该代码我得到一个错误

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

标记的行中。

如何修复它,以便将更改推送到新分支并在 GitHub 上创建拉取请求?

解决方法

您需要做的是直接使用gitgitpython 教程的结尾对此进行了说明。

基本上,当你有一个 repo 对象时,你可以像这样调用每个 git 函数

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

例如,调用 git 命令

git push --set-upstream origin testbranch

你愿意

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

有关“-”的特殊规则适用。

因此,为了创建一个新分支并将其推送到 github,整个序列变为

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","new_branch")

你如何在 github 上为新分支创建拉取请求,这是我还没有掌握的一些不同的魔法......