Skip to content

Commit 65c4ee2

Browse files
committed
no-mistakes(review): Narrow template scopes; keep C# shared files whole
1 parent bc5b521 commit 65c4ee2

8 files changed

Lines changed: 126 additions & 11 deletions

File tree

‎server/csharp/MetaObjects.Cli.Tests/GenEntitiesSelectionTests.cs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,35 @@ public void Selecting_an_object_the_context_does_not_cover_still_renders_the_who
8686
Assert.Equal(full, Read("AppDbContext.g.cs"));
8787
}
8888

89+
[Fact]
90+
public void Shared_files_inside_a_per_object_generator_still_render_whole_when_the_selection_does_not_touch_them()
91+
{
92+
// A shared enum and a decimal wire helper are consumed only by Gadget; selecting Product
93+
// contributes nothing to either, yet each is built from the whole model.
94+
File.WriteAllText(Path.Combine(MetaDir, "meta.gadget.json"),
95+
"{ \"metadata.root\": { \"package\": \"acme\", \"children\": [" +
96+
"{ \"field.enum\": { \"name\": \"GadgetState\", \"abstract\": true, \"@values\": [\"ON\", \"OFF\"] } }," +
97+
"{ \"object.entity\": { \"name\": \"Gadget\", \"children\": [" +
98+
"{ \"source.rdb\": { \"@table\": \"gadgets\" } }," +
99+
"{ \"field.long\": { \"name\": \"id\" } }," +
100+
"{ \"field.decimal\": { \"name\": \"price\" } }," +
101+
"{ \"field.enum\": { \"name\": \"state\", \"extends\": \"GadgetState\" } }," +
102+
"{ \"identity.primary\": { \"@fields\": \"id\" } }]}}]}}");
103+
Assert.Equal(0, Gen().ExitCode);
104+
var enums = Read("Enums.g.cs");
105+
var wire = Read("DecimalWire.g.cs");
106+
Assert.Contains("GadgetState", enums);
107+
Directory.Delete(OutDir, recursive: true);
108+
109+
var (exit, stdout, stderr) = Gen("--entities", "Product");
110+
111+
Assert.True(exit == 0, $"exit={exit}\n{stdout}\n{stderr}");
112+
Assert.Equal(enums, Read("Enums.g.cs"));
113+
Assert.Equal(wire, Read("DecimalWire.g.cs"));
114+
Assert.False(Has("Gadget.g.cs"));
115+
Assert.True(Has("Product.g.cs"));
116+
}
117+
89118
[Fact]
90119
public void A_narrowed_run_neither_deletes_nor_forgets_the_unselected_files()
91120
{

‎server/csharp/MetaObjects.Codegen/CodegenRunner.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ internal static RunResult Run(
194194
/// </para>
195195
/// <para>
196196
/// A generator answering <see cref="IGenerator.WholeModel"/> skips the probe: its single file would
197-
/// otherwise vanish from the narrowed run whenever the selection contributes nothing to it.
197+
/// otherwise vanish from the narrowed run whenever the selection contributes nothing to it. A shared
198+
/// file inside a per-object generator (<see cref="EmittedFile.WholeModel"/>) is kept the same way.
198199
/// </para>
199200
/// </summary>
200201
private static IEnumerable<EmittedFile> Emit(IGenerator generator, GenContext ctx, HashSet<string> selection)
@@ -204,7 +205,7 @@ private static IEnumerable<EmittedFile> Emit(IGenerator generator, GenContext ct
204205
if (generator.WholeModel) return all;
205206
var kept = generator.Generate(ctx.NarrowForProbe(o => selection.Contains(o.Name)))
206207
.Select(f => f.Path).ToHashSet(StringComparer.Ordinal);
207-
return all.Where(f => kept.Contains(f.Path)).ToList();
208+
return all.Where(f => f.WholeModel || kept.Contains(f.Path)).ToList();
208209
}
209210

210211
/// <summary>

‎server/csharp/MetaObjects.Codegen/Generator.cs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,15 @@
88
namespace MetaObjects.Codegen;
99

1010
/// <summary>A file a generator produced. <paramref name="Path"/> is relative to the out dir.</summary>
11-
public sealed record EmittedFile(string Path, string Content);
11+
public sealed record EmittedFile(string Path, string Content)
12+
{
13+
/// <summary>
14+
/// <c>true</c> for a file built from the whole model (a shared enum, a wire helper, the report
15+
/// export writer): an <c>--entities</c> selection never drops it, because no selected object owns
16+
/// it. <c>false</c>, the default, is a per-object file the selection narrows.
17+
/// </summary>
18+
public bool WholeModel { get; init; }
19+
}
1220

1321
/// <summary>Resolved generation config.</summary>
1422
public sealed record GenConfig

‎server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,7 +1161,7 @@ protected virtual IEnumerable<EmittedFile> EmitSharedEnumFiles(GenContext ctx, I
11611161
sb.AppendLine();
11621162
sb.Append(SharedEnumDeclaration(e));
11631163
var fileName = $"{e.Name}.g.cs";
1164-
return new EmittedFile(e.Declaration is { } decl ? OutputPaths.Of(decl, ctx, fileName) : fileName, sb.ToString());
1164+
return new EmittedFile(e.Declaration is { } decl ? OutputPaths.Of(decl, ctx, fileName) : fileName, sb.ToString()) { WholeModel = true };
11651165
}).ToList();
11661166

11671167
var flat = new StringBuilder();
@@ -1191,7 +1191,7 @@ protected virtual IEnumerable<EmittedFile> EmitSharedEnumFiles(GenContext ctx, I
11911191
flat.AppendLine();
11921192
}
11931193
}
1194-
return [new EmittedFile("Enums.g.cs", flat.ToString())];
1194+
return [new EmittedFile("Enums.g.cs", flat.ToString()) { WholeModel = true }];
11951195
}
11961196

