o
    0iϨ                  '   @   s  d Z ddlZ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dlmZ ddlmZmZmZmZmZmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZ ddlm Z  erhddl!m"Z" e#e$Z%dZ&dZ'de(de)e(e(f fddZ*eG dd dZ+eG dd dZ,eG dd dZ-eddG dd dZ.eG dd dZ/eG dd  d Z0eG d!d" d"Z1de(de)e(e(f fd#d$Z2de(de3fd%d&Z4eG d'd( d(Z5eG d)d* d*Z6G d+d, d,Z7d-e(de8e)e(e(f  fd.d/Z9d0e(dee)e(e:e;f  fd1d2Z<d3d4d5e(d6e(dee)e(e:e;ef  fd7d8Z=d9e;de(fd:d;Z>dd<de(d=ed> d?e:d@e;dAe:dBe;dCe(dDe(dEe3dFe3dGe3dHee de5fdIdJZ?	K	K	K	K	K		dkdLe(dMe(d3d4dNe3dFe3dEe3dOe3dGe3dPee7 dQee de6fdRdSZ@dTe6ddfdUdVZAdTe6dWe(ddfdXdYZBdWe(de6fdZd[ZCdldTe6d3d4d\e3dQee ddf
d]d^ZDdTe6ddfd_d`ZE		dmdKdKdKdKdKddddddKdKdKddadLee( dMee( d3d4dNe3dFe3dEe3dOe3dGe3dbee8e(  dcee8e(  ddee( dTee( deee( dfe3d\e3dge3dhee3e(df de6f$didjZFdS )nzzShared logic for bucket operations.

This module contains the core buckets logic used by both the CLI and the Python API.
    N)	dataclassfield)datetimetimezone)Path)TYPE_CHECKINGAnyIteratorLiteralOptionalUnion   )	constantslogging)BucketNotFoundError)XetFileDatadisable_progress_barsenable_progress_barsparse_datetime)
StatusLineHfApihf://buckets/  pathreturnc                 C   sn   |  dd}t|dk s|d r|d std|  d|d  d|d  }t|dkr1|d nd}||fS )zSplit 'namespace/name(/optional/prefix)' into ('namespace/name', 'prefix').

    Returns (bucket_id, prefix) where prefix may be empty string.
    Raises ValueError if path doesn't contain at least namespace/name.
    /   r   r   zInvalid bucket path: 'z)'. Expected format: namespace/bucket_name )splitlen
ValueError)r   parts	bucket_idprefix r%   R/home/kim/smarthome/.venv/lib/python3.10/site-packages/huggingface_hub/_buckets.py_split_bucket_id_and_prefix5   s   r'   c                   @   sB   e Zd ZU dZeed< eed< eed< eed< eed< dd Z	d	S )

BucketInfoa  
    Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].

    Attributes:
        id (`str`):
            ID of the bucket.
        private (`bool`):
            Is the bucket private.
        created_at (`datetime`):
            Date of creation of the bucket on the Hub.
        size (`int`):
            Size of the bucket in bytes.
        total_files (`int`):
            Total number of files in the bucket.
    idprivate
created_atsizetotal_filesc                 K   sV   | d| _| d| _t| d| _| d| _| d| _| jjdi | d S )Nr)   r*   Z	createdAtr,   Z
totalFilesr%   )	popr)   r*   r   r+   r,   r-   __dict__update)selfkwargsr%   r%   r&   __init__[   s   zBucketInfo.__init__N)
__name__
__module____qualname____doc__str__annotations__boolr   intr3   r%   r%   r%   r&   r(   C   s   
 r(   c                   @   s   e Zd ZU eeeef ed< eed< eddZ	e
e ed< eddZe
e ed< eddZeed	< eddZe
e ed
< dddZdS )_BucketAddFilesourcedestinationN)defaultxet_hashr,   Finitmtimecontent_typer   c                 C   sx   d | _ t| jttfrt| jd | _ | j d u r"t| jd | _ tt| jt	s2t
j| jd nt d | _d S )Nr   r   )rD   
isinstancer=   r8   r   	mimetypes
guess_typer>   r;   bytesosr   getmtimetimerC   )r1   r%   r%   r&   __post_init__n   s   
(
z_BucketAddFile.__post_init__r   N)r4   r5   r6   r   r8   r   rH   r9   r   r@   r   r,   r;   rC   rD   rL   r%   r%   r%   r&   r<   d   s   
 r<   c                   @   s   e Zd ZU eed< dS )_BucketDeleteFiler   N)r4   r5   r6   r8   r9   r%   r%   r%   r&   rN   z   s   
 rN   T)frozenc                   @   s"   e Zd ZU dZeed< eed< dS )BucketFileMetadataa%  Data structure containing information about a file in a bucket.

    Returned by [`get_bucket_file_metadata`].

    Args:
        size (`int`):
            Size of the file in bytes.
        xet_file_data (`XetFileData`):
            Xet information for the file (hash and refresh route).
    r,   Zxet_file_dataN)r4   r5   r6   r7   r;   r9   r   r%   r%   r%   r&   rP      s   
 rP   c                   @   sf   e Zd ZU dZeed< dZeed< eddZeed< eddZ	eed< eddZ
eed	< dddZdS )	BucketUrla  Describes a bucket URL on the Hub.

    `BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties:
    - endpoint (`str`)
    - namespace (`str`)
    - bucket_id (`str`)
    - url (`str`)
    - handle (`str`)

    Args:
        url (`str`):
            String value of the bucket url.
        endpoint (`str`, *optional*):
            Endpoint of the Hub. Defaults to <https://huggingface.co>.
    urlr   endpointFrA   	namespacer#   handler   Nc                 C   s   | j ptj| _ | j| j dd}|dr|tdd  }t|\}}|r/t	d| j |
dd | _|| _d| j | _d S )Nr   r   zbuckets/zUnable to parse bucket URL: r   r   )rS   r   ZENDPOINTrR   replacestrip
startswithr    r'   r!   r   rT   r#   rU   )r1   Zurl_pathr#   r$   r%   r%   r&   rL      s   
zBucketUrl.__post_init__rM   )r4   r5   r6   r7   r8   r9   rS   r   rT   r#   rU   rL   r%   r%   r%   r&   rQ      s   
 rQ   c                   @   sV   e Zd ZU dZed ed< eed< eed< eed< ee	 ed< ee	 ed< d	d
 Z
