o
    )j,                     @   s   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 ddlmZ e	 ZG d	d
 d
eZG dd dedZdS )    N)ListOptional)urlparse
urlunparse)
get_logger   )MASTER_MODEL_BRANCH   )GitErrorc                       s    e Zd Zi Z fddZ  ZS )	Singletonc                    s0   | | j vrtt| j|i || j | < | j |  S N)
_instancessuperr   __call__)clsargskwargs	__class__ S/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/hub/git.pyr      s   

zSingleton.__call__)__name__
__module____qualname__r   r   __classcell__r   r   r   r   r      s    r   c                   @   s  e Zd ZdZdZdAdefddZdejfdd	Z	d
d Z
dedefddZdefddZdd Zdd Z	dAdededededee f
ddZdd Ze dfdedee d efd!d"Zded#efd$d%Zded&efd'd(Zded&efd)d*Zdefd+d,Z	-	.dBded/edefd0d1Z	dCdededed2ed3ed4efd5d6Zdefd7d8Zdefd9d:Zefded;ed#ed<efd=d>Zdefd?d@Z dS )DGitCommandWrapperzSome git operation wrapper
    gitNpathc                 C   s   |p| j | _d S r   )default_git_pathgit_path)selfr   r   r   r   __init__   s   zGitCommandWrapper.__init__returnc              
   G   s   t d| tj }d|d< | jg|}dd |D }tj|tj	tj	|d}z|
  |W S  tjyl } z/|jjddd	}|jjddd	}d
|v rZt d |W  Y d}~S t d|||f  t|d}~ww )a^  Run git command, if command return 0, return subprocess.response
             otherwise raise GitError, message is stdout and stderr.

        Args:
            args: List of command args.

        Raises:
            GitError: Exception with stdout and stderr.

        Returns:
            subprocess.CompletedProcess: the command response
         0GIT_TERMINAL_PROMPTc                 S   s   g | ]}|r|qS r   r   ).0itemr   r   r   
<listcomp>2   s    z6GitCommandWrapper._run_git_command.<locals>.<listcomp>)stdoutstderrenvzutf-8replace)errorsznothing to commitz;Nothing to commit, your local repo is upto date with remoteNz8Running git command: %s failed 
 stdout: %s 
 stderr: %s)loggerdebugjoinosenvironcopyr   
subprocessrunPIPEcheck_returncodeCalledProcessErrorr)   decoder*   infoerrorr
   )r    r   Zgit_envcommandresponser;   Zstd_outZstd_errr   r   r   _run_git_command!   s<   
z"GitCommandWrapper._run_git_commandc                 C   sX   |  |}d|vr*| ||}d||f }|d}| j| }t|jd d S d S )N//oauth2z-C %s remote set-url origin %sr#   utf8)get_repo_remote_url
_add_tokensplitr>   r.   r/   r)   r9   )r    repo_dirZ
auth_tokenurlZauth_urlcmd_argsrspr   r   r   config_auth_tokenJ   s   


z#GitCommandWrapper.config_auth_tokentokenrE   c                 C   s   |s|S | dr|S zt|}W n ty   | Y S w |jdvr$|S |jdkr+|S |jp/d}|jr;| d|j }d| d| }t|j|dS )	a  Inject OAuth2 token into an HTTP(S) git URL.

        Uses ``urllib.parse`` for reliable URL component handling,
        avoiding naive string replacement that can corrupt URLs
        containing multiple ``://`` sequences.

        Args:
            token: OAuth2 access token.
            url:   Remote URL (HTTP, HTTPS, or SSH).

        Returns:
            URL with ``oauth2:<token>@`` injected into the *netloc*,
            or the original *url* unchanged when:

            * *token* is falsy,
            * the URL already carries an ``oauth2`` credential,
            * the scheme is not HTTP/HTTPS (e.g. ``ssh://``, ``git@``).
        zgit@)httphttpsoauth2 :zoauth2:@)netloc)	
startswithr   	Exceptionschemeusernamehostnameportr   _replace)r    rI   rE   parsedhostrP   r   r   r   rB   S   s$   



zGitCommandWrapper._add_tokenc                 C   s@   |rd|v r| d}| d}|d | ||d d   }|S )Nr?   rL   rO   r	   )find)r    rE   start_indexZ	end_indexr   r   r   remove_token_from_url   s
   

z'GitCommandWrapper.remove_token_from_urlc                 C   s.   ddg}z| j |  W dS  ty   Y dS w )Nlfsr+   TFr>   r
   )r    cmdr   r   r   is_lfs_installed   s   
z"GitCommandWrapper.is_lfs_installedc                 C   s4   d|dddg}z| j |  W dS  ty   Y dS w )N-Cr]   installz--forceTFr^   )r    rD   r_   r   r   r   git_lfs_install   s   
z!GitCommandWrapper.git_lfs_installrepo_base_dir	repo_namebranchc           	   	   C   s   |  ||}|rd||||f }nd||f }t| |d}z| j| }t|jd |W S  tyU   tj	
||}tj	tj	
|drTtd| Y dS  w )a   git clone command wrapper.
        For public project, token can None, private repo, there must token.

        Args:
            repo_base_dir (str): The local base dir, the repository will be clone to local_dir/repo_name
            token (str): The git token, must be provided for private project.
            url (str): The remote url
            repo_name (str): The local repository path name.
            branch (str, optional): _description_. Defaults to None.

        Returns:
            The popen response.
        z-C %s clone %s %s --branch %sz-C %s clone %sr#   r@   z.gitzgit clone exited with non-zero status but the repository was cloned successfully at %s. This is usually caused by a post-clone hook (e.g. core.hooksPath). Continuing.N)rB   r.   r/   rC   r>   r)   r9   r
   r1   r   r0   isdirwarning)	r    rd   rI   rE   re   rf   Z
