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