
                             d Z ddlmZ ddlm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
mZ ddlZ G d	 d
ej                        Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)zJSON schema YAML validator module.

Usage:

  # Get a validator for the JSON schema in the file schema_path.
  validator = yaml_validator.Validator(schema_path)
  # Validate parsed YAML data.
  validator.Validate(parsed_yaml_data)
    )absolute_import)division)unicode_literalsN)
exceptions)yaml)pkg_resourcesc                       e Zd ZdZy)ErrorzErrors for this module.N__name__
__module____qualname____doc__     )lib/googlecloudsdk/core/yaml_validator.pyr
   r
   (       r   r
   c                       e Zd ZdZy)InvalidSchemaErrorzJSON schema is invalid.Nr   r   r   r   r   r   ,   r   r   r   c                       e Zd ZdZy)InvalidSchemaVersionErrorzJSON schema version is invalid.Nr   r   r   r   r   r   0   s    'r   r   c                       e Zd ZdZy)RefErrorz&Ref error -- YAML $ref path not found.Nr   r   r   r   r   r   4   s    .r   r   c                   "     e Zd ZdZ fdZ xZS )ValidationErrorzValidation error -- YAML data does not match the schema.

  Attributes:
      message: A user-readable error message describing the validation error.
  c                 N    t         t        |   |       |j                  | _        y )N)superr   __init__message)selferror	__class__s     r   r   zValidationError.__init__?   s    	/4)%0==DLr   )r   r   r   r   r   __classcell__)r"   s   @r   r   r   8   s    ! !r   r   c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)	ValidatorzJSON schema validator.c                     t         j                  j                  |       G  fddt        j                        }	 t        j                  t        j                  |            } j                  ||       |j                  |      }t        j                  j                  |      ||       _         j                  j                    _        y# t        $ r}t        |      d}~ww xY w)a  "Initilaizes the schema and validator for schema_path.

    The validator resolves references to all other schemas in the directory
    of schema_path.

    Yes, it's really this ugly defining a validator with a resolver to
    pkg_resources resources.

    Raises:
      IOError: if schema not found in installed resources.
      files.Error: if schema file not found.
      SchemaError: if the schema is invalid.

    Args:
      schema_path: JSON schema file path.

    Returns:
      The schema to validate and the validator.
    c                   (    e Zd ZdZe fd       Zy)'Validator.__init__.<locals>.RefResolverz+$ref: resolver that consults pkg_resources.c                     t         j                  j                  |       }t        j                  |      }	 t        j                  |      }j                  ||       |S # t        $ r}t        |      d}~ww xY w)z>pkg_resources $ref override -- schema_dir closure needed here.N)
ospathjoinr   GetResourceFromFiler   load	Exceptionr   ValidateSchemaVersion)refr+   dataschemae
schema_dirr    s        r   resolve_remotez6Validator.__init__.<locals>.RefResolver.resolve_remote`   so     ww||J,006	&99T?& 	""640  	&"1%
%	&s   A! !	A:*A55A:N)r   r   r   r   staticmethodr6   )r5   r    s   r   RefResolverr(   ]   s    7	 	r   r8   N)resolver)r*   r+   dirname
jsonschemar8   r   r.   r   r-   r/   r   r0   from_schema
validatorsvalidator_for
_validatorvalidate	_validate)r    schema_pathr8   r3   r4   r9   r5   s   `     @r   r   zValidator.__init__G   s    ( -Jj,, "yy::;GHf 	v{3&&v.H ++99&A#DO__--DN  "q!!"s   (C 	C*C%%C*c                     	 |j                  d      }|r"|j                  d      r|j                  d      st	        dj                  ||            y# t        $ r d}Y Mw xY w)z.Validates the parsed_yaml JSON schema version.z$schemaNzhttp://json-schema.org/z/schema#zZSchema [{}] version [{}] is invalid. Expected "$schema: http://json-schema.org/*/schema#".)getAttributeError
startswithendswithr   format)r    r3   r+   versions       r   r0   zValidator.ValidateSchemaVersionv   sr    

9%g 89Z(%//5vdG/DF F )	  gs   A A! A!c                     	 | j                  |       y# t        j                  $ r}t        |      d}~wt        j                  $ r}t	        |      d}~ww xY w)zValidates parsed_yaml against JSON schema.

    Args:
      parsed_yaml: YAML to validate

    Raises:
      ValidationError: if the template doesn't obey the schema.
    N)rA   r;   RefResolutionErrorr   r   )r    parsed_yamlr4   s      r   ValidatezValidator.Validate   sM    
nn[!(( QK%% As    A2AAAc           
         	 | j                  |       y# t        j                  $ r}t        |      d}~wt        j                  j
                  $ r}t        j                         }|j                  dj                  |             |j                  rdj                  |j                        }nd}|j                  r|j                  d   nd}|r#dj                  d |j                  D              }nd}|j                  dj                  |r|j                  nd|r|j                  nd|r|j                   nd||             |j#                         |_        t        |      d}~ww xY w)	zValidates parsed_yaml against JSON schema.

    Provides details of validation failure in the returned error message.
    Args:
      parsed_yaml: YAML to validate

    Raises:
      ValidationError: if the template doesn't obey the schema.
    Nz%ERROR: Schema validation failed: {}

zRoot Exception: {} c              3   >   K   | ]  }d j                  |        yw)z[{}]N)rH   ).0elems     r   	<genexpr>z6Validator.ValidateWithDetailedError.<locals>.<genexpr>   s     F-ETV]]4 -Es   zAdditional Details:
Error Message: {msg}

Failing Validation Schema: {schema}

Failing Element: {instance}

Failing Element Path: {path}

{additional_cause}
)msginstancer3   r+   additional_cause)rA   r;   rK   r   r   r   ioStringIOwriterH   causecontextr,   absolute_pathr   rV   r3   getvalue)r    rL   r4   verU   additional_exception
root_error
error_paths           r   ValidateWithDetailedErrorz#Validator.ValidateWithDetailedError   s2     
nn[!(( QK  00  KKMc	ii9@@DE	3::288D!%'ZZ2::b>Tj	WWFZ-E-EFH
 
	ii '
 (.v.8
**d4>Z00D0::,,#%9 (. (;
< <<>bjB9 s    E)2!E)DE$$E)c                 8    | j                   j                  |      S )a  Validates parsed_yaml against JSON schema and returns all errors.

    Args:
      parsed_yaml: YAML to validate

    Raises:
      ValidationError: if the template doesn't obey the schema.

    Returns:
      A list of all errors, empty if no validation errors.
    )r?   iter_errors)r    rL   s     r   IteratezValidator.Iterate   s     ??&&{33r   N)	r   r   r   r   r   r0   rM   rc   rf   r   r   r   r%   r%   D   s!    -.^F * X4r   r%   )r   
__future__r   r   r   rX   r*   googlecloudsdk.corer   r   googlecloudsdk.core.utilr   r;   r
   r   r   r   r   objectr%   r   r   r   <module>rk      sw     '  ' 	 	 * $ 2  J     ( (/u /	!e 	!G4 G4r   