~lool/launchpad-work-items-tracker/linaro-staging-merge-with-linaro

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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
#!/usr/bin/python
#
# Pull work items from various sources (blueprint whiteboards, linked blueprint
# bugs, wiki pages) and put them into a database.
#
# Copyright (C) 2010, 2011 Canonical Ltd.
# License: GPL-3

import urllib, re, sys, optparse, smtplib, pwd, os, urlparse
import logging
from email.mime.text import MIMEText

from launchpadlib.launchpad import Launchpad, EDGE_SERVICE_ROOT

from lpworkitems.collect import CollectorStore, PersonCache, WorkitemParser, bug_wi_states
from lpworkitems.database import get_store
from lpworkitems.error_collector import (
    BlueprintURLError,
    ErrorCollector,
    StderrErrorCollector,
    )
from lpworkitems.models import (
    Blueprint,
    BlueprintGroup,
    Person,
    TeamParticipation,
    Workitem,
    )
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("lpworkitems")


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


def data_error(spec_url, msg, warning=False):
    '''Log an error in the input data for a particular spec.

    Depending on the program mode this gets printed to stderr, or mailed to the
    corresponding team contact.
    '''
    global error_collector

    error = BlueprintURLError(spec_url, msg, warning=warning)
    error_collector.store_error(error)
    dbg('Queueing data error: ' + error.format_for_display())


def web_link(item):
    """Get a link to the Launchpad API object on the website."""
    api_link = item.self_link
    parts = urlparse.urlparse(api_link)
    link = parts.scheme + "://" + parts.netloc.replace("api.", "") + "/" + parts.path.split("/", 2)[2]
    return link.decode("utf-8")


import simplejson
_orig_loads = simplejson.loads
def loads(something):
    return _orig_loads(unicode_or_None(something))
simplejson.loads = loads


########################################################################
#
# Functions for parsing Launchpad data
#
########################################################################


def lp_import_blueprint(collector, bp):
    '''Import details of a blueprint into the specs table.

    If a blueprint does not have a status, use the description.

    NOTE: We do not fill in "team" right now; let's see whether we will need
    that really.

    Return the created Blueprint on success, or None if not added.
    '''
    model_bp = Blueprint.from_launchpad(bp)
    if model_bp.milestone_name not in collector.valid_milestone_names():
        data_error(web_link(bp), 'milestone "%s" is unknown/invalid' % model_bp.milestone_name, True)
    model_bp = collector.store_blueprint(model_bp)
    if model_bp:
        dbg('lp_import_blueprint: added blueprint: %s' % bp.name)
    return model_bp


def add_dependencies(collector, group_name, deps):
    for dependency in deps.values():
        collector.add_blueprint_to_group(dependency.name, group_name)


def lp_import_spec_group(collector, bp, area, deps):
    '''Import details of a spec group into the spec_groups table.

    Return the BlueprintGroup on success, or None if not added.
    '''
    model_group = BlueprintGroup.from_launchpad(bp)
    model_group.area = area
    if model_group.milestone_name not in collector.valid_milestone_names():
        data_error(web_link(bp), 'milestone "%s" is unknown/invalid' % model_group.milestone, True)

    model_group = collector.store_blueprint_group(model_group)
    if model_group is None:
        return False
    else:
        dbg('lp_import_spec_group: added blueprint group: %s' % bp.name)
    add_dependencies(collector, model_group.name, deps)
    return model_group

def parse_meta_item(collector, line, bp_name):
    '''Parse a meta information line from a blueprint

    '''

    line = line.strip()
    if not line:
        return

    try:
        (key, value) = line.rsplit(':', 1)
        key   = key.strip()
        value = value.strip()
    except ValueError:
        dbg("\tMeta line '%s' can not be parsed" % line)
        return

    dbg( "\t\tMeta for %s: key='%s' value='%s'" % (bp_name, key, value) )
    collector.store_meta(key, value, bp_name)


