Skip to content

Commit

Permalink
fix: Replace use of imp with importlib
Browse files Browse the repository at this point in the history
Original PR and information found at #1187
  • Loading branch information
arsenetar committed Feb 19, 2024
1 parent 9f22835 commit 13dd00c
Showing 1 changed file with 8 additions and 42 deletions.
50 changes: 8 additions & 42 deletions hscommon/pygettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
#

import os
import imp
import importlib.machinery
import importlib.util
import sys
import glob
import token
Expand Down Expand Up @@ -110,7 +111,7 @@ def _visit_pyfiles(list, dirname, names):
# get extension for python source files
if "_py_ext" not in globals():
global _py_ext
_py_ext = [triple[0] for triple in imp.get_suffixes() if triple[2] == imp.PY_SOURCE][0]
_py_ext = importlib.machinery.SOURCE_SUFFIXES[0]

# don't recurse into CVS directories
if "CVS" in names:
Expand All @@ -120,45 +121,6 @@ def _visit_pyfiles(list, dirname, names):
list.extend([os.path.join(dirname, file) for file in names if os.path.splitext(file)[1] == _py_ext])


def _get_modpkg_path(dotted_name, pathlist=None):
"""Get the filesystem path for a module or a package.
Return the file system path to a file for a module, and to a directory for
a package. Return None if the name is not found, or is a builtin or
extension module.
"""
# split off top-most name
parts = dotted_name.split(".", 1)

if len(parts) > 1:
# we have a dotted path, import top-level package
try:
file, pathname, description = imp.find_module(parts[0], pathlist)
if file:
file.close()
except ImportError:
return None

# check if it's indeed a package
if description[2] == imp.PKG_DIRECTORY:
# recursively handle the remaining name parts
pathname = _get_modpkg_path(parts[1], [pathname])
else:
pathname = None
else:
# plain name
try:
file, pathname, description = imp.find_module(dotted_name, pathlist)
if file:
file.close()
if description[2] not in [imp.PY_SOURCE, imp.PKG_DIRECTORY]:
pathname = None
except ImportError:
pathname = None

return pathname


def getFilesForName(name):
"""Get a list of module files for a filename, a module or package name,
or a directory.
Expand All @@ -173,7 +135,11 @@ def getFilesForName(name):
return file_list

# try to find module or package
name = _get_modpkg_path(name)
try:
spec = importlib.util.find_spec(name)
name = spec.origin
except ImportError:
name = None
if not name:
return []

Expand Down

0 comments on commit 13dd00c

Please sign in to comment.