o
    gw                     @   s   d dl m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Zd dl	Z	d dl
mZ d dlZd dlmZ edddgZdd	 Zd
d Zeejddd ZdddZG dd deZG dd deZG dd deeZdd Zedkr~ee  dS dS )    )print_functionN)
namedtuple)MutableMappingPropertyTupledatametac                 C   s,   t | tjr| dpt | tjo| dS )z
    Check whether a metadata key refers to "runtime metadata" that should
    not be dumped when writing out property files.

    Such keys are those starting with two underscores, e. g. ``__foo``.

    Handles both unicode and byte metadata keys.
    __s   __)
isinstancesix	text_type
startswithbinary_type)key r   X/var/www/html/portale_awareness/portale-venv/lib/python3.10/site-packages/jproperties.py_is_runtime_meta3   s   
r   c                 C   s2   dd }t | tjr| d} ttd|| S )a  
    Escape non-printable (or non-ASCII) characters using Java-compatible Unicode escape sequences.

    This function is based on code from the JSON library module shipped with Python 2.7.3
    (json/encoder.py, function py_encode_basestring_ascii), which is Copyright (c) 2001, 2002, 2003,
    2004, 2005, 2006 Python Software Foundation; All Rights Reserved. See the file LICENSE included
    with jProperties for the full license terms. If that file is not available, then please see:
    https://www.python.org/download/releases/2.7.3/license/

    Differences to the aforementioned original version of py_encode_basestring_ascii():
      - Always tries to decode str objects as UTF-8, even if they don't contain any UTF-8
        characters.  This is so that we always return an unicode object.
      - Only processes non-printable or non-ASCII characters. Also _always_ replaces these
        characters with Java-compatible Unicode escape sequences (the original function replaced
        e. g. newlines with "
" etc.).
      - Does not wrap the resulting string in double quotes (").

    :type unicode_obj: unicode
    :param unicode_obj: The source string containing data to escape.
    :rtype : unicode
    :return: A unicode object. This does not contain any non-ASCII characters anymore.
    c                 S   sT   |  d}t|}|dk rd|S |d8 }d|d? d@ B }d|d@ B }d||S )	Nr      z	\u{0:04x}   
        z\u{0:04x}\u{1:04x})groupordformat)matchsns1s2r   r   r   replaceY   s   

z"_escape_non_ascii.<locals>.replaceutf-8z[^ -~])r	   r
   r   decoderesubr   )unicode_objr   r   r   r   _escape_non_asciiB   s   
r%   jproperties.jbackslashreplacec                 C   s*   t | ts| t| j| j| j | jfS )a  
    Encoding error handler which replaces invalid characters with Java-compliant Unicode escape sequences.

    :param err: An `:exc:UnicodeEncodeError` instance.
    :return: See https://docs.python.org/2/library/codecs.html?highlight=codecs#codecs.register_error
    )r	   UnicodeEncodeErrorr%   objectstartend)errr   r   r    _jbackslashreplace_error_handlerp   s   
r,   Fc                 C   s   t | tjr| d} nt | tjst| } tddtddtddi}|sD|tdd	td
dtddtddtddtddi | |}|sR|dd}nt	
dd|}|r_t|}|S )a|  
    Escape a string so that it can safely be written as a key/value to a property file.

    :type raw_str: unicode
    :param raw_str: The string to escape.
    :param only_leading_spaces: Controls which whitespace characters to escape (other illegal, non-whitespace characters
            are always escaped). If True, then only escape a possibly present single leading space character (this is
             used for the value of a key-value pair). If False, escape all whitespace characters.
    :param escape_non_printing: Whether to escape legal, but non-printable ASCII characters as well.
    :param line_breaks_only: Only escape , 
 and  and not characters like : and =. Note: This does not
    invalidate/influence the other parameters like only_leading_spaces -- spaces are always escaped as per
    only_leading_spaces.
    :rtype : unicode
    :return: The escaped string.
    r    z\r
