import{_ as h,D as l,c as t,j as i,a as s,I as k,w as p,a9 as a,o as e}from"./chunks/framework.C4_mTacX.js";const B=JSON.parse('{"title":"liteyuki.plugin.load","description":"","frontmatter":{"title":"liteyuki.plugin.load"},"headers":[],"relativePath":"en/dev/api/plugin/load.md","filePath":"en/dev/api/plugin/load.md","lastUpdated":1725101868000}'),E={name:"en/dev/api/plugin/load.md"},d=a(`

Module liteyuki.plugin.load

Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved

@Time : 2024/7/23 下午11:59 @Author : snowykami @Email : snowykami@outlook.com @File : load.py @Software: PyCharm


func load_plugin(module_path: str | Path) -> Optional[Plugin]

Description: 加载单个插件,可以是本地插件或是通过 pip 安装的插件。

Arguments:

Source code or View on GitHub
python
def load_plugin(module_path: str | Path) -> Optional[Plugin]:
    module_path = path_to_module_name(Path(module_path)) if isinstance(module_path, Path) else module_path
    try:
        module = import_module(module_path)
        _plugins[module.__name__] = Plugin(name=module.__name__, module=module, module_name=module_path)
        if module.__dict__.get('__plugin_metadata__', None):
            metadata: 'PluginMetadata' = module.__dict__['__plugin_metadata__']
            display_name = module.__name__.split('.')[-1]
        elif module.__dict__.get('__liteyuki_plugin_meta__', None):
            metadata: 'PluginMetadata' = module.__dict__['__liteyuki_plugin_meta__']
            display_name = format_display_name(f"{metadata.name}({module.__name__.split('.')[-1]})", metadata.type)
        elif module.__dict__.get('__plugin_meta__', None):
            metadata: 'PluginMetadata' = module.__dict__['__plugin_meta__']
            display_name = format_display_name(f"{metadata.name}({module.__name__.split('.')[-1]})", metadata.type)
        else:
            logger.opt(colors=True).warning(f'The metadata of Liteyuki plugin "{module.__name__}" is not specified, use empty.')
            metadata = PluginMetadata(name=module.__name__)
            display_name = module.__name__.split('.')[-1]
        _plugins[module.__name__].metadata = metadata
        logger.opt(colors=True).success(f'Succeeded to load liteyuki plugin "{display_name}"')
        return _plugins[module.__name__]
    except Exception as e:
        logger.opt(colors=True).success(f'Failed to load liteyuki plugin "<r>{module_path}</r>"')
        traceback.print_exc()
        return None

func load_plugins(*plugin_dir: str, *, ignore_warning: bool = True) -> set[Plugin]

Description: 导入文件夹下多个插件

Arguments:

Source code or View on GitHub
python
def load_plugins(*plugin_dir: str, ignore_warning: bool=True) -> set[Plugin]:
    plugins = set()
    for dir_path in plugin_dir:
        if not os.path.exists(dir_path):
            if not ignore_warning:
                logger.warning(f"Plugins dir '{dir_path}' does not exist.")
            continue
        if not os.listdir(dir_path):
            if not ignore_warning:
                logger.warning(f"Plugins dir '{dir_path}' is empty.")
            continue
        if not os.path.isdir(dir_path):
            if not ignore_warning:
                logger.warning(f"Plugins dir '{dir_path}' is not a directory.")
            continue
        for f in os.listdir(dir_path):
            path = Path(os.path.join(dir_path, f))
            module_name = None
            if os.path.isfile(path) and f.endswith('.py') and (f != '__init__.py'):
                module_name = f'{path_to_module_name(Path(dir_path))}.{f[:-3]}'
            elif os.path.isdir(path) and os.path.exists(os.path.join(path, '__init__.py')):
                module_name = path_to_module_name(path)
            if module_name:
                load_plugin(module_name)
                if _plugins.get(module_name):
                    plugins.add(_plugins[module_name])
    return plugins

func format_display_name(display_name: str, plugin_type: PluginType) -> str

Description: 设置插件名称颜色,根据不同类型插件设置颜色

Arguments:

`,20),r=i("strong",null,"Return",-1),g=a(`
Source code or View on GitHub
python
def format_display_name(display_name: str, plugin_type: PluginType) -> str:
    color = 'y'
    match plugin_type:
        case PluginType.APPLICATION:
            color = 'm'
        case PluginType.TEST:
            color = 'g'
        case PluginType.MODULE:
            color = 'e'
        case PluginType.SERVICE:
            color = 'c'
    return f'<{color}>{display_name} [{plugin_type.name}]</{color}>'
`,1);function y(F,o,u,_,C,c){const n=l("y");return e(),t("div",null,[d,i("p",null,[r,s(": str: 设置后的插件名称 "),k(n,null,{default:p(()=>[s("name")]),_:1})]),g])}const A=h(E,[["render",y]]);export{B as __pageData,A as default};