]> piware.de Git - bin.git/blob - workitems.py
workitems: add tracking of assignee (DB schema change)
[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 text(db):
312     '''Print work item completion as text.'''
313
314     data = workitems_over_time(db)
315
316     print 'History:'
317     for d in sorted(data.keys()):
318         print d, data[d]
319
320     print '\nBlueprint completion:'
321     data = blueprint_completion(db)
322     for (bp, (todo, done, postponed, status)) in data.iteritems():
323         # TODO print status
324         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
325                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
326
327 def csv(db, from_date, to_date):
328     '''Print work item status as csv.'''
329
330     def _fmtdate(d):
331         '''Convert datetime.date into MM/DD/YYYY'''
332
333         return '%s/%s/%s' % (d.month, d.day, d.year)
334
335     def _fromstr(s):
336         '''Convert YYYY-MM-DD string to datetime.date'''
337
338         (y, m, d) = s.split('-')
339         return datetime.date(int(y), int(m), int(d))
340
341     data = workitems_over_time(db)
342
343     dates = sorted(data.keys())
344     if not dates:
345         return
346
347     f = _fromstr(from_date or dates[0])
348     t = _fromstr(to_date or dates[-1])
349
350     d = f
351     while d <= t:
352         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
353         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
354                 entry.get('todo', 0), entry.get('done', 0),
355                 entry.get('postponed', 0))
356         d += datetime.timedelta(days=1)
357
358 def html(db):
359     '''Print work item status as HTML.'''
360
361     print '''<html>
362 <head>
363   <title>Work item status</title>
364   <style type="text/css">
365     body { background: #CCCCB0; color: black; }
366     a { text-decoration: none; }
367     table { border-collapse: collapse; border-style: solid none; 
368             border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
369     table th { text-align: left; border-style: none none solid none; 
370                border-width: 3px; padding-right: 10px; }
371     table td { text-align: left; border-style: none none dotted none; 
372                border-width: 1px; padding-right: 10px; }
373
374     a { color: blue; }
375   </style>
376 </head>
377
378 <body>
379
380 <h1>History</h1>
381 <p><img src="burndown.png" alt="burndown" /></p>
382
383 <h1>Status by blueprint</h1>
384 <table>
385   <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th> <th>Status</th></tr>
386 '''
387
388     data = blueprint_completion(db)
389
390     completion = []
391     for (bp, (todo, done, postponed, status)) in data.iteritems():
392         completion.append((bp,
393             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
394
395     completion.sort(key=lambda k: k[1], reverse=True)
396
397     for (bp, percent) in completion:
398         if bp.startswith('http:'):
399             url = bp
400         else:
401             url = '%s/ubuntu/+spec/%s' % (blueprints_base_url, bp)
402         print '  <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td> <td>%s</td></tr>' % (
403                 url, bp, data[bp][0], data[bp][2],
404                 data[bp][1], percent,
405                 data[bp][-1])
406
407     print '</table>'
408
409     print '</body></html>'
410
411 def import_moin(db, urls):
412     '''Collect blueprint work items from a moin wiki.'''
413
414     for url in urls:
415         for (d, s) in get_moin_workitems(url):
416             add_work_item(db, url, d, s, 'nobody')
417
418 #
419 # main
420 #
421
422 (opts, args) = parse_argv()
423
424 db = get_db(opts.database)
425
426 if opts.dump:
427     dump(db)
428 elif opts.text:
429     text(db)
430 elif opts.html:
431     html(db)
432 elif opts.csv:
433     csv(db, opts.from_date, opts.to_date)
434 else:
435     import_lp(db, opts.pattern, opts.release)
436     import_moin(db, opts.moin)
437     db.commit()
438