~mabac/launchpad-work-items-tracker/fix-none-whiteboard

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#!/usr/bin/python
#
# Copyright (C) 2010, 2011 Canonical Ltd.
# License: GPL-3

import sys
import re
import optparse
import report_tools

level = 0
count_zero = { 'total':0 }
state2level = {}
level2colour = {}
state2human = {}
for name, colour, human in [
#            ('done',        '#ff9933',      "Complete"),
            ('postponed',   '#999999',      "Postponed"),
            ('done',        'lightblue',      "Complete"),
            ('todo',        '#00cc00',      "Todo"),
            ('inprogress',  '#00ff00',      "In Progress"),
            ('green',       '#00ff00',      "On Track"),
            ('amber',       '#ffff00',      "At Risk"),
            ('red',         '#ff0000',      "In Danger"),
            ('no-items',    '#ffff00',      "No Work Items")
        ]:
    state2level[name] = level
    level2colour[level] = colour
    state2human[name] = human
    count_zero[name] = 0
    level += 1


def state_out(state):
    if state in state2human:
        return state2human[state]
    else:
        return state


def conf_error(usage, line):
    sys.stderr.write("Config error: %s\n" % (line))
    sys.stderr.write("              %s\n" % (usage))
    sys.exit(1)


def data_sanitise(data):
    # Run through the whole table and clean up all the items.
    # Pull out any unknown milestones and add them to the list.
    for (bp, i) in data.iteritems():
        new_tasks = []
        for task in i['tasks']:
            # Pull off any colour modifiers, update status if not closed.
            for control in 'green', 'amber', 'red':
                if task['description'].endswith('[' + control + ']'):
                    if not task['state'] in ('done', 'postponed') :
                        task['state'] = control
                    task['description'] = task['description'].rstrip('[' + control + ']')
            # Shunt null milestones to 'None'.
            if task['milestone'] == None or task['milestone'] == '':
                task['milestone'] = "None"
            if task['state'] == 'todo' and i['implementation'] == 'Deferred':
                task['state'] = 'postponed'

            new_tasks.append(task)
        i['tasks'] = new_tasks

    return data


def data_milestones(data, milestones=[]):
    # Pull out any unknown milestones and add them to the list.
    for (bp, i) in data.iteritems():
        for task in i['tasks']:
            # Check if this miletone is unknown, shunt null ones to 'None'.
            if task['milestone'] == None or task['milestone'] == '':
                task['milestone'] = "None"
            if not task['milestone'] in milestones:
                milestones.append(task['milestone'])

    return milestones


html = re.compile(r'<[^>]*>')
buglink = re.compile(r'(bug +|LP: +)#?(\d+)', re.I)
def text_sanitise(text):
    text = text.replace("\n", " ")
    text = html.sub(" ", text)
    text = buglink.sub(r'\1Bug:\2', text)
    if not isinstance(text, unicode):
        text = unicode(text, 'UTF-8')
    return text


def blueprint_order(a, b):
    return cmp(a.lower(), b.lower())


