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

mozilla / relman-auto-nag / #5034

24 May 2024 06:06PM CUT coverage: 21.862% (-0.01%) from 21.874%
#5034

push

coveralls-python

benjaminmah
Added check for dependencies in `get_bugs` to prevent setting needinfo

716 of 3604 branches covered (19.87%)

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

1 existing line in 1 file now uncovered.

1933 of 8842 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

69
    def filter_bugs(self, bugs):
×
70
        # We must remove bugs which have open dependencies (except meta bugs)
71
        # because devs may wait for those bugs to be fixed before their patch
72
        # can land.
73

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

76
        def bug_handler(bug, data):
×
77
            if (
×
78
                bug["status"] in {"RESOLVED", "VERIFIED", "CLOSED"}
79
                or "meta" in bug["keywords"]
80
            ):
81
                data.add(bug["id"])
×
82

83
        useless = set()
×
84
        Bugzilla(
×
85
            bugids=list(all_deps),
86
            include_fields=["id", "keywords", "status"],
87
            bughandler=bug_handler,
88
            bugdata=useless,
89
        ).get_data().wait()
90

91
        for bugid, info in bugs.items():
×
92
            # finally deps will contain open bugs which are not meta
93
            info["deps"] -= useless
×
94

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

98
        return bugs
×
99

100
    def check_phab(self, attachment, reviewers_phid):
×
101
        """Check if the patch in Phabricator has been r+"""
102
        if attachment["is_obsolete"] == 1:
×
103
            return None
×
104

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

107
        # extract the revision
108
        rev = PHAB_URL_PAT.search(phab_url).group(1)
×
109
        try:
×
110
            data = self.phab.load_revision(
×
111
                rev_id=int(rev), queryKey="all", attachments={"reviewers": 1}
112
            )
113
        except PhabricatorRevisionNotFoundException:
×
114
            return None
×
115

116
        # this is a timestamp
117
        last_modified = data["fields"]["dateModified"]
×
118
        last_modified = lmdutils.get_date_from_timestamp(last_modified)
×
119
        if (self.date - last_modified).days <= self.nweeks * 7:
×
120
            # Do not do anything if recent changes in the bug
121
            return False
×
122

123
        reviewers = data["attachments"]["reviewers"]["reviewers"]
×
124

125
        if not reviewers:
×
126
            return False
×
127

128
        # Check for dependencies in the stackGraph field
129
        stack_graph = data["fields"].get("stackGraph", {})
×
130
        current_revision_phid = data.get("phid")
×
131
        dependencies = stack_graph.get(current_revision_phid, [])
×
132

133
        if dependencies:
×
134
            return None
×
135

136
        for reviewer in reviewers:
×
137
            if reviewer["status"] != "accepted":
×
138
                return False
×
139
            reviewers_phid.add(reviewer["reviewerPHID"])
×
140

141
        value = data["fields"]["status"].get("value", "")
×
142
        if value == "changes-planned":
×
143
            # even if the patch is r+ and not published, some changes may be required
144
            # so with the value 'changes-planned', the dev can say it's still a wip
145
            return False
×
146

147
        if value != "published":
×
148
            return True
×
149

150
        return False
×
151

152
    def handle_attachment(self, attachment, res):
×
153
        ct = attachment["content_type"]
×
154
        c = None
×
155
        if ct == "text/x-phabricator-request":
×
156
            if "phab" not in res or res["phab"]:
×
157
                c = self.check_phab(attachment, res["reviewers_phid"])
×
158
                if c is not None:
×
159
                    res["phab"] = c
×
160

161
        if c is not None:
×
162
            attacher = attachment["creator"]
×
163
            if "author" in res:
×
164
                if attacher in res["author"]:
×
165
                    res["author"][attacher] += 1
×
166
                else:
167
                    res["author"][attacher] = 1
×
168
            else:
169
                res["author"] = {attacher: 1}
×
170

171
            if "count" in res:
×
172
                res["count"] += 1
×
173
            else:
174
                res["count"] = 1
×
175

176
    def get_patch_data(self, bugs):
×
177
        """Get patch information in bugs"""
178
        nightly_pat = Bugzilla.get_landing_patterns(channels=["nightly"])[0][0]
×
179

180
        def comment_handler(bug, bugid, data):
×
181
            # if a comment contains a backout: don't nag
182
            for comment in bug["comments"]:
×
183
                comment = comment["text"].lower()
×
184
                if nightly_pat.match(comment) and (
×
185
                    "backed out" in comment or "backout" in comment
186
                ):
187
                    data[bugid]["backout"] = True
×
188

189
        def attachment_id_handler(attachments, bugid, data):
×
190
            for a in attachments:
×
191
                if (
×
192
                    a["content_type"] == "text/x-phabricator-request"
193
                    and a["is_obsolete"] == 0
194
                ):
195
                    data.append(a["id"])
×
196

197
        def attachment_handler(attachments, data):
×
198
            for attachment in attachments:
×
199
                bugid = str(attachment["bug_id"])
×
200
                if bugid in data:
×
201
                    data[bugid].append(attachment)
×
202
                else:
203
                    data[bugid] = [attachment]
×
204

205
        bugids = list(bugs.keys())
×
206
        data = {
×
207
            bugid: {"backout": False, "author": None, "count": 0} for bugid in bugids
208
        }
209

210
        # Get the ids of the attachments of interest
211
        # to avoid to download images, videos, ...
212
        attachment_ids = []
×
213
        Bugzilla(
×
214
            bugids=bugids,
215
            attachmenthandler=attachment_id_handler,
216
            attachmentdata=attachment_ids,
217
            attachment_include_fields=["is_obsolete", "content_type", "id"],
218
        ).get_data().wait()
219

