章 ▾ 第2版

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

go-git

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

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を使用すると、すべてのファイルを異なる方法で簡単に保存できます。例えば、すべてをディスク上の単一アーカイブにまとめるか、すべてをインメモリに保持するかなどです。

その他の高度なユースケースには、https://github.com/go-git/go-git/blob/master/_examples/custom_http/main.goで見られるような、微調整可能なHTTPクライアントが含まれます。

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