Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,21 @@ here.**

## [Unreleased]

- **C#: an unchanged file is never rewritten.** `dotnet meta gen` already left identical output alone
when the project keeps a hash manifest. It now does the same on the path with no manifest (output
written outside the project, or a program that runs the generators with no state directory), which
reports the file `unchanged` instead of `written`. `dotnet meta eject --force` compares each copy
(the generator, its emitters and the helper runtime) before writing it and reports one that already
matches the reference as `[unchanged]`. The gen fingerprint is rewritten only when it changes.
- **C#: the routes, expression-indexes, report-export, requirement-tests, shared-model and api-docs
generators are built from overridable pieces (ADR-0063 item 7).** The routes generator works out
what a file serves once (`PlanStandardRoutes`, `PlanTphRoutes`) and writes it from one
`protected virtual` method per piece: the file header, the list, item, create, update and delete
routes, the M:N traversals, the TPH polymorphic list and item routes, the sort dispatch and the
helper members. Its `Append*` helpers are renamed `Write*` and are `protected virtual`; its other
helpers and records are `protected`. The other generators follow the same rule, and `ApiDocsGenerator`
is no longer sealed. A subclass overrides the piece it wants and keeps the rest. Output is
byte-identical. These methods are not a stability contract.
- **Java and Kotlin: template and documentation output is recorded in the hash manifest.** The
`template` and `mustache` generators, the api, HTML, JSON and PlantUML documentation pages and the
`META-INF/services` registration wrote through a byte compare only, so a hand edit to one of them
Expand Down
6 changes: 3 additions & 3 deletions docs/features/own-your-codegen.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,8 @@ they are handed **no gen-state directory at all**. Only an embedder calling
`CodegenRunner.Run`, `decide_and_write` or a JVM generator directly can do that;
`dotnet meta gen`, `metaobjects gen` and `mvn metaobjects:generate` always supply one. In that fallback a hand edit inside a generated file keeps its marker and is
overwritten silently, which is exactly the failure the hash manifest exists to prevent —
so if you embed a runner, supply a gen-state directory.
so if you embed a runner, supply a gen-state directory. (C# leaves a file that already holds
exactly the generated bytes alone and reports it `unchanged`; the marker rule decides only a file that differs.)

