importroute 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anish Pentyala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include LICENSE README.md
2
+ recursive-include docs *.md
3
+ recursive-include tests *.py
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: importroute
3
+ Version: 0.1.0
4
+ Summary: Explain declared Python filesystem import routes without importing target packages
5
+ Author: Anish Pentyala
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/anishpentyala/importroute
8
+ Project-URL: Repository, https://github.com/anishpentyala/importroute
9
+ Project-URL: Issues, https://github.com/anishpentyala/importroute/issues
10
+ Keywords: python,imports,debugging,static-analysis
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # importroute
17
+
18
+ [![Tests](https://github.com/anishpentyala/importroute/actions/workflows/tests.yml/badge.svg)](https://github.com/anishpentyala/importroute/actions)
19
+
20
+ Explain where a Python name would be found in an explicit, ordered set of directories, without importing the target package.
21
+
22
+ ## Quickstart
23
+
24
+ ```sh
25
+ python -m pip install "git+https://github.com/anishpentyala/importroute.git"
26
+ mkdir -p demo/checkout demo/site
27
+ printf 'raise RuntimeError("do not import this")\n' > demo/checkout/widget.py
28
+ printf 'pass\n' > demo/site/widget.py
29
+ importroute widget --path demo/checkout --path demo/site --expect-under demo/site --json
30
+ ```
31
+
32
+ This exits 1 with top-level `FAILED` and per-module `EXPECTATION_FAILED`: the first root selects the checkout's
33
+ `widget.py`, outside the expected site directory. The exception in that file
34
+ does not run. Reverse the two `--path` arguments and this example passes.
35
+ This models declared filesystem roots, not custom import hooks or a live
36
+ process's full import behavior.
37
+
38
+ A PyPI release is being prepared. Until its package page is linked here, use the
39
+ source-install command above.
40
+
41
+ A checkout can hide an installed dependency. A regular package in a later root can replace earlier namespace portions. A package can also win over a same-name module at one root. `importroute` shows the candidates and the route through each dotted-name component, and can fail a CI check when that route leaves an expected directory.
42
+
43
+ This is a bounded filesystem model, **not proof of what a running process imports**. It does not evaluate initializers, custom finders, editable-install hooks, `.pth` files, archives, the module cache, or a package's dynamic `__path__` changes. It does not prove that selected code can load or is safe.
44
+
45
+ ## Install
46
+
47
+ Python 3.10 or newer. No runtime dependencies.
48
+
49
+ ```sh
50
+ python -m pip install .
51
+ importroute --help
52
+ ```
53
+
54
+ Run the tool with the interpreter whose default extension suffixes you want to model. Installation from this checkout is the supported installation instruction. No package-registry release is assumed.
55
+
56
+ ## A reproducible shadowing check
57
+
58
+ ```sh
59
+ mkdir -p demo/checkout demo/site
60
+ printf 'raise RuntimeError("do not import this")\n' > demo/checkout/widget.py
61
+ printf 'pass\n' > demo/site/widget.py
62
+
63
+ importroute widget --path demo/checkout --path demo/site
64
+ ```
65
+
66
+ The report selects `demo/checkout/widget.py` and lists `demo/site/widget.py` as a later-root candidate. Paths are displayed as absolute paths. The first file's exception does not run.
67
+
68
+ Require the selected route to stay under the intended directory:
69
+
70
+ ```sh
71
+ importroute widget --path demo/checkout --path demo/site \
72
+ --expect-under demo/site --json
73
+ ```
74
+
75
+ This exits 1 with top-level `FAILED` and per-module `EXPECTATION_FAILED`, because the first directory wins. Reversing the two `--path` arguments makes this example pass.
76
+
77
+ For a dotted name:
78
+
79
+ ```sh
80
+ importroute acme.plugins.reader --path ./src --path ./vendor --json
81
+ ```
82
+
83
+ Each component has its own `search_roots`, `candidates`, `selection`, `ignored_roots`, and `errors`. Child lookup follows the selected package directories, not the original top-level roots. Regular packages are assumed to retain their default directory `__path__`.
84
+
85
+ ## Python API
86
+
87
+ ```python
88
+ from importroute import trace_imports
89
+
90
+ report = trace_imports(
91
+ ["widget", "acme.plugins.reader"],
92
+ ["./src", "./vendor"],
93
+ expected_root="./src",
94
+ )
95
+ print(report["status"])
96
+ ```
97
+
98
+ Inputs must be iterables, not one string. Module names are absolute dotted identifiers. Relative names and path/glob patterns are rejected. Paths are literal: no environment-variable or tilde expansion. An empty path means the current directory. The function does not change `sys.path`.
99
+
100
+ ## Selection rules
101
+
102
+ The model uses exact-case directory entries and the running interpreter's default extension, source, then legacy-bytecode suffix order.
103
+
104
+ - Within one root, a regular package beats a same-name module, including extension modules. Among matching files, default loader suffix order applies.
105
+ - Across roots, the first concrete module or regular package wins.
106
+ - Namespace portions combine in root order only if there is no concrete match. A later concrete match discards earlier namespace portions.
107
+ - A plain module cannot have a child. A selected regular package's missing child does not fall back to unrelated top-level roots.
108
+ - `__pycache__` entries without source are not treated as legacy same-directory `.pyc` candidates. Extension and bytecode files are located, never loaded or validated.
109
+
110
+ `--expect-under` checks the physical path of **every selected component**, including every namespace portion. A symlink pointing outside fails even when its lexical path is inside. The expected root must be an existing directory. This is a location check, not a trust or containment sandbox.
111
+
112
+ ## Reports and exit codes
113
+
114
+ JSON reports use `format: "importroute/v1"`. All queries are retained. The overall status gives `INCOMPLETE` priority over failures.
115
+
116
+ | Exit | Meaning |
117
+ | --- | --- |
118
+ | 0 | Every query is `LOCATED`, with any expectation satisfied |
119
+ | 1 | A query is `MISSING`, `PARENT_NOT_PACKAGE`, or `EXPECTATION_FAILED` |
120
+ | 2 | Invalid input, command usage, or output failure |
121
+ | 3 | At least one query is `INCOMPLETE` |
122
+
123
+ An `INCOMPLETE` step may include a tentative selection from readable roots. Do not treat it as a passing result. Unreadable directories, non-directory roots such as archives, scan-budget exhaustion, and failed physical-path checks are explicit failures to complete the model. Missing roots are listed and ignored. Even an unsupported root after an apparent winner causes `INCOMPLETE`, because this tool promises a candidate inventory, not only a winner.
124
+
125
+ Top-level names with builtin or frozen precedence in this interpreter return `INCOMPLETE` instead of pretending a directory candidate is the runtime winner. Other non-filesystem behavior is excluded by the stated assumptions, not detected automatically.
126
+
127
+ Limits per call: 128 queries, 64 initial roots, 32 components per query, and 100,000 directory entries. One additional entry may be observed to detect that the entry budget was exceeded. Directory-name caches live only for the call. These are work limits, not a timeout: a slow filesystem or network mount can still block an operating-system call.
128
+
129
+ ## When to use something else
130
+
131
+ For the spec selected by the real import system, use `importlib.util.find_spec`. Looking up a dotted name there can execute its parent package. If runtime behavior matters, reproduce the real process and inspect the actual imported module instead of relying on this model.
132
+
133
+ Ruff's `A005` checks standard-library name shadowing. deptry checks dependency declarations and imports. Import Linter checks architecture contracts. Those solve different problems; this tool does not replace them. Its narrower task is an explicit-directory route explanation with all candidates and an expected-root gate.
134
+
135
+ [Detect Shadowed Modules](https://github.com/iloveitaly/detect-shadowed-modules/blob/master/README.md) is a closer alternative for duplicate-directory checks across an environment's search paths. Its CLI includes uv editable locations and installed-distribution ownership; its Python API also accepts explicit roots. Prefer it for that environment-wide inventory. `importroute` instead follows requested dotted names, includes ordinary module files and loader suffix precedence, distinguishes namespace accumulation from concrete-package selection, and checks the physical path of every selected component against an expected root.
136
+
137
+ Do not run Python itself on a hostile checkout merely because this tool does not import target packages. Interpreter startup, the installed tool, and its own imports remain part of your execution environment. Use a trusted installation and working directory. Filesystem observations can race with concurrent changes and are not an atomic snapshot. The model intentionally does not follow platform case-folding or `PYTHONCASEOK` behavior.
138
+
139
+ ## Development
140
+
141
+ ```sh
142
+ python -m unittest discover -s tests -v
143
+ ```
144
+
145
+ Tests compare 25 two-root layout pairs with the standard-library finder and 120 seeded nested layouts with actual harmless imports in isolated child processes. They also cover namespace precedence, suffix selection, symlinks, scan limits, no target execution, and output failures. This is Linux validation, not a claim of complete cross-platform import emulation.
146
+
147
+ See [design and sources](docs/design.md) for the scope and evidence.
148
+
149
+ MIT licensed.
@@ -0,0 +1,134 @@
1
+ # importroute
2
+
3
+ [![Tests](https://github.com/anishpentyala/importroute/actions/workflows/tests.yml/badge.svg)](https://github.com/anishpentyala/importroute/actions)
4
+
5
+ Explain where a Python name would be found in an explicit, ordered set of directories, without importing the target package.
6
+
7
+ ## Quickstart
8
+
9
+ ```sh
10
+ python -m pip install "git+https://github.com/anishpentyala/importroute.git"
11
+ mkdir -p demo/checkout demo/site
12
+ printf 'raise RuntimeError("do not import this")\n' > demo/checkout/widget.py
13
+ printf 'pass\n' > demo/site/widget.py
14
+ importroute widget --path demo/checkout --path demo/site --expect-under demo/site --json
15
+ ```
16
+
17
+ This exits 1 with top-level `FAILED` and per-module `EXPECTATION_FAILED`: the first root selects the checkout's
18
+ `widget.py`, outside the expected site directory. The exception in that file
19
+ does not run. Reverse the two `--path` arguments and this example passes.
20
+ This models declared filesystem roots, not custom import hooks or a live
21
+ process's full import behavior.
22
+
23
+ A PyPI release is being prepared. Until its package page is linked here, use the
24
+ source-install command above.
25
+
26
+ A checkout can hide an installed dependency. A regular package in a later root can replace earlier namespace portions. A package can also win over a same-name module at one root. `importroute` shows the candidates and the route through each dotted-name component, and can fail a CI check when that route leaves an expected directory.
27
+
28
+ This is a bounded filesystem model, **not proof of what a running process imports**. It does not evaluate initializers, custom finders, editable-install hooks, `.pth` files, archives, the module cache, or a package's dynamic `__path__` changes. It does not prove that selected code can load or is safe.
29
+
30
+ ## Install
31
+
32
+ Python 3.10 or newer. No runtime dependencies.
33
+
34
+ ```sh
35
+ python -m pip install .
36
+ importroute --help
37
+ ```
38
+
39
+ Run the tool with the interpreter whose default extension suffixes you want to model. Installation from this checkout is the supported installation instruction. No package-registry release is assumed.
40
+
41
+ ## A reproducible shadowing check
42
+
43
+ ```sh
44
+ mkdir -p demo/checkout demo/site
45
+ printf 'raise RuntimeError("do not import this")\n' > demo/checkout/widget.py
46
+ printf 'pass\n' > demo/site/widget.py
47
+
48
+ importroute widget --path demo/checkout --path demo/site
49
+ ```
50
+
51
+ The report selects `demo/checkout/widget.py` and lists `demo/site/widget.py` as a later-root candidate. Paths are displayed as absolute paths. The first file's exception does not run.
52
+
53
+ Require the selected route to stay under the intended directory:
54
+
55
+ ```sh
56
+ importroute widget --path demo/checkout --path demo/site \
57
+ --expect-under demo/site --json
58
+ ```
59
+
60
+ This exits 1 with top-level `FAILED` and per-module `EXPECTATION_FAILED`, because the first directory wins. Reversing the two `--path` arguments makes this example pass.
61
+
62
+ For a dotted name:
63
+
64
+ ```sh
65
+ importroute acme.plugins.reader --path ./src --path ./vendor --json
66
+ ```
67
+
68
+ Each component has its own `search_roots`, `candidates`, `selection`, `ignored_roots`, and `errors`. Child lookup follows the selected package directories, not the original top-level roots. Regular packages are assumed to retain their default directory `__path__`.
69
+
70
+ ## Python API
71
+
72
+ ```python
73
+ from importroute import trace_imports
74
+
75
+ report = trace_imports(
76
+ ["widget", "acme.plugins.reader"],
77
+ ["./src", "./vendor"],
78
+ expected_root="./src",
79
+ )
80
+ print(report["status"])
81
+ ```
82
+
83
+ Inputs must be iterables, not one string. Module names are absolute dotted identifiers. Relative names and path/glob patterns are rejected. Paths are literal: no environment-variable or tilde expansion. An empty path means the current directory. The function does not change `sys.path`.
84
+
85
+ ## Selection rules
86
+
87
+ The model uses exact-case directory entries and the running interpreter's default extension, source, then legacy-bytecode suffix order.
88
+
89
+ - Within one root, a regular package beats a same-name module, including extension modules. Among matching files, default loader suffix order applies.
90
+ - Across roots, the first concrete module or regular package wins.
91
+ - Namespace portions combine in root order only if there is no concrete match. A later concrete match discards earlier namespace portions.
92
+ - A plain module cannot have a child. A selected regular package's missing child does not fall back to unrelated top-level roots.
93
+ - `__pycache__` entries without source are not treated as legacy same-directory `.pyc` candidates. Extension and bytecode files are located, never loaded or validated.
94
+
95
+ `--expect-under` checks the physical path of **every selected component**, including every namespace portion. A symlink pointing outside fails even when its lexical path is inside. The expected root must be an existing directory. This is a location check, not a trust or containment sandbox.
96
+
97
+ ## Reports and exit codes
98
+
99
+ JSON reports use `format: "importroute/v1"`. All queries are retained. The overall status gives `INCOMPLETE` priority over failures.
100
+
101
+ | Exit | Meaning |
102
+ | --- | --- |
103
+ | 0 | Every query is `LOCATED`, with any expectation satisfied |
104
+ | 1 | A query is `MISSING`, `PARENT_NOT_PACKAGE`, or `EXPECTATION_FAILED` |
105
+ | 2 | Invalid input, command usage, or output failure |
106
+ | 3 | At least one query is `INCOMPLETE` |
107
+
108
+ An `INCOMPLETE` step may include a tentative selection from readable roots. Do not treat it as a passing result. Unreadable directories, non-directory roots such as archives, scan-budget exhaustion, and failed physical-path checks are explicit failures to complete the model. Missing roots are listed and ignored. Even an unsupported root after an apparent winner causes `INCOMPLETE`, because this tool promises a candidate inventory, not only a winner.
109
+
110
+ Top-level names with builtin or frozen precedence in this interpreter return `INCOMPLETE` instead of pretending a directory candidate is the runtime winner. Other non-filesystem behavior is excluded by the stated assumptions, not detected automatically.
111
+
112
+ Limits per call: 128 queries, 64 initial roots, 32 components per query, and 100,000 directory entries. One additional entry may be observed to detect that the entry budget was exceeded. Directory-name caches live only for the call. These are work limits, not a timeout: a slow filesystem or network mount can still block an operating-system call.
113
+
114
+ ## When to use something else
115
+
116
+ For the spec selected by the real import system, use `importlib.util.find_spec`. Looking up a dotted name there can execute its parent package. If runtime behavior matters, reproduce the real process and inspect the actual imported module instead of relying on this model.
117
+
118
+ Ruff's `A005` checks standard-library name shadowing. deptry checks dependency declarations and imports. Import Linter checks architecture contracts. Those solve different problems; this tool does not replace them. Its narrower task is an explicit-directory route explanation with all candidates and an expected-root gate.
119
+
120
+ [Detect Shadowed Modules](https://github.com/iloveitaly/detect-shadowed-modules/blob/master/README.md) is a closer alternative for duplicate-directory checks across an environment's search paths. Its CLI includes uv editable locations and installed-distribution ownership; its Python API also accepts explicit roots. Prefer it for that environment-wide inventory. `importroute` instead follows requested dotted names, includes ordinary module files and loader suffix precedence, distinguishes namespace accumulation from concrete-package selection, and checks the physical path of every selected component against an expected root.
121
+
122
+ Do not run Python itself on a hostile checkout merely because this tool does not import target packages. Interpreter startup, the installed tool, and its own imports remain part of your execution environment. Use a trusted installation and working directory. Filesystem observations can race with concurrent changes and are not an atomic snapshot. The model intentionally does not follow platform case-folding or `PYTHONCASEOK` behavior.
123
+
124
+ ## Development
125
+
126
+ ```sh
127
+ python -m unittest discover -s tests -v
128
+ ```
129
+
130
+ Tests compare 25 two-root layout pairs with the standard-library finder and 120 seeded nested layouts with actual harmless imports in isolated child processes. They also cover namespace precedence, suffix selection, symlinks, scan limits, no target execution, and output failures. This is Linux validation, not a claim of complete cross-platform import emulation.
131
+
132
+ See [design and sources](docs/design.md) for the scope and evidence.
133
+
134
+ MIT licensed.
@@ -0,0 +1,30 @@
1
+ # Design and sources
2
+
3
+ Research checked November 21, 2026. This is a small diagnostic for a specific workflow, not a claim that filesystem import analysis is new or that no competing tool exists.
4
+
5
+ ## Intended use
6
+
7
+ A developer declares the ordered source and vendor directories that their build or CI expects. The tool explains which file or package portion that declaration selects at each component. An optional physical-root expectation turns unexpected shadowing into a failing check. Unlike an installed-artifact comparison, this works on ordinary source trees and explains candidate precedence.
8
+
9
+ There is a tradeoff: skipping target execution means dynamic package behavior cannot be known. A useful report must state its model instead of calling a located file importable. Candidate enumeration also means an inaccessible later root produces an incomplete result even if an earlier winner is visible.
10
+
11
+ ## Source ledger
12
+
13
+ - [Python importlib documentation](https://docs.python.org/3/library/importlib.html), Python Software Foundation, official API documentation. Establishes that dotted `importlib.util.find_spec` imports the parent; describes default filesystem finder APIs and loader suffixes. High confidence for API behavior, not a promise about arbitrary custom importers.
14
+ - [Python import reference](https://docs.python.org/3/reference/import.html), Python Software Foundation, language reference. Supports the distinction between module cache, meta path, path hooks, parent `__path__`, and filesystem lookup. High confidence.
15
+ - [PEP 420](https://peps.python.org/pep-0420/), Python namespace-package specification. Supports ordered namespace accumulation and concrete-package precedence. High confidence for the intended algorithm; the tool still uses the interpreter's actual suffix lists.
16
+ - [CPython issue 92994](https://github.com/python/cpython/issues/92994), public issue discussion. Evidence that a supposedly execution-free dotted spec lookup can surprise developers by importing parent modules. It does not establish demand for this particular tool, usage, or adoption. Medium confidence as problem evidence.
17
+ - [Ruff A005](https://docs.astral.sh/ruff/rules/stdlib-module-shadowing/), Astral, rule documentation. An existing solution for standard-library module naming conflicts. Prefer it when that is the question. High confidence for documented rule scope.
18
+ - [deptry](https://github.com/osprey-oss/deptry/), project README. Checks missing, unused, and transitive dependencies by comparing imports with dependency declarations. It is not presented here as a general route debugger. High confidence for the documented core purpose, not an exhaustive feature audit.
19
+ - [Import Linter](https://import-linter.readthedocs.io/en/stable/), project documentation. Enforces architecture contracts between modules and offers architecture exploration. Prefer it for dependency direction and layering rules. High confidence for documented purpose.
20
+ - [Find a module path without importing](https://stackoverflow.com/questions/4693608/find-path-of-module-without-importing-in-python), community question and answers. Shows the recurring question and the important limitation that dynamic parent behavior prevents a universally correct execution-free answer. Community context, not a normative algorithm or proof of current product demand.
21
+
22
+ - [Detect Shadowed Modules README](https://github.com/iloveitaly/detect-shadowed-modules/blob/master/README.md), project documentation, read November21,2026. Closer existing diagnostic: duplicate immediate directory names across search roots, optional uv editable-path discovery, ownership hints, JSON and conflict exit codes. Source inspection at10598cbf8e45c9f5666e87b4f4336984f878e8cd confirmed `find_conflicts(paths=...)` accepts explicit roots and its helper filters to immediate subdirectories. Explicit roots and JSON are therefore not unique features of this project. The narrower contribution here is dotted-name route modeling for module/package/namespace selection and a physical expected-root gate. This is a scoped comparison, not an exhaustive audit of that project's current or future capabilities.
23
+
24
+ No external source code is copied into this project. The implementation is a bounded directory model, with the standard-library finder and actual harmless subprocess imports used as test oracles.
25
+
26
+ ## Validation and limits
27
+
28
+ The tests cover a 25-pair two-root grid and 120 seeded nested layouts. The nested oracle starts isolated child processes that import only test-created harmless modules. Invalid extension and bytecode files are used only with spec lookup, never loaded. Additional checks cover no target source reads, no target writes, custom-hook avoidance, symlink expectations, errors, special files, and output handling.
29
+
30
+ The scan budget applies across a whole call, including later queries. A single look-ahead entry can exceed the stated count by one to detect exhaustion. Root and component counts bound the remaining loop structure. None of these bounds cancels a slow filesystem call. No concurrent-filesystem snapshot, security certification, or Windows/macOS parity is claimed.
@@ -0,0 +1,4 @@
1
+ """Declared directory lookup, never a target-package import."""
2
+ from .core import trace_imports
3
+
4
+ __all__ = ["trace_imports"]
@@ -0,0 +1,86 @@
1
+ """Command-line display and strict process exit handling."""
2
+ import argparse
3
+ import inspect
4
+ import json
5
+ import os
6
+ import sys
7
+ from functools import partial
8
+
9
+ from .core import trace_imports
10
+
11
+ CODES = {'LOCATED': 0, 'FAILED': 1, 'INVALID': 2, 'INCOMPLETE': 3}
12
+
13
+
14
+ def _human(report):
15
+ if report['status'] == 'INVALID':
16
+ return 'INVALID: ' + repr(report['error']) + '\n'
17
+ lines = ['Filesystem import routes, not runtime import verification.']
18
+ for item in report['modules']:
19
+ lines.append(item['module'] + ': ' + item['status'])
20
+ if 'reason' in item:
21
+ lines.append(' ' + repr(item['reason']))
22
+ for step in item['steps']:
23
+ lines.append(' ' + step['module'])
24
+ for candidate in step['candidates']:
25
+ location = (repr(candidate['origin']) if candidate['origin'] else
26
+ ', '.join(repr(path) for path in candidate['locations']))
27
+ lines.append(' ' + candidate['disposition'] + ': ' + candidate['kind'] + ' ' + location)
28
+ for error in step['errors']:
29
+ lines.append(' unchecked root ' + repr(error['root']) + ': ' + repr(error['detail']))
30
+ if step['selection'] is None:
31
+ lines.append(' no candidate found in checked directories')
32
+ for outside in item.get('expectation', {}).get('outside', []):
33
+ lines.append(' outside expected root: ' + repr(outside['physical_path']))
34
+ lines.append(report['scope'])
35
+ return '\n'.join(lines) + '\n'
36
+
37
+
38
+ def _run(argv=None):
39
+ options = {}
40
+ if 'color' in inspect.signature(argparse.ArgumentParser).parameters:
41
+ options['color'] = False
42
+ if 'color' in inspect.signature(argparse.HelpFormatter).parameters:
43
+ options['formatter_class'] = partial(argparse.HelpFormatter, color=False)
44
+ parser = argparse.ArgumentParser(
45
+ description='Explain explicit Python filesystem routes without importing target packages.',
46
+ **options)
47
+ parser.add_argument('modules', nargs='+', help='absolute dotted module identifiers, at most 128')
48
+ parser.add_argument('--path', action='append', required=True,
49
+ help='ordered search directory, repeat for each root; at most 64')
50
+ parser.add_argument('--expect-under', help='require every selected component under this directory')
51
+ parser.add_argument('--json', action='store_true', help='emit the full versioned JSON report')
52
+ args = parser.parse_args(argv)
53
+ try:
54
+ report = trace_imports(args.modules, args.path, expected_root=args.expect_under)
55
+ except (OSError, ValueError, TypeError) as exc:
56
+ report = {'format': 'importroute/v1', 'status': 'INVALID', 'error': str(exc)}
57
+ payload = (json.dumps(report, ensure_ascii=True, allow_nan=False, sort_keys=True) + '\n'
58
+ if args.json else _human(report))
59
+ try:
60
+ if sys.stdout.write(payload) != len(payload):
61
+ return 2, True
62
+ sys.stdout.flush()
63
+ except (OSError, ValueError, AttributeError):
64
+ return 2, True
65
+ return CODES[report['status']], False
66
+
67
+
68
+ def main(argv=None):
69
+ """Return the code without replacing or closing caller-owned stdout."""
70
+ return _run(argv)[0]
71
+
72
+
73
+ def entrypoint():
74
+ code, failed = _run()
75
+ if failed:
76
+ try:
77
+ descriptor = sys.stdout.fileno()
78
+ with open(os.devnull, 'w') as sink:
79
+ os.dup2(sink.fileno(), descriptor)
80
+ except (OSError, ValueError, AttributeError):
81
+ sys.stdout = open(os.devnull, 'w')
82
+ return code
83
+
84
+
85
+ if __name__ == '__main__':
86
+ sys.exit(entrypoint())