Bitbucketで特定プロジェクトのリポジトリ一覧を取得する


概要

Bitbucket APIで特定プロジェクトのrepository名リストを取得します。

Requirement

APIレスポンスの加工にjqコマンドを使用するので適宜インストールしてください。

# macの場合 以下でOK
brew install jq

手順

以下のスクリプトを作成。

list_bitbucket_repositories.sh
#!/bin/bash

bitbucket_username=$1
bitbucket_password=$2
workspace_id=$3
project_name=$4

PAGE_LEN=100

repo_size=`curl -s -u ${bitbucket_username}:${bitbucket_password} https://api.bitbucket.org/2.0/repositories/${workspace_id} | jq '.size'`
page_count=$((repo_size / PAGE_LEN + 1))

for page in `seq ${page_count}`
do
  repos=`curl -s -u ${bitbucket_username}:${bitbucket_password} "https://api.bitbucket.org/2.0/repositories/${workspace_id}?pagelen=${PAGE_LEN}&page=${page}&sort=name" | jq ".values | map(select(.project.name == \"${project_name}\"))" | jq '.[]' | jq -r '.name'`
  echo "${repos}"
done

実行します。

例として、WorkSpaceID=testworkspace のワークスペース配下にプロジェクトが複数あり、その中のTestProjectというプロジェクトに紐づくリポジトリ名のリストを取得したい場合を考えます。


$ sh list_bitbucket_repositories.sh {bitbucketログインアカウント} {bitbucketログインパスワード} {ワークスペースID} {プロジェクト名}

# 例
$ sh list_bitbucket_repositories.sh testuser testpass testworkspace TestProject
test-android-repo
test-ios-repo
test-server-repo
...

内容

1. ワークスペース内の全リポジトリ数を取得

$ curl -s -u {bitbucket_username}:{bitbucket_password} 'https://api.bitbucket.org/2.0/repositories/{workspace_id}' | jq '.size'

# 例
$ curl -s -u testuser:testpass 'https://api.bitbucket.org/2.0/repositories/testworkspace' | jq '.size'
388

ワークスペース内にリポジトリが388件あることが分かります。

2. リポジトリ名を取得

$ curl -s -u {bitbucket_username}:{bitbucket_password} 'https://api.bitbucket.org/2.0/repositories/{workspace_id}?pagelen=100&page=1&sort=name' | jq '.values | map(select(.project.name == "{project_name}"))' | jq '.[]' | jq -r '.name'

# 例
$ curl -s -u testuser:testpass 'https://api.bitbucket.org/2.0/repositories/testworkspace?pagelen=100&page=1&sort=name' | jq '.values | map(select(.project.name == "TestProject"))' | jq '.[]' | jq -r '.name'
test-android-repo
test-ios-repo
test-server-repo
...

ワークスペース内の全リポジトリ一覧からTestProjectプロジェクトに紐づくリポジトリのみフィルタしnameフィールドを出力します。
APIのレスポンス数(pagelen)は100が最大なので、必要に応じてpageパラメータをincrementします。

詳細はAPI documentを参考にしてください