Use SNBTLib to support files out of the box
This commit is contained in:
parent
db452cb3f0
commit
553f8654c2
4 changed files with 61 additions and 58 deletions
|
|
@ -7,7 +7,6 @@ isort==5.12.0
|
||||||
lazy-object-proxy==1.9.0
|
lazy-object-proxy==1.9.0
|
||||||
mccabe==0.7.0
|
mccabe==0.7.0
|
||||||
mypy-extensions==1.0.0
|
mypy-extensions==1.0.0
|
||||||
nbtlib==2.0.4
|
|
||||||
numpy==1.24.2
|
numpy==1.24.2
|
||||||
packaging==23.0
|
packaging==23.0
|
||||||
pathspec==0.11.1
|
pathspec==0.11.1
|
||||||
|
|
@ -15,6 +14,7 @@ platformdirs==3.1.1
|
||||||
pylint==2.17.1
|
pylint==2.17.1
|
||||||
pytoolconfig==1.2.5
|
pytoolconfig==1.2.5
|
||||||
rope==1.7.0
|
rope==1.7.0
|
||||||
|
snbtlib==0.0.6
|
||||||
tomli==2.0.1
|
tomli==2.0.1
|
||||||
tomlkit==0.11.6
|
tomlkit==0.11.6
|
||||||
typing-extensions==4.5.0
|
typing-extensions==4.5.0
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ LICENSE: MIT
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from typing import Any, Dict, Union
|
from typing import Any, Dict, Union, List
|
||||||
|
|
||||||
from colorama import Fore
|
from colorama import Fore
|
||||||
|
|
||||||
|
|
@ -32,10 +32,6 @@ class Advancement:
|
||||||
for dep in self.__quest["dependencies"]:
|
for dep in self.__quest["dependencies"]:
|
||||||
if dep in self.__idmp:
|
if dep in self.__idmp:
|
||||||
return f"{self.__namespace}:{self.__idmp[dep]}"
|
return f"{self.__namespace}:{self.__idmp[dep]}"
|
||||||
q_nm = self.get_title()
|
|
||||||
print(
|
|
||||||
f"{Fore.YELLOW}[i] Failed to detect parent for self.__quest {q_nm}{Fore.RESET}"
|
|
||||||
)
|
|
||||||
return f"{self.__namespace}:root"
|
return f"{self.__namespace}:root"
|
||||||
|
|
||||||
def get_title(self) -> Union[str, Dict[str, Any]]:
|
def get_title(self) -> Union[str, Dict[str, Any]]:
|
||||||
|
|
@ -45,7 +41,7 @@ class Advancement:
|
||||||
"""
|
"""
|
||||||
if "title" in self.__quest:
|
if "title" in self.__quest:
|
||||||
try: # some titles are json colored
|
try: # some titles are json colored
|
||||||
return json.loads(self.__quest["title"])
|
return json.loads(self.__quest["title"].replace('\\"', '"'))
|
||||||
except json.decoder.JSONDecodeError:
|
except json.decoder.JSONDecodeError:
|
||||||
return self.__quest["title"]
|
return self.__quest["title"]
|
||||||
else: # attempt to salvage name by fancifying the unloc name
|
else: # attempt to salvage name by fancifying the unloc name
|
||||||
|
|
@ -99,17 +95,55 @@ class Advancement:
|
||||||
return task["item"]
|
return task["item"]
|
||||||
return "minecraft:air"
|
return "minecraft:air"
|
||||||
|
|
||||||
def is_valid(self) -> bool:
|
def get_validation_errors(self) -> List[str]:
|
||||||
"""Verifies that self is valid and doesn't have any unintended defaults"""
|
"""
|
||||||
|
Verifies that self is valid and doesn't have any unintended defaults
|
||||||
|
Returns a string list of individual validation errors
|
||||||
|
"""
|
||||||
|
ret: List[str] = []
|
||||||
if self.get_parent() == "minecraft:root":
|
if self.get_parent() == "minecraft:root":
|
||||||
return False
|
ret.append("Parent could not be determined. Defaulted to 'minecraft:root'")
|
||||||
if self.get_icon_item() == "minecraft:air":
|
if self.get_icon_item() == "minecraft:air":
|
||||||
return False
|
ret.append("Icon could not be determined. Defaulted to 'minecraft:air")
|
||||||
if self.get_title() == self.__quest["id"]:
|
if self.get_title() == self.__quest["id"]:
|
||||||
return False
|
ret.append(
|
||||||
|
f"Advancement Name could not be determined. Defaulted to '{self.__quest['id']}'"
|
||||||
|
)
|
||||||
if not self.get_description():
|
if not self.get_description():
|
||||||
return False
|
ret.append("Description could not be parsed. Defaulted to ''")
|
||||||
return self.get_criteria() != "minecraft:air"
|
if self.get_criteria() == "minecraft:air":
|
||||||
|
# Determine the root of the issue
|
||||||
|
if "tasks" not in self.__quest:
|
||||||
|
ret.append("Quest has no tasks. Defaulted Criteria to 'minecraft:air'")
|
||||||
|
else:
|
||||||
|
has_normal_item = False
|
||||||
|
has_non_item = False
|
||||||
|
has_complex_item = False
|
||||||
|
for task in self.__quest["tasks"]:
|
||||||
|
if "item" not in task:
|
||||||
|
has_non_item = True
|
||||||
|
elif isinstance(task["item"], str):
|
||||||
|
has_normal_item = True
|
||||||
|
else:
|
||||||
|
has_complex_item = True
|
||||||
|
|
||||||
|
if not has_normal_item: # is immediately invalid
|
||||||
|
if has_non_item:
|
||||||
|
if (
|
||||||
|
has_complex_item
|
||||||
|
): # Has mix of Non-Item tasks and Tasks with NBT
|
||||||
|
ret.append(
|
||||||
|
"Quest only has mix of Task(s) with Complex Items with NBT and Non-Item-Based Tasks. Defaulted Criteria to 'minecraft:air'"
|
||||||
|
)
|
||||||
|
else: # Only has Non-Item Tasks
|
||||||
|
ret.append(
|
||||||
|
"Quest only has Task(s) which are Non-Item-Based. Defaulted Criteria to 'minecraft:air'"
|
||||||
|
)
|
||||||
|
elif has_complex_item: # Only has NBT Item Tasks
|
||||||
|
ret.append(
|
||||||
|
"Quest only has Task(s) which contain Items that specify NBT. Defaulted Criteria to 'minecraft:air'"
|
||||||
|
)
|
||||||
|
return ret
|
||||||
|
|
||||||
def to_json(self) -> Dict[str, Any]:
|
def to_json(self) -> Dict[str, Any]:
|
||||||
"""Returns self as json"""
|
"""Returns self as json"""
|
||||||
19
src/main.py
19
src/main.py
|
|
@ -7,11 +7,11 @@ import json
|
||||||
import os
|
import os
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
import snbtlib
|
||||||
from colorama import Fore
|
from colorama import Fore
|
||||||
|
|
||||||
|
from advancement import Advancement
|
||||||
from param_parser import CommandlineConfigParser
|
from param_parser import CommandlineConfigParser
|
||||||
from quest_utils import Advancement
|
|
||||||
from snbt_fixer import get_fixed_snbt_dict
|
|
||||||
|
|
||||||
Json: type = Dict[str, Any]
|
Json: type = Dict[str, Any]
|
||||||
|
|
||||||
|
|
@ -21,7 +21,8 @@ def main(parmesan: CommandlineConfigParser) -> None:
|
||||||
infile = parmesan.get_argument("input")
|
infile = parmesan.get_argument("input")
|
||||||
namespace = parmesan.get_argument("namespace") or "minecraft"
|
namespace = parmesan.get_argument("namespace") or "minecraft"
|
||||||
|
|
||||||
data = get_fixed_snbt_dict(infile)
|
with open(infile, "r", encoding="utf-8") as file_handle:
|
||||||
|
data: Json = snbtlib.loads(file_handle.read()) # type: ignore
|
||||||
|
|
||||||
idmp = build_id_filename_mapping(data)
|
idmp = build_id_filename_mapping(data)
|
||||||
for quest in data["quests"]:
|
for quest in data["quests"]:
|
||||||
|
|
@ -42,10 +43,14 @@ def main(parmesan: CommandlineConfigParser) -> None:
|
||||||
def create_adv_from_quest(quest: Json, namespace: str, idmp: Dict[str, str]) -> Json:
|
def create_adv_from_quest(quest: Json, namespace: str, idmp: Dict[str, str]) -> Json:
|
||||||
"""Creates an advancement from a singular quest"""
|
"""Creates an advancement from a singular quest"""
|
||||||
adv = Advancement(quest, namespace, idmp)
|
adv = Advancement(quest, namespace, idmp)
|
||||||
if not adv.is_valid():
|
errors = adv.get_validation_errors()
|
||||||
|
if errors:
|
||||||
|
print(f"\n{'-'*os.get_terminal_size().columns}\n")
|
||||||
print(
|
print(
|
||||||
f"{Fore.YELLOW}FTB Quest with ID {quest['id']} (in {idmp[quest['id']]}.json) has validation errors. Still creating advancement but requires manual verification{Fore.RESET}"
|
f"{Fore.YELLOW}[i] Validation Errors for Quest '{idmp[quest['id']]}' were found:{Fore.RESET}"
|
||||||
)
|
)
|
||||||
|
for error in errors:
|
||||||
|
print(f" • {error}")
|
||||||
return adv.to_json()
|
return adv.to_json()
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -58,7 +63,9 @@ def build_id_filename_mapping(data: Json) -> Dict[str, str]:
|
||||||
# user-defined title
|
# user-defined title
|
||||||
if "title" in quest:
|
if "title" in quest:
|
||||||
try: # some titles are json colored
|
try: # some titles are json colored
|
||||||
file_name_root: str = json.loads(quest["title"])["text"]
|
file_name_root: str = json.loads(quest["title"].replace('\\"', '"'))[
|
||||||
|
"text"
|
||||||
|
]
|
||||||
except json.decoder.JSONDecodeError:
|
except json.decoder.JSONDecodeError:
|
||||||
file_name_root = quest["title"]
|
file_name_root = quest["title"]
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
"""
|
|
||||||
AUTHOR: Jose Stovall | oitsjustjose@git
|
|
||||||
LICENSE: MIT
|
|
||||||
"""
|
|
||||||
|
|
||||||
from typing import Any, Dict
|
|
||||||
|
|
||||||
import nbtlib
|
|
||||||
import snbtlib
|
|
||||||
|
|
||||||
|
|
||||||
def get_fixed_snbt_dict(file_path: str) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
FTB Quests doesn't properly use Commas when saving their SNBT (idiots)
|
|
||||||
This script properly inserts them again
|
|
||||||
"""
|
|
||||||
|
|
||||||
with open(file_path, "r", encoding="utf-8") as f_handle:
|
|
||||||
data = f_handle.readlines()
|
|
||||||
# Iterate over all rows, checking to see if a comma might go here
|
|
||||||
# This will place excess commas in cases of ]}, }], etc. Clean up later
|
|
||||||
for idx, row in enumerate(data):
|
|
||||||
clean = row.replace("\n", "").replace("\t", "")
|
|
||||||
if clean.endswith("{") or clean.endswith("["):
|
|
||||||
continue
|
|
||||||
data[idx] = f"{clean},"
|
|
||||||
|
|
||||||
as_str = " ".join(data)
|
|
||||||
as_str = as_str.replace("], ", "],")
|
|
||||||
as_str = as_str.replace("}, ", "},")
|
|
||||||
for sym1 in ["}", "]"]:
|
|
||||||
for sym2 in ["}", "]"]:
|
|
||||||
as_str = as_str.replace(f"{sym1},{sym2}", f"{sym1}{sym2}")
|
|
||||||
as_str = as_str[: len(as_str) - 1]
|
|
||||||
|
|
||||||
snbt = snbtlib.loads(as_str)
|
|
||||||
snbt: Dict[str, Any] = snbt
|
|
||||||
return snbt
|
|
||||||
Loading…
Reference in a new issue