Last active
April 29, 2016 13:53
-
-
Save boechat107/976913970727aec5efeaa99b250d9f5a to your computer and use it in GitHub Desktop.
Simple script to fetch information about a Github user's repositories
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
#!/usr/bin/python | |
import argparse | |
import urllib2 | |
import json | |
import pprint | |
def sort_by(dictlist, k, **kwargs): | |
return sorted(dictlist, key=(lambda d: d[k]), **kwargs) | |
def filter_repo_info(repo_data): | |
"""Given a repository dictionary, returns a new dictionary with just the | |
relevant keys. | |
""" | |
relevant_keys = ['stargazers_count', 'forks_count', | |
'name', 'description', 'url'] | |
return {k: repo_data[k] for k in relevant_keys} | |
def get_repos(username): | |
"""Returns a list of dictionaries containing all repositories of an user.""" | |
url = "https://api.github.com/users/{0}/repos".format(username) | |
return json.loads(urllib2.urlopen(url).read()) | |
def take_top_repos(repos, n): | |
"""Returns relevant info the top n repositories of the given username.""" | |
## Sorting the repositories by the stars count. | |
srepos = sort_by(repos, 'stargazers_count', reverse=True) | |
## Filtering the relevant info from the top N repositories. | |
return [filter_repo_info(r) for r in srepos[:n]] | |
def repos_stats(repos): | |
"""Returns a dictionary with the average number of stargazers and forks.""" | |
n_repos = float(len(repos)) | |
counters = reduce(lambda cnt, repo: (cnt[0] + repo['stargazers_count'], | |
cnt[1] + repo['forks_count']), | |
repos, | |
(0, 0)) | |
return {'avg_stars': counters[0] / n_repos, | |
'avg_forks': counters[1] / n_repos} | |
def main(args): | |
pp = pprint.PrettyPrinter(indent=4) | |
repos = get_repos(args.username) | |
stats = repos_stats(repos) | |
top_repos = take_top_repos(repos, args.top_n) | |
print "\nTop repositories of {0}:\n".format(args.username) | |
pp.pprint(top_repos) | |
print "\nSome statistics:\n" | |
pp.pprint(stats) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('username', metavar='username', | |
help="Github username") | |
parser.add_argument('-n', '--top-n', type=int, default=5, | |
help="Number of top repositories") | |
ns = parser.parse_args() | |
main(ns) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment