| 269 | """ |
| 270 | |
| 271 | def __init__( |
| 272 | self, |
| 273 | package_name: str, |
| 274 | package_path: "str" = "templates", |
| 275 | encoding: str = "utf-8", |
| 276 | ) -> None: |
| 277 | package_path = os.path.normpath(package_path).rstrip(os.path.sep) |
| 278 | |
| 279 | # normpath preserves ".", which isn't valid in zip paths. |
| 280 | if package_path == os.path.curdir: |
| 281 | package_path = "" |
| 282 | elif package_path[:2] == os.path.curdir + os.path.sep: |
| 283 | package_path = package_path[2:] |
| 284 | |
| 285 | self.package_path = package_path |
| 286 | self.package_name = package_name |
| 287 | self.encoding = encoding |
| 288 | |
| 289 | # Make sure the package exists. This also makes namespace |
| 290 | # packages work, otherwise get_loader returns None. |
| 291 | import_module(package_name) |
| 292 | spec = importlib.util.find_spec(package_name) |
| 293 | assert spec is not None, "An import spec was not found for the package." |
| 294 | loader = spec.loader |
| 295 | assert loader is not None, "A loader was not found for the package." |
| 296 | self._loader = loader |
| 297 | self._archive = None |
| 298 | template_root = None |
| 299 | |
| 300 | if isinstance(loader, zipimport.zipimporter): |
| 301 | self._archive = loader.archive |
| 302 | pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore |
| 303 | template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep) |
| 304 | else: |
| 305 | roots: t.List[str] = [] |
| 306 | |
| 307 | # One element for regular packages, multiple for namespace |
| 308 | # packages, or None for single module file. |
| 309 | if spec.submodule_search_locations: |
| 310 | roots.extend(spec.submodule_search_locations) |
| 311 | # A single module file, use the parent directory instead. |
| 312 | elif spec.origin is not None: |
| 313 | roots.append(os.path.dirname(spec.origin)) |
| 314 | |
| 315 | for root in roots: |
| 316 | root = os.path.join(root, package_path) |
| 317 | |
| 318 | if os.path.isdir(root): |
| 319 | template_root = root |
| 320 | break |
| 321 | |
| 322 | if template_root is None: |
| 323 | raise ValueError( |
| 324 | f"The {package_name!r} package was not installed in a" |
| 325 | " way that PackageLoader understands." |
| 326 | ) |
| 327 | |
| 328 | self._template_root = template_root |