Skip to content

Commit

Permalink
Merge pull request #78 from blink1073/setup-mypy
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Apr 11, 2022
2 parents 889d34f + 7cc8f8f commit 0935357
Show file tree
Hide file tree
Showing 10 changed files with 123 additions and 53 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
found = True
break
except URLError as e:
if e.reason.errno == errno.ECONNREFUSED:
if e.reason.errno == errno.ECONNREFUSED: # type:ignore
time.sleep(1)
continue
raise
Expand Down
23 changes: 23 additions & 0 deletions .mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[mypy]
check_untyped_defs = true
disallow_incomplete_defs = true
no_implicit_optional = true
pretty = true
show_error_context = true
show_error_codes = true
strict_equality = true
strict_optional = true
warn_no_return = true
warn_return_any = true
warn_unused_configs = true
warn_unused_ignores = true
warn_redundant_casts = true

[mypy-keen]
ignore_missing_imports = True

[mypy-there]
ignore_missing_imports = True

[mypy-yieldbreaker]
ignore_missing_imports = True
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ repos:
]
stages: [manual]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v0.942"
hooks:
- id: mypy
args: ["--config-file", ".mypy.ini"]
additional_dependencies: [types-requests, types-PyYAML, types-mock, tornado, black, pytest, gitpython, pyjwt]
stages: [manual]

- repo: https://github.com/sirosen/check-jsonschema
rev: 0.14.2
hooks:
Expand Down
10 changes: 5 additions & 5 deletions meeseeksdev/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"scikit-image",
]

usr_denylist = []
usr_denylist: list = []

