Skip to content

Commit

Permalink
Fix source root not recognized (#10036)
Browse files Browse the repository at this point in the history
(cherry picked from commit be53085)
  • Loading branch information
Julfried authored and github-actions[bot] committed Nov 17, 2024
1 parent ea8ed7e commit bc37374
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/10026.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fixes the issue with --source-root option not working when the source files are in a subdirectory of the source root (e.g. when using a /src layout).

Closes #10026
2 changes: 1 addition & 1 deletion pylint/lint/expand_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def discover_package_path(modulepath: str, source_roots: Sequence[str]) -> str:
# Look for a source root that contains the module directory
for source_root in source_roots:
source_root = os.path.realpath(os.path.expanduser(source_root))
if os.path.commonpath([source_root, dirname]) == source_root:
if os.path.commonpath([source_root, dirname]) in [dirname, source_root]:
return source_root

# Fall back to legacy discovery by looking for __init__.py upwards as
Expand Down
36 changes: 36 additions & 0 deletions tests/pyreverse/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,42 @@ def test_project_root_in_sys_path() -> None:
assert sys.path == [PROJECT_ROOT_DIR]


def test_discover_package_path_source_root_as_parent(tmp_path: Any) -> None:
"""Test discover_package_path when source root is a parent of the module."""
# Create this temporary structure:
# /tmp_path/
# └── project/
# └── my-package/
# └── __init__.py
project_dir = tmp_path / "project"
package_dir = project_dir / "mypackage"
package_dir.mkdir(parents=True)
(package_dir / "__init__.py").touch()

# Test with project_dir as source root (parent of package)
result = discover_package_path(str(package_dir), [str(project_dir)])
assert result == str(project_dir)


def test_discover_package_path_source_root_as_child(tmp_path: Any) -> None:
"""Test discover_package_path when source root is a child of the module."""
# Create this temporary structure:
# /tmp_path/
# └── project/
# └── src/
# └── my-package/
# └── __init__.py
project_dir = tmp_path / "project"
src_dir = project_dir / "src"
package_dir = src_dir / "mypackage"
package_dir.mkdir(parents=True)
(package_dir / "__init__.py").touch()

# Test with src_dir as source root (child of project)
result = discover_package_path(str(project_dir), [str(src_dir)])
assert result == str(src_dir)


@mock.patch("pylint.pyreverse.main.Linker", new=mock.MagicMock())
@mock.patch("pylint.pyreverse.main.DiadefsHandler", new=mock.MagicMock())
@mock.patch("pylint.pyreverse.main.writer")
Expand Down

0 comments on commit bc37374

Please sign in to comment.