Skip to content

Commit 20e1722

Browse files
committed
Further refine black_bindings
1 parent 4c695a7 commit 20e1722

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

tools/black_bindings.py

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,32 @@
66
import sys
77

88

9-
def transform(s):
9+
def transform(fn, s):
1010
lines = s.rstrip().split("\n")
1111
lines = [line.removeprefix("//| ").removeprefix("//|") for line in lines]
12+
while lines and not lines[0]:
13+
del lines[0]
14+
1215
s = "\n".join(lines) + "\n"
1316
if s[0] == " ":
1417
prefix = "if 0:\n"
1518
else:
1619
prefix = ""
1720
s = prefix + s
18-
result = subprocess.run(
19-
["black", "-q", "--pyi", "-"],
20-
input=s,
21-
check=True,
22-
stdout=subprocess.PIPE,
23-
encoding="utf-8",
24-
)
21+
try:
22+
result = subprocess.run(
23+
["black", "-q", "--pyi", "-"],
24+
input=s,
25+
check=True,
26+
stdout=subprocess.PIPE,
27+
encoding="utf-8",
28+
)
29+
except subprocess.CalledProcessError as e:
30+
print(f"{fn}:0: Failed to process block:\n{s}")
31+
return s
32+
2533
result = result.stdout[len(prefix) :]
26-
result = (result.rstrip() + "\n").split("\n")
34+
result = (result.rstrip()).split("\n")
2735
return "\n".join("//| " + line if line else "//|" for line in result) + "\n"
2836

2937

@@ -33,20 +41,23 @@ def process_one_file(fn):
3341

3442
old_end = 0
3543

36-
newcontent = []
37-
for m in re.finditer("(?m)((?:^//\|.*\n)+)", content):
38-
newcontent.append(content[old_end : m.start()])
39-
newcontent.append(transform(m.group()))
44+
parts = []
45+
for m in re.finditer("(?m)((?:^//\|.*\n)(?:^//\|.*\n|^\n)*)", content):
46+
parts.append(content[old_end : m.start()])
47+
parts.append(transform(fn, m.group()))
4048
old_end = m.end()
41-
newcontent.append(content[old_end:])
49+
parts.append(content[old_end:])
50+
newcontent = "".join(parts)
4251

43-
with open(fn, "w", encoding="utf-8") as f:
44-
f.write("".join(newcontent))
52+
if newcontent != content:
53+
with open(fn, "w", encoding="utf-8") as f:
54+
f.write(newcontent)
4555

4656

4757
if __name__ == "__main__":
4858
# Use a thread pool because most processing is inside black!
4959
executor = ThreadPoolExecutor(max_workers=os.cpu_count())
50-
for fn in sys.argv[1:]:
51-
executor.submit(process_one_file, fn)
60+
futures = [executor.submit(process_one_file, fn) for fn in sys.argv[1:]]
61+
for f in futures:
62+
f.result()
5263
executor.shutdown()

0 commit comments

Comments
 (0)