Github 계정 내 모든 repository 내 특정 collaborator 일괄 제거 스크립트

yeshyungseok·2024년 2월 5일
0
post-thumbnail

스크립트(python)

import requests
import math

username = 'github ID'
collaborator = '제거하고자 하는 collaborator의 github ID'
token = 'github personal access token'
repositories_count = 200 # 리포지토리 개수, 200은 예시
success_count, failure_count = 0, 0


headers = {'Authorization': f'token {token}'}
max_page = math.ceil(repositories_count / 100) + 1

for page in range(1, max_page):
    # 회사 github 리포지토리 목록 100개 단위로 조회
    repositories_url = f'https://api.github.com/search/repositories?q=user:{username}&per_page={100}&page={page}'
    repositories = requests.get(repositories_url, headers=headers).json()['items']
    for repo in repositories:
        repo_name = repo['name']
        collaborator_url = f'https://api.github.com/repos/{username}/{repo_name}/collaborators/{collaborator}'

        # 리포지토리 확인하여 collaborator 목록에서 삭제
        response = requests.delete(collaborator_url, headers=headers)
        if response.status_code == 204:
            success_count += 1
            print(f'Successfully removed {collaborator} from {repo_name}')
        else:
            failure_count += 1
            print(f'Failed to remove {collaborator} from {repo_name}. Status code: {response.status_code}')

        # 리포지토리 확인하여 삭제되었는지 확인. 아직 존재한다면 응답코드 204
        response = requests.get(collaborator_url, headers=headers)
        if response.status_code == 204:
            remain_count += 1
            remain_list.append(repo_name)

print(f'total repositories: {success_count + failure_count}')
print(f'Success: {success_count}')
print(f'Fail: {failure_count}')

# 제거에 실패한 레포지토리가 존재한다면, 해당 리스트들을 출력
if remain_count:
    print(f'{collaborator} still remains in {failure_count} repositories.')
    print(f'Repositories:')
    [print(remain) for remain in remain_list]

GitHub REST API에서 제공하는 API를 활용해 깃허브 계정 내 존재하는 모든 레포지토리에서 특정 계정을 collaborator 명단에서 제거할 수 있는 스크립트를 작성했다.


해당 스크립트를 사용하기 위해서는 python requests 모듈을 설치해야 한다.

적게는 수 십 개, 많게는 수 천 개의 레포지토리를 보유하고 있는 기업 혹은 기관의 github 계정에서 퇴사자가 발생했을 시, 모든 레포지토리를 확인하며 일일이 collaborator를 제거해야 하는 불상사를 막을 수 있을 것이다.

profile
FE 개발자

0개의 댓글