From 0fbbf4925d496fdeea7e49e13671835ffb093aa9 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Thu, 19 Nov 2020 03:13:01 +0100 Subject: [PATCH] Store configuration in user configuration directory --- squirrelbattle/game.py | 7 ++++--- squirrelbattle/resources.py | 8 ++++++++ squirrelbattle/settings.py | 9 ++++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/squirrelbattle/game.py b/squirrelbattle/game.py index b22c4ed..f06843d 100644 --- a/squirrelbattle/game.py +++ b/squirrelbattle/game.py @@ -136,13 +136,14 @@ class Game: """ Loads the game from a file """ - if os.path.isfile("save.json"): - with open("save.json", "r") as f: + file_path = ResourceManager.get_config_path("save.json") + if os.path.isfile(file_path): + with open(file_path, "r") as f: self.load_state(json.loads(f.read())) def save_game(self) -> None: """ Saves the game to a file """ - with open("save.json", "w") as f: + with open(ResourceManager.get_config_path("save.json"), "w") as f: f.write(json.dumps(self.save_state())) diff --git a/squirrelbattle/resources.py b/squirrelbattle/resources.py index c71c267..fc6f708 100644 --- a/squirrelbattle/resources.py +++ b/squirrelbattle/resources.py @@ -7,7 +7,15 @@ class ResourceManager: and stores files in config directory. """ BASE_DIR = Path(__file__).resolve().parent / 'assets' + # FIXME This might not work on not-UNIX based systems. + CONFIG_DIR = Path.home() / '.config' / 'squirrel-battle' @classmethod def get_asset_path(cls, filename: str) -> str: return str(cls.BASE_DIR / filename) + + @classmethod + def get_config_path(cls, filename: str) -> str: + cls.CONFIG_DIR.mkdir(parents=True) if not cls.CONFIG_DIR.is_dir() \ + else None + return str(cls.CONFIG_DIR / filename) diff --git a/squirrelbattle/settings.py b/squirrelbattle/settings.py index 258d88f..6c2e31c 100644 --- a/squirrelbattle/settings.py +++ b/squirrelbattle/settings.py @@ -2,6 +2,8 @@ import json import os from typing import Any, Generator +from .resources import ResourceManager + class Settings: """ @@ -81,13 +83,14 @@ class Settings: """ Loads the settings from a file """ - if os.path.isfile("settings.json"): - with open("settings.json", "r") as f: + file_path = ResourceManager.get_config_path("settings.json") + if os.path.isfile(file_path): + with open(file_path, "r") as f: self.loads_from_string(f.read()) def write_settings(self) -> None: """ Dumps the settings into a file """ - with open("settings.json", "w") as f: + with open(ResourceManager.get_config_path("settings.json"), "w") as f: f.write(self.dumps_to_string())