Skip to content

Commit 675bf47

Browse files
chantrafacebook-github-bot
authored andcommitted
Revert codemod (#64)
Summary: Those 2 codemod assumed python 3.10+ and currently break upstream KPD. 3.9 is still what is shipped on CentOS 9, probably good to keep around. Pull Request resolved: facebookincubator/kernel-patches-daemon#64 Reviewed By: chantra Differential Revision: D64507585 fbshipit-source-id: 8c32c0f7fee37eba7bf5b4980919afbcc29ec06f
1 parent 19e8a1c commit 675bf47

16 files changed

+142
-141
lines changed

kernel_patches_daemon/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class ScriptMetricsExporter:
3636
def __init__(self, script: str) -> None:
3737
self.script = script
3838

39-
def export(self, project: str, metrics: dict) -> None:
39+
def export(self, project: str, metrics: Dict) -> None:
4040
if os.path.isfile(self.script) and os.access(self.script, os.X_OK):
4141
p = Popen([self.script], stdout=PIPE, stdin=PIPE, stderr=PIPE)
4242
p.communicate(input=json.dumps(metrics).encode())

kernel_patches_daemon/branch_worker.py

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
import tempfile
2020
import time
2121
from collections import namedtuple
22-
from collections.abc import Generator, Sequence
2322
from contextlib import contextmanager
2423
from datetime import datetime, timedelta, timezone
2524
from email.mime.application import MIMEApplication
@@ -28,7 +27,7 @@
2827
from enum import Enum
2928
from pathlib import Path
3029
from subprocess import PIPE
31-
from typing import Any, Final, IO
30+
from typing import Any, Dict, Final, Generator, IO, List, Optional, Sequence, Tuple
3231

3332
import dateutil.parser
3433
import git
@@ -161,7 +160,7 @@ def __str__(self):
161160
)
162161

163162

