Instantly share code, notes, and snippets.

Embed
What would you like to do?
List github repos under org creating a .csv file (github enterprise - python 3 - github api
import requests
import json
import argparse
import logging
github_api_url = "https://github.infra.int.daas-watchguard.com/api/v3"
ghe_access_token = 'your github personal access token'
#logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO, filename='ghe_org_repo_list.log')
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument(
'--orgname', '-o',
type=str,
required=True,
help='Github Org Name'
)
parser.add_argument(
'--csvfile', '-f',
dest='csvfile',
action='store_true',
required=False,
help='Write csv file'
)
parser.set_defaults(csvfile=False)
def get_repos_list(org_name):
global headers
pull_url = github_api_url + "/orgs/" + org_name + "/repos"
payload = {
"type": "all"
}
repo_list = []
pull_response = requests.get(pull_url, headers=headers, json=payload)
logging.info("response status code: " + str(pull_response.status_code))
response_json = pull_response.json()
for item in response_json:
repo_list.append(item["name"])
while 'next' in pull_response.links.keys():
pull_response = requests.get(pull_response.links['next']['url'], headers=headers, json=payload)
response_json = pull_response.json()
for item in response_json:
repo_list.append(item["name"])
return repo_list
def list_repos(repo_list):
for repo in repo_list:
logging.info(repo)
def write_to_csv(repo_list, org_name):
file = open("repolist_" + org_name + ".csv", "w")
file.write("Organization,Repository\n")
for repo in repo_list:
file.write(org_name + "," + repo + "\n")
file.close()
def main():
# get arguments
args = parser.parse_args()
org_name = args.orgname.lower()
csvfile = args.csvfile
global headers
headers = {'Authorization': 'token ' + ghe_access_token, 'Accept': 'application/vnd.github.loki-preview+json'}
repo_list = get_repos_list(org_name)
logging.info("Number of repos: " + str(len(repo_list)))
list_repos(repo_list)
if csvfile:
write_to_csv(repo_list, org_name)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment