o
    tfD                     @  s4  d Z ddlmZ ddlZddlZddlmZ ddlmZ ddlZddl	m
Z ddl	mZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZmZmZmZ dZd>ddZd?ddZd@dd Z	!			"dAdBd(d)Z dCd*d+Z!	!dDdEd.d/Z"dFd1d2Z#	3				"dGdHd6d7Z$	dIdJd:d;Z%G d<d= d=eZ&dS )Kz Frontend config storage helpers.    )annotationsN)glob)Any)Draft7Validator)ValidationError)_tz)
APIHandler)ConfigManagerrecursive_update)web   )DEFAULT_LOCALEL10N_SCHEMA_NAME
SYS_LOCALEis_valid_localez.jupyterlab-settingsschemas_dirstrschema_name	overridesdict[str, Any]labextensions_pathlist[str] | Nonereturntuple[dict[str, Any], str]c                 C  sr  d}d}d}d}|dur7| d\}}	}
|D ] }tj||d||
d }tj|r6tj||d} |} nq|du r@t| |}tj|sNtd|| t|d	d
+}zt	
|}W n tyw } z|}td||t|f dd}~ww W d   n1 sw   Y  t|||}zt| W n ty } z|}td||t|f dd}~ww t| |}||fS )z=Returns a dict containing a parsed and validated JSON schema.zSchema not found: %szFailed parsing schema (%s): %sz!Failed validating schema (%s): %sN:Zschemas.json  utf-8encoding  )	partitionospathjoinexists_pathr   	HTTPErroropenjsonload	Exceptionr   	_override	ValidatorZcheck_schema_get_version)r   r   r   r   notfound_errorparse_errorZvalidation_errorr#   Zext_name_Zplugin_nameZext_pathtargetfidschemaenameversion r8   i/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/jupyterlab_server/settings_utils.py_get_schema   sJ   

r:   settings_dirr4   r   c                 C  sH  t | |dt}d}i }d}d}d}d}	d}
tj|rmt|}t|j	 }	t|j
	 }
t|dd/}z| p=|}t|}W n ty] } ztd||t|f dd}~ww W d   n1 shw   Y  t|rt|}z|| W n ty } z||t|f }d}i }W Y d}~nd}~ww t||||	|
d	S )
z
    Returns a dictionary containing the raw user settings, the parsed user
    settings, a validation warning for a schema, and file times.
    Fz{}Nz#Failed validating settings (%s): %sz Failed loading settings (%s): %sr   r   r    )rawsettingswarninglast_modifiedcreated)r&   SETTINGS_EXTENSIONr"   r#   r%   stattzutcfromtimestampst_mtime	isoformatst_ctimer(   readjson5loadsr+   r   r'   r   lenr-   validater   dict)r;   r   r4   r#   r<   r=   r>   Zvalidation_warningr0   r?   r@   rB   r3   r5   	validatorr8   r8   r9   _get_user_settingsO   sF   

rO   c                 C  s   t | |}tjtj|d d}z#t|dd}t|}|d W  d   W S 1 s.w   Y  W dS  ty?   Y dS w )zEReturns the package version for a given schema or 'N/A' if not found.r   zpackage.json.origr   r   r7   NzN/A)	r&   r"   r#   r$   splitr(   r)   r*   r+   )r   r   r#   package_pathr3   packager8   r8   r9   r.   w   s   

