U
    9%e                  	   @   s  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZ ddlmZ eeZeeeddf d	d
dZdeeee f eeee	f  ejdddZedeeee f eeee	f  eeee ee f ddf dddZdS )zFContains utilities to easily handle subprocesses in `huggingface_hub`.    N)contextmanager)StringIO)Path)IO	GeneratorListOptionalTupleUnion   )
get_logger)returnc                  c   s"   t  } tj}| t_| V  |t_dS )a  Capture output that is printed to terminal.

    Taken from https://stackoverflow.com/a/34738440

    Example:
    ```py
    >>> with capture_output() as output:
    ...     print("hello world")
    >>> assert output.getvalue() == "hello world
"
    ```
    N)r   sysstdout)outputZprevious_output r   `/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/huggingface_hub/utils/_subprocess.pycapture_output   s
    r   T)commandfolderr   c              	   K   sP   t | tr|  } t |tr$t|}tj| ftjtj|dd|pDt d|S )aX  
    Method to run subprocesses. Calling this will capture the `stderr` and `stdout`,
    please call `subprocess.run` manually in case you would like for them not to
    be captured.

    Args:
        command (`str` or `List[str]`):
            The command to execute as a string or list of strings.
        folder (`str`, *optional*):
            The folder in which to run the command. Defaults to current working
            directory (from `os.getcwd()`).
        check (`bool`, *optional*, defaults to `True`):
            Setting `check` to `True` will raise a `subprocess.CalledProcessError`
            when the subprocess has a non-zero exit code.
        kwargs (`Dict[str]`):
            Keyword arguments to be passed to the `subprocess.run` underlying command.

    Returns:
        `subprocess.CompletedProcess`: The completed process.
    utf-8replace)stderrr   checkencodingerrorscwd)	
isinstancestrsplitr   
subprocessrunPIPEosgetcwd)r   r   r   kwargsr   r   r   run_subprocess3   s     


r&   c              	   k   s   t | tr|  } tj| ftjtjtjdd|p4t d|8}|j	dk	sTt
d|jdk	sft
d|j	|jfV  W 5 Q R X dS )a  Run a subprocess in an interactive mode in a context manager.

    Args:
        command (`str` or `List[str]`):
            The command to execute as a string or list of strings.
        folder (`str`, *optional*):
            The folder in which to run the command. Defaults to current working
            directory (from `os.getcwd()`).
        kwargs (`Dict[str]`):
            Keyword arguments to be passed to the `subprocess.run` underlying command.

    Returns:
        `Tuple[IO[str], IO[str]]`: A tuple with `stdin` and `stdout` to interact
        with the process (input and output are utf-8 encoded).

    Example:
    ```python
    with _interactive_subprocess("git credential-store get") as (stdin, stdout):
        # Write to stdin
        stdin.write("url=hf.co
username=obama
".encode("utf-8"))
        stdin.flush()

        # Read from stdout
        output = stdout.read().decode("utf-8")
    ```
    r   r   )stdinr   r   r   r   r   Nz'subprocess is opened as subprocess.PIPE)r   r   r   r    Popenr"   STDOUTr#   r$   r'   AssertionErrorr   )r   r   r%   processr   r   r   run_interactive_subprocess_   s$     

	r,   )NT)N)__doc__r#   r    r   
contextlibr   ior   pathlibr   typingr   r   r   r   r	   r
   loggingr   __name__loggerr   r   CompletedProcessr&   r,   r   r   r   r   <module>   s2      , 