Skip to content

Commit

Permalink
files: lookup resources via importlib if available
Browse files Browse the repository at this point in the history
  • Loading branch information
Dav1dde committed May 20, 2024
1 parent 5dd44f1 commit 976973c
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions glad/files/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,19 @@
from urllib.parse import urlparse

try:
from pkg_resources import resource_exists, resource_stream
from importlib.resources import files

def resource_open(package, name, *args, **kwargs):
return files(package).joinpath(name).open(*args, **kwargs)
except ImportError:
def resource_exists(*args, **kwargs):
return False
try:
from pkg_resources import resource_stream

def resource_stream(*args, **kwargs):
return None
def resource_open(package, name, *args, **kwargs):
return resource_stream(package, name)
except ImportError:
def resource_open(package, name, *args, **kwargs):
raise FileNotFoundError


BASE_PATH = os.path.abspath(os.path.dirname(__file__))
Expand All @@ -29,12 +35,13 @@ class GladFileException(Exception):
def open_local(name, *args, **kwargs):
# use pkg_resources when available, makes it work in zipped modules
# or other environments
if resource_exists(__name__, name):
logger.info('opening packaged resource: %r', name)
return resource_stream(__name__, name)
try:
return resource_open(__name__, name, *args, **kwargs)
except FileNotFoundError:
pass

# fallback to filesystem
logger.info('opening packaged path: %r', name)
logger.info('falling back to packaged path: %r', name)
local_path = os.path.normpath(os.path.join(BASE_PATH, os.path.join(name)))
if not local_path.startswith(BASE_PATH):
raise GladFileException('unsafe file path, won\'t open {!r}'.format(local_path))
Expand Down

0 comments on commit 976973c

Please sign in to comment.