usr_allowlist = [
"Carreau",
Expand Down Expand Up @@ -91,12 +91,12 @@ def load_config_from_env():
"""
Load the configuration, for now stored in the environment
"""
config = {}
config: dict = {}

integration_id = os.environ.get("GITHUB_INTEGRATION_ID")
integration_id_str = os.environ.get("GITHUB_INTEGRATION_ID")
botname = os.environ.get("GITHUB_BOT_NAME", None)

if not integration_id:
if not integration_id_str:
raise ValueError("Please set GITHUB_INTEGRATION_ID")

if not botname:
Expand All @@ -106,7 +106,7 @@ def load_config_from_env():

botname = botname.replace("@", "")
at_botname = "@" + botname
integration_id = int(integration_id)
integration_id = int(integration_id_str)

if "B64KEY" in os.environ:
config["key"] = base64.b64decode(bytes(os.environ["B64KEY"], "ASCII"))
Expand Down
5 changes: 4 additions & 1 deletion meeseeksdev/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

from textwrap import dedent
from typing import Generator, Optional

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


@write
def migrate_issue_request(*, session: Session, payload: dict, arguments: str, local_config=None):
def migrate_issue_request(
*, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
) -> Generator:
"""[to] {org}/{repo}
Need to be admin on target repo. Replicate all comments on target repo and close current on.
Expand Down
43 changes: 28 additions & 15 deletions meeseeksdev/meeseeksbox/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import traceback
from pathlib import Path
from textwrap import dedent
from typing import Generator, Optional

import git
import mock
Expand Down Expand Up @@ -117,12 +118,12 @@ def _compute_pwd_changes(allowlist):
print("== pwd", os.getcwd())
print("== listdir", os.listdir())

for p in glob.glob("**/*.py", recursive=True):
print("=== scanning", p, p in allowlist)
if p not in allowlist:
for path in glob.glob("**/*.py", recursive=True):
print("=== scanning", path, path in allowlist)
if path not in allowlist:
# we don't touch files not in this PR.
continue
p = Path(p)
p = Path(path)
old = p.read_text()
new = black.format_str(old, mode=black.FileMode())
if new != old:
Expand Down Expand Up @@ -309,7 +310,9 @@ def black_suggest(*, session, payload, arguments, local_config=None):
print("== Done cleaning ")


def prep_for_command(name, session, payload, arguments, local_config=None):
def prep_for_command(
name: str, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
) -> Generator:
"""Prepare to run a command against a local checkout of a repo."""
print(f"===== running command {name} =====")
print("===== ============ =====")
Expand Down Expand Up @@ -337,6 +340,7 @@ def prep_for_command(name, session, payload, arguments, local_config=None):

# Check to see if we can successfully push changees to the PR.
target_session = yield "{}/{}".format(author_login, repo_name)

if target_session:
print("installed on target repository")
atk = target_session.token()
Expand Down Expand Up @@ -424,12 +428,14 @@ def push_the_work(session, payload, arguments, local_config=None):
"GET", f"https://api.github.com/repos/{org_name}/{repo_name}"
).json()["default_branch"]
repo.git.checkout(default_branch)
repo.branches.workbranch.delete(repo, "workbranch", force=True)
repo.branches.workbranch.delete(repo, "workbranch", force=True) # type:ignore[attr-defined]
return succeeded


@admin
def precommit(*, session, payload, arguments, local_config=None):
def precommit(
*, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
) -> Generator:
comment_url = payload["issue"]["comments_url"]

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

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

s_clone_time = 0
s_clone_time = 0.0
s_success = False
s_reason = "unknown"
s_fork_time = 0
s_clean_time = 0
s_ff_time = 0
s_fork_time = 0.0
s_clean_time = 0.0
s_ff_time = 0.0
s_slug = ""

def keen_stats():
nonlocal s_slug
Expand Down Expand Up @@ -816,7 +823,7 @@ def keen_stats():
print("== All has been fetched correctly")

print("Cherry-picking %s" % merge_sha)
args = ("-x", "-m", "1", merge_sha)
args: tuple = ("-x", "-m", "1", merge_sha)

msg = "Backport PR #%i: %s" % (prnumber, prtitle)
remote_submit_branch = f"auto-backport-of-pr-{prnumber}-on-{target_branch}"
Expand Down Expand Up @@ -925,7 +932,11 @@ def keen_stats():
session.post_comment(
comment_url, "Hum, I actually crashed, that should not have happened."
)
print("\n" + e.stderr.decode("utf8", "replace"), file=sys.stderr)
if hasattr(e, "stderr"):
print(
"\n" + e.stderr.decode("utf8", "replace"), # type:ignore[attr-defined]
file=sys.stderr,
)
print("\n" + repo.git.status(), file=sys.stderr)
add_event("error", {"git_crash": 1})
s_reason = "Unknown error line 501"
Expand Down Expand Up @@ -964,7 +975,7 @@ def keen_stats():
succeeded = False

repo.git.checkout(default_branch)
repo.branches.workbranch.delete(repo, "workbranch", force=True)
repo.branches.workbranch.delete(repo, "workbranch", force=True) # type:ignore[attr-defined]

# TODO checkout the default_branch and get rid of branch

Expand Down Expand Up @@ -1142,7 +1153,9 @@ def untag(session, payload, arguments, local_config=None):


@write
def migrate_issue_request(*, session: Session, payload: dict, arguments: str, local_config=None):
def migrate_issue_request(
*, session: Session, payload: dict, arguments: str, local_config: Optional[dict] = None
) -> Generator:
"""Todo:
- Works through pagination of comments
Expand Down
16 changes: 9 additions & 7 deletions meeseeksdev/meeseeksbox/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import re
import time
from asyncio import Future
from concurrent.futures import ThreadPoolExecutor as Pool

import tornado.httpserver
Expand All @@ -26,7 +27,7 @@

class Config:
botname = None
integration_id = None
integration_id = -1
key = None
botname = None
at_botname = None
Expand Down Expand Up @@ -79,7 +80,7 @@ def _strip_extras(c):
return c


def process_mentionning_comment(body, bot_re):
def process_mentioning_comment(body: str, bot_re: re.Pattern) -> list:
"""
Given a comment body and a bot name parse this into a tuple of (command, arguments)
"""
Expand Down Expand Up @@ -233,7 +234,7 @@ def mention_bot_re(self):
botname = self.config.botname
return re.compile("@?" + re.escape(botname) + r"(?:\[bot\])?", re.IGNORECASE)

def dispatch_action(self, type_, payload):
def dispatch_action(self, type_: str, payload: dict) -> Future:
botname = self.config.botname
repo = payload.get("repository", {}).get("full_name", red + "<unknown repo>" + normal)
# new issue/PR opened
Expand Down Expand Up @@ -349,13 +350,13 @@ def dispatch_action(self, type_, payload):
milestone = is_pr.get("milestone", {})
if milestone:
description.append(milestone.get("description", "") or "")
description = "\n".join(description)
description_str = "\n".join(description)
if "on-merge:" in description and is_pr["base"]["ref"] in (
"master",
"main",
):
did_backport = False
for description_line in description.splitlines():
for description_line in description_str.splitlines():
line = description_line.strip()
if line.startswith("on-merge:"):
todo = line[len("on-merge:") :].strip()
Expand All @@ -381,6 +382,7 @@ def dispatch_action(self, type_, payload):
else:
pass
# print(f"({repo}) can't deal with `{type_}` yet")
return self.finish()

# def _action_allowed(args):
# """
Expand All @@ -393,7 +395,7 @@ def dispatch_action(self, type_, payload):
# - If pull-request, the requester is the author.
# """

def dispatch_on_mention(self, body, payload, user):
def dispatch_on_mention(self, body: str, payload: dict, user: str) -> None:
"""
Core of the logic that let people require actions from the bot.
Expand Down Expand Up @@ -445,7 +447,7 @@ def dispatch_on_mention(self, body, payload, user):
print(user, "is legitimate author of this PR, letting commands go through")

permission_level = session._get_permission(org, repo, user)
command_args = process_mentionning_comment(body, self.mention_bot_re)
command_args = process_mentioning_comment(body, self.mention_bot_re)
for (command, arguments) in command_args:
print(" :: treating", command, arguments)
add_event(
Expand Down
Loading

0 comments on commit 0935357

Please sign in to comment.