o
    i]P                     @   s  d Z ddlm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	 ddl
Z
ddlmZ ddlmZ ddlmZ eded	gZd
dgZdaG dd deZedAddZdBddZdd ZdCdefddZdd ZdCddZdd  Zd!d" ZdDd$d%Z dCd&d'Z!dCd(d)Z"d*d+ Z#d,d- Z$d.d/ Z%d0d1 Z&d2d3 Z'd4d5 Z(d6d7 Z)d8d9 Z*d:d; Z+d<d= Z,d>d? Z-e.d@kre-  dS dS )Ea  pipreqs - Generate pip requirements.txt file based on imports

Usage:
    pipreqs [options] [<path>]

Arguments:
    <path>                The path to the directory containing the application
                          files for which a requirements file should be
                          generated (defaults to the current working
                          directory).

Options:
    --use-local           Use ONLY local package info instead of querying PyPI.
    --pypi-server <url>   Use custom PyPi server.
    --proxy <url>         Use Proxy, parameter will be passed to requests
                          library. You can also just set the environments
                          parameter in your terminal:
                          $ export HTTP_PROXY="http://10.10.1.10:3128"
                          $ export HTTPS_PROXY="https://10.10.1.10:1080"
    --debug               Print debug information
    --ignore <dirs>...    Ignore extra directories, each separated by a comma
    --no-follow-links     Do not follow symbolic links in the project
    --encoding <charset>  Use encoding parameter for file open
    --savepath <file>     Save the list of requirements in the given file
    --print               Output the list of requirements in the standard
                          output
    --force               Overwrite existing requirements.txt
    --diff <file>         Compare modules in requirements.txt to project
                          imports
    --clean <file>        Clean up requirements.txt by removing modules
                          that are not imported in project
    --mode <scheme>       Enables dynamic versioning with <compat>,
                          <gt> or <non-pin> schemes.
                          <compat> | e.g. Flask~=1.1.2
                          <gt>     | e.g. Flask>=1.1.2
                          <no-pin> | e.g. Flask
    --scan-notebooks      Look for imports in jupyter notebook files.
    )contextmanagerN)docopt)json2package)	HTTPError)__version__z^import (.+)$z!^from ((?!\.+).*?) import (?:.*)$z.pyz.pywFc                       s$   e Zd ZdZef fdd	Z  ZS )NbconvertNotInstalledzVIn order to scan jupyter notebooks, please install the nbconvert and ipython librariesc                    s   t  | d S N)super__init__)selfmessage	__class__ J/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/pipreqs/pipreqs.pyr
   A      zNbconvertNotInstalled.__init__)__name__
__module____qualname__default_messager
   __classcell__r   r   r   r   r   <   s    r   rc              	   c   s    | r| dkr |rd|v rt j}nd|v rt j}ntd|t| |}z|V  W |t jt jfvr8|  dS dS |t jt jfvrG|  w w )a  Open a file or ``sys.stdout`` depending on the provided filename.

    Args:
        filename (str): The path to the file that should be opened. If
            ``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
            returned depending on the desired mode. Defaults to ``None``.
        mode (str): The mode that should be used to open the file.

    Yields:
        A file handle.

    -r   wzInvalid mode for file: {}N)sysstdinstdout
ValueErrorformatopenclose)filenamemodefiler   r   r   _openE   s   

