summaryrefslogtreecommitdiff
path: root/meta/common/__init__.py
blob: 04e3bdfbb09fac2127f3522935ed7302f86790a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import os
import os.path
import datetime
import hashlib
import sys
from urllib.parse import urlparse
from typing import Any, Optional, Callable

import requests
from cachecontrol import CacheControl  # type: ignore
from cachecontrol.caches import FileCache  # type: ignore

LAUNCHER_MAVEN = "https://files.prismlauncher.org/maven/%s"


def serialize_datetime(dt: datetime.datetime):
    if dt.tzinfo is None:
        return dt.replace(tzinfo=datetime.timezone.utc).isoformat()

    return dt.isoformat()


def cache_path():
    if "META_CACHE_DIR" in os.environ:
        return os.environ["META_CACHE_DIR"]
    return "cache"


def launcher_path():
    if "META_LAUNCHER_DIR" in os.environ:
        return os.environ["META_LAUNCHER_DIR"]
    return "launcher"


def upstream_path():
    if "META_UPSTREAM_DIR" in os.environ:
        return os.environ["META_UPSTREAM_DIR"]
    return "upstream"


def ensure_upstream_dir(path):
    path = os.path.join(upstream_path(), path)
    if not os.path.exists(path):
        os.makedirs(path)


def ensure_component_dir(component_id: str):
    path = os.path.join(launcher_path(), component_id)
    if not os.path.exists(path):
        os.makedirs(path)


def transform_maven_key(maven_key: str):
    return maven_key.replace(":", ".")


def replace_old_launchermeta_url(url: str):
    o = urlparse(url)
    if o.netloc == "launchermeta.mojang.com":
        return o._replace(netloc="piston-meta.mojang.com").geturl()

    return url


def get_all_bases(cls: type, bases: Optional[list[type]] = None):
    bases = bases or []
    bases.append(cls)
    for c in cls.__bases__:
        get_all_bases(c, bases)
    return tuple(bases)


def merge_dict(base: dict[Any, Any], overlay: dict[Any, Any]):
    for k, v in base.items():
        if isinstance(v, dict):
            merge_dict(v, overlay.setdefault(k, {}))  # type: ignore
        else:
            if k not in overlay:
                overlay[k] = v

    return overlay


def default_session():
    cache = FileCache(os.path.join(cache_path(), "http_cache"))
    sess = CacheControl(requests.Session(), cache)

    sess.headers.update({"User-Agent": "PrismLauncherMeta/1.0"})

    return sess


def remove_files(file_paths: list[str]) -> None:
    for file_path in file_paths:
        try:
            if os.path.isfile(file_path):
                os.remove(file_path)
        except Exception as e:
            print(e)


def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


def file_hash(
    filename: str, hashtype: Callable[[], "hashlib._Hash"], blocksize: int = 65536
) -> str:
    hashtype = hashtype()
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            hashtype.update(block)
    return hashtype.hexdigest()


def get_file_sha1_from_file(file_name: str, sha1_file: str) -> Optional[str]:
    if os.path.isfile(sha1_file):
        with open(sha1_file, "r") as file:
            return file.read()
    if not os.path.isfile(file_name):
        return None
    new_sha1 = file_hash(file_name, hashlib.sha1)
    with open(sha1_file, "w") as file:
        file.write(new_sha1)
    return None