]> piware.de Git - bin.git/blob - workitems.py
workitems: Overwrite data from same day
[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 = set(['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('-t', '--text', action='store_true', default=False,
45         help='Print work item summary in text format', dest='text')
46     optparser.add_option('-c', '--csv', action='store_true', default=False,
47         help='Print work item summary in text format', dest='csv')
48     optparser.add_option('--from', metavar='YYYY-MM-DD',
49         help='Generate CSV data from this day on', dest='from_date')
50     optparser.add_option('--to', metavar='YYYY-MM-DD',
51         help='Generate CSV data until this day', dest='to_date')
52
53     (opts, args) = optparser.parse_args()
54
55     if not opts.database:
56         optparser.error('No database given')
57     if not opts.dump and not opts.text and not opts.csv:
58         if not opts.release:
59             optparser.error('No release given')
60         if not opts.pattern:
61             optparser.error('No pattern given')
62
63     return (opts, args)
64
65 def get_blueprints(url, name_pattern):
66     '''Return a list of blueprint URLs for the current release.'''
67
68     blueprint_name_filter = re.compile('href="(/ubuntu/\+spec/%s[^"]+)"' %
69             name_pattern)
70
71     result = []
72     for l in urllib.urlopen(url):
73         m = blueprint_name_filter.search(l)
74         if m:
75             result.append(blueprints_base_url + m.group(1))
76
77     return result
78
79 def get_workitems(blueprint_url):
80     '''Collect work items from a particular blueprint URL.
81
82     This will return a list of ('item', 'status') pairs.
83     '''
84     work_items_re = re.compile('(<p>|^)work items:\s*<br />', re.I)
85
86     found_workitems = False
87     result = []
88     for l in urllib.urlopen(blueprint_url):
89         if not found_workitems:
90             if work_items_re.search(l):
91                 found_workitems = True
92             continue
93
94         l = l.replace('<br />', '').replace('</div>', '').strip()
95
96         # ends with empty line
97         if l.endswith('</p>') or not l:
98             break
99
100         try:
101             (desc, state) = l.rsplit(':', 1)
102         except ValueError:
103             print >> sys.stderr, 'ERROR: invalid work item format: ' + l
104             continue
105         desc = desc.strip()
106         state = state.strip().lower()
107         if not state:
108             state = 'todo'
109         if state not in valid_states:
110             print >> sys.stderr, 'ERROR: invalid state "%s" for work item "%s"' % (
111                 state, desc)
112             continue
113         result.append((desc, state))
114
115     return result
116
117 def dump(db):
118     '''Dump database contents.'''
119
120     cur = db.cursor()
121     cur.execute('SELECT * FROM work_items')
122     for (blueprint, workitem, status, date) in cur:
123         print '%s [%s]\t%s: %s' % (date, blueprint, workitem, status)
124
125 def add_work_item(db, blueprint, item, status):
126     '''Add work item to database.'''
127
128     cur = db.cursor()
129     cur.execute('INSERT INTO work_items VALUES (?, ?, ?, date(CURRENT_TIMESTAMP))',
130             (blueprint, item, status))
131
132 def import_lp(db, name_pattern, release):
133     '''Collect blueprint work items from Launchpad into DB.'''
134
135     blueprints = get_blueprints('%s//ubuntu/%s/+specs' % (blueprints_base_url,
136         opts.release), name_pattern)
137
138     cur = db.cursor()
139     cur.execute('DELETE FROM work_items WHERE date = date(CURRENT_TIMESTAMP)')
140
141     for bp in blueprints:
142         #print 'Checking', bp
143         bpname = bp.split('/')[-1]
144         work_items = get_workitems(bp)
145         if not work_items:
146             print >> sys.stderr, 'WARNING: %s has no work items' % bpname
147         for (item, status) in work_items:
148             add_work_item(db, bpname, item, status)
149     db.commit()
150
151 def workitems_over_time(db):
152     '''Calculate work item development over time.
153
154     Return date -> state -> count mapping.
155     '''
156     data = {}
157     for s in valid_states:
158         cur = db.cursor()
159         cur.execute('SELECT date, count(*) FROM work_items WHERE status=? GROUP BY date',
160                 (s,))
161         for (date, num) in cur:
162             data.setdefault(date, {})[s] = num
163     return data
164
165 def blueprint_status(db):
166     '''Determine current blueprint status.
167
168     Return blueprint -> [todo, done, postponed] mapping.
169     '''
170     data = {}
171
172     # last date
173     cur = db.cursor()
174     cur.execute('SELECT max(date) FROM work_items')
175     (last_date,) = cur.fetchone()
176
177     index = 0
178     for s in valid_states:
179         cur = db.cursor()
180         cur.execute('SELECT blueprint, count(workitem) FROM work_items '
181                 'WHERE status = ? AND date = ? GROUP BY blueprint', 
182                 (s, last_date))
183         for (bp, num) in cur:
184             data.setdefault(bp, [0, 0, 0])[index] = num
185         index += 1
186
187     return data
188
189 def text(db):
190     '''Print work item status as text.'''
191
192     data = workitems_over_time(db)
193
194     print 'History:'
195     for d in sorted(data.keys()):
196         print d, data[d]
197
198     print '\nBlueprint status:'
199     data = blueprint_status(db)
200     for (bp, (todo, done, postponed)) in data.iteritems():
201         print '%s: %i/%i (%i%%)' % (bp, postponed+done, todo+done+postponed, 
202                 int(float(postponed+done)/(todo+done+postponed)*100 + 0.5))
203
204 def csv(db, from_date, to_date):
205     '''Print work item status as csv.'''
206
207     def _fmtdate(d):
208         '''Convert datetime.date into MM/DD/YYYY'''
209
210         return '%s/%s/%s' % (d.month, d.day, d.year)
211
212     def _fromstr(s):
213         '''Convert YYYY-MM-DD string to datetime.date'''
214
215         (y, m, d) = s.split('-')
216         return datetime.date(int(y), int(m), int(d))
217
218     data = workitems_over_time(db)
219
220     dates = sorted(data.keys())
221
222     f = _fromstr(from_date or dates[0])
223     t = _fromstr(to_date or dates[-1])
224
225     d = f
226     while d <= t:
227         entry = data.get('%i-%02i-%02i' % (d.year, d.month, d.day), {})
228         print '%02i/%02i/%i,%i,%i,%i' % (d.month, d.day, d.year, 
229                 entry.get('todo', 0), entry.get('done', 0),
230                 entry.get('postponed', 0))
231         d += datetime.timedelta(days=1)
232
233 #
234 # main
235 #
236
237 (opts, args) = parse_argv()
238
239 db = get_db(opts.database)
240
241 if opts.dump:
242     dump(db)
243 elif opts.text:
244     text(db)
245 elif opts.csv:
246     csv(db, opts.from_date, opts.to_date)
247 else:
248     import_lp(db, opts.pattern, opts.release)
249