Skip to content

Instantly share code, notes, and snippets.

@jonjozwiak
Created October 2, 2024 21:07
Show Gist options
  • Select an option

  • Save jonjozwiak/bf14f180cf164e5a391e6e7004c8b040 to your computer and use it in GitHub Desktop.

Select an option

Save jonjozwiak/bf14f180cf164e5a391e6e7004c8b040 to your computer and use it in GitHub Desktop.
List all public repos in your enterprise by org
import os
import requests
import csv
# Read GitHub token from environment variable
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
if not GITHUB_TOKEN:
raise EnvironmentError("Please set the GITHUB_TOKEN environment variable.")
GITHUB_GRAPHQL_URL = 'https://api.github.com/graphql'
ENTERPRISE_NAME = 'YOUR-ENTERPRISE-HERE'
# Headers for authentication
headers = {
'Authorization': f'bearer {GITHUB_TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
def run_query(query, variables):
response = requests.post(GITHUB_GRAPHQL_URL, json={'query': query, 'variables': variables}, headers=headers)
response.raise_for_status()
return response.json()
def get_enterprise_organizations_and_repos(enterprise):
query = """
query($enterprise: String!, $cursor: String) {
enterprise(slug: $enterprise) {
organizations(first: 100, after: $cursor) {
nodes {
login
repositories(first: 100, privacy: PUBLIC) {
totalCount
nodes {
name
}
pageInfo {
endCursor
hasNextPage
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
"""
variables = {'enterprise': enterprise, 'cursor': None}
organizations = []
while True:
result = run_query(query, variables)
orgs = result['data']['enterprise']['organizations']['nodes']
organizations.extend(orgs)
page_info = result['data']['enterprise']['organizations']['pageInfo']
if page_info['hasNextPage']:
variables['cursor'] = page_info['endCursor']
else:
break
return organizations
def main():
organizations = get_enterprise_organizations_and_repos(ENTERPRISE_NAME)
with open('public_repo_count.csv', mode='w', newline='') as count_file, \
open('public_repo_list.csv', mode='w', newline='') as list_file:
count_writer = csv.writer(count_file)
list_writer = csv.writer(list_file)
count_writer.writerow(['organization', 'repo_count'])
list_writer.writerow(['organization', 'repo'])
for org in organizations:
org_name = org['login']
repo_count = org['repositories']['totalCount'] if org['repositories'] else 0
count_writer.writerow([org_name, repo_count])
if org['repositories'] and org['repositories']['nodes']:
for repo in org['repositories']['nodes']:
if repo and 'name' in repo:
list_writer.writerow([org_name, repo['name']])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment