You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@trafficcontrol.apache.org by GitBox <gi...@apache.org> on 2021/12/14 14:08:27 UTC
[GitHub] [trafficcontrol] zrhoffman opened a new pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
zrhoffman opened a new pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424
<!--
Thank you for contributing! Please be sure to read our contribution guidelines: https://github.com/apache/trafficcontrol/blob/master/CONTRIBUTING.md
If this closes or relates to an existing issue, please reference it using one of the following:
Closes: #ISSUE
Related: #ISSUE
If this PR fixes a security vulnerability, DO NOT submit! Instead, contact
the Apache Traffic Control Security Team at security@trafficcontrol.apache.org and follow the
guidelines at https://apache.org/security regarding vulnerability disclosure.
-->
This PR adds the *Assign Triage Role* GitHub Action, which
* Runs on the first day of every month
* Gathers a list of contributors without push access who have had 2 or more Issue-closing Pull Requests merged in the past 31 days
* Creates a Pull Request that summarizes their contributions, explains what ATC [collaborators](https://s.apache.org/asfyamltriage) are, and adds their usernames to `.asf.yaml`.
<!-- **^ Add meaningful description above** --><hr>
## Which Traffic Control components are affected by this PR?
<!-- Please delete all components from this list that are NOT affected by this PR.
Feel free to add the name of a tool or script that is affected but not on the list.
-->
- Automation - GitHub Actions<!-- Please specify which (GitHub Actions, Docker images, Ansible Roles, etc.) -->
- Other - `.asf.yaml`
## What is the best way to verify this PR?
<!-- Please include here ALL the steps necessary to test your PR.
If your PR has tests (and most should), provide the steps needed to run the tests.
If not, please provide step-by-step instructions to test the PR manually and explain why your PR does not need tests. -->
1.
1. Push the [`zrhoffman:atc-collaborators`](https://github.com/zrhoffman/trafficcontrol/tree/atc-collaborators) branch to the `master` branch of your own ATC fork
2. Go to Actions -> *Assign Triage Role*
3. To the right of the text on the blue bar saying *This workflow has a `workflow_dispatch` event trigger.*, click the gray *Run workflow* dropdown
4. Set *Count commits starting X days ago* from 31 to around 60 for the purposes of testing, in case no one has had 2 Issue-closing Pull Requests merged within the past 31 days
5. Click the green *Run workflow* button, then wait for the run of the *Assign Triage Role* workflow to complete (on my fork, it usually takes around 40 seconds).
6. Still on your fork, go to *Pull requests* and open the Pull Request titled *ATC Collaborators for December 2021*
7. Look at the generated Pull Request, form opinions
**Note:** The `#` and `@` symbols are intentionally replaced with similar-looking characters when the workflow runs on forks so that PRs and Users are not unnecessarily mentioned.
2. Run the `assign_triage_role` tests:
```shell
cd .github/actions/assign-triage-role
python3 -m unittest discover ./tests
## PR submission checklist
- [x] This PR has tests <!-- If not, please delete this text and explain why this PR does not need tests. -->
- [x] This PR has documentation <!-- If not, please delete this text and explain why this PR does not need documentation. -->
- [x] This PR has a CHANGELOG.md entry <!-- A fix for a bug from an ATC release, an improvement, or a new feature should have a changelog entry. -->
- [x] This PR **DOES NOT FIX A SERIOUS SECURITY VULNERABILITY** (see [the Apache Software Foundation's security guidelines](https://apache.org/security) for details)
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] zrhoffman commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
zrhoffman commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771719503
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
Review comment:
That was the order that PyCharm put them in (ordered `import`, then ordered `from [...] import`). I agree that having them so far apart looks weird, though.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] zrhoffman commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
zrhoffman commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771683277
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
Review comment:
Parenthesizing imports in 9601a60e5d
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] ocket8888 commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
ocket8888 commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771662991
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
Review comment:
If you want to avoid using backslashes on every line, you can use parenthesis to group the imports into a single multiline statement. But you don't have to.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+ today: date
+ target_branch_name: str
+ owner: str
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ repo_name = GITHUB_REPOSITORY
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(MINIMUM_COMMITS)
+ self.since_days_ago = int(SINCE_DAYS_AGO)
+ self.today = date.today()
+
+ self.target_branch_name = GITHUB_REF_NAME
+ self.owner = GITHUB_REPOSITORY_OWNER
+
+ def since_day(self) -> date:
+ """
+ Gets a date :var self.since_days_ago: before :var self.day:
+ """
+ return self.today - timedelta(days=self.since_days_ago)
+
+ def get_committers(self) -> set[str]:
+ """
+ Gets a dict whose keys are the usernames of committers
+ """
+ return {user.login for user in self.repo.get_collaborators() if user.permissions.push}
+
+ def prs_by_contributor(self, committers: set[str]) -> dict[
+ NamedUser, list[(Issue, Issue)]]:
+ """
+ Returns a dict of Pull Requests, associated by committer, within the last
+ :var self.since_day: days of :var self.today:.
+ """
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query = (f"repo:{repo_name} is:issue linked:pr is:closed closed:"
+ f"{self.since_day()}..{self.today}")
+ linked_issues = self.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = {}
+ for linked_issue in linked_issues:
+ timeline = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data["source"]["issue"]
+ if "pull_request" not in pr_text:
+ continue
+ pull_request = Issue(self.repo.__getattribute__("_requester"), event.raw_headers,
+ pr_text, completed=True)
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(
+ f"Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}")
+ # Skip unmerged PRs
+ if "merged_at" not in pull_request.pull_request.raw_data:
+ continue
+ author = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = []
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser,
+ list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ """
+ Returns a dict of contributors who had at least self.minimum_commits Issue-closing Pull
+ Requests merged in the past self.since_days_ago days
+ """
+ return {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull
+ # Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]],
+ description: str) -> None:
+ """
+ Writes the list of collaborators to .asf.yaml
+ """
+ collaborators: list[str] = list(prs_by_contributor)
+ with open(ASF_YAML_FILE, encoding="utf-8") as stream:
+ github_key: Final[str] = "github"
+ collaborators_key: Final[str] = "collaborators"
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f"Could not load YAML file {ASF_YAML_FILE}: {e}")
Review comment:
should this be printing to stderr?
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+ today: date
+ target_branch_name: str
+ owner: str
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ repo_name = GITHUB_REPOSITORY
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(MINIMUM_COMMITS)
+ self.since_days_ago = int(SINCE_DAYS_AGO)
+ self.today = date.today()
+
+ self.target_branch_name = GITHUB_REF_NAME
+ self.owner = GITHUB_REPOSITORY_OWNER
+
+ def since_day(self) -> date:
+ """
+ Gets a date :var self.since_days_ago: before :var self.day:
+ """
+ return self.today - timedelta(days=self.since_days_ago)
+
+ def get_committers(self) -> set[str]:
+ """
+ Gets a dict whose keys are the usernames of committers
Review comment:
it's actually a set
##########
File path: .github/actions/assign-triage-role/assign_triage_role/templates/pr_template.md
##########
@@ -0,0 +1,66 @@
+<!--
+Thank you for contributing! Please be sure to read our contribution guidelines: https://github.com/apache/trafficcontrol/blob/master/CONTRIBUTING.md
+If this closes or relates to an existing issue, please reference it using one of the following:
+
+Closes: #ISSUE
+Related: #ISSUE
+
+If this PR fixes a security vulnerability, DO NOT submit! Instead, contact
+the Apache Traffic Control Security Team at security@trafficcontrol.apache.org and follow the
+guidelines at https://apache.org/security regarding vulnerability disclosure.
+-->
Review comment:
If I ever have to edit this template, the first thing I'm going to do is get rid of all these comments meant for human authors on GitHub. They aren't hurting anything, but I'm just saying it'd increase the signal-to-noise ratio in this file.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+ today: date
+ target_branch_name: str
+ owner: str
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ repo_name = GITHUB_REPOSITORY
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(MINIMUM_COMMITS)
+ self.since_days_ago = int(SINCE_DAYS_AGO)
+ self.today = date.today()
+
+ self.target_branch_name = GITHUB_REF_NAME
+ self.owner = GITHUB_REPOSITORY_OWNER
+
+ def since_day(self) -> date:
+ """
+ Gets a date :var self.since_days_ago: before :var self.day:
+ """
+ return self.today - timedelta(days=self.since_days_ago)
+
+ def get_committers(self) -> set[str]:
+ """
+ Gets a dict whose keys are the usernames of committers
+ """
+ return {user.login for user in self.repo.get_collaborators() if user.permissions.push}
+
+ def prs_by_contributor(self, committers: set[str]) -> dict[
+ NamedUser, list[(Issue, Issue)]]:
+ """
+ Returns a dict of Pull Requests, associated by committer, within the last
+ :var self.since_day: days of :var self.today:.
+ """
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query = (f"repo:{repo_name} is:issue linked:pr is:closed closed:"
+ f"{self.since_day()}..{self.today}")
+ linked_issues = self.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = {}
+ for linked_issue in linked_issues:
+ timeline = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data["source"]["issue"]
+ if "pull_request" not in pr_text:
+ continue
+ pull_request = Issue(self.repo.__getattribute__("_requester"), event.raw_headers,
+ pr_text, completed=True)
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(
+ f"Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}")
+ # Skip unmerged PRs
+ if "merged_at" not in pull_request.pull_request.raw_data:
+ continue
+ author = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = []
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser,
+ list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ """
+ Returns a dict of contributors who had at least self.minimum_commits Issue-closing Pull
+ Requests merged in the past self.since_days_ago days
+ """
+ return {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull
+ # Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]],
+ description: str) -> None:
+ """
+ Writes the list of collaborators to .asf.yaml
+ """
+ collaborators: list[str] = list(prs_by_contributor)
+ with open(ASF_YAML_FILE, encoding="utf-8") as stream:
+ github_key: Final[str] = "github"
+ collaborators_key: Final[str] = "collaborators"
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f"Could not load YAML file {ASF_YAML_FILE}: {e}")
+ sys.exit(1)
Review comment:
should this be handled in __main__ like the other exception?
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
Review comment:
unused class member
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] zrhoffman commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
zrhoffman commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771709752
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
Review comment:
In any case, the `YamlError` import was moved to `__main__` in f5207efd64.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] ocket8888 commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
ocket8888 commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771715639
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
Review comment:
It's not an issue in CPython, dunno if there's a rule for it in Pylint. I'd probably feel better about it if they were at least grouped right next to each other.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] ocket8888 commented on pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
ocket8888 commented on pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#issuecomment-997057909
> our Pylint configuration did not complain about single-quoted strings
My mistake. The ESLint configuration(s) we have care, I think, so I probably just got those confused. If the Pylint config doesn't have a rule set for it, then it's not a rule. It's a bit late to correct myself, unfortunately, since you already changed them all.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] zrhoffman commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
zrhoffman commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771421656
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
Review comment:
Changed to a `set` in d67ddc01e8
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
Review comment:
Removed `TriageRoleAssigner.get_repo_name()` in bcbdaf99d9
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
Review comment:
Moved `try`/`except` to `__main__` in 0abb05f55e
##########
File path: .github/actions/assign-triage-role/assign_triage_role/templates/single_contributor.md
##########
@@ -0,0 +1,2 @@
+* @{CONTRIBUTOR_USERNAME} fixed {CONTRIBUTION_COUNT} Issues:
Review comment:
Added SPDX license identifier in e45e9b7503
##########
File path: .github/actions/assign-triage-role/assign_triage_role/templates/single_pr.md
##########
@@ -0,0 +1 @@
+ - #{ISSUE_NUMBER}, fixed by #{PR_NUMBER}
Review comment:
Added SPDX license identifier in e45e9b7503
##########
File path: .github/actions/assign-triage-role/assign_triage_role/__main__.py
##########
@@ -0,0 +1,31 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import sys
+
+from github.MainClass import Github
+
+from assign_triage_role.constants import ENV_GITHUB_TOKEN
+from assign_triage_role.triage_role_assigner import TriageRoleAssigner
+
+
+def main() -> None:
+ try:
+ github_token: str = os.environ[ENV_GITHUB_TOKEN]
+ except KeyError:
+ print(f'Environment variable {ENV_GITHUB_TOKEN} must be defined.')
+ sys.exit(1)
+ gh = Github(login_or_token=github_token)
+ TriageRoleAssigner(gh).run()
+
+main()
Review comment:
Moved logic out of `main()` in 66cdc8529c
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
Review comment:
Doing `from yaml import YAMLError` after `import yaml` is an issue? Is there a pylint rule for that?
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
Review comment:
Moved the check below the `pull_request is None` check in 722895aa60
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
Review comment:
Using `[]` in db7db0a200
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
Review comment:
`return`ing the value in d14c51d23b
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
Review comment:
Checking the response status code instead in 5a117a32ce
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
Review comment:
No longer using `str()` as of f442dad613
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
+ for contributor, pr_tuples in prs_by_contributor.items():
+ pr_list: str = ''
+ for pr, linked_issue in pr_tuples:
+ pr_line = pr_line_template.format(ISSUE_NUMBER=linked_issue.number, PR_NUMBER=pr.number)
+ pr_list += pr_line + '\n'
Review comment:
Using `str.join()` in f442dad613
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
+ for contributor, pr_tuples in prs_by_contributor.items():
+ pr_list: str = ''
+ for pr, linked_issue in pr_tuples:
+ pr_line = pr_line_template.format(ISSUE_NUMBER=linked_issue.number, PR_NUMBER=pr.number)
+ pr_list += pr_line + '\n'
+ contrib_list: str = contrib_list_template.format(CONTRIBUTOR_USERNAME=contributor, CONTRIBUTION_COUNT=len(pr_tuples), PR_LIST=pr_list)
+ contrib_list_list += contrib_list + '\n'
+ if contrib_list_list == '':
+ contrib_list_list = EMPTY_CONTRIB_LIST_LIST
+
+ list_of_contributors, congrats, expire = self.list_of_contributors(prs_by_contributor, today)
+
+ pr_body: str = pr_template.format(CONTRIB_LIST_LIST=contrib_list_list, MONTH=today.strftime('%B'), CONGRATS=congrats, LIST_OF_CONTRIBUTORS=list_of_contributors, EXPIRE=expire, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago, SINCE_DAY=since_day, TODAY=today)
+ # If on a fork, do not ping users or reference Issues or Pull Requests
+ if self.repo.parent is not None:
+ pr_body = re.sub(r'@(?!trafficcontrol)([A-Za-z0-9]+)', r'@\1', pr_body)
+ pr_body = re.sub(r'#([0-9])', r'⌗\1', pr_body)
+ print('Templated PR body')
+ return pr_body
+
+ def create_pr(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], commit_message: str, owner: str,
+ source_branch_name: str, target_branch: str, since_day: date, today: date) -> None:
+ prs: PaginatedList = self.gh.search_issues(f'repo:{self.repo.full_name} is:pr is:open head:{source_branch_name}')
+ for list_item in prs:
+ pr: PullRequest = self.repo.get_pull(list_item.number)
+ if pr.head.ref != source_branch_name:
+ continue
+ print(f'Pull request for branch {source_branch_name} already exists:\n{pr.html_url}')
+ return
+
+ pr_body: str = self.get_pr_body(prs_by_contributor, since_day, today)
+ pr: PullRequest = self.repo.create_pull(
+ title=commit_message,
+ body=pr_body,
+ head=f'{owner}:{source_branch_name}',
+ base=target_branch,
+ maintainer_can_modify=True,
+ )
+ try:
+ collaborators_label: Label = self.repo.get_label('collaborators')
+ process_label: Label = self.repo.get_label('process')
+ pr.add_to_labels(collaborators_label, process_label)
+ except UnknownObjectException:
+ print('Unable to find a label named "collaborators".')
Review comment:
Printing to stderr in f9dbfe7b98
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
+ for contributor, pr_tuples in prs_by_contributor.items():
+ pr_list: str = ''
+ for pr, linked_issue in pr_tuples:
+ pr_line = pr_line_template.format(ISSUE_NUMBER=linked_issue.number, PR_NUMBER=pr.number)
+ pr_list += pr_line + '\n'
+ contrib_list: str = contrib_list_template.format(CONTRIBUTOR_USERNAME=contributor, CONTRIBUTION_COUNT=len(pr_tuples), PR_LIST=pr_list)
+ contrib_list_list += contrib_list + '\n'
+ if contrib_list_list == '':
+ contrib_list_list = EMPTY_CONTRIB_LIST_LIST
+
+ list_of_contributors, congrats, expire = self.list_of_contributors(prs_by_contributor, today)
+
+ pr_body: str = pr_template.format(CONTRIB_LIST_LIST=contrib_list_list, MONTH=today.strftime('%B'), CONGRATS=congrats, LIST_OF_CONTRIBUTORS=list_of_contributors, EXPIRE=expire, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago, SINCE_DAY=since_day, TODAY=today)
+ # If on a fork, do not ping users or reference Issues or Pull Requests
+ if self.repo.parent is not None:
+ pr_body = re.sub(r'@(?!trafficcontrol)([A-Za-z0-9]+)', r'@\1', pr_body)
+ pr_body = re.sub(r'#([0-9])', r'⌗\1', pr_body)
+ print('Templated PR body')
+ return pr_body
+
+ def create_pr(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], commit_message: str, owner: str,
+ source_branch_name: str, target_branch: str, since_day: date, today: date) -> None:
+ prs: PaginatedList = self.gh.search_issues(f'repo:{self.repo.full_name} is:pr is:open head:{source_branch_name}')
+ for list_item in prs:
+ pr: PullRequest = self.repo.get_pull(list_item.number)
+ if pr.head.ref != source_branch_name:
+ continue
+ print(f'Pull request for branch {source_branch_name} already exists:\n{pr.html_url}')
+ return
+
+ pr_body: str = self.get_pr_body(prs_by_contributor, since_day, today)
+ pr: PullRequest = self.repo.create_pull(
+ title=commit_message,
+ body=pr_body,
+ head=f'{owner}:{source_branch_name}',
+ base=target_branch,
+ maintainer_can_modify=True,
+ )
+ try:
+ collaborators_label: Label = self.repo.get_label('collaborators')
+ process_label: Label = self.repo.get_label('process')
+ pr.add_to_labels(collaborators_label, process_label)
+ except UnknownObjectException:
+ print('Unable to find a label named "collaborators".')
+ print(f'Created pull request {pr.html_url}')
+
+ def get_repo_owner(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY_OWNER)
+ return repo_name
Review comment:
Made environment variables module-level constants in bcbdaf99d9
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
Review comment:
Extending `GitHub` class in 1a91d0dea4
##########
File path: CHANGELOG.md
##########
@@ -22,6 +22,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
- [#6032](https://github.com/apache/trafficcontrol/issues/6032) Add t3c setting mode 0600 for secure files
- [#6405](https://github.com/apache/trafficcontrol/issues/6405) Added cache config version to all t3c apps and config file headers
- Traffic Vault: Added additional flag to TV Riak (Deprecated) Util
+- ATC Collaborators: Added a GitHub Action to grant the GitHub Triage role for a month to contributors who closed 2 Issues in the past month
Review comment:
Removed changelog entry in 3dd11ef81a
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] zrhoffman commented on pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
zrhoffman commented on pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#issuecomment-996750690
> I haven't run this through our Pylint configuration, but I can tell you right now it won't like all of the single-quoted strings and no docstrings anywhere.
Added docstrings in af30ba1a23, but our Pylint configuration did not complain about single-quoted strings. Switched to double-quoted strings in c961ceb50e, though our Python coding standards should mention it somewhere if we follow it.
* Changed named list and dict declarations to brackets in db7db0a200
* Removed unnecessary typehints in 1f26c4959a
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] ocket8888 commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
ocket8888 commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r770797084
##########
File path: .github/actions/assign-triage-role/assign_triage_role/__main__.py
##########
@@ -0,0 +1,31 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import sys
+
+from github.MainClass import Github
+
+from assign_triage_role.constants import ENV_GITHUB_TOKEN
+from assign_triage_role.triage_role_assigner import TriageRoleAssigner
+
+
+def main() -> None:
+ try:
+ github_token: str = os.environ[ENV_GITHUB_TOKEN]
+ except KeyError:
+ print(f'Environment variable {ENV_GITHUB_TOKEN} must be defined.')
+ sys.exit(1)
+ gh = Github(login_or_token=github_token)
+ TriageRoleAssigner(gh).run()
+
+main()
Review comment:
nit: typically the reason people wrap a script's logic in a `main` function to be called at the module scope is so they can wrap execution easily in a check for `__name__ == "__main__"`, which avoids logic running when the module is imported. You're not doing that here, and `main` even terminates execution early with `sys.exit`, so this is almost totally equivalent to just having all of the logic in the module scope instead of wrapped in a function at all. It's a sort of protection that's being obviated by using `__main__.py`.
This probably isn't a big deal since in terms of "wasted" code/space we're really just talking about like 7 extra indentation characters, and we don't expect anyone to import `__main__` from this package - but also this isn't a package at all since there's no `__init__.py`. Which also isn't really a problem.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
Review comment:
Personally I think forcing a `sys.exit` at an unknown point in execution is hazardous. The way I'd normally handle this is with a `try`/`except` in `main` or where it's called (usually I have `main` return an `int` to use as an exit code and do the `try`/`except` in there to determine the returned value, but either way accomplishes the same thing).
To avoid swallowing errors that aren't accounted for that could be a detriment to debugging, I'd normally make a class that inherits from `Exception` and always `raise from` to that class, so I can just `except` that one type.
There are other failure states that can be communicated up the call stack like this - in fact currently are being raised to the root scope without being handled by forcing a `sys.exit` in this way, which is a little inconsistent. For example, if the environment variables aren't properly set, parsing some of them to `int`s in the `__init__` of this class will raise a `ValueError`, which currently dumps a stack trace that ends at the point where `main` is called.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
Review comment:
re-using the name of the input mutable collection is ill-advised because they're passed by reference, so if you mutate that collection you can change data in the calling scope. That's not actually happening here, because the reference is just being rebound, but that reference is never used, so you could avoid all contention about the issue by simply `return`ing the value instead of assigning a label to it.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
Review comment:
Since that's just checking if a string can be found in `message`, it's both simpler and faster to check `"No commit found for the ref" in message`
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
Review comment:
nit but calling a list constructor is something like 4 vm instructions slower than just doing `[]`
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
Review comment:
`dict[str, None]` looks a lot like the common Go pattern of emulating a set using `map[string]struct{}` - should this just be a set? You can also construct a set just by calling `set` on an iterable, don't need a separate comprehension. Plus `sorted` constructs a `list` no matter what the input iterable is, so you could just leave it as a generator instead of creating a list from the generator before passing it into `sorted`. But if you're just making an unordered collection out of it in any case, why bother sorting it?
tl;dr I'd just do
```python3
return {user.login for user in self.repo.get_collaborators() if user.permissions.push}
```
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
Review comment:
duplicate `yaml` import. The fact that this doesn't execute module code twice is an implementation detail of CPython.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
Review comment:
nit but this variable assignment isn't used. It could just be one line that returns the value directly. Also, the only work done in this method is calling a static method with a Final argument - should this method be static? Or alternatively, since that method is also a trivial one-line function, do we need these two methods at all?
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
Review comment:
nit: it's something like 4 instructions faster to use a literal empty string (`""`) than calling `str`.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/templates/single_pr.md
##########
@@ -0,0 +1 @@
+ - #{ISSUE_NUMBER}, fixed by #{PR_NUMBER}
Review comment:
Same as above RE: license header
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
+ for contributor, pr_tuples in prs_by_contributor.items():
+ pr_list: str = ''
+ for pr, linked_issue in pr_tuples:
+ pr_line = pr_line_template.format(ISSUE_NUMBER=linked_issue.number, PR_NUMBER=pr.number)
+ pr_list += pr_line + '\n'
Review comment:
nit but this looks sort of like a manual implementation of `str.join` e.g. `"\n".join(pr_line_template.format(ISSUE_NUMBER=issue.number, PR_NUMBER=pr.number for pr, issue in pr_tuples) + "\n"`
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
+ for contributor, pr_tuples in prs_by_contributor.items():
+ pr_list: str = ''
+ for pr, linked_issue in pr_tuples:
+ pr_line = pr_line_template.format(ISSUE_NUMBER=linked_issue.number, PR_NUMBER=pr.number)
+ pr_list += pr_line + '\n'
+ contrib_list: str = contrib_list_template.format(CONTRIBUTOR_USERNAME=contributor, CONTRIBUTION_COUNT=len(pr_tuples), PR_LIST=pr_list)
+ contrib_list_list += contrib_list + '\n'
+ if contrib_list_list == '':
+ contrib_list_list = EMPTY_CONTRIB_LIST_LIST
+
+ list_of_contributors, congrats, expire = self.list_of_contributors(prs_by_contributor, today)
+
+ pr_body: str = pr_template.format(CONTRIB_LIST_LIST=contrib_list_list, MONTH=today.strftime('%B'), CONGRATS=congrats, LIST_OF_CONTRIBUTORS=list_of_contributors, EXPIRE=expire, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago, SINCE_DAY=since_day, TODAY=today)
+ # If on a fork, do not ping users or reference Issues or Pull Requests
+ if self.repo.parent is not None:
+ pr_body = re.sub(r'@(?!trafficcontrol)([A-Za-z0-9]+)', r'@\1', pr_body)
+ pr_body = re.sub(r'#([0-9])', r'⌗\1', pr_body)
+ print('Templated PR body')
+ return pr_body
+
+ def create_pr(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], commit_message: str, owner: str,
+ source_branch_name: str, target_branch: str, since_day: date, today: date) -> None:
+ prs: PaginatedList = self.gh.search_issues(f'repo:{self.repo.full_name} is:pr is:open head:{source_branch_name}')
+ for list_item in prs:
+ pr: PullRequest = self.repo.get_pull(list_item.number)
+ if pr.head.ref != source_branch_name:
+ continue
+ print(f'Pull request for branch {source_branch_name} already exists:\n{pr.html_url}')
+ return
+
+ pr_body: str = self.get_pr_body(prs_by_contributor, since_day, today)
+ pr: PullRequest = self.repo.create_pull(
+ title=commit_message,
+ body=pr_body,
+ head=f'{owner}:{source_branch_name}',
+ base=target_branch,
+ maintainer_can_modify=True,
+ )
+ try:
+ collaborators_label: Label = self.repo.get_label('collaborators')
+ process_label: Label = self.repo.get_label('process')
+ pr.add_to_labels(collaborators_label, process_label)
+ except UnknownObjectException:
+ print('Unable to find a label named "collaborators".')
Review comment:
should this (and one or two other similar cases in this module) be printing to stderr since it's an error/warning?
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
Review comment:
I would probably make this inherit from `Github` so you can do `TriageRoleAssigner(args...)` instead of `TriageRoleAssigner(Github(args...))` but that's not a big deal at all.
##########
File path: CHANGELOG.md
##########
@@ -22,6 +22,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
- [#6032](https://github.com/apache/trafficcontrol/issues/6032) Add t3c setting mode 0600 for secure files
- [#6405](https://github.com/apache/trafficcontrol/issues/6405) Added cache config version to all t3c apps and config file headers
- Traffic Vault: Added additional flag to TV Riak (Deprecated) Util
+- ATC Collaborators: Added a GitHub Action to grant the GitHub Triage role for a month to contributors who closed 2 Issues in the past month
Review comment:
This isn't actually a change to the software that's present in any given version. Collaborators will have permissions on GitHub, and can e.g. triage backport issues for old versions. It's not a change of which people using the software need to be made aware. Which is to say, I don't think this needs a changelog entry.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
Review comment:
based on usage, it does look like this should just be a `set`.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/templates/single_contributor.md
##########
@@ -0,0 +1,2 @@
+* @{CONTRIBUTOR_USERNAME} fixed {CONTRIBUTION_COUNT} Issues:
Review comment:
Shouldn't this file have a comment node license header?
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
Review comment:
accessing a property of an `Optional` value could cause raising an `AttributeError` which isn't handled. This check should go below the check for `pull_request is None` below.
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from typing import Optional, Final
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import BadCredentialsException, GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ENV_GITHUB_TOKEN, ENV_GITHUB_REPOSITORY, ENV_SINCE_DAYS_AGO, ENV_MINIMUM_COMMITS, ASF_YAML_FILE, APACHE_LICENSE_YAML, ENV_GITHUB_REF_NAME, GIT_AUTHOR_EMAIL_TEMPLATE, ENV_GIT_AUTHOR_NAME, SINGLE_PR_TEMPLATE_FILE, SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, ENV_GITHUB_REPOSITORY_OWNER
+
+
+class TriageRoleAssigner:
+ gh: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+
+ def __init__(self, gh: Github) -> None:
+ self.gh = gh
+ repo_name: str = self.get_repo_name()
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(self.getenv(ENV_MINIMUM_COMMITS))
+ self.since_days_ago = int(self.getenv(ENV_SINCE_DAYS_AGO))
+
+ @staticmethod
+ def getenv(env_name: str) -> str:
+ return os.environ[env_name]
+
+ def get_repo_name(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY)
+ return repo_name
+
+ def get_repo(self, repo_name: str) -> Repository:
+ try:
+ repo: Repository = self.gh.get_repo(repo_name)
+ except BadCredentialsException:
+ print(f'Credentials from {ENV_GITHUB_TOKEN} were bad.')
+ sys.exit(1)
+ return repo
+
+ def get_committers(self) -> dict[str, None]:
+ committers: list[str] = sorted([user.login for user in self.repo.get_collaborators() if user.permissions.push])
+ committers_dict: dict[str, None] = {committer: None for committer in committers}
+ return committers_dict
+
+ def prs_by_contributor(self, since_day: date, today: date, committers: dict[str, None]) -> dict[NamedUser, list[(Issue, Issue)]]:
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query: str = f'repo:{repo_name} is:issue linked:pr is:closed closed:{since_day}..{today}'
+ linked_issues: PaginatedList[Issue] = self.gh.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = dict[NamedUser, list[(Issue, Issue)]]()
+ for linked_issue in linked_issues:
+ timeline: PaginatedList[TimelineEvent] = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data['source']['issue']
+ if 'pull_request' not in pr_text:
+ continue
+ pull_request = Issue(self.repo._requester, event.raw_headers, pr_text, completed=True)
+ # Skip unmerged PRs
+ if 'merged_at' not in pull_request.pull_request.raw_data:
+ continue
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(f'Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}')
+ author: NamedUser = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = list[(Issue, Issue)]()
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ prs_by_contributor: dict[str, list[(Issue, Issue)]] = {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+ return prs_by_contributor
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], description: str):
+ collaborators: list[str] = [contributor for contributor in prs_by_contributor]
+ with open(ASF_YAML_FILE) as stream:
+ github_key: Final[str] = 'github'
+ collaborators_key: Final[str] = 'collaborators'
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f'Could not load YAML file {ASF_YAML_FILE}: {e}')
+ sys.exit(1)
+ if github_key not in asf_yaml:
+ asf_yaml[github_key] = dict[str, dict]()
+ asf_yaml[github_key][collaborators_key] = collaborators
+
+ with open(os.path.join(os.path.dirname(__file__), APACHE_LICENSE_YAML)) as stream:
+ apache_license = stream.read().format(DESCRIPTION=description, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago)
+
+ with open(ASF_YAML_FILE, 'w') as stream:
+ stream.write(apache_license)
+ yaml.dump(asf_yaml, stream)
+
+ def push_changes(self, target_branch_name: str, source_branch_name: str, commit_message: str) -> Commit:
+ target_branch: Branch = self.repo.get_branch(target_branch_name)
+ sha: str = target_branch.commit.sha
+ source_branch_ref: str = f'refs/heads/{source_branch_name}'
+ self.repo.create_git_ref(source_branch_ref, sha)
+ print(f'Created branch {source_branch_name}')
+
+ with open(ASF_YAML_FILE) as stream:
+ asf_yaml = stream.read()
+
+ asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
+ kwargs = {'path': ASF_YAML_FILE,
+ 'message': commit_message,
+ 'content': asf_yaml,
+ 'sha': asf_yaml_contentfile.sha,
+ 'branch': source_branch_name,
+ }
+ try:
+ git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
+ git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
+ author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
+ kwargs['author'] = author
+ kwargs['committer'] = author
+ except KeyError:
+ print('Committing using the default author')
+
+ commit: Commit = self.repo.update_file(**kwargs).get('commit')
+ print(f'Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}')
+ return commit
+
+ def get_repo_file_contents(self, branch: str) -> str:
+ return self.repo.get_contents(ASF_YAML_FILE,
+ f'refs/heads/{branch}').decoded_content.rstrip().decode()
+
+ def branch_exists(self, branch: str) -> bool:
+ try:
+ self.get_repo_file_contents(branch)
+ return True
+ except GithubException as e:
+ message = e.data.get('message')
+ if not re.match(r'No commit found for the ref', message):
+ raise e
+ return False
+
+ @staticmethod
+ def list_of_contributors(prs_by_contributor: dict[str, list[(Issue, Issue)]], today: date) -> tuple[str, str, str]:
+ if len(prs_by_contributor) > 0:
+ joiner: str = ', ' if len(prs_by_contributor) > 2 else ' '
+ list_of_contributors: list[str] = [f'@{contributor}' for contributor in prs_by_contributor.keys()]
+ if len(list_of_contributors) > 1:
+ list_of_contributors[-1] = f'and {list_of_contributors[-1]}'
+ list_of_contributors: str = joiner.join(list_of_contributors)
+ congrats: str = CONGRATS
+ expire: str = EXPIRE.format(MONTH=today.strftime('%B'))
+ else:
+ list_of_contributors: str = EMPTY_LIST_OF_CONTRIBUTORS
+ congrats: str = ''
+ expire: str = ''
+
+ return list_of_contributors, congrats, expire
+
+ def get_pr_body(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], since_day: date, today: date) -> str:
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_PR_TEMPLATE_FILE)) as stream:
+ pr_line_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), SINGLE_CONTRIBUTOR_TEMPLATE_FILE)) as stream:
+ contrib_list_template = stream.read()
+ with open(os.path.join(os.path.dirname(__file__), PR_TEMPLATE_FILE)) as stream:
+ pr_template = stream.read()
+
+ contrib_list_list: str = str()
+ for contributor, pr_tuples in prs_by_contributor.items():
+ pr_list: str = ''
+ for pr, linked_issue in pr_tuples:
+ pr_line = pr_line_template.format(ISSUE_NUMBER=linked_issue.number, PR_NUMBER=pr.number)
+ pr_list += pr_line + '\n'
+ contrib_list: str = contrib_list_template.format(CONTRIBUTOR_USERNAME=contributor, CONTRIBUTION_COUNT=len(pr_tuples), PR_LIST=pr_list)
+ contrib_list_list += contrib_list + '\n'
+ if contrib_list_list == '':
+ contrib_list_list = EMPTY_CONTRIB_LIST_LIST
+
+ list_of_contributors, congrats, expire = self.list_of_contributors(prs_by_contributor, today)
+
+ pr_body: str = pr_template.format(CONTRIB_LIST_LIST=contrib_list_list, MONTH=today.strftime('%B'), CONGRATS=congrats, LIST_OF_CONTRIBUTORS=list_of_contributors, EXPIRE=expire, ISSUE_THRESHOLD=self.minimum_commits, SINCE_DAYS_AGO=self.since_days_ago, SINCE_DAY=since_day, TODAY=today)
+ # If on a fork, do not ping users or reference Issues or Pull Requests
+ if self.repo.parent is not None:
+ pr_body = re.sub(r'@(?!trafficcontrol)([A-Za-z0-9]+)', r'@\1', pr_body)
+ pr_body = re.sub(r'#([0-9])', r'⌗\1', pr_body)
+ print('Templated PR body')
+ return pr_body
+
+ def create_pr(self, prs_by_contributor: dict[str, list[(Issue, Issue)]], commit_message: str, owner: str,
+ source_branch_name: str, target_branch: str, since_day: date, today: date) -> None:
+ prs: PaginatedList = self.gh.search_issues(f'repo:{self.repo.full_name} is:pr is:open head:{source_branch_name}')
+ for list_item in prs:
+ pr: PullRequest = self.repo.get_pull(list_item.number)
+ if pr.head.ref != source_branch_name:
+ continue
+ print(f'Pull request for branch {source_branch_name} already exists:\n{pr.html_url}')
+ return
+
+ pr_body: str = self.get_pr_body(prs_by_contributor, since_day, today)
+ pr: PullRequest = self.repo.create_pull(
+ title=commit_message,
+ body=pr_body,
+ head=f'{owner}:{source_branch_name}',
+ base=target_branch,
+ maintainer_can_modify=True,
+ )
+ try:
+ collaborators_label: Label = self.repo.get_label('collaborators')
+ process_label: Label = self.repo.get_label('process')
+ pr.add_to_labels(collaborators_label, process_label)
+ except UnknownObjectException:
+ print('Unable to find a label named "collaborators".')
+ print(f'Created pull request {pr.html_url}')
+
+ def get_repo_owner(self) -> str:
+ repo_name: str = self.getenv(ENV_GITHUB_REPOSITORY_OWNER)
+ return repo_name
Review comment:
I have the same question as above with `get_repo_name` for this one.
Now that I'm thinking about it, I think you could probably just set these up at import time, since the environment isn't manipulated during execution, as module-level constants:
```python3
REPO_NAME: Final[str] = os.environ.get(ENV_GITHUB_REPOSITORY_OWNER)
```
(`.get` makes the retrieval "safe", but also Optional; if the environment variable `FOO` is not set, `os.environ["FOO"]` raises a KeyError, which isn't handled throughout this code, but `os.environ.get("FOO")` returns `None`, which would also need to be handled.)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] zrhoffman commented on a change in pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
zrhoffman commented on a change in pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424#discussion_r771683639
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+ today: date
+ target_branch_name: str
+ owner: str
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ repo_name = GITHUB_REPOSITORY
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(MINIMUM_COMMITS)
+ self.since_days_ago = int(SINCE_DAYS_AGO)
+ self.today = date.today()
+
+ self.target_branch_name = GITHUB_REF_NAME
+ self.owner = GITHUB_REPOSITORY_OWNER
+
+ def since_day(self) -> date:
+ """
+ Gets a date :var self.since_days_ago: before :var self.day:
+ """
+ return self.today - timedelta(days=self.since_days_ago)
+
+ def get_committers(self) -> set[str]:
+ """
+ Gets a dict whose keys are the usernames of committers
Review comment:
Documented as a set in 8cc43ea274
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
Review comment:
Removed class member in 110291d6f5
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+ today: date
+ target_branch_name: str
+ owner: str
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ repo_name = GITHUB_REPOSITORY
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(MINIMUM_COMMITS)
+ self.since_days_ago = int(SINCE_DAYS_AGO)
+ self.today = date.today()
+
+ self.target_branch_name = GITHUB_REF_NAME
+ self.owner = GITHUB_REPOSITORY_OWNER
+
+ def since_day(self) -> date:
+ """
+ Gets a date :var self.since_days_ago: before :var self.day:
+ """
+ return self.today - timedelta(days=self.since_days_ago)
+
+ def get_committers(self) -> set[str]:
+ """
+ Gets a dict whose keys are the usernames of committers
+ """
+ return {user.login for user in self.repo.get_collaborators() if user.permissions.push}
+
+ def prs_by_contributor(self, committers: set[str]) -> dict[
+ NamedUser, list[(Issue, Issue)]]:
+ """
+ Returns a dict of Pull Requests, associated by committer, within the last
+ :var self.since_day: days of :var self.today:.
+ """
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query = (f"repo:{repo_name} is:issue linked:pr is:closed closed:"
+ f"{self.since_day()}..{self.today}")
+ linked_issues = self.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = {}
+ for linked_issue in linked_issues:
+ timeline = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data["source"]["issue"]
+ if "pull_request" not in pr_text:
+ continue
+ pull_request = Issue(self.repo.__getattribute__("_requester"), event.raw_headers,
+ pr_text, completed=True)
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(
+ f"Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}")
+ # Skip unmerged PRs
+ if "merged_at" not in pull_request.pull_request.raw_data:
+ continue
+ author = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = []
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser,
+ list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ """
+ Returns a dict of contributors who had at least self.minimum_commits Issue-closing Pull
+ Requests merged in the past self.since_days_ago days
+ """
+ return {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull
+ # Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]],
+ description: str) -> None:
+ """
+ Writes the list of collaborators to .asf.yaml
+ """
+ collaborators: list[str] = list(prs_by_contributor)
+ with open(ASF_YAML_FILE, encoding="utf-8") as stream:
+ github_key: Final[str] = "github"
+ collaborators_key: Final[str] = "collaborators"
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f"Could not load YAML file {ASF_YAML_FILE}: {e}")
+ sys.exit(1)
Review comment:
Handling `YAMLError` in `__main__` in f5207efd64
##########
File path: .github/actions/assign-triage-role/assign_triage_role/templates/pr_template.md
##########
@@ -0,0 +1,66 @@
+<!--
+Thank you for contributing! Please be sure to read our contribution guidelines: https://github.com/apache/trafficcontrol/blob/master/CONTRIBUTING.md
+If this closes or relates to an existing issue, please reference it using one of the following:
+
+Closes: #ISSUE
+Related: #ISSUE
+
+If this PR fixes a security vulnerability, DO NOT submit! Instead, contact
+the Apache Traffic Control Security Team at security@trafficcontrol.apache.org and follow the
+guidelines at https://apache.org/security regarding vulnerability disclosure.
+-->
Review comment:
Removed human-intended comments in acc658fce1
##########
File path: .github/actions/assign-triage-role/assign_triage_role/triage_role_assigner.py
##########
@@ -0,0 +1,342 @@
+"""
+Assign Triage Role
+"""
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import os
+import re
+import sys
+from datetime import date, timedelta
+from http.client import NOT_FOUND
+from typing import Optional, Final
+from xml.dom import minidom
+from xml.dom.minidom import Node, Element
+
+import yaml
+from github import TimelineEvent
+from github.Branch import Branch
+from github.Commit import Commit
+from github.ContentFile import ContentFile
+from github.GithubException import GithubException, UnknownObjectException
+from github.InputGitAuthor import InputGitAuthor
+from github.Issue import Issue
+from github.Label import Label
+from github.MainClass import Github
+from github.NamedUser import NamedUser
+from github.PaginatedList import PaginatedList
+from github.PullRequest import PullRequest
+from github.Repository import Repository
+from yaml import YAMLError
+
+from assign_triage_role.constants import GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE, ASF_YAML_FILE, \
+ APACHE_LICENSE_YAML, GIT_AUTHOR_EMAIL_TEMPLATE, SINGLE_PR_TEMPLATE_FILE, \
+ SINGLE_CONTRIBUTOR_TEMPLATE_FILE, PR_TEMPLATE_FILE, EMPTY_CONTRIB_LIST_LIST, \
+ EMPTY_LIST_OF_CONTRIBUTORS, CONGRATS, EXPIRE, GITHUB_REPOSITORY, GIT_AUTHOR_NAME, \
+ GITHUB_REPOSITORY_OWNER, MINIMUM_COMMITS, SINCE_DAYS_AGO, GITHUB_REF_NAME
+
+
+class TriageRoleAssigner(Github):
+ """
+ Triage Role Assigner
+ """
+ github: Github
+ repo: Repository
+ minimum_commits: int
+ since_days_ago: int
+ today: date
+ target_branch_name: str
+ owner: str
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ repo_name = GITHUB_REPOSITORY
+ self.repo = self.get_repo(repo_name)
+
+ self.minimum_commits = int(MINIMUM_COMMITS)
+ self.since_days_ago = int(SINCE_DAYS_AGO)
+ self.today = date.today()
+
+ self.target_branch_name = GITHUB_REF_NAME
+ self.owner = GITHUB_REPOSITORY_OWNER
+
+ def since_day(self) -> date:
+ """
+ Gets a date :var self.since_days_ago: before :var self.day:
+ """
+ return self.today - timedelta(days=self.since_days_ago)
+
+ def get_committers(self) -> set[str]:
+ """
+ Gets a dict whose keys are the usernames of committers
+ """
+ return {user.login for user in self.repo.get_collaborators() if user.permissions.push}
+
+ def prs_by_contributor(self, committers: set[str]) -> dict[
+ NamedUser, list[(Issue, Issue)]]:
+ """
+ Returns a dict of Pull Requests, associated by committer, within the last
+ :var self.since_day: days of :var self.today:.
+ """
+ # Search for PRs and Issues on the parent repo if running on a fork
+ repo_name = self.repo.full_name if self.repo.parent is None else self.repo.parent.full_name
+
+ query = (f"repo:{repo_name} is:issue linked:pr is:closed closed:"
+ f"{self.since_day()}..{self.today}")
+ linked_issues = self.search_issues(query=query)
+ prs_by_contributor: dict[NamedUser, list[(Issue, Issue)]] = {}
+ for linked_issue in linked_issues:
+ timeline = linked_issue.get_timeline()
+ pull_request: Optional[Issue] = None
+ for event in timeline:
+ if event.id is not None:
+ continue
+ if event.event != GH_TIMELINE_EVENT_TYPE_CROSS_REFERENCE:
+ continue
+ pr_text = event.raw_data["source"]["issue"]
+ if "pull_request" not in pr_text:
+ continue
+ pull_request = Issue(self.repo.__getattribute__("_requester"), event.raw_headers,
+ pr_text, completed=True)
+ # Do not break, in case the Issue has ever been linked to more than 1 PR in the past
+ if pull_request is None:
+ raise Exception(
+ f"Unable to find a linked Pull Request for Issue {self.repo.full_name}#{linked_issue.number}")
+ # Skip unmerged PRs
+ if "merged_at" not in pull_request.pull_request.raw_data:
+ continue
+ author = pull_request.user
+ if author.login in committers:
+ continue
+ if author not in prs_by_contributor:
+ prs_by_contributor[author] = []
+ prs_by_contributor[author].append((pull_request, linked_issue))
+ return prs_by_contributor
+
+ def ones_who_meet_threshold(self, prs_by_contributor: dict[NamedUser,
+ list[(Issue, Issue)]]) -> dict[str, list[(Issue, Issue)]]:
+ """
+ Returns a dict of contributors who had at least self.minimum_commits Issue-closing Pull
+ Requests merged in the past self.since_days_ago days
+ """
+ return {
+ # use only the username as the dict key
+ contributor.login: pull_requests
+ # sort contributors by commit count
+ for contributor, pull_requests in sorted(
+ prs_by_contributor.items(),
+ key=lambda item: len(item[1]),
+ # highest commit count first
+ reverse=True)
+ # only include contributors who had at least self.minimum_commits Issue-closing Pull
+ # Requests merged in the past self.since_days_ago days
+ if len(pull_requests) >= self.minimum_commits
+ }
+
+ def set_collaborators_in_asf_yaml(self, prs_by_contributor: dict[str, list[(Issue, Issue)]],
+ description: str) -> None:
+ """
+ Writes the list of collaborators to .asf.yaml
+ """
+ collaborators: list[str] = list(prs_by_contributor)
+ with open(ASF_YAML_FILE, encoding="utf-8") as stream:
+ github_key: Final[str] = "github"
+ collaborators_key: Final[str] = "collaborators"
+ try:
+ asf_yaml: dict[str, dict] = yaml.safe_load(stream)
+ except YAMLError as e:
+ print(f"Could not load YAML file {ASF_YAML_FILE}: {e}")
Review comment:
Printing to stderr in f5207efd64
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [trafficcontrol] ocket8888 merged pull request #6424: GHA: Grant Collaborator status to contributors who close 2 Issues in past month
Posted by GitBox <gi...@apache.org>.
ocket8888 merged pull request #6424:
URL: https://github.com/apache/trafficcontrol/pull/6424
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@trafficcontrol.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org