pyi-deps 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.
- pyi_deps-0.1.0/LICENSE +21 -0
- pyi_deps-0.1.0/PKG-INFO +192 -0
- pyi_deps-0.1.0/README.md +179 -0
- pyi_deps-0.1.0/pyi_deps/__init__.py +188 -0
- pyi_deps-0.1.0/pyi_deps.egg-info/PKG-INFO +192 -0
- pyi_deps-0.1.0/pyi_deps.egg-info/SOURCES.txt +10 -0
- pyi_deps-0.1.0/pyi_deps.egg-info/dependency_links.txt +1 -0
- pyi_deps-0.1.0/pyi_deps.egg-info/entry_points.txt +2 -0
- pyi_deps-0.1.0/pyi_deps.egg-info/top_level.txt +1 -0
- pyi_deps-0.1.0/pyproject.toml +25 -0
- pyi_deps-0.1.0/setup.cfg +4 -0
- pyi_deps-0.1.0/tests/test_pyi_deps.py +147 -0
pyi_deps-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 suimajian
|
|
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.
|
pyi_deps-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyi-deps
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Generate PyInstaller hidden imports by scanning a staged Python tree
|
|
5
|
+
Author: suimajian
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/suimajian/pyi-deps
|
|
8
|
+
Keywords: pyinstaller,packaging,hiddenimports,frozen
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# pyi-deps
|
|
15
|
+
|
|
16
|
+
Generate the `hiddenimports` list PyInstaller cannot see for itself, by parsing
|
|
17
|
+
the code instead of trusting a hand-written list.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
Not on PyPI yet — `pip install pyi-deps` will 404 until 0.1.0 is published.
|
|
22
|
+
Install from the repository instead:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install git+https://github.com/suimajian/pyi-deps
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The sdist and wheel are attached to the
|
|
29
|
+
[releases](https://github.com/suimajian/pyi-deps/releases); the publish step is
|
|
30
|
+
waiting for credentials, so nothing has been uploaded to the index.
|
|
31
|
+
|
|
32
|
+
## Use
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
python -m pyi_deps --root src/runtime --out build/_deps.py
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
# build/_deps.py — generated, imported by the entry script
|
|
40
|
+
# Generated by pyi_deps -- do not edit.
|
|
41
|
+
# Imported by the entry script so PyInstaller's static analysis sees these.
|
|
42
|
+
try:
|
|
43
|
+
import bs4 # noqa: F401
|
|
44
|
+
except ImportError:
|
|
45
|
+
pass
|
|
46
|
+
try:
|
|
47
|
+
import requests # noqa: F401
|
|
48
|
+
except ImportError:
|
|
49
|
+
pass
|
|
50
|
+
try:
|
|
51
|
+
import tiktoken # noqa: F401
|
|
52
|
+
except ImportError:
|
|
53
|
+
pass
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## The problem it solves
|
|
57
|
+
|
|
58
|
+
PyInstaller freezes an app by walking `import` statements from the entry script.
|
|
59
|
+
Anything it cannot see statically has to be named by hand:
|
|
60
|
+
|
|
61
|
+
| Setup | What PyInstaller sees |
|
|
62
|
+
| --- | --- |
|
|
63
|
+
| `import x` in the entry script | yes |
|
|
64
|
+
| `import x` in a module the entry script imports | yes |
|
|
65
|
+
| `runpy.run_path("runtime/main.py")` | **nothing inside that file** |
|
|
66
|
+
| `importlib.import_module(name)` from a plugin table | **no** |
|
|
67
|
+
|
|
68
|
+
The third row is the common one for launchers: one small entry script, the real
|
|
69
|
+
code shipped as loose files next to it. The build works, then the installed app
|
|
70
|
+
dies with `ModuleNotFoundError: No module named 'logging.handlers'` on a code
|
|
71
|
+
path nobody exercised during the smoke test.
|
|
72
|
+
|
|
73
|
+
The fix everyone reaches for is a manually maintained hidden-import list. It is
|
|
74
|
+
correct the day it is written and wrong the first time someone in the runtime
|
|
75
|
+
tree adds an import — with no test failing, because the failure only appears in
|
|
76
|
+
a frozen build.
|
|
77
|
+
|
|
78
|
+
This tool turns that list into a scan. The generated module is imported by the
|
|
79
|
+
entry script, so PyInstaller's normal analysis picks the imports up from there:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
# entry script
|
|
83
|
+
import _deps # noqa: F401 (generated at build time)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Usage
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
# in the build script, right before PyInstaller runs
|
|
90
|
+
python -m pyi_deps --root stage/runtime --out stage/_deps.py \
|
|
91
|
+
--local app --local config \
|
|
92
|
+
--exclude PIL
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
| Flag | Meaning |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `--root` | directory to scan recursively (`.py` only, `__pycache__` skipped) |
|
|
98
|
+
| `--out` | where to write the generated module |
|
|
99
|
+
| `--local` | top-level name that is part of the app, so never emitted (repeatable) |
|
|
100
|
+
| `--exclude` | import prefix to leave out of the build, e.g. `PIL` (repeatable) |
|
|
101
|
+
| `--no-submodules` | skip `from package import module` resolution (cross-builds) |
|
|
102
|
+
| `--include-stdlib` | also list `os`, `json`, … (off by default: the generated file is for dependencies) |
|
|
103
|
+
|
|
104
|
+
## Every import is wrapped in `try/except`
|
|
105
|
+
|
|
106
|
+
The scan cannot tell a required import from one the code guards itself:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
try:
|
|
110
|
+
import win32api # optional on this platform
|
|
111
|
+
except ImportError:
|
|
112
|
+
win32api = None
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
A bare `import win32api` in the generated module would turn that optional
|
|
116
|
+
dependency into a hard requirement — and because the entry script imports the
|
|
117
|
+
generated module, the app would die at startup on exactly the machines the guard
|
|
118
|
+
was written for. So each name gets its own `try` block:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
try:
|
|
122
|
+
import win32api # noqa: F401
|
|
123
|
+
except ImportError:
|
|
124
|
+
pass # optional dependency: PyInstaller still sees the import
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
PyInstaller's analysis is static, so an import inside a `try` is still found and
|
|
128
|
+
still bundled; only the runtime behaviour changes. One `try` per name, not one
|
|
129
|
+
around the block: otherwise the first missing package would skip all the rest.
|
|
130
|
+
|
|
131
|
+
As a library:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from pyi_deps import scan, render
|
|
135
|
+
|
|
136
|
+
names = scan("stage/runtime", local_modules={"app"}, exclude_prefixes=("PIL",))
|
|
137
|
+
Path("stage/_deps.py").write_text(render(names), encoding="utf-8")
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## The submodule detail
|
|
141
|
+
|
|
142
|
+
`from Crypto.Cipher import AES` imports **a module**, not an attribute. PyInstaller
|
|
143
|
+
bundles `Crypto.Cipher` and the binding then fails at runtime, because `AES` is a
|
|
144
|
+
separate extension. The scanner asks `importlib.util.find_spec` whether each
|
|
145
|
+
imported name resolves to a module and, if so, emits the full dotted path
|
|
146
|
+
(`Crypto.Cipher.AES`) as well.
|
|
147
|
+
|
|
148
|
+
That check needs the packages installed on the scanning machine, which is why
|
|
149
|
+
`--no-submodules` exists for cross-builds. Note what it does: `find_spec("a.b.c")`
|
|
150
|
+
**imports `a.b`** to look inside it, so a package with import-time side effects
|
|
151
|
+
(reads config, opens a connection) runs them during the scan. Do the scan in the
|
|
152
|
+
same throwaway environment you build in, or pass `--no-submodules` and accept
|
|
153
|
+
losing the submodule hint.
|
|
154
|
+
|
|
155
|
+
## Limits
|
|
156
|
+
|
|
157
|
+
- Only static `import` / `from ... import` statements. `importlib.import_module(var)`
|
|
158
|
+
with a runtime-computed name is still your problem.
|
|
159
|
+
- It collects *names*, not versions. Pair it with a pinned requirements file.
|
|
160
|
+
- A syntax error in the tree is surfaced, not skipped: a broken file at build
|
|
161
|
+
time is better than a missing import at run time.
|
|
162
|
+
- Standard library names are filtered out by default (`--include-stdlib` keeps
|
|
163
|
+
them). They are already bundled; listing them only hides the real ones.
|
|
164
|
+
- Relative imports (`from . import x`) are ignored — a staged build directory has
|
|
165
|
+
no package context to resolve them against.
|
|
166
|
+
- It does not read the installed distributions' `top_level.txt`; what is on disk
|
|
167
|
+
under the scanned root is what gets listed.
|
|
168
|
+
|
|
169
|
+
## Scope and non-goals
|
|
170
|
+
|
|
171
|
+
- **Not a packaging tool.** It writes one module of `try: import x` lines and
|
|
172
|
+
stops. No hooks, no spec files, no version pinning.
|
|
173
|
+
- **Not a sandbox.** `find_spec` may import parent packages, so scan inside the
|
|
174
|
+
same throwaway environment you build in.
|
|
175
|
+
- **No import-time validation of your code** — that is what `pytest` and running
|
|
176
|
+
the frozen build are for.
|
|
177
|
+
|
|
178
|
+
## Status
|
|
179
|
+
|
|
180
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
181
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
182
|
+
secret exists, so nothing is published by accident.
|
|
183
|
+
|
|
184
|
+
## Tests
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
python -m pytest -q
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Licence
|
|
191
|
+
|
|
192
|
+
MIT.
|
pyi_deps-0.1.0/README.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# pyi-deps
|
|
2
|
+
|
|
3
|
+
Generate the `hiddenimports` list PyInstaller cannot see for itself, by parsing
|
|
4
|
+
the code instead of trusting a hand-written list.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
Not on PyPI yet — `pip install pyi-deps` will 404 until 0.1.0 is published.
|
|
9
|
+
Install from the repository instead:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install git+https://github.com/suimajian/pyi-deps
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The sdist and wheel are attached to the
|
|
16
|
+
[releases](https://github.com/suimajian/pyi-deps/releases); the publish step is
|
|
17
|
+
waiting for credentials, so nothing has been uploaded to the index.
|
|
18
|
+
|
|
19
|
+
## Use
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python -m pyi_deps --root src/runtime --out build/_deps.py
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
# build/_deps.py — generated, imported by the entry script
|
|
27
|
+
# Generated by pyi_deps -- do not edit.
|
|
28
|
+
# Imported by the entry script so PyInstaller's static analysis sees these.
|
|
29
|
+
try:
|
|
30
|
+
import bs4 # noqa: F401
|
|
31
|
+
except ImportError:
|
|
32
|
+
pass
|
|
33
|
+
try:
|
|
34
|
+
import requests # noqa: F401
|
|
35
|
+
except ImportError:
|
|
36
|
+
pass
|
|
37
|
+
try:
|
|
38
|
+
import tiktoken # noqa: F401
|
|
39
|
+
except ImportError:
|
|
40
|
+
pass
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## The problem it solves
|
|
44
|
+
|
|
45
|
+
PyInstaller freezes an app by walking `import` statements from the entry script.
|
|
46
|
+
Anything it cannot see statically has to be named by hand:
|
|
47
|
+
|
|
48
|
+
| Setup | What PyInstaller sees |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `import x` in the entry script | yes |
|
|
51
|
+
| `import x` in a module the entry script imports | yes |
|
|
52
|
+
| `runpy.run_path("runtime/main.py")` | **nothing inside that file** |
|
|
53
|
+
| `importlib.import_module(name)` from a plugin table | **no** |
|
|
54
|
+
|
|
55
|
+
The third row is the common one for launchers: one small entry script, the real
|
|
56
|
+
code shipped as loose files next to it. The build works, then the installed app
|
|
57
|
+
dies with `ModuleNotFoundError: No module named 'logging.handlers'` on a code
|
|
58
|
+
path nobody exercised during the smoke test.
|
|
59
|
+
|
|
60
|
+
The fix everyone reaches for is a manually maintained hidden-import list. It is
|
|
61
|
+
correct the day it is written and wrong the first time someone in the runtime
|
|
62
|
+
tree adds an import — with no test failing, because the failure only appears in
|
|
63
|
+
a frozen build.
|
|
64
|
+
|
|
65
|
+
This tool turns that list into a scan. The generated module is imported by the
|
|
66
|
+
entry script, so PyInstaller's normal analysis picks the imports up from there:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# entry script
|
|
70
|
+
import _deps # noqa: F401 (generated at build time)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Usage
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
# in the build script, right before PyInstaller runs
|
|
77
|
+
python -m pyi_deps --root stage/runtime --out stage/_deps.py \
|
|
78
|
+
--local app --local config \
|
|
79
|
+
--exclude PIL
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
| Flag | Meaning |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `--root` | directory to scan recursively (`.py` only, `__pycache__` skipped) |
|
|
85
|
+
| `--out` | where to write the generated module |
|
|
86
|
+
| `--local` | top-level name that is part of the app, so never emitted (repeatable) |
|
|
87
|
+
| `--exclude` | import prefix to leave out of the build, e.g. `PIL` (repeatable) |
|
|
88
|
+
| `--no-submodules` | skip `from package import module` resolution (cross-builds) |
|
|
89
|
+
| `--include-stdlib` | also list `os`, `json`, … (off by default: the generated file is for dependencies) |
|
|
90
|
+
|
|
91
|
+
## Every import is wrapped in `try/except`
|
|
92
|
+
|
|
93
|
+
The scan cannot tell a required import from one the code guards itself:
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
try:
|
|
97
|
+
import win32api # optional on this platform
|
|
98
|
+
except ImportError:
|
|
99
|
+
win32api = None
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
A bare `import win32api` in the generated module would turn that optional
|
|
103
|
+
dependency into a hard requirement — and because the entry script imports the
|
|
104
|
+
generated module, the app would die at startup on exactly the machines the guard
|
|
105
|
+
was written for. So each name gets its own `try` block:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
try:
|
|
109
|
+
import win32api # noqa: F401
|
|
110
|
+
except ImportError:
|
|
111
|
+
pass # optional dependency: PyInstaller still sees the import
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
PyInstaller's analysis is static, so an import inside a `try` is still found and
|
|
115
|
+
still bundled; only the runtime behaviour changes. One `try` per name, not one
|
|
116
|
+
around the block: otherwise the first missing package would skip all the rest.
|
|
117
|
+
|
|
118
|
+
As a library:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from pyi_deps import scan, render
|
|
122
|
+
|
|
123
|
+
names = scan("stage/runtime", local_modules={"app"}, exclude_prefixes=("PIL",))
|
|
124
|
+
Path("stage/_deps.py").write_text(render(names), encoding="utf-8")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## The submodule detail
|
|
128
|
+
|
|
129
|
+
`from Crypto.Cipher import AES` imports **a module**, not an attribute. PyInstaller
|
|
130
|
+
bundles `Crypto.Cipher` and the binding then fails at runtime, because `AES` is a
|
|
131
|
+
separate extension. The scanner asks `importlib.util.find_spec` whether each
|
|
132
|
+
imported name resolves to a module and, if so, emits the full dotted path
|
|
133
|
+
(`Crypto.Cipher.AES`) as well.
|
|
134
|
+
|
|
135
|
+
That check needs the packages installed on the scanning machine, which is why
|
|
136
|
+
`--no-submodules` exists for cross-builds. Note what it does: `find_spec("a.b.c")`
|
|
137
|
+
**imports `a.b`** to look inside it, so a package with import-time side effects
|
|
138
|
+
(reads config, opens a connection) runs them during the scan. Do the scan in the
|
|
139
|
+
same throwaway environment you build in, or pass `--no-submodules` and accept
|
|
140
|
+
losing the submodule hint.
|
|
141
|
+
|
|
142
|
+
## Limits
|
|
143
|
+
|
|
144
|
+
- Only static `import` / `from ... import` statements. `importlib.import_module(var)`
|
|
145
|
+
with a runtime-computed name is still your problem.
|
|
146
|
+
- It collects *names*, not versions. Pair it with a pinned requirements file.
|
|
147
|
+
- A syntax error in the tree is surfaced, not skipped: a broken file at build
|
|
148
|
+
time is better than a missing import at run time.
|
|
149
|
+
- Standard library names are filtered out by default (`--include-stdlib` keeps
|
|
150
|
+
them). They are already bundled; listing them only hides the real ones.
|
|
151
|
+
- Relative imports (`from . import x`) are ignored — a staged build directory has
|
|
152
|
+
no package context to resolve them against.
|
|
153
|
+
- It does not read the installed distributions' `top_level.txt`; what is on disk
|
|
154
|
+
under the scanned root is what gets listed.
|
|
155
|
+
|
|
156
|
+
## Scope and non-goals
|
|
157
|
+
|
|
158
|
+
- **Not a packaging tool.** It writes one module of `try: import x` lines and
|
|
159
|
+
stops. No hooks, no spec files, no version pinning.
|
|
160
|
+
- **Not a sandbox.** `find_spec` may import parent packages, so scan inside the
|
|
161
|
+
same throwaway environment you build in.
|
|
162
|
+
- **No import-time validation of your code** — that is what `pytest` and running
|
|
163
|
+
the frozen build are for.
|
|
164
|
+
|
|
165
|
+
## Status
|
|
166
|
+
|
|
167
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
168
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
169
|
+
secret exists, so nothing is published by accident.
|
|
170
|
+
|
|
171
|
+
## Tests
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
python -m pytest -q
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Licence
|
|
178
|
+
|
|
179
|
+
MIT.
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Collect the imports of a staged Python tree so PyInstaller can see them.
|
|
2
|
+
|
|
3
|
+
PyInstaller's analysis starts at the entry script and follows ``import``
|
|
4
|
+
statements statically. That misses two common setups:
|
|
5
|
+
|
|
6
|
+
* scripts executed with ``runpy`` (a launcher loads them by path), and
|
|
7
|
+
* imports resolved at runtime by a plugin mechanism.
|
|
8
|
+
|
|
9
|
+
Both fail the same way: the app runs fine from source, then the frozen build
|
|
10
|
+
dies with ``ModuleNotFoundError`` on first use. The usual fix is a hand-written
|
|
11
|
+
list of hidden imports — which drifts the moment somebody adds an import.
|
|
12
|
+
|
|
13
|
+
This module replaces the list with a scan: parse every ``.py`` file under a
|
|
14
|
+
root, collect ``import x`` and ``from x import y``, drop local modules and
|
|
15
|
+
anything you asked to exclude, and emit a generated module that imports the
|
|
16
|
+
rest. PyInstaller sees the generated module because it is imported by the entry
|
|
17
|
+
script; the imports are real, so nothing has to be kept in sync by hand.
|
|
18
|
+
|
|
19
|
+
python -m pyi_deps --root src/runtime --out build/_deps.py
|
|
20
|
+
|
|
21
|
+
A subtlety worth the code: ``from Crypto.Cipher import AES`` names a module,
|
|
22
|
+
not an attribute, and PyInstaller will bundle ``Crypto.Cipher`` but not
|
|
23
|
+
``AES``. The scanner checks each imported name with :func:`importlib.util.find_spec`
|
|
24
|
+
and adds ``Crypto.Cipher.AES`` when it resolves.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import argparse
|
|
30
|
+
import ast
|
|
31
|
+
import importlib.util
|
|
32
|
+
import sys
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Iterable, Sequence
|
|
35
|
+
|
|
36
|
+
__all__ = ["scan", "render", "main"]
|
|
37
|
+
|
|
38
|
+
HEADER = (
|
|
39
|
+
"# Generated by pyi_deps -- do not edit.\n"
|
|
40
|
+
"# Imported by the entry script so PyInstaller's static analysis sees these.\n"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _submodule_exists(name: str) -> bool:
|
|
45
|
+
try:
|
|
46
|
+
return importlib.util.find_spec(name) is not None
|
|
47
|
+
except (ImportError, AttributeError, ValueError):
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_excluded(name: str, prefixes: Sequence[str]) -> bool:
|
|
52
|
+
return any(name == p or name.startswith(p + ".") for p in prefixes)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _stdlib_names() -> frozenset:
|
|
56
|
+
"""Top-level standard library modules, for filtering the output."""
|
|
57
|
+
names = getattr(sys, "stdlib_module_names", None) # Python 3.10+
|
|
58
|
+
if names is not None:
|
|
59
|
+
return frozenset(names)
|
|
60
|
+
# 3.9 has no sys.stdlib_module_names; this list only needs to cover what a
|
|
61
|
+
# normal project imports, and a miss here costs one harmless extra import.
|
|
62
|
+
return frozenset({
|
|
63
|
+
"abc", "argparse", "array", "ast", "asyncio", "base64", "binascii", "bisect",
|
|
64
|
+
"builtins", "bz2", "calendar", "codecs", "collections", "concurrent", "configparser",
|
|
65
|
+
"contextlib", "copy", "csv", "ctypes", "dataclasses", "datetime", "decimal", "difflib",
|
|
66
|
+
"dis", "email", "enum", "errno", "faulthandler", "filecmp", "fileinput", "fnmatch",
|
|
67
|
+
"fractions", "ftplib", "functools", "gc", "getopt", "getpass", "gettext", "glob",
|
|
68
|
+
"gzip", "hashlib", "heapq", "hmac", "html", "http", "imaplib", "importlib", "inspect",
|
|
69
|
+
"io", "ipaddress", "itertools", "json", "keyword", "linecache", "locale", "logging",
|
|
70
|
+
"lzma", "mailbox", "math", "mimetypes", "multiprocessing", "netrc", "numbers",
|
|
71
|
+
"operator", "os", "pathlib", "pickle", "pkgutil", "platform", "plistlib", "pprint",
|
|
72
|
+
"queue", "random", "re", "readline", "secrets", "select", "selectors", "shlex",
|
|
73
|
+
"shutil", "signal", "site", "smtplib", "socket", "sqlite3", "ssl", "stat", "statistics",
|
|
74
|
+
"string", "struct", "subprocess", "sys", "sysconfig", "tarfile", "tempfile", "textwrap",
|
|
75
|
+
"threading", "time", "timeit", "tkinter", "token", "tokenize", "traceback", "types",
|
|
76
|
+
"typing", "unicodedata", "unittest", "urllib", "uuid", "venv", "warnings", "wave",
|
|
77
|
+
"weakref", "webbrowser", "xml", "zipfile", "zipimport", "zlib",
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def scan(root: str | Path, *, local_modules: Iterable[str] = (),
|
|
82
|
+
exclude_prefixes: Iterable[str] = (), resolve_submodules: bool = True,
|
|
83
|
+
include_stdlib: bool = False) -> list[str]:
|
|
84
|
+
"""Return every import found under *root*, sorted and unique.
|
|
85
|
+
|
|
86
|
+
Standard library names are dropped by default: the generated module is meant
|
|
87
|
+
to list third-party dependencies, and ``import os`` in it is only noise.
|
|
88
|
+
|
|
89
|
+
``local_modules`` are top-level names that live next to the scanned files and
|
|
90
|
+
are resolved by the runtime itself; excluding them keeps the generated module
|
|
91
|
+
importable outside the frozen build.
|
|
92
|
+
|
|
93
|
+
``resolve_submodules`` controls the ``from package import module`` heuristic;
|
|
94
|
+
it needs the packages to be importable on the machine doing the scan, so turn
|
|
95
|
+
it off when cross-building. That heuristic uses
|
|
96
|
+
:func:`importlib.util.find_spec`, which imports the parent package — run it in
|
|
97
|
+
the same throwaway environment you build in.
|
|
98
|
+
"""
|
|
99
|
+
local = set(local_modules)
|
|
100
|
+
excludes = tuple(exclude_prefixes)
|
|
101
|
+
stdlib = frozenset() if include_stdlib else _stdlib_names()
|
|
102
|
+
names: set[str] = set()
|
|
103
|
+
|
|
104
|
+
for path in sorted(Path(root).rglob("*.py")):
|
|
105
|
+
if "__pycache__" in path.parts:
|
|
106
|
+
continue
|
|
107
|
+
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
|
108
|
+
for node in ast.walk(tree):
|
|
109
|
+
if isinstance(node, ast.Import):
|
|
110
|
+
for alias in node.names:
|
|
111
|
+
names.add(alias.name)
|
|
112
|
+
elif isinstance(node, ast.ImportFrom):
|
|
113
|
+
# level > 0 is a relative import: it stays inside the package.
|
|
114
|
+
if node.level or not node.module:
|
|
115
|
+
continue
|
|
116
|
+
names.add(node.module)
|
|
117
|
+
if not resolve_submodules:
|
|
118
|
+
continue
|
|
119
|
+
for alias in node.names:
|
|
120
|
+
if alias.name == "*":
|
|
121
|
+
continue
|
|
122
|
+
full = node.module + "." + alias.name
|
|
123
|
+
if _submodule_exists(full):
|
|
124
|
+
names.add(full)
|
|
125
|
+
|
|
126
|
+
return sorted(
|
|
127
|
+
n for n in names
|
|
128
|
+
if n.split(".")[0] not in local
|
|
129
|
+
and n.split(".")[0] not in stdlib
|
|
130
|
+
and not _is_excluded(n, excludes)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def render(names: Iterable[str]) -> str:
|
|
135
|
+
"""Render the generated module source.
|
|
136
|
+
|
|
137
|
+
Every import is wrapped in its own ``try/except ImportError``. The scan cannot
|
|
138
|
+
tell an import that is required from one the code guards with
|
|
139
|
+
``try: import x / except ImportError``, and a bare ``import x`` in this file
|
|
140
|
+
would turn every optional dependency into a hard requirement — the generated
|
|
141
|
+
module is imported by the entry script, so a missing package would abort
|
|
142
|
+
startup before the app's own guard ever runs.
|
|
143
|
+
|
|
144
|
+
PyInstaller is not affected: it analyses imports statically, and an import
|
|
145
|
+
inside a ``try`` block is still seen and still pulled into the bundle. One
|
|
146
|
+
``try`` per name, not one around the block, because a single missing package
|
|
147
|
+
would otherwise skip every import after it.
|
|
148
|
+
"""
|
|
149
|
+
body = "".join(
|
|
150
|
+
"try:\n"
|
|
151
|
+
f" import {name} # noqa: F401\n"
|
|
152
|
+
"except ImportError:\n"
|
|
153
|
+
" pass # optional dependency: PyInstaller still sees the import\n"
|
|
154
|
+
for name in names
|
|
155
|
+
)
|
|
156
|
+
return HEADER + body
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def main(argv: list[str] | None = None) -> int:
|
|
160
|
+
parser = argparse.ArgumentParser(
|
|
161
|
+
prog="pyi_deps", description="Scan a staged tree and emit a PyInstaller deps module."
|
|
162
|
+
)
|
|
163
|
+
parser.add_argument("--root", required=True, help="directory to scan recursively")
|
|
164
|
+
parser.add_argument("--out", required=True, help="path of the generated .py file")
|
|
165
|
+
parser.add_argument("--local", action="append", default=[],
|
|
166
|
+
help="local module name to ignore (repeatable)")
|
|
167
|
+
parser.add_argument("--exclude", action="append", default=[],
|
|
168
|
+
help="import prefix to exclude, e.g. PIL (repeatable)")
|
|
169
|
+
parser.add_argument("--no-submodules", action="store_true",
|
|
170
|
+
help="skip the 'from package import module' resolution")
|
|
171
|
+
parser.add_argument("--include-stdlib", action="store_true",
|
|
172
|
+
help="also list standard library modules (off by default)")
|
|
173
|
+
args = parser.parse_args(argv)
|
|
174
|
+
|
|
175
|
+
names = scan(args.root, local_modules=args.local, exclude_prefixes=args.exclude,
|
|
176
|
+
resolve_submodules=not args.no_submodules,
|
|
177
|
+
include_stdlib=args.include_stdlib)
|
|
178
|
+
out = Path(args.out)
|
|
179
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
180
|
+
# Path.write_text(newline=...) only exists from 3.10; Path.open does the job on 3.9.
|
|
181
|
+
with out.open("w", encoding="utf-8", newline="\n") as handle:
|
|
182
|
+
handle.write(render(names))
|
|
183
|
+
print(f"pyi_deps: {len(names)} imports -> {out}")
|
|
184
|
+
return 0
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
if __name__ == "__main__":
|
|
188
|
+
sys.exit(main())
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyi-deps
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Generate PyInstaller hidden imports by scanning a staged Python tree
|
|
5
|
+
Author: suimajian
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/suimajian/pyi-deps
|
|
8
|
+
Keywords: pyinstaller,packaging,hiddenimports,frozen
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# pyi-deps
|
|
15
|
+
|
|
16
|
+
Generate the `hiddenimports` list PyInstaller cannot see for itself, by parsing
|
|
17
|
+
the code instead of trusting a hand-written list.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
Not on PyPI yet — `pip install pyi-deps` will 404 until 0.1.0 is published.
|
|
22
|
+
Install from the repository instead:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install git+https://github.com/suimajian/pyi-deps
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The sdist and wheel are attached to the
|
|
29
|
+
[releases](https://github.com/suimajian/pyi-deps/releases); the publish step is
|
|
30
|
+
waiting for credentials, so nothing has been uploaded to the index.
|
|
31
|
+
|
|
32
|
+
## Use
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
python -m pyi_deps --root src/runtime --out build/_deps.py
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
# build/_deps.py — generated, imported by the entry script
|
|
40
|
+
# Generated by pyi_deps -- do not edit.
|
|
41
|
+
# Imported by the entry script so PyInstaller's static analysis sees these.
|
|
42
|
+
try:
|
|
43
|
+
import bs4 # noqa: F401
|
|
44
|
+
except ImportError:
|
|
45
|
+
pass
|
|
46
|
+
try:
|
|
47
|
+
import requests # noqa: F401
|
|
48
|
+
except ImportError:
|
|
49
|
+
pass
|
|
50
|
+
try:
|
|
51
|
+
import tiktoken # noqa: F401
|
|
52
|
+
except ImportError:
|
|
53
|
+
pass
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## The problem it solves
|
|
57
|
+
|
|
58
|
+
PyInstaller freezes an app by walking `import` statements from the entry script.
|
|
59
|
+
Anything it cannot see statically has to be named by hand:
|
|
60
|
+
|
|
61
|
+
| Setup | What PyInstaller sees |
|
|
62
|
+
| --- | --- |
|
|
63
|
+
| `import x` in the entry script | yes |
|
|
64
|
+
| `import x` in a module the entry script imports | yes |
|
|
65
|
+
| `runpy.run_path("runtime/main.py")` | **nothing inside that file** |
|
|
66
|
+
| `importlib.import_module(name)` from a plugin table | **no** |
|
|
67
|
+
|
|
68
|
+
The third row is the common one for launchers: one small entry script, the real
|
|
69
|
+
code shipped as loose files next to it. The build works, then the installed app
|
|
70
|
+
dies with `ModuleNotFoundError: No module named 'logging.handlers'` on a code
|
|
71
|
+
path nobody exercised during the smoke test.
|
|
72
|
+
|
|
73
|
+
The fix everyone reaches for is a manually maintained hidden-import list. It is
|
|
74
|
+
correct the day it is written and wrong the first time someone in the runtime
|
|
75
|
+
tree adds an import — with no test failing, because the failure only appears in
|
|
76
|
+
a frozen build.
|
|
77
|
+
|
|
78
|
+
This tool turns that list into a scan. The generated module is imported by the
|
|
79
|
+
entry script, so PyInstaller's normal analysis picks the imports up from there:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
# entry script
|
|
83
|
+
import _deps # noqa: F401 (generated at build time)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Usage
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
# in the build script, right before PyInstaller runs
|
|
90
|
+
python -m pyi_deps --root stage/runtime --out stage/_deps.py \
|
|
91
|
+
--local app --local config \
|
|
92
|
+
--exclude PIL
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
| Flag | Meaning |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `--root` | directory to scan recursively (`.py` only, `__pycache__` skipped) |
|
|
98
|
+
| `--out` | where to write the generated module |
|
|
99
|
+
| `--local` | top-level name that is part of the app, so never emitted (repeatable) |
|
|
100
|
+
| `--exclude` | import prefix to leave out of the build, e.g. `PIL` (repeatable) |
|
|
101
|
+
| `--no-submodules` | skip `from package import module` resolution (cross-builds) |
|
|
102
|
+
| `--include-stdlib` | also list `os`, `json`, … (off by default: the generated file is for dependencies) |
|
|
103
|
+
|
|
104
|
+
## Every import is wrapped in `try/except`
|
|
105
|
+
|
|
106
|
+
The scan cannot tell a required import from one the code guards itself:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
try:
|
|
110
|
+
import win32api # optional on this platform
|
|
111
|
+
except ImportError:
|
|
112
|
+
win32api = None
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
A bare `import win32api` in the generated module would turn that optional
|
|
116
|
+
dependency into a hard requirement — and because the entry script imports the
|
|
117
|
+
generated module, the app would die at startup on exactly the machines the guard
|
|
118
|
+
was written for. So each name gets its own `try` block:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
try:
|
|
122
|
+
import win32api # noqa: F401
|
|
123
|
+
except ImportError:
|
|
124
|
+
pass # optional dependency: PyInstaller still sees the import
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
PyInstaller's analysis is static, so an import inside a `try` is still found and
|
|
128
|
+
still bundled; only the runtime behaviour changes. One `try` per name, not one
|
|
129
|
+
around the block: otherwise the first missing package would skip all the rest.
|
|
130
|
+
|
|
131
|
+
As a library:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from pyi_deps import scan, render
|
|
135
|
+
|
|
136
|
+
names = scan("stage/runtime", local_modules={"app"}, exclude_prefixes=("PIL",))
|
|
137
|
+
Path("stage/_deps.py").write_text(render(names), encoding="utf-8")
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## The submodule detail
|
|
141
|
+
|
|
142
|
+
`from Crypto.Cipher import AES` imports **a module**, not an attribute. PyInstaller
|
|
143
|
+
bundles `Crypto.Cipher` and the binding then fails at runtime, because `AES` is a
|
|
144
|
+
separate extension. The scanner asks `importlib.util.find_spec` whether each
|
|
145
|
+
imported name resolves to a module and, if so, emits the full dotted path
|
|
146
|
+
(`Crypto.Cipher.AES`) as well.
|
|
147
|
+
|
|
148
|
+
That check needs the packages installed on the scanning machine, which is why
|
|
149
|
+
`--no-submodules` exists for cross-builds. Note what it does: `find_spec("a.b.c")`
|
|
150
|
+
**imports `a.b`** to look inside it, so a package with import-time side effects
|
|
151
|
+
(reads config, opens a connection) runs them during the scan. Do the scan in the
|
|
152
|
+
same throwaway environment you build in, or pass `--no-submodules` and accept
|
|
153
|
+
losing the submodule hint.
|
|
154
|
+
|
|
155
|
+
## Limits
|
|
156
|
+
|
|
157
|
+
- Only static `import` / `from ... import` statements. `importlib.import_module(var)`
|
|
158
|
+
with a runtime-computed name is still your problem.
|
|
159
|
+
- It collects *names*, not versions. Pair it with a pinned requirements file.
|
|
160
|
+
- A syntax error in the tree is surfaced, not skipped: a broken file at build
|
|
161
|
+
time is better than a missing import at run time.
|
|
162
|
+
- Standard library names are filtered out by default (`--include-stdlib` keeps
|
|
163
|
+
them). They are already bundled; listing them only hides the real ones.
|
|
164
|
+
- Relative imports (`from . import x`) are ignored — a staged build directory has
|
|
165
|
+
no package context to resolve them against.
|
|
166
|
+
- It does not read the installed distributions' `top_level.txt`; what is on disk
|
|
167
|
+
under the scanned root is what gets listed.
|
|
168
|
+
|
|
169
|
+
## Scope and non-goals
|
|
170
|
+
|
|
171
|
+
- **Not a packaging tool.** It writes one module of `try: import x` lines and
|
|
172
|
+
stops. No hooks, no spec files, no version pinning.
|
|
173
|
+
- **Not a sandbox.** `find_spec` may import parent packages, so scan inside the
|
|
174
|
+
same throwaway environment you build in.
|
|
175
|
+
- **No import-time validation of your code** — that is what `pytest` and running
|
|
176
|
+
the frozen build are for.
|
|
177
|
+
|
|
178
|
+
## Status
|
|
179
|
+
|
|
180
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
181
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
182
|
+
secret exists, so nothing is published by accident.
|
|
183
|
+
|
|
184
|
+
## Tests
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
python -m pytest -q
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Licence
|
|
191
|
+
|
|
192
|
+
MIT.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pyi_deps
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pyi-deps"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Generate PyInstaller hidden imports by scanning a staged Python tree"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "suimajian" }]
|
|
13
|
+
keywords = ["pyinstaller", "packaging", "hiddenimports", "frozen"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://github.com/suimajian/pyi-deps"
|
|
17
|
+
|
|
18
|
+
[project.scripts]
|
|
19
|
+
pyi-deps = "pyi_deps:main"
|
|
20
|
+
|
|
21
|
+
[tool.setuptools]
|
|
22
|
+
packages = ["pyi_deps"]
|
|
23
|
+
|
|
24
|
+
[tool.pytest.ini_options]
|
|
25
|
+
testpaths = ["tests"]
|
pyi_deps-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
|
|
5
|
+
from pyi_deps import main, render, scan
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _tree(tmp_path, files: dict[str, str]):
|
|
9
|
+
for name, src in files.items():
|
|
10
|
+
p = tmp_path / name
|
|
11
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
12
|
+
p.write_text(src, encoding="utf-8")
|
|
13
|
+
return tmp_path
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_collects_plain_and_from_imports(tmp_path):
|
|
17
|
+
root = _tree(tmp_path, {
|
|
18
|
+
"a.py": "import os\nimport requests\nfrom bs4 import BeautifulSoup\n",
|
|
19
|
+
})
|
|
20
|
+
names = scan(root, local_modules=(), resolve_submodules=False)
|
|
21
|
+
assert "requests" in names and "bs4" in names
|
|
22
|
+
assert "os" not in names, "standard library is filtered out by default"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_drops_local_modules(tmp_path):
|
|
26
|
+
root = _tree(tmp_path, {
|
|
27
|
+
"app.py": "import requests\nimport config\n",
|
|
28
|
+
"config.py": "X = 1\n",
|
|
29
|
+
})
|
|
30
|
+
names = scan(root, local_modules={"config"})
|
|
31
|
+
assert "requests" in names
|
|
32
|
+
assert "config" not in names
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_prefix_exclusion_matches_package_tree(tmp_path):
|
|
36
|
+
root = _tree(tmp_path, {"a.py": "import PIL\nimport PIL.Image\nimport numpy\n"})
|
|
37
|
+
names = scan(root, exclude_prefixes=("PIL",))
|
|
38
|
+
assert names == ["numpy"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_relative_imports_are_ignored(tmp_path):
|
|
42
|
+
root = _tree(tmp_path, {"pkg/a.py": "from .b import thing\nfrom .. import c\n"})
|
|
43
|
+
assert scan(root) == []
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_recurses_into_subdirectories_and_skips_pycache(tmp_path):
|
|
47
|
+
root = _tree(tmp_path, {
|
|
48
|
+
"top.py": "import top_level\n",
|
|
49
|
+
"pkg/deep/mod.py": "import deep_mod\n",
|
|
50
|
+
"__pycache__/junk.py": "import should_not_appear\n",
|
|
51
|
+
})
|
|
52
|
+
names = scan(root)
|
|
53
|
+
assert "top_level" in names and "deep_mod" in names
|
|
54
|
+
assert "should_not_appear" not in names
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_resolves_from_package_import_module(tmp_path):
|
|
58
|
+
root = _tree(tmp_path, {"a.py": "from json import decoder\n"})
|
|
59
|
+
names = scan(root, resolve_submodules=True, include_stdlib=True)
|
|
60
|
+
assert "json" in names
|
|
61
|
+
assert "json.decoder" in names
|
|
62
|
+
|
|
63
|
+
names_no_resolve = scan(root, resolve_submodules=False, include_stdlib=True)
|
|
64
|
+
assert "json.decoder" not in names_no_resolve
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_include_stdlib_keeps_standard_library(tmp_path):
|
|
68
|
+
root = _tree(tmp_path, {"a.py": "import os\nimport requests\n"})
|
|
69
|
+
assert scan(root, include_stdlib=True) == ["os", "requests"]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_output_is_sorted_and_unique(tmp_path):
|
|
73
|
+
root = _tree(tmp_path, {
|
|
74
|
+
"a.py": "import requests\nimport os\n",
|
|
75
|
+
"b.py": "import requests\n",
|
|
76
|
+
})
|
|
77
|
+
names = scan(root)
|
|
78
|
+
assert names == sorted(set(names))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_render_is_importable_and_commented():
|
|
82
|
+
src = render(["os", "json"])
|
|
83
|
+
assert "Generated by pyi_deps" in src
|
|
84
|
+
assert "import os # noqa: F401" in src
|
|
85
|
+
compile(src, "<generated>", "exec")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_optional_import_does_not_break_the_generated_module(tmp_path):
|
|
89
|
+
"""`try: import x / except ImportError` must survive into the generated file.
|
|
90
|
+
|
|
91
|
+
A bare `import x` would make a missing optional package abort startup, which is
|
|
92
|
+
the exact failure this tool exists to prevent.
|
|
93
|
+
"""
|
|
94
|
+
root = _tree(tmp_path, {
|
|
95
|
+
"win.py": "try:\n import win32api\nexcept ImportError:\n win32api = None\n",
|
|
96
|
+
})
|
|
97
|
+
names = scan(root, resolve_submodules=False)
|
|
98
|
+
assert "win32api" in names
|
|
99
|
+
|
|
100
|
+
out = tmp_path / "_deps.py"
|
|
101
|
+
assert main(["--root", str(root), "--out", str(out)]) == 0
|
|
102
|
+
src = out.read_text(encoding="utf-8")
|
|
103
|
+
assert "try:" in src and "except ImportError" in src
|
|
104
|
+
|
|
105
|
+
# Import it in a fresh interpreter: the module must not raise.
|
|
106
|
+
import subprocess
|
|
107
|
+
import sys as _sys
|
|
108
|
+
result = subprocess.run(
|
|
109
|
+
[_sys.executable, "-c", "import importlib.util,sys;"
|
|
110
|
+
"spec=importlib.util.spec_from_file_location('deps', sys.argv[1]);"
|
|
111
|
+
"m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);print('ok')",
|
|
112
|
+
str(out)],
|
|
113
|
+
capture_output=True, text=True,
|
|
114
|
+
)
|
|
115
|
+
assert result.returncode == 0, result.stderr
|
|
116
|
+
assert "ok" in result.stdout
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_cli_writes_file(tmp_path, capsys):
|
|
120
|
+
root = _tree(tmp_path, {"a.py": "import requests\n"})
|
|
121
|
+
out = tmp_path / "build" / "_deps.py"
|
|
122
|
+
rc = main(["--root", str(root), "--out", str(out)])
|
|
123
|
+
assert rc == 0
|
|
124
|
+
assert out.read_text(encoding="utf-8").startswith("# Generated by pyi_deps")
|
|
125
|
+
assert "import requests" in out.read_text(encoding="utf-8")
|
|
126
|
+
assert "1 imports" in capsys.readouterr().out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_cli_accepts_local_and_exclude(tmp_path):
|
|
130
|
+
root = _tree(tmp_path, {"a.py": "import app\nimport PIL\nimport requests\n"})
|
|
131
|
+
out = tmp_path / "_deps.py"
|
|
132
|
+
assert main(["--root", str(root), "--out", str(out), "--local", "app",
|
|
133
|
+
"--exclude", "PIL"]) == 0
|
|
134
|
+
text = out.read_text(encoding="utf-8")
|
|
135
|
+
assert "import requests" in text
|
|
136
|
+
assert "import app" not in text
|
|
137
|
+
assert "import PIL" not in text
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_syntax_error_in_source_propagates(tmp_path):
|
|
141
|
+
root = _tree(tmp_path, {"bad.py": "def broken(:\n"})
|
|
142
|
+
try:
|
|
143
|
+
scan(root)
|
|
144
|
+
except SyntaxError:
|
|
145
|
+
pass
|
|
146
|
+
else:
|
|
147
|
+
raise AssertionError("scan() should surface a SyntaxError, not skip the file")
|