go-git - Git 的 Go 语言实现


Apache
跨平台
Google Go

软件简介

go-git 是一个 Go 语言实现的高度可扩展的 Git 实现库。可以使用友好的 API 来管理 Git
的仓库。支持不同类型的存储,包括内存文件系统,也可以通过接口 [Storer](https://godoc.org/gopkg.in/src-d/go- git.v4/plumbing/storer)实现对存储的扩展。

该项目从 2015 年开始开发。项目旨在兼容 git ,所有的操作实现与git完全一样。两者的兼容比较请阅读 compatibility
documentation
.

基本示例

一个实现 git clone 的最基本示例:

// Clone the given repository to the given directory
Info("git clone https://github.com/src-d/go-git")

_, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{
    URL:      "https://github.com/src-d/go-git",
    Progress: os.Stdout,
})

CheckIfError(err)

输出结果:

Counting objects: 4924, done.
Compressing objects: 100% (1333/1333), done.
Total 4924 (delta 530), reused 6 (delta 6), pack-reused 3533

实现内存存储的示例

将 git 仓库克隆到内存中,并打印 HEAD 的历史记录,类似 git log :

// Clones the given repository in memory, creating the remote, the local
// branches and fetching the objects, exactly as:
Info("git clone https://github.com/src-d/go-siva")

r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
    URL: "https://github.com/src-d/go-siva",
})

CheckIfError(err)

// Gets the HEAD history from HEAD, just like this command:
Info("git log")

// ... retrieves the branch pointed by HEAD
ref, err := r.Head()
CheckIfError(err)


// ... retrieves the commit history
cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
CheckIfError(err)

// ... just iterates over the commits, printing it
err = cIter.ForEach(func(c *object.Commit) error {
    fmt.Println(c)
    return nil
})
CheckIfError(err)

输出结果:

commit ded8054fd0c3994453e9c8aacaf48d118d42991e
Author: Santiago M. Mola <santi@mola.io>
Date:   Sat Nov 12 21:18:41 2016 +0100

    index: ReadFrom/WriteTo returns IndexReadError/IndexWriteError. (#9)

commit df707095626f384ce2dc1a83b30f9a21d69b9dfc
Author: Santiago M. Mola <santi@mola.io>
Date:   Fri Nov 11 13:23:22 2016 +0100

    readwriter: fix bug when writing index. (#10)

    When using ReadWriter on an existing siva file, absolute offset for
    index entries was not being calculated correctly.
...

更多的示例请看 examples.