Untracked files matching the following rules: - Rule "!.vscode/launch.json": 1 file - Rule "*.prof": 6 files
79 lines
3.1 KiB
Python
79 lines
3.1 KiB
Python
# profileAnalyzer/core/profile_manager.py
|
|
|
|
"""
|
|
Manages loading and saving of launch profiles from a JSON file.
|
|
"""
|
|
import json
|
|
import os
|
|
from dataclasses import asdict, is_dataclass, fields
|
|
from typing import List, Optional
|
|
|
|
from .core import LaunchProfile
|
|
|
|
class LaunchProfileManager:
|
|
"""Handles the persistence of a list of LaunchProfile objects."""
|
|
def __init__(self, filepath: str):
|
|
self.filepath = filepath
|
|
self.profiles: List[LaunchProfile] = []
|
|
self.load_profiles()
|
|
|
|
def load_profiles(self):
|
|
"""Loads launch profiles from the JSON file."""
|
|
if not os.path.exists(self.filepath):
|
|
self.profiles = []
|
|
return
|
|
|
|
try:
|
|
with open(self.filepath, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
self.profiles = []
|
|
for profile_data in data:
|
|
# To handle old profiles gracefully, only pass known fields
|
|
known_fields = {f.name for f in fields(LaunchProfile)}
|
|
filtered_data = {k: v for k, v in profile_data.items() if k in known_fields}
|
|
self.profiles.append(LaunchProfile(**filtered_data))
|
|
except (json.JSONDecodeError, TypeError) as e:
|
|
print(f"Error reading or parsing profiles file '{self.filepath}': {e}")
|
|
self.profiles = []
|
|
|
|
def save_profiles(self):
|
|
"""Saves the current list of profiles to the JSON file."""
|
|
try:
|
|
data_to_save = [asdict(profile) for profile in self.profiles]
|
|
with open(self.filepath, 'w', encoding='utf-8') as f:
|
|
json.dump(data_to_save, f, indent=4)
|
|
except IOError as e:
|
|
print(f"Error saving profiles to file '{self.filepath}': {e}")
|
|
|
|
def get_profiles(self) -> List[LaunchProfile]:
|
|
return self.profiles
|
|
|
|
def get_profile_by_name(self, name: str) -> Optional[LaunchProfile]:
|
|
return next((p for p in self.profiles if p.name == name), None)
|
|
|
|
def add_profile(self, profile: LaunchProfile) -> bool:
|
|
if self.get_profile_by_name(profile.name):
|
|
print(f"Error: A profile with the name '{profile.name}' already exists.")
|
|
return False
|
|
self.profiles.append(profile)
|
|
self.save_profiles()
|
|
return True
|
|
|
|
def update_profile(self, profile_name: str, updated_profile: LaunchProfile) -> bool:
|
|
if profile_name != updated_profile.name and self.get_profile_by_name(updated_profile.name):
|
|
print(f"Error: Cannot rename to '{updated_profile.name}', as it already exists.")
|
|
return False
|
|
for i, p in enumerate(self.profiles):
|
|
if p.name == profile_name:
|
|
self.profiles[i] = updated_profile
|
|
self.save_profiles()
|
|
return True
|
|
return False
|
|
|
|
def delete_profile(self, profile_name: str) -> bool:
|
|
profile_to_delete = self.get_profile_by_name(profile_name)
|
|
if profile_to_delete:
|
|
self.profiles.remove(profile_to_delete)
|
|
self.save_profiles()
|
|
return True
|
|
return False |