Skip to content
Myr

Revert "PackageLoader doesn't depend on setuptools"

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This reverts commit 4b6077a8c0a0f56bb8dbac37f8f9027130b4091c.

authored by David Lord · committed by David Lord · parent cf53e22 · Browse files · 3 files+47 added−134 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+47 added−134 removed

  • tests:+0 added−50 removed
  • other:+47 added−84 removed

3 files+47 added−134 removed

modified:src/jinja2/loaders.py+47 added-84 removed
1 unmodified line
2"""API and implementations for loading templates from different data3sources.4"""5import os6import pkgutil6import sys7import weakref8from hashlib import sha19from os import path
204 unmodified lines
214 return sorted(found)215216217class PackageLoader(BaseLoader):219 """Load templates from a directory in a Python package.218 """Load templates from python eggs or packages. It is constructed with219 the name of the python package and the path to the templates in that220 package::221221 :param package_name: Import name of the package that contains the222 template directory.223 :param package_path: Directory within the imported package that224 contains the templates.225 :param encoding: Encoding of template files.222 loader = PackageLoader('mypackage', 'views')223227 The following example looks up templates in the ``pages`` directory228 within the ``project.ui`` package.224 If the package path is not given, ``'templates'`` is assumed.225230 .. code-block:: python231232 loader = PackageLoader("project.ui", "pages")233234 Only packages installed as directories (standard pip behavior) or235 zip/egg files (less common) are supported. The Python API for236 introspecting data in packages is too limited to support other237 installation methods the way this loader requires.238239 .. versionchanged:: 2.11.0240 No longer uses ``setuptools`` as a dependency.226 Per default the template encoding is ``'utf-8'`` which can be changed227 by setting the `encoding` parameter to something else. Due to the nature228 of eggs it's only possible to reload templates if the package was loaded229 from the file system and not a zip file.230 """231232 def __init__(self, package_name, package_path="templates", encoding="utf-8"):244 if package_path == os.path.curdir:245 package_path = ""246 elif package_path[:2] == os.path.curdir + os.path.sep:247 package_path = package_path[2:]233 from pkg_resources import DefaultProvider234 from pkg_resources import get_provider235 from pkg_resources import ResourceManager236249 package_path = os.path.normpath(package_path)250251 self.package_name = package_name252 self.package_path = package_path237 provider = get_provider(package_name)238 self.encoding = encoding239 self.manager = ResourceManager()240 self.filesystem_bound = isinstance(provider, DefaultProvider)241 self.provider = provider242 self.package_path = package_path243255 self._loader = pkgutil.get_loader(package_name)256 # Zip loader's archive attribute points at the zip.257 self._archive = getattr(self._loader, "archive", None)258 self._template_root = os.path.join(259 os.path.dirname(self._loader.get_filename(package_name)), package_path260 ).rstrip(os.path.sep)261244 def get_source(self, environment, template):263 p = os.path.join(self._template_root, *split_template_path(template))245 pieces = split_template_path(template)246 p = "/".join((self.package_path,) + tuple(pieces))247265 if self._archive is None:266 # Package is a directory.267 if not os.path.isfile(p):268 raise TemplateNotFound(template)248 if not self.provider.has_resource(p):249 raise TemplateNotFound(template)250270 with open(p, "rb") as f:271 source = f.read()251 filename = uptodate = None252273 mtime = os.path.getmtime(p)253 if self.filesystem_bound:254 filename = self.provider.get_resource_filename(self.manager, p)255 mtime = path.getmtime(filename)256275 def up_to_date():276 return os.path.isfile(p) and os.path.getmtime(p) == mtime257 def uptodate():258 try:259 return path.getmtime(filename) == mtime260 except OSError:261 return False262278 else:279 # Package is a zip file.280 try:281 source = self._loader.get_data(p)282 except OSError:283 raise TemplateNotFound(template)263 source = self.provider.get_resource_string(self.manager, p)264 return source.decode(self.encoding), filename, uptodate265285 # Could use the zip's mtime for all template mtimes, but286 # would need to safely reload the module if it's out of287 # date, so just report it as always current.288 up_to_date = None266 def list_templates(self):267 path = self.package_path268290 return source.decode(self.encoding), p, up_to_date269 if path[:2] == "./":270 path = path[2:]271 elif path == ".":272 path = ""273292 def list_templates(self):274 offset = len(path)275 results = []276295 if self._archive is None:296 # Package is a directory.297 offset = len(self._template_root)277 def _walk(path):278 for filename in self.provider.resource_listdir(path):279 fullname = path + "/" + filename280299 for dirpath, _, filenames in os.walk(self._template_root):300 dirpath = dirpath[offset:].lstrip(os.path.sep)301 results.extend(302 os.path.join(dirpath, name).replace(os.path.sep, "/")303 for name in filenames304 )305 else:306 if not hasattr(self._loader, "_files"):307 raise TypeError(308 "This zip import does not have the required"309 " metadata to list templates."310 )281 if self.provider.resource_isdir(fullname):282 _walk(fullname)283 else:284 results.append(fullname[offset:].lstrip("/"))285312 # Package is a zip file.313 prefix = (314 self._template_root[len(self._archive) :].lstrip(os.path.sep)315 + os.path.sep316 )317 offset = len(prefix)318319 for name in self._loader._files.keys():320 # Find names under the templates directory that aren't directories.321 if name.startswith(prefix) and name[-1] != os.path.sep:322 results.append(name[offset:].replace(os.path.sep, "/"))323286 _walk(path)287 results.sort()288 return results289290
214 unmodified lines
deleted:tests/res/package.zipbinary

A binary file, deleted.

modified:tests/test_loader.py-50 removed
8 unmodified lines
9import pytest1011from jinja2 import Environment12from jinja2 import loaders13from jinja2 import PackageLoader13from jinja2._compat import PY214from jinja2._compat import PYPY15from jinja2.exceptions import TemplateNotFound16from jinja2.loaders import split_template_path
302 unmodified lines
319 mod_loader = loaders.ModuleLoader([pathlib.Path(mod_path), "/tmp/templates"])320 self.mod_env = Environment(loader=mod_loader)321322 self._test_common()324325326@pytest.fixture()327def package_dir_loader(monkeypatch):328 monkeypatch.syspath_prepend(os.path.dirname(__file__))329 return PackageLoader("res")330331332@pytest.mark.parametrize(333 ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]334)335def test_package_dir_source(package_dir_loader, template, expect):336 source, name, up_to_date = package_dir_loader.get_source(None, template)337 assert source.rstrip() == expect338 assert name.endswith(os.path.join(*split_template_path(template)))339 assert up_to_date()340341342def test_package_dir_list(package_dir_loader):343 templates = package_dir_loader.list_templates()344 assert "foo/test.html" in templates345 assert "test.html" in templates346347348@pytest.fixture()349def package_zip_loader(monkeypatch):350 monkeypatch.syspath_prepend(351 os.path.join(os.path.dirname(__file__), "res", "package.zip")352 )353 return PackageLoader("t_pack")354355356@pytest.mark.parametrize(357 ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]358)359def test_package_zip_source(package_zip_loader, template, expect):360 source, name, up_to_date = package_zip_loader.get_source(None, template)361 assert source.rstrip() == expect362 assert name.endswith(os.path.join(*split_template_path(template)))363 assert up_to_date is None364365366@pytest.mark.xfail(367 PYPY,368 reason="PyPy's zipimporter doesn't have a _files attribute.",369 raises=TypeError,370)371def test_package_zip_list(package_zip_loader):372 assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]