From 9739d1351a946629c842bb85b95749a916d68efc Mon Sep 17 00:00:00 2001 From: Josh Johanning Date: Wed, 8 Jan 2025 15:19:24 -0600 Subject: [PATCH] feat: add script to add all repository users to a project --- gh-cli/README.md | 6 ++ .../add-all-users-in-repository-to-project.sh | 57 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100755 gh-cli/add-all-users-in-repository-to-project.sh diff --git a/gh-cli/README.md b/gh-cli/README.md index c92e852..9ce5284 100644 --- a/gh-cli/README.md +++ b/gh-cli/README.md @@ -69,6 +69,12 @@ See the [docs](https://cli.github.com/manual/gh_auth_login) for further informat Adds all members of an organization to a team. +### add-all-users-in-repository-to-project.sh + +Adds all users who are direct members of the repository to a ProjectV2 with a given role. + +Requires: `./add-user-to-project.sh` + ### add-branch-protection-status-checks.sh Adds a status check to the branch protection status check contexts. diff --git a/gh-cli/add-all-users-in-repository-to-project.sh b/gh-cli/add-all-users-in-repository-to-project.sh new file mode 100755 index 0000000..4cf2556 --- /dev/null +++ b/gh-cli/add-all-users-in-repository-to-project.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +# Adds a all users in a repository to a ProjectV2 + +# needs: gh auth login -s project +# needs: ./add-user-to-project.sh + +function print_usage { + echo "Usage: $0 " + echo "Example: ./add-all-users-in-repository-to-project.sh joshjohanning-org my-repo 1234 WRITER" + echo "Valid roles: ADMIN, WRITER, READER, NONE" + exit 1 +} + +if [ -z "$4" ]; then + print_usage +fi + +organization="$1" +repository="$2" +project_number="$3" +role=$(echo "$4" | tr '[:lower:]' '[:upper:]') + +case "$role" in + "ADMIN" | "WRITER" | "READER" | "NONE") + ;; + *) + print_usage + ;; +esac + +# get list of directly added users in a repository +users=$(gh api graphql --paginate -f owner="$organization" -f repo="$repository" -f query=' +query($owner: String!, $repo: String!, $endCursor:String) { + repository(owner: $owner, name: $repo) { + collaborators(first: 100, affiliation: DIRECT, after:$endCursor) { + edges { + node { + login + id + } + } + pageInfo { + hasNextPage + endCursor + } + } + } +} +' --jq '.data.repository.collaborators.edges[].node') + +# for each user, add them to the project +for user in $users; do + user_login=$(echo $user | jq -r '.login') + echo "Adding $user_login to project $project_id with role $role" + ./add-user-to-project.sh $organization $repository $project_number $user_login $role +done