
    6hY              	         S r SSKJr  SSKrSSKrSSKJr  SSKJrJ	r	J
r
JrJrJrJrJrJrJr  SSKJr  SrS rS	 r0 r\R0                  " \5      r0 r\R4                  " \5      r\" S
SSS9  \" S
S\S9  \" S
SSS9  \" S
SSS9  \" S
SSS9  \" S
SSS9  \" S
SSS9  \" S
SSS9  \" SSSS9  SrSrSr " S S5      r " S S\5      r  " S  S!\5      r! " S" S#\5      r"S$ r#S% r$S& r%S' r&S( r'S) r(S?S* jr)S+ r*S, r+S- r,S. r-S/ r.S0 r/S1 r0S2 r1S3 r2S4r3\" \3/ S55      S6 5       r4S7 r5S8 r6\" S9S5S:S\" S;5      4/S55       S@ SAS< jj5       r7\" S=/ S55      SAS> j5       r8g)Ba6  advertise pre-generated bundles to seed clones

"clonebundles" is a server-side extension used to advertise the existence
of pre-generated, externally hosted bundle files to clients that are
cloning so that cloning can be faster, more reliable, and require less
resources on the server. "pullbundles" is a related feature for sending
pre-generated bundle files to clients as part of pull operations.

Cloning can be a CPU and I/O intensive operation on servers. Traditionally,
the server, in response to a client's request to clone, dynamically generates
a bundle containing the entire repository content and sends it to the client.
There is no caching on the server and the server will have to redundantly
generate the same outgoing bundle in response to each clone request. For
servers with large repositories or with high clone volume, the load from
clones can make scaling the server challenging and costly.

This extension provides server operators the ability to offload
potentially expensive clone load to an external service. Pre-generated
bundles also allow using more CPU intensive compression, reducing the
effective bandwidth requirements.

Here's how clone bundles work:

1. A server operator establishes a mechanism for making bundle files available
   on a hosting service where Mercurial clients can fetch them.
2. A manifest file listing available bundle URLs and some optional metadata
   is added to the Mercurial repository on the server.
3. A client initiates a clone against a clone bundles aware server.
4. The client sees the server is advertising clone bundles and fetches the
   manifest listing available bundles.
5. The client filters and sorts the available bundles based on what it
   supports and prefers.
6. The client downloads and applies an available bundle from the
   server-specified URL.
7. The client reconnects to the original server and performs the equivalent
   of :hg:`pull` to retrieve all repository data not in the bundle. (The
   repository could have been updated between when the bundle was created
   and when the client started the clone.) This may use "pullbundles".

Instead of the server generating full repository bundles for every clone
request, it generates full bundles once and they are subsequently reused to
bootstrap new clones. The server may still transfer data at clone time.
However, this is only data that has been added/changed since the bundle was
created. For large, established repositories, this can reduce server load for
clones to less than 1% of original.

Here's how pullbundles work:

1. A manifest file listing available bundles and describing the revisions
   is added to the Mercurial repository on the server.
2. A new-enough client informs the server that it supports partial pulls
   and initiates a pull.
3. If the server has pull bundles enabled and sees the client advertising
   partial pulls, it checks for a matching pull bundle in the manifest.
   A bundle matches if the format is supported by the client, the client
   has the required revisions already and needs something from the bundle.
4. If there is at least one matching bundle, the server sends it to the client.
5. The client applies the bundle and notices that the server reply was
   incomplete. It initiates another pull.

To work, this extension requires the following of server operators:

* Generating bundle files of repository content (typically periodically,
  such as once per day).
* Clone bundles: A file server that clients have network access to and that
  Python knows how to talk to through its normal URL handling facility
  (typically an HTTP/HTTPS server).
* A process for keeping the bundles manifest in sync with available bundle
  files.

Strictly speaking, using a static file hosting server isn't required: a server
operator could use a dynamic service for retrieving bundle data. However,
static file hosting services are simple and scalable and should be sufficient
for most needs.

Bundle files can be generated with the :hg:`bundle` command. Typically
:hg:`bundle --all` is used to produce a bundle of the entire repository.

The bundlespec option `stream` (see :hg:`help bundlespec`)
can be used to produce a special *streaming clonebundle*, typically using
:hg:`bundle --all --type="none-streamv2"`.
These are bundle files that are extremely efficient
to produce and consume (read: fast). However, they are larger than
traditional bundle formats and require that clients support the exact set
of repository data store formats in use by the repository that created them.
Typically, a newer server can serve data that is compatible with older clients.
However, *streaming clone bundles* don't have this guarantee. **Server
operators need to be aware that newer versions of Mercurial may produce
streaming clone bundles incompatible with older Mercurial versions.**

A server operator is responsible for creating a ``.hg/clonebundles.manifest``
file containing the list of available bundle files suitable for seeding
clones. If this file does not exist, the repository will not advertise the
existence of clone bundles when clients connect. For pull bundles,
``.hg/pullbundles.manifest`` is used.

