|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright: (c) 2025, Gaspard Micol (@gmicol) <[email protected]> |
| 4 | + |
| 5 | +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 | + |
| 7 | +from __future__ import absolute_import, division, print_function |
| 8 | + |
| 9 | +__metaclass__ = type |
| 10 | + |
| 11 | +from copy import deepcopy |
| 12 | + |
| 13 | + |
| 14 | +# Custom NDConfigCollection Exceptions |
| 15 | +class NDConfigCollectionError(Exception): |
| 16 | + """Base exception for NDConfigCollection errors.""" |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +class NDConfigNotFoundError(NDConfigCollectionError, KeyError): |
| 21 | + """Raised when a configuration is not found by its identifier.""" |
| 22 | + pass |
| 23 | + |
| 24 | + |
| 25 | +class NDIdentifierMismatchError(NDConfigCollectionError, ValueError): |
| 26 | + """Raised when an identifier in a config does not match the expected key.""" |
| 27 | + pass |
| 28 | + |
| 29 | + |
| 30 | +class InvalidNDConfigError(NDConfigCollectionError, TypeError): |
| 31 | + """Raised when a provided config is not a dictionary or is missing the identifier key.""" |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +# TODO: Maybe add a get_diff_config function |
| 36 | +# TODO: Handle multiple identifiers |
| 37 | +# TODO: Add descriptions |
| 38 | +# NOTE: New data structure for ND Network Resource Module |
| 39 | +class NDConfigCollection: |
| 40 | + def __init__(self, identifier_key, data=None): |
| 41 | + if not isinstance(identifier_key, str): |
| 42 | + raise TypeError("identifier_key must be a string.") |
| 43 | + self.identifier_key = identifier_key |
| 44 | + self.config_collection = {} |
| 45 | + |
| 46 | + if data is not None: |
| 47 | + if isinstance(data, list): |
| 48 | + self.list_view = data |
| 49 | + elif isinstance(data, dict): |
| 50 | + self.config_collection = data |
| 51 | + else: |
| 52 | + raise TypeError("data must be a list of dicts or dict of configs.") |
| 53 | + |
| 54 | + @property |
| 55 | + def list_view(self): |
| 56 | + return [v.copy() for v in self.config_collection.values()] |
| 57 | + |
| 58 | + @list_view.setter |
| 59 | + def list_view(self, new_list): |
| 60 | + if not isinstance(new_list, list): |
| 61 | + raise TypeError("list_view must be set to a list.") |
| 62 | + |
| 63 | + new_dict = {} |
| 64 | + for item in new_list: |
| 65 | + if not isinstance(item, dict): |
| 66 | + raise TypeError("All items in list_view must be dicts.") |
| 67 | + if self.identifier_key not in item: |
| 68 | + raise InvalidNDConfigError(f"Missing '{self.identifier_key}' in item: {item}") |
| 69 | + |
| 70 | + key = item[self.identifier_key] |
| 71 | + new_dict[key] = item.copy() |
| 72 | + self.config_collection = new_dict |
| 73 | + |
| 74 | + # Basic Operations |
| 75 | + def replace(self, config): |
| 76 | + if not isinstance(config, dict): |
| 77 | + raise InvalidNDConfigError("Config must be a dict.") |
| 78 | + if self.identifier_key not in config: |
| 79 | + raise InvalidNDConfigError(f"Missing '{self.identifier_key}' in config: {config}") |
| 80 | + |
| 81 | + key = config[self.identifier_key] |
| 82 | + self.config_collection[key] = config.copy() |
| 83 | + |
| 84 | + def merge(self, config): |
| 85 | + if not isinstance(config, dict): |
| 86 | + raise InvalidNDConfigError("Config must be a dict.") |
| 87 | + if self.identifier_key not in config: |
| 88 | + raise InvalidNDConfigError(f"Missing '{self.identifier_key}' in config: {config}") |
| 89 | + |
| 90 | + key = config[self.identifier_key] |
| 91 | + if key in self.config_collection: |
| 92 | + self.config_collection[key].update(config.copy()) |
| 93 | + else: |
| 94 | + self.config_collection[key] = config.copy() |
| 95 | + |
| 96 | + def remove(self, identifier): |
| 97 | + if identifier not in self.config_collection: |
| 98 | + raise NDConfigNotFoundError(f"Configuration with identifier '{identifier}' not found.") |
| 99 | + del self.config_collection[identifier] |
| 100 | + |
| 101 | + def get(self, identifier): |
| 102 | + config = self.config_collection.get(identifier) |
| 103 | + if config is None: |
| 104 | + raise NDConfigNotFoundError(f"Configuration with identifier '{identifier}' not found.") |
| 105 | + return config.copy() |
| 106 | + |
| 107 | + # Magic Methods |
| 108 | + def __len__(self): |
| 109 | + return len(self.config_collection) |
| 110 | + |
| 111 | + def __contains__(self, identifier): |
| 112 | + return identifier in self.config_collection |
| 113 | + |
| 114 | + def __iter__(self): |
| 115 | + for config in self.config_collection.values(): |
| 116 | + yield config.copy() |
| 117 | + |
| 118 | + def __getitem__(self, identifier): |
| 119 | + return self.get(identifier) |
| 120 | + |
| 121 | + def __setitem__(self, identifier, config): |
| 122 | + if not isinstance(config, dict): |
| 123 | + raise InvalidNDConfigError("Config must be a dict when setting via __setitem__.") |
| 124 | + if self.identifier_key not in config: |
| 125 | + raise InvalidNDConfigError(f"Config must contain '{self.identifier_key}' when setting via __setitem__.") |
| 126 | + if config[self.identifier_key] != identifier: |
| 127 | + raise NDIdentifierMismatchError( |
| 128 | + f"Identifier '{identifier}' in key does not match '{self.identifier_key}' value " |
| 129 | + f"'{config[self.identifier_key]}' in config." |
| 130 | + ) |
| 131 | + self.replace(config) |
| 132 | + |
| 133 | + def __delitem__(self, identifier): |
| 134 | + self.remove(identifier) |
| 135 | + |
| 136 | + def __eq__(self, other): |
| 137 | + if not isinstance(other, NDConfigCollection): |
| 138 | + # TODO: Make it works for list and dict as well. For now just raise an error. |
| 139 | + raise InvalidNDConfigError("Can only do __eq__ with another NDConfigCollection instance.") |
| 140 | + |
| 141 | + if self.identifier_key != other.identifier_key: |
| 142 | + return False |
| 143 | + |
| 144 | + return self.config_collection == other.config_collection |
| 145 | + |
| 146 | + def __repr__(self): |
| 147 | + return f"NDConfigCollection(identifier_key='{self.identifier_key}', count={len(self)})" |
| 148 | + |
| 149 | + def __ne__(self, other): |
| 150 | + return not self.__eq__(other) |
| 151 | + |
| 152 | + # Standard Dictionary-like Views |
| 153 | + def keys(self): |
| 154 | + return self.config_collection.keys() |
| 155 | + |
| 156 | + def values(self): |
| 157 | + for v in self.config_collection.values(): |
| 158 | + yield v.copy() |
| 159 | + |
| 160 | + def items(self): |
| 161 | + for k, v in self.config_collection.items(): |
| 162 | + yield k, v.copy() |
| 163 | + |
| 164 | + # Utility/Convenience Functions |
| 165 | + def clear(self): |
| 166 | + self.config_collection.clear() |
| 167 | + |
| 168 | + def find_by_attribute(self, attribute_name, attribute_value): |
| 169 | + matching_configs = [] |
| 170 | + for config in self.values(): |
| 171 | + if config.get(attribute_name) == attribute_value: |
| 172 | + matching_configs.append(config.copy()) |
| 173 | + return matching_configs |
| 174 | + |
| 175 | + def copy(self): |
| 176 | + return NDConfigCollection(self.identifier_key, data=deepcopy(self.config_collection)) |
| 177 | + |
| 178 | + def sanitize(self, keys_to_remove=None, values_to_remove=None, recursive=True, remove_none_values=True): |
| 179 | + if keys_to_remove is None: |
| 180 | + keys_to_remove = [] |
| 181 | + if values_to_remove is None: |
| 182 | + values_to_remove = [] |
| 183 | + |
| 184 | + sanitized_collection = self.copy() |
| 185 | + for k, v in self.items(): |
| 186 | + if k in keys_to_remove: |
| 187 | + del sanitized_collection[k] |
| 188 | + elif v in values_to_remove or (v is None and remove_none_values): |
| 189 | + del sanitized_collection[k] |
| 190 | + elif isinstance(v, dict) and recursive: |
| 191 | + sanitized_collection[k] = self.sanitize(v, keys_to_remove, values_to_remove) |
| 192 | + elif isinstance(v, list) and recursive: |
| 193 | + for index, item in enumerate(v): |
| 194 | + if isinstance(item, dict): |
| 195 | + sanitized_collection[k][index] = self.sanitize(item, keys_to_remove, values_to_remove) |
| 196 | + return sanitized_collection |
| 197 | + |
| 198 | + def get_diff_identifiers(self, other_collection): |
| 199 | + if not isinstance(other_collection, NDConfigCollection): |
| 200 | + raise InvalidNDConfigError("Can only do get_removed_identifiers with another NDConfigCollection instance.") |
| 201 | + |
| 202 | + if self.identifier_key != other_collection.identifier_key: |
| 203 | + raise NDIdentifierMismatchError(f"Cannot do get_removed_identifiers with another NDConfigCollection with different identifier_key. Expected '{self.identifier_key}', got '{other_collection.identifier_key}'.") |
| 204 | + current_identifiers = set(self.config_collection.keys()) |
| 205 | + other_identifiers = set(other_collection.config_collection.keys()) |
| 206 | + |
| 207 | + return list(current_identifiers - other_identifiers) |
0 commit comments