99import os
1010import pathlib
1111import re
12+ import subprocess
1213from subprocess import list2cmdline , run
1314from tempfile import NamedTemporaryFile
1415
1516CLANG_FORMAT_VERSION = '18.1.6'
1617CLANG_FORMAT_INCLUDE_REGEX = re .compile (r'^.*\.(cpp|h)$' )
1718
18-
1919def format_directories (directory_list ):
2020 """Format C++ files in the given directories using clang-format"""
21- filepaths_file = NamedTemporaryFile (delete = False )
22-
21+ cpu_count = os .cpu_count () or 1
22+
23+ filepaths_files = [NamedTemporaryFile (delete = False ) for _ in range (cpu_count )]
24+
25+ index = 0
2326 for root_dir in directory_list :
2427 if os .path .exists (root_dir ):
2528 for dirpath , dirnames , filenames in os .walk (root_dir ):
2629 for filename in filenames :
2730 filepath = pathlib .Path (dirpath , filename ).as_posix ()
2831 if CLANG_FORMAT_INCLUDE_REGEX .match (filename ):
29- filepaths_file .write (f"{ filepath } \n " .encode ())
30-
31- filepaths_file .close ()
32-
33- cmd = ['pipx' , 'run' , f'clang-format=={ CLANG_FORMAT_VERSION } ' ,
34- f'--files={ filepaths_file .name } ' , '-i' , '-style=file:.clang-format' ]
35-
36- print (f"Formatting generated files: { list2cmdline (cmd )} " )
37- run (cmd )
38-
32+ filepaths_files [index % cpu_count ].write (f"{ filepath } \n " .encode ())
33+ index += 1
34+
35+ for filepaths_file in filepaths_files :
36+ filepaths_file .close ()
37+
38+ processes = []
39+ for filepaths_file in filepaths_files :
40+ cmd = ['pipx' , 'run' , f'clang-format=={ CLANG_FORMAT_VERSION } ' ,
41+ f'--files={ filepaths_file .name } ' , '-i' , '-style=file:.clang-format' ]
42+ p = subprocess .Popen (cmd )
43+ processes .append (p )
44+ print (f"Formatting generated files: { list2cmdline (cmd )} " )
45+
46+ for p in processes :
47+ p .wait ()
48+
3949 # Clean up temp file
40- os .unlink (filepaths_file .name )
50+ for filepaths_file in filepaths_files :
51+ os .unlink (filepaths_file .name )
0 commit comments