def parse_complexity_item(collector, line, bp_name, bp_url, def_milestone, def_assignee):
    line = line.strip()
    # remove special characters people tend to type
    line = re.sub('[^\w -.]', '', line)
    if not line:
        return

    dbg("\tParsing complexity line '%s'" % line)

    num         = None
    milestone   = None
    assignee    = None

    try:
        complexity_list = line.split()
        complexity_list.reverse()

        # we may not have any values in the list, so append our
        # default values in the right order so they can be mapped
        defs = [None, def_milestone, def_assignee]
        for i in range(len(complexity_list), len(defs)):
            complexity_list.append(defs[i])
        (num, milestone, assignee) = complexity_list
        if not num:
            data_error(bp_url, 'No complexity points defined for %s' % line)

        dbg('\tComplexity: %s MS: %s Who: %s' % (num, milestone, assignee))
        collector.store_complexity(assignee, num, milestone, bp_name)
    except ValueError:
        data_error(bp_url, "\tComplexity line '%s' could not be parsed %s" % (line, ValueError))


def milestone_extract(text, valid_milestones):
    words = text.replace('(', ' ').replace(')', ' ').replace('[', ' ').replace(
            ']', ' ').replace('<wbr></wbr>', '').split()

    for word in words:
        if word in valid_milestones:
            return word
    return None

def lp_import_blueprint_workitems(collector, bp, distro_release, people_cache=None, projects=None):
    '''Collect work items from a Launchpad blueprint.

    This includes work items from the whiteboard as well as linked bugs.
    '''
    work_items_re = re.compile('^work items(.*)\s*:\s*$', re.I)
    meta_re = re.compile('^Meta.*?:$', re.I)
    complexity_re = re.compile('^Complexity.*?:$', re.I)

    in_workitems_block = False
    in_meta_block = False
    in_complexity_block = False
    work_items = []

    model_bp = collector.store.find(
        Blueprint, Blueprint.name == bp.name).one()
    assert model_bp is not None, "Asked to process workitems of %s when it is not in the db" % bp.name

    dbg('lp_import_blueprint_workitems(): processing %s (spec milestone: %s, spec assignee: %s, spec implementation: %s)' % (
        bp.name, model_bp.milestone_name, model_bp.assignee_name,
        model_bp.implementation))

    valid_milestones = collector.valid_milestone_names()
    global error_collector
    parser = WorkitemParser(
        model_bp, model_bp.milestone_name, collector.lp, people_cache=people_cache,
        error_collector=error_collector)

    # Get work items from both the whiteboard and the new workitems_text
    # property. Once the migration is completed and nobody's using the
    # whiteboard for work items we can change this to pull work items only
    # from bp.workitems_text.
    workitems_text = bp.whiteboard
    if workitems_text is None:
        workitems_text = ''
    if getattr(bp, 'workitems_text', '') != '':
        workitems_text += "\n" + bp.workitems_text
    if workitems_text:
        for l in workitems_text.splitlines():
            if not in_workitems_block:
                m = work_items_re.search(l)
                if m:
                    in_workitems_block = True
                    dbg('lp_import_blueprint_workitems(): starting work items block at ' + l)
                    milestone = milestone_extract(m.group(1), valid_milestones)
                    dbg('  ... setting milestone to ' + str(milestone))
                    parser.milestone_name = milestone or parser.blueprint.milestone_name
                continue

            if in_workitems_block:
                dbg("\tworkitem (raw): '%s'" % (l.strip()))
                if not l.strip():
                    dbg('lp_import_blueprint_workitems(): closing work items block with line: ' + l)
                    in_workitems_block = False
                    parser.milestone_name = parser.blueprint.milestone_name
                workitem = parser.parse_blueprint_workitem(l)
                if workitem is not None:
                    work_items.append(workitem)

    if bp.whiteboard:
        for l in bp.whiteboard.splitlines():
            if not in_meta_block and not in_complexity_block:
                if meta_re.search(l):
                    in_meta_block = True
                if complexity_re.search(l):
                    in_complexity_block = True
                continue

            if in_meta_block:
                dbg("\tmeta line (raw): '%s'" % (l.strip()))
                if not l.strip():
                    in_meta_block = False
                    continue
                parse_meta_item(collector, l, bp.name)

            if in_complexity_block:
                dbg("\tcomplexity block line (raw): '%s'" % (l.strip()))
                if not l.strip():
                    in_complexity_block = False
                    continue
                parse_complexity_item(collector, l, model_bp.name,
                        model_bp.url, model_bp.milestone_name,
                        model_bp.assignee_name)

    if collector.lp:
        for bug in bp.bugs:
            work_items.extend(
                parser.get_workitems_from_bug(
                    bug, projects=projects, distro_release=distro_release))

    if not work_items:
        #data_error(bp_url, 'no work items defined', True)
        pass

    if model_bp.implementation == u'Deferred':
        for workitem in work_items:
            if workitem.status == Workitem.STATUS_TODO:
                workitem.status = Workitem.STATUS_POSTPONED

    for workitem in work_items:
        collector.store_workitem(workitem)