The manifest file contains a newline (\n) delimited list of entries.

Each line in this file defines an available bundle. Lines have the format:

    <URL> [<key>=<value>[ <key>=<value>]]

That is, a URL followed by an optional, space-delimited list of key=value
pairs describing additional properties of this bundle. Both keys and values
are URI encoded.

For pull bundles, the URL is a path under the ``.hg`` directory of the
repository.

Keys in UPPERCASE are reserved for use by Mercurial and are defined below.
All non-uppercase keys can be used by site installations. An example use
for custom properties is to use the *datacenter* attribute to define which
data center a file is hosted in. Clients could then prefer a server in the
data center closest to them.

The following reserved keys are currently defined:

BUNDLESPEC
   A "bundle specification" string that describes the type of the bundle.

   These are string values that are accepted by the "--type" argument of
   :hg:`bundle`.

   The values are parsed in strict mode, which means they must be of the
   "<compression>-<type>" form. See
   mercurial.exchange.parsebundlespec() for more details.

   :hg:`debugbundle --spec` can be used to print the bundle specification
   string for a bundle file. The output of this command can be used verbatim
   for the value of ``BUNDLESPEC`` (it is already escaped).

   Clients will automatically filter out specifications that are unknown or
   unsupported so they won't attempt to download something that likely won't
   apply.

   The actual value doesn't impact client behavior beyond filtering:
   clients will still sniff the bundle type from the header of downloaded
   files.

   **Use of this key is highly recommended**, as it allows clients to
   easily skip unsupported bundles. If this key is not defined, an old
   client may attempt to apply a bundle that it is incapable of reading.

REQUIRESNI
   Whether Server Name Indication (SNI) is required to connect to the URL.
   SNI allows servers to use multiple certificates on the same IP. It is
   somewhat common in CDNs and other hosting providers. Older Python
   versions do not support SNI. Defining this attribute enables clients
   with older Python versions to filter this entry without experiencing
   an opaque SSL failure at connection time.

   If this is defined, it is important to advertise a non-SNI fallback
   URL or clients running old Python releases may not be able to clone
   with the clonebundles facility.

   Value should be "true".

REQUIREDRAM
   Value specifies expected memory requirements to decode the payload.
   Values can have suffixes for common bytes sizes. e.g. "64MB".

   This key is often used with zstd-compressed bundles using a high
   compression level / window size, which can require 100+ MB of memory
   to decode.

heads
   Used for pull bundles. This contains the ``;`` separated changeset
   hashes of the heads of the bundle content.

bases
   Used for pull bundles. This contains the ``;`` separated changeset
   hashes of the roots of the bundle content. This can be skipped if
   the bundle was created without ``--base``.

Manifests can contain multiple entries. Assuming metadata is defined, clients
will filter entries from the manifest that they don't support. The remaining
entries are optionally sorted by client preferences
(``ui.clonebundleprefers`` config option). The client then attempts
to fetch the bundle at the first URL in the remaining list.

**Errors when downloading a bundle will fail the entire clone operation:
clients do not automatically fall back to a traditional clone.** The reason
for this is that if a server is using clone bundles, it is probably doing so
because the feature is necessary to help it scale. In other words, there
is an assumption that clone load will be offloaded to another service and
that the Mercurial server isn't responsible for serving this clone load.
If that other service experiences issues and clients start mass falling back to
the original Mercurial server, the added clone load could overwhelm the server
due to unexpected load and effectively take it offline. Not having clients
automatically fall back to cloning from the original server mitigates this
scenario.

Because there is no automatic Mercurial server fallback on failure of the
bundle hosting service, it is important for server operators to view the bundle
hosting service as an extension of the Mercurial server in terms of
availability and service level agreements: if the bundle hosting service goes
down, so does the ability for clients to clone. Note: clients will see a
message informing them how to bypass the clone bundles facility when a failure
occurs. So server operators should prepare for some people to follow these
instructions when a failure occurs, thus driving more load to the original
Mercurial server when the bundle hosting service fails.


inline clonebundles
-------------------

It is possible to transmit clonebundles inline in case repositories are
accessed over SSH. This avoids having to setup an external HTTPS server
and results in the same access control as already present for the SSH setup.

Inline clonebundles should be placed into the `.hg/bundle-cache` directory.
A clonebundle at `.hg/bundle-cache/mybundle.bundle` is referred to
in the `clonebundles.manifest` file as `peer-bundle-cache://mybundle.bundle`.


auto-generation of clone bundles
--------------------------------

It is possible to set Mercurial to automatically re-generate clone bundles when
enough new content is available.

Mercurial will take care of the process asynchronously. The defined list of
bundle-type will be generated, uploaded, and advertised. Older bundles will get
decommissioned as newer ones replace them.

Bundles Generation:
...................

