Git
章 ▾ 第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には、注目すべき高度な機能がいくつかあります。その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を使用すると、すべてのファイルをディスク上の単一のアーカイブにパックしたり、すべてをメモリ内に保持したりするなど、さまざまな方法で保存するのが簡単になります。

その他の高度な使用例には、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に関するより詳しい情報が必要な場合は、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