Skip to content

Commit e0aa905

Browse files
authored
[misc] Switch code formatter from yapf to black (taichi-dev#7785)
Issue: # ### Brief Summary
1 parent 80b9465 commit e0aa905

File tree

399 files changed

+13089
-10784
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

399 files changed

+13089
-10784
lines changed

.github/workflows/scripts/build.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@
55

66
import ti_build.entry
77

8-
if __name__ == '__main__':
8+
if __name__ == "__main__":
99
sys.exit(ti_build.entry.main())

.github/workflows/scripts/ghstack-perm-check.py

+56-49
Original file line numberDiff line numberDiff line change
@@ -12,91 +12,98 @@
1212

1313
def main():
1414
gh = requests.Session()
15-
gh.headers.update({
16-
'Authorization': f'Bearer {os.environ["GITHUB_TOKEN"]}',
17-
'Accept': 'application/vnd.github+json',
18-
'X-GitHub-Api-Version': '2022-11-28',
19-
})
15+
gh.headers.update(
16+
{
17+
"Authorization": f'Bearer {os.environ["GITHUB_TOKEN"]}',
18+
"Accept": "application/vnd.github+json",
19+
"X-GitHub-Api-Version": "2022-11-28",
20+
}
21+
)
2022
EV = json.loads(sys.stdin.read())
21-
REPO = EV['repository']
22-
PR = EV['event']['client_payload']['pull_request']
23-
NUMBER = PR['number']
23+
REPO = EV["repository"]
24+
PR = EV["event"]["client_payload"]["pull_request"]
25+
NUMBER = PR["number"]
2426

2527
def must(cond, msg):
2628
if not cond:
2729
print(msg)
2830
gh.post(
29-
f'https://api.github.com/repos/{REPO}/issues/{NUMBER}/comments',
31+
f"https://api.github.com/repos/{REPO}/issues/{NUMBER}/comments",
3032
json={
31-
'body': f'ghstack bot failed: {msg}',
32-
})
33+
"body": f"ghstack bot failed: {msg}",
34+
},
35+
)
3336
exit(1)
3437

35-
head_ref = PR['head']['ref']
36-
must(head_ref and re.match(r'^gh/[A-Za-z0-9-]+/[0-9]+/head$', head_ref),
37-
'Not a ghstack PR')
38-
orig_ref = head_ref.replace('/head', '/orig')
39-
print(':: Fetching newest master...')
40-
must(os.system('git fetch origin master') == 0, "Can't fetch master")
41-
print(':: Fetching orig branch...')
38+
head_ref = PR["head"]["ref"]
4239
must(
43-
os.system(f'git fetch origin {orig_ref}') == 0,
44-
"Can't fetch orig branch")
40+
head_ref and re.match(r"^gh/[A-Za-z0-9-]+/[0-9]+/head$", head_ref),
41+
"Not a ghstack PR",
42+
)
43+
orig_ref = head_ref.replace("/head", "/orig")
44+
print(":: Fetching newest master...")
45+
must(os.system("git fetch origin master") == 0, "Can't fetch master")
46+
print(":: Fetching orig branch...")
47+
must(os.system(f"git fetch origin {orig_ref}") == 0, "Can't fetch orig branch")
4548

4649
proc = subprocess.Popen(
47-
'git log FETCH_HEAD...$(git merge-base FETCH_HEAD origin/master)',
50+
"git log FETCH_HEAD...$(git merge-base FETCH_HEAD origin/master)",
4851
stdout=subprocess.PIPE,
49-
shell=True)
52+
shell=True,
53+
)
5054
out, _ = proc.communicate()
51-
must(proc.wait() == 0, '`git log` command failed!')
55+
must(proc.wait() == 0, "`git log` command failed!")
5256

5357
pr_numbers = re.findall(
54-
r'Pull Request resolved: https://github.com/.*?/pull/([0-9]+)',
55-
out.decode('utf-8'))
58+
r"Pull Request resolved: https://github.com/.*?/pull/([0-9]+)",
59+
out.decode("utf-8"),
60+
)
5661
pr_numbers = list(map(int, pr_numbers))
57-
must(pr_numbers and pr_numbers[0] == NUMBER,
58-
'Extracted PR numbers not seems right!')
62+
must(
63+
pr_numbers and pr_numbers[0] == NUMBER, "Extracted PR numbers not seems right!"
64+
)
5965

6066
for n in pr_numbers:
61-
print(f':: Checking PR status #{n}... ', end='')
62-
resp = gh.get(f'https://api.github.com/repos/{REPO}/pulls/{n}')
63-
must(resp.ok, 'Error Getting PR Object!')
67+
print(f":: Checking PR status #{n}... ", end="")
68+
resp = gh.get(f"https://api.github.com/repos/{REPO}/pulls/{n}")
69+
must(resp.ok, "Error Getting PR Object!")
6470
pr_obj = resp.json()
6571

