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 000000000..ef2ec6899 --- /dev/null +++ b/changelog.d/gen-skip-key-linked-generator-packages.md @@ -0,0 +1,12 @@ +- **`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`, 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/features/cli.md b/docs/features/cli.md index 32a64b34f..da70bb0d8 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. diff --git a/docs/ports/rust.md b/docs/ports/rust.md index b02fcb250..80881619d 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -244,7 +244,11 @@ 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), 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/build.rs b/server/rust/metaobjects-codegen/build.rs index 6a5171bb6..30160c19d 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 23726156c..f517681ed 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -296,6 +296,222 @@ pub const OWNED_MANIFEST: &str = "codegen/Cargo.toml"; /// The owned crate's generator list. pub const OWNED_MAIN: &str = "codegen/main.rs"; +/// 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"]; + +/// 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 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_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(); + // 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)>| -> String { + let manifest = std::fs::canonicalize(&manifest).unwrap_or(manifest); + let text = std::fs::read_to_string(&manifest).unwrap_or_default(); + 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() { + 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]`. + enqueue(root, &mut queue); + } + for rel in deps.paths { + let dir = base.join(&rel); + let dir = std::fs::canonicalize(&dir).unwrap_or(dir); + if engine.contains(&dir) || !hashed.insert(dir.clone()) { + 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. + 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, + )); + } + } + entries +} + +/// 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| logical_lines(&t).iter().any(|l| l == "[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 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 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); + in_dependencies = header == "replace" + || first == Some("patch") + || header + .split('.') + .any(|s| matches!(s.trim(), "dependencies" | "build-dependencies")); + continue; + } + if !in_dependencies { + continue; + } + 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 +} + +/// The `[package]` name a `Cargo.toml` declares. +fn manifest_package_name(text: &str) -> Option { + let mut in_package = false; + 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") { + return Some(name); + } + } + 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; + let mut escaped = false; + 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 => 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, + } +} + +/// 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 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; + } + after.trim_start().strip_prefix('=').map(str::trim_start) + }) +} + +/// 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 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), + } + } + 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 +690,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); @@ -840,3 +1057,83 @@ 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 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( + "[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); + } + + #[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); + } +} diff --git a/server/rust/metaobjects-codegen/src/fingerprint.rs b/server/rust/metaobjects-codegen/src/fingerprint.rs index eeea61ee1..0cc7aa3b2 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 87e9685d9..2e282cf75 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -480,6 +480,92 @@ 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()); + // The real engine checkout, as `eject --engine ` writes it. + let engine = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.write( + "codegen/Cargo.toml", + &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. + p.write( + "ws/Cargo.toml", + "[workspace]\nmembers = [\"linked\"]\n\n[workspace.dependencies]\nshared = { path = \"shared\" }\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"); + } + // Another checkout of a crate named like the engine's: not the engine that runs. + p.write( + "fork-of-engine/metaobjects/Cargo.toml", + "[package]\nname = \"metaobjects\"\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, 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!( + 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, 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("dev-only/src/lib.rs", "// v2\n"); + p.write("commented-out/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 3a62b84d1..34cbea6df 100644 --- a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -23,9 +23,11 @@ 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"; +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 = 3; +export const FINGERPRINT_FORMAT = 4; /** One input: what kind it is, which one, and the SHA-256 of its content. */ export interface FingerprintEntry { @@ -169,7 +171,8 @@ 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). 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): FingerprintEntry[] { const entries: FingerprintEntry[] = []; @@ -212,8 +215,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[] { @@ -246,11 +249,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, @@ -284,9 +282,13 @@ function configGraphEntries(configFile: string, projectRoot: string, seen: Set = { }, }; +/** + * 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(packageNameOf), + 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/src/lib/package-name.ts b/server/typescript/packages/cli/src/lib/package-name.ts new file mode 100644 index 000000000..4a703e7a2 --- /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 b9736b5dc..1594460fa 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 new file mode 100644 index 000000000..e153f7da0 --- /dev/null +++ b/server/typescript/packages/cli/test/gen-fingerprint-linked-package.test.ts @@ -0,0 +1,144 @@ +// 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 { tmpdir } from "node:os"; +import { join } 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"; + +// 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 }); }); + +/** 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" }; + +/** 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(dependencies: Record = {}): { root: string; linkedIndex: string } { + const root = mkdtempSync(join(SCRATCH, "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 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}"; +export default defineConfig({ outDir: "generated", generators: [linked()] }); +`); + return { root, linkedIndex }; +} + +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 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); + + const before = await inputsFor(p.root, ENGINE); + expect(before.entries.filter((e) => e.kind === "generator-package" && e.name.startsWith(`${ENGINE_PKG}/`))).toEqual([]); + 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, [])); + }); +}); 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 6d4dffc7c..412874889 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.