220
        # Once we've the ids we can get the data
221
        attachments_by_bug = {}
×
222
        Bugzilla(
×
223
            attachmentids=attachment_ids,
224
            attachmenthandler=attachment_handler,
225
            attachmentdata=attachments_by_bug,
226
            attachment_include_fields=[
227
                "bug_id",
228
                "data",
229
                "is_obsolete",
230
                "content_type",
231
                "id",
232
                "creator",
233
            ],
234
        ).get_data().wait()
235

236
        for bugid, attachments in attachments_by_bug.items():
×
237
            res = {"reviewers_phid": set()}
×
238
            for attachment in attachments:
×
239
                self.handle_attachment(attachment, res)
×
240

241
            if "phab" in res:
×
242
                if res["phab"]:
×
243
                    data[bugid]["reviewers_phid"] = res["reviewers_phid"]
×
244
                    data[bugid]["author"] = res["author"]
×
245
                    data[bugid]["count"] = res["count"]
×
246

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

249
        if not data:
×
250
            return data
×
251

252
        Bugzilla(
×
253
            bugids=list(data.keys()),
254
            commenthandler=comment_handler,
255
            commentdata=data,
256
            comment_include_fields=["text"],
257
        ).get_data().wait()
258

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

261
        return data
×
262

263
    def get_bz_userid(self, phids):
×
264
        if not phids:
×
265
            return {}
×
266

267
        try:
×
268
            data = self.phab.load_bz_account(user_phids=list(phids))
×
269
            users = {x["phid"]: x["id"] for x in data}
×
270
        except PhabricatorBzNotFoundException:
×
271
            return {}
×
272

273
        def handler(user, data):
×
274
            data[str(user["id"])] = user["name"]
×
275

276
        data = {}
×
277
        BugzillaUser(
×
278
            user_names=list(users.values()),
279
            include_fields=["id", "name"],
280
            user_handler=handler,
281
            user_data=data,
282
        ).wait()
283

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

286
    def get_nicks(self, nicknames):
×
287
        def handler(user, data):
×
288
            data[user["name"]] = user["nick"]
×
289

290
        users = set(nicknames.values())
×
291
        data = {}
×
292
        if users:
×
293
            BugzillaUser(
×
294
                user_names=list(users),
295
                include_fields=["name", "nick"],
296
                user_handler=handler,
297
                user_data=data,
298
            ).wait()
299

300
        for bugid, name in nicknames.items():
×
301
            nicknames[bugid] = (name, data[name])
×
302

303
        return nicknames
×
304

305
    def get_bz_params(self, date):
×
306
        self.date = lmdutils.get_date_ymd(date)
×
307
        fields = ["flags", "depends_on"]
×
308
        params = {
×
309
            "include_fields": fields,
310
            "resolution": "---",
311
            "f1": "attachment.ispatch",
312
            "n2": 1,
313
            "f2": "attachments.isobsolete",
314
            "f3": "attachments.mimetype",
315
            "o3": "anywordssubstr",
316
            "v3": "text/x-phabricator-request",
317
            "f4": "creation_ts",
318
            "o4": "greaterthan",
319
            "v4": f"-{self.nyears}y",
320
            "f5": "days_elapsed",
321
            "o5": "greaterthaneq",
322
            "v5": self.nweeks * 7,
323
            "n6": 1,
324
            "f6": "longdesc",
325
            "o6": "casesubstring",
326
            "v6": "which didn't land and no activity in this bug for",
327
            "f7": "status_whiteboard",
328
            "o7": "notsubstring",
329
            "v7": "[reminder-test ",
330
        }
331

332
        return params
×
333

334
    def get_bugs(self, date="today", bug_ids=[]):
×
335
        bugs = super(NotLanded, self).get_bugs(date=date, bug_ids=bug_ids)
×
336
        bugs = self.filter_bugs(bugs)
×
337
        bugs_patch = self.get_patch_data(bugs)
×
338
        res = {}
×
339

340
        reviewers_phid = set()
×
341
        nicknames = {}
×
342
        for bugid, data in bugs_patch.items():
×
343
            reviewers_phid |= data["reviewers_phid"]
×
344
            assignee = bugs[bugid]["assigned_to"]
×
345
            if not assignee:
×
346
                assignee = max(data["author"], key=data["author"].get)
×
347
                nicknames[bugid] = assignee
×
348

349
        bz_reviewers = self.get_bz_userid(reviewers_phid)
×
350
        all_reviewers = set(bz_reviewers.keys())
×
351
        nicknames = self.get_nicks(nicknames)
×
352

353
        for bugid, data in bugs_patch.items():
×
354
            res[bugid] = d = bugs[bugid]
×
355
            self.extra_ni[bugid] = data["count"]
×
356
            assignee = d["assigned_to"]
×
357
            nickname = d["nickname"]
×
358

359
            if not assignee:
×
360
                assignee, nickname = nicknames[bugid]
×
361

362
            if not assignee:
×
363
                continue
×
364

NEW
365
            stack_graph = data.get("stackGraph", {})
×
NEW
366
            current_revision_phid = data.get("phid")
×
NEW
367
            dependencies = stack_graph.get(current_revision_phid, [])
×
368

NEW
369
            if dependencies:
×
NEW
370
                continue
×
371

UNCOV
372
            self.add_auto_ni(bugid, {"mail": assignee, "nickname": nickname})
×
373

374
            common = all_reviewers & data["reviewers_phid"]
×
375
            if common:
×
376
                reviewer = random.choice(list(common))
×
377
                self.add_auto_ni(
×
378
                    bugid, {"mail": bz_reviewers[reviewer], "nickname": None}
379
                )
380

381
        return res
×
382

383

384
if __name__ == "__main__":
×
385
    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