clone_argsr=   rD   r   r   r   clone   s,   


zGitCommandWrapper.clonec           	      C   s   ddl m} | \}}|rB|rDd|||f }| j|d }t|jd d|||f }| j|d }t|jd d S d S d S )Nr   )ModelScopeConfigz-C %s/%s config user.name %sr#   r@   z-C %s/%s config user.email %s)	Zmodelscope.hub.apirj   Zget_user_infor>   rC   r.   r/   r)   r9   )	r    rd   re   rj   Z	user_nameZ
user_emailZconfig_user_name_argsr=   Zconfig_user_email_argsr   r   r   add_user_info   s    zGitCommandWrapper.add_user_infoFrD   files	all_filesc                 C   sZ   |rd| }nt |dkrd|}d||f }|d}| j| }t|jd |S )Nz-C %s add -Ar   r#   z-C %s add %sr@   )lenr0   rC   r>   r.   r/   r)   r9   )r    rD   rl   rm   Zadd_argsZ	files_strrG   r   r   r   add   s   



zGitCommandWrapper.addmessagec                 C   s6   dd| ddd| g}| j | }t|jd |S )zRun git commit command

        Args:
            repo_dir (str): the repository directory.
            message (str): commit message.

        Returns:
            The command popen response.
        ra   %scommit-mz'%s'r@   )r>   r.   r:   r)   r9   )r    rD   rp   Zcommit_argsrG   r   r   r   rr      s   

zGitCommandWrapper.commitrevisionc                 C   s   dd| dd| g}| j | S )Nra   rq   checkoutr>   r    rD   rt   cmdsr   r   r   ru      s   
zGitCommandWrapper.checkoutc                 C   s   dd| dd|g}| j | S )Nra   rq   ru   z-brv   rw   r   r   r   
new_branch   s   
zGitCommandWrapper.new_branchc                 C   s|   dd| ddg}| j | }dd |jd tjD }t|dkr3d	|d
 d	dd  gS dd |dd  D S )Nra   rq   rf   z-rc                 S   s   g | ]}|  qS r   )stripr&   liner   r   r   r(      s    z9GitCommandWrapper.get_remote_branches.<locals>.<listcomp>r@   r	   /r   c                 S   s$   g | ]}d  |d dd qS )r}   r	   N)r0   rC   r{   r   r   r   r(     s   $ )	r>   r)   r9   rz   rC   r1   lineseprn   r0   )r    rD   rx   rG   r:   r   r   r   get_remote_branches   s   
z%GitCommandWrapper.get_remote_branchesoriginmasterremotec                 C   s   d|d||g}| j | S )Nra   pullrv   )r    rD   r   rf   rx   r   r   r   r     s   
zGitCommandWrapper.pulllocal_branchremote_branchforcec           	      C   sR   |  ||}d||||f }|r|d7 }|d}| j| }t|jd |S )Nz-C %s push %s %s:%sz -fr#   r@   )rB   rC   r>   r.   r/   r)   r9   )	r    rD   rI   rE   r   r   r   Z	push_argsrG   r   r   r   push  s   

zGitCommandWrapper.pushc                 C   s0   d| }| d}| j| }|jd}| S )Nz$-C %s config --get remote.origin.urlr#   r@   )rC   r>   r)   r9   rz   )r    rD   rF   rG   rE   r   r   r   rA      s
   

z%GitCommandWrapper.get_repo_remote_urlc                 C   sZ   d| }| d}| j| }|jd }g }| tjD ]}|| dd  q|S )Nz-C %s lfs ls-filesr#   r@   )rC   r>   r)   r9   rz   r1   r~   append)r    rD   rF   rG   outrl   r|   r   r   r   list_lfs_files'  s   

z GitCommandWrapper.list_lfs_filestag_namerefc                 C   s6   d|d|dd| |g}| j | }t|jd |S )Nra   tagrs   z"%s"r@   r>   r.   r/   r)   r9   )r    rD   r   rp   r   rF   rG   r   r   r   r   2  s   

zGitCommandWrapper.tagc                 C   s.   d|dd|g}| j | }t|jd |S )Nra   r   r   r@   r   )r    rD   r   rF   rG   r   r   r   push_tag?  s   
zGitCommandWrapper.push_tagr   )r   r   )F)!r   r   r   __doc__r   strr!   r4   CompletedProcessr>   rH   rB   r\   r`   rc   r   ri   rk   listr   boolro   rr   ru   ry   r   r   r   rA   r   r   r   r   r   r   r   r   r      s    )	/
.



r   )	metaclass)r1   r4   typingr   r   urllib.parser   r   Zmodelscope.utils.loggerr   Zutils.constantr   r-   r
   r.   typer   r   r   r   r   r   <module>   s   
