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

fedora-llvm-team / llvm-snapshots / 13502145680

24 Feb 2025 03:52PM UTC coverage: 39.557% (-0.03%) from 39.589%
13502145680

Pull #1102

github

web-flow
Merge 0a8cf0223 into c9663040e
Pull Request #1102: [workflows] reorg

10173 of 25717 relevant lines covered (39.56%)

0.4 hits per line

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

99.12
/snapshot_manager/snapshot_manager/github_util.py
1
"""
2
github_util
3
"""
4

5
import datetime
1✔
6
import enum
1✔
7
import logging
1✔
8
import os
1✔
9
import pathlib
1✔
10
import typing
1✔
11

12
import fnc
1✔
13
import github
1✔
14
import github.GithubException
1✔
15
import github.Issue
1✔
16
import github.IssueComment
1✔
17
import github.Label
1✔
18
import github.PaginatedList
1✔
19
import github.Repository
1✔
20

21
import snapshot_manager.build_status as build_status
1✔
22
import snapshot_manager.config as config
1✔
23
import snapshot_manager.github_graphql as github_graphql
1✔
24
import snapshot_manager.util as util
1✔
25

26

27
@enum.unique
1✔
28
class Reaction(enum.StrEnum):
1✔
29
    """An enum to represent the possible comment reactions"""
30

31
    THUMBS_UP = "THUMBS_UP"  # Represents the :+1: emoji.
1✔
32
    THUMBS_DOWN = "THUMBS_DOWN"  # Represents the :-1: emoji.
1✔
33
    LAUGH = "LAUGH"  # Represents the :laugh: emoji.
1✔
34
    HOORAY = "HOORAY"  # Represents the :hooray: emoji.
1✔
35
    CONFUSED = "CONFUSED"  # Represents the :confused: emoji.
1✔
36
    HEART = "HEART"  # Represents the :heart: emoji.
1✔
37
    ROCKET = "ROCKET"  # Represents the :rocket: emoji.
1✔
38
    EYES = "EYES"  # Represents the :eyes: emoji.
1✔
39

40

41
class MissingToken(Exception):
1✔
42
    """Could not retrieve a Github token."""
43

44

45
class GithubClient:
1✔
46
    dirname = pathlib.Path(os.path.dirname(__file__))
1✔
47

48
    def __init__(self, config: config.Config, github_token: str = None, **kwargs):
1✔
49
        """
50
        Keyword Arguments:
51
            github_token (str, optional): github personal access token.
52
        """
53
        self.config = config
1✔
54
        if github_token is None:
1✔
55
            logging.info(
1✔
56
                f"Reading Github token from this environment variable: {self.config.github_token_env}"
57
            )
58
            github_token = os.getenv(self.config.github_token_env)
1✔
59
        if github_token is None or len(github_token) == 0:
1✔
60
            # We can't proceed without a Github token, otherwise we'll trigger
61
            # an assertion failure.
62
            raise MissingToken("Could not retrieve the token")
1✔
63
        auth = github.Auth.Token(github_token)
1✔
64
        self.github = github.Github(auth=auth)
1✔
65
        self.gql = github_graphql.GithubGraphQL(token=github_token, raise_on_error=True)
1✔
66
        self._label_cache = None
1✔
67
        self.__repo_cache = None
1✔
68

69
    @classmethod
1✔
70
    def abspath(cls, p: tuple[str, pathlib.Path]) -> pathlib.Path:
1✔
71
        return cls.dirname.joinpath(p)
1✔
72

73
    @property
1✔
74
    def gh_repo(self) -> github.Repository.Repository:
1✔
75
        if self.__repo_cache is None:
1✔
76
            self.__repo_cache = self.github.get_repo(self.config.github_repo)
1✔
77
        return self.__repo_cache
1✔
78

79
    def get_todays_github_issue(
1✔
80
        self,
81
        strategy: str,
82
        creator: str = "github-actions[bot]",
83
        github_repo: str | None = None,
84
    ) -> github.Issue.Issue | None:
85
        """Returns the github issue (if any) for today's snapshot that was build with the given strategy.
86

87
        If no issue was found, `None` is returned.
88

89
        Args:
90
            strategy (str): The build strategy to pick (e.g. "standalone", "big-merge").
91
            creator (str|None, optional): The author who should have created the issue. Defaults to github-actions[bot]
92
            repo (str|None, optional): The repo to use. This is only useful for testing purposes. Defaults to None which will result in whatever the github_repo property has.
93

94
        Raises:
95
            ValueError if the strategy is empty
96

97
        Returns:
98
            github.Issue.Issue|None: The found issue or None.
99
        """
