Skip to content

Commit 9ee5393

Browse files
miss-islingtonMariatta
authored andcommitted
🤖 Format code using black (#106)
Closes #105 (I'm a bot 🤖)
1 parent 92ae45c commit 9ee5393

10 files changed

+824
-943
lines changed

miss_islington/__main__.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@
1616
from . import delete_branch
1717
from . import status_change
1818

19-
router = routing.Router(backport_pr.router,
20-
delete_branch.router,
21-
status_change.router)
19+
router = routing.Router(backport_pr.router, delete_branch.router, status_change.router)
2220

2321
cache = cachetools.LRUCache(maxsize=500)
2422

@@ -29,14 +27,14 @@ async def main(request):
2927

3028
secret = os.environ.get("GH_SECRET")
3129
event = sansio.Event.from_http(request.headers, body, secret=secret)
32-
print('GH delivery ID', event.delivery_id, file=sys.stderr)
30+
print("GH delivery ID", event.delivery_id, file=sys.stderr)
3331
if event.event == "ping":
3432
return web.Response(status=200)
3533
oauth_token = os.environ.get("GH_AUTH")
3634
async with aiohttp.ClientSession() as session:
37-
gh = gh_aiohttp.GitHubAPI(session, "python/cpython",
38-
oauth_token=oauth_token,
39-
cache=cache)
35+
gh = gh_aiohttp.GitHubAPI(
36+
session, "python/cpython", oauth_token=oauth_token, cache=cache
37+
)
4038
# Give GitHub some time to reach internal consistency.
4139
await asyncio.sleep(1)
4240
await router.dispatch(event, gh)

miss_islington/backport_pr.py

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,27 @@
1515
async def backport_pr(event, gh, *args, **kwargs):
1616
if event.data["pull_request"]["merged"]:
1717

18-
issue_number = event.data['pull_request']['number']
19-
merged_by = event.data['pull_request']['merged_by']['login']
20-
created_by = event.data['pull_request']['user']['login']
18+
issue_number = event.data["pull_request"]["number"]
19+
merged_by = event.data["pull_request"]["merged_by"]["login"]
20+
created_by = event.data["pull_request"]["user"]["login"]
2121

22-
commit_hash = event.data['pull_request']['merge_commit_sha']
22+
commit_hash = event.data["pull_request"]["merge_commit_sha"]
2323

2424
pr_labels = []
25-
if event.data['action'] == 'labeled':
25+
if event.data["action"] == "labeled":
2626
pr_labels = [event.data["label"]]
2727
else:
28-
gh_issue = await gh.getitem(event.data['repository']['issues_url'],
29-
{'number': f"{event.data['pull_request']['number']}"})
30-
pr_labels = await gh.getitem(gh_issue['labels_url'])
28+
gh_issue = await gh.getitem(
29+
event.data["repository"]["issues_url"],
30+
{"number": f"{event.data['pull_request']['number']}"},
31+
)
32+
pr_labels = await gh.getitem(gh_issue["labels_url"])
3133

32-
branches = [label['name'].split()[-1]
33-
for label in pr_labels
34-
if label['name'].startswith("needs backport to")]
34+
branches = [
35+
label["name"].split()[-1]
36+
for label in pr_labels
37+
if label["name"].startswith("needs backport to")
38+
]
3539

3640
if branches:
3741
easter_egg = ""
@@ -42,19 +46,19 @@ async def backport_pr(event, gh, *args, **kwargs):
4246
thanks_to = f"Thanks @{created_by} for the PR 🌮🎉."
4347
else:
4448
thanks_to = f"Thanks @{created_by} for the PR, and @{merged_by} for merging it 🌮🎉."
45-
message = f"{thanks_to}. I'm working now to backport this PR to: {', '.join(branches)}."\
46-
f"\n🐍🍒⛏🤖 {easter_egg}"
49+
message = f"{thanks_to}. I'm working now to backport this PR to: {', '.join(branches)}." f"\n🐍🍒⛏🤖 {easter_egg}"
4750

4851
await util.leave_comment(gh, issue_number, message)
4952

50-
sorted_branches = sorted(branches,
51-
reverse=True,
52-
key=lambda v: tuple(map(int, v.split('.'))))
53+
sorted_branches = sorted(
54+
branches, reverse=True, key=lambda v: tuple(map(int, v.split(".")))
55+
)
5356

5457
for branch in sorted_branches:
55-
tasks.backport_task.delay(commit_hash,
56-
branch,
57-
issue_number=issue_number,
58-
created_by=created_by,
59-
merged_by=merged_by)
60-
58+
tasks.backport_task.delay(
59+
commit_hash,
60+
branch,
61+
issue_number=issue_number,
62+
created_by=created_by,
63+
merged_by=merged_by,
64+
)

miss_islington/delete_branch.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ async def delete_branch(event, gh, *args, **kwargs):
99
Delete the branch once miss-islington's PR is closed.
1010
"""
1111
if event.data["pull_request"]["user"]["login"] == "miss-islington":
12-
branch_name = event.data['pull_request']['head']['ref']
12+
branch_name = event.data["pull_request"]["head"]["ref"]
1313
url = f"/repos/miss-islington/cpython/git/refs/heads/{branch_name}"
1414
await gh.delete(url)
15-

miss_islington/status_change.py

Lines changed: 40 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,18 @@
66

77
router = routing.Router()
88

9-
TITLE_RE = re.compile(r'\[(?P<branch>\d+\.\d+)\].+?(?P<pr>\d+)\)')
9+
TITLE_RE = re.compile(r"\[(?P<branch>\d+\.\d+)\].+?(?P<pr>\d+)\)")
1010

1111

1212
@router.register("status")
1313
async def check_status(event, gh, *args, **kwargs):
1414
"""
1515
Check the state change
1616
"""
17-
if event.data["commit"].get("committer") \
18-
and event.data["commit"]["committer"]["login"] == "miss-islington":
17+
if (
18+
event.data["commit"].get("committer")
19+
and event.data["commit"]["committer"]["login"] == "miss-islington"
20+
):
1921
sha = event.data["sha"]
2022
await check_ci_status_and_approval(gh, sha, leave_comment=True)
2123

@@ -32,45 +34,53 @@ async def pr_reviewed(event, gh, *args, **kwargs):
3234

3335
async def check_ci_status_and_approval(gh, sha, leave_comment=False):
3436

35-
result = await gh.getitem(f'/repos/python/cpython/commits/{sha}/status')
37+
result = await gh.getitem(f"/repos/python/cpython/commits/{sha}/status")
3638
all_ci_status = [status["state"] for status in result["statuses"]]
3739
all_ci_context = [status["context"] for status in result["statuses"]]
3840

39-
if "pending" not in all_ci_status \
40-
and "continuous-integration/travis-ci/pr" in all_ci_context:
41-
async for ref in gh.getiter('/repos/miss-islington/cpython/git/refs/heads/'):
41+
if (
42+
"pending" not in all_ci_status
43+
and "continuous-integration/travis-ci/pr" in all_ci_context
44+
):
45+
async for ref in gh.getiter("/repos/miss-islington/cpython/git/refs/heads/"):
4246
if "backport-" in ref["ref"] and ref["object"]["sha"] == sha:
4347
backport_branch_name = ref["ref"].split("/")[-1]
44-
async for pr_response in gh.getiter(f'/repos/python/cpython/pulls?state=open&head=miss-islington:{backport_branch_name}'):
48+
async for pr_response in gh.getiter(
49+
f"/repos/python/cpython/pulls?state=open&head=miss-islington:{backport_branch_name}"
50+
):
4551
pr_number = pr_response["number"]
4652
normalized_pr_title = util.normalize_title(
47-
pr_response["title"],
48-
pr_response["body"])
53+
pr_response["title"], pr_response["body"]
54+
)
4955

5056
title_match = TITLE_RE.match(normalized_pr_title)
5157
if title_match:
5258

5359
if leave_comment:
54-
original_pr_number = title_match.group('pr')
55-
original_pr_url = f"/repos/python/cpython/pulls/{original_pr_number}"
60+
original_pr_number = title_match.group("pr")
61+
original_pr_url = (
62+
f"/repos/python/cpython/pulls/{original_pr_number}"
63+
)
5664
original_pr_result = await gh.getitem(original_pr_url)
5765
pr_author = original_pr_result["user"]["login"]
5866
committer = original_pr_result["merged_by"]["login"]
5967

60-
participants = util.get_participants(
61-
pr_author, committer)
62-
emoji = "✅" if result['state'] == "success" else "❌"
68+
participants = util.get_participants(pr_author, committer)
69+
emoji = "✅" if result["state"] == "success" else "❌"
6370

64-
await util.leave_comment(gh,
71+
await util.leave_comment(
72+
gh,
6573
pr_number=pr_number,
66-
message=f"{participants}: Backport status check is done, and it's a {result['state']} {emoji} .")
74+
message=f"{participants}: Backport status check is done, and it's a {result['state']} {emoji} .",
75+
)
6776

68-
if result['state'] == "success":
69-
async for review in gh.getiter(f"/repos/python/cpython/pulls/{pr_number}/reviews"):
77+
if result["state"] == "success":
78+
async for review in gh.getiter(
79+
f"/repos/python/cpython/pulls/{pr_number}/reviews"
80+
):
7081
reviewer = review["user"]["login"]
7182
approved = review["state"].lower() == "approved"
72-
if approved \
73-
and await util.is_core_dev(gh, reviewer):
83+
if approved and await util.is_core_dev(gh, reviewer):
7484
await merge_pr(gh, pr_number, sha)
7585
break
7686

@@ -81,14 +91,13 @@ async def merge_pr(gh, pr_number, sha):
8191
pr_commit_msg = commit["commit"]["message"].split("\n")
8292

8393
cleaned_up_title = f"{pr_commit_msg[0]}"
84-
await gh.put(f"/repos/python/cpython/pulls/{pr_number}/merge",
85-
data={"commit_title": cleaned_up_title,
86-
"commit_message": "\n".join(pr_commit_msg[1:]),
87-
"sha": sha,
88-
"merge_method": "squash"
89-
}
90-
)
94+
await gh.put(
95+
f"/repos/python/cpython/pulls/{pr_number}/merge",
96+
data={
97+
"commit_title": cleaned_up_title,
98+
"commit_message": "\n".join(pr_commit_msg[1:]),
99+
"sha": sha,
100+
"merge_method": "squash",
101+
},
102+
)
91103
break
92-
93-
94-

miss_islington/tasks.py

Lines changed: 37 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,30 @@
88

99
from . import util
1010

11-
app = celery.Celery('backport_cpython')
11+
app = celery.Celery("backport_cpython")
1212

13-
app.conf.update(BROKER_URL=os.environ['REDIS_URL'],
14-
CELERY_RESULT_BACKEND=os.environ['REDIS_URL'])
13+
app.conf.update(
14+
BROKER_URL=os.environ["REDIS_URL"], CELERY_RESULT_BACKEND=os.environ["REDIS_URL"]
15+
)
1516

1617

1718
@app.task(rate_limit="1/m")
1819
def setup_cpython_repo():
1920
print("Setting up CPython repository")
20-
if "cpython" not in os.listdir('.'):
21+
if "cpython" not in os.listdir("."):
2122
subprocess.check_output(
22-
f"git clone https://{os.environ.get('GH_AUTH')}:[email protected]/miss-islington/cpython.git".split())
23-
subprocess.check_output("git config --global user.email '[email protected]'".split())
24-
subprocess.check_output(["git", "config", "--global", "user.name", "'Miss Islington (bot)'"])
25-
os.chdir('./cpython')
23+
f"git clone https://{os.environ.get('GH_AUTH')}:[email protected]/miss-islington/cpython.git".split()
24+
)
2625
subprocess.check_output(
27-
f"git remote add upstream https://{os.environ.get('GH_AUTH')}:[email protected]/python/cpython.git".split())
26+
"git config --global user.email '[email protected]'".split()
27+
)
28+
subprocess.check_output(
29+
["git", "config", "--global", "user.name", "'Miss Islington (bot)'"]
30+
)
31+
os.chdir("./cpython")
32+
subprocess.check_output(
33+
f"git remote add upstream https://{os.environ.get('GH_AUTH')}:[email protected]/python/cpython.git".split()
34+
)
2835
print("Finished setting up CPython Repo")
2936
else:
3037
print("cpython directory already exists")
@@ -35,49 +42,55 @@ def backport_task(commit_hash, branch, *, issue_number, created_by, merged_by):
3542
"""Backport a commit into a branch."""
3643
if not util.is_cpython_repo():
3744
# cd to cpython if we're not already in it
38-
if "cpython" in os.listdir('.'):
39-
os.chdir('./cpython')
45+
if "cpython" in os.listdir("."):
46+
os.chdir("./cpython")
4047
else:
4148
print(f"pwd: {os.getcwd()}, listdir: {os.listdir('.')}")
42-
util.comment_on_pr(issue_number,
43-
f"""{util.get_participants(created_by, merged_by)}, Something is wrong... I can't backport for now.
49+
util.comment_on_pr(
50+
issue_number,
51+
f"""{util.get_participants(created_by, merged_by)}, Something is wrong... I can't backport for now.
4452
Please backport using [cherry_picker](https://pypi.org/project/cherry-picker/) on command line.
4553
```
4654
cherry_picker {commit_hash} {branch}
4755
```
48-
""")
56+
""",
57+
)
4958
util.assign_pr_to_core_dev(issue_number, merged_by)
50-
cp = cherry_picker.CherryPicker('origin', commit_hash, [branch],
51-
prefix_commit=False)
59+
cp = cherry_picker.CherryPicker(
60+
"origin", commit_hash, [branch], prefix_commit=False
61+
)
5262
try:
5363
cp.backport()
5464
except cherry_picker.BranchCheckoutException:
55-
util.comment_on_pr(issue_number,
56-
f"""Sorry {util.get_participants(created_by, merged_by)}, I had trouble checking out the `{branch}` backport branch.
65+
util.comment_on_pr(
66+
issue_number,
67+
f"""Sorry {util.get_participants(created_by, merged_by)}, I had trouble checking out the `{branch}` backport branch.
5768
Please backport using [cherry_picker](https://pypi.org/project/cherry-picker/) on command line.
5869
```
5970
cherry_picker {commit_hash} {branch}
6071
```
61-
""")
72+
""",
73+
)
6274
util.assign_pr_to_core_dev(issue_number, merged_by)
6375
cp.abort_cherry_pick()
6476
except cherry_picker.CherryPickException:
65-
util.comment_on_pr(issue_number,
66-
f"""Sorry, {util.get_participants(created_by, merged_by)}, I could not cleanly backport this to `{branch}` due to a conflict.
77+
util.comment_on_pr(
78+
issue_number,
79+
f"""Sorry, {util.get_participants(created_by, merged_by)}, I could not cleanly backport this to `{branch}` due to a conflict.
6780
Please backport using [cherry_picker](https://pypi.org/project/cherry-picker/) on command line.
6881
```
6982
cherry_picker {commit_hash} {branch}
7083
```
71-
""")
84+
""",
85+
)
7286
util.assign_pr_to_core_dev(issue_number, merged_by)
7387
cp.abort_cherry_pick()
7488

7589

7690
class InitRepoStep(bootsteps.StartStopStep):
77-
7891
def start(self, c):
7992
print("Initialize the repository.")
8093
setup_cpython_repo()
8194

8295

83-
app.steps['worker'].add(InitRepoStep)
96+
app.steps["worker"].add(InitRepoStep)

0 commit comments

Comments
 (0)