6
20
2012
4

使用 pygit2 创建提交

本文来自依云's Blog,转载请注明。

pygit2 是 libgit2 的 Python 绑定,而 libgit2 是一个可动态链接的 git 库,除去头文件和 pkgconfig 信息就一个 .so 文件。它是我在 The Architecture of Open Source Applications(AOSA)第二巻讲 git 的部分中看到的。git 本身遵循了传统的 Unix 哲学,提供了一系列的命令来管理源码库。这对于 shell 脚本是非常不错,可是对于嵌入到其它应用(如 IDE、Web 服务)中却不太好用。于是,我们有了 libgit2。

很遗憾的是,我并没有找到 API 文档,只有一些示例性的用法介绍,更别提教程之类。即使在 pygit2 中,使用help命令能够得到的信息也很有限。所以,我只能在 Python 这样动态语言的交互式会话时独自探索。

下面是我搜索出来的使用 pygit2 进行提交的过程:

导入需要用到的模块:

import pygit2
import time

我的 git 仓库,还有 index:

repo = pygit2.Repository('/home/lilydjwg/.vim/.git')
ind = repo.index

先看看未提交到 index 的修改(相当于git diff

print(ind.diff())

唔,我看到就一个plugin/colorizer.vim文件修改了。把它加到 index 中(相当于git add)。如果是git rm的话就用del ind[filename]了。操作之后要调用write()方法写入更改。

ind.add('plugin/colorizer.vim')
ind.write()

写入 tree 对象,其返回值是二进制编码的 hash 值(使用binascii.b2a_hex可编码成 git 命令中使用的字符串)

oid = ind.write_tree()

作者和提交者的信息,其中最后一个参数(offset)是以分钟计的时区偏移(当然是相对于 UTC)。邮件地址很显然被打码了 :-)

author = pygit2.Signature('依云', 'a@b.c', int(time.time()), 480)

创建提交。其中HEAD是个「符号引用」(symbolic reference),而repo.head就是当前最后一个提交了,oid属性还是二进制编码的 hash 啦。这里,提交者和作者是同一人,因此我都使用刚刚创建的author对象了。这步就是git commit命令了。

repo.create_commit('HEAD', author, author, 'colorizer: solved name color conflict', oid, [repo.head.oid])

在命令行下看看结果是否正确:

>>> git cat-file -p HEAD
tree 20e8937d41b6df16da2c8c5661f9c4a8dd31b5a1
parent ab9c662ce0d1cb2deac7a9ae388ecb40d8ec5e15
author 依云 <a@b.c> 1340188028 +0800
committer 依云 <a@b.c> 1340188028 +0800

colorizer: solved name color conflict
Category: python | Tags: python Git | Read Count: 10202
maplebeats 说:
Jun 20, 2012 11:16:45 PM

邮件地址打码?不是地球人都知道的吗?

Avatar_small
依云 说:
Jun 20, 2012 11:22:59 PM

所以那个不是防人类的 ^_^

Sunday 说:
Aug 14, 2012 10:04:53 AM

pyGit2 咋安装呢,折腾了好久,还下了CMake,也是无果,郁闷中~

Avatar_small
依云 说:
Aug 14, 2012 10:20:27 AM

yaourt -S python-libgit2-git :D
自己弄的话,python setup.py install 就行了嘛。

所以我猜你在编 libgit2-git?简单的办法是:
cmake .
make && make install
ldconfig


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

| Theme: Aeros 2.0 by TheBuckmaker.com