技術備忘記

日々調べたこととかとりとめなく

GoからGitHub APIを利用する

はじめに

とあるツールを作っていて、GoのコードからGithub APIを叩く必要があったので、使用したライブラリや、スニペットなどを残しておこうと思います。ちなみにエラーハンドリングは一切していないです。予めご了承ください。

使用ライブラリ

go-github を使いました。Goから Github APIを利用する際に使用するライブラリとしては、現状実質これ一択になると思います。 ドキュメントがすごくしっかりしているので、Github API v3の知識がそれなりにさえあれば、ほぼ詰まることなくやりたいことが実現できると思います。オススメです。

スニペット

oauth2 認証

owner := "your github account name"
repo := "your github repository"
token := "your github access token"

ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(oauth2.NoContext, ts)

cl := github.NewClient(tc)
srv := cl.Git // *github.GitService

push 的な流れ

branch 作成

dRef, _, _ := srv.GetRef(owner, repo, "heads/develop")
branchName := "feature/new_branch"
ref := &github.Reference{
    Ref: github.String("refs/heads/" + branchName),
    Object: &github.GitObject{
        SHA: mRef.Object.SHA,
    },
}
// developから新しくfeature/new_branchを作成
srv.CreateRef(owner, repo, ref)

commit tree 作成

blob := &github.Blob{
    Content:  github.String("test"),
    Encoding: github.String("utf-8"),
    Size:     github.Int(len("test")),
}
resB, _, _ = srv.CreateBlob(owner, repo, blob)

entry := github.TreeEntry{
    Path: github.String("path/to/test"),
    Mode: github.String("100644"),
    Type: github.String("blob"),
    SHA: resB.SHA,
}

entries := []github.TreeEntry{entry}

tree, _, err := srv.CreateTree(owner, repo, *dRef.Object.SHA, entries)

commit

// developの最新commitを取得
parent, _, _ := srv.GetCommit(owner, repo, *dRef.Object.SHA)

commit := &github.Commit{
    Message: github.String("commit from golang!"),
    Tree:    tree,
    Parents: []github.Commit{*parent},
}
// commit作成
resC, _, err := srv.CreateCommit(owner, repo, commit)

// 作成したbranchに紐付ける
nref := &github.Reference{
    Ref: github.String("refs/heads/" + branchName),
    Object: &github.GitObject{
        Type: github.String("commit"),
        SHA:  resC.SHA,
    },
}
srv.UpdateRef(owner, repo, nref, false)

pull request

prSrv := cl.PullRequests
npr := &github.NewPullRequest{
    Title: github.String("test"),
    Head:  github.String(owner + ":" + branchName),
    Base:  github.String("develop"),
    Body:  github.String("test"),
}
prSrv.Create(owner, repo, npr)

pull 的な流れ

dRef, _, _ := srv.GetRef(owner, repo, "heads/develop")

tree, _, _ := srv.GetTree(owner, repo, *dRef.Object.SHA, true)

for _, e := range tree.Entries {
    if *e.Type != "blob" {
        continue
    }
    blob, _, _ := srv.GetBlob(owner, repo, *e.SHA)
    dec, _ := base64.StdEncoding.DecodeString(*blob.Content)
    fmt.Println(dec)
}

終わりに

今回はブログというか、本当に備忘といった感じです。 まあ本ブログのテーマ通りなので良いのですが (^^;)