66from functools import partial
77import time
88import sys
9-
10- # Yapf requires python 3.6+
11- if not (sys .version_info .major == 3 and sys .version_info .minor >= 6 ):
12- raise RuntimeError (
13- "Requires Python 3.6+, currently using Python {}.{}." .format (
14- sys .version_info .major , sys .version_info .minor ))
15-
16- # Check and import yapf
17- # > not found: throw exception
18- # > version mismatch: throw exception
19- try :
20- import yapf
21- except :
22- raise ImportError (
23- "yapf not found. Install with `pip install yapf==0.30.0`." )
24- if yapf .__version__ != "0.30.0" :
25- raise RuntimeError (
26- "yapf 0.30.0 required. Install with `pip install yapf==0.30.0`." )
27- print ("Using yapf version {}" .format (yapf .__version__ ))
28-
29- # Check and import nbformat
30- # > not found: throw exception
31- try :
32- import nbformat
33- except :
34- raise ImportError (
35- "nbformat not found. Install with `pip install nbformat`." )
36- print ("Using nbformat version {}" .format (nbformat .__version__ ))
9+ import yapf
10+ import nbformat
3711
3812PYTHON_FORMAT_DIRS = ["." ]
39-
4013JUPYTER_FORMAT_DIRS = ["." ]
41-
4214# Note: also modify CPP_FORMAT_DIRS in check_cpp_style.cmake.
4315CPP_FORMAT_DIRS = ["." ]
4416
@@ -86,8 +58,8 @@ def _apply_style(file_path, style_config):
8658 style_config = style_config ,
8759 in_place = True )
8860
89- def run (self , do_apply_style , no_parallel , verbose ):
90- if do_apply_style :
61+ def run (self , apply , no_parallel , verbose ):
62+ if apply :
9163 print ("Applying Python style..." )
9264 else :
9365 print ("Checking Python style..." )
@@ -112,7 +84,7 @@ def run(self, do_apply_style, no_parallel, verbose):
11284 for is_valid , file_path in zip (is_valid_files , self .file_paths ):
11385 if not is_valid :
11486 changed_files .append (file_path )
115- if do_apply_style :
87+ if apply :
11688 self ._apply_style (file_path , self .style_config )
11789 print ("Formatting takes {:.2f}s" .format (time .time () - start_time ))
11890
@@ -126,7 +98,7 @@ def __init__(self, file_paths, style_config):
12698 self .style_config = style_config
12799
128100 @staticmethod
129- def _check_or_apply_style (file_path , style_config , do_apply_style ):
101+ def _check_or_apply_style (file_path , style_config , apply ):
130102 """Returns true if style is valid.
131103
132104 Since there are common code for check and apply style, the two functions
@@ -142,27 +114,39 @@ def _check_or_apply_style(file_path, style_config, do_apply_style):
142114 if cell ["cell_type" ] != "code" :
143115 continue
144116 src = cell ["source" ]
117+ if not src .strip (): # Ignore empty cells.
118+ continue
145119 lines = src .split ("\n " )
146- if len ( lines ) <= 0 or "# noqa" in lines [0 ]:
120+ if "# noqa" in lines [0 ]:
147121 continue
122+ # Ignore cells starting with shell commands or jupyter magics.
123+ # These are not valid python code and yapf will fail.
124+ if src .lstrip ().startswith (('!' , '%' )):
125+ continue
126+
148127 # yapf will puts a `\n` at the end of each cell, and if this is the
149128 # only change, cell_changed is still False.
150- formatted_src , cell_changed = yapf .yapflib .yapf_api .FormatCode (
151- src , style_config = style_config )
129+ try :
130+ formatted_src , cell_changed = yapf .yapflib .yapf_api .FormatCode (
131+ src , style_config = style_config )
132+ except Exception :
133+ # This may happen for cells with valid python and magics/shell
134+ # commands mixed. We will just ignore formatting for these cells.
135+ continue
152136 if formatted_src .endswith ("\n " ):
153137 formatted_src = formatted_src [:- 1 ]
154138 if cell_changed :
155139 cell ["source" ] = formatted_src
156140 changed = True
157141
158- if do_apply_style :
142+ if apply :
159143 with open (file_path , "w" ) as f :
160144 nbformat .write (notebook , f , version = nbformat .NO_CONVERT )
161145
162146 return not changed
163147
164- def run (self , do_apply_style , no_parallel , verbose ):
165- if do_apply_style :
148+ def run (self , apply , no_parallel , verbose ):
149+ if apply :
166150 print ("Applying Jupyter style..." )
167151 else :
168152 print ("Checking Jupyter style..." )
@@ -177,22 +161,22 @@ def run(self, do_apply_style, no_parallel, verbose):
177161 is_valid_files = map (
178162 partial (self ._check_or_apply_style ,
179163 style_config = self .style_config ,
180- do_apply_style = False ), self .file_paths )
164+ apply = False ), self .file_paths )
181165 else :
182166 with multiprocessing .Pool (multiprocessing .cpu_count ()) as pool :
183167 is_valid_files = pool .map (
184168 partial (self ._check_or_apply_style ,
185169 style_config = self .style_config ,
186- do_apply_style = False ), self .file_paths )
170+ apply = False ), self .file_paths )
187171
188172 changed_files = []
189173 for is_valid , file_path in zip (is_valid_files , self .file_paths ):
190174 if not is_valid :
191175 changed_files .append (file_path )
192- if do_apply_style :
176+ if apply :
193177 self ._check_or_apply_style (file_path ,
194178 style_config = self .style_config ,
195- do_apply_style = True )
179+ apply = True )
196180 print ("Formatting takes {:.2f}s" .format (time .time () - start_time ))
197181
198182 return changed_files
@@ -207,8 +191,8 @@ def run(self, do_apply_style, no_parallel, verbose):
207191
208192 parser = argparse .ArgumentParser ()
209193 parser .add_argument (
210- "--do_apply_style " ,
211- dest = "do_apply_style " ,
194+ "--apply " ,
195+ dest = "apply " ,
212196 action = "store_true" ,
213197 default = False ,
214198 help = "Apply style to files in-place." ,
@@ -242,16 +226,16 @@ def run(self, do_apply_style, no_parallel, verbose):
242226
243227 changed_files = []
244228 changed_files .extend (
245- python_formatter .run (do_apply_style = args .do_apply_style ,
229+ python_formatter .run (apply = args .apply ,
246230 no_parallel = args .no_parallel ,
247231 verbose = args .verbose ))
248232 changed_files .extend (
249- jupyter_formatter .run (do_apply_style = args .do_apply_style ,
233+ jupyter_formatter .run (apply = args .apply ,
250234 no_parallel = args .no_parallel ,
251235 verbose = args .verbose ))
252236
253237 if len (changed_files ) != 0 :
254- if args .do_apply_style :
238+ if args .apply :
255239 print ("Style applied to the following files:" )
256240 print ("\n " .join (changed_files ))
257241 else :
0 commit comments