def generate_tables(data, milestones = True):
    status_table = []
    tasks_table = []
    count_all = count_zero.copy()

    keys = data.keys()
    keys.sort(blueprint_order)

    for bp in keys:
        i = data[bp]
        (status, items) = (i['status'], i['tasks'])

        a = bp.split(' ', 1)
        if len(a) == 2:
            bp = a[1]
        name = "[[%s|%s]]" % (i['url'], bp)

        # Work out the master colour for the item, and accumulate stats
        count = count_zero.copy()
        masterl = 0
        masters = None
        for item in items:
            (desc, state, assignee, milestone) = (item['description'],
                        item['state'], item['assignee'], item['milestone'])

            #print masterl, state, desc, state2level[state]
            if masterl <= state2level[state]:
                masterl = state2level[state]
                masters = state
            count['total'] += 1
            count[state] += 1
            count_all['total'] += 1
            count_all[state] += 1

        if not masters:
            masters = 'no-items'
            masterl = state2level[masters]
        masterc = level2colour[masterl]

        # Emit the status table.
        status_table.append("||<rowbgcolor=\"%s\"> %s (%s/%s/%s) || %s || %s ||" % \
            (masterc, name, count['done'], count['postponed'], count['total'], \
                text_sanitise(status), state_out(masters)))

        # Emit the tasks table.
        current = 0
        for item in items:
            current += 1
            (desc, state, assignee, milestone) = (item['description'],
                        item['state'], item['assignee'], item['milestone'])
            if milestone == 'None':
                milestone = ''
            desc = text_sanitise(desc)
            itemc = level2colour[state2level[state]]
            if current == 1:
                entry = "||<(^ |%s rowbgcolor=\"%s\" bgcolor=\"%s\"> %s (%s/%s/%s) ||" % (len(items), itemc, masterc, name, count['done'], count['postponed'], count['total'])
            else:
                entry = "||<rowbgcolor=\"%s\">" % (itemc)
            entry += " %s || %s || " % (desc, assignee)
            if milestones:
                entry += " %s || " % (milestone)
            entry += " %s ||" % (state_out(state))
            tasks_table.append(entry)

    pcnt = ((count_all['done'] + count_all['postponed']) * 100) / \
                                                        count_all['total']
    tasks_table.append('')
    tasks_table.append("|| Total (%s/%s/%s) %d%%||" % \
        (count_all['done'], count_all['postponed'], count_all['total'], pcnt))

    return ("\n".join(status_table), "\n".join(tasks_table))


def generate_blueprint_list(data):
    blueprint_list = []

    keys = data.keys()
    keys.sort(blueprint_order)

    for bp in keys:
        i = data[bp]
        (status, assignee) = (i['status'], i['assignee'])

        a = bp.split(' ', 1)
        if len(a) == 2:
            bp = a[1]
        name = "[[%s|%s]]" % (i['url'], bp)

        if assignee:
            assignee = " (" + assignee + ")"
        else:
            assignee = ''

        blueprint_list.append(" 1. " + name + assignee + "\n")

    return "".join(blueprint_list)


if __name__ == '__main__':
    report_tools.fix_stdouterr()

    # argv parsing
    optparser = optparse.OptionParser()
    optparser.add_option('-d', '--database',
        help='Path to database', dest='database', metavar='PATH')
    optparser.add_option('-t', '--team',
            help='Restrict report to a particular team', dest='team')
    optparser.add_option('-v', '--version',
        help='Report version', dest='version')

    (opts, args) = optparser.parse_args()
    if not opts.database:
        optparser.error('No database given')

    store = report_tools.get_store(opts.database)

    data = report_tools.blueprint_tasks_completion(store, team=opts.team)
    data = data_sanitise(data)

    # Get the default milestones for this database augmenting that with any
    # mentioned by the user which are not listed.  Finally ensure we list
    # those items with no milestone last.
    milestones = report_tools.milestone_list(store)
    milestones = data_milestones(data, milestones)
    try:
        milestones.remove('None')
    except:
        pass
    milestones.append('')

    # WIKI: indicate this is a non-reportable update.
    print "@@ Trivial: (x) Yes  ( ) No"

    # Generate the overall list of blueprints
    if opts.version > 1:
        blueprint_list = generate_blueprint_list(data)

        print "## blueprint_list"
        print "== Blueprints =="
        print blueprint_list

    # Generate the top level tables -- those will all entries.
    (status, tasks) = generate_tables(data)

    # Title the table
    print "## activity_tables"
    print "== Activity Status =="
    print "||<20%> '''Blueprint/Activity''' || '''Overview''' ||<10%> '''Status''' ||";
    print status
    print
    print "== Activity Task Status =="
    print "||<20%> '''Blueprint/Activity''' || '''Task''' ||<10%> '''Assignee''' ||<10%> '''Milestone''' ||<10%> '''Status''' ||";
    print tasks

    # Generate per milestone tables.
    for stone in milestones:
        data = report_tools.blueprint_tasks_completion(store,
                                            team=opts.team, milestone=stone)
        data = data_sanitise(data)
        if stone == '':
            stone = 'None'

        if len(data):
            print ""
            print "== Milestone %s ==" % (stone)
            (status, tasks) = generate_tables(data, milestones=False)
            print "||<20%> '''Blueprint/Activity''' || '''Task''' ||<10%> '''Assignee''' ||<10%> '''Status''' ||";
            print tasks