def _import_teams_recurse(collector, cfg, team, top_level_team_names,
        people_cache=None, recursive=False):
    dbg('lp_import_teams(): Importing members for team ' + team.name)
    for member in team.members:
        if people_cache is not None:
            people_cache.set_valid_person(member.name)
        collector.store_person(
            member.name,
            display_name=member.display_name)
        for top_level_team_name in top_level_team_names:
            collector.store_team_participation(
                member.name, top_level_team_name)
        if member.is_team:
            collector.store_team_structure(
                member.name, team.name)
            if recursive or team.name in cfg.get('recursive_teams', []):
                _import_teams_recurse(
                        collector, cfg, member, top_level_team_names + [member.name],
                        people_cache=people_cache, recursive=True)


def lp_import_teams(collector, cfg, people_cache=None):
    '''Import configured teams from Launchpad into DB.

    This needs the "teams" map from configuration.
    '''
    if collector.store.find(TeamParticipation).any() is not None:
        dbg('lp_import_teams(): teams table already filled')
        if people_cache is not None:
            for person in collector.store.find(Person):
                people_cache.set_valid_person(person.name)
        return

    for team in cfg.get('teams', {}).keys():
        _import_teams_recurse(
            collector, cfg, collector.lp.people[team], [unicode_or_None(team)],
            people_cache=people_cache)


def lp_import_bug_workitems(lp_project, collector, cfg):
    '''Collect work items from a bug list query'''

    if 'work_item_bugs' not in cfg:
        return

    # synthesize a spec for this project
    name = lp_project.title
    blueprint = Blueprint()
    blueprint.name = name
    blueprint.url = (
        u'https://launchpad.net/' + lp_project.name)
    blueprint.implementation = u'Unknown'
    blueprint.status = lp_project.summary or name
    collector.store_blueprint(blueprint)

    for task in lp_project.searchTasks(status=bug_wi_states.keys(), **cfg['work_item_bugs']):
        id = task.self_link.split('/')[-1]
        title = task.title.split('"', 1)[1].rstrip('"')
        state = bug_wi_states[task.status]
        if state is None:
            dbg('lp_import_bug_workitems: ignoring #%s: %s (status: %s)' % (id, title, task.status))
            continue
        dbg('lp_import_bug_workitems: #%s: %s (%s)' % (id, title, state))

        if task.milestone:
            milestone = task.milestone.name
        else:
            milestone = None
        if task.assignee:
            assignee = task.assignee.name
        else:
            assignee = None

        workitem = Workitem()
        workitem.description = title
        workitem.blueprint_name = blueprint.name
        workitem.assignee_name = assignee
        workitem.milestone_name = milestone
        workitem.status = state
        collector.store_workitem(workitem)