z\nz\f#z\#!z\!=z\=:z\:\z\\	z\t z\ z^ z\\ )r	   r
   r   r!   r   r   update	translater   r"   r#   r%   )raw_stronly_leading_spacesescape_non_printingline_breaks_only
trans_dictescaped_strr   r   r   _escape_str   s2   

r?   c                   @   s   e Zd ZdZdS )PropertyErrorz>Base exception class for all exceptions raised by this module.N)__name__
__module____qualname____doc__r   r   r   r   r@      s    r@   c                   @   s"   e Zd ZdZdddZdd ZdS )
ParseErrora  
    Raised on parse errors in property files.

    :ivar message: The error message (string).
    :ivar line_number: Number of the line where the error occurred (integer).
    :ivar file_obj: The file object we were reading from when the error occurred (may be None).
    Nc                 C   s   || _ || _|| _dS )a  
        Create a new ParseError exception.

        :param message: Error message.
        :param line_number: Line number of error.
        :param file_obj: File object we were reading from when the error occurred.
        :return: A new :exc:`.ParseError` object.
        N)messageline_numberfile_obj)selfrF   rG   rH   r   r   r   __init__   s   	
zParseError.__init__c                 C   s*   t | jdsdn| jj}d|| j| jf S )z
        Get a human-readable string representation of this object.

        :return: Human-readable string representation of this object.
        filenamez	<unknown>zParse error in %s:%d: %s)hasattrrH   rK   rG   rF   )rI   rK   r   r   r   __str__   s   zParseError.__str__N)rA   rB   rC   rD   rJ   rM   r   r   r   r   rE      s    
rE   c                       s*  e Zd ZdZdZdZee Zd< fdd	Zdd Zd	d
 Z	dd Z
dd Zdd Zedd Zejdd Zejdd Zdd Zdd Zdd Zdd Zdd Zd=d d!Zd"d# Zd$d% Zd<d&d'Zd=d(d)Zd=d*d+Zd,d- Zd.d/ Zd=d0d1Zd2d3 Zd>d5d6Z 		d?d8d9Z!e"j#fd:d;Z$  Z%S )@
Propertiesz
    A parser for Java property files.

    This class implements parsing Java property files as defined here:
    http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#load(java.io.Reader)
    z
z 	Tc                    s0   t t| j|i | || _|   |   dS )a  
        Create a new property file parser.

        :param process_escapes_in_values: If False, do not process escape sequences in values when parsing and try hard
        not to produce any escape sequences when writing, i. e. output strings literally. However, some things like
        leading whitespace and newlines are always escaped (since there is not good way around this).
        :return: A new :class:`.Properties`.
        N)superrO   rJ   _process_escapes_in_valuesresetclear)rI   process_escapes_in_valuesargskwargs	__class__r   r   rJ      s   zProperties.__init__c                 C   s
   t | jS rN   )len_propertiesrI   r   r   r   __len__
     
zProperties.__len__c                 C   s@   t |tjs
td|| jvrtdt| j| | j|i S N,Property keys must be of type str or unicodezKey not found)	r	   r
   string_types	TypeErrorrZ   KeyErrorr   	_metadataget)rI   itemr   r   r   __getitem__  s   
zProperties.__getitem__c                 C   s|   t |tjs
tdd }t |tr|\}}t |tjstd|d ur,t |ts,td|| j|< |d ur<|| j|< d S d S )Nr_   z.Property values must be of type str or unicode!Metadata needs to be a dictionary)r	   r
   r`   ra   tupledictrZ   rc   )rI   r   valuemetadatar   r   r   __setitem__  s   

zProperties.__setitem__c                 C   sh   t |tjs
td|| jvrtd| j|= || jv r | j|= z	| j| W d S  t	y3   Y d S w r^   )
r	   r
   r`   ra   rZ   rb   rc   
