app/liteyuki/utils/resource.py

56 lines
1.6 KiB
Python
Raw Normal View History

2024-03-19 00:27:40 +08:00
import os
import nonebot
import yaml
2024-03-23 19:55:12 +08:00
from typing import Any
2024-03-19 00:27:40 +08:00
2024-03-24 09:43:34 +08:00
from liteyuki.utils.data import LiteModel
2024-03-19 00:27:40 +08:00
_resource_data = {}
_loaded_resource_packs = [] # 按照加载顺序排序
2024-03-19 00:27:40 +08:00
class ResourceMetadata(LiteModel):
name: str = "Unknown"
version: str = "0.0.1"
description: str = "Unknown"
path: str
def load_resource_from_dir(path: str):
"""
把资源包按照文件相对路径加载到资源包中后加载的优先级更高顺便加载语言
Args:
path: 资源文件夹
Returns:
"""
for root, dirs, files in os.walk(path):
for file in files:
relative_path = os.path.relpath(os.path.join(root, file), path).replace("\\", "/")
abs_path = os.path.join(root, file).replace("\\", "/")
_resource_data[relative_path] = abs_path
if os.path.exists(os.path.join(path, "metadata.yml")):
with open(os.path.join(path, "metadata.yml"), "r", encoding="utf-8") as f:
metadata = yaml.safe_load(f)
else:
metadata = ResourceMetadata()
metadata["path"] = path
if os.path.exists(os.path.join(path, "lang")):
2024-03-24 09:43:34 +08:00
from liteyuki.utils.language import load_from_dir
2024-03-19 00:27:40 +08:00
load_from_dir(os.path.join(path, "lang"))
_loaded_resource_packs.append(ResourceMetadata(**metadata))
2024-03-30 19:24:09 +08:00
def get_path(path: str, abs_path: bool = False, default: Any = None) -> str | Any:
"""
获取资源包中的文件
Args:
2024-03-30 19:24:09 +08:00
abs_path:
default: 默认
path: 文件相对路径
Returns: 文件绝对路径
"""
2024-03-30 19:24:09 +08:00
return _resource_data.get(path, default) if not abs_path else os.path.abspath(_resource_data.get(path, default))