100
        if not strategy:
1✔
101
            raise ValueError("parameter 'strategy' must not be empty")
1✔
102

103
        if github_repo is None:
1✔
104
            github_repo = self.config.github_repo
1✔
105

106
        # See https://docs.github.com/en/search-github/searching-on-github/searching-issues-and-pull-requests
107
        # label:broken_snapshot_detected
108
        query = f"is:issue repo:{github_repo} author:{creator} label:strategy/{strategy} {self.config.yyyymmdd} in:title"
1✔
109
        issues = self.github.search_issues(query)
1✔
110
        if issues is not None and issues.totalCount > 0:
1✔
111
            logging.info(
×
112
                f"Found today's ({self.config.yyyymmdd}) issue: {issues[0].html_url}"
113
            )
114
            return issues[0]
×
115
        logging.info(f"Found no issue for today ({self.config.yyyymmdd})")
1✔
116
        return None
1✔
117

118
    @property
1✔
119
    def initial_comment(self) -> str:
1✔
120
        llvm_release = util.get_release_for_yyyymmdd(self.config.yyyymmdd)
1✔
121
        llvm_git_revision = util.get_git_revision_for_yyyymmdd(self.config.yyyymmdd)
1✔
122
        return f"""
1✔
123
<p>
124
This issue exists to let you know that we are about to monitor the builds
125
of the LLVM (v{llvm_release}, <a href="https://github.com/llvm/llvm-project/commit/{llvm_git_revision}">llvm/llvm-project@ {llvm_git_revision[:7]}</a>) snapshot for <a href="{self.config.copr_monitor_url}">{self.config.yyyymmdd}</a>.
126
<details>
127
<summary>At certain intervals the CI system will update this very comment over time to reflect the progress of builds.</summary>
128
<dl>
129
<dt>Log analysis</dt>
130
<dd>For example if a build fails on the <code>fedora-rawhide-x86_64</code> platform,
131
we'll analyze the build log (if any) to identify the cause of the failure. The cause can be any of <code>{build_status.ErrorCause.list()}</code>.
132
For each cause we will list the packages and the relevant log excerpts.</dd>
133
<dt>Use of labels</dt>
134
<dd>Let's assume a unit test test in upstream LLVM was broken.
135
We will then add these labels to this issue: <code>error/test</code>, <code>build_failed_on/fedora-rawhide-x86_64</code>.
136
If you manually restart a build in Copr and can bring it to a successful state, we will automatically
137
remove the aforementioned labels.
138
</dd>
139
</dl>
140
</details>
141
</p>
142

143
{self.config.update_marker}
144

145
{self.last_updated_html()}
146
"""
147

148
    @classmethod
1✔
149
    def last_updated_html(cls) -> str:
1✔
150
        return f"<p><b>Last updated: {datetime.datetime.now().isoformat()}</b></p>"
1✔
151

152
    def issue_title(self, strategy: str = None, yyyymmdd: str = None) -> str:
1✔
153
        """Constructs the issue title we want to use"""
154
        if strategy is None:
1✔
155
            strategy = self.config.build_strategy
1✔
156
        if yyyymmdd is None:
1✔
157
            yyyymmdd = self.config.yyyymmdd
1✔
158
        llvm_release = util.get_release_for_yyyymmdd(yyyymmdd)
1✔
159
        llvm_git_revision = util.get_git_revision_for_yyyymmdd(yyyymmdd)
1✔
160
        return f"Snapshot for {yyyymmdd}, v{llvm_release}, {llvm_git_revision[:7]} ({strategy})"
1✔
161

162
    def create_or_get_todays_github_issue(
1✔
163
        self,
164
        creator: str = "github-actions[bot]",
165
    ) -> tuple[github.Issue.Issue, bool]:
166
        issue = self.get_todays_github_issue(
1✔
167
            strategy=self.config.build_strategy,
168
            creator=creator,
169
            github_repo=self.config.github_repo,
170
        )
171
        if issue is not None:
1✔
172
            return (issue, False)
1✔
173

174
        strategy = self.config.build_strategy
1✔
175
        logging.info("Creating issue for today")
1✔
176

177
        issue = self.gh_repo.create_issue(
1✔
178
            title=self.issue_title(), body=self.initial_comment
179
        )
180
        self.create_labels_for_strategies(labels=[strategy])
1✔
181

182
        issue.add_to_labels(f"strategy/{strategy}")
1✔
183
        return (issue, True)
1✔
184

185
    @property
1✔
186
    def label_cache(self, refresh: bool = False) -> github.PaginatedList.PaginatedList:
