diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fc6b97f76..dd6d4c915c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,28 @@ here.** ## [Unreleased] +- **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 + was overwritten without the refusal every other generated file gets. They now go through + `GeneratedFileWriter.writeUnmarked`: each file is recorded under `.metaobjects/.gen-state/.hashes/`, + unchanged bytes are not rewritten, and a hand edit is refused by name under `handEdits: keep`. An + existing file at one of these paths that the manifest has no record of is taken as generated + output on the first run (it can carry no `GENERATED` marker), so upgrading refuses nothing. The + orphan sweep and `metaobjects:verify` now see these files too: one a template stops emitting is + deleted when untouched, as other generated files are. The documentation generators also no longer + create an empty file before writing, so `metaobjects:verify`'s in-memory render leaves nothing on + disk. +- **Java and Kotlin: a gate that every generator writes through `GeneratedFileWriter`.** + `GeneratorWritePathTest` runs every registered Java and Kotlin generator over the shared fitness + corpus and fails when a file is left on disk that the writer did not write, or when a second run + changes a file's bytes or modification time, so a new generator cannot skip the hash manifest or + the unchanged-bytes check. +- **Java and Kotlin: `mvn metaobjects:eject -Dforce=true` no longer rewrites an identical copy.** An + owned generator, template, support or runtime file, or the `codegen/pom.xml`, that already holds + exactly the reference content is left alone and reported as identical, with or without `force`. + The codegen fingerprint, `metaobjects:fmt` and `metaobjects:init` also compare before they write. + - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` diff --git a/docs/features/codegen-concepts.md b/docs/features/codegen-concepts.md index d189e9648b..a1a6dc89c9 100644 --- a/docs/features/codegen-concepts.md +++ b/docs/features/codegen-concepts.md @@ -156,8 +156,8 @@ thing in git and the only thing anyone reads. ## 7. Safety: never clobbering hand edits The backstop under every strategy above is that the generator will not silently eat your -work. **Every port decides from the committed hash manifest, and the `@generated` header is -not the decision:** +work. **Every port decides from the committed hash manifest. The `@generated` header is not +the decision, except on Java and Kotlin for a file the manifest has no record of:** - **TypeScript** decides from `.metaobjects/.gen-state/` — the snapshot body if this machine has one (three-way merge), otherwise the committed `.hashes/` (byte-for-byte @@ -175,14 +175,9 @@ not the decision:** marker, refuse one without it — and in that mode the header IS load-bearing, in both directions. Neither `dotnet meta gen` nor `metaobjects gen` can put you there: both always supply the directory. If you embed either runner, supply one too. -- **Java and Kotlin** decide from the same committed hash manifest since 8.1.0 (ADR-0060): - `GeneratedFileWriter` records what it writes, and an edited file is refused. The - `GENERATED` header token decides only for a file the manifest has no record of: one that - carries it is adopted as generated output, one that does not is refused. A refusal there - is a warning, not a build failure. - -Both are stated in full, per port, in -[own-your-codegen.md](own-your-codegen.md). +- **Java and Kotlin** decide from the same committed manifest, and their refusal is a + warning, not a build failure. The full rule is in + [own-your-codegen.md](own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). ## 8. Bind metadata → native types at build time, never runtime reflection @@ -298,8 +293,8 @@ registered escaper formats; a `target` field is **rejected** (the CLI ports have output-target concept). The same neutral data dict, output-pattern grammar, and conformance corpus apply, so a spec renders byte-identically across ports. The standard write path decides from the hash manifest, not the header (section 7), so a template need -not emit the `@generated` marker. The JVM's `TemplateScopeGenerator` writes directly and -keeps no manifest record.) +not emit the `@generated` marker. The JVM's `TemplateScopeGenerator` is recorded in the same +manifest (see [own-your-codegen.md](own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port)). **The spec is declared, never discovered.** Through 1.0 both CLI ports also read a `--template-spec` flag or a project-root `template-spec.json` on their own. Since 1.1.0 a spec diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 14dc2c29e5..0edcfb714b 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -242,14 +242,8 @@ deferred (see [enum-datatype-design.md](../superpowers/specs/2026-05-23-enum-dat Two rules follow from int-backing being a **persistence-layer codec**: -- **An array is mapped element by element.** An enum field with `isArray: true` that - carries `@intValueMap` (its own, or inherited from a shared enum) stores each element as - its declared integer: an `integer[]` column on Postgres, and a JSON array of numbers - (`[5,0]`) where an engine keeps arrays as JSON text (SQLite, D1, MySQL). Each element reads - back as its member. A null array stays null and an empty one stays empty. The array column - has no `CHECK`, the same as a string-backed enum array. Where a port's runtime stores no - primitive array on an engine, see that port's page under [docs/ports/](../ports/) for what it - does there. +- **An array is mapped element by element.** See [Int-backed enum arrays](#int-backed-enum-arrays) + below. - **A stored integer that maps to no member throws on read**, in every port. The row holds data the model says is impossible (a hand-written `INSERT`, or a member removed without a migration); surfacing the raw integer would hand you a "member" that is not one — and is @@ -278,6 +272,36 @@ the Drizzle column codec, the runtime ObjectManager and the view, report and Cub (TypeScript); the OMDB codec (Java); the Exposed `customEnumeration` (Kotlin); the generated Spring enum's `dbValue()` (for a hand-written repository); the Python ObjectManager. +### Int-backed enum arrays + +This section is the one description of the int-backed enum array for every port; the port pages +name only their own classes and point here. + +An enum field with `isArray: true` that carries `@intValueMap` (its own, or inherited from a +shared enum) stores each element as its declared integer: an `integer[]` column on Postgres, and +a JSON array of numbers (`[5,0]`) where an engine keeps arrays as JSON text (SQLite, D1, MySQL). +Each element reads back as its member, in order. A null array stays null and an empty one stays +empty. A stored integer with no member throws on read, as it does for a scalar. The array column +has no `CHECK` (membership of an enum array is checked by the application), while a scalar column +sharing the enum keeps its integer `CHECK`. The generated type is the port's list of the enum +(`List`, `IList`, an array of the union). + +| Port | Engines it stores the array on | Where the mapping lives | +|---|---|---| +| TypeScript | Postgres, SQLite, D1, MySQL | the Drizzle column codec and the runtime ObjectManager | +| C# | Postgres, SQLite, MySQL | the element converter of an EF Core primitive collection; a non-required array is `IList?` | +| Java | Postgres, SQLite, MySQL, Derby | the OMDB codec (`JdbcCodecs`; `PostgresDriver.nativeArrayElementType` on Postgres). A member with no declared integer is refused on write with an `SQLException` naming the field. A repository you write yourself maps each element through the generated enum's `dbValue()` and `fromDbValue(int)` | +| Kotlin | Postgres, SQLite, MySQL | the generated `portableIntEnumArray(name, { toInt }, { fromInt })` column, emitted into `MetaIntEnumArrayColumnType.kt` only in a package that has such a column. Its two lambdas are generated `when` expressions, so a member with no integer is a compile error | +| Python | Postgres only | the codec in `metaobjects.runtime.values`, called by `ObjectManagerDb`. SQLite and MySQL store no primitive array in this runtime, so an enum array of either kind is Postgres-only there | + +The `roundtrip-int-enum-array` persistence scenario +([fixtures/persistence-conformance/README.md](../../fixtures/persistence-conformance/README.md#int-backed-enum-array-scenario)) +gates the Postgres, MySQL, SQLite and D1 columns of this table on the ports that run it. Derby is +not in that corpus. A **string-backed** enum array is a different case: Java's OMDB +maps no native array column for it, and Kotlin's Exposed generator emits a scalar column for it, +so a generated Kotlin controller for such an entity does not compile +([KNOWN_GAPS.md](../../server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md)). + ### Sharing one enum — abstract `field.enum` + `extends` Reuse a constraint set across entities by declaring one **abstract** `field.enum` diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index e4a959b3e0..2641337a7f 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -15,7 +15,7 @@ There are **7 drift sources**, and the toolchain has a guard for each. | **Code-vs-API-doc** | Cross-port codegen from the same metadata. | Build time | | **DB-vs-metadata** | `meta verify --db` (TS CLI) — introspects the live DB and fails if it has drifted from metadata. Includes modeled projection **view bodies** (a changed `CREATE VIEW` is drift, reported with what differs: the first differing excerpt of the text on SQLite/D1, the deparsed body on Postgres's scratch-database path, a fingerprint mismatch otherwise). A view `meta migrate` drops and recreates only because the migration alters a table it reads, with its definition unchanged, is not drift and is not reported; a hand-authored *unmodeled* view is unmanaged and never flagged. A schema concern owned by the Node toolchain regardless of server language; on the JVM ports the runtime auto-create/validator path was removed (ADR-0015) and the `metaobjects:verify` Maven goal is not available. Cloudflare D1 has no client wire protocol, so it can't go through `--db`'s Kysely-driver introspection — use `meta verify --dialect d1 [--d1 ] [--remote]` instead (the same wrangler-shelled-out path `meta migrate --dialect d1` uses); `--remote` is required to check the *deployed* database, not the local `wrangler dev` shadow copy. Pointing `--db file:` at wrangler's local D1 state directory (`.wrangler/state/**/d1/**`) still runs, but only verifies that local copy — `verify` warns when it detects this. | CI on every PR | | **Migration-vs-metadata** | The Node `meta migrate` emits migrations FROM metadata diffs — they cannot drift from metadata by construction. Schema migrations for **every** port are owned by this Node toolchain (`@metaobjectsdev/cli migrate`, ADR-0015); the C# and Python migrate surfaces were removed. | Build time | -| **Generated-edited** | `@generated` headers in emitted code + a committed hash manifest that refuses an edited file by name; in TypeScript only, a three-way merge also preserves hand-edits on the machine that generated the file. `verify --codegen` names each edited file in every port. In TypeScript it fails on one when `.metaobjects/config.json` sets `"verify": { "handEdits": "fail" }` (what `meta init` writes) and reports it as a notice otherwise; the C#, Java, Kotlin and Python gates compare bytes, so an edit always fails there ([cli.md](cli.md)). | Build time (CI) | +| **Generated-edited** | A committed hash manifest refuses an edited generated file by name in every port; only TypeScript also three-way merges, on the machine that generated it. The rule is in [own-your-codegen.md](own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). `verify --codegen` names each edited file in every port. In TypeScript it fails on one when `.metaobjects/config.json` sets `"verify": { "handEdits": "fail" }` (what `meta init` writes) and reports it as a notice otherwise; the C#, Java, Kotlin and Python gates compare bytes, so an edit always fails there ([cli.md](cli.md)). | Build time (CI) | | **Prompt-vs-payload** | FR-004 `Renderer.verify` parses `{{...}}` references in templates and checks each one exists on the payload VO. | Build time + runtime | | **Generated-vs-runtime** | Kotlin / Java `MetadataStartupValidator` (from Spring `ApplicationReadyEvent`) re-loads metadata at startup and asserts the generated table objects match. | App startup | diff --git a/docs/features/migrations/jvm-codegen-hash-manifest.md b/docs/features/migrations/jvm-codegen-hash-manifest.md index b214072ab9..09a6d058e9 100644 --- a/docs/features/migrations/jvm-codegen-hash-manifest.md +++ b/docs/features/migrations/jvm-codegen-hash-manifest.md @@ -18,8 +18,8 @@ Through 8.0.x, `mvn metaobjects:generate` decided whether it could overwrite a f had edited it. A file that was no longer generated (a renamed value object, a deleted entity) stayed on disk forever, because nothing recorded what a run had written. -From 8.1.0 the Java and Kotlin generators record every file they write in a committed hash -manifest, the same one TypeScript, Python and C# use: +From 8.1.0 the Java and Kotlin generators record the generated source they write in a committed +hash manifest, the same one TypeScript, Python and C# use: ``` /.metaobjects/.gen-state/.hashes/.json @@ -39,14 +39,8 @@ generator of your own) and that generator's output directory within the module: } ``` -With it: - -- a file that still matches its record is overwritten as before; -- **a file you edited is refused by name**, and the build logs a warning (it does not fail); -- **a file no generator emits any more is deleted** when it still matches its record, and - refused by name when you edited it; -- a file the manifest has no record of, and that has no `GENERATED` token, is refused, as - before. +The rules that apply now, for every port, are stated once in +[Hand edits and the hash manifest](../own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). ## What to do @@ -122,11 +116,12 @@ also deleted, when every generator writing into its directory sets `overwrite`. That still works: deleting the line is an edit, so the file no longer matches its record and is refused. -## What does not change +## What does not change, and what 1.3.0 adds -- User templates (`TemplateScopeGenerator`, `MustacheTemplateGenerator`), the api-docs pages - and the `META-INF/services` registration are not recorded. They are written on every run as - before, and the run never deletes them. +- User templates, the documentation pages and the `META-INF/services` registration were not + recorded in 8.1.0, so they had no hand-edit protection there. From 1.3.0 they are + recorded like every other generated file. An existing file at such a path with no record + is adopted on the first run, not refused (see the CHANGELOG, 1.3.0 section). - A refusal is still a warning on the JVM. `mvn metaobjects:verify` is the gate that fails: it reports a stale file, says whether `generate` deletes it, and tells you to delete an edited one yourself. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 0f2254a794..6a800c8208 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -443,6 +443,10 @@ diff -u node_modules/@metaobjectsdev/codegen-ts/src/templates/zod-validators.ts codegen/templates/zod-validators.ts ``` +## Hand edits and the hash manifest (every port) + +This is the one statement of the hand-edit guard. The other docs point here. + Whatever you own, hand-edits inside a generated file survive regeneration — but *how* they survive depends on what the toolchain can see, and it is worth knowing which case you are in: @@ -534,12 +538,13 @@ adopts every generated file, deletes nothing, and prints one notice to commit th The token alone decides only when no manifest is configured, which `mvn metaobjects:generate` never does (an embedder driving a generator directly can). -**Four write paths bypass the guard on purpose**, and they are not oversights: user-supplied -templates (`TemplateScopeGenerator`, `MustacheTemplateGenerator`), the `api-docs` generators' -pages, and the `META-INF/services` registration whose entire content is a bare -fully-qualified name. None of them emits content MetaObjects authors, so none is recorded in -the manifest. They are overwritten on every run, and the orphan sweep never deletes them. -`GeneratedFileWriter`'s javadoc lists them. +**Output that cannot carry the `GENERATED` token takes the unmarked path.** User-supplied +templates (`TemplateScopeGenerator`, `MustacheTemplateGenerator`), the api, HTML, JSON and +PlantUML documentation pages and the `META-INF/services` registration (a bare fully-qualified +name, with nowhere to put a token) are recorded in the manifest like every other generated file. +An unchanged file is not rewritten, and a hand edit is refused by name. The one difference is +adoption: a file at such a path that the manifest has no record of is taken as this toolchain's +output, because the path was only ever written by it. `GeneratedFileWriter`'s javadoc lists them. Two consequences to hold on to: @@ -1204,7 +1209,9 @@ Eject never edits an existing pom. It prints the three things to wire: the `` on the codegen module for the module that runs `metaobjects:generate`, and the new `` for each ``. It never overwrites a copy without `-Dforce`, and `-Dlist` marks each owned copy `identical` -or `DIFFERS: N behind, M of your own`. A copy is `identical` only when every file it owns is: +or `DIFFERS: N behind, M of your own`. A file that already holds exactly the reference bytes +is reported `IDENTICAL` and left unwritten, with or without `-Dforce`, so its timestamp does +not move. A copy is `identical` only when every file it owns is: the classes copied with it, its templates, the shared support classes it imports and the helper runtime its output imports. A differing one is named (`[owned — DIFFERS: 0 behind, 1 of your own; differing: api/index.md.mustache]`), so a resync diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index ede23a890d..4c8b174a68 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -463,10 +463,9 @@ The codegen emits: enum-as-string via `HasConversion()`. An int-backed enum (`@intValueMap`) gets a converter pair that stores the declared integer and throws on a stored integer the map does not describe, and on a write of a value it does not describe (a cast integer, say), rather - than storing another member's integer. On an `isArray` enum that pair is the element converter of an EF Core primitive - collection, so a Postgres column is `integer[]` and a SQLite or MySQL column is a JSON array - of numbers (`[5,0]`). A non-required int-backed enum array is an `IList?`, so a NULL - column reads back as null. + than storing another member's integer. On an `isArray` enum that pair is the element converter + of an EF Core primitive collection; see + [Int-backed enum arrays](../features/field-types.md#int-backed-enum-arrays). - `AuthorRoutes.g.cs` — CRUD minimal-API endpoints. - `AuthorFilterAllowlist.g.cs` — the server-side filter/sort allowlist feeding the generated list handler. diff --git a/docs/ports/java.md b/docs/ports/java.md index 7b77925e62..3e9858e8f2 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -35,11 +35,10 @@ reference generator in the printed entry; without it no documentation generator ## Regeneration and hand edits There is no three-way merge on the JVM (that is TypeScript-only). `mvn metaobjects:generate` -records each file it writes in `.metaobjects/.gen-state/.hashes/`: a file that still matches -is overwritten, and an edited one is refused by name (`keep`, the default) -or replaced (`overwrite`). `mvn metaobjects:eject -Dnames=` copies a -generator into your repo to own. Commit the manifest. Details: -[Own your codegen](../features/own-your-codegen.md). +records each file it writes in `.metaobjects/.gen-state/.hashes/`; an edited file is refused by +name, and `overwrite` replaces it instead. `mvn metaobjects:eject -Dnames=` +copies a generator into your repo to own. Commit the manifest. The rules for every port: +[Hand edits and the hash manifest](../features/own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). ## Undo an eject, strict loading, and diagnostics @@ -946,12 +945,10 @@ the output-pattern grammar are gated byte-identical against the shared `fixtures/template-codegen-conformance/` corpus, so a template that renders here renders the same everywhere. -One deliberate difference from the other ports: this generator writes its output -**directly**, not through `GeneratedFileWriter`, so your template is under no -obligation to emit a marker, and its output is not recorded in the codegen hash manifest. -The tradeoff is that these files are overwritten on every run, and the orphan sweep never -deletes one that is no longer rendered — keep hand edits out of them, and delete a stale one -yourself. +Its output is recorded in the codegen hash manifest like the rest of the Java output, so your +template need not emit a marker. An unchanged file is not rewritten, a hand edit is refused by +name, and a file the template no longer renders is deleted when untouched. The rules for every +port are in [Hand edits and the hash manifest](../features/own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). The data dict your template receives is documented in [`codegen-data-shapes.md`](../features/codegen-data-shapes.md). @@ -1052,17 +1049,11 @@ the runtime classpath, and no stored-procedure callable generator exists (FR-015 TypeScript, C# and Kotlin only). OMDB is data access only; schema migrations are owned by the Node `meta` CLI. -OMDB persists an int-backed `field.enum` array (`@intValueMap` with `isArray: true`, own or -inherited) as each member's declared integer: a native `integer[]` on Postgres -(`PostgresDriver.nativeArrayElementType`), and on SQLite, MySQL and Derby a JSON array of numbers -(`[5,0]`) in a text column, read back as the members in order. A member with no declared integer is -refused on write with an `SQLException` naming the field, and a stored integer with no member fails -the read the way an unmapped scalar does; a null array stays null and an empty one stays empty. The -`roundtrip-int-enum-array` persistence scenario runs in the Java runners. A string-backed enum array -is not covered: a native array column is mapped only for `field.string`, `field.uuid`, -`field.decimal` and the int-backed enum. The generated Spring enum for -an int-backed enum carries `dbValue()` and `fromDbValue(int)`, and the payload types an array field as -`List`, so a repository you write maps each element. +OMDB persists an int-backed `field.enum` array on Postgres, SQLite, MySQL and Derby; the stored +form, the Java specifics and the gating scenario are in +[Int-backed enum arrays](../features/field-types.md#int-backed-enum-arrays). A string-backed enum +array is not covered: a native array column is mapped only for `field.string`, `field.uuid`, +`field.decimal` and the int-backed enum. ## Capability snapshot diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 3f2f1bef5a..a8aa038109 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -25,10 +25,10 @@ Two modules: ## Regeneration and hand edits There is no three-way merge on the JVM (that is TypeScript-only). Kotlin runs through the same -`mvn metaobjects:generate` write path as Java: a file that still matches the committed hash -manifest (`.metaobjects/.gen-state/.hashes/`) is overwritten, and an edited one is refused by -name (or replaced with `overwrite`). `mvn metaobjects:eject -Dnames=` -copies a generator into your repo to own. +`mvn metaobjects:generate` write path as Java, and the same committed manifest +(`.metaobjects/.gen-state/.hashes/`) decides. The rules for every port are in +[Hand edits and the hash manifest](../features/own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). +`mvn metaobjects:eject -Dnames=` copies a generator into your repo to own. ## Undo an eject, strict loading, and diagnostics @@ -950,13 +950,9 @@ the contract is universal. A `field.enum` with `isArray: true` loads, string-backed or int-backed (`@intValueMap`, own or inherited from a shared abstract enum), and the data class types it `List`. -An **int-backed** enum array gets one array column over the declared integers, -`portableIntEnumArray(name, { toInt }, { fromInt })`: a native `INTEGER[]` on Postgres and a -JSON array of numbers (`[5,0]`) on SQLite and MySQL, the same stored form as every other port. -The two lambdas are the generated symbol-to-integer `when` expressions, so a member with no -integer is a compile error, and a stored integer with no member throws on read. The column type is -emitted into `MetaIntEnumArrayColumnType.kt` beside the tables, only in a package that has such a -column. The `roundtrip-int-enum-array` persistence scenario runs in this port. +An **int-backed** enum array gets one generated array column over the declared integers, +`portableIntEnumArray`. Its stored form, the Kotlin specifics and the gating scenario are in +[Int-backed enum arrays](../features/field-types.md#int-backed-enum-arrays). A **string-backed** enum array still has no Exposed array column: `enumColumnSpec` emits the scalar `enumerationByName(...)` for it, so the generated controller for such an entity does not compile. @@ -970,7 +966,7 @@ Persist it through your own column until the generator emits one. | Code-vs-API-doc | Cross-port codegen from same metadata | Build time | | DB-vs-metadata | `MetadataStartupValidator.validate(loader)` at Spring `ApplicationReadyEvent`; live-DB schema drift: TS toolchain `meta verify --db` | App startup; CI on every PR (TS) | | Migration-vs-metadata | TS toolchain `meta migrate` emits from metadata diffs (`meta:migrate` Maven goal was removed) | Build time | -| Generated-edited | `@generated` KotlinPoet headers | Code review | +| Generated-edited | Hash manifest: an edited file is refused by name; `mvn metaobjects:verify` reports it | Build time | | Prompt-vs-payload | `KotlinRenderHelperGenerator`'s build-time drift gate + Java `Renderer.verify` | Build time + runtime | | Generated-vs-runtime | `MetadataStartupValidator.validate(loader)` from Spring `ApplicationReadyEvent` | App startup | diff --git a/docs/ports/python.md b/docs/ports/python.md index 3aaf7509e1..b9146d0b01 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -781,12 +781,10 @@ that file's root package, so `package` on such a node is already the full A `field.enum` with `@intValueMap` (own or inherited from a shared abstract enum) is stored as its declared integers while `ObjectManager` callers pass and receive member symbols. The codec in `metaobjects.runtime.values` (called by `ObjectManagerDb`) encodes on every write and on filter operands, and decodes on -every read. On an `isArray: true` field it does this for each element. On Postgres the array is an -`integer[]` holding the ints in order: `["PUBLISHED", "DRAFT"]` is stored as `{5,0}`. An empty -array stays empty, a null array stays null, and a null element stays a null element. An int that -has no member raises `ValueError` on read, whether it is a scalar or an array element. SQLite and -MySQL cannot store an array of any primitive type in this runtime, so an enum array of either kind -is Postgres-only. +every read. On an `isArray: true` field it does this for each element, on Postgres only (see +[Int-backed enum arrays](../features/field-types.md#int-backed-enum-arrays)); a null element stays +a null element. An int that has no member raises `ValueError` on read, whether it is a scalar or an +array element. ### Run-time validation diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java index 1daff71195..bce483dc41 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java @@ -29,15 +29,17 @@ * Wire it in the pom like any generator — {@code } plus an * {@code }{@code } — from a module the plugin's * classpath can see (the {@code codegen/} module {@code mvn metaobjects:eject} scaffolds is - * one). {@code mvn metaobjects:verify} re-runs it into a temp dir and diffs, with nothing to + * one). {@code mvn metaobjects:verify} re-runs it in memory and diffs, with nothing to * register. * *

