U
    Ø–]9  ã                   @   sv   d dl Z d dl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mZ e 	e
¡ZG dd„ deƒZd	d
„ ZdS )é    Né   )Úauth)Ú	constants)Úerrors)Úutilsc                   @   s0   e Zd Zddd„Ze d¡dd„ ƒZd	d
„ ZdS )ÚBuildApiMixinNFTc           (   	   C   sì  d }}i }|pi }|pi }|dkr4|dkr4t dƒ‚|rJ|	dk	rJt d¡‚| ¡ D ]}|tjkrRt d |¡¡‚qR|rˆ|s‚t dƒ‚|}n¾|dk	rœt |¡}nª| 	d¡r¬|}nšt
j |¡sÂt dƒ‚n„t
j |d¡}d} t
j |¡rt|d	ƒ*}!ttd
d„ dd„ |! ¡  ¡ D ƒƒƒ} W 5 Q R X t||ƒ}tj|| ||d}|rBdn|	}	|  d¡}"|||||||
|dœ}#|# |¡ |r | j ¡ }$|$ ¡ D ]\}%}&| |%|&¡ qˆ|rº|# dt |¡i¡ |rêt | jd¡rà|# d|i¡ n
t  d¡‚|r t | jd¡r|# dt |¡i¡ n
t  d¡‚|rVt | jd¡rL|# dt |¡i¡ n
t  d¡‚|r†t | jd¡r||# d|i¡ n
t  d¡‚|r¶t | jd¡r¬|# d|i¡ n
t  d ¡‚|ræt | jd¡rÜ|# d!|i¡ n
t  d"¡‚|dk	r.t !| jd#¡r
t  d$¡‚t"|t#ƒr t $|¡}|# d%|i¡ |dk	rZt !| jd&¡rRt  d'¡‚||#d(< |dk	r†t !| jd)¡r~t  d*¡‚||#d+< |dk	r¦d,d-i}|	r¦|	|d.< |  %|¡ | j&|"||#|d/|d0}'|dk	rÞ|sÞ| '¡  | j(|'|d1S )2a¯  
        Similar to the ``docker build`` command. Either ``path`` or ``fileobj``
        needs to be set. ``path`` can be a local path (to a directory
        containing a Dockerfile) or a remote URL. ``fileobj`` must be a
        readable file-like object to a Dockerfile.

        If you have a tar file for the Docker build context (including a
        Dockerfile) already, pass a readable file-like object to ``fileobj``
        and also pass ``custom_context=True``. If the stream is compressed
        also, set ``encoding`` to the correct value (e.g ``gzip``).

        Example:
            >>> from io import BytesIO
            >>> from docker import APIClient
            >>> dockerfile = '''
            ... # Shared Volume
            ... FROM busybox:buildroot-2014.02
            ... VOLUME /data
            ... CMD ["/bin/sh"]
            ... '''
            >>> f = BytesIO(dockerfile.encode('utf-8'))
            >>> cli = APIClient(base_url='tcp://127.0.0.1:2375')
            >>> response = [line for line in cli.build(
            ...     fileobj=f, rm=True, tag='yourname/volume'
            ... )]
            >>> response
            ['{"stream":" ---\u003e a9eb17255234\n"}',
             '{"stream":"Step 1 : VOLUME /data\n"}',
             '{"stream":" ---\u003e Running in abdc1e6896c6\n"}',
             '{"stream":" ---\u003e 713bca62012e\n"}',
             '{"stream":"Removing intermediate container abdc1e6896c6\n"}',
             '{"stream":"Step 2 : CMD [\"/bin/sh\"]\n"}',
             '{"stream":" ---\u003e Running in dba30f2a1a7e\n"}',
             '{"stream":" ---\u003e 032b8b2855fc\n"}',
             '{"stream":"Removing intermediate container dba30f2a1a7e\n"}',
             '{"stream":"Successfully built 032b8b2855fc\n"}']

        Args:
            path (str): Path to the directory containing the Dockerfile
            fileobj: A file object to use as the Dockerfile. (Or a file-like
                object)
            tag (str): A tag to add to the final image
            quiet (bool): Whether to return the status
            nocache (bool): Don't use the cache when set to ``True``
            rm (bool): Remove intermediate containers. The ``docker build``
                command now defaults to ``--rm=true``, but we have kept the old
                default of `False` to preserve backward compatibility
            timeout (int): HTTP timeout
            custom_context (bool): Optional if using ``fileobj``
            encoding (str): The encoding for a stream. Set to ``gzip`` for
                compressing
            pull (bool): Downloads any updates to the FROM image in Dockerfiles
            forcerm (bool): Always remove intermediate containers, even after
                unsuccessful builds
            dockerfile (str): path within the build context to the Dockerfile
            buildargs (dict): A dictionary of build arguments
            container_limits (dict): A dictionary of limits applied to each
                container created by the build process. Valid keys:

                - memory (int): set memory limit for build
                - memswap (int): Total memory (memory + swap), -1 to disable
                    swap
                - cpushares (int): CPU shares (relative weight)
                - cpusetcpus (str): CPUs in which to allow execution, e.g.,
                    ``"0-3"``, ``"0,1"``
            decode (bool): If set to ``True``, the returned stream will be
                decoded into dicts on the fly. Default ``False``
            shmsize (int): Size of `/dev/shm` in bytes. The size must be
                greater than 0. If omitted the system uses 64MB
            labels (dict): A dictionary of labels to set on the image
            cache_from (:py:class:`list`): A list of images used for build
                cache resolution
            target (str): Name of the build-stage to build in a multi-stage
                Dockerfile
            network_mode (str): networking mode for the run commands during
                build
            squash (bool): Squash the resulting images layers into a
                single layer.
            extra_hosts (dict): Extra hosts to add to /etc/hosts in building
                containers, as a mapping of hostname to IP address.
            platform (str): Platform in the format ``os[/arch[/variant]]``
            isolation (str): Isolation technology used during build.
                Default: `None`.
            use_config_proxy (bool): If ``True``, and if the docker client
                configuration file (``~/.docker/config.json`` by default)
                contains a proxy configuration, the corresponding environment
                variables will be set in the container being built.

        Returns:
            A generator for the build output.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
            ``TypeError``
                If neither ``path`` nor ``fileobj`` is specified.
        Nz,Either path or fileobj needs to be provided.z.Can not use custom encoding if gzip is enabledz Invalid container_limits key {0}z,You must specify fileobj with custom_context)zhttp://zhttps://zgit://zgithub.com/zgit@z-You must specify a directory to build in pathz.dockerignoreÚrc                 S   s   | dko| d dkS )NÚ r   ú#© )Úxr   r   ú2/usr/lib/python3/dist-packages/docker/api/build.pyÚ<lambda>›   ó    z%BuildApiMixin.build.<locals>.<lambda>c                 S   s   g | ]}|  ¡ ‘qS r   )Ústrip)Ú.0Úlr   r   r   Ú
<listcomp>œ   s     z'BuildApiMixin.build.<locals>.<listcomp>)ÚexcludeÚ
dockerfileÚgzipr   z/build)ÚtÚremoteÚqÚnocacheÚrmÚforcermÚpullr   Ú	buildargsz1.22Úshmsizez/shmsize was only introduced in API version 1.22z1.23Úlabelsz.labels was only introduced in API version 1.23z1.25Z	cachefromz2cache_from was only introduced in API version 1.25z1.29Útargetz.target was only introduced in API version 1.29Znetworkmodez4network_mode was only introduced in API version 1.25Úsquashz.squash was only introduced in API version 1.25z1.27z3extra_hosts was only introduced in API version 1.27Z
extrahostsz1.32z0platform was only introduced in API version 1.32Úplatformz1.24z1isolation was only introduced in API version 1.24Ú	isolationzContent-Typezapplication/tarzContent-EncodingT)ÚdataÚparamsÚheadersÚstreamÚtimeout)Údecode))Ú	TypeErrorr   ZDockerExceptionÚkeysr   ZCONTAINER_LIMITS_KEYSÚformatr   ZmkbuildcontextÚ
startswithÚosÚpathÚisdirÚjoinÚexistsÚopenÚlistÚfilterÚreadÚ
splitlinesÚprocess_dockerfileZtarÚ_urlÚupdateZ_proxy_configsZget_environmentÚitemsÚ
setdefaultÚjsonÚdumpsZversion_gteZ_versionZInvalidVersionZ
version_ltÚ
isinstanceÚdictZformat_extra_hostsÚ_set_auth_headersÚ_postÚcloseZ_stream_helper)(Úselfr0   ÚtagÚquietZfileobjr   r   r)   Zcustom_contextÚencodingr   r   r   Zcontainer_limitsr*   r   r   r   r    Z
cache_fromr!   Znetwork_moder"   Zextra_hostsr#   r$   Zuse_config_proxyr   Úcontextr'   ÚkeyZdockerignorer   ÚfÚur&   Z
proxy_argsÚkÚvZresponser   r   r   Úbuild   s   iÿ
ÿ

þ
   ÿ
ø


ÿÿÿÿÿÿ
ÿ

ÿ
ÿ

ú	zBuildApiMixin.buildz1.31c                 C   s   |   d¡}|  |  |¡d¡S )a|  
        Delete the builder cache

        Returns:
            (dict): A dictionary containing information about the operation's
                    result. The ``SpaceReclaimed`` key indicates the amount of
                    bytes of disk space reclaimed.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        z/build/pruneT)r:   Z_resultrC   )rE   Zurlr   r   r   Úprune_builds  s    
zBuildApiMixin.prune_buildsc              	   C   s°   t  d¡ | jr| jjr2t  d¡ tj| jd| _| jr¢| j ¡ }tj|krjtj	|krj| 
tj	i ¡|tj< t  d d dd„ | ¡ D ƒ¡¡¡ |r¬t |¡|d< n
t  d	¡ d S )
NzLooking for auth configz2No auth config in memory - loading from filesystem)Úcredstore_envzSending auth config ({0})z, c                 s   s   | ]}t |ƒV  qd S )N)Úrepr)r   rM   r   r   r   Ú	<genexpr>=  s     z2BuildApiMixin._set_auth_headers.<locals>.<genexpr>zX-Registry-ConfigzNo auth config found)ÚlogÚdebugZ_auth_configsZis_emptyr   Zload_configrQ   Zget_all_credentialsZ	INDEX_URLZ
INDEX_NAMEÚgetr-   r2   r,   Zencode_header)rE   r'   Z	auth_datar   r   r   rB   &  s,    

ÿ

ÿÿÿÿ
zBuildApiMixin._set_auth_headers)NNFNFFNFNFFNNFNFNNNNNNNNNT)Ú__name__Ú
__module__Ú__qualname__rO   r   Zminimum_versionrP   rB   r   r   r   r   r      s:                                         ù
  
r   c              
   C   sä   | sdS | }t j | ¡s\t j || ¡}tjr\| tj¡r\d tjt j 	|t
tjƒd … ¡¡}t j |¡d t j |¡d kst j ||¡ d¡rÆt|dƒ&}d t d¡¡| ¡ fW  5 Q R £ S Q R X | |krÜt j ||¡} | d fS )N)NNz{}{}r   z..r   z.dockerfile.{0:x}é    )r/   r0   Úisabsr2   r   ZIS_WINDOWS_PLATFORMr.   ZWINDOWS_LONGPATH_PREFIXr-   ÚnormpathÚlenÚ
splitdriveÚrelpathr4   ÚrandomZgetrandbitsr7   )r   r0   Zabs_dockerfileZdfr   r   r   r9   I  s0    
ÿÿþ ÿþr9   )r>   Zloggingr/   r`   r	   r   r   r   r   Z	getLoggerrW   rT   Úobjectr   r9   r   r   r   r   Ú<module>   s   
  <