def lp_import(collector, cfg, name_pattern=None):
    '''Collect blueprint work items and status from Launchpad into DB.'''

    projects = []
    non_distro_projects = {}
    milestones = []

    def add_milestones(project):
        milestones.extend([ms for ms in project.all_milestones])

    if 'release' in cfg:
        lp_project = collector.lp.distributions['ubuntu'].getSeries(name_or_version=cfg['release'])
        projects.append((lp_project, None))
        add_milestones(lp_project)
    else:
        assert 'project' in cfg, 'Configuration needs to specify project or release'
        lp_project = collector.lp.projects[cfg['project']]
        if 'project_series' in cfg:
            lp_project_series = lp_project.getSeries(name=cfg['project_series'])
            add_milestones(lp_project_series)
        else:
            lp_project_series = None
            add_milestones(lp_project)
        projects.append((lp_project, lp_project_series))
        if lp_project_series is not None:
            non_distro_projects[lp_project.name] = lp_project_series.name
        else:
            non_distro_projects[lp_project.name] = None

    people_cache = PersonCache(collector.lp)

    lp_import_teams(collector, cfg, people_cache=people_cache)

    extra_projects = cfg.get('extra_projects', {})
    is_dict = getattr(extra_projects, 'keys', None) is not None
    for extra_project_name in extra_projects:
        extra_project = collector.lp.projects[extra_project_name]
        if is_dict and extra_projects[extra_project_name] is not None:
            extra_project_series = extra_project.getSeries(
                name=extra_projects[extra_project_name])
            if extra_project_series is None:
                raise AssertionError(
                    "%s has no series named %s"
                    % (extra_project_name, extra_projects[extra_project_name]))
            add_milestones(extra_project_series)
        else:
            extra_project_series = None
            add_milestones(extra_project)
        projects.append((extra_project, extra_project_series))
        if extra_project_series is not None:
            non_distro_projects[extra_project.name] = extra_project_series.name
        else:
            non_distro_projects[extra_project.name] = None

    collector.store_lp_milestones(milestones)

    spec_group_matchers = cfg.get('spec_groups', {})
    spec_group_bps = {}
    accepted_bps = {}
    spec_groups = {}

    def _add_to_dict(bp, collection):
        if bp.self_link not in collection:
            collection[bp.self_link] = bp

    def add_blueprint(bp):
        _add_to_dict(bp, accepted_bps)

    def add_spec_group_blueprint(bp, group):
        this_group_bps = spec_group_bps.setdefault(group, {})
        _add_to_dict(bp, this_group_bps)

    def add_spec_group_dependencies(group, current):
        for dependency in current.dependencies:
            add_spec_group_blueprint(dependency, group)
            add_spec_group_dependencies(group, dependency)

    def add_spec_group(bp, area):
        if bp.self_link not in spec_groups:
            spec_groups[bp.self_link] = (bp, area)
        add_spec_group_dependencies(bp.self_link, bp)

    for project, series in projects:
    # XXX: should this be valid_ or all_specifications?
        project_spec_group_matcher = spec_group_matchers.get(project.name, None)
        project_bps = project.valid_specifications
        for bp in project_bps:
            if name_pattern is not None and re.search(name_pattern, bp.name) is None:
                continue
            if project_spec_group_matcher is not None:
                match = re.search(project_spec_group_matcher, bp.name)
                if match is not None:
                    area = None
                    groups = match.groups()
                    if len(groups) > 0:
                        area = groups[0]
                    add_spec_group(bp, area)
                    continue
            if series is None:
                add_blueprint(bp)
        if series is not None:
            for bp in series.valid_specifications:
                if name_pattern is not None and re.search(name_pattern, bp.name) is None:
                    continue
                if project_spec_group_matcher is not None:
                    match = re.search(project_spec_group_matcher, bp.name)
                    if match is not None:
                        continue
                add_blueprint(bp)

    for bp in accepted_bps.values():
        if lp_import_blueprint(collector, bp):
            lp_import_blueprint_workitems(collector, bp, cfg.get('release'),
                    people_cache=people_cache, projects=non_distro_projects)

    for spec_group, area in spec_groups.values():
        possible_deps = spec_group_bps.get(spec_group.self_link, {})
        deps = {}
        for possible_dep in possible_deps:
            if possible_dep in accepted_bps:
                deps[possible_dep] = possible_deps[possible_dep]
        if deps:
            lp_import_spec_group(collector, spec_group, area, deps)

    lp_import_bug_workitems(lp_project, collector, cfg)