The extension can generate multiple variants of the clone bundle. Each
different variant will be defined by the "bundle-spec" they use::

    [clone-bundles]
    auto-generate.formats= zstd-v2, gzip-v2

See `hg help bundlespec` for details about available options.

By default, new bundles are generated when 5% of the repository contents or at
least 1000 revisions are not contained in the cached bundles. This option can
be controlled by the `clone-bundles.trigger.below-bundled-ratio` option
(default 0.95) and the `clone-bundles.trigger.revs` option (default 1000)::

    [clone-bundles]
    trigger.below-bundled-ratio=0.95
    trigger.revs=1000

This logic can be manually triggered using the `admin::clone-bundles-refresh`
command, or automatically on each repository change if
`clone-bundles.auto-generate.on-change` is set to `yes`::

    [clone-bundles]
    auto-generate.on-change=yes
    auto-generate.formats= zstd-v2, gzip-v2

Automatic Inline serving
........................

The simplest way to serve the generated bundle is through the Mercurial
protocol. However it is not the most efficient as request will still be served
by that main server. It is useful in case where authentication is complexe or
when an efficient mirror system is already in use anyway. See the `inline
clonebundles` section above for details about inline clonebundles

To automatically serve generated bundle through inline clonebundle, simply set
the following option::

    auto-generate.serve-inline=yes

Enabling this option disable the managed upload and serving explained below.

Bundles Upload and Serving:
...........................

This is the most efficient way to serve automatically generated clone bundles,
but requires some setup.

The generated bundles need to be made available to users through a "public" URL.
This should be donne through `clone-bundles.upload-command` configuration. The
value of this command should be a shell command. It will have access to the
bundle file path through the `$HGCB_BUNDLE_PATH` variable. And the expected
basename in the "public" URL is accessible at::

  [clone-bundles]
  upload-command=sftp put $HGCB_BUNDLE_PATH       sftp://bundles.host/clone-bundles/$HGCB_BUNDLE_BASENAME

If the file was already uploaded, the command must still succeed.

After upload, the file should be available at an url defined by
`clone-bundles.url-template`.

  [clone-bundles]
  url-template=https://bundles.host/cache/clone-bundles/{basename}

Old bundles cleanup:
....................

When new bundles are generated, the older ones are no longer necessary and can
be removed from storage. This is done through the `clone-bundles.delete-command`
configuration. The command is given the url of the artifact to delete through
the `$HGCB_BUNDLE_URL` environment variable.

  [clone-bundles]
  delete-command=sftp rm sftp://bundles.host/clone-bundles/$HGCB_BUNDLE_BASENAME

If the file was already deleted, the command must still succeed.
    )annotationsN)_)
bundlecachescommandserror
extensions	localrepolocknode	registrarutilwireprotov1server)procutils   ships-with-hg-corec                    U " X5      nUR                   R                  [        R                  5      (       a"  UR	                  S5        UR	                  S5        U$ )Ns   clonebundless   clonebundles_manifest)vfsexistsr   CB_MANIFEST_FILEappend)origrepoprotocapss       4/usr/lib/python3/dist-packages/hgext/clonebundles.pycapabilitiesr   S  sE    D
 xx|4455O$,-K    c                D    [         R                  " [        S[        5        g )N_capabilities)r   wrapfunctionr   r   )uis    r   extsetupr    `  s    -Mr      clone-bundles   auto-generate.on-changeF)default   auto-generate.formats   auto-generate.serve-inline   trigger.below-bundled-ratiogffffff?   trigger.revsi     upload-command   delete-command   url-template   devel   debug.clonebundless   clonebundles-autobundlessA   full-%(bundle_type)s-%(revs)d_revs-%(tip_short)s_tip-%(op_id)s.hgs   clonebundles.auto-genc                  :    \ rS rSrSrSrS rS rS rS r	S r
S	rg
)
BundleBasei  aj  represents the core of properties that matters for us in a bundle

:bundle_type: the bundlespec (see hg help bundlespec)
:revs:        the number of revisions in the repo at bundle creation time
:tip_rev:     the rev-num of the tip revision
:tip_node:    the node id of the tip-most revision in the bundle

:ready:       True if the bundle is ready to be served
Fc                4    Xl         X l        X0l        X@l        g N)bundle_typerevstip_revtip_node)selfr1   r2   r3   r4   s        r   __init__BundleBase.__init__  s    &	 r   c                    [         R                  " U R                  5      nUR                  R                  R                  U5      U R                  :H  $ )zxis this bundle applicable to the current repository

This is useful for detecting bundles made irrelevant by stripping.
)r   binr4   	changelogindexget_revr3   )r5   r   r4   s      r   	valid_forBundleBase.valid_for  s:    
 88DMM*~~##++H5EEr   c                    U R                   U R                  U R                  U R                  4nUR                   UR                  UR                  UR                  4nX#:H  $ r0   )readyr1   r3   r4   )r5   otherleftrights       r   __eq__BundleBase.__eq__  sJ    

