Skip to content

Instantly share code, notes, and snippets.

@r-leyshon
Created April 16, 2024 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-leyshon/4fca0d78749ac302e93872beb020251a to your computer and use it in GitHub Desktop.
Save r-leyshon/4fca0d78749ac302e93872beb020251a to your computer and use it in GitHub Desktop.
Add a group of collaborators to a repository
import warnings
import requests
import toml
from pyprojroot import here
CONFIG = toml.load(here("secrets.toml"))
AGENT = CONFIG["USER"]["AGENT"]
USERS = CONFIG["GITHUB"]["USERNAMES"]
PAT = CONFIG["GITHUB"]["PAT"]
def batch_add_collabs_to_repo(
owner:str, repo:str, users:list, pat:str, agent:str, permission:str="push",
) -> list:
"""Add a group of collaborators to a repository.
Requires authentication. Uses put request with default permission set to
"push". Rate limit of 50 users per 24 hour period applies, unless working
with an organization repository.
Parameters
----------
owner : str
The GitHub username of the repository owner.
repo : str
The repository name.
users : list
A list of valid usernames to add as collaborators. Warns if user not
found.
pat : str
This request requires authentication. Use a valid GitHub PAT.
agent : str
Your user agent.
permission : str, optional
Level of access to grant. Accepts pull, triage, push, maintain, admin,
by default "push"
Returns
-------
list
A list of the responses.
"""
if len(users) > 50:
warnings.warn(
"Limit of 50 users per 24 hr period to personal repos only")
perms = ["pull", "triage", "push", "maintain", "admin"]
if permission not in perms:
raise ValueError(f"permission must be one of {perms}")
params = {
"Accept": "application/vnd.github+json",
"permission": permission,
}
SLUG = "https://api.github.com/repos"
endpoint = f"{SLUG}/{owner}/{repo}/collaborators/USERNAME"
responses = []
for i in users:
url = endpoint.replace("USERNAME", i)
resp = requests.put(
url,
params=params,
headers={
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": agent,
"Authorization": f"Bearer {pat}"
})
if not resp.ok:
warnings.warn(f"Add {i} failed: {resp.reason}")
responses.append(resp)
return responses
resps = batch_add_collabs_to_repo(
"r-leyshon", "pytest-playground", users=USERS, pat=PAT, agent=AGENT
)
[USER]
AGENT = "<INSERT_USER_AGENT>"
[GITHUB]
PAT = "<INSERT_PAT>"
USERNAMES = [
"<USER_1>",
"<USER_2>",
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment