Engine split step 7: engine_cut.py and its paint split (paint modules to crates/engine-paint/src)

This commit is contained in:
aiongg committed 2026-11-23 14:06:43 +00:00
1 parent b0b1718695
commit 1086d71fd9
94 files changed
+731 -48

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
# Engine split (photocraft#15710): the crate each engine module goes to. A unit is a module of
# crates/engine-core/src: `cmd/<name>` for one declared in cmd.rs, `<name>` for one declared in lib.rs.
# Its files are the module's file and every file its `mod` declarations reach. scripts/engine_split/engine_cut.py reads it. A module not listed stays in core.
unit crate
actions_record core
adjust_params model
allocation core
build_info core
canvas_geom model
channel_clip model
clip_group core
cmd/actions_cmds files
cmd/actions_edit_cmds files
cmd/adjust_cmds image
cmd/adjust_params model
cmd/adjustment_brush_cmds paint
cmd/adjustment_brush_cmds_tests paint
cmd/align_cmds vector
cmd/analysis_cmds image
cmd/artboard_cmds model
cmd/atn_cmds files
cmd/automate_cmds files
cmd/background_cmds model
cmd/brush_cmds paint
cmd/brush_key_cmds paint
cmd/brush_preset_cmds store
cmd/channel_cmds model
cmd/color_cmds model
cmd/color_to_alpha_cmds image
cmd/comps_cmds vector
cmd/contour_lib_cmds store
cmd/cutout_cmds image
cmd/distort_cmds image
cmd/document_preset_cmds store
cmd/edit_cmds model
cmd/edit_menu_cmds image
cmd/enabled core
cmd/eraser_cmds paint
cmd/export_preset_cmds store
cmd/exr_cmds files
cmd/extra_cmds image
cmd/face_cmds paint
cmd/file_cmds files
cmd/fill_cmds paint
cmd/fill_key_cmds paint
cmd/float_cmds vector
cmd/font_library_cmds store
cmd/frame_cmds vector
cmd/fx_view_cmds store
cmd/fx_visibility_cmds store
cmd/gallery_cmds image
cmd/gradient_fill_cmds store
cmd/group_view_cmds image
cmd/history_cmds model
cmd/history_menu_cmds model
cmd/history_options_cmds model
cmd/history_select_cmds model
cmd/history_source_cmds model
cmd/image_cmds image
cmd/layer_copy_cmds model
cmd/layer_css_cmds vector
cmd/layer_label_cmds image
cmd/layer_list_cmds image
cmd/layer_mask_props_cmds image
cmd/layer_menu_cmds image
cmd/layer_multi_cmds model
cmd/layer_nav_cmds image
cmd/layer_params core
cmd/layer_references core
cmd/layer_xmp_cmds vector
cmd/lens_cmds image
cmd/magnetic_cmds image
cmd/mask_view_cmds model
cmd/migrate_cmds store
cmd/mode_cmds image
cmd/multichannel_cmds image
cmd/notes_cmds vector
cmd/ops core
cmd/paint_cmds paint
cmd/params core
cmd/path_edit_cmds vector
cmd/pattern_cmds store
cmd/pattern_fill_cmds store
cmd/perspective_crop_cmds image
cmd/photo_cmds image
cmd/pick_cmds paint
cmd/plugin_cmds image
cmd/preset_import_cmds store
cmd/print_cmds files
cmd/rasterize_style_cmds vector
cmd/redeye_cmds paint
cmd/render_cmds image
cmd/retouch_cmds paint
cmd/sample_cmds model
cmd/sampler_cmds paint
cmd/select_extra_cmds image
cmd/selection_cmds image
cmd/slice_cmds vector
cmd/smart_cmds vector
cmd/smart_svg_cmds vector
cmd/smartselect_cmds image
cmd/solid_fill_cmds store
cmd/stamp_cmds paint
cmd/style_asl_cmds store
cmd/swatch_cmds store
cmd/symmetry_cmds vector
cmd/timeline_cmds files
cmd/transform_cmds vector
cmd/trap_cmds vector
cmd/type_area_cmds vector
cmd/type_caret_cmds vector
cmd/type_cmds vector
cmd/type_extra_cmds vector
cmd/type_mask_cmds vector
cmd/type_spell_cmds vector
cmd/type_styles_cmds vector
cmd/variables_cmds files
cmd/vector_clipboard model
cmd/vector_cmds vector
cmd/video_cmds files
cmd/vp_cmds image
cmd/warp_cmds vector
cmd/web_cmds files
cmd/wia_cmds files
color_channels model
command_hints core
crop_fill image
display_color model
doc_path core
doc_state core
error core
filters image
filters_ext image
group_options core
guide_layout core
hidden_target core
inspect core
installed_profiles core
jobs core
keymap_defs store
layer_place core
layer_style store
link_watch model
malloc_tuning core
memory core
memory_gate core
new_layer core
param_check core
pixels core
prefs store
preset_store store
presets store
proof_sim model
scratch core
select_mask_edits image
session core
shell_commands core
shortcut_sets store
snap core
cmd/table/paint paint
cmd/table/image image
cmd/table/model model
cmd/table/store store
pixel_fill core
content_sampling model
brush_defs store
brush_clear_background_tests paint
brush_pressure_size_default_tests paint
eraser_gray_background_tests paint
pencil_auto_erase_exact_tests paint
mixer_indexed_bitmap_tests paint
mixer_toggle_commands_tests paint
cmd/gradient_alpha_method_tests paint
action_history core
damage core
slots core
state core
install core
registry core
hooks core
1 # Engine split (photocraft#15710): the crate each engine module goes to. A unit is a module of
2 # crates/engine-core/src: `cmd/<name>` for one declared in cmd.rs, `<name>` for one declared in lib.rs.
3 # Its files are the module's file and every file its `mod` declarations reach. scripts/engine_split/engine_cut.py reads it. A module not listed stays in core.
4 unit crate
5 actions_record core
6 adjust_params model
7 allocation core
8 build_info core
9 canvas_geom model
10 channel_clip model
11 clip_group core
12 cmd/actions_cmds files
13 cmd/actions_edit_cmds files
14 cmd/adjust_cmds image
15 cmd/adjust_params model
16 cmd/adjustment_brush_cmds paint
17 cmd/adjustment_brush_cmds_tests paint
18 cmd/align_cmds vector
19 cmd/analysis_cmds image
20 cmd/artboard_cmds model
21 cmd/atn_cmds files
22 cmd/automate_cmds files
23 cmd/background_cmds model
24 cmd/brush_cmds paint
25 cmd/brush_key_cmds paint
26 cmd/brush_preset_cmds store
27 cmd/channel_cmds model
28 cmd/color_cmds model
29 cmd/color_to_alpha_cmds image
30 cmd/comps_cmds vector
31 cmd/contour_lib_cmds store
32 cmd/cutout_cmds image
33 cmd/distort_cmds image
34 cmd/document_preset_cmds store
35 cmd/edit_cmds model
36 cmd/edit_menu_cmds image
37 cmd/enabled core
38 cmd/eraser_cmds paint
39 cmd/export_preset_cmds store
40 cmd/exr_cmds files
41 cmd/extra_cmds image
42 cmd/face_cmds paint
43 cmd/file_cmds files
44 cmd/fill_cmds paint
45 cmd/fill_key_cmds paint
46 cmd/float_cmds vector
47 cmd/font_library_cmds store
48 cmd/frame_cmds vector
49 cmd/fx_view_cmds store
50 cmd/fx_visibility_cmds store
51 cmd/gallery_cmds image
52 cmd/gradient_fill_cmds store
53 cmd/group_view_cmds image
54 cmd/history_cmds model
55 cmd/history_menu_cmds model
56 cmd/history_options_cmds model
57 cmd/history_select_cmds model
58 cmd/history_source_cmds model
59 cmd/image_cmds image
60 cmd/layer_copy_cmds model
61 cmd/layer_css_cmds vector
62 cmd/layer_label_cmds image
63 cmd/layer_list_cmds image
64 cmd/layer_mask_props_cmds image
65 cmd/layer_menu_cmds image
66 cmd/layer_multi_cmds model
67 cmd/layer_nav_cmds image
68 cmd/layer_params core
69 cmd/layer_references core
70 cmd/layer_xmp_cmds vector
71 cmd/lens_cmds image
72 cmd/magnetic_cmds image
73 cmd/mask_view_cmds model
74 cmd/migrate_cmds store
75 cmd/mode_cmds image
76 cmd/multichannel_cmds image
77 cmd/notes_cmds vector
78 cmd/ops core
79 cmd/paint_cmds paint
80 cmd/params core
81 cmd/path_edit_cmds vector
82 cmd/pattern_cmds store
83 cmd/pattern_fill_cmds store
84 cmd/perspective_crop_cmds image
85 cmd/photo_cmds image
86 cmd/pick_cmds paint
87 cmd/plugin_cmds image
88 cmd/preset_import_cmds store
89 cmd/print_cmds files
90 cmd/rasterize_style_cmds vector
91 cmd/redeye_cmds paint
92 cmd/render_cmds image
93 cmd/retouch_cmds paint
94 cmd/sample_cmds model
95 cmd/sampler_cmds paint
96 cmd/select_extra_cmds image
97 cmd/selection_cmds image
98 cmd/slice_cmds vector
99 cmd/smart_cmds vector
100 cmd/smart_svg_cmds vector
101 cmd/smartselect_cmds image
102 cmd/solid_fill_cmds store
103 cmd/stamp_cmds paint
104 cmd/style_asl_cmds store
105 cmd/swatch_cmds store
106 cmd/symmetry_cmds vector
107 cmd/timeline_cmds files
108 cmd/transform_cmds vector
109 cmd/trap_cmds vector
110 cmd/type_area_cmds vector
111 cmd/type_caret_cmds vector
112 cmd/type_cmds vector
113 cmd/type_extra_cmds vector
114 cmd/type_mask_cmds vector
115 cmd/type_spell_cmds vector
116 cmd/type_styles_cmds vector
117 cmd/variables_cmds files
118 cmd/vector_clipboard model
119 cmd/vector_cmds vector
120 cmd/video_cmds files
121 cmd/vp_cmds image
122 cmd/warp_cmds vector
123 cmd/web_cmds files
124 cmd/wia_cmds files
125 color_channels model
126 command_hints core
127 crop_fill image
128 display_color model
129 doc_path core
130 doc_state core
131 error core
132 filters image
133 filters_ext image
134 group_options core
135 guide_layout core
136 hidden_target core
137 inspect core
138 installed_profiles core
139 jobs core
140 keymap_defs store
141 layer_place core
142 layer_style store
143 link_watch model
144 malloc_tuning core
145 memory core
146 memory_gate core
147 new_layer core
148 param_check core
149 pixels core
150 prefs store
151 preset_store store
152 presets store
153 proof_sim model
154 scratch core
155 select_mask_edits image
156 session core
157 shell_commands core
158 shortcut_sets store
159 snap core
160 cmd/table/paint paint
161 cmd/table/image image
162 cmd/table/model model
163 cmd/table/store store
164 pixel_fill core
165 content_sampling model
166 brush_defs store
167 brush_clear_background_tests paint
168 brush_pressure_size_default_tests paint
169 eraser_gray_background_tests paint
170 pencil_auto_erase_exact_tests paint
171 mixer_indexed_bitmap_tests paint
172 mixer_toggle_commands_tests paint
173 cmd/gradient_alpha_method_tests paint
174 action_history core
175 damage core
176 slots core
177 state core
178 install core
179 registry core
180 hooks core
+533
View File
@@ -0,0 +1,533 @@
#!/usr/bin/env python3
"""Engine split, steps 7-12: cut one engine crate out of `photocraft-engine-core`.
`scripts/engine_split/crates.tsv` names the crate of each engine module. A cut moves the modules of
one crate, with every file their `mod` declarations reach, from `crates/engine-core/src` to the same
paths under `crates/engine-<crate>/src`, so git's rename detection carries edits to them.
python3 scripts/engine_split/engine_cut.py split <crate>
On the day's main: `git mv` the crate's files, drop their declarations from core's `lib.rs`,
`cmd.rs` and `cmd/table.rs`, and in the moved files point `crate::cmd::<core item>` at
`crate::commands::<core item>` (the crate's own `cmd` module holds only its modules). Calls of
`Session` methods that became the crate's traits get the trait's import (TRAITS). The
hand-written part of the step (the crate's Cargo.toml, lib.rs, cmd.rs, install.rs, the
install lists, tooling) is its own commit, cherry-picked after this one.
python3 scripts/engine_split/engine_cut.py imports <crate>
Prints the import block the crate's root needs: every name its code reaches as `crate::x`
that the crate doesn't define, so moved code compiles without path edits.
python3 scripts/engine_split/engine_cut.py branch <crate> --base <merge-base> --head <branch>
On a branch rebased onto the cut (`--head` is the branch from before the rebase, `ORIG_HEAD`
right after it):
- moves files the branch added under core that belong to the crate's modules (new files in
a directory that still exists in core, such as `cmd/`, stay where git put them);
- moves `mod` lines the branch added to core's `cmd.rs`/`lib.rs` for the crate's modules,
and `TABLES` entries it added to core's `install.rs` naming them, into the crate's files;
- adds the import-block names the branch's moved code needs;
- adds trait imports for the trait methods it calls;
- lists, as NOT DONE, tests the branch added or edited in core that run one of the
crate's command ids: core installs only its own commands, so they fail at run time
with `UnknownCommand` and belong in the top crate's `tests/it`.
cargo check --message-format json ... | python3 scripts/engine_split/engine_cut.py fix
Widens to `pub` each core item the compiler reports as private where another engine crate
uses it (E0603, E0624, and E0616 when the note names the field).
Running split or branch twice gives the same result. What it cannot do is printed at the end.
"""
import argparse, json, os, re, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from rust_source import MOD_DECL, compiled_files, git, git_show, inline_mods, mask, module_file # noqa: E402
CORE = "crates/engine-core/src"
MAP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "crates.tsv")
ROOTS = ["crates", "apps"]
# Session methods that became a crate's extension traits at its cut: method -> (module, trait).
TRAITS = {
"paint": {
"offer_live_stroke": ("brush_cmds", "LiveStrokeExt"),
"offer_live_retouch": ("retouch_cmds", "LiveRetouchExt"),
"offer_live_dab": ("retouch_cmds", "LiveRetouchExt"),
},
}
# Names a crate's root defines itself, which its import block must not bring from core.
OWN = {"cmd", "install", "session", "command_tables", "register"}
def crate_src(crate):
return f"crates/engine-{crate}/src"
def units(crate):
out = []
with open(MAP) as f:
for line in f:
if line.startswith("#") or line.startswith("unit\t") or not line.strip():
continue
u, c = line.rstrip("\n").split("\t")
if c == crate:
out.append(u)
return out
def unit_root(u, src=CORE):
for f in (f"{src}/{u}.rs", f"{src}/{u}/mod.rs"):
if os.path.isfile(f):
return f
return None
def reach(root):
"""`root` and every file its `mod` declarations reach."""
seen, todo = [], [root]
while todo:
f = todo.pop()
if f in seen:
continue
seen.append(f)
src = open(f).read()
m = mask(src)
for d in MOD_DECL.finditer(m):
child = module_file(f, d.group(2), src[d.start(1) : d.end(1)], [dir_ for dir_, _ in inline_mods(src, m, d.start())])
if child:
todo.append(os.path.normpath(child))
return seen
def crate_files(crate, src=CORE):
files = []
for u in units(crate):
r = unit_root(u, src)
if r:
files += [f for f in reach(r) if f not in files]
return files
def read(path):
with open(path, encoding="utf-8") as f:
return f.read()
def write(path, text):
with open(path, "w", encoding="utf-8") as f:
f.write(text)
def decl_re(name):
"""A declaration line of module `name` with its attributes, or a `pub use cmd::name;` line."""
return re.compile(r"^(?:[ \t]*#\[[^\n]*\]\n)*[ \t]*(?:pub(?:\([a-z]+\))?\s+)?(?:mod\s+" + name + r"\s*;|use\s+cmd::" + name + r"\s*;)[ \t]*\n", re.M)
def drop_decls(crate):
"""Removes the crate's module declarations from core's lib.rs, cmd.rs and cmd/table.rs."""
changed = []
for u in units(crate):
parts = u.split("/")
parent = {1: [f"{CORE}/lib.rs"], 2: [f"{CORE}/cmd.rs", f"{CORE}/lib.rs"], 3: [f"{CORE}/cmd/table.rs"]}[len(parts)]
for p in parent:
text = read(p)
new = decl_re(parts[-1]).sub("", text)
if new != text:
write(p, new)
changed.append(p)
return changed
def own_cmd_names(crate):
return {u.split("/")[1] for u in units(crate) if u.startswith("cmd/")} | {"table"}
CMD_PATH = re.compile(r"\bcrate::cmd::(\w+)")
CMD_USE = re.compile(r"\buse crate::cmd::\{")
SUPER_PATH = re.compile(r"(?<![A-Za-z0-9_:])super::(\w+)")
def point_cmd_at_core(text, crate, path=""):
"""`crate::cmd::x` for an x the crate doesn't hold becomes `crate::commands::x`, and so does
`super::x` in a module declared in `cmd.rs` (`cmd/<module>.rs`), whose parent was core's `cmd`."""
own = own_cmd_names(crate)
masked = mask(text)
edits = [(m.start(), m.end(), f"crate::commands::{m.group(1)}") for m in CMD_PATH.finditer(masked) if m.group(1) not in own]
if path in {f"{crate_src(crate)}/{u}.rs" for u in units(crate) if u.startswith("cmd/") and u.count("/") == 1}:
edits += [(m.start(), m.end(), f"crate::commands::{m.group(1)}") for m in SUPER_PATH.finditer(masked) if m.group(1) not in own and m.group(1) != "super"]
edits += [(m.start(), m.end(), "use crate::commands::{") for m in CMD_USE.finditer(masked)]
for s, e, r in sorted(edits, reverse=True):
text = text[:s] + r + text[e:]
return text
def rust_files(roots):
"""The .rs files under `roots` that some crate target compiles: a file no module reaches never
builds, and CI's unreached-rs guard flags any edit to it."""
return sorted(compiled_files(roots))
def tree_files(src):
"""Every .rs file under a crate's `src` (a crate cut by this script may not have its
Cargo.toml yet, so `compiled_files` can't reach it)."""
return sorted(os.path.join(d, n) for d, _, fs in os.walk(src) for n in fs if n.endswith(".rs"))
def trait_root(path, crate):
if path.startswith(crate_src(crate) + "/"):
return "crate"
if path.startswith(CORE + "/"):
return None # core can't name an upper crate's trait
return f"photocraft_engine_{crate}" if path.startswith(f"crates/engine-{crate}/") else "photocraft_engine"
def add_trait_imports(path, crate):
"""Adds `use <root>::<module>::<Trait>;` for each trait method the file calls."""
methods = TRAITS.get(crate, {})
if not methods:
return False
text = read(path)
masked = mask(text)
root = trait_root(path, crate)
needed = {}
for m in re.finditer(r"\.(" + "|".join(methods) + r")\s*\(", masked):
module, trait = methods[m.group(1)]
if re.search(r"\b(?:use|trait)\b[^;{]*\b" + trait + r"\b", masked):
continue
needed.setdefault(trait, (module, m.start()))
if not needed or root is None:
return False
for trait, (module, pos) in sorted(needed.items(), key=lambda x: -x[1][1]):
body = enclosing_mod(mask(text), pos)
line = f"use {root}::{module}::{trait};\n"
if body is not None:
nl = text.index("\n", body) + 1
indent = re.match(r"[ \t]*", text[nl:]).group(0)
text = text[:nl] + indent + line + text[nl:]
else:
um = re.search(r"^use ", mask(text), re.M)
at = um.start() if um else 0
text = text[:at] + line + text[at:]
write(path, text)
return True
def enclosing_mod(masked, pos):
from rust_source import block_end
best = None
for m in re.finditer(r"\bmod\s+\w+\s*\{", masked[:pos]):
if block_end(masked, m.start()) > pos:
best = m.end()
return best
def split(crate):
files = crate_files(crate)
if not files:
print(f"nothing of `{crate}` left in {CORE}")
for f in files:
dst = crate_src(crate) + f[len(CORE) :]
os.makedirs(os.path.dirname(dst), exist_ok=True)
git("mv", f, dst)
print(f"moved {len(files)} files to {crate_src(crate)}")
print("declarations dropped in:", ", ".join(sorted(set(drop_decls(crate)))) or "none")
finish(crate, tree_files(crate_src(crate)))
def finish(crate, moved):
n = 0
for f in moved:
text = read(f)
new = point_cmd_at_core(text, crate, f)
if new != text:
write(f, new)
n += 1
print(f"crate::cmd paths pointed at core's commands in {n} files")
t = sum(add_trait_imports(f, crate) for f in sorted(set(rust_files(ROOTS)) | set(moved)))
print(f"trait imports added in {t} files")
def import_names(crate, files=None):
"""(names the crate's code reaches as `crate::x` that it doesn't define, the subset only its
tests reach)."""
from rust_source import in_test, test_regions
lib = f"{crate_src(crate)}/lib.rs"
regions = test_regions(lib) if os.path.exists(lib) else {}
files = files if files is not None else tree_files(crate_src(crate))
own = OWN | {u.split("/")[-1] for u in units(crate)}
used, in_code = set(), set()
for f in files:
masked = mask(read(f))
ranges = regions.get(f, [])
hits = [(m.start(), m.group(1)) for m in re.finditer(r"\bcrate::([A-Za-z_][A-Za-z0-9_]*)", masked)]
for m in re.finditer(r"\buse crate::\{([^}]*)\}", masked):
hits += [(m.start(), n) for n in re.findall(r"(?:^|,)\s*([A-Za-z_][A-Za-z0-9_]*)", m.group(1))]
for pos, n in hits:
if n in own or n == "self":
continue
used.add(n)
if not in_test(ranges, pos):
in_code.add(n)
return sorted(in_code), sorted(used - in_code)
def import_block(crate):
code, tests = import_names(crate)
out = "use photocraft_engine_core::{" + ", ".join(code) + "};"
if tests:
out += "\n#[cfg(test)]\nuse photocraft_engine_core::{" + ", ".join(tests) + "};"
return out
def imports(crate):
print("// The core items this crate's code names as `crate::x` (photocraft#15710).")
print(import_block(crate))
def crate_ids(crate):
ids = set()
for f in tree_files(crate_src(crate)):
ids |= set(re.findall(r'(?:\b\w+!\(\s*|\bid:\s*)"([a-z][A-Za-z0-9_]*\.[A-Za-z0-9_.]+)"', read(f)))
return ids
def branch(crate, base, head):
not_done = []
changed = git("diff", "--name-status", "-M", base, head).splitlines()
added = [l.split("\t")[-1] for l in changed if l.startswith("A")]
# Files git left in core that the crate's modules declare.
roots = [unit_root(u) for u in units(crate)]
left = [f for r in roots if r for f in reach(r)]
for f in left:
dst = crate_src(crate) + f[len(CORE) :]
os.makedirs(os.path.dirname(dst), exist_ok=True)
git("mv", f, dst)
# Declarations and table entries the branch added in core for the crate's modules.
own = {u.split("/")[-1] for u in units(crate)}
for core_file, crate_file in ((f"{CORE}/cmd.rs", f"{crate_src(crate)}/cmd.rs"), (f"{CORE}/lib.rs", f"{crate_src(crate)}/lib.rs")):
text = read(core_file)
for name in own:
m = decl_re(name).search(text)
if m:
text = text[: m.start()] + text[m.end() :]
ct = read(crate_file)
if not decl_re(name).search(ct):
write(crate_file, ct.rstrip("\n") + "\n" + m.group(0))
write(core_file, text)
inst = f"{CORE}/install.rs"
text = read(inst)
entry = re.compile(r'^[ \t]*\("[^"]+",\s*crate::(?:cmd::)?(' + "|".join(sorted(own)) + r')::specs\),[ \t]*\n', re.M)
for m in list(entry.finditer(text))[::-1]:
text = text[: m.start()] + text[m.end() :]
not_done.append(f"{crate_src(crate)}/install.rs: add the table entry `{m.group(0).strip()}` to TABLES")
write(inst, text)
finish(crate, left + [f for f in added if f.startswith(crate_src(crate) + "/") and os.path.exists(f)])
# Import block names the moved code now needs.
lib = f"{crate_src(crate)}/lib.rs"
lt = read(lib)
m = re.search(r"use photocraft_engine_core::\{[^}]*\};(?:\n#\[cfg\(test\)\]\nuse photocraft_engine_core::\{[^}]*\};)?", lt)
if m:
write(lib, lt[: m.start()] + import_block(crate) + lt[m.end() :])
# Tests in core that run the crate's commands.
ids = crate_ids(crate)
pat = re.compile(r'"(' + "|".join(re.escape(i) for i in sorted(ids)) + r')"') if ids else None
for l in changed:
f = l.split("\t")[-1]
if pat and f.startswith(CORE + "/") and f.endswith(".rs") and os.path.exists(f):
diff = git("diff", base, head, "--", f)
hits = sorted({m.group(1) for m in pat.finditer("\n".join(x for x in diff.splitlines() if x.startswith("+")))})
if hits:
not_done.append(f"{f}: the branch's lines run {', '.join(hits)}; a test doing that moves to crates/engine/tests/it")
report(not_done)
USE_STMT = re.compile(r"^([ \t]*)(?:pub(?:\([^)]*\))?\s+)?use\s+", re.M)
def widen(text, pos, end):
"""`text` with the item named at `pos`..`end` made `pub`: its definition line, or for a name in
a `use` list, its own `pub use` line beside the list."""
masked = mask(text)
stmt = None
for m in USE_STMT.finditer(masked, 0, pos):
stmt = m
if stmt is not None:
semi = masked.find(";", stmt.start())
if stmt.start() < pos < semi and ";" not in masked[stmt.end() : pos]:
body = text[stmt.end() : semi]
name = text[pos:end]
if "{" not in body:
head = text[stmt.start() : stmt.end()]
return text[: stmt.start()] + stmt.group(1) + "pub use " + text[stmt.end() :] if not head.lstrip().startswith("pub use") else text
if "{" in body[body.index("{") + 1 : body.rindex("}")]:
return None
prefix = body[: body.index("{")]
# Edit only at and after `pos`, so the offsets of earlier names stay valid.
after = re.match(r"\s*,\s*", text[end:semi])
if after:
text = text[:pos] + text[end + after.end() :]
else:
before = re.search(r",\s*$", text[stmt.end() : pos])
if not before:
return None
text = text[: stmt.end() + before.start()] + text[end:]
masked = mask(text)
semi = masked.find(";", stmt.start())
line_end = text.index("\n", semi) + 1
if re.fullmatch(r"\{\s*\}", text[stmt.end() + len(prefix) : semi].strip() or "{}"):
return text[: stmt.start()] + f"{stmt.group(1)}pub use {prefix}{name};\n" + text[line_end:]
return text[:line_end] + f"{stmt.group(1)}pub use {prefix}{name};\n" + text[line_end:]
ls = text.rfind("\n", 0, pos) + 1
le = text.find("\n", pos)
line = text[ls:le]
new = re.sub(r"^(\s*)(?:pub\((?:crate|super|in [^)]*)\)\s+)?(?!pub\b)", r"\1pub ", line, count=1)
return text[:ls] + new + text[le:]
def child_module(f, name):
src = read(f)
for d in MOD_DECL.finditer(mask(src)):
if d.group(2) == name:
return module_file(f, name, src[d.start(1) : d.end(1)])
return None
def reexported(d):
"""(file, ("chars", start, end)) of the definition a refused `pub use` names."""
m = re.search(r"`([A-Za-z_][A-Za-z0-9_]*)`", d["message"])
spans = [s for c in d.get("children", []) for s in c.get("spans", [])] + [s for s in d.get("spans", []) if s.get("is_primary")]
spans = [s for s in spans if s["file_name"].startswith(CORE + "/")]
if not m or not spans:
return None
name, f = m.group(1), spans[0]["file_name"]
text = read(f)
line = text.split("\n")[spans[0]["line_start"] - 1]
um = re.search(r"use\s+((?:[a-z_][a-z0-9_]*::)+)(?:\{[^}]*\b" + name + r"\b|" + name + r"\b)", line)
if not um:
return None
segs = [x for x in um.group(1).split("::") if x]
cur = f
for seg in segs:
if seg == "crate":
cur = f"{CORE}/lib.rs"
elif seg == "super":
return None
else:
cur = child_module(cur, seg)
if cur is None:
return None
src = read(cur)
dm = re.search(r"^[ \t]*(?:pub\([a-z]+\)\s+)?(?:const\s+|async\s+)*(?:fn|struct|enum|const|static|type|trait|mod)\s+(" + name + r")\b", src, re.M)
if not dm:
um2 = re.search(r"^[ \t]*(?:pub\([a-z]+\)\s+)?use\s[^;]*\b(" + name + r")\b[^;]*;", mask(src), re.M)
if not um2:
return None
return cur, ("chars", um2.start(1), um2.end(1))
return cur, ("chars", dm.start(1), dm.end(1))
def fix(stream):
defs_by_file = {}
left = []
for line in stream:
line = line.strip()
if not line.startswith("{"):
continue
try:
msg = json.loads(line)
except ValueError:
continue
if msg.get("reason") != "compiler-message":
continue
d = msg["message"]
code = (d.get("code") or {}).get("code")
if code in ("E0364", "E0365"):
# A `pub use` of an item that is only `pub(crate)` where it is defined.
target = reexported(d)
if target:
defs_by_file.setdefault(target[0], set()).add(target[1])
else:
left.append(d.get("rendered", d["message"]).splitlines()[0])
continue
if code not in ("E0603", "E0624", "E0616"):
continue
defs = [s for c in d.get("children", []) for s in c.get("spans", []) if "defined here" in (c.get("message") or "") or "private" in (c.get("message") or "")]
defs += [s for s in d.get("spans", []) if not s.get("is_primary")]
defs = [s for s in defs if s["file_name"].startswith(CORE + "/")]
if not defs:
left.append(d.get("rendered", d["message"]).splitlines()[0])
continue
sp = defs[0]
defs_by_file.setdefault(sp["file_name"], set()).add(("bytes", sp["byte_start"], sp["byte_end"]))
n = 0
for f, spans in defs_by_file.items():
text = read(f)
raw = text.encode("utf-8")
for kind, b0, b1 in sorted(spans, key=lambda x: x[1] if x[0] == "bytes" else len(text[: x[1]].encode("utf-8")), reverse=True):
if kind == "bytes":
c0, c1 = len(raw[:b0].decode("utf-8", "ignore")), len(raw[:b1].decode("utf-8", "ignore"))
else:
c0, c1 = b0, b1
new = widen(text, c0, c1)
if new is not None and new != text:
print(f"WIDENED: {f}: {text[c0:c1]}")
if new is None:
left.append(f"{f}: `{text[c0:c1]}` in a nested use list")
elif new != text:
text = new
n += 1
write(f, text)
print(f"widened {n} items in {len(defs_by_file)} files")
for l in sorted(set(left)):
print("BY HAND:", l)
report([])
CANNOT_DO = """
What this script cannot do:
- items that core-crate code uses from the cut crate: they move down by hand (each cut's PR
lists where they went), or become a hook or a trait of the crate;
- core tests that run the cut crate's commands: they fail at run time with `UnknownCommand`
and move to crates/engine/tests/it, against the public API;
- the crate's own install list and `command_ids.txt` (crates/engine/src/install/) for a new
command or table: add them by hand;
- core items that only a test of the crate uses under `#[cfg(test)]`: core is then an ordinary
dependency, so the item doesn't exist there.
"""
def report(not_done):
for n in not_done:
print("NOT DONE:", n)
print(CANNOT_DO)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="mode", required=True)
for name in ("split", "imports"):
p = sub.add_parser(name)
p.add_argument("crate")
p = sub.add_parser("branch")
p.add_argument("crate")
p.add_argument("--base", required=True)
p.add_argument("--head", required=True)
sub.add_parser("fix")
a = ap.parse_args()
os.chdir(git("rev-parse", "--show-toplevel").strip())
if a.mode == "split":
split(a.crate)
report([])
elif a.mode == "imports":
imports(a.crate)
elif a.mode == "branch":
branch(a.crate, a.base, a.head)
else:
fix(sys.stdin)
if __name__ == "__main__":
main()