import re from pathlib import Path from pydantic import BaseModel class MasterIocSubs(BaseModel): content: str @classmethod def read_from_file(cls, path: Path) -> "MasterIocSubs": with open(path) as f: file_content = f.read() return MasterIocSubs(content=file_content) def update_content( self, service_name: str, starton: str = "0", # TODO: ok defaults? autooff: str = "0", # TODO: ok defaults? ): """ Parses the configuration text and appends a new row before the closing bracket. """ quoted_service = f'"{service_name}"' new_row = f' {{ "{{{{ agebd_env_suffix_upper }}}}", {quoted_service:<22} , "{starton}", "{autooff}" }}' # Use regex to find the last closing curly brace of the configuration block # This targets the line that contains only a lone closing brace, optional spaces, and maybe a comma/semicolon. pattern = r"(\s*\n\s*\}(?:;|,)?\s*$)" if re.search(pattern, self.content, re.MULTILINE): # Insert our new row right before that closing brace line self.content = re.sub( pattern, f"\n{new_row}\\1", self.content, count=1, flags=re.MULTILINE ) else: raise ValueError( "Could not locate the closing structure format '}' inside the configuration." ) def write_to_file(self, path: Path) -> None: with open(path, "w") as f: f.write(self.content)