o
    O%                     @   s   d Z ddlmZ ddlm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ZddlZddlmZ dd Zd	d
 Zdd Zdd Zdd Zdd Zdd Zd"ddZdd Zdd Zd"ddZejdd Zd#d d!ZdS )$z0Utilities for accessing local package resources.    )absolute_import)division)unicode_literalsN)filesc                 C   s"   |  d}|dkr| d| S dS )z+Returns package name for given module name..r   N )rfind)module_namelast_dot_idx r   C/tmp/google-cloud-sdk/lib/googlecloudsdk/core/util/pkg_resources.py_GetPackageName"   s   
r   c                 C   s   t t| |S )zCGet a resource as a byte string for given resource in same package.)pkgutilget_datar   )r	   resource_namer   r   r   GetResource*   s   r   c                 C   sJ   t j| rt| S tt j| }t|dr|	| S t
d| )aA  Gets the given resource as a byte string.

  This is similar to GetResource(), but uses file paths instead of module names.

  Args:
    path: str, filesystem like path to a file/resource.

  Returns:
    The contents of the resource as a byte string.

  Raises:
    IOError: if resource is not found under given path.
  r   zFile not found {0})ospathisfiler   ReadBinaryFileContentsr   get_importerdirnamehasattrr   IOErrorformat)r   importerr   r   r   GetResourceFromFile/   s   


r   c                 C   s   t j|r6t jt j|ds|tjv S t j|| }t j|r.t jt j|dS t j|d S | d}t	t jj|g|dd R  }|sPdS t
|d}|rZ|jn|j}||d duS )zChecks if given name can be imported at given path.

  Args:
    name: str, module name without '.' or suffixes.
    path: str, filesystem path to location of the module.

  Returns:
    True, if name is importable.
  __init__.py.pyr   NF	find_spec)r   r   isdirr   joinsysexistssplitr   r   r   r    find_module)namer   	name_pathr   find_spec_existsfind_methodr   r   r   IsImportableG   s   

"
r+   c                 C   s   t jt j|drtj| t j|d}nt j|d r*tj| |d }nt|| S tj|}|t	j
| < |j| |S )a  Loads module at given path under given name.

  Note that it also updates sys.modules with name_to_give.

  Args:
    name_to_give: str, name to assign to loaded module
    module_path: str, python path to location of the module, this is either
      filesystem path or path into egg or zip package

  Returns:
    Imported module

  Raises:
    ImportError: if module cannot be imported.
  r   r   )r   r   r   r"   	importlibutilspec_from_file_location_GetModuleFromPathViaPkgutilmodule_from_specr#   modulesloaderexec_module)name_to_givemodule_pathspecmoduler   r   r   GetModuleFromPathe   s   

r8   c                 C   sn   t tj| }|std| t|d}|r|jn|j	}tj
| }||r0t|| ||S td| )z5Loads module by using pkgutil.get_importer mechanism.z{0} not foundr    )r   r   r   r   r   ImportErrorr   r   r    r&   basename_LoadModule)r5   r4   r   r)   r*   r	   r   r   r   r/      s   
r/   c                 C   s\   |  |}t|}| |r|g|_tj|d|_n|d |_t	||j
 |tj|< |S )z-Loads the module or package under given name.z__init__.pycz.pyc)get_codetypes
ModuleType
is_package__path__r   r   r"   __file__exec__dict__r#   r1   )r   r5   r	   r4   coder7   r   r   r   r;      s   




r;   c           
      c   s   t  }|du r
g }|du rd}| D ]s}||sq|t|d tj}t|dkrG|d drG|d |vrG||d  |d dfV  t|dkrNqtj|d }tj	|\}}|dksj|d	krk||vrkq|d	krq|n|}	d
|vr|	|vr||	 |	dfV  qdS )zDYields module names from given list of file paths with given prefix.Nr         r   r   T__init__r   r   F)
set
startswithlenr%   r   sepaddr   r:   splitext)
	file_listextra_extensionsprefixyielded	file_pathfile_path_partsfilenamemodnameextto_yieldr   r   r   _IterModules   s8   


rX   c                 C   sj   g }t | D ]+}t jt j| |r|| qt j| |d}t j|r2|t j|d q|S )z=List packages or modules which can be imported at given path.r   )r   listdirr   r   r"   append)r   importablesrT   pkg_init_filepathr   r   r   _ListPackagesAndFiles   s   r]   c                 C   s    t | dr
| j}|S |  }|S )z&Get a list of files from the importer._files)r   r^   
_get_files)r   
files_listr   r   r   _GetFilesList   s
   
ra   c                 C   s~   g }t j| rtt| |}nt| }tt|||j}g g }}|D ]\}}|r1|	| q%|	| q%t
|t
|fS )a$  Returns list of packages and modules in given path.

  Args:
    path: str, filesystem path
    extra_extensions: [str], The list of file extra extensions that should be
      considered modules for the purposes of listing (in addition to .py).

  Returns:
    tuple([packages], [modules])
  )r   r   r!   rX   r]   r   r   ra   rP   rZ   sorted)r   rO   iter_modulesr   packagesr1   r'   ispkgr   r   r   ListPackage   s   

rf   c                 c   sX    t j| rt| }z
|V  W |  dS |  w t| }t|dt j	V  dS )z!Get a file reader for given path.zutf-8N)
r   r   r   r   
FileReadercloser   strr%   linesep)r   fbyte_stringr   r   r   GetFileTextReaderByLine   s   
rm   *.*c                 C   s   t j| rt|  d| S t| }t|ds!td| g }t	|D ]2}|
|js0q'|t|jd t j}t|dkrDq't|d | rY|t j| |d  q'|S )a,  Get files from a given directory that match a pattern.

  Args:
    path_dir: str, filesystem path to directory
    filter_pattern: str, pattern to filter files to retrieve.

  Returns:
    List of filtered files from a directory.

  Raises:
    IOError: if resource is not found under given path.
  /r   zPath not found {0}NrF   r   )r   r   r!   globr   r   r   r   r   ra   rI   rP   rJ   r%   rK   fnmatchrZ   r"   )path_dirfilter_patternr   filtered_filesrR   rS   r   r   r   GetFilesFromDirectory  s$   

ru   )N)rn   )__doc__
__future__r   r   r   
contextlibrq   rp   importlib.utilr,   r   r   r#   r=   googlecloudsdk.core.utilr   r   r   r   r+   r8   r/   r;   rX   r]   ra   rf   contextmanagerrm   ru   r   r   r   r   <module>   s6   (
"
	