164-
def get_ci_base(series: Series) -> dict:
163+
def get_ci_base(series: Series) -> Dict:
165164
"""Retrieve the object (cover letter or patch) that we use as the base for
166165
sending emails in response to.
167166
"""
@@ -260,7 +259,7 @@ def build_email(
260259
msg_id: str,
261260
body: str,
262261
boundary: str = "",
263-
) -> tuple[list[str], str]:
262+
) -> Tuple[List[str], str]:
264263
"""
265264
Builds complete email (including headers) to be sent along with curl command
266265
necessary to send it.
@@ -354,11 +353,13 @@ def execute_command(cmd: str) -> None:
354353
os.system(cmd)
355354

356355

357-
def _uniq_tmp_folder(url: str | None, branch: str | None, base_directory: str) -> str:
356+
def _uniq_tmp_folder(
357+
url: Optional[str], branch: Optional[str], base_directory: str
358+
) -> str:
358359
# use same folder for multiple invocation to avoid cloning whole tree every time
359360
# but use different folder for different workers identified by url and branch name
360361
sha = hashlib.sha256()
361-
sha.update(f"{url}/{branch}".encode())
362+
sha.update(f"{url}/{branch}".encode("utf-8"))
362363
# pyre-fixme[6]: For 1st argument expected `PathLike[Variable[AnyStr <: [str,
363364
# bytes]]]` but got `Optional[str]`.
364365
repo_name = remove_unsafe_chars(os.path.basename(url))
@@ -379,9 +380,9 @@ def temporary_patch_file(content: bytes) -> Generator[IO, None, None]:
379380
tmp_patch_file.close()
380381

381382

382-
def create_color_labels(labels_cfg: dict[str, str], repo: Repository) -> None:
383-
repo_labels: dict[str, GithubLabel] = {x.name.lower(): x for x in repo.get_labels()}
384-
labels_cfg: dict[str, str] = {k.lower(): v for k, v in labels_cfg.items()}
383+
def create_color_labels(labels_cfg: Dict[str, str], repo: Repository) -> None:
384+
repo_labels: Dict[str, GithubLabel] = {x.name.lower(): x for x in repo.get_labels()}
385+
labels_cfg: Dict[str, str] = {k.lower(): v for k, v in labels_cfg.items()}
385386

386387
for label, color in labels_cfg.items():
387388
if repo_label := repo_labels.get(label):
@@ -503,7 +504,7 @@ def slugify_context(s: str):
503504
def __init__(
504505
self,
505506
patchwork: Patchwork,
506-
labels_cfg: dict[str, Any],
507+
labels_cfg: Dict[str, Any],
507508
repo_branch: str,
508509
repo_url: str,
509510
upstream_url: str,
@@ -512,10 +513,10 @@ def __init__(
512513
ci_repo_url: str,
513514
ci_branch: str,
514515
log_extractor: GithubLogExtractor,
515-
github_oauth_token: str | None = None,
516-
app_auth: Auth.AppInstallationAuth | None = None,
517-
email: EmailConfig | None = None,
518-
http_retries: int | None = None,
516+
github_oauth_token: Optional[str] = None,
517+
app_auth: Optional[Auth.AppInstallationAuth] = None,
518+
email: Optional[EmailConfig] = None,
519+
http_retries: Optional[int] = None,
519520
) -> None:
520521
super().__init__(
521522
repo_url=repo_url,
@@ -547,7 +548,7 @@ def __init__(
547548
create_color_labels(labels_cfg, self.repo)
548549
# member variables
549550
self.branches = {}
550-
self.prs: dict[str, PullRequest] = {}
551+
self.prs: Dict[str, PullRequest] = {}
551552
self.all_prs = {}
552553
self._closed_prs = None
553554

@@ -564,7 +565,7 @@ def _add_pull_request_comment(self, pr: PullRequest, message: str) -> None:
564565
try:
565566
pr.create_issue_comment(message)
566567
except GithubException as e:
567-
if not isinstance(e.data, dict):
568+
if not isinstance(e.data, Dict):
568569
raise e
569570
emsg = e.data.get("message")
570571
if emsg is not None and emsg in KNOWN_OK_COMMENT_EXCEPTIONS:
@@ -576,7 +577,7 @@ def _add_pull_request_comment(self, pr: PullRequest, message: str) -> None:
576577

577578
def _update_e2e_pr(
578579
self, title: str, base_branch: str, branch: str, has_codechange: bool
579-
) -> PullRequest | None:
580+
) -> Optional[PullRequest]:
580581
"""Check if there is open PR on e2e branch, reopen if necessary."""
581582
pr = None
582583

@@ -597,7 +598,9 @@ def _update_e2e_pr(
597598

598599
return pr
599600

600-
def update_e2e_test_branch_and_update_pr(self, branch: str) -> PullRequest | None:
601+
def update_e2e_test_branch_and_update_pr(
602+
self, branch: str
603+
) -> Optional[PullRequest]:
601604
base_branch = branch + "_base"
602605
branch_name = branch + "_test"
603606

@@ -721,8 +724,8 @@ def _close_pr(self, pr: PullRequest) -> None:
721724
pr.edit(state="closed")
722725

723726
async def _guess_pr(
724-
self, series: Series, branch: str | None = None
725-
) -> PullRequest | None:
727+
self, series: Series, branch: Optional[str] = None
728+
) -> Optional[PullRequest]:
726729
"""
727730
Series could change name
728731
first series in a subject could be changed as well
@@ -754,11 +757,11 @@ async def _comment_series_pr(
754757
self,
755758
series: Series,
756759
branch_name: str,
757-
message: str | None = None,
760+
message: Optional[str] = None,
758761
can_create: bool = False,
759762
close: bool = False,
760763
has_merge_conflict: bool = False,
761-
) -> PullRequest | None:
764+
) -> Optional[PullRequest]:
762765
"""
763766
Appends comment to a PR.
764767
"""
@@ -894,7 +897,7 @@ def _add_ci_files(self) -> None:
894897

