
    bi>                     z    d dl Z d dlZd dlZd dlZddlmZmZmZmZ  ej                  e
      Z G d d      Zd Zy)    N   )auth	constantserrorsutilsc                   \    e Zd Z	 	 	 	 	 	 	 	 ddZ ej
                  d      dd       Zd Zy)BuildApiMixinNc                 v   dx}}i }|xs i }|xs i }||t        d      |r|	t        j                  d      |.t        j                  |      st        j                  d| d      |j                         D ]-  }|t        j                  vst        j                  d| 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}$|$j1                  |       |rD| j2                  j5                         }%|%j7                         D ]  \  }&}'|j9                  |&|'        |r&|$j1                  dt;        j<                  |      i       |rIt        j>                  | j@                  d      r|$j1                  d|i       nt        jB                  d      |r\t        j>                  | j@                  d      r'|$j1                  dt;        j<                  |      i       nt        jB                  d      |r\t        j>                  | j@                  d      r'|$j1                  dt;        j<                  |      i       nt        jB                  d      |rIt        j>                  | j@                  d      r|$j1                  d|i       nt        jB                  d      |rIt        j>                  | j@                  d      r|$j1                  d|i       nt        jB                  d      |rIt        j>                  | j@                  d      r|$j1                  d|i       nt        jB                  d      |mt        jD                  | j@                  d       rt        jB                  d!      tG        |tH              rt        jJ                  |      }|$j1                  d"|i       |:t        jD                  | j@                  d#      rt        jB                  d$      ||$d%<   |:t        jD                  | j@                  d&      rt        jB                  d'      ||$d(<   |d)d*i}|	r|	|d+<   | jM                  |       | jO                  |#||$|d,|-      }(||s|jQ                          | jS                  |(|.      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
            gzip (bool): If set to ``True``, gzip compression/encoding is used
            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 tag 'z': invalid reference formatz,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    K/home/cdr/jupyterlab/.venv/lib/python3.12/site-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   DockerExceptionr   	match_tagkeysr   CONTAINER_LIMITS_KEYS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))selfr5   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lineur(   
proxy_argskvresponses)                                            r   buildzBuildApiMixin.build   sl   T  +1rO	<GOJKKH(((@  ???3',,#C5(CD  $((* 	C)999,,#C5(CD 	
  NOOG **73G__ ? @Ft$KLL77<<o>LGww~~l+,' 1"6923&&(2E2E2GH$H$ 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 I s   !-V.V)%V.)V..V8z1.31c                 8   | j                  d      }|||fdk7  r5t        j                  | j                  d      rt	        j
                  d      i }|t        j                  |      |d<   |||d<   |||d<   | j                  | j                  ||      d	      S )
a/  
        Delete the builder cache

        Args:
            filters (dict): Filters to process on the prune list.
                Needs Docker API v1.39+
                Available filters:
                - dangling (bool):  When set to true (or 1), prune only
                unused and untagged images.
                - until (str): Can be Unix timestamps, date formatted
                timestamps, or Go duration strings (e.g. 10m, 1h30m) computed
                relative to the daemon's local time.
            keep_storage (int): Amount of disk space in bytes to keep for cache.
                Needs Docker API v1.39+
            all (bool): Remove all types of build cache.
                Needs Docker API v1.39+

        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/pruneNNNz1.39zS`filters`, `keep_storage`, and `all` args are only available for API version > 1.38filterszkeep-storageall)r(   T)	rA   r   rL   rJ   r   rK   convert_filters_resultrQ   )rT   rl   keep_storagerm   urlr(   s         r   prune_buildszBuildApiMixin.prune_builds  s    8 ii'\3'+==$$T]]F;'')   % 5 5g >F9#%1F>"?F5M||DJJs6J:DAAr   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dj                  d |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 (%s)z, c              3   2   K   | ]  }t        |        y w)N)repr).0rf   s     r   	<genexpr>z2BuildApiMixin._set_auth_headers.<locals>.<genexpr>X  s     5a$q'5s   zX-Registry-ConfigzNo auth config found)logdebug_auth_configsis_emptyr   load_configrt   get_all_credentials	INDEX_URL
INDEX_NAMEgetr7   encode_header)rT   r)   	auth_datas      r   rP   zBuildApiMixin._set_auth_headersA  s    		+, !!T%7%7%@%@IIJK!%!1!1"00"D **>>@I i/OOy0,5MM$//2,N	$..)II*		5955
 /3/A/A0+, 
 II,-r   )NNFNFFNFNFFNNFNFNNNNNNNNNTrk   )__name__
__module____qualname__ri   r   minimum_versionrr   rP   r   r   r   r	   r	      sJ    >B/38=?C@DFJFJ#G<R U6")B #)BV.r   r	   c                 P   | sy| }t         j                  j                  |       st         j                  j                  ||       }t        j
                  rl|j                  t        j                        rMt         j                  j                  |t        t        j                        d        }t        j                   | }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)NNr   z..z.dockerfile.   r   )r4   r5   isabsr7   r   IS_WINDOWS_PLATFORMr3   WINDOWS_LONGPATH_PREFIXnormpathlen
splitdriverelpathr9   randomgetrandbitsr<   )r   r5   abs_dockerfiler   dfs        r   r?   r?   c  sP   N77==$dJ7((T__11.3ww''s9#D#DEFGIH ) A AB8*MN
4 #rww'9'9.'I!'LLGGOOND1<<TB.! 	Rv11#6q9:		 	 ^# WW__^T:
	 	s    )FF%)rG   loggingr4   r   r   r   r   r   r   	getLoggerr   ry   r	   r?   r   r   r   <module>r      s;      	  - -g!U. U.p
r   