LoginSignup
0
1

More than 5 years have passed since last update.

googleのgo github SDKを使ってrevision間の差分抽出をしてみたメモ

Last updated at Posted at 2017-11-08

TL;DR

特定のファイルがdiffに含まれるdeployを抽出してアラート出すとか、
承認入れるとかそんなことをする必要が出てきたので,githubのgoSDKを
使ってみたメモ。

ライブラリ

Google様が用意してくれていたので巨人の肩に乗る。やったぜ。
ちなみにv4(GraphQL)は未対応。

go-github

使い方

  • 認証情報のsetUpをざっくり書く
package github

import (
    "os"

    "github.com/google/go-github/github"
    "golang.org/x/oauth2"
)

func NewClient() *github.Client {
    ts := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")},
    )
    tc := oauth2.NewClient(oauth2.NoContext, ts)

    return github.NewClient(tc)
}

サンプルコードでは環境変数に認証情報をおいてますが、この辺はお好みで。

  • 特定のcommitとcommitの差分を取得するコード
    • このendpoint に対応するCompareCommits を使って取得する。
    • contextは第1引数で渡す方が行儀良いです(手抜き
package github

import (
    "context"

    ggithub "github.com/google/go-github/github"
)

type ChangeDiffFetcher struct {
    client *github.Client
}

func NewChangeDiffFetcher() *ChangeDiffFetcher {
    return &ChangeDiffFetcher{
        NewClient(),
    }
}

// from~toのDiffのchangeFilesを取得する
func (c *ChangeDiffFetcher) FetchDiffFiles(from string, to string) ([]ggithub.CommitFile, error) {
    compare, _, err := c.client.Repositories.CompareCommits(context.TODO(), "ownerName", "repositoryName", from, to)
    if err != nil {
        return nil, err
    }

    return compare.Files, nil
}
  • 取得できるgithub.CommitFileに含まれるデータはこんな感じ
 49 // CommitFile represents a file modified in a commit.
 50 type CommitFile struct {↲
 51 >...SHA         *string `json:"sha,omitempty"`
 52 >...Filename    *string `json:"filename,omitempty"`
 53 >...Additions   *int    `json:"additions,omitempty"`
 54 >...Deletions   *int    `json:"deletions,omitempty"`
 55 >...Changes     *int    `json:"changes,omitempty"`
 56 >...Status      *string `json:"status,omitempty"`
 57 >...Patch       *string `json:"patch,omitempty"`
 58 >...BlobURL     *string `json:"blob_url,omitempty"`
 59 >...RawURL      *string `json:"raw_url,omitempty"`
 60 >...ContentsURL *string `json:"contents_url,omitempty"`
 61 }

まとめ

githubのAPIは充実してるので
goでサクッと使えるのはありがたい。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1