D,,dllDMMJe//O}r   c                    X:X  + $ r0    r5   rA   s     r   __neq__BundleBase.__neq__  s      r   c                    X:X  a  gg)Nr   rG   rH   s     r   __cmp__BundleBase.__cmp__  s    =r   )r1   r2   r4   r3   N)__name__
__module____qualname____firstlineno____doc__r@   r6   r=   rD   rI   rM   __static_attributes__rG   r   r   r.   r.     s(     E!F
!r   r.   c                  L   ^  \ rS rSrSrU 4S jr\S 5       rS rSS jr	Sr
U =r$ )	RequestedBundlei  zA bundle that should be generated.

Additional attributes compared to BundleBase
:heads:       list of head revisions (as rev-num)
:op_id:       a "unique" identifier for the operation triggering the change
c                B   > XPl         X`l        [        TU ]  UUUU5        g r0   )	head_revsop_idsuperr6   )r5   r1   r2   r3   r4   rX   rY   	__class__s          r   r6   RequestedBundle.__init__  s&    "
		
r   c                    U R                   U R                  U R                  U R                  U R                  U R                  SS U R
                  S.n[        U-  $ )z4A filename that can be used for the generated bundleN   )s   bundle_types   revss   headss   tip_revs   tip_nodes	   tip_shorts   op_id)r1   r2   rX   r3   r4   rY   BUNDLE_MASK)r5   datas     r   suggested_filename"RequestedBundle.suggested_filename  sR     !,,YYnn--,jj
 T!!r   c           
     v    [         R                  " UR                  UUS/U R                  U R                  SS9  g)z!generate the bundle at `filepath`s   nullT)baserevtypequietN)r   bundler   rX   r1   )r5   r   	file_paths      r   generate_bundleRequestedBundle.generate_bundle  s3    GG!!	
r   c           	         Uc  [         R                  " 5       nUc  [        R                  " 5       n[	        U R
                  U R                  U R                  U R                  UUU5      $ )z1return a GeneratingBundle object from this object)	osgetpidr
   _getlockprefixGeneratingBundler1   r2   r3   r4   )r5   ri   hostnamepids       r   
generatingRequestedBundle.generating  sZ    ;))+C**,HIILLMM
 	
r   )rX   rY   )NN)rO   rP   rQ   rR   rS   r6   propertyra   rj   rs   rT   __classcell__r[   s   @r   rV   rV     s0    
 " "


 
r   rV   c                  X   ^  \ rS rSrSrSrU 4S jr\S 5       rS r	U 4S jr
S rS	rU =r$ )
rp   i  a+  A bundle being generated

extra attributes compared to BundleBase:

:hostname: the hostname of the machine generating the bundle
:pid:      the pid of the process generating the bundle
:filepath: the target filename of the bundle

These attributes exist to help detect stalled generation processes.
Fc                J   > XPl         X`l        Xpl        [        TU ]  XX45        g r0   )rq   rr   filepathrZ   r6   )	r5   r1   r2   r3   r4   rq   rr   rz   r[   s	           r   r6   GeneratingBundle.__init__  s#     ! G>r   c           	     8   UR                  S5      (       d   eUR                  5       u  nnnnnnnn	[        R                  R	                  U5      n[        R                  R	                  U	5      n	[        U5      n[        U5      n[        U5      nU " X4XVXxU	5      $ );create an object by deserializing a line from AUTO_GEN_FILE   PENDING-v1 )
startswithsplitr   urlrequnquoteint)
clsline__r1   r2   r3   r4   rq   rr   rz   s
             r   	from_lineGeneratingBundle.from_line  s     ~.... JJL		
;;&&x0;;&&x04yg,#hw(
 	
r   c           	         SnU R                   U R                  U R                  U R                  [        R
                  R                  U R                  5      U R                  [        R
                  R                  U R                  5      4nX-  $ ):serialize the object to include as a line in AUTO_GEN_FILEs   PENDING-v1 %s %d %d %s %s %d %s)