_key_orderremove
ValueErrorrI   r   r   r   r   __delitem__+  s   

zProperties.__delitem__c                 C   s
   | j  S rN   )rZ   __iter__r[   r   r   r   rr   ?  r]   zProperties.__iter__c                 C   s   | j S rN   rZ   r[   r   r   r   
propertiesB  s   zProperties.propertiesc                 C   s
   || _ d S rN   rs   )rI   rj   r   r   r   rt   F     
c                 C   s
   i | _ d S rN   rs   r[   r   r   r   rt   K  ru   c                 C   s   | j |i S )z
        Get the metadata for a key.

        :param key: The key to get metadata for.
        :return: Metadata for the key (always a dictionary, but empty if there is no metadata).
        )rc   rd   rp   r   r   r   getmetaP  s   zProperties.getmetac                 C   s    t |ts	td|| j|< dS )av  
        Set the metadata for a key.

        If the key starts with "__", then it is added, but will not be output when the file is written.

        :param key: The key to set the metadata for.
        :param metadata: The metadata to set for the key. Needs to be a dictionary.
        :return: None.
        :raise: TypeError if the metadata is not a dictionary.
        rg   N)r	   ri   ra   rc   )rI   r   rk   r   r   r   setmetaY  s   
zProperties.setmetac                 C   s0   | j du r| jd}|dkrt || _ | j S )a  
        Peek at the next character in the input stream.

        This implements a lookahead of one character. Use _getc() to actually read (or skip) the
        next character. Repeated calls to this method return the same character unless _getc() is called
        inbetween.

        :return: Next character in input stream.
        :raise: EOFError on EOF. IOError on other errors.
        N    )
_lookahead_source_filereadEOFErrorrI   cr   r   r   _peeki  s   
zProperties._peekc                 C   s   |   }d| _|S )aB  
        Read the next character from the input stream and return it.

        To only peek at the next character, use _peek(). Calling _getc() honors a possibly present lookahead
        and clears it.

        :return: Next character in input stream.
        :raise: EOFError on EOF and IOError on other errors.
        N)r   rz   r~   r   r   r   _getc~  s   
zProperties._getcc                 C   s   |   }|dkr.|  jd7  _|   z|   dkr!|   W dS W dS  ty-   Y dS w |dkr?|  jd7  _|   dS dS )z
        Skip a line terminator sequence (on of , 
 or 
) and increment the line number counter.

        This method is a no-op if the next character in the input stream is not  or 
.

        :return: None.
        :raise: EOFError, IOError.
        r-   rx   r.   N)r   _line_numberr   r}   r~   r   r   r   _handle_eol  s   	zProperties._handle_eolFc                 C   s>   	 |   }|| jvrdS || jv r|rdS |   n|   q)a&  
        Skip all adjacent whitespace in the input stream.

        Properly increments the line number counter when encountering line terminators.

        :param stop_at_eol: Determines whether to skip line terminators as well.
        :return: None
        :raise: EOFError, IOError
        TN)r   _ALLWHITESPACE_EOLr   r   )rI   stop_at_eolr   r   r   r   _skip_whitespace  s   



zProperties._skip_whitespacec                 C   sP   d}z|   | jvr||  7 }|   | jvs
|   W |S  ty'   Y |S w )zSkip a natural line.

        This simply skips all characters until a line terminator sequence is encountered
        (which is skipped as well).

        :return: The text on the line.
        :raise: IOError.
        ry   )r   r   r   r   r}   )rI   liner   r   r   _skip_natural_line  s   	
