章节 ▾ 第二版

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

go-git

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

go-git 专注于可扩展性、兼容性,并支持大多数底层(plumbing)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 的信息,其 API 文档位于 https://pkg.go.dev/github.com/go-git/go-git/v5,以及一组使用示例位于 https://github.com/go-git/go-git/tree/master/_examples

scroll-to-top