895898
async def try_apply_mailbox_series(
896899
self, branch_name: str, series: Series
897-
) -> tuple[bool, Exception | None, Any | None]:
900+
) -> Tuple[bool, Optional[Exception], Optional[Any]]:
898901
"""Try to apply a mailbox series and return (True, None, None) if successful"""
899902
# The pull request will be created against `repo_pr_base_branch`. So
900903
# prepare it for that.
@@ -916,7 +919,7 @@ async def try_apply_mailbox_series(
916919

917920
async def apply_push_comment(
918921
self, branch_name: str, series: Series
919-
) -> PullRequest | None:
922+
) -> Optional[PullRequest]:
920923
comment = (
921924
f"Upstream branch: {self.upstream_sha}\nseries: {series.web_url}\n"
922925
f"version: {series.version}\n"
@@ -999,7 +1002,7 @@ async def apply_push_comment(
9991002

10001003
async def checkout_and_patch(
10011004
self, branch_name: str, series_to_apply: Series
1002-
) -> PullRequest | None:
1005+
) -> Optional[PullRequest]:
10031006
"""
10041007
Patch in place and push.
10051008
Returns true if whole series applied.
@@ -1049,7 +1052,7 @@ def _is_relevant_pr(self, pr: PullRequest) -> bool:
10491052
return True
10501053
return False
10511054

1052-
def closed_prs(self) -> list[Any]:
1055+
def closed_prs(self) -> List[Any]:
10531056
# GH api is not working: https://github.community/t/is-api-head-filter-even-working/135530
10541057
# so i have to implement local cache
10551058
# and local search
@@ -1061,7 +1064,7 @@ def closed_prs(self) -> list[Any]:
10611064
)
10621065
return self._closed_prs
10631066

1064-
def filter_closed_pr(self, head: str) -> PullRequest | None:
1067+
def filter_closed_pr(self, head: str) -> Optional[PullRequest]:
10651068
# this assumes only the most recent one closed PR per head
10661069
res = None
10671070
for pr in self.closed_prs():
@@ -1092,7 +1095,7 @@ async def sync_checks(self, pr: PullRequest, series: Series) -> None:
10921095

10931096
logger.info(f"Fetching workflow runs for {pr}: {pr.head.ref} (@ {pr.head.sha})")
10941097

1095-
statuses: list[Status] = []
1098+
statuses: List[Status] = []
10961099
jobs = []
10971100

10981101
# Note that we are interested in listing *all* runs and not just, say,
@@ -1162,7 +1165,7 @@ async def sync_checks(self, pr: PullRequest, series: Series) -> None:
11621165
await self.evaluate_ci_result(status, series, pr, jobs)
11631166

11641167
async def evaluate_ci_result(
1165-
self, status: Status, series: Series, pr: PullRequest, jobs: list[WorkflowJob]
1168+
self, status: Status, series: Series, pr: PullRequest, jobs: List[WorkflowJob]
11661169
) -> None:
11671170
"""Evaluate the result of a CI run and send an email as necessary."""
11681171
email = self.email

kernel_patches_daemon/config.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import os
1313
import re
1414
from dataclasses import dataclass
15+
from typing import Dict, List, Optional, Set
1516

1617

1718
logger = logging.getLogger(__name__)
@@ -43,7 +44,7 @@ def _read_private_key(cls, private_key_path: os.PathLike) -> str:
4344
) from e
4445

4546
@classmethod
46-
def from_json(cls, json: dict) -> "GithubAppAuthConfig":
47+
def from_json(cls, json: Dict) -> "GithubAppAuthConfig":
4748
private_key_config = json.keys() & {
4849
"private_key",
4950
"private_key_path",
@@ -77,12 +78,12 @@ class BranchConfig:
7778
upstream_branch: str
7879
ci_repo: str
7980
ci_branch: str
80-
github_oauth_token: str | None
81-
github_app_auth: GithubAppAuthConfig | None
81+
github_oauth_token: Optional[str]
82+
github_app_auth: Optional[GithubAppAuthConfig]
8283

8384
@classmethod
84-
def from_json(cls, json: dict) -> "BranchConfig":
85-
github_app_auth_config: GithubAppAuthConfig | None = None
85+
def from_json(cls, json: Dict) -> "BranchConfig":
86+
github_app_auth_config: Optional[GithubAppAuthConfig] = None
8687
if app_auth_json := json.get("github_app_auth"):
8788
try:
8889
github_app_auth_config = GithubAppAuthConfig.from_json(app_auth_json)
@@ -107,21 +108,21 @@ class EmailConfig:
107108
smtp_user: str
108109
smtp_from: str
109110
smtp_pass: str
110-
smtp_to: list[str]
111-
smtp_cc: list[str]
112-
smtp_http_proxy: str | None
111+
smtp_to: List[str]
112+
smtp_cc: List[str]
113+
smtp_http_proxy: Optional[str]
113114
# List of email addresses of patch submitters to whom we send email
114115
# notifications only for *their* very submission. This attribute is meant to
115116
# be temporary while the email notification feature is being rolled out.
116117
# Once we send email notifications to all patch submitters it can be
117118
# removed.
118-
submitter_allowlist: list[re.Pattern]
119+
submitter_allowlist: List[re.Pattern]
119120
# Ignore the `submitter_allowlist` entries and send emails to all patch
120121
# submitters, unconditionally.
121122
ignore_allowlist: bool
122123

123124
@classmethod
124-
def from_json(cls, json: dict) -> "EmailConfig":
125+
def from_json(cls, json: Dict) -> "EmailConfig":
125126
return cls(
126127
smtp_host=json["host"],
127128
smtp_port=json.get("port", 465),
@@ -142,13 +143,13 @@ def from_json(cls, json: dict) -> "EmailConfig":
142143
class PatchworksConfig:
143144
base_url: str
144145
project: str
145-
search_patterns: list[dict]
146+
search_patterns: List[Dict]
146147
lookback: int
147-
user: str | None
148-
token: str | None
148+
user: Optional[str]
149+
token: Optional[str]
149150

150151
@classmethod
151-
def from_json(cls, json: dict) -> "PatchworksConfig":
152+
def from_json(cls, json: Dict) -> "PatchworksConfig":
152153
return cls(
153154
base_url=json["server"],
154155
project=json["project"],
@@ -163,13 +164,13 @@ def from_json(cls, json: dict) -> "PatchworksConfig":
163164
class KPDConfig:
164165
version: int
165166
patchwork: PatchworksConfig
166-
email: EmailConfig | None
167-
branches: dict[str, BranchConfig]
168-
tag_to_branch_mapping: dict[str, list[str]]
167+
email: Optional[EmailConfig]
168+
branches: Dict[str, BranchConfig]
169+
tag_to_branch_mapping: Dict[str, List[str]]
169170
base_directory: str
170171

171172
@classmethod
172-
def from_json(cls, json: dict) -> "KPDConfig":
173+
def from_json(cls, json: Dict) -> "KPDConfig":
173174
try:
174175
version = int(json["version"])
175176
except (KeyError, IndexError) as e:

kernel_patches_daemon/daemon.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
import logging
1111
import signal
1212
import threading
13-
from collections.abc import Callable
14-
from typing import Final
13+
from typing import Callable, Dict, Final, Optional
1514

1615
from kernel_patches_daemon.config import KPDConfig
1716
from kernel_patches_daemon.github_sync import GithubSync
@@ -33,8 +32,8 @@ class KernelPatchesWorker:
3332
def __init__(
3433
self,
3534
kpd_config: KPDConfig,
36-
labels_cfg: dict[str, str],
37-
metrics_logger: Callable | None = None,
35+
labels_cfg: Dict[str, str],
36+
metrics_logger: Optional[Callable] = None,
3837
loop_delay: int = DEFAULT_LOOP_DELAY,
3938
max_concurrent_restarts: int = DEFAULT_MAX_CONCURRENT_RESTARTS,
4039
) -> None:
@@ -77,12 +76,12 @@ class KernelPatchesDaemon:
7776
def __init__(
7877
self,
7978
kpd_config: KPDConfig,
80-
labels_cfg: dict[str, str],
81-
metrics_logger: Callable | None = None,
79+
labels_cfg: Dict[str, str],
80+
metrics_logger: Optional[Callable] = None,
8281
max_concurrent_restarts: int = 1,
8382
) -> None:
8483
self._stopping_lock = threading.Lock()
85-
self._task: asyncio.Task | None = None
84+
self._task: Optional[asyncio.Task] = None
8685
self.worker = KernelPatchesWorker(
8786
kpd_config=kpd_config,
8887
labels_cfg=labels_cfg,

kernel_patches_daemon/github_connector.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import os
1111
from datetime import timedelta
1212
from enum import Enum
13+
from typing import Optional
1314
from urllib.parse import urlparse
1415

1516
from github import Auth, Github, GithubException, GithubIntegration
@@ -60,9 +61,9 @@ class GithubConnector:
6061
def __init__(
6162
self,
6263
repo_url: str,
63-
github_oauth_token: str | None = None,
64-
app_auth: Auth.AppInstallationAuth | None = None,
65-
http_retries: int | None = None,
64+
github_oauth_token: Optional[str] = None,
65+
app_auth: Optional[Auth.AppInstallationAuth] = None,
66+
http_retries: Optional[int] = None,
6667
) -> None:
6768

6869
assert bool(github_oauth_token) ^ bool(

0 commit comments

Comments
 (0)