nataliaking
12/20/2016 - 6:04 PM

cleanup-forks-from-github.py

#! /usr/bin/python3

import argparse
from operator import attrgetter
import os
import sys
from github import Github


def main():
    desc = 'List and delete fork repositories in a GitHub org (env: GH_TOKEN)'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('--github-token',
                        help='GitHub API Token',
                        dest='token',
                        default=os.environ.get('GH_TOKEN', None),)
    parser.add_argument('-d,--delete',
                        help='delete forks in organization',
                        dest='delete',
                        action='store_true')
    parser.add_argument('--org',
                        help='github organization',
                        dest='org',
                        required=True)
    args = parser.parse_args()
    if not args.token:
        sys.exit(parser.print_usage())

    g = Github(args.token)
    forks = retrieve_forks(g, args.org)
    if args.delete:
        answer = input('please confirm deletion! [y/n]\n')
        if answer == 'yes' or answer == 'y':
            delete_forks(forks)
    else:
        list_forks(forks)


def list_forks(forks):
    for fork in forks:
        print(fork.name)


def delete_forks(forks):
    for fork in forks:
        fork.delete()


def retrieve_forks(g, org):
    org = g.get_organization(org)
    repos = org.get_repos('forks')
    forks = [repo for repo in repos]
    return sorted(forks, key=attrgetter('name'))

    
if __name__ == '__main__':
    main()