fork/nix-minecraft

git clone https://git.julia.blue/fork/nix-minecraft

Infinidogetextile-servers: replace unpacked libraries with classpathe857551

lazymc
7.7 KiB252 linesraw
1#!/usr/bin/env nix-shell
2#!nix-shell -i python3 -p python3Packages.requests python3Packages.jq
3
4import json
5import subprocess
6import requests
7import jq
8import logging
9import sys
10import re
11from pathlib import Path
12
13logging.basicConfig(level=logging.INFO)
14logger = logging.getLogger()
15
16
17def versiontuple(v):
18    return tuple(map(int, (v.partition("-")[0].split("."))))
19
20
21ENDPOINT = "https://meta.quiltmc.org/v3/versions"
22MAVEN = "https://maven.quiltmc.org/repository/release/"
23
24# These filters specify which Quilt loader and Minecraft game versions to package.
25
26# Only package Quilt versions greater than 0.17.0 (using QuiltServerLauncher main class)
27LOADER_VERSION_FILTER = lambda version: (
28    version["separator"] == "." and versiontuple(version["version"]) >= (0, 17, 0)
29)
30
31SNAPSHOT_REGEX = re.compile("([0-9]{2})w([0-9]{1,2}).+")
32
33
34# Package all game versions supported by Quilt
35def GAME_VERSION_FILTER(version):
36    snapshotmatch = re.fullmatch(SNAPSHOT_REGEX, version["version"])
37
38    if snapshotmatch == None:
39        return versiontuple(version["version"]) >= (1, 18, 2)
40    else:
41        return tuple(map(int, snapshotmatch.groups())) >= (22, 11)
42
43
44# Uncomment to package only major releases:
45# GAME_VERSION_FILTER = lambda version: version["stable"] and versiontuple(version["version"]) > (1, 18, 2)
46
47
48def get(*args: str):
49    return requests.get("/".join((ENDPOINT,) + args)).json()
50
51
52def get_game_versions():
53    """
54    Returns a list of game versions that the Fabric loader supports, filtered
55    using the GAME_VERSION_FILTER above. The `version` variable is in the format
56    {"verson": string, "stable": bool}
57    """
58    logger.info("Fetching game versions")
59    data = get("game")
60    return [version["version"] for version in data if GAME_VERSION_FILTER(version)]
61
62
63def get_loader_versions():
64    """
65    Returns a list of the Fabric loader versions that should be packaged, filtered
66    using the LOADER_VERSION_FILTER above. The `version` variable is in the format
67    {"separater": string, "build": int, "maven": string, "version": string, "stable": bool}
68    """
69    logger.info("Fetching loader versions")
70    data = get("loader")
71    return [version["version"] for version in data if LOADER_VERSION_FILTER(version)]
72
73
74PROCESS_LOADER_VERSION = jq.compile(
75    "{"
76    "mainClass: .launcherMeta.mainClass.server,"
77    "libraries: ((.launcherMeta.libraries | [.common[], .server[]]) + [{name: .loader.maven, url: $URL}])"
78    "}",
79    args={"URL": MAVEN},
80)
81
82
83def fetch_loader_version(loader_version):
84    """
85    Return the loader information for a given loader version
86    """
87    # Quilt's API doesn't expose loader information without a game version
88    game_version = "1.19"
89
90    return PROCESS_LOADER_VERSION.input_value(
91        get("loader", game_version, loader_version)
92    ).first()
93
94
95def fetch_game_version(game_version):
96    """
97    Return game-version-specific libraries for a given game version
98    """
99    get_ = lambda item: get(item, game_version)[0]["maven"]
100    return {
101        "libraries": [
102            {"name": get_("intermediary"), "url": MAVEN},
103            {"name": get_("hashed"), "url": MAVEN},
104        ]
105    }
106
107
108def prefetch_libraries(logger, version_libraries, libraries):
109    logger = logger.getChild("libraries")
110    ret = []
111
112    for library in version_libraries:
113        name, url = library["name"], library["url"]
114
115        if not name in libraries or any(not v for k, v in libraries[name].items()):
116            logger.info(f"Fetching {name}")
117            ldir, lname, lversion = name.split(":")
118            lfilename = f"{lname}-{lversion}.jar"
119            lurl = "/".join(
120                (
121                    url.rstrip("/"),
122                    ldir.replace(".", "/"),
123                    lname,
124                    lversion,
125                    f"{lname}-{lversion}.jar",
126                )
127            )
128
129            lhash = subprocess.run(
130                ["nix-prefetch-url", lurl], capture_output=True, encoding="UTF-8"
131            ).stdout.rstrip("\n")
132
133            libraries[name] = {"name": lfilename, "url": lurl, "sha256": lhash}
134        else:
135            logger.debug(f"Using cached {name}")
136
137        ret.append(name)
138
139    return ret
140
141
142def gen_loader_locks(logger, version, libraries):
143    """
144    Return the lock information for a given loader version, returned in the format
145    {
146        "mainClass": string,
147        "libraries": [
148            {"name": string, "url": string, "sha256": string},
149            ...
150        ]
151    }
152    """
153    ret = {
154        "mainClass": version["mainClass"],
155        "libraries": prefetch_libraries(logger, version["libraries"], libraries),
156    }
157
158    return ret
159
160
161def gen_game_locks(logger, version, libraries):
162    """
163    Return the lock information for a given loader version, returned in the format
164    {
165        "libraries": [
166            {"name": string, "url": string, "sha256": string},
167            ...
168        ]
169    }
170    """
171    return {"libraries": prefetch_libraries(logger, version["libraries"], libraries)}
172
173
174def main(
175    versions_loader, versions_game, libraries, loader_locks, game_locks, lib_locks
176):
177    """
178    Fetch the relevant information and update the lockfiles.
179    `versions` and `libraries` are data from the existing files, while
180    `locks` and `lib_locks` are file objects to be written to
181    """
182    loader_versions = get_loader_versions()
183    game_versions = get_game_versions()
184
185    logger.info("Starting fetch")
186    try:
187        logger.info("Fetching loader versions")
188        loader_logger = logger.getChild("loader")
189        for loader_version in loader_versions:
190            if not versions_loader.get(loader_version, None):
191                loader_logger.info(f"Fetching version: {loader_version}")
192                versions_loader[loader_version] = gen_loader_locks(
193                    loader_logger, fetch_loader_version(loader_version), libraries
194                )
195            else:
196                loader_logger.info(f"Version {loader_version} already locked")
197
198        logger.info("Fetching game versions")
199        game_logger = logger.getChild("game")
200        for game_version in game_versions:
201            if not versions_game.get(game_version, None):
202                game_logger.info(f"Fetching version: {game_version}")
203                versions_game[game_version] = gen_game_locks(
204                    game_logger, fetch_game_version(game_version), libraries
205                )
206            else:
207                game_logger.info(f"Version {game_version} already locked")
208
209    except KeyboardInterrupt:
210        logger.warning("Cancelled fetching, writing and exiting")
211
212    json.dump(versions_loader, loader_locks, indent=2)
213    json.dump(versions_game, game_locks, indent=2)
214    json.dump(libraries, lib_locks, indent=2)
215    loader_locks.write("\n")
216    game_locks.write("\n")
217    lib_locks.write("\n")
218
219
220if __name__ == "__main__":
221    folder = Path(__file__).parent
222    llo = folder / "loader_locks.json"
223    glo = folder / "game_locks.json"
224    llo.touch()
225    glo.touch()
226
227    build_support_folder = folder.parent / "build-support"
228    li = build_support_folder / "libraries.json"
229    li.touch()
230
231    with (
232        open(llo, "r") as loader_locks,
233        open(glo, "r") as game_locks,
234        open(li, "r") as lib_locks,
235    ):
236        versions_loader = {} if llo.stat().st_size == 0 else json.load(loader_locks)
237        versions_game = {} if glo.stat().st_size == 0 else json.load(game_locks)
238        libraries = {} if li.stat().st_size == 0 else json.load(lib_locks)
239
240    with (
241        open(llo, "w") as loader_locks,
242        open(glo, "w") as game_locks,
243        open(li, "w") as lib_locks,
244    ):
245        main(
246            versions_loader,
247            versions_game,
248            libraries,
249            loader_locks,
250            game_locks,
251            lib_locks,
252        )