zProperties._skip_natural_linec                 C   s   |    |  dkr9|  }| jr7| jr7| j| ji }|dd |dr-|dd }|d  |d 7  < dS |    | d}| 	d}t
|sStd	| j| j|| j|< dS )
a  
        Parse a comment line.

        Usually, comment lines are simply skipped, as expected. However, if the character AFTER the comment line
        marker (i. e. the hash or the colon) is a colon, then the line is parsed for a key-value pair (except that
        line continuation is disabled) and the resulting pair is recorded as metadata for the NEXT, real key-value
        pair.

        :return: None.
        :raise: EOFError and IOError.
        r3   _docry   r6   rx   Nr.   Tz$Empty key in metadata key-value pair)r   r   r   _metadoc	_prev_keyrc   
setdefaultr   
_parse_key_parse_valuerY   rE   r   r{   _next_metadata)rI   docstrprev_metadatar   rj   r   r   r   _parse_comment  s(   


zProperties._parse_commentc              
   C   s  |   dkr
|   z|   }W n
 ty   Y dS w || jv r;|r9z|   | d W dS  ty8   Y dS w dS |   |dv rItd| S |dkr| j}zd}tdD ]}||  7 }qWt	|dd	}d
|  krpdkrn n^d}ztdD ]}||  7 }qyW n	 ty   Y nw |dd dkst
|dkrtd|| jt	|dd dd	}d|  krdksn td|| jd}	|	|d@ d> 7 }	|	|d@ 7 }	|	}td|dW S  ttfy }
 z	tt|
|| jd}
~
ww |S )a  Handle escape sequences like , 
 etc.

        Also handles line continuation.

        :param allow_line_continuation: If True, fold multiple natural lines into a single logical line if the line
            terminator is escaped. If False, then ignore line continuation attempts and drop the backslash used to
            escape the line terminator.
        :return: The evaluated escape sequence (string).
        :raise: EOFError and IOError.
        r4   ry   Trntfzu'\%s'u      )baser   i     N   z\uzgHigh surrogate unicode escape sequence not followed by another (low surrogate) unicode escape sequence.r   i  zLow surrogate unicode escape sequence expected after high surrogate escape sequence, but got a non-low-surrogate unicode escape sequence.r   r   r   z=Izutf-32)r   r   r}   r   r   r   evalr   rangeintrY   rE   r{   structpackr!   ro   str)rI   allow_line_continuationescaped_charstart_linenumbercodepoint_hexi	codepointcodepoint2_hex
codepoint2final_codepointer   r   r   _handle_escape  sp   
zProperties._handle_escapec                 C   sr   |  | d}	 z|  }W n
 ty   Y |S w |dkr&|| | 7 }q|| jv s/|dv r2	 |S ||  7 }q)a2  Parse and return the key of a key-value pair, possibly split over multiple natural lines.

        :param single_line_only: True to ignore line continuation, False to allow it.
        :rtype : unicode
        :return: The key, which may be empty.
        :raise: IOError, EOFError and ParseError.
        ry   Tr4   :=)r   r   r}   r   r   r   )rI   single_line_onlyr   r   r   r   r   r   `  s"   
zProperties._parse_keyc                 C   s   z|  d |  dv r|   |  d W n
 ty    Y dS w d}	 z|  }W n
 ty4   Y |S w |dkrE| jrE|| | 7 }q#|| jv rQ|   	 |S ||  7 }q$)aI  
        Parse and return the value of a key-value pair, possibly split over multiple natural lines.

        :param single_line_only: True to ignore line continuation, False to allow it.
        :rtype : unicode
        :return: The value, which may be an empty string.
        :raise: IOError, EOFError and ParseError.
        Tr   ry   r4   )r   r   r   r}   rQ   r   r   r   )rI   r   rj   r   r   r   r   r     s2   


zProperties._parse_valuec                 C   s   z
|    |  }W n
 ty   Y dS w |dv r+z|   W dS  ty*   Y dS w z
|  }|  }W n
 ty?   Y dS w || jvrK| j| || j|< t	| j
r^| j
| j|< i | _
|| _dS )a'  
        Parse a single logical line which may consist of multiple natural lines.

        Actually this may skip multiple empty natural lines at once and thus "parse" multiple (empty) logical lines
        (since an empty natural line is a single logical line). In practice, this does not matter.

        :return: False if there is nothing more to parse, True if this method should be called again to continue
                 parsing. A return value of False means that EOF was encountered in a non-error state.
        :raise: ParseError.
        Fz!#T)r   r   r}   r   r   r   rZ   rm   appendrY   r   rc   r   )rI   r   r   rj   r   r   r   _parse_logical_line  s6   



zProperties._parse_logical_linec                 C   s   |   r	 |   sdS dS )z
        Parse the entire input stream and record parsed key-value pairs.

        :return: None.
        :raise: See :meth:`._parse__parse_logical_line`.
        N)r   r[   r   r   r   _parse  s   zProperties._parsec                 C   s(   d| _ d| _d| _i | _d| _|| _dS )z
        Reset the parser state so that a new file can be parsed.

        Does not clear the internal property list so that multiple files can parsed consecutively.

        :return: None
        Nrx   )r{   r   rz   r   r   r   )rI   metadocr   r   r   rR     s   	
zProperties.resetc                 C   s   i | _ i | _g | _dS )zU
        Remove all properties and related metadata.

        :return: None.
        N)rZ   rc   rm   r[   r   r   r   rS     s   
zProperties.clear
iso-8859-1c                 C   sp   |  | t|tjrt||| _nt|tjr"t|| _n|dur/t	||| _n|| _| 
  dS )aa  
        Load, decode and parse an input stream (or string).

        :param source_data: Input data to parse. May be a :class:`str` which will be decoded according to
                `encoding`, a :class:`unicode` object or a file-like object. In the last case, if `encoding`
                is None, the file-like object is expected to provide transparent decoding to :class:`unicode`
                (see :func:`codecs.open`); otherwise, if `encoding` is not None, then data from the file-like
                object will be decoded using that encoding.
        :param encoding: If `source_data` is a :class:`str`, this specifies what encoding should be used to decode it.
        :return: None
        :raise: IOError, EOFError, ParseError, UnicodeDecodeError (if source_data needs to be decoded),
                 LookupError (if encoding is unknown).
        N)rR   r	   r
   r   StringIOr!   r{   r   codecs	getreaderr   )rI   source_dataencodingr   r   r   r   load  s   
zProperties.loadNc              
   C   s  t |}||d}|o|t dk}	|dur5tdd|}tdd|}tdd	|}td
| |d |r_g d}
g d}t }td|
|j ||j	d  |j
|j|j|j|jf |d t| j}t| j}||8 }t|}|  t| j|D ]H}|| jv r| |}|st|rt|D ]}t|rqtdt|t|| df |d qtdt||	dt| j| d|	| j df |d q|dS )a  
        Write a plain text representation of the properties to a stream.

        :param out_stream: The target stream where the data should be written. Should be opened in binary mode.
        :type initial_comments: unicode
        :param initial_comments: A string to output as an initial comment (a commented "header"). May safely contain
                unescaped line terminators.
        :param encoding: The encoding to write the data in.
        :param strict: Set to True to exactly behave like the Java property file writer. In particular, this will cause
            any non-printing characters in property keys and values to be escaped using "<BACKSLASH>uXXXX" escape
            sequences if the encoding is set to iso-8859-1. False causes sane behaviour, i. e. only use unicode escape
            sequences if the characters cannot be represented in the target encoding.
        :param strip_meta: Whether to strip metadata when writing.
        :param timestamp: True to write a comment line with the current time and date after the initial comments.
        :return: None.
        :raise: LookupError (if encoding is unknown), IOError, UnicodeEncodeError (if data cannot be encoded as
                 `encoding`.
        r&   latin_1Nz	(\r\n|\r)r.   z
\n(?![#!])z
#z	(\n[#!]):z\g<1>\:r0   file)MonTueWedThuFriSatSun)JanFebMarAprMayJunJulAugSepOctNovDecz##%s %s %02d %02d:%02d:%02d UTC %04drx   z#: %s=%sT%s=%s)r;   )r;   r<   )r   lookupstreamwriterr"   r#   printtimegmtimetm_wdaytm_montm_mdaytm_hourtm_mintm_sectm_yearsetrZ   rm   listsort	itertoolschainrv   rY   sortedr   r?   rQ   )rI   
out_streaminitial_commentsr   strict
strip_meta	timestampout_codec_infowrapped_out_streamproperties_escape_nonprintingday_of_weekmonthnowunordered_keysordered_keysunordered_keys_xsr   rk   mkeyr   r   r   store6  s   
		



	zProperties.storec                 C   s:   t d|d | jD ]}d|| j| f }t ||d q	dS )z
        Debugging method: Print an unsorted list of properties to `out_stream`.
        :param out_stream: Where to print the property list.
        :return: None
        z-- listing properties --r   r   N)r   rZ   )rI   r   r   msgr   r   r   r     s
   
zProperties.list)T)F)r   F)Nr   TTT)&rA   rB   rC   rD   r   _WHITESPACEr   rJ   r\   rf   rl   rq   rr   propertyrt   setterdeleterrv   rw   r   r   r   r   r   r   r   r   r   r   r   rR   rS   r   r   sysstderrr   __classcell__r   r   rW   r   rO      sL    


	

.
\
+4

#
 rO   c                  C   s  t jtjd } ttjdk stjd dkrZtdtjd tdtjd tdtjd td	|  tjd td
tjd tdtjd tdtjd tdtjd tdtjd dS ttjdk rcdntjd }ttjdk rqdntjd }ttjdk ptjd  dk}zt	tjd d}t
|}||| W n  tttttfy } ztd|tjd W Y d}~dS d}~ww z|tjrtjjntjd| |f |d W dS  tttfy } ztd|tjd W Y d}~dS d}~ww )a  
    Main function for interactive use.

    Loads a property file and dumps it to stdout, optionally converting between encodings.
    Escape sequence handling in property values can also be disabled (it is enabled by default).

    Reads parameters from `sys.argv`:

    - Input file path.
    - Optional: Input file encoding, defaults to `utf-8`.
    - Optional: Output encoding, defaults to `utf-8`.
    - Optional: `false` to take escape sequences in property values literally instead of parsing them.
      This will also try hard not to output any escape sequences in values and thus will output everything
      literally, as long as this does not lead to invalid output.

    :rtype: int
    :return: 0 on success, non-zero on error.
    r   r   rx   z-hzVLoads a property file and dumps it to stdout, optionally converting between encodings.r   zJEscape sequence handling can also be disabled (it is enabled by default).
zUsage:zI %s [-h] input_file [input_encoding [output_encoding [process_escapes]]]
zNThe input and output encodings default to `utf-8'. If `false' is given for thezO`process_escapes' parameter, then escape sequences in property values are takenzNliterally, i. e. they are treated like normal characters. This will also causezOthe writer to try hard not to output any escape sequences in values and thus itzRwill output everything literally, as long as this does not lead to invalid output.   r    r      falserbz!Error: Could not read input file:Nz,File generated by %s (escapes in values: %s)Fz!Error: Could not dump properties:)ospathbasenamer   argvrY   r   r   loweropenrO   r   IOErrorr}   rE   UnicodeDecodeErrorLookupErrorr   r
   PY3stdoutbufferr'   )	prog_namein_encout_encrT   fpr   r   r   r   main  sV    r  __main__)FFF)
__future__r   r   	functoolsr   r   r"   r   r   r   collectionsr   r
   six.moves.collections_abcr   r   r   r%   partialregister_errorr,   r?   	Exceptionr@   rE   r(   rO   r  rA   exitr   r   r   r   <module>   s<   .

>$     c?