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