Globalize split pack script

This commit is contained in:
oitsjustjose 2026-07-04 19:35:39 -05:00
commit 85e19a79eb

339
linux/split-pack Executable file
View file

@ -0,0 +1,339 @@
#!/bin/bash
# Set up the python environment
if [ ! -f "/tmp/shell-scripts/venv/bin/python" ]; then
mkdir -p /tmp/shell-scripts
python3 -m venv /tmp/shell-scripts/venv > /dev/null 2>&1
fi
# Install reqs
/tmp/shell-scripts/venv/bin/pip install colorama tomli requests > /dev/null 2>&1
# Delete the existing output folder if it exists
if [ -d "$(pwd)/__release__" ]; then
# After we prompt the user, of course.
read -p "__release__ already exists, replace it? " -n 1 -r
echo # Newline
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Okay, quitting!"
exit 0
else
rm -rf "$(pwd)/__release__"
fi
fi
# Finally run the script
/tmp/shell-scripts/venv/bin/python << EOF
import json
import os
import shutil
import traceback
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from sys import stdout
from typing import List, Union
from zipfile import BadZipFile, ZipFile
import requests
import tomli # Use instead of toml because of https://github.com/uiri/toml/issues/382
from colorama import Fore
from tomli import TOMLDecodeError
LOADERS = ["minecraft", "neoforge", "forge", "fabric"]
class Side(Enum):
COMMON = 0
CLIENT = 1
@dataclass
class ResolvedMod:
path: Path
mod_ids: List[str]
sides: List[Side]
@dataclass
class Config:
# Paths used throughout
this_dir: Path
out_dir: Path
scan_dir: Path
client_mods_dir: Path
common_mods_dir: Path
# Overrides by modId
client_overrides: List[str]
common_overrides: List[str]
class ModResolutionException(Exception):
def __init__(self, jar_file: Path, message: str, traceback_str: str):
self.__jar_file__ = jar_file
self.__message__ = message
self.__traceback_str__ = traceback_str
def to_str(self) -> str:
jar_str = Fore.GREEN + str(self.__jar_file__.name) + Fore.RESET
traceback_str = Fore.LIGHTBLACK_EX + self.__traceback_str__ + Fore.RESET
return f"[{jar_str}]: {self.__message__}:\n\n{traceback_str}"
class ModResolver:
def __init__(self, config: Config, jar_file: Path):
self.__config__ = config
self.__jar_file__ = jar_file
def __is_library__(self) -> bool:
"""Reads the Jar Manifest to determine if a mod is a Library Mod
Returns:
bool: True if it is, False otherwise
"""
try:
with ZipFile(self.__jar_file__, "r") as jar:
with jar.open("META-INF/MANIFEST.MF") as handle:
data = handle.read().decode()
return "LIBRARY" in data
except Exception:
return False
def __get_overriden_side__(self) -> Union[Side, None]:
"""Reads the config to see if any mod_id in mod_ids has an override
Returns:
Union[Side, None]: None if no override is found, otherwise the corresponding Side that any mod_id has been given
"""
for mod_id in self.__mod_ids__:
if mod_id in self.__config__.client_overrides:
return Side.CLIENT
if mod_id in self.__config__.common_overrides:
return Side.COMMON
return None
def __resolve_sides__(self) -> List[Side]:
"""Gets a list of possible Sides that the given mod defines
Returns:
List[Side]: All possible Sides that the various mod_ids in the data have defined
"""
# Iter over all _important_ "Dependencies" and check the side from there
sides: List[Side] = list()
# For each mod_id, get its dependencies (remember a jar can have multiple sub-mods e.g. BuildCraft)
for mod_id in self.__mod_ids__:
# Get all dependencies for this mod w/ safeguard if the mod_id somehow isn't in the toml
deps = self.__data__["dependencies"][mod_id] if mod_id in self.__data__["dependencies"] else []
# Then whittle them down by Loaders
deps = list(filter(lambda x: x["modId"] in LOADERS, deps))
# Lastly remap to a nice, clean set
sides += list(map(lambda x: Side.CLIENT if "side" in x and x["side"].lower() == "client" else Side.COMMON, deps))
return sides
def resolve(self) -> ResolvedMod:
"""The full
Raises:
ModResolutionException: KeyError was caught and passed forward
ModResolutionException: TOMLDecodeError was caught and passed forward
ModResolutionException: BadZipFile was caught and passed forward
Returns:
ResolvedMod: _description_
"""
# If the file is a library mod, assume it's common. mod_ids goes unused from here.
if self.__is_library__():
return ResolvedMod(path=self.__jar_file__, mod_ids=[], sides=[Side.COMMON])
try:
with ZipFile(self.__jar_file__, "r") as jar:
with jar.open("META-INF/neoforge.mods.toml") as handle:
self.__data__ = tomli.loads(handle.read().decode())
# Getting all of the ModIDs is the easy part (dedup'd for iter efficiency)
self.__mod_ids__: List[str] = list(map(lambda x: x["modId"], self.__data__["mods"]))
self.__mod_ids__ = list(set(self.__mod_ids__))
# Check against our config to see if any mod_id has an override
overriden_side = self.__get_overriden_side__()
sides = [overriden_side] if overriden_side else self.__resolve_sides__()
return ResolvedMod(path=self.__jar_file__, mod_ids=self.__mod_ids__, sides=list(set(sides)))
except KeyError:
raise ModResolutionException(self.__jar_file__, "🔔 Failed to find Key in Jar", traceback.format_exc())
except TOMLDecodeError:
raise ModResolutionException(self.__jar_file__, "⛔ Failed to load TOML in Jar", traceback.format_exc())
except BadZipFile:
raise ModResolutionException(self.__jar_file__, "🔥 Failed to open Jar", traceback.format_exc())
def load_config() -> Config:
"""Loads the rest of the config in from split.config.json
Returns:
Config: The configuration needed for the remaining parts of this script
"""
print("Loading config...")
this_dir = Path("$(pwd)").resolve()
# We can assume this path doesn't exist because of pre-Python checks at the bash level
out_dir = this_dir.joinpath("__release__")
with open(this_dir.joinpath("split.config.json"), "r", encoding="utf-8") as handle:
config = json.loads(handle.read())
return Config(
this_dir=this_dir,
out_dir=out_dir,
scan_dir=this_dir.joinpath("mods"),
client_mods_dir=out_dir.joinpath("automodpack/host-modpack/main/mods").resolve(),
common_mods_dir=out_dir.joinpath("mods").resolve(),
client_overrides=config["client_overrides"],
common_overrides=config["common_overrides"],
)
def prep_dirs(config: Config) -> None:
"""Sets up all required working directories, making them where needed and copying
over prerequisite files that will always be there (like configs, kubejs scripts)
Args:
config (Config): the app config
"""
print("Preparing output directories...")
# Create the out dir, copy over folders we'll always copy
os.makedirs(config.out_dir, exist_ok=True)
for subdir in ["config", "defaultconfigs", "kubejs"]:
shutil.copytree(config.this_dir.joinpath(subdir), config.out_dir.joinpath(subdir))
# Prep the directories we'll be writing to
os.makedirs(config.client_mods_dir, exist_ok=True)
os.makedirs(config.common_mods_dir, exist_ok=True)
def download_automodpack(config: Config) -> None:
"""Downloads the latest build of AutoModpack from GitHub Releases
Args:
config (Config): The global app config
Raises:
Exception: various thrown while doing HTTP calls
"""
# Change these to whatever you need to based on your actual versioning
LOADER = "neoforge"
VERSION = "1.21.1"
print(f"Downloading automodpack for {LOADER} {VERSION}")
resp = requests.get("https://api.github.com/repos/Skidamek/AutoModpack/releases/latest")
if not resp.ok:
raise Exception(f"Got status {resp.status_code} while downloading AutoModpack :(")
data = json.loads(resp.content)
dl_url, dl_name = None, ""
for asset in data["assets"]:
if f"mc{VERSION}-{LOADER}" in asset["name"]:
dl_url = asset["browser_download_url"]
dl_name = asset["name"]
break
if not dl_url:
raise Exception(f"Failed to find any version of AutoModpack for {LOADER}-{VERSION}")
resp = requests.get(dl_url)
if not resp.ok:
raise Exception(f"Got status {resp.status_code} while downloading {dl_url}")
with open(config.common_mods_dir.joinpath(dl_name), "wb") as handle:
handle.write(resp.content)
def resolve_mods(config: Config) -> List[ResolvedMod]:
"""Resolves all mods in the mods_dir with their respective modId
Args:
config (Config): The global app config
Returns:
List[ResolvedMod]: A list of ResolvedMod instances
"""
print("Resolving all mod jar files to their corresponding mod id")
resolved_mods: List[ResolvedMod] = list()
errors: List[ModResolutionException] = list()
for root, _, files in os.walk(config.scan_dir):
for file in list(filter(lambda x: x.endswith(".jar"), files)):
# Print each file out as we scan it
print(file)
jar_path = Path(f"{root}/{file}").resolve()
try:
resolved = ModResolver(config, jar_path).resolve()
resolved_mods.append(resolved)
except ModResolutionException as e:
errors.append(e)
pass
# Undo the print to avoid spamming the console
stdout.write("\033[F")
stdout.write("\033[K")
# stdout cleanup before proceeding
stdout.write("\033[F")
stdout.write("\033[K")
if errors:
print("Hit the following snags during the Mod Resolution Process:")
for error in errors:
print(error.to_str())
return resolved_mods
def move_mods(config: Config, resolved_mods: List[ResolvedMod]) -> None:
"""Moves all mods where they need to go based on the config and resolved mods
Args:
config (Config): The global app config
resolved_mods (List[ResolvedMod]): The list of fully resolved mods
"""
def __move(mod: ResolvedMod):
"""
The full relocate process, but for a single mod to keep control flow easy
"""
# Copy to Client-Only if there's only one distinct side and it's CLIENT_ONLY.
if mod.sides == [Side.CLIENT]:
shutil.copy(mod.path, config.client_mods_dir)
return
shutil.copy(mod.path, config.common_mods_dir)
return
print("Splitting Mods & Cleaning Up")
for mod in resolved_mods:
__move(mod)
def main():
"""
Goes through the entire workflow of this script:
1. Opens and resolves the Script's Config
2. Prepares any necessary output dirs
3. Downloads automodpack from GitHub Releases
4. Resolve all mods to their Mod IDs
5. Move the mods now that we know what they are
"""
config = load_config()
prep_dirs(config)
download_automodpack(config)
resolved = resolve_mods(config)
move_mods(config, resolved)
if __name__ == "__main__":
main()
EOF