
    %g                     v   d Z ddlZddlZddlZddlZddlZddlZddlmZm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlmZ  ej*                         dk(  rd	nd
ZdedefdZ	 d"dededededef
dZej6                  dede	d   fd       Zdeeej:                  eeef   df   de	ee      fdZ ej6                  e      Z	 d#deeej:                  eeef   e
e   df   de de	ee      fdZ!ej6                  ddddeeej:                  eeef   e"e e
e   df   dede de	eee"e df      fd       Z# G d  d!      Z$y)$zE
Utilities for interacting with the filesystem on multiple platforms
    N)AnyIteratorListMappingOptionalTupleUnion)_TMPDIR   )write_stan_json)
get_loggerWindowsz.exe pathreturnc                 6   t        j                         dk7  r| S t        j                  j	                  |       sDt        j                  j                  |       sHt        j                  j                  |       d   dk7  r#t        j                  j                  |       \  }}n| d}}t        j                  j                  |      st        dj                  |            ddl}ddlm} |j                  j                  j                  }|j                   |j"                  |j$                  g|_        |j$                  |_        d}	 |j+                  |      } ||||      }||k\  r|j,                  }	n|}0|r"t        j                  j/                  |	|      }
|
S |	}
|
S )z
    Gets the short path name of a given long path.
    http://stackoverflow.com/a/23598461/200291

    On non-Windows platforms, returns the path

    If (base)path does not exist, function raises RuntimeError
    r   r   r   zXWindows short path function needs a valid directory. Base directory does not exist: "{}"r   N)wintypes)platformsystemosr   isfileisdirsplitextsplitexistsRuntimeErrorformatctypesr   windllkernel32GetShortPathNameWLPCWSTRLPWSTRDWORDargtypesrestypecreate_unicode_buffervaluejoin)r   	base_path	file_namer   r   _GetShortPathNameWoutput_buf_size
output_bufneededshort_base_path
short_paths              W/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/utils/filesystem.pywindows_short_pathr3      sr    I%	ww~~dGGMM$BGG$4$4T$:1$=$C!ww}}T2	9#R9	77>>)$228&2C
 	

  	00 
 	#
 "*O
11/B
#Iz?Kf$(..O$O   	_i0 
   
     dirprefixsuffix	name_onlyc                 r    t        j                  d||| |      }|j                  }|j                          |S )z
    Create a named unique file, return filename.
    Flag 'name_only' will create then delete the tmp file;
    this lets us create filename args for commands which
    disallow overwriting existing files (e.g., 'stansummary').
    zw+)moder6   r7   r5   delete)tempfileNamedTemporaryFilenameclose)r5   r6   r7   r8   fdr   s         r2   create_named_text_filerA   N   s8     
	$	$&S
B 77DHHJKr4   new_dirc              #      K   t        j                         }t        j                  |        	 d t        j                  |       y# t        j                  |       w xY ww)zActs like pushd/popd.N)r   getcwdchdir)rB   previous_dirs     r2   pushdrG   _   s?      99;LHHW
s   *A!A A!AA!datac              #     K   | d yt        | t        t        j                  f      rt        |        yt	        t
        dd      }t               j                  d|       t        ||        	 | t        j                  t              5  t        j                  |       ddd       y# 1 sw Y   yxY w# t        j                  t              5  t        j                  |       ddd       w # 1 sw Y   w xY wxY ww)zContext manager for json files.Nr   .json)r5   r6   r7   zinput tempfile: %s)
isinstancestrr   PathLikerA   r
   r   debugr   
contextlibsuppressPermissionErrorremove)rH   	data_files     r2   _temp_single_jsonrT   j   s      |
$bkk*+$i&72gNIL+Y7It$!  1 	!IIi 	! 	! 	!Z  1 	!IIi 	! 	! 	!sN   A.D1B9 5DB-$	D-B62D9C>C2)	C>2C;7C>>Dinputbasec           	   #   J  K   t        | t              rt        t        ddd      }t	        t        |             D cg c].  }t        j                  j                  |      d   d||z    dz   0 }}t        | |      D ]h  \  }}t        |t              rt        ||       #t        |t              rt        j                  ||       Jt        dt        t!        |            z          	 | |D ]9  }t#        j$                  t&              5  t        j(                  |       d d d        ; y t+        |       E d {    y c c}w # 1 sw Y   _xY w# |D ]E  }t#        j$                  t&              5  t        j(                  |       d d d        ;# 1 sw Y   DxY w w xY w7 ew)Nr   rJ   T)r5   r6   r7   r8   r   _z2A list of inits must contain dicts or strings, not)rK   listrA   r
   rangelenr   r   r   zipdictr   rL   shutilcopy