dS )
BucketFilez
    Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].

    Similar to [`RepoFile`] but for files in buckets.
    filetyper   r,   r@   rC   uploaded_atc                 K   sv   | d| _| d| _| d| _| d| _| dd }|r$t|nd | _| dd }|r6t|| _d S d | _d S )Nr[   r   r,   ZxetHashrC   
uploadedAt)r.   r[   r   r,   r@   r   rC   r\   )r1   r2   rC   r\   r%   r%   r&   r3      s   zBucketFile.__init__N)r4   r5   r6   r7   r
   r9   r8   r;   r   r   r3   r%   r%   r%   r&   rY      s   
 rY   c                   @   s:   e Zd ZU dZed ed< eed< ee ed< dd Z	dS )	BucketFolderz
    Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].

    Similar to [`RepoFolder`] but for directories in buckets.
    	directoryr[   r   r\   c                 K   s`   | d| _| d| _| dd p| dd }|r+t|tr$|| _d S t|| _d S d | _d S )Nr[   r   r]   r\   )r.   r[   r   rE   r   r   r\   )r1   r2   r\   r%   r%   r&   r3      s   zBucketFolder.__init__N)
r4   r5   r6   r7   r
   r9   r8   r   r   r3   r%   r%   r%   r&   r^      s   
 r^   c                 C   s,   |  tstd|  dt t| tS )zParse a bucket path like hf://buckets/namespace/bucket_name/prefix into (bucket_id, prefix).

    Returns:
        tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string.
    zInvalid bucket path: z. Must start with )rX   BUCKET_PREFIXr!   r'   removeprefixr   r%   r%   r&   _parse_bucket_path   s   
rc   c                 C   s
   |  tS )z!Check if a path is a bucket path.)rX   r`   rb   r%   r%   r&   _is_bucket_path   s   
rd   c                   @   sr   e Zd ZU dZed ed< eed< dZee	 ed< dZ
eed< dZee ed	< dZee ed
< dZee ed< dS )SyncOperationz,Represents a sync operation to be performed.)uploaddownloaddeleteskipactionr   Nr,   r   reasonlocal_mtimeremote_mtimebucket_file)r4   r5   r6   r7   r
   r9   r8   r,   r   r;   rk   rl   rm   rn   rY   r%   r%   r%   r&   re     s   
 re   c                   @   s^   e Zd ZU dZeed< eed< eed< eedZee	 ed< de
