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('-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')
63 (opts, args) = optparser.parse_args()
66 optparser.error('No database given')
67 if not opts.dump and not opts.text and not opts.csv and not opts.html:
69 optparser.error('No release given')
71 optparser.error('No pattern given')
75 def get_blueprints(url, name_pattern):
76 '''Return a list of blueprint URLs for the current release.'''
78 blueprint_name_filter = re.compile('href="(/ubuntu/\+spec/%s[^"]+)"' %
82 for l in urllib.urlopen(url):
83 m = blueprint_name_filter.search(l)
85 result.append(blueprints_base_url + m.group(1))
89 def get_blueprint_workitems(blueprint_url):
90 '''Collect work items from a particular blueprint URL.
92 This will return a list of ('item', 'status', 'assignee') tuples.
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">')
97 found_workitems = False
98 found_assignee = False
100 default_assignee = 'nobody'
101 for l in urllib.urlopen(blueprint_url):
104 if '<dt>Assignee:' in l:
105 found_assignee = True
108 if found_assignee and not found_workitems:
109 m = assignee_re.search(l)
111 default_assignee = m.group(1)
112 found_assignee = False
114 if not found_workitems:
115 if work_items_re.search(l):
116 found_workitems = True
121 l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
127 (desc, state) = l.rsplit(':', 1)
129 print >> sys.stderr, 'ERROR: invalid work item format: ' + l
132 state = state.strip().lower()
135 if state == 'completed':
137 if state == 'inprogress':
139 if state == 'postpone':
141 if state not in valid_states:
142 print >> sys.stderr, 'ERROR: invalid state "%s" for work item "%s"' % (
146 if desc.startswith('['):
148 off = desc.index(']')
149 assignee = desc[1:off]
150 desc = desc[off+1:].strip()
152 print >> sys.stderr, 'ERROR: missing closing "]" for assignee for work item "%s"' % desc
154 assignee = default_assignee
156 result.append((desc, state, assignee))
163 def get_blueprint_status(blueprint_url):
164 '''Collect status from a particular blueprint URL.
166 This will return a list of lines.
168 status_re = re.compile('(<p>|^)status:\s*<br />', re.I)
172 for l in urllib.urlopen(blueprint_url):
175 if status_re.search(l):
181 l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
186 result.append(l.strip())
191 return "\n".join(result)
193 def get_moin_workitems(url):
194 '''Collect work items from a moin wiki URL.
196 Every line starting with "|| " is treated as a work item.
198 Return a list of ('item', 'status') pairs.
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()
208 result.append((desc, 'done'))
210 elif 'POSTPONED' in f:
211 result.append((desc, 'done'))
214 result.append((desc, 'todo'))
219 '''Dump database contents.'''
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)
227 print '\n== Status =='
229 cur.execute('SELECT * FROM status')
230 for (blueprint, status, date) in cur:
231 print '%s: %s [%s]' % (blueprint, status, date)
233 def add_work_item(db, blueprint, item, status, assignee):
234 '''Add work item to database.'''
237 cur.execute('INSERT INTO work_items VALUES (?, ?, ?, ?, date(CURRENT_TIMESTAMP))',
238 (blueprint, item, status, assignee))
240 def add_status(db, blueprint, status):
241 '''Add blueprint status to database.'''
247 cur.execute('INSERT INTO status VALUES (?, ?, date(CURRENT_TIMESTAMP))',
250 def import_lp(db, name_pattern, release):
251 '''Collect blueprint work items and status from Launchpad into DB.'''
253 blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
254 opts.release), name_pattern)
257 cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
258 cur.execute('DELETE FROM status WHERE date = date(CURRENT_TIMESTAMP)')
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)
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)
271 def workitems_over_time(db):
272 '''Calculate work item development over time.
274 Return date -> state -> count mapping.
277 for s in valid_states:
279 cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
281 for (date, num) in cur:
282 data.setdefault(date, {})[s] = num
285 def blueprint_completion(db):
286 '''Determine current blueprint completion.
288 Return blueprint -> [todo, done, postponed, status] mapping.
294 cur.execute('SELECT max(date) FROM work_items')
295 (last_date,) = cur.fetchone()
298 for s in valid_states:
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',
304 for (bp, num, status) in cur:
305 data.setdefault(bp, [0, 0, 0, ''])[index] = num
306 data[bp][-1] = status or ''
312 '''Print work item completion as text.'''
314 data = workitems_over_time(db)
317 for d in sorted(data.keys()):
320 print '\nBlueprint completion:'
321 data = blueprint_completion(db)
322 for (bp, (todo, done, postponed, status)) in data.iteritems():
324 print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed,
325 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
327 def csv(db, from_date, to_date):
328 '''Print work item status as csv.'''
331 '''Convert datetime.date into MM/DD/YYYY'''
333 return '%s/%s/%s' % (d.month, d.day, d.year)
336 '''Convert YYYY-MM-DD string to datetime.date'''
338 (y, m, d) = s.split('-')
339 return datetime.date(int(y), int(m), int(d))
341 data = workitems_over_time(db)
343 dates = sorted(data.keys())
347 f = _fromstr(from_date or dates[0])
348 t = _fromstr(to_date or dates[-1])
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)
359 '''Print work item status as HTML.'''
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; }
381 <p><img src="burndown.png" alt="burndown" /></p>
383 <h1>Status by blueprint</h1>
385 <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th> <th>Status</th></tr>
388 data = blueprint_completion(db)
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)))
395 completion.sort(key=lambda k: k[1], reverse=True)
397 for (bp, percent) in completion:
398 if bp.startswith('http:'):
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,
409 print '</body></html>'
411 def import_moin(db, urls):
412 '''Collect blueprint work items from a moin wiki.'''
415 for (d, s) in get_moin_workitems(url):
416 add_work_item(db, url, d, s, 'nobody')
422 (opts, args) = parse_argv()
424 db = get_db(opts.database)
433 csv(db, opts.from_date, opts.to_date)
435 import_lp(db, opts.pattern, opts.release)
436 import_moin(db, opts.moin)