章节 ▾ 第二版

A2.4 附录 B: 在你的应用中嵌入 Git - go-git

go-git

如果你想将 Git 集成到用 Golang 编写的服务中,还有纯 Go 库实现。此实现没有任何原生依赖项,因此不容易出现手动内存管理错误。它对于标准 Golang 性能分析工具(如 CPU、内存分析器、竞争检测器等)也是透明的。

go-git 专注于可扩展性、兼容性,并支持大多数底层 API,其文档可在 https://github.com/go-git/go-git/blob/master/COMPATIBILITY.md 查看。

这是一个使用 Go API 的基本示例

import "github.com/go-git/go-git/v5"

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

一旦你有了 Repository 实例,你就可以访问信息并对其进行更改。

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

// get the commit object, pointed by ref
commit, err := r.CommitObject(ref.Hash())

// retrieves the commit history
history, err := commit.History()

// iterates over the commits and print each
for _, c := range history {
    fmt.Println(c)
}

高级功能

go-git 有几个显著的高级功能,其中之一是可插拔存储系统,类似于 Libgit2 后端。默认实现是内存存储,速度非常快。

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

可插拔存储提供了许多有趣的选择。例如,https://github.com/go-git/go-git/tree/master/_examples/storage 允许你将引用、对象和配置存储在 Aerospike 数据库中。

另一个功能是灵活的文件系统抽象。使用 https://pkg.go.dev/github.com/go-git/go-billy/v5?tab=doc#Filesystem 可以很容易地以不同的方式存储所有文件,例如将它们全部打包到磁盘上的单个存档中,或者将它们全部保留在内存中。

另一个高级用例包括可精细调整的 HTTP 客户端,例如在 https://github.com/go-git/go-git/blob/master/_examples/custom_http/main.go 中找到的客户端。

customClient := &http.Client{
    Transport: &http.Transport{ // accept any certificate (might be useful for testing)
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    },
    Timeout: 15 * time.Second,  // 15 second timeout
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse // don't follow redirect
    },
}

// Override http(s) default protocol to use our custom client
client.InstallProtocol("https", githttp.NewClient(customClient))

// Clone repository using the new client if the protocol is https://
r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: url})

延伸阅读

go-git 的全部功能超出了本书的范围。如果你想了解更多关于 go-git 的信息,可以在 https://pkg.go.dev/github.com/go-git/go-git/v5 找到 API 文档,并在 https://github.com/go-git/go-git/tree/master/_examples 找到一系列使用示例。