fork/nix-minecraft

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

Infinidogefix(fabric,quilt): touch locks.json/libraries.json64a768c

module/fix-14
5.0 KiB159 linesraw
1#!/usr/bin/env nix-shell
2#!nix-shell -i python3.10 -p python310Packages.requests
3
4import json
5import subprocess
6import requests
7import re
8from pathlib import Path
9
10
11def versiontuple(v):
12    return tuple(map(int, (v.partition("-")[0].split("."))))
13
14
15ENDPOINT = "https://meta.quiltmc.org/v3/versions"
16
17# These filters specify which Quilt loader and Minecraft game versions to package.
18
19# Only package Quilt versions greater than 0.17.0 (using QuiltServerLauncher main class)
20LOADER_VERSION_FILTER = lambda version: (
21    version["separator"] == "." and versiontuple(version["version"]) >= (0, 17, 0)
22)
23
24SNAPSHOT_REGEX = re.compile("([0-9]{2})w([0-9]{1,2})[a-z]+")
25
26# Package all game versions supported by Quilt
27def GAME_VERSION_FILTER(version):
28    snapshotmatch = re.fullmatch(SNAPSHOT_REGEX, version["version"])
29
30    if snapshotmatch == None:
31        return versiontuple(version["version"]) >= (1, 18, 2)
32    else:
33        return tuple(map(int, snapshotmatch.groups())) >= (22, 11)
34
35
36# Uncomment to package only major releases:
37# GAME_VERSION_FILTER = lambda version: version["stable"] and versiontuple(version["version"]) > (1, 18, 2)
38
39
40def get_game_versions():
41    """
42    Returns a list of game versions that the Quilt loader supports, filtered
43    using the GAME_VERSION_FILTER above. The `version` variable is in the format
44    {"verson": string, "stable": bool}
45    """
46    print("Fetching game versions")
47    data = requests.get(f"{ENDPOINT}/game").json()
48    return [version["version"] for version in data if GAME_VERSION_FILTER(version)]
49
50
51def get_loader_versions():
52    """
53    Returns a list of the Quilt loader versions that should be packaged, filtered
54    using the LOADER_VERSION_FILTER above. The `version` variable is in the format
55    {"separater": string, "build": int, "maven": string, "version": string, "stable": bool}
56    """
57    print("Fetching loader versions")
58    data = requests.get(f"{ENDPOINT}/loader").json()
59    return [version["version"] for version in data if LOADER_VERSION_FILTER(version)]
60
61
62def fetch_version(game_version, loader_version):
63    """
64    Return the server json for a given game and loader version
65    """
66    return requests.get(
67        f"{ENDPOINT}/loader/{game_version}/{loader_version}/server/json"
68    ).json()
69
70
71def gen_locks(version, libraries):
72    """
73    Return the lock information for a given server json, returned in the format
74    {
75        "mainClass": string,
76        "libraries": [
77            {"name": string, "url": string, "sha256": string},
78            ...
79        ]
80    }
81    """
82    ret = {"mainClass": version["mainClass"], "libraries": []}
83
84    for library in version["libraries"]:
85        name, url = library["name"], library["url"]
86
87        if not name in libraries:
88            print(f"- - - Fetching library {name}")
89            ldir, lname, lversion = name.split(":")
90            lfilename = f"{lname}-{lversion}.zip"
91            lurl = f"{url}{ldir.replace('.', '/')}/{lname}/{lversion}/{lname}-{lversion}.jar"
92
93            lhash = subprocess.run(
94                ["nix-prefetch-url", lurl], capture_output=True, encoding="UTF-8"
95            ).stdout.rstrip("\n")
96
97            libraries[name] = {"name": lfilename, "url": lurl, "sha256": lhash}
98        else:
99            pass
100            # print(f"- - - Using cached library {name}")
101
102        ret["libraries"].append(name)
103
104    return ret
105
106
107def main(versions, libraries, locks, lib_locks):
108    """
109    Fetch the relevant information and update the lockfiles.
110    `versions` and `libraries` are data from the existing files, while
111    `locks` and `lib_locks` are file objects to be written to
112    """
113    loader_versions = get_loader_versions()
114    game_versions = get_game_versions()
115
116    print("Starting fetch")
117    try:
118        for loader_version in loader_versions:
119            print(f"- Loader: {loader_version}")
120            if not versions.get(loader_version, None):
121                versions[loader_version] = {}
122
123            for game_version in game_versions:
124                if not versions[loader_version].get(game_version, None):
125                    print(f"- - Game: {game_version}")
126                    versions[loader_version][game_version] = gen_locks(
127                        fetch_version(game_version, loader_version), libraries
128                    )
129                else:
130                    print(f"- - Game: {game_version}: Already locked")
131
132    except KeyboardInterrupt:
133        print("Cancelled fetching, writing and exiting")
134
135    json.dump(versions, locks, indent=2)
136    json.dump(libraries, lib_locks, indent=2)
137    locks.write("\n")
138    lib_locks.write("\n")
139
140
141if __name__ == "__main__":
142    folder = Path(__file__).parent
143    lo = folder / "locks.json"
144    li = folder / "libraries.json"
145    lo.touch()
146    li.touch()
147
148    with (
149        open(lo, "r") as locks,
150        open(li, "r") as lib_locks,
151    ):
152        versions = {} if lo.stat().st_size == 0 else json.load(locks)
153        libraries = {} if li.stat().st_size == 0 else json.load(lib_locks)
154
155    with (
156        open(lo, "w") as locks,
157        open(li, "w") as lib_locks,
158    ):
159        main(versions, libraries, locks, lib_locks)