3
x[W                 @   s`   d Z ddlmZ ddlZddlZddlZejdZejdZ	G dd de
ZG dd	 d	eZdS )
z.
utils.plugins - Plugin loading functionality
    )PathNzplugin-loaderz\* depends: (.+)c               @   s<   e Zd ZdZdddZdd Zddd	Zd
d Zdd ZdS )PluginLoaderz
    Infobot's plugin loader.

    Generates a dependency graph and returns a list of loaded modules when
    load_all() is called.
    pluginsNc             C   s   | | _ | _i | _|rt|nt | _t| j}g }xF|j D ]:}|j rV|d j sb|j	j
dr>|j| jkr>|j| q>W x|D ]}| j| qW dS )z? Initializes the PluginLoader by generating a dependency graph z__init__.pyz.pyN)plugin_packageplugin_directorygraphset	blacklistr   Ziterdiris_direxistsnameendswithstemappendparseDepends)selfr   r	   pathZplugin_pathsZsubpath r   /opt/Infobot/core/plugins.py__init__   s    

zPluginLoader.__init__c             C   s   |j  rt|d }nt|}t|v}xP|D ]H}d|krRtjd|j d d S tj|}|r.|jdj	d| j
|< q.W || j
kr|jdkrg | j
|< W d Q R X d S )Nz__init__.pyz* noloadzNot loading plugin z due to noload directive   z, )r
   stropenloggerinfor   
DEPENDS_REsearchgroupsplitr   r   )r   r   Z	main_filepluginlinematchr   r   r   r   (   s    


zPluginLoader.parseDependsc             C   s$   |s| j  d|j }tj|}|S )N.)r   r   	importlibimport_module)r   Zplugin_pathr   r   r   r   r   load_plugin=   s    
zPluginLoader.load_pluginc          	   C   sf   x`| j j D ]R\}}t|| j@ }|rt|dkr6dnd}td|j ddj| d| dqW d S )	Nr   ZareiszPlugin z
 requires z, z, which z blacklisted.)r   itemsr   r	   lenDependencyErrorr   join)r   r   depsZblacklisted_depsZ	verb_formr   r   r   check_impossible_loadsD   s
    z#PluginLoader.check_impossible_loadsc             C   s   | j   g }| jddd x| jrdd | jj D }xj|j D ]^\}}|j| j| | j|= x<| jj D ].\}}y|j|j W ql tk
r   Y qlX qlW q@W qW |S )Nz__init__.pyr   )r   c             S   s   i | ]\}}|s||qS r   r   ).0r   r+   r   r   r   
<dictcomp>R   s    z)PluginLoader.load_all.<locals>.<dictcomp>)r,   r%   r   r'   r   remover   
ValueError)r   r   Zsatisfied_pluginsZsatisfied_plugin_r   r+   r   r   r   load_allL   s    zPluginLoader.load_all)r   N)N)	__name__
__module____qualname____doc__r   r   r%   r,   r2   r   r   r   r   r      s   

r   c               @   s   e Zd ZdS )r)   N)r3   r4   r5   r   r   r   r   r)   b   s   r)   )r6   Zpathlibr   r#   relogging	getLoggerr   compiler   objectr   	Exceptionr)   r   r   r   r   <module>   s   

R