1✔
187
        """Will query the labels of a github repo only once and return it afterwards.
188

189
        Args:
190
            refresh (bool, optional): The cache will be emptied. Defaults to False.
191

192
        Returns:
193
            github.PaginatedList.PaginatedList: An enumerable list of github.Label.Label objects
194
        """
195
        if self._label_cache is None or refresh:
1✔
196
            self._label_cache = self.gh_repo.get_labels()
1✔
197
        return self._label_cache
1✔
198

199
    def is_label_in_cache(self, name: str, color: str) -> bool:
1✔
200
        """Returns True if the label exists in the cache.
201

202
        Args:
203
            name (str): Name of the label to look for
204
            color (str): Color string of the label to look for
205

206
        Returns:
207
            bool: True if the label is in the cache
208
        """
209
        for label in self.label_cache:
1✔
210
            if label.name == name and label.color == color:
1✔
211
                return True
1✔
212
        return False
1✔
213

214
    def create_labels(
1✔
215
        self,
216
        prefix: str,
217
        color: str,
218
        labels: list[str] = [],
219
    ) -> list[github.Label.Label]:
220
        """Iterates over the given labels and creates or edits each label in the list
221
        with the given prefix and color."""
222
        if labels is None or len(labels) == 0:
1✔
223
            return None
1✔
224

225
        labels = set(labels)
1✔
226
        labels = list(labels)
1✔
227
        labels.sort()
1✔
228
        res = []
1✔
229
        for label in labels:
1✔
230
            labelname = label
1✔
231
            if not labelname.startswith(prefix):
1✔
232
                labelname = f"{prefix}{label}"
1✔
233
            if self.is_label_in_cache(name=labelname, color=color):
1✔
234
                continue
1✔
235
            logging.info(
1✔
236
                f"Creating label: repo={self.config.github_repo} name={labelname} color={color}",
237
            )
238
            try:
1✔
239
                res.append(self.gh_repo.create_label(color=color, name=labelname))
1✔
240
            except:
1✔
241
                self.gh_repo.get_label(name=labelname).edit(
1✔
242
                    name=labelname, color=color, description=""
243
                )
244
        return res
1✔
245

246
    @classmethod
1✔
247
    def get_label_names_on_issue(
1✔
248
        cls, issue: github.Issue.Issue, prefix: str
249
    ) -> list[str]:
250
        return [
1✔
251
            label.name for label in issue.get_labels() if label.name.startswith(prefix)
252
        ]
253

254
    @classmethod
1✔
255
    def get_error_label_names_on_issue(cls, issue: github.Issue.Issue) -> list[str]:
1✔
256
        return cls.get_label_names_on_issue(issue, prefix="error/")
1✔
257

258
    @classmethod
1✔
259
    def get_build_failed_on_names_on_issue(cls, issue: github.Issue.Issue) -> list[str]:
1✔
260
        return cls.get_label_names_on_issue(issue, prefix="build_failed_on/")
1✔
261

262
    def create_labels_for_error_causes(
1✔
263
        self, labels: list[str], **kw_args
264
    ) -> list[github.Label.Label]:
265
        return self.create_labels(
1✔
266
            labels=labels, prefix="error/", color="FBCA04", **kw_args
267
        )
268

269
    def create_labels_for_build_failed_on(
1✔
270
        self, labels: list[str], **kw_args
271
    ) -> list[github.Label.Label]:
272
        return self.create_labels(
1✔
273
            labels=labels, prefix="build_failed_on/", color="F9D0C4", **kw_args
274
        )
275

276
    def create_labels_for_strategies(
1✔
277
        self, labels: list[str], **kw_args
278
    ) -> list[github.Label.Label]:
279
        return self.create_labels(
1✔
280
            labels=labels, prefix="strategy/", color="FFFFFF", *kw_args
281
        )
282

283
    def create_labels_for_in_testing(
1✔
284
        self, labels: list[str], **kw_args
285
    ) -> list[github.Label.Label]:
286
        return self.create_labels(
1✔
287
            labels=labels,
288
            prefix=self.config.label_prefix_in_testing,
289
            color="FEF2C0",
290
            *kw_args,
291
        )
292

293
    def create_labels_for_tested_on(
1✔
294
        self, labels: list[str], **kw_args
295
    ) -> list[github.Label.Label]:
296
        return self.create_labels(
1✔
297
            labels=labels,
298
            prefix=self.config.label_prefix_tested_on,
299
            color="0E8A16",
300
            *kw_args,
301
        )
302

303
    def create_labels_for_tests_failed_on(
1✔
304
        self, labels: list[str], **kw_args
305
    ) -> list[github.Label.Label]:
