LoginSignup
6
1

More than 5 years have passed since last update.

GitのコミットハッシュからGithubのプルリクエスト番号を取得する

Last updated at Posted at 2019-01-17

概要

どうしてもshellscriptでGitのコミットハッシュから、Githubのプルリクエストの番号を取得する必要があった

前提

GithubのPersonal access tokenを事前に取得しておくこと
( https://github.com/settings/tokens/new から取得)
privateリポジトリの場合、 Full control of private repositories にチェックを入れないとうまくいかなかった

また、下記コマンドを使用するのであらかじめインストールしておくこと

  • curl
  • jq

コード

pull_requests=(`curl -s -H "Authorization: Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}" "https://api.github.com/search/issues?q=repo%3A${GITHUB_USER_NAME}%2F${REPOSITORY_NAME}+is%3Apr+${GIT_COMMIT_HASH}" | jq ".items[].number"`)

で変数 pull_requests に配列でプルリクエストのIDが入る
あとはその配列をよしなに使う

解説

Githubの検索APIを使って、 issues をプルリク限定のみに絞り込んでコミットハッシュで検索している
( +is%3Apr の後に +is%3Aopenをつけて open なプルリクのみ検索とかも可能)
curl で叩くと

{
  "total_count": 1,
  "incomplete_results": false,
  "items": [
    {
      "url": "https://api.github.com/repos/hoge/fuga/issues/1234",
      "repository_url": "https://api.github.com/repos/hoge/fuga",
      "labels_url": "https://api.github.com/repos/hoge/fuga/issues/1234/labels{/name}",
      "comments_url": "https://api.github.com/repos/hoge/fuga/issues/1234/comments",
      "events_url": "https://api.github.com/repos/hoge/fuga/issues/1234/events",
      "html_url": "https://github.com/hoge/fuga/pull/1234",
      "id": 123456789,
      "node_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
      "number": 1234, # プルリクエスト番号
      "title": "P-Rタイトル",
      ...
      ...
      ...
    }
  ]
}

というような感じで、そのコミットハッシュが含まれるプルリクエストの情報が(存在すれば) JSON で返ってくるので、 jq コマンドで整形している

6
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
6
1