]> piware.de Git - bin.git/blob - workitems.py
d5621062e2a58e07da80ac6575bf17b9cfcaeeaf
[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         end = False
95         if not found_workitems:
96             if work_items_re.search(l):
97                 found_workitems = True
98             continue
99
100         if '</p>' in l:
101             end = True
102         l = l.replace('<br />', '').replace('</div>', '').replace('</p>', '').strip()
103
104         if not l:
105             break
106
107         try:
108             (desc, state) = l.rsplit(':', 1)
109         except ValueError:
110             print >> sys.stderr, 'ERROR: invalid work item format: ' + l
111             continue
112         desc = desc.strip()
113         state = state.strip().lower()
114         if not state:
115             state = 'todo'
116         if state == 'completed':
117             state = 'done'
118         if state == 'inprogress':
119             state = 'todo'
120         if state == 'postpone':
121             state = 'postponed'
122         if state not in valid_states:
123             print >> sys.stderr, 'ERROR: invalid state "%s" for work item "%s"' % (
124                 state, desc)
125             continue
126         result.append((desc, state))
127
128         if end:
129             break
130
131     return result
132
133 def get_moin_workitems(url):
134     '''Collect work items from a moin wiki URL.
135
136     Every line starting with "|| " is treated as a work item.
137
138     Return a list of ('item', 'status') pairs.
139     '''
140     result = []
141     for line in urllib.urlopen(url):
142         if line.startswith('|| '):
143             fields = line.strip().split('||')
144             assert not fields[0] # should be empty
145             desc = fields[1].strip()
146             for f in fields[2:]:
147                 if 'DONE' in f:
148                     result.append((desc, 'done'))
149                     break
150                 elif 'POSTPONED' in f:
151                     result.append((desc, 'done'))
152                     break
153             else:
154                 result.append((desc, 'todo'))
155
156     return result
157
158 def dump(db):
159     '''Dump database contents.'''
160
161     cur = db.cursor()
162     cur.execute('SELECT * FROM work_items')
163     for (blueprint, workitem, status, date) in cur:
164         print '%s [%s]\t%s: %s' % (date, blueprint, workitem, status)
165
166 def add_work_item(db, blueprint, item, status):
167     '''Add work item to database.'''
168
169     cur = db.cursor()
170     cur.execute('INSERT INTO work_items VALUES (?, ?, ?, date(CURRENT_TIMESTAMP))',
171             (blueprint, item, status))
172
173 def import_lp(db, name_pattern, release):
174     '''Collect blueprint work items from Launchpad into DB.'''
175
176     blueprints = get_blueprints('%s//ubuntu/%s/+specs?batch=300' % (blueprints_base_url,
177         opts.release), name_pattern)
178
179     cur = db.cursor()
180     cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
181
182     for bp in blueprints:
183         #print 'Checking', bp
184         bpname = bp.split('/')[-1]
185         work_items = get_blueprint_workitems(bp)
186         if not work_items:
187             print >> sys.stderr, 'WARNING: %s has no work items' % bpname
188         for (item, status) in work_items:
189             add_work_item(db, bpname, item, status)
190
191 def workitems_over_time(db):
192     '''Calculate work item development over time.
193
194     Return date -> state -> count mapping.
195     '''
196     data = {}
197     for s in valid_states:
198         cur = db.cursor()
199         cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
200                 (s,))
201         for (date, num) in cur:
202             data.setdefault(date, {})[s] = num
203     return data
204
205 def blueprint_status(db):
206     '''Determine current blueprint status.
207
208     Return blueprint -> [todo, done, postponed] mapping.
209     '''
210     data = {}
211
212     # last date
213     cur = db.cursor()
214     cur.execute('SELECT max(date) FROM work_items')
215     (last_date,) = cur.fetchone()
216
217     index = 0
218     for s in valid_states:
219         cur = db.cursor()
220         cur.execute('SELECT blueprint, count(workitem) FROM work_items '
221                 'WHERE status = ? AND date = ? GROUP BY blueprint', 
222                 (s, last_date))
223         for (bp, num) in cur:
224             data.setdefault(bp, [0, 0, 0])[index] = num
225         index += 1
226
227     return data
228
229 def text(db):
230     '''Print work item status as text.'''
231
232     data = workitems_over_time(db)
233
234     print 'History:'
235     for d in sorted(data.keys()):
236         print d, data[d]
237
238     print '\nBlueprint status:'
239     data = blueprint_status(db)
240     for (bp, (todo, done, postponed)) in data.iteritems():
241         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
242                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
243
244 def csv(db, from_date, to_date):
245     '''Print work item status as csv.'''
246
247     def _fmtdate(d):
248         '''Convert datetime.date into MM/DD/YYYY'''
249
250         return '%s/%s/%s' % (d.month, d.day, d.year)
251
252     def _fromstr(s):
253         '''Convert YYYY-MM-DD string to datetime.date'''
254
255         (y, m, d) = s.split('-')
256         return datetime.date(int(y), int(m), int(d))
257
258     data = workitems_over_time(db)
259
260     dates = sorted(data.keys())
261
262     f = _fromstr(from_date or dates[0])
263     t = _fromstr(to_date or dates[-1])
264
265     d = f
266     while d <= t:
267         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
268         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
269                 entry.get('todo', 0), entry.get('done', 0),
270                 entry.get('postponed', 0))
271         d += datetime.timedelta(days=1)
272
273 def html(db):
274     '''Print work item status as HTML.'''
275
276     print '''<html>
277 <head>
278   <title>Work item status</title>
279   <style type="text/css">
280     body { background: #CCCCB0; color: black; }
281     a { text-decoration: none; }
282     table { border-collapse: collapse; border-style: solid none; 
283             border-width: 3px; margin-bottom: 3ex; empty-cells: show; }
284     table th { text-align: left; border-style: none none solid none; 
285                border-width: 3px; padding-right: 10px; }
286     table td { text-align: left; border-style: none none dotted none; 
287                border-width: 1px; padding-right: 10px; }
288
289     a { color: blue; }
290   </style>
291 </head>
292
293 <body>
294
295 <h1>History</h1>
296 <p><img src="burndown.png" alt="burndown" /></p>
297
298 <h1>Status by blueprint</h1>
299 <table>
300   <tr><th>Blueprint</th> <th>todo/postponed/done</th> <th>Completion</th></tr>
301 '''
302
303     data = blueprint_status(db)
304
305     completion = []
306     for (bp, (todo, done, postponed)) in data.iteritems():
307         completion.append((bp,
308             int(float(postponed+done)/(todo+done+postponed)*100 + 0.5)))
309
310     completion.sort(key=lambda k: k[1], reverse=True)
311
312     for (bp, percent) in completion:
313         print '  <tr><td><a href="%s/ubuntu/+spec/%s">%s</a></td> <td>%i/%i/%i</td> <td>%i%%</td></tr>' % (
314                 blueprints_base_url, bp, bp, data[bp][0], data[bp][2],
315                 data[bp][1], percent)
316
317     print '</table>'
318
319     print '</body></html>'
320
321 def import_moin(db, urls):
322     '''Collect blueprint work items from a moin wiki.'''
323
324     for url in urls:
325         for (d, s) in get_moin_workitems(url):
326             add_work_item(db, url, d, s)
327
328 #
329 # main
330 #
331
332 (opts, args) = parse_argv()
333
334 db = get_db(opts.database)
335
336 if opts.dump:
337     dump(db)
338 elif opts.text:
339     text(db)
340 elif opts.html:
341     html(db)
342 elif opts.csv:
343     csv(db, opts.from_date, opts.to_date)
344 else:
345     import_lp(db, opts.pattern, opts.release)
346     import_moin(db, opts.moin)
347     db.commit()
348