306
        return self.create_labels(
1✔
307
            labels=labels,
308
            prefix=self.config.label_prefix_tests_failed_on,
309
            color="D93F0B",
310
            *kw_args,
311
        )
312

313
    def create_labels_for_llvm_releases(
1✔
314
        self, labels: list[str], **kw_args
315
    ) -> list[github.Label.Label]:
316
        return self.create_labels(
1✔
317
            labels=labels,
318
            prefix=self.config.label_prefix_llvm_release,
319
            color="2F3950",
320
            *kw_args,
321
        )
322

323
    @classmethod
1✔
324
    def get_comment(
1✔
325
        cls, issue: github.Issue.Issue, marker: str
326
    ) -> github.IssueComment.IssueComment:
327
        """Walks through all comments associated with the `issue` and returns the first one that has the `marker` in its body.
328

329
        Args:
330
            issue (github.Issue.Issue): The github issue to look for
331
            marker (str): The text to look for in the comment's body. (e.g. `"<!--MY MARKER-->"`)
332

333
        Returns:
334
            github.IssueComment.IssueComment: The comment containing the marker or `None`.
335
        """
336
        for comment in issue.get_comments():
1✔
337
            if marker in comment.body:
1✔
338
                return comment
1✔
339
        return None
1✔
340

341
    @classmethod
1✔
342
    def create_or_update_comment(
1✔
343
        cls, issue: github.Issue.Issue, marker: str, comment_body: str
344
    ) -> github.IssueComment.IssueComment:
345
        comment = cls.get_comment(issue=issue, marker=marker)
1✔
346
        if comment is None:
1✔
347
            return issue.create_comment(body=comment_body)
1✔
348
        try:
1✔
349
            comment.edit(body=comment_body)
1✔
350
        except github.GithubException as ex:
1✔
351
            raise ValueError(
1✔
352
                f"Failed to update github comment with marker {marker} and comment body: {comment_body}"
353
            ) from ex
354
        return comment
1✔
355

356
    @classmethod
1✔
357
    def remove_labels_safe(
1✔
358
        cls, issue: github.Issue.Issue, label_names_to_be_removed: list[str]
359
    ):
360
        """Removes all of the given labels from the issue.
361

362
        Args:
363
            issue (github.Issue.Issue): The issue from which to remove the labels
364
            label_names_to_be_removed (list[str]): A list of label names that shall be removed if they exist on the issue.
365
        """
366
        current_set = {label.name for label in issue.get_labels()}
1✔
367

368
        remove_set = set(label_names_to_be_removed)
1✔
369
        intersection = current_set.intersection(remove_set)
1✔
370
        for label in intersection:
1✔
371
            logging.info(f"Removing label '{label}' from issue: {issue.title}")
1✔
372
            issue.remove_from_labels(label)
1✔
373

374
    @typing.overload
1✔
375
    def minimize_comment_as_outdated(
1✔
376
        self, comment: github.IssueComment.IssueComment
377
    ) -> bool: ...
378

379
    @typing.overload
1✔
380
    def minimize_comment_as_outdated(self, node_id: str) -> bool: ...
1✔
381

382
    def minimize_comment_as_outdated(
1✔
383
        self,
384
        object: str | github.IssueComment.IssueComment,
385
    ) -> bool:
386
        """Minimizes a comment identified by the `object` argument with the reason `OUTDATED`.
387

388
        Args:
389
            object (str | github.IssueComment.IssueComment): The comment to minimize
390

391
        Raises:
392
            ValueError: If the `object` has a wrong type.
393

394
        Returns:
395
            bool: True if the comment was properly minimized.
396
        """
397
        node_id = ""
1✔
398
        if isinstance(object, github.IssueComment.IssueComment):
1✔
399
            node_id = object.raw_data["node_id"]
1✔
400
        elif isinstance(object, str):
1✔
401
            node_id = object
1✔
402
        else:
403
            raise ValueError(f"invalid comment object passed: {object}")
1✔
404

405
        res = self.gql.run_from_file(
1✔
406
            variables={
407
                "classifier": "OUTDATED",
408
                "id": node_id,
409
            },
410
            filename=self.abspath("graphql/minimize_comment.gql"),
411
        )
412

413
        return bool(
1✔
414
            fnc.get(
415
                "data.minimizeComment.minimizedComment.isMinimized", res, default=False
416
            )
417
        )
418

419
    @typing.overload
1✔
420
    def unminimize_comment(self, comment: github.IssueComment.IssueComment) -> bool: ...
1✔
421

422
    @typing.overload
1✔
423
    def unminimize_comment(self, node_id: str) -> bool: ...
1✔
424

