Config master.py
Shadow Agency ∞
Theory of a Personal KOS ☀
Structured-Key DataShadow ☀
Shadow Agency Code ☀
AI Agency Workflow Schemes ☀
The Cognitive Mesh ☀
Interlocution Protocol
"""
ConfigMaster Class
v.2024.05.15
Author: Claude (Opus 3 LLM @claude.ai)
Prompt Engineer: XenoEngineer@groupKOS.com (Catcliffe Development)
Copyright (c) 2024, Catcliffe Development
This module provides a class for handling configuration files in a simple and intuitive way.
The ConfigMaster class allows reading, writing, and manipulating configuration data
stored in a format similar to INI files. It supports fail-graceful behavior when the
configuration file doesn't exist during the initial load and saves defaulted values
provided by the calling code.
Features:
- Load and save configuration data from/to files
- Get, set, update, and remove values in sections
- Case-insensitive section and key names
- Support for default values
- Handling of comment lines
- Dictionary-like access to sections and key-value pairs
- Iteration over sections and key-value pairs
- Merging configuration data from multiple sources
- Error handling and validation for section and key names
- Fail-graceful behavior when the configuration file doesn't exist during initial load
- Persistence of defaulted values provided by the calling code
Usage:
1. Create an instance of the ConfigMaster class with the file path:
config = ConfigMaster('config.txt')
2. Get values from sections with default values:
value = config.get('Section1', 'Key1', 'DefaultValue')
3. Set values in sections:
config.set('Section1', 'Key1', 'Value1')
4. Save the configuration to the file:
config.save()
5. Iterate over sections and key-value pairs:
for section in config.sections():
for key, value in config.items(section):
print(f"{key}: {value}")
Example configuration file format:
[Section1]
Key1: Value1
Key2: Value2
[Section2]
Key3: Value3
; This is a comment
# This is also a comment
Developed as a collaboration between Claude (LLM) and XenoEngineer (Catcliffe Development).
"""
import os
class ConfigMaster:
def __init__(self, file_path):
self.file_path = file_path
self.config = {} # Dictionary to store the configuration data
self.comments = [] # List to store comment lines
self.load() # Load the configuration data from the file
def load(self):
"""
Load the configuration data from the file.
If the file doesn't exist, create an empty configuration.
"""
if not os.path.isfile(self.file_path):
# File doesn't exist, create an empty configuration
self.config = {}
else:
# File exists, load the configuration data
current_section = None
with open(self.file_path, 'r') as config_file:
for line in config_file:
line = line.strip()
if line.startswith(';') or line.startswith('#'):
self.comments.append(line)
elif line.startswith('[') and line.endswith(']'):
current_section = line[1:-1].lower()
self.config[current_section] = {}
elif ':' in line:
key, value = line.split(':', 1)
self.config[current_section][key.strip().lower()] = value.strip()
def save(self):
"""
Save the configuration data to the file.
"""
with open(self.file_path, 'w') as config_file:
config_file.writelines(line + '\n' for line in self.comments)
for section, section_config in self.config.items():
if section != 'default':
config_file.write(f"[{section}]\n")
for key, value in section_config.items():
config_file.write(f"{key}: {value}\n")
config_file.write("\n")
def get(self, section, key, default=None):
"""
Get the value of a specific key in a section.
If the key doesn't exist, return the default value and update the configuration.
"""
section = section.lower()
key = key.lower()
if section in self.config and key in self.config[section]:
return self.config[section][key]
else:
# Key doesn't exist, update the configuration with the default value
self.set(section, key, default)
return default
def set(self, section, key, value):
"""
Set the value of a specific key in a section.
If the section doesn't exist, create it.
"""
section = section.lower()
key = key.lower()
self._validate_section_key(section, key)
if section not in self.config:
self.config[section] = {}
self.config[section][key] = value
def update(self, section, data):
"""
Update the configuration data in a specific section with the provided data.
The data should be a dictionary containing key-value pairs.
"""
section = section.lower()
self._validate_section(section)
self.config.setdefault(section, {}).update({k.lower(): v for k, v in data.items()})
def remove(self, section, key):
"""
Remove a specific key from a section.
"""
section = section.lower()
key = key.lower()
if section in self.config and key in self.config[section]:
del self.config[section][key]
def add_section(self, section):
"""
Add a new section to the configuration.
If the section already exists, no action is taken.
"""
section = section.lower()
if section not in self.config:
self.config[section] = {}
def remove_section(self, section):
"""
Remove a specific section from the configuration.
"""
section = section.lower()
if section in self.config:
del self.config[section]
def has_key(self, section, key):
"""
Check if a specific key exists in a section.
"""
section = section.lower()
key = key.lower()
return section in self.config and key in self.config[section]
def has_section(self, section):
"""
Check if a specific section exists in the configuration.
"""
return section.lower() in self.config
def sections(self):
"""
Get a list of all section names.
"""
return list(self.config.keys())
def items(self, section):
"""
Get a list of key-value pairs in a specific section.
"""
section = section.lower()
return list(self.config.get(section, {}).items())
def merge(self, other_config):
"""
Merge the configuration data from another ConfigMaster instance or a dictionary.
The other_config parameter can be either a ConfigMaster instance or a dictionary
containing section-key-value mappings.
"""
if isinstance(other_config, ConfigMaster):
other_config = other_config.config
for section, section_config in other_config.items():
self.config.setdefault(section.lower(), {}).update({k.lower(): v for k, v in section_config.items()})
def _validate_section_key(self, section, key):
"""
Validate the section and key names.
Raise an error if the names are invalid.
"""
if not section or not key:
raise ValueError("Section and key cannot be empty")
if ':' in key:
raise ValueError("Key cannot contain ':' character")
def _validate_section(self, section):
"""
Validate the section name.
Raise an error if the name is invalid.
"""
if not section:
raise ValueError("Section cannot be empty")
def __getitem__(self, section):
"""
Get the configuration dictionary of a specific section.
"""
return self.config[section.lower()]
def __setitem__(self, section, section_config):
"""
Set the configuration dictionary of a specific section.
"""
self.config[section.lower()] = {k.lower(): v for k, v in section_config.items()}
def __delitem__(self, section):
"""
Remove a specific section from the configuration.
"""
del self.config[section.lower()]
def __contains__(self, section):
"""
Check if a specific section exists in the configuration.
"""
return section.lower() in self.config