
    O%                         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 Zd Zd	 Zd
 Zd Zd Zd ZddZd Zd ZddZej6                  d        ZddZy)z0Utilities for accessing local package resources.    )absolute_import)division)unicode_literalsN)filesc                 :    | j                  d      }|dkD  r| d| S y)z+Returns package name for given module name..r   N )rfind)module_namelast_dot_idxs     -lib/googlecloudsdk/core/util/pkg_resources.py_GetPackageNamer   "   s*    ""3',A}%%	    c                 @    t        j                  t        |       |      S )zCGet a resource as a byte string for given resource in same package.)pkgutilget_datar   )r   resource_names     r   GetResourcer   *   s    			/+6	FFr   c                 <   t         j                  j                  |       rt        j                  |       S t        j                  t         j                  j                  |             }t        |d      r|j                  |       S t        dj                  |             )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   importers     r   GetResourceFromFiler    /   st     WW^^D''--!!"''//$"78(Xz"T""$++D122r   c                    t         j                  j                  |      rt         j                  j                  t         j                  j	                  |d            s|t
        j                  v S t         j                  j	                  ||       }t         j                  j                  |      r=t         j                  j                  t         j                  j	                  |d            S t         j                  j                  |dz         S | j                  d      }t        j                  t        j                  j                  |g|dd        }|syt        |d      }|r|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_methods         r   IsImportabler0   G   s    WW]]477>>"'',,t];<SXXT4(I	ww}}YWW^^BGGLLMBCC77>>)e+,,jjo)!!"'',,t"Ein"EF(	X{3&6""H<P<P+	Yr]	#4	//r   c                 <   t         j                  j                  t         j                  j                  |d            r?t        j
                  j                  | t         j                  j                  |d            }nRt         j                  j                  |dz         r$t        j
                  j                  | |dz         }nt        ||       S t        j
                  j                  |      }|t        j                  | <   |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modules       r   GetModuleFromPathr>   e   s      WW^^BGGLLm<=>>11bggll;>D 
ww~~kE)*>>11kE)D (\BB>>**40&$#++l++&!	-r   c                    t        j                  t        j                  j	                  |             }|st        dj                  |             t        |d      }|r|j                  n|j                  }t        j                  j                  |       } ||      rt        || ||      S t        dj                  |             )z5Loads module by using pkgutil.get_importer mechanism.z{0} not foundr%   )r   r   r   r   r   ImportErrorr   r   r%   r+   basename_LoadModule)r;   r:   r   r.   r/   r   s         r   r5   r5      s    !!"''//+">?(	
o,,[9
::X{3&6""H<P<P+  -+xk<HHO**;788r   c                 6   | j                  |      }t        j                  |      }| j                  |      r.|g|_        t
        j                  j                  |d      |_        n
|dz   |_        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(   r7   )r   r;   r   r:   coder=   s         r   rB   rB      s~    			;	'$L)&%"mFOggll;?FO!F*FO tV__$#++l	-r   c              #   `  K   t               }|g }|d}| D ]  }|j                  |      s|t        |      d j                  t        j
                        }t        |      dk(  r8|d   j                  d      r$|d   |vr|j                  |d          |d   df t        |      dk7  rt        j                  j                  |d         }t        j                  j                  |      \  }}|dk(  s	|d	k7  r||vr|d	k(  r|n|}	d
|vs|	|vs|j                  |	       |	df  yw)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   rA   splitext)
	file_listextra_extensionsprefixyielded	file_pathfile_path_partsfilenamemodnameextto_yields
             r   _IterModulesra      s;    E'^Fi'F.44RVV<O
?q _Q%7%B%B& 
	7	*OA&'a $&&
?q ww 23H77##H-LGS*#=M2M,wHH
'hg5kk(eO1 s   DD.D.D.c                    g }t        j                  |       D ]  }t         j                  j                  t         j                  j	                  | |            r|j                  |       Rt         j                  j	                  | |d      }t         j                  j                  |      s|j                  t         j                  j	                  |d              |S )z=List packages or modules which can be imported at given path.r"   )r   listdirr   r   r'   append)r   importablesr]   pkg_init_filepaths       r   _ListPackagesAndFilesrg      s    +**T"h	ww~~bggll423"'',,tX}E	)	*277<<-@A # 
r   c                 Z    t        | d      r| j                  }|S | j                         }|S )z&Get a list of files from the importer._files)r   ri   
_get_files)r   
files_lists     r   _GetFilesListrl      s3    Xx J 
 $$&J	r   c                 l   g }t         j                  j                  |       rt        t	        |       |      }n5t        j                  |       }t        t        |      ||j                        }g g }}|D ]*  \  }}|r|j                  |       |j                  |       , 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&   ra   rg   r   r   rl   rY   rd   sorted)r   rX   iter_modulesr   packagesr7   r,   ispkgs           r   ListPackagerr      s     ,WW]]4 5d ;=MNL##D)Hh!18??L "G(!kdEoodnnT	 "
 
	6'?	**r   c              #   6  K   t         j                  j                  |       r+t        j                  |       }	 | |j                          yt        |       }t        |d      j                  t         j                         y# |j                          w xY ww)z!Get a file reader for given path.zutf-8N)
r   r   r   r   
FileReadercloser    strr*   linesep)r   fbyte_strings      r   GetFileTextReaderByLinerz      sm      WW^^DAgggi%d+K
k7
#
)
)"**
55 ggis   5BB ABBBc                 l   t         j                  j                  |       rt        j                  |  d|       S t	        j
                  |       }t        |d      st        dj                  |             g }t        |      D ]  }|j                  |j                        s|t        |j                        d j                  t         j                        }t        |      dk7  rct        j                  |d   |       s~|j!                  t         j                  j#                  | |d                 |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}NrO   r   )r   r   r&   globr   r   r   r   r   rl   rR   rY   rS   r*   rT   fnmatchrd   r'   )path_dirfilter_patternr   filtered_filesr[   r\   s         r   GetFilesFromDirectoryr     s    WW]]899z>"2344##H-H8Z((//9::N"8,	!!(//2!#hoo"6"89??Go	_		"	+/?	AGGLL?1#56	
 - r   )N)z*.*)__doc__
__future__r   r   r   
contextlibr~   r}   importlib.utilr2   r   r   r(   rE   googlecloudsdk.core.utilr   r   r   r    r0   r>   r5   rB   ra   rg   rl   rr   contextmanagerrz   r    r   r   <module>r      s     7 &  '     	  
  *G
300<%P9 D
+: 
6 
6#r   