]> piware.de Git - bin.git/blob - workitems.py
workitems: add by-assignee report to HTML output
[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(1000) NOT NULL,
24             status VARCHAR(20) NOT NULL,
25             assignee VARCHAR(200) NOT NULL,
26             date TIMESTAMP NOT NULL)''')
27         cur.execute('''CREATE TABLE status (
28             blueprint VARCHAR(255) NOT NULL,
29             status VARCHAR(1000) NOT NULL,
30             date TIMESTAMP NOT NULL)''')
31         db.commit()
32
33     return db
34
35 def parse_argv():
36     '''Parse CLI arguments.
37
38     Return (options, args) tuple.
39     '''
40     optparser = optparse.OptionParser()
41     optparser.add_option('-d', '--database',
42         help='Path to database', dest='database', metavar='PATH')
43     optparser.add_option('-r', '--release',
44         help='Release name', dest='release')
45     optparser.add_option('-p', '--pattern', metavar='REGEX',
46         help='Regex pattern for blueprint name', dest='pattern')
47     optparser.add_option('-D', '--dump', action='store_true', default=False,
48         help='Dump database', dest='dump')
49     optparser.add_option('-m', '--moin', metavar='URL',
50         help='moin URL for additional work items (can be given multiple times)', 
51         action='append', dest='moin', default=[])
52     optparser.add_option('-t', '--text', action='store_true', default=False,
53         help='Print work item summary in text format', dest='text')
54     optparser.add_option('-c', '--csv', action='store_true', default=False,
55         help='Print work item summary in CSV format', dest='csv')
56     optparser.add_option('-H', '--html', action='store_true', default=False,
57         help='Generate work item HTML report', dest='html')
58     optparser.add_option('--from', metavar='YYYY-MM-DD',
59         help='Generate CSV data from this day on', dest='from_date')
60     optparser.add_option('--to', metavar='YYYY-MM-DD',
61         help='Generate CSV data until this day', dest='to_date')
62
63     (opts, args) = optparser.parse_args()
64
65     if not opts.database:
66         optparser.error('No database given')
67     if not opts.dump and not opts.text and not opts.csv and not opts.html:
68         if not opts.release:
69             optparser.error('No release given')
70         if not opts.pattern:
71             optparser.error('No pattern given')
72
73     return (opts, args)
74
75 def get_blueprints(url, name_pattern):
76     '''Return a list of blueprint URLs for the current release.'''
77
78     blueprint_name_filter = re.compile('href="(/ubuntu/\+spec/%s[^"]+)"' %
79             name_pattern)
80
81     result = []
82     for l in urllib.urlopen(url):
83         m = blueprint_name_filter.search(l)
84         if m:
85             result.append(blueprints_base_url + m.group(1))
86
87     return result
88
89 def get_blueprint_workitems(blueprint_url):
90     '''Collect work items from a particular blueprint URL.
91
92     This will return a list of ('item', 'status', 'assignee') tuples.
93     '''
94     work_items_re = re.compile('(<p>|^)work items:\s*<br />', re.I)
95     assignee_re = re.compile('<a href="https://.*launchpad.net/~([a-zA-Z0-9_-]+)" class=".*person">')
96
97     found_workitems = False
98     found_assignee = False
99     result = []
100     default_assignee = 'nobody'
101     for l in urllib.urlopen(blueprint_url):
102         end = False
103
104         if '<dt>Assignee:' in l:
105             found_assignee = True
106             continue
107
108         if found_assignee and not found_workitems:
109             m = assignee_re.search(l)
110             if m:
111                 default_assignee = m.group(1)
112                 found_assignee = False
113
114         if not found_workitems:
115             if work_items_re.search(l):
116                 found_workitems = True
117             continue
118
119         if '</p>' in l:
120             end = True
121         l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
122
123         if not l:
124             break
125
126         try:
127             (desc, state) = l.rsplit(':', 1)
128         except ValueError:
129             print >> sys.stderr, 'ERROR: invalid work item format: ' + l
130             continue
131         desc = desc.strip()
132         state = state.strip().lower()
133         if not state:
134             state = 'todo'
135         if state == 'completed':
136             state = 'done'
137         if state == 'inprogress':
138             state = 'todo'
139         if state == 'postpone':
140             state = 'postponed'
141         if state not in valid_states:
142             print >> sys.stderr, 'ERROR: invalid state "%s" for work item "%s"' % (
143                 state, desc)
144             continue
145
146         if desc.startswith('['):
147             try:
148                 off = desc.index(']')
149                 assignee = desc[1:off]
150                 desc = desc[off+1:].strip()
151             except ValueError:
152                 print >> sys.stderr, 'ERROR: missing closing "]" for assignee for work item "%s"' % desc
153         else:
154             assignee = default_assignee
155
156         result.append((desc, state, assignee))
157
158         if end:
159             break
160
161     return result
162
163 def get_blueprint_status(blueprint_url):
164     '''Collect status from a particular blueprint URL.
165
166     This will return a list of lines.
167     '''
168     status_re = re.compile('(<p>|^)status:\s*<br />', re.I)
169
170     found_status = False
171     result = []
172     for l in urllib.urlopen(blueprint_url):
173         end = False
174         if not found_status:
175             if status_re.search(l):
176                 found_status = True
177             continue
178
179         if '</p>' in l:
180             end = True
181         l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
182
183         if not l:
184             break
185
186         result.append(l.strip())
187
188         if end:
189             break
190
191     return "\n".join(result)
192
193 def get_moin_workitems(url):
194     '''Collect work items from a moin wiki URL.
195
196     Every line starting with "|| " is treated as a work item.
197
198     Return a list of ('item', 'status') pairs.
199     '''
200     result = []
201     for line in urllib.urlopen(url):
202         if line.startswith('|| '):
203             fields = line.strip().split('||')
204             assert not fields[0] # should be empty
205             desc = fields[1].strip()
206             for f in fields[2:]:
207                 if 'DONE' in f:
208                     result.append((desc, 'done'))
209                     break
210                 elif 'POSTPONED' in f:
211                     result.append((desc, 'done'))
212                     break
213             else:
214                 result.append((desc, 'todo'))
215
216     return result
217
218 def dump(db):
219     '''Dump database contents.'''
220
221     cur = db.cursor()
222     cur.execute('SELECT * FROM work_items')
223     print '== Work items: =='
224     for (blueprint, workitem, item_status, assignee, date) in cur:
225         print '%s [%s, %s]\t%s: %s' % (date, blueprint, assignee, workitem, item_status)
226
227     print '\n== Status =='
228     cur = db.cursor()
229     cur.execute('SELECT * FROM status')
230     for (blueprint, status, date) in cur:
231         print '%s: %s [%s]' % (blueprint, status, date)
232
233 def add_work_item(db, blueprint, item, status, assignee):
234     '''Add work item to database.'''
235
236     cur = db.cursor()
237     cur.execute('INSERT INTO work_items VALUES (?, ?, ?, ?, date(CURRENT_TIMESTAMP))',
238             (blueprint, item, status, assignee))
239
240 def add_status(db, blueprint, status):
241     '''Add blueprint status to database.'''
242
243     if not status:
244         return
245
246     cur = db.cursor()
247     cur.execute('INSERT INTO status VALUES (?, ?, date(CURRENT_TIMESTAMP))',
248             (blueprint, status))
249
250 def import_lp(db, name_pattern, release):
251     '''Collect blueprint work items and status from Launchpad into DB.'''
252
253     blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
254         opts.release), name_pattern)
255
256     cur = db.cursor()
257     cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
258     cur.execute('DELETE FROM status WHERE date = date(CURRENT_TIMESTAMP)')
259
260     for bp in blueprints:
261         #print 'Checking', bp
262         bpname = bp.split('/')[-1]
263         work_items = get_blueprint_workitems(bp)
264         status = get_blueprint_status(bp)
265         if not work_items:
266             print >> sys.stderr, 'WARNING: %s has no work items' % bpname
267         for (item, state, assignee) in work_items:
268             add_work_item(db, bpname, item, state, assignee)
269         add_status(db, bpname, status)
270
271 def workitems_over_time(db):
272     '''Calculate work item development over time.
273
274     Return date -> state -> count mapping.
275     '''
276     data = {}
277     for s in valid_states:
278         cur = db.cursor()
279         cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
280                 (s,))
281         for (date, num) in cur:
282             data.setdefault(date, {})[s] = num
283     return data
284
285 def blueprint_completion(db):
286     '''Determine current blueprint completion.
287
288     Return blueprint -> [todo, done, postponed, status] mapping.
289     '''
290     data = {}
291
292     # last date
293     cur = db.cursor()
294     cur.execute('SELECT max(date) FROM work_items')
295     (last_date,) = cur.fetchone()
296
297     index = 0
298     for s in valid_states:
299         cur = db.cursor()
300         cur.execute('SELECT w.blueprint, count(w.workitem), s.status FROM work_items w '
301                 'LEFT JOIN status s ON w.blueprint = s.blueprint '
302                 'WHERE w.status = ? AND w.date = ? GROUP BY w.blueprint',
303                 (s, last_date))
304         for (bp, num, status) in cur:
305             data.setdefault(bp, [0, 0, 0, ''])[index] = num
306             data[bp][-1] = status or ''
307         index += 1
308
309     return data
310
311 def assignee_completion(db):
312     '''Determine current by-assignee completion.
313
314     Return assignee -> [todo, done, postponed] mapping.
315     '''
316     data = {}
317
318     # last date
319     cur = db.cursor()
320     cur.execute('SELECT max(date) FROM work_items')
321     (last_date,) = cur.fetchone()
322
323     index = 0
324     for s in valid_states:
325         cur = db.cursor()
326         cur.execute('SELECT assignee, count(workitem) FROM work_items '
327                 'WHERE date=? and status=? GROUP BY assignee',
328                 (last_date, s))
329         for (a, num) in cur:
330             data.setdefault(a, [0, 0, 0])[index] = num
331         index += 1
332
333     return data
334
335 def text(db):
336     '''Print work item completion as text.'''
337
338     data = workitems_over_time(db)
339
340     print 'History:'
341     for d in sorted(data.keys()):
342         print d, data[d]
343
344     print '\nBlueprint completion:'
345     data = blueprint_completion(db)
346     for (bp, (todo, done, postponed, status)) in data.iteritems():
347         # TODO print status
348         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
349                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
350
351 def csv(db, from_date, to_date):
352     '''Print work item status as csv.'''
353
354     def _fmtdate(d):
355         '''Convert datetime.date into MM/DD/YYYY'''
356
357         return '%s/%s/%s' % (d.month, d.day, d.year)
358
359     def _fromstr(s):
360         '''Convert YYYY-MM-DD string to datetime.date'''
361
362         (y, m, d) = s.split('-')
363         return datetime.date(int(y), int(m), int(d))
364
365     data = workitems_over_time(db)
366
367     dates = sorted(data.keys())
368     if not dates:
369         return
370
371     f = _fromstr(from_date or dates[0])
372     t = _fromstr(to_date or dates[-1])
373
374     d = f
375     while d <= t:
376         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
377         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
378                 entry.get('todo', 0), entry.get('done', 0),
379                 entry.get('postponed', 0))
380         d += datetime.timedelta(days=1)
381
382 def html(db):
383     '''Print work item status as HTML.'''
384
385     print '''<html>
386 <head>
387   <title>Work item status</title>
388   <style type="text/css">
389     body { background: #CCCCB0; color: black; }
390     a { text-decoration: none; }
391     table { border-collapse: collapse; border-style: solid none; 
392             border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
393     table th { text-align: left; border-style: none none solid none; 
394                border-width: 3px; padding-right: 10px; }
395     table td { text-align: left; border-style: none none dotted none; 
396                border-width: 1px; padding-right: 10px; }
397
398     a { color: blue; }
399   </style>
400 </head>
401
402 <body>
403
404 <h1>History</h1>
405 <p><img src="burndown.png" alt="burndown" /></p>
406
407 <h1>Status by blueprint</h1>
408 <table>
409   <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th> <th>Status</th></tr>
410 '''
411
412     data = blueprint_completion(db)
413
414     completion = []
415     for (bp, (todo, done, postponed, status)) in data.iteritems():
416         completion.append((bp,
417             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
418
419     completion.sort(key=lambda k: k[1], reverse=True)
420
421     for (bp, percent) in completion:
422         if bp.startswith('http:'):
423             url = bp
424         else:
425             url = '%s/ubuntu/+spec/%s' % (blueprints_base_url, bp)
426         print '  <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td> <td>%s</td></tr>' % (
427                 url, bp, data[bp][0], data[bp][2],
428                 data[bp][1], percent,
429                 data[bp][-1])
430
431     print '</table>'
432
433     print '''
434 <h1>Status by assignee</h1>
435 <table>
436   <tr><th>Assignee</th> <th>todo/postponed/done</th> <th>Completion</th></tr>
437 '''
438     data = assignee_completion(db)
439
440     completion = []
441     for (a, (todo, done, postponed)) in data.iteritems():
442         completion.append((a,
443             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
444
445     completion.sort(key=lambda k: k[0], reverse=False)
446
447     for (a, percent) in completion:
448         url = '%s/~%s/+specs?role=assignee' % (blueprints_base_url, a)
449         print '  <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td></tr>' % (
450                 url, a, data[a][0], data[a][2],
451                 data[a][1], percent)
452     print '</table>'
453
454     print '</body></html>'
455
456 def import_moin(db, urls):
457     '''Collect blueprint work items from a moin wiki.'''
458
459     for url in urls:
460         for (d, s) in get_moin_workitems(url):
461             add_work_item(db, url, d, s, 'nobody')
462
463 #
464 # main
465 #
466
467 (opts, args) = parse_argv()
468
469 db = get_db(opts.database)
470
471 if opts.dump:
472     dump(db)
473 elif opts.text:
474     text(db)
475 elif opts.html:
476     html(db)
477 elif opts.csv:
478     csv(db, opts.from_date, opts.to_date)
479 else:
480     import_lp(db, opts.pattern, opts.release)
481     import_moin(db, opts.moin)
482     db.commit()
483