Git
章節 ▾ 第二版

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 的使用範例集。

scroll-to-top