
    2.a8                         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j                  e
      Z G d d      Zd	 Zy)
    N   )auth)	constants)errors)utilsc                   Z    e Zd Z	 	 	 	 	 	 	 	 ddZ ej
                  d      d        Zd Zy)BuildApiMixinNc                    dx}}i }|xs i }|xs i }||t        d      |r|	t        j                  d      |j                         D ],  }|t        j
                  vst        j                  d|        |r|st        d      |}n%|t        j                  |      }n|j                  d      r|}nt        j                  j                  |      st        d      t        j                  j                  |d      }d} t        j                  j                  |      rbt        |      5 }!t        t!        d	 |!j#                         j%                         D "cg c]  }"|"j'                          c}"            } ddd       t)        ||      }t        j*                  || ||
      }|rdn|	}	| j-                  d      }#|||||||
|d}$|$j/                  |       |rD| j0                  j3                         }%|%j5                         D ]  \  }&}'|j7                  |&|'        |r&|$j/                  dt9        j:                  |      i       |rIt        j<                  | j>                  d      r|$j/                  d|i       nt        j@                  d      |r\t        j<                  | j>                  d      r'|$j/                  dt9        j:                  |      i       nt        j@                  d      |r\t        j<                  | j>                  d      r'|$j/                  dt9        j:                  |      i       nt        j@                  d      |rIt        j<                  | j>                  d      r|$j/                  d|i       nt        j@                  d      |rIt        j<                  | j>                  d      r|$j/                  d|i       nt        j@                  d      |rIt        j<                  | j>                  d      r|$j/                  d|i       nt        j@                  d      |mt        jB                  | j>                  d      rt        j@                  d       tE        |tF              rt        jH                  |      }|$j/                  d!|i       |:t        jB                  | j>                  d"      rt        j@                  d#      ||$d$<   |:t        jB                  | j>                  d%      rt        j@                  d&      ||$d'<   |d(d)i}|	r|	|d*<   | jK                  |       | jM                  |#||$|d+|,      }(||s|jO                          | jQ                  |(|-      S c c}"w # 1 sw Y    xY w).a  
        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 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.dockerignorec                      | dk7  xr | d   dk7  S )N r   # )xs    2/usr/lib/python3/dist-packages/docker/api/build.py<lambda>z%BuildApiMixin.build.<locals>.<lambda>   s    !r'"9adck     )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.25	cachefromz2cache_from was only introduced in API version 1.25z1.29targetz.target was only introduced in API version 1.29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.27
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   DockerExceptionkeysr   CONTAINER_LIMITS_KEYSr   mkbuildcontext
startswithospathisdirjoinexistsopenlistfilterread
splitlinesstripprocess_dockerfiletar_urlupdate_proxy_configsget_environmentitems
setdefaultjsondumpsversion_gte_versionInvalidVersion
version_lt
isinstancedictformat_extra_hosts_set_auth_headers_postclose_stream_helper))selfr4   tagquietfileobjr   r   r+   custom_contextencodingr   r   r   container_limitsr,   r   r   r   r   
cache_fromr!   network_moder#   extra_hostsr%   r&   use_config_proxyr   contextr)   keydockerignorer   flur(   
proxy_argskvresponses)                                            r   buildzBuildApiMixin.build   s6   R  +1rO	<GOJKKH(((@  $((* 	C)999,,3C59 	  NOOG **73G__ ? @Ft$KLL77<<o>LGww~~l+,' 1"69,-FFH,?,?,ABqB$ G
 ,J=Jiig*4G "&v8HIIh$	
 	&',,<<>J"((* +1$$Q*+MM;

9(=>?  7y'23++E    7xF);<=++D    7{DJJz,BCD++H    7x01++D    7}l;<++J    7x01++D  "v6++I  +t,#66{CMM<56v6++F  "*F: v6++G  #,F;%'89G.6*+w'::  
 ~MMO""8F";;o C s   0-U=U84U=8U==Vz1.31c                 f    | j                  d      }| j                  | j                  |      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@   _resultrP   )rS   urls     r   prune_buildszBuildApiMixin.prune_builds  s+     ii'||DJJsOT22r   c           	         t         j                  d       | j                  r| j                  j                  r:t         j                  d       t	        j
                  | j                        | _        | j                  r| j                  j                         }t        j                  |vrCt        j                  |v r1|j                  t        j                  i       |t        j                  <   t         j                  dj                  dj                  d |j                         D                           |rt	        j                  |      |d<   y y t         j                  d       y )	NzLooking for auth configz2No auth config in memory - loading from filesystem)credstore_envzSending auth config ({})z, c              3   2   K   | ]  }t        |        y w)N)repr).0re   s     r   	<genexpr>z2BuildApiMixin._set_auth_headers.<locals>.<genexpr>=  s     @!d1g@s   zX-Registry-ConfigzNo auth config found)logdebug_auth_configsis_emptyr   load_configrn   get_all_credentials	INDEX_URL
INDEX_NAMEgetformatr6   r/   encode_header)rS   r)   	auth_datas      r   rO   zBuildApiMixin._set_auth_headers&  s   		+, !!T%7%7%@%@IIJK!%!1!1"00"D **>>@I i/OOy0,5MM$//2,N	$..)II*11II@y~~/?@@ /3/A/A0+, 
 II,-r   )NNFNFFNFNFFNNFNFNNNNNNNNNT)__name__
__module____qualname__rh   r   minimum_versionrl   rO   r   r   r   r	   r	      sG    >B/38=?C@DFJFJ#C<J U6"3 #3  .r   r	   c           	      d   | sy| }t         j                  j                  |       st         j                  j                  ||       }t        j
                  rv|j                  t        j                        rWdj                  t        j                  t         j                  j                  |t        t        j                        d              }t         j                  j                  |      d   t         j                  j                  |      d   k7  s/t         j                  j                  ||      j                  d      r>t        |      5 }dt        j                  d      d|j!                         fcd d d        S | |k(  r t         j                  j                  ||      } | d fS # 1 sw Y   2xY w)N)NNz{}{}r   z..z.dockerfile.   r   )r3   r4   isabsr6   r   IS_WINDOWS_PLATFORMr2   WINDOWS_LONGPATH_PREFIXr|   normpathlen
splitdriverelpathr8   randomgetrandbitsr;   )r   r4   abs_dockerfiledfs       r   r>   r>   I  sQ   N77==$dJ7((T__11.3#]]11  "3y'H'H#I#JKN 	4 #rww'9'9.'I!'LLGGOOND1<<TB.! 	Rv11#6q9:		 	 ^# WW__^T:
	 	s   
)F&&F/)rF   loggingr3   r   r   r   r   r   r   	getLoggerr   rs   r	   r>   r   r   r   <module>r      sC      	      g!w. w.t	r   