LoginSignup
1
0

GitHubのTeamにリポジトリをAPIで追加するスクリプト

Posted at

なぜこのようなスクリプト

Organizationの権限管理をTeamでやりたいということになった。

Teamにはアクセスできるリポジトリを設定できる。
しかしOrganizationのリポジトリが200以上あるためこれを手作業でやるのは苦行である。

そこでGitHubのAPIを使用して指定したTeamにOrganization配下のリポジトリを設定する簡単なスクリプトを作った。

作成したスクリプト

実行コマンド。
リポジトリの一覧APIの結果件数が最大100までなので、100件以上ある場合のため引数でページ番号を指定する。

./add-repo-to-team.sh 1

エラー制御はしていない。
リポジトリ一覧APIの結果件数を増やしたい場合は per_page を設定するといいが今回は細かく確認したかったのでデフォルトのままにしてある。

add-repo-to-team.sh
#!/bin/bash

page="$1"
if [ -z "$page" ]; then
    echo "リポジトリ一覧のページ番号を設定してください。"
    exit 1
fi

read -p "GitHubパーソナルアクセストークンを入力してください( https://github.com/settings/tokens/new でrepoをオンにする): " token
if [ -z "$token" ]; then
    echo "パーソナルアクセストークンを設定してください。"
    exit 1
fi

read -p "Organization名を入力してください: " org
if [ -z "$org" ]; then
    echo "Organization名を設定してください。"
    exit 1
fi

read -p "Team名を入力してください: " team_slug
if [ -z "$team_slug" ]; then
    echo "Team名を入力してください。"
    exit 1
fi

# リポジトリ一覧取得
# https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#list-organization-repositories
response=$(curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $token" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/orgs/$org/repos?page="$page")
# echo "$response"

for repo_name in $(echo "$response" | jq -r '.[].name'); do
    echo "$repo_name"

    # Teamにリポジトリを追加する
    # https://docs.github.com/en/rest/teams/teams?apiVersion=2022-11-28#add-or-update-team-project-permissions
    response=$(curl -s \
      -X PUT \
      -H "Accept: application/vnd.github+json" \
      -H "Authorization: Bearer $token" \
      -H "X-GitHub-Api-Version: 2022-11-28" \
      https://api.github.com/orgs/$org/teams/$team_slug/repos/$org/$repo_name \
      -d '{"permission":"push"}')
    # echo "$response"
done
1
0
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
1
0