From f800f070f77b2f1446ed449bd14ae983e3cc8ba4 Mon Sep 17 00:00:00 2001 From: Lukas Niessen Date: Wed, 30 Sep 2026 18:23:52 +0200 Subject: [PATCH 1/2] feat: add detailed inspection and highlighted output for v0.0.2 --- CHANGELOG.md | 11 ++++ README.md | 61 ++++++++++++++++++-- build.zig.zon | 2 +- release/v0.0.2.json | 11 ++++ release/v0.0.2.md | 75 +++++++++++++++++++++++++ scripts/build_docs.py | 2 +- scripts/release.py | 8 +-- scripts/test_release.py | 8 +-- src/common/extraction/project_graph.zig | 7 ++- src/common/logging/check_logger.zig | 67 +++++++++++++++++++++- src/common/logging/types.zig | 2 + src/files/fluentapi/files.zig | 6 ++ src/graph/fluentapi/project_graph.zig | 50 ++++++++++++++++- src/metrics/fluentapi/metrics.zig | 74 +++++++++++++++++++++++- test/readme.zig | 8 ++- test/readme/logging.zig | 26 +++++++++ 16 files changed, 394 insertions(+), 24 deletions(-) create mode 100644 release/v0.0.2.json create mode 100644 release/v0.0.2.md create mode 100644 test/readme/logging.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index ee89f51..cebd432 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,15 @@ All notable changes to ArchUnitZig are recorded here. Versions follow semantic versioning, while the `0.x` series remains explicitly pre-stable. +## [0.0.2] - 2026-09-30 + +- Add opt-in debug inspection of discovered files, dependency edges, selected files and graph reports. +- Log passing built-in and custom metric values without re-running callbacks. +- Add explicit ANSI severity highlighting for writer logs; file and structured records stay plain. +- Document verbosity, sinks and formatted failures with an executable README example. +- Preserve quiet defaults, graph/rule results and existing sink-error propagation. +- Continue to support exactly Zig 0.16.0. + ## [0.0.1] - 2026-08-24 First honest preview release for Zig 0.16.0. @@ -25,3 +34,5 @@ First honest preview release for Zig 0.16.0. - Public APIs are preview quality and may change before a stable release. [0.0.1]: https://github.com/LukasNiessen/ArchUnitZig/releases/tag/v0.0.1 + +[0.0.2]: https://github.com/LukasNiessen/ArchUnitZig/releases/tag/v0.0.2 diff --git a/README.md b/README.md index 01722d0..1bbe1d5 100644 --- a/README.md +++ b/README.md @@ -6,19 +6,19 @@ ArchUnitZig turns a Zig project into a dependency graph and lets you enforce arc ordinary `zig test` tests. Rules are lazy values: constructing a fluent chain performs no I/O; checking it returns structured violations or integrates with Zig's test runner. -The `v0.0.1` preview targets exactly Zig 0.16.0. Its public surface ships file rules, +The `v0.0.2` preview targets exactly Zig 0.16.0. Its public surface ships file rules, named layers, slices and PlantUML diagrams, Zig-native metrics, graph reports, native test helpers, explicit per-check logging, and low-level extraction/projection data. ## Install -Use the immutable `v0.0.1` archive rather than a mutable branch. The canonical Zig package hash, +Use the immutable `v0.0.2` archive rather than a mutable branch. The canonical Zig package hash, copy-paste `build.zig.zon` dependency, release limitations, and rollback procedure are recorded in -the [version-specific release record](release/v0.0.1.md). +the [version-specific release record](release/v0.0.2.md). ```console -zig fetch --save-exact=archunit https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.1.tar.gz +zig fetch --save-exact=archunit https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.2.tar.gz ``` The explicit `--save=archunit` name is the key used by `b.dependency` below. Add an architecture @@ -358,7 +358,7 @@ resolved package identities, canonical paths, manifest fingerprints, and ignore | Area | Current contract | | --- | --- | | Zig version | Exactly Zig 0.16.x APIs are targeted; other Zig versions are not supported until explicitly tested. | -| Releases | `v0.0.1` is an immutable preview, not a stable compatibility promise; pin its archive URL and package hash. | +| Releases | `v0.0.2` is an immutable preview, not a stable compatibility promise; pin its archive URL and package hash. | | Build discovery | ArchUnitZig does not execute or claim to understand arbitrary `build.zig`; named modules need explicit compilation-unit mappings. | | Dynamic dependencies | Only literal `@import`, `@embedFile`, and `@cInclude` operands are dependency facts. Non-literal operands are parser diagnostics, not guessed names. | | Package internals | Package-origin modules remain external. ArchUnitZig does not recursively analyze fetched dependency source as part of the current project. | @@ -380,6 +380,57 @@ Logging is disabled by default. A check can borrow an ordinary writer, structure file sink with explicit output directory and prefix. Levels are `debug`, `info`, `warn`, and `.@"error"`; logging failures propagate, and no process-global stdout/stderr logger is configured. +### Detailed inspection and highlighted output + +Choose `debug` for the fullest inspection: cache decisions, discovered files and dependencies, +selected files, graph report nodes and edges, and measured built-in and custom metric values, +including passing subjects. Higher levels keep the transcript compact: `info` shows lifecycle, +extraction and exports, `warn` shows violations, and `.@"error"` shows failed operations. +`include_progress`, `include_metrics`, and `include_violations` independently filter event families. +Inspection uses existing results and calls each custom calculation/predicate only once. + + +```zig +const std = @import("std"); +const archunit = @import("archunit"); + +test "inspect a rule with explicit verbosity and highlighted output" { + var files = try archunit.files(std.testing.allocator, .{}); + defer files.deinit(); + var service = try files.inFile(&.{"src/service/root.zig"}); + defer service.deinit(); + var should = try service.should(); + defer should.deinit(); + var rule = try should.haveName(.{ .glob = "root.zig" }); + defer rule.deinit(std.testing.allocator); + + var output: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + var options = archunit.CheckOptions.init(std.testing.allocator, std.testing.io); + options.logging = .{ + .level = .debug, + .writer = &output.writer, + .writer_color = true, + }; + var violations = try rule.check(options); + defer violations.deinit(std.testing.allocator); + try std.testing.expect(violations.passes()); + try std.testing.expect(std.mem.indexOf(u8, output.written(), "selected file: src/service/root.zig") != null); +} +``` + +`writer_color = true` enables cyan debug, green info, yellow warning, and red error records. +It is opt-in: ordinary writers remain plain by default, and file/structured sinks always remain +plain. A writer is borrowed only while the operation runs. To save a transcript, set +`.file = .{ .output_directory = "architecture-logs", .mode = .append }`; the logger creates a +UTC-timestamped file. Use `.logger` with `LogSink` to route structured events to your application. + +The numbered failure formatter above includes selectors, source locations, dependency evidence, +cycles and metric values. Set its `.color.mode` to `.always` for highlighted failures, `.never` +for plain CI text, or `.auto` with an explicit terminal context. Log verbosity and failure +formatting are independent and do not change the returned violations. Configured sink errors +continue to propagate; logging is disabled unless explicitly requested. + Architecture disagreements are data-only `Violation` values. Invalid selectors/options are user errors, while parsing, allocation, I/O, and violated internal invariants are technical errors with an owned `ErrorContext` diagnostic. Paths are normalized to project-relative `/` identifiers in diff --git a/build.zig.zon b/build.zig.zon index 27c9479..331e236 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .archunit, - .version = "0.0.1", + .version = "0.0.2", .fingerprint = 0xd8492c79dce02cec, // Changing this has security and trust implications. .minimum_zig_version = "0.16.0", .dependencies = .{ diff --git a/release/v0.0.2.json b/release/v0.0.2.json new file mode 100644 index 0000000..725b006 --- /dev/null +++ b/release/v0.0.2.json @@ -0,0 +1,11 @@ +{ + "schema_version": 1, + "package_name": "archunit", + "version": "0.0.2", + "tag": "v0.0.2", + "zig_version": "0.16.0", + "license": "MIT", + "archive_url": "https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.2.tar.gz", + "package_hash": "archunit-0.0.2-7Czg3Jt_GQDfTmFjR1HxQu9QJWMgJxKIe81V-QabeYbO", + "release_notes": "release/v0.0.2.md" +} diff --git a/release/v0.0.2.md b/release/v0.0.2.md new file mode 100644 index 0000000..4d486cc --- /dev/null +++ b/release/v0.0.2.md @@ -0,0 +1,75 @@ +# ArchUnitZig v0.0.2 preview + +This patch adds opt-in debug inspection and writer highlighting to the Zig-native architecture +testing library. Discovered files, dependencies, graph selections and all metric verdicts are +inspectable without changing quiet defaults or re-running callbacks. It remains a preview release. + +## Install with Zig 0.16.0 + +Pinned archive URL: + +```text +https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.2.tar.gz +``` + +Canonical Zig package content hash (the checksum after applying `build.zig.zon.paths`): + +```text +archunit-0.0.2-7Czg3Jt_GQDfTmFjR1HxQu9QJWMgJxKIe81V-QabeYbO +``` + +Fetch it directly: + +```console +zig fetch --save-exact=archunit https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.2.tar.gz +``` + +Or add the reviewed pair to `build.zig.zon`: + +```zig +.dependencies = .{ + .archunit = .{ + .url = "https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.2.tar.gz", + .hash = "archunit-0.0.2-7Czg3Jt_GQDfTmFjR1HxQu9QJWMgJxKIe81V-QabeYbO", + }, +}, +``` + +Then expose `archunit.module("archunit")` to an ordinary Zig test module as shown in the README. +The release workflow repeats this exact network fetch in a fresh external project and runs a real +acyclic-architecture rule before publication. + +## What ships + +- File, layer, slice, metric, cycle, dependency, and graph-report architecture rules. +- AST-backed Zig/ZON/resource/C extraction, explicit module contexts, `.archignore`, and + package-qualified workspace analysis. +- Structured violations, deterministic renderers, `std.testing` helpers, explicit logging, + documentation, acceptance fixtures, dogfood rules, and performance budgets. +- Package metadata for version `0.0.2`, exact Zig `0.16.0`, MIT `LICENSE`, `CHANGELOG.md`, + `CONTRIBUTING.md`, and `THIRD_PARTY_LICENSES.md`. + +See [CHANGELOG.md](../CHANGELOG.md) for the release summary. + +## Limitations + +- The public API is preview quality and may change before a stable release. +- Exactly Zig 0.16.0 is supported and tested; other compiler versions are not claimed compatible. +- `build.zig` is never executed or partially guessed. Named modules and compilation roots require + explicit context; workspace discovery finds manifests, not arbitrary build-graph logic. +- Package dependencies remain external, dynamic import operands remain diagnostics, and the library + deliberately does not invent class/interface metrics for Zig. + +## License and integrity + +ArchUnitZig is MIT licensed. Its regex dependency is pinned separately and retains Apache-2.0 and +BSD-derived notices in `THIRD_PARTY_LICENSES.md`. The attached `v0.0.2.json` repeats the reviewed +version, archive URL, Zig content checksum, compiler version, license, and notes path. GitHub +immutable releases lock this release and its annotated tag after publication. + +## Rollback + +Do not move, delete, or reuse `v0.0.2`. To roll back an upgrade, restore the previously reviewed +dependency URL/hash pair in `build.zig.zon` and refetch. The prior reviewed release is +[v0.0.1](v0.0.1.md). Maintainers fix defects forward under a new semantic version; they never +rewrite this tag or checksum. diff --git a/scripts/build_docs.py b/scripts/build_docs.py index 4d74c2a..71a5071 100644 --- a/scripts/build_docs.py +++ b/scripts/build_docs.py @@ -124,7 +124,7 @@ def render_page(root: Path, config: dict, page: dict, next_page: dict | None) ->
-

