fmu-settings 0.3.2__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fmu-settings might be problematic. Click here for more details.

Files changed (47) hide show
  1. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/PKG-INFO +4 -1
  2. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/pyproject.toml +3 -0
  3. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/_fmu_dir.py +4 -0
  4. fmu_settings-0.5.0/src/fmu/settings/_global_config.py +270 -0
  5. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/_init.py +16 -8
  6. fmu_settings-0.5.0/src/fmu/settings/_resources/config_managers.py +49 -0
  7. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/_resources/lock_manager.py +23 -2
  8. fmu_settings-0.3.2/src/fmu/settings/_resources/config_managers.py → fmu_settings-0.5.0/src/fmu/settings/_resources/pydantic_resource_manager.py +107 -42
  9. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/_version.py +3 -3
  10. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu_settings.egg-info/PKG-INFO +4 -1
  11. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu_settings.egg-info/SOURCES.txt +2 -0
  12. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu_settings.egg-info/requires.txt +3 -0
  13. fmu_settings-0.5.0/tests/conftest.py +349 -0
  14. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/tests/test_fmu_dir.py +25 -0
  15. fmu_settings-0.5.0/tests/test_global_config.py +484 -0
  16. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/tests/test_init.py +18 -0
  17. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/tests/test_resources/test_lock_manager.py +66 -0
  18. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/tests/test_resources/test_resource_managers.py +24 -0
  19. fmu_settings-0.3.2/src/fmu/settings/_resources/pydantic_resource_manager.py +0 -103
  20. fmu_settings-0.3.2/tests/conftest.py +0 -164
  21. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/.coveragerc +0 -0
  22. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/.github/pull_request_template.md +0 -0
  23. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/.github/workflows/ci.yml +0 -0
  24. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/.github/workflows/codeql.yml +0 -0
  25. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/.github/workflows/publish.yml +0 -0
  26. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/.gitignore +0 -0
  27. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/CONTRIBUTING.md +0 -0
  28. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/LICENSE +0 -0
  29. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/README.md +0 -0
  30. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/SECURITY.md +0 -0
  31. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/setup.cfg +0 -0
  32. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/__init__.py +0 -0
  33. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/__init__.py +0 -0
  34. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/_logging.py +0 -0
  35. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/_resources/__init__.py +0 -0
  36. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/models/__init__.py +0 -0
  37. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/models/_enums.py +0 -0
  38. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/models/_mappings.py +0 -0
  39. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/models/lock_info.py +0 -0
  40. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/models/project_config.py +0 -0
  41. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/models/user_config.py +0 -0
  42. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/py.typed +0 -0
  43. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu/settings/types.py +0 -0
  44. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu_settings.egg-info/dependency_links.txt +0 -0
  45. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/src/fmu_settings.egg-info/top_level.txt +0 -0
  46. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/tests/test_resources/test_project_config.py +0 -0
  47. {fmu_settings-0.3.2 → fmu_settings-0.5.0}/tests/test_resources/test_user_config.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fmu-settings
3
- Version: 0.3.2
3
+ Version: 0.5.0
4
4
  Summary: A library for managing FMU settings
5
5
  Author-email: Equinor <fg-fmu_atlas@equinor.com>
6
6
  License: GPL-3.0
@@ -17,7 +17,9 @@ Classifier: Natural Language :: English
17
17
  Requires-Python: >=3.11
18
18
  Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
+ Requires-Dist: PyYAML
20
21
  Requires-Dist: annotated_types
22
+ Requires-Dist: fmu-config
21
23
  Requires-Dist: fmu-datamodels
22
24
  Requires-Dist: pydantic
23
25
  Provides-Extra: dev
@@ -27,6 +29,7 @@ Requires-Dist: pytest-cov; extra == "dev"
27
29
  Requires-Dist: pytest-mock; extra == "dev"
28
30
  Requires-Dist: pytest-xdist; extra == "dev"
29
31
  Requires-Dist: ruff; extra == "dev"
32
+ Requires-Dist: types-PyYAML; extra == "dev"
30
33
  Dynamic: license-file
31
34
 
32
35
  # fmu-settings
@@ -28,7 +28,9 @@ classifiers = [
28
28
  ]
29
29
  dynamic = ["version"]
30
30
  dependencies = [
31
+ "PyYAML",
31
32
  "annotated_types", # Dependency in Pydantic also
33
+ "fmu-config",
32
34
  "fmu-datamodels",
33
35
  "pydantic",
34
36
  ]
