aboutsummaryrefslogtreecommitdiff
path: root/ardsmm/__init__.py
blob: cb0b90ed57c9b062ba8d10806b3ee308fd20ebaa (plain) (blame)
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
import json
import sys
from typing import Any
from ardsmm._version import __version__, __version_tuple__


class ArmaConfigMod:
    data: dict[Any, Any]
    MOD_SCHEMA = {
        "modId": str,
        "name": str,
        "version": str,
    }

    def __init__(self, mod_dict):
        if isinstance(mod_dict, str):
            if mod_dict.endswith(","):
                mod_dict = mod_dict[:-1]
            self.data = json.loads(mod_dict)
        else:
            self.data = mod_dict
        self.check()

    def check(self):
        for key, expected_type in self.MOD_SCHEMA.items():
            if key not in self.data.keys():
                raise KeyError(f"Mod key '{key}' is missing")
            elif expected_type is not type(self.data[key]):
                raise TypeError(f"Mod '{key}' value should be {expected_type}, but got {type(self.data[key])}")


class ArmaConfig:
    mods: list[Any]
    data: dict[Any, Any]
    file: str
    DEFAULT_INDENT = 4

    def __init__(self, configfile):
        self.file = configfile
        self.data = {}
        self.mods = []
        self.read()

    def read(self):
        with open(self.file, "r") as fp:
            self.data = json.load(fp)

        if not self.data.get("game"):
            self.data["game"] = {}
            if not self.data["game"].get("mods"):
                self.data["game"]["mods"]: []

        for mod in self.data["game"]["mods"]:
            self.mods.append(ArmaConfigMod(mod))

    def to_string(self, indent=DEFAULT_INDENT):
        return json.dumps(self.data, indent=indent)

    def append_mod(self, s):
        mod = ArmaConfigMod(s)

        if mod.data["name"] in [x.data["name"] for x in self.mods]:
            print(f"[Skip  ] {mod.data['name']} exists", file=sys.stderr)
            return
        print(f"[Append] {mod.data['name']}", file=sys.stderr)
        self.mods.append(mod)

    def update(self):
        self.data["game"]["mods"] = sorted(
            [x.data for x in self.mods],
            key=lambda y: y["name"]
        )