**Say the condition out loud, because it is where teams get surprised.** The merge is
machine-local. Edit a generated file, push it, and the *next* clone — a colleague's, a CI
Expand Down Expand Up @@ -1591,8 +1592,7 @@ The list names every generator the project runs, owned or packaged, so ejecting
a nine-entry list changes one entry, not the other eight. `--generators` narrows a run to the
declared entries named, matching an owned copy by its registry name too, and never adds
one. The owned project finds metadata exactly as the tool does, including
`.metaobjects/config.json`'s `sources` and `libraries`. Eject never overwrites a copy without `--force`, and
`dotnet meta gen --list` marks owned copies `identical` or `DIFFERS: N behind, M of your
`.metaobjects/config.json`'s `sources` and `libraries`. Eject never overwrites a copy without `--force`; with it, a copy already byte-identical to the reference is left alone and reported `[unchanged]`. `dotnet meta gen --list` marks owned copies `identical` or `DIFFERS: N behind, M of your
own`, and names an emitter that was edited or removed after eject
(`Fr019SharedEnum.cs DIFFERS: 0 behind, 1 of your own`). The `template` primitive is not
ejectable; it has no emit logic of its own.
Expand Down
12 changes: 7 additions & 5 deletions docs/ports/csharp.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,13 @@ prints a warning naming the line to change. See

**Generators write through a code writer.** `MetaObjects.Codegen.Writer.CsWriter` is where a
generator's layout lives (ADR-0063): it owns the indent, the braces, the `using` lines and the
blank lines, so a generator states what the file says and not how many spaces it takes. The
filter allowlist, names, callable, output-prompt, output-parser and extractor generators are
written on it, and so is the mirror record they share. Each is a class whose file is built from
one overridable method per piece (`WriteFileHeader`, `WriteTypeDoc`, `WriteMembers` and so on),
so an owned copy, or a subclass of the shipped one, changes the piece it wants and keeps the rest.
blank lines, so a generator states what the file says and not how many spaces it takes. Every
generator that emits C# source is written on it; the JSON, Markdown and template generators are
not. Each such generator is a class whose file is built from one overridable method per
piece (`WriteFileHeader`, `WriteTypeDoc`, `WriteMembers` and so on; in the routes generator
`WriteListRoute`, `WriteCreateRoute`, `WriteUpdateRoute` and the rest, over a plan worked out once
by `PlanStandardRoutes` or `PlanTphRoutes`), so an owned copy, or a subclass of the shipped one,
changes the piece it wants and keeps the rest.
Those methods are not a stability contract. A test keeps new hand-typed layout out of the
generator source: a file that still builds text with `AppendLine` is on an allowlist with a
written reason, and the list only gets shorter.
Expand Down
21 changes: 21 additions & 0 deletions server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,27 @@ public void Force_replaces_an_edited_copy()
Assert.DoesNotContain("hand edit", File.ReadAllText(copyPath));
}

[Fact]
public void Force_over_an_unedited_copy_rewrites_nothing()
{
// Compare before write: --force over files that already match the reference reports them
// unchanged and leaves their bytes and timestamps alone.
Assert.Equal(0, EjectCommand.Run(["routes"], _root, force: false).ExitCode);
var copyPath = Path.Combine(GeneratorsDir, "RoutesGenerator.cs");
var parser = Path.Combine(RuntimeDir, "FilterParser.cs");
var stamp = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
File.SetLastWriteTimeUtc(copyPath, stamp);
File.SetLastWriteTimeUtc(parser, stamp);

var forced = EjectCommand.Run(["routes"], _root, force: true);

Assert.Equal(0, forced.ExitCode);
Assert.Contains(forced.Out, l => l.Contains("RoutesGenerator.cs [unchanged]"));
Assert.Contains(forced.Out, l => l.Contains("FilterParser.cs [unchanged]"));
Assert.Equal(stamp, File.GetLastWriteTimeUtc(copyPath));
Assert.Equal(stamp, File.GetLastWriteTimeUtc(parser));
}

[Fact]
public void A_second_eject_of_a_different_generator_does_not_touch_the_existing_scaffold()
{
Expand Down
21 changes: 17 additions & 4 deletions server/csharp/MetaObjects.Cli/EjectCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,7 @@ public static Outcome Run(IReadOnlyList<string> names, string root, bool force)
var file = entry.SourceFileName!;
var rewritten = EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSource(name)!);
var dest = Path.Combine(generatorsDir, file);
var status = File.Exists(dest) ? "replaced" : "created";
File.WriteAllText(dest, rewritten);
var status = WriteOwnedCopy(dest, rewritten, File.Exists(dest) ? "replaced" : "created");
outLines.Add($"ejected \"{name}\" -> codegen/generators/{file} [{status}]");
}
outLines.AddRange(EjectCompanions(root, names.Select(n => known[n]).ToList(), force));
Expand Down Expand Up @@ -352,6 +351,19 @@ public static Outcome Undo(IReadOnlyList<string> names, string root, bool force)
return new Outcome(0, lines, []);
}

/// <summary>
/// Write one reference copy to <paramref name="dest"/> and return the status to report:
/// <paramref name="status"/> when the bytes were written, <c>unchanged</c> when the file on
/// disk already holds exactly <paramref name="content"/>. An identical file is never
/// rewritten, so <c>--force</c> over an unedited copy leaves it, and its timestamp, alone.
/// </summary>
private static string WriteOwnedCopy(string dest, string content, string status)
{
if (File.Exists(dest) && File.ReadAllText(dest) == content) return "unchanged";
File.WriteAllText(dest, content);
return status;
}

/// <summary>
/// Copy the emitters the ejected <paramref name="entries"/> write their output through
/// (<see cref="GeneratorRegistryEntry.Companions"/>) next to the generators, each once however
Expand Down Expand Up @@ -382,7 +394,8 @@ private static List<string> EjectCompanions(string root, IReadOnlyList<Generator
continue;
}
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
File.WriteAllText(dest, EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSourcePath(sourcePath)));
status = WriteOwnedCopy(
dest, EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSourcePath(sourcePath)), status);
lines.Add($" {relative} [{status}]");
}
return lines;
Expand Down Expand Up @@ -416,7 +429,7 @@ private static List<string> EjectRuntime(string root, IReadOnlyList<string> user
lines.Add($" {HelperRuntime.OwnedDirectory}/{file} [kept — already yours]");
continue;
}
File.WriteAllText(dest, HelperRuntime.OwnedReference(file));
status = WriteOwnedCopy(dest, HelperRuntime.OwnedReference(file), status);
lines.Add($" {HelperRuntime.OwnedDirectory}/{file} [{status}]");
}
lines.Add(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,9 +409,14 @@ public void Runner_writes_generated_files_but_refuses_handwritten()
Assert.Contains(r1.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "written");
Assert.True(File.Exists(Path.Combine(dir, "Subscriber.g.cs")));

// Re-run overwrites the @generated file.
// Re-running over identical output leaves the file alone.
var r2 = CodegenRunner.Run(config, Load(), [new EntityGenerator()]);
Assert.Contains(r2.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "written");
Assert.Contains(r2.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "unchanged");

// A stale @generated file is overwritten.
File.WriteAllText(Path.Combine(dir, "Subscriber.g.cs"), "// <auto-generated/>\n// stale\n");
var r2b = CodegenRunner.Run(config, Load(), [new EntityGenerator()]);
Assert.Contains(r2b.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "written");

// A hand-written file (no marker) is refused.
File.WriteAllText(Path.Combine(dir, "Subscriber.g.cs"), "// my hand-written file\n");
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// TphM2mRoutesTests — FW-8: M:N traversal inside a TPH hierarchy (C# port).
//
// A TPH base's routes generator never consulted M2MNavigationBuilder at all — neither
// GenerateTphRoutes (the base + per-subtype CRUD emitter) nor AppendTphSubtypeRoutes
// GenerateTphRoutes (the base + per-subtype CRUD emitter) nor WriteTphSubtypeRoutes
// asked the relation map a single question — so every many-to-many navigation declared
// anywhere in a TPH hierarchy vanished from the generated API. Nothing failed: a route
// that is never mounted is an ABSENCE, not a compile error, which is why the existing
Expand Down
13 changes: 9 additions & 4 deletions server/csharp/MetaObjects.Codegen/CodegenRunner.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion server/csharp/MetaObjects.Codegen/GenFingerprint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,10 @@ public static void Write(
format = FormatVersion, model, identity, outputs,
untracked = (untracked ?? []).Order(StringComparer.Ordinal).ToArray(),
}, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(PathFor(projectRoot), json + "\n");
// Compared first, like every other write: a run that changes nothing leaves the file alone.
var path = PathFor(projectRoot);
var text = json + "\n";
if (!File.Exists(path) || File.ReadAllText(path) != text) File.WriteAllText(path, text);
}

private static string? DiskHash(string projectRoot, string key)
Expand Down
18 changes: 14 additions & 4 deletions server/csharp/MetaObjects.Codegen/Generators/ApiDocsGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

namespace MetaObjects.Codegen.Generators;

public sealed class ApiDocsGenerator : IGenerator
public class ApiDocsGenerator : IGenerator
{
/// <summary>The api-surface subdirectory of the cross-port docs contract.</summary>
public const string DefaultApiSubDir = "api/csharp";
Expand All @@ -38,8 +38,8 @@ public sealed class ApiDocsGenerator : IGenerator

public IEnumerable<EmittedFile> Generate(GenContext ctx)
{
var model = new CSharpApiModelBuilder(ctx.Config, ctx.Applicability).Build(ctx.Root, ProjectName);
var renderer = new CSharpApiDocsRenderer();
var model = BuildModel(ctx);
var renderer = NewRenderer();
const DocsPaths.Layout layout = DocsPaths.Layout.Package;
// Refused before anything is yielded: two pages that are one file must not half-write.
DocsPaths.AssertNoDuplicateDocPaths(model.Units.Select(u => (
Expand All @@ -58,5 +58,15 @@ public IEnumerable<EmittedFile> Generate(GenContext ctx)
yield return Page("AGENT-API.md", renderer.RenderAgentApi(model));
}

private EmittedFile Page(string pagePath, string content) => new(ApiSubDir + "/" + pagePath, content);
// The pieces, one overridable method each (ADR-0063 item 7). Not a stability contract.

/// <summary>The page model the pages are rendered from.</summary>
protected virtual CSharpApiModel BuildModel(GenContext ctx) =>
new CSharpApiModelBuilder(ctx.Config, ctx.Applicability).Build(ctx.Root, ProjectName);

/// <summary>The renderer that turns the page model into Markdown.</summary>
protected virtual CSharpApiDocsRenderer NewRenderer() => new();

/// <summary>One page, under <see cref="ApiSubDir"/>.</summary>
protected virtual EmittedFile Page(string pagePath, string content) => new(ApiSubDir + "/" + pagePath, content);
}
Loading
Loading