fork/nix-minecraft

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

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

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