Skip to content

Commit

Permalink
staticx: Use importlib.resources over pkg_resources for asset access
Browse files Browse the repository at this point in the history
pkg_resources is deprecated:
https://setuptools.pypa.io/en/latest/pkg_resources.html

This prefers importlib.metadata (introduced in Python 3.8) and uses the
backport importlib_metadata for Python 3.7 (to be removed in #264).

This instead uses importlib.resources.files() (introduced in Python 3.9)
and uses the backport importlib_resources for Python 3.7-3.8 (to be
removed in #264, #265).

This was chosen over the alternative of using the deprecated (as of
Python 3.11) function importlib.resources.open_binary() (introduced in
Python 3.7), as it seems simpler.
  • Loading branch information
JonathonReinhart committed Jan 14, 2024
1 parent 77ccfa5 commit 0cec14f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ dependencies = [
"pyelftools",
# TODO(#264): Remove when Python 3.7 support is removed.
"importlib_metadata; python_version<'3.8'",
# TODO(#265): Remove when Python 3.8 support is removed.
"importlib_resources; python_version<'3.9'",
]
description = "Build static self-extracting app from dynamic executable"
license = {file = "LICENSE.txt"}
Expand Down
12 changes: 10 additions & 2 deletions staticx/assets.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import pkg_resources
import sys
from .utils import copy_fileobj_to_tempfile

# TODO(#265): Remove backport when Python 3.8 support is removed.
# importlib.resources.files() was added in Python 3.9.
if sys.version_info >= (3, 9):
import importlib.resources as importlib_resources
else:
import importlib_resources # backport


def locate_asset(name, debug):
mode = 'debug' if debug else 'release'
path = '/'.join(('assets', mode, name))
try:
return pkg_resources.resource_stream(__name__, path)
return importlib_resources.files("staticx").joinpath(path).open("rb")
except FileNotFoundError:
raise KeyError(f"Asset not found: {name!r} (mode={mode!r})")

Expand Down
2 changes: 1 addition & 1 deletion staticx/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def get_version():
# Otherwise, we're either installed (e.g. via pip), or running from
# an 'sdist' source distribution, and have a local PKG_INFO file.

# TODO(#242): Remove backport when Python 3.7 support is removed.
# TODO(#264): Remove backport when Python 3.7 support is removed.
if sys.version_info >= (3, 8):
import importlib.metadata as importlib_metadata
else:
Expand Down

0 comments on commit 0cec14f

Please sign in to comment.