o
    th,                     @   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 )zbase64 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*   





"