eeeef f fdd	Zd
S )SyncPlanz Represents a complete sync plan.r=   dest	timestamp)default_factory
operationsr   c                 C   st   t dd | jD }t dd | jD }t dd | jD }t dd | jD }t dd | jD }|||||dS )Nc                 s       | ]
}|j d krdV  qdS )rf   r   Nrj   .0opr%   r%   r&   	<genexpr>      z#SyncPlan.summary.<locals>.<genexpr>c                 s   rt   )rg   r   Nru   rv   r%   r%   r&   ry     rz   c                 s   rt   )rh   r   Nru   rv   r%   r%   r&   ry     rz   c                 s   rt   )ri   r   Nru   rv   r%   r%   r&   ry     rz   c                 s   s$    | ]}|j d v r|jpdV  qdS )rf   rg   r   N)rj   r,   rv   r%   r%   r&   ry     s   " )uploads	downloadsdeletesskips
total_size)sumrs   )r1   r|   r}   r~   r   r   r%   r%   r&   summary  s   zSyncPlan.summaryN)r4   r5   r6   r7   r8   r9   r   listrs   re   dictr   r;   r   r%   r%   r%   r&   ro     s   
 "ro   c                   @   s`   e Zd ZdZ			ddeee  deee  deeeeef   fddZded	e	fd
dZ
dS )FilterMatcherz4Matches file paths against include/exclude patterns.Ninclude_patternsexclude_patternsfilter_rulesc                 C   s"   |pg | _ |pg | _|pg | _dS )a  Initialize the filter matcher.

        Args:
            include_patterns: Patterns to include (from --include)
            exclude_patterns: Patterns to exclude (from --exclude)
            filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples
        Nr   r   r   )r1   r   r   r   r%   r%   r&   r3   1  s   

zFilterMatcher.__init__r   r   c                 C   sr   | j D ]\}}t||r|dk  S q| jD ]}t||r" dS q| jD ]}t||r1 dS q&| jr7dS dS )zCheck if a path should be included based on the filter rules.

        Filtering rules:
        - Filters are evaluated in order, first matching rule decides
        - If no rules match, include by default (unless include patterns are specified)
        +FT)r   fnmatchr   r   )r1   r   signpatternr%   r%   r&   matchesB  s   

zFilterMatcher.matches)NNN)r4   r5   r6   r7   r   r   r8   tupler3   r:   r   r%   r%   r%   r&   r   .  s    


r   filter_filec                 C   s   g }t | G}|D ];}| }|r|drq	|dr*|d|dd  f q	|dr=|d|dd  f q	|d|f q	W d   |S 1 sPw   Y  |S )zParse a filter file and return a list of (sign, pattern) tuples.

    Filter file format:
    - Lines starting with "+" are include patterns
    - Lines starting with "-" are exclude patterns
    - Empty lines and lines starting with "#" are ignored
    #r   r   N-)openrW   rX   append)r   rulesfliner%   r%   r&   _parse_filter_file_  s    



r   
local_pathc           	      c   s    t j| } t j| std|  t | D ]3\}}}|D ]+}t j||}t j|| }|t j	d}t j
|}t j|d }|||fV  q qdS )zsList all files in a local directory.

    Yields:
        tuple: (relative_path, size, mtime_ms) for each file
    z Local path must be a directory: r   r   N)rI   r   abspathisdirr!   walkjoinrelpathrV   sepgetsizerJ   )	r   root_filesfilename	full_pathrel_pathr,   mtime_msr%   r%   r&   _list_local_files|  s   r   apir   r#   r$   c                 c   s    | j ||pdddD ]I}t|trq|j}|r>||d r*|t|d d }n||kr=d|v r:|ddd n|}nq|}|jrJ|j d nd}||j	||fV  qdS )	zList all files in a bucket with a given prefix.

    Yields:
        tuple: (relative_path, size, mtime_ms, bucket_file) for each file.
            bucket_file is the BucketFile object from list_bucket_tree.
    NT)r$   	recursiver   r   r   r   )
