6
6
import sys
7
7
8
8
9
- def transform (s ):
9
+ def transform (fn , s ):
10
10
lines = s .rstrip ().split ("\n " )
11
11
lines = [line .removeprefix ("//| " ).removeprefix ("//|" ) for line in lines ]
12
+ while lines and not lines [0 ]:
13
+ del lines [0 ]
14
+
12
15
s = "\n " .join (lines ) + "\n "
13
16
if s [0 ] == " " :
14
17
prefix = "if 0:\n "
15
18
else :
16
19
prefix = ""
17
20
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
+
25
33
result = result .stdout [len (prefix ) :]
26
- result = (result .rstrip () + " \n " ).split ("\n " )
34
+ result = (result .rstrip ()).split ("\n " )
27
35
return "\n " .join ("//| " + line if line else "//|" for line in result ) + "\n "
28
36
29
37
@@ -33,20 +41,23 @@ def process_one_file(fn):
33
41
34
42
old_end = 0
35
43
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 ()))
40
48
old_end = m .end ()
41
- newcontent .append (content [old_end :])
49
+ parts .append (content [old_end :])
50
+ newcontent = "" .join (parts )
42
51
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 )
45
55
46
56
47
57
if __name__ == "__main__" :
48
58
# Use a thread pool because most processing is inside black!
49
59
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 ()
52
63
executor .shutdown ()
0 commit comments