Skip to content

Commit 33b2034

Browse files
committed
refactor: simplify pass on the owned-copy tooling
Share one findOwned and the codegen directory name in the Maven plugin, compute the identical set once in Python undo, reuse the config-name and api-prefix constants, and collapse a duplicated list in the TypeScript undo.
1 parent daeec54 commit 33b2034

7 files changed

Lines changed: 16 additions & 29 deletions

File tree

‎server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataEjectMojo.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ public class MetaDataEjectMojo extends AbstractMojo {
123123
@Parameter(property = "undo", defaultValue = "false")
124124
boolean undo;
125125

126-
private static final String CODEGEN_DIR = "codegen";
126+
static final String CODEGEN_DIR = "codegen";
127127

128128
@Override
129129
public void execute() throws MojoExecutionException, MojoFailureException {
@@ -881,7 +881,7 @@ private String ownedSupportRows(Path codegenRoot) {
881881

882882
/** The owned copy named {@code filename} under {@code codegen/src/main/<lang>}, or
883883
* {@code null}. It may live under ANY package the adopter chose. */
884-
private static Path findOwned(Path codegenRoot, String langDir, String filename) throws IOException {
884+
static Path findOwned(Path codegenRoot, String langDir, String filename) throws IOException {
885885
if (codegenRoot == null) return null;
886886
Path srcRoot = codegenRoot.resolve("src/main/" + langDir);
887887
if (!Files.isDirectory(srcRoot)) return null;

‎server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ private void noteOwnedStock() {
137137
if (project == null || project.getBasedir() == null) return;
138138
try {
139139
String line = OwnedStock.notice(OwnedStock.find(
140-
project.getBasedir().toPath().resolve("codegen"),
140+
project.getBasedir().toPath().resolve(MetaDataEjectMojo.CODEGEN_DIR),
141141
OwnedStock.classpath(getClass().getClassLoader())));
142142
if (line != null) getLog().info("MetaData Mojo > " + line);
143143
} catch (IOException | RuntimeException ignored) {

‎server/java/maven-plugin/src/main/java/com/metaobjects/mojo/OwnedStock.java‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ static List<Copy> find(Path codegenRoot, Reader reader) throws IOException {
8383
for (EjectSupport.Entry e : EjectSupport.allEntries()) {
8484
if (e.resourcePath == null) continue;
8585
String langDir = e.port == EjectSupport.Port.KOTLIN ? "kotlin" : "java";
86-
Path found = findOwned(codegenRoot, langDir, e.simpleName() + "." + e.port.extension);
86+
Path found = MetaDataEjectMojo.findOwned(codegenRoot, langDir, e.simpleName() + "." + e.port.extension);
8787
if (found == null) continue;
8888
Path srcRoot = codegenRoot.resolve("src/main/" + langDir);
8989
String ownedPackage = srcRoot.relativize(found.getParent()).toString()
@@ -131,7 +131,7 @@ private static List<String> shared(Path codegenRoot, EjectSupport.Entry e, Reade
131131
if (e.port == EjectSupport.Port.JAVA) {
132132
for (String source : e.sources()) {
133133
for (String simple : EjectSupport.supportFor(reader.read(e.resourceOf(source)))) {
134-
if (findOwned(codegenRoot, "java", simple + ".java") != null) out.add(simple);
134+
if (MetaDataEjectMojo.findOwned(codegenRoot, "java", simple + ".java") != null) out.add(simple);
135135
}
136136
}
137137
out.addAll(e.runtime);
@@ -157,14 +157,6 @@ static String notice(List<Copy> copies) {
157157
+ "`mvn metaobjects:eject -Dundo=true`.";
158158
}
159159

160-
private static Path findOwned(Path codegenRoot, String langDir, String filename) throws IOException {
161-
Path srcRoot = codegenRoot.resolve("src/main/" + langDir);
162-
if (!Files.isDirectory(srcRoot)) return null;
163-
try (var walk = Files.walk(srcRoot)) {
164-
return walk.filter(p -> p.getFileName().toString().equals(filename)).findFirst().orElse(null);
165-
}
166-
}
167-
168160
private static void fold(int[] totals, List<String> differing, String name, EjectSupport.Comparison cmp) {
169161
totals[0] += cmp.behind;
170162
totals[1] += cmp.ownedOnly;

‎server/python/src/metaobjects/cli.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1322,7 +1322,7 @@ def _cmd_init(args: argparse.Namespace) -> int:
13221322
wrote: list[str] = []
13231323
kept: list[str] = []
13241324
for rel, text in (
1325-
("metaobjects.config.yaml", config),
1325+
(_CONFIG_NAME, config),
13261326
("metaobjects/meta.app.yaml", _INIT_METADATA),
13271327
):
13281328
path = root / rel
@@ -1336,7 +1336,7 @@ def _cmd_init(args: argparse.Namespace) -> int:
13361336
print(f"wrote {rel}")
13371337
for rel in kept:
13381338
print(f"kept {rel} (already exists)")
1339-
if args.with_docs and "metaobjects.config.yaml" in kept:
1339+
if args.with_docs and _CONFIG_NAME in kept:
13401340
print("note: add the docs target yourself: `docs: {outDir: docs, generators: [api-docs]}`")
13411341
print("next: describe your entities in metaobjects/, then run `metaobjects gen`.")
13421342
return 0

‎server/python/src/metaobjects/codegen/eject.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,7 @@ def owned_token(entry: GeneratorEntry) -> str:
7979

8080

8181
def packaged_source(entry: GeneratorEntry) -> str:
82-
assert entry.source_module is not None
83-
module = importlib.import_module(entry.source_module)
84-
assert module.__file__ is not None
85-
return Path(module.__file__).read_text(encoding="utf-8")
82+
return packaged_module_path(entry).read_text(encoding="utf-8")
8683

8784

8885
def ejected_source(entry: GeneratorEntry) -> str:
@@ -211,7 +208,8 @@ def undo(names: list[str], root: Path, *, force: bool = False) -> EjectResult:
211208

212209
if names:
213210
chosen = [known[n] for n in names]
214-
differing = [e for e in chosen if e not in identical_owned(root)]
211+
identical = identical_owned(root)
212+
differing = [e for e in chosen if e not in identical]
215213
if differing and not force:
216214
return EjectResult(2, [], [
217215
f"{e.name} differs from the shipped generator; nothing removed. Inspect: "

‎server/python/src/metaobjects/codegen/runtime/api_docs_builder.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
FieldShape,
3939
)
4040
from metaobjects.codegen import type_map
41+
from metaobjects.codegen.config import DEFAULT_API_PREFIX
4142
from metaobjects.codegen.model_walk import package_of
4243
from .m2m_codegen import (
4344
build_object_index,
@@ -94,7 +95,7 @@ def _is_email_kind(tmpl: MetaData) -> bool:
9495
class PythonApiModelBuilder:
9596
"""Builds the :class:`ApiModel` SDK-surface IR from a loaded ``MetaRoot``."""
9697

97-
def __init__(self, api_prefix: str = "/api") -> None:
98+
def __init__(self, api_prefix: str = DEFAULT_API_PREFIX) -> None:
9899
#: The path the documented routes mount under (``apiPrefix``; ``""`` = at the root).
99100
self.api_prefix = api_prefix
100101

‎server/typescript/packages/cli/src/commands/eject.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -719,29 +719,25 @@ async function undoCommand(names: readonly string[], force: boolean, cwd: string
719719
const stillReached = new Set(remaining.flatMap((r) => closureOf(r.name).templates.map((f) => f.path)));
720720
const removed: string[] = [];
721721
const keptCompanions: string[] = [];
722-
const toRemove: string[] = [];
723722

724-
for (const r of targets) toRemove.push(`${OWNED_GENERATORS_DIR}/${r.name}.ts`);
723+
for (const r of targets) removed.push(`${OWNED_GENERATORS_DIR}/${r.name}.ts`);
725724
const templateRows = await templateCopyStatus(cwd, packagedTemplates());
726725
const dropTemplates = new Set(targets.flatMap((r) => (r.templates ?? []).map((t) => t.path)));
727726
for (const row of templateRows) {
728727
if (!dropTemplates.has(row.path) || stillReached.has(row.path)) continue;
729-
if (row.verdict === "identical" || row.verdict === "reformatted") toRemove.push(row.path);
728+
if (row.verdict === "identical" || row.verdict === "reformatted") removed.push(row.path);
730729
else keptCompanions.push(row.path);
731730
}
732731
// The adapter source is one shared tree: it goes only when nothing left in the project emits
733732
// code that imports it.
734733
const adapterDropped = targets.some((r) => ejectsRuntime(r.name)) && !remaining.some((r) => ejectsRuntime(r.name));
735734
if (adapterDropped) {
736735
for (const row of await runtimeCopyStatus(cwd)) {
737-
if (row.verdict === "identical" || row.verdict === "reformatted") toRemove.push(row.path);
736+
if (row.verdict === "identical" || row.verdict === "reformatted") removed.push(row.path);
738737
else keptCompanions.push(row.path);
739738
}
740739
}
741-
for (const rel of toRemove) {
742-
await rm(join(cwd, rel), { force: true });
743-
removed.push(rel);
744-
}
740+
for (const rel of removed) await rm(join(cwd, rel), { force: true });
745741
await pruneEmptyDirs(cwd, [OWNED_TEMPLATES_DIR, OWNED_RUNTIME_DIR, OWNED_GENERATORS_DIR]);
746742

747743
const undone: UndoneRow[] = targets.map((r) => {

0 commit comments

Comments
 (0)