🚧 Set schema on location resolve

This commit is contained in:
GeoffreyCoulaud
2023-06-19 23:11:55 +02:00
parent f9000be272
commit e57a2a74df
7 changed files with 32 additions and 15 deletions

View File

@@ -2,6 +2,8 @@ from pathlib import Path
from typing import Callable, Mapping, Iterable
from os import PathLike
from src import shared
PathSegment = str | PathLike | Path
PathSegments = Iterable[PathSegment]
Candidate = PathSegments | Callable[[], PathSegments]
@@ -16,19 +18,24 @@ class Location:
Class representing a filesystem location
* A location may have multiple candidate roots
* From its root, multiple subpaths are named and should exist
* The path in the schema is always favored
* From the candidate root, multiple subpaths should exist for it to be valid
* When resolved, the schema is updated with the picked chosen
"""
schema_key: str
candidates: Iterable[Candidate]
paths: Mapping[str, tuple[bool, PathSegments]]
root: Path = None
def __init__(
self,
schema_key: str,
candidates: Iterable[Candidate],
paths: Mapping[str, tuple[bool, PathSegments]],
) -> None:
super().__init__()
self.schema_key = schema_key
self.candidates = candidates
self.paths = paths
@@ -47,16 +54,26 @@ class Location:
def resolve(self) -> None:
"""Choose a root path from the candidates for the location.
If none fits, raise a UnresolvableLocationError"""
if self.root is not None:
return
for candidate in self.candidates:
if callable(candidate):
candidate = candidate()
# Get the schema candidate
schema_candidate = shared.schema.get_string(self.schema_key)
# Find the first matching candidate
for candidate in (schema_candidate, *self.candidates):
candidate = Path(candidate).expanduser()
if self.check_candidate(candidate):
self.root = candidate
return
raise UnresolvableLocationError()
if not self.check_candidate(candidate):
continue
self.root = candidate
break
else:
# No good candidate found
raise UnresolvableLocationError()
# Update the schema with the found candidate
shared.schema.set_string(self.schema_key, str(candidate))
def __getitem__(self, key: str):
"""Get the computed path from its key for the location"""