LoginSignup
8
2

More than 5 years have passed since last update.

GoでGitHubAPIを操作する〜Enterpriseから逃げるは恥だが役に立ったはず

Last updated at Posted at 2016-12-21

ディップ Advent Calendar 2016 - Qiitaにまたしてもやって参りました。

GoでGitHubAPIを操作するネタです。

なぜやるか

とあるデータをGitHubEnterpriseに自動的にブランチを切ってぶっこんでプルリクまで出したい。  
ʕ•ᴥ•ʔ<とにかくGoでやりたい!

やったこと

APIを読んだ

go-githubなるものの存在を知った

ʕ•ᴥ•ʔ<go-github!使いたい!
とりあえず検証するためのリポジトリを作り、Tokenでも取得しよう。

ʕ•ᴥ•ʔ<Tokenはココで取得できるよ!

githubでトークンを取得する

importはこんな感じ。

main.go
import (
    "flag"

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

    config "path/to/config"
)

go-githubを見るとGitHubのユーザと対象のリポジトリ、そして先ほどのTokenが必要そうなので用意しておく。

environments.go
package github

import (
    "os"
)

type Environments struct {
    GitHubOwner      string
    GitHubRepository string
    GitHubToken      string
}

var (
    GetEnvironments = func() *Environments {
        return &Environments{
            GitHubOwner:      os.Getenv("GH_OWNER"),
            GitHubRepository: os.Getenv("GH_REPOSITORY"),
            GitHubToken:      os.Getenv("GH_TOKEN"),
        }
    }
)

サンプルはこんな感じ。
パラメータで渡したブランチを作成してくれる...はず。

main.go
var (
    branchName = flag.String("branch", "", "create branch name")
    baseBranch = "master"
)

func init() {

    logrus.SetLevel(logrus.DebugLevel)
    logrus.SetFormatter(&logrus.JSONFormatter{})

    flag.Parse()
}

func main() {

    client := getGitClient()
    service := client.Git

    createBranch(service)
}

func getGitClient() *github.Client {

    ts := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: config.GetEnvironments().GitHubToken},
    )
    tc := oauth2.NewClient(oauth2.NoContext, ts)
    return github.NewClient(tc)
}

func createBranch(service *github.GitService) error {

    base := baseBranch
    new := *branchName

    masterRef, _, _ := service.GetRef(
        config.GetEnvironments().GitHubOwner,
        config.GetEnvironments().GitHubRepository,
        "heads/" + base,
    )


    ref := &github.Reference{
        Ref: github.String("refs/heads/" + new),
        Object: &github.GitObject{
            SHA: masterRef.Object.SHA,
        },
    }
    _, _, err := service.CreateRef(
        config.GetEnvironments().GitHubOwner,
        config.GetEnvironments().GitHubRepository,
        ref,
    )

    return err
}

試しに走らせてみよう!

go run main.go --branch "feature/new_branch"

ʕ•ᴥ•ʔ<Dream!

そして...

お気づきだろうか。
わたしが懸命にテストしていたのは、GitHubなのであって、GitHubEnterpriseではないのでした。

ココの部分なんとかならないのかな。

github.com/google/go-github/blob/master/github/github.go
defaultBaseURL = "https://api.github.com/"

Issueも上がってるし!誰か...誰か...

8
2
2

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
8
2