diff --git a/crates/cli/src/stdlib.rs b/crates/cli/src/stdlib.rs index 476beca..7421398 100644 --- a/crates/cli/src/stdlib.rs +++ b/crates/cli/src/stdlib.rs @@ -51,14 +51,24 @@ impl StdlibBundle { /// machine path: the release archive must ship a verified `stdlib/` next to /// the binary (RFC-EXT-0003 H-08, ADR). pub fn discover() -> Result, String> { - if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) { - return Self::load(PathBuf::from(dir)).map(Some); + let override_dir = std::env::var_os(STDLIB_DIR_ENV).map(PathBuf::from); + let exe_dir = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(Path::to_path_buf)); + Self::discover_with(override_dir, exe_dir) + } + + /// Discovery with the explicit override and the executable directory passed + /// in. The override is authoritative: a bad `MARQDO_STDLIB_DIR` fails even + /// when a valid sibling Bundle exists (no silent fallback). + fn discover_with( + override_dir: Option, + exe_dir: Option, + ) -> Result, String> { + if let Some(dir) = override_dir { + return Self::load(dir).map(Some); } - Self::discover_from_exe_dir( - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(Path::to_path_buf)), - ) + Self::discover_from_exe_dir(exe_dir) } /// Discover from the directory that holds the executable, without the explicit @@ -454,21 +464,41 @@ pub fn aliases_digest(aliases: &[PublicAlias]) -> String { mod tests { use super::*; - fn dev_bundle() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("..") - .join("..") - .join("stdlib") + /// A small synthetic Bundle so loader unit tests never depend on the + /// product tree (ADR-0070 test-lane separation). + fn write_synthetic_bundle(root: &Path) { + for (relative, body) in [ + ("io.mq.md", "## @knowledge test\n"), + ("io/console.mq.md", "## @knowledge console\n"), + ] { + let path = root.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, body).unwrap(); + } + let digest = tree_digest(root).unwrap(); + let manifest = serde_json::json!({ + "name": "test-stdlib", + "version": "0.0.0-test", + "digest": digest, + }); + std::fs::write( + root.join("stdlib.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); } #[test] - fn dev_bundle_verifies_and_resolves() { - let bundle = StdlibBundle::load(dev_bundle()).unwrap(); - assert!(bundle.digest.starts_with("sha256:")); + fn synthetic_bundle_verifies_and_resolves() { + let dir = tempfile::tempdir().unwrap(); + write_synthetic_bundle(dir.path()); + let bundle = StdlibBundle::load(dir.path()).unwrap(); + assert_eq!(bundle.version(), "0.0.0-test"); let io = bundle.resolve("io").unwrap(); assert_eq!(io.relative_path, "io.mq.md"); - assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@")); + assert!(io.package.instance_id.starts_with("std:test-stdlib@")); assert!(bundle.resolve("../escape").is_err()); + assert!(bundle.resolve("/absolute").is_err()); } #[test] @@ -476,44 +506,31 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let bundle = dir.path().join("stdlib"); std::fs::create_dir_all(&bundle).unwrap(); - for entry in std::fs::read_dir(dev_bundle()).unwrap() { - let entry = entry.unwrap(); - let target = bundle.join(entry.file_name()); - if entry.path().is_dir() { - copy_dir(&entry.path(), &target); - } else { - std::fs::copy(entry.path(), target).unwrap(); - } - } + write_synthetic_bundle(&bundle); let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf())) .unwrap() .expect("sibling stdlib"); - assert_eq!(found.root, bundle.canonicalize().unwrap()); + assert_eq!(found.root(), bundle.canonicalize().unwrap()); } - fn copy_dir(source: &std::path::Path, target: &std::path::Path) { - std::fs::create_dir_all(target).unwrap(); - for entry in std::fs::read_dir(source).unwrap() { - let entry = entry.unwrap(); - let destination = target.join(entry.file_name()); - if entry.path().is_dir() { - copy_dir(&entry.path(), &destination); - } else { - std::fs::copy(entry.path(), destination).unwrap(); - } - } + #[test] + fn bad_override_fails_closed_even_with_a_valid_sibling() { + let dir = tempfile::tempdir().unwrap(); + let sibling = dir.path().join("stdlib"); + std::fs::create_dir_all(&sibling).unwrap(); + write_synthetic_bundle(&sibling); + let error = StdlibBundle::discover_with( + Some(dir.path().join("missing")), + Some(dir.path().to_path_buf()), + ) + .unwrap_err(); + assert!(error.contains("cannot open stdlib directory"), "{error}"); } #[test] fn digest_tamper_is_rejected() { let dir = tempfile::tempdir().unwrap(); - let source = dev_bundle(); - for entry in std::fs::read_dir(&source).unwrap() { - let entry = entry.unwrap(); - if entry.path().is_file() { - std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap(); - } - } + write_synthetic_bundle(dir.path()); std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap(); let error = StdlibBundle::load(dir.path()).unwrap_err(); assert!(error.contains("digest mismatch"), "{error}"); diff --git a/crates/cli/tests/architecture_boundaries.rs b/crates/cli/tests/architecture_boundaries.rs index 45061d6..ed33384 100644 --- a/crates/cli/tests/architecture_boundaries.rs +++ b/crates/cli/tests/architecture_boundaries.rs @@ -6,6 +6,9 @@ //! stdio/file/TCP resource endpoints. They are source and digest checks, not an //! OS-sandbox proof. +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use sha2::{Digest, Sha256}; @@ -88,7 +91,14 @@ fn runtime_depends_on_the_host_platform_layer_without_a_cycle() { #[test] fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); + // Phase A (ADR-0070): the pinned Bundle is still the checkout tree. Phase B + // replaces this assertion when the ecosystem Bundle becomes the input. + assert_eq!( + root, + repo_root().join("stdlib").canonicalize().unwrap(), + "the Phase A stdlib pin must resolve to the in-repo stdlib tree" + ); let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap(); assert_eq!(manifest["name"], "marqdo-stdlib"); @@ -103,7 +113,7 @@ fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() { #[test] fn stdlib_imports_resolve_inside_the_bundle() { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); for entry in walk_markdown(&root) { let is_test = entry.starts_with(root.join("tests")); let text = read(&entry); @@ -439,7 +449,7 @@ const _: fn(marqdo_value::Value) = |value| match value { /// hard-coded runtime names. Recompute the canonical metadata digest. #[test] fn official_stdlib_public_aliases_are_verified_metadata() { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap(); let aliases = manifest["public_aliases"] diff --git a/crates/cli/tests/conformance_semantics.rs b/crates/cli/tests/conformance_semantics.rs index 6ef7a19..0bcffc5 100644 --- a/crates/cli/tests/conformance_semantics.rs +++ b/crates/cli/tests/conformance_semantics.rs @@ -20,6 +20,9 @@ //! expectation; the checked-in goldens were reviewed individually. use std::fs; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use marqdo_host::{Capabilities, Host, StdHost}; @@ -291,7 +294,7 @@ fn normalise_relative(path: &Path) -> String { /// unique registry, run the single binding pass and install its table. There is /// no `print_override` and no runtime name guessing. fn bind_calls_with_stdlib_aliases(program: &mut Program) { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); let mut loaded = std::collections::BTreeSet::new(); let mut official = Vec::new(); if root.join("stdlib.json").is_file() { @@ -428,7 +431,7 @@ fn install_entry_stdlib_imports( module_id: &ModuleId, analysis: &marqdo_frontend::AnalysisResult, ) { - let root = repo_root().join("stdlib"); + let root = stdlib_support::bundle_dir(); let Some(imports) = analysis .document .frontmatter() diff --git a/crates/cli/tests/p2_closure.rs b/crates/cli/tests/p2_closure.rs index 12be670..a7014d3 100644 --- a/crates/cli/tests/p2_closure.rs +++ b/crates/cli/tests/p2_closure.rs @@ -3,6 +3,9 @@ #[path = "support/observation.rs"] pub mod observation; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use std::process::Command; @@ -109,7 +112,8 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() { #[test] fn p2_stdlib_table_also_runs_in_pure_mode() { - let path = repo_root().join("stdlib").join("tests").join("table.mq.md"); + let bundle = stdlib_support::bundle_dir(); + let path = bundle.join("tests").join("table.mq.md"); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) .args([ "run", @@ -119,8 +123,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() { "--output", "json", ]) - .current_dir(repo_root().join("stdlib")) - .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) + .current_dir(&bundle) + .env("MARQDO_STDLIB_DIR", &bundle) .output() .expect("run table self-test"); assert_eq!( diff --git a/crates/cli/tests/stdlib_alias_routing.rs b/crates/cli/tests/stdlib_alias_routing.rs index 5747ec5..3493948 100644 --- a/crates/cli/tests/stdlib_alias_routing.rs +++ b/crates/cli/tests/stdlib_alias_routing.rs @@ -5,6 +5,9 @@ //! runtime name special case and no hard-coded per-function scan. #![cfg(unix)] +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::sync::atomic::{AtomicU32, Ordering}; @@ -35,15 +38,6 @@ impl Drop for TempDir { } } -fn repo() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output { let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo")); command.args(args).current_dir(dir); @@ -62,7 +56,7 @@ fn stdout(output: &Output) -> String { } fn copy_stdlib(target: &Path) { - let source = repo().join("stdlib"); + let source = stdlib_support::bundle_dir(); std::fs::create_dir_all(target).unwrap(); for entry in std::fs::read_dir(&source).unwrap() { let entry = entry.unwrap(); diff --git a/crates/cli/tests/stdlib_bundle.rs b/crates/cli/tests/stdlib_bundle.rs index 65f2bc9..f95ea04 100644 --- a/crates/cli/tests/stdlib_bundle.rs +++ b/crates/cli/tests/stdlib_bundle.rs @@ -1,23 +1,17 @@ //! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10). +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::path::{Path, PathBuf}; use std::process::Command; -fn repo_root() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - fn binary() -> &'static str { env!("CARGO_BIN_EXE_marqdo") } fn stdlib_dir() -> PathBuf { - repo_root().join("stdlib") + stdlib_support::bundle_dir() } fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output { diff --git a/crates/cli/tests/stdlib_http.rs b/crates/cli/tests/stdlib_http.rs index 570400b..cddcf97 100644 --- a/crates/cli/tests/stdlib_http.rs +++ b/crates/cli/tests/stdlib_http.rs @@ -3,24 +3,18 @@ #[path = "support/observation.rs"] pub mod observation; -use std::path::Path; -use std::process::Command; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; -fn repo_root() -> std::path::PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} +use std::process::Command; #[test] fn stdlib_http_parses_chunked_responses_and_builds_requests() { + let bundle = stdlib_support::bundle_dir(); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) .args(["run", "tests/http.mq.md", "--output", "json"]) - .current_dir(repo_root().join("stdlib")) - .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) + .current_dir(&bundle) + .env("MARQDO_STDLIB_DIR", &bundle) .output() .expect("run http self-test"); assert_eq!( diff --git a/crates/cli/tests/stdlib_product.rs b/crates/cli/tests/stdlib_product.rs index 6b64505..fc3a2e4 100644 --- a/crates/cli/tests/stdlib_product.rs +++ b/crates/cli/tests/stdlib_product.rs @@ -8,20 +8,14 @@ #[path = "support/observation.rs"] pub mod observation; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Mutex, MutexGuard}; -fn repo_root() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - static FS_LOCK: Mutex<()> = Mutex::new(()); fn lock_fs(name: &str) -> Option> { @@ -33,7 +27,7 @@ fn lock_fs(name: &str) -> Option> { } fn stdlib_dir() -> PathBuf { - repo_root().join("stdlib") + stdlib_support::bundle_dir() } struct TestFile { diff --git a/crates/cli/tests/stdlib_table.rs b/crates/cli/tests/stdlib_table.rs index a1ca0a1..2603c01 100644 --- a/crates/cli/tests/stdlib_table.rs +++ b/crates/cli/tests/stdlib_table.rs @@ -3,23 +3,17 @@ #[path = "support/observation.rs"] pub mod observation; -use std::path::Path; +#[path = "support/stdlib.rs"] +pub mod stdlib_support; + use std::process::Command; -fn repo_root() -> std::path::PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .parent() - .unwrap() - .to_path_buf() -} - fn run_table_self_test() -> serde_json::Value { + let bundle = stdlib_support::bundle_dir(); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) .args(["run", "tests/table.mq.md", "--output", "json"]) - .current_dir(repo_root().join("stdlib")) - .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) + .current_dir(&bundle) + .env("MARQDO_STDLIB_DIR", &bundle) .output() .expect("run table self-test"); assert_eq!( diff --git a/crates/cli/tests/support/stdlib.rs b/crates/cli/tests/support/stdlib.rs new file mode 100644 index 0000000..0782a08 --- /dev/null +++ b/crates/cli/tests/support/stdlib.rs @@ -0,0 +1,356 @@ +//! Pinned stdlib Bundle resolver shared by test harnesses (ADR-0070). +//! +//! Product tests consume one explicit Bundle whose identity is pinned in +//! `tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest and +//! alias digest). `MARQDO_TEST_STDLIB_BUNDLE` may change the location, but the +//! Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN` may change the pin +//! file. A bad explicit input fails even when the default location is valid — +//! there is no silent fallback. + +use std::path::{Component, Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +pub const BUNDLE_ENV: &str = "MARQDO_TEST_STDLIB_BUNDLE"; +pub const PIN_ENV: &str = "MARQDO_TEST_BUNDLE_PIN"; + +/// The checkout root (this test support module lives in `crates/cli/tests`). +pub fn repo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("crates directory") + .parent() + .expect("repository root") + .to_path_buf() +} + +/// Pin file path, overridable for a candidate Bundle. +pub fn pin_path() -> PathBuf { + std::env::var_os(PIN_ENV) + .map(PathBuf::from) + .unwrap_or_else(|| { + repo_root() + .join("tools") + .join("stdlib") + .join("bundle-pin.json") + }) +} + +/// One pinned Bundle identity (`tools/stdlib/bundle-pin.json`). +#[derive(Debug, Clone)] +pub struct BundlePin { + pub name: String, + pub version: String, + pub source_commit: String, + pub source_path: PathBuf, + pub tree_digest: String, + pub aliases_digest: String, +} + +impl BundlePin { + pub fn load(path: &Path) -> Self { + let text = std::fs::read_to_string(path) + .unwrap_or_else(|error| panic!("cannot read Bundle pin {}: {error}", path.display())); + let value: serde_json::Value = serde_json::from_str(&text) + .unwrap_or_else(|error| panic!("invalid Bundle pin {}: {error}", path.display())); + assert_eq!( + value.get("schema").and_then(serde_json::Value::as_str), + Some("marqdo.stdlib-bundle-pin"), + "{} must use the marqdo.stdlib-bundle-pin schema", + path.display() + ); + assert_eq!( + value + .get("schema_version") + .and_then(serde_json::Value::as_u64), + Some(1), + "{} must use pin schema_version 1", + path.display() + ); + let source = value + .get("source") + .unwrap_or_else(|| panic!("Bundle pin {} has no source object", path.display())); + let source_path = source + .get("path") + .and_then(serde_json::Value::as_str) + .unwrap_or_else(|| panic!("Bundle pin {} has no source.path", path.display())); + validate_relative(source_path) + .unwrap_or_else(|error| panic!("Bundle pin {} source.path: {error}", path.display())); + Self { + name: required_str(&value, "name", path), + version: required_str(&value, "version", path), + source_commit: required_str(source, "commit", path), + source_path: PathBuf::from(source_path), + tree_digest: required_str(&value, "tree_digest", path), + aliases_digest: required_str(&value, "aliases_digest", path), + } + } + + /// The committed pin for the current checkout. + pub fn committed() -> Self { + Self::load(&pin_path()) + } +} + +fn required_str(value: &serde_json::Value, field: &str, path: &Path) -> String { + value + .get(field) + .and_then(serde_json::Value::as_str) + .filter(|text| !text.is_empty()) + .unwrap_or_else(|| panic!("Bundle pin {} has no `{field}`", path.display())) + .to_string() +} + +/// One verified Bundle on disk. +#[derive(Debug, Clone)] +pub struct Bundle { + root: PathBuf, + pub name: String, + pub version: String, + pub tree_digest: String, + pub aliases_digest: String, +} + +impl Bundle { + /// Resolve the Bundle for a product test: explicit override or pinned path, + /// verified against the pin. + pub fn pinned() -> Self { + let pin = BundlePin::committed(); + let explicit = std::env::var_os(BUNDLE_ENV).map(PathBuf::from); + let root = explicit + .clone() + .unwrap_or_else(|| repo_root().join(&pin.source_path)); + let bundle = Self::verify(&root).unwrap_or_else(|error| match &explicit { + Some(_) => panic!( + "{BUNDLE_ENV} does not name a valid stdlib Bundle at {}: {error}", + root.display() + ), + None => panic!( + "pinned stdlib Bundle at {} is invalid: {error}", + root.display() + ), + }); + let mismatches = [ + ("name", &pin.name, &bundle.name), + ("version", &pin.version, &bundle.version), + ("tree_digest", &pin.tree_digest, &bundle.tree_digest), + ( + "aliases_digest", + &pin.aliases_digest, + &bundle.aliases_digest, + ), + ]; + for (field, expected, actual) in mismatches { + assert_eq!( + expected, + actual, + "stdlib Bundle at {} does not match the pin field `{field}`", + root.display() + ); + } + for required in ["stdlib.json", "io.mq.md", "io/console.mq.md"] { + assert!( + bundle.root.join(required).is_file(), + "stdlib Bundle at {} is missing required file {required}", + bundle.root.display() + ); + } + assert_eq!( + pin.source_commit.len(), + 40, + "the pin must record a full source commit, got {:?}", + pin.source_commit + ); + bundle + } + + /// Verify one unpacked Bundle root. + pub fn verify(root: &Path) -> Result { + if !root.is_dir() { + return Err(format!("not a directory: {}", root.display())); + } + let manifest_path = root.join("stdlib.json"); + if !manifest_path.is_file() { + return Err(format!("missing manifest: {}", manifest_path.display())); + } + let text = std::fs::read_to_string(&manifest_path) + .map_err(|error| format!("cannot read {}: {error}", manifest_path.display()))?; + let manifest: serde_json::Value = serde_json::from_str(&text) + .map_err(|error| format!("invalid {}: {error}", manifest_path.display()))?; + let name = manifest + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| format!("{} has no name", manifest_path.display()))? + .to_string(); + let version = manifest + .get("version") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| format!("{} has no version", manifest_path.display()))? + .to_string(); + let declared = manifest + .get("digest") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| format!("{} has no digest", manifest_path.display()))? + .to_string(); + let actual = tree_digest(root)?; + if declared != actual { + return Err(format!( + "tree digest mismatch: stdlib.json declares {declared}, the files are {actual}" + )); + } + let aliases = manifest + .get("public_aliases") + .and_then(serde_json::Value::as_array) + .cloned() + .unwrap_or_default(); + let declared_aliases = manifest + .get("aliases_digest") + .and_then(serde_json::Value::as_str) + .map(ToString::to_string); + let actual_aliases = aliases_digest(&aliases); + match (declared_aliases, aliases.is_empty()) { + (Some(declared_aliases), _) => { + if declared_aliases != actual_aliases { + return Err(format!( + "alias digest mismatch: stdlib.json declares {declared_aliases}, \ + the alias table is {actual_aliases}" + )); + } + } + (None, false) => { + return Err(format!( + "{} declares public_aliases without aliases_digest", + manifest_path.display() + )); + } + (None, true) => {} + } + Ok(Self { + root: root + .canonicalize() + .map_err(|error| format!("cannot canonicalize {}: {error}", root.display()))?, + name, + version, + tree_digest: actual, + aliases_digest: actual_aliases, + }) + } + + pub fn root(&self) -> &Path { + &self.root + } +} + +/// Resolve and verify the pinned Bundle once per test process. +pub fn bundle() -> &'static Bundle { + static BUNDLE: std::sync::OnceLock = std::sync::OnceLock::new(); + BUNDLE.get_or_init(Bundle::pinned) +} + +/// Bundle root for fixtures and `MARQDO_STDLIB_DIR`. +pub fn bundle_dir() -> PathBuf { + bundle().root().to_path_buf() +} + +/// Content digest over all `.mq.md` files: sorted relative path, NUL, bytes, NUL. +pub fn tree_digest(root: &Path) -> Result { + let mut files = Vec::new(); + collect_markdown(root, root, &mut files)?; + files.sort(); + let mut hasher = Sha256::new(); + for (relative, path) in files { + let bytes = std::fs::read(&path) + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; + hasher.update(relative.as_bytes()); + hasher.update([0]); + hasher.update(&bytes); + hasher.update([0]); + } + Ok(format!("sha256:{}", hex(&hasher.finalize()))) +} + +/// Canonical digest over the official public-alias table. +pub fn aliases_digest(aliases: &[serde_json::Value]) -> String { + let mut entries: Vec<&serde_json::Value> = aliases.iter().collect(); + entries.sort_by_key(|alias| { + ( + alias["target_module"].as_str().unwrap_or("").to_string(), + alias["target_function"].as_str().unwrap_or("").to_string(), + ) + }); + let mut hasher = Sha256::new(); + for alias in entries { + if let Some(module) = alias["target_module"].as_str() { + hasher.update(module.as_bytes()); + } + hasher.update([0]); + if let Some(function) = alias["target_function"].as_str() { + hasher.update(function.as_bytes()); + } + hasher.update([0]); + let mut names: Vec<&str> = alias["public_names"] + .as_array() + .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect()) + .unwrap_or_default(); + names.sort(); + for name in names { + hasher.update(name.as_bytes()); + hasher.update([0]); + } + } + format!("sha256:{}", hex(&hasher.finalize())) +} + +fn collect_markdown( + root: &Path, + dir: &Path, + out: &mut Vec<(String, PathBuf)>, +) -> Result<(), String> { + let entries = std::fs::read_dir(dir) + .map_err(|error| format!("cannot read {}: {error}", dir.display()))?; + for entry in entries { + let entry = entry.map_err(|error| format!("cannot read {}: {error}", dir.display()))?; + let path = entry.path(); + if path.is_dir() { + collect_markdown(root, &path, out)?; + } else if path + .file_name() + .is_some_and(|name| name.to_string_lossy().ends_with(".mq.md")) + { + let relative = path + .strip_prefix(root) + .map_err(|_| "stdlib file escaped its root".to_string())? + .components() + .map(|component| component.as_os_str().to_string_lossy().to_string()) + .collect::>() + .join("/"); + out.push((relative, path)); + } + } + Ok(()) +} + +fn validate_relative(path: &str) -> Result<(), String> { + let mut normalised = PathBuf::new(); + for component in Path::new(path).components() { + match component { + Component::Normal(part) => normalised.push(part), + Component::CurDir => {} + Component::ParentDir | Component::RootDir | Component::Prefix(_) => { + return Err("must be a relative path inside the repository".to_string()) + } + } + } + if normalised.as_os_str().is_empty() { + return Err("must not be empty".to_string()); + } + Ok(()) +} + +fn hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push_str(&format!("{byte:02x}")); + } + out +}