Migrate read_file from pkg_resources to importlib.resources

In python 3.9, we can get any resource from a package subdirectory using
files(), but on older versions of python, even where importlib.resources exists,
we need the backport.
This commit is contained in:
Eli Schwartz 2020-12-07 12:37:42 -05:00
parent 0a9cfaa35a
commit 1649c6fe19
No known key found for this signature in database
GPG Key ID: CEB167EFB5722BD6
5 changed files with 15 additions and 5 deletions

View File

@ -131,6 +131,8 @@ The following software and libraries are required to run qutebrowser:
* http://pygments.org/[pygments]
* https://github.com/yaml/pyyaml[PyYAML]
* https://www.attrs.org/[attrs]
* https://importlib-resources.readthedocs.io/[importlib_resources] (on python
3.8 or older)
The following libraries are optional:

View File

@ -42,6 +42,11 @@ from typing import (Any, Callable, IO, Iterator, Optional, Sequence, Tuple, Type
from PyQt5.QtCore import QUrl, QVersionNumber
from PyQt5.QtGui import QClipboard, QDesktopServices
from PyQt5.QtWidgets import QApplication
# We cannot use the stdlib version on 3.7-3.8 because we need the files() API.
if sys.version_info >= (3, 9):
import importlib.resources as importlib_resources
else:
import importlib_resources
import pkg_resources
import yaml
try:
@ -216,13 +221,12 @@ def read_file(filename: str, binary: bool = False) -> Any:
with open(fn, 'r', encoding='utf-8') as f:
return f.read()
else:
data = pkg_resources.resource_string(
qutebrowser.__name__, filename)
p = importlib_resources.files(qutebrowser) / filename
if binary:
return data
return p.read_bytes()
return data.decode('UTF-8')
return p.read_text()
def resource_filename(filename: str) -> str:

View File

@ -263,6 +263,7 @@ def _module_versions() -> Sequence[str]:
('pygments', ['__version__']),
('yaml', ['__version__']),
('attr', ['__version__']),
('importlib_resources', []),
('PyQt5.QtWebEngineWidgets', []),
('PyQt5.QtWebEngine', ['PYQT_WEBENGINE_VERSION_STR']),
('PyQt5.QtWebKitWidgets', []),

View File

@ -71,7 +71,8 @@ try:
entry_points={'gui_scripts':
['qutebrowser = qutebrowser.qutebrowser:main']},
zip_safe=True,
install_requires=['pypeg2', 'jinja2', 'pygments', 'PyYAML', 'attrs'],
install_requires=['pypeg2', 'jinja2', 'pygments', 'PyYAML', 'attrs',
'importlib_resources>=1.1.0; python_version < "3.9"'],
python_requires='>=3.6',
name='qutebrowser',
version=_get_constant('version'),

View File

@ -561,11 +561,13 @@ class ImportFake:
('pygments', True),
('yaml', True),
('attr', True),
('importlib_resources', True),
('PyQt5.QtWebEngineWidgets', True),
('PyQt5.QtWebEngine', True),
('PyQt5.QtWebKitWidgets', True),
])
self.no_version_attribute = ['sip',
'importlib_resources',
'PyQt5.QtWebEngineWidgets',
'PyQt5.QtWebKitWidgets',
'PyQt5.QtWebEngine']