425
    def unminimize_comment(
1✔
426
        self,
427
        object: str | github.IssueComment.IssueComment,
428
    ) -> bool:
429
        """Unminimizes a comment with the given `node_id`.
430

431
        Args:
432
            node_id (str): A comment's `node_id`.
433

434
        Returns:
435
            bool: True if the comment was unminimized
436
        """
437

438
        node_id = ""
1✔
439
        if isinstance(object, github.IssueComment.IssueComment):
1✔
440
            node_id = object.raw_data["node_id"]
1✔
441
        elif isinstance(object, str):
1✔
442
            node_id = object
1✔
443
        else:
444
            raise ValueError(f"invalid comment object passed: {object}")
1✔
445

446
        res = self.gql.run_from_file(
1✔
447
            variables={
448
                "id": node_id,
449
            },
450
            filename=self.abspath("graphql/unminimize_comment.gql"),
451
        )
452

453
        is_minimized = fnc.get(
1✔
454
            "data.unminimizeComment.unminimizedComment.isMinimized", res, default=True
455
        )
456
        return not is_minimized
1✔
457

458
    @typing.overload
1✔
459
    def add_comment_reaction(
1✔
460
        self, comment: github.IssueComment.IssueComment, reaction: Reaction
461
    ) -> bool: ...
462

463
    @typing.overload
1✔
464
    def add_comment_reaction(self, node_id: str, reaction: Reaction) -> bool: ...
1✔
465

466
    def add_comment_reaction(
1✔
467
        self,
468
        object: str | github.IssueComment.IssueComment,
469
        reaction: Reaction,
470
    ) -> bool:
471
        """Adds a reaction to a comment with the given emoji name
472

473
        Args:
474
            object (str | github.IssueComment.IssueComment): The comment object or node ID to add reaction to.
475
            reaction (Reaction): The name of the reaction.
476

477
        Raises:
478
            ValueError: If the the `object` has a wrong type.
479

480
        Returns:
481
            bool: True if the comment reaction was added successfully.
482
        """
483
        node_id = ""
1✔
484
        if isinstance(object, github.IssueComment.IssueComment):
1✔
485
            node_id = object.raw_data["node_id"]
1✔
486
        elif isinstance(object, str):
1✔
487
            node_id = object
1✔
488
        else:
489
            raise ValueError(f"invalid comment object passed: {object}")
1✔
490

491
        res = self.gql.run_from_file(
1✔
492
            variables={
493
                "comment_id": node_id,
494
                "reaction": reaction,
495
            },
496
            filename=self.abspath("graphql/add_comment_reaction.gql"),
497
        )
498

499
        actual_reaction = fnc.get(
1✔
500
            "data.addReaction.reaction.content", res, default=None
501
        )
502
        actual_comment_id = fnc.get("data.addReaction.subject.id", res, default=None)
1✔
503

504
        return actual_reaction == str(reaction) and actual_comment_id == node_id
1✔
505

506
    def label_in_testing(self, chroot: str) -> str:
1✔
507
        return f"{self.config.label_prefix_in_testing}{chroot}"
1✔
508

509
    def label_failed_on(self, chroot: str) -> str:
1✔
510
        return f"{self.config.label_prefix_tests_failed_on}{chroot}"
1✔
511

512
    def label_tested_on(self, chroot: str) -> str:
1✔
513
        return f"{self.config.label_prefix_tested_on}{chroot}"
1✔
514

515
    def flip_test_label(
1✔
516
        self, issue: github.Issue.Issue, chroot: str, new_label: str | None
517
    ):
518
        """Let's you change the label on an issue for a specific chroot.
519

520
         If `new_label` is `None`, then all test labels will be removed.
521

522
        Args:
523
            issue (github.Issue.Issue): The issue to modify
524
            chroot (str): The chroot for which you want to flip the test label
525
            new_label (str | None): The new label or `None`.
526
        """
527
        in_testing = self.label_in_testing(chroot)
1✔
528
        tested_on = self.label_tested_on(chroot)
1✔
529
        failed_on = self.label_failed_on(chroot)
1✔
530

531
        all_states = [in_testing, tested_on, failed_on]
1✔
532
        existing_test_labels = [
1✔
533
            label.name for label in issue.get_labels() if label.name in all_states
534
        ]
535

536
        new_label_already_present = False
1✔
537
        for label in existing_test_labels:
1✔
538
            if label != new_label:
1✔
539
                issue.remove_from_labels(label)
1✔
540
            else:
541
                new_label_already_present = True
1✔
542

543
        if not new_label_already_present:
1✔
544
            if new_label is not None:
1✔
545
                issue.add_to_labels(new_label)
1✔
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

© 2026 Coveralls, Inc