########################################################################
#
# Functions for parsing Moin wiki data
#
########################################################################

def escape_url(url):
    '''Correctly escape data intended to be included in a URL'''
    return urllib.quote(url)


def get_moin_workitems_group(url, default_assignee):
    '''Collect work items from a moin wiki URL.

    Sections at == are treated as groups, first paragraph is status
    Every line starting with "|| " is treated as a work item.

    Return a list of ('name', 'status', [items...]), where each item
    is ('description', 'state', 'assignee', 'milestone').
    '''
    field_off = {}
    field_re = re.compile('^## WORKITEMS\s+(.*\S)\s*$')
    result = []
    section = []
    status = u''
    collect = 0
    name = None
    in_section = False
    for line in urllib.urlopen(url):
        # Find the field designators and record them.
        line = line.decode("utf-8")
        m = field_re.match(line)
        if m:
            field_off = {}
            for pair in m.group(1).split(u' '):
                if pair.index(u'='):
                    (field, offset) = pair.split(u'=')
                    field_off[field] = int(offset)
            continue

        if line.startswith(u'== '):
            if in_section:
                result.append([name, status, section])
            fields = line.strip().split(u'==')
            assert not fields[0] # should be empty
            name = fields[1].strip()
            section = []
            collect = 1
            status = u''
        elif line.startswith(u'|| '):
            if not in_section:
                in_section = True
            collect = 0
            fields = line.strip().split(u'||')
            assert not fields[0] # should be empty
            assignee = default_assignee
            istatus = u'todo'
            milestone = None
            # Find the description
            if u'description' in field_off:
                which = field_off[u'description']
            else:
                which = 1
            desc = fields[which].strip()
            if u'status' in field_off:
                which = field_off[u'status']
                status_search = [ fields[which] ]
            else:
                status_search = fields[2:]
            for f in status_search:
                if u'DONE' in f or u'POSTPONED' in f or u'TODO' in f or u'INPROGRESS' in f or u'BLOCKED' in f:
                    ff = f.split()
                    if len(ff) == 2:
                        assignee = ff[1]
                    if u'DONE' in f:
                        istatus = u'done'
                        break
                    elif u'POSTPONED' in f:
                        istatus = u'postponed'
                        break
                    elif u'BLOCKED' in f:
                        istatus = u'blocked'
                        break
                    elif u'INPROGRESS' in f:
                        istatus = u'inprogress'
                        break
                    else:
                        istatus = u'todo'
                        break
            if u'assignee' in field_off:
                which = field_off[u'assignee']
                new_assignee = fields[which].strip()
                if new_assignee:
                    assignee = new_assignee
            if u'milestone' in field_off:
                which = field_off[u'milestone']
                new_milestone = fields[which].strip()
                if new_milestone:
                    milestone = new_milestone
            section.append((desc, istatus, assignee, milestone))
        elif line.startswith(u'||'):
            pass
        elif line != u'':
            if collect:
                status += u" " + line.strip()

    status = status.replace(u'<wbr>', u'').replace(u'</wbr>', u'').strip()
    if in_section:
        result.append([name, status, section])

    return result


