如何使用远程分支进行拉取和推送

4

我正在尝试自动化一个更改过程,目前会生成需要手动推送到Git的源代码。我正在尝试使用GitPython来封装该代码:

from git import *

# create the local repo
repo = Repo.init("/tmp/test/repo", bare=True)
assert repo.bare == True

# check status of active branch
repo.is_dirty()

# clone the remote repo
remote_repo = repo.clone("http://user:pass@git/repo.git")

# compile source code into repository
# ... 

# track untracked files
repo.untracked_files

# commit changes locally
repo.commit("commit changes")

# push changes to master
remote_repo.push()

当我尝试运行这个程序时,我得到了以下错误:

Traceback (most recent call last):

File "git_test2.py", line 33, in

repo.commit("commit changes")

BadObject: 636f6d6d6974206368616e676573

该脚本可以拉取远程仓库,但提交时失败。是否有更好的方法解决这个问题?


你能贴出一个回溯信息,显示错误在代码中的哪个位置引发的吗? - Wooble
2个回答

4
您使用的一些功能可能不会按您预期的方式工作。通常,Repo方法与具有相同名称的git子命令不等效。

如果您正在尝试克隆远程存储库,则可以使用单行代码完成:

repo = Repo.clone_from("http://user:pass@git/repo.git", "/tmp/test/repo")

请查看API参考文档,获取更多关于如何使用GitPython的信息。


1
你不能对一个裸仓库进行提交,只能推送/拉取。类比在本地如何操作,尝试克隆一个裸仓库并执行操作,它们将无法工作。
我不熟悉Python的git绑定,但我想你需要克隆一个工作仓库,可选地检出给定分支而不是主分支,完成工作后,只针对这些内容调用git add,然后提交。
另外,repo.untracked_files 是一个简单的列表操作,它不会添加它们。
老实说,看起来你只是盲目地从https://pythonhosted.org/GitPython/0.3.1/tutorial.html复制粘贴,而没有真正阅读它所说的内容。
例如,你需要操作索引对象。
index = repo.index
for ( path, stage ), entry in index.entries.iteritems: pass
index.add(['SOMEFILE'])
new_commit = index.commit("YOUR COMMIT MESSAGE")
#do somethign with new commit    

另一个我找到的例子。
import git
repo = git.Repo( '/home/me/repodir' )
print repo.git.status()
# checkout and track a remote branch
print repo.git.checkout( 'origin/somebranch', b='somebranch' )
# add a file
print repo.git.add( 'somefile' )
# commit
print repo.git.commit( m='my commit message' )
# now we are one commit ahead
print repo.git.status()
# now push

啊,回想起来,使用拉取操作是否比克隆更合适,然后进行更改、提交和推送呢? - user3242205
不,你需要克隆,但不应该使用裸仓库。此外,你的其余用法是虚假的,请查看我的更新。 - UpAndAdam
你可以在裸仓库上使用gitpython。你也可以在其中创建提交,但只能在“HEAD”分支上进行。 - Kenneth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接