comparison python/pypi.py @ 369:11cf7018ebff

new crappy package for helping me with http://k0s.org/portfolio/python/python-tools.txt
author Jeff Hammel <jhammel@mozilla.com>
date Sun, 21 Jul 2013 05:27:28 -0700
parents
children 016d27ca39e4
comparison
equal deleted inserted replaced
368:6f1e4562c06a 369:11cf7018ebff
1 #!/usr/bin/env python
2
3 """
4 pypi strawman that should really be in PaInt
5
6 ref http://wiki.python.org/moin/PyPIJSON
7 """
8
9 import json
10 import optparse
11 import os
12 import sys
13 import textwrap
14 import urllib2
15
16 def package_data(package, index='http://pypi.python.org/pypi'):
17 """
18 returns dict of {url:, description:, home_page: }
19 """
20
21 # if package name given, -> url
22 url = package
23 if '://' not in url:
24 url = '%s/%s' % (index, package)
25 url = url.rstrip('/')
26
27 if not url.endswith('/json'):
28 url = '%s/json' % (url)
29
30 # read the URL
31 try:
32 page = urllib2.urlopen(url).read()
33 except:
34 raise # TODO: better error handling
35
36 data = json.loads(page)
37 info = data['info']
38
39 # massage the data
40 return {'summary': info.get('summary', ''),
41 'package_url': info['package_url'],
42 'name': info['name'],
43 'home_page': info.get('home_page')
44 # etc
45 }
46
47
48 def main(args=sys.argv[1:]):
49
50 # command line parser
51 usage = '%prog [options] package <another_package> <...>'
52 parser = optparse.OptionParser(usage=usage, description=__doc__)
53 parser.add_option('-t', '--tag', dest='tags',
54 action='append', help="tags for packages")
55 options, args = parser.parse_args(args)
56 if not args:
57 parser.print_usage()
58 parser.exit()
59
60 # one crappy ass template
61 template = """ * %(package_url)s
62 %(summary)s
63 %(tags)s
64 """
65
66 # get package data
67 packages = {}
68 for package in args:
69 data = package_data(package)
70 packages[data['name']] = data
71
72 # render the damn thing
73 rendered = []
74 for name in sorted(packages.keys(), key=lambda x: x.lower()):
75 values = packages[name].copy()
76 if options.tags:
77 values['tags'] = '{%s}' % ', '.join(options.tags)
78 else:
79 values['tags'] = ''
80 if values['home_page'] and values['home_page'] != values['package_url']:
81 values['summary'] = '%s %s' % (values['summary'],
82 values['home_page'])
83 values['summary'] = textwrap.fill(values['summary'], 69,
84 initial_indent=' ',
85 subsequent_indent=' ')
86 string = template % values
87 rendered.append(string.strip())
88
89 print '\n\n'.join([i.strip() for i in rendered])
90
91 if __name__ == '__main__':
92 main()