66-
resp = gh.get(
67-
f'https://api.github.com/repos/{REPO}/pulls/{NUMBER}/reviews')
68-
must(resp.ok, 'Error Getting PR Reviews!')
72+
resp = gh.get(f"https://api.github.com/repos/{REPO}/pulls/{NUMBER}/reviews")
73+
must(resp.ok, "Error Getting PR Reviews!")
6974
reviews = resp.json()
7075
idmap = {}
7176
approved = False
7277
for r in reviews:
73-
s = r['state']
74-
if s not in ('COMMENTED', ):
75-
idmap[r['user']['login']] = r['state']
78+
s = r["state"]
79+
if s not in ("COMMENTED",):
80+
idmap[r["user"]["login"]] = r["state"]
7681

7782
for u, cc in idmap.items():
78-
approved = approved or cc == 'APPROVED'
79-
must(cc in ('APPROVED', 'DISMISSED'),
80-
f'@{u} has stamped PR #{n} `{cc}`, please resolve it first!')
83+
approved = approved or cc == "APPROVED"
84+
must(
85+
cc in ("APPROVED", "DISMISSED"),
86+
f"@{u} has stamped PR #{n} `{cc}`, please resolve it first!",
87+
)
8188

82-
must(approved, f'PR #{n} is not approved yet!')
89+
must(approved, f"PR #{n} is not approved yet!")
8390

8491
resp = gh.get(
8592
f'https://api.github.com/repos/{REPO}/commits/{pr_obj["head"]["sha"]}/check-runs'
8693
)
87-
must(resp.ok, 'Error getting check runs status!')
94+
must(resp.ok, "Error getting check runs status!")
8895
checkruns = resp.json()
89-
for cr in checkruns['check_runs']:
90-
status = cr.get('conclusion', cr['status'])
91-
name = cr['name']
96+
for cr in checkruns["check_runs"]:
97+
status = cr.get("conclusion", cr["status"])
98+
name = cr["name"]
9299
must(
93-
status == 'success',
94-
f'PR #{n} check-run `{name}`\'s status `{status}` is not success!'
100+
status == "success",
101+
f"PR #{n} check-run `{name}`'s status `{status}` is not success!",
95102
)
96-
print('SUCCESS!')
103+
print("SUCCESS!")
97104

98-
print(':: All PRs are ready to be landed!')
105+
print(":: All PRs are ready to be landed!")
99106

100107

101-
if __name__ == '__main__':
108+
if __name__ == "__main__":
102109
main()

.github/workflows/scripts/post-benchmark-to-github-pr.py

+47-43
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import json
66
import os
77
import sqlite3
8+
89
# -- stdlib --
910
from pathlib import Path
1011

@@ -15,101 +16,103 @@
1516

1617
# -- code --
1718
gh = requests.Session()
18-
gh.headers.update({
19-
'Authorization': f'Bearer {os.environ["GITHUB_TOKEN"]}',
20-
'Accept': 'application/vnd.github+json',
21-
'X-GitHub-Api-Version': '2022-11-28',
22-
})
19+
gh.headers.update(
20+
{
21+
"Authorization": f'Bearer {os.environ["GITHUB_TOKEN"]}',
22+
"Accept": "application/vnd.github+json",
23+
"X-GitHub-Api-Version": "2022-11-28",
24+
}
25+
)
2326

2427

2528
def post_comment(repo, number, msg):
2629
gh.post(
27-
f'https://api.github.com/repos/{repo}/issues/{number}/comments',
28-
json={'body': msg},
30+
f"https://api.github.com/repos/{repo}/issues/{number}/comments",
31+
json={"body": msg},
2932
)
3033

3134

3235
def get_db():
33-
db = sqlite3.connect(':memory:')
34-
db.execute('CREATE TABLE release (name TEXT, value REAL)')
35-
db.execute('CREATE UNIQUE INDEX release_name ON release (name)')
36-
db.execute('CREATE TABLE current (name TEXT, value REAL)')
37-
db.execute('CREATE UNIQUE INDEX current_name ON current (name)')
36+
db = sqlite3.connect(":memory:")
37+
db.execute("CREATE TABLE release (name TEXT, value REAL)")
38+
db.execute("CREATE UNIQUE INDEX release_name ON release (name)")
39+
db.execute("CREATE TABLE current (name TEXT, value REAL)")
40+
db.execute("CREATE UNIQUE INDEX current_name ON current (name)")
3841
return db
3942

4043

41-
IGNORE_TAGS = {'type', 'release', 'impl'}
44+
IGNORE_TAGS = {"type", "release", "impl"}
4245