(r.   r   F	extension
translatorids_onlybooltuple[list[Any], list[Any]]c                   s`  i  i }g }t j| sd|  g}g |fS | d | }	dd t|	ddD }
|
  |
D ]_}t j|| }t j|\}}d||dt|  g	d	d
 }}|r[t
|d |< q,t| ||d\}}|durl||}t|||}|d r~||d t
d|||d| |< q,|durg }
|D ]}|d | }	|
dd t|	ddD  q|
  |
D ]e}|	t jd
}|d\}}t j|\}}d||dt|  g	d	d
 }}||v rq|rt
|d||< qt| |||d\}}t|||}|d r
||d t
d|||d|||< q |  fddt  ddD }||fS )ac  
    Returns a tuple containing:
     - the list of plugins, schemas, and their settings,
       respecting any defaults that may have been overridden if `ids_only=False`,
       otherwise a list of dict containing only the ids of plugins.
     - the list of warnings that were generated when
       validating the user overrides against the schemas.
    z'Settings directory does not exist at %sz/**/*c                 S  s   g | ]}|qS r8   r8   .0r#   r8   r8   r9   
<listcomp>   s    z"_list_settings.<locals>.<listcomp>T)	recursiver   N\/)idr>   r^   r4   r7   z/**/schemas/**/*c                 s  s    | ]}|V  qd S Nr8   rX   r8   r8   r9   	<genexpr>   s    z!_list_settings.<locals>.<genexpr>zschemas/r   c                   s   g | ]} | qS r8   r8   )rY   keyr=   r8   r9   rZ      s    )reverser8   )r"   r#   r%   r   sortrelpathrP   r$   rK   replacerM   r:   rO   appendpopextendsepupdatesortedkeys)r   r;   r   rS   r   rT   rU   Zfederated_settingswarningsZschema_patternZschema_pathsZschema_pathrel_pathZrel_schema_dirZschema_baseZ_idr   r4   r7   user_settingsZext_dirZschema_path_base_dirsettings_listr8   rd   r9   _list_settings   sv   




ru   c                 C  s   | |v r@||  }|D ]5}||d v r4|d | d }t |tr't|||  n|| }||d | d< q
t|| d|d |< q
|S )z3Override default values in the schema if necessary.
propertiesdefault)rw   )
isinstancerM   r
   )r   r4   r   defaultsrc   Znew_defaultsr8   r8   r9   r,      s   
r,   root_dir	make_dirsc              
   C  s   d}d}z| d\}}tj| |}tj||| }	W n ty-   td|| dw |rXtj|sXzt| W |	S  tyW }
 ztd||t	|
f dd}
~
ww |	S )a1  
    Returns the local file system path for a schema name in the given root
    directory. This function can be used to filed user overrides in addition to
    schema files. If the `make_dirs` flag is set to `True` it will create the
    parent directory for the calculated path if it does not exist.
    zSettings not found (%s)z Failed writing settings (%s): %sr   r   Nr    )
rP   r"   r#   r$   r+   r   r'   r%   makedirsr   )rz   r   r{   rS   r/   Zwrite_errorZpackage_dirplugin
parent_dirr#   r5   r8   r8   r9   r&      s$   
r&   app_settings_dirc                 C  sV  i d}}t j| d}tg tt j|dtt j|d}|t j| dt j| dg7 }|D ]X}t j|s=q4t|ddA}z$|d	rPt	|}nt
	|}| D ]\}}	t||i |	 qYW n ty| }
 z|
}W Y d
}
~
nd
}
~
ww W d
   n1 sw   Y  q4tdd}|d D ]\}}	t||i |	 q||fS )zGet overrides settings from `app_settings_dir`.

    The ordering of paths is:
    - {app_settings_dir}/overrides.d/*.{json,json5} (many, namespaced by package)
    - {app_settings_dir}/overrides.{json,json5} (singleton, owned by the user)
     zoverrides.dz*.jsonz*.json5zoverrides.jsonzoverrides.json5r   r   z.json5NZ	labconfig)config_dir_nameZdefault_setting_overrides)r"   r#   r$   rn   r   r%   r(   endswithrI   r*   r)   itemsr
   
setdefaultr+   r	   get)r   r   errorZoverrides_dZall_override_pathsZoverrides_pathr3   Zpath_overridesZ	plugin_idconfigr5   cmr8   r8   r9   _get_overrides  sF   
	


r   r   dict[str, Any] | None tuple[dict[str, Any], list[Any]]c                 C  s   i }g }	|du rt | \}}
|r9t||||\}}|dur!||}t|||}|dg}	|||d|}||	fS t||||||d\}}	d|i}||	fS )aK  
    Get settings.

    Parameters
    ----------
    app_settings_dir:
        Path to applications settings.
    schemas_dir: str
        Path to schemas.
    settings_dir:
        Path to settings.
    schema_name str, optional
        Schema name. Default is "".
    overrides: dict, optional
        Settings overrides. If not provided, the overrides will be loaded
        from the `app_settings_dir`. Default is None.
    labextensions_path: list, optional
        List of paths to federated labextensions containing their own schema files.
    translator: Callable[[Dict], Dict] or None, optional
        Translate a schema. It requires the schema dictionary and returns its translation

    Returns
    -------
    tuple
        The first item is a dictionary with a list of setting if no `schema_name`
        was provided (only the ids if `ids_only=True`), otherwise it is a dictionary
        with id, raw, scheme, settings and version keys.
        The second item is a list of warnings. Warnings will either be a list of
        i) strings with the warning messages or ii) `None`.
    Nr>   r_   )r   rT   rU   r=   )r   r:   rO   rj   ru   )r   r   r;   r   r   r   rT   rU   resultrp   _errorr4   r7   rr   rt   r8   r8   r9   get_settingsL  s.   (
	r   raw_settingsNonec                 C  s|   t |}t| |||d\}}t|}	|	| t||dt}
t|
ddd}|| W d   dS 1 s7w   Y  dS )a  
    Save ``raw_settings`` settings for ``schema_name``.

    Parameters
    ----------
    schemas_dir: str
        Path to schemas.
    settings_dir: str
        Path to settings.
    schema_name str
        Schema name.
    raw_settings: str
        Raw serialized settings dictionary
    overrides: dict
        Settings overrides.
    labextensions_path: list, optional
        List of paths to federated labextensions containing their own schema files.
    rb   Twr   r   N)	rI   rJ   r:   r-   rL   r&   rA   r(   write)r   r;   r   r   r   r   payloadr4   r1   rN   r#   r3   r8   r8   r9   save_settings  s   


"r   c                      s0   e Zd ZdZ	dd fddZdddZ  ZS )SchemaHandlerz6Base handler for handler requiring access to settings.Nr   r   r   r;   r   r   r   r   kwargsr   r   r   c           	        sb   t  jdi | d}|st|\}}|| _|| _|| _|| _|| _|r/d}| j	|| dS dS )zInitialize the handler.NzFailed loading overrides: %sr8   )
super
initializer   r   r   r   r;   r   logr>   )	selfr   r   r;   r   r   r   r   Zoverrides_warning	__class__r8   r9   r     s   
zSchemaHandler.initializec              
   C  s   zt | j| j| jt| j| jd\}}W n tjy1 } zd}| j	
|| i }W Y d}~nd}~ww |di dp<t}|dkrCt}t|sIt}|S )aQ  
        Get the current locale as specified in the translation-extension settings.

        Returns
        -------
        str
            The current locale string.

        Notes
        -----
        If the locale setting is not available or not valid, it will default to jupyterlab_server.translation_utils.DEFAULT_LOCALE.
        )r   r   r   z4Missing or misshapen translation settings schema:
%sNr=   localerw   )r   r   r   r;   r   r   r   r   r'   r   r>   r   r   r   r   )r   r=   r1   r5   Zschema_warningZcurrent_localer8   r8   r9   get_current_locale  s*   z SchemaHandler.get_current_localer`   )r   r   r   r   r;   r   r   r   r   r   r   r   r   r   )r   r   )__name__
__module____qualname____doc__r   r   __classcell__r8   r8   r   r9   r     s
    r   )
r   r   r   r   r   r   r   r   r   r   )r;   r   r   r   r4   r   r   r   )r   r   r   r   r   r   )r   NNF)r   r   r;   r   r   r   rS   r   r   r   rT   r   rU   rV   r   rW   )r   r   r4   r   r   r   r   r   )Fr   )
rz   r   r   r   r{   rV   rS   r   r   r   )r   r   r   r   )r   NNNF)r   r   r   r   r;   r   r   r   r   r   r   r   rT   r   rU   rV   r   r   r`   )r   r   r;   r   r   r   r   r   r   r   r   r   r   r   )'r   
__future__r   r)   r"   r   typingr   rI   Z
jsonschemar   r-   r   Zjupyter_serverr   rC   Zjupyter_server.base.handlersr   Z&jupyter_server.services.config.managerr	   r
   tornador   Ztranslation_utilsr   r   r   r   rA   r:   rO   r.   ru   r,   r&   r   r   r   r   r8   r8   r8   r9   <module>   sH    

5
(
a
7K)