Skip to content

Commit 0a2ac6e

Browse files
committed
add mypy support
1 parent 79e0cb5 commit 0a2ac6e

10 files changed

Lines changed: 134 additions & 51 deletions

File tree

.github/workflows/connect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
found = True
1414
break
1515
except URLError as e:
16-
if e.reason.errno == errno.ECONNREFUSED:
16+
if e.reason.errno == errno.ECONNREFUSED: # type:ignore
1717
time.sleep(1)
1818
continue
1919
raise

.mypy.ini

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
[mypy]
2+
check_untyped_defs = true
3+
disallow_incomplete_defs = true
4+
no_implicit_optional = true
5+
pretty = true
6+
show_error_context = true
7+
show_error_codes = true
8+
strict_equality = true
9+
strict_optional = true
10+
warn_no_return = true
11+
warn_return_any = true
12+
warn_unused_configs = true
13+
warn_unused_ignores = true
14+
warn_redundant_casts = true
15+
16+
[mypy-black]
17+
ignore_missing_imports = True
18+
19+
[mypy-jwt]
20+
ignore_missing_imports = True
21+
22+
[mypy-git]
23+
ignore_missing_imports = True
24+
25+
[mypy-keen]
26+
ignore_missing_imports = True
27+
28+
[mypy-pytest]
29+
ignore_missing_imports = True
30+
31+
[mypy-there]
32+
ignore_missing_imports = True
33+
34+
[mypy-yieldbreaker]
35+
ignore_missing_imports = True

.pre-commit-config.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,14 @@ repos:
3636
]
3737
stages: [manual]
3838

39+
- repo: https://github.com/pre-commit/mirrors-mypy
40+
rev: "v0.942"
41+
hooks:
42+
- id: mypy
43+
args: ["--config-file", ".mypy.ini"]
44+
additional_dependencies: [types-requests, types-PyYAML, types-mock, tornado]
45+
stages: [manual]
46+
3947
- repo: https://github.com/sirosen/check-jsonschema
4048
rev: 0.14.2
4149
hooks:

meeseeksdev/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
"scikit-image",
4040
]
4141

42-
usr_denylist = []
42+
usr_denylist: list = []
4343

4444
usr_allowlist = [
4545
"Carreau",
@@ -91,12 +91,12 @@ def load_config_from_env():
9191
"""
9292
Load the configuration, for now stored in the environment
9393
"""
94-
config = {}
94+
config: dict = {}
9595

96-
integration_id = os.environ.get("GITHUB_INTEGRATION_ID")
96+
integration_id_str = os.environ.get("GITHUB_INTEGRATION_ID")
9797
botname = os.environ.get("GITHUB_BOT_NAME", None)
9898

99-
if not integration_id:
99+
if not integration_id_str:
100100
raise ValueError("Please set GITHUB_INTEGRATION_ID")
101101

102102
if not botname:
@@ -106,7 +106,7 @@ def load_config_from_env():
106106

107107
botname = botname.replace("@", "")
108108
at_botname = "@" + botname
109-
integration_id = int(integration_id)
109+
integration_id = int(integration_id_str)
110110

111111
if "B64KEY" in os.environ:
112112
config["key"] = base64.b64decode(bytes(os.environ["B64KEY"], "ASCII"))

meeseeksdev/commands.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
from textwrap import dedent
6+
from typing import Generator, Optional
67

78
from .meeseeksbox.commands import tag, untag
89
from .meeseeksbox.scopes import everyone, pr_author, write
@@ -49,7 +50,9 @@ def open(*, session, payload, arguments, local_config=None):
4950

5051

5152
@write
52-
def migrate_issue_request(*, session: Session, payload: dict, arguments: str, local_config=None):
53+
def migrate_issue_request(
54+
*, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
55+
) -> Generator:
5356
"""[to] {org}/{repo}
5457
5558
Need to be admin on target repo. Replicate all comments on target repo and close current on.

meeseeksdev/meeseeksbox/commands.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import traceback
1212
from pathlib import Path
1313
from textwrap import dedent
14+
from typing import Generator, Optional
1415

1516
import git
1617
import mock
@@ -117,12 +118,12 @@ def _compute_pwd_changes(allowlist):
117118
print("== pwd", os.getcwd())
118119
print("== listdir", os.listdir())
119120

120-
for p in glob.glob("**/*.py", recursive=True):
121-
print("=== scanning", p, p in allowlist)
122-
if p not in allowlist:
121+
for path in glob.glob("**/*.py", recursive=True):
122+
print("=== scanning", path, path in allowlist)
123+
if path not in allowlist:
123124
# we don't touch files not in this PR.
124125
continue
125-
p = Path(p)
126+
p = Path(path)
126127
old = p.read_text()
127128
new = black.format_str(old, mode=black.FileMode())
128129
if new != old:
@@ -309,7 +310,9 @@ def black_suggest(*, session, payload, arguments, local_config=None):
309310
print("== Done cleaning ")
310311

311312

312-
def prep_for_command(name, session, payload, arguments, local_config=None):
313+
def prep_for_command(
314+
name: str, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
315+
) -> Generator:
313316
"""Prepare to run a command against a local checkout of a repo."""
314317
print(f"===== running command {name} =====")
315318
print("===== ============ =====")
@@ -335,8 +338,11 @@ def prep_for_command(name, session, payload, arguments, local_config=None):
335338
repo_name = pr_data["head"]["repo"]["name"]
336339
maintainer_can_modify = pr_data["maintainer_can_modify"]
337340

341+
print(f"Got author login {author_login}")
342+
338343
# Check to see if we can successfully push changees to the PR.
339344
target_session = yield "{}/{}".format(author_login, repo_name)
345+
340346
if target_session:
341347
print("installed on target repository")
342348
atk = target_session.token()
@@ -429,7 +435,9 @@ def push_the_work(session, payload, arguments, local_config=None):
429435

430436

431437
@admin
432-
def precommit(*, session, payload, arguments, local_config=None):
438+
def precommit(
439+
*, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
440+
) -> Generator:
433441
comment_url = payload["issue"]["comments_url"]
434442

435443
"""Run pre-commit against a PR and push the changes."""
@@ -602,12 +610,13 @@ def safe_backport(session, payload, arguments, local_config=None):
602610

603611
print = lambda *args, **kwargs: builtins.print(" [backport]", *args, **kwargs)
604612

605-
s_clone_time = 0
613+
s_clone_time = 0.0
606614
s_success = False
607615
s_reason = "unknown"
608-
s_fork_time = 0
609-
s_clean_time = 0
610-
s_ff_time = 0
616+
s_fork_time = 0.0
617+
s_clean_time = 0.0
618+
s_ff_time = 0.0
619+
s_slug = ""
611620

612621
def keen_stats():
613622
nonlocal s_slug
@@ -816,7 +825,7 @@ def keen_stats():
816825
print("== All has been fetched correctly")
817826

818827
print("Cherry-picking %s" % merge_sha)
819-
args = ("-x", "-m", "1", merge_sha)
828+
args: tuple = ("-x", "-m", "1", merge_sha)
820829

821830
msg = "Backport PR #%i: %s" % (prnumber, prtitle)
822831
remote_submit_branch = f"auto-backport-of-pr-{prnumber}-on-{target_branch}"
@@ -925,7 +934,10 @@ def keen_stats():
925934
session.post_comment(
926935
comment_url, "Hum, I actually crashed, that should not have happened."
927936
)
928-
print("\n" + e.stderr.decode("utf8", "replace"), file=sys.stderr)
937+
if hasattr(e, "stderr"):
938+
print(
939+
"\n" + e.stderr.decode("utf8", "replace"), file=sys.stderr
940+
) # type:ignore[attr-defined]
929941
print("\n" + repo.git.status(), file=sys.stderr)
930942
add_event("error", {"git_crash": 1})
931943
s_reason = "Unknown error line 501"
@@ -1133,7 +1145,9 @@ def untag(session, payload, arguments, local_config=None):
11331145

11341146

11351147
@write
1136-
def migrate_issue_request(*, session: Session, payload: dict, arguments: str, local_config=None):
1148+
def migrate_issue_request(
1149+
*, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
1150+
) -> Generator:
11371151
"""Todo:
11381152
11391153
- Works through pagination of comments

meeseeksdev/meeseeksbox/core.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
import json
55
import re
66
import time
7+
from asyncio import Future
78
from concurrent.futures import ThreadPoolExecutor as Pool
9+
from typing import Optional
810

911
import tornado.httpserver
1012
import tornado.ioloop
@@ -26,7 +28,7 @@
2628

2729
class Config:
2830
botname = None
29-
integration_id = None
31+
integration_id = -1
3032
key = None
3133
botname = None
3234
at_botname = None
@@ -79,7 +81,7 @@ def _strip_extras(c):
7981
return c
8082

8183

82-
def process_mentionning_comment(body, bot_re):
84+
def process_mentioning_comment(body: str, bot_re: re.Pattern) -> list:
8385
"""
8486
Given a comment body and a bot name parse this into a tuple of (command, arguments)
8587
"""
@@ -233,7 +235,7 @@ def mention_bot_re(self):
233235
botname = self.config.botname
234236
return re.compile("@?" + re.escape(botname) + r"(?:\[bot\])?", re.IGNORECASE)
235237

236-
def dispatch_action(self, type_, payload):
238+
def dispatch_action(self, type_: str, payload: dict) -> Future:
237239
botname = self.config.botname
238240
repo = payload.get("repository", {}).get("full_name", red + "<unknown repo>" + normal)
239241
# new issue/PR opened
@@ -349,13 +351,13 @@ def dispatch_action(self, type_, payload):
349351
milestone = is_pr.get("milestone", {})
350352
if milestone:
351353
description.append(milestone.get("description", "") or "")
352-
description = "\n".join(description)
354+
description_str = "\n".join(description)
353355
if "on-merge:" in description and is_pr["base"]["ref"] in (
354356
"master",
355357
"main",
356358
):
357359
did_backport = False
358-
for description_line in description.splitlines():
360+
for description_line in description_str.splitlines():
359361
line = description_line.strip()
360362
if line.startswith("on-merge:"):
361363
todo = line[len("on-merge:") :].strip()
@@ -381,6 +383,7 @@ def dispatch_action(self, type_, payload):
381383
else:
382384
pass
383385
# print(f"({repo}) can't deal with `{type_}` yet")
386+
return self.finish()
384387

385388
# def _action_allowed(args):
386389
# """
@@ -393,7 +396,7 @@ def dispatch_action(self, type_, payload):
393396
# - If pull-request, the requester is the author.
394397
# """
395398

396-
def dispatch_on_mention(self, body, payload, user):
399+
def dispatch_on_mention(self, body: str, payload: dict, user: str) -> None:
397400
"""
398401
Core of the logic that let people require actions from the bot.
399402
@@ -445,7 +448,7 @@ def dispatch_on_mention(self, body, payload, user):
445448
print(user, "is legitimate author of this PR, letting commands go through")
446449

447450
permission_level = session._get_permission(org, repo, user)
448-
command_args = process_mentionning_comment(body, self.mention_bot_re)
451+
command_args = process_mentioning_comment(body, self.mention_bot_re)
449452
for (command, arguments) in command_args:
450453
print(" :: treating", command, arguments)
451454
add_event(

0 commit comments

Comments
 (0)