detect-shadowed-modules 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Detect conflicting directory names across Python's sys.path.
4
+
5
+ When Python imports a module, it searches directories in sys.path order. If the
6
+ same directory name exists in multiple sys.path entries, only the first one is
7
+ used—potentially shadowing packages you intended to import. This script identifies
8
+ such conflicts to help diagnose import issues.
9
+
10
+ Example conflict scenario:
11
+ sys.path = ['/project', '/usr/lib/python3/site-packages']
12
+
13
+ If both contain a 'requests/' directory:
14
+ - /project/requests/ <- This shadows the real package
15
+ - /usr/lib/python3/site-packages/requests/
16
+
17
+ Importing 'requests' will use /project/requests/, not the installed package.
18
+
19
+ Usage:
20
+ detect-shadowed-modules # Print conflicts to stdout
21
+ detect-shadowed-modules -q # Quiet mode (conflicts only)
22
+ detect-shadowed-modules --json # Output as JSON
23
+ """
24
+
25
+ import argparse
26
+ import importlib.metadata
27
+ import json
28
+ import logging
29
+ import os
30
+ import sys
31
+ from collections import defaultdict
32
+ from pathlib import Path
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ def setup_logging(quiet: bool = False) -> None:
38
+ """Configure logging with appropriate verbosity."""
39
+ level = logging.WARNING if quiet else logging.INFO
40
+ logging.basicConfig(
41
+ level=level,
42
+ format="%(levelname)s: %(message)s",
43
+ handlers=[logging.StreamHandler(sys.stderr)],
44
+ )
45
+
46
+
47
+ def get_subdirectories(path: Path) -> list[str]:
48
+ """
49
+ Get immediate subdirectory names, excluding hidden dirs, __pycache__, and metadata dirs.
50
+
51
+ Args:
52
+ path: Directory to scan.
53
+
54
+ Returns:
55
+ List of subdirectory names (not full paths).
56
+ """
57
+ if not path.is_dir():
58
+ logger.debug(f"Skipping non-directory: {path}")
59
+ return []
60
+
61
+ subdirs = []
62
+ try:
63
+ for entry in path.iterdir():
64
+ if not entry.is_dir():
65
+ continue
66
+ name = entry.name
67
+ # Skip hidden dirs, __pycache__, and package metadata dirs
68
+ if (
69
+ name.startswith(".")
70
+ or name == "__pycache__"
71
+ or name.endswith(".dist-info")
72
+ or name.endswith(".egg-info")
73
+ ):
74
+ logger.debug(f" Skipping: {name}/")
75
+ continue
76
+ subdirs.append(name)
77
+ logger.debug(f" Found: {name}/")
78
+ except PermissionError:
79
+ logger.warning(f"Permission denied: {path}")
80
+ except OSError as e:
81
+ logger.warning(f"Error accessing {path}: {e}")
82
+
83
+ return subdirs
84
+
85
+
86
+ def find_package_owner(directory_name: str) -> str | None:
87
+ """
88
+ Find the installed distribution that provides a top-level package name.
89
+
90
+ Args:
91
+ directory_name: The name of the directory (e.g., 'requests', 'numpy').
92
+
93
+ Returns:
94
+ Package name if found, None otherwise.
95
+ """
96
+ try:
97
+ # Try to find a distribution that provides this top-level name
98
+ # This works for most packages where the directory name matches the package
99
+ dist = importlib.metadata.distribution(directory_name)
100
+ return dist.metadata["Name"]
101
+ except importlib.metadata.PackageNotFoundError:
102
+ pass
103
+
104
+ # Fallback: check top_level.txt in all distributions
105
+ for dist in importlib.metadata.distributions():
106
+ try:
107
+ top_level = dist.read_text("top_level.txt")
108
+ if top_level and directory_name in top_level.strip().split("\n"):
109
+ return dist.metadata["Name"]
110
+ except FileNotFoundError:
111
+ continue
112
+
113
+ return None
114
+
115
+
116
+ def find_package_owner_by_path(directory: Path) -> str | None:
117
+ """
118
+ Find the installed distribution that owns files in a specific directory.
119
+
120
+ This is slower but more accurate for directories that don't match their
121
+ package name (e.g., a 'tests/' dir installed by some package).
122
+
123
+ Args:
124
+ directory: Full path to the directory.
125
+
126
+ Returns:
127
+ Package name if found, None otherwise.
128
+ """
129
+ directory = directory.resolve()
130
+
131
+ for dist in importlib.metadata.distributions():
132
+ for f in dist.files or []:
133
+ try:
134
+ full = dist.locate_file(f)
135
+ if full:
136
+ full_path = Path(str(full)).resolve()
137
+ # Check if this file is inside the directory we're looking for
138
+ if directory in full_path.parents or full_path.parent == directory:
139
+ return dist.metadata["Name"]
140
+ except (OSError, ValueError):
141
+ continue
142
+
143
+ return None
144
+
145
+
146
+ def find_conflicts(paths: list[str] | None = None) -> dict[str, list[Path]]:
147
+ """
148
+ Find directory names that appear in multiple sys.path locations.
149
+
150
+ Args:
151
+ paths: List of paths to check. Defaults to sys.path.
152
+
153
+ Returns:
154
+ Dict mapping conflicting directory names to the paths containing them.
155
+ """
156
+ if paths is None:
157
+ paths = sys.path
158
+
159
+ dir_locations: dict[str, list[Path]] = defaultdict(list)
160
+
161
+ for path_str in paths:
162
+ # Empty string means current working directory
163
+ path = Path(path_str or os.getcwd()).resolve()
164
+
165
+ for subdir in get_subdirectories(path):
166
+ dir_locations[subdir].append(path)
167
+
168
+ # Keep only directories appearing in multiple locations
169
+ return {name: locs for name, locs in dir_locations.items() if len(locs) > 1}
170
+
171
+
172
+ def format_report(conflicts: dict[str, list[Path]]) -> str:
173
+ """Format conflicts as a human-readable report."""
174
+ # ANSI color codes
175
+ green = "\033[92m"
176
+ red = "\033[91m"
177
+ reset = "\033[0m"
178
+
179
+ if not conflicts:
180
+ return f"{green}No conflicting directory names found{reset}"
181
+
182
+ lines = [
183
+ f"{red}Conflicting directory names detected:{reset}",
184
+ "",
185
+ "These directories exist in multiple sys.path locations. The first",
186
+ "location listed will shadow the others during import.",
187
+ "",
188
+ ]
189
+
190
+ for name in sorted(conflicts):
191
+ locations = conflicts[name]
192
+ owner = find_package_owner(name)
193
+ lines.append(f" {name}/")
194
+ for i, loc in enumerate(locations):
195
+ full_path = loc / name
196
+ prefix = " → " if i == 0 else " "
197
+ suffix = " (shadows others)" if i == 0 else " (shadowed)"
198
+ owner_info = f" [{owner}]" if owner and i > 0 else ""
199
+ lines.append(f"{prefix}{full_path}{owner_info}{suffix}")
200
+ lines.append("")
201
+
202
+ return "\n".join(lines)
203
+
204
+
205
+ def format_json(conflicts: dict[str, list[Path]]) -> str:
206
+ """Format conflicts as JSON, including shadowed directories and what shadows them."""
207
+ shadowed = []
208
+
209
+ for name, locations in conflicts.items():
210
+ shadowing_path = locations[0] / name
211
+ # Try fast name-based lookup first, fall back to slower path-based lookup
212
+ owner = find_package_owner(name)
213
+ if owner is None:
214
+ owner = find_package_owner_by_path(shadowing_path)
215
+
216
+ # Skip the first location (it's the one doing the shadowing)
217
+ for loc in locations[1:]:
218
+ full_path = loc / name
219
+ shadowed.append(
220
+ {
221
+ "path": str(full_path),
222
+ "shadowed_by": str(shadowing_path),
223
+ "owner": owner,
224
+ }
225
+ )
226
+
227
+ return json.dumps({"shadowed": shadowed}, indent=2)
228
+
229
+
230
+ def main() -> int:
231
+ """Main entry point. Returns exit code (0=no conflicts, 1=conflicts found)."""
232
+ parser = argparse.ArgumentParser(
233
+ description="Detect conflicting directory names in sys.path.",
234
+ formatter_class=argparse.RawDescriptionHelpFormatter,
235
+ epilog=__doc__,
236
+ )
237
+ parser.add_argument(
238
+ "-q",
239
+ "--quiet",
240
+ action="store_true",
241
+ help="Quiet mode: only show conflicts, not scanning progress",
242
+ )
243
+ parser.add_argument(
244
+ "--json",
245
+ action="store_true",
246
+ dest="json_output",
247
+ help="Output as JSON",
248
+ )
249
+ args = parser.parse_args()
250
+
251
+ setup_logging(quiet=args.quiet or args.json_output)
252
+
253
+ logger.debug("Scanning sys.path for directory conflicts...")
254
+ conflicts = find_conflicts()
255
+
256
+ if args.json_output:
257
+ print(format_json(conflicts))
258
+ else:
259
+ print(format_report(conflicts))
260
+
261
+ return 1 if conflicts else 0
262
+
263
+
264
+ if __name__ == "__main__":
265
+ sys.exit(main())
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.3
2
+ Name: detect-shadowed-modules
3
+ Version: 0.1.0
4
+ Summary: Detect conflicting directory names across Python's sys.path that shadow installed packages
5
+ Keywords: import,shadowing,diagnostics
6
+ Author: Michael Bianco
7
+ Author-email: Michael Bianco <mike@mikebian.co>
8
+ Requires-Python: >=3.11
9
+ Project-URL: Repository, https://github.com/iloveitaly/detect-shadowed-modules
10
+ Description-Content-Type: text/markdown
11
+
12
+ # detect-shadowed-modules
13
+
14
+ Detect conflicting directory names across Python's `sys.path` that may be shadowing your installed packages.
15
+
16
+ ## Problem
17
+
18
+ When Python imports a module, it searches directories in `sys.path` order. If the same directory name exists in multiple `sys.path` entries, only the first one is used—potentially shadowing packages you intended to import. This can lead to confusing import errors and unexpected behavior.
19
+
20
+ ### Example Conflict Scenario
21
+
22
+ ```python
23
+ sys.path = ['/project', '/usr/lib/python3/site-packages']
24
+ ```
25
+
26
+ If both paths contain a `requests/` directory:
27
+ - `/project/requests/` ← This shadows the real package
28
+ - `/usr/lib/python3/site-packages/requests/`
29
+
30
+ When you `import requests`, Python will use `/project/requests/` instead of the installed package, which is likely not what you want!
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ uv add detect-shadowed-modules
36
+ ```
37
+
38
+ Or, you can just use via uvx:
39
+
40
+ ```sh
41
+ uvx detect-shadowed-modules@latest --help
42
+ ```
43
+
44
+ ## Usage
45
+
46
+ ### Command Line
47
+
48
+ ```bash
49
+ # Print conflicts to stdout with scanning progress
50
+ detect-shadowed-modules
51
+
52
+ # Quiet mode (conflicts only, no progress messages)
53
+ detect-shadowed-modules -q
54
+
55
+ # Output as JSON
56
+ detect-shadowed-modules --json
57
+ ```
58
+
59
+ ### As a Python Module
60
+
61
+ ```python
62
+ import detect_shadowed_modules
63
+
64
+ # Find conflicts
65
+ conflicts = detect_shadowed_modules.find_conflicts()
66
+
67
+ # Generate a human-readable report
68
+ report = detect_shadowed_modules.format_report(conflicts)
69
+ print(report)
70
+
71
+ # Or get JSON output
72
+ json_output = detect_shadowed_modules.format_json(conflicts)
73
+ print(json_output)
74
+ ```
75
+
76
+ ## Output Examples
77
+
78
+ ### Human-Readable Format
79
+
80
+ ```
81
+ Conflicting directory names detected:
82
+
83
+ These directories exist in multiple sys.path locations. The first
84
+ location listed will shadow the others during import.
85
+
86
+ requests/
87
+ → /home/user/myproject/requests (shadows others)
88
+ /usr/lib/python3/site-packages/requests [requests] (shadowed)
89
+ ```
90
+
91
+ ### JSON Format
92
+
93
+ ```json
94
+ {
95
+ "shadowed": [
96
+ {
97
+ "path": "/usr/lib/python3/site-packages/requests",
98
+ "shadowed_by": "/home/user/myproject/requests",
99
+ "owner": "requests"
100
+ }
101
+ ]
102
+ }
103
+ ```
104
+
105
+ ## How It Works
106
+
107
+ The tool scans all directories in `sys.path` and:
108
+ 1. Identifies subdirectories in each path
109
+ 2. Detects when the same directory name appears in multiple locations
110
+ 3. Reports which packages are being shadowed and by what
111
+ 4. Attempts to identify the installed package that owns each directory
112
+
113
+ Excluded from scanning:
114
+ - Hidden directories (starting with `.`)
115
+ - `__pycache__` directories
116
+ - Package metadata directories (`.dist-info`, `.egg-info`)
117
+
118
+ ## Exit Codes
119
+
120
+ - `0`: No conflicts found
121
+ - `1`: Conflicts detected
122
+
123
+ This makes it easy to use in CI/CD pipelines or pre-commit hooks.
124
+
125
+ ## [MIT License](LICENSE.md)
@@ -0,0 +1,5 @@
1
+ detect_shadowed_modules/__init__.py,sha256=bhX9q7HQo88HHedwx0cro_GzHmN6-ClPs-ZOxN7ads0,8329
2
+ detect_shadowed_modules-0.1.0.dist-info/WHEEL,sha256=XV0cjMrO7zXhVAIyyc8aFf1VjZ33Fen4IiJk5zFlC3g,80
3
+ detect_shadowed_modules-0.1.0.dist-info/entry_points.txt,sha256=Ug1qCDSk_3JFxwcrsKNYCTFgcjT07UyprvtSyT5jLUk,74
4
+ detect_shadowed_modules-0.1.0.dist-info/METADATA,sha256=UYXO-a4TdHue2932zc0oobG0RIDwVpxhDELIEB7hXhc,3167
5
+ detect_shadowed_modules-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.9.26
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ detect-shadowed-modules = detect_shadowed_modules:main
3
+