Skip to content

Commit

Permalink
Use pkgutil.get_data for zip-safe resource loading
Browse files Browse the repository at this point in the history
When running from a Zip file (`zipapp`, `*.pyz`), loading resources
from package data can not be done by directly reading files relative
to `__file__`, since there is no valid path on the file system for
zipped files.

Using `pkgutil.get_data` ensures that loading files from a Zip archive
is handled accordingly.

Resolved: python-poetry#2965
  • Loading branch information
sinoroc committed Sep 25, 2020
1 parent 977832e commit aed9bd7
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions poetry/json/__init__.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
import json
import os
import pkgutil

from io import open
from typing import List

import jsonschema


SCHEMA_DIR = os.path.join(os.path.dirname(__file__), "schemas")


class ValidationError(ValueError):

pass


def validate_object(obj, schema_name): # type: (dict, str) -> List[str]
schema = os.path.join(SCHEMA_DIR, "{}.json".format(schema_name))

if not os.path.exists(schema):
# 'poetry.json.schemas' is not an acceptable package (it is a namespace
# package since it does not contain an '__init__.py' initializer). So we
# use 'poetry.json' and the rest is part of the resource name.
schema_resource_name = "schemas/{}.json".format(schema_name)

schema_binary = pkgutil.get_data("poetry.json", schema_resource_name)
if schema_binary is None:
raise ValueError("Schema {} does not exist.".format(schema_name))

with open(schema, encoding="utf-8") as f:
schema = json.loads(f.read())
schema = json.loads(schema_binary)

validator = jsonschema.Draft7Validator(schema)
validation_errors = sorted(validator.iter_errors(obj), key=lambda e: e.path)
Expand Down

0 comments on commit aed9bd7

Please sign in to comment.