Initial Commit
This commit is contained in:
commit
db452cb3f0
9 changed files with 398 additions and 0 deletions
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
*.snbt
|
||||
lib/
|
||||
lib64/
|
||||
lib64
|
||||
share/
|
||||
bin/
|
||||
out/
|
||||
__pycache__/
|
||||
3
.vscode/settings.json
vendored
Normal file
3
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"python.analysis.typeCheckingMode": "basic"
|
||||
}
|
||||
10
README.md
Normal file
10
README.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
# FTBQ2ADV
|
||||
|
||||
I'll write this eventually. It's 1AM.
|
||||
|
||||
Python >= 3.9 pls
|
||||
|
||||
Usage:
|
||||
|
||||
1. `pip install -r requirements.txt`
|
||||
2. `python main.py --input <YOUR SNBT FILE> --namespace <the namespace these advancements are for>`
|
||||
3
pyvenv.cfg
Normal file
3
pyvenv.cfg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
home = /usr/bin
|
||||
include-system-site-packages = false
|
||||
version = 3.8.10
|
||||
21
requirements.txt
Normal file
21
requirements.txt
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
astroid==2.15.0
|
||||
black==23.1.0
|
||||
click==8.1.3
|
||||
colorama==0.4.6
|
||||
dill==0.3.6
|
||||
isort==5.12.0
|
||||
lazy-object-proxy==1.9.0
|
||||
mccabe==0.7.0
|
||||
mypy-extensions==1.0.0
|
||||
nbtlib==2.0.4
|
||||
numpy==1.24.2
|
||||
packaging==23.0
|
||||
pathspec==0.11.1
|
||||
platformdirs==3.1.1
|
||||
pylint==2.17.1
|
||||
pytoolconfig==1.2.5
|
||||
rope==1.7.0
|
||||
tomli==2.0.1
|
||||
tomlkit==0.11.6
|
||||
typing-extensions==4.5.0
|
||||
wrapt==1.15.0
|
||||
82
src/main.py
Normal file
82
src/main.py
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
"""
|
||||
AUTHOR: Jose Stovall | oitsjustjose@git
|
||||
LICENSE: MIT
|
||||
"""
|
||||
import codecs
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
from colorama import Fore
|
||||
|
||||
from param_parser import CommandlineConfigParser
|
||||
from quest_utils import Advancement
|
||||
from snbt_fixer import get_fixed_snbt_dict
|
||||
|
||||
Json: type = Dict[str, Any]
|
||||
|
||||
|
||||
def main(parmesan: CommandlineConfigParser) -> None:
|
||||
"""Main func which uses the confparser to build adv. JSONs from a quest SNBT"""
|
||||
infile = parmesan.get_argument("input")
|
||||
namespace = parmesan.get_argument("namespace") or "minecraft"
|
||||
|
||||
data = get_fixed_snbt_dict(infile)
|
||||
|
||||
idmp = build_id_filename_mapping(data)
|
||||
for quest in data["quests"]:
|
||||
advancement = create_adv_from_quest(quest, namespace, idmp)
|
||||
with codecs.open(
|
||||
f'./out/{idmp[quest["id"]]}.json', "w", "utf-8"
|
||||
) as file_handle:
|
||||
data_as_str = (
|
||||
json.dumps(advancement, indent=2)
|
||||
# Fix \\& -> \\§ -> &
|
||||
.replace("\\\\\\u00a7", "&")
|
||||
# Fix \u00a7 -> §
|
||||
.replace("\\u00a7", "§")
|
||||
)
|
||||
file_handle.write(data_as_str)
|
||||
|
||||
|
||||
def create_adv_from_quest(quest: Json, namespace: str, idmp: Dict[str, str]) -> Json:
|
||||
"""Creates an advancement from a singular quest"""
|
||||
adv = Advancement(quest, namespace, idmp)
|
||||
if not adv.is_valid():
|
||||
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}"
|
||||
)
|
||||
return adv.to_json()
|
||||
|
||||
|
||||
def build_id_filename_mapping(data: Json) -> Dict[str, str]:
|
||||
"""Creates a mapping of FTB Quest Id to the filename generated by yours truly"""
|
||||
id_to_filename_mapping: Dict[str, str] = {}
|
||||
|
||||
for quest in data["quests"]:
|
||||
file_name_root: str = f"{quest['id']}"
|
||||
# user-defined title
|
||||
if "title" in quest:
|
||||
try: # some titles are json colored
|
||||
file_name_root: str = json.loads(quest["title"])["text"]
|
||||
except json.decoder.JSONDecodeError:
|
||||
file_name_root = quest["title"]
|
||||
else:
|
||||
for task in quest["tasks"]:
|
||||
if task["item"]:
|
||||
file_name_root: str = task["item"].split(":")[1]
|
||||
break
|
||||
file_name_root: str = file_name_root.replace(" ", "_").replace("-", "_").lower()
|
||||
id_to_filename_mapping[quest["id"]] = file_name_root
|
||||
return id_to_filename_mapping
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not os.path.exists("./out"):
|
||||
os.mkdir("./out")
|
||||
|
||||
main(
|
||||
CommandlineConfigParser(
|
||||
required_args={"input": str}, optional_args={"namespace": str}
|
||||
)
|
||||
)
|
||||
103
src/param_parser.py
Normal file
103
src/param_parser.py
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
"""
|
||||
AUTHOR: Jose Stovall | oitsjustjose@git
|
||||
LICENSE: MIT
|
||||
"""
|
||||
import sys
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from colorama import Fore
|
||||
|
||||
|
||||
class CommandlineConfigParser:
|
||||
def __init__(
|
||||
self,
|
||||
required_args: Dict[str, Any],
|
||||
optional_args: Dict[str, Any] = {},
|
||||
singleflags: List[str] = [],
|
||||
) -> None:
|
||||
# Saved for future querying
|
||||
self.__args: Dict[str, Any] = {}
|
||||
# Unknown args will be marked as junk and printed later.
|
||||
self.__junk: Dict[str, Any] = {}
|
||||
|
||||
for arg in sys.argv[1:]:
|
||||
# Case for \-[a-zA-Z],
|
||||
if (
|
||||
arg.startswith("-")
|
||||
and not arg.startswith("--")
|
||||
and arg[1:] in singleflags
|
||||
):
|
||||
self.__args[arg[1:]] = True
|
||||
elif arg.startswith("--"): # arg is a key
|
||||
plain_arg = arg[2:]
|
||||
if plain_arg in required_args or plain_arg in optional_args:
|
||||
self.__args[plain_arg] = None
|
||||
else: # it's a junk param, but don't trash it
|
||||
self.__junk[plain_arg] = None
|
||||
else: # arg is a val
|
||||
# get last unintialized arg and set it
|
||||
k = self.__get_last_key(self.__args)
|
||||
if not k:
|
||||
continue
|
||||
# Last key is uninitialized, must be it
|
||||
if self.__args[k] is None:
|
||||
argtype = str
|
||||
if k in required_args:
|
||||
argtype = required_args[k]
|
||||
elif k in optional_args:
|
||||
argtype = optional_args[k]
|
||||
self.__args[k] = self.__try_cast(arg, argtype)
|
||||
else: # It's junk, no attempted dyncasting
|
||||
k = self.__get_last_key(self.__junk)
|
||||
self.__junk[k] = arg
|
||||
self.__validate(required_args, optional_args, singleflags)
|
||||
|
||||
def get_argument(self, key: str) -> Any:
|
||||
try:
|
||||
return self.__args[key]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
def get_all_args(self) -> Dict[str, Any]:
|
||||
return self.__args
|
||||
|
||||
def __validate(self, required, optional, single):
|
||||
for key in required:
|
||||
if key not in self.__args:
|
||||
print(f"{Fore.RED}[!] Missing required parameter --{key}{Fore.RESET}")
|
||||
sys.exit(0)
|
||||
for key in optional:
|
||||
if key not in self.__args:
|
||||
print(
|
||||
f"{Fore.LIGHTBLACK_EX}[i] Optional key {key} missing from args{Fore.RESET}"
|
||||
)
|
||||
for key in single:
|
||||
if key not in self.__args:
|
||||
print(
|
||||
f"{Fore.LIGHTBLACK_EX}[i] Optional key {key} missing from args{Fore.RESET}"
|
||||
)
|
||||
for key in self.__junk:
|
||||
print(
|
||||
f"{Fore.YELLOW}Unrecognized key {key} was provided. Ignoring.{Fore.RESET}"
|
||||
)
|
||||
|
||||
def __get_last_key(self, dict_in: Dict[str, Any]) -> str:
|
||||
k = ""
|
||||
for key in dict_in:
|
||||
k = key
|
||||
return k
|
||||
|
||||
def __try_cast(self, var: Any, t: Any) -> Any:
|
||||
try:
|
||||
return t(var)
|
||||
except (TypeError, ValueError):
|
||||
print(f"'{var}' could not be cast to type {t}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cls = CommandlineConfigParser(
|
||||
required_args={"passcode": int},
|
||||
optional_args={"beans": bool},
|
||||
singleflags=["shmeef"],
|
||||
)
|
||||
130
src/quest_utils.py
Normal file
130
src/quest_utils.py
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
"""
|
||||
AUTHOR: Jose Stovall | oitsjustjose@git
|
||||
LICENSE: MIT
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, Union
|
||||
|
||||
from colorama import Fore
|
||||
|
||||
Quest: type = Dict[str, Any]
|
||||
|
||||
|
||||
class Advancement:
|
||||
"""An advancement as made from an FTB Quest"""
|
||||
|
||||
def __init__(self, quest: Quest, namespace: str, id_map: Dict[str, str]):
|
||||
"""
|
||||
Creates an Advancement from a Quest, Namespace and Mapping of
|
||||
Quest ID -> Advancement Filename
|
||||
"""
|
||||
self.__quest = quest
|
||||
self.__namespace = namespace
|
||||
self.__idmp = id_map
|
||||
|
||||
def get_parent(self) -> str:
|
||||
"""
|
||||
Gets the parent for a self.__quest with a given ID mapping.
|
||||
Returns <self.__namespace>:root as fallback
|
||||
"""
|
||||
if "dependencies" in self.__quest and self.__quest["dependencies"]:
|
||||
for dep in self.__quest["dependencies"]:
|
||||
if dep in self.__idmp:
|
||||
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"
|
||||
|
||||
def get_title(self) -> Union[str, Dict[str, Any]]:
|
||||
"""
|
||||
Attempts to get the title of a self.__quest.
|
||||
Returns the self.__quest ID as fallback
|
||||
"""
|
||||
if "title" in self.__quest:
|
||||
try: # some titles are json colored
|
||||
return json.loads(self.__quest["title"])
|
||||
except json.decoder.JSONDecodeError:
|
||||
return self.__quest["title"]
|
||||
else: # attempt to salvage name by fancifying the unloc name
|
||||
for task in self.__quest["tasks"]:
|
||||
if "item" in task and isinstance(task["item"], str):
|
||||
name = task["item"].split(":")[1].split("_")
|
||||
name = " ".join(map(lambda x: x[0].upper() + x[1:], name))
|
||||
return name
|
||||
print(
|
||||
f"{Fore.YELLOW}[i] Failed to detect advancement name from self.__quest {self.__quest['id']}{Fore.RESET}"
|
||||
)
|
||||
return f"{self.__quest['id']}"
|
||||
|
||||
def get_icon_item(self) -> str:
|
||||
"""
|
||||
Attempts to get the icon item from a self.__quest's icon or its dependencies.
|
||||
Returns 'minecraft:air' as fallback
|
||||
"""
|
||||
# Icon is manually specified for self.__quest. Easy money
|
||||
if "icon" in self.__quest:
|
||||
return self.__quest["icon"]
|
||||
for task in self.__quest["tasks"]:
|
||||
if "item" in task and isinstance(task["item"], str):
|
||||
return task["item"]
|
||||
if "icon" in task and isinstance(task["icon"], str):
|
||||
return task["icon"]
|
||||
return "minecraft:air"
|
||||
|
||||
def get_description(self) -> str:
|
||||
"""
|
||||
Attempts to build the description (and fix FTBself.__quests's whack formatting)
|
||||
Returns Empty String as fallback
|
||||
"""
|
||||
if "description" in self.__quest:
|
||||
return (
|
||||
" ".join(self.__quest["description"])
|
||||
.replace("&", "§")
|
||||
.replace(" ", " ")
|
||||
)
|
||||
return ""
|
||||
|
||||
def get_criteria(self) -> str:
|
||||
"""
|
||||
Attempts to get the criteria item (only the first one) from the quest
|
||||
Advanced critiera such as and|or *might* come soon, but I didn't need this personally
|
||||
Returns 'minecraft:air' as default
|
||||
"""
|
||||
for task in self.__quest["tasks"]:
|
||||
if "item" in task and isinstance(task["item"], str):
|
||||
# yes, [task["item"]] is correct because the task expects multiple items
|
||||
return task["item"]
|
||||
return "minecraft:air"
|
||||
|
||||
def is_valid(self) -> bool:
|
||||
"""Verifies that self is valid and doesn't have any unintended defaults"""
|
||||
if self.get_parent() == "minecraft:root":
|
||||
return False
|
||||
if self.get_icon_item() == "minecraft:air":
|
||||
return False
|
||||
if self.get_title() == self.__quest["id"]:
|
||||
return False
|
||||
if not self.get_description():
|
||||
return False
|
||||
return self.get_criteria() != "minecraft:air"
|
||||
|
||||
def to_json(self) -> Dict[str, Any]:
|
||||
"""Returns self as json"""
|
||||
return {
|
||||
"parent": self.get_parent(),
|
||||
"display": {
|
||||
"icon": {"item": self.get_icon_item()},
|
||||
"title": {"text": self.get_title()},
|
||||
"description": {"text": self.get_description()},
|
||||
},
|
||||
"criteria": {
|
||||
"0": {
|
||||
"conditions": {"items": [{"items": [[self.get_criteria()]]}]},
|
||||
"trigger": "minecraft:inventory_changed",
|
||||
}
|
||||
},
|
||||
"requirements": [["0"]],
|
||||
}
|
||||
38
src/snbt_fixer.py
Normal file
38
src/snbt_fixer.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"""
|
||||
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