~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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/python
#
# Pull items from the Linaro roadmap in Kanbantool and put them into a database.

import urllib2, re, sys, optparse, smtplib, pwd, os
import simplejson
import logging
from email.mime.text import MIMEText

from lpworkitems.collect_roadmap import (
    CollectorStore,
    get_json_item,
    lookup_kanban_priority,
    )
from lpworkitems.database import get_store
from lpworkitems.error_collector import (
    ErrorCollector,
    StderrErrorCollector,
    )
from lpworkitems.models_roadmap import (
    Lane,
    Card,
    )
from utils import unicode_or_None
import report_tools


# An ErrorCollector to collect the data errors for later reporting
error_collector = None


logger = logging.getLogger("linaroroadmap")


def dbg(msg):
    '''Print out debugging message if debugging is enabled.'''
    logger.debug(msg)


def get_kanban_url(item_url, api_token):
    base_url = 'https://linaro.kanbantool.com/api/v1'
    return "%s/%s?api_token=%s" % (base_url, item_url, api_token)


def get_json_data(url):
    data = None
    try:
        data = simplejson.load(urllib2.urlopen(url))
    except urllib2.HTTPError, e:
        print "HTTP error for url '%s': %d" % (url, e.code)
    except urllib2.URLError, e:
        print "Network error for url '%s': %s" % (url, e.reason.args[1])
    except ValueError, e:
        print "Data error for url '%s': %s" % (url, e.args[0])

    return data


def kanban_import_lanes(collector, workflow_stages, cfg):
    nodes = {}
    root_node_id = None
    lanes_to_ignore = ['Legend']

    # Iterate over all workflow_stages which may be in any order.
    for workflow_stage in workflow_stages:
        if workflow_stage['name'] in lanes_to_ignore:
            dbg("Ignoring lane %s." % workflow_stage['name'])
            continue
        parent_id = workflow_stage['parent_id']
        if parent_id is None:
            assert root_node_id is None, 'We have already found the root node.'
            root_node_id = workflow_stage['id']
        else:
            if parent_id not in nodes:
                nodes[parent_id] = []
            # Add child workflow_stage
            nodes[parent_id].append(workflow_stage)

    statuses = []
    for node in nodes[root_node_id]:
        assert node['parent_id'] == root_node_id
        model_lane = Lane(get_json_item(node, 'name'),
                          node['id'])
        if model_lane.name == cfg['current_lane']:
            model_lane.is_current = True
        else:
            model_lane.is_current = False
        collector.store_lane(model_lane)
        node_id = node['id']
        if node_id in nodes:
            statuses.extend(nodes[node_id])
    return statuses


def kanban_import_cards(collector, tasks, status_list, card_types, papyrs_token):
    types_to_ignore = ['Summits']
    for task in tasks:
        dbg("Collecting card '%s'." % (task['task']['name']))
        status_id = task['task']['workflow_stage_id']
        assert status_id is not None
        task_status = None
        for status in status_list:
            if status['id'] == status_id:
                task_status = status
                break
        card_type_id = task['task']['card_type_id']
        card_type_name = None
        for card_type in card_types:
            if card_type['id'] == card_type_id:
                card_type_name = card_type['name']
                break
        else:
            dbg("Cannot find type for card '%s'." % (task['task']['name']))
        if card_type_name in types_to_ignore:
            dbg("Ignoring card '%s' since it\'s type is '%s'." %  \
                    (task['task']['name'], card_type['name']))
        else:
            if task_status is not None:
                lane_id = task_status['parent_id']
                assert lane_id is not None
            else:
                lane_id = status_id
            if not collector.lane_is_collected(lane_id):
                dbg("Ignoring card '%s' since it\'s Lane is ignored." %  \
                        (task['task']['name']))
                continue
            model_card = Card(get_json_item(task['task'], 'name'),
                              task['task']['id'], lane_id,
                              get_json_item(task['task'], 'external_id'))
            if task_status is not None:
                model_card.status = get_json_item(task_status, 'name')
            model_card.team = unicode_or_None(card_type_name)
            model_card.priority = lookup_kanban_priority(
                task['task']['priority'])
            model_card.size = get_json_item(task['task'], 'size_estimate')
            model_card.sponsor = get_json_item(task['task'],
                                               'custom_field_1')

            external_link = task['task']['custom_field_2']
            if external_link is not None and external_link is not '':
                model_card.url = unicode_or_None(external_link)
                dbg('Getting Papyrs information from %s.' % external_link)
                papyrs_data = papyrs_import(collector, external_link, papyrs_token)
                model_card.description = get_json_item(papyrs_data,
                                                       'description')
                model_card.acceptance_criteria = get_json_item(
                    papyrs_data, 'acceptance_criteria')
            collector.store_card(model_card)


