TL;DR
特定のファイルがdiffに含まれるdeployを抽出してアラート出すとか、
承認入れるとかそんなことをする必要が出てきたので,githubのgoSDKを
使ってみたメモ。
ライブラリ
Google様が用意してくれていたので巨人の肩に乗る。やったぜ。
ちなみにv4(GraphQL)は未対応。
使い方
- 認証情報のsetUpをざっくり書く
- githubのtoken取得はこちらの記事あたりが良いかも
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引数で渡す方が行儀良いです(手抜き
-
このendpoint に対応する
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でサクッと使えるのはありがたい。