チャプター ▾ 第2版

A2.4 付録 B: アプリケーションに Git を組み込む - go-git

go-git

Go言語で書かれたサービスにGitを統合したい場合、純粋なGoライブラリ実装も存在します。この実装はネイティブな依存関係を持たないため、手動によるメモリ管理エラーの影響を受けません。また、CPU、メモリプロファイラ、競合検出器などの標準的なGo言語のパフォーマンス分析ツールに対しても透過的です。

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にはいくつかの注目すべき高度な機能があり、その1つはプラグ可能なストレージシステムです。これは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データベースに保存できます。

もう1つの機能は、柔軟なファイルシステム抽象化です。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