53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
# markdownconverter/utils/config.py
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
# Definisci i percorsi basati sulla posizione del file
|
|
APP_ROOT_DIR = Path(__file__).parent.parent.parent
|
|
CONFIG_DIR = APP_ROOT_DIR / "config"
|
|
CONFIG_FILE = CONFIG_DIR / "app_config.json"
|
|
|
|
# Costanti per le chiavi del dizionario
|
|
KEY_LAST_MARKDOWN = "last_markdown_file"
|
|
KEY_LAST_PROFILE = "last_selected_profile"
|
|
KEY_PROFILES = "profiles"
|
|
KEY_TEMPLATE_PATH = "template_path"
|
|
KEY_VALUES = "values"
|
|
|
|
|
|
def get_default_config() -> dict:
|
|
"""Restituisce la struttura di configurazione predefinita."""
|
|
return {KEY_LAST_MARKDOWN: "", KEY_LAST_PROFILE: "", KEY_PROFILES: {}}
|
|
|
|
|
|
def save_configuration(config_data: dict):
|
|
"""Salva il dizionario di configurazione nel file JSON."""
|
|
try:
|
|
CONFIG_DIR.mkdir(exist_ok=True)
|
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
json.dump(config_data, f, indent=4)
|
|
except IOError as e:
|
|
print(f"Error saving configuration: {e}")
|
|
|
|
|
|
def load_configuration() -> dict:
|
|
"""Carica la configurazione dal file JSON."""
|
|
defaults = get_default_config()
|
|
if not CONFIG_FILE.is_file():
|
|
return defaults
|
|
|
|
try:
|
|
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
loaded_config = json.load(f)
|
|
|
|
# Assicura solo la presenza delle chiavi di primo livello
|
|
for key, default_value in defaults.items():
|
|
loaded_config.setdefault(key, default_value)
|
|
|
|
return loaded_config
|
|
|
|
except (json.JSONDecodeError, IOError) as e:
|
|
print(f"Error loading or parsing config file: {e}. Returning default config.")
|
|
return defaults
|