r1   r2   r3   r4   r   r   quoterq   rr   rz   r5   templr`   s      r   to_lineGeneratingBundle.to_line  si    2IILLMMKKdmm,HHKKdmm,
 |r   c                   > [         TU ]  U5      (       d  gU R                  U R                  U R                  4nUR                  UR                  UR                  4nX#:H  $ NF)rZ   rD   rq   rr   rz   )r5   rA   rB   rC   r[   s       r   rD   GeneratingBundle.__eq__*  sM    w~e$$txx7ENN;}r   c                r    [        U R                  U R                  U R                  U R                  UU5      $ )z)return a GeneratedBundle from this object)GeneratedBundler1   r2   r3   r4   )r5   urlbasenames      r   uploadedGeneratingBundle.uploaded1  s3    IILLMM
 	
r   )rz   rq   rr   )rO   rP   rQ   rR   rS   r@   r6   classmethodr   r   rD   r   rT   rv   rw   s   @r   rp   rp     s<    	 E? 
 
,	
 	
r   rp   c                  X   ^  \ rS rSrSrSrU 4S jr\S 5       rS r	S r
U 4S jrS	rU =r$ )
r   i=  a%  A bundle that is done being generated and can be served

extra attributes compared to BundleBase:

:file_url: the url where the bundle is available.
:basename: the "basename" used to upload (useful for deletion)

These attributes exist to generate a bundle manifest
(.hg/pullbundles.manifest)
Tc                >   > XPl         X`l        [        TU ]  XX45        g r0   )file_urlr   rZ   r6   )r5   r1   r2   r3   r4   r   r   r[   s          r   r6   GeneratedBundle.__init__K  s     ! G>r   c                    UR                  S5      (       d   eUR                  5       u  nnnnnnn[        U5      n[        U5      n[        R                  R                  U5      nU " X4XVXx5      $ )r}      DONE-v1 )r   r   r   r   r   r   )	r   r   r   r1   r2   r3   r4   r   r   s	            r   r   GeneratedBundle.from_lineR  ss     {++++ JJL	
4yg,;;&&x0;gLLr   c                    SnU R                   U R                  U R                  U R                  [        R
                  R                  U R                  5      U R                  4nX-  $ )r   s   DONE-v1 %s %d %d %s %s %s)	r1   r2   r3   r4   r   r   r   r   r   r   s      r   r   GeneratedBundle.to_lined  sS    ,IILLMMKKdmm,MM
 |r   c                    SnU R                   R                  S5      (       a  US-  nXR                   U R                  4-  $ )zAserialize the object to include as a line in pullbundles.manifests   %s BUNDLESPEC=%ss   https    REQUIRESNI=true)r   r   r1   )r5   r   s     r   manifest_lineGeneratedBundle.manifest_lineq  s?    #==##G,,((Et'7'7888r   c                `   > [         TU ]  U5      (       d  gU R                  UR                  :H  $ r   )rZ   rD   r   )r5   rA   r[   s     r   rD   GeneratedBundle.__eq__x  s(    w~e$$}}..r   )r   r   )rO   rP   rQ   rR   rS   r@   r6   r   r   r   r   rD   rT   rv   rw   s   @r   r   r   =  s>    	 E? M M"9/ /r   r   c                (   / nU R                  5        H{  nUR                  S5      (       a&  UR                  [        R	                  U5      5        M?  UR                  S5      (       d  MW  UR                  [
        R	                  U5      5        M}     U$ )z9parse the AUTO_GEN_FILE to return a list of Bundle objectr~   r   )
splitlinesr   r   rp   r   r   )contentbundlesr   s      r   parse_auto_genr   ~  sn    G""$??>**NN+55d;<__[))NN?44T:;	 %
 Nr   c                    / nU  H%  nUR                  SUR                  5       -  5        M'     UR                  5         SR                  U5      $ )z5serialize a list of Bundle as a AUTO_GEN_FILE content   %s
