|
| 1 | +#!/usr/bin/python3 |
| 2 | +from concurrent.futures import ThreadPoolExecutor |
| 3 | +import os |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | + |
| 8 | + |
| 9 | +def transform(fn, s): |
| 10 | + lines = s.rstrip().split("\n") |
| 11 | + lines = [line.removeprefix("//| ").removeprefix("//|") for line in lines] |
| 12 | + while lines and not lines[0]: |
| 13 | + del lines[0] |
| 14 | + |
| 15 | + s = "\n".join(lines) + "\n" |
| 16 | + if s[0] == " ": |
| 17 | + prefix = "if 0:\n" |
| 18 | + else: |
| 19 | + prefix = "" |
| 20 | + s = prefix + s |
| 21 | + try: |
| 22 | + # Line length is 95 so that with "//| " the max is 99 |
| 23 | + result = subprocess.run( |
| 24 | + ["black", "--pyi", "-l95", "-q", "-"], |
| 25 | + input=s, |
| 26 | + check=True, |
| 27 | + stdout=subprocess.PIPE, |
| 28 | + encoding="utf-8", |
| 29 | + ) |
| 30 | + except subprocess.CalledProcessError as e: |
| 31 | + print(f"{fn}:0: Failed to process block:\n{s}") |
| 32 | + raise |
| 33 | + |
| 34 | + result = result.stdout[len(prefix) :].strip("\n") |
| 35 | + result = (result.rstrip()).split("\n") |
| 36 | + return "\n".join("//| " + line if line else "//|" for line in result) + "\n" |
| 37 | + |
| 38 | + |
| 39 | +def process_one_file(fn): |
| 40 | + with open(fn, "r", encoding="utf-8") as f: |
| 41 | + content = f.read() |
| 42 | + |
| 43 | + old_end = 0 |
| 44 | + |
| 45 | + parts = [] |
| 46 | + for m in re.finditer("(?m)((?:^//\|.*\n)(?:^//\|.*\n)*)", content): |
| 47 | + parts.append(content[old_end : m.start()]) |
| 48 | + parts.append(transform(fn, m.group())) |
| 49 | + old_end = m.end() |
| 50 | + parts.append(content[old_end:]) |
| 51 | + newcontent = "".join(parts) |
| 52 | + |
| 53 | + if newcontent != content: |
| 54 | + with open(fn, "w", encoding="utf-8") as f: |
| 55 | + f.write(newcontent) |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + # Use a thread pool because most processing is inside black! |
| 60 | + executor = ThreadPoolExecutor(max_workers=os.cpu_count()) |
| 61 | + futures = [executor.submit(process_one_file, fn) for fn in sys.argv[1:]] |
| 62 | + status = 0 |
| 63 | + for f in futures: |
| 64 | + try: |
| 65 | + f.result() |
| 66 | + except Exception as e: |
| 67 | + status = 1 |
| 68 | + executor.shutdown() |
| 69 | + raise SystemExit(status) |
0 commit comments