使用python操作git有gitpython/gittle等。最开始使用的是gitpython,但是对我来说比较难理解。折腾之后换成gittle,用起来则比较顺手。
只是使用了其基本功能。
- 安装
pip install gittle
- 引入gittle
from gittle import Gittle
- 基本使用
克隆代码: from gittle import Gittle repo_path = '/tmp/gittle_bare' repo_url = 'git://github.com/FriendCode/gittle.git' repo = Gittle.clone(repo_url, repo_path) 初始化一个目录: repo = Gittle.init(path) 使用已存在的目录: repo = Gittle(path) 更详细的操作: https://github.com/FriendCode/gittle
我的例子:
def update_mirror(proj_name, proj_url, proj_ref):
repo = Gittle('/codes/%s' % proj_name)
code_depart = proj_ref.split('/')[1]
code_branch = str(proj_ref.split('/')[2])
repo.switch_branch(code_branch)
ori_uri = repo.remotes['origin']
i22_uri = repo.remotes['i22']
repo.pull(origin_uri=ori_uri, branch_name=code_branch)
repo.push(origin_uri=i22_uri, branch_name=code_branch)
遇到的问题
问题1:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/gittle/gittle.py", line 360, in pull
return self.pull_from(origin_uri, branch_name)
File "/usr/local/lib/python2.7/dist-packages/gittle/gittle.py", line 356, in pull_from
return self.fetch(origin_uri)
File "/usr/local/lib/python2.7/dist-packages/gittle/gittle.py", line 407, in fetch
remote_refs = self.fetch_remote(origin_uri)
File "/usr/local/lib/python2.7/dist-packages/gittle/gittle.py", line 364, in fetch_remote
client, remote_path = self.get_client(origin_uri=origin_uri)
File "/usr/local/lib/python2.7/dist-packages/gittle/gittle.py", line 328, in get_client
client, remote_path = get_transport_and_path(origin_uri, **client_kwargs)
File "/usr/local/lib/python2.7/dist-packages/dulwich/client.py", line 1116, in get_transport_and_path
user_host, path = location.split(':')
ValueError: too many values to unpack
解决:在gittle的github的issue list中,给出需要升级dulwich,默认安装的版本太老。
pip install --upgrade dulwich
问题2:
TypeError: refname is not a bytestring: u'refs/heads/test_common'
原因代码中proj_ref类型为unicode,而不是bytestring,使用str()转换后问题即解决。