Skip to content

Instantly share code, notes, and snippets.

@LukeB42
Created January 11, 2015 20:10
Show Gist options
  • Save LukeB42/14532718d124c682d398 to your computer and use it in GitHub Desktop.
Save LukeB42/14532718d124c682d398 to your computer and use it in GitHub Desktop.
Search github on the command line with the github3 package
#!/usr/bin/env python
import sys, github3
def search_github(terms):
data = []
results = github3.api.search_repositories(' '.join(terms))
for i in results:
j = i.to_json()
item={}
item['url'] = j['git_url'].encode('ascii','ignore')
if j['description']:
item['desc'] = j['description'].encode('ascii','ignore')
else:
item['desc'] = ''
item['lang'] = j['language'].encode('ascii','ignore')
item['modified'] = j['updated_at'].encode('ascii','ignore')
item['score'] = str(int(j['score'])).encode('ascii','ignore')
data.append(item)
return str(TablePrinter(format(data), ul='-')(data))
class TablePrinter(object):
"Print a list of dicts as a table"
def __init__(self, fmt, sep=' ', ul=None):
"""
@param fmt: list of tuple(heading, key, width)
heading: str, column label
key: dictionary key to value to print
width: int, column width in chars
@param sep: string, separation between columns
@param ul: string, character to underline column label, or None for no underlining
"""
super(TablePrinter,self).__init__()
self.fmt = str(sep).join('{lb}{0}:{1}{rb}'.format(key, width, lb='{', rb='}') for heading,key,width in fmt)
self.head = {key:heading for heading,key,width in fmt}
self.ul = {key:str(ul)*width for heading,key,width in fmt} if ul else None
self.width = {key:width for heading,key,width in fmt}
def row(self, data):
return self.fmt.format(**{ k:str(data.get(k,''))[:w] for k,w in self.width.iteritems() })
def __call__(self, dataList):
_r = self.row
res = [_r(data) for data in dataList]
res.insert(0, _r(self.head))
if self.ul:
res.insert(1, _r(self.ul))
return '\n'.join(res)
def format(data):
fmt=[]
tmp={}
for item in data:
for key,value in item.items():
if not key in tmp.keys():
if value: tmp[key] = len(str(value))
elif len(str(value)) > tmp[key]:
if value: tmp[key] = len(str(value))
for key,value in tmp.items():
fmt.append((key, key, value))
return(fmt)
if __name__ == '__main__':
if len(sys.argv) < 2:
print "%s terms <language:language>" % sys.argv[0]
raise SystemExit
terms = sys.argv[1:]
results = search_github(terms)
results = results.encode('ascii', 'ignore')
print results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment