• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla / relman-auto-nag / #5166

16 Jul 2024 07:39PM CUT coverage: 21.857% (-0.03%) from 21.886%
#5166

push

coveralls-python

benjaminmah
Added Phabricator changes

716 of 3606 branches covered (19.86%)

0 of 12 new or added lines in 1 file covered. (0.0%)

2 existing lines in 1 file now uncovered.

1933 of 8844 relevant lines covered (21.86%)

0.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/bugbot/rules/not_landed.py
1
# This Source Code Form is subject to the terms of the Mozilla Public
2
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
# You can obtain one at http://mozilla.org/MPL/2.0/.
4

5
import base64
×
6
import random
×
7
import re
×
8

9
from libmozdata import utils as lmdutils
×
10
from libmozdata.bugzilla import Bugzilla, BugzillaUser
×
11
from libmozdata.phabricator import (
×
12
    PhabricatorAPI,
13
    PhabricatorBzNotFoundException,
14
    PhabricatorRevisionNotFoundException,
15
)
16

17
from bugbot import utils
×
18
from bugbot.bzcleaner import BzCleaner
×
19

20
PHAB_URL_PAT = re.compile(r"https://phabricator\.services\.mozilla\.com/D([0-9]+)")
×
21

22

23
class NotLanded(BzCleaner):
×
24
    def __init__(self):
×
25
        super(NotLanded, self).__init__()
×
26
        self.nweeks = utils.get_config(self.name(), "number_of_weeks", 2)
×
27
        self.nyears = utils.get_config(self.name(), "number_of_years", 2)
×
28
        self.phab = PhabricatorAPI(utils.get_login_info()["phab_api_key"])
×
29
        self.extra_ni = {}
×
30

31
    def description(self):
×
32
        return "Open bugs with no activity for {} weeks and a r+ patch which hasn't landed".format(
×
33
            self.nweeks
34
        )
35

36
    def has_assignee(self):
×
37
        return True
×
38

39
    def get_extra_for_template(self):
×
40
        return {"nweeks": self.nweeks}
×
41

42
    def get_extra_for_needinfo_template(self):
×
43
        self.extra_ni.update(self.get_extra_for_template())
×
44
        return self.extra_ni
×
45

46
    def columns(self):
×
47
        return ["id", "summary", "assignee"]
×
48

49
    def handle_bug(self, bug, data):
×
50
        if self.has_bot_set_ni(bug):
×
51
            return None
×
52

53
        bugid = str(bug["id"])
×
54
        assignee = bug.get("assigned_to", "")
×
55
        if utils.is_no_assignee(assignee):
×
56
            assignee = ""
×
57
            nickname = ""
×
58
        else:
59
            nickname = bug["assigned_to_detail"]["nick"]
×
60

61
        data[bugid] = {
×
62
            "assigned_to": assignee,
63
            "nickname": nickname,
64
            "deps": set(bug["depends_on"]),
65
        }
66

67
        return bug
×
68

NEW
69
    def update_revision_status(self, rev_id, status_type, value):
×
NEW
70
        try:
×
NEW
71
            self.phab.request(
×
72
                "differential.revision.edit",
73
                objectIdentifier=rev_id,
74
                transactions=[{"type": status_type, "value": value}],
75
            )
NEW
76
            print(
×
77
                f"Successfully updated revision {rev_id} with {status_type} to {value}"
78
            )
NEW
79
        except Exception as e:
×
NEW
80
            print(
×
81
                f"Failed to update revision {rev_id} with {status_type} to {value}: {e}"
82
            )
83

UNCOV
84
    def filter_bugs(self, bugs):
×
85
        # We must remove bugs which have open dependencies (except meta bugs)
86
        # because devs may wait for those bugs to be fixed before their patch
87
        # can land.
88

89
        all_deps = set(dep for info in bugs.values() for dep in info["deps"])
×
90

91
        def bug_handler(bug, data):
×
92
            if (
×
93
                bug["status"] in {"RESOLVED", "VERIFIED", "CLOSED"}
94
                or "meta" in bug["keywords"]
95
            ):
96
                data.add(bug["id"])
×
97

98
        useless = set()
×
99
        Bugzilla(
×
100
            bugids=list(all_deps),
101
            include_fields=["id", "keywords", "status"],
102
            bughandler=bug_handler,
103
            bugdata=useless,
104
        ).get_data().wait()
105

106
        for bugid, info in bugs.items():
×
107
            # finally deps will contain open bugs which are not meta
108
            info["deps"] -= useless
×
109

110
        # keep bugs with no deps
111
        bugs = {bugid: info for bugid, info in bugs.items() if not info["deps"]}
×
112

113
        return bugs
×
114

115
    def check_phab(self, attachment, reviewers_phid):
×
116
        """Check if the patch in Phabricator has been r+"""
117
        if attachment["is_obsolete"] == 1:
×
118
            return None
×
119

120
        phab_url = base64.b64decode(attachment["data"]).decode("utf-8")
×
121

122
        # extract the revision
123
        rev = PHAB_URL_PAT.search(phab_url).group(1)
×
124
        try:
×
125
            data = self.phab.load_revision(
×
126
                rev_id=int(rev), queryKey="all", attachments={"reviewers": 1}
127
            )
128
        except PhabricatorRevisionNotFoundException:
×
129
            return None
×
130

131
        # this is a timestamp
132
        last_modified = data["fields"]["dateModified"]
×
133
        last_modified = lmdutils.get_date_from_timestamp(last_modified)
×
134
        if (self.date - last_modified).days <= self.nweeks * 7:
×
135
            # Do not do anything if recent changes in the bug
136
            return False
×
137

138
        reviewers = data["attachments"]["reviewers"]["reviewers"]
×
139

140
        if not reviewers:
×
141
            return False
×
142

143
        for reviewer in reviewers:
×
144
            if reviewer["status"] != "accepted":
×
145
                return False
×
146
            reviewers_phid.add(reviewer["reviewerPHID"])
×
147

148
        value = data["fields"]["status"].get("value", "")
×
149
        if value == "changes-planned":
×
150
            # even if the patch is r+ and not published, some changes may be required
151
            # so with the value 'changes-planned', the dev can say it's still a wip
152
            return False
×
153

154
        if value != "published":
×
155
            return True
×
156

157
        return False
×
158

159
    def handle_attachment(self, attachment, res):
×
160
        ct = attachment["content_type"]
×
161
        c = None
×
162
        if ct == "text/x-phabricator-request":
×
163
            if "phab" not in res or res["phab"]:
×
164
                c = self.check_phab(attachment, res["reviewers_phid"])
×
165
                if c is not None:
×
166
                    res["phab"] = c
×
167

168
        if c is not None:
×
169
            attacher = attachment["creator"]
×
170
            if "author" in res:
×
171
                if attacher in res["author"]:
×
172
                    res["author"][attacher] += 1
×
173
                else:
174
                    res["author"][attacher] = 1
×
175
            else:
176
                res["author"] = {attacher: 1}
×
177

178
            if "count" in res:
×
179
                res["count"] += 1
×
180
            else:
181
                res["count"] = 1
×
182

183
    def get_patch_data(self, bugs):
×
184
        """Get patch information in bugs"""
185
        nightly_pat = Bugzilla.get_landing_patterns(channels=["nightly"])[0][0]
×
186

187
        def comment_handler(bug, bugid, data):
×
188
            # if a comment contains a backout: don't nag
189
            for comment in bug["comments"]:
×
190
                comment = comment["text"].lower()
×
191
                if nightly_pat.match(comment) and (
×
192
                    "backed out" in comment or "backout" in comment
193
                ):
194
                    data[bugid]["backout"] = True
×
195

196
        def attachment_id_handler(attachments, bugid, data):
×
197
            for a in attachments:
×
198
                if (
×
199
                    a["content_type"] == "text/x-phabricator-request"
200
                    and a["is_obsolete"] == 0
201
                ):
202
                    data.append(a["id"])
×
203

204
        def attachment_handler(attachments, data):
×
205
            for attachment in attachments:
×
206
                bugid = str(attachment["bug_id"])
×
207
                if bugid in data:
×
208
                    data[bugid].append(attachment)
×
209
                else:
210
                    data[bugid] = [attachment]
×
211

212
        bugids = list(bugs.keys())
×
213
        data = {
×
214
            bugid: {"backout": False, "author": None, "count": 0} for bugid in bugids
215
        }
216

217
        # Get the ids of the attachments of interest
218
        # to avoid to download images, videos, ...
219
        attachment_ids = []
×
220
        Bugzilla(
×
221
            bugids=bugids,
222
            attachmenthandler=attachment_id_handler,
223
            attachmentdata=attachment_ids,
224
            attachment_include_fields=["is_obsolete", "content_type", "id"],
225
        ).get_data().wait()
226

227
        # Once we've the ids we can get the data
228
        attachments_by_bug = {}
×
229
        Bugzilla(
×
230
            attachmentids=attachment_ids,
231
            attachmenthandler=attachment_handler,
232
            attachmentdata=attachments_by_bug,
233
            attachment_include_fields=[
234
                "bug_id",
235
                "data",
236
                "is_obsolete",
237
                "content_type",
238
                "id",
239
                "creator",
240
            ],
241
        ).get_data().wait()
242

243
        for bugid, attachments in attachments_by_bug.items():
×
244
            res = {"reviewers_phid": set()}
×
245
            for attachment in attachments:
×
246
                self.handle_attachment(attachment, res)
×
247

248
            if "phab" in res:
×
249
                if res["phab"]:
×
250
                    data[bugid]["reviewers_phid"] = res["reviewers_phid"]
×
251
                    data[bugid]["author"] = res["author"]
×
252
                    data[bugid]["count"] = res["count"]
×
253

254
        data = {bugid: v for bugid, v in data.items() if v["author"]}
×
255

256
        if not data:
×
257
            return data
×
258