r   )r   r   sortjoinr   linesbs      r   dumps_auto_genr     s?    EWqyy{*+ 	JJL88E?r   c                h    U R                   R                  [        5      nU(       d  / $ [        U5      $ )z=read the AUTO_GEN_FILE for the <repo> a list of Bundle object)r   tryreadAUTO_GEN_FILEr   )r   r`   s     r   read_auto_genr     s)    88M*D	$r   c                    U R                   c   e[        U5      nU R                  [        SSS9 nUR	                  U5        SSS5        g! , (       d  f       g= f)<write a list of Bundle objects into the repo's AUTO_GEN_FILEN   wbTmode
atomictemp)_cb_lock_refr   r   r   write)r   r   r`   fs       r   write_auto_genr     sI    ((('"D	-e	=	 
>	=	=s   A
Ac                    [        U 5      n U R                  S S9  / nU  H%  nUR                  SUR                  5       -  5        M'     SR	                  U5      $ )r   c                    U R                   $ r0   )r1   r   s    r   <lambda>#generate_manifest.<locals>.<lambda>  s    q}}r   )keyr   r   )listr   r   r   r   r   s      r   generate_manifestr     sO    7mGLL,L-EWq001 88E?r   c                ,   U R                  5          [        U 5      n0 nU Ht  nUR                  (       a  UR                  U 5      (       d  M,  UR	                  UR
                  5      nUb  UR                  UR                  :  a  Mf  X2UR
                  '   Mv     [        UR                  5       5      nU R                  [        R                  SSS9 nUR                  U5        SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)z/update the clonebundle manifest with latest urlNr   Tr   )clonebundles_lockr   r@   r=   getr1   r2   r   valuesr   r   r   r   )r   r   	per_typesr   currentmanifestr   s          r   update_ondisk_manifestr     s    				!%	AGGD 1 1mmAMM2G"w||qvv'='(amm$  %Y%5%5%78XX))$  
GGH
 
"	!
 
 
"	!s$   C DC4#D4
D	>D
Dc                   U R                  5          [        U 5      nU(       a  U Vs/ s H  oDU;  d  M
  UPM     nnU Vs/ s H  oDU;  d  M
  UPM     nnUR                  U5        [        X5        / nUR                  U5        UR                  U5        [	        S U 5       5      (       a  [        U 5        SSS5        gs  snf s  snf ! , (       d  f       g= f)zcmodify the repo's AUTO_GEN_FILE

This method also regenerates the clone bundle manifest when neededc              3  8   #    U  H  oR                   v   M     g 7fr0   )r@   ).0r   s     r   	<genexpr>%update_bundle_list.<locals>.<genexpr>  s     ,1wws   N)r   r   extendr   anyr   )r   new_bundlesdel_bundlesr   r   all_changeds         r   update_bundle_listr     s     
			!%")B'Qk-Aq'GB"-B+Q'1Aq+B{#t%;';',,,,"4( 
"	! CB	 
"	!s3   C	CCC	CCA$C
C
Cc                    UR                   (       a   eU R                  5          U R                  R                  UR                  5        [        X/S9  SSS5        g! , (       d  f       g= f)z(remove a GeneratingBundle file and entryr   N)r@   r   r   	tryunlinkrz   r   )r   targets     r   cleanup_tmp_bundler     sG    ||				!6??+4X6 
"	!	!s   0A
A+c                    U R                  5          [        U 5      nX;   a+  UR                  U 5      (       a  [        X5      n[	        X/S9  SSS5        [        X5        g! , (       d  f       N= f)zGupload a generated bundle and advertise it in the clonebundles.manifestr   N)r   r   r=   upload_bundler   r   )r   r   r   results       r   finalize_one_bundler     sZ    				!%!1!1$!7!7"40Ft:	 
"
 t$ 
"	!s   <A!!
A/c                d   / n0 nU HY  nUR                  U 5      (       d  UR                  U5        M,  UR                  UR                  / 5      nUR                  U5        M[     [	        U5       H=  nX6   n[        U5      S:  d  M  UR                  S SS9  UR                  USS 5        M?     U$ )zfinds outdated bundles   c                    U R                   $ r0   )r2   r   s    r   r   'find_outdated_bundles.<locals>.<lambda>  s    166r   T)r   reverseN)r=   r   
setdefaultr1   sortedlenr   r   )r   r   oldsr   r   lr   alls           r   find_outdated_bundlesr     s    DI{{4  KKN  3	  i ns8a<HH)4H8KKAB 	 !
 Kr   c                    U R                  5          [        U 5      n[        X5      nU H  n[        X5        M     [	        XS9  SSS5        g! , (       d  f       g= f)z+finds outdated bundles and get them deletedr   N)r   r   r   delete_bundler   )r   r   r   os       r   collect_garbager     sH    				!%$T3A$" 42 
"	!	!s   4A
Ac                   U R                   R                  SS5      nU R                  R                  UR                  5      nU(       a  U R                   R                  SS5      nU R                  R                  U5      nU R                  R                  U5        U R                  R                  XS5      n[        R                  " UR                  USS9  [        R                  U-   nUR                  Xs5      $ U R                   R                  SS5      nU R                   R                  SS5      nUR                  US	.n	[        R                  " U	S
9n
U R                   R                  XS
9nU(       a  [        R                   " SX4-  5      eUR#                  S5      R%                  UR#                  S5      S9R'                  S5      nUR                  Xs5      $ )zupload the result of a GeneratingBundle and return a GeneratedBundle

The upload is done using the `clone-bundles.upload-command`
r!   r%      server   peer-bundle-cache-rootT)hardlinkr(   r*   )s   HGCB_BUNDLE_PATHs   HGCB_BUNDLE_BASENAMEenviron   command returned status %d: %sutf8)r   )r   configr   r   rz   r   makedirsr   	copyfilesr   CLONEBUNDLESCHEMEr   r   shellenvironsystemr   Abortdecodeformatencode)r   rh   inliner   bundle_cache_rootdest_dirdestr   cmd	variablesenvrets               r   r   r      sq   
 WW^^,.KLFxx  1H GGNN96OP88==!23(#xx}}X0vt<,,x7s--ggnn-/@Aggnn-?!'%-
	 ##I6ggnnSn.++?3*LMMJJvVX__V4V5VF^ 	
 s--r   c                $   UR                   (       d   eUR                  R                  [        R                  5      nU(       a  SnOSnX1R
                  -  nU R                  R                  SS5      (       a  U R                  R                  U5        OU R                  R                  U5        U(       aX  U R                  R                  SS5      nU R                  R                  XAR
                  5      n[        R                  " U5        gU R                  R                  SS5      nUR                  UR
                  S	.n[        R                   " US
9nU R                  R#                  XhS
9n	U	(       a  [$        R&                  " SX4-  5      eg)zdelete a bundle from storages)   clone-bundles: deleting inline bundle %s
s"   clone-bundles: deleting bundle %s
r+   r,   r   r   r!   r)   )s   HGCB_BUNDLE_URLs   HGCB_BASENAMEr   r   N)r@   r   r   r   r  r   r   
configboolr   debugr   r   r   r   r   r   r  r  r   r  )
r   rh   r
  msgr  inline_pathr  r  r  r  s
             r   r   r   "  s%   <<<__''(F(FGF;4??Cww($9::cc GGNN96OPhhmm$5G{#ggnn-/@A &$oo
	 ##I6ggnnSn.++?3*LMM r   c           	        / n/ nU R                  S5      n U R                  R                  SS5      n[        U R                  R	                  SS5      5      nU R                  R                  SS5      n[        U R                  5      nUU R                  R                  5       U R                  R                  5       [        R                  " U R                  R                  5       5      US.n	U Hj  n
[        R                  " X
SS9R                  5       n
[!        XXgX5      (       d  M:  U	R#                  5       nXS	'   [%        S
0 UD6nUR'                  U5        Ml     UR)                  [+        X5      5        X44$ )z|find the list of bundles that need action

returns a list of RequestedBundle objects that need to be generated and
uploaded.s	   immutabler!   r$   r&   r'   )r2   rX   r3   r4   rY   F)strictr1   rG   )filteredr   
configlistfloatr   	configintr   r:   headrevstiprevr   hextipr   parsebundlespecas_specnew_bundle_neededcopyrV   r   r   r   )r   r   rY   create_bundlesdelete_bundlestargetsratioabs_revsr2   generic_datatr`   r   s                r   auto_bundle_needed_actionsr,  B  sE   
 NN==&Dgg  !13KLG')GHE ww  !1?CHt~~D^^,,.>>((*HHT^^//12L ((?GGITEQEE$$&D"#'$'A!!!$  />?))r   c                    [        XR-  XS-
  5      nU H=  nUR                  U 5      (       a  UR                  U:w  a  M+  UR                  U:  d  M=    g   g)zEconsider the current cached content and trigger new bundles if neededFT)maxr=   r1   r2   )r   r   r(  r)  r1   r2   	thresholdr   s           r   r#  r#  b  sM    T\T_6I{{4  AMM[$@66I	 
 r   c           	     \   [         R                  R                  U5      n[        R                  " 5       SU R
                  [        /n[        R                  " 5       nSnSnSn/ nSn	U R                  R                  SS5      (       aT  [        R                  n[        R                  nU R                  R                  XQR                  -  5        UR                  n	O'U R                  R                  XQR                  -  5        [        R                   n
U
" UUUUUU	S9  U H
  nU" 5         M     g)zstart the generation of a single bundle file

the `bundle` argument should be a RequestedBundle object.

This data is passed to the `debugmakeclonebundles` "as is".
s   --cwd.   clone-bundles: starting bundle generation: %s
Nr+   r,   )stdin_bytesstdoutstderrrecord_wait)r   pickledumpsr   hgexecutablepathINTERNAL_CMDr  r   r  r3  r4  r   r1   r   r  runbgcommand)r   rh   r`   r  r  r  r3  r4  waitsr5  bgr   s               r   start_one_bundler>  m  s     ;;V$D  "Hdii
FC



!C
<CFFEKww($9::c.../llc.../			B 	 r   s"   debug::internal-make-clone-bundlesr   c                   [         R                  R                  [        R                  5      n[        R                  R                  5         [        U5        UR                  nUR                  R                  S5      nUR                  R                  SU5      nUR                  U5      n[        X/S9  UR                  X5        UR                  5         [        X5        g)z/Internal command to auto-generate debug bundles   tmp-bundlesr   N)r   r6  loadr   stdincloser   ra   r   r  r   rs   r   rj   
invalidater   )r   r   requested_bundlefnamefpathrh   s         r   debugmakeclonebundlesrH    s     {{''7NND//EHHn-EHHMM.%0E((/Ft2$$T1OO%r   c                @   ^ [         R                  " U 5      mU4S jnU$ )Nc                   > T" 5       nUc   e[        U5      n[        XS[        U 5      -  5      u  p4U H  n[        X5        M     g )Ns   %d_txn)r   r,  idr>  )trr   r   newr   r`   reporefs         r   
autobundle%make_auto_bundler.<locals>.autobundle  sL    y%,TI2<NODT( r   )weakrefref)source_reporO  rN  s     @r   make_auto_bundlerrT    s    kk+&G r   c                   ^ TR                  5       (       d  g " U4S jSTR                  5      nTR                  R                  [        5        TR                  R                  [
        R                  5        UTl        g)zinstall the two pieces needed for automatic clonebundle generation

- add a "post-close" hook that fires bundling when needed
- introduce a clone-bundle lock to let multiple processes meddle with the
  state files.
Nc                  T   >^  \ rS rSrU U4S jr\R                  SS j5       rSrU =r	$ )"reposetup.<locals>.autobundlesrepoi  c                >  > [         TU ]  " U0 UD6nTR                  R                  SS5      nTR                  R	                  SS5      nU(       aL  U(       d&  TR                  R                  [        S5      5        U$ UR                  [        [        U 5      5        U$ )Nr!   r"   r$   sS   clone-bundle auto-generate enabled, but no formats specified: disabling generation
)
rZ   transactionr   r  r  warnr   addpostcloseCAT_POSTCLOSErT  )r5   argskwargsrL  enabledr'  r[   r   s         r   rY  .reposetup.<locals>.autobundlesrepo.transaction  s    $d5f5Bgg(( *G gg(( ":G GGLLP I OOM3DT3JKIr   c           
     4   [        U S5      (       d  SU l        U R                  U R                  5      nUb  UR                  5         U$ U R	                  U R
                  SUSS[        S5      U R                  -  S9n[        R                  " U5      U l        U$ )z1Lock the repository file related to clone bundlesr   Ns   clonebundleslocks   repository %s)r   locknamewait	releasefn	acquirefndesc)
hasattrr   _currentlockr
   _lockr   r   origrootrQ  rR  )r5   rc  r   s      r   r   4reposetup.<locals>.autobundlesrepo.clonebundles_lock  s     400$(!!!$"3"34A}

HH,'(4==8  A !(ADHr   )r   )T)
rO   rP   rQ   rR   rY  r	   unfilteredmethodr   rT   rv   )r[   r   s   @r   autobundlesreporW    s"    	* 
	#	#	 
$	r   rm  )localr[   _wlockfreeprefixaddr   r   r   )r   r   rm  s    ` r   	reposetuprq    s[     ::<<)$.. )V 	m,l;;<$DNr   s   admin::clone-bundles-refreshs
   backgrounds)   start bundle generation in the backgroundc                   UR                   R                  SS5      nUR                   R                  SS5      n[        U5      nUc  S[        R
                  " 5       -  n[        XU5      u  pgU(       a  U(       d  U H  n[        X5        M     [        XS9  U(       a  UR                  R                  S5      n	U(       a  U H  n
[        X5        M     gU H  n
U(       a)  SnUR                   R                  XR                  -  5        U
R                  nUR                  R                  SU5      n	U
R!                  U	5      n[        X/S	9  U
R#                  X5        [%        X5      n[        X/S	9  ['        U5        [)        X5        M     g)
zgenerate clone bundles according to the configuration

This runs the logic for automatic generation, removing outdated bundles and
generating new ones if necessary. See :hg:`help -e clone-bundles` for
details about how to configure this feature.
r+   r,   s"   clonebundles.override-operation-idNs   %d_acbrr   r@  r1  r   )r   r  r   r   rm   rn   r,  r   r   r   r  r>  r   r1   ra   r   rs   rj   r   r   r   )r   r   
backgroundr  rY   r   createdeleter   rG  rE  r  rF  generating_bundler   s                  r   cmd_admin_clone_bundles_refreshrw    sH   . GGx)>?EGGNN8%JKED!G}RYY[(/uENF 6 A$" 44!!.1 &T4 !' !'Hc$@$@@A$77EHHMM.%8E 0 ; ;E Bt1DE,,T9"4;Ft:"4(t7 !'r   s   admin::clone-bundles-clearc                    [        U5      nU Vs/ s H  o3R                  (       d  M  UPM     nnU H  n[        X5        M     [        XS9  gs  snf )zremove existing clone bundle caches

See `hg help admin::clone-bundles-refresh` for details on how to regenerate
them.

This command will only affect bundles currently available, it will not
affect bundles being asynchronously generated.
r   N)r   r@   r   r   )r   r   r   r   ru  r   s         r   cmd_admin_clone_bundles_clearry  1  sE     D!G ,AGGaF,d t0 -s
   AA)rG   rG   )F)r   zlocalrepo.localrepository)9rS   
__future__r   rm   rQ  mercurial.i18nr   	mercurialr   r   r   r   r	   r
   r   r   r   r   mercurial.utilsr   
testedwithr   r    configtable
configitemcmdtablecommandr   r\  r_   r   r.   rV   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r,  r#  r>  r:  rH  rT  rq  rw  ry  rG   r   r   <module>r     s#  qf	 # 	     #

N !!+.



H
% 
7 G 
5t D 
:E J 
;T J 
_d ; 
. = 
. = 
_d ; 
8*E : , I  )& &R:
j :
zK
z K
\>/j >/B ()$7%$3.DN@*@ F 5 	r3&  &&7%t 	# :;		
  28
#2828j 		&C01 11r   