def moin_import(collector, cfg):
    '''Collect blueprint work items from a moin wiki.'''

    for url, default_assignee in cfg.get('moin_pages', {}).iteritems():
        url = unicode_or_None(url)
        default_assignee = unicode_or_None(default_assignee)
        dbg('moin_import(): processing %s (default assignee: %s)' % (url, default_assignee))
        for group, status, items in get_moin_workitems_group(url, default_assignee):
            url_clean = url.replace('?action=raw', '')
            name = url_clean.split('://', 1)[1].split('/', 1)[1]
            if group:
                name += u' ' + group
                spec_url = u'%s#%s' % (url_clean, escape_url(group))
                dbg('  got group %s: name="%s", url="%s"' % (group, name, spec_url))
            else:
                spec_url = url_clean
                dbg('  no group: name="%s", url="%s"' % (name, spec_url))

            blueprint = Blueprint()
            blueprint.name = name
            blueprint.url = spec_url
            blueprint.priority = u'Medium'
            blueprint.implementation = u'Unknown'
            blueprint.status = status
            collector.store_blueprint(blueprint)
            for (desc, state, assignee, milestone) in items:
                workitem = Workitem()
                workitem.description = desc
                workitem.blueprint_name = name
                workitem.status = state
                workitem.assignee_name = assignee
                workitem.milestone_name = milestone
                collector.store_workitem(workitem)


########################################################################
#
# 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('-p', '--pattern', metavar='REGEX',
        help='Regex pattern for blueprint name (optional, mainly for testing)', dest='pattern')
    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('--refresh', action='store_true', default=False,
        help='Regenerate teams and milestones tables.', dest='refresh')

    (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 send_error_mails(cfg):
    '''Send data_errors to contacts.

    Data error contacts are defined in the configuration in the 
    "project_notification_addresses" map (which assigns project names to a list
    of email addresses). If no address list for a project is found, the error
    goes to stderr.
    '''
    global error_collector

    # sort errors into address buckets
    emails = {} # email address -> contents

    dbg('mailing %i data errors' % len(error_collector.errors))
    for error in error_collector.errors:
        project_name = error.get_project_name()
        if project_name is not None:
            addresses = cfg['project_notification_addresses'][project_name]
            dbg('spec %s is targetted to "%s", mailing to %s' % (error.get_blueprint_name(),
                                                                 project_name, ', '.join(addresses)))
            for a in addresses:
                emails.setdefault(a, '')
                emails[a] += error.format_for_display() + '\n'
        else:
            print >> sys.stderr, error.format_for_display(), '(no error_contact pattern)'

    # send mails
    for addr, contents in emails.iteritems():
        msg = MIMEText(contents.encode('ascii', 'replace'))
        msg['Subject'] = 'Errors in work item definitions'
        msg['From'] = 'Launchpad work item tracker <work-items-tracker-hackers@lists.launchpad.net>'
        msg['To'] = addr
        s = smtplib.SMTP()
        s.connect()
        s.sendmail(os.environ.get('EMAIL', pwd.getpwuid(os.geteuid()).pw_name + '@localhost'),
                addr, msg.as_string())
        s.quit()


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 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)

    if 'bug_status_map' in cfg:
        bug_status_map = cfg['bug_status_map']
        for key, val in bug_status_map.items():
            bug_status_map[key] = unicode_or_None(val)
        bug_wi_states.update(bug_status_map)

    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)

    if "beta" in EDGE_SERVICE_ROOT:
        lp = Launchpad.login_with('ubuntu-work-items', service_root=EDGE_SERVICE_ROOT.replace("edge.", "").replace("beta", "devel"))
    else:
        lp = Launchpad.login_with('ubuntu-work-items', service_root="production", version="devel")

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

    # reset status for current day
    collector.clear_todays_workitems()
    # We can delete all blueprints while keeping work items for previous days
    # because there's no foreign key reference from WorkItem to Blueprint.
    collector.clear_blueprints()
    collector.clear_metas()
    collector.clear_complexitys()
    collector.clear_blueprint_groups()
    if opts.refresh:
        collector.clear_milestones()
        collector.clear_people_and_teams()

    lp_import(collector, cfg, opts.pattern)
    moin_import(collector, cfg)

    store.commit()
    if opts.mail:
        send_error_mails(cfg)

    os.unlink(lock_path)


if __name__ == '__main__':
    main()