AutoCython-zhang 2.3.9__tar.gz → 2.3.10__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.
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/AutoCython.py +7 -3
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/_version.py +1 -1
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/compile.py +161 -44
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/obfuscate.py +133 -47
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/run_tasks.py +22 -4
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/tools.py +99 -72
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/PKG-INFO +2 -2
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/top_level.txt +0 -1
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/PKG-INFO +2 -2
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/README.md +1 -1
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython/__init__.py +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/SOURCES.txt +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/dependency_links.txt +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/entry_points.txt +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/requires.txt +1 -1
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/LICENSE +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/MANIFEST.in +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/pyproject.toml +0 -0
- {autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/setup.cfg +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import os
|
|
2
2
|
import sys
|
|
3
3
|
from .run_tasks import run_tasks
|
|
4
|
-
from .compile import compile_to_binary
|
|
4
|
+
from .compile import check_output_collisions, compile_to_binary
|
|
5
5
|
from .tools import parse_arguments, find_python_files
|
|
6
6
|
from .tools import show_no_compilable_files, show_file_not_found, show_path_not_found
|
|
7
7
|
|
|
@@ -13,23 +13,26 @@ def compile():
|
|
|
13
13
|
if args.file:
|
|
14
14
|
if os.path.isfile(args.file):
|
|
15
15
|
compile_file = args.file
|
|
16
|
+
check_output_collisions([compile_file])
|
|
16
17
|
del_source = args.del_source
|
|
17
18
|
tasks = [
|
|
18
|
-
# 函数, 位置参数, 关键字参数
|
|
19
|
+
# 函数, 显示名称, 位置参数, 关键字参数
|
|
19
20
|
(compile_to_binary, compile_file, (compile_file, del_source, True, obfuscate_seed), {}),
|
|
20
21
|
]
|
|
21
22
|
run_tasks(tasks, max_workers=1, raise_on_failure=True) # 执行编译
|
|
22
23
|
else:
|
|
23
24
|
show_file_not_found(args.file)
|
|
25
|
+
sys.exit(1)
|
|
24
26
|
elif args.path:
|
|
25
27
|
if os.path.exists(args.path) and not os.path.isfile(args.path):
|
|
26
28
|
compile_file_list = find_python_files(args.path)
|
|
27
29
|
if compile_file_list:
|
|
30
|
+
check_output_collisions(compile_file_list)
|
|
28
31
|
del_source = args.del_source
|
|
29
32
|
tasks = []
|
|
30
33
|
for compile_file in compile_file_list:
|
|
31
34
|
tasks.append(
|
|
32
|
-
# 函数, 位置参数, 关键字参数
|
|
35
|
+
# 函数, 显示名称, 位置参数, 关键字参数
|
|
33
36
|
(compile_to_binary, compile_file, (compile_file, del_source, True, obfuscate_seed), {}),
|
|
34
37
|
)
|
|
35
38
|
run_tasks(tasks, max_workers=args.conc, raise_on_failure=True) # 执行编译
|
|
@@ -37,6 +40,7 @@ def compile():
|
|
|
37
40
|
show_no_compilable_files(args.path)
|
|
38
41
|
else:
|
|
39
42
|
show_path_not_found(args.path)
|
|
43
|
+
sys.exit(1)
|
|
40
44
|
except KeyboardInterrupt:
|
|
41
45
|
sys.exit(130)
|
|
42
46
|
except Exception as e:
|
|
@@ -9,7 +9,7 @@ import sys
|
|
|
9
9
|
import tempfile
|
|
10
10
|
import tokenize
|
|
11
11
|
|
|
12
|
-
from .obfuscate import obfuscate_source
|
|
12
|
+
from .obfuscate import _collect_identifier_names, _fresh_name, obfuscate_source
|
|
13
13
|
|
|
14
14
|
_SUPPORTED_CYTHON_MAJOR = 3
|
|
15
15
|
|
|
@@ -58,6 +58,12 @@ def _safe_relative_path(rel_path: str) -> str:
|
|
|
58
58
|
_SCOPE_TYPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
|
|
59
59
|
|
|
60
60
|
|
|
61
|
+
def _unwrap_subscript(node):
|
|
62
|
+
while isinstance(node, ast.Subscript):
|
|
63
|
+
node = node.value
|
|
64
|
+
return node
|
|
65
|
+
|
|
66
|
+
|
|
61
67
|
def _dotted_name(node):
|
|
62
68
|
parts = []
|
|
63
69
|
while isinstance(node, ast.Attribute):
|
|
@@ -91,7 +97,12 @@ def _collect_scope_bindings(nodes, scope_node):
|
|
|
91
97
|
bound.add(args.vararg.arg)
|
|
92
98
|
if args.kwarg:
|
|
93
99
|
bound.add(args.kwarg.arg)
|
|
94
|
-
|
|
100
|
+
match_capture_types = tuple(
|
|
101
|
+
node_type for node_type in (
|
|
102
|
+
getattr(ast, "MatchAs", None),
|
|
103
|
+
getattr(ast, "MatchStar", None),
|
|
104
|
+
) if node_type is not None
|
|
105
|
+
)
|
|
95
106
|
match_mapping = getattr(ast, "MatchMapping", None)
|
|
96
107
|
for node in nodes:
|
|
97
108
|
if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
|
|
@@ -104,7 +115,7 @@ def _collect_scope_bindings(nodes, scope_node):
|
|
|
104
115
|
for alias in node.names:
|
|
105
116
|
if alias.name != "*":
|
|
106
117
|
bound.add(alias.asname or alias.name.split(".", 1)[0])
|
|
107
|
-
elif
|
|
118
|
+
elif match_capture_types and isinstance(node, match_capture_types) and node.name:
|
|
108
119
|
bound.add(node.name)
|
|
109
120
|
elif match_mapping is not None and isinstance(node, match_mapping) and node.rest:
|
|
110
121
|
bound.add(node.rest)
|
|
@@ -191,7 +202,7 @@ def _find_pydantic_model_classes(tree):
|
|
|
191
202
|
if isinstance(node, ast.ClassDef):
|
|
192
203
|
is_model = False
|
|
193
204
|
for base in node.bases:
|
|
194
|
-
dotted = _dotted_name(base)
|
|
205
|
+
dotted = _dotted_name(_unwrap_subscript(base))
|
|
195
206
|
if dotted in base_names or dotted in known_models:
|
|
196
207
|
is_model = True
|
|
197
208
|
break
|
|
@@ -227,6 +238,90 @@ def _find_pydantic_model_classes(tree):
|
|
|
227
238
|
return model_classes
|
|
228
239
|
|
|
229
240
|
|
|
241
|
+
def _base_class_exprs(node, shadowed_names):
|
|
242
|
+
"""提取类定义中无副作用且未被类体遮蔽的基类表达式源码。"""
|
|
243
|
+
exprs = []
|
|
244
|
+
for base in node.bases:
|
|
245
|
+
dotted = _dotted_name(_unwrap_subscript(base))
|
|
246
|
+
if dotted and dotted.split(".", 1)[0] not in shadowed_names:
|
|
247
|
+
exprs.append(dotted)
|
|
248
|
+
return exprs
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _build_pydantic_shim_source(node, forbidden_names):
|
|
252
|
+
"""为单个 Pydantic BaseModel 子类生成保留继承与既有配置的兼容代码。"""
|
|
253
|
+
legacy_config = next(
|
|
254
|
+
(
|
|
255
|
+
item for item in node.body
|
|
256
|
+
if isinstance(item, ast.ClassDef) and item.name == "Config"
|
|
257
|
+
),
|
|
258
|
+
None,
|
|
259
|
+
)
|
|
260
|
+
cls_var = _fresh_name("_ac_c", forbidden_names)
|
|
261
|
+
scope_nodes = list(_walk_scope_nodes(node.body))
|
|
262
|
+
bound_names = _collect_scope_bindings(scope_nodes, node)
|
|
263
|
+
base_var = _fresh_name("_ac_b", forbidden_names)
|
|
264
|
+
type_var = _fresh_name("_ac_t", forbidden_names)
|
|
265
|
+
base_exprs = _base_class_exprs(node, bound_names)
|
|
266
|
+
if base_exprs:
|
|
267
|
+
bases_tuple = "(" + ", ".join(base_exprs) + ",)"
|
|
268
|
+
inherited_ignored = (
|
|
269
|
+
f'*({type_var} for {base_var} in {bases_tuple} '
|
|
270
|
+
f'for {cls_var} in {base_var}.__mro__ '
|
|
271
|
+
f'if "model_config" in {cls_var}.__dict__ '
|
|
272
|
+
f'and {cls_var}.__dict__["model_config"].__class__ is {{}}.__class__ '
|
|
273
|
+
f'for {type_var} in {cls_var}.__dict__["model_config"].get("ignored_types", ())), '
|
|
274
|
+
f'*({type_var} for {base_var} in {bases_tuple} '
|
|
275
|
+
f'for {cls_var} in {base_var}.__mro__ '
|
|
276
|
+
f'if "Config" in {cls_var}.__dict__ '
|
|
277
|
+
f'and "".__class__.__class__ in {cls_var}.__dict__["Config"].__class__.__mro__ '
|
|
278
|
+
f'and "ignored_types" in {cls_var}.__dict__["Config"].__dict__ '
|
|
279
|
+
f'for {type_var} in {cls_var}.__dict__["Config"].__dict__["ignored_types"]), '
|
|
280
|
+
)
|
|
281
|
+
else:
|
|
282
|
+
inherited_ignored = ""
|
|
283
|
+
|
|
284
|
+
if legacy_config is not None:
|
|
285
|
+
return (
|
|
286
|
+
f'Config.ignored_types = ({inherited_ignored}'
|
|
287
|
+
f'*([{cls_var}.__dict__["ignored_types"] for {cls_var} in Config.__mro__ '
|
|
288
|
+
f'if "ignored_types" in {cls_var}.__dict__] or [()])[0], '
|
|
289
|
+
f'(lambda: None).__class__)'
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
has_star_import = any(
|
|
293
|
+
isinstance(item, ast.ImportFrom) and any(alias.name == "*" for alias in item.names)
|
|
294
|
+
for item in scope_nodes
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
has_model_config = "model_config" in bound_names or has_star_import
|
|
298
|
+
locals_shadowed = "locals" in bound_names or has_star_import
|
|
299
|
+
|
|
300
|
+
if not has_model_config:
|
|
301
|
+
return (
|
|
302
|
+
f'model_config = {{"ignored_types": ({inherited_ignored}'
|
|
303
|
+
f'(lambda: None).__class__)}}'
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
if not locals_shadowed:
|
|
307
|
+
own_expr = '(model_config if "model_config" in locals() else {})'
|
|
308
|
+
return (
|
|
309
|
+
f'model_config = {{**{own_expr}, '
|
|
310
|
+
f'"ignored_types": ({inherited_ignored}*{own_expr}.get("ignored_types", ()), '
|
|
311
|
+
f'(lambda: None).__class__)}}'
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
return (
|
|
315
|
+
'try:\n'
|
|
316
|
+
' model_config = {**model_config, '
|
|
317
|
+
f'"ignored_types": ({inherited_ignored}*model_config.get("ignored_types", ()), '
|
|
318
|
+
'(lambda: None).__class__)}\n'
|
|
319
|
+
'except NameError:\n'
|
|
320
|
+
f' model_config = {{"ignored_types": ({inherited_ignored}'
|
|
321
|
+
'(lambda: None).__class__)}'
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
|
|
230
325
|
def _add_pydantic_ignored_types(source_code: str) -> str:
|
|
231
326
|
"""Make Pydantic v2 models tolerate Cython's bound method type.
|
|
232
327
|
|
|
@@ -254,31 +349,19 @@ def _add_pydantic_ignored_types(source_code: str) -> str:
|
|
|
254
349
|
# plain source even though only one model needs the compatibility shim.
|
|
255
350
|
lines = source_code.splitlines(keepends=True)
|
|
256
351
|
newline = "\r\n" if "\r\n" in source_code else "\n"
|
|
352
|
+
forbidden_names = _collect_identifier_names(tree)
|
|
257
353
|
insertions = []
|
|
258
354
|
for node in class_nodes:
|
|
259
355
|
if not node.body or node.lineno == node.end_lineno:
|
|
260
356
|
continue
|
|
261
|
-
|
|
262
|
-
(
|
|
263
|
-
item for item in node.body
|
|
264
|
-
if isinstance(item, ast.ClassDef) and item.name == "Config"
|
|
265
|
-
),
|
|
266
|
-
None,
|
|
267
|
-
)
|
|
268
|
-
if legacy_config is not None:
|
|
269
|
-
config_source = (
|
|
270
|
-
'Config.ignored_types = (*Config.__dict__.get("ignored_types", ()), '
|
|
271
|
-
'(lambda: None).__class__)'
|
|
272
|
-
)
|
|
273
|
-
else:
|
|
274
|
-
config_source = (
|
|
275
|
-
'model_config = {**(model_config if "model_config" in locals() else {}), '
|
|
276
|
-
'"ignored_types": (*(model_config if "model_config" in locals() else {})'
|
|
277
|
-
'.get("ignored_types", ()), (lambda: None).__class__)}'
|
|
278
|
-
)
|
|
357
|
+
config_source = _build_pydantic_shim_source(node, forbidden_names)
|
|
279
358
|
class_line = lines[node.lineno - 1]
|
|
280
359
|
class_indent = class_line[: len(class_line) - len(class_line.lstrip())]
|
|
281
|
-
|
|
360
|
+
body_stmt = next(
|
|
361
|
+
(item for item in node.body if item.lineno > node.lineno),
|
|
362
|
+
node.body[0],
|
|
363
|
+
)
|
|
364
|
+
body_line = lines[body_stmt.lineno - 1]
|
|
282
365
|
body_indent = body_line[: len(body_line) - len(body_line.lstrip())]
|
|
283
366
|
if not body_indent or len(body_indent) <= len(class_indent):
|
|
284
367
|
body_indent = class_indent + " "
|
|
@@ -289,12 +372,17 @@ def _add_pydantic_ignored_types(source_code: str) -> str:
|
|
|
289
372
|
) + newline
|
|
290
373
|
insertions.append((insert_at, len(body_indent), indented_config))
|
|
291
374
|
|
|
375
|
+
if not insertions:
|
|
376
|
+
return source_code
|
|
377
|
+
|
|
378
|
+
if lines and not lines[-1].endswith(("\n", "\r")):
|
|
379
|
+
lines[-1] = lines[-1] + newline
|
|
380
|
+
|
|
292
381
|
for line_number, _, text in sorted(
|
|
293
382
|
insertions,
|
|
294
383
|
key=lambda item: (item[0], -item[1]),
|
|
295
384
|
reverse=True,
|
|
296
385
|
):
|
|
297
|
-
offset = line_number
|
|
298
386
|
offset = min(line_number, len(lines))
|
|
299
387
|
lines.insert(offset, text)
|
|
300
388
|
return "".join(lines)
|
|
@@ -415,9 +503,12 @@ def _validate_cython_syntax(source_code: str, file_path: str) -> None:
|
|
|
415
503
|
if not unsupported:
|
|
416
504
|
return
|
|
417
505
|
feature, node = unsupported[0]
|
|
506
|
+
lineno = getattr(node, 'lineno', '?')
|
|
507
|
+
col_offset = getattr(node, 'col_offset', None)
|
|
508
|
+
column = col_offset + 1 if isinstance(col_offset, int) else '?'
|
|
418
509
|
raise UnsupportedSyntaxError(
|
|
419
510
|
f'Cython 3.x does not support {feature} in {file_path} '
|
|
420
|
-
f'(line {
|
|
511
|
+
f'(line {lineno}, column {column}).'
|
|
421
512
|
)
|
|
422
513
|
|
|
423
514
|
|
|
@@ -541,7 +632,7 @@ def _copy_package_inits(
|
|
|
541
632
|
rel_init_path = _safe_relative_path(rel_init_path)
|
|
542
633
|
temp_init_path = os.path.join(temp_dir, rel_init_path)
|
|
543
634
|
os.makedirs(os.path.dirname(temp_init_path), exist_ok=True)
|
|
544
|
-
shutil.
|
|
635
|
+
shutil.copyfile(init_path, temp_init_path)
|
|
545
636
|
|
|
546
637
|
if current_dir == compile_root:
|
|
547
638
|
break
|
|
@@ -552,6 +643,31 @@ def _copy_package_inits(
|
|
|
552
643
|
current_dir = parent_dir
|
|
553
644
|
|
|
554
645
|
|
|
646
|
+
def check_output_collisions(file_paths) -> None:
|
|
647
|
+
"""检测同一目录下规范化模块名冲突(含遮蔽同目录既有同名 .py 文件),避免覆盖或误删。"""
|
|
648
|
+
seen = {}
|
|
649
|
+
for file_path in file_paths:
|
|
650
|
+
abs_path = os.path.abspath(file_path)
|
|
651
|
+
source_dir = os.path.dirname(abs_path)
|
|
652
|
+
stem, _ = os.path.splitext(os.path.basename(abs_path))
|
|
653
|
+
safe_stem = _safe_module_component(stem)
|
|
654
|
+
key = (source_dir, safe_stem)
|
|
655
|
+
previous = seen.get(key)
|
|
656
|
+
if previous is not None and previous != abs_path:
|
|
657
|
+
raise ValueError(
|
|
658
|
+
f"Output module name collision ({safe_stem!r}) between "
|
|
659
|
+
f"{previous} and {abs_path}"
|
|
660
|
+
)
|
|
661
|
+
if safe_stem != stem:
|
|
662
|
+
existing_peer = os.path.abspath(os.path.join(source_dir, f"{safe_stem}.py"))
|
|
663
|
+
if existing_peer != abs_path and os.path.isfile(existing_peer):
|
|
664
|
+
raise ValueError(
|
|
665
|
+
f"Output module name collision ({safe_stem!r}) between "
|
|
666
|
+
f"{abs_path} and existing {existing_peer}"
|
|
667
|
+
)
|
|
668
|
+
seen[key] = abs_path
|
|
669
|
+
|
|
670
|
+
|
|
555
671
|
def compile_to_binary(file_path: str, del_source=False, obfuscate=True, obfuscate_seed=None):
|
|
556
672
|
"""
|
|
557
673
|
将指定的 Python 文件(.py)通过 Cython 编译为二进制扩展文件
|
|
@@ -583,41 +699,42 @@ def compile_to_binary(file_path: str, del_source=False, obfuscate=True, obfuscat
|
|
|
583
699
|
temp_dir = tempfile.mkdtemp()
|
|
584
700
|
|
|
585
701
|
try:
|
|
586
|
-
# Keep the source tree
|
|
587
|
-
#
|
|
588
|
-
#
|
|
589
|
-
|
|
702
|
+
# Keep the source tree inside a non-package subdirectory of build_root:
|
|
703
|
+
# 1) ``collections.py`` (or another stdlib name) is not in build_root
|
|
704
|
+
# itself, so it cannot shadow stdlib modules on sys.path[0];
|
|
705
|
+
# 2) Extension receives a clean relative subpath free of ``..`` and free
|
|
706
|
+
# of any glob metacharacters (such as ``[py311]``) in TMPDIR.
|
|
590
707
|
build_root = os.path.join(temp_dir, 'build')
|
|
708
|
+
source_root = os.path.join(build_root, '_src')
|
|
591
709
|
temp_file_path = os.path.join(source_root, module_layout['safe_rel_path'])
|
|
710
|
+
rel_temp_file_path = os.path.relpath(temp_file_path, build_root).replace(os.sep, '/')
|
|
592
711
|
os.makedirs(os.path.dirname(temp_file_path), exist_ok=True)
|
|
593
|
-
os.makedirs(build_root, exist_ok=True)
|
|
594
712
|
_copy_package_inits(
|
|
595
713
|
abs_file_path,
|
|
596
714
|
module_layout['compile_root'],
|
|
597
715
|
source_root,
|
|
598
716
|
sanitize=True,
|
|
599
717
|
)
|
|
600
|
-
shutil.copy2(abs_file_path, temp_file_path)
|
|
601
718
|
# ``tokenize.open`` honors a PEP 263 coding cookie (and UTF-8 BOM)
|
|
602
|
-
# instead of assuming that every input file is UTF-8.
|
|
603
|
-
|
|
719
|
+
# instead of assuming that every input file is UTF-8. Read directly
|
|
720
|
+
# from ``abs_file_path`` so read-only (0444) sources do not propagate
|
|
721
|
+
# non-writable mode bits onto ``temp_file_path``.
|
|
722
|
+
with tokenize.open(abs_file_path) as source_file:
|
|
604
723
|
original_source = source_file.read()
|
|
605
724
|
source_encoding = source_file.encoding
|
|
606
725
|
|
|
607
726
|
_validate_cython_syntax(original_source, file_path)
|
|
608
727
|
|
|
609
|
-
def write_source(source):
|
|
610
|
-
_write_source(temp_file_path, source, source_encoding)
|
|
611
|
-
|
|
612
728
|
if obfuscate:
|
|
613
729
|
try:
|
|
614
730
|
compatible_source = _add_pydantic_ignored_types(original_source)
|
|
615
|
-
|
|
616
|
-
write_source(obfuscated)
|
|
731
|
+
transformed_source = obfuscate_source(compatible_source, seed=obfuscate_seed)
|
|
617
732
|
except Exception as exc:
|
|
618
733
|
raise RuntimeError(f"Obfuscation failed for {file_path}: {exc}") from exc
|
|
619
734
|
else:
|
|
620
|
-
|
|
735
|
+
transformed_source = _add_pydantic_ignored_types(original_source)
|
|
736
|
+
|
|
737
|
+
_write_source(temp_file_path, transformed_source, source_encoding)
|
|
621
738
|
|
|
622
739
|
setup_code = f"""
|
|
623
740
|
from setuptools import setup
|
|
@@ -630,7 +747,6 @@ compiler_directives = {{
|
|
|
630
747
|
'always_allow_keywords': True,
|
|
631
748
|
'binding': True,
|
|
632
749
|
'embedsignature': False,
|
|
633
|
-
'wraparound': False,
|
|
634
750
|
}}
|
|
635
751
|
|
|
636
752
|
setup(
|
|
@@ -638,7 +754,7 @@ setup(
|
|
|
638
754
|
[
|
|
639
755
|
Extension(
|
|
640
756
|
{repr(module_layout['qualified_module_name'])},
|
|
641
|
-
[{repr(
|
|
757
|
+
[{repr(rel_temp_file_path)}],
|
|
642
758
|
)
|
|
643
759
|
],
|
|
644
760
|
compiler_directives=compiler_directives,
|
|
@@ -666,9 +782,10 @@ setup(
|
|
|
666
782
|
error_msg = result.stderr.decode('utf-8', errors='replace')
|
|
667
783
|
raise RuntimeError(f"Compilation failed: {error_msg}")
|
|
668
784
|
|
|
785
|
+
escaped_build_dir = glob.escape(os.path.join(build_root, 'build'))
|
|
669
786
|
patterns = [
|
|
670
|
-
os.path.join(
|
|
671
|
-
os.path.join(
|
|
787
|
+
os.path.join(escaped_build_dir, '**', f"{safe_module_name}*{target_ext}"),
|
|
788
|
+
os.path.join(escaped_build_dir, '**', f"*{safe_module_name}*{target_ext}"),
|
|
672
789
|
]
|
|
673
790
|
matches = []
|
|
674
791
|
for pattern in patterns:
|
|
@@ -5,8 +5,10 @@
|
|
|
5
5
|
"""
|
|
6
6
|
import ast
|
|
7
7
|
import hashlib
|
|
8
|
+
import io
|
|
8
9
|
import random
|
|
9
10
|
import re
|
|
11
|
+
import tokenize
|
|
10
12
|
|
|
11
13
|
_UNSAFE_CALLS = frozenset({'globals', 'locals', 'eval', 'exec', 'vars'})
|
|
12
14
|
_REFLECTION_CALLS = frozenset({
|
|
@@ -27,17 +29,30 @@ _MATCH_BINDER_TYPES = tuple(
|
|
|
27
29
|
) if node_type is not None
|
|
28
30
|
)
|
|
29
31
|
_MATCH_MAPPING_TYPE = getattr(ast, 'MatchMapping', None)
|
|
32
|
+
_TYPE_PARAM_TYPES = tuple(
|
|
33
|
+
node_type for node_type in (
|
|
34
|
+
getattr(ast, 'TypeVar', None),
|
|
35
|
+
getattr(ast, 'ParamSpec', None),
|
|
36
|
+
getattr(ast, 'TypeVarTuple', None),
|
|
37
|
+
) if node_type is not None
|
|
38
|
+
)
|
|
39
|
+
_TYPE_ALIAS_TYPE = getattr(ast, 'TypeAlias', None)
|
|
40
|
+
_CODING_COOKIE_RE = re.compile(r'^#.*coding[:=]\s*[-\w.]+', re.IGNORECASE)
|
|
41
|
+
_CYTHON_DIRECTIVE_RE = re.compile(r'^#\s*(?:cython|distutils)\s*:')
|
|
30
42
|
_PATTERN_SKIP_ATTR = '_autocython_skip_literal_obf'
|
|
31
|
-
|
|
43
|
+
_HARD_SCOPE_NODES = (
|
|
32
44
|
ast.FunctionDef,
|
|
33
45
|
ast.AsyncFunctionDef,
|
|
34
46
|
ast.ClassDef,
|
|
35
47
|
ast.Lambda,
|
|
48
|
+
) + ((_TYPE_ALIAS_TYPE,) if _TYPE_ALIAS_TYPE is not None else ())
|
|
49
|
+
_COMP_SCOPE_NODES = (
|
|
36
50
|
ast.ListComp,
|
|
37
51
|
ast.SetComp,
|
|
38
52
|
ast.DictComp,
|
|
39
53
|
ast.GeneratorExp,
|
|
40
54
|
)
|
|
55
|
+
_SCOPE_BOUNDARY_NODES = _HARD_SCOPE_NODES + _COMP_SCOPE_NODES
|
|
41
56
|
|
|
42
57
|
|
|
43
58
|
class _EscapedStringLiteral(str):
|
|
@@ -170,9 +185,7 @@ def _is_docstring_stmt(stmt):
|
|
|
170
185
|
if not isinstance(stmt, ast.Expr):
|
|
171
186
|
return False
|
|
172
187
|
value = stmt.value
|
|
173
|
-
|
|
174
|
-
return isinstance(value.value, str)
|
|
175
|
-
return isinstance(value, ast.Str)
|
|
188
|
+
return isinstance(value, ast.Constant) and isinstance(value.value, str)
|
|
176
189
|
|
|
177
190
|
|
|
178
191
|
def _mark_pattern_constants(pattern):
|
|
@@ -205,8 +218,17 @@ def _mark_annotation_constants(tree):
|
|
|
205
218
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
206
219
|
mark_arg_annotations(node.args)
|
|
207
220
|
mark(node.returns)
|
|
221
|
+
for type_param in getattr(node, 'type_params', ()):
|
|
222
|
+
mark(type_param)
|
|
223
|
+
elif isinstance(node, ast.ClassDef):
|
|
224
|
+
for type_param in getattr(node, 'type_params', ()):
|
|
225
|
+
mark(type_param)
|
|
208
226
|
elif isinstance(node, ast.AnnAssign):
|
|
209
227
|
mark(node.annotation)
|
|
228
|
+
elif _TYPE_ALIAS_TYPE is not None and isinstance(node, _TYPE_ALIAS_TYPE):
|
|
229
|
+
mark(node.value)
|
|
230
|
+
for type_param in getattr(node, 'type_params', ()):
|
|
231
|
+
mark(type_param)
|
|
210
232
|
return tree
|
|
211
233
|
|
|
212
234
|
|
|
@@ -291,7 +313,7 @@ def _collect_nonlocal_global_names(body):
|
|
|
291
313
|
|
|
292
314
|
def _collect_direct_bound_names(body):
|
|
293
315
|
"""收集当前作用域直接绑定的名称,不穿透嵌套作用域。"""
|
|
294
|
-
bound = _collect_names(body, ast.Store)
|
|
316
|
+
bound = _collect_names(body, (ast.Store, ast.Del))
|
|
295
317
|
bound.update(_collect_string_bound_names(body))
|
|
296
318
|
return bound
|
|
297
319
|
|
|
@@ -341,6 +363,8 @@ def _collect_identifier_names(node):
|
|
|
341
363
|
names.add(child.name)
|
|
342
364
|
elif _MATCH_MAPPING_TYPE is not None and isinstance(child, _MATCH_MAPPING_TYPE) and child.rest:
|
|
343
365
|
names.add(child.rest)
|
|
366
|
+
elif _TYPE_PARAM_TYPES and isinstance(child, _TYPE_PARAM_TYPES):
|
|
367
|
+
names.add(child.name)
|
|
344
368
|
return names
|
|
345
369
|
|
|
346
370
|
|
|
@@ -361,20 +385,32 @@ def _collect_load_names_no_nested(nodes):
|
|
|
361
385
|
|
|
362
386
|
|
|
363
387
|
def _collect_nested_scope_nodes(body):
|
|
364
|
-
"""收集 body
|
|
388
|
+
"""收集 body 中的直接/间接嵌套函数、lambda 与类作用域节点(穿透推导式)。"""
|
|
365
389
|
nested = []
|
|
366
390
|
for node in body:
|
|
367
|
-
if isinstance(node,
|
|
391
|
+
if isinstance(node, _HARD_SCOPE_NODES):
|
|
368
392
|
nested.append(node)
|
|
369
393
|
continue
|
|
370
394
|
for child in ast.iter_child_nodes(node):
|
|
371
|
-
if isinstance(child,
|
|
395
|
+
if isinstance(child, _HARD_SCOPE_NODES):
|
|
372
396
|
nested.append(child)
|
|
373
397
|
else:
|
|
374
398
|
nested.extend(_collect_nested_scope_nodes([child]))
|
|
375
399
|
return nested
|
|
376
400
|
|
|
377
401
|
|
|
402
|
+
def _collect_outer_expr_refs(expr_nodes, local_names):
|
|
403
|
+
"""收集在外层作用域求值的头部表达式对 local_names 的读写与嵌套闭包引用。"""
|
|
404
|
+
if not expr_nodes:
|
|
405
|
+
return set()
|
|
406
|
+
refs = set()
|
|
407
|
+
for root in expr_nodes:
|
|
408
|
+
for child in ast.walk(root):
|
|
409
|
+
if isinstance(child, ast.Name) and child.id in local_names:
|
|
410
|
+
refs.add(child.id)
|
|
411
|
+
return refs
|
|
412
|
+
|
|
413
|
+
|
|
378
414
|
def _collect_function_like_free_refs(node, local_names):
|
|
379
415
|
"""收集嵌套函数/lambda 中引用的外层变量名。"""
|
|
380
416
|
body = node.body if isinstance(node.body, list) else [node.body]
|
|
@@ -390,7 +426,8 @@ def _collect_function_like_free_refs(node, local_names):
|
|
|
390
426
|
outer_expr_nodes.extend(node.decorator_list)
|
|
391
427
|
if node.returns is not None:
|
|
392
428
|
outer_expr_nodes.append(node.returns)
|
|
393
|
-
|
|
429
|
+
outer_expr_nodes.extend(getattr(node, 'type_params', ()))
|
|
430
|
+
free.update(_collect_outer_expr_refs(outer_expr_nodes, local_names))
|
|
394
431
|
|
|
395
432
|
for name in _collect_load_names_no_nested(body):
|
|
396
433
|
if name in local_names and name not in nested_locals and name not in global_names:
|
|
@@ -406,46 +443,76 @@ def _collect_function_like_free_refs(node, local_names):
|
|
|
406
443
|
|
|
407
444
|
|
|
408
445
|
def _collect_class_free_refs(node, local_names):
|
|
409
|
-
"""
|
|
446
|
+
"""收集嵌套类体中直接引用的外层变量名(含 nonlocal 声明)。"""
|
|
410
447
|
free = set()
|
|
411
448
|
outer_expr_nodes = list(node.decorator_list)
|
|
412
449
|
outer_expr_nodes.extend(node.bases)
|
|
413
450
|
outer_expr_nodes.extend(keyword.value for keyword in node.keywords)
|
|
414
|
-
|
|
451
|
+
outer_expr_nodes.extend(getattr(node, 'type_params', ()))
|
|
452
|
+
free.update(_collect_outer_expr_refs(outer_expr_nodes, local_names))
|
|
415
453
|
|
|
454
|
+
nonlocal_names, global_names = _collect_nonlocal_global_names(node.body)
|
|
416
455
|
for name in _collect_load_names_no_nested(node.body):
|
|
417
|
-
if name in local_names:
|
|
456
|
+
if name in local_names and name not in global_names:
|
|
418
457
|
free.add(name)
|
|
458
|
+
free.update(nonlocal_names & local_names)
|
|
419
459
|
free.update(_collect_nested_free_refs(node.body, local_names))
|
|
420
460
|
return free
|
|
421
461
|
|
|
422
462
|
|
|
423
|
-
def _collect_comprehension_free_refs(node, local_names):
|
|
424
|
-
"""保守收集 comprehension 中对外层变量的引用。
|
|
425
|
-
|
|
426
|
-
comprehension 是隐式函数作用域;为避免 Cython/CPython 闭包细节差异,
|
|
427
|
-
只要其中出现外层局部名,就将该外层名排除出重命名集合。
|
|
428
|
-
"""
|
|
429
|
-
free = set()
|
|
430
|
-
for child in ast.walk(node):
|
|
431
|
-
if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Load) and child.id in local_names:
|
|
432
|
-
free.add(child.id)
|
|
433
|
-
return free
|
|
434
|
-
|
|
435
|
-
|
|
436
463
|
def _collect_nested_free_refs(body, local_names):
|
|
437
|
-
"""
|
|
464
|
+
"""收集嵌套函数/lambda/类/type 别名作用域中引用的外层变量名(闭包变量)"""
|
|
438
465
|
free = set()
|
|
439
466
|
for node in _collect_nested_scope_nodes(body):
|
|
440
467
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
|
|
441
468
|
free.update(_collect_function_like_free_refs(node, local_names))
|
|
442
469
|
elif isinstance(node, ast.ClassDef):
|
|
443
470
|
free.update(_collect_class_free_refs(node, local_names))
|
|
444
|
-
elif isinstance(node,
|
|
445
|
-
|
|
471
|
+
elif _TYPE_ALIAS_TYPE is not None and isinstance(node, _TYPE_ALIAS_TYPE):
|
|
472
|
+
alias_exprs = [node.value, *getattr(node, 'type_params', ())]
|
|
473
|
+
free.update(_collect_outer_expr_refs(alias_exprs, local_names))
|
|
446
474
|
return free
|
|
447
475
|
|
|
448
476
|
|
|
477
|
+
def _collect_comp_target_names(comp_node):
|
|
478
|
+
"""收集推导式自身迭代变量名(隐式作用域局部绑定)。"""
|
|
479
|
+
targets = set()
|
|
480
|
+
for gen in comp_node.generators:
|
|
481
|
+
for child in ast.walk(gen.target):
|
|
482
|
+
if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store):
|
|
483
|
+
targets.add(child.id)
|
|
484
|
+
return targets
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _apply_rename_in_function_scope(nodes, active_map):
|
|
488
|
+
"""在当前函数作用域内应用局部变量重命名,安全穿透推导式并尊重其迭代目标遮蔽。"""
|
|
489
|
+
if not active_map:
|
|
490
|
+
return
|
|
491
|
+
for node in nodes:
|
|
492
|
+
if isinstance(node, _HARD_SCOPE_NODES):
|
|
493
|
+
continue
|
|
494
|
+
if isinstance(node, _COMP_SCOPE_NODES):
|
|
495
|
+
if node.generators:
|
|
496
|
+
_apply_rename_in_function_scope([node.generators[0].iter], active_map)
|
|
497
|
+
comp_targets = _collect_comp_target_names(node)
|
|
498
|
+
inner_map = {k: v for k, v in active_map.items() if k not in comp_targets}
|
|
499
|
+
if inner_map:
|
|
500
|
+
if isinstance(node, ast.DictComp):
|
|
501
|
+
_apply_rename_in_function_scope([node.key, node.value], inner_map)
|
|
502
|
+
else:
|
|
503
|
+
_apply_rename_in_function_scope([node.elt], inner_map)
|
|
504
|
+
for idx, gen in enumerate(node.generators):
|
|
505
|
+
_apply_rename_in_function_scope([gen.target], inner_map)
|
|
506
|
+
if idx > 0:
|
|
507
|
+
_apply_rename_in_function_scope([gen.iter], inner_map)
|
|
508
|
+
_apply_rename_in_function_scope(gen.ifs, inner_map)
|
|
509
|
+
continue
|
|
510
|
+
if isinstance(node, ast.Name) and node.id in active_map:
|
|
511
|
+
node.id = active_map[node.id]
|
|
512
|
+
for child in ast.iter_child_nodes(node):
|
|
513
|
+
_apply_rename_in_function_scope([child], active_map)
|
|
514
|
+
|
|
515
|
+
|
|
449
516
|
def _hash_name(name, salt):
|
|
450
517
|
"""基于原名+salt生成短 hash 标识符,避免明显的序号模式"""
|
|
451
518
|
h = hashlib.md5(f'{salt}:{name}'.encode()).hexdigest()[:8]
|
|
@@ -502,10 +569,8 @@ class _LocalVarRenamer(ast.NodeTransformer):
|
|
|
502
569
|
for name in sorted(local_names):
|
|
503
570
|
rename_map[name] = _fresh_name(_hash_name(name, salt), forbidden)
|
|
504
571
|
|
|
505
|
-
#
|
|
506
|
-
|
|
507
|
-
if isinstance(child, ast.Name) and child.id in rename_map:
|
|
508
|
-
child.id = rename_map[child.id]
|
|
572
|
+
# 应用重命名(不穿透嵌套函数/lambda/类作用域,但精确穿透推导式并处理迭代目标遮蔽与 := 绑定)
|
|
573
|
+
_apply_rename_in_function_scope(node.body, rename_map)
|
|
509
574
|
|
|
510
575
|
# 递归处理嵌套函数/类(它们有自己的作用域)
|
|
511
576
|
self.generic_visit(node)
|
|
@@ -791,6 +856,37 @@ class _OpaquePredicateInserter(ast.NodeTransformer):
|
|
|
791
856
|
return result
|
|
792
857
|
|
|
793
858
|
|
|
859
|
+
def _extract_header_directives(source_code: str):
|
|
860
|
+
"""仅从文件首部实质代码前的真实注释 token 中提取解释器/Cython/distutils 指令。"""
|
|
861
|
+
directives = []
|
|
862
|
+
source_lines = source_code.splitlines()
|
|
863
|
+
seen_lines = set()
|
|
864
|
+
try:
|
|
865
|
+
tokens = tokenize.generate_tokens(io.StringIO(source_code).readline)
|
|
866
|
+
for tok in tokens:
|
|
867
|
+
if tok.type in (tokenize.ENCODING, tokenize.NL):
|
|
868
|
+
continue
|
|
869
|
+
if tok.type == tokenize.COMMENT:
|
|
870
|
+
line_no = tok.start[0]
|
|
871
|
+
if line_no in seen_lines or line_no > len(source_lines):
|
|
872
|
+
continue
|
|
873
|
+
comment = tok.string
|
|
874
|
+
raw_line = source_lines[line_no - 1]
|
|
875
|
+
if (line_no == 1 and comment.startswith('#!')) or (
|
|
876
|
+
line_no <= 2 and _CODING_COOKIE_RE.match(comment)
|
|
877
|
+
):
|
|
878
|
+
directives.append(raw_line)
|
|
879
|
+
seen_lines.add(line_no)
|
|
880
|
+
elif _CYTHON_DIRECTIVE_RE.match(comment):
|
|
881
|
+
directives.append(raw_line)
|
|
882
|
+
seen_lines.add(line_no)
|
|
883
|
+
continue
|
|
884
|
+
break
|
|
885
|
+
except tokenize.TokenError:
|
|
886
|
+
pass
|
|
887
|
+
return directives
|
|
888
|
+
|
|
889
|
+
|
|
794
890
|
def obfuscate_source(source_code: str, seed=None) -> str:
|
|
795
891
|
"""对源码执行六重 AST 变换:去 docstring、局部变量重命名、
|
|
796
892
|
字符串改写、常量折叠、控制流平坦化、虚假分支。
|
|
@@ -827,21 +923,11 @@ def obfuscate_source(source_code: str, seed=None) -> str:
|
|
|
827
923
|
ast.fix_missing_locations(tree)
|
|
828
924
|
result = ast.unparse(tree)
|
|
829
925
|
|
|
830
|
-
# AST has no comment nodes. Preserve source-level directives that
|
|
831
|
-
# Cython/Python interpretation, plus the encoding declaration needed
|
|
832
|
-
# decode the generated file. Ordinary comments
|
|
833
|
-
#
|
|
834
|
-
directive_lines =
|
|
835
|
-
source_lines = source_code.splitlines()
|
|
836
|
-
for index, line in enumerate(source_lines):
|
|
837
|
-
stripped = line.lstrip()
|
|
838
|
-
if index < 2 and (
|
|
839
|
-
stripped.startswith('#!')
|
|
840
|
-
or re.match(r'^#.*coding[:=]\s*[-\w.]+', stripped)
|
|
841
|
-
):
|
|
842
|
-
directive_lines.append(line)
|
|
843
|
-
elif re.match(r'^\s*#\s*(?:cython|distutils)\s*:', line):
|
|
844
|
-
directive_lines.append(line)
|
|
926
|
+
# AST has no comment nodes. Preserve source-level header directives that
|
|
927
|
+
# alter Cython/Python interpretation, plus the encoding declaration needed
|
|
928
|
+
# to decode the generated file. Ordinary comments, string contents, and
|
|
929
|
+
# function-local comments remain omitted from the module header.
|
|
930
|
+
directive_lines = _extract_header_directives(source_code)
|
|
845
931
|
if directive_lines:
|
|
846
932
|
result = '\n'.join(directive_lines) + '\n' + result
|
|
847
933
|
return result
|
|
@@ -14,15 +14,33 @@ from rich.progress import Progress, BarColumn, TimeRemainingColumn, TimeElapsedC
|
|
|
14
14
|
from .tools import get_system_language
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
def _normalize_task_entry(entry):
|
|
18
|
+
"""兼容四元组 (func, name, args, kwargs) 与三元组 (func, args, kwargs)。"""
|
|
19
|
+
if len(entry) == 4:
|
|
20
|
+
func, name, args, kwargs = entry
|
|
21
|
+
return func, name, args, kwargs
|
|
22
|
+
if len(entry) == 3:
|
|
23
|
+
func, args, kwargs = entry
|
|
24
|
+
name = getattr(func, "__name__", str(func))
|
|
25
|
+
return func, name, args, kwargs
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"Each task must be (func, name, args, kwargs) or (func, args, kwargs), got {len(entry)}-tuple"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
17
31
|
def run_tasks(task_list, max_workers=2, language=None, raise_on_failure=False):
|
|
18
32
|
"""
|
|
19
33
|
并发执行任务列表并实时显示状态
|
|
20
34
|
|
|
21
|
-
:param task_list: 任务列表,每个元素是 (函数, 位置参数元组, 关键字参数字典)
|
|
22
|
-
|
|
35
|
+
:param task_list: 任务列表,每个元素是 (函数, 显示名称, 位置参数元组, 关键字参数字典)
|
|
36
|
+
(兼容省略显示名称的三元组 (函数, 位置参数元组, 关键字参数字典))
|
|
37
|
+
:param max_workers: 最大并发线程数(必须 >= 1)
|
|
23
38
|
:param language: 显示语言 ('en' 或 'zh', 默认根据系统语言自动判断)
|
|
24
39
|
:param raise_on_failure: 若存在失败任务,是否抛出 RuntimeError
|
|
25
40
|
"""
|
|
41
|
+
if max_workers < 1:
|
|
42
|
+
raise ValueError("max_workers must be >= 1")
|
|
43
|
+
normalized_tasks = [_normalize_task_entry(item) for item in task_list]
|
|
26
44
|
print("""\n █████╗ ██╗ ██╗████████╗ ██████╗ ██████╗██╗ ██╗████████╗██╗ ██╗ ██████╗ ███╗ ██╗
|
|
27
45
|
██╔══██╗██║ ██║╚══██╔══╝██╔═══██╗██╔════╝╚██╗ ██╔╝╚══██╔══╝██║ ██║██╔═══██╗████╗ ██║
|
|
28
46
|
███████║██║ ██║ ██║ ██║ ██║██║ ╚████╔╝ ██║ ███████║██║ ██║██╔██╗ ██║
|
|
@@ -105,7 +123,7 @@ def run_tasks(task_list, max_workers=2, language=None, raise_on_failure=False):
|
|
|
105
123
|
"error": None,
|
|
106
124
|
"lock": threading.Lock() # 添加锁保证线程安全
|
|
107
125
|
}
|
|
108
|
-
for idx, (func, name, args, kwargs) in enumerate(
|
|
126
|
+
for idx, (func, name, args, kwargs) in enumerate(normalized_tasks, 1)
|
|
109
127
|
]
|
|
110
128
|
|
|
111
129
|
# 创建进度条
|
|
@@ -285,7 +303,7 @@ if __name__ == "__main__": # pragma: no cover
|
|
|
285
303
|
time.sleep(seconds)
|
|
286
304
|
return f"Long task {seconds}s"
|
|
287
305
|
|
|
288
|
-
# 创建任务列表 (函数, 位置参数, 关键字参数)
|
|
306
|
+
# 创建任务列表 (函数, 显示名称, 位置参数, 关键字参数)
|
|
289
307
|
tasks = [
|
|
290
308
|
(task_success, task_success.__name__, (0.5,), {}),
|
|
291
309
|
(task_failure, task_failure.__name__, (), {}),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import ast
|
|
2
|
+
import io
|
|
2
3
|
import os
|
|
3
4
|
import sys
|
|
4
5
|
import locale
|
|
@@ -15,7 +16,28 @@ _SKIP_DIRS = frozenset({
|
|
|
15
16
|
})
|
|
16
17
|
|
|
17
18
|
|
|
18
|
-
def
|
|
19
|
+
def _iter_python_files(path):
|
|
20
|
+
"""单遍确定性遍历目录下所有 .py 文件(跳过虚拟环境与构建产物目录)。"""
|
|
21
|
+
for root, dirs, files in os.walk(path):
|
|
22
|
+
dirs.sort()
|
|
23
|
+
files.sort()
|
|
24
|
+
dirs[:] = [
|
|
25
|
+
d for d in dirs
|
|
26
|
+
if d not in _SKIP_DIRS and not d.endswith(".egg-info")
|
|
27
|
+
]
|
|
28
|
+
for file in files:
|
|
29
|
+
if file.endswith(".py"):
|
|
30
|
+
yield os.path.join(root, file)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _is_within_root(abs_root: str, candidate_path: str) -> bool:
|
|
34
|
+
try:
|
|
35
|
+
return os.path.commonpath([abs_root, candidate_path]) == abs_root
|
|
36
|
+
except ValueError:
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _find_dynamic_split_sources(path, py_files=None):
|
|
19
41
|
"""Find split facades and implementation fragments under ``path``.
|
|
20
42
|
|
|
21
43
|
kd-dist splits oversized modules into a small facade which executes the
|
|
@@ -24,43 +46,44 @@ def _find_dynamic_split_sources(path):
|
|
|
24
46
|
the source fragments at runtime, while each fragment depends on globals
|
|
25
47
|
supplied by the facade.
|
|
26
48
|
"""
|
|
49
|
+
abs_root = os.path.abspath(path)
|
|
27
50
|
dynamic_sources = set()
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
51
|
+
candidates = _iter_python_files(path) if py_files is None else py_files
|
|
52
|
+
for facade in candidates:
|
|
53
|
+
try:
|
|
54
|
+
with io.open(facade, "rb") as raw_file:
|
|
55
|
+
raw_bytes = raw_file.read()
|
|
56
|
+
except OSError:
|
|
57
|
+
continue
|
|
58
|
+
if b"_kd_exec_split_parts" not in raw_bytes and b"\x00" not in raw_bytes:
|
|
59
|
+
continue
|
|
60
|
+
try:
|
|
61
|
+
with tokenize.open(facade) as source_file:
|
|
62
|
+
tree = ast.parse(source_file.read(), filename=facade)
|
|
63
|
+
except (OSError, SyntaxError, UnicodeDecodeError, LookupError):
|
|
64
|
+
continue
|
|
65
|
+
facade_dir = os.path.dirname(facade)
|
|
66
|
+
for node in tree.body:
|
|
67
|
+
if not isinstance(node, ast.Assign):
|
|
68
|
+
continue
|
|
69
|
+
if not any(
|
|
70
|
+
isinstance(target, ast.Name) and target.id == "_kd_exec_split_parts"
|
|
71
|
+
for target in node.targets
|
|
72
|
+
):
|
|
37
73
|
continue
|
|
38
|
-
facade = os.path.join(root, file)
|
|
39
74
|
try:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
except (OSError, SyntaxError, UnicodeDecodeError, LookupError):
|
|
75
|
+
parts = ast.literal_eval(node.value)
|
|
76
|
+
except (TypeError, ValueError):
|
|
43
77
|
continue
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
for target in node.targets
|
|
50
|
-
):
|
|
51
|
-
continue
|
|
52
|
-
try:
|
|
53
|
-
parts = ast.literal_eval(node.value)
|
|
54
|
-
except (TypeError, ValueError):
|
|
55
|
-
continue
|
|
56
|
-
if not isinstance(parts, (list, tuple)):
|
|
78
|
+
if not isinstance(parts, (list, tuple)):
|
|
79
|
+
continue
|
|
80
|
+
dynamic_sources.add(os.path.abspath(facade))
|
|
81
|
+
for part in parts:
|
|
82
|
+
if not isinstance(part, str) or not part.endswith(".py"):
|
|
57
83
|
continue
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
for part in parts
|
|
62
|
-
if isinstance(part, str) and part.endswith(".py")
|
|
63
|
-
)
|
|
84
|
+
resolved = os.path.abspath(os.path.join(facade_dir, part))
|
|
85
|
+
if _is_within_root(abs_root, resolved):
|
|
86
|
+
dynamic_sources.add(resolved)
|
|
64
87
|
return dynamic_sources
|
|
65
88
|
|
|
66
89
|
def get_system_language():
|
|
@@ -93,45 +116,37 @@ def find_python_files(path):
|
|
|
93
116
|
return any(marker in line for marker in exclude_markers)
|
|
94
117
|
|
|
95
118
|
valid_py_files = []
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
line1 = f.readline()
|
|
128
|
-
line2 = f.readline()
|
|
129
|
-
if not has_exclude_marker(line1) and not has_exclude_marker(line2):
|
|
130
|
-
valid_py_files.append(filepath)
|
|
131
|
-
except Exception as e:
|
|
132
|
-
print(f"无法读取文件 {filepath}: {e}")
|
|
133
|
-
except Exception as e:
|
|
134
|
-
print(f"处理文件 {filepath} 时出错: {e}")
|
|
119
|
+
all_py_files = list(_iter_python_files(path))
|
|
120
|
+
dynamic_split_sources = _find_dynamic_split_sources(path, py_files=all_py_files)
|
|
121
|
+
|
|
122
|
+
for filepath in all_py_files:
|
|
123
|
+
if os.path.basename(filepath) == "__init__.py":
|
|
124
|
+
continue
|
|
125
|
+
if os.path.abspath(filepath) in dynamic_split_sources:
|
|
126
|
+
continue
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
with open(filepath, 'r', encoding='utf-8') as f:
|
|
130
|
+
# 读取头两行
|
|
131
|
+
line1 = f.readline()
|
|
132
|
+
line2 = f.readline()
|
|
133
|
+
|
|
134
|
+
# 检查是否包含排除标记
|
|
135
|
+
if not has_exclude_marker(line1) and not has_exclude_marker(line2):
|
|
136
|
+
valid_py_files.append(filepath)
|
|
137
|
+
except UnicodeDecodeError:
|
|
138
|
+
# 保持历史扫描契约:无 coding cookie 的 legacy source
|
|
139
|
+
# 仍可被发现,真正的 PEP 263 解析留给编译阶段。
|
|
140
|
+
try:
|
|
141
|
+
with open(filepath, 'r', encoding='latin-1') as f:
|
|
142
|
+
line1 = f.readline()
|
|
143
|
+
line2 = f.readline()
|
|
144
|
+
if not has_exclude_marker(line1) and not has_exclude_marker(line2):
|
|
145
|
+
valid_py_files.append(filepath)
|
|
146
|
+
except Exception as e:
|
|
147
|
+
print(f"无法读取文件 {filepath}: {e}")
|
|
148
|
+
except Exception as e:
|
|
149
|
+
print(f"处理文件 {filepath} 时出错: {e}")
|
|
135
150
|
|
|
136
151
|
return valid_py_files
|
|
137
152
|
|
|
@@ -152,6 +167,7 @@ def parse_arguments():
|
|
|
152
167
|
'version_help': 'Show program version',
|
|
153
168
|
'version_text': f'v{__version__}',
|
|
154
169
|
'required_error': 'The following arguments are required: {}',
|
|
170
|
+
'conc_error': 'argument -c/--conc: must be a positive integer (>= 1)',
|
|
155
171
|
'epilog': 'Example:\n AutoCython -f demo.py\n AutoCython -p path'
|
|
156
172
|
},
|
|
157
173
|
'zh': {
|
|
@@ -165,6 +181,7 @@ def parse_arguments():
|
|
|
165
181
|
'version_help': '显示程序版本',
|
|
166
182
|
'version_text': f'v{__version__}',
|
|
167
183
|
'required_error': '缺少必要参数: {}',
|
|
184
|
+
'conc_error': '参数 -c/--conc: 必须为大于等于 1 的正整数',
|
|
168
185
|
'epilog': '示例:\n AutoCython -f demo.py\n AutoCython -p path'
|
|
169
186
|
}
|
|
170
187
|
}
|
|
@@ -214,6 +231,9 @@ def parse_arguments():
|
|
|
214
231
|
print(f"\nerror: {msg['required_error'].format('-f/--file, -p/--path')}", file=sys.stderr)
|
|
215
232
|
sys.exit(2)
|
|
216
233
|
|
|
234
|
+
if args.conc < 1:
|
|
235
|
+
parser.error(msg['conc_error'])
|
|
236
|
+
|
|
217
237
|
return args
|
|
218
238
|
|
|
219
239
|
def show_no_compilable_files(path):
|
|
@@ -235,6 +255,13 @@ def show_file_not_found(file):
|
|
|
235
255
|
def show_path_not_found(path):
|
|
236
256
|
lang = get_system_language()
|
|
237
257
|
|
|
258
|
+
if os.path.isfile(path):
|
|
259
|
+
if lang == 'zh':
|
|
260
|
+
print(f"路径 {path} 不是有效目录!")
|
|
261
|
+
else:
|
|
262
|
+
print(f"Path {path} is not a valid directory!")
|
|
263
|
+
return
|
|
264
|
+
|
|
238
265
|
if lang == 'zh':
|
|
239
266
|
print(f"路径 {path} 不存在!")
|
|
240
267
|
else:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AutoCython-zhang
|
|
3
|
-
Version: 2.3.
|
|
3
|
+
Version: 2.3.10
|
|
4
4
|
Summary: 自动Cython,使用Cython批量编译.py文件为.pyd文件!
|
|
5
5
|
Author-email: zhang_gavin <qq814608@163.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -64,7 +64,7 @@ pip install AutoCython-zhang
|
|
|
64
64
|
|
|
65
65
|
兼容性补充:Pydantic 兼容 shim 只对词法作用域内可识别的 `pydantic.BaseModel` 子类生效,且仅补充 Cython 所需的 `ignored_types`;Pydantic v2 的 `model_config`(包括条件、`try`、带注解和继承场景)及 legacy `class Config` 均保留,`pydantic.v1` 不会被误判。字符串混淆采用编译期 ASCII escaped literal,不生成 runtime decoder、缓存或 `sys.intern` 副作用;运行时得到的仍是普通 Python `str`。编译产物先写入目标目录的 staging 文件,校验成功后才原子替换旧产物,截断或失败的中间文件不会覆盖已有结果。
|
|
66
66
|
|
|
67
|
-
> v2.3.
|
|
67
|
+
> v2.3.10 恢复了字符串/字节序列的负索引语义,完善了 Python 3.14 AST、PEP 572/695 混淆作用域、头部指令安全提取、Pydantic 泛型/继承垫片与只读源码/重名冲突保护。
|
|
68
68
|
|
|
69
69
|
### 依赖
|
|
70
70
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AutoCython-zhang
|
|
3
|
-
Version: 2.3.
|
|
3
|
+
Version: 2.3.10
|
|
4
4
|
Summary: 自动Cython,使用Cython批量编译.py文件为.pyd文件!
|
|
5
5
|
Author-email: zhang_gavin <qq814608@163.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -64,7 +64,7 @@ pip install AutoCython-zhang
|
|
|
64
64
|
|
|
65
65
|
兼容性补充:Pydantic 兼容 shim 只对词法作用域内可识别的 `pydantic.BaseModel` 子类生效,且仅补充 Cython 所需的 `ignored_types`;Pydantic v2 的 `model_config`(包括条件、`try`、带注解和继承场景)及 legacy `class Config` 均保留,`pydantic.v1` 不会被误判。字符串混淆采用编译期 ASCII escaped literal,不生成 runtime decoder、缓存或 `sys.intern` 副作用;运行时得到的仍是普通 Python `str`。编译产物先写入目标目录的 staging 文件,校验成功后才原子替换旧产物,截断或失败的中间文件不会覆盖已有结果。
|
|
66
66
|
|
|
67
|
-
> v2.3.
|
|
67
|
+
> v2.3.10 恢复了字符串/字节序列的负索引语义,完善了 Python 3.14 AST、PEP 572/695 混淆作用域、头部指令安全提取、Pydantic 泛型/继承垫片与只读源码/重名冲突保护。
|
|
68
68
|
|
|
69
69
|
### 依赖
|
|
70
70
|
|
|
@@ -44,7 +44,7 @@ pip install AutoCython-zhang
|
|
|
44
44
|
|
|
45
45
|
兼容性补充:Pydantic 兼容 shim 只对词法作用域内可识别的 `pydantic.BaseModel` 子类生效,且仅补充 Cython 所需的 `ignored_types`;Pydantic v2 的 `model_config`(包括条件、`try`、带注解和继承场景)及 legacy `class Config` 均保留,`pydantic.v1` 不会被误判。字符串混淆采用编译期 ASCII escaped literal,不生成 runtime decoder、缓存或 `sys.intern` 副作用;运行时得到的仍是普通 Python `str`。编译产物先写入目标目录的 staging 文件,校验成功后才原子替换旧产物,截断或失败的中间文件不会覆盖已有结果。
|
|
46
46
|
|
|
47
|
-
> v2.3.
|
|
47
|
+
> v2.3.10 恢复了字符串/字节序列的负索引语义,完善了 Python 3.14 AST、PEP 572/695 混淆作用域、头部指令安全提取、Pydantic 泛型/继承垫片与只读源码/重名冲突保护。
|
|
48
48
|
|
|
49
49
|
### 依赖
|
|
50
50
|
|
|
File without changes
|
|
File without changes
|
{autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{autocython_zhang-2.3.9 → autocython_zhang-2.3.10}/AutoCython_zhang.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|