refactor-utils 4.0.0__tar.gz → 4.0.1__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.
- {refactor_utils-4.0.0/src/refactor_utils.egg-info → refactor_utils-4.0.1}/PKG-INFO +5 -3
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/pyproject.toml +9 -5
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/__init__.py +1 -1
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/bundle.py +27 -79
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/cli.py +7 -21
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/core.py +11 -35
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/discovery.py +5 -15
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/imports.py +1 -4
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/logging_setup.py +2 -6
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/merged_file.py +2 -5
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/modernize.py +13 -46
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/ordering.py +3 -10
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/parser.py +18 -68
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/resolver.py +23 -84
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/writer.py +4 -12
- {refactor_utils-4.0.0 → refactor_utils-4.0.1/src/refactor_utils.egg-info}/PKG-INFO +5 -3
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/tests/test_smoke.py +1 -3
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/LICENSE +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/README.md +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/setup.cfg +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/__main__.py +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/models.py +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/py.typed +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils/resources.py +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils.egg-info/SOURCES.txt +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils.egg-info/dependency_links.txt +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils.egg-info/entry_points.txt +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils.egg-info/requires.txt +0 -0
- {refactor_utils-4.0.0 → refactor_utils-4.0.1}/src/refactor_utils.egg-info/top_level.txt +0 -0
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: refactor-utils
|
|
3
|
-
Version: 4.0.
|
|
3
|
+
Version: 4.0.1
|
|
4
4
|
Summary: Consolidate a Python package into one dependency-ordered file, or pack it into a self-extracting zip bundle.
|
|
5
|
-
Author:
|
|
5
|
+
Author-email: Isaac Onagh <hellboynaz@gmail.com>
|
|
6
6
|
License: MIT
|
|
7
|
-
Project-URL: Homepage, https://
|
|
7
|
+
Project-URL: Homepage, https://github.com/i4147/refactor-utils
|
|
8
|
+
Project-URL: Repository, https://github.com/i4147/refactor-utils
|
|
9
|
+
Project-URL: Issues, https://github.com/i4147/refactor-utils/issues
|
|
8
10
|
Keywords: consolidate,bundle,merge,python,single-file,zip,modernize,six,pathlib
|
|
9
11
|
Classifier: Development Status :: 4 - Beta
|
|
10
12
|
Classifier: Environment :: Console
|
|
@@ -4,12 +4,11 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "refactor-utils"
|
|
7
|
-
version = "4.0.
|
|
7
|
+
version = "4.0.1"
|
|
8
8
|
description = "Consolidate a Python package into one dependency-ordered file, or pack it into a self-extracting zip bundle."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
11
11
|
license = { text = "MIT" }
|
|
12
|
-
authors = [{ name = "Z User" }]
|
|
13
12
|
keywords = ["consolidate", "bundle", "merge", "python", "single-file", "zip", "modernize", "six", "pathlib"]
|
|
14
13
|
classifiers = [
|
|
15
14
|
"Development Status :: 4 - Beta",
|
|
@@ -29,6 +28,9 @@ dependencies = [
|
|
|
29
28
|
"tomli>=2.0.0; python_version < '3.11'",
|
|
30
29
|
]
|
|
31
30
|
|
|
31
|
+
[[project.authors]]
|
|
32
|
+
name = "Isaac Onagh"
|
|
33
|
+
email = "hellboynaz@gmail.com"
|
|
32
34
|
[project.optional-dependencies]
|
|
33
35
|
format = ["black>=23.0", "ruff>=0.1.0"]
|
|
34
36
|
progress = ["tqdm>=4.0"]
|
|
@@ -38,7 +40,9 @@ dev = ["pytest>=7.0", "black", "ruff"]
|
|
|
38
40
|
pyrefactor = "refactor_utils.cli:main"
|
|
39
41
|
|
|
40
42
|
[project.urls]
|
|
41
|
-
Homepage = "https://
|
|
43
|
+
Homepage = "https://github.com/i4147/refactor-utils"
|
|
44
|
+
Repository = "https://github.com/i4147/refactor-utils"
|
|
45
|
+
Issues = "https://github.com/i4147/refactor-utils/issues"
|
|
42
46
|
|
|
43
47
|
[tool.setuptools.packages.find]
|
|
44
48
|
where = ["src"]
|
|
@@ -54,5 +58,5 @@ keep_docstrings = true
|
|
|
54
58
|
keep_comments = true
|
|
55
59
|
|
|
56
60
|
[tool.ruff]
|
|
57
|
-
line-length =
|
|
58
|
-
target-version = "
|
|
61
|
+
line-length = 120
|
|
62
|
+
target-version = "py311"
|
|
@@ -68,9 +68,7 @@ _COMPRESSIONS: dict[str, int] = {
|
|
|
68
68
|
|
|
69
69
|
_BINARY_SUFFIXES: frozenset[str] = frozenset({".so", ".pyd", ".dylib"})
|
|
70
70
|
|
|
71
|
-
_IGNORED_TOPS: frozenset[str] = frozenset(
|
|
72
|
-
{"__main__", "__builtins__", "builtins", "__future__"}
|
|
73
|
-
)
|
|
71
|
+
_IGNORED_TOPS: frozenset[str] = frozenset({"__main__", "__builtins__", "builtins", "__future__"})
|
|
74
72
|
|
|
75
73
|
_STRICT_WARNING_KINDS: frozenset[str] = frozenset({"unresolved", "broken"})
|
|
76
74
|
|
|
@@ -134,9 +132,7 @@ class ConsolidationPlan:
|
|
|
134
132
|
else:
|
|
135
133
|
entry_desc = f"{self.entry} -> bundle:/{self.entry_archive}"
|
|
136
134
|
lines = [f"entry : {entry_desc}"]
|
|
137
|
-
lines.append(
|
|
138
|
-
"search : " + (", ".join(str(p) for p in self.search_paths) or "-")
|
|
139
|
-
)
|
|
135
|
+
lines.append("search : " + (", ".join(str(p) for p in self.search_paths) or "-"))
|
|
140
136
|
modules = sorted(self.modules)
|
|
141
137
|
head = ", ".join(modules[:20])
|
|
142
138
|
if len(modules) > 20:
|
|
@@ -158,10 +154,7 @@ class ConsolidationPlan:
|
|
|
158
154
|
|
|
159
155
|
|
|
160
156
|
def _is_excluded(name: str, patterns: Sequence[str]) -> bool:
|
|
161
|
-
return any(
|
|
162
|
-
fnmatch.fnmatchcase(name, pattern) or name.startswith(pattern + ".")
|
|
163
|
-
for pattern in patterns
|
|
164
|
-
)
|
|
157
|
+
return any(fnmatch.fnmatchcase(name, pattern) or name.startswith(pattern + ".") for pattern in patterns)
|
|
165
158
|
|
|
166
159
|
|
|
167
160
|
def _validate_dotted(name: str, what: str) -> str:
|
|
@@ -219,9 +212,7 @@ def _walk_tree(
|
|
|
219
212
|
prune_dir: Callable[[tuple[str, ...]], bool] | None = None,
|
|
220
213
|
prune_file: Callable[[tuple[str, ...]], bool] | None = None,
|
|
221
214
|
) -> Iterator[tuple[Path, tuple[str, ...]]]:
|
|
222
|
-
def recurse(
|
|
223
|
-
directory: Path, seen: set[str]
|
|
224
|
-
) -> Iterator[tuple[Path, tuple[str, ...]]]:
|
|
215
|
+
def recurse(directory: Path, seen: set[str]) -> Iterator[tuple[Path, tuple[str, ...]]]:
|
|
225
216
|
try:
|
|
226
217
|
with os.scandir(directory) as iterator:
|
|
227
218
|
entries = sorted(iterator, key=lambda item: item.name)
|
|
@@ -391,9 +382,7 @@ def _scan_module(module_name: str, path: Path, is_package: bool) -> _ScanResult:
|
|
|
391
382
|
encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
|
|
392
383
|
tree = ast.parse(raw.decode(encoding), filename=str(path))
|
|
393
384
|
except (OSError, SyntaxError, UnicodeDecodeError, LookupError) as exc:
|
|
394
|
-
return _ScanResult(
|
|
395
|
-
set(), [PlanWarning("parse", f"could not parse {path}: {exc}")]
|
|
396
|
-
)
|
|
385
|
+
return _ScanResult(set(), [PlanWarning("parse", f"could not parse {path}: {exc}")])
|
|
397
386
|
scanner = _ImportScanner(module_name, is_package, str(path))
|
|
398
387
|
scanner.visit(tree)
|
|
399
388
|
return _ScanResult(scanner.imports, scanner.notes)
|
|
@@ -473,9 +462,7 @@ def _site_dirs(extra: Sequence[Path]) -> list[Path]:
|
|
|
473
462
|
return dirs
|
|
474
463
|
|
|
475
464
|
|
|
476
|
-
def _resolve_thirdparty(
|
|
477
|
-
requests: Sequence[str | Path], site_paths: Sequence[Path]
|
|
478
|
-
) -> dict[str, _ThirdPartyPackage]:
|
|
465
|
+
def _resolve_thirdparty(requests: Sequence[str | Path], site_paths: Sequence[Path]) -> dict[str, _ThirdPartyPackage]:
|
|
479
466
|
resolved: dict[str, _ThirdPartyPackage] = {}
|
|
480
467
|
if not requests:
|
|
481
468
|
return resolved
|
|
@@ -485,9 +472,7 @@ def _resolve_thirdparty(
|
|
|
485
472
|
if request_path.is_dir() or request_path.is_file():
|
|
486
473
|
name = request_path.stem if request_path.is_file() else request_path.name
|
|
487
474
|
_validate_dotted(name, f"package path {request_path}")
|
|
488
|
-
resolved[name] = _ThirdPartyPackage(
|
|
489
|
-
name, request_path, request_path.is_dir()
|
|
490
|
-
)
|
|
475
|
+
resolved[name] = _ThirdPartyPackage(name, request_path, request_path.is_dir())
|
|
491
476
|
continue
|
|
492
477
|
name = _validate_dotted(str(request), "--include-package entry")
|
|
493
478
|
if name in resolved:
|
|
@@ -506,9 +491,7 @@ def _resolve_thirdparty(
|
|
|
506
491
|
break
|
|
507
492
|
if found is None:
|
|
508
493
|
searched = ", ".join(str(d) for d in dirs) or "<no site directories>"
|
|
509
|
-
raise ConsolidationError(
|
|
510
|
-
f"--include-package {name!r}: package not found in: {searched}"
|
|
511
|
-
)
|
|
494
|
+
raise ConsolidationError(f"--include-package {name!r}: package not found in: {searched}")
|
|
512
495
|
resolved[name] = found
|
|
513
496
|
return resolved
|
|
514
497
|
|
|
@@ -529,13 +512,9 @@ def _find_package_dir(directory: Path) -> Path:
|
|
|
529
512
|
if len(candidates) == 1:
|
|
530
513
|
return candidates[0]
|
|
531
514
|
if not candidates:
|
|
532
|
-
raise ConsolidationError(
|
|
533
|
-
f"{directory} is not a package and contains no package"
|
|
534
|
-
)
|
|
515
|
+
raise ConsolidationError(f"{directory} is not a package and contains no package")
|
|
535
516
|
names = ", ".join(child.name for child in candidates)
|
|
536
|
-
raise ConsolidationError(
|
|
537
|
-
f"{directory} contains multiple packages ({names}); pass one explicitly"
|
|
538
|
-
)
|
|
517
|
+
raise ConsolidationError(f"{directory} contains multiple packages ({names}); pass one explicitly")
|
|
539
518
|
|
|
540
519
|
|
|
541
520
|
def _has_main_function(init_path: Path) -> bool:
|
|
@@ -546,10 +525,7 @@ def _has_main_function(init_path: Path) -> bool:
|
|
|
546
525
|
except (OSError, SyntaxError, UnicodeDecodeError, LookupError):
|
|
547
526
|
return False
|
|
548
527
|
for node in tree.body:
|
|
549
|
-
if (
|
|
550
|
-
isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
|
|
551
|
-
and node.name == "main"
|
|
552
|
-
):
|
|
528
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == "main":
|
|
553
529
|
return True
|
|
554
530
|
if isinstance(node, ast.ImportFrom):
|
|
555
531
|
for alias in node.names:
|
|
@@ -562,9 +538,7 @@ def _has_main_function(init_path: Path) -> bool:
|
|
|
562
538
|
return False
|
|
563
539
|
|
|
564
540
|
|
|
565
|
-
def _synthesize_main(
|
|
566
|
-
pkg_name: str, pkg_dir: Path, override: str | None
|
|
567
|
-
) -> tuple[str, list[str]]:
|
|
541
|
+
def _synthesize_main(pkg_name: str, pkg_dir: Path, override: str | None) -> tuple[str, list[str]]:
|
|
568
542
|
if override is not None:
|
|
569
543
|
parts = override.split(".")
|
|
570
544
|
module_file = pkg_dir / "/".join(parts) + ".py"
|
|
@@ -575,19 +549,13 @@ def _synthesize_main(
|
|
|
575
549
|
f"(tried {module_file} and {package_init})"
|
|
576
550
|
)
|
|
577
551
|
target = f"{pkg_name}.{override}"
|
|
578
|
-
source = (
|
|
579
|
-
"import runpy as _runpy\n"
|
|
580
|
-
f"_runpy.run_module({target!r}, run_name='__main__', alter_sys=True)\n"
|
|
581
|
-
)
|
|
552
|
+
source = f"import runpy as _runpy\n_runpy.run_module({target!r}, run_name='__main__', alter_sys=True)\n"
|
|
582
553
|
return source, [target]
|
|
583
554
|
|
|
584
555
|
for candidate in _ENTRY_CANDIDATES:
|
|
585
556
|
if (pkg_dir / f"{candidate}.py").is_file():
|
|
586
557
|
target = f"{pkg_name}.{candidate}"
|
|
587
|
-
source = (
|
|
588
|
-
"import runpy as _runpy\n"
|
|
589
|
-
f"_runpy.run_module({target!r}, run_name='__main__', alter_sys=True)\n"
|
|
590
|
-
)
|
|
558
|
+
source = f"import runpy as _runpy\n_runpy.run_module({target!r}, run_name='__main__', alter_sys=True)\n"
|
|
591
559
|
return source, [target]
|
|
592
560
|
|
|
593
561
|
init = pkg_dir / "__init__.py"
|
|
@@ -678,8 +646,7 @@ def analyze_bundle(
|
|
|
678
646
|
if existing.source != file:
|
|
679
647
|
warn(
|
|
680
648
|
"conflict",
|
|
681
|
-
f"module {name!r}: keeping {existing.source}, ignoring "
|
|
682
|
-
f"duplicate at {file}",
|
|
649
|
+
f"module {name!r}: keeping {existing.source}, ignoring duplicate at {file}",
|
|
683
650
|
)
|
|
684
651
|
return
|
|
685
652
|
modules[name] = BundledModule(name, file, is_package)
|
|
@@ -781,8 +748,7 @@ def analyze_bundle(
|
|
|
781
748
|
elif top in modules:
|
|
782
749
|
warn(
|
|
783
750
|
"broken",
|
|
784
|
-
f"import chain {name!r} (imported by {importer}): {name!r} "
|
|
785
|
-
f"not found inside bundled package {top!r}",
|
|
751
|
+
f"import chain {name!r} (imported by {importer}): {name!r} not found inside bundled package {top!r}",
|
|
786
752
|
)
|
|
787
753
|
|
|
788
754
|
def process_scan(result: _ScanResult, importer: str) -> None:
|
|
@@ -820,8 +786,7 @@ def analyze_bundle(
|
|
|
820
786
|
located = _locate(entry_module, search_paths)
|
|
821
787
|
if located is None:
|
|
822
788
|
raise ConsolidationError(
|
|
823
|
-
f"module {entry_module!r} not found in: "
|
|
824
|
-
f"{', '.join(str(p) for p in search_paths)}"
|
|
789
|
+
f"module {entry_module!r} not found in: {', '.join(str(p) for p in search_paths)}"
|
|
825
790
|
)
|
|
826
791
|
embed_located(located, entry_module)
|
|
827
792
|
if located.is_package:
|
|
@@ -856,8 +821,7 @@ def analyze_bundle(
|
|
|
856
821
|
if any(m == top_name or m.startswith(top_name + ".") for m in modules):
|
|
857
822
|
warn(
|
|
858
823
|
"note",
|
|
859
|
-
f"--include-package {top_name}: a local copy was already bundled; "
|
|
860
|
-
"the third-party entry was ignored",
|
|
824
|
+
f"--include-package {top_name}: a local copy was already bundled; the third-party entry was ignored",
|
|
861
825
|
)
|
|
862
826
|
continue
|
|
863
827
|
embed_thirdparty(top_name, package)
|
|
@@ -878,9 +842,7 @@ def analyze_bundle(
|
|
|
878
842
|
failures = [w for w in warnings if w.kind in _STRICT_WARNING_KINDS]
|
|
879
843
|
if failures:
|
|
880
844
|
detail = "\n ".join(str(w) for w in failures)
|
|
881
|
-
raise ConsolidationError(
|
|
882
|
-
f"strict mode: {len(failures)} unresolved import(s):\n {detail}"
|
|
883
|
-
)
|
|
845
|
+
raise ConsolidationError(f"strict mode: {len(failures)} unresolved import(s):\n {detail}")
|
|
884
846
|
|
|
885
847
|
return ConsolidationPlan(
|
|
886
848
|
entry=entry_file or entry_pkg_dir or Path(str(entry)).resolve(),
|
|
@@ -926,8 +888,7 @@ def _parse_data_spec(
|
|
|
926
888
|
return [(path, path.name)], pattern
|
|
927
889
|
warn(
|
|
928
890
|
"note",
|
|
929
|
-
f"--include-data {spec!r}: {prefix!r} is neither a bundled package "
|
|
930
|
-
"nor an existing directory",
|
|
891
|
+
f"--include-data {spec!r}: {prefix!r} is neither a bundled package nor an existing directory",
|
|
931
892
|
)
|
|
932
893
|
return None
|
|
933
894
|
|
|
@@ -956,8 +917,7 @@ def _collect_data(
|
|
|
956
917
|
if archive in module_archives:
|
|
957
918
|
warn(
|
|
958
919
|
"conflict",
|
|
959
|
-
f"data file {source} collides with bundled module {archive}; "
|
|
960
|
-
"the module wins",
|
|
920
|
+
f"data file {source} collides with bundled module {archive}; the module wins",
|
|
961
921
|
)
|
|
962
922
|
return
|
|
963
923
|
existing = out.get(archive)
|
|
@@ -965,8 +925,7 @@ def _collect_data(
|
|
|
965
925
|
if existing != source:
|
|
966
926
|
warn(
|
|
967
927
|
"conflict",
|
|
968
|
-
f"bundle path {archive!r} already provided by {existing}; "
|
|
969
|
-
f"ignoring {source}",
|
|
928
|
+
f"bundle path {archive!r} already provided by {existing}; ignoring {source}",
|
|
970
929
|
)
|
|
971
930
|
return
|
|
972
931
|
out[archive] = source
|
|
@@ -974,11 +933,7 @@ def _collect_data(
|
|
|
974
933
|
if "*" in package_data:
|
|
975
934
|
targets = sorted(package_dirs.items())
|
|
976
935
|
else:
|
|
977
|
-
targets = sorted(
|
|
978
|
-
(name, package_dirs[name])
|
|
979
|
-
for name in set(package_data)
|
|
980
|
-
if name in package_dirs
|
|
981
|
-
)
|
|
936
|
+
targets = sorted((name, package_dirs[name]) for name in set(package_data) if name in package_dirs)
|
|
982
937
|
for name in package_data:
|
|
983
938
|
if name != "*" and name not in package_dirs:
|
|
984
939
|
warn(
|
|
@@ -1159,8 +1114,7 @@ def _archive_members(plan: ConsolidationPlan) -> dict[str, Path | bytes]:
|
|
|
1159
1114
|
existing = members.get(archive)
|
|
1160
1115
|
if existing is not None and existing != module.source:
|
|
1161
1116
|
raise ConsolidationError(
|
|
1162
|
-
f"internal error: archive path {archive!r} maps to both "
|
|
1163
|
-
f"{existing} and {module.source}"
|
|
1117
|
+
f"internal error: archive path {archive!r} maps to both {existing} and {module.source}"
|
|
1164
1118
|
)
|
|
1165
1119
|
members[archive] = module.source
|
|
1166
1120
|
for archive, source in sorted(plan.synthetic_files.items()):
|
|
@@ -1172,9 +1126,7 @@ def _archive_members(plan: ConsolidationPlan) -> dict[str, Path | bytes]:
|
|
|
1172
1126
|
return members
|
|
1173
1127
|
|
|
1174
1128
|
|
|
1175
|
-
def _render_header(
|
|
1176
|
-
plan: ConsolidationPlan, *, compression: str, deterministic: bool
|
|
1177
|
-
) -> str:
|
|
1129
|
+
def _render_header(plan: ConsolidationPlan, *, compression: str, deterministic: bool) -> str:
|
|
1178
1130
|
top_names = sorted({module.name.split(".")[0] for module in plan.modules.values()})
|
|
1179
1131
|
lines = [
|
|
1180
1132
|
"# " + "=" * 74,
|
|
@@ -1212,9 +1164,7 @@ def render_bundle(
|
|
|
1212
1164
|
) -> str:
|
|
1213
1165
|
"""Render *plan* into a runnable self-extracting python script."""
|
|
1214
1166
|
if compression not in _COMPRESSIONS:
|
|
1215
|
-
raise ConsolidationError(
|
|
1216
|
-
f"unknown compression {compression!r}; expected one of {sorted(_COMPRESSIONS)}"
|
|
1217
|
-
)
|
|
1167
|
+
raise ConsolidationError(f"unknown compression {compression!r}; expected one of {sorted(_COMPRESSIONS)}")
|
|
1218
1168
|
interpreter = python or sys.executable or "python3"
|
|
1219
1169
|
members = _archive_members(plan)
|
|
1220
1170
|
timestamp = _zip_timestamp(deterministic)
|
|
@@ -1235,9 +1185,7 @@ def render_bundle(
|
|
|
1235
1185
|
info.compress_type = compress_type
|
|
1236
1186
|
archive.writestr(info, data)
|
|
1237
1187
|
payload = base64.b64encode(buffer.getvalue()).decode("ascii")
|
|
1238
|
-
chunks = "\n".join(
|
|
1239
|
-
f' "{payload[index : index + 76]}"' for index in range(0, len(payload), 76)
|
|
1240
|
-
)
|
|
1188
|
+
chunks = "\n".join(f' "{payload[index : index + 76]}"' for index in range(0, len(payload), 76))
|
|
1241
1189
|
if not chunks:
|
|
1242
1190
|
chunks = ' ""'
|
|
1243
1191
|
|
|
@@ -42,9 +42,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
42
42
|
"--name",
|
|
43
43
|
default=None,
|
|
44
44
|
metavar="NAME",
|
|
45
|
-
help=(
|
|
46
|
-
"name of the generated file\n(default: the source name, e.g. output/<source>.py)"
|
|
47
|
-
),
|
|
45
|
+
help=("name of the generated file\n(default: the source name, e.g. output/<source>.py)"),
|
|
48
46
|
)
|
|
49
47
|
p.add_argument(
|
|
50
48
|
"-j",
|
|
@@ -59,9 +57,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
59
57
|
default="process",
|
|
60
58
|
help="executor type for parallel parsing (default: process)",
|
|
61
59
|
)
|
|
62
|
-
p.add_argument(
|
|
63
|
-
"--progress", action="store_true", help="show progress bar during parsing"
|
|
64
|
-
)
|
|
60
|
+
p.add_argument("--progress", action="store_true", help="show progress bar during parsing")
|
|
65
61
|
# Discovery / filtering
|
|
66
62
|
p.add_argument(
|
|
67
63
|
"-x",
|
|
@@ -69,9 +65,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
69
65
|
action="append",
|
|
70
66
|
default=[],
|
|
71
67
|
metavar="GLOB",
|
|
72
|
-
help=(
|
|
73
|
-
"extra path glob to skip (repeatable)\nprecedence: default excludes < --include < --exclude"
|
|
74
|
-
),
|
|
68
|
+
help=("extra path glob to skip (repeatable)\nprecedence: default excludes < --include < --exclude"),
|
|
75
69
|
)
|
|
76
70
|
p.add_argument(
|
|
77
71
|
"--include",
|
|
@@ -132,9 +126,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
132
126
|
"--imports",
|
|
133
127
|
choices=["prune", "keep", "strict"],
|
|
134
128
|
default="prune",
|
|
135
|
-
help=(
|
|
136
|
-
"import handling: prune (default, drop unused), keep (keep all),\nstrict (prune and warn on unused)"
|
|
137
|
-
),
|
|
129
|
+
help=("import handling: prune (default, drop unused), keep (keep all),\nstrict (prune and warn on unused)"),
|
|
138
130
|
)
|
|
139
131
|
p.add_argument(
|
|
140
132
|
"--keep-docstrings",
|
|
@@ -242,10 +234,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
242
234
|
action="append",
|
|
243
235
|
default=[],
|
|
244
236
|
metavar="DIR",
|
|
245
|
-
help=(
|
|
246
|
-
"extra directories to search for local packages (repeatable;\n"
|
|
247
|
-
"':'-separated lists allowed)"
|
|
248
|
-
),
|
|
237
|
+
help=("extra directories to search for local packages (repeatable;\n':'-separated lists allowed)"),
|
|
249
238
|
)
|
|
250
239
|
bundle.add_argument(
|
|
251
240
|
"--exclude-module",
|
|
@@ -253,8 +242,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
253
242
|
default=[],
|
|
254
243
|
metavar="PAT",
|
|
255
244
|
help=(
|
|
256
|
-
"exclude modules/packages (fnmatch on dotted names;\
|
|
257
|
-
"a bare name excludes its whole subtree; repeatable)"
|
|
245
|
+
"exclude modules/packages (fnmatch on dotted names;\na bare name excludes its whole subtree; repeatable)"
|
|
258
246
|
),
|
|
259
247
|
)
|
|
260
248
|
bundle.add_argument(
|
|
@@ -447,9 +435,7 @@ def main(argv=None) -> int:
|
|
|
447
435
|
|
|
448
436
|
def _run_bundle(args) -> int:
|
|
449
437
|
if args.source is None:
|
|
450
|
-
logger.error(
|
|
451
|
-
"--bundle requires a SOURCE (entry script, package dir, or module name)"
|
|
452
|
-
)
|
|
438
|
+
logger.error("--bundle requires a SOURCE (entry script, package dir, or module name)")
|
|
453
439
|
return 2
|
|
454
440
|
output: str | Path | None
|
|
455
441
|
if args.stdout:
|
|
@@ -92,9 +92,7 @@ def _parse_all(
|
|
|
92
92
|
|
|
93
93
|
return tqdm(iterator, total=total, desc="Parsing")
|
|
94
94
|
except ImportError:
|
|
95
|
-
logger.info(
|
|
96
|
-
"Progress bar requested but tqdm not installed — falling back to log"
|
|
97
|
-
)
|
|
95
|
+
logger.info("Progress bar requested but tqdm not installed — falling back to log")
|
|
98
96
|
return iterator
|
|
99
97
|
|
|
100
98
|
def run_pool(pool_cls, todo) -> None:
|
|
@@ -119,11 +117,7 @@ def _parse_all(
|
|
|
119
117
|
src = futures[fut]
|
|
120
118
|
try:
|
|
121
119
|
res = fut.result()
|
|
122
|
-
if (
|
|
123
|
-
isinstance(res, tuple)
|
|
124
|
-
and len(res) == 2
|
|
125
|
-
and isinstance(res[1], ModuleInfo)
|
|
126
|
-
):
|
|
120
|
+
if isinstance(res, tuple) and len(res) == 2 and isinstance(res[1], ModuleInfo):
|
|
127
121
|
results[res[0]] = res[1]
|
|
128
122
|
else:
|
|
129
123
|
results[src.module] = res
|
|
@@ -179,13 +173,9 @@ def validate_syntax(text: str, filename: str = "<consolidated>") -> ast.Module:
|
|
|
179
173
|
line = lines[exc.lineno - 1].strip()
|
|
180
174
|
where = f"line {exc.lineno}" if exc.lineno else "unknown line"
|
|
181
175
|
detail = f": {line!r}" if line else ""
|
|
182
|
-
raise ConsolidationError(
|
|
183
|
-
f"generated {filename} is not valid python: {exc.msg} ({where}){detail}"
|
|
184
|
-
) from exc
|
|
176
|
+
raise ConsolidationError(f"generated {filename} is not valid python: {exc.msg} ({where}){detail}") from exc
|
|
185
177
|
except ValueError as exc:
|
|
186
|
-
raise ConsolidationError(
|
|
187
|
-
f"generated {filename} is not valid python: {exc}"
|
|
188
|
-
) from exc
|
|
178
|
+
raise ConsolidationError(f"generated {filename} is not valid python: {exc}") from exc
|
|
189
179
|
|
|
190
180
|
|
|
191
181
|
def consolidate(
|
|
@@ -242,13 +232,9 @@ def consolidate(
|
|
|
242
232
|
if not modernize and cfg.get("modernize"):
|
|
243
233
|
modernize = str(cfg["modernize"])
|
|
244
234
|
if imports_mode not in ("prune", "keep", "strict"):
|
|
245
|
-
raise ConsolidationError(
|
|
246
|
-
f"imports_mode must be one of prune/keep/strict, got {imports_mode!r}"
|
|
247
|
-
)
|
|
235
|
+
raise ConsolidationError(f"imports_mode must be one of prune/keep/strict, got {imports_mode!r}")
|
|
248
236
|
if main_name is not None and not is_valid_identifier(main_name):
|
|
249
|
-
raise ConsolidationError(
|
|
250
|
-
f"--main-name {main_name!r} is not a valid python identifier"
|
|
251
|
-
)
|
|
237
|
+
raise ConsolidationError(f"--main-name {main_name!r} is not a valid python identifier")
|
|
252
238
|
source, output = Path(source), Path(output)
|
|
253
239
|
merged_path: Path | None = Path(merged_file) if merged_file else None
|
|
254
240
|
if merged_path is not None:
|
|
@@ -286,9 +272,7 @@ def consolidate(
|
|
|
286
272
|
df
|
|
287
273
|
for df in data_files
|
|
288
274
|
if any(
|
|
289
|
-
fnmatch.fnmatch(df.relative, pat)
|
|
290
|
-
or fnmatch.fnmatch(Path(df.path).name, pat)
|
|
291
|
-
for pat in data_glob
|
|
275
|
+
fnmatch.fnmatch(df.relative, pat) or fnmatch.fnmatch(Path(df.path).name, pat) for pat in data_glob
|
|
292
276
|
)
|
|
293
277
|
]
|
|
294
278
|
if not files:
|
|
@@ -348,9 +332,7 @@ def consolidate(
|
|
|
348
332
|
logger.info("Renamed {}:{} -> {}", mod, orig, final)
|
|
349
333
|
for mod, name in plan.deduped:
|
|
350
334
|
logger.info("Deduped {} from {}", name, mod)
|
|
351
|
-
mod_text = render_consolidated(
|
|
352
|
-
plan, source_name, do_format=do_format, formatter=formatter
|
|
353
|
-
)
|
|
335
|
+
mod_text = render_consolidated(plan, source_name, do_format=do_format, formatter=formatter)
|
|
354
336
|
exports = sum(len(v) for v in plan.exports.values())
|
|
355
337
|
if modernize:
|
|
356
338
|
# Apply modernization passes (six -> py3, os.path -> pathlib) to the
|
|
@@ -362,9 +344,7 @@ def consolidate(
|
|
|
362
344
|
if report.changed:
|
|
363
345
|
mod_text = tree.code
|
|
364
346
|
except Exception as exc:
|
|
365
|
-
raise ConsolidationError(
|
|
366
|
-
f"modernize pass failed on consolidated output: {exc}"
|
|
367
|
-
) from exc
|
|
347
|
+
raise ConsolidationError(f"modernize pass failed on consolidated output: {exc}") from exc
|
|
368
348
|
validate_syntax(mod_text, filename)
|
|
369
349
|
diff_text = ""
|
|
370
350
|
target = output / filename
|
|
@@ -389,9 +369,7 @@ def consolidate(
|
|
|
389
369
|
sys.stdout.write(diff_text)
|
|
390
370
|
if check:
|
|
391
371
|
if diff_text:
|
|
392
|
-
raise ConsolidationError(
|
|
393
|
-
"check failed: output would change (diff not empty)"
|
|
394
|
-
)
|
|
372
|
+
raise ConsolidationError("check failed: output would change (diff not empty)")
|
|
395
373
|
logger.success("Check passed: output up to date")
|
|
396
374
|
return ConsolidationResult(
|
|
397
375
|
output,
|
|
@@ -426,9 +404,7 @@ def consolidate(
|
|
|
426
404
|
logger.info("Would embed {} data file(s)", len(resources))
|
|
427
405
|
if copy_data:
|
|
428
406
|
for df in data_files:
|
|
429
|
-
logger.info(
|
|
430
|
-
"Would copy data file {} -> {}/{}", df.path, output, df.relative
|
|
431
|
-
)
|
|
407
|
+
logger.info("Would copy data file {} -> {}/{}", df.path, output, df.relative)
|
|
432
408
|
return ConsolidationResult(
|
|
433
409
|
output,
|
|
434
410
|
[],
|
|
@@ -117,9 +117,7 @@ def detect_base(root: Path) -> Path:
|
|
|
117
117
|
if (root / "__init__.py").is_file():
|
|
118
118
|
return root.parent
|
|
119
119
|
src = root / "src"
|
|
120
|
-
if src.is_dir() and any(
|
|
121
|
-
p.is_dir() and (p / "__init__.py").is_file() for p in src.iterdir()
|
|
122
|
-
):
|
|
120
|
+
if src.is_dir() and any(p.is_dir() and (p / "__init__.py").is_file() for p in src.iterdir()):
|
|
123
121
|
return src
|
|
124
122
|
return root
|
|
125
123
|
|
|
@@ -162,9 +160,7 @@ def _is_excluded(
|
|
|
162
160
|
default_hit = any(fnmatch.fnmatch(name, g) for g in EXCLUDED_FILE_GLOBS)
|
|
163
161
|
if default_hit:
|
|
164
162
|
if include and _matches(rel, posix, name, include):
|
|
165
|
-
logger.debug(
|
|
166
|
-
"Re-included {} via --include (overrode default exclude)", path
|
|
167
|
-
)
|
|
163
|
+
logger.debug("Re-included {} via --include (overrode default exclude)", path)
|
|
168
164
|
return False
|
|
169
165
|
logger.debug("Skipping {} (default exclude)", path)
|
|
170
166
|
return True
|
|
@@ -204,9 +200,7 @@ def _walk(
|
|
|
204
200
|
if is_symlink and not follow_symlinks:
|
|
205
201
|
try:
|
|
206
202
|
target = entry.resolve()
|
|
207
|
-
if target in skip or any(
|
|
208
|
-
str(target).startswith(str(s) + os.sep) for s in skip
|
|
209
|
-
):
|
|
203
|
+
if target in skip or any(str(target).startswith(str(s) + os.sep) for s in skip):
|
|
210
204
|
continue
|
|
211
205
|
except OSError:
|
|
212
206
|
logger.warning("Broken symlink skipped: {}", entry)
|
|
@@ -329,9 +323,7 @@ def discover_data_files(
|
|
|
329
323
|
if exclude and _matches(rel, entry.as_posix(), entry.name, exclude):
|
|
330
324
|
continue
|
|
331
325
|
if any(fnmatch.fnmatch(entry.name, g) for g in EXCLUDED_FILE_GLOBS):
|
|
332
|
-
if not (
|
|
333
|
-
include and _matches(rel, entry.as_posix(), entry.name, include)
|
|
334
|
-
):
|
|
326
|
+
if not (include and _matches(rel, entry.as_posix(), entry.name, include)):
|
|
335
327
|
continue
|
|
336
328
|
if _is_data_file(entry):
|
|
337
329
|
data_files.append(DataFile(entry, rel))
|
|
@@ -342,9 +334,7 @@ def discover_data_files(
|
|
|
342
334
|
return data_files
|
|
343
335
|
|
|
344
336
|
|
|
345
|
-
def read_pyproject_section(
|
|
346
|
-
config_path: Path | str, section: str = "pyrefactor"
|
|
347
|
-
) -> dict:
|
|
337
|
+
def read_pyproject_section(config_path: Path | str, section: str = "pyrefactor") -> dict:
|
|
348
338
|
try:
|
|
349
339
|
import tomllib
|
|
350
340
|
except ImportError: # pragma: no cover - py<3.11
|
|
@@ -43,10 +43,7 @@ def _wrap(module: str, items: list[str]) -> str:
|
|
|
43
43
|
def _dedupe_aliases(items: Iterable[str]) -> set[str]:
|
|
44
44
|
plain = {i for i in items if " as " not in i}
|
|
45
45
|
aliased = {i for i in items if " as " in i}
|
|
46
|
-
return {
|
|
47
|
-
i if i.split(" as ", 1)[1] != i.split(" as ", 1)[0] else i.split(" as ", 1)[0]
|
|
48
|
-
for i in aliased
|
|
49
|
-
} | plain
|
|
46
|
+
return {i if i.split(" as ", 1)[1] != i.split(" as ", 1)[0] else i.split(" as ", 1)[0] for i in aliased} | plain
|
|
50
47
|
|
|
51
48
|
|
|
52
49
|
def future_section(names: Iterable[str]) -> str:
|
|
@@ -38,9 +38,7 @@ class _ShimLogger:
|
|
|
38
38
|
def __init__(self, inner: logging.Logger) -> None:
|
|
39
39
|
self._inner = inner
|
|
40
40
|
|
|
41
|
-
def _log(
|
|
42
|
-
self, level: int, message: object, args: tuple, exc_info: bool = False
|
|
43
|
-
) -> None:
|
|
41
|
+
def _log(self, level: int, message: object, args: tuple, exc_info: bool = False) -> None:
|
|
44
42
|
self._inner.log(level, _fmt_message(message, args), exc_info=exc_info)
|
|
45
43
|
|
|
46
44
|
def trace(self, message: object, *args: object) -> None:
|
|
@@ -72,9 +70,7 @@ class _ShimLogger:
|
|
|
72
70
|
if not isinstance(handler, logging.NullHandler):
|
|
73
71
|
self._inner.removeHandler(handler)
|
|
74
72
|
|
|
75
|
-
def add(
|
|
76
|
-
self, sink, level: str = "DEBUG", rotation=None, enqueue=False, format=None
|
|
77
|
-
):
|
|
73
|
+
def add(self, sink, level: str = "DEBUG", rotation=None, enqueue=False, format=None):
|
|
78
74
|
if isinstance(sink, (str, bytes)) or hasattr(sink, "__fspath__"):
|
|
79
75
|
handler: logging.Handler = logging.FileHandler(sink, encoding="utf-8")
|
|
80
76
|
else:
|
|
@@ -26,8 +26,7 @@ def parse_merged_file(text: str) -> list[tuple[str, str]]:
|
|
|
26
26
|
matches = list(HEADER_RE.finditer(text))
|
|
27
27
|
if not matches:
|
|
28
28
|
raise ValueError(
|
|
29
|
-
"no '# File: <path>' headers found; use a directory/package "
|
|
30
|
-
"source for loose .py files instead"
|
|
29
|
+
"no '# File: <path>' headers found; use a directory/package source for loose .py files instead"
|
|
31
30
|
)
|
|
32
31
|
out: list[tuple[str, str]] = []
|
|
33
32
|
for i, m in enumerate(matches):
|
|
@@ -42,9 +41,7 @@ def parse_merged_file(text: str) -> list[tuple[str, str]]:
|
|
|
42
41
|
return out
|
|
43
42
|
|
|
44
43
|
|
|
45
|
-
def _derive_module_layout(
|
|
46
|
-
pairs: list[tuple[str, str]], stem: str
|
|
47
|
-
) -> tuple[str, list[tuple[Path, str]]]:
|
|
44
|
+
def _derive_module_layout(pairs: list[tuple[str, str]], stem: str) -> tuple[str, list[tuple[Path, str]]]:
|
|
48
45
|
"""Pick a top-level package name and per-entry relative paths.
|
|
49
46
|
|
|
50
47
|
Two header styles are supported:
|