fork/nix-minecraft

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

Infinidogetextile-servers: replace unpacked libraries with classpathe857551

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