Skip to content

Commit

Permalink
Use importlib.resources to load schema and licenses (#670)
Browse files Browse the repository at this point in the history
  • Loading branch information
edgarrmondragon authored Dec 9, 2023
1 parent 3b08d13 commit dc8e254
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
21 changes: 19 additions & 2 deletions src/poetry/core/json/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from __future__ import annotations

import json
import sys

from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any

import fastjsonschema
Expand All @@ -13,14 +15,29 @@
SCHEMA_DIR = Path(__file__).parent / "schemas"


if sys.version_info < (3, 9):

def _get_schema_file(schema_name: str) -> Path:
return SCHEMA_DIR / f"{schema_name}.json"

else:
from importlib.resources import files

if TYPE_CHECKING:
from importlib.abc import Traversable

def _get_schema_file(schema_name: str) -> Traversable:
return files(__package__) / "schemas" / f"{schema_name}.json"


class ValidationError(ValueError):
pass


def validate_object(obj: dict[str, Any], schema_name: str) -> list[str]:
schema_file = SCHEMA_DIR / f"{schema_name}.json"
schema_file = _get_schema_file(schema_name)

if not schema_file.exists():
if not schema_file.is_file():
raise ValueError(f"Schema {schema_name} does not exist.")

with schema_file.open(encoding="utf-8") as f:
Expand Down
21 changes: 19 additions & 2 deletions src/poetry/core/spdx/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,29 @@

import functools
import json
import sys

from pathlib import Path
from typing import TYPE_CHECKING

from poetry.core.spdx.license import License


if sys.version_info < (3, 9):
from pathlib import Path

def _get_license_file() -> Path:
return Path(__file__).parent / "data" / "licenses.json"

else:
from importlib.resources import files

if TYPE_CHECKING:
from importlib.abc import Traversable

def _get_license_file() -> Traversable:
return files(__package__) / "data" / "licenses.json"


def license_by_id(identifier: str) -> License:
if not identifier:
raise ValueError("A license identifier is required")
Expand All @@ -21,7 +38,7 @@ def license_by_id(identifier: str) -> License:
@functools.lru_cache
def _load_licenses() -> dict[str, License]:
licenses = {}
licenses_file = Path(__file__).parent / "data" / "licenses.json"
licenses_file = _get_license_file()

with licenses_file.open(encoding="utf-8") as f:
data = json.load(f)
Expand Down

0 comments on commit dc8e254

Please sign in to comment.