Last active
June 30, 2021 04:49
-
-
Save barezina/caca78b96b8455295cf4a13c8ad16a93 to your computer and use it in GitHub Desktop.
Bulk remove collaborator from all repos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__ . '/vendor/autoload.php'; | |
use GuzzleHttp\Client; | |
/** | |
* Remove the specified user from all repositories | |
* that we are authenticated to see and manage. | |
*/ | |
$client = new GuzzleHttp\Client(); | |
$githubUsername = ''; | |
$githubAccessToken = ''; | |
$userToRemove = ''; | |
$gh = new Client([ | |
'base_uri' => 'https://api.github.com', | |
'auth' => [ | |
$githubUsername, | |
$githubAccessToken | |
] | |
]); | |
$res = $gh->request('GET', 'user', []); | |
echo "\n"; | |
echo "Removing $userToRemove as a collaborator from all repos administered by $githubUsername\n\n"; | |
for ($i = 1; $i < 11; $i++) { | |
$repoResponse = $gh->request('GET', "user/repos?per_page=100&page=$i"); | |
$repos = json_decode((string) $repoResponse->getBody(), true); | |
if (count($repos) == 0) { | |
break; | |
} | |
foreach ($repos as $repo) { | |
if ($repo['owner']['login'] == $githubUsername) { | |
$repoName = $repo['full_name']; | |
$removeCollaborator = "repos/$repoName/collaborators/$userToRemove"; | |
$gh->request('DELETE', $removeCollaborator); | |
echo $userToRemove . ' removed from ' . $repoName . "\n"; | |
// Make sure the user to remove isn't in an invited state | |
// If so, remove their invite. | |
$inviteResponse = $gh->request('GET', "repos/$repoName/invitations"); | |
$inviteList = json_decode((string)$inviteResponse->getBody(), true); | |
foreach ($inviteList as $invite) { | |
$inviteId = $invite['id']; | |
$invitee = $invite['invitee']['login']; | |
if ($invitee == $userToRemove) { | |
echo "Removing invite $inviteId for $invitee to $repoName\n"; | |
$removeInvitePath = "repos/$repoName/invitations/$inviteId"; | |
$gh->request('DELETE', $removeInvitePath); | |
} | |
} | |
} | |
} | |
} | |
echo "\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment