#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Configuration management for Storm Games. Provides functionality for: - Reading and writing configuration files - Global and local configuration handling """ import configparser import os from xdg import BaseDirectory class Config: """Configuration management class for Storm Games.""" def __init__(self, gameTitle): """Initialize configuration system for a game. Args: gameTitle (str): Title of the game """ self.gameTitle = gameTitle self.globalPath = os.path.join(BaseDirectory.xdg_config_home, "storm-games") self.gamePath = os.path.join(self.globalPath, str.lower(str.replace(gameTitle, " ", "-"))) # Create game directory if it doesn't exist if not os.path.exists(self.gamePath): os.makedirs(self.gamePath) # Initialize config parsers self.localConfig = configparser.ConfigParser() self.globalConfig = configparser.ConfigParser() # Load existing configurations self.read_local_config() self.read_global_config() def read_local_config(self): """Read local configuration from file.""" try: with open(os.path.join(self.gamePath, "config.ini"), 'r') as configFile: self.localConfig.read_file(configFile) except: pass def read_global_config(self): """Read global configuration from file.""" try: with open(os.path.join(self.globalPath, "config.ini"), 'r') as configFile: self.globalConfig.read_file(configFile) except: pass def write_local_config(self): """Write local configuration to file.""" with open(os.path.join(self.gamePath, "config.ini"), 'w') as configFile: self.localConfig.write(configFile) def write_global_config(self): """Write global configuration to file.""" with open(os.path.join(self.globalPath, "config.ini"), 'w') as configFile: self.globalConfig.write(configFile) # Global variables for backward compatibility localConfig = configparser.ConfigParser() globalConfig = configparser.ConfigParser() gamePath = "" globalPath = "" def write_config(writeGlobal=False): """Write configuration to file. Args: writeGlobal (bool): If True, write to global config, otherwise local (default: False) """ if not writeGlobal: with open(gamePath + "/config.ini", 'w') as configFile: localConfig.write(configFile) else: with open(globalPath + "/config.ini", 'w') as configFile: globalConfig.write(configFile) def read_config(readGlobal=False): """Read configuration from file. Args: readGlobal (bool): If True, read global config, otherwise local (default: False) """ if not readGlobal: try: with open(gamePath + "/config.ini", 'r') as configFile: localConfig.read_file(configFile) except: pass else: try: with open(globalPath + "/config.ini", 'r') as configFile: globalConfig.read_file(configFile) except: pass