@@ -41,6 +43,7 @@ dev = [
41
43
  "pytest-mock",
42
44
  "pytest-xdist",
43
45
  "ruff",
46
+ "types-PyYAML",
44
47
  ]
45
48
 
46
49
  [project.urls]
@@ -82,7 +82,9 @@ class FMUDirectoryBase:
82
82
  FileNotFoundError: If config file doesn't exist
83
83
  ValueError: If the updated config is invalid
84
84
  """
85
+ logger.info(f"Setting {key} in {self.path}")
85
86
  self.config.set(key, value)
87
+ logger.debug(f"Set {key} to {value}")
86
88
 
87
89
  def update_config(
88
90
  self: Self, updates: dict[str, Any]
@@ -147,6 +149,7 @@ class FMUDirectoryBase:
147
149
  relative_path: Path relative to the .fmu directory
148
150
  data: Bytes to write
149
151
  """
152
+ self._lock.ensure_can_write()
150
153
  file_path = self.get_file_path(relative_path)
151
154
  file_path.parent.mkdir(parents=True, exist_ok=True)
152
155
 
@@ -163,6 +166,7 @@ class FMUDirectoryBase:
163
166
  content: Text content to write
164
167
  encoding: Text encoding to use. Default utf-8
165
168
  """
169
+ self._lock.ensure_can_write()
166
170
  file_path = self.get_file_path(relative_path)
167
171
  file_path.parent.mkdir(parents=True, exist_ok=True)
168
172
 
@@ -0,0 +1,270 @@
1
+ """Functions related to finding and validating an existing global configuration."""
2
+
3
+ from pathlib import Path
4
+ from typing import Final
5
+
6
+ from pydantic import ValidationError
7
+
8
+ from fmu.config.utilities import yaml_load
9
+ from fmu.datamodels.fmu_results.global_configuration import GlobalConfiguration
10
+
11
+ from ._logging import null_logger
12
+
13
+ logger: Final = null_logger(__name__)
14
+
15
+
16
+ class InvalidGlobalConfigurationError(ValueError):
17
+ """Raised when a GlobalConfiguration contains invalid or disallowed content.
18
+
19
+ This includes Drogon test data or other disallowed masterdata.
20
+ This error is only raised when strict validation is enabled.
21
+ """
22
+
23
+
24
+ # These should all be normalized to lower case.
25
+ INVALID_NAMES: Final[tuple[str, ...]] = (
26
+ "drogon",
27
+ "drogon_2020",
28
+ "drogon_has_no_stratcolumn",
29
+ )
30
+ INVALID_UUIDS: Final[tuple[str, ...]] = (
31
+ "ad214d85-dac7-19da-e053-c918a4889309",
32
+ "ad214d85-8a1d-19da-e053-c918a4889310",
33
+ "00000000-0000-0000-0000-000000000000",
34
+ )
35
+ INVALID_STRAT_NAMES: Final[tuple[str, ...]] = (
36
+ "basevolantis",
37
+ "basetherys",
38
+ "basevalysar",
39
+ "basevolon",
40
+ "therys",
41
+ "toptherys",
42
+ "topvolantis",
43
+ "topvolon",
44
+ "topvalysar",
45
+ "valysar",
46
+ "volantis",
47
+ "volon",
48
+ )
49
+
50
+
51
+ def validate_global_configuration_strictly(cfg: GlobalConfiguration) -> None: # noqa: PLR0912
52
+ """Does stricter checks against a valid GlobalConfiguration file.
53
+
54
+ This is to prevent importing existing but incorrect data that should not make it
55
+ into a project .fmu configuration. An example of this is Drogon masterdata.
56
+
57
+ Args:
58
+ cfg: A GlobalConfiguration instance to be validated
59
+
60
+ Raises:
61
+ InvalidGlobalConfigurationError: If some value in the GlobalConfiguration
62
+ is invalid or not allowed
63
+ """
64
+ # Check model and access
65
+ if cfg.model.name.lower() in INVALID_NAMES:
66
+ raise InvalidGlobalConfigurationError(
67
+ f"Invalid name in 'model': {cfg.model.name}"
68
+ )
69
+ if cfg.access.asset.name.lower() in INVALID_NAMES:
70
+ raise InvalidGlobalConfigurationError(
71
+ f"Invalid name in 'access.asset': {cfg.access.asset.name}"
72
+ )
73
+
74
+ # Check masterdata
75
+
76
+ # smda.country
77
+ for country in cfg.masterdata.smda.country:
78
+ if str(country.uuid) in INVALID_UUIDS:
79
+ raise InvalidGlobalConfigurationError(
80
+ f"Invalid SMDA UUID in 'smda.country': {country.uuid}"
81
+ )
82
+
83
+ # smda.discovery
84
+ for discovery in cfg.masterdata.smda.discovery:
85
+ if discovery.short_identifier.lower() in INVALID_NAMES:
86
+ raise InvalidGlobalConfigurationError(
87
+ f"Invalid SMDA short identifier in 'smda.discovery': "
88
+ f"{discovery.short_identifier}"
89
+ )
90
+ if str(discovery.uuid) in INVALID_UUIDS:
91
+ raise InvalidGlobalConfigurationError(
92
+ f"Invalid SMDA UUID in 'smda.discovery': {discovery.uuid}"
93
+ )
94
+
95
+ # smda.field
96
+ for field in cfg.masterdata.smda.field:
97
+ if field.identifier.lower() in INVALID_NAMES:
98
+ raise InvalidGlobalConfigurationError(
99
+ f"Invalid SMDA identifier in 'smda.field': {field.identifier}"
100
+ )
101
+ if str(field.uuid) in INVALID_UUIDS:
102
+ raise InvalidGlobalConfigurationError(
103
+ f"Invalid SMDA UUID in 'smda.field': {field.uuid}"
104
+ )
105
+
106
+ # smda.coordinate_system
107
+ if (coord_uuid := str(cfg.masterdata.smda.coordinate_system.uuid)) in INVALID_UUIDS:
108
+ raise InvalidGlobalConfigurationError(
109
+ f"Invalid SMDA UUID in 'smda.coordinate_system': {coord_uuid}"
110
+ )
111
+
112
+ # smda.stratigraphic_column
113
+ strat = cfg.masterdata.smda.stratigraphic_column
114
+ if strat.identifier.lower() in INVALID_NAMES:
115
+ raise InvalidGlobalConfigurationError(
116
+ f"Invalid SMDA identifier in 'smda.stratigraphic_column': "
117
+ f"{strat.identifier}"
118
+ )
119
+ if str(strat.uuid) in INVALID_UUIDS:
120
+ raise InvalidGlobalConfigurationError(
121
+ f"Invalid SMDA UUID in 'smda.stratigraphic_column': {strat.uuid}"
122
+ )
123
+
124
+ # Check stratigraphy
125
+
126
+ if cfg.stratigraphy:
127
+ for key in cfg.stratigraphy:
128
+ if key.lower() in INVALID_STRAT_NAMES:
129
+ raise InvalidGlobalConfigurationError(
130
+ f"Invalid stratigraphy name in 'smda.stratigraphy': {key}"
131
+ )
132
+
133
+
134
+ def load_global_configuration_if_present(
135
+ path: Path, fmu_load: bool = False
136
+ ) -> GlobalConfiguration | None:
137
+ """Loads a global config/global variables at a path.
138
+
139
+ This loads via fmu-config, which is capable of loading a global _config_, which is
140
+ different from the global _variables_ in that it may still be in separate files
141
+ linked by the custom '!include' directive.
142
+
143
+ Args:
144
+ path: The path to the yaml file
145
+ fmu_load: Whether or not to load in the custom 'fmu' format. Default False.
146
+
147
+ Returns:
148
+ GlobalConfiguration instance or None.
149
+ """
150
+ loader = "fmu" if fmu_load else "standard"
151
+ try:
152
+ global_variables_dict = yaml_load(path, loader=loader)
153
+ global_config = GlobalConfiguration.model_validate(global_variables_dict)
154
+ logger.debug(f"Global variables at {path} has valid settings data")
155
+ except ValidationError as e:
156
+ logger.debug(f"Global variables at {path} failed validation: {e}")
157
+ return None
158
+ except Exception as e:
159
+ logger.debug(
160
+ f"Failed to load global variables at {path}: {type(e).__name__}: {e}"
161
+ )
162
+ return None
163
+ return global_config
164
+
165
+
166
+ def _find_global_variables_file(paths: list[Path]) -> GlobalConfiguration | None:
167
+ """Finds a valid global variables file, or not.
168
+
169
+ This is the _output_ file after fmuconfig is run.
170
+
171
+ Args:
172
+ paths: A list of Paths to check.
173
+
174
+ Returns:
175
+ A validated GlobalConfiguration or None.
176
+ """
177
+ for path in paths:
178
+ if not path.exists():
179
+ continue
180
+
181
+ global_variables_path = path
182
+ # If the path is a dir, and doesn't contain the right file, move on.
183
+ if path.is_dir():
184
+ global_variables_path = path / "global_variables.yml"
185
+ if not global_variables_path.exists():
186
+ continue
187
+
188
+ logger.info(f"Found global variables at {path}")
189
+ global_config = load_global_configuration_if_present(global_variables_path)
190
+ if not global_config:
191
+ continue
192
+ return global_config
193
+
194
+ return None
195
+
196
+
197
+ def _find_global_config_file(paths: list[Path]) -> GlobalConfiguration | None:
198
+ """Finds a valid global configuration file, or not.
199
+
200
+ This is the _input_ file, before fmuconfig is run.
201
+
202
+ Args:
203
+ paths: A list of Paths to check.
204
+
205
+ Returns:
206
+ A validated GlobalConfiguration or None.
207
+ """
208
+ for path in paths:
209
+ if not path.exists():
210
+ continue
211
+
212
+ logger.info(f"Found global config at {path}")
213
+ # May be global_config*.yml or global_master*.yml
214
+ for global_config_path in path.glob("**/global*.yml"):
215
+ global_config = load_global_configuration_if_present(
216
+ global_config_path, fmu_load=True
217
+ )
218
+ if not global_config:
219
+ continue
220
+ return global_config
221
+
222
+ return None
223
+
224
+
225
+ def find_global_config(
226
+ base_path: str | Path,
227
+ extra_output_paths: list[Path] | None = None,
228
+ extra_input_dirs: list[Path] | None = None,
229
+ strict: bool = True,
230
+ ) -> GlobalConfiguration | None:
231
+ """Try to locate a global configuration with valid masterdata in known location.
232
+
233
+ Extra paths may be provided
234
+
235
+ Args:
236
+ base_path: The path to the project root
237
+ extra_output_paths: A list of extra paths to a global _variables_.
238
+ extra_input_dirs: A list of extra dirs to a global _config_ might be.
239
+ strict: If True, valid data but invalid _content_ is disallowed, i.e. Drogon
240
+ data. Default True.
241
+
242
+ Returns:
243
+ A valid GlobalConfiguration instance, or None.
244
+ """
245
+ base_path = Path(base_path)
246
+
247
+ # Loads with 'fmu_load=False'
248
+ known_output_paths = [base_path / "fmuconfig/output/global_variables.yml"]
249
+ if extra_output_paths:
250
+ known_output_paths += extra_output_paths
251
+
252
+ global_config = _find_global_variables_file(known_output_paths)
253
+ if global_config:
254
+ if strict:
255
+ validate_global_configuration_strictly(global_config)
256
+ return global_config
257
+
258
+ # Loads with 'fmu_load=True'
259
+ known_input_paths = [base_path / "fmuconfig/input"]
260
+ if extra_input_dirs:
261
+ known_input_paths += extra_input_dirs
262
+
263
+ global_config = _find_global_config_file(known_input_paths)
264
+ if global_config:
265
+ if strict:
266
+ validate_global_configuration_strictly(global_config)
267
+ return global_config
268
+
269
+ logger.info("No global variables or config with valid settings data found.")
270
+ return None
@@ -4,6 +4,8 @@ from pathlib import Path
4
4
  from textwrap import dedent
5
5
  from typing import Any, Final
6
6
 
7
+ from fmu.datamodels.fmu_results.global_configuration import GlobalConfiguration
8
+
7
9
  from ._fmu_dir import ProjectFMUDirectory, UserFMUDirectory
8
10
  from ._logging import null_logger
9
11
  from .models.project_config import ProjectConfig
@@ -66,7 +68,9 @@ def _create_fmu_directory(base_path: Path) -> None:
66
68
 
67
69
 
68
70
  def init_fmu_directory(
69
- base_path: str | Path, config_data: ProjectConfig | dict[str, Any] | None = None
71
+ base_path: str | Path,
72
+ config_data: ProjectConfig | dict[str, Any] | None = None,
73
+ global_config: GlobalConfiguration | None = None,
70
74
  ) -> ProjectFMUDirectory:
71
75
  """Creates and initializes a .fmu directory.
