From a732522fcbeb9eb2b90b78cc8718d8fde21988b5 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:27:36 -0500 Subject: [PATCH 1/8] fix(codegen): the gen skip key covers linked generator packages (TypeScript, Rust) TypeScript: the ADR-0064 key dropped every @metaobjectsdev/* import of the config on the assumption that the CLI aliases it onto its engine, while the engine half hashes only the CLI's own dependencies. A package the CLI does not depend on (an independent pack) was then hashed by nothing. Only the packages the CLI actually aliases (CLI_ALIASED_PACKAGES) are left out now. Rust: a crate the owned codegen crate depends on by path is now an input, followed through its own path dependencies; the engine crates its source hash covers are left out. Java (plugin and project classpath content), C# (project references by content, packages by version) and Python (every named module's package by content) had no such gap. --- .../gen-skip-key-linked-generator-packages.md | 10 ++ docs/ports/rust.md | 5 +- server/rust/metaobjects-codegen/src/engine.rs | 113 ++++++++++++++++ .../metaobjects-codegen/tests/run_engine.rs | 53 ++++++++ .../packages/cli/src/lib/gen-fingerprint.ts | 13 +- .../cli/src/lib/load-metaobjects-config.ts | 12 ++ .../gen-fingerprint-linked-package.test.ts | 128 ++++++++++++++++++ 7 files changed, 328 insertions(+), 6 deletions(-) create mode 100644 changelog.d/gen-skip-key-linked-generator-packages.md create mode 100644 server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts diff --git a/changelog.d/gen-skip-key-linked-generator-packages.md b/changelog.d/gen-skip-key-linked-generator-packages.md new file mode 100644 index 0000000000..3e3c69d835 --- /dev/null +++ b/changelog.d/gen-skip-key-linked-generator-packages.md @@ -0,0 +1,10 @@ +- **`meta gen` and `cargo meta gen`: the skip key now covers a linked generator package.** In + TypeScript, the ADR-0064 skip key ignored every `@metaobjectsdev/*` package the config imported, + on the assumption that the CLI aliases it onto its own engine copy. Only the packages the CLI + actually aliases are left out now. Any other `@metaobjectsdev/*` package, such as an independent + pack, is hashed like any third-party generator package: a linked or source checkout by the content + of its files, an installed one by its version. In Rust, a crate the owned `codegen/` crate depends + on by `path` is now an input too, followed through that crate's own path dependencies; the + `metaobjects` and `metaobjects-codegen` engine crates are still covered by the engine's own source + hash. Before this change, editing such a package's generator code while the model, the config and + the lockfile stayed the same left the key unchanged, and `gen` skipped over stale output. diff --git a/docs/ports/rust.md b/docs/ports/rust.md index b02fcb2507..c43a141e65 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -244,7 +244,10 @@ surface (`metaobjects_codegen::{emitted, generator, names, plan, writer}`); the writes (the transport, the command helpers) is inside the generator, so an owned `client` owns its transport too. Every file in `codegen/` is an input of the skip key, whether `eject` wrote it or you added it (a module beside the generator list, say), so editing any of them regenerates. Only the -crate's build directory (`codegen/target`) and its `Cargo.lock` are left out. +crate's build directory (`codegen/target`) and its `Cargo.lock` are left out. A crate it depends on by +`path` (a linked checkout of a pack's generators, say) is an input too, followed through that crate's +own path dependencies, except the `metaobjects` and `metaobjects-codegen` engine crates, whose source +the engine's own hash already covers. `cargo meta gen --list` shows each owned copy as `identical`, or as `DIFFERS` with how many shipped lines it lacks and how many are its own. diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 23726156c7..dfc9e50630 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -296,6 +296,118 @@ pub const OWNED_MANIFEST: &str = "codegen/Cargo.toml"; /// The owned crate's generator list. pub const OWNED_MAIN: &str = "codegen/main.rs"; +/// The crates whose sources [`ENGINE_SOURCE_HASH`] already covers. A path dependency on one +/// of them is the engine, counted once as such. +const ENGINE_CRATES: &[&str] = &["metaobjects", "metaobjects-codegen"]; + +/// What in a path dependency's directory is not an input: cargo's build output and VCS state. +const PATH_DEPENDENCY_NOT_INPUTS: &[&str] = &["target", ".git"]; + +/// Every crate the owned crate reaches through a `path` dependency (a linked or source +/// checkout: a pack's generators, a sibling crate of the adopter's), followed through each +/// one's own manifest, by the content of its directory. Its version does not move when its +/// code does, and cargo rebuilds the owned binary from it, so an edit there changes what the +/// owned generators emit. An engine crate is left out (see [`ENGINE_CRATES`]); a registry or +/// git dependency is named by `codegen/Cargo.toml` itself, which the key already hashes. +fn path_dependency_entries(owned_manifest: &Path) -> Vec { + let mut entries = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut queue = vec![owned_manifest.to_path_buf()]; + while let Some(manifest) = queue.pop() { + let Ok(text) = std::fs::read_to_string(&manifest) else { + continue; + }; + let base = manifest.parent().unwrap_or(Path::new(".")); + for rel in manifest_path_dependencies(&text) { + let dir = base.join(&rel); + let dir = std::fs::canonicalize(&dir).unwrap_or(dir); + if !seen.insert(dir.clone()) { + continue; + } + let dep_manifest = dir.join("Cargo.toml"); + let Ok(dep_text) = std::fs::read_to_string(&dep_manifest) else { + // Cargo will fail on it; until it exists, its absence is the input. + entries.push(InputEntry::new( + KIND_GENERATOR, + format!("path-dependency:{rel}"), + ABSENT, + )); + continue; + }; + let name = manifest_package_name(&dep_text).unwrap_or_else(|| rel.clone()); + if ENGINE_CRATES.contains(&name.as_str()) { + continue; + } + entries.push(InputEntry::new( + KIND_GENERATOR, + format!("path-dependency:{name}"), + hash_tree_except(&dir, PATH_DEPENDENCY_NOT_INPUTS), + )); + queue.push(dep_manifest); + } + } + entries +} + +/// The `path` of every dependency a `Cargo.toml` declares in a table the build compiles +/// (`[dependencies]`, `[build-dependencies]`, their `target.*` and `workspace` forms, and +/// `[dependencies.]`). Dev-dependencies are not built into the owned binary. A line +/// scan, not a TOML parser: the forms cargo writes and the scaffold uses are one-line. +fn manifest_path_dependencies(text: &str) -> Vec { + let mut out = Vec::new(); + let mut in_dependencies = false; + for line in text.lines().map(str::trim) { + if line.starts_with('#') { + continue; + } + if line.starts_with('[') { + let header = line.trim_start_matches('[').split(']').next().unwrap_or(""); + in_dependencies = header + .split('.') + .map(|s| s.trim()) + .any(|s| s == "dependencies" || s == "build-dependencies"); + continue; + } + if in_dependencies && let Some(path) = toml_key_string(line, "path") { + out.push(path); + } + } + out +} + +/// The `[package]` name a `Cargo.toml` declares. +fn manifest_package_name(text: &str) -> Option { + let mut in_package = false; + for line in text.lines().map(str::trim) { + if line.starts_with('[') { + in_package = line == "[package]"; + } else if in_package && let Some(name) = toml_key_string(line, "name") { + return Some(name); + } + } + None +} + +/// The basic-string value of `key` on one TOML line, whether the line is `key = "v"` or an +/// inline table holding it (`dep = { path = "v", ... }`). +fn toml_key_string(line: &str, key: &str) -> Option { + let mut from = 0; + while let Some(at) = line[from..].find(key).map(|i| i + from) { + from = at + key.len(); + let before = line[..at].chars().next_back(); + if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '-') { + continue; + } + let rest = line[from..].trim_start(); + let Some(rest) = rest.strip_prefix('=') else { + continue; + }; + let rest = rest.trim_start().strip_prefix('"')?; + return rest.find('"').map(|end| rest[..end].to_string()); + } + None +} + /// Everything a run knows before it renders: the loaded model, where the files go, the /// manifest and the skip key. struct Prepared<'g> { @@ -474,6 +586,7 @@ fn prepare<'g>( OWNED_DIR, hash_tree_except(&project_root.join(OWNED_DIR), OWNED_NOT_INPUTS), )); + entries.extend(path_dependency_entries(&project_root.join(OWNED_MANIFEST))); } let key = fold(&entries); let stored = fingerprint::read_stored(&gen_state); diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 87e9685d9e..1c64128f20 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -480,6 +480,59 @@ fn every_source_of_an_owned_crate_is_an_input_and_its_build_output_is_not() { assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); } +#[test] +fn a_crate_the_owned_crate_reaches_by_path_is_an_input_and_an_engine_crate_is_not() { + // A pack's generators, linked from a checkout: cargo rebuilds the owned binary from their + // source, and their version does not move when their code does. A skip that did not see + // an edit there would report "nothing changed" over stale output. + let p = Scratch::project("owned-path-deps", &shop_files()); + p.write( + "codegen/Cargo.toml", + "[package]\nname = \"codegen\"\n\n[[bin]]\nname = \"codegen\"\npath = \"main.rs\"\n\n\ + [dependencies]\n\ + metaobjects = { path = \"../engine/metaobjects\" }\n\ + linked-generators = { path = \"../linked\" }\n\n\ + [dev-dependencies]\nscratch-only = { path = \"../dev-only\" }\n", + ); + p.write("codegen/main.rs", "fn main() {}\n"); + p.write( + "linked/Cargo.toml", + "[package]\nname = \"linked-generators\"\n\n[dependencies.deeper]\npath = \"../deeper\"\n", + ); + p.write("linked/src/lib.rs", "// v1\n"); + p.write("deeper/Cargo.toml", "[package]\nname = \"deeper\"\n"); + p.write("deeper/src/lib.rs", "// v1\n"); + p.write( + "engine/metaobjects/Cargo.toml", + "[package]\nname = \"metaobjects\"\n", + ); + p.write("engine/metaobjects/src/lib.rs", "// v1\n"); + p.write( + "dev-only/Cargo.toml", + "[package]\nname = \"scratch-only\"\n", + ); + p.write("dev-only/src/lib.rs", "// v1\n"); + gen_ok(&p); + assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); + + // An edit to the linked crate's source, and to a crate it reaches by path in turn. + p.write("linked/src/lib.rs", "// v2\n"); + let r = gen_ok(&p); + assert_eq!(r.outcome, Outcome::Generated); + assert_eq!(r.no_skip_reason, Some("an input changed")); + assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); + p.write("deeper/src/lib.rs", "// v2\n"); + assert_eq!(gen_ok(&p).outcome, Outcome::Generated); + assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); + + // Not inputs: the linked crate's build output, an engine crate (the engine's own source + // hash covers it) and a dev-dependency, which is not built into the owned binary. + p.write("linked/target/debug/out.rs", "build output"); + p.write("engine/metaobjects/src/lib.rs", "// v2\n"); + p.write("dev-only/src/lib.rs", "// v2\n"); + assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); +} + #[test] fn naming_an_entity_limits_the_run_and_never_skips_or_stores_a_key() { let p = Scratch::project("named", &shop_files()); diff --git a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts index 3a62b84d17..67ee0bef7e 100644 --- a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -23,6 +23,7 @@ import { fileURLToPath } from "node:url"; import type { Collection } from "@metaobjectsdev/sdk/collection"; import { readManifestState } from "@metaobjectsdev/codegen-ts"; import { GEN_CONFIG_FILE } from "./gen-collection.js"; +import { CLI_ALIASED_PACKAGES } from "./load-metaobjects-config.js"; /** Bumped whenever what goes into the fingerprint changes, so an old stored key never matches. */ export const FINGERPRINT_FORMAT = 3; @@ -212,8 +213,8 @@ function cliPackageDir(): string | undefined { } /** - * The engine: this CLI and every package it runs (the config's `@metaobjectsdev/*` imports - * are aliased onto these copies). A compiled single binary has no package tree on disk; its + * The engine: this CLI and every package it runs (the config's imports of the packages in + * `CLI_ALIASED_PACKAGES` are aliased onto these copies). A compiled single binary has no package tree on disk; its * identity is the binary's own content. */ function engineEntries(seen: Set): FingerprintEntry[] { @@ -284,9 +285,11 @@ function configGraphEntries(configFile: string, projectRoot: string, seen: Set = { }, }; +/** + * The packages whose imports the loader rewrites onto the CLI's own copy (every subpath of + * each, and bare `ts-poet`, which goes to the engine's printer). The config never runs the + * project's copy of these, so the `meta gen` skip key counts them as part of the engine + * (gen-fingerprint.ts). Any other package the config imports, `@metaobjectsdev/*` or not, + * runs from the project and is hashed as a generator package. + */ +export const CLI_ALIASED_PACKAGES: ReadonlySet = new Set([ + ...Object.keys(CLI_PKG_PATHS).map((spec) => spec.split("/").slice(0, 2).join("/")), + TS_POET_PKG, +]); + // Resolve a codegen specifier to an absolute path, so a user's // metaobjects.config.ts can import @metaobjectsdev/codegen-ts* without // declaring it directly — the CLI's own copy is used. diff --git a/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts new file mode 100644 index 0000000000..d18ab8ad87 --- /dev/null +++ b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts @@ -0,0 +1,128 @@ +// ADR-0064 — the `meta gen` skip key covers the code of every generator package the config +// imports, `@metaobjectsdev/*` ones included, except the packages the CLI aliases onto its own +// engine (those are the engine, counted once as such). +// +// The defect this pins: the key dropped EVERY `@metaobjectsdev/*` import on the assumption +// that the CLI aliases it, while the engine half only hashes the CLI's own dependencies. A +// package the CLI does not depend on (an independent pack, say) was then hashed by nothing, +// so editing a linked copy's generator left the key unchanged and `meta gen` skipped over +// stale output. +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { genCommand } from "../src/commands/gen.js"; +import { + computeGenInputs, decideGenSkip, keyFor, withModel, + type FingerprintEntry, type GenSelection, +} from "../src/lib/gen-fingerprint.js"; +import { CLI_ALIASED_PACKAGES } from "../src/lib/load-metaobjects-config.js"; +import { collectionLoadOptions } from "../src/lib/collection-load-options.js"; +import { loadMemory, resolveCollection } from "@metaobjectsdev/sdk"; +import { modelHashTree } from "@metaobjectsdev/codegen-ts"; + +// Inside the monorepo, so the config's engine imports resolve as in the other command tests. +const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures/__tmp__"); +const made: string[] = []; +afterAll(() => { for (const d of made) rmSync(d, { recursive: true, force: true }); }); + +/** A `@metaobjectsdev/*` package the CLI does not depend on, linked from a source checkout. */ +const LINKED = "@metaobjectsdev/linked-generator-fixture"; + +const linkedSource = (text: string) => `export function linked() { + return { + name: "linked", + generate() { + return [{ path: "linked.txt", content: ${JSON.stringify(text)} }]; + }, + }; +} +`; + +/** A package the CLI aliases onto its engine (see `CLI_ALIASED_PACKAGES`). */ +const ENGINE_PKG = "@metaobjectsdev/codegen-ts"; + +const ENGINE: FingerprintEntry[] = [{ kind: "engine", name: "(test)", hash: "fixed" }]; +const SELECTION: GenSelection = { entities: [], generators: undefined, strict: false, baseline: "default" }; + +function makeProject(): { root: string; linkedIndex: string } { + mkdirSync(WORKSPACE_TMP, { recursive: true }); + const root = mkdtempSync(join(WORKSPACE_TMP, "gen-linked-")); + made.push(root); + mkdirSync(join(root, ".git")); + mkdirSync(join(root, "metaobjects")); + mkdirSync(join(root, ".metaobjects")); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }) + "\n"); + writeFileSync(join(root, "metaobjects", "meta.shop.json"), JSON.stringify({ + "metadata.root": { package: "shop", children: [{ "object.value": { name: "Note", children: [{ "field.string": { name: "text" } }] } }] }, + }) + "\n"); + + // The linked package: its source lives outside any node_modules, as with a workspace + // member, a clone or `bun link`, and the project's node_modules holds a symlink to it. + const source = join(root, "linked-checkout"); + mkdirSync(source); + writeFileSync(join(source, "package.json"), JSON.stringify({ name: LINKED, version: "0.1.0", type: "module", main: "index.ts" }) + "\n"); + writeFileSync(join(source, "index.ts"), linkedSource("first\n")); + mkdirSync(join(root, "node_modules", "@metaobjectsdev"), { recursive: true }); + symlinkSync(source, join(root, "node_modules", LINKED), "dir"); + + writeFileSync(join(root, "metaobjects.config.ts"), `import { defineConfig } from "@metaobjectsdev/codegen-ts"; +import { linked } from "${LINKED}"; +export default defineConfig({ outDir: "generated", generators: [linked()] }); +`); + return { root, linkedIndex: join(source, "index.ts") }; +} + +async function inputsFor(root: string, engine?: FingerprintEntry[]) { + const c = await resolveCollection(root); + const model = await loadMemory(c.configDir, collectionLoadOptions(c)); + return withModel(computeGenInputs(root, c, c, SELECTION, engine), modelHashTree(model)); +} + +const quiet = async (fn: () => Promise): Promise => { + const log = console.log; const err = console.error; + console.log = () => {}; console.error = () => {}; + try { return await fn(); } finally { console.log = log; console.error = err; } +}; + +describe("the skip key covers a linked @metaobjectsdev/* generator package (ADR-0064)", () => { + test("after a real gen, editing the linked package's generator makes the next gen render", async () => { + const p = makeProject(); + expect(await quiet(() => genCommand([], p.root, "text"))).toBe(0); + expect(readFileSync(join(p.root, "generated", "linked.txt"), "utf-8")).toBe("first\n"); + expect(decideGenSkip(await inputsFor(p.root))).toEqual({ skip: true, recorded: ["generated/linked.txt"] }); + + writeFileSync(p.linkedIndex, linkedSource("second\n")); + // The decision `meta gen` makes before rendering. (Rendering again here would prove nothing + // more: this process already imported the linked module, and the runtime caches it.) + expect(decideGenSkip(await inputsFor(p.root))).toEqual({ skip: false, reason: "an input changed" }); + }); + + test("the linked package is hashed by content; editing it changes the key", async () => { + const p = makeProject(); + const before = await inputsFor(p.root, ENGINE); + const names = before.entries.filter((e) => e.kind === "generator-package").map((e) => e.name); + expect(names).toContain(`${LINKED}/index.ts`); + expect(CLI_ALIASED_PACKAGES.has(LINKED)).toBe(false); + + writeFileSync(p.linkedIndex, linkedSource("second\n")); + expect(keyFor(await inputsFor(p.root, ENGINE), [])).not.toBe(keyFor(before, [])); + }); + + test("an import the CLI aliases onto its engine is not hashed from the project's copy", async () => { + // The config imports `@metaobjectsdev/codegen-ts`, which the CLI rewrites onto its own + // copy: the engine half counts that. A linked copy in the project's node_modules never + // runs, so editing it must leave the key alone. + const p = makeProject(); + const fake = join(p.root, "engine-checkout"); + mkdirSync(fake); + writeFileSync(join(fake, "package.json"), JSON.stringify({ name: ENGINE_PKG, version: "0.0.0", main: "index.ts" }) + "\n"); + writeFileSync(join(fake, "index.ts"), "export const v = 1;\n"); + symlinkSync(fake, join(p.root, "node_modules", ENGINE_PKG), "dir"); + expect(CLI_ALIASED_PACKAGES.has(ENGINE_PKG)).toBe(true); + + const before = await inputsFor(p.root, ENGINE); + expect(before.entries.filter((e) => e.kind === "generator-package" && e.name.startsWith(`${ENGINE_PKG}/`))).toEqual([]); + writeFileSync(join(fake, "index.ts"), "export const v = 2;\n"); + expect(keyFor(await inputsFor(p.root, ENGINE), [])).toBe(keyFor(before, [])); + }); +}); From c29b00c7ca231b16fd989b54586846f3e887ee3d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:36:03 -0500 Subject: [PATCH 2/8] fix(codegen): skip key review follow-ups Rust: follow workspace-inherited path dependencies, [patch]/[replace] tables, single-quoted paths and trailing comments. TypeScript: leave the CLI-aliased packages out of a generator package's closure too. Both ports bump their fingerprint format. The linked-package test runs in scratch. --- .../gen-skip-key-linked-generator-packages.md | 7 +- docs/ports/rust.md | 7 +- server/rust/metaobjects-codegen/src/engine.rs | 168 ++++++++++++++---- .../metaobjects-codegen/src/fingerprint.rs | 2 +- .../metaobjects-codegen/tests/run_engine.rs | 64 ++++--- .../packages/cli/src/lib/gen-fingerprint.ts | 13 +- .../cli/src/lib/load-metaobjects-config.ts | 10 +- .../gen-fingerprint-linked-package.test.ts | 21 ++- 8 files changed, 206 insertions(+), 86 deletions(-) diff --git a/changelog.d/gen-skip-key-linked-generator-packages.md b/changelog.d/gen-skip-key-linked-generator-packages.md index 3e3c69d835..8f78908065 100644 --- a/changelog.d/gen-skip-key-linked-generator-packages.md +++ b/changelog.d/gen-skip-key-linked-generator-packages.md @@ -4,7 +4,8 @@ actually aliases are left out now. Any other `@metaobjectsdev/*` package, such as an independent pack, is hashed like any third-party generator package: a linked or source checkout by the content of its files, an installed one by its version. In Rust, a crate the owned `codegen/` crate depends - on by `path` is now an input too, followed through that crate's own path dependencies; the - `metaobjects` and `metaobjects-codegen` engine crates are still covered by the engine's own source - hash. Before this change, editing such a package's generator code while the model, the config and + on by `path`, in a build table or a `[patch]`, is now an input too, followed through that crate's + own path dependencies and the workspace it inherits from; the `metaobjects` and + `metaobjects-codegen` engine crates are still covered by the engine's own source hash. Both ports + bump their fingerprint format, so the first `gen` after upgrading renders once. Before this change, editing such a package's generator code while the model, the config and the lockfile stayed the same left the key unchanged, and `gen` skipped over stale output. diff --git a/docs/ports/rust.md b/docs/ports/rust.md index c43a141e65..80881619db 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -245,9 +245,10 @@ writes (the transport, the command helpers) is inside the generator, so an owned transport too. Every file in `codegen/` is an input of the skip key, whether `eject` wrote it or you added it (a module beside the generator list, say), so editing any of them regenerates. Only the crate's build directory (`codegen/target`) and its `Cargo.lock` are left out. A crate it depends on by -`path` (a linked checkout of a pack's generators, say) is an input too, followed through that crate's -own path dependencies, except the `metaobjects` and `metaobjects-codegen` engine crates, whose source -the engine's own hash already covers. +`path` (a linked checkout of a pack's generators, say), in a build table or a `[patch]`, is an input +too, followed through that crate's own path dependencies and the workspace it inherits from. The +`metaobjects` and `metaobjects-codegen` engine crates are left out, because the engine's own hash +already covers their source; a path dependency on `metaobjects-render` is hashed like any other. `cargo meta gen --list` shows each owned copy as `identical`, or as `DIFFERS` with how many shipped lines it lacks and how many are its own. diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index dfc9e50630..8adff01a74 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -297,7 +297,8 @@ pub const OWNED_MANIFEST: &str = "codegen/Cargo.toml"; pub const OWNED_MAIN: &str = "codegen/main.rs"; /// The crates whose sources [`ENGINE_SOURCE_HASH`] already covers. A path dependency on one -/// of them is the engine, counted once as such. +/// of them is the engine, counted once as such. The third engine crate, `metaobjects-render`, +/// is not in that hash, so a path dependency on it is hashed like any other. const ENGINE_CRATES: &[&str] = &["metaobjects", "metaobjects-codegen"]; /// What in a path dependency's directory is not an input: cargo's build output and VCS state. @@ -305,23 +306,36 @@ const PATH_DEPENDENCY_NOT_INPUTS: &[&str] = &["target", ".git"]; /// Every crate the owned crate reaches through a `path` dependency (a linked or source /// checkout: a pack's generators, a sibling crate of the adopter's), followed through each -/// one's own manifest, by the content of its directory. Its version does not move when its -/// code does, and cargo rebuilds the owned binary from it, so an edit there changes what the -/// owned generators emit. An engine crate is left out (see [`ENGINE_CRATES`]); a registry or -/// git dependency is named by `codegen/Cargo.toml` itself, which the key already hashes. +/// one's own manifest and through the workspace a `workspace = true` dependency inherits +/// from, by the content of its directory. Its version does not move when its code does, and +/// cargo rebuilds the owned binary from it, so an edit there changes what the owned +/// generators emit. An engine crate is left out (see [`ENGINE_CRATES`]); a registry or git +/// dependency is named by `codegen/Cargo.toml` itself, which the key already hashes. fn path_dependency_entries(owned_manifest: &Path) -> Vec { let mut entries = Vec::new(); - let mut seen: HashSet = HashSet::new(); + let mut crates: HashSet = HashSet::new(); + let mut scanned: HashSet = HashSet::new(); let mut queue = vec![owned_manifest.to_path_buf()]; while let Some(manifest) = queue.pop() { + let manifest = std::fs::canonicalize(&manifest).unwrap_or(manifest); + if !scanned.insert(manifest.clone()) { + continue; + } let Ok(text) = std::fs::read_to_string(&manifest) else { continue; }; let base = manifest.parent().unwrap_or(Path::new(".")); - for rel in manifest_path_dependencies(&text) { + let deps = manifest_dependencies(&text); + if deps.inherits_workspace + && let Some(root) = workspace_root_manifest(base) + { + // The inherited entries' paths live in the root's `[workspace.dependencies]`. + queue.push(root); + } + for rel in deps.paths { let dir = base.join(&rel); let dir = std::fs::canonicalize(&dir).unwrap_or(dir); - if !seen.insert(dir.clone()) { + if !crates.insert(dir.clone()) { continue; } let dep_manifest = dir.join("Cargo.toml"); @@ -349,27 +363,56 @@ fn path_dependency_entries(owned_manifest: &Path) -> Vec { entries } -/// The `path` of every dependency a `Cargo.toml` declares in a table the build compiles -/// (`[dependencies]`, `[build-dependencies]`, their `target.*` and `workspace` forms, and -/// `[dependencies.]`). Dev-dependencies are not built into the owned binary. A line +/// The nearest `Cargo.toml` at or above `dir` that declares `[workspace]`. +fn workspace_root_manifest(dir: &Path) -> Option { + dir.ancestors().map(|d| d.join("Cargo.toml")).find(|m| { + std::fs::read_to_string(m).is_ok_and(|t| { + t.lines() + .any(|l| strip_toml_comment(l).trim() == "[workspace]") + }) + }) +} + +/// What a manifest's build-relevant dependency tables say. +struct ManifestDependencies { + /// The `path` of every dependency, as written (relative to the manifest's directory). + paths: Vec, + /// Whether any dependency inherits its declaration from the workspace (`workspace = true`). + inherits_workspace: bool, +} + +/// The dependencies a `Cargo.toml` declares in a table the build reads: `[dependencies]`, +/// `[build-dependencies]`, their `target.*`, `workspace` and `[dependencies.]` forms, +/// `[patch.*]` and `[replace]`. Dev-dependencies are not built into the owned binary. A line /// scan, not a TOML parser: the forms cargo writes and the scaffold uses are one-line. -fn manifest_path_dependencies(text: &str) -> Vec { - let mut out = Vec::new(); +fn manifest_dependencies(text: &str) -> ManifestDependencies { + let mut out = ManifestDependencies { + paths: Vec::new(), + inherits_workspace: false, + }; let mut in_dependencies = false; - for line in text.lines().map(str::trim) { - if line.starts_with('#') { + for line in text.lines().map(|l| strip_toml_comment(l).trim()) { + if line.starts_with('[') { + let header = line + .trim_start_matches('[') + .split(']') + .next() + .unwrap_or("") + .trim(); + let mut segments = header.split('.').map(str::trim); + in_dependencies = header == "replace" + || segments.clone().next() == Some("patch") + || segments.any(|s| s == "dependencies" || s == "build-dependencies"); continue; } - if line.starts_with('[') { - let header = line.trim_start_matches('[').split(']').next().unwrap_or(""); - in_dependencies = header - .split('.') - .map(|s| s.trim()) - .any(|s| s == "dependencies" || s == "build-dependencies"); + if !in_dependencies { continue; } - if in_dependencies && let Some(path) = toml_key_string(line, "path") { - out.push(path); + if let Some(path) = toml_key_string(line, "path") { + out.paths.push(path); + } + if toml_key_value(line, "workspace").is_some_and(|v| v.starts_with("true")) { + out.inherits_workspace = true; } } out @@ -378,7 +421,7 @@ fn manifest_path_dependencies(text: &str) -> Vec { /// The `[package]` name a `Cargo.toml` declares. fn manifest_package_name(text: &str) -> Option { let mut in_package = false; - for line in text.lines().map(str::trim) { + for line in text.lines().map(|l| strip_toml_comment(l).trim()) { if line.starts_with('[') { in_package = line == "[package]"; } else if in_package && let Some(name) = toml_key_string(line, "name") { @@ -388,22 +431,71 @@ fn manifest_package_name(text: &str) -> Option { None } -/// The basic-string value of `key` on one TOML line, whether the line is `key = "v"` or an -/// inline table holding it (`dep = { path = "v", ... }`). +/// One TOML line without its trailing comment (a `#` outside any string). +fn strip_toml_comment(line: &str) -> &str { + let mut quote: Option = None; + let mut escaped = false; + for (i, c) in line.char_indices() { + match quote { + Some('"') if escaped => escaped = false, + Some('"') if c == '\\' => escaped = true, + Some(q) if c == q => quote = None, + Some(_) => {} + None if c == '"' || c == '\'' => quote = Some(c), + None if c == '#' => return &line[..i], + None => {} + } + } + line +} + +/// The raw text after `key =` on one TOML line, whether the line is `key = v` or an inline +/// table holding it (`dep = { path = "v", ... }`). Occurrences inside strings are skipped. +fn toml_key_value<'a>(line: &'a str, key: &str) -> Option<&'a str> { + let mut quote: Option = None; + let mut escaped = false; + let mut prev: Option = None; + for (i, c) in line.char_indices() { + match quote { + Some('"') if escaped => escaped = false, + Some('"') if c == '\\' => escaped = true, + Some(q) if c == q => quote = None, + Some(_) => {} + None if c == '"' || c == '\'' => quote = Some(c), + None => { + let bounded = !prev.is_some_and(|p| p.is_alphanumeric() || p == '_' || p == '-'); + if bounded && line[i..].starts_with(key) { + let after = &line[i + key.len()..]; + let next = after.chars().next(); + if !next.is_some_and(|n| n.is_alphanumeric() || n == '_' || n == '-') + && let Some(value) = after.trim_start().strip_prefix('=') + { + return Some(value.trim_start()); + } + } + } + } + prev = Some(c); + } + None +} + +/// The string value of `key` on one TOML line: a basic string (`"v"`, with `\\` and `\"` +/// unescaped) or a literal one (`'v'`). fn toml_key_string(line: &str, key: &str) -> Option { - let mut from = 0; - while let Some(at) = line[from..].find(key).map(|i| i + from) { - from = at + key.len(); - let before = line[..at].chars().next_back(); - if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '-') { - continue; + let value = toml_key_value(line, key)?; + if let Some(rest) = value.strip_prefix('\'') { + return rest.find('\'').map(|end| rest[..end].to_string()); + } + let rest = value.strip_prefix('"')?; + let mut out = String::new(); + let mut chars = rest.chars(); + while let Some(c) = chars.next() { + match c { + '"' => return Some(out), + '\\' => out.push(chars.next()?), + other => out.push(other), } - let rest = line[from..].trim_start(); - let Some(rest) = rest.strip_prefix('=') else { - continue; - }; - let rest = rest.trim_start().strip_prefix('"')?; - return rest.find('"').map(|end| rest[..end].to_string()); } None } diff --git a/server/rust/metaobjects-codegen/src/fingerprint.rs b/server/rust/metaobjects-codegen/src/fingerprint.rs index eeea61ee12..0cc7aa3b27 100644 --- a/server/rust/metaobjects-codegen/src/fingerprint.rs +++ b/server/rust/metaobjects-codegen/src/fingerprint.rs @@ -26,7 +26,7 @@ use crate::hashes::HashManifest; use crate::sha256::{Sha256, hex, sha256_hex}; /// Bump when the key's own recipe changes: every stored key then misses. -pub const FINGERPRINT_FORMAT: u64 = 1; +pub const FINGERPRINT_FORMAT: u64 = 2; /// Where this port keeps its key, beside the (committed) manifest and never committed /// itself (`.gen-state/*` is ignored except `.hashes/`). diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 1c64128f20..c4586d2f97 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -491,45 +491,63 @@ fn a_crate_the_owned_crate_reaches_by_path_is_an_input_and_an_engine_crate_is_no "[package]\nname = \"codegen\"\n\n[[bin]]\nname = \"codegen\"\npath = \"main.rs\"\n\n\ [dependencies]\n\ metaobjects = { path = \"../engine/metaobjects\" }\n\ - linked-generators = { path = \"../linked\" }\n\n\ - [dev-dependencies]\nscratch-only = { path = \"../dev-only\" }\n", + linked-generators = { path = '../ws/linked' } # path = \"../commented-out\"\n\n\ + [dev-dependencies]\nscratch-only = { path = \"../dev-only\" }\n\n\ + [patch.crates-io]\nforked = { path = \"../fork\" }\n", ); p.write("codegen/main.rs", "fn main() {}\n"); + // The linked crate is a member of a workspace and inherits one dependency from its root. p.write( - "linked/Cargo.toml", - "[package]\nname = \"linked-generators\"\n\n[dependencies.deeper]\npath = \"../deeper\"\n", + "ws/Cargo.toml", + "[workspace]\nmembers = [\"linked\"]\n\n[workspace.dependencies]\nshared = { path = \"shared\" }\n", ); - p.write("linked/src/lib.rs", "// v1\n"); - p.write("deeper/Cargo.toml", "[package]\nname = \"deeper\"\n"); - p.write("deeper/src/lib.rs", "// v1\n"); + p.write( + "ws/linked/Cargo.toml", + "[package]\nname = \"linked-generators\"\n\n[dependencies.deeper]\npath = \"../deeper\"\n\n\ + [dependencies]\nshared = { workspace = true }\n", + ); + for dir in [ + "ws/linked", + "ws/deeper", + "ws/shared", + "fork", + "dev-only", + "commented-out", + ] { + if dir != "ws/linked" { + p.write(&format!("{dir}/Cargo.toml"), "[package]\nname = \"dep\"\n"); + } + p.write(&format!("{dir}/src/lib.rs"), "// v1\n"); + } p.write( "engine/metaobjects/Cargo.toml", "[package]\nname = \"metaobjects\"\n", ); p.write("engine/metaobjects/src/lib.rs", "// v1\n"); - p.write( - "dev-only/Cargo.toml", - "[package]\nname = \"scratch-only\"\n", - ); - p.write("dev-only/src/lib.rs", "// v1\n"); gen_ok(&p); assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); - // An edit to the linked crate's source, and to a crate it reaches by path in turn. - p.write("linked/src/lib.rs", "// v2\n"); - let r = gen_ok(&p); - assert_eq!(r.outcome, Outcome::Generated); - assert_eq!(r.no_skip_reason, Some("an input changed")); - assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); - p.write("deeper/src/lib.rs", "// v2\n"); - assert_eq!(gen_ok(&p).outcome, Outcome::Generated); - assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); + // An edit to the linked crate's source, to a crate it reaches by path in turn, to one it + // inherits from its workspace, and to a patched crate. + for dir in ["ws/linked", "ws/deeper", "ws/shared", "fork"] { + p.write(&format!("{dir}/src/lib.rs"), "// v2\n"); + let r = gen_ok(&p); + assert_eq!( + r.outcome, + Outcome::Generated, + "an edit to {dir} must regenerate" + ); + assert_eq!(r.no_skip_reason, Some("an input changed")); + assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); + } // Not inputs: the linked crate's build output, an engine crate (the engine's own source - // hash covers it) and a dev-dependency, which is not built into the owned binary. - p.write("linked/target/debug/out.rs", "build output"); + // hash covers it), a dev-dependency, which is not built into the owned binary, and a + // path that only a comment names. + p.write("ws/linked/target/debug/out.rs", "build output"); p.write("engine/metaobjects/src/lib.rs", "// v2\n"); p.write("dev-only/src/lib.rs", "// v2\n"); + p.write("commented-out/src/lib.rs", "// v2\n"); assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); } diff --git a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts index 67ee0bef7e..4b673c306f 100644 --- a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -26,7 +26,7 @@ import { GEN_CONFIG_FILE } from "./gen-collection.js"; import { CLI_ALIASED_PACKAGES } from "./load-metaobjects-config.js"; /** Bumped whenever what goes into the fingerprint changes, so an old stored key never matches. */ -export const FINGERPRINT_FORMAT = 3; +export const FINGERPRINT_FORMAT = 4; /** One input: what kind it is, which one, and the SHA-256 of its content. */ export interface FingerprintEntry { @@ -170,9 +170,13 @@ function packageEntries(kind: string, dir: string): FingerprintEntry[] { /** * The packages a package runs on: every `@metaobjectsdev/*` dependency, followed all the - * way, by full identity; every other dependency by its `package.json` (its version). + * way, by full identity; every other dependency by its `package.json` (its version). A + * dependency named in `skip` is left out: a generator package's copy of a package the CLI + * aliases onto its engine never runs, so only the engine's copy counts. */ -function packageClosureEntries(kind: string, rootDir: string, seen: Set): FingerprintEntry[] { +function packageClosureEntries( + kind: string, rootDir: string, seen: Set, skip: ReadonlySet = new Set(), +): FingerprintEntry[] { const entries: FingerprintEntry[] = []; const visit = (dir: string): void => { let real = dir; @@ -182,6 +186,7 @@ function packageClosureEntries(kind: string, rootDir: string, seen: Set) entries.push(...packageEntries(kind, dir)); const pkg = readJson(join(dir, "package.json")); for (const dep of dependencyNames(pkg)) { + if (skip.has(dep)) continue; const depDir = findPackageDir(dep, dir); if (depDir === undefined) { entries.push({ kind, name: `${dep}/package.json`, hash: "absent" }); @@ -290,7 +295,7 @@ function configGraphEntries(configFile: string, projectRoot: string, seen: Set = { }; /** - * The packages whose imports the loader rewrites onto the CLI's own copy (every subpath of - * each, and bare `ts-poet`, which goes to the engine's printer). The config never runs the - * project's copy of these, so the `meta gen` skip key counts them as part of the engine - * (gen-fingerprint.ts). Any other package the config imports, `@metaobjectsdev/*` or not, - * runs from the project and is hashed as a generator package. + * The packages whose imports the loader points at the CLI's own copy (every subpath of each, + * and bare `ts-poet`, which goes to the engine's printer): rewritten in the config's source, + * and mapped by the jiti alias for the modules it imports. The `meta gen` skip key counts + * them as part of the engine (gen-fingerprint.ts). Any other package the config imports, + * `@metaobjectsdev/*` or not, runs from the project and is hashed as a generator package. */ export const CLI_ALIASED_PACKAGES: ReadonlySet = new Set([ ...Object.keys(CLI_PKG_PATHS).map((spec) => spec.split("/").slice(0, 2).join("/")), diff --git a/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts index d18ab8ad87..bc7b58ad1d 100644 --- a/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts +++ b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts @@ -9,7 +9,8 @@ // stale output. import { afterAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { genCommand } from "../src/commands/gen.js"; import { computeGenInputs, decideGenSkip, keyFor, withModel, @@ -20,8 +21,9 @@ import { collectionLoadOptions } from "../src/lib/collection-load-options.js"; import { loadMemory, resolveCollection } from "@metaobjectsdev/sdk"; import { modelHashTree } from "@metaobjectsdev/codegen-ts"; -// Inside the monorepo, so the config's engine imports resolve as in the other command tests. -const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures/__tmp__"); +// Throwaway projects live in RAM scratch. The config's engine import resolves anyway: the +// CLI rewrites it onto its own copy. +const SCRATCH = process.env.DEV_SCRATCH ?? tmpdir(); const made: string[] = []; afterAll(() => { for (const d of made) rmSync(d, { recursive: true, force: true }); }); @@ -45,8 +47,7 @@ const ENGINE: FingerprintEntry[] = [{ kind: "engine", name: "(test)", hash: "fix const SELECTION: GenSelection = { entities: [], generators: undefined, strict: false, baseline: "default" }; function makeProject(): { root: string; linkedIndex: string } { - mkdirSync(WORKSPACE_TMP, { recursive: true }); - const root = mkdtempSync(join(WORKSPACE_TMP, "gen-linked-")); + const root = mkdtempSync(join(SCRATCH, "gen-linked-")); made.push(root); mkdirSync(join(root, ".git")); mkdirSync(join(root, "metaobjects")); @@ -60,7 +61,9 @@ function makeProject(): { root: string; linkedIndex: string } { // member, a clone or `bun link`, and the project's node_modules holds a symlink to it. const source = join(root, "linked-checkout"); mkdirSync(source); - writeFileSync(join(source, "package.json"), JSON.stringify({ name: LINKED, version: "0.1.0", type: "module", main: "index.ts" }) + "\n"); + writeFileSync(join(source, "package.json"), JSON.stringify({ + name: LINKED, version: "0.1.0", type: "module", main: "index.ts", dependencies: { [ENGINE_PKG]: "*" }, + }) + "\n"); writeFileSync(join(source, "index.ts"), linkedSource("first\n")); mkdirSync(join(root, "node_modules", "@metaobjectsdev"), { recursive: true }); symlinkSync(source, join(root, "node_modules", LINKED), "dir"); @@ -109,9 +112,9 @@ describe("the skip key covers a linked @metaobjectsdev/* generator package (ADR- }); test("an import the CLI aliases onto its engine is not hashed from the project's copy", async () => { - // The config imports `@metaobjectsdev/codegen-ts`, which the CLI rewrites onto its own - // copy: the engine half counts that. A linked copy in the project's node_modules never - // runs, so editing it must leave the key alone. + // The config imports `@metaobjectsdev/codegen-ts`, and the linked package depends on it; + // the CLI points both at its own copy, which the engine half counts. A linked copy in the + // project's node_modules never runs, so editing it must leave the key alone. const p = makeProject(); const fake = join(p.root, "engine-checkout"); mkdirSync(fake); From 3c02bc1436988942f4c698e24383e40a258365bb Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:41:23 -0500 Subject: [PATCH 3/8] refactor(codegen): simplify the skip key's linked-package hashing One packageNameOf for the CLI; one quote-aware TOML line scanner in Rust; each manifest read once; engine crates matched by the directories build.rs hashed rather than by name, so another checkout named like one is hashed. --- server/rust/metaobjects-codegen/build.rs | 12 ++ server/rust/metaobjects-codegen/src/engine.rs | 168 ++++++++++-------- .../metaobjects-codegen/tests/run_engine.rs | 43 +++-- .../packages/cli/src/lib/gen-fingerprint.ts | 6 +- .../cli/src/lib/load-metaobjects-config.ts | 3 +- .../packages/cli/src/lib/package-name.ts | 7 + .../packages/cli/src/lib/runtime-eject.ts | 7 +- .../gen-fingerprint-linked-package.test.ts | 31 ++-- 8 files changed, 166 insertions(+), 111 deletions(-) create mode 100644 server/typescript/packages/cli/src/lib/package-name.ts diff --git a/server/rust/metaobjects-codegen/build.rs b/server/rust/metaobjects-codegen/build.rs index 6a5171bb6a..30160c19d8 100644 --- a/server/rust/metaobjects-codegen/build.rs +++ b/server/rust/metaobjects-codegen/build.rs @@ -55,4 +55,16 @@ fn main() { "cargo:rustc-env=METAOBJECTS_ENGINE_SOURCE_HASH={}", sha256::hex(&hasher.finish()) ); + // The crate directories that hash covers, so the skip key can leave a path dependency on + // one of them out instead of hashing it twice (and only those: matched by directory, not + // by name, so another checkout of a crate with the same name is still hashed). + let dirs = [manifest.clone(), manifest.join("../metaobjects")] + .into_iter() + .map(|d| std::fs::canonicalize(&d).unwrap_or(d)); + println!( + "cargo:rustc-env=METAOBJECTS_ENGINE_CRATE_DIRS={}", + std::env::join_paths(dirs) + .expect("engine crate directories") + .to_string_lossy() + ); } diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 8adff01a74..c356dd0730 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -296,10 +296,10 @@ pub const OWNED_MANIFEST: &str = "codegen/Cargo.toml"; /// The owned crate's generator list. pub const OWNED_MAIN: &str = "codegen/main.rs"; -/// The crates whose sources [`ENGINE_SOURCE_HASH`] already covers. A path dependency on one -/// of them is the engine, counted once as such. The third engine crate, `metaobjects-render`, -/// is not in that hash, so a path dependency on it is hashed like any other. -const ENGINE_CRATES: &[&str] = &["metaobjects", "metaobjects-codegen"]; +/// The crate directories [`ENGINE_SOURCE_HASH`] was taken over, as `build.rs` hashed them +/// (`metaobjects-codegen` and `metaobjects`). A path dependency on one of them is the engine, +/// counted once as such; any other directory is hashed, `metaobjects-render` included. +const ENGINE_CRATE_DIRS: &str = env!("METAOBJECTS_ENGINE_CRATE_DIRS"); /// What in a path dependency's directory is not an input: cargo's build output and VCS state. const PATH_DEPENDENCY_NOT_INPUTS: &[&str] = &["target", ".git"]; @@ -309,55 +309,55 @@ const PATH_DEPENDENCY_NOT_INPUTS: &[&str] = &["target", ".git"]; /// one's own manifest and through the workspace a `workspace = true` dependency inherits /// from, by the content of its directory. Its version does not move when its code does, and /// cargo rebuilds the owned binary from it, so an edit there changes what the owned -/// generators emit. An engine crate is left out (see [`ENGINE_CRATES`]); a registry or git +/// generators emit. An engine crate is left out (see [`ENGINE_CRATE_DIRS`]); a registry or git /// dependency is named by `codegen/Cargo.toml` itself, which the key already hashes. fn path_dependency_entries(owned_manifest: &Path) -> Vec { + let engine: HashSet = std::env::split_paths(ENGINE_CRATE_DIRS).collect(); let mut entries = Vec::new(); - let mut crates: HashSet = HashSet::new(); - let mut scanned: HashSet = HashSet::new(); - let mut queue = vec![owned_manifest.to_path_buf()]; - while let Some(manifest) = queue.pop() { + // Every manifest queued so far, by canonical path: each is read and scanned once. + let mut queued: HashSet = HashSet::new(); + let mut queue = Vec::new(); + let mut enqueue = |manifest: PathBuf, queue: &mut Vec<(PathBuf, String)>| -> Option { let manifest = std::fs::canonicalize(&manifest).unwrap_or(manifest); - if !scanned.insert(manifest.clone()) { - continue; + if !queued.insert(manifest.clone()) { + return None; } - let Ok(text) = std::fs::read_to_string(&manifest) else { - continue; - }; + let text = std::fs::read_to_string(&manifest).unwrap_or_default(); + queue.push((manifest, text.clone())); + Some(text) + }; + enqueue(owned_manifest.to_path_buf(), &mut queue); + while let Some((manifest, text)) = queue.pop() { let base = manifest.parent().unwrap_or(Path::new(".")); let deps = manifest_dependencies(&text); if deps.inherits_workspace && let Some(root) = workspace_root_manifest(base) { // The inherited entries' paths live in the root's `[workspace.dependencies]`. - queue.push(root); + enqueue(root, &mut queue); } for rel in deps.paths { let dir = base.join(&rel); let dir = std::fs::canonicalize(&dir).unwrap_or(dir); - if !crates.insert(dir.clone()) { + if engine.contains(&dir) { continue; } - let dep_manifest = dir.join("Cargo.toml"); - let Ok(dep_text) = std::fs::read_to_string(&dep_manifest) else { - // Cargo will fail on it; until it exists, its absence is the input. - entries.push(InputEntry::new( - KIND_GENERATOR, - format!("path-dependency:{rel}"), - ABSENT, - )); + let Some(dep_text) = enqueue(dir.join("Cargo.toml"), &mut queue) else { continue; }; - let name = manifest_package_name(&dep_text).unwrap_or_else(|| rel.clone()); - if ENGINE_CRATES.contains(&name.as_str()) { - continue; - } + let name = manifest_package_name(&dep_text).unwrap_or(rel); + // A crate with no manifest: cargo will fail on it; until it exists, its absence + // is the input. + let hash = if dep_text.is_empty() { + ABSENT.to_string() + } else { + hash_tree_except(&dir, PATH_DEPENDENCY_NOT_INPUTS) + }; entries.push(InputEntry::new( KIND_GENERATOR, format!("path-dependency:{name}"), - hash_tree_except(&dir, PATH_DEPENDENCY_NOT_INPUTS), + hash, )); - queue.push(dep_manifest); } } entries @@ -393,16 +393,13 @@ fn manifest_dependencies(text: &str) -> ManifestDependencies { let mut in_dependencies = false; for line in text.lines().map(|l| strip_toml_comment(l).trim()) { if line.starts_with('[') { - let header = line - .trim_start_matches('[') - .split(']') - .next() - .unwrap_or("") - .trim(); - let mut segments = header.split('.').map(str::trim); + let header = line.trim_matches(|c| c == '[' || c == ']').trim(); + let first = header.split('.').next().map(str::trim); in_dependencies = header == "replace" - || segments.clone().next() == Some("patch") - || segments.any(|s| s == "dependencies" || s == "build-dependencies"); + || first == Some("patch") + || header + .split('.') + .any(|s| matches!(s.trim(), "dependencies" | "build-dependencies")); continue; } if !in_dependencies { @@ -431,53 +428,43 @@ fn manifest_package_name(text: &str) -> Option { None } -/// One TOML line without its trailing comment (a `#` outside any string). -fn strip_toml_comment(line: &str) -> &str { +/// The characters of one TOML line that sit outside any string, with their byte offsets. +fn unquoted(line: &str) -> impl Iterator + '_ { let mut quote: Option = None; let mut escaped = false; - for (i, c) in line.char_indices() { + line.char_indices().filter(move |&(_, c)| { match quote { Some('"') if escaped => escaped = false, Some('"') if c == '\\' => escaped = true, Some(q) if c == q => quote = None, Some(_) => {} None if c == '"' || c == '\'' => quote = Some(c), - None if c == '#' => return &line[..i], - None => {} + None => return true, } + false + }) +} + +/// One TOML line without its trailing comment (a `#` outside any string). +fn strip_toml_comment(line: &str) -> &str { + match unquoted(line).find(|&(_, c)| c == '#') { + Some((i, _)) => &line[..i], + None => line, } - line } /// The raw text after `key =` on one TOML line, whether the line is `key = v` or an inline /// table holding it (`dep = { path = "v", ... }`). Occurrences inside strings are skipped. fn toml_key_value<'a>(line: &'a str, key: &str) -> Option<&'a str> { - let mut quote: Option = None; - let mut escaped = false; - let mut prev: Option = None; - for (i, c) in line.char_indices() { - match quote { - Some('"') if escaped => escaped = false, - Some('"') if c == '\\' => escaped = true, - Some(q) if c == q => quote = None, - Some(_) => {} - None if c == '"' || c == '\'' => quote = Some(c), - None => { - let bounded = !prev.is_some_and(|p| p.is_alphanumeric() || p == '_' || p == '-'); - if bounded && line[i..].starts_with(key) { - let after = &line[i + key.len()..]; - let next = after.chars().next(); - if !next.is_some_and(|n| n.is_alphanumeric() || n == '_' || n == '-') - && let Some(value) = after.trim_start().strip_prefix('=') - { - return Some(value.trim_start()); - } - } - } + let ident = |c: char| c.is_alphanumeric() || c == '_' || c == '-'; + unquoted(line).find_map(|(i, _)| { + let bounded = !line[..i].chars().next_back().is_some_and(ident); + let after = line[i..].strip_prefix(key)?; + if !bounded || after.chars().next().is_some_and(ident) { + return None; } - prev = Some(c); - } - None + after.trim_start().strip_prefix('=').map(str::trim_start) + }) } /// The string value of `key` on one TOML line: a basic string (`"v"`, with `\\` and `\"` @@ -1045,3 +1032,44 @@ fn remove_empty_parents(path: &Path, stop: &Path) { cur = dir.parent(); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_path_dependency_on_the_engine_crates_is_left_to_the_engine_hash() { + // The directories `build.rs` hashed into ENGINE_SOURCE_HASH: this crate and the loader. + let engine = Path::new(env!("CARGO_MANIFEST_DIR")); + let scratch = + std::env::var_os("DEV_SCRATCH").map_or_else(std::env::temp_dir, PathBuf::from); + let dir = scratch.join(format!("mo-engine-path-deps-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = dir.join("Cargo.toml"); + std::fs::write( + &manifest, + format!( + "[dependencies]\nmetaobjects = {{ path = {:?} }}\nmetaobjects-codegen = {{ path = {:?} }}\n", + engine.join("../metaobjects"), + engine, + ), + ) + .unwrap(); + let entries = path_dependency_entries(&manifest); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(entries, Vec::new()); + } + + #[test] + fn the_line_scan_reads_the_forms_cargo_accepts() { + let deps = manifest_dependencies( + "[package]\nname = \"x\"\n[[bin]]\npath = \"main.rs\"\n\ + [dependencies]\na = { path = 'lit' } # path = \"comment\"\nb = { version = \"1\", path = \"b\\\\c\" }\n\ + c.workspace = true\n[dependencies.d]\npath = \"d\"\n\ + [target.'cfg(unix)'.build-dependencies]\ne = { path = \"e\" }\n\ + [dev-dependencies]\nf = { path = \"f\" }\n[patch.crates-io]\ng = { path = \"g\" }\n", + ); + assert_eq!(deps.paths, ["lit", "b\\c", "d", "e", "g"]); + assert!(deps.inherits_workspace); + } +} diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index c4586d2f97..2e282cf759 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -486,14 +486,22 @@ fn a_crate_the_owned_crate_reaches_by_path_is_an_input_and_an_engine_crate_is_no // source, and their version does not move when their code does. A skip that did not see // an edit there would report "nothing changed" over stale output. let p = Scratch::project("owned-path-deps", &shop_files()); + // The real engine checkout, as `eject --engine ` writes it. + let engine = PathBuf::from(env!("CARGO_MANIFEST_DIR")); p.write( "codegen/Cargo.toml", - "[package]\nname = \"codegen\"\n\n[[bin]]\nname = \"codegen\"\npath = \"main.rs\"\n\n\ - [dependencies]\n\ - metaobjects = { path = \"../engine/metaobjects\" }\n\ - linked-generators = { path = '../ws/linked' } # path = \"../commented-out\"\n\n\ - [dev-dependencies]\nscratch-only = { path = \"../dev-only\" }\n\n\ - [patch.crates-io]\nforked = { path = \"../fork\" }\n", + &format!( + "[package]\nname = \"codegen\"\n\n[[bin]]\nname = \"codegen\"\npath = \"main.rs\"\n\n\ + [dependencies]\n\ + metaobjects = {{ path = {:?} }}\n\ + metaobjects-codegen = {{ path = {:?} }}\n\ + metaobjects-fork = {{ path = \"../fork-of-engine/metaobjects\" }}\n\ + linked-generators = {{ path = '../ws/linked' }} # path = \"../commented-out\"\n\n\ + [dev-dependencies]\nscratch-only = {{ path = \"../dev-only\" }}\n\n\ + [patch.crates-io]\nforked = {{ path = \"../fork\" }}\n", + engine.join("../metaobjects"), + engine, + ), ); p.write("codegen/main.rs", "fn main() {}\n"); // The linked crate is a member of a workspace and inherits one dependency from its root. @@ -519,17 +527,25 @@ fn a_crate_the_owned_crate_reaches_by_path_is_an_input_and_an_engine_crate_is_no } p.write(&format!("{dir}/src/lib.rs"), "// v1\n"); } + // Another checkout of a crate named like the engine's: not the engine that runs. p.write( - "engine/metaobjects/Cargo.toml", + "fork-of-engine/metaobjects/Cargo.toml", "[package]\nname = \"metaobjects\"\n", ); - p.write("engine/metaobjects/src/lib.rs", "// v1\n"); + p.write("fork-of-engine/metaobjects/src/lib.rs", "// v1\n"); gen_ok(&p); assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); // An edit to the linked crate's source, to a crate it reaches by path in turn, to one it - // inherits from its workspace, and to a patched crate. - for dir in ["ws/linked", "ws/deeper", "ws/shared", "fork"] { + // inherits from its workspace, to a patched crate, and to a crate that only shares an + // engine crate's name. + for dir in [ + "ws/linked", + "ws/deeper", + "ws/shared", + "fork", + "fork-of-engine/metaobjects", + ] { p.write(&format!("{dir}/src/lib.rs"), "// v2\n"); let r = gen_ok(&p); assert_eq!( @@ -541,11 +557,10 @@ fn a_crate_the_owned_crate_reaches_by_path_is_an_input_and_an_engine_crate_is_no assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); } - // Not inputs: the linked crate's build output, an engine crate (the engine's own source - // hash covers it), a dev-dependency, which is not built into the owned binary, and a - // path that only a comment names. + // Not inputs: the linked crate's build output, a dev-dependency, which is not built into + // the owned binary, and a path that only a comment names. (The real engine crates are not + // either: the engine's own source hash covers them; `engine.rs` tests that directly.) p.write("ws/linked/target/debug/out.rs", "build output"); - p.write("engine/metaobjects/src/lib.rs", "// v2\n"); p.write("dev-only/src/lib.rs", "// v2\n"); p.write("commented-out/src/lib.rs", "// v2\n"); assert_eq!(gen_ok(&p).outcome, Outcome::Skipped); diff --git a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts index 4b673c306f..d4206021b6 100644 --- a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -24,6 +24,7 @@ import type { Collection } from "@metaobjectsdev/sdk/collection"; import { readManifestState } from "@metaobjectsdev/codegen-ts"; import { GEN_CONFIG_FILE } from "./gen-collection.js"; import { CLI_ALIASED_PACKAGES } from "./load-metaobjects-config.js"; +import { packageNameOf } from "./package-name.js"; /** Bumped whenever what goes into the fingerprint changes, so an old stored key never matches. */ export const FINGERPRINT_FORMAT = 4; @@ -252,11 +253,6 @@ function resolveRelative(spec: string, fromFile: string): string | undefined { return undefined; } -function packageNameOf(spec: string): string { - const parts = spec.split("/"); - return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!; -} - /** * `metaobjects.config.ts` and its import graph: every local module it reaches, by content, * and every package it imports, by identity. An owned (ejected) generator is a local module, diff --git a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts index 1ef6150594..7d0a097e58 100644 --- a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts +++ b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts @@ -13,6 +13,7 @@ import { registerColumnNamingStrategy, registerTableNamingRule, registerPluralizer, } from "@metaobjectsdev/metadata"; +import { packageNameOf } from "./package-name.js"; const CONFIG_FILE = "metaobjects.config.ts"; @@ -98,7 +99,7 @@ const CLI_PKG_PATHS: Record = { * `@metaobjectsdev/*` or not, runs from the project and is hashed as a generator package. */ export const CLI_ALIASED_PACKAGES: ReadonlySet = new Set([ - ...Object.keys(CLI_PKG_PATHS).map((spec) => spec.split("/").slice(0, 2).join("/")), + ...Object.keys(CLI_PKG_PATHS).map(packageNameOf), TS_POET_PKG, ]); diff --git a/server/typescript/packages/cli/src/lib/package-name.ts b/server/typescript/packages/cli/src/lib/package-name.ts new file mode 100644 index 0000000000..4a703e7a20 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/package-name.ts @@ -0,0 +1,7 @@ +// server/typescript/packages/cli/src/lib/package-name.ts + +/** The package an import specifier names: `@scope/name/sub` → `@scope/name`; `name/sub` → `name`. */ +export function packageNameOf(spec: string): string { + const parts = spec.split("/"); + return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!; +} diff --git a/server/typescript/packages/cli/src/lib/runtime-eject.ts b/server/typescript/packages/cli/src/lib/runtime-eject.ts index b9736b5dc8..1594460fae 100644 --- a/server/typescript/packages/cli/src/lib/runtime-eject.ts +++ b/server/typescript/packages/cli/src/lib/runtime-eject.ts @@ -29,6 +29,7 @@ import { } from "@metaobjectsdev/codegen-ts"; import { compareOwnedCopy, type OwnedComparison } from "./owned-copy.js"; import { cliVersion } from "./version.js"; +import { packageNameOf } from "./package-name.js"; /** * The ejectable generators whose OUTPUT imports the adapter tier, and the adapter modules @@ -105,12 +106,6 @@ function specifiersOf(source: string): string[] { return out; } -/** `@scope/name/sub` → `@scope/name`; `name/sub` → `name`. */ -function packageNameOf(spec: string): string { - const parts = spec.split("/"); - return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!; -} - function toPosix(p: string): string { return p.split(sep).join("/"); } diff --git a/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts index bc7b58ad1d..4173523b17 100644 --- a/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts +++ b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts @@ -46,6 +46,18 @@ const ENGINE_PKG = "@metaobjectsdev/codegen-ts"; const ENGINE: FingerprintEntry[] = [{ kind: "engine", name: "(test)", hash: "fixed" }]; const SELECTION: GenSelection = { entities: [], generators: undefined, strict: false, baseline: "default" }; +/** A package checked out at `/` and linked into the project's node_modules, as + * a workspace member, a clone or `bun link` is. Returns its entry file. */ +function linkPackage(root: string, dir: string, manifest: { name: string; dependencies?: Record }, index: string): string { + const source = join(root, dir); + mkdirSync(source); + writeFileSync(join(source, "package.json"), JSON.stringify({ version: "0.1.0", type: "module", main: "index.ts", ...manifest }) + "\n"); + writeFileSync(join(source, "index.ts"), index); + mkdirSync(join(root, "node_modules", "@metaobjectsdev"), { recursive: true }); + symlinkSync(source, join(root, "node_modules", manifest.name), "dir"); + return join(source, "index.ts"); +} + function makeProject(): { root: string; linkedIndex: string } { const root = mkdtempSync(join(SCRATCH, "gen-linked-")); made.push(root); @@ -59,20 +71,13 @@ function makeProject(): { root: string; linkedIndex: string } { // The linked package: its source lives outside any node_modules, as with a workspace // member, a clone or `bun link`, and the project's node_modules holds a symlink to it. - const source = join(root, "linked-checkout"); - mkdirSync(source); - writeFileSync(join(source, "package.json"), JSON.stringify({ - name: LINKED, version: "0.1.0", type: "module", main: "index.ts", dependencies: { [ENGINE_PKG]: "*" }, - }) + "\n"); - writeFileSync(join(source, "index.ts"), linkedSource("first\n")); - mkdirSync(join(root, "node_modules", "@metaobjectsdev"), { recursive: true }); - symlinkSync(source, join(root, "node_modules", LINKED), "dir"); + const linkedIndex = linkPackage(root, "linked-checkout", { name: LINKED, dependencies: { [ENGINE_PKG]: "*" } }, linkedSource("first\n")); writeFileSync(join(root, "metaobjects.config.ts"), `import { defineConfig } from "@metaobjectsdev/codegen-ts"; import { linked } from "${LINKED}"; export default defineConfig({ outDir: "generated", generators: [linked()] }); `); - return { root, linkedIndex: join(source, "index.ts") }; + return { root, linkedIndex }; } async function inputsFor(root: string, engine?: FingerprintEntry[]) { @@ -116,16 +121,12 @@ describe("the skip key covers a linked @metaobjectsdev/* generator package (ADR- // the CLI points both at its own copy, which the engine half counts. A linked copy in the // project's node_modules never runs, so editing it must leave the key alone. const p = makeProject(); - const fake = join(p.root, "engine-checkout"); - mkdirSync(fake); - writeFileSync(join(fake, "package.json"), JSON.stringify({ name: ENGINE_PKG, version: "0.0.0", main: "index.ts" }) + "\n"); - writeFileSync(join(fake, "index.ts"), "export const v = 1;\n"); - symlinkSync(fake, join(p.root, "node_modules", ENGINE_PKG), "dir"); + const fakeIndex = linkPackage(p.root, "engine-checkout", { name: ENGINE_PKG }, "export const v = 1;\n"); expect(CLI_ALIASED_PACKAGES.has(ENGINE_PKG)).toBe(true); const before = await inputsFor(p.root, ENGINE); expect(before.entries.filter((e) => e.kind === "generator-package" && e.name.startsWith(`${ENGINE_PKG}/`))).toEqual([]); - writeFileSync(join(fake, "index.ts"), "export const v = 2;\n"); + writeFileSync(fakeIndex, "export const v = 2;\n"); expect(keyFor(await inputsFor(p.root, ENGINE), [])).toBe(keyFor(before, [])); }); }); From 5fc9403d4e427016f45bf1590cb5b6bfb35d80b8 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:44:57 -0500 Subject: [PATCH 4/8] no-mistakes(review): Scan multi-line Cargo.toml tables in Rust skip key --- server/rust/metaobjects-codegen/src/engine.rs | 52 ++++++++++++++++--- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index c356dd0730..efb7df6348 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -366,10 +366,8 @@ fn path_dependency_entries(owned_manifest: &Path) -> Vec { /// The nearest `Cargo.toml` at or above `dir` that declares `[workspace]`. fn workspace_root_manifest(dir: &Path) -> Option { dir.ancestors().map(|d| d.join("Cargo.toml")).find(|m| { - std::fs::read_to_string(m).is_ok_and(|t| { - t.lines() - .any(|l| strip_toml_comment(l).trim() == "[workspace]") - }) + std::fs::read_to_string(m) + .is_ok_and(|t| logical_lines(&t).iter().any(|l| l == "[workspace]")) }) } @@ -383,15 +381,15 @@ struct ManifestDependencies { /// The dependencies a `Cargo.toml` declares in a table the build reads: `[dependencies]`, /// `[build-dependencies]`, their `target.*`, `workspace` and `[dependencies.]` forms, -/// `[patch.*]` and `[replace]`. Dev-dependencies are not built into the owned binary. A line -/// scan, not a TOML parser: the forms cargo writes and the scaffold uses are one-line. +/// `[patch.*]` and `[replace]`. Dev-dependencies are not built into the owned binary. A scan +/// over logical lines (a multi-line inline table or array is one), not a TOML parser. fn manifest_dependencies(text: &str) -> ManifestDependencies { let mut out = ManifestDependencies { paths: Vec::new(), inherits_workspace: false, }; let mut in_dependencies = false; - for line in text.lines().map(|l| strip_toml_comment(l).trim()) { + for line in logical_lines(text).iter().map(String::as_str) { if line.starts_with('[') { let header = line.trim_matches(|c| c == '[' || c == ']').trim(); let first = header.split('.').next().map(str::trim); @@ -418,7 +416,7 @@ fn manifest_dependencies(text: &str) -> ManifestDependencies { /// The `[package]` name a `Cargo.toml` declares. fn manifest_package_name(text: &str) -> Option { let mut in_package = false; - for line in text.lines().map(|l| strip_toml_comment(l).trim()) { + for line in logical_lines(text).iter().map(String::as_str) { if line.starts_with('[') { in_package = line == "[package]"; } else if in_package && let Some(name) = toml_key_string(line, "name") { @@ -428,6 +426,34 @@ fn manifest_package_name(text: &str) -> Option { None } +/// The logical lines of a TOML text: comments stripped, each trimmed, and the physical lines +/// of an inline table or array still open at a line's end joined onto it with a space. +fn logical_lines(text: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + let mut depth = 0i32; + for raw in text.lines() { + let line = strip_toml_comment(raw).trim(); + depth += unquoted(line).fold(0, |d, (_, c)| match c { + '{' | '[' => d + 1, + '}' | ']' => d - 1, + _ => d, + }); + if !current.is_empty() { + current.push(' '); + } + current.push_str(line); + if depth <= 0 { + depth = 0; + out.push(std::mem::take(&mut current)); + } + } + if !current.is_empty() { + out.push(current); + } + out +} + /// The characters of one TOML line that sit outside any string, with their byte offsets. fn unquoted(line: &str) -> impl Iterator + '_ { let mut quote: Option = None; @@ -1072,4 +1098,14 @@ mod tests { assert_eq!(deps.paths, ["lit", "b\\c", "d", "e", "g"]); assert!(deps.inherits_workspace); } + + #[test] + fn the_line_scan_reads_inline_tables_and_arrays_that_span_lines() { + let deps = manifest_dependencies( + "[dependencies]\nlinked = { # { opens nothing\n features = [\n \"x\",\n ],\n path = \"../linked\",\n}\n\ + next = { path = \"next\" }\n[dev-dependencies]\nskipped = {\npath = \"skipped\"\n}\n", + ); + assert_eq!(deps.paths, ["../linked", "next"]); + assert!(!deps.inherits_workspace); + } } From 33568261ecc3cc2ce9513a843ce890ac988ceef6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:47:03 -0500 Subject: [PATCH 5/8] no-mistakes(review): Hash path deps that are also workspace roots --- server/rust/metaobjects-codegen/src/engine.rs | 50 +++++++++++++++---- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index efb7df6348..f517681ed0 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -314,17 +314,18 @@ const PATH_DEPENDENCY_NOT_INPUTS: &[&str] = &["target", ".git"]; fn path_dependency_entries(owned_manifest: &Path) -> Vec { let engine: HashSet = std::env::split_paths(ENGINE_CRATE_DIRS).collect(); let mut entries = Vec::new(); - // Every manifest queued so far, by canonical path: each is read and scanned once. + // Every manifest queued so far, by canonical path: each is scanned once. let mut queued: HashSet = HashSet::new(); + // Every crate directory already hashed: a crate is one entry however it is reached. + let mut hashed: HashSet = HashSet::new(); let mut queue = Vec::new(); - let mut enqueue = |manifest: PathBuf, queue: &mut Vec<(PathBuf, String)>| -> Option { + let mut enqueue = |manifest: PathBuf, queue: &mut Vec<(PathBuf, String)>| -> String { let manifest = std::fs::canonicalize(&manifest).unwrap_or(manifest); - if !queued.insert(manifest.clone()) { - return None; - } let text = std::fs::read_to_string(&manifest).unwrap_or_default(); - queue.push((manifest, text.clone())); - Some(text) + if queued.insert(manifest.clone()) { + queue.push((manifest, text.clone())); + } + text }; enqueue(owned_manifest.to_path_buf(), &mut queue); while let Some((manifest, text)) = queue.pop() { @@ -339,12 +340,10 @@ fn path_dependency_entries(owned_manifest: &Path) -> Vec { for rel in deps.paths { let dir = base.join(&rel); let dir = std::fs::canonicalize(&dir).unwrap_or(dir); - if engine.contains(&dir) { + if engine.contains(&dir) || !hashed.insert(dir.clone()) { continue; } - let Some(dep_text) = enqueue(dir.join("Cargo.toml"), &mut queue) else { - continue; - }; + let dep_text = enqueue(dir.join("Cargo.toml"), &mut queue); let name = manifest_package_name(&dep_text).unwrap_or(rel); // A crate with no manifest: cargo will fail on it; until it exists, its absence // is the input. @@ -1086,6 +1085,35 @@ mod tests { assert_eq!(entries, Vec::new()); } + #[test] + fn a_path_dependency_on_the_workspace_root_it_inherits_from_is_still_hashed() { + let scratch = + std::env::var_os("DEV_SCRATCH").map_or_else(std::env::temp_dir, PathBuf::from); + let dir = scratch.join(format!("mo-engine-ws-root-dep-{}", std::process::id())); + std::fs::create_dir_all(dir.join("codegen")).unwrap(); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write( + dir.join("Cargo.toml"), + "[package]\nname = \"app\"\n\n[workspace]\nmembers = [\"codegen\"]\n\n\ + [workspace.dependencies]\nserde = \"1\"\n", + ) + .unwrap(); + let manifest = dir.join("codegen/Cargo.toml"); + std::fs::write( + &manifest, + "[package]\nname = \"codegen\"\n\n[dependencies]\nserde.workspace = true\napp = { path = \"..\" }\n", + ) + .unwrap(); + std::fs::write(dir.join("src/lib.rs"), "// v1\n").unwrap(); + let before = path_dependency_entries(&manifest); + std::fs::write(dir.join("src/lib.rs"), "// v2\n").unwrap(); + let after = path_dependency_entries(&manifest); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(after.len(), 1); + assert_ne!(before, after); + } + #[test] fn the_line_scan_reads_the_forms_cargo_accepts() { let deps = manifest_dependencies( From ee0a6b23bea83ad34b3bde7e106ca20e8b2962ca Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:50:47 -0500 Subject: [PATCH 6/8] no-mistakes(review): Hash pack deps the CLI aliases; rewrap changelog --- .../gen-skip-key-linked-generator-packages.md | 5 ++-- .../packages/cli/src/lib/gen-fingerprint.ts | 22 ++++++++--------- .../gen-fingerprint-linked-package.test.ts | 24 ++++++++++++++----- 3 files changed, 31 insertions(+), 20 deletions(-) diff --git a/changelog.d/gen-skip-key-linked-generator-packages.md b/changelog.d/gen-skip-key-linked-generator-packages.md index 8f78908065..ef2ec6899a 100644 --- a/changelog.d/gen-skip-key-linked-generator-packages.md +++ b/changelog.d/gen-skip-key-linked-generator-packages.md @@ -7,5 +7,6 @@ on by `path`, in a build table or a `[patch]`, is now an input too, followed through that crate's own path dependencies and the workspace it inherits from; the `metaobjects` and `metaobjects-codegen` engine crates are still covered by the engine's own source hash. Both ports - bump their fingerprint format, so the first `gen` after upgrading renders once. Before this change, editing such a package's generator code while the model, the config and - the lockfile stayed the same left the key unchanged, and `gen` skipped over stale output. + bump their fingerprint format, so the first `gen` after upgrading renders once. Before this + change, editing such a package's generator code while the model, the config and the lockfile + stayed the same left the key unchanged, and `gen` skipped over stale output. diff --git a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts index d4206021b6..34cbea6dfd 100644 --- a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -171,13 +171,10 @@ function packageEntries(kind: string, dir: string): FingerprintEntry[] { /** * The packages a package runs on: every `@metaobjectsdev/*` dependency, followed all the - * way, by full identity; every other dependency by its `package.json` (its version). A - * dependency named in `skip` is left out: a generator package's copy of a package the CLI - * aliases onto its engine never runs, so only the engine's copy counts. + * way, by full identity; every other dependency by its `package.json` (its version). The + * shared `seen` set counts one physical copy once, so the engine's copy is not repeated. */ -function packageClosureEntries( - kind: string, rootDir: string, seen: Set, skip: ReadonlySet = new Set(), -): FingerprintEntry[] { +function packageClosureEntries(kind: string, rootDir: string, seen: Set): FingerprintEntry[] { const entries: FingerprintEntry[] = []; const visit = (dir: string): void => { let real = dir; @@ -187,7 +184,6 @@ function packageClosureEntries( entries.push(...packageEntries(kind, dir)); const pkg = readJson(join(dir, "package.json")); for (const dep of dependencyNames(pkg)) { - if (skip.has(dep)) continue; const depDir = findPackageDir(dep, dir); if (depDir === undefined) { entries.push({ kind, name: `${dep}/package.json`, hash: "absent" }); @@ -286,12 +282,14 @@ function configGraphEntries(configFile: string, projectRoot: string, seen: Set = {}): { root: string; linkedIndex: string } { const root = mkdtempSync(join(SCRATCH, "gen-linked-")); made.push(root); mkdirSync(join(root, ".git")); @@ -71,7 +71,7 @@ function makeProject(): { root: string; linkedIndex: string } { // The linked package: its source lives outside any node_modules, as with a workspace // member, a clone or `bun link`, and the project's node_modules holds a symlink to it. - const linkedIndex = linkPackage(root, "linked-checkout", { name: LINKED, dependencies: { [ENGINE_PKG]: "*" } }, linkedSource("first\n")); + const linkedIndex = linkPackage(root, "linked-checkout", { name: LINKED, dependencies }, linkedSource("first\n")); writeFileSync(join(root, "metaobjects.config.ts"), `import { defineConfig } from "@metaobjectsdev/codegen-ts"; import { linked } from "${LINKED}"; @@ -116,10 +116,10 @@ describe("the skip key covers a linked @metaobjectsdev/* generator package (ADR- expect(keyFor(await inputsFor(p.root, ENGINE), [])).not.toBe(keyFor(before, [])); }); - test("an import the CLI aliases onto its engine is not hashed from the project's copy", async () => { - // The config imports `@metaobjectsdev/codegen-ts`, and the linked package depends on it; - // the CLI points both at its own copy, which the engine half counts. A linked copy in the - // project's node_modules never runs, so editing it must leave the key alone. + test("an import only the config makes of a package the CLI aliases is not hashed from the project's copy", async () => { + // The config imports `@metaobjectsdev/codegen-ts`; the CLI points that import at its own + // copy, which the engine half counts. A linked copy in the project's node_modules never + // runs for the config, so editing it must leave the key alone. const p = makeProject(); const fakeIndex = linkPackage(p.root, "engine-checkout", { name: ENGINE_PKG }, "export const v = 1;\n"); expect(CLI_ALIASED_PACKAGES.has(ENGINE_PKG)).toBe(true); @@ -129,4 +129,16 @@ describe("the skip key covers a linked @metaobjectsdev/* generator package (ADR- writeFileSync(fakeIndex, "export const v = 2;\n"); expect(keyFor(await inputsFor(p.root, ENGINE), [])).toBe(keyFor(before, [])); }); + + test("a linked package's own dependency on a package the CLI aliases is hashed", async () => { + // Only the config file is rewritten onto the CLI's copies; a module inside the pack + // resolves the dependency through the project, so that copy runs and must count. + const p = makeProject({ [ENGINE_PKG]: "*" }); + const depIndex = linkPackage(p.root, "engine-checkout", { name: ENGINE_PKG }, "export const v = 1;\n"); + + const before = await inputsFor(p.root, ENGINE); + expect(before.entries.some((e) => e.kind === "generator-package" && e.name === `${ENGINE_PKG}/index.ts`)).toBe(true); + writeFileSync(depIndex, "export const v = 2;\n"); + expect(keyFor(await inputsFor(p.root, ENGINE), [])).not.toBe(keyFor(before, [])); + }); }); From cb5343e41ea273f23829b942f93cd2e954b9580e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:01:57 -0500 Subject: [PATCH 7/8] no-mistakes(document): Document pack imports in gen skip key --- docs/features/cli.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/features/cli.md b/docs/features/cli.md index 32a64b34f8..da70bb0d8a 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -278,8 +278,10 @@ nothing. No port has a `doctor` command: `eject --list` (or the matching goal) i Every port's `gen` loads the metadata, then computes a key before it renders anything: the loaded model (each node in its canonical effective form, so reformatting or splitting a metadata file changes nothing) plus everything the generators are built from (the engine's built code, -the codegen config and every owned generator, the template roots, declared extra inputs, the -project config, the output-changing flags). When the key matches the last successful run and +every generator package the config imports beyond the engine's own (a pack or a third-party +package: by its content when linked, by its version when installed), the codegen config and every +owned generator, the template roots, declared extra inputs, the project config, the +output-changing flags). When the key matches the last successful run and every generated file still holds the bytes that run left, `gen` says so and renders and writes nothing. The key lives in `.metaobjects/.gen-state/.fingerprint-.json` (on the JVM, one per owner module), which is not committed. From c674a012528399cc266be6d78e95da65e456701a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:03:29 -0500 Subject: [PATCH 8/8] no-mistakes(document): Name pack generators in ADR-0064 identity --- .../ADR-0064-skip-codegen-when-nothing-changed.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md index 6d4dffc7c1..4128748892 100644 --- a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md +++ b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md @@ -55,9 +55,12 @@ before anything renders: version (a linked or locally built engine changes with its content), plus its templates, partials, helpers and options: in practice the engine package and its MetaObjects dependencies, the port's codegen config and every owned generator file it reaches, and the - template roots. A generator that reads anything else declares it as an extra input; one that - cannot declare its inputs is marked not cacheable (`cache: false` in TypeScript, the port's - equivalent elsewhere), and a run that includes it never skips. + template roots. Every generator package the codegen config imports is part of that identity, + whatever its npm scope, third-party and independently published packs included, and is hashed + like any other generator package; only the packages the CLI aliases onto its own engine copy + count as the engine instead. A generator that reads anything else declares it as an extra + input; one that cannot declare its inputs is marked not cacheable (`cache: false` in + TypeScript, the port's equivalent elsewhere), and a run that includes it never skips. - **The run.** The project config (`.metaobjects/config.json`) and every flag that changes output: generator selection, strict mode, the baseline mode.