
    ^h*R                    :   S r SSKJr  SSKrSSKrSSKrSSKrSSKJrJ	r	  SSK
Jr  SSKJr  SSKrSSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJr  SSKJrJrJr  S rS rSS jr SS jr!S r"S r#\SS j5       r$\SS j5       r% " S S\\5      r& " S S\&5      r'g)z9
Utilities for file-based Contents/Checkpoints managers.
    )annotationsN)decodebytesencodebytes)contextmanager)partial)run_sync)	HTTPError)BoolEnum)Configurable)LoggingConfigurable)ApiPathto_api_path
to_os_pathc                0    [         R                  " X5        g)zreplace dst with srcN)osreplacesrcdsts     a/home/james-whalen/.local/lib/python3.13/site-packages/jupyter_server/services/contents/fileio.pyreplace_filer      s    JJs    c                T   #    [        [        R                  X5      I Sh  vN   g N7f)z#replace dst with src asynchronouslyN)r   r   r   r   s     r   async_replace_filer       s     
2::s
(((s   (&(c                p   [         R                  " U [         R                  5      (       d5  U(       a  UR                  SU SS9  [	        [
        R                  SU  35      e[        R                  " X5         [        R                  " X5        g! [         a    U(       a  UR                  SUSS9   g gf = f)zRcopy src to dst

like shutil.copy2, but log errors in copystat instead of raising
 Source file, %s, is not writableTexc_infoFile is not writable: copystat on %s failedN)r   accessW_OKdebugPermissionErrorerrnoEACCESshutilcopyfilecopystatOSErrorr   r   logs      r   
copy2_safer.   %   s     99S"''""II8#IMell.DSE,JKK
OOCC! CII-sTIB Cs   7B "B54B5c                  #    [         R                  " U [         R                  5      (       d5  U(       a  UR                  SU SS9  [	        [
        R                  SU  35      e[        [        R                  X5      I Sh  vN    [        [        R                  X5      I Sh  vN   g N( N! [         a    U(       a  UR                  SUSS9   g gf = f7f)zacopy src to dst asynchronously

like shutil.copy2, but log errors in copystat instead of raising
r   Tr   r    Nr!   )r   r"   r#   r$   r%   r&   r'   r   r(   r)   r*   r+   r,   s      r   async_copy2_safer0   8   s     
 99S"''""II8#IMell.DSE,JKK
6??C
---Cv111 .1 CII-sTIB CsH   A=C?B( CB, "B*#B, 'C*B, ,"CCCCc                    [         R                  R                  U 5      u  p[         R                  R                  USU-   5      $ )zpName of the intermediate file used in atomic writes.

The .~ prefix will make Dropbox ignore the temporary file.z.~r   pathsplitjoinr3   dirnamebasenames      r   path_to_intermediater9   J   s2     d+G77<<11r   c                    [         R                  R                  U 5      u  p[         R                  R                  XS-   5      $ )zEName of invalid file after a failed atomic write and subsequent read.z.invalidr2   r6   s      r   path_to_invalidr;   R   s/    d+G77<<J!677r   c              +  F  #    [         R                  R                  U 5      (       aQ  [         R                  R                  [         R                  R	                  U 5      [         R
                  " U 5      5      n [         R                  R	                  U 5      =(       d    [         R                  " 5       n[         R                  R                  U 5      (       a  [         R                  " U[         R                  5      (       dm  [         R                  " U [         R                  5      (       aC  U(       a  SOSnU(       a  [        X4SU0UD6nO[        X40 UD6n Uv   UR                  5         g[        U 5      n[         R                  R                  U 5      (       a
  [        XUS9  U(       a"  UR                  SS5        [        U S4SU0UD6nO[        U S40 UD6n Uv   UR#                  5         [         R$                  " UR'                  5       5        UR                  5         [         R                  R                  U5      (       a  [         R(                  " U5        gg! UR                  5         f = f! [         a    UR                  5         [!        X5        e f = f7f)a  Context manager to write to a file only if the entire write is successful.

This works by copying the previous file contents to a temporary file in the
same directory, and renaming that file back to the target if the context
exits with an error. If the context is successful, the new data is synced to
disk and the temporary file is removed.

Parameters
----------
path : str
    The target file to write to.
text : bool, optional
    Whether to open the file in text mode (i.e. to write unicode). Default is
    True.
encoding : str, optional
    The encoding to use for files opened in text mode. Default is UTF-8.
**kwargs
    Passed to :func:`io.open`.
wwbencodingNr-   newline
)r   r3   islinkr5   r7   readlinkgetcwdisfiler"   r#   opencloser9   r.   
setdefaultBaseExceptionr   flushfsyncfilenoremove)	r3   textr?   r-   kwargsdirpathmodefileobjtmp_paths	            r   atomic_writingrU   X   s    0 
ww~~dww||BGGOOD12;;t3DE ggood#2ryy{G	ww~~dBIIgrww$?$?BIIdTVT[T[D\D\s4CCFCG400G	MMMO#D)H	ww~~d4s+)T*tS>8>v>tT,V, MMOHHW^^MMO 
ww~~h
		(  ; MMO"  X$	s8   EJ!I" B J!I7 "B J!"I44J!7'JJ!c              +    #    [         R                  R                  U 5      (       aQ  [         R                  R                  [         R                  R	                  U 5      [         R
                  " U 5      5      n U(       a"  UR                  SS5        [        U S4SU0UD6nO[        U S40 UD6n Uv   UR                  5         g! [         a    UR                  5         e f = f7f)a  Context manager to write file without doing atomic writing
(for weird filesystem eg: nfs).

Parameters
----------
path : str
    The target file to write to.
text : bool, optional
    Whether to open the file in text mode (i.e. to write unicode). Default is
    True.
encoding : str, optional
    The encoding to use for files opened in text mode. Default is UTF-8.
**kwargs
    Passed to :func:`io.open`.
rA   rB   r=   r?   r>   N)
r   r3   rC   r5   r7   rD   rI   rG   rJ   rH   )r3   rO   r?   r-   rP   rS   s         r   _simple_writingrW      s     ( 
ww~~dww||BGGOOD12;;t3DE)T*tS>8>v>tT,V,
 MMO	  s   B,C#/C 3C#C  C#c                      \ rS rSrSr\" SSSS9r\" \R                  SSSS9r
\S	 5       r\S
 5       r\SS j5       rS rS r S SS jjrSS jrSS jr S       SS jjrS rSrg)FileManagerMixin   as  
Mixin for ContentsAPI classes that interact with the filesystem.

Provides facilities for reading, writing, and copying files.

Shared by FileContentsManager and FileCheckpoints.

Note
----
Classes using this mixin must provide the following attributes:

root_dir : unicode
    A directory against against which API-style paths are to be resolved.

log : logging.Logger
Ta  By default notebooks are saved on disk on a temporary file and then if successfully written, it replaces the old ones.
      This procedure, namely 'atomic_writing', causes some bugs on file system without operation order enforcement (like some networked fs).
      If set to False, the new notebook is written directly on the old one which could fail (eg: full filesystem or quota ))confighelpsha256z:Hash algorithm to use for file content, support by hashlib)default_valuer[   r\   c              /     #    U R                  U5         [        U/UQ70 UD6 nUv   SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f7f)z<wrapper around io.open that turns permission errors into 403N)perm_to_403rG   selfos_pathargsrP   fs        r   rG   FileManagerMixin.open   sF      g&W(Ft(Fv(F!G )G&&(F(F&&s/   AA:A	A
A	A
AAc              /  X  #    U R                  U5         U R                  US'   U R                  (       a  [        U/UQ70 UD6 nUv   SSS5        O[	        U/UQ70 UD6 nUv   SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       N(= f! , (       d  f       g= f7f)zwrapper around atomic_writing that turns permission errors to 403.
Depending on flag 'use_atomic_writing', the wrapper perform an actual atomic writing or
simply writes the file (whatever an old exists or not)r-   N)r`   r-   use_atomic_writingrU   rW   ra   s        r   rU   FileManagerMixin.atomic_writing   s     
 g& HHF5M&&#G=d=f=G >= %W>t>v>!G ? '& >= ?> '&sL   B*0BA7	B!B&B.	B*7
B	B
B	B
B'#B*c              #    #     Sv   g! [          as  nUR                  [        R                  [        R                  1;   a?  U(       d  UR                  =(       d    Sn[        XR                  S9n[        SSU-  5      Uee SnAff = f7f)z7context manager for turning permission errors into 403.Nzunknown file)rooti  zPermission denied: %s)r+   r&   EPERMr'   filenamer   root_dirr	   )rb   rc   er3   s       r   r`   FileManagerMixin.perm_to_403   sn     	 
	ww5;;55 jj:NG"7?%<t%CD!K
	s%   B		 B	
BA.BBB	c                ,    [        XU R                  S9  gz@copy src to dest

like shutil.copy2, but log errors in copystat
r@   N)r.   r-   rb   r   dests      r   _copyFileManagerMixin._copy  s    
 	3$((+r   c                (   [         R                  R                  U R                  5      n[         R                  R	                  U5      S   (       a  [        SSU-  5      e[        [        U5      U5      n [         R                  " U5        [         R                  R                  U5      [         R                  R                  -   R                  U5      (       d  [        SSU-  5      eU$ ! [         a     Nk[         a    [        SU S35      Sef = f)zGiven an API path, return its file system path.

Parameters
----------
path : str
    The relative API path to the named file.

Returns
-------
path : str
    Native, absolute OS path to for a file.

Raises
------
404: if path is outside root
r   i  z%s is not a relative API pathz is not a valid pathNz%%s is outside root contents directory)r   r3   abspathrn   
splitdriver	   r   r   lstatr+   
ValueErrorsep
startswith)rb   r3   rk   rc   s       r   _get_os_pathFileManagerMixin._get_os_path  s    & wwt}}-77d#A&C!@4!GHHWT]D1	JHHW (277;;6BB4HHC!H4!OPP  	  	JCD6)=!>?TI	Js   6C+ +
D7DNc                   U R                  USUS9n [        R                  " US   UUS9nU(       a  XeS   4$ U$ ! [         a  nUn SnAOSnAff = f[	        U5      n	U R
                  (       a$  [        R                  R                  U	5      (       d  [        SSU S	U< 35      e[        U5      n
[        X5        [        X5        U R                  XX4S
9$ ) Read a notebook from an os path.rO   )rawr   
as_versioncapture_validation_error   N  Unreadable Notebook:  r   r   )
_read_filenbformatreads	Exceptionr9   rh   r   r3   existsr	   r;   r   _read_notebookrb   rc   r   r   r   answernbro   e_origrT   invalid_files              r   r   FileManagerMixin._read_notebook;  s     &c:		q	%)AB '*Bq	?1r1 	F	 (0&&bggnnX.F.F'y&<  'w/W+X'"":R # 
 	
s   %; ; 
AAAc                    U R                  USS9 n[        R                  " UU[        R                  US9  SSS5        g! , (       d  f       g= fzSave a notebook to an os_path.utf-8)r?   )versionr   N)rU   r   write
NO_CONVERTrb   rc   r   r   re   s        r   _save_notebookFileManagerMixin._save_notebook_  sA      7 ;qNN ++)A	 <;;s   &A  
Ac                    U R                   n[        R                  " U5      nUR                  U5        UR	                  5       US.$ )a  Compute the hash hexdigest for the provided bytes.

The hash algorithm is provided by the `hash_algorithm` attribute.

Parameters
----------
byte_content : bytes
    The bytes to hash

Returns
-------
A dictionary to be appended to a model {"hash": str, "hash_algorithm": str}.
)hashhash_algorithm)r   hashlibnewupdate	hexdigest)rb   byte_content	algorithmhs       r   	_get_hashFileManagerMixin._get_hashi  s:     ''	KK	"	CCr   c                T   [         R                  R                  U5      (       d  [        SSU-  5      eU R	                  US5       nUR                  5       nSSS5        US:X  a  U(       a  WSU4$ WS4$ Ub  US:X  a/   U(       a  WR                  S5      SU4$ WR                  S5      S4$ U(       a  [        W5      R                  S5      SU4$ [        W5      R                  S5      S4$ ! , (       d  f       N= f! [         a  nUS:X  a  [        SSU-  S	S
9Ue SnANuSnAff = fa-  Read a non-notebook file.

Parameters
----------
os_path: str
    The path to be read.
format: str
    If 'text', the contents will be decoded as UTF-8.
    If 'base64', the raw bytes contents will be encoded as base64.
    If 'byte', the raw bytes contents will be returned.
    If not specified, try to decode as UTF-8, and fall back to base64
raw: bool
    [Optional] If True, will return as third argument the raw bytes content

Returns
-------
(content, format, byte_content) It returns the content in the given format
as well as the raw byte content.
r   zCannot read non-file %srbNbyterO   utf8z%s is not UTF-8 encodedz
bad format)reasonasciibase64)	r   r3   rF   r	   rG   readdecodeUnicodeErrorr   rb   rc   formatr   re   bcontentro   s          r   r   FileManagerMixin._read_file|  sG   , ww~~g&&C!:W!DEEYYw%vvxH & V36Hfh/NXv<NN>Vv-  __V,fh? !/"  "))'2HhG	
 H%,,W5	
5 &%&   V##1G;+ 	 $s*   C-?C> C> -
C;>
D'D""D'c                T   US;  a  [        SS5      e US:X  a  UR                  S5      nOUR                  S5      n[        U5      n U R	                  US
S9 nUR                  U5        S	S	S	5        g	! [         a  n[        SSU SU 35      UeS	nAff = f! , (       d  f       g	= fzSave content of a generic file.>   rO   r   r   z:Must specify format of file contents as 'text' or 'base64'rO   r   r   zEncoding error saving z: NF)rO   )r	   encoder   r   rU   r   rb   rc   contentr   r   	b64_bytesro   re   s           r   
_save_fileFileManagerMixin._save_file  s    ++L 	Q">>&1#NN73	&y1   u 5GGH 65  	QC#9'"QC!HIqP	Q 65s(   A4 A4 B4
B>BB
B' )    NFr   boolN)r   bytesreturnzdict[str, str]Frc   strr   z
str | Noner   r   r   z8tuple[str | bytes, str] | tuple[str | bytes, str, bytes])__name__
__module____qualname____firstlineno____doc__r
   rh   r   r   algorithms_availabler   r   rG   rU   r`   ru   r~   r   r   r   r   r   __static_attributes__r   r   r   rY   rY      s    "  $$I	N  
     ,%P QV"
IM"
HD( =B:
:
$.:
59:
	A:
xr   rY   c                  ^    \ rS rSrSrS r S
 SS jjrSS jr S       SS jjrS r	S	r
g)AsyncFileManagerMixini  zQ
Mixin for ContentsAPI classes that interact with the filesystem asynchronously.
c                H   #    [        XU R                  S9I Sh  vN   g N7frr   )r0   r-   rs   s      r   ru   AsyncFileManagerMixin._copy  s     
 sdhh777s   " "Nc                8  #    U R                  USU5      I Sh  vN n [        [        [        R                  UUS9US   5      I Sh  vN nU(       a  XeS   4$ U$  NB N! [
         a  nUn SnAOSnAff = f[        U5      n	U R                  (       a$  [        R                  R                  U	5      (       d  [        SSU SU< 35      e[        U5      n
[        X5      I Sh  vN    [        X5      I Sh  vN    U R                  XX4S	9I Sh  vN  nU$ 7f)
r   rO   Nr   r   r   r   r   r   r   )r   r   r   r   r   r   r9   rh   r   r3   r   r	   r;   r   r   r   s              r   r   $AsyncFileManagerMixin._read_notebook  s     w<<	NN)-E
 q	 B '*Bq	?1r1 =  	F	 (0&&bggnnX.F.F'y&<  'w/ 777 333**:R + 
 
 
 s{   DAD)A  A	A  DA  DA   
A6*A1,D1A66A/D%C(&D9C<:DDDc           	        #    U R                  USS9 n[        [        [        R                  [        R
                  US9UU5      I Sh  vN   SSS5        g N! , (       d  f       g= f7fr   )rU   r   r   r   r   r   r   s        r   r   $AsyncFileManagerMixin._save_notebook   sd       7 ;qNN$//-E
    <; <;s.   A*6A	A
A	A*A
A'#A*c                z  #    [         R                  R                  U5      (       d  [        SSU-  5      eU R	                  US5       n[        UR                  5      I Sh  vN nSSS5        US:X  a  U(       a  WSU4$ WS4$ Ub  US:X  a/   U(       a  WR                  S5      SU4$ WR                  S5      S4$ U(       a  [        W5      R                  S5      SU4$ [        W5      R                  S5      S4$  N! , (       d  f       N= f! [         a  nUS:X  a  [        SSU-  S	S
9Ue SnANwSnAff = f7fr   )
r   r3   rF   r	   rG   r   r   r   r   r   r   s          r   r    AsyncFileManagerMixin._read_file  sQ    , ww~~g&&C!:W!DEEYYw%%aff--H & V36Hfh/NXv<NN>Vv-  __V,fh? !/"  "))'2HhG	
 h'..w7B	
3 . &%&   V##1G;+ 	 $sg   AD;C>!C<"C>&'D;D (D;)D ;AD;<C>>
DD;
D8D3.D;3D88D;c                z  #    US;  a  [        SS5      e US:X  a  UR                  S5      nOUR                  S5      n[        U5      n U R	                  US
S9 n[        UR                  U5      I S	h  vN   S	S	S	5        g	! [         a  n[        SSU SU 35      UeS	nAff = f N2! , (       d  f       g	= f7fr   )r	   r   r   r   rU   r   r   r   s           r   r    AsyncFileManagerMixin._save_fileF  s     ++L 	Q">>&1#NN73	&y1   u 5177H--- 65  	QC#9'"QC!HIqP	Q . 65s\   B;B B;B 
B;B*5B(6B*:	B;
B%B  B%%B;(B**
B84B;r   r   r   r   r   r   )r   r   r   r   r   ru   r   r   r   r   r   r   r   r   r   r     sW    8 QV&IM&P =B7
7
$.7
597
	A7
r.r   r   r   )Tr   N)(r   
__future__r   r&   r   r   r(   r   r   r   
contextlibr   	functoolsr   r   anyio.to_threadr   tornado.webr	   	traitletsr
   r   traitlets.configr   traitlets.config.configurabler   jupyter_server.utilsr   r   r   r   r   r.   r0   r9   r;   rU   rW   rY   r   r   r   r   <module>r      s    #   	  + %   $ !   ) = A A
)
C&C$28 D DN # #LB*L BJK., K.r   