@@ -298,7 +298,11 @@ def src_info(self) -> Dict[str, Any]:
298298 return result
299299
300300 def format_model (
301- self , save : bool = False , canonicalize : Union [bool , List [str ]] = False
301+ self ,
302+ save : bool = False ,
303+ canonicalize : Union [bool , str , List [str ]] = False ,
304+ * ,
305+ unsafe : bool = False ,
302306 ) -> None :
303307 """
304308 Run stanc's auto-formatter on the model code. Either saves directly
@@ -311,37 +315,43 @@ def format_model(
311315 the Stan model, removing things like deprecated syntax. Default is
312316 False. If True, all canonicalizations are run. If it is a list of
313317 strings, those options are passed to stanc (new in Stan 2.29)
318+ :param unsafe: If True, do not create stanfile.bak backups before
319+ writing to the file. Only do this if you're sure you have other
320+ copies of the file or are using a version control system like Git.
314321 """
315322 if self .stan_file is None or not os .path .isfile (self .stan_file ):
316323 raise ValueError ("No Stan file found for this module" )
317324 try :
318- # TODO need include paths if they exist.
319- cmd = [
320- os .path .join ('.' , 'bin' , 'stanc' + EXTENSION ),
321- '--auto-format' ,
322- ]
325+ cmd = (
326+ [os .path .join (cmdstan_path (), 'bin' , 'stanc' + EXTENSION )]
327+ # handle include-paths, allow-undefined etc
328+ + self ._compiler_options .compose_stanc ()
329+ + [self .stan_file ]
330+ )
331+
323332 if canonicalize :
324333 if isinstance (canonicalize , list ):
325334 cmd .append ('--canonicalize=' + ',' .join (canonicalize ))
335+ elif isinstance (canonicalize , str ):
336+ cmd .append ('--canonicalize=' + canonicalize )
326337 else :
327338 cmd .append ('--print-canonical' )
328339
329- cmd .append (self .stan_file )
340+ if not (cmdstan_version_before (2 , 29 ) and canonicalize ):
341+ cmd .append ('--auto-format' )
330342
331343 out = subprocess .run (
332- cmd ,
333- cwd = cmdstan_path (),
334- capture_output = True ,
335- text = True ,
336- check = True ,
344+ cmd , capture_output = True , text = True , check = True
337345 )
338346 if out .stderr :
339- print (out .stderr )
347+ get_logger (). warning (out .stderr )
340348 result = out .stdout
341349 if save :
342- shutil .copyfile (self .stan_file , self .stan_file + '.bak' )
343- with (open (self .stan_file , 'w' )) as file :
344- file .write (result )
350+ if result :
351+ if not unsafe :
352+ shutil .copyfile (self .stan_file , self .stan_file + '.bak' )
353+ with (open (self .stan_file , 'w' )) as file :
354+ file .write (result )
345355 else :
346356 print (result )
347357
0 commit comments