ValueErrortyperO   rP   rQ   rR   rT   )rU   rV   mother_filei	new_filesinitfiles          r2   _temp_multiinputrg      s     % -7d

 3u:&
 GG[)!,1T6(%/@@
	 
 eY/ 		JD$$%d+D#&D$' H$t*o& 			$! $((9 $IIdO$ $$ %U++++
$$ $ " $((9 $IIdO$ $ $$ 	,se   ;F#3E0A9F#*E .F#E"F#;F!<
F#E	F#F1F		FF	FF#T)allow_multipleidinitsrh   ri   c             #      K   t        | t        t        f      r|  y |rt        | |      E d {    y t        | t              rt        d      t        |       E d {    y 7 47 w)N)rV   z(Expected single initialization, got list)rK   floatintrg   rY   r`   rT   )rj   rh   ri   s      r2   
temp_initsrn      s`      %%&#E333eT"GHH$U+++	 	4 	,s!   .A)A%.A)A' A)'A)c                       e Zd ZdZ ej
                  d      Z ej
                  d      Zede	de
fd       Zde	fdZdee	e
f   fdZdd
Zy	)SanitizedOrTmpFilePathzO
    Context manager for tmpfiles, handles special characters in filepath.
    z[\s~]z\s	file_pathr   c                     t        j                         dk(  r$t        | j                  j	                  |            S t        | j
                  j	                  |            S )Nr   )r   r   boolWINDOWS_PATTERNsearchUNIXISH_PATTERN)clsrq   s     r2   _has_special_charsz)SanitizedOrTmpFilePath._has_special_chars   sI    ??	)++229=>>C''..y9::r4   c                    d | _         | j                  t        j                  j	                  |            rt        j                  j                  t        j                  j	                  |            \  }}t        j                  |d       	 t        |      }t        j                  j                  |      r t        j                  j                  ||      }| j                  t        j                  j	                  |            rot        j                         }| j                  |      rt        d      t        j                  d|      \  }}t        j                  ||       || _        || _         y || _        y # t        $ r Y w xY w)NT)exist_okzUnable to generate temporary path without spaces or special characters! 
 Please move your stan file to a location without spaces or special characters.z.stan)r7   r5   )_tmpdirrx   r   r   abspathr   makedirsr3   r   r)   r   r<   mkdtempmkstempr^   r_   _path)selfrq   r*   r+   r0   tmpdirrX   r   s           r2   __init__zSanitizedOrTmpFilePath.__init__   s$   ""277??9#=>#%77==1K#L IyKK	D1"4Y"?77>>/2 "_i HI ""277??9#=>%%'F&&v."E  &&g6BGAtKK	4(DJ!DL"DJ%   s   A
E< <	FFc                 6    | j                   | j                  d ufS )N)r   r{   )r   s    r2   	__enter__z SanitizedOrTmpFilePath.__enter__   s    zz4<<t333r4   Nc                 `    | j                   r"t        j                  | j                   d       y y )NT)ignore_errors)r{   r^   rmtree)r   exc_typeexc_valexc_tbs       r2   __exit__zSanitizedOrTmpFilePath.__exit__   s     <<MM$,,d; r4   )r   N)__name__
__module____qualname____doc__recompilerv   rt   classmethodrL   rs   rx   r   r   r   r    r4   r2   rp   rp      so     !bjj*O bjj'O;3 ;4 ; ;
## #<45d+ 4<r4   rp   )F)r   )%r   rO   r   r   r   r^   r<   typingr   r   r   r   r   r   r	   	cmdstanpyr
   jsonr   loggingr   r   	EXTENSIONrL   r3   rs   rA   contextmanagerrG   rM   rT   temp_single_jsonrm   rg   rl   rn   rp   r   r4   r2   <module>r      s    	  	   G G G  ! %hoo'94F"	7S 7S 7v ;@	#&37" 3 8D>  !
R[['#s("3T9
:!hsm!* -:,,->? 
 ",bkk738#4d3iEF",
", hsm",J   ,R[['#s(+UCcDH,
 , 	, eCT)*+, ,&1< 1<r4   