Merge pull request #4610 from eprigorodov/feature-4602-namespace-path
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents fb89745, b06df0a · Browse files · 4 files·+59 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+59 added−27 removed
- tests:+19 added−15 removed
- other:+40 added−12 removed
Provenance
- Commit
c7f2ab8- Tree
43ac395- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
fb89745- Parent 2
b06df0a
4 files changed+59 added−27 removed
modified:src/flask/scaffold.py+37 added-12 removed
1 import importlib.util2 import os3+import pathlib4 import pkgutil5 import sys6 import typing as t7 from collections import defaultdict772 unmodified lines780 f" import hooks."781 )782 783 784+def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:785+ # Path.is_relative_to doesn't exist until Python 3.9786+ try:787+ path.relative_to(base)788+ return True789+ except ValueError:790+ return False791+792+783-def _find_package_path(root_mod_name):793+def _find_package_path(import_name):794 """Find the path that contains the package or module."""795+ root_mod_name, _, _ = import_name.partition(".")796+797 try:786- spec = importlib.util.find_spec(root_mod_name)798+ root_spec = importlib.util.find_spec(root_mod_name)799 788- if spec is None:800+ if root_spec is None:801 raise ValueError("not found")802 # ImportError: the machinery told us it does not exist803 # ValueError:804 # - the module name was invalid805 # - the module name is __main__794- # - *we* raised `ValueError` due to `spec` being `None`806+ # - *we* raised `ValueError` due to `root_spec` being `None`807 except (ImportError, ValueError):808 pass # handled below809 else:810 # namespace package799- if spec.origin in {"namespace", None}:800- return os.path.dirname(next(iter(spec.submodule_search_locations)))811+ if root_spec.origin in {"namespace", None}:812+ package_spec = importlib.util.find_spec(import_name)813+ if package_spec is not None and package_spec.submodule_search_locations:814+ # Pick the path in the namespace that contains the submodule.815+ package_path = pathlib.Path(816+ os.path.commonpath(package_spec.submodule_search_locations)817+ )818+ search_locations = (819+ location820+ for location in root_spec.submodule_search_locations821+ if _path_is_relative_to(package_path, location)822+ )823+ else:824+ # Pick the first path.825+ search_locations = iter(root_spec.submodule_search_locations)826+ return os.path.dirname(next(search_locations))827 # a package (with __init__.py)802- elif spec.submodule_search_locations:803- return os.path.dirname(os.path.dirname(spec.origin))828+ elif root_spec.submodule_search_locations:829+ return os.path.dirname(os.path.dirname(root_spec.origin))830 # just a normal module831 else:806- return os.path.dirname(spec.origin)832+ return os.path.dirname(root_spec.origin)833 834 # we were unable to find the `package_path` using PEP 451 loaders835 loader = pkgutil.get_loader(root_mod_name)836 33 unmodified lines870 The path is the entry in :attr:`sys.path` that contains the package871 for import. If the package is not installed, it's assumed that the872 package was imported from the current working directory.873 """848- root_mod_name, _, _ = import_name.partition(".")849- package_path = _find_package_path(root_mod_name)874+ package_path = _find_package_path(import_name)875 py_prefix = os.path.abspath(sys.prefix)876 877 # installed to the system853- if package_path.startswith(py_prefix):878+ if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):879 return py_prefix, package_path880 881 site_parent, site_folder = os.path.split(package_path)882 17 unmodified linesmodified:tests/test_instance_config.py+19 added-15 removed
1-import os1 import sys2 3 import pytest4 8 unmodified lines13 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))14 assert app.instance_path == str(modules_tmpdir)15 16 18-@pytest.mark.xfail(reason="weird interaction with tox")19-def test_main_module_paths(modules_tmpdir, purge_module):20- app = modules_tmpdir.join("main_app.py")21- app.write('import flask\n\napp = flask.Flask("__main__")')22- purge_module("main_app")23-24- from main_app import app25-26- here = os.path.abspath(os.getcwd())27- assert app.instance_path == os.path.join(here, "instance")28-29-30-@pytest.mark.xfail(reason="weird interaction with tox")17 def test_uninstalled_module_paths(modules_tmpdir, purge_module):18 app = modules_tmpdir.join("config_module_app.py").write(19 "import os\n"20 "import flask\n"6 unmodified lines27 28 assert app.instance_path == str(modules_tmpdir.join("instance"))29 30 45-@pytest.mark.xfail(reason="weird interaction with tox")31 def test_uninstalled_package_paths(modules_tmpdir, purge_module):32 app = modules_tmpdir.mkdir("config_package_app")33 init = app.join("__init__.py")34 init.write(8 unmodified lines43 44 assert app.instance_path == str(modules_tmpdir.join("instance"))45 46 47+def test_uninstalled_namespace_paths(tmpdir, monkeypatch, purge_module):48+ def create_namespace(package):49+ project = tmpdir.join(f"project-{package}")50+ monkeypatch.syspath_prepend(str(project))51+ project.join("namespace").join(package).join("__init__.py").write(52+ "import flask\napp = flask.Flask(__name__)\n", ensure=True53+ )54+ return project55+56+ _ = create_namespace("package1")57+ project2 = create_namespace("package2")58+ purge_module("namespace.package2")59+ purge_module("namespace")60+61+ from namespace.package2 import app62+63+ assert app.instance_path == str(project2.join("instance"))64+65+66 def test_installed_module_paths(67 modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader68 ):69 site_packages.join("site_app.py").write(56 unmodified linesmodified:CHANGES.rst+2 added
6 unmodified lines7 8 - Inline some optional imports that are only used for certain CLI9 commands. :pr:`4606`10 - Relax type annotation for ``after_request`` functions. :issue:`4600`11+- ``instance_path`` for namespace packages uses the path closest to12+ the imported submodule. :issue:`4600`13 14 15 Version 2.1.216 -------------1280 unmodified linesmodified:tox.ini+1 added
7 unmodified lines8 docs9 skip_missing_interpreters = true10 11 [testenv]12+envtmpdir = {toxworkdir}/tmp/{envname}13 deps =14 -r requirements/tests.txt15 min: -r requirements/tests-pallets-min.txt16 dev: -r requirements/tests-pallets-dev.txt18 unmodified lines