197 lines
6.8 KiB
Python
197 lines
6.8 KiB
Python
import json
|
|
import shutil
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
|
|
@dataclass
|
|
class ModpackInfo:
|
|
name: str
|
|
version: str
|
|
|
|
|
|
@dataclass
|
|
class Paths:
|
|
is_modrinth: bool
|
|
this_dir: Path
|
|
config: Path
|
|
activepath: Path
|
|
activepath_zip: Path
|
|
|
|
@staticmethod
|
|
def create(file: Path):
|
|
this_dir = Path(__file__).parent.resolve()
|
|
ap = this_dir.joinpath("activepack").resolve()
|
|
|
|
return Paths(
|
|
is_modrinth=file.suffix == ".mrpack",
|
|
this_dir=this_dir,
|
|
config=this_dir.joinpath("configuration.json").resolve(),
|
|
activepath=ap,
|
|
activepath_zip=ap.with_suffix(file.suffix).resolve(),
|
|
)
|
|
|
|
def clean(self):
|
|
if self.activepath.exists():
|
|
shutil.rmtree(self.activepath)
|
|
if self.activepath_zip.exists():
|
|
self.activepath_zip.unlink()
|
|
|
|
|
|
class Processor: # TODO: we need Prism native pack support too
|
|
def __init__(self, pack_path: Path):
|
|
self.pack_path = pack_path
|
|
self.paths = Paths.create(pack_path)
|
|
self.step = "Copy Pack to Temp Dir & Unzip It"
|
|
|
|
# Read in the config
|
|
with open(self.paths.config, "r", encoding="utf-8") as fh:
|
|
self.config = json.loads(fh.read())
|
|
|
|
def override(self, path: Path) -> Path:
|
|
"""Unlinks / rmtrees a path if it exists, then returns it"""
|
|
if path.exists():
|
|
if path.is_dir():
|
|
shutil.rmtree(path)
|
|
else:
|
|
path.unlink()
|
|
return path
|
|
|
|
def run(self) -> None:
|
|
"""Common staging steps between both packs"""
|
|
# Copy the original file to ./activepack.[mrpack|zip]
|
|
shutil.copy(self.pack_path, self.paths.activepath_zip)
|
|
shutil.unpack_archive(self.paths.activepath_zip, self.paths.activepath, "zip")
|
|
print(f"✅ {self.step}")
|
|
|
|
self.step = "Clean up files we don't want to ship"
|
|
for p in [f"overrides/{x}" for x in self.config["remove"]]:
|
|
rm_path = self.paths.activepath.joinpath(p)
|
|
if not rm_path.exists():
|
|
continue
|
|
if rm_path.is_dir():
|
|
shutil.rmtree(rm_path)
|
|
print(f" 🗑️ 📁 {rm_path.name}")
|
|
else:
|
|
rm_path.unlink()
|
|
print(f" 🗑️ {rm_path.name}")
|
|
print(f"✅ {self.step}")
|
|
|
|
def post_run(self) -> None:
|
|
"""Common post-run staging steps between both types"""
|
|
info = self.get_pack_info()
|
|
|
|
# Always use .zip, shutil.make_archive has no clue what an mrpack is
|
|
self.step = "Re-archive the modified, cleaned up pack"
|
|
out_file = self.override(self.paths.this_dir.joinpath(f"{info.name} {info.version}.zip").resolve())
|
|
shutil.make_archive(out_file.with_suffix("").name, "zip", self.paths.activepath)
|
|
print(f"✅ {self.step}")
|
|
|
|
self.step = "Clean up unzipped pack and rename to mrpack if necessary"
|
|
shutil.rmtree(self.paths.activepath)
|
|
out_file = out_file.rename(self.override(out_file.with_suffix(self.pack_path.suffix)))
|
|
print(f"✅ {self.step}")
|
|
|
|
self.step = "Move re-packed modpack to the original pack's directory"
|
|
final_output = self.pack_path.parent.joinpath(out_file.name).resolve()
|
|
if final_output.exists():
|
|
final_output.unlink()
|
|
|
|
shutil.move(out_file, final_output)
|
|
self.paths.clean()
|
|
print("🎉 Done! Successfully cleaned modpack!")
|
|
|
|
def get_pack_info(self) -> ModpackInfo:
|
|
"""Common method for getting pack info in general"""
|
|
manifest_path = self.paths.activepath.joinpath("manifest.json").resolve()
|
|
with open(manifest_path, "r", encoding="utf-8") as fh:
|
|
manifest = json.loads(fh.read())
|
|
return ModpackInfo(manifest["name"], manifest["version"])
|
|
|
|
|
|
class ModrinthProcessor(Processor):
|
|
def __init__(self, pack_path: Path):
|
|
super().__init__(pack_path)
|
|
|
|
def run(self):
|
|
super().run()
|
|
self.post_run()
|
|
|
|
def get_pack_info(self) -> ModpackInfo:
|
|
"""Uses modrinth.index.json instead of manifest.json, and versionId instead of version"""
|
|
manifest_path = self.paths.activepath.joinpath("modrinth.index.json").resolve()
|
|
with open(manifest_path, "r", encoding="utf-8") as fh:
|
|
manifest = json.loads(fh.read())
|
|
return ModpackInfo(manifest["name"], manifest["versionId"])
|
|
|
|
|
|
class CurseForgeProcessor(Processor):
|
|
def __init__(self, pack_path: Path):
|
|
super().__init__(pack_path)
|
|
|
|
def run(self):
|
|
super().run()
|
|
self.__patch_neo_compat()
|
|
self.post_run()
|
|
|
|
def __patch_neo_compat(self):
|
|
"""Fixes an issue with CurseForge exports from Prism that makes them
|
|
incompatible with the CurseForge launcher because CurseForge is stupid"""
|
|
self.step = "Patch CurseForge Manifest to be compatible with NeoForge"
|
|
manifest_path = self.paths.activepath.joinpath("manifest.json").resolve()
|
|
if not manifest_path.exists():
|
|
print(f"[CurseForge+NeoForge Compat]: Failed to find a manifest at {manifest_path}")
|
|
return
|
|
|
|
with open(manifest_path, "r") as handle:
|
|
manifest = json.loads(handle.read())
|
|
|
|
if "minecraft" not in manifest:
|
|
print("[CurseForge+NeoForge Compat]: Missing key { minecraft }")
|
|
return
|
|
|
|
if "modLoaders" not in manifest["minecraft"]:
|
|
print("[CurseForge+NeoForge Compat]: Missing key { minecraft.modLoaders }")
|
|
return
|
|
|
|
mc_version = manifest["minecraft"]["version"]
|
|
if mc_version not in ["1.20.1"]:
|
|
return
|
|
|
|
for modloader in manifest["minecraft"]["modLoaders"]:
|
|
if "neo" not in modloader["id"]:
|
|
continue
|
|
|
|
# Other versions might not need this patch, hard to say - 1.20.1 definitely does.
|
|
if mc_version == "1.20.1":
|
|
neo_version = modloader["id"].replace("neoforge-", "")
|
|
modloader["id"] = f"neoforge-{mc_version}-{neo_version}"
|
|
|
|
with open(manifest_path, "w") as handle:
|
|
handle.write(json.dumps(manifest))
|
|
|
|
|
|
def main(og_pack_path_raw: str):
|
|
og_pack_path = Path(og_pack_path_raw).resolve()
|
|
if not og_pack_path.exists():
|
|
raise Exception(f"Failed to find the Pack at {og_pack_path_raw}!")
|
|
|
|
processor = ModrinthProcessor(og_pack_path) if og_pack_path.suffix == ".mrpack" else CurseForgeProcessor(og_pack_path)
|
|
try:
|
|
processor.run()
|
|
except Exception as e:
|
|
# Clean up any paths we made but still raise our exception
|
|
processor.paths.clean()
|
|
print(f"Failure during step [{processor.step}]:")
|
|
raise e
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2:
|
|
print("Missing required parameter: <FILE> (the path to the .mrpack or .zip export)")
|
|
sys.exit(1)
|
|
try:
|
|
main(sys.argv[1])
|
|
except Exception as e:
|
|
print(e)
|