11971197
/// <summary>
@@ -2130,7 +2130,7 @@ public override void Write(Utf8JsonWriter writer, IList<decimal> value, JsonSeri
21302130
""";
21312131

21322132
private static EmittedFile EmitDecimalWireFile(string ns, string fileName) =>
2133-
new(fileName, DecimalWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n");
2133+
new(fileName, DecimalWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n") { WholeModel = true };
21342134

21352135
// field.duration — the duration wire form (fixtures/duration-wire/). This text is the
21362136
// Runtime/DurationWire.cs source with its namespace as __NS__; DurationWireTests gates the two
@@ -2398,7 +2398,7 @@ public override void Write(Utf8JsonWriter writer, IList<TimeSpan> value, JsonSer
23982398
""";
23992399

24002400
private static EmittedFile EmitDurationWireFile(string ns, string fileName) =>
2401-
new(fileName, DurationWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n");
2401+
new(fileName, DurationWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n") { WholeModel = true };
24022402

24032403
// true iff FIELD is a field.duration (single or @isArray): a System.TimeSpan property carrying
24042404
// the per-property ISO-8601 converter.
@@ -2544,7 +2544,7 @@ private static EmittedFile EmitNetValidationFile(string ns, string fileName)
25442544
sb.AppendLine(" }");
25452545
sb.AppendLine(" }");
25462546
sb.AppendLine("}");
2547-
return new EmittedFile(fileName, sb.ToString());
2547+
return new EmittedFile(fileName, sb.ToString()) { WholeModel = true };
25482548
}
25492549

25502550
// One property's declaration line, from the two hooks: `public <type> <name> { <setter> }`

‎server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public IEnumerable<EmittedFile> Generate(GenContext ctx)
8080
.ToList();
8181
if (served.Count == 0) yield break;
8282

83-
yield return new EmittedFile("ReportExportWriter.g.cs", SharedWriter(ctx, HasDurationColumn(served)));
83+
yield return new EmittedFile("ReportExportWriter.g.cs", SharedWriter(ctx, HasDurationColumn(served))) { WholeModel = true };
8484
foreach (var report in served)
8585
yield return new EmittedFile(OutputPaths.Of(report, ctx, CSharpNaming.Pascal(report.Name) + "Export.g.cs"), ReportModule(report, ctx));
8686
}

‎server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import java.nio.file.Path;
1616
import java.nio.file.Paths;
1717
import java.util.List;
18+
import java.util.stream.Collectors;
1819

1920
/**
2021
* Maven-wirable declarative Mustache template generator (SP-1b). Reads the
@@ -59,10 +60,13 @@ public void execute(MetaDataLoader loader) {
5960
File outDir = getOutputDir();
6061

6162
List<MetaObject> objects = com.metaobjects.generator.util.GeneratorUtil.ownMetaObjects(loader);
63+
List<MetaObject> walked = ScopeWalk.PER_ENTITY.equals(scope)
64+
? objects.stream().filter(this::inEntitySelection).collect(Collectors.toList())
65+
: objects;
6266
List<EmittedFile> files = TemplateGenerator.generate(
6367
scope,
6468
template,
65-
root -> ScopeWalk.forScope(scope, outputPattern).apply(objects),
69+
root -> ScopeWalk.forScope(scope, outputPattern).apply(walked),
6670
provider,
6771
format,
6872
objects);
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.metaobjects.generator.template;
2+
3+
import com.metaobjects.generator.GeneratorBase;
4+
import com.metaobjects.loader.MetaDataLoader;
5+
import com.metaobjects.loader.MetaDataLoaderTestBase;
6+
import org.junit.Test;
7+
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
import java.util.List;
11+
import java.util.Map;
12+
import java.util.stream.Collectors;
13+
import java.util.stream.Stream;
14+
15+
import static org.junit.Assert.assertEquals;
16+
17+
/**
18+
* Oracle: the shared template-codegen corpus, whose {@code expected/} tree names the file each
19+
* scope writes for the full model. A per-entity scope narrowed to one object writes that
20+
* object's file only; per-package and per-model files stay whole.
21+
*/
22+
public class TemplateScopeGeneratorSelectionTest extends MetaDataLoaderTestBase {
23+
24+
private static Path corpus() {
25+
return Path.of(System.getProperty("user.dir")).resolve("../../..")
26+
.resolve("fixtures/template-codegen-conformance").normalize();
27+
}
28+
29+
private List<String> run(String scope, String pattern, List<String> entities) throws Exception {
30+
Path corpus = corpus();
31+
MetaDataLoader loader = initLoader(List.of(corpus.resolve("metadata/meta.shop.json").toUri()));
32+
Path out = Files.createTempDirectory("tmpl-select-java");
33+
String template = switch (scope) {
34+
case ScopeWalk.PER_ENTITY -> "entity";
35+
case ScopeWalk.PER_PACKAGE -> "package";
36+
default -> "model";
37+
};
38+
TemplateScopeGenerator gen = new TemplateScopeGenerator();
39+
gen.setArgs(Map.of(
40+
TemplateScopeGenerator.ARG_TEMPLATE, template,
41+
TemplateScopeGenerator.ARG_SCOPE, scope,
42+
TemplateScopeGenerator.ARG_OUTPUT_PATTERN, pattern,
43+
TemplateScopeGenerator.ARG_TEMPLATES_DIR, corpus.resolve("templates").toString(),
44+
GeneratorBase.ARG_OUTPUTDIR, out.toString()));
45+
gen.setEntities(entities);
46+
gen.execute(loader);
47+
try (Stream<Path> s = Files.walk(out)) {
48+
return s.filter(Files::isRegularFile)
49+
.map(p -> out.relativize(p).toString())
50+
.sorted()
51+
.collect(Collectors.toList());
52+
}
53+
}
54+
55+
@Test public void perEntityScopeWritesOnlyTheSelectedObject() throws Exception {
56+
assertEquals(List.of("Product.txt"), run(ScopeWalk.PER_ENTITY, "{name}.txt", List.of("Product")));
57+
}
58+
59+
@Test public void perEntityScopeWithNoSelectionWritesEveryObject() throws Exception {
60+
assertEquals(List.of("Order.txt", "Product.txt"), run(ScopeWalk.PER_ENTITY, "{name}.txt", List.of()));
61+
}
62+
63+
@Test public void wholeModelScopesStayWholeUnderASelection() throws Exception {
64+
assertEquals(List.of("_model.txt"), run(ScopeWalk.PER_MODEL, "_model.txt", List.of("Product")));
65+
assertEquals(List.of("shop/_package.txt"),
66+
run(ScopeWalk.PER_PACKAGE, "{package}/_package.txt", List.of("Product")));
67+
}
68+
}

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,12 @@ protected void executeGenerators(MetaDataLoader loader, List<Generator> generato
9292
getLog().info("MetaData Mojo > Generating only " + String.join(", ", selected)
9393
+ " (meta.entities); files built from the whole model still see every object.");
9494
for (Generator gen : generatorImpls) {
95-
if (gen instanceof GeneratorBase) ((GeneratorBase) gen).setEntities(selected);
95+
if (gen instanceof GeneratorBase) {
96+
((GeneratorBase) gen).setEntities(selected);
97+
} else {
98+
getLog().warn("MetaData Mojo > " + gen.getClass().getName()
99+
+ " cannot narrow to meta.entities; it renders every object.");
100+
}
96101
}
97102
}
98103

0 commit comments

Comments
 (0)