トップ «前の日記(2022/05/26 (木) ) 最新 次の日記(2022/05/28 (土) )» 編集 RSS feed

HsbtDiary


2022/05/27 (金) [長年日記]

GitHub の pull-request を API のみで作成するのはちょっと面倒

タイトルが全てですが、更新内容、ファイルパスがあればシュッと作れるじゃん?と思ったらそうでもなかったのでログっておきます。結論としては以下のようなコードを書く必要がある。

github = Octokit::Client.new

repo = "github/github"
branch_name = "feature/awesome-github"
path = "README.md"
commit_message = "oops"
content = "Hello! GitHub"
pr_title = "Update README.md"

default_branch = github.repo(repo).default_branch
github.create_ref(repo, "refs/heads/#{branch_name}", github.ref(repo, "heads/#{default_branch}").object.sha)
github.create_contents(repo, path, commit_message, content, :branch => branch_name)
github.create_pull_request(repo, default_branch, branch_name, pr_title)

渡す必要がある変数は repo から pr_title までの内容となっていて、実際の処理は下部にある 4 行。これ、Git の内部構造や pull-request を知っていれば、そうだね、って内容なのでいいんだけど、この辺は一つの API でできて欲しいんだよなあ。

最初、create_ref の部分が見当もつかなくて、同僚の @pyama86 や @k1low から Ruby や Go で書いた実装を教えてもらってから一番短い形でこれ、というのにたどり着いた。最近は上のコードをあちこちで使って、仕事で使ってる GHES の方にバシバシ機械的に作成した pull-request を投げてます。