doppelcode 0.7.0b5.post1__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,121 @@
1
+ """Public names of the external Python modules a project imports - read from their source files,
2
+ never by importing (running) them, so a third-party package cannot execute code during an export.
3
+
4
+ harvest({"os", "json", "numpy.linalg"}, project_modules) -> (names, unresolved modules)
5
+
6
+ Only the public API is collected (module-level names, classes, methods, class attributes, attributes
7
+ set on self), not parameters or local variables (keyword arguments to library calls are protected by
8
+ the call rule in project.build_mapping): a library's local
9
+ named "text" must not stop the project's own "text" from being hidden.
10
+ Built-in modules compiled into the interpreter (sys, math, ...) have no source: dir() is used, which
11
+ runs no third-party code. Frozen stdlib modules (os, ...) are read from the stdlib folder; extension
12
+ modules (.pyd / .so) are not imported, their .pyi stub is read when present.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ast
18
+
19
+ from . import pyparse
20
+ import importlib.machinery
21
+ import importlib.util
22
+ import sys
23
+ import sysconfig
24
+ from pathlib import Path
25
+
26
+ _MAX_FILES = 400
27
+ _MAX_BYTES = 20_000_000
28
+
29
+
30
+ def _module_files(top: str) -> list[Path]:
31
+ try:
32
+ spec = importlib.util.find_spec(top) # top-level only: does not import anything
33
+ except (ImportError, ValueError, AttributeError):
34
+ spec = None
35
+ files: list[Path] = []
36
+ if spec is not None and spec.submodule_search_locations:
37
+ for loc in spec.submodule_search_locations:
38
+ for p in sorted(Path(loc).rglob("*.py*")):
39
+ if p.suffix in (".py", ".pyi") and not any("test" in part.lower() for part in p.parts[-3:-1]):
40
+ files.append(p)
41
+ if len(files) >= _MAX_FILES:
42
+ return files
43
+ return files
44
+ if spec is not None and spec.origin and spec.origin.endswith((".py", ".pyi")):
45
+ return [Path(spec.origin)]
46
+ if spec is not None and spec.origin and spec.origin.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
47
+ stub = Path(spec.origin)
48
+ stub = stub.with_name(stub.name.split(".")[0] + ".pyi")
49
+ return [stub] if stub.is_file() else []
50
+ stdlib = Path(sysconfig.get_paths()["stdlib"]) # frozen modules (os, ...) have a source here
51
+ for cand in (stdlib / f"{top}.py", stdlib / top / "__init__.py"):
52
+ if cand.is_file():
53
+ return [cand] if cand.name != "__init__.py" else sorted(cand.parent.rglob("*.py"))[:_MAX_FILES]
54
+ return []
55
+
56
+
57
+ def public_names(src: str) -> set[str]:
58
+ """API names of a module source: not the locals inside its functions."""
59
+ try:
60
+ tree = pyparse.parse(src)
61
+ except (SyntaxError, ValueError):
62
+ return set()
63
+ names: set[str] = set()
64
+
65
+ def scope(body: list, in_class: bool) -> None:
66
+ for node in body:
67
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
68
+ names.add(node.name)
69
+ for sub in ast.walk(node): # self.attr = ... inside methods
70
+ if isinstance(sub, ast.Attribute) and isinstance(sub.ctx, ast.Store):
71
+ names.add(sub.attr)
72
+ elif isinstance(node, ast.ClassDef):
73
+ names.add(node.name)
74
+ scope(node.body, True)
75
+ elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
76
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
77
+ for t in targets:
78
+ for sub in ast.walk(t):
79
+ if isinstance(sub, ast.Name):
80
+ names.add(sub.id)
81
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
82
+ for alias in node.names:
83
+ names.add((alias.asname or alias.name).split(".")[0])
84
+ elif isinstance(node, (ast.If, ast.Try, ast.With)):
85
+ scope(getattr(node, "body", []) + getattr(node, "orelse", []) + getattr(node, "finalbody", [])
86
+ + [h for hnd in getattr(node, "handlers", []) for h in hnd.body], in_class)
87
+
88
+ scope(tree.body, False)
89
+ # private library internals (_helper) cannot be what the project calls; dunders stay
90
+ return {n for n in names if not n.startswith("_") or (n.startswith("__") and n.endswith("__"))}
91
+
92
+
93
+ def harvest(modules: set[str], project_modules: set[str]) -> tuple[set[str], set[str]]:
94
+ names: set[str] = set()
95
+ unresolved: set[str] = set()
96
+ for mod in sorted(modules):
97
+ top = mod.split(".")[0]
98
+ if not top or top in project_modules:
99
+ continue
100
+ names.update(mod.split("."))
101
+ if top in sys.builtin_module_names:
102
+ try:
103
+ names.update(dir(__import__(top)))
104
+ except ImportError:
105
+ unresolved.add(top)
106
+ continue
107
+ files = _module_files(top)
108
+ if not files:
109
+ unresolved.add(top)
110
+ continue
111
+ size = 0
112
+ for path in files:
113
+ try:
114
+ data = path.read_bytes()
115
+ except OSError:
116
+ continue
117
+ size += len(data)
118
+ if size > _MAX_BYTES:
119
+ break
120
+ names.update(public_names(data.decode("utf-8", "replace")))
121
+ return names, unresolved
doppelcode/pyparse.py ADDED
@@ -0,0 +1,14 @@
1
+ """ast.parse for project and library sources. Their SyntaxWarnings (for example an invalid escape sequence
2
+ in a regex string) come from the code being read, not from DoppelCode, so they are not printed."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import ast
7
+ import warnings
8
+
9
+
10
+ def parse(src: str, **kwargs) -> ast.AST:
11
+ with warnings.catch_warnings():
12
+ warnings.simplefilter("ignore", SyntaxWarning)
13
+ warnings.simplefilter("ignore", DeprecationWarning)
14
+ return ast.parse(src, **kwargs)