refactor-utils 0.1.0__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.
- refactor_utils/__init__.py +15 -0
- refactor_utils/cli.py +38 -0
- refactor_utils/core.py +184 -0
- refactor_utils/movers.py +123 -0
- refactor_utils/options.py +13 -0
- refactor_utils/utils.py +67 -0
- refactor_utils-0.1.0.dist-info/METADATA +27 -0
- refactor_utils-0.1.0.dist-info/RECORD +11 -0
- refactor_utils-0.1.0.dist-info/WHEEL +5 -0
- refactor_utils-0.1.0.dist-info/entry_points.txt +2 -0
- refactor_utils-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""
|
|
2
|
+
refactor_utils package
|
|
3
|
+
|
|
4
|
+
Provides a CLI `pyrefactor` to reorganize small packages:
|
|
5
|
+
- move top-level functions -> myutil.py
|
|
6
|
+
- move UPPERCASE constants -> constants.py
|
|
7
|
+
- move top-level classes -> classes.py
|
|
8
|
+
|
|
9
|
+
Modes:
|
|
10
|
+
- small: top-level only
|
|
11
|
+
- merge: recursively merge everything into top-level modules
|
|
12
|
+
- subpkg: keep subpackages separate (each gets own myutil/constants/classes)
|
|
13
|
+
- dry-run: show proposed changes without writing
|
|
14
|
+
"""
|
|
15
|
+
__version__ = "0.1.0"
|
refactor_utils/cli.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
from .options import Options
|
|
4
|
+
from .core import run
|
|
5
|
+
|
|
6
|
+
def parse_args():
|
|
7
|
+
p = argparse.ArgumentParser(prog="pyrefactor", description="Refactor small python packages")
|
|
8
|
+
p.add_argument("run", nargs="?", default="run", help="command: run")
|
|
9
|
+
p.add_argument("--mode", choices=["small", "merge", "subpkg", "dry-run"], default="small", help="operation mode")
|
|
10
|
+
p.add_argument("--root", default=".", help="root package folder (default: current directory)")
|
|
11
|
+
p.add_argument("--no-backup", action="store_true", help="do not create .bak backups")
|
|
12
|
+
p.add_argument("--no-format", action="store_true", help="do not attempt to auto-format files")
|
|
13
|
+
p.add_argument("--func-file", default="myutil.py", help="target functions filename")
|
|
14
|
+
p.add_argument("--const-file", default="constants.py", help="target constants filename")
|
|
15
|
+
p.add_argument("--class-file", default="classes.py", help="target classes filename")
|
|
16
|
+
p.add_argument("--quiet", action="store_true", help="suppress verbose output")
|
|
17
|
+
p.add_argument("--undo", action="store_true", help="restore backups (.bak) for top-level files")
|
|
18
|
+
return p.parse_args()
|
|
19
|
+
|
|
20
|
+
def main():
|
|
21
|
+
args = parse_args()
|
|
22
|
+
opts = Options(
|
|
23
|
+
mode=args.mode,
|
|
24
|
+
root=args.root,
|
|
25
|
+
backup=not args.no_backup,
|
|
26
|
+
format=not args.no_format,
|
|
27
|
+
target_funcs=args.func_file,
|
|
28
|
+
target_consts=args.const_file,
|
|
29
|
+
target_classes=args.class_file,
|
|
30
|
+
verbose=not args.quiet,
|
|
31
|
+
undo=args.undo,
|
|
32
|
+
)
|
|
33
|
+
if opts.verbose:
|
|
34
|
+
print(f"Running pyrefactor mode={opts.mode} root={opts.root}")
|
|
35
|
+
run(opts)
|
|
36
|
+
|
|
37
|
+
if __name__ == "__main__":
|
|
38
|
+
main()
|
refactor_utils/core.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Dict, List, Tuple
|
|
3
|
+
from .options import Options
|
|
4
|
+
from . import movers, utils
|
|
5
|
+
|
|
6
|
+
# Helper to write top-level __init__.py
|
|
7
|
+
def write_top_init(all_funcs: List[str], all_consts: List[str], all_classes: List[str], opts: Options, dry_run: bool):
|
|
8
|
+
imports = []
|
|
9
|
+
items = []
|
|
10
|
+
if all_funcs:
|
|
11
|
+
imports.append(f"from .{os.path.splitext(opts.target_funcs)[0]} import " + ", ".join(sorted(set(all_funcs))))
|
|
12
|
+
items.extend(all_funcs)
|
|
13
|
+
if all_consts:
|
|
14
|
+
imports.append(f"from .{os.path.splitext(opts.target_consts)[0]} import " + ", ".join(sorted(set(all_consts))))
|
|
15
|
+
items.extend(all_consts)
|
|
16
|
+
if all_classes:
|
|
17
|
+
imports.append(f"from .{os.path.splitext(opts.target_classes)[0]} import " + ", ".join(sorted(set(all_classes))))
|
|
18
|
+
items.extend(all_classes)
|
|
19
|
+
content = "\n".join(imports) + "\n\n__all__ = " + movers.make_all_list(items) + "\n"
|
|
20
|
+
if opts.verbose:
|
|
21
|
+
print("Writing top-level __init__.py with these imports:")
|
|
22
|
+
for li in imports:
|
|
23
|
+
print(" ", li)
|
|
24
|
+
print("And __all__ with", len(items), "items")
|
|
25
|
+
utils.overwrite_file(opts.root + "/" + "__init__.py", content, dry_run)
|
|
26
|
+
|
|
27
|
+
def run_small(opts: Options):
|
|
28
|
+
# top-level only (non-recursive)
|
|
29
|
+
py_files = utils.list_py_files(opts.root, recursive=False)
|
|
30
|
+
# only consider files in root, skip __init__.py (we'll rewrite)
|
|
31
|
+
paths = [p for p in py_files if os.path.abspath(p) != os.path.abspath(os.path.join(opts.root, "__init__.py"))]
|
|
32
|
+
all_funcs, all_consts, all_classes, file_map = movers.collect_from_files(paths)
|
|
33
|
+
if opts.verbose:
|
|
34
|
+
print("Found (top-level) functions:", all_funcs)
|
|
35
|
+
print("Found (top-level) constants:", all_consts)
|
|
36
|
+
print("Found (top-level) classes:", all_classes)
|
|
37
|
+
|
|
38
|
+
func_content, const_content, class_content, _, _, _ = movers.build_top_level_modules(file_map)
|
|
39
|
+
targets = {
|
|
40
|
+
"funcs": os.path.join(opts.root, opts.target_funcs),
|
|
41
|
+
"consts": os.path.join(opts.root, opts.target_consts),
|
|
42
|
+
"classes": os.path.join(opts.root, opts.target_classes),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if opts.backup:
|
|
46
|
+
utils.ensure_backups(list(targets.values()) + [os.path.join(opts.root, "__init__.py")])
|
|
47
|
+
|
|
48
|
+
utils.write_file(targets["funcs"], func_content, dry_run=(opts.mode == "dry-run"))
|
|
49
|
+
utils.write_file(targets["consts"], const_content, dry_run=(opts.mode == "dry-run"))
|
|
50
|
+
utils.write_file(targets["classes"], class_content, dry_run=(opts.mode == "dry-run"))
|
|
51
|
+
|
|
52
|
+
write_top_init(all_funcs, all_consts, all_classes, opts, dry_run=(opts.mode == "dry-run"))
|
|
53
|
+
|
|
54
|
+
if opts.format and not (opts.mode == "dry-run"):
|
|
55
|
+
for t in targets.values():
|
|
56
|
+
utils.try_format(t)
|
|
57
|
+
utils.try_format(os.path.join(opts.root, "__init__.py"))
|
|
58
|
+
|
|
59
|
+
def run_merge(opts: Options):
|
|
60
|
+
# recursive scan; move everything into top-level modules
|
|
61
|
+
py_files = utils.list_py_files(opts.root, recursive=True)
|
|
62
|
+
# skip the generated top-level targets and their backups
|
|
63
|
+
skip = {os.path.join(opts.root, "__init__.py"),
|
|
64
|
+
os.path.join(opts.root, opts.target_funcs),
|
|
65
|
+
os.path.join(opts.root, opts.target_consts),
|
|
66
|
+
os.path.join(opts.root, opts.target_classes)}
|
|
67
|
+
paths = [p for p in py_files if os.path.abspath(p) not in {os.path.abspath(s) for s in skip}]
|
|
68
|
+
all_funcs, all_consts, all_classes, file_map = movers.collect_from_files(paths)
|
|
69
|
+
|
|
70
|
+
if opts.verbose:
|
|
71
|
+
print("Found functions:", all_funcs)
|
|
72
|
+
print("Found constants:", all_consts)
|
|
73
|
+
print("Found classes:", all_classes)
|
|
74
|
+
|
|
75
|
+
func_content, const_content, class_content, _, _, _ = movers.build_top_level_modules(file_map)
|
|
76
|
+
targets = {
|
|
77
|
+
"funcs": os.path.join(opts.root, opts.target_funcs),
|
|
78
|
+
"consts": os.path.join(opts.root, opts.target_consts),
|
|
79
|
+
"classes": os.path.join(opts.root, opts.target_classes),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if opts.backup:
|
|
83
|
+
utils.ensure_backups(list(targets.values()) + [os.path.join(opts.root, "__init__.py")])
|
|
84
|
+
|
|
85
|
+
# overwrite mode for merge (we want a single merged file)
|
|
86
|
+
utils.overwrite_file(targets["funcs"], func_content, dry_run=(opts.mode == "dry-run"))
|
|
87
|
+
utils.overwrite_file(targets["consts"], const_content, dry_run=(opts.mode == "dry-run"))
|
|
88
|
+
utils.overwrite_file(targets["classes"], class_content, dry_run=(opts.mode == "dry-run"))
|
|
89
|
+
|
|
90
|
+
write_top_init(all_funcs, all_consts, all_classes, opts, dry_run=(opts.mode == "dry-run"))
|
|
91
|
+
|
|
92
|
+
if opts.format and not (opts.mode == "dry-run"):
|
|
93
|
+
for t in targets.values():
|
|
94
|
+
utils.try_format(t)
|
|
95
|
+
utils.try_format(os.path.join(opts.root, "__init__.py"))
|
|
96
|
+
|
|
97
|
+
def run_subpkg(opts: Options):
|
|
98
|
+
# recursively create per-subpackage modules
|
|
99
|
+
py_files = utils.list_py_files(opts.root, recursive=True)
|
|
100
|
+
skip = {os.path.join(opts.root, "__init__.py")}
|
|
101
|
+
paths = [p for p in py_files if os.path.abspath(p) not in {os.path.abspath(s) for s in skip}]
|
|
102
|
+
all_funcs, all_consts, all_classes, file_map = movers.collect_from_files(paths)
|
|
103
|
+
|
|
104
|
+
pkg_map = movers.build_subpkg_modules(opts.root, file_map)
|
|
105
|
+
# For each package (key=relpath), write files into that package folder
|
|
106
|
+
written_items = {"funcs": [], "consts": [], "classes": []}
|
|
107
|
+
for pkg, (func_content, const_content, class_content, buckets) in pkg_map.items():
|
|
108
|
+
# pkg == "" means top-level root
|
|
109
|
+
folder = os.path.join(opts.root, pkg) if pkg else opts.root
|
|
110
|
+
func_target = os.path.join(folder, opts.target_funcs)
|
|
111
|
+
const_target = os.path.join(folder, opts.target_consts)
|
|
112
|
+
class_target = os.path.join(folder, opts.target_classes)
|
|
113
|
+
if opts.backup:
|
|
114
|
+
utils.ensure_backups([func_target, const_target, class_target, os.path.join(folder, "__init__.py")])
|
|
115
|
+
utils.write_file(func_target, func_content, dry_run=(opts.mode == "dry-run"))
|
|
116
|
+
utils.write_file(const_target, const_content, dry_run=(opts.mode == "dry-run"))
|
|
117
|
+
utils.write_file(class_target, class_content, dry_run=(opts.mode == "dry-run"))
|
|
118
|
+
# try to update that package's __init__.py to re-export
|
|
119
|
+
items = []
|
|
120
|
+
if buckets["funcs"]:
|
|
121
|
+
items.extend([n for n, _ in buckets["funcs"]])
|
|
122
|
+
if buckets["consts"]:
|
|
123
|
+
items.extend([n for n, _ in buckets["consts"]])
|
|
124
|
+
if buckets["classes"]:
|
|
125
|
+
items.extend([n for n, _ in buckets["classes"]])
|
|
126
|
+
if items:
|
|
127
|
+
imports = []
|
|
128
|
+
if buckets["funcs"]:
|
|
129
|
+
imports.append(f"from .{os.path.splitext(opts.target_funcs)[0]} import " + ", ".join([n for n, _ in buckets["funcs"]]))
|
|
130
|
+
if buckets["consts"]:
|
|
131
|
+
imports.append(f"from .{os.path.splitext(opts.target_consts)[0]} import " + ", ".join([n for n, _ in buckets["consts"]]))
|
|
132
|
+
if buckets["classes"]:
|
|
133
|
+
imports.append(f"from .{os.path.splitext(opts.target_classes)[0]} import " + ", ".join([n for n, _ in buckets["classes"]]))
|
|
134
|
+
content = "\n".join(imports) + "\n\n__all__ = " + movers.make_all_list(items) + "\n"
|
|
135
|
+
utils.overwrite_file(os.path.join(folder, "__init__.py"), content, dry_run=(opts.mode == "dry-run"))
|
|
136
|
+
written_items["funcs"].extend([n for n, _ in buckets["funcs"]])
|
|
137
|
+
written_items["consts"].extend([n for n, _ in buckets["consts"]])
|
|
138
|
+
written_items["classes"].extend([n for n, _ in buckets["classes"]])
|
|
139
|
+
|
|
140
|
+
# do NOT modify top-level __init__.py here (unless top-level items were present)
|
|
141
|
+
# If top-level items found (pkg == ""), ensure exported in top-level __init__
|
|
142
|
+
top_buckets = pkg_map.get("", None)
|
|
143
|
+
if top_buckets:
|
|
144
|
+
_, _, _, buckets = top_buckets
|
|
145
|
+
if buckets and (buckets["funcs"] or buckets["consts"] or buckets["classes"]):
|
|
146
|
+
write_top_init([n for n, _ in buckets["funcs"]],
|
|
147
|
+
[n for n, _ in buckets["consts"]],
|
|
148
|
+
[n for n, _ in buckets["classes"]],
|
|
149
|
+
opts,
|
|
150
|
+
dry_run=(opts.mode == "dry-run"))
|
|
151
|
+
|
|
152
|
+
if opts.format and not (opts.mode == "dry-run"):
|
|
153
|
+
# format all generated files by scanning pkg_map locations
|
|
154
|
+
for pkg in pkg_map:
|
|
155
|
+
folder = os.path.join(opts.root, pkg) if pkg else opts.root
|
|
156
|
+
utils.try_format(os.path.join(folder, opts.target_funcs))
|
|
157
|
+
utils.try_format(os.path.join(folder, opts.target_consts))
|
|
158
|
+
utils.try_format(os.path.join(folder, opts.target_classes))
|
|
159
|
+
|
|
160
|
+
def run(opts: Options):
|
|
161
|
+
# central dispatcher
|
|
162
|
+
if opts.undo:
|
|
163
|
+
# restore backups for common files
|
|
164
|
+
targets = [os.path.join(opts.root, opts.target_funcs),
|
|
165
|
+
os.path.join(opts.root, opts.target_consts),
|
|
166
|
+
os.path.join(opts.root, opts.target_classes),
|
|
167
|
+
os.path.join(opts.root, "__init__.py")]
|
|
168
|
+
restored = utils.restore_backups(targets)
|
|
169
|
+
if opts.verbose:
|
|
170
|
+
print("Restored:", restored)
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
if opts.mode == "small":
|
|
174
|
+
run_small(opts)
|
|
175
|
+
elif opts.mode == "merge":
|
|
176
|
+
run_merge(opts)
|
|
177
|
+
elif opts.mode == "subpkg":
|
|
178
|
+
run_subpkg(opts)
|
|
179
|
+
elif opts.mode == "dry-run":
|
|
180
|
+
# shrink to dry-run variants of merge (simulate)
|
|
181
|
+
opts = opts.__class__(**{**opts.__dict__, "mode": "dry-run"})
|
|
182
|
+
run_merge(opts)
|
|
183
|
+
else:
|
|
184
|
+
raise ValueError("Unknown mode: " + str(opts.mode))
|
refactor_utils/movers.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import os
|
|
3
|
+
from typing import List, Tuple
|
|
4
|
+
|
|
5
|
+
# helper: extract code snippet by lineno
|
|
6
|
+
def _get_block(source_lines: List[str], node) -> str:
|
|
7
|
+
start = node.lineno - 1
|
|
8
|
+
end = getattr(node, "end_lineno", None)
|
|
9
|
+
if end is None:
|
|
10
|
+
# fallback (older Python) — collect until next blank line (best-effort)
|
|
11
|
+
end = start + 1
|
|
12
|
+
while end < len(source_lines) and source_lines[end].strip() != "":
|
|
13
|
+
end += 1
|
|
14
|
+
return "\n".join(source_lines[start:end]) + "\n"
|
|
15
|
+
|
|
16
|
+
def parse_top_level_items(path: str):
|
|
17
|
+
"""
|
|
18
|
+
Parse a python file and return lists of (name, code) for:
|
|
19
|
+
- functions (top-level)
|
|
20
|
+
- constants (top-level UPPERCASE assignments)
|
|
21
|
+
- classes (top-level)
|
|
22
|
+
"""
|
|
23
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
24
|
+
src = f.read()
|
|
25
|
+
tree = ast.parse(src)
|
|
26
|
+
lines = src.splitlines()
|
|
27
|
+
funcs = []
|
|
28
|
+
consts = []
|
|
29
|
+
classes = []
|
|
30
|
+
for node in tree.body:
|
|
31
|
+
if isinstance(node, ast.FunctionDef):
|
|
32
|
+
funcs.append((node.name, _get_block(lines, node)))
|
|
33
|
+
elif isinstance(node, ast.ClassDef):
|
|
34
|
+
classes.append((node.name, _get_block(lines, node)))
|
|
35
|
+
elif isinstance(node, ast.Assign):
|
|
36
|
+
# only simple name target
|
|
37
|
+
if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
|
|
38
|
+
name = node.targets[0].id
|
|
39
|
+
if name.isupper():
|
|
40
|
+
consts.append((name, _get_block(lines, node)))
|
|
41
|
+
return funcs, consts, classes
|
|
42
|
+
|
|
43
|
+
def collect_from_files(paths: List[str]):
|
|
44
|
+
"""Collect items across many files. Returns aggregated lists and a map by file."""
|
|
45
|
+
all_funcs = []
|
|
46
|
+
all_consts = []
|
|
47
|
+
all_classes = []
|
|
48
|
+
file_map = {}
|
|
49
|
+
for p in paths:
|
|
50
|
+
try:
|
|
51
|
+
funcs, consts, classes = parse_top_level_items(p)
|
|
52
|
+
except SyntaxError:
|
|
53
|
+
funcs, consts, classes = [], [], []
|
|
54
|
+
file_map[p] = {"funcs": funcs, "consts": consts, "classes": classes}
|
|
55
|
+
all_funcs.extend([name for name, _ in funcs])
|
|
56
|
+
all_consts.extend([name for name, _ in consts])
|
|
57
|
+
all_classes.extend([name for name, _ in classes])
|
|
58
|
+
return all_funcs, all_consts, all_classes, file_map
|
|
59
|
+
|
|
60
|
+
def make_all_list(names: List[str]) -> str:
|
|
61
|
+
# return a python list literal with stable ordering
|
|
62
|
+
uniq = sorted(dict.fromkeys(names))
|
|
63
|
+
return "[" + ", ".join(f"'{n}'" for n in uniq) + "]"
|
|
64
|
+
|
|
65
|
+
def build_top_level_modules(file_map, dry_run=False, targets=None):
|
|
66
|
+
"""
|
|
67
|
+
Merge all found codeblocks into top-level modules (for `merge` and `small`).
|
|
68
|
+
`targets` is dict with keys: funcs, consts, classes (file paths).
|
|
69
|
+
"""
|
|
70
|
+
targets = targets or {}
|
|
71
|
+
func_blocks = []
|
|
72
|
+
const_blocks = []
|
|
73
|
+
class_blocks = []
|
|
74
|
+
|
|
75
|
+
for p, buckets in file_map.items():
|
|
76
|
+
func_blocks.extend(buckets["funcs"])
|
|
77
|
+
const_blocks.extend(buckets["consts"])
|
|
78
|
+
class_blocks.extend(buckets["classes"])
|
|
79
|
+
|
|
80
|
+
# produce content strings
|
|
81
|
+
func_content = "# auto-generated by refactor_utils\n\n"
|
|
82
|
+
for _, block in func_blocks:
|
|
83
|
+
func_content += block + "\n"
|
|
84
|
+
|
|
85
|
+
const_content = "# auto-generated constants\n\n"
|
|
86
|
+
for _, block in const_blocks:
|
|
87
|
+
const_content += block + "\n"
|
|
88
|
+
|
|
89
|
+
class_content = "# auto-generated classes\n\n"
|
|
90
|
+
for _, block in class_blocks:
|
|
91
|
+
class_content += block + "\n"
|
|
92
|
+
|
|
93
|
+
return func_content, const_content, class_content, func_blocks, const_blocks, class_blocks
|
|
94
|
+
|
|
95
|
+
def build_subpkg_modules(root: str, file_map, dry_run=False, targets=None):
|
|
96
|
+
"""
|
|
97
|
+
For `subpkg` mode: create per-subpackage myutil/constants/classes.
|
|
98
|
+
We'll group files by their package path (folder relative to root).
|
|
99
|
+
"""
|
|
100
|
+
grouped = {}
|
|
101
|
+
for path, buckets in file_map.items():
|
|
102
|
+
# determine immediate package folder relative to root
|
|
103
|
+
rel = os.path.relpath(os.path.dirname(path), root)
|
|
104
|
+
key = rel if rel != "." else ""
|
|
105
|
+
grouped.setdefault(key, {"funcs": [], "consts": [], "classes": []})
|
|
106
|
+
grouped[key]["funcs"].extend(buckets["funcs"])
|
|
107
|
+
grouped[key]["consts"].extend(buckets["consts"])
|
|
108
|
+
grouped[key]["classes"].extend(buckets["classes"])
|
|
109
|
+
|
|
110
|
+
# produce map: package -> (func_content, const_content, class_content)
|
|
111
|
+
out = {}
|
|
112
|
+
for pkg, buckets in grouped.items():
|
|
113
|
+
func_content = "# auto-generated for package: %s\n\n" % (pkg or "top")
|
|
114
|
+
for _, block in buckets["funcs"]:
|
|
115
|
+
func_content += block + "\n"
|
|
116
|
+
const_content = "# auto-generated constants for %s\n\n" % (pkg or "top")
|
|
117
|
+
for _, block in buckets["consts"]:
|
|
118
|
+
const_content += block + "\n"
|
|
119
|
+
class_content = "# auto-generated classes for %s\n\n" % (pkg or "top")
|
|
120
|
+
for _, block in buckets["classes"]:
|
|
121
|
+
class_content += block + "\n"
|
|
122
|
+
out[pkg] = (func_content, const_content, class_content, buckets)
|
|
123
|
+
return out
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
@dataclass(frozen=True)
|
|
4
|
+
class Options:
|
|
5
|
+
mode: str # 'small' | 'merge' | 'subpkg' | 'dry-run'
|
|
6
|
+
root: str = "."
|
|
7
|
+
backup: bool = True
|
|
8
|
+
format: bool = True
|
|
9
|
+
target_funcs: str = "myutil.py"
|
|
10
|
+
target_consts: str = "constants.py"
|
|
11
|
+
target_classes: str = "classes.py"
|
|
12
|
+
verbose: bool = True
|
|
13
|
+
undo: bool = False
|
refactor_utils/utils.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
import subprocess
|
|
4
|
+
from typing import List, Tuple
|
|
5
|
+
|
|
6
|
+
BACKUP_SUFFIX = ".bak"
|
|
7
|
+
|
|
8
|
+
def list_py_files(root: str, recursive: bool = True):
|
|
9
|
+
py_files = []
|
|
10
|
+
for dirpath, _, filenames in os.walk(root):
|
|
11
|
+
for fname in filenames:
|
|
12
|
+
if not fname.endswith(".py"):
|
|
13
|
+
continue
|
|
14
|
+
# skip backup files and package installer artifacts
|
|
15
|
+
if fname.endswith(BACKUP_SUFFIX + ".py"):
|
|
16
|
+
continue
|
|
17
|
+
full = os.path.join(dirpath, fname)
|
|
18
|
+
# skip typical virtual env folders if present
|
|
19
|
+
if "/.venv/" in full or "/venv/" in full:
|
|
20
|
+
continue
|
|
21
|
+
py_files.append(full)
|
|
22
|
+
if not recursive:
|
|
23
|
+
break
|
|
24
|
+
return py_files
|
|
25
|
+
|
|
26
|
+
def ensure_backups(paths: List[str]):
|
|
27
|
+
for p in paths:
|
|
28
|
+
if os.path.exists(p):
|
|
29
|
+
shutil.copy2(p, p + BACKUP_SUFFIX)
|
|
30
|
+
|
|
31
|
+
def restore_backups(paths: List[str]):
|
|
32
|
+
restored = []
|
|
33
|
+
for p in paths:
|
|
34
|
+
bak = p + BACKUP_SUFFIX
|
|
35
|
+
if os.path.exists(bak):
|
|
36
|
+
shutil.copy2(bak, p)
|
|
37
|
+
restored.append(p)
|
|
38
|
+
return restored
|
|
39
|
+
|
|
40
|
+
def try_format(path: str):
|
|
41
|
+
if not os.path.exists(path):
|
|
42
|
+
return False
|
|
43
|
+
# try ruff first
|
|
44
|
+
try:
|
|
45
|
+
subprocess.run(["ruff", "format", path], check=False)
|
|
46
|
+
except Exception:
|
|
47
|
+
pass
|
|
48
|
+
# fall back to yapf
|
|
49
|
+
try:
|
|
50
|
+
subprocess.run(["yapf", "-i", path], check=False)
|
|
51
|
+
except Exception:
|
|
52
|
+
pass
|
|
53
|
+
return True
|
|
54
|
+
|
|
55
|
+
def write_file(path: str, content: str, dry_run: bool):
|
|
56
|
+
if dry_run:
|
|
57
|
+
return
|
|
58
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
59
|
+
with open(path, "a", encoding="utf-8") as f:
|
|
60
|
+
f.write(content)
|
|
61
|
+
|
|
62
|
+
def overwrite_file(path: str, content: str, dry_run: bool):
|
|
63
|
+
if dry_run:
|
|
64
|
+
return
|
|
65
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
66
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
67
|
+
f.write(content)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: refactor_utils
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Utilities to refactor small python packages: extract funcs/constants/classes into modules
|
|
5
|
+
Author-email: You <you@example.com>
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
|
|
9
|
+
# refactor_utils
|
|
10
|
+
|
|
11
|
+
Small utility to reorganize small Python packages.
|
|
12
|
+
|
|
13
|
+
Install locally:
|
|
14
|
+
```bash
|
|
15
|
+
pip install -e .pyrefactor run --mode small
|
|
16
|
+
pyrefactor run --mode merge
|
|
17
|
+
pyrefactor run --mode subpkg
|
|
18
|
+
pyrefactor run --mode dry-run
|
|
19
|
+
pyrefactor run --mode merge --undo
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
after install
|
|
23
|
+
goto project dir abd run:
|
|
24
|
+
|
|
25
|
+
pyrefactor run --mode dry-run --root path/to/yourpkg
|
|
26
|
+
|
|
27
|
+
pyrefactor run --mode merge --root path/to/yourpkg
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
refactor_utils/__init__.py,sha256=IvBmjcEqtVtvZlWGKFNNWmeg3Ol1_UHxFsZJ4dp263Y,452
|
|
2
|
+
refactor_utils/cli.py,sha256=CU8-qxRbvoZ6LQx117Wx2qW7buNl78SDEj3vQN9u-UA,1650
|
|
3
|
+
refactor_utils/core.py,sha256=SWXz4v9rMsoeg64lN9vi5IVb_UhiVOAuFwmyfRD1Oa4,9259
|
|
4
|
+
refactor_utils/movers.py,sha256=U535-ZbZMGxMlIdEQqv-e16wf3Imjm-h9_Gpg6x7jB8,4791
|
|
5
|
+
refactor_utils/options.py,sha256=pvBZK5imWgyTrRt8Fkyv02p9nKZgyGhCAa7rXNsRtVg,362
|
|
6
|
+
refactor_utils/utils.py,sha256=kADqkvLKgSoiez4PtsoBEtLK6R_B_GQqN_W1_I0rBFU,1905
|
|
7
|
+
refactor_utils-0.1.0.dist-info/METADATA,sha256=_x_FvCrag3ZiDNlcQGagU_tsk9VaUDblw-QvdzdUwIk,676
|
|
8
|
+
refactor_utils-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
9
|
+
refactor_utils-0.1.0.dist-info/entry_points.txt,sha256=QjdAS1RWnvOm42Io1yMEqc9hFTZZVgsIIaRyZYpQzCw,55
|
|
10
|
+
refactor_utils-0.1.0.dist-info/top_level.txt,sha256=_VNHwV1GnWF7XVetu99g049WM_BbBVpWOgodNiPHnN4,15
|
|
11
|
+
refactor_utils-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
refactor_utils
|