]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
feat(tools): run async_to_sync.py concurrently
authorDenis Laxalde <denis.laxalde@dalibo.com>
Fri, 1 Mar 2024 13:21:35 +0000 (14:21 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Wed, 10 Apr 2024 21:47:10 +0000 (23:47 +0200)
Multi-processing is used by default (using all available processors),
but can be disabled or limited with the -j/--jobs option.

tools/async_to_sync.py

index c4c053a1ab78b91de4f0f3ac8b6d50439a55692d..3ff046e767355a19e650fa08cc1f8b874d7e49d0 100755 (executable)
@@ -12,6 +12,7 @@ Hint: in order to explore the AST of a module you can run:
 from __future__ import annotations
 
 import os
+from concurrent.futures import ProcessPoolExecutor
 import sys
 import logging
 import subprocess as sp
@@ -83,27 +84,36 @@ def main() -> int:
             PYVER,
         )
 
-    outputs = []
-    for fpin in opt.inputs:
-        fpout = fpin.parent / fpin.name.replace("_async", "")
-        outputs.append(str(fpout))
-        logger.info("converting %s", fpin)
-        with fpin.open() as f:
-            source = f.read()
+    if opt.jobs == 1:
+        logger.debug("multi-processing disabled")
+        for fpin in opt.inputs:
+            convert(fpin)
+    else:
+        with ProcessPoolExecutor(max_workers=opt.jobs) as executor:
+            outputs = executor.map(convert, opt.inputs)
 
-        tree = ast.parse(source, filename=str(fpin))
-        tree = async_to_sync(tree, filepath=fpin)
-        output = tree_to_str(tree, fpin)
+    if opt.check:
+        return check([str(o) for o in outputs])
 
-        with fpout.open("w") as f:
-            print(output, file=f)
+    return 0
 
-        sp.check_call(["black", "-q", str(fpout)])
 
-    if opt.check:
-        return check(outputs)
+def convert(fpin: Path) -> Path:
+    fpout = fpin.parent / fpin.name.replace("_async", "")
+    logger.info("converting %s", fpin)
+    with fpin.open() as f:
+        source = f.read()
 
-    return 0
+    tree = ast.parse(source, filename=str(fpin))
+    tree = async_to_sync(tree, filepath=fpin)
+    output = tree_to_str(tree, fpin)
+
+    with fpout.open("w") as f:
+        print(output, file=f)
+
+    sp.check_call(["black", "-q", str(fpout)])
+
+    return fpout
 
 
 def check(outputs: list[str]) -> int:
@@ -567,6 +577,16 @@ def parse_cmdline() -> Namespace:
     parser.add_argument(
         "--all", action="store_true", help="process all the files of the project"
     )
+    parser.add_argument(
+        "-j",
+        "--jobs",
+        type=int,
+        metavar="N",
+        help=(
+            "process files concurrently using at most N workers; "
+            "if unspecified, the number of processors on the machine will be used"
+        ),
+    )
     container = parser.add_mutually_exclusive_group()
     container.add_argument(
         "--docker",