259
        Bugzilla(
×
260
            bugids=list(data.keys()),
261
            commenthandler=comment_handler,
262
            commentdata=data,
263
            comment_include_fields=["text"],
264
        ).get_data().wait()
265

NEW
266
        for bugid, attachments in attachments_by_bug.items():
×
NEW
267
            if bugid in data:
×
NEW
268
                if data[bugid]["backout"]:
×
NEW
269
                    phab_url = base64.b64decode(attachment["data"]).decode("utf-8")
×
NEW
270
                    rev = PHAB_URL_PAT.search(phab_url).group(1)
×
NEW
271
                    self.update_revision_status(int(rev), "plan-changes", True)
×
272

UNCOV
273
        data = {bugid: v for bugid, v in data.items() if not v["backout"]}
×
274

275
        return data
×
276

277
    def get_bz_userid(self, phids):
×
278
        if not phids:
×
279
            return {}
×
280

281
        try:
×
282
            data = self.phab.load_bz_account(user_phids=list(phids))
×
283
            users = {x["phid"]: x["id"] for x in data}
×
284
        except PhabricatorBzNotFoundException:
×
285
            return {}
×
286

287
        def handler(user, data):
×
288
            data[str(user["id"])] = user["name"]
×
289

290
        data = {}
×
291
        BugzillaUser(
×
292
            user_names=list(users.values()),
293
            include_fields=["id", "name"],
294
            user_handler=handler,
295
            user_data=data,
296
        ).wait()
297

298
        return {phid: data[id] for phid, id in users.items()}
×
299

300
    def get_nicks(self, nicknames):
×
301
        def handler(user, data):
×
302
            data[user["name"]] = user["nick"]
×
303

304
        users = set(nicknames.values())
×
305
        data = {}
×
306
        if users:
×
307
            BugzillaUser(
×
308
                user_names=list(users),
309
                include_fields=["name", "nick"],
310
                user_handler=handler,
311
                user_data=data,
312
            ).wait()
313

314
        for bugid, name in nicknames.items():
×
315
            nicknames[bugid] = (name, data[name])
×
316

317
        return nicknames
×
318

319
    def get_bz_params(self, date):
×
320
        self.date = lmdutils.get_date_ymd(date)
×
321
        fields = ["flags", "depends_on"]
×
322
        params = {
×
323
            "include_fields": fields,
324
            "resolution": "---",
325
            "f1": "attachment.ispatch",
326
            "n2": 1,
327
            "f2": "attachments.isobsolete",
328
            "f3": "attachments.mimetype",
329
            "o3": "anywordssubstr",
330
            "v3": "text/x-phabricator-request",
331
            "f4": "creation_ts",
332
            "o4": "greaterthan",
333
            "v4": f"-{self.nyears}y",
334
            "f5": "days_elapsed",
335
            "o5": "greaterthaneq",
336
            "v5": self.nweeks * 7,
337
            "n6": 1,
338
            "f6": "longdesc",
339
            "o6": "casesubstring",
340
            "v6": "which didn't land and no activity in this bug for",
341
            "f7": "status_whiteboard",
342
            "o7": "notsubstring",
343
            "v7": "[reminder-test ",
344
        }
345

346
        return params
×
347

348
    def get_bugs(self, date="today", bug_ids=[]):
×
349
        bugs = super(NotLanded, self).get_bugs(date=date, bug_ids=bug_ids)
×
350
        bugs = self.filter_bugs(bugs)
×
351
        bugs_patch = self.get_patch_data(bugs)
×
352
        res = {}
×
353

354
        reviewers_phid = set()
×
355
        nicknames = {}
×
356
        for bugid, data in bugs_patch.items():
×
357
            reviewers_phid |= data["reviewers_phid"]
×
358
            assignee = bugs[bugid]["assigned_to"]
×
359
            if not assignee:
×
360
                assignee = max(data["author"], key=data["author"].get)
×
361
                nicknames[bugid] = assignee
×
362

363
        bz_reviewers = self.get_bz_userid(reviewers_phid)
×
364
        all_reviewers = set(bz_reviewers.keys())
×
365
        nicknames = self.get_nicks(nicknames)
×
366

367
        for bugid, data in bugs_patch.items():
×
368
            res[bugid] = d = bugs[bugid]
×
369
            self.extra_ni[bugid] = data["count"]
×
370
            assignee = d["assigned_to"]
×
371
            nickname = d["nickname"]
×
372

373
            if not assignee:
×
374
                assignee, nickname = nicknames[bugid]
×
375

376
            if not assignee:
×
377
                continue
×
378

379
            self.add_auto_ni(bugid, {"mail": assignee, "nickname": nickname})
×
380

381
            common = all_reviewers & data["reviewers_phid"]
×
382
            if common:
×
383
                reviewer = random.choice(list(common))
×
384
                self.add_auto_ni(
×
385
                    bugid, {"mail": bz_reviewers[reviewer], "nickname": None}
386
                )
387

388
        return res
×
389

390

391
if __name__ == "__main__":
×
392
    NotLanded().run()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc