#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'ZL'
import importlib.util
import os

def import_source(module_name,module_path):
    module_spec = importlib.util.spec_from_file_location(module_name, module_path)  #根据给定的模块名和路径创建一个模块规范对象
    module = importlib.util.module_from_spec(module_spec)                           #根据模块规范创建一个新模块对象
    module_spec.loader.exec_module(module)                                          #执行模块的代码,将其导入到新创建的模块对象中
    return module

#遍历指定目录的文件,并去除掉一部分文件
def walk_py(path):
    for dir_path, dir_names, filenames in os.walk(path):
        if dir_path.endswith("__pycache__"):
            continue

        for f in filenames:
            if f.startswith('_') or f.endswith('_.py'):
                continue

            split = f.split('.')

            if len(split) == 2 and split[1] == 'py':
                abspath = os.path.abspath(os.path.join(dir_path, f))
                yield abspath, split[0]


def load_plugins(path):
    plugins = []
    for file_path, name in walk_py(path):
        try:
            module = import_source(spec="repoc_plugins", path=file_path)
            Plugin = getattr(module, 'Plugin')
            plugin = Plugin()
            setattr(plugin, '_plugin_name', name)
            plugins.append(plugin)
        except Exception as e:
            print("load plugin error from {}".format(file_path))

    return plugins