def kanban_import(collector, cfg, board_id, api_token, papyrs_token):
    '''Collect roadmap items from KanbanTool into DB.'''
    board_url = get_kanban_url('boards/%s.json' % board_id, api_token)
    board = get_json_data(board_url)
    assert board is not None, "Could not access board %s." % board_id
    card_types = board['board']['card_types']
    status_list = kanban_import_lanes(collector,
                                      board['board']['workflow_stages'], cfg)

    tasks_url = get_kanban_url('boards/%s/tasks.json' % board_id, api_token)
    tasks = get_json_data(tasks_url)
    kanban_import_cards(collector, tasks, status_list, card_types, papyrs_token)


def papyrs_import(collector, requirement_url, papyrs_token):
    description = None
    acceptance_criteria = None

    page = get_json_data(requirement_url + '?json&auth_token=%s' % papyrs_token)
    if page is None:
        return {'description': None,
                'acceptance_criteria': None}

    page_text_items = page[0]
    page_extra_items = page[1]

    has_found_description = False
    last_heading = ''
    for page_item in page_text_items:
        if page_item['classname'] == 'Heading':
            last_heading = page_item['text']
        if page_item['classname'] == 'Paragraph':
            if not has_found_description:
                description = page_item['html']
                has_found_description = True
            elif 'Acceptance Criteria' in last_heading:
                acceptance_criteria = page_item['html']

    return {'description': get_first_paragraph(description),
            'acceptance_criteria': get_first_paragraph(acceptance_criteria)}


def get_first_paragraph(text):
    if text is None:
        return None
    # This might break, depending on what type of line breaks
    # whoever authors the Papyrs document uses.
    first_pararaph, _, _ = text.partition('<br>')
    return first_pararaph


########################################################################
#
# Program operations and main
#
########################################################################

def parse_argv():
    '''Parse CLI arguments.

    Return (options, args) tuple.
    '''
    optparser = optparse.OptionParser()
    optparser.add_option('-d', '--database',
        help='Path to database', dest='database', metavar='PATH')
    optparser.add_option('-c', '--config',
        help='Path to configuration file', dest='config', metavar='PATH')
    optparser.add_option('--debug', action='store_true', default=False,
        help='Enable debugging output in parsing routines')
    optparser.add_option('--mail', action='store_true', default=False,
        help='Send data errors as email (according to "error_config" map in '
            'config file) instead of printing to stderr', dest='mail')
    optparser.add_option('--board',
        help='Board id at Kanbantool', dest='board')
    optparser.add_option('--kanbantoken',
        help='Kanbantool API token for authentication', dest='kanban_token')
    optparser.add_option('--papyrstoken',
        help='Papyrs API token for authentication', dest='papyrs_token')

    (opts, args) = optparser.parse_args()

    if not opts.database:
        optparser.error('No database given')
    if not opts.config:
        optparser.error('No config given')

    return opts, args


def setup_logging(debug):
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter("%(message)s")
    ch.setFormatter(formatter)
    logger.setLevel(logging.INFO)
    logger.addHandler(ch)
    if debug:
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        ch.setFormatter(formatter)
        logger.setLevel(logging.DEBUG)


def update_todays_blueprint_daily_count_per_state(collector):
    """Clear today's entries and create them again to reflect the current
    state of blueprints."""
    collector.clear_todays_blueprint_daily_count_per_state()
    collector.store_roadmap_bp_count_per_state()


def main():
    report_tools.fix_stdouterr()

    (opts, args) = parse_argv()

    setup_logging(opts.debug)

    global error_collector
    if opts.mail:
        error_collector = ErrorCollector()
    else:
        error_collector = StderrErrorCollector()

    cfg = report_tools.load_config(opts.config)

    lock_path = opts.database + ".lock"
    lock_f = open(lock_path, "wb")
    if report_tools.lock_file(lock_f) is None:
        print "Another instance is already running"
        sys.exit(0)

    store = get_store(opts.database)
    collector = CollectorStore(store, '', error_collector)

    collector.clear_lanes()
    collector.clear_cards()

    kanban_import(collector, cfg, opts.board, opts.kanban_token, opts.papyrs_token)

    update_todays_blueprint_daily_count_per_state(collector)

    store.commit()

    os.unlink(lock_path)


if __name__ == '__main__':
    main()