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