fork/nix-minecraft

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

Infinidogefabric-servers: refactor to use textile helpersada6252

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