72
76
 
@@ -74,9 +78,11 @@ def init_fmu_directory(
74
78
  function.
75
79
 
76
80
  Args:
77
- base_path: Directory where .fmu should be created
81
+ base_path: Directory where .fmu should be created.
78
82
  config_data: Optional ProjectConfig instance or dictionary with configuration
79
- data
83
+ data.
84
+ global_config: Optional GlobaConfiguration instance with existing global config
85
+ data.
80
86
 
81
87
  Returns:
82
88
  Instance of FMUDirectory
@@ -98,12 +104,14 @@ def init_fmu_directory(
98
104
  fmu_dir.config.reset()
99
105
  if config_data:
100
106
  if isinstance(config_data, ProjectConfig):
101
- config_dict = config_data.model_dump()
102
- fmu_dir.update_config(config_dict)
103
- elif isinstance(config_data, dict):
104
- fmu_dir.update_config(config_data)
107
+ config_data = config_data.model_dump()
108
+ fmu_dir.update_config(config_data)
105
109
 
106
- logger.debug(f"Successfully initialized .fmu directory at '{fmu_dir}'")
110
+ if global_config:
111
+ for key, value in global_config.model_dump().items():
112
+ fmu_dir.set_config_value(key, value)
113
+
114
+ logger.info(f"Successfully initialized .fmu directory at '{fmu_dir}'")
107
115
  return fmu_dir
108
116
 
109
117
 
@@ -0,0 +1,49 @@
1
+ """The generic configuration file in a .fmu directory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Final, Self
7
+
8
+ from fmu.settings._logging import null_logger
9
+ from fmu.settings.models.project_config import ProjectConfig
10
+ from fmu.settings.models.user_config import UserConfig
11
+
12
+ from .pydantic_resource_manager import (
13
+ MutablePydanticResourceManager,
14
+ )
15
+
16
+ if TYPE_CHECKING:
17
+ # Avoid circular dependency for type hint in __init__ only
18
+ from fmu.settings._fmu_dir import (
19
+ ProjectFMUDirectory,
20
+ UserFMUDirectory,
21
+ )
22
+
23
+ logger: Final = null_logger(__name__)
24
+
25
+
26
+ class ProjectConfigManager(MutablePydanticResourceManager[ProjectConfig]):
27
+ """Manages the .fmu configuration file in a project."""
28
+
29
+ def __init__(self: Self, fmu_dir: ProjectFMUDirectory) -> None:
30
+ """Initializes the ProjectConfig resource manager."""
31
+ super().__init__(fmu_dir, ProjectConfig)
32
+
33
+ @property
34
+ def relative_path(self: Self) -> Path:
35
+ """Returns the relative path to the config file."""
36
+ return Path("config.json")
37
+
38
+
39
+ class UserConfigManager(MutablePydanticResourceManager[UserConfig]):
40
+ """Manages the .fmu configuration file in a user's home directory."""
41
+
42
+ def __init__(self: Self, fmu_dir: UserFMUDirectory) -> None:
43
+ """Initializes the UserConfig resource manager."""
44
+ super().__init__(fmu_dir, UserConfig)
45
+
46
+ @property
47
+ def relative_path(self: Self) -> Path:
48
+ """Returns the relative path to the config file."""
49
+ return Path("config.json")
@@ -168,6 +168,25 @@ class LockManager(PydanticResourceManager[LockInfo]):
168
168
  return False
169
169
  return self._is_mine(self._cache) and not self._is_stale()
170
170
 
171
+ def ensure_can_write(self: Self) -> None:
172
+ """Raise PermissionError if another process currently holds the lock."""
173
+ try:
174
+ lock_info = self.load(force=True, store_cache=False)
175
+ except Exception:
176
+ lock_info = None
177
+
178
+ if (
179
+ self.exists
180
+ and lock_info is not None
181
+ and not self.is_acquired()
182
+ and not self._is_stale(lock_info=lock_info)
183
+ ):
184
+ raise PermissionError(
185
+ "Cannot write to .fmu directory because it is locked by "
186
+ f"{lock_info.user}@{lock_info.hostname} (PID: {lock_info.pid}). "
187
+ f"Lock expires at {time.ctime(lock_info.expires_at)}."
188
+ )
189
+
171
190
  def refresh(self: Self) -> None:
172
191
  """Refresh/extend the lock expiration time.
173
192
 
@@ -239,9 +258,11 @@ class LockManager(PydanticResourceManager[LockInfo]):
239
258
  except Exception:
240
259
  return None
241
260
 
242
- def _is_stale(self: Self) -> bool:
261
+ def _is_stale(self: Self, lock_info: LockInfo | None = None) -> bool:
243
262
  """Check if existing lock is stale (expired or process dead)."""
244
- lock_info = self._safe_load()
263
+ if lock_info is None:
264
+ lock_info = self._safe_load()
265
+
245
266
  if not lock_info:
246
267
  return True
247
268
 
@@ -1,43 +1,124 @@
1
- """The generic configuration file in a .fmu directory."""
1
+ """Contains the base class used for interacting with resources."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from pathlib import Path
6
- from typing import TYPE_CHECKING, Any, Final, Self, TypeVar
5
+ import json
6
+ from typing import TYPE_CHECKING, Any, Generic, Self, TypeVar
7
7
 
8
- from pydantic import ValidationError
8
+ from pydantic import BaseModel, ValidationError
9
9
 
10
- from fmu.settings._logging import null_logger
11
- from fmu.settings.models.project_config import ProjectConfig
12
- from fmu.settings.models.user_config import UserConfig
13
- from fmu.settings.types import ResettableBaseModel # noqa: TC001
14
-
15
- from .pydantic_resource_manager import PydanticResourceManager
10
+ from fmu.settings.types import ResettableBaseModel
16
11
 
17
12
  if TYPE_CHECKING:
18
13
  # Avoid circular dependency for type hint in __init__ only
19
- from fmu.settings._fmu_dir import (
20
- FMUDirectoryBase,
21
- ProjectFMUDirectory,
22
- UserFMUDirectory,
23
- )
14
+ from pathlib import Path
24
15
 
25
- logger: Final = null_logger(__name__)
16
+ from fmu.settings._fmu_dir import FMUDirectoryBase
26
17
 
27
- T = TypeVar("T", bound=ResettableBaseModel)
18
+ PydanticResource = TypeVar("PydanticResource", bound=BaseModel)
19
+ MutablePydanticResource = TypeVar("MutablePydanticResource", bound=ResettableBaseModel)
28
20
 
29
21
 
30
- class ConfigManager(PydanticResourceManager[T]):
31
- """Manages the .fmu configuration file."""
22
+ class PydanticResourceManager(Generic[PydanticResource]):
23
+ """Base class for managing resources represented by Pydantic models."""
32
24
 
33
- def __init__(self: Self, fmu_dir: FMUDirectoryBase, config: type[T]) -> None:
34
- """Initializes the Config resource manager."""
35
- super().__init__(fmu_dir, config)
25
+ def __init__(
26
+ self: Self, fmu_dir: FMUDirectoryBase, model_class: type[PydanticResource]
27
+ ) -> None:
28
+ """Initializes the resource manager.
29
+
30
+ Args:
31
+ fmu_dir: The FMUDirectory instance
32
+ model_class: The Pydantic model class this manager handles
33
+ """
34
+ self.fmu_dir = fmu_dir
35
+ self.model_class = model_class
36
+ self._cache: PydanticResource | None = None
36
37
 
37
38
  @property
38
39
  def relative_path(self: Self) -> Path:
39
- """Returns the relative path to the config file."""
40
- return Path("config.json")
40
+ """Returns the path to the resource file _inside_ the .fmu directory.
41
+
42
+ Must be implemented by subclasses.
43
+ """
44
+ raise NotImplementedError
45
+
46
+ @property
47
+ def path(self: Self) -> Path:
48
+ """Returns the full path to the resource file."""
49
+ return self.fmu_dir.get_file_path(self.relative_path)
50
+
51
+ @property
52
+ def exists(self: Self) -> bool:
53
+ """Returns whether or not the resource exists."""
54
+ return self.path.exists()
55
+
56
+ def load(
57
+ self: Self, force: bool = False, store_cache: bool = True
58
+ ) -> PydanticResource:
59
+ """Loads the resource from disk and validates it as a Pydantic model.
60
+
61
+ Args:
62
+ force: Force a re-read even if the file is already cached.
63
+ store_cache: Whether or not to cache the loaded model internally. This is
64
+ best used with 'force=True' because if a model is already stored in
65
+ _cache it will be returned without re-loading. Default True.
66
+
67
+ Returns:
68
+ Validated Pydantic model
69
+
70
+ Raises:
71
+ ValueError: If the resource file is missing or data does not match the
72
+ model schema
73
+ """
74
+ if self._cache is None or force:
75
+ if not self.exists:
76
+ raise FileNotFoundError(
77
+ f"Resource file for '{self.__class__.__name__}' not found "
78
+ f"at: '{self.path}'"
79
+ )
80
+
81
+ try:
82
+ content = self.fmu_dir.read_text_file(self.relative_path)
83
+ data = json.loads(content)
84
+ validated_model = self.model_class.model_validate(data)
85
+ if store_cache:
86
+ self._cache = validated_model
87
+ else:
88
+ return validated_model
89
+ except ValidationError as e:
90
+ raise ValueError(
91
+ f"Invalid content in resource file for '{self.__class__.__name__}: "
92
+ f"'{e}"
93
+ ) from e
94
+ except json.JSONDecodeError as e:
95
+ raise ValueError(
96
+ f"Invalid JSON in resource file for '{self.__class__.__name__}': "
97
+ f"'{e}'"
98
+ ) from e
99
+
100
+ return self._cache
101
+
102
+ def save(self: Self, model: PydanticResource) -> None:
103
+ """Save the Pydantic model to disk.
104
+
105
+ Args:
106
+ model: Validated Pydantic model instance
107
+ """
108
+ self.fmu_dir._lock.ensure_can_write()
109
+ json_data = model.model_dump_json(by_alias=True, indent=2)
110
+ self.fmu_dir.write_text_file(self.relative_path, json_data)
111
+ self._cache = model
112
+
113
+
114
+ class MutablePydanticResourceManager(PydanticResourceManager[MutablePydanticResource]):
115
+ """Manages the .fmu configuration file."""
116
+
117
+ def __init__(
118
+ self: Self, fmu_dir: FMUDirectoryBase, config: type[MutablePydanticResource]
119
+ ) -> None:
120
+ """Initializes the Config resource manager."""
121
+ super().__init__(fmu_dir, config)
41
122
 
42
123
  def _get_dot_notation_key(
43
124
  self: Self, config_dict: dict[str, Any], key: str, default: Any = None
@@ -144,7 +225,7 @@ class ConfigManager(PydanticResourceManager[T]):
144
225
  f"at: '{self.path}' when setting key {key}"
145
226
  ) from e
146
227
 
147
- def update(self: Self, updates: dict[str, Any]) -> T:
228
+ def update(self: Self, updates: dict[str, Any]) -> MutablePydanticResource:
148
229
  """Updates multiple configuration values at once.
149
230
 
150
231
  Args:
@@ -183,7 +264,7 @@ class ConfigManager(PydanticResourceManager[T]):
183
264
 
184
265
  return updated_config
185
266
 
186
- def reset(self: Self) -> T:
267
+ def reset(self: Self) -> MutablePydanticResource:
187
268
  """Resets the configuration to defaults.
188
269
 
189
270
  Returns:
@@ -192,19 +273,3 @@ class ConfigManager(PydanticResourceManager[T]):
192
273
  config = self.model_class.reset()
193
274
  self.save(config)
194
275
  return config
195
-
196
-
197
- class ProjectConfigManager(ConfigManager[ProjectConfig]):
198
- """Manages the .fmu configuration file in a project."""
199
-
200
- def __init__(self: Self, fmu_dir: ProjectFMUDirectory) -> None:
201
- """Initializes the ProjectConfig resource manager."""
202
- super().__init__(fmu_dir, ProjectConfig)
203
-
204
-
205
- class UserConfigManager(ConfigManager[UserConfig]):
206
- """Manages the .fmu configuration file in a user's home directory."""
207
-
208
- def __init__(self: Self, fmu_dir: UserFMUDirectory) -> None:
209
- """Initializes the UserConfig resource manager."""
210
- super().__init__(fmu_dir, UserConfig)
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.3.2'
32
- __version_tuple__ = version_tuple = (0, 3, 2)
31
+ __version__ = version = '0.5.0'
32
+ __version_tuple__ = version_tuple = (0, 5, 0)
33
33
 
34
- __commit_id__ = commit_id = 'g9ea88b68f'
34
+ __commit_id__ = commit_id = 'g53ff72079'