【github】組織配下にある全リポジトリのブランチをAPIを使って一覧出力する

IT

年末の棚卸しに必要だったのでAPIで抽出するシェルスクリプトを作成した。

トークンの管理にはMacのキーチェーンを使っているが、そこをゴニョゴニョすれば他のOSでも使えるはず。

GITHUB_DOMAIN="*********"
ORG="********"

# トークン取得
if [ -z "$TOKEN" ]; then
    # トークンを取得する
    TOKEN=$(security find-generic-password -s "${GITHUB_DOMAIN}"-token -w 2>/dev/null)
    # 見つからなかったらトークンの入力を促す
    if [ -z "${TOKEN}" ]; then
        echo "${GITHUB_DOMAIN} のAPIトークンを入力してください。入力されたトークンはmacOSのkeychainに保存します。"
        read -r -s TOKEN
        echo
        # 未入力なら終了
        if [ -z "${TOKEN}" ]; then
            echo "終了します。"
            exit 1
        fi
        security add-generic-password -a 'github-api-tool' -s "${GITHUB_DOMAIN}"-token -w "${TOKEN}"
    fi
fi
HEADER_TMP=$(mktemp)
URL_LIST=$(mktemp)
REPOSITORY_API_URL="https://${GITHUB_DOMAIN}/api/v3/orgs/${ORG}/repos?page=1&per_page=100"
while [ -n "${REPOSITORY_API_URL}" ]; do
  curl -D "${HEADER_TMP}" -s --location --request GET "${REPOSITORY_API_URL}" \
  --header "Authorization: token ${TOKEN}" | yq '.[].url' >> "${URL_LIST}"
  # ヘッダに次のページのURLが書かれている間は繰り返す
  REPOSITORY_API_URL=$(grep '^link: <.*>; rel="next"' "${HEADER_TMP}" | sed -E 's/link: <(.*)>; rel="next".*/\1/')
done

BRANCHES_TMP=$(mktemp)
rm -f branches.txt
while read -r URL; do
    curl -s --location --request GET ${URL}/branches \
    --header "Authorization: token ${TOKEN}" | yq  "\"${URL}/branches/\" + .[].name" >> "${BRANCHES_TMP}"
done < "${URL_LIST}"

while read -r URL; do
    curl -s --location --request GET ${URL} \
    --header "Authorization: token ${TOKEN}" | yq  "[._links.html, .commit.author.login, .commit.commit.author.date]|@tsv"
done < "${BRANCHES_TMP}"
IT
広告
一郎くんどっとこむ