Zlist_bucket_treerE   r^   r   rX   r    rsplitrC   rq   r,   )r   r#   r$   itemr   r   r   r%   r%   r&   _list_remote_files  s   
r   r   c                 C   s   t j| d tjd S )z3Convert mtime in milliseconds to ISO format string.r   )tz)r   fromtimestampr   utc	isoformat)r   r%   r%   r&   _mtime_to_iso  s   r   )rn   rj   r{   source_sizesource_mtime	dest_size
dest_mtimesource_newer_labeldest_newer_labelignore_sizesignore_timesignore_existingrn   c                 C   s  t |dkr|n|}t |dkr|n|}| |||d}|
r'tdddd|S ||k}|| tk}|rV|r@td|||d|S || tk}|rJ|nd}tdd|d|S |	ro|retd|d|d|S tddd	d|S |ss|r|rwdn|}td|||d|S tddd
d|S )a  Compare source and dest files and return the appropriate sync operation.

    This is a unified helper for both upload and download directions.

    Args:
        path: Relative file path
        action: "upload" or "download"
        source_size: Size of the source file (bytes)
        source_mtime: Mtime of the source file (milliseconds)
        dest_size: Size of the destination file (bytes)
        dest_mtime: Mtime of the destination file (milliseconds)
        source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer")
        dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer")
        ignore_sizes: Only compare mtime
        ignore_times: Only compare size
        ignore_existing: Skip files that exist on receiver
        bucket_file: BucketFile object (for downloads only)

    Returns:
        SyncOperation describing the action to take
    rf   )r   r,   rl   rm   ri   z&exists on receiver (--ignore-existing))rj   rk   )rj   rk   rn   z
same mtimezsize differsz	same sizeZ	identicalNr%   )r   re   _SYNC_TIME_WINDOW_MS)r   rj   r   r   r   r   r   r   r   r   r   rn   Zlocal_mtime_isoZremote_mtime_isoZbase_kwargsZsize_differsZsource_newerZ
dest_newerskip_reasonrk   r%   r%   r&   _compare_files_for_sync  s2   $r   Fr=   rp   rh   existingfilter_matcherstatusc
           "      C   s  |pt  }t|  ot|}