4346

4447
def flatten_metric(m):
45-
tags = [f'{k}={v}' for k, v in m['tags'].items() if k not in IGNORE_TAGS]
46-
tags = ','.join(sorted(tags))
47-
return (f'{m["name"]}@{tags}', m['value'])
48+
tags = [f"{k}={v}" for k, v in m["tags"].items() if k not in IGNORE_TAGS]
49+
tags = ",".join(sorted(tags))
50+
return (f'{m["name"]}@{tags}', m["value"])
4851

4952

5053
def fmt(v):
5154
if 0 < abs(v) < 1:
52-
return f'{v:.3g}'
55+
return f"{v:.3g}"
5356
else:
54-
return f'{v:.3f}'
57+
return f"{v:.3f}"
5558

5659

5760
def render_result(baseline, sha, rs):
5861
texts = []
5962
_ = texts.append
60-
_(f'## Benchmark Report')
61-
_(f'Baseline: `{baseline}`')
62-
_(f'Current: `{sha}`')
63-
_('')
64-
_('| Item | Baseline | Current | Change |')
65-
_('| --- | --- | --- | --- |')
63+
_(f"## Benchmark Report")
64+
_(f"Baseline: `{baseline}`")
65+
_(f"Current: `{sha}`")
66+
_("")
67+
_("| Item | Baseline | Current | Change |")
68+
_("| --- | --- | --- | --- |")
6669
for name, cv, rv, rate in rs:
67-
cmap = ['red', 'green']
68-
if ':wall_time@' in name:
70+
cmap = ["red", "green"]
71+
if ":wall_time@" in name:
6972
cv *= 1000
7073
rv *= 1000
71-
cmap = ['green', 'red']
74+
cmap = ["green", "red"]
7275

7376
if rate > 5.0:
7477
color = cmap[1]
7578
elif rate < -5.0:
7679
color = cmap[0]
7780
else:
78-
color = 'gray'
81+
color = "gray"
7982

8083
rate = f'{" +"[rate > 0]}{rate:.2f}'
8184

82-
_(fr'| {name} | {fmt(rv)} | {fmt(cv)} | $\textcolor{{{color}}}{{\textsf{{{rate}\\%}}}}$ |'
83-
)
85+
_(
86+
rf"| {name} | {fmt(rv)} | {fmt(cv)} | $\textcolor{{{color}}}{{\textsf{{{rate}\\%}}}}$ |"
87+
)
8488

85-
return '\n'.join(texts)
89+
return "\n".join(texts)
8690

8791

8892
def main():
8993
parser = argparse.ArgumentParser()
90-
parser.add_argument('event')
91-
parser.add_argument('result')
94+
parser.add_argument("event")
95+
parser.add_argument("result")
9296
options = parser.parse_args()
9397

9498
db = get_db()
9599

96100
current = json.loads(Path(options.result).read_text())
97101
for item in current:
98-
db.execute('INSERT OR IGNORE INTO current VALUES (?, ?)',
99-
flatten_metric(item))
102+
db.execute("INSERT OR IGNORE INTO current VALUES (?, ?)", flatten_metric(item))
100103

101104
ver = requests.get(
102-
'https://benchmark.taichi-lang.cn/releases?order=vnum.desc&limit=1'
103-
).json()[0]['version']
105+
"https://benchmark.taichi-lang.cn/releases?order=vnum.desc&limit=1"
106+
).json()[0]["version"]
104107
release = requests.get(
105-
f'https://benchmark.taichi-lang.cn/taichi_benchmark?tags->>type=eq.release&tags->>release=eq.{ver}'
108+
f"https://benchmark.taichi-lang.cn/taichi_benchmark?tags->>type=eq.release&tags->>release=eq.{ver}"
106109
).json()
107110

108111
for item in release:
109-
db.execute('INSERT OR IGNORE INTO release VALUES (?, ?)',
110-
flatten_metric(item))
112+
db.execute("INSERT OR IGNORE INTO release VALUES (?, ?)", flatten_metric(item))
111113

112-
rs = db.execute('''
114+
rs = db.execute(
115+
"""
113116
SELECT
114117
c.name AS name,
115118
c.value AS cv,
@@ -119,7 +122,8 @@ def main():
119122
current c
120123
LEFT JOIN release r ON (r.name = c.name)
121124
ORDER BY name
122-
''')
125+
"""
126+
)
123127

124128
event = json.loads(Path(options.event).read_text())
125129
sha = event["client_payload"]["pull_request"]["head"]["sha"]
@@ -132,5 +136,5 @@ def main():
132136
)
133137

134138

135-
if __name__ == '__main__':
139+
if __name__ == "__main__":
136140
main()

0 commit comments

Comments
 (0)