Zig 0.16 · v0.0.1 preview

+

Zig 0.16 · v0.0.2 preview

{fragment} {next_link}
diff --git a/scripts/release.py b/scripts/release.py index 7aa09ee..ffe4c32 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -14,7 +14,7 @@ ROOT = Path(__file__).resolve().parent.parent -DEFAULT_METADATA = ROOT / "release" / "v0.0.1.json" +DEFAULT_METADATA = ROOT / "release" / "v0.0.2.json" REPOSITORY = "LukasNiessen/ArchUnitZig" @@ -63,9 +63,9 @@ def validate(root: Path, metadata_path: Path, expected_tag: str | None = None) - if re.fullmatch(hash_pattern, metadata.package_hash) is None: errors.append("package_hash is not a canonical Zig package hash for this name/version") if metadata.zig_version != "0.16.0": - errors.append("v0.0.1 supports exactly Zig 0.16.0") + errors.append("v0.0.2 supports exactly Zig 0.16.0") if metadata.license != "MIT": - errors.append("v0.0.1 package license must be MIT") + errors.append("v0.0.2 package license must be MIT") zon = (root / "build.zig.zon").read_text(encoding="utf-8") for value in ( @@ -81,7 +81,7 @@ def validate(root: Path, metadata_path: Path, expected_tag: str | None = None) - readme = (root / "README.md").read_text(encoding="utf-8") require(readme, metadata.archive_url, errors, "README.md") - require(readme, "release/v0.0.1.md", errors, "README.md") + require(readme, metadata.release_notes, errors, "README.md") changelog = (root / "CHANGELOG.md").read_text(encoding="utf-8") require(changelog, f"## [{metadata.version}]", errors, "CHANGELOG.md") require(changelog, metadata.zig_version, errors, "CHANGELOG.md") diff --git a/scripts/test_release.py b/scripts/test_release.py index 4a8dbb4..b82eea3 100644 --- a/scripts/test_release.py +++ b/scripts/test_release.py @@ -10,12 +10,12 @@ class ReleaseContractTests(unittest.TestCase): def test_repository_release_metadata_is_complete(self) -> None: - metadata = release.validate(release.ROOT, release.DEFAULT_METADATA, "v0.0.1") - self.assertEqual("0.0.1", metadata.version) + metadata = release.validate(release.ROOT, release.DEFAULT_METADATA, "v0.0.2") + self.assertEqual("0.0.2", metadata.version) self.assertEqual("0.16.0", metadata.zig_version) - self.assertTrue(metadata.archive_url.endswith("/v0.0.1.tar.gz")) + self.assertTrue(metadata.archive_url.endswith("/v0.0.2.tar.gz")) self.assertEqual( - "archunit-0.0.1-7Czg3AZHGQBbO-ej1RHt71ZUIRQ9HxG6O6tHl4w0r8LN", + "archunit-0.0.2-7Czg3Jt_GQDfTmFjR1HxQu9QJWMgJxKIe81V-QabeYbO", metadata.package_hash, ) diff --git a/src/common/extraction/project_graph.zig b/src/common/extraction/project_graph.zig index 2ff3d25..5d7579b 100644 --- a/src/common/extraction/project_graph.zig +++ b/src/common/extraction/project_graph.zig @@ -130,8 +130,11 @@ fn extractProjectGraphObserved( defer cache_key.deinit(allocator); if (graph_cache.cloneGraphFromCache(allocator, cache_key) catch { return diagnostics.failTechnical(.out_of_memory, "project_graph.cache_get", project.path, error.OutOfMemory); - }) |cached| { + }) |cached_value| { + var cached = cached_value; + errdefer cached.deinit(allocator); try logger.logCache("cache hit"); + try logger.logGraph(&cached); try logger.logExtraction("project graph extraction completed from cache"); return cached; } @@ -160,6 +163,7 @@ fn extractProjectGraphObserved( graph_cache.storeGraphInCache(cache_key, graph) catch { return diagnostics.failTechnical(.out_of_memory, "project_graph.cache_put", project.path, error.OutOfMemory); }; + try logger.logGraph(&graph); try logger.logExtraction("project graph extraction completed"); return graph; } @@ -167,6 +171,7 @@ fn extractProjectGraphObserved( const NoopLogger = struct { fn logExtraction(_: NoopLogger, _: []const u8) error{}!void {} fn logCache(_: NoopLogger, _: []const u8) error{}!void {} + fn logGraph(_: NoopLogger, _: anytype) error{}!void {} }; fn extractLocatedGraph( diff --git a/src/common/logging/check_logger.zig b/src/common/logging/check_logger.zig index f34515e..28ee82a 100644 --- a/src/common/logging/check_logger.zig +++ b/src/common/logging/check_logger.zig @@ -74,6 +74,38 @@ pub const CheckLogger = struct { return self.emit(.debug, .cache, "{s}", .{message}); } + /// Detailed inspection is opt-in and avoids formatting/iteration at higher levels. + pub fn inspectsProgress(self: *const CheckLogger) bool { + return self.options.include_progress and self.options.level == .debug; + } + + pub fn logSubject(self: *CheckLogger, stage: []const u8, subject: []const u8) anyerror!void { + if (!self.inspectsProgress()) return; + try self.emit(.debug, .extraction, "{s}: {s}", .{ stage, safeSubject(subject) }); + } + + pub fn logCount(self: *CheckLogger, stage: []const u8, count: usize) anyerror!void { + if (!self.inspectsProgress()) return; + try self.emit(.debug, .extraction, "{s}={d}", .{ stage, count }); + } + + pub fn logDependency(self: *CheckLogger, source: []const u8, target: []const u8, external: bool) anyerror!void { + if (!self.inspectsProgress()) return; + try self.emit(.debug, .extraction, "dependency: {s} -> {s}; external={}", .{ safeSubject(source), safeSubject(target), external }); + } + + pub fn logGraph(self: *CheckLogger, graph: anytype) anyerror!void { + if (!self.inspectsProgress()) return; + try self.logCount("extracted edges", graph.items().len); + for (graph.items()) |edge| { + if (std.mem.eql(u8, edge.source, edge.target)) { + try self.logSubject("discovered file", edge.source); + } else { + try self.logDependency(edge.source, edge.target, edge.external); + } + } + } + pub fn logViolation(self: *CheckLogger, violation: assertion.Violation) anyerror!void { if (!self.options.include_violations) return; try self.emit(.warn, .violation, "kind={s}", .{@tagName(violation.kind())}); @@ -151,7 +183,16 @@ pub const CheckLogger = struct { .message = safe_message, }; if (self.options.logger) |sink| try sink.write(record); - if (self.options.writer) |writer| try writer.writeAll(line); + if (self.options.writer) |writer| { + if (self.options.writer_color) try writer.writeAll(switch (level) { + .debug => "\x1b[36m", + .info => "\x1b[32m", + .warn => "\x1b[33m", + .@"error" => "\x1b[31m", + }); + try writer.writeAll(line); + if (self.options.writer_color) try writer.writeAll("\x1b[0m"); + } if (self.options.file != null) try self.writeFile(timestamp, line); } @@ -607,3 +648,27 @@ test "logger rendering cleans up every allocation failure" { .{}, ); } + +test "ANSI writer highlighting leaves structured records plain and inspection respects level" { + const PlainSink = struct { + fn write(record: LogRecord) !void { + try std.testing.expect(std.mem.indexOfScalar(u8, record.message, 0x1b) == null); + } + }; + for ([_]LogLevel{ .debug, .info }) |level| { + var output: Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + var logger = try CheckLogger.init(std.testing.allocator, std.testing.io, .{ + .level = level, + .writer = &output.writer, + .writer_color = true, + .logger = LogSink.fromStateless(PlainSink.write), + }); + defer logger.deinit(); + try logger.startCheck("color"); + try logger.logSubject("selected file", "src/example.zig"); + try std.testing.expect(std.mem.indexOf(u8, output.written(), "\x1b[32m") != null); + try std.testing.expectEqual(level == .debug, std.mem.indexOf(u8, output.written(), "selected file: src/example.zig") != null); + try std.testing.expect(std.mem.endsWith(u8, output.written(), "\x1b[0m")); + } +} diff --git a/src/common/logging/types.zig b/src/common/logging/types.zig index a1da33e..427f3e0 100644 --- a/src/common/logging/types.zig +++ b/src/common/logging/types.zig @@ -147,6 +147,8 @@ pub const LoggingOptions = struct { logger: ?LogSink = null, file: ?LogFileOptions = null, clock: LogClock = .{}, + /// ANSI severity highlighting for the writer only; files and structured records stay plain. + writer_color: bool = false, include_progress: bool = true, include_violations: bool = true, include_metrics: bool = true, diff --git a/src/files/fluentapi/files.zig b/src/files/fluentapi/files.zig index 5453b44..4ef3c26 100644 --- a/src/files/fluentapi/files.zig +++ b/src/files/fluentapi/files.zig @@ -652,6 +652,9 @@ pub const FilesHaveNoCycles = struct { ) anyerror!assertion.ViolationList { var selected = try self.rule.select(graph); defer selected.deinit(); + if (options.logger) |logger| { + for (selected.items()) |subject| try logger.logSubject("selected file", subject); + } if (try guardRuleSelection(&self.rule, selected.len(), options, "files.have_no_cycles")) |early| return early; var cycles = try file_cycles.projectSelectedFileCycles( @@ -737,6 +740,9 @@ pub const FilesMatchPattern = struct { ) anyerror!assertion.ViolationList { var selected = try self.rule.select(graph); defer selected.deinit(); + if (options.logger) |logger| { + for (selected.items()) |subject| try logger.logSubject("selected file", subject); + } if (try guardRuleSelection( &self.rule, selected.len(), diff --git a/src/graph/fluentapi/project_graph.zig b/src/graph/fluentapi/project_graph.zig index 9a19b24..9d7b688 100644 --- a/src/graph/fluentapi/project_graph.zig +++ b/src/graph/fluentapi/project_graph.zig @@ -258,7 +258,17 @@ pub const ProjectGraphBuilder = struct { options.logger, ); defer graph.deinit(options.allocator); - return snapshot_factory.createSnapshot(options.allocator, &graph, self.queryOptions()); + var snapshot_value = try snapshot_factory.createSnapshot(options.allocator, &graph, self.queryOptions()); + errdefer snapshot_value.deinit(options.allocator); + if (options.logger) |logger| { + try logger.logCount("report nodes", snapshot_value.nodes.len); + try logger.logCount("report edges", snapshot_value.edges.len); + if (logger.inspectsProgress()) { + for (snapshot_value.nodes) |node| try logger.logSubject("report node", node.label); + for (snapshot_value.edges) |edge| try logger.logDependency(edge.source, edge.target, edge.external); + } + } + return snapshot_value; } pub fn summary( @@ -826,3 +836,41 @@ test "real fixture fluent render and export terminals share the snapshot contrac defer std.testing.allocator.free(expected); try std.testing.expectEqualStrings(expected, exported); } + +test "debug inspection preserves graph snapshots on fresh and cached extraction" { + var builder = try projectGraph(std.testing.allocator, .{ .locator = "test/fixtures/graph-basic" }); + defer builder.deinit(); + var options = CheckOptions.init(std.testing.allocator, std.testing.io); + options.clear_cache = true; + const quiet = try builder.toJson(options); + defer std.testing.allocator.free(quiet); + for ([_]bool{ true, false }) |clear| { + var output: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + options.clear_cache = clear; + options.logging = .{ .level = .debug, .writer = &output.writer }; + const logged = try builder.toJson(options); + defer std.testing.allocator.free(logged); + try std.testing.expectEqualStrings(quiet, logged); + for ([_][]const u8{ "discovered file: src/app/main.zig", "dependency: src/app/main.zig ->", "report nodes=", "report node:" }) |detail| { + try std.testing.expect(std.mem.indexOf(u8, output.written(), detail) != null); + } + try std.testing.expect(std.mem.indexOf(u8, output.written(), if (clear) "cache miss" else "cache hit") != null); + } +} + +test "inspection sink failures clean up fresh and cached graph ownership" { + const FailInspection = struct { + fn write(record: fluentapi.LogRecord) !void { + if (std.mem.startsWith(u8, record.message, "extracted edges=")) return error.InspectionSinkFailed; + } + }; + var builder = try projectGraph(std.testing.allocator, .{ .locator = "test/fixtures/graph-basic" }); + defer builder.deinit(); + var options = CheckOptions.init(std.testing.allocator, std.testing.io); + options.logging = .{ .level = .debug, .logger = fluentapi.LogSink.fromStateless(FailInspection.write) }; + for ([_]bool{ true, false }) |clear| { + options.clear_cache = clear; + try std.testing.expectError(error.InspectionSinkFailed, builder.snapshot(options)); + } +} diff --git a/src/metrics/fluentapi/metrics.zig b/src/metrics/fluentapi/metrics.zig index 5c62b4b..c8813a3 100644 --- a/src/metrics/fluentapi/metrics.zig +++ b/src/metrics/fluentapi/metrics.zig @@ -892,6 +892,7 @@ pub const MetricThresholdRule = struct { errdefer result.deinit(options.allocator); for (measurements.items()) |measurement| { const measured = assertion.MetricValue{ .unsigned = @intCast(measurement.value) }; + if (options.logger) |logger| try logger.logMetric(self.metric.name(), measured, measurement.target_identifier); if (try threshold_assertion.passes(measured, self.comparison, threshold_value)) continue; var payload = try assertion.MetricViolation.init( options.allocator, @@ -1225,6 +1226,7 @@ pub const DependencyThresholdRule = struct { var result = assertion.ViolationList{}; errdefer result.deinit(options.allocator); for (measurements.items()) |measurement| { + if (options.logger) |logger| try logger.logMetric(self.metric.name(), measurement.value, measurement.target_identifier); if (try threshold_assertion.passes(measurement.value, self.comparison, self.threshold_value)) continue; var payload = try assertion.MetricViolation.init( options.allocator, @@ -1410,10 +1412,12 @@ pub const MetricPredicateRule = struct { defer subjects.deinit(options.allocator); try subjects.ensureTotalCapacity(options.allocator, analysis.subjects.items.len); for (analysis.subjects.items) |info| { + const measured = try self.metric.value(info); + if (options.logger) |logger| try logger.logMetric(self.metric.name(), measured, info.identifier); subjects.appendAssumeCapacity(.{ .info = info, .metric_name = self.metric.name(), - .value = try self.metric.value(info), + .value = measured, }); } return predicate_assertion.gatherMetricPredicateViolations( @@ -1718,10 +1722,11 @@ pub const CustomMetricThresholdRule = struct { if (try guardCustomMetricEmpty(&self.selection, analysis.subjects.items.len, options)) |guarded| { return guarded; } + const observed = ObservedMetricCalculation{ .definition_value = self.selection.definition(), .logger = options.logger }; return custom_calculation.gatherThresholdViolations( options.allocator, analysis.subjects.items, - self.selection.definition(), + observed.definition(), self.comparison, self.threshold_value, ); @@ -1757,15 +1762,40 @@ pub const CustomMetricPredicateRule = struct { if (try guardCustomMetricEmpty(&self.selection, analysis.subjects.items.len, options)) |guarded| { return guarded; } + const observed = ObservedMetricCalculation{ .definition_value = self.selection.definition(), .logger = options.logger }; return custom_calculation.gatherPredicateViolations( options.allocator, analysis.subjects.items, - self.selection.definition(), + observed.definition(), self.predicate, ); } }; +// This scoped adapter observes the value returned by the original callback exactly once. +// Pure calculation modules keep their existing callback API and never import logging. +const ObservedMetricCalculation = struct { + definition_value: custom_calculation.CustomMetricDefinition, + logger: ?*fluentapi.CheckLogger, + + fn definition(self: *const ObservedMetricCalculation) custom_calculation.CustomMetricDefinition { + if (self.logger == null) return self.definition_value; + var observed = self.definition_value; + observed.calculation = custom_calculation.CustomMetricCalculation.fromContext( + ObservedMetricCalculation, + self, + calculate, + ); + return observed; + } + + fn calculate(self: *const ObservedMetricCalculation, allocator: Allocator, info: custom_calculation.CustomMetricInfo) anyerror!assertion.MetricValue { + const value = try self.definition_value.calculation.calculate(allocator, info); + if (self.logger) |logger| try logger.logMetric(self.definition_value.name, value, info.identifier); + return value; + } +}; + const CustomMetricSubjectAnalysis = struct { structural_analysis: ?MetricAnalysis = null, dependency_analysis: ?dependency_calculation.DependencyMetricSnapshot = null, @@ -3084,3 +3114,41 @@ test "metrics builder chains release every partial allocation" { .{}, ); } + +test "passing custom metric inspection evaluates calculation and predicate once per check" { + const Counts = struct { + calculations: *usize, + predicates: *usize, + fn calculate(self: *const @This(), _: Allocator, _: custom_calculation.CustomMetricInfo) !assertion.MetricValue { + self.calculations.* += 1; + return .{ .unsigned = 7 }; + } + fn predicate(self: *const @This(), _: Allocator, value: assertion.MetricValue, _: custom_calculation.CustomMetricInfo) !bool { + self.predicates.* += 1; + return value.unsigned == 7; + } + }; + var calculations: usize = 0; + var predicates: usize = 0; + const counts = Counts{ .calculations = &calculations, .predicates = &predicates }; + var root = try metrics(std.testing.allocator, .{ .locator = "test/fixtures/metrics-structural" }); + defer root.deinit(); + var selected = try root.inFile(&.{"src/root.zig"}); + defer selected.deinit(); + var custom = try selected.customMetric("inspection", "Observed once", custom_calculation.CustomMetricCalculation.fromContext(Counts, &counts, Counts.calculate)); + defer custom.deinit(); + var rule = try custom.shouldSatisfy(custom_calculation.CustomMetricPredicate.fromContext(Counts, &counts, Counts.predicate)); + defer rule.deinit(std.testing.allocator); + var options = CheckOptions.init(std.testing.allocator, std.testing.io); + var quiet = try rule.check(options); + defer quiet.deinit(std.testing.allocator); + var output: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + options.logging = .{ .level = .debug, .writer = &output.writer }; + var logged = try rule.check(options); + defer logged.deinit(std.testing.allocator); + try std.testing.expect(quiet.passes() and logged.passes()); + try std.testing.expectEqual(@as(usize, 2), calculations); + try std.testing.expectEqual(@as(usize, 2), predicates); + try std.testing.expect(std.mem.indexOf(u8, output.written(), "[metric] name=inspection value=7 subject=src/root.zig") != null); +} diff --git a/test/readme.zig b/test/readme.zig index 6d697e1..144fb05 100644 --- a/test/readme.zig +++ b/test/readme.zig @@ -16,6 +16,7 @@ const source_blocks = [_]SourceBlock{ .{ .id = "metrics-example", .path = "../../../test/readme/metrics.zig" }, .{ .id = "graph-example", .path = "../../../test/readme/graph.zig" }, .{ .id = "testing-example", .path = "../../../test/readme/testing.zig" }, + .{ .id = "logging-example", .path = "../../../test/readme/logging.zig" }, }; test { @@ -26,6 +27,7 @@ test { _ = @import("readme/metrics.zig"); _ = @import("readme/graph.zig"); _ = testing_example; + _ = @import("readme/logging.zig"); } test "README examples execute from the consumer project" { @@ -53,7 +55,7 @@ test "every README fence is synchronized with exercised documentation" { } try std.testing.expectEqualStrings( - "zig fetch --save-exact=archunit https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.1.tar.gz", + "zig fetch --save-exact=archunit https://github.com/LukasNiessen/ArchUnitZig/archive/refs/tags/v0.0.2.tar.gz", try fencedBlock(allocator, readme, "install"), ); var failure = try testing_example.renderedFailure(); @@ -62,8 +64,8 @@ test "every README fence is synchronized with exercised documentation" { failure.message, try fencedBlock(allocator, readme, "failure-output"), ); - try std.testing.expectEqual(@as(usize, 20), countOccurrences(readme, "```")); - try std.testing.expectEqual(@as(usize, 10), countOccurrences(readme, "