章節 ▾ 第二版

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 找到一系列使用示例。