summaryrefslogtreecommitdiffstats
path: root/gamechestcli/gamechest/config.py
blob: 38b02fddff3da7c6815c3e27091660c6d2850386 (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
from pathlib import Path
from dataclasses import dataclass, asdict

import yaml
from xdg.BaseDirectory import load_first_config, save_config_path, xdg_data_home

CONFIG_PATH_TUPLE = ('org.devys.gamechest', 'config.yaml')


@dataclass
class GamechestConfig:

    # TODO issue: having a Path() here raise yaml dump error when saving
    games_path: Path = Path(xdg_data_home)
    #games_path: str

    @classmethod
    def load_config_from_path(cls, path):
        #import dataconf
        #conf = dataconf.file('test.yaml', GamechestConfig)
        #print(conf.games_path)
        with Path(path).open() as fdin:
            config_yaml = yaml.safe_load(fdin)
        for key in ('games_path', ):
            config_yaml[key] = Path(config_yaml[key]).expanduser()
        return cls(**config_yaml)

    @classmethod
    def load_config(cls):
        first_config_path = load_first_config(*CONFIG_PATH_TUPLE)
        return_config = None
        if first_config_path is None:
            return_config = GamechestConfig()
            return_config.save_config()
        else:
            return_config = cls.load_config_from_path(first_config_path)
        return return_config

    def save_config(self):
        save_path = (
            Path(save_config_path(*CONFIG_PATH_TUPLE[:-1]))
            / CONFIG_PATH_TUPLE[-1]
        )
        with save_path.open('w', encoding='utf8') as fdout:
            yaml.safe_dump(asdict(self), fdout)


if __name__ == "__main__":
    #print(GamechestConfig.load_config_from_path('test.yaml'))
    print(GamechestConfig.load_config())