~sil2100/+junk/issues_tracker

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
#!/usr/bin/python

from launchpadlib.launchpad import Launchpad
import lazr
import json
import datetime
import os
import os.path

lp = None


def get_launchpad():
    global lp
    if not lp:
        lp = Launchpad.login_anonymously(
            'landing-team-issues', 'production', version='devel')
    return lp


def output_issue_for_email(f, issue):
    f.write('** {}\n{}\n'.format(issue['name'].encode('utf8'), issue['bug_link']))
    if issue['age'] > 0:
        f.write('[Time counter {}/7]\n'.format(issue['age']))
    if 'whitelisted' in issue and issue['whitelisted']:
        f.write('[WHITELISTED]\n')
    if len(issue['mps']):
        f.write(' => Merge requests present\n')
    if issue['comments']:
        f.write(' -> {}'.format(issue['comments']))
    f.write('\n')


def output_issues_for_email(f, issues, filtering):
    final_list = filter(filtering, issues)
    if len(final_list) > 0:
        for issue in final_list:
            output_issue_for_email(f, issue)
    else:
        f.write('None.\n')


def output_for_email(path, issues):
    blockers = []
    observed = []

    for issue in issues:
        if (issue['category'] == 'blocker' and 'whitelisted' not in issue):
            blockers.append(issue)
        else:
            observed.append(issue)

    with open(path, "w") as f:
        f.write('* Blocking issues (stable):\n\n')
        output_issues_for_email(
            f, blockers, lambda x: 'ubuntu-rtm' in x['target'])

        f.write('\n* Blocking issues (devel):\n\n')
        output_issues_for_email(
            f, blockers, lambda x: 'ubuntu' in x['target'])

        f.write('\n\n* Issues in need of attention:\n\n')
        output_issues_for_email(f, observed, lambda x: True)


def check_if_not_closed(task):
    return (task.status not in (
        'Fix Released', 'Invalid', 'Won\'t Fix', 'Incomplete'))


if __name__ == '__main__':
    get_launchpad()
    issues = []
    tasks = lp.load(
        'https://api.launchpad.net/devel/~landing-team-trackers').searchTasks()

    dt = datetime.datetime(1, 1, 1)
    already_bugs = []

    for task in tasks:
        bug = task.bug

        if bug.id in already_bugs:
            continue
        already_bugs.append(bug.id)

        issue = {}
        issue['name'] = bug.title
        issue['priority'] = 'high'  # Default to medium
        issue['bug_number'] = bug.id
        issue['bug_link'] = bug.web_link
        issue['category'] = None
        issue['age'] = -1
        issue['status'] = {}
        issue['target'] = []
        issue['pt_priority'] = ""
        issue['pt_milestone'] = ""

        # Classes: lt-blocker lt-important
        # Priority: lt-prio-high lt-prio-medium lt-prio-low
        # Others: lt-whitelisted

        # Tags example: lt-date-20140717 lt-category-visible lt-prio-high

        for tag in bug.tags:
            # Check the age of the bug
            if tag.startswith('lt-date-'):
                date = tag[8:]
                start = dt.strptime(date, "%Y%m%d").date()
                now = dt.now().date()
                daydiff = now.weekday() - start.weekday()
                days = ((now - start).days - daydiff) / 7 * 5 + min(daydiff, 5)
                issue['age'] = days
            # Check bug category (e.g. user visible etc.)
            elif tag == 'lt-important':
                issue['category'] = "important"
            # Check bug priority
            elif tag.startswith('lt-prio-'):
                issue['priority'] = tag[8:]
            # Look for the blocker tag
            elif tag == 'lt-blocker':
                issue['category'] = "blocker"
            elif tag == 'lt-whitelisted':
                issue['whitelisted'] = True

        if not issue['category']:
            continue

        pt_task = next((t for t in bug.bug_tasks_collection if
                        t.bug_target_name == 'canonical-devices-system-image'),
                       None)
        if pt_task:
            # This bug has been recorded by the product team
            issue['pt_priority'] = pt_task.importance
            if pt_task.milestone:
                issue['pt_milestone'] = pt_task.milestone.name
            if (check_if_not_closed(pt_task) and pt_task.status != "Fix Committed"):
                issue['target'].append('ubuntu-rtm')

        for task in bug.bug_tasks_collection:
            issue['status'][task.bug_target_name] = task.status

            if (not pt_task and
                    'ubuntu-rtm' not in issue['target'] and
                    'Ubuntu RTM' in task.bug_target_name):
                print('Huh?')
                if (check_if_not_closed(task)):
                    print('WTF?')
                    issue['target'].append('ubuntu-rtm')
            elif ('ubuntu' not in issue['target'] and
                    '(Ubuntu)' in task.bug_target_name):
                if (check_if_not_closed(task)):
                    issue['target'].append('ubuntu')

        if not issue['target']:
            issue['target'].append('ubuntu')

        # Fetch custom landing-team comments (for now locally stored)
        comment_path = '{}_comments'.format(issue['bug_number'])
        issue['comments'] = ""
        if os.path.isfile(comment_path):
            with open(comment_path, 'r') as f:
                issue['comments'] = f.read()

        # Check if any comments were added
        if bug.message_count > 0:
            message = bug.messages_collection[bug.message_count - 1]
            comment = {
                'link': message.web_link,
                'date': message.date_created.isoformat(),
                'author': message.owner.name,
                'content': message.content
                }
            issue['last_comment'] = comment

        # TODO: List the current project status

        # Check if MRs are added, add information about them
        merges = []
        for branch in bug.linked_branches_collection:
            mps = branch.branch.landing_targets_collection
            for mp in mps:
                proposal = {
                    'link': mp.web_link,
                    'branch': branch.branch.bzr_identity,
                    'status': mp.queue_status
                    }
                merges.append(proposal)
        issue['mps'] = merges

        issues.append(issue)

    output_for_email('landing-email', issues)
    status_file = 'status.json'
    new_file = '{}.new'.format(status_file)
    json.dump({'issues': issues}, open(new_file, 'w'))
    os.rename(new_file, status_file)