|
1 | | -class CatalogManager: ... |
| 1 | +"""SuperSTAC Catalog Manager""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +import attr |
| 5 | +from typing import Any, Dict, Optional, Union |
| 6 | + |
| 7 | +from superstac.enums import CatalogOutputFormat |
| 8 | +from superstac.exceptions import ( |
| 9 | + CatalogConfigFileNotFound, |
| 10 | + InvalidCatalogSchemaError, |
| 11 | + InvalidCatalogYAMLError, |
| 12 | +) |
| 13 | +from superstac.models import CatalogEntry, AuthInfo |
| 14 | +import yaml |
| 15 | + |
| 16 | + |
| 17 | +@attr.s(auto_attribs=True) |
| 18 | +class CatalogManager: |
| 19 | + catalogs: Dict[str, CatalogEntry] = attr.Factory(dict) |
| 20 | + |
| 21 | + def register_catalog( |
| 22 | + self, |
| 23 | + name: str, |
| 24 | + url: str, |
| 25 | + is_private: Optional[bool] = False, |
| 26 | + summary: Optional[str] = None, |
| 27 | + auth: Optional[AuthInfo] = None, |
| 28 | + ) -> CatalogEntry: |
| 29 | + """Register a single STAC catalog in state. |
| 30 | +
|
| 31 | + Args: |
| 32 | + name (str): The name of the catalog. |
| 33 | + url (str): A valid URL to the catalog. |
| 34 | + is_private (Optional[bool], optional): Indicates if the catalog requires authentication or not. Defaults to False. |
| 35 | + summary (Optional[str], optional): A short description of the catalog. Defaults to None. |
| 36 | + auth (Optional[AuthInfo], optional): Authentication parameters for the catalog. Defaults to None. |
| 37 | +
|
| 38 | + Raises: |
| 39 | + InvalidCatalogSchemaError: If an invalid parameter is encountered. |
| 40 | +
|
| 41 | + Returns: |
| 42 | + CatalogEntry: The registered STAC catalog. |
| 43 | + """ |
| 44 | + if is_private and auth is None: |
| 45 | + raise InvalidCatalogSchemaError( |
| 46 | + f"Authentication parameters is required for private catalogs. If this is a mistake, you can set 'is_private' to False or provide the {AuthInfo.__annotations__} parameters." |
| 47 | + ) |
| 48 | + self.catalogs[name] = CatalogEntry( |
| 49 | + name=name, |
| 50 | + url=url, |
| 51 | + summary=summary, |
| 52 | + is_private=is_private, |
| 53 | + auth=AuthInfo(**auth.__dict__) if auth and not is_private else None, |
| 54 | + ) |
| 55 | + return self.catalogs[name] |
| 56 | + |
| 57 | + def get_available_catalogs( |
| 58 | + self, format: Union[str, CatalogOutputFormat] = CatalogOutputFormat.DICT |
| 59 | + ) -> list[Union[dict[str, Any], str]]: |
| 60 | + """Get the available STAC catalogs. |
| 61 | +
|
| 62 | + Raises: |
| 63 | + ValueError: When an invalid format is provided. |
| 64 | +
|
| 65 | + Returns: |
| 66 | + list[CatalogEntry]: The list of all available STAC catalogs. |
| 67 | + """ |
| 68 | + if isinstance(format, str): |
| 69 | + try: |
| 70 | + format = CatalogOutputFormat(format.lower()) |
| 71 | + except ValueError: |
| 72 | + raise ValueError(f"Invalid format: {format}") |
| 73 | + |
| 74 | + return [ |
| 75 | + c.as_dict() if format == CatalogOutputFormat.DICT else c.as_json() |
| 76 | + for c in self.catalogs.values() |
| 77 | + if c.is_available |
| 78 | + ] |
| 79 | + |
| 80 | + def load_catalogs_from_config( |
| 81 | + self, file: Union[str, Path, None] = None |
| 82 | + ) -> Dict[str, CatalogEntry]: |
| 83 | + if file is None: |
| 84 | + base_dir = Path(__file__).parent |
| 85 | + file = base_dir / ".superstac.yml" |
| 86 | + |
| 87 | + path = Path(file).expanduser().resolve() |
| 88 | + |
| 89 | + if not path.exists(): |
| 90 | + raise CatalogConfigFileNotFound(f"Config file not found at {path}") |
| 91 | + |
| 92 | + try: |
| 93 | + with open(path, "r") as f: |
| 94 | + data = yaml.safe_load(f) or {} |
| 95 | + except yaml.YAMLError as e: |
| 96 | + raise InvalidCatalogYAMLError(f"YAML parsing failed: {e}") from e |
| 97 | + except Exception as e: |
| 98 | + raise InvalidCatalogYAMLError( |
| 99 | + f"Unexpected error reading config: {e}" |
| 100 | + ) from e |
| 101 | + |
| 102 | + catalogs = data.get("catalogs") |
| 103 | + if not isinstance(catalogs, dict): |
| 104 | + raise InvalidCatalogSchemaError( |
| 105 | + f"Missing or invalid 'catalogs' section in config file: {path}" |
| 106 | + ) |
| 107 | + |
| 108 | + # Register each catalog |
| 109 | + for name, spec in catalogs.items(): |
| 110 | + self.register_catalog( |
| 111 | + name=name, |
| 112 | + url=spec.get("url"), |
| 113 | + is_private=spec.get("is_private", False), |
| 114 | + summary=spec.get("summary"), |
| 115 | + auth=AuthInfo(**spec["auth"]) if "auth" in spec else None, |
| 116 | + ) |
| 117 | + |
| 118 | + return self.catalogs |
| 119 | + |
| 120 | + |
| 121 | +## TEST |
| 122 | + |
| 123 | + |
| 124 | +if __name__ == "__main__": |
| 125 | + # cm = CatalogManager() |
| 126 | + # cm.register_catalog(name="My Catalog", url="https://example.com/stac") |
| 127 | + # print(cm.load_catalogs_from_config()) |
| 128 | + # print(cm.get_available_catalogs()) |
| 129 | + ... |
0 commit comments