]> piware.de Git - bin.git/blob - workitems.py
workitems: fix crash on empty list
[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 status (
27             blueprint VARCHAR(255) NOT NULL,
28             status VARCHAR(1000) 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', 'status') 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', 'status') 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 * FROM work_items')
197     print '== Work items: =='
198     for (blueprint, workitem, item_status, date) in cur:
199         print '%s [%s]\t%s: %s' % (date, blueprint, workitem, item_status)
200
201     print '\n== Status =='
202     cur = db.cursor()
203     cur.execute('SELECT * FROM status')
204     for (blueprint, status, date) in cur:
205         print '%s: %s [%s]' % (blueprint, status, date)
206
207 def add_work_item(db, blueprint, item, status):
208     '''Add work item to database.'''
209
210     cur = db.cursor()
211     cur.execute('INSERT INTO work_items VALUES (?, ?, ?, date(CURRENT_TIMESTAMP))',
212             (blueprint, item, status))
213
214 def add_status(db, blueprint, status):
215     '''Add blueprint status to database.'''
216
217     if not status:
218         return
219
220     cur = db.cursor()
221     cur.execute('INSERT INTO status VALUES (?, ?, date(CURRENT_TIMESTAMP))',
222             (blueprint, status))
223
224 def import_lp(db, name_pattern, release):
225     '''Collect blueprint work items and status from Launchpad into DB.'''
226
227     blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
228         opts.release), name_pattern)
229
230     cur = db.cursor()
231     cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
232     cur.execute('DELETE FROM status WHERE date = date(CURRENT_TIMESTAMP)')
233
234     for bp in blueprints:
235         #print 'Checking', bp
236         bpname = bp.split('/')[-1]
237         work_items = get_blueprint_workitems(bp)
238         status = get_blueprint_status(bp)
239         if not work_items:
240             print >> sys.stderr, 'WARNING: %s has no work items' % bpname
241         for (item, state) in work_items:
242             add_work_item(db, bpname, item, state)
243         add_status(db, bpname, status)
244
245 def workitems_over_time(db):
246     '''Calculate work item development over time.
247
248     Return date -> state -> count mapping.
249     '''
250     data = {}
251     for s in valid_states:
252         cur = db.cursor()
253         cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
254                 (s,))
255         for (date, num) in cur:
256             data.setdefault(date, {})[s] = num
257     return data
258
259 def blueprint_completion(db):
260     '''Determine current blueprint completion.
261
262     Return blueprint -> [todo, done, postponed, status] mapping.
263     '''
264     data = {}
265
266     # last date
267     cur = db.cursor()
268     cur.execute('SELECT max(date) FROM work_items')
269     (last_date,) = cur.fetchone()
270
271     index = 0
272     for s in valid_states:
273         cur = db.cursor()
274         cur.execute('SELECT w.blueprint, count(w.workitem), s.status FROM work_items w '
275                 'LEFT JOIN status s ON w.blueprint = s.blueprint '
276                 'WHERE w.status = ? AND w.date = ? GROUP BY w.blueprint',
277                 (s, last_date))
278         for (bp, num, status) in cur:
279             data.setdefault(bp, [0, 0, 0, ''])[index] = num
280             data[bp][-1] = status or ''
281         index += 1
282
283     return data
284
285 def text(db):
286     '''Print work item completion as text.'''
287
288     data = workitems_over_time(db)
289
290     print 'History:'
291     for d in sorted(data.keys()):
292         print d, data[d]
293
294     print '\nBlueprint completion:'
295     data = blueprint_completion(db)
296     for (bp, (todo, done, postponed, status)) in data.iteritems():
297         # TODO print status
298         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
299                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
300
301 def csv(db, from_date, to_date):
302     '''Print work item status as csv.'''
303
304     def _fmtdate(d):
305         '''Convert datetime.date into MM/DD/YYYY'''
306
307         return '%s/%s/%s' % (d.month, d.day, d.year)
308
309     def _fromstr(s):
310         '''Convert YYYY-MM-DD string to datetime.date'''
311
312         (y, m, d) = s.split('-')
313         return datetime.date(int(y), int(m), int(d))
314
315     data = workitems_over_time(db)
316
317     dates = sorted(data.keys())
318     if not dates:
319         return
320
321     f = _fromstr(from_date or dates[0])
322     t = _fromstr(to_date or dates[-1])
323
324     d = f
325     while d <= t:
326         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
327         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
328                 entry.get('todo', 0), entry.get('done', 0),
329                 entry.get('postponed', 0))
330         d += datetime.timedelta(days=1)
331
332 def html(db):
333     '''Print work item status as HTML.'''
334
335     print '''<html>
336 <head>
337   <title>Work item status</title>
338   <style type="text/css">
339     body { background: #CCCCB0; color: black; }
340     a { text-decoration: none; }
341     table { border-collapse: collapse; border-style: solid none; 
342             border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
343     table th { text-align: left; border-style: none none solid none; 
344                border-width: 3px; padding-right: 10px; }
345     table td { text-align: left; border-style: none none dotted none; 
346                border-width: 1px; padding-right: 10px; }
347
348     a { color: blue; }
349   </style>
350 </head>
351
352 <body>
353
354 <h1>History</h1>
355 <p><img src="burndown.png" alt="burndown" /></p>
356
357 <h1>Status by blueprint</h1>
358 <table>
359   <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th> <th>Status</th></tr>
360 '''
361
362     data = blueprint_completion(db)
363
364     completion = []
365     for (bp, (todo, done, postponed, status)) in data.iteritems():
366         completion.append((bp,
367             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
368
369     completion.sort(key=lambda k: k[1], reverse=True)
370
371     for (bp, percent) in completion:
372         print '  <tr><td><a href="%s/ubuntu/+spec/%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td> <td>%s</td></tr>' % (
373                 blueprints_base_url, bp, bp, data[bp][0], data[bp][2],
374                 data[bp][1], percent,
375                 data[bp][-1])
376
377     print '</table>'
378
379     print '</body></html>'
380
381 def import_moin(db, urls):
382     '''Collect blueprint work items from a moin wiki.'''
383
384     for url in urls:
385         for (d, s) in get_moin_workitems(url):
386             add_work_item(db, url, d, s)
387
388 #
389 # main
390 #
391
392 (opts, args) = parse_argv()
393
394 db = get_db(opts.database)
395
396 if opts.dump:
397     dump(db)
398 elif opts.text:
399     text(db)
400 elif opts.html:
401     html(db)
402 elif opts.csv:
403     csv(db, opts.from_date, opts.to_date)
404 else:
405     import_lp(db, opts.pattern, opts.release)
406     import_moin(db, opts.moin)
407     db.commit()
408