r$   utf-8Tc                    s>  t  }t  }g }d}g d|r)g }|D ]}	|tjtj|	 q| t  tj| |d}
|
D ]\}}}fdd|D |d d < |tj| dd |D }|dd |D   fdd|D }|D ]e}tj	||}t
||}z.t|}t|D ]!}t|tjr|jD ]}||j qqt|tjr||j qW ql ty } z|rt| td	|  W Y d }~qltd	|  |d }~ww q5d
d |D D ]}|d\}}}|| q|t ||@  }td| tt	dd}dd |D }W d    n	1 sw   Y  t|| S )NF)z.hgz.svnz.gitz.tox__pycache__envvenvz.ipynb_checkpoints)followlinksc                    s   g | ]}| vr|qS r   r   ).0d)ignore_dirsr   r   
<listcomp>~       z#get_all_imports.<locals>.<listcomp>c                 S   s   g | ]	}t |tr|qS r   )file_ext_is_allowedDEFAULT_EXTENSIONS)r*   r#   r   r   r   r-          c                 S   s   g | ]
}t j|d  qS r   ospathsplitext)r*   r!   r   r   r   r-          c                    s   g | ]	}t | r|qS r   )r/   )r*   fn)
extensionsr   r   r-      r1   zFailed on file: %sc                 S   s   g | ]}|r|qS r   r   )r*   nr   r   r   r-          .zFound packages: {0}stdlibr   c                 S   s   h | ]}|  qS r   stripr*   xr   r   r   	<setcomp>   r;   z"get_all_imports.<locals>.<setcomp>)setappendr4   r5   basenamerealpathextendget_file_extensionswalkjoinread_file_contentastparse
isinstanceImportnamesaddname
ImportFrommodule	Exception	traceback	print_excloggingwarnerror	partitiondebugr   r   list)r5   encodingextra_ignore_dirsfollow_linksimportsraw_imports
candidatesignore_errorsignore_dirs_parsederI   rootdirsfilespy_files	file_namecontentstreenodesubnodeexcrR   cleaned_name_packagesfdatar   )r9   r,   r   get_all_importsd   sf   




rv   c                   C   s   t rtdg S tS )N.ipynb)scan_noteboooksr0   r   r   r   r   rH      s   rH   rk   c                 C   sf   t | tr#t| d|d}| }W d    |S 1 sw   Y  |S t | dgr1tr1t| |d}|S )Nr   r^   rw   )r/   r0   r   readrx   
ipynb_2_py)rk   r^   rt   rl   r   r   r   rK      s   


rK   c                 C   s   t j| d |v S )N   r3   )rk   
acceptabler   r   r   r/      s   r/   c                 C   s   t  }|| \}}||S )z

    Args:
        file_name (str): notebook file path to parse as python script
        encoding  (str): encoding of file

    Returns:
        str: parsed string

    )PythonExporterfrom_filenameencode)rk   r^   exporterbodyrr   r   r   r   r{      s   
r{   c              
      s   t | d5}tdjt|| ddd |D d d| d  |d	 fd
d|D d	  W d    d S 1 s=w   Y  d S )Nr   z/Writing {num} requirements: {imports} to {file}, c                 S      g | ]}|d  qS rR   r   r@   r   r   r   r-      r;   z.generate_requirements_file.<locals>.<listcomp>)numr#   ra   {name}z	{version}
c                 3   s8    | ]}|d  r j di |ndj di |V  qdS )versionr   Nr   )r   r*   itemfmtr   r   	<genexpr>   s
    &
z-generate_requirements_file.<locals>.<genexpr>)r$   rX   r\   r   lenrJ   write)r5   ra   symbolout_filer   r   r   generate_requirements_file   s   "r   c                 C   s   t d| | d S )Nr   )r   )ra   r   r   r   r   output_requirements   r   r   https://pypi.python.org/pypi/c              	   C   s   g }| D ]`}z9t d| tjd|||d}|jdkr1t|jdr+t|j	 }nt|j}n|jdkr>t
|j|jdW n t
yN   t d| Y qw t d	||j|j|j |||jd
 q|S )NzMImport named "%s" not found locally. Trying to resolve it at the PyPI server.z{0}{1}/json)proxies   decodei,  )status_codereasonz/Package "%s" does not exist or network problemszImport named "%s" was resolved to "%s:%s" package (%s).
Please, verify manually the final list of requirements.txt to avoid possible dependency confusions.rR   r   )rX   warningrequestsgetr   r   hasattrcontentr   r   r   r   rR   latest_release_idpypi_urlrD   )ra   pypi_serverproxyresultr   responseru   r   r   r   get_imports_info   s8   

	r   c                 C   s0  g }g d}t jD ]}t|D ]\}}}|D ]|}d|v rtj||}t|d| d`}|tjd d}	z| 	 d}
W n   Y W d    qt
 }|
D ]}||vrd|	d |vrd|| qSd }t|	d	kry|	d	 d
ddd}||	d ||d W d    n1 sw   Y  qqq	|S )N)tests_testseggEGGinfo	top_levelr   ry   r   r   r   r|   z.dist z.egg)rR   r   exports)r   r5   r4   rI   rJ   r   splitseprz   r?   r]   rD   r   replace)r^   rs   ignorer5   rg   rh   ri   r   rt   packagetop_level_modulesfiltered_top_level_modulesrT   r   r   r   r   get_locally_installed_packages  sB   


"r   c                    sZ   t  }g  | D ]}|D ]}||d v s||d kr | qq fddt D }|S )Nr   rR   c                    s(   g | ]\}}| |d  d vr|qS )r|   Nr   )r*   r:   ir   r   r   r-   ?  s   ( z$get_import_local.<locals>.<listcomp>)r   rD   	enumerate)ra   r^   localr   r   result_uniquer   r   r   get_import_local/  s   
r   c                 C   sr   t  }ttdd}tdd |D }W d   n1 sw   Y  | D ]}|||| q%t|dd dS )	zGet PyPI package names from a list of imports.

    Args:
        pkgs (List[str]): List of import names.

    Returns:
        List[str]: The corresponding PyPI package names.

    mappingr   c                 s   s    | ]
}|  d V  qdS ):N)r?   r   r@   r   r   r   r   P  s    z get_pkg_names.<locals>.<genexpr>Nc                 S   s   |   S r   lower)sr   r   r   <lambda>V  s    zget_pkg_names.<locals>.<lambda>key)rC   r   rJ   dictrQ   r   sorted)pkgsr   rt   ru   pkgr   r   r   get_pkg_namesD  s   
r   c                 C   sH   d| v rt d |  }|r|dd } | dd dd  S )Nzimport r   z as r<   )REGEXPmatchr?   groupsr[   )rR   r   r   r   r   get_name_without_aliasY  s
   r   c                 C   s   t jt jt| S r   )r4   r5   rJ   dirname__file__)rt   r   r   r   rJ   a  s   rJ   c           
   
      s<  g }g d}zt | d}W n0 ty#   td|  d td Y n0 ty= } ztd|  dt|  |d}~ww zd	d
 |	 D }W |
  n|
  w dd
 |D }|D ]? t fdd
|D sq| dd  D ]'}||v r |}|d }|d dd}	||	d}||vr||  nqsq\|S )u9  Parse a requirements formatted file.

    Traverse a string until a delimiter is detected, then split at said
    delimiter, get module name by element index, create a dict consisting of
    module:version, and add dict to list of parsed modules.

    If file ´file_´ is not found in the system, the program will print a
    helpful message and end its execution immediately.

    Args:
        file_: File to parse.

    Raises:
        OSerror: If there's any issues accessing the file.

    Returns:
        list: The contents of the file, excluding comments.
    )<>=!~r   zFile z- was not found. Please, fix it and run again.r|   z$There was an error opening the file z: Nc                 S   s   g | ]
}|d kr|  qS )r   r>   r@   r   r   r   r-     r7   z&parse_requirements.<locals>.<listcomp>c                 S   s   g | ]
}|d    r|qS r2   )isalphar@   r   r   r   r-     r7   c                    s   g | ]}| v qS r   r   )r*   yrA   r   r   r-     r;   r   r   r   r   r   )r   FileNotFoundErrorprintr   exitOSErrorrX   rZ   str	readlinesr    anyrD   r   r   )
file_modulesdelimrt   rZ   ru   r   rT   module_namemodule_versionr   r   r   parse_requirementse  s>   


r   c                    sP   t |  fddtt D  fddttD tt  }|S )a>  Compare modules in a file to imported modules in a project.

    Args:
        file_ (str): File to parse for modules to be compared.
        imports (tuple): Modules being imported in the project.

    Returns:
        set: The modules not imported in the project, but do exist in the
            specified file.
    c                       g | ]} | d  qS r   r   r*   r   )ra   r   r   r-     r.   z#compare_modules.<locals>.<listcomp>c                    r   r   r   r   )r   r   r   r-     r.   )r   ranger   rC   r   ra   modules_not_importedr   )ra   r   r   compare_modules  s
   r   c              	   C   s0   t | |}td| ddd |D  dS )zFDisplay the difference between modules in a file and imported modules.zBThe following modules are in {} but do not seem to be imported: {}r   c                 s   s    | ]}|V  qd S r   r   r@   r   r   r   r     s    zdiff.<locals>.<genexpr>N)r   rX   r   r   rJ   r   r   r   r   diff  s
   
r   c                 C   s   t | |}t|dkrtd|   dS td|}g }zt| d}W n ty5   t	d
|   w z,| D ]}||du rI|| q;|d |  |D ]}|| qUW |  n|  w td|   dS )z9Remove modules that aren't imported in project from file.r   zNothing to clean in N|zr+zFailed on file: {}z(Successfully cleaned up requirements in )r   r   rX   r   recompilerJ   r   r   rZ   r   r   r   rD   seektruncater   r    )r   ra   r   	re_removeto_writert   r   r   r   r   clean  s0   


r   c                 C   sJ   | dkrdd |D }d}||fS | dkrd}||fS | dkr!d}||fS )	zDEnables dynamic versioning with <compat>, <gt> or <non-pin> schemes.no-pinc                 S   s   g | ]	}|d  ddqS )rR   r   r   r   r   r   r   r   r-     r1   z&dynamic_versioning.<locals>.<listcomp>r   gtz>=compatz~=r   )schemera   r   r   r   r   dynamic_versioning  s   r   c                   C   s:   t s	td d S z	ddlma W d S  ty   t w )Nz#Not scanning for jupyter notebooks.r   )r~   )rx   rX   r   	nbconvertr~   ImportErrorr   r   r   r   r   handle_scan_noteboooks  s   
r   c                    s,  |  d}|  d}|  d }|  ddat  | d }|d u r#d}|d u r.tjtj}|r5|d}| d	 r=| d	 ntj|d
}| d s]| d	 s]| d s]tj	|r]t
d d S t||||d}t|}t
dd|  d}d }| d r| d }| d r| d | d d}| d rt
d t||d}	nt
d t||d  fdd|D }
 t|
||d }	t|	dd d}	| d rt| d |	 d S | d  rt| d  |	 d S | d! r|  d!}|d"v rt||	\}	}ntd#d$}| d rt|	| t
d% d S t||	| t
d&|  d S )'Nz
--encodingz--ignorez--no-follow-linksz--scan-notebooksFz<path>r%   ,z
--savepathzrequirements.txtz--printz--forcez<requirements.txt already exists, use --force to overwrite it)r^   r_   r`   zFound imports: r   r   z--pypi-serverz--proxy)httphttpsz--use-localz9Getting package information ONLY from local installation.ry   z,Getting packages information from Local/PyPIc                    s<   g | ]}|  d d  D vr|  dd  D vr|qS )c                 S   s   g | ]}|d  D ]}|qqS )r   r   )r*   rA   r   r   r   r   r-   7  s    z#init.<locals>.<listcomp>.<listcomp>c                 S   r   r   r   r@   r   r   r   r-   9  r;   r   r@   r   r   r   r-   0  s    zinit.<locals>.<listcomp>)r   r   c                 S   s   | d   S )NrR   r   r   r   r   r   r   >  s    zinit.<locals>.<lambda>r   z--diffz--cleanz--mode)r   r   r   zFInvalid argument for mode flag, use 'compat', 'gt' or 'no-pin' insteadz==z Successfully output requirementsz(Successfully saved requirements file in )r   rx   r   r4   r5   abspathcurdirr   rJ   existsrX   r   rv   r   r\   r   r   r   r   r   r   r   r   r   r   )argsr^   r_   r`   
input_pathr5   rc   r   r   ra   
differencer   r   r   r  r   init  s   










r  c                  C   s\   t ttd} | d rtjntj}tj|dd zt|  W d S  ty-   t	
d Y d S w )N)r   z--debugz%(levelname)s: %(message)s)levelr   r   )r   __doc__r   rX   DEBUGINFObasicConfigr  KeyboardInterruptr   r   )r  	log_levelr   r   r   main[  s   r  __main__)Nr   )r%   NT)r%   )r   N)/r
  
contextlibr   r4   r   r   rX   rL   rV   r   r   yargr   yarg.exceptionsr   pipreqsr   r   r   r0   rx   r   r   r$   rv   rH   r   rK   r/   r{   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r  r  r   r   r   r   r   <module>   sV   &	
J	


!
);
 e
