]> piware.de Git - bin.git/blob - workitems.py
workitems: fix parsing of last line
[bin.git] / workitems.py
1 #!/usr/bin/python
2
3 import urllib, re, sys, optparse, os.path, datetime
4 import sqlite3 as dbapi2
5
6 blueprints_base_url = 'https://blueprints.launchpad.net'
7
8 valid_states = ['todo', 'done', 'postponed']
9
10 def get_db(dbpath):
11     '''Open/initialize database.
12
13     This creates the database if it does not exist.
14     '''
15     init = not os.path.exists(dbpath)
16
17     db = dbapi2.connect(dbpath)
18
19     if init:
20         cur = db.cursor()
21         cur.execute('''CREATE TABLE work_items (
22             blueprint VARCHAR(255) NOT NULL,
23             workitem VARCHAR(255) NOT NULL,
24             status VARCHAR(20) NOT NULL,
25             date TIMESTAMP NOT NULL)''')
26         db.commit()
27
28     return db
29
30 def parse_argv():
31     '''Parse CLI arguments.
32
33     Return (options, args) tuple.
34     '''
35     optparser = optparse.OptionParser()
36     optparser.add_option('-d', '--database',
37         help='Path to database', dest='database', metavar='PATH')
38     optparser.add_option('-r', '--release',
39         help='Release name', dest='release')
40     optparser.add_option('-p', '--pattern', metavar='REGEX',
41         help='Regex pattern for blueprint name', dest='pattern')
42     optparser.add_option('-D', '--dump', action='store_true', default=False,
43         help='Dump database', dest='dump')
44     optparser.add_option('-m', '--moin', metavar='URL',
45         help='moin URL for additional work items (can be given multiple times)', 
46         action='append', dest='moin', default=[])
47     optparser.add_option('-t', '--text', action='store_true', default=False,
48         help='Print work item summary in text format', dest='text')
49     optparser.add_option('-c', '--csv', action='store_true', default=False,
50         help='Print work item summary in CSV format', dest='csv')
51     optparser.add_option('-H', '--html', action='store_true', default=False,
52         help='Generate work item HTML report', dest='html')
53     optparser.add_option('--from', metavar='YYYY-MM-DD',
54         help='Generate CSV data from this day on', dest='from_date')
55     optparser.add_option('--to', metavar='YYYY-MM-DD',
56         help='Generate CSV data until this day', dest='to_date')
57
58     (opts, args) = optparser.parse_args()
59
60     if not opts.database:
61         optparser.error('No database given')
62     if not opts.dump and not opts.text and not opts.csv and not opts.html:
63         if not opts.release:
64             optparser.error('No release given')
65         if not opts.pattern:
66             optparser.error('No pattern given')
67
68     return (opts, args)
69
70 def get_blueprints(url, name_pattern):
71     '''Return a list of blueprint URLs for the current release.'''
72
73     blueprint_name_filter = re.compile('href="(/ubuntu/\+spec/%s[^"]+)"' %
74             name_pattern)
75
76     result = []
77     for l in urllib.urlopen(url):
78         m = blueprint_name_filter.search(l)
79         if m:
80             result.append(blueprints_base_url + m.group(1))
81
82     return result
83
84 def get_blueprint_workitems(blueprint_url):
85     '''Collect work items from a particular blueprint URL.
86
87     This will return a list of ('item', 'status') pairs.
88     '''
89     work_items_re = re.compile('(<p>|^)work items:\s*<br />', re.I)
90
91     found_workitems = False
92     result = []
93     for l in urllib.urlopen(blueprint_url):
94         end = False
95         if not found_workitems:
96             if work_items_re.search(l):
97                 found_workitems = True
98             continue
99
100         if '</p>' in l:
101             end = True
102         l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
103
104         # ends with empty line
105         if end or not l:
106             break
107
108         try:
109             (desc, state) = l.rsplit(':', 1)
110         except ValueError:
111             print >> sys.stderr, 'ERROR: invalid work item format: ' + l
112             continue
113         desc = desc.strip()
114         state = state.strip().lower()
115         if not state:
116             state = 'todo'
117         if state == 'completed':
118             state = 'done'
119         if state == 'inprogress':
120             state = 'todo'
121         if state not in valid_states:
122             print >> sys.stderr, 'ERROR: invalid state "%s" for work item "%s"' % (
123                 state, desc)
124             continue
125         result.append((desc, state))
126
127     return result
128
129 def get_moin_workitems(url):
130     '''Collect work items from a moin wiki URL.
131
132     Every line starting with "|| " is treated as a work item.
133
134     Return a list of ('item', 'status') pairs.
135     '''
136     result = []
137     for line in urllib.urlopen(url):
138         if line.startswith('|| '):
139             fields = line.strip().split('||')
140             assert not fields[0] # should be empty
141             desc = fields[1].strip()
142             for f in fields[2:]:
143                 if 'DONE' in f:
144                     result.append((desc, 'done'))
145                     break
146                 elif 'POSTPONED' in f:
147                     result.append((desc, 'done'))
148                     break
149             else:
150                 result.append((desc, 'todo'))
151
152     return result
153
154 def dump(db):
155     '''Dump database contents.'''
156
157     cur = db.cursor()
158     cur.execute('SELECT * FROM work_items')
159     for (blueprint, workitem, status, date) in cur:
160         print '%s [%s]\t%s: %s' % (date, blueprint, workitem, status)
161
162 def add_work_item(db, blueprint, item, status):
163     '''Add work item to database.'''
164
165     cur = db.cursor()
166     cur.execute('INSERT INTO work_items VALUES (?, ?, ?, date(CURRENT_TIMESTAMP))',
167             (blueprint, item, status))
168
169 def import_lp(db, name_pattern, release):
170     '''Collect blueprint work items from Launchpad into DB.'''
171
172     blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
173         opts.release), name_pattern)
174
175     cur = db.cursor()
176     cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
177
178     for bp in blueprints:
179         #print 'Checking', bp
180         bpname = bp.split('/')[-1]
181         work_items = get_blueprint_workitems(bp)
182         if not work_items:
183             print >> sys.stderr, 'WARNING: %s has no work items' % bpname
184         for (item, status) in work_items:
185             add_work_item(db, bpname, item, status)
186
187 def workitems_over_time(db):
188     '''Calculate work item development over time.
189
190     Return date -> state -> count mapping.
191     '''
192     data = {}
193     for s in valid_states:
194         cur = db.cursor()
195         cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
196                 (s,))
197         for (date, num) in cur:
198             data.setdefault(date, {})[s] = num
199     return data
200
201 def blueprint_status(db):
202     '''Determine current blueprint status.
203
204     Return blueprint -> [todo, done, postponed] mapping.
205     '''
206     data = {}
207
208     # last date
209     cur = db.cursor()
210     cur.execute('SELECT max(date) FROM work_items')
211     (last_date,) = cur.fetchone()
212
213     index = 0
214     for s in valid_states:
215         cur = db.cursor()
216         cur.execute('SELECT blueprint, count(workitem) FROM work_items '
217                 'WHERE status = ? AND date = ? GROUP BY blueprint', 
218                 (s, last_date))
219         for (bp, num) in cur:
220             data.setdefault(bp, [0, 0, 0])[index] = num
221         index += 1
222
223     return data
224
225 def text(db):
226     '''Print work item status as text.'''
227
228     data = workitems_over_time(db)
229
230     print 'History:'
231     for d in sorted(data.keys()):
232         print d, data[d]
233
234     print '\nBlueprint status:'
235     data = blueprint_status(db)
236     for (bp, (todo, done, postponed)) in data.iteritems():
237         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
238                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
239
240 def csv(db, from_date, to_date):
241     '''Print work item status as csv.'''
242
243     def _fmtdate(d):
244         '''Convert datetime.date into MM/DD/YYYY'''
245
246         return '%s/%s/%s' % (d.month, d.day, d.year)
247
248     def _fromstr(s):
249         '''Convert YYYY-MM-DD string to datetime.date'''
250
251         (y, m, d) = s.split('-')
252         return datetime.date(int(y), int(m), int(d))
253
254     data = workitems_over_time(db)
255
256     dates = sorted(data.keys())
257
258     f = _fromstr(from_date or dates[0])
259     t = _fromstr(to_date or dates[-1])
260
261     d = f
262     while d <= t:
263         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
264         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
265                 entry.get('todo', 0), entry.get('done', 0),
266                 entry.get('postponed', 0))
267         d += datetime.timedelta(days=1)
268
269 def html(db):
270     '''Print work item status as HTML.'''
271
272     print '''<html>
273 <head>
274   <title>Work item status</title>
275   <style type="text/css">
276     body { background: #CCCCB0; color: black; }
277     a { text-decoration: none; }
278     table { border-collapse: collapse; border-style: solid none; 
279             border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
280     table th { text-align: left; border-style: none none solid none; 
281                border-width: 3px; padding-right: 10px; }
282     table td { text-align: left; border-style: none none dotted none; 
283                border-width: 1px; padding-right: 10px; }
284
285     a { color: blue; }
286   </style>
287 </head>
288
289 <body>
290
291 <h1>History</h1>
292 <p><img src="burndown.png" alt="burndown" /></p>
293
294 <h1>Status by blueprint</h1>
295 <table>
296   <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th></tr>
297 '''
298
299     data = blueprint_status(db)
300
301     completion = []
302     for (bp, (todo, done, postponed)) in data.iteritems():
303         completion.append((bp,
304             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
305
306     completion.sort(key=lambda k: k[1], reverse=True)
307
308     for (bp, percent) in completion:
309         print '  <tr><td><a href="%s/ubuntu/+spec/%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td></tr>' % (
310                 blueprints_base_url, bp, bp, data[bp][0], data[bp][2],
311                 data[bp][1], percent)
312
313     print '</table>'
314
315     print '</body></html>'
316
317 def import_moin(db, urls):
318     '''Collect blueprint work items from a moin wiki.'''
319
320     for url in urls:
321         for (d, s) in get_moin_workitems(url):
322             add_work_item(db, url, d, s)
323
324 #
325 # main
326 #
327
328 (opts, args) = parse_argv()
329
330 db = get_db(opts.database)
331
332 if opts.dump:
333     dump(db)
334 elif opts.text:
335     text(db)
336 elif opts.html:
337     html(db)
338 elif opts.csv:
339     csv(db, opts.from_date, opts.to_date)
340 else:
341     import_lp(db, opts.pattern, opts.release)
342     import_moin(db, opts.moin)
343     db.commit()
344