Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
62 changes: 57 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

<!-- readme-test:install -->
```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
Expand Down Expand Up @@ -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. |
Expand All @@ -380,6 +380,58 @@ 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.

<!-- readme-test:logging-example -->
```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 generic writer has no terminal identity: the host supplies terminal and environment
policy and should leave `writer_color` false for CI, files, redirected output, or `NO_COLOR`. 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
Expand Down
2 changes: 1 addition & 1 deletion build.zig.zon
Original file line number Diff line number Diff line change
@@ -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 = .{
Expand Down
11 changes: 11 additions & 0 deletions release/v0.0.2.json
Original file line number Diff line number Diff line change
@@ -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-7Czg3E-AGQDSUqSoO1TEnmtB9PqF0BmUrlW825VVuAHz",
"release_notes": "release/v0.0.2.md"
}
75 changes: 75 additions & 0 deletions release/v0.0.2.md
Original file line number Diff line number Diff line change
@@ -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-7Czg3E-AGQDSUqSoO1TEnmtB9PqF0BmUrlW825VVuAHz
```

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-7Czg3E-AGQDSUqSoO1TEnmtB9PqF0BmUrlW825VVuAHz",
},
},
```

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.
2 changes: 1 addition & 1 deletion scripts/build_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def render_page(root: Path, config: dict, page: dict, next_page: dict | None) ->
</ul>
</nav>
<main class="content" id="main-content">
<p class="eyebrow">Zig 0.16 · v0.0.1 preview</p>
<p class="eyebrow">Zig 0.16 · v0.0.2 preview</p>
{fragment}
{next_link}
</main>
Expand Down
8 changes: 4 additions & 4 deletions scripts/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand Down Expand Up @@ -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 (
Expand All @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions scripts/test_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -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-7Czg3E-AGQDSUqSoO1TEnmtB9PqF0BmUrlW825VVuAHz",
metadata.package_hash,
)

Expand Down
7 changes: 6 additions & 1 deletion src/common/extraction/project_graph.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -160,13 +163,15 @@ 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;
}

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(
Expand Down
67 changes: 66 additions & 1 deletion src/common/logging/check_logger.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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())});
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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"));
}
}
2 changes: 2 additions & 0 deletions src/common/logging/types.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading