diff --git a/pylsp/_utils.py b/pylsp/_utils.py index 0ce0e8cb..0cf10a2d 100644 --- a/pylsp/_utils.py +++ b/pylsp/_utils.py @@ -122,14 +122,13 @@ def find_parents(root, path, names): def path_to_dot_name(path): """Given a path to a module, derive its dot-separated full name.""" - directory = os.path.dirname(path) + directory = pathlib.Path(os.path.dirname(path)) module_name, _ = os.path.splitext(os.path.basename(path)) full_name = [module_name] - while os.path.exists(os.path.join(directory, "__init__.py")): - this_directory = os.path.basename(directory) - directory = os.path.dirname(directory) - full_name = [this_directory] + full_name - return ".".join(full_name) + while directory.name and (directory / "__init__.py").exists(): + full_name.append(directory.name) + directory = directory.parent + return ".".join(reversed(full_name)) def match_uri_to_workspace(uri, workspaces): diff --git a/test/test_utils.py b/test/test_utils.py index 5d58dc55..d07cc223 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -3,6 +3,7 @@ import multiprocessing import os +import subprocess import sys import time from threading import Thread @@ -215,6 +216,29 @@ def test_find_parents_cross_mount(tmpdir, monkeypatch) -> None: assert result == [] +def test_path_to_dot_name_in_package_cwd(tmp_path) -> None: + (tmp_path / "__init__.py").touch() + script = """ +from types import SimpleNamespace + +from pylsp.workspace import Document + +workspace = SimpleNamespace(_config=None) +assert Document('', workspace).dot_path == '' +assert Document('untitled:Untitled-1', workspace).dot_path == 'Untitled-1' +""" + subprocess.run([sys.executable, "-c", script], cwd=tmp_path, timeout=10, check=True) + + +def test_path_to_dot_name_nested_package(tmp_path) -> None: + parent = tmp_path / "pkg" + nested = parent / "nested" + nested.mkdir(parents=True) + (parent / "__init__.py").touch() + (nested / "__init__.py").touch() + assert _utils.path_to_dot_name(str(nested / "module.py")) == "pkg.nested.module" + + def test_merge_dicts() -> None: assert _utils.merge_dicts( {"a": True, "b": {"x": 123, "y": {"hello": "world"}}},