-
-
Save msarahan/33dcf4b13c83ada1e721c519b5f5f25d to your computer and use it in GitHub Desktop.
This file contains 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
"""Set all repositories of a given GitHub organization name for a given user | |
to watching. | |
""" | |
import argparse | |
import json | |
import requests | |
import os | |
def get_repos(url, repo_list=[], auth=None): | |
req = None | |
if auth: | |
try: | |
req = requests.get(url, auth=auth) | |
except requests.exceptions.ConnectionError: | |
# handle tokens for people with 2FA | |
req = requests.get(url, auth=(auth[1], 'x-oauth-basic')) | |
else: | |
req = requests.get(url) | |
if (req.ok): | |
repos = json.loads(req.text or req.content) | |
repo_list += repos | |
links = getattr(req, 'links', None) | |
if links and 'next' in links and 'url' in links['next']: | |
get_repos(links['next']['url'], repo_list=repo_list, auth=auth) | |
return repo_list | |
def main(user, password_or_auth_token, org_name, outfile): | |
auth = (user, password_or_auth_token) | |
repo_url = 'https://api.github.com/orgs/{0}/repos'.format(org_name) | |
headers = {'Content-Type': 'application/json; charset=UTF-8'} | |
repo_list = get_repos(repo_url, auth=auth) | |
lines = [] | |
if os.path.isfile(outfile): | |
with open(outfile) as f: | |
f.seek(0) | |
lines = [it.strip('\n').strip('\r') for it in f] | |
with open(outfile, 'a') as f: | |
for repo in repo_list: | |
repo_name = repo['name'] | |
if repo_name in lines: | |
continue | |
url = 'https://api.github.com/repos/{0}/{1}/subscription'.format( | |
org_name, | |
repo_name | |
) | |
res = requests.put( | |
url=url, | |
data='{"subscribed": "1"}', | |
headers=headers, | |
auth=auth | |
) | |
if res.status_code == 200: | |
f.write('{0}\n'.format(repo_name)) | |
print('status {0} | repo {1}'.format( | |
res.status_code, | |
repo_name | |
)) | |
else: | |
print('ERROR! status {0} | repo {1}'.format( | |
res.status_code, | |
repo_name | |
)) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Watch/unwatch GitHub Repositories') # noqa | |
parser.add_argument('user', type=str, help='GitHub username') | |
parser.add_argument('password_or_auth_token', type=str, help='GitHub password/auth token') | |
parser.add_argument('org_name', type=str, help='GitHub organization name') | |
parser.add_argument('--outfile', type=str, default='repos_set.txt', help='Name of the file to write each successful changed repository to. Used for avoiding unnecessart API calls.') # noqa | |
args = parser.parse_args() | |
main(**vars(args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment