如何拉,推远程分支

时间:2014-03-26 19:05:26

标签: python git gitpython

我试图自动化一个更改过程,该过程当前创建了手动推送到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()

当我尝试运行时,我得到了

  

追踪(最近一次呼叫最后一次):

     

文件" git_test2.py",第33行,

     

repo.commit("提交更改")

     

BadObject:636f6d6d6974206368616e676573

该脚本能够提取远程存储库,但在提交时失败。有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

您正在使用的某些功能可能无法按预期方式工作。通常,Repo方法等同于具有相同名称的git子命令。

如果您尝试克隆远程存储库,可以在一行中实现:

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

有关如何使用GitPython的更多信息,请参阅API Reference

答案 1 :(得分:1)

您无法针对裸存储库提交。你只能推/拉他们。通过并行考虑如何在本地执行此操作。尝试克隆一个裸仓库并执行操作,它们将无法工作。

我并不熟悉pythonic git绑定,但是想象你需要克隆一个工作的存储库,可选择检查一个给定的分支而不是master,做你的工作,只针对那些东西调用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