pytorch/.github/scripts/check_labels.py
Ning Xu 2c76838d7f Issue-88098: extract utils from check labels (#94597)
Fixes #88098

This is a mirror of the same PR (https://github.com/Goldspear/pytorch/pull/2) that has been reviewed in my fork (due to it's a stacked PR).

======================
## Context

This is the 2nd of the 3 PRs to address issue-88098.

## What Changed
1. Extract comment related utils from trymerge.py to github_utils.py
2. Extract label related utils from trymerge.py and check_labels.py to label_utils.py

## Tests
* pytorch-dummy repo [trymerge run ](https://github.com/Goldspear/pytorch-dummy/actions/runs/4118944174)merged the test PR [OK](https://github.com/Goldspear/pytorch-dummy/pull/2).

## Note to Reviewers
Due to higher degree of complexity involved to extract GitHubPR class, it's worth having a separate issue to handle that part of refactoring. This issue only focusing on refactoring where necessary to ship the functional diff.

* 1st PR: https://github.com/pytorch/pytorch/pull/94179
* 2nd PR: this one
* 3rd PR: https://github.com/Goldspear/pytorch/pull/3

Pull Request resolved: https://github.com/pytorch/pytorch/pull/94597
Approved by: https://github.com/ZainRizvi
2023-02-12 12:18:53 +00:00

61 lines
1.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Check whether a PR has required labels."""
from typing import Any
from gitutils import (
get_git_remote_name,
get_git_repo_dir,
GitRepo,
)
from trymerge import GitHubPR
from github_utils import (
gh_delete_comment,
gh_post_pr_comment,
)
from label_utils import (
LABEL_ERR_MSG,
is_label_err_comment,
has_required_labels,
)
def delete_all_label_err_comments(pr: "GitHubPR") -> None:
for comment in pr.get_comments():
if is_label_err_comment(comment):
gh_delete_comment(pr.org, pr.project, comment.database_id)
def add_label_err_comment(pr: "GitHubPR") -> None:
# Only make a comment if one doesn't exist already
if not any(is_label_err_comment(comment) for comment in pr.get_comments()):
gh_post_pr_comment(pr.org, pr.project, pr.pr_num, LABEL_ERR_MSG)
def parse_args() -> Any:
from argparse import ArgumentParser
parser = ArgumentParser("Check PR labels")
parser.add_argument("pr_num", type=int)
return parser.parse_args()
def main() -> None:
args = parse_args()
repo = GitRepo(get_git_repo_dir(), get_git_remote_name())
org, project = repo.gh_owner_and_name()
pr = GitHubPR(org, project, args.pr_num)
try:
if not has_required_labels(pr):
print(LABEL_ERR_MSG)
add_label_err_comment(pr)
exit(1)
else:
delete_all_label_err_comments(pr)
except Exception as e:
pass
if __name__ == "__main__":
main()