t| ot| }|
s|stdt| |ttj d}d}|
rt	j
| }t|\}}t	j
|sJtd| i }t|D ]\}}}||r`||f||< |	rm|	dt| d qP|	r{|	dt| d i }|	rz||j}W n	 ty   Y nw z4t|||D ]+\}}}}||r||f||< |	r|durd| nd}|	d	t| | d qW n ty   td
| d Y nw |	r|	d	t| d t| t| B }|	r|	dt| d t|D ]}||}||}|rA|sA|r,|jt d||d dt!|d d q|jt d||d dt!|d d q|rd|rd|\}}|\}}|jt"|d||||dd|||d q|s|r|r|jt d||d dt!|d d q|S t| \}}t	j
|}i }i } |	rz||j}W n
 ty   Y nw t|||D ]3\}}}}!||r||f||< |!| |< |	r|durd| nd}|	d	t| | d q|	r|	d	t| d i }t	j
|r t|D ] \}}}||r||f||< |	r|	dt| d q|	r.|	dt| d t| t| B }|	rH|	dt| d t|D ]}||}||}|r|s|rv|jt d||d dt!|d d qL|jt d||d dt!|d | |d qL|r|r|\}}|\}}|jt"|d||||dd|||| |d qL|s|r|r|jt d||d dt!|d d qL|S )zCompute the sync plan by comparing source and destination.

    Returns:
        SyncPlan with all operations to be performed
    z[One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.r=   rp   rq   NzSource must be a directory: zScanning local directory (z files)r   r   zScanning remote bucket (zBucket 'z' not found, treating as empty.zComparing files (z paths)ri   r   znew file (--existing)r   )rj   r   r,   rk   rl   rf   znew filezlocal newerzremote newer)r   rj   r   r   r   r   r   r   r   r   r   rh   znot in source (--delete))rj   r   r,   rk   rm   rg   )rj   r   r,   rk   rm   rn   )r   rj   r   r   r   r   r   r   r   r   r   rn   )#r   rd   r!   ro   r   nowr   r   r   rI   r   r   rc   r   r   r   r0   r    doneZbucket_infor-   	Exceptionr   r   loggerdebugsetkeyssortedgetrs   r   re   r   r   )"r=   rp   r   rh   r   r   r   r   r   r   	is_uploadis_downloadplanZremote_totalr   r#   r$   Zlocal_filesr   r,   r   Zremote_filesr   	total_strZ	all_pathsr   Z
local_infoZremote_infoZ
local_sizerl   Zremote_sizerm   Zbucket_file_maprn   r%   r%   r&   _compute_sync_plan   s|  







	
k







r   r   c                 C   s   d| j | j| j|  d}|t|d  | jD ]4}d|j|j	|j
d}|jdur0|j|d< |jdur:|j|d< |jdurD|j|d	< |t|d  qdS )
z1Write a sync plan as JSONL to a file-like object.header)r[   r=   rp   rq   r   
	operation)r[   rj   r   rk   Nr,   rl   rm   )r=   rp   rq   r   writejsondumpsrs   rj   r   rk   r,   rl   rm   )r   r   r   rx   op_dictr%   r%   r&   _write_plan  s*   






r   	plan_filec                 C   s:   t |d}t| | W d   dS 1 sw   Y  dS )z!Save a sync plan to a JSONL file.wN)r   r   )r   r   r   r%   r%   r&   
_save_plan  s   "r   c                 C   s   t | }| }W d   n1 sw   Y  |s!td|  t|d }|ddkr3tdt|d |d |d	 d
}|dd D ].}t|}|ddkrUqF|jt	|d |d |d|dd|d|dd qF|S )z#Load a sync plan from a JSONL file.NzEmpty plan file: r   r[   r   z0Invalid plan file: expected header as first liner=   rp   rq   r   r   r   rj   r   r,   rk   r   rl   rm   )rj   r   r,   rk   rl   rm   )
r   	readlinesr!   r   loadsr   ro   rs   r   re   )r   r   linesr   r   r   r   r%   r%   r&   
_load_plan  s8   



r   verbosec              	   C   s  t | j o
t | j}t | jot | j }|rtj| j}t| j\}}|d}g }	g }
| jD ]n}|j	dkretj
||j}|rK| d|j n|j}|r]td|j d|j d |	||f q2|j	dkr|rt| d|j n|j}|rtd|j d|j d |
| q2|j	dkr|rtd	|j d|j d q2|	s|
r|rg }|	r|d
t|	 d |
r|dt|
 d |d
|  |j||	pd|
pdd dS dS |rt| j\}}|d}tj| j}tj|dd g }g }| jD ]}|j	dkrStj
||j}tjtj|dd |r,td|j d|j d |jdur<||j|f q|rG| d|j n|j}|||f q|j	dkrxtj
||j}|rqtd|j d|j d || q|j	dkr|rtd	|j d|j d qt|dkr|r|dt| d ||| |r|r|dt| d |D ]9}tj|rt| tj|}||krzt| tj|}W n
 ty   Y nw ||ksאqdS dS )zExecute a sync plan.r   rf   z  Uploading: z ()rh   z  Deleting: ri   z  Skipping: z
uploading z filesz	deleting z, N)addrh   T)exist_okrg   z  Downloading: r   zDownloading z	Deleting z local files)rd   r=   rp   rI   r   r   rc   rstriprs   rj   r   printrk   r   r    r   
capitalizeZbatch_bucket_filesmakedirsdirnamern   Zdownload_bucket_filesexistsremovermdirOSError)r   r   r   r   r   r   r   r#   r$   Z	add_filesZdelete_pathsrx   
local_fileZremote_pathr"   Zdownload_filesZdelete_files	file_pathparentr%   r%   r&   _execute_plan9  s   










*r   c                 C   sl   |   }td| j d| j  td|d   td|d   td|d   td	|d
   dS )z!Print a summary of the sync plan.zSync plan: z -> z  Uploads: r|   z  Downloads: r}   z  Deletes: r~   z	  Skips: r   N)r   r   r=   rp   )r   r   r%   r%   r&   _print_plan_summary  s   r   )rh   r   r   r   r   includeexcludefilter_fromr   applydry_runr   quiettokenr   r   r   r   r   r   r   c                C   s  |durddl m} ||d}|r| s|rtd|dur!td|r'td|r-td|r3td	|r9td
|	r?td|
rEtd|rKtd|rQtd|rWtdt|}t| d}|skt| td |rpt  zt||||d W |rt	  n|rt	  w w |std |S | r|stdt
| }t
|}|r|rtd|s|std|r|rtd|r|rtd|r|rtd|rtj|rtj|std| ntj| std|  d}|
rt|
}t||	|d}t| o| d}t| |||||||||d
}|rt|tj |S |r3t|| |s1t| td|  |S |s:t| | }|d d kr\|d! d kr\|d" d kr\|sZtd# |S |sctd$ |rit  zt||||d W |ryt	  n|rt	  w w |std |S )%a  Sync files between a local directory and a bucket.

    This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
    (``hf://buckets/...``) and the other must be a local directory path.

    Args:
        source (`str`, *optional*):
            Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
            Required unless using ``apply``.
        dest (`str`, *optional*):
            Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
            Required unless using ``apply``.
        api ([`HfApi`]):
            The HfApi instance to use for API calls.
        delete (`bool`, *optional*, defaults to `False`):
            Delete destination files not present in source.
        ignore_times (`bool`, *optional*, defaults to `False`):
            Skip files only based on size, ignoring modification times.
        ignore_sizes (`bool`, *optional*, defaults to `False`):
            Skip files only based on modification times, ignoring sizes.
        existing (`bool`, *optional*, defaults to `False`):
            Skip creating new files on receiver (only update existing files).
        ignore_existing (`bool`, *optional*, defaults to `False`):
            Skip updating files that exist on receiver (only create new files).
        include (`list[str]`, *optional*):
            Include files matching patterns (fnmatch-style).
        exclude (`list[str]`, *optional*):
            Exclude files matching patterns (fnmatch-style).
        filter_from (`str`, *optional*):
            Path to a filter file with include/exclude rules.
        plan (`str`, *optional*):
            Save sync plan to this JSONL file instead of executing.
        apply (`str`, *optional*):
            Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
        dry_run (`bool`, *optional*, defaults to `False`):
            Print sync plan to stdout as JSONL without executing.
        verbose (`bool`, *optional*, defaults to `False`):
            Show detailed per-file operations.
        quiet (`bool`, *optional*, defaults to `False`):
            Suppress all output and progress bars.
        token (Union[bool, str, None], optional):
            A valid user access token. If not provided, the locally saved token will be used.

    Returns:
        [`SyncPlan`]: The computed (or loaded) sync plan.

    Raises:
        `ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).

    Example:
        ```python
        >>> from huggingface_hub import HfApi
        >>> api = HfApi()

        # Upload local directory to bucket
        >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")

        # Download bucket to local directory
        >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")

        # Sync with delete and filtering
        >>> api.sync_bucket(
        ...     "./data",
        ...     "hf://buckets/username/my-bucket",
        ...     delete=True,
        ...     include=["*.safetensors"],
        ... )

        # Dry run: preview what would be synced
        >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
        >>> plan.summary()
        {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}

        # Save plan for review, then apply
        >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
        >>> api.sync_bucket(apply="sync-plan.jsonl")
        ```
    Nr   r   )r   z,Cannot specify source/dest when using apply.z#Cannot specify both plan and apply.z'Cannot specify delete when using apply.z-Cannot specify ignore_times when using apply.z-Cannot specify ignore_sizes when using apply.z(Cannot specify include when using apply.z(Cannot specify exclude when using apply.z,Cannot specify filter_from when using apply.z)Cannot specify existing when using apply.z0Cannot specify ignore_existing when using apply.z(Cannot specify dry_run when using apply.)enabledzExecuting plan...)r   r   zSync completed.z7Both source and dest are required (unless using apply).z?Remote to remote sync is not supported. One path must be local.z?One of source or dest must be a bucket path (hf://buckets/...).z2Cannot specify both ignore_times and ignore_sizes.z1Cannot specify both existing and ignore_existing.z%Cannot specify both dry_run and plan.z!Destination must be a directory: z&Source must be an existing directory: r   )
r=   rp   r   rh   r   r   r   r   r   r   zPlan saved to: r|   r   r}   r~   zNothing to sync.z
Syncing...)hf_apir   r!   r   r   r   r   r   r   r   rd   rI   r   r   r   r   r   r   r   sysstdoutr   r   )r=   rp   r   rh   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z	sync_planr   Zsource_is_bucketZdest_is_bucketr   r   r   r%   r%   r&   sync_bucket_internal  s   c

*r   )FFFFFNN)FN)NN)Gr7   r   r   rF   rI   r   rK   dataclassesr   r   r   r   pathlibr   typingr   r   r	   r
   r   r   r   r   r   errorsr   utilsr   r   r   r   Zutils._terminalr   r   r   Z
get_loggerr4   r   r`   r   r8   r   r'   r(   r<   rN   rP   rQ   rY   r^   rc   r:   rd   re   ro   r   r   r   r;   floatr   r   r   r   r   r   r   r   r   r   r   r%   r%   r%   r&   <module>   sH   
 (
1 *"	

L	

 l$+c	


