From 2578325a4f5c69b758856b447eaf119f69e32e98 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Wed, 8 Oct 2025 13:23:19 -0500 Subject: [PATCH] Full pack publishing refactor --- minecraft/publishing/Pack Cleanup.bat | 12 ++ minecraft/publishing/main.py | 197 ++++++++++++++++++ .../publishing/neo+/Pack Cleanup (Modern).bat | 12 -- minecraft/publishing/neo+/main.py | 169 --------------- .../pre-neo/Pack Cleanup (Retro).bat | 12 -- minecraft/publishing/pre-neo/main.py | 184 ---------------- minecraft/publishing/pre-neo/requirements.txt | 39 ---- 7 files changed, 209 insertions(+), 416 deletions(-) create mode 100644 minecraft/publishing/Pack Cleanup.bat create mode 100644 minecraft/publishing/main.py delete mode 100644 minecraft/publishing/neo+/Pack Cleanup (Modern).bat delete mode 100644 minecraft/publishing/neo+/main.py delete mode 100644 minecraft/publishing/pre-neo/Pack Cleanup (Retro).bat delete mode 100644 minecraft/publishing/pre-neo/main.py delete mode 100644 minecraft/publishing/pre-neo/requirements.txt diff --git a/minecraft/publishing/Pack Cleanup.bat b/minecraft/publishing/Pack Cleanup.bat new file mode 100644 index 0000000..47a60ac --- /dev/null +++ b/minecraft/publishing/Pack Cleanup.bat @@ -0,0 +1,12 @@ +@echo off + +:loop + +@echo Processing file: %1 +python.exe .\main.py %1 +pause + +shift +if not "%~1"=="" goto loop + +@REM pause \ No newline at end of file diff --git a/minecraft/publishing/main.py b/minecraft/publishing/main.py new file mode 100644 index 0000000..9c83eea --- /dev/null +++ b/minecraft/publishing/main.py @@ -0,0 +1,197 @@ +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: (the path to the .mrpack or .zip export)") + sys.exit(1) + try: + main(sys.argv[1]) + except Exception as e: + print(e) diff --git a/minecraft/publishing/neo+/Pack Cleanup (Modern).bat b/minecraft/publishing/neo+/Pack Cleanup (Modern).bat deleted file mode 100644 index 8d4c000..0000000 --- a/minecraft/publishing/neo+/Pack Cleanup (Modern).bat +++ /dev/null @@ -1,12 +0,0 @@ -@echo off - -:loop - -@echo Processing file: %1 -C:\Users\Jose\AppData\Local\Programs\Python\Python310\python.exe .\main.py %1 -@echo "Done!" - -shift -if not "%~1"=="" goto loop - -@REM pause \ No newline at end of file diff --git a/minecraft/publishing/neo+/main.py b/minecraft/publishing/neo+/main.py deleted file mode 100644 index 0bf33d1..0000000 --- a/minecraft/publishing/neo+/main.py +++ /dev/null @@ -1,169 +0,0 @@ -"""@author Jose Stovall | github.com/oitsjustjose""" - -import json -import shutil -import sys -from dataclasses import dataclass -from pathlib import Path - -IS_MODRINTH = sys.argv[1].endswith(".mrpack") - -THIS_DIR = Path(__file__).parent.resolve() -CONFIG_PATH = THIS_DIR.joinpath("../configuration.json").resolve() - -PACK_UNZIP_PATH = THIS_DIR.joinpath("activepack").resolve() -PACK_ZIP_PATH = PACK_UNZIP_PATH.with_suffix("mrpack" if IS_MODRINTH else "zip").resolve() - - -@dataclass -class ModpackInfo: - name: str - version: str - - -def print(obj) -> None: - """Override the initial print so it goes to a logfile instead!""" - log_nm_base = sys.argv[1].split("\\")[-1] - with open(f"./{log_nm_base}.log", "a+", encoding="utf-8") as log_handle: - log_handle.write(f"{str(obj)}\n") - - -def __cleanup() -> None: - """File and dir cleanup for when the program exits""" - if PACK_ZIP_PATH.exists(): - PACK_ZIP_PATH.unlink() - if PACK_UNZIP_PATH.exists(): - shutil.rmtree(PACK_UNZIP_PATH) - - -def __get_pack_info() -> ModpackInfo: - """ - Gets the modpack info based on the currently unzipped pack - Returns None in the event of any failures - """ - if not PACK_UNZIP_PATH.exists(): - raise Exception(f"[__get_pack_info]: Failed to get Modpack Info: {PACK_UNZIP_PATH} does not exist!") - - manifest_path = PACK_UNZIP_PATH.joinpath("modrinth.index.json" if IS_MODRINTH else "manifest.json").resolve() - - if not manifest_path: - raise Exception("[__get_pack_info]: Failed to get Modpack Info: could not find a valid manifest path!") - - with open(manifest_path, "r") as handle: - manifest = json.loads(handle.read()) - - return ModpackInfo(manifest["name"], manifest["versionId" if IS_MODRINTH else "version"]) - - -def __patch_neo_curse() -> None: - """ - Fixes an issue with CurseForge exports from Prism that makes them incompatible - with the CurseForge launcher because CurseForge is fucking stupid - """ - manifest_path = PACK_UNZIP_PATH.joinpath("manifest.json") - - if not manifest_path.exists(): - print(f"[__patch_neo_curse]: Failed to find manifest at {manifest_path}") - return - - with open(manifest_path, "r") as handle: - manifest = json.loads(handle.read()) - - if "minecraft" not in manifest: - print("[__patch_neo_curse]: Missing key { minecraft }") - return - - if "modLoaders" not in manifest["minecraft"]: - print("[__patch_neo_curse]: Missing key { minecraft.modLoaders }") - return - - mc_version = manifest["minecraft"]["version"] - if mc_version not in ["1.20.1"]: - print(f"[__patch_neo_curse]: Minecraft {mc_version} does not need NeoForge cleanup (or if it does, clean up this script!)") - 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() -> None: - """ - Processing flow (souper crude): - - 1. Load the cleanup config - 2. Open the original zipped file - 3. Iterate through each cleanup config entry (don't forget to path prepend "overrides/"), deleting - 4. Re-zip if necessary? - 5. Profit? - """ - - if len(sys.argv) != 2: - print("Missing 2nd parameter File") - return - - # Copy the original file to ./activepack.[mrpack|zip] - shutil.copy(sys.argv[1], PACK_ZIP_PATH) - print("Copied pack to local dir") - - # Unzip the modpack -- .mrpacks are just glorified zip files too :) - shutil.unpack_archive(PACK_ZIP_PATH, PACK_UNZIP_PATH, "zip") - print("Unarchived pack successfully!") - - # Read in the config if it exists - if it doesn't, early exit - if not CONFIG_PATH.exists(): - print(f"Failed to find configuration at {CONFIG_PATH}") - __cleanup() - return - - with open(CONFIG_PATH, "r") as handle: - config = json.loads(handle.read())["remove"] - - # Prepend the "overrides/" path, remove all files necessary - for target in [f"overrides/{x}" for x in config]: - rm_path = PACK_UNZIP_PATH.joinpath(target) - if not rm_path.exists(): - continue - - if rm_path.is_dir(): - shutil.rmtree(rm_path) - print(f"Removed dir {rm_path}") - else: - rm_path.unlink() - print(f"Removed file {rm_path}") - - # Fix CurseForge packs being pissed about NeoForge :V - if not IS_MODRINTH: - __patch_neo_curse() - - # Zip up the pack & cleanup the old working directory - info = __get_pack_info() - out_file = THIS_DIR.joinpath(f"{info.name} {info.version}").with_suffix(".zip").resolve() - # Zip up the working path into the out_file's folder - shutil.make_archive(out_file.with_suffix("").name, "zip", PACK_UNZIP_PATH) - # Remove the no longer used working path - shutil.rmtree(PACK_UNZIP_PATH) - # Change the suffix to .mrpack if it's a modrinth file - if IS_MODRINTH: - out_file = out_file.rename(out_file.with_suffix(".mrpack")) - - # Move the file back to where it should've started from - back = Path(sys.argv[1]).parent.resolve() - shutil.move(out_file, back.joinpath(f"{out_file.stem}.{out_file.suffix}")) - print(f"Successfully processed & moved/replaced {'Modrinth' if IS_MODRINTH else 'CurseForge'} modpack") - - -if __name__ == "__main__": - try: - main() - except Exception as e: - __cleanup() - print(e) diff --git a/minecraft/publishing/pre-neo/Pack Cleanup (Retro).bat b/minecraft/publishing/pre-neo/Pack Cleanup (Retro).bat deleted file mode 100644 index 8d4c000..0000000 --- a/minecraft/publishing/pre-neo/Pack Cleanup (Retro).bat +++ /dev/null @@ -1,12 +0,0 @@ -@echo off - -:loop - -@echo Processing file: %1 -C:\Users\Jose\AppData\Local\Programs\Python\Python310\python.exe .\main.py %1 -@echo "Done!" - -shift -if not "%~1"=="" goto loop - -@REM pause \ No newline at end of file diff --git a/minecraft/publishing/pre-neo/main.py b/minecraft/publishing/pre-neo/main.py deleted file mode 100644 index 2c0fb5e..0000000 --- a/minecraft/publishing/pre-neo/main.py +++ /dev/null @@ -1,184 +0,0 @@ -"""@author Jose Stovall | github.com/oitsjustjose""" - -import json -import shutil -import subprocess -import sys -from pathlib import Path -from typing import Any -from zipfile import ZipFile -import toml - -THIS_DIR = Path(__file__).parent.resolve() -CONFIG_PATH = THIS_DIR.joinpath("../configuration.json").resolve() - -PACK_UNZIP_PATH = THIS_DIR.joinpath("activepack").resolve() -PACK_ZIP_PATH = PACK_UNZIP_PATH.with_suffix(".zip").resolve() - -TROUBLEMAKERS_PATH = THIS_DIR.joinpath("troublemakers").resolve() -RESOURCE_PACKS_DIR = PACK_UNZIP_PATH.joinpath("minecraft").joinpath("resourcepacks").resolve() -MMC_EXPORT_CONFIG_PATH = THIS_DIR.joinpath("config.toml").resolve() - - -def print(obj: Any): - """override""" - log_nm_base = sys.argv[1].split("\\")[-1] - with open(f"./{log_nm_base}.log", "a+", encoding="utf-8") as log_handle: - log_handle.write(f"{str(obj)}\n") - - -def _clean_pack(): - """ - Removes client-only configs/files - """ - with open(CONFIG_PATH, "r", encoding="utf-8") as handle: - config = json.loads(handle.read()) - - for to_del in config["remove"]: - fpath = PACK_UNZIP_PATH.joinpath("minecraft").joinpath(to_del).resolve() - - if not fpath.exists(): - continue - if fpath.is_dir(): - shutil.rmtree(fpath) - print(f"Removed directory {fpath}") - else: - fpath.unlink() - print(f"Removed file {fpath}") - - -def _get_modpack_outnames(): - """ - Gets the MR_{packname}.mrpack and CF_{packname}.zip names based off of the config.toml contents - Args: join (bool) [False]: Whether to join them to the current dir or not - Returns: Tuple[str, str]: The MR_ and CF_ paths (in that order) - """ - with open(MMC_EXPORT_CONFIG_PATH, "r", encoding="utf-8") as handle: - name = toml.loads(handle.read())["name"] - return [ - THIS_DIR.joinpath(f"MR_{name}.mrpack"), - THIS_DIR.joinpath(f"CF_{name}.zip"), - ] - - -def __cleanup() -> None: - """Cleans up output files""" - MMC_EXPORT_CONFIG_PATH.unlink() - PACK_ZIP_PATH.unlink() - shutil.rmtree(PACK_UNZIP_PATH) - shutil.rmtree(TROUBLEMAKERS_PATH) - for file in THIS_DIR.iterdir(): - if file.name.startswith("CF_") or file.name.startswith("MR_"): - file.unlink() - - -def main() -> None: - """ - The main run function. - Args: None - Returns: None - Process Flow: - 1. Move file to this dir - 2. Unzip it, then: - 1. Clean up the client mods - 2. Grab the config.toml - 3. Find any exceptive files that are going to be a PITA and remove them (a. la. Witchery in the RP's dir) - 3. Re-zip - 4. mmc-export - 5. Move files from step 3 into output files - 6. Move output folders back to originating dir - """ - if len(sys.argv) != 2: - print("Missing 2nd parameter File") - return - - if not TROUBLEMAKERS_PATH.exists(): - TROUBLEMAKERS_PATH.mkdir() - - # STEP 1: copy the modpack locally - shutil.copy(sys.argv[1], PACK_ZIP_PATH) - print("STEP 1: SUCCESS") - - # STEP 2: unzip the pack - shutil.unpack_archive(PACK_ZIP_PATH, PACK_UNZIP_PATH, "zip") - print("STEP 2: SUCCESS") - - # STEP 2.1: clean up client mods - _clean_pack() - print("STEP 2.1: SUCCESS") - - # STEP 2.2: grab the config.toml file - config_toml_path = PACK_UNZIP_PATH.joinpath("config.toml").resolve() - - if not config_toml_path.exists(): - raise Exception("Failed to find a valid config.toml inside the modpack. Please see this example: https://github.com/RozeFound/mmc-export/blob/master/example_config.toml") - - shutil.move(config_toml_path, MMC_EXPORT_CONFIG_PATH) - print("STEP 2.2: SUCCESS") - - # STEP 2.3: grab PITA resourcepacks files like Witchery's 1.7.10 jar - if RESOURCE_PACKS_DIR.exists(): - for res_pack in RESOURCE_PACKS_DIR.iterdir(): - if res_pack.is_dir() or res_pack.suffix == ".zip": - continue - shutil.move(res_pack, TROUBLEMAKERS_PATH.joinpath(res_pack.name)) - print(f"STEP 2.3: Potential Troublemaker Found & Relocated: {res_pack.name}") - else: - print("No resourcepacks dir - skipping") - - # STEP 3: re-zip & cleanup - shutil.make_archive(str(PACK_ZIP_PATH.with_suffix("")), "zip", PACK_UNZIP_PATH) - shutil.rmtree(PACK_UNZIP_PATH) - print("STEP 3: SUCCESS") - - # ---- ANY FURTHER REFERENCES TO PACK_UNZIPPED_PATH ARE BAD!! ---- # - - # STEP 4: MMC-EXPORT - print("MMC-Exporter is running, please wait") - status = subprocess.Popen( - [ - "mmc-export.exe", - "-i", - PACK_ZIP_PATH, - "-f", - "Modrinth", - "CurseForge", - "-c", - MMC_EXPORT_CONFIG_PATH, - "-o", - THIS_DIR, - ], - shell=True, - ).wait() - - if status != 0: - print("Failed to convert MMC pack to Curse and/or Modrinth. See above log.") - return - - print("STEP 4: SUCCESS") - - # STEP 5: Move Troublemakers back to inside each zip - output_files = _get_modpack_outnames() - for file in output_files: - with ZipFile(THIS_DIR.joinpath(file), "a") as zipf: - for file in TROUBLEMAKERS_PATH.iterdir(): - zipf.write(file, f"overrides/resourcepacks/{file.name}") - print("STEP 5: SUCCESS") - - # STEP 6: Move finished pack files back to OG dir - back = Path(sys.argv[1]).parent.resolve() - for file in output_files + [THIS_DIR.joinpath("bundled_links.md").resolve()]: - shutil.move(file, back.joinpath(file.name)) - - print("STEP 6: SUCCESS") - - __cleanup() - print("DONE") - - -if __name__ == "__main__": - try: - main() - except Exception as e: - __cleanup() - print(e) diff --git a/minecraft/publishing/pre-neo/requirements.txt b/minecraft/publishing/pre-neo/requirements.txt deleted file mode 100644 index 7c0bb5e..0000000 --- a/minecraft/publishing/pre-neo/requirements.txt +++ /dev/null @@ -1,39 +0,0 @@ -aiofiles==24.1.0 -aiohappyeyeballs==2.6.1 -aiohttp-client-cache==0.7.3 -aiohttp-client-cache[filesystem]==0.7.3 -aiohttp>=3.8.3 -aiohttp==3.12.15 -aiosignal==1.4.0 -aiosqlite==0.21.0 -async-timeout==5.0.1 -attrs==25.3.0 -certifi>=2025.8.3 -cffi==2.0.0 -cryptography>=41.0.3,<45.0.0 -frozenlist==1.7.0 -gql-query-builder==0.1.8.dev2+g15ccddc7e -idna==3.10 -importlib_metadata==8.7.0 -itsdangerous==2.2.0 -jaraco.classes==3.4.0 -keyring==23.13.1 -MarkupSafe==3.0.2 -more-itertools==10.8.0 -multidict==6.6.4 -murmurhash2==0.2.10 -propcache==0.3.2 -pycparser==2.23 -python-forge==18.6.0 -pywin32-ctypes==0.2.3 -six==1.17.0 -tenacity==8.5.0 -toml==0.10.2 -tomli_w==1.2.0 -tomli==2.2.1 -typing_extensions==4.15.0 -url-normalize==1.4.3 -Werkzeug==2.3.8 -xxhash==3.5.0 -yarl==1.20.1 -zipp==3.23.0 \ No newline at end of file