章節 ▾ 第二版

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