3 import urllib, re, sys, optparse, os.path, datetime
4 import sqlite3 as dbapi2
6 blueprints_base_url = 'https://blueprints.launchpad.net'
8 valid_states = ['todo', 'done', 'postponed']
11 '''Open/initialize database.
13 This creates the database if it does not exist.
15 init = not os.path.exists(dbpath)
17 db = dbapi2.connect(dbpath)
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)''')
36 '''Parse CLI arguments.
38 Return (options, args) tuple.
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('--milestone',
46 help='Milestone name', dest='milestone')
47 optparser.add_option('-p', '--pattern', metavar='REGEX',
48 help='Regex pattern for blueprint name', dest='pattern')
49 optparser.add_option('-D', '--dump', action='store_true', default=False,
50 help='Dump database', dest='dump')
51 optparser.add_option('-m', '--moin', metavar='URL',
52 help='moin URL for additional work items (can be given multiple times)',
53 action='append', dest='moin', default=[])
54 optparser.add_option('-t', '--text', action='store_true', default=False,
55 help='Print work item summary in text format', dest='text')
56 optparser.add_option('-c', '--csv', action='store_true', default=False,
57 help='Print work item summary in CSV format', dest='csv')
58 optparser.add_option('-H', '--html', action='store_true', default=False,
59 help='Generate work item HTML report', dest='html')
60 optparser.add_option('--from', metavar='YYYY-MM-DD',
61 help='Generate CSV data from this day on', dest='from_date')
62 optparser.add_option('--to', metavar='YYYY-MM-DD',
63 help='Generate CSV data until this day', dest='to_date')
65 (opts, args) = optparser.parse_args()
68 optparser.error('No database given')
69 if not opts.dump and not opts.text and not opts.csv and not opts.html:
71 optparser.error('No release given')
73 optparser.error('No pattern given')
77 def get_blueprints(url, name_pattern, milestone):
78 '''Return a list of blueprint URLs for the current release.'''
80 blueprint_name_filter = re.compile('href="(/ubuntu/\+spec/%s[^"]+)"' %
87 for l in urllib.urlopen(url):
90 if ('/+milestone/%s"' % milestone) in l:
94 if bp and (not milestone or found_ms):
99 m = blueprint_name_filter.search(l)
101 bp = blueprints_base_url + m.group(1)
106 def get_blueprint_workitems(blueprint_url):
107 '''Collect work items from a particular blueprint URL.
109 This will return a list of ('item', 'status', 'assignee') tuples.
111 work_items_re = re.compile('(<p>|^)work items:\s*<br />', re.I)
112 assignee_re = re.compile('<a href="https://.*launchpad.net/~([a-zA-Z0-9_-]+)" class=".*person">')
114 found_workitems = False
115 found_assignee = False
117 default_assignee = 'nobody'
118 for l in urllib.urlopen(blueprint_url):
121 if '<dt>Assignee:' in l:
122 found_assignee = True
125 if found_assignee and not found_workitems:
126 m = assignee_re.search(l)
128 default_assignee = m.group(1)
129 found_assignee = False
131 if not found_workitems:
132 if work_items_re.search(l):
133 found_workitems = True
138 l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').replace('<wbr></wbr>', '').strip()
144 (desc, state) = l.rsplit(':', 1)
146 print >> sys.stderr, 'ERROR: invalid work item format: ' + l
149 state = state.strip().lower()
152 if state == 'completed':
154 if state == 'inprogress':
156 if state == 'postpone':
158 if state not in valid_states:
159 print >> sys.stderr, 'ERROR: invalid state "%s" for work item "%s"' % (
163 if desc.startswith('['):
165 off = desc.index(']')
166 assignee = desc[1:off]
167 desc = desc[off+1:].strip()
169 print >> sys.stderr, 'ERROR: missing closing "]" for assignee for work item "%s"' % desc
171 assignee = default_assignee
173 result.append((desc, state, assignee))
180 def get_blueprint_status(blueprint_url):
181 '''Collect status from a particular blueprint URL.
183 This will return a list of lines.
185 status_re = re.compile('(<p>|^)status:\s*<br />', re.I)
189 for l in urllib.urlopen(blueprint_url):
192 if status_re.search(l):
198 l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
203 result.append(l.strip())
208 return "\n".join(result)
210 def get_moin_workitems(url):
211 '''Collect work items from a moin wiki URL.
213 Every line starting with "|| " is treated as a work item.
215 Return a list of ('item', 'status') pairs.
218 for line in urllib.urlopen(url):
219 if line.startswith('|| '):
220 fields = line.strip().split('||')
221 assert not fields[0] # should be empty
222 desc = fields[1].strip()
225 result.append((desc, 'done'))
227 elif 'POSTPONED' in f:
228 result.append((desc, 'done'))
231 result.append((desc, 'todo'))
236 '''Dump database contents.'''
239 cur.execute('SELECT * FROM work_items')
240 print '== Work items: =='
241 for (blueprint, workitem, item_status, assignee, date) in cur:
242 print '%s [%s, %s]\t%s: %s' % (date, blueprint, assignee, workitem, item_status)
244 print '\n== Status =='
246 cur.execute('SELECT * FROM status')
247 for (blueprint, status, date) in cur:
248 print '%s: %s [%s]' % (blueprint, status, date)
250 def add_work_item(db, blueprint, item, status, assignee):
251 '''Add work item to database.'''
254 cur.execute('INSERT INTO work_items VALUES (?, ?, ?, ?, date(CURRENT_TIMESTAMP))',
255 (blueprint, item, status, assignee))
257 def add_status(db, blueprint, status):
258 '''Add blueprint status to database.'''
264 cur.execute('INSERT INTO status VALUES (?, ?, date(CURRENT_TIMESTAMP))',
267 def import_lp(db, name_pattern, release, milestone):
268 '''Collect blueprint work items and status from Launchpad into DB.'''
270 blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
271 release), name_pattern, milestone)
274 cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
275 cur.execute('DELETE FROM status WHERE date = date(CURRENT_TIMESTAMP)')
277 for bp in blueprints:
278 #print 'Checking', bp
279 bpname = bp.split('/')[-1]
280 work_items = get_blueprint_workitems(bp)
281 status = get_blueprint_status(bp)
283 print >> sys.stderr, 'WARNING: %s has no work items' % bpname
284 for (item, state, assignee) in work_items:
285 add_work_item(db, bpname, item, state, assignee)
286 add_status(db, bpname, status)
288 def workitems_over_time(db):
289 '''Calculate work item development over time.
291 Return date -> state -> count mapping.
294 for s in valid_states:
296 cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
298 for (date, num) in cur:
299 data.setdefault(date, {})[s] = num
302 def blueprint_completion(db):
303 '''Determine current blueprint completion.
305 Return blueprint -> [todo, done, postponed, status] mapping.
311 cur.execute('SELECT max(date) FROM work_items')
312 (last_date,) = cur.fetchone()
315 for s in valid_states:
317 cur.execute('SELECT w.blueprint, count(w.workitem), s.status FROM work_items w '
318 'LEFT JOIN status s ON w.blueprint = s.blueprint '
319 'WHERE w.status = ? AND w.date = ? GROUP BY w.blueprint',
321 for (bp, num, status) in cur:
322 data.setdefault(bp, [0, 0, 0, ''])[index] = num
323 data[bp][-1] = status or ''
328 def assignee_completion(db):
329 '''Determine current by-assignee completion.
331 Return assignee -> [todo, done, postponed] mapping.
337 cur.execute('SELECT max(date) FROM work_items')
338 (last_date,) = cur.fetchone()
341 for s in valid_states:
343 cur.execute('SELECT assignee, count(workitem) FROM work_items '
344 'WHERE date=? and status=? GROUP BY assignee',
347 data.setdefault(a, [0, 0, 0])[index] = num
353 '''Print work item completion as text.'''
355 data = workitems_over_time(db)
358 for d in sorted(data.keys()):
361 print '\nBlueprint completion:'
362 data = blueprint_completion(db)
363 for (bp, (todo, done, postponed, status)) in data.iteritems():
365 print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed,
366 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
368 def csv(db, from_date, to_date):
369 '''Print work item status as csv.'''
372 '''Convert datetime.date into MM/DD/YYYY'''
374 return '%s/%s/%s' % (d.month, d.day, d.year)
377 '''Convert YYYY-MM-DD string to datetime.date'''
379 (y, m, d) = s.split('-')
380 return datetime.date(int(y), int(m), int(d))
382 data = workitems_over_time(db)
384 dates = sorted(data.keys())
388 f = _fromstr(from_date or dates[0])
389 t = _fromstr(to_date or dates[-1])
393 entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
394 print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year,
395 entry.get('todo', 0), entry.get('done', 0),
396 entry.get('postponed', 0))
397 d += datetime.timedelta(days=1)
400 '''Print work item status as HTML.'''
404 <title>Work item status</title>
405 <style type="text/css">
406 body { background: #CCCCB0; color: black; }
407 a { text-decoration: none; }
408 table { border-collapse: collapse; border-style: solid none;
409 border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
410 table th { text-align: left; border-style: none none solid none;
411 border-width: 3px; padding-right: 10px; }
412 table td { text-align: left; border-style: none none dotted none;
413 border-width: 1px; padding-right: 10px; }
422 <p><img src="burndown.png" alt="burndown" /></p>
424 <h1>Status by blueprint</h1>
426 <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th> <th>Status</th></tr>
429 data = blueprint_completion(db)
432 for (bp, (todo, done, postponed, status)) in data.iteritems():
433 completion.append((bp,
434 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
436 completion.sort(key=lambda k: k[1], reverse=True)
438 for (bp, percent) in completion:
439 if bp.startswith('http:'):
442 url = '%s/ubuntu/+spec/%s' % (blueprints_base_url, bp)
443 print ' <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td> <td>%s</td></tr>' % (
444 url, bp, data[bp][0], data[bp][2],
445 data[bp][1], percent,
451 <h1>Status by assignee</h1>
453 <tr><th>Assignee</th> <th>todo/postponed/done</th> <th>Completion</th></tr>
455 data = assignee_completion(db)
458 for (a, (todo, done, postponed)) in data.iteritems():
459 completion.append((a,
460 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
462 completion.sort(key=lambda k: k[0], reverse=False)
464 for (a, percent) in completion:
465 url = '%s/~%s/+specs?role=assignee' % (blueprints_base_url, a)
466 print ' <tr><td><a href="%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td></tr>' % (
467 url, a, data[a][0], data[a][2],
471 print '</body></html>'
473 def import_moin(db, urls):
474 '''Collect blueprint work items from a moin wiki.'''
477 for (d, s) in get_moin_workitems(url):
478 add_work_item(db, url, d, s, 'nobody')
484 (opts, args) = parse_argv()
486 db = get_db(opts.database)
495 csv(db, opts.from_date, opts.to_date)
497 import_lp(db, opts.pattern, opts.release, opts.milestone)
498 import_moin(db, opts.moin)