]> piware.de Git - bin.git/blob - workitems.py
workitems: HTML-escape text fields
[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') pairs.
217     '''
218     result = []
219     for line in urllib.urlopen(url):
220         if line.startswith('|| '):
221             fields = line.strip().split('||')
222             assert not fields[0] # should be empty
223             desc = fields[1].strip()
224             for f in fields[2:]:
225                 if 'DONE' in f:
226                     result.append((desc, 'done'))
227                     break
228                 elif 'POSTPONED' in f:
229                     result.append((desc, 'done'))
230                     break
231             else:
232                 result.append((desc, 'todo'))
233
234     return result
235
236 def dump(db):
237     '''Dump database contents.'''
238
239     cur = db.cursor()
240     cur.execute('SELECT * FROM work_items')
241     print '== Work items: =='
242     for (blueprint, workitem, item_status, assignee, date) in cur:
243         print '%s [%s, %s]\t%s: %s' % (date, blueprint, assignee, workitem, item_status)
244
245     print '\n== Status =='
246     cur = db.cursor()
247     cur.execute('SELECT * FROM status')
248     for (blueprint, status, date) in cur:
249         print '%s: %s [%s]' % (blueprint, status, date)
250
251 def add_work_item(db, blueprint, item, status, assignee):
252     '''Add work item to database.'''
253
254     cur = db.cursor()
255     cur.execute('INSERT INTO work_items VALUES (?, ?, ?, ?, date(CURRENT_TIMESTAMP))',
256             (blueprint, item, status, assignee))
257
258 def add_status(db, blueprint, status):
259     '''Add blueprint status to database.'''
260
261     if not status:
262         return
263
264     cur = db.cursor()
265     cur.execute('INSERT INTO status VALUES (?, ?, date(CURRENT_TIMESTAMP))',
266             (blueprint, status))
267
268 def import_lp(db, name_pattern, release, milestone):
269     '''Collect blueprint work items and status from Launchpad into DB.'''
270
271     blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
272         release), name_pattern, milestone)
273
274     cur = db.cursor()
275     cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
276     cur.execute('DELETE FROM status WHERE date = date(CURRENT_TIMESTAMP)')
277
278     for bp in blueprints:
279         #print 'Checking', bp
280         bpname = bp.split('/')[-1]
281         work_items = get_blueprint_workitems(bp)
282         status = get_blueprint_status(bp)
283         if not work_items:
284             print >> sys.stderr, 'WARNING: %s has no work items' % bpname
285         for (item, state, assignee) in work_items:
286             add_work_item(db, bpname, item, state, assignee)
287         add_status(db, bpname, status)
288
289 def workitems_over_time(db):
290     '''Calculate work item development over time.
291
292     Return date -> state -> count mapping.
293     '''
294     data = {}
295     for s in valid_states:
296         cur = db.cursor()
297         cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
298                 (s,))
299         for (date, num) in cur:
300             data.setdefault(date, {})[s] = num
301     return data
302
303 def blueprint_completion(db):
304     '''Determine current blueprint completion.
305
306     Return blueprint -> [todo, done, postponed, status] mapping.
307     '''
308     data = {}
309
310     # last date
311     cur = db.cursor()
312     cur.execute('SELECT max(date) FROM work_items')
313     (last_date,) = cur.fetchone()
314
315     index = 0
316     for s in valid_states:
317         cur = db.cursor()
318         cur.execute('SELECT w.blueprint, count(w.workitem), s.status FROM work_items w '
319                 'LEFT JOIN status s ON w.blueprint = s.blueprint '
320                 'WHERE w.status = ? AND w.date = ? GROUP BY w.blueprint',
321                 (s, last_date))
322         for (bp, num, status) in cur:
323             data.setdefault(bp, [0, 0, 0, ''])[index] = num
324             data[bp][-1] = status or ''
325         index += 1
326
327     return data
328
329 def assignee_completion(db):
330     '''Determine current by-assignee completion.
331
332     Return assignee -> [todo, done, postponed] mapping.
333     '''
334     data = {}
335
336     # last date
337     cur = db.cursor()
338     cur.execute('SELECT max(date) FROM work_items')
339     (last_date,) = cur.fetchone()
340
341     index = 0
342     for s in valid_states:
343         cur = db.cursor()
344         cur.execute('SELECT assignee, count(workitem) FROM work_items '
345                 'WHERE date=? and status=? GROUP BY assignee',
346                 (last_date, s))
347         for (a, num) in cur:
348             data.setdefault(a, [0, 0, 0])[index] = num
349         index += 1
350
351     return data
352
353 def text(db):
354     '''Print work item completion as text.'''
355
356     data = workitems_over_time(db)
357
358     print 'History:'
359     for d in sorted(data.keys()):
360         print d, data[d]
361
362     print '\nBlueprint completion:'
363     data = blueprint_completion(db)
364     for (bp, (todo, done, postponed, status)) in data.iteritems():
365         # TODO print status
366         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
367                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
368
369 def csv(db, from_date, to_date):
370     '''Print work item status as csv.'''
371
372     def _fmtdate(d):
373         '''Convert datetime.date into MM/DD/YYYY'''
374
375         return '%s/%s/%s' % (d.month, d.day, d.year)
376
377     def _fromstr(s):
378         '''Convert YYYY-MM-DD string to datetime.date'''
379
380         (y, m, d) = s.split('-')
381         return datetime.date(int(y), int(m), int(d))
382
383     data = workitems_over_time(db)
384
385     dates = sorted(data.keys())
386     if not dates:
387         return
388
389     f = _fromstr(from_date or dates[0])
390     t = _fromstr(to_date or dates[-1])
391
392     d = f
393     while d <= t:
394         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
395         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
396                 entry.get('todo', 0), entry.get('done', 0),
397                 entry.get('postponed', 0))
398         d += datetime.timedelta(days=1)
399
400 def html(db):
401     '''Print work item status as HTML.'''
402
403     print '''<html>
404 <head>
405   <title>Work item status</title>
406   <style type="text/css">
407     body { background: #CCCCB0; color: black; }
408     a { text-decoration: none; }
409     table { border-collapse: collapse; border-style: solid none; 
410             border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
411     table th { text-align: left; border-style: none none solid none; 
412                border-width: 3px; padding-right: 10px; }
413     table td { text-align: left; border-style: none none dotted none; 
414                border-width: 1px; padding-right: 10px; }
415
416     a { color: blue; }
417   </style>
418 </head>
419
420 <body>
421
422 <h1>History</h1>
423 <p><img src="burndown.png" alt="burndown" /></p>
424
425 <h1>Status by blueprint</h1>
426 <table>
427   <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th> <th>Status</th></tr>
428 '''
429
430     data = blueprint_completion(db)
431
432     completion = []
433     for (bp, (todo, done, postponed, status)) in data.iteritems():
434         completion.append((bp,
435             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
436
437     completion.sort(key=lambda k: k[1], reverse=True)
438
439     for (bp, percent) in completion:
440         if bp.startswith('http:'):
441             url = bp
442         else:
443             url = '%s/ubuntu/+spec/%s' % (blueprints_base_url, escape(bp))
444         print '  <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td> <td>%s</td></tr>' % (
445                 url, escape(bp), data[bp][0], data[bp][2],
446                 data[bp][1], percent,
447                 escape(data[bp][-1]))
448
449     print '</table>'
450
451     print '''
452 <h1>Status by assignee</h1>
453 <table>
454   <tr><th>Assignee</th> <th>todo/postponed/done</th> <th>Completion</th></tr>
455 '''
456     data = assignee_completion(db)
457
458     completion = []
459     for (a, (todo, done, postponed)) in data.iteritems():
460         completion.append((a,
461             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
462
463     completion.sort(key=lambda k: k[0], reverse=False)
464
465     for (a, percent) in completion:
466         url = '%s/~%s/+specs?role=assignee' % (blueprints_base_url, a)
467         print '  <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td></tr>' % (
468                 url, escape(a), data[a][0], data[a][2],
469                 data[a][1], percent)
470     print '</table>'
471
472     print '</body></html>'
473
474 def import_moin(db, urls):
475     '''Collect blueprint work items from a moin wiki.'''
476
477     for url in urls:
478         for (d, s) in get_moin_workitems(url):
479             add_work_item(db, url, d, s, 'nobody')
480
481 #
482 # main
483 #
484
485 (opts, args) = parse_argv()
486
487 db = get_db(opts.database)
488
489 if opts.dump:
490     dump(db)
491 elif opts.text:
492     text(db)
493 elif opts.html:
494     html(db)
495 elif opts.csv:
496     csv(db, opts.from_date, opts.to_date)
497 else:
498     import_lp(db, opts.pattern, opts.release, opts.milestone)
499     import_moin(db, opts.moin)
500     db.commit()
501