Writing. A file whose content carries this toolchain's {@code GENERATED} header * comment goes through {@link GeneratedFileWriter}, so an existing file WITHOUT the marker — * one someone took ownership of — is refused with a warning, exactly as for the reference * generators. Content that carries no such header (JSON, YAML — formats that cannot hold a - * comment) is written as given: the marker rule would let run 1 write it and refuse it on - * every run after, freezing it behind a green build. + * comment) goes through {@link GeneratedFileWriter#writeUnmarked}: it is recorded in the hash + * manifest and guarded the same way, but never refused for lacking a marker it cannot carry (the + * marker rule would let run 1 write it and refuse it on every run after, freezing it behind a + * green build). */ public abstract class FileEmittingGenerator extends GeneratorBase { @@ -63,7 +65,7 @@ public void execute(MetaDataLoader loader) { if (GeneratedFileWriter.looksGenerated(f.content())) { GeneratedFileWriter.write(target, f.content()); } else { - GeneratedFileWriter.writeIfChanged(target, f.content()); + GeneratedFileWriter.writeUnmarked(target, f.content()); } } catch (IOException e) { throw new GeneratorException(getClass().getSimpleName() + ": could not write " + target + ": " + e, e); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java index 9ddfb75a61..1cc1afeb9c 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java @@ -62,7 +62,6 @@ public void execute( MetaDataLoader loader ) { filename = path; File fp = new File(outDir, path ); - if ( !fp.exists()) fp.mkdirs(); String fn = getSingleOutputFilename( md ); File f = new File( fp, fn ); @@ -99,7 +98,6 @@ public void execute( MetaDataLoader loader ) { // Create output file File outf = new File(finalOutDir, getOutputFilename()); - outf.createNewFile(); // Get the printwriter out = finalBuffer; // written below, and only when the bytes differ from what is on disk @@ -140,7 +138,7 @@ else if ( out != null ) { } if ( finalFile != null && out != null ) { try { - GeneratedFileWriter.writeIfChanged(finalFile.toPath(), finalBuffer.toByteArray()); + GeneratedFileWriter.writeUnmarked(finalFile.toPath(), finalBuffer.toByteArray()); } catch (IOException e) { throw new GeneratorException( "Unable to write to file [" + filename + "]: " + e, e ); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java index 7376c52bce..8b21c7c118 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java @@ -26,7 +26,6 @@ public void execute( MetaDataLoader loader ) { // Create output file filename = getOutputFilename(); outf = new File(getOutputDir(), filename ); - outf.createNewFile(); // Get the printwriter pw = new PrintWriter(buffer); // written below, and only when the bytes differ from what is on disk @@ -52,7 +51,7 @@ public void execute( MetaDataLoader loader ) { else if ( pw != null ) pw.close(); if ( outf != null && pw != null ) { try { - com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(outf.toPath(), buffer.toByteArray()); + com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(outf.toPath(), buffer.toByteArray()); } catch (IOException e) { throw new GeneratorException( "Unable to write to file [" + filename + "]: " + e, e ); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java index 5b01c5186e..7358523e80 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java @@ -27,7 +27,6 @@ public void execute(MetaDataLoader loader) { try { // Create output file outf = new File(getOutputDir(), getOutputFilename()); - outf.createNewFile(); // Create the HTML Writer fos = buffer; // written below, and only when the bytes differ from what is on disk @@ -46,7 +45,7 @@ public void execute(MetaDataLoader loader) { // NOTE: This is critical as the close flushes the HTML to the outputstream if (writer != null) writer.close(); else if (fos != null) fos.close(); - if (outf != null && fos != null) com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(outf.toPath(), buffer.toByteArray()); + if (outf != null && fos != null) com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(outf.toPath(), buffer.toByteArray()); } catch (IOException e) { log.error("Error closing HTML file [" + outf + "]: " + e, e); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java index c41be7f4e6..e5ce91f183 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java @@ -27,7 +27,6 @@ public void execute(MetaDataLoader loader) { try { // Create output file outf = new File(getOutputDir(), getOutputFilename()); - outf.createNewFile(); // Create the JSON Writer fos = buffer; // written below, and only when the bytes differ from what is on disk @@ -46,7 +45,7 @@ public void execute(MetaDataLoader loader) { // NOTE: This is critical as the close flushes the JSON to the outputstream if (writer != null) writer.close(); else if (fos != null) fos.close(); - if (outf != null && fos != null) com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(outf.toPath(), buffer.toByteArray()); + if (outf != null && fos != null) com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(outf.toPath(), buffer.toByteArray()); } catch (IOException e) { log.error("Error closing JSON file [" + outf + "]: " + e, e); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java index e2095434fb..9e62923a22 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java @@ -200,13 +200,10 @@ private void emitProviderSource(Map fqnToClass) throws IOExcepti private void emitServicesRegistration() throws IOException { File servicesDir = new File(getOutputDir(), "META-INF" + File.separatorChar + "services"); - if (!servicesDir.exists()) servicesDir.mkdirs(); File services = new File(servicesDir, ObjectClassBindingProvider.class.getName()); - // NOT routed through GeneratedFileWriter, deliberately: a META-INF/services file's - // content is a bare provider FQN with nowhere to carry a GENERATED marker. Guarding it - // would make the FIRST run write and every run after refuse — the artifact frozen while - // the build stays green, which is the failure the guard exists to prevent. - GeneratedFileWriter.writeIfChanged(services.toPath(), (PROVIDER_FQN + "\n").getBytes(StandardCharsets.UTF_8)); + // Unmarked: a META-INF/services file's content is a bare provider FQN with nowhere to + // carry a GENERATED marker. + GeneratedFileWriter.writeUnmarked(services.toPath(), (PROVIDER_FQN + "\n").getBytes(StandardCharsets.UTF_8)); } private static String escape(String s) { diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java index b0d4d38df2..f4078e0920 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java @@ -79,17 +79,11 @@ public void execute(MetaDataLoader loader) { for (EmittedFile f : files) { Path target = outDir.toPath().resolve(f.path()); try { - Files.createDirectories(target.getParent()); - // NOT routed through GeneratedFileWriter, deliberately. This emits whatever - // a USER's `--template-spec` Mustache renders — SQL, markdown, CSV, anything - // — and that content carries no obligation to include the `GENERATED` marker - // the guard looks for. Guarding it made the first run write and every run - // after silently refuse, so metadata changes stopped reaching the artifact - // with the build still green. - // - // The marker floor protects output whose header WE control. User template - // output is not that. - com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(target, f.content()); + // Unmarked: this emits whatever a USER's `--template-spec` Mustache renders — + // SQL, markdown, CSV, anything — and that content carries no obligation to + // include the `GENERATED` marker. It is still recorded in the hash manifest, so + // unchanged bytes are not rewritten and a hand edit is refused by name. + com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(target, f.content()); } catch (IOException e) { throw new GeneratorException( "Failed to write template-codegen output [" + target + "]: " + e.getMessage(), e); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index 81f2ba7a6d..31683df3ee 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -54,10 +54,9 @@ * {@code mvn metaobjects:generate}, where failing the reactor over a file the user chose * to own would punish exactly the person the guard is protecting. * - *

WHAT THIS GUARD MUST NOT WRAP. It only fits output whose header we - * control, because "no marker ⇒ not ours" is sound only when our own emitters always - * write the marker. These write paths deliberately bypass it, and re-routing them would - * break them silently rather than loudly: + *

Output that cannot carry the marker. "No marker ⇒ not ours" is sound only for + * output whose header we control. Some output has no room for one, and goes through + * {@link #writeUnmarked} instead of {@link #write}: * *

    *
  • The {@code api-docs} generators' pages — rendered from {@code templates/api/*.mustache}, @@ -66,14 +65,22 @@ * renders (SQL, markdown, CSV); the content is not ours to require a marker of.
  • *
  • {@code MustacheTemplateGenerator} — same reason: the body comes from a user-supplied * mustache template, in an output format we do not choose.
  • + *
  • The HTML, JSON and PlantUML documentation generators.
  • *
  • {@code JavaObjectCodeGenerator}'s {@code META-INF/services} registration — the file's * entire content is a bare provider FQN, with nowhere to put a marker.
  • *
* - *

Guarding any of these made the FIRST run write and every run after refuse, so the artifact - * froze while the build stayed green — the exact silent-staleness failure this class was - * added to prevent, produced by the class itself. Before wrapping a new write site, check - * that its emitter actually writes the marker. + *

Routing these through {@link #write} would make the FIRST run write and every run after + * refuse, so the artifact froze while the build stayed green. {@link #writeUnmarked} records them + * in the hash manifest like every other generated file, so a hand edit to one is refused by name + * as it is in the other ports, but an existing file it has no record of is taken as this + * toolchain's output (the path has only ever been written by it) rather than refused for lacking + * a marker it could never have carried. + * + *

Every generator writes through this class. {@code GeneratorWritePathTest} (in the Maven plugin) runs + * every registered Java and Kotlin generator and fails the build when a file is left on disk that + * this class did not write, or when a second run rewrites a file, so a new generator cannot skip + * the manifest or the unchanged-bytes check. */ public final class GeneratedFileWriter { @@ -394,19 +401,40 @@ public enum Outcome { * with a generic one. */ public static Outcome write(Path outFile, String content) throws IOException { + return write(outFile, content, false); + } + + /** + * {@link #write} for output that cannot carry the {@code GENERATED} marker (template output, + * documentation pages, a {@code META-INF/services} file; see the class comment). The one + * difference: a file at this path that the manifest has no record of, or any file when no + * manifest is configured, is taken as this toolchain's output instead of refused for lacking + * the marker. Once recorded, it is guarded like every other generated file: unchanged bytes + * are not rewritten and a hand edit is refused under {@code handEdits=keep}. + */ + public static Outcome writeUnmarked(Path outFile, String content) throws IOException { + return write(outFile, content, true); + } + + /** {@link #writeUnmarked(Path, String)} for UTF-8 bytes already encoded. */ + public static Outcome writeUnmarked(Path outFile, byte[] utf8) throws IOException { + return write(outFile, new String(utf8, StandardCharsets.UTF_8), true); + } + + private static Outcome write(Path outFile, String content, boolean unmarked) throws IOException { Run run = ACTIVE_RUN.get(); if (run != null) { run.emittedPaths.add(outFile.toAbsolutePath().normalize()); } if (run == null || run.genStateDir == null) { - return writeMarkerOnly(outFile, content, run); + return writeMarkerOnly(outFile, content, run, unmarked); } String key = OrphanSweep.keyFor(run.projectRoot, outFile); if (key == null) { run.untrackedCount++; - return writeMarkerOnly(outFile, content, run); + return writeMarkerOnly(outFile, content, run, unmarked); } if (!Files.exists(outFile)) { @@ -423,8 +451,10 @@ public static Outcome write(Path outFile, String content) throws IOException { // output, from before a manifest existed (or before this generator's entry did) // — adopt it. No marker ⇒ hand-written, refused exactly as always; `handEdits` // never applies here, because a file never recorded as ours is not ours to - // replace under any policy. - if (looksGenerated(current)) { + // replace under any policy. Unmarked output has no marker to look for: its path + // was only ever written by this toolchain, unconditionally before it joined the + // manifest, so it is adopted. + if (unmarked || looksGenerated(current)) { performWrite(outFile, content, run); run.record(key, HashManifest.contentHash(content)); run.adoptedPaths.add(outFile.toString()); @@ -467,14 +497,15 @@ public static Outcome write(Path outFile, String content) throws IOException { } /** The legacy, manifest-less decision: overwrite a marker-bearing file, refuse any other. */ - private static Outcome writeMarkerOnly(Path outFile, String content, Run run) throws IOException { + private static Outcome writeMarkerOnly(Path outFile, String content, Run run, boolean unmarked) + throws IOException { // The marker question comes FIRST, and a refusal returns before anything is // claimed. A path the adopter hand-owns is a path NO generator can write, so two // generators emitting different content there is not an order-dependent output — // there is no output. Claiming first threw a GeneratorException and killed the // build over a conflict that could not reach disk, contradicting this class's own // rule that refusing is a WARNING and never a build failure. - if (Files.exists(outFile) + if (!unmarked && Files.exists(outFile) && !looksGenerated(Files.readString(outFile, StandardCharsets.UTF_8))) { LOG.warn(refusedMessage(outFile)); if (run != null) run.refusedCount++; diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java index 9d0a0bfed9..39c8fd3fef 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java @@ -559,4 +559,82 @@ public void captureRun_holdsEveryWriteInMemoryAndWritesNothing() throws Exceptio assertFalse("a capture run writes no file", Files.exists(tmp.getRoot().toPath().resolve("virtual"))); assertNull(GeneratedFileWriter.currentRun()); } + + // === output that cannot carry the marker (template, docs, services files) ========= + + private static final String PAGE = "# Customer\n\nA page with no marker.\n"; + + @Test + public void unmarked_noManifest_overwritesWhatIsThereInsteadOfRefusing() throws Exception { + Path out = tmp.getRoot().toPath().resolve("docs/customer.md"); + Files.createDirectories(out.getParent()); + Files.writeString(out, "old page\n"); + assertEquals(GeneratedFileWriter.Outcome.WRITTEN, GeneratedFileWriter.writeUnmarked(out, PAGE)); + assertEquals(PAGE, Files.readString(out)); + } + + @Test + public void unmarked_withManifest_isRecordedAndAnExistingUnrecordedFileIsAdopted() throws Exception { + Path project = tmp.newFolder().toPath(); + Path genState = project.resolve(".metaobjects/.gen-state"); + Path out = project.resolve("docs/customer.md"); + Files.createDirectories(out.getParent()); + Files.writeString(out, "a page from before the manifest\n"); + + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + assertEquals(GeneratedFileWriter.Outcome.WRITTEN, GeneratedFileWriter.writeUnmarked(out, PAGE)); + assertEquals(List.of(out.toString()), run.adoptedPaths()); + } + assertEquals(PAGE, Files.readString(out)); + assertEquals(HashManifest.contentHash(PAGE), HashManifest.recordedHash(genState, "docs/customer.md")); + } + + @Test + public void unmarked_withManifest_unchangedBytesAreNotRewritten() throws Exception { + Path project = tmp.newFolder().toPath(); + Path genState = project.resolve(".metaobjects/.gen-state"); + Path out = project.resolve("docs/customer.md"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + GeneratedFileWriter.writeUnmarked(out, PAGE.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + Files.setLastModifiedTime(out, LONG_AGO); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + assertEquals(GeneratedFileWriter.Outcome.UNCHANGED, GeneratedFileWriter.writeUnmarked(out, PAGE)); + } + assertEquals(LONG_AGO, Files.getLastModifiedTime(out)); + } + + @Test + public void unmarked_withManifest_aHandEditIsRefusedByNameUnderKeep() throws Exception { + Path project = tmp.newFolder().toPath(); + Path genState = project.resolve(".metaobjects/.gen-state"); + Path out = project.resolve("docs/customer.md"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + GeneratedFileWriter.writeUnmarked(out, PAGE); + } + String edited = PAGE + "my own paragraph\n"; + Files.writeString(out, edited); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + run.attributeTo("api-docs", GeneratedFileWriter.HAND_EDITS_KEEP, null); + assertEquals(GeneratedFileWriter.Outcome.REFUSED, GeneratedFileWriter.writeUnmarked(out, PAGE + "new\n")); + } + assertEquals(edited, Files.readString(out)); + assertEquals(HashManifest.contentHash(PAGE), HashManifest.recordedHash(genState, "docs/customer.md")); + } + + @Test + public void unmarked_captureRun_holdsTheBytesAndWritesNothing() throws Exception { + Path out = tmp.getRoot().toPath().resolve("virtual/docs/customer.md"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginCaptureRun()) { + GeneratedFileWriter.writeUnmarked(out, PAGE); + assertEquals(PAGE, new String(run.captured().get(out.toAbsolutePath().normalize()), + java.nio.charset.StandardCharsets.UTF_8)); + } + assertFalse(Files.exists(tmp.getRoot().toPath().resolve("virtual"))); + } } diff --git a/server/java/codegen-kotlin/README.md b/server/java/codegen-kotlin/README.md index a695d11ffd..89ef6b1285 100644 --- a/server/java/codegen-kotlin/README.md +++ b/server/java/codegen-kotlin/README.md @@ -174,7 +174,7 @@ No hand-written Exposed wiring needed. | Generated-code-vs-metadata (codegen drift) | `meta:verify` goal (regenerate-to-temp + compare) | Build time / CI | | Code-vs-API-doc | Cross-port codegen from same metadata | Build time | | DB-vs-metadata, Migration-vs-metadata | TypeScript toolchain (`@metaobjectsdev/cli migrate`) — schema migrations and live-DB schema-drift verification are TS-only | Build time / CI | -| Generated-edited | `@generated` headers in KotlinPoet output | Code review | +| Generated-edited | Hash manifest: an edited file is refused by name; `mvn metaobjects:verify` reports it | Build time | | Prompt-vs-payload | `KotlinRenderHelperGenerator`'s build-time drift gate + Java `Renderer.verify` | Build time + runtime | | Generated-vs-runtime | `MetadataStartupValidator.validate(loader)` from Spring `ApplicationReadyEvent` | App startup | diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md index 830e038dd5..45a1e60ed5 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md @@ -235,8 +235,8 @@ An `isArray` `field.enum` that is string-backed is typed `List` on the data c `KotlinExposedTableGenerator.enumColumnSpec` emits a SCALAR column for it (`enumerationByName` / `customEnumeration`), so the generated controller for the entity does not compile. Nothing silently stores symbols in the wrong column: the mismatch fails the build. The fix is the same shape as the -int-backed one, which has its own array column (`portableIntEnumArray`, in -`MetaIntEnumArrayColumnType.kt`): an array column whose element codec is the enum's. The compile +int-backed one ([Int-backed enum arrays](../../../../../../../../../../docs/features/field-types.md#int-backed-enum-arrays)): +an array column whose element codec is the enum's. The compile gates carry no string-backed enum array, so none of them excludes anything. ## Composite-FK relationships not emitted diff --git a/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java b/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java index df7b50b7af..f1d541bbed 100644 --- a/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java +++ b/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java @@ -294,14 +294,11 @@ private void generateFileFromTemplate(MetaObject metaObject, TemplateDefinition String fileName = className + "." + template.getOutputFileExtension(); String packagePath = template.isPackagePath() ? getPackagePath(metaObject) : ""; - // Create output directory + // Write generated file (the writer creates the directory). Unmarked: the body is a + // user template's output, in a format we do not choose. Path outputPath = Paths.get(outputDir, packagePath); - Files.createDirectories(outputPath); - - // Write generated file File outputFile = outputPath.resolve(fileName).toFile(); - com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged( - outputFile.toPath(), generatedCode, java.nio.charset.Charset.defaultCharset()); + com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(outputFile.toPath(), generatedCode); log.debug("Generated file: {}", outputFile.getAbsolutePath()); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/FmtSupport.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/FmtSupport.java index 01ea9c1647..7cf7b8828c 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/FmtSupport.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/FmtSupport.java @@ -366,7 +366,7 @@ private static String readString(Path path) { private static void writeString(Path path, String content) { try { - Files.writeString(path, content, StandardCharsets.UTF_8); + com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(path, content); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java index 413ebc5cde..192fa7d422 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java @@ -203,7 +203,7 @@ static void write(Path file, Stored stored) { o.add("outputs", outs); try { Files.createDirectories(file.getParent()); - Files.writeString(file, GSON.toJson(o) + "\n", StandardCharsets.UTF_8); + com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(file, GSON.toJson(o) + "\n"); } catch (IOException e) { throw new UncheckedIOException("Could not write the codegen fingerprint at " + file, e); } diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/InitMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/InitMojo.java index aa5723424d..731fabff61 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/InitMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/InitMojo.java @@ -104,8 +104,7 @@ static Result scaffold(Path root) throws IOException { kept.add(f[0]); continue; } - Files.createDirectories(path.getParent()); - Files.writeString(path, f[1], StandardCharsets.UTF_8); + com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(path, f[1]); wrote.add(f[0]); } return new Result(wrote, kept); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataEjectMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataEjectMojo.java index aab627e11d..436a703221 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataEjectMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataEjectMojo.java @@ -14,6 +14,7 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; +import com.metaobjects.generator.util.GeneratedFileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; @@ -392,6 +393,9 @@ private void ejectTemplates(List resolved, Path resourc getLog().info("Copied template " + ref + " -> " + target + ", REPLACING the file that was there (-Dforce=true)."); break; + case IDENTICAL: + getLog().info(target + IDENTICAL_NOTE); + break; case PRESERVED: getLog().info(target + " already exists — " + describeOwned(target, content) + " Left untouched (-Dforce=true replaces it)."); @@ -419,6 +423,9 @@ private void ejectSupport(Set support, Path dir, String pkg) throws Mojo getLog().info("Copied support " + simpleName + " -> " + target + ", REPLACING the file that was there (-Dforce=true)."); break; + case IDENTICAL: + getLog().info(target + IDENTICAL_NOTE); + break; case PRESERVED: getLog().info(target + " already exists — " + describeOwned(target, owned) + " Left untouched (-Dforce=true replaces it)."); @@ -502,6 +509,9 @@ private void ejectRuntime(List runtime, Path runtimeRoot, String runtime getLog().info("Copied runtime " + simpleName + " -> " + target + ", REPLACING the file that was there (-Dforce=true)."); break; + case IDENTICAL: + getLog().info(target + IDENTICAL_NOTE); + break; case PRESERVED: getLog().info(target + " already exists — " + describeOwned(target, owned) + " Left untouched (-Dforce=true replaces it)."); @@ -550,18 +560,24 @@ private void printRuntimeWiring(Path runtimeRoot, String runtimePkg, List " + target + ", REPLACING the file " + "that was there (-Dforce=true)."); break; + case IDENTICAL: + getLog().info(target + IDENTICAL_NOTE); + break; case PRESERVED: try { String existing = Files.readString(target, StandardCharsets.UTF_8); @@ -600,7 +619,8 @@ private void reportEject(String what, Path target, String rewritten, WriteStatus } /** Writes {@code codegen/pom.xml} only if absent (or {@code -Dforce=true}). Returns - * whether it wrote (vs. left an existing one alone). */ + * whether the pom is now the reference one (written, or already identical) rather than an + * existing one left alone. */ private boolean writeCodegenPomIfNeeded(Path codegenRoot, String pkg, Set ports) throws MojoExecutionException { Path pom = codegenRoot.resolve("pom.xml"); @@ -612,7 +632,10 @@ private boolean writeCodegenPomIfNeeded(Path codegenRoot, String pkg, SetThe JVM ports have no shared runner loop: each generator writes its own files, and the hash + * manifest, the hand-edit refusal, the output-path collision check, the in-memory capture + * {@code verify} renders through and the unchanged-bytes check all live in that one class. A + * generator that opens a file any other way silently loses all five. + * + *

The oracle is the disk. Each generator in both registries runs, as the Maven goal runs it, + * over the shared fitness corpus inside one {@link GeneratedFileWriter.Run} with a manifest; every + * file then left under the output directory must be among the run's emitted paths, because a + * file only the writer saw is a file the writer owns. A second run over the same tree must then + * leave every file's bytes and modification time alone. A generator that writes a file by another + * API fails the first check whatever API it used; one that rewrites unchanged bytes fails the + * second. + */ +public class GeneratorWritePathTest { + + private Path root; + private Path repo; + private Path canonical; + private MetaDataLoader loader; + + @Before + public void setUp() throws IOException { + repo = findRepo(); + canonical = repo.resolve("fixtures/persistence-conformance/canonical"); + String scratch = System.getenv("DEV_SCRATCH"); + Path base = scratch == null || scratch.isBlank() ? Path.of(System.getProperty("java.io.tmpdir")) : Path.of(scratch); + Files.createDirectories(base); + root = Files.createTempDirectory(base, "generator-write-path-"); + URI uri = URIHelper.toURI("model:file:" + + canonical.resolve("meta.fitness.json").toAbsolutePath().toString().replace('\\', '/')); + loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "generator-write-path-test"); + loader.setSourceURIs(List.of(uri)); + loader.init(); + } + + @After + public void tearDown() throws IOException { + if (root == null) return; + try (Stream s = Files.walk(root)) { + for (Path p : s.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(p); + } + } + + private static Path findRepo() { + for (Path p = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize(); p != null; p = p.getParent()) { + if (Files.isDirectory(p.resolve("fixtures/persistence-conformance/canonical"))) return p; + } + throw new IllegalStateException("could not locate the repository root"); + } + + /** One generator to run: a stable name beside the language port, and a fresh instance per run. */ + private record Entry(String name, Supplier factory) {} + + private static Generator construct(String classname) { + try { + return (Generator) Class.forName(classname).getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(classname, e); + } + } + + private static List registered() { + List all = new ArrayList<>(); + GeneratorRegistry.list().forEach((name, info) -> + all.add(new Entry("java-" + name, () -> construct(info.classname())))); + GeneratorRegistryKt.getGENERATOR_REGISTRY().forEach((name, info) -> + all.add(new Entry("kotlin-" + name, () -> info.getFactory().invoke()))); + return all; + } + + private Map args(Entry e, Path outDir) { + Map a = new LinkedHashMap<>(); + a.put("outputDir", outDir.toString()); + a.put("packageName", "fitness"); + a.put("templateRoot", canonical.resolve("prompts").toString()); + a.put("type", "class"); + a.put("flavor", "pojoAware"); + switch (e.name()) { + case "java-template" -> { + a.put("template", "entity"); + a.put("scope", "perEntity"); + a.put("outputPattern", "{name}.txt"); + a.put("templatesDir", repo.resolve("fixtures/template-codegen-conformance/templates").toString()); + } + case "java-ai-docs", "java-html-docs", "java-json-schema", "java-plantuml" -> + a.put("outputFilename", "document.out"); + case "java-shared-model", "kotlin-shared-model" -> { + a.put("name", "fitness"); + a.put("include", "fitness::**"); + a.put("files", canonical.resolve("meta.fitness.json").toString()); + a.put("version", "1.0.0"); + } + case "java-mustache" -> { + a.put("templatePath", repo.resolve("server/java/codegen-mustache/src/test/resources/templates").toString()); + a.put("targetLanguage", "java"); + a.put("templateName", "basic-entity"); + } + default -> { } + } + return a; + } + + /** Generators keyed off model nodes the fitness corpus does not declare, so they write nothing over it. */ + private static final List NO_INPUT_IN_CORPUS = + List.of("java-trace-helper", "java-requirement-tests", "kotlin-stored-proc", "kotlin-requirement-tests"); + + /** What each run wrote: the files left on disk, and the paths the writer was asked for. */ + private record Result(Map disk, Set emitted) {} + + private Result run(List entries, Path outRoot, Path genState) throws Exception { + Set emitted = new TreeSet<>(); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, root); + for (Entry e : entries) { + run.attributeTo(e.name()); + // A directory each: the entity and value-object tiers both write a type per value + // object, and this test measures the write path, not a coherent project. + Generator g = e.factory().get(); + g.setArgs(args(e, outRoot.resolve(e.name()))); + g.execute(loader); + } + emitted.addAll(run.emittedPaths()); + } + Map disk = new TreeMap<>(); + try (Stream s = Files.walk(outRoot)) { + for (Path p : s.filter(Files::isRegularFile).toList()) disk.put(p.toAbsolutePath().normalize(), Files.readAllBytes(p)); + } + return new Result(disk, emitted); + } + + @Test + public void everyFileOnDiskWasWrittenThroughTheWriterAndASecondRunWritesNothing() throws Exception { + List entries = registered(); + assertTrue("both registries should contribute", entries.stream().anyMatch(e -> e.name().startsWith("java-")) + && entries.stream().anyMatch(e -> e.name().startsWith("kotlin-"))); + Path out = root.resolve("out"); + Path genState = root.resolve(".metaobjects/.gen-state"); + + Result first = run(entries, out, genState); + assertFalse("the corpus generated nothing at all", first.disk().isEmpty()); + List bypassed = new ArrayList<>(); + for (Path p : first.disk().keySet()) if (!first.emitted().contains(p)) bypassed.add(out.relativize(p)); + assertEquals("These files are on disk but no GeneratedFileWriter call produced them: write generated files with " + + "GeneratedFileWriter.write (or writeUnmarked for output that cannot carry the GENERATED marker), so " + + "the file is recorded in the hash manifest and unchanged bytes are never rewritten.", + List.of(), bypassed); + + Map recorded = HashManifest.load(genState); + List unrecorded = new ArrayList<>(); + for (Path p : first.disk().keySet()) { + if (!recorded.containsKey(root.relativize(p).toString().replace('\\', '/'))) unrecorded.add(out.relativize(p)); + } + assertEquals("These files are on disk but the hash manifest has no record of them: a generator that writes " + + "through writeIfChanged skips the manifest, so a hand edit to its output is never refused.", + List.of(), unrecorded); + + List silent = new ArrayList<>(); + for (Entry e : entries) { + Path dir = out.resolve(e.name()); + boolean wrote; + try (Stream s = Files.isDirectory(dir) ? Files.walk(dir) : Stream.empty()) { + wrote = s.anyMatch(Files::isRegularFile); + } + if (!wrote) silent.add(e.name()); + } + assertEquals("The generators that write no file over the fitness corpus changed: a generator newly silent was " + + "given wrong args and the gate proves nothing about it; one that now writes belongs out of " + + "NO_INPUT_IN_CORPUS.", NO_INPUT_IN_CORPUS, silent); + + FileTime old = FileTime.fromMillis(1_000_000_000_000L); + for (Path p : first.disk().keySet()) Files.setLastModifiedTime(p, old); + + Result second = run(entries, out, genState); + assertEquals("a second run changed the set of files", first.disk().keySet(), second.disk().keySet()); + List rewritten = new ArrayList<>(); + for (Map.Entry e : second.disk().entrySet()) { + boolean sameBytes = Arrays.equals(first.disk().get(e.getKey()), e.getValue()); + boolean sameTime = Files.getLastModifiedTime(e.getKey()).equals(old); + if (!sameBytes || !sameTime) rewritten.add(out.relativize(e.getKey())); + } + assertEquals("a second run over an unchanged tree must not write any file", List.of(), rewritten); + } +} diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataEjectMojoTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataEjectMojoTest.java index 682602a2cd..ff011b2c0b 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataEjectMojoTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataEjectMojoTest.java @@ -162,6 +162,36 @@ public void forceReplacesAnEditedCopyWithTheReference() throws Exception { assertFalse(content.contains("hand-edited")); } + @Test + public void forceLeavesAnIdenticalCopyAndPomUnwritten() throws Exception { + mojo("dto", false, null, null).execute(); + Path target = codegenRoot().resolve("src/main/java/com/acme/codegen/SpringDtoGenerator.java"); + Path pom = codegenRoot().resolve("pom.xml"); + java.nio.file.attribute.FileTime longAgo = java.nio.file.attribute.FileTime.fromMillis(1_000_000_000_000L); + Files.setLastModifiedTime(target, longAgo); + Files.setLastModifiedTime(pom, longAgo); + + mojo("dto", true, null, null).execute(); + + assertEquals("an identical copy is not rewritten, even with force", longAgo, Files.getLastModifiedTime(target)); + assertEquals("an identical pom is not rewritten, even with force", longAgo, Files.getLastModifiedTime(pom)); + } + + @Test + public void forceOverAnIdenticalPomStillPrintsTheModulesHint() throws Exception { + mojo("dto", false, null, null).execute(); + MetaDataEjectMojo again = mojo("dto", true, null, null); + Log log = Mockito.mock(Log.class); + again.setLog(log); + + again.execute(); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CharSequence.class); + Mockito.verify(log, Mockito.atLeastOnce()).info(captor.capture()); + assertTrue(captor.getAllValues().stream() + .anyMatch(m -> m.toString().contains("Add this module to the parent pom's :"))); + } + @Test public void aSecondPomIsLeftUntouchedWithoutForce() throws Exception { mojo("dto", false, null, null).execute(); diff --git a/server/typescript/packages/codegen-ts/.gitignore b/server/typescript/packages/codegen-ts/.gitignore index 74463d4f00..7400388270 100644 --- a/server/typescript/packages/codegen-ts/.gitignore +++ b/server/typescript/packages/codegen-ts/.gitignore @@ -1,3 +1,5 @@ # Per-case tsc workspaces for reference-binding-compile.test.ts (mkdtempSync in test/, # removed in finally); left behind only when a run is killed or times out. test/tmp-reference-binding-*/ +# Same for typed-create-compile.test.ts (mkdtempSync in test/, removed in finally). +test/tmp-typed-create-*/