From 06bb318567d9226d498a9f905f0ee95a7572cad0 Mon Sep 17 00:00:00 2001 From: oskvr37 Date: Mon, 22 Jul 2024 13:55:41 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20update=20config=20class?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tiddl/__init__.py | 8 +++++--- tiddl/config.py | 32 +++++++++++++++++++++++--------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/tiddl/__init__.py b/tiddl/__init__.py index 6714aea..20cae5f 100644 --- a/tiddl/__init__.py +++ b/tiddl/__init__.py @@ -10,14 +10,16 @@ def main(): print("✅ TIDDL installed!") config = Config() - if not config.config["token"]: + + if not config["token"]: auth = getDeviceAuth() print(f"Go to https://{auth['verificationUriComplete']} and add device!") input("Hit enter when you are ready") token = getToken(auth["deviceCode"]) print(token) - config.config.update({"token": token["access_token"]}) - config.save() + config.update({"token": token["access_token"]}) + else: + print(config) if __name__ == "__main__": diff --git a/tiddl/config.py b/tiddl/config.py index bb9513a..ec20816 100644 --- a/tiddl/config.py +++ b/tiddl/config.py @@ -1,12 +1,12 @@ import json -from typing import TypedDict +from typing import TypedDict, Any -class Settings(TypedDict): +class Settings(TypedDict, total=False): download_path: str -class ConfigData(TypedDict): +class ConfigData(TypedDict, total=False): token: str settings: Settings @@ -17,15 +17,29 @@ DEFAULT_CONFIG: ConfigData = {"token": "", "settings": {"download_path": "tiddl" class Config: def __init__(self) -> None: - self.config: ConfigData = DEFAULT_CONFIG + self._config: ConfigData = DEFAULT_CONFIG - # load config from file or create new try: with open(FILENAME, "r") as f: - self.config = json.load(f) + loaded_config = json.load(f) + self._config.update(loaded_config) except FileNotFoundError: - self.save() + self._save() # save default config if file does not exist - def save(self): + def _save(self) -> None: with open(FILENAME, "w") as f: - json.dump(self.config, f) + json.dump(self._config, f, indent=2) + + def __getitem__(self, key: str) -> Any: + return self._config[key] + + def __iter__(self): + return iter(self._config) + + def __str__(self) -> str: + return json.dumps(self._config, indent=2) + + def update(self, data: ConfigData) -> ConfigData: + self._config.update(data) + self._save() + return self._config.copy()