o
    x[h,  ã                   @   sÄ   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 d dlm	Z	m
Z
 dZe e¡Ze	 d¡dd„ ƒZe	 d¡d	d
„ ƒZeddfdd„Zeddfdd„Zdd„ Ze	 d¡dd„ ƒZefdd„ZdS )é    N)Ú	b64decodeÚ	b64encode)ÚperformanceÚutili¤  zBase64 decodingc                 C   s,   t | ƒ}z| d¡W S  ty   | Y S w )z‹base64 decode data

    :param source: a bytes or str to decode
    :return: base64 as a decoded str if utf-8 encoded, otherwise bytes
    úutf-8)r   ÚdecodeÚUnicodeDecodeError)ÚsourceÚdecoded© r   ú9/usr/lib/python3/dist-packages/cloudinit/atomic_helper.pyÚb64d   s   ÿr   zBase64 encodingc                 C   s"   t | tƒs
|  d¡} t| ƒ d¡S )zdbase64 encode data

    :param source: a bytes or str to decode
    :return: base64 encoded str
    r   )Ú
isinstanceÚbytesÚencoder   r   )r	   r   r   r   Úb64e   s   

r   ÚwbFc                 C   sD   t  d| › �¡� t| ||||ƒW  d  ƒ S 1 sw   Y  dS )zCopen filename in mode omode, write content, set permissions to modezWriting N)r   ÚTimedÚ_write_file)ÚfilenameÚcontentÚmodeÚomodeÚpreserve_moder   r   r   Ú
write_file*   s   $ÿr   c           	   
   C   sÜ   |rzt  | ¡}t |j¡}W n	 ty   Y nw d }z:t j | ¡}t |¡ t	j
|d|d�}t d| |j||t|ƒ¡ | |¡ | ¡  t  |j|¡ t  |j| ¡ W d S  tym } z|d urgt  |j¡ |‚d }~ww )NF)ÚdirÚdeleter   zOAtomically writing to file %s (via temporary file %s) - %s: [%o] %d bytes/chars)ÚosÚstatÚS_IMODEÚst_modeÚOSErrorÚpathÚdirnamer   Ú
ensure_dirÚtempfileÚNamedTemporaryFileÚLOGÚdebugÚnameÚlenÚwriteÚcloseÚchmodÚrenameÚ	ExceptionÚunlink)	r   r   r   r   r   Ú	file_statÚtfr#   Úer   r   r   r   3   s<   
ÿ
ù
	€ýr   c                 C   s2   zd  t| ƒ¡W S  ty   d  t| ƒ¡ Y S w )z1Handler for types which aren't json serializable.z
ci-b64:{0}z)Warning: redacted unserializable type {0})Úformatr   ÚAttributeErrorÚtype)Ú_objr   r   r   Újson_serialize_defaultU   s
   ÿr8   zDumping jsonc                 C   s   t j| dddtd�S )z%Return data in nicely formatted json.é   T)ú,z: )ÚindentÚ	sort_keysÚ
separatorsÚdefault)ÚjsonÚdumpsr8   )Údatar   r   r   Ú
json_dumps]   s   ûrB   c                 C   s   t | t|ƒd d|d�S )NÚ
Úw)r   r   )r   rB   )r   rA   r   r   r   r   Ú
write_jsoni   s   
ürE   )r?   Úloggingr   r   r%   Úbase64r   r   Ú	cloudinitr   r   Ú
_DEF_PERMSÚ	getLoggerÚ__name__r'   Útimedr   r   r   r   r8   rB   rE   r   r   r   r   Ú<module>   s*   



ÿ

ÿ"
