Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use serializable config & add multi folder support #1

Merged
merged 7 commits into from
Sep 26, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ A MCDR plugin to help you update region files in game

`!!region list` 列出待更新的区域文件 / list all added region files

`!!region history` 输出上一次update的结果 / print the result of the lastest update
`!!region history` 输出上一次update的结果 / print the result of the latest update

`!!region update` 更新列表中的区域文件,这将重启服务器 / update all selected region files, which will restart the server

Expand All @@ -40,5 +40,28 @@ A MCDR plugin to help you update region files in game

# 例子 / Sample

`!!region add 0 3 2` 添加主世界的r.3.2.mca至更新列表 / add overworld's r.3.2.mca to the updating list
`!!region add 0 3 2` 添加主世界的r.3.2.mca至更新列表 / add overworld 's r.3.2.mca to the updating list
401U marked this conversation as resolved.
Show resolved Hide resolved

# 配置 / Config

1.17+ 的存档中, 实体相关数据被单独存储到之前的区块数据之外

可以修改配置项 `dimension_region_folder` 如下, 来让实体数据在更新时也进行同步

For 1.17+, the entities data was saved in an specified folder outside region folder.

You can modify the config `dimension_region_folder` to make entities sync during region update

```json5
{
"enabled": true,
"source_world_directory": "./qb_multi/slot1/world",
"destination_world_directory": "./server/world",
"dimension_region_folder": {
"-1": ["DIM-1/region", "DIM-1/entities"],
"0": ["region", "entities"],
"1": ["DIM1/region", "DIM1/entities"]
}
}
```

7 changes: 5 additions & 2 deletions mcdreforged.plugin.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
{
"id": "region_file_updater",
"version": "1.4.1",
"version": "1.4.2",
401U marked this conversation as resolved.
Show resolved Hide resolved
"name": "Region file Updater",
"description": {
"en_us": "A MCDR plugin to help you update region files in game",
"zh_cn": "一个从指定位置拉取region文件至本服存档的插件"
},
"author": "Fallen_Breath",
"author": [
"Fallen_Breath",
"YehowahLiu"
401U marked this conversation as resolved.
Show resolved Hide resolved
],
"link": "https://github.com/TISUnion/RegionFileUpdater",
"dependencies": {
"minecraft_data_api": "*"
Expand Down
66 changes: 38 additions & 28 deletions region_file_updater/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
# -*- coding: utf-8 -*-
import json
import os
import shutil
import time
from json import JSONDecodeError
from typing import List, Tuple, Callable, Any, Optional
from typing import Dict, Iterable, List, Tuple, Optional, Union

from mcdreforged.api.all import *

PLUGIN_METADATA = ServerInterface.get_instance().as_plugin_server_interface().get_self_metadata()
config = {
'enabled': True,
'source_world_directory': './qb_multi/slot1/world',
'destination_world_directory': './server/world',
'dimension_region_folder': {


class Config(Serializable):
enabled: bool = True,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SyntaxError due to the , here

source_world_directory: str = './qb_multi/slot1/world'
destination_world_directory: str = './server/world'
dimension_region_folder: Dict[str, Union[str, List[str]]] = {
'-1': 'DIM-1/region',
'0': 'region',
'1': 'DIM1/region'
}
}
DEFAULT_CONFIG = config.copy()
CONFIG_FILE_PATH = os.path.join('config', '{}.json'.format(PLUGIN_METADATA.id))


config: Optional[Config] = None
Prefix = '!!region'
PluginName = PLUGIN_METADATA.name
LogFilePath = os.path.join('logs', '{}.log'.format(PluginName))
Expand Down Expand Up @@ -58,8 +57,17 @@ def __init__(self, x: int, z: int, dim: int):
def to_file_name(self):
return 'r.{}.{}.mca'.format(self.x, self.z)

def to_file_path(self):
return os.path.join(config['dimension_region_folder'][str(self.dim)], self.to_file_name())
def to_file_list(self):
file_list = []
folders = config.dimension_region_folder[str(self.dim)]
if isinstance(folders, str):
file_list.append(os.path.join(folders, self.to_file_name()))
elif isinstance(folders, Iterable):
for folder in folders:
file_list.append(os.path.join(folder, self.to_file_name()))
else:
pass
return file_list

def __eq__(self, other):
if not isinstance(other, type(self)):
Expand Down Expand Up @@ -148,19 +156,20 @@ def region_update(source: CommandSource):
print_log(source.get_server(), '{} 更新了 {} 个区域文件:'.format(source, len(regionList)))
historyList.clear()
for region in regionList:
source_dir = os.path.join(config['source_world_directory'], region.to_file_path())
destination = os.path.join(config['destination_world_directory'], region.to_file_path())
try:
source.get_server().logger.info('- "{}" -> "{}"'.format(source_dir, destination))
shutil.copyfile(source_dir, destination)
except Exception as e:
msg = '失败,错误信息:{}'.format(str(e))
flag = False
else:
msg = '成功'
flag = True
historyList.append((region, flag))
print_log(source.get_server(), ' {}: {}'.format(region, msg))
for region_file in region.to_file_list():
source_dir = os.path.join(config.source_world_directory, region_file)
destination = os.path.join(config.destination_world_directory, region_file)
try:
source.get_server().logger.info('- "{}" -> "{}"'.format(source_dir, destination))
shutil.copyfile(source_dir, destination)
except Exception as e:
msg = '失败,错误信息:{}'.format(str(e))
flag = False
else:
msg = '成功'
flag = True
historyList.append((region, flag))
print_log(source.get_server(), ' {}: {}'.format(region, msg))

regionList.clear()
time.sleep(1)
Expand All @@ -184,7 +193,8 @@ def on_load(server: PluginServerInterface, old):

def load_config(source: Optional[CommandSource]):
global config, server_inst
config = server_inst.load_config_simple(CONFIG_FILE_PATH, DEFAULT_CONFIG, in_data_folder=False, source_to_reply=source, echo_in_console=False)
config_file_path = os.path.join('config', '{}.json'.format(PLUGIN_METADATA.id))
config = server_inst.load_config_simple(config_file_path, in_data_folder=False, source_to_reply=source, echo_in_console=False, target_class=Config)


def reload_config(source: CommandSource):
Expand Down Expand Up @@ -213,7 +223,7 @@ def get_region_parm_node(callback):
then(Literal('history').runs(show_history)).
then(
Literal('update').
requires(lambda: config['enabled']).
requires(lambda: config.enabled).
on_error(RequirementNotMet, lambda src: src.reply('{}未启用!请在配置文件中开启'.format(PLUGIN_METADATA.name)), handled=True).
runs(region_update)
).
Expand Down