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
55 changes: 54 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ go get github.com/LukasNiessen/ArchUnitGo
```

Go 1.26 or newer. The only direct dependency is `golang.org/x/tools`, which is how the extractor talks
to the Go toolchain. The latest release is v0.0.1; it is pre-1.0, so the API may still move.
to the Go toolchain. Releases are pre-1.0, so the API may still move.

The package is `archunit` while the last element of the module path is `ArchUnitGo`, so give the
import the name it has:
Expand Down Expand Up @@ -423,6 +423,59 @@ holds the file a CI job archives, and the four levels are `LogLevelDebug`, `LogL
default), `LogLevelWarn` and `LogLevelError`. A technical failure is still the error `Check` returns;
a log line is never how this library reports something.

### Detailed inspection

`LogLevelDebug` shows each extracted file and dependency, import kinds and external targets,
selected source/target files, layer and slice membership, progress counts, metric measurements,
violations, and the outcome. It observes the graph used by the check, including cached graphs,
without repeating custom calculations.

```go
violations, err := rule.Check(&archunit.CheckOptions{
Logging: &archunit.LogOptions{
Writer: os.Stderr,
Level: archunit.LogLevelDebug,
File: "build/archunit.log",
},
})
```

| Level | Included output |
| --- | --- |
| `LogLevelDebug` | Graph inspection, selections, progress, and everything below |
| `LogLevelInfo` | Check start/end, metric measurements, warnings and errors |
| `LogLevelWarn` | Violations and technical failures |
| `LogLevelError` | Technical failures |

Example debug lines:

```text
debug inspect: discovered file: "internal/api/handler.go"
debug inspect: selected file: "internal/api/handler.go"
debug progress: selected files: 1
```

`Writer` and `File` can be used together; omit `Writer` for file-only logging. Files append unless
`Overwrite` is true. `Timestamp` adds a caller-supplied timestamp to the filename. Archive the log
as a CI artifact. A requested log that cannot be opened, written, or closed still returns a
technical error. No destination means no output or file creation.

### Readable, colored failure reports

Numbered violations retain the source, requirement, and dependency or metric evidence. Enable
the existing semantic palette when displaying them in a terminal:

```go
report := archunit.NewResultFactory(&archunit.MessageOptions{
Palette: archunit.DefaultPalette(),
}).Result(violations)
fmt.Println(report.Message)
```

Failures are red, subjects cyan, requirements yellow, and successful results green. Omit the
palette for plain text in CI logs and artifacts. `MaxViolations` limits a long report and its
footer states how many violations were omitted. Formatting leaves returned violations unchanged.

## 🚫 Keeping One Import Out of the Graph

Some imports are not dependencies. The directive is written the way Go writes a machine-readable
Expand Down
14 changes: 10 additions & 4 deletions archunit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3322,8 +3322,7 @@ func TestARuleOfThisRepositoryLogsWhatItDidThroughThePublicSurface(t *testing.T)
if len(violations) != 2 {
t.Fatalf("%s reported %v, want the two empty populations", rule, violations)
}
// The five records of the fixed vocabulary, in the order a check writes them: the rule, the steps it took
// and how much of the project each came to, what it found, and what came of it.
// The lifecycle records retain their order and shape alongside graph inspection.
want := strings.Join([]string{
"info start check: " + rule.String(),
"debug progress: selected files: 0",
Expand All @@ -3333,8 +3332,15 @@ func TestARuleOfThisRepositoryLogsWhatItDidThroughThePublicSurface(t *testing.T)
"info end check: " + rule.String() + ": 2 violations",
"",
}, "\n")
if log.String() != want {
t.Errorf("the log holds\n%s\nwant\n%s", log.String(), want)
records := strings.Split(log.String(), "\n")
lifecycle := slices.DeleteFunc(records, func(record string) bool {
return strings.HasPrefix(record, "debug inspect:")
})
if actual := strings.Join(lifecycle, "\n"); actual != want {
t.Errorf("the lifecycle log holds\n%s\nwant\n%s", actual, want)
}
if !strings.Contains(log.String(), `debug inspect: discovered file: "common/logging/inspection.go"`) {
t.Error("debug logging must expose discovered files even when the selectors match nothing")
}
}

Expand Down
48 changes: 48 additions & 0 deletions common/logging/inspection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package logging

import (
"fmt"
"maps"
"slices"
"strconv"

"github.com/LukasNiessen/ArchUnitGo/common/extraction"
)

// LogGraph records every discovered file and dependency at debug level, including
// external targets and import kinds. It does not re-extract or change the graph.
func (l *Logger) LogGraph(graph extraction.Graph) {
if !l.enabled(LevelDebug) {
return
}
for _, edge := range graph {
if edge.IsSelfEdge() {
l.record(LevelDebug, "inspect", "discovered file: "+strconv.Quote(edge.Source))
continue
}
l.record(LevelDebug, "inspect", fmt.Sprintf("dependency: %q -> %q (external=%t, kinds=%s)",
edge.Source, edge.Target, edge.External, edge.ImportKinds))
}
}

// LogSelection records the members of one selection at debug level. It preserves
// the caller's order and quotes identifiers so control characters cannot add lines.
func (l *Logger) LogSelection(step string, identifiers []string) {
if !l.enabled(LevelDebug) {
return
}
for _, identifier := range identifiers {
l.record(LevelDebug, "inspect", step+": "+strconv.Quote(identifier))
}
}

// LogMembership records each layer or slice and its selected files at debug level.
// Labels are sorted without mutating the supplied membership map.
func (l *Logger) LogMembership(kind string, membership map[string][]string) {
if !l.enabled(LevelDebug) {
return
}
for _, label := range slices.Sorted(maps.Keys(membership)) {
l.LogSelection(kind+" "+strconv.Quote(label), membership[label])
}
}
48 changes: 48 additions & 0 deletions common/logging/inspection_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package logging_test

import (
"bytes"
"strings"
"testing"

"github.com/LukasNiessen/ArchUnitGo/common/extraction"
"github.com/LukasNiessen/ArchUnitGo/common/logging"
)

func TestInspectionIsDebugOnlyAndQuotesIdentifiers(t *testing.T) {
graph := extraction.NewGraph(
extraction.SelfEdge("api/handler.go"),
extraction.NewEdge("api/handler.go", "database/sql", true, extraction.ImportKindPlain),
)
for _, level := range []logging.Level{logging.LevelDebug, logging.LevelInfo, logging.LevelWarn, logging.LevelError} {
var output bytes.Buffer
log, err := logging.NewLogger(&logging.Options{Writer: &output, Level: level})
if err != nil {
t.Fatal(err)
}
log.LogGraph(graph)
log.LogSelection("selected file", []string{"name\nwith-newline.go"})
log.LogMembership("layer", map[string][]string{"z": {"z.go"}, "a": {"a.go"}})
if err := log.Close(); err != nil {
t.Fatal(err)
}
if level != logging.LevelDebug {
if output.Len() != 0 {
t.Fatalf("inspection escaped threshold %v: %s", level, &output)
}
continue
}
for _, want := range []string{`discovered file: "api/handler.go"`, `dependency: "api/handler.go" -> "database/sql"`, `external=true`, `name\nwith-newline.go`} {
if !strings.Contains(output.String(), want) {
t.Errorf("missing %q in %s", want, &output)
}
}
if strings.Index(output.String(), `layer "a"`) > strings.Index(output.String(), `layer "z"`) {
t.Fatal("membership labels must be ordered")
}
}
var disabled *logging.Logger
disabled.LogGraph(graph)
disabled.LogSelection("selected file", nil)
disabled.LogMembership("layer", nil)
}
6 changes: 3 additions & 3 deletions common/logging/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
//
// Two decisions shape the whole package. The destination is injected per check rather than owned by the
// library, so nothing is logged until a rule is handed a bag that says where to write; and the vocabulary
// is fixed at five records — start check, end check, log progress, log violation, log metric — so that a
// log has the same five shapes of line whatever family of rule wrote it, and a reader who has learned one
// has learned all of them. Level says which of them are written.
// uses five lifecycle records — start check, end check, log progress, log violation, log metric — plus
// debug inspection of graphs and selections. Every family uses the same aligned format, and Level says
// which records are written.
//
// Nothing here is a channel for reporting a failure. A technical failure is the error Check returns and a
// broken rule is a violation in the list it returns; both are logged as well, because a log of a run is
Expand Down
7 changes: 4 additions & 3 deletions files/fluentapi/adhere_to.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,13 @@ func (b FilesShouldNotBuilder) AdhereTo(predicate filesassertion.FilePredicate,
// violations say nothing.
func (c FilesAdherenceCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) {
return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) {
// The graph is deliberately dropped: this rule judges each selected file on its own contents, so the
// dependencies between them say nothing about it.
_, selected, err := c.rule.scope.resolve(options)
// Dependencies are available for debug inspection; the assertion still judges only file contents.
graph, selected, err := c.rule.scope.resolve(options)
if err != nil {
return nil, err
}
log.LogGraph(graph)
log.LogSelection("selected file", selected)
log.LogProgress("selected files", len(selected))

if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 {
Expand Down
3 changes: 3 additions & 0 deletions files/fluentapi/depend_on_external_modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ func (c FilesExternalDependencyCondition) Check(options *kernel.CheckOptions) ([
if err != nil {
return nil, err
}
log.LogGraph(graph)
log.LogSelection("selected file", selected)
log.LogProgress("selected files", len(selected))

if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 {
Expand All @@ -155,6 +157,7 @@ func (c FilesExternalDependencyCondition) Check(options *kernel.CheckOptions) ([
}

modules := projection.SelectExternalModules(graph, c.modules...)
log.LogSelection("external module", modules)
log.LogProgress("external modules matched", len(modules))
dependencies := kernelprojection.ProjectEdges(graph, projection.PerExternalDependencyEdge(selected, modules))
log.LogProgress("dependencies from the selected files to those modules", len(dependencies))
Expand Down
3 changes: 3 additions & 0 deletions files/fluentapi/depend_on_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ func (c FilesDependencyCondition) Check(options *kernel.CheckOptions) ([]asserti
return nil, err
}
objects := projection.SelectFiles(graph, c.objects...)
log.LogGraph(graph)
log.LogSelection("selected file", selected)
log.LogProgress("selected files", len(selected))
log.LogSelection("target file", objects)
log.LogProgress("files to depend on", len(objects))

if empty := options.GatherEmptyTestViolations(c.populations(len(selected), len(objects))...); len(empty) > 0 {
Expand Down
2 changes: 2 additions & 0 deletions files/fluentapi/have_no_cycles.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ func (c FilesCyclesCondition) Check(options *kernel.CheckOptions) ([]assertion.V
if err != nil {
return nil, err
}
log.LogGraph(graph)
log.LogSelection("selected file", selected)
log.LogProgress("selected files", len(selected))

if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 {
Expand Down
29 changes: 29 additions & 0 deletions files/fluentapi/logged_progress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package fluentapi_test

import (
"bytes"
"reflect"
"slices"
"strings"
"testing"
Expand Down Expand Up @@ -126,3 +127,31 @@ func loggedRecords(t *testing.T, rule kernel.Checkable, prefix string) []string
}
return records
}

func TestDebugInspectionExplainsSelectionWithoutChangingResults(t *testing.T) {
fixture := fixtureLocator(t, writeFixtureProject(t))
rule := fluentapi.ProjectFiles(fixture).InFolder("internal/api/**").Should().HaveName("*_missing.go")
baseline, err := rule.Check(nil)
if err != nil {
t.Fatal(err)
}
for _, level := range []logging.Level{logging.LevelDebug, logging.LevelInfo} {
var output bytes.Buffer
actual, err := rule.Check(&kernel.CheckOptions{Logging: &logging.Options{Writer: &output, Level: level}})
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(actual, baseline) {
t.Fatalf("logging changed violations: %v", actual)
}
if level == logging.LevelDebug {
for _, want := range []string{"inspect: discovered file:", "inspect: dependency:", "inspect: selected file:"} {
if !strings.Contains(output.String(), want) {
t.Errorf("missing %q in %s", want, &output)
}
}
} else if strings.Contains(output.String(), "inspect:") {
t.Fatal("info must omit inspection")
}
}
}
6 changes: 3 additions & 3 deletions files/fluentapi/naming_condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ type FilesNamingCondition struct {
// opened, written or closed — and never a failing rule. When it is non-nil the violations say nothing.
func (c FilesNamingCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) {
return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) {
// The graph is deliberately dropped: what a file is called and where it lives is on the file, so this
// rule is about the selection and not about the dependencies between the files in it.
_, selected, err := c.rule.scope.resolve(options)
graph, selected, err := c.rule.scope.resolve(options)
if err != nil {
return nil, err
}
log.LogGraph(graph)
log.LogSelection("selected file", selected)
log.LogProgress("selected files", len(selected))

if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 {
Expand Down
2 changes: 2 additions & 0 deletions layers/fluentapi/policy_condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ func (c LayersPolicyCondition) Check(options *kernel.CheckOptions) ([]assertion.
if err != nil {
return nil, err
}
log.LogGraph(graph)
log.LogMembership("layer", membership)
log.LogProgress("declared layers", len(c.policy.declaredLayers()))
log.LogProgress("clauses", len(c.policy.clauses))

Expand Down
11 changes: 10 additions & 1 deletion metrics/fluentapi/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import (
"github.com/LukasNiessen/ArchUnitGo/common/archerror"
"github.com/LukasNiessen/ArchUnitGo/common/extraction"
kernel "github.com/LukasNiessen/ArchUnitGo/common/fluentapi"
"github.com/LukasNiessen/ArchUnitGo/common/logging"
"github.com/LukasNiessen/ArchUnitGo/common/matching"
metricsextraction "github.com/LukasNiessen/ArchUnitGo/metrics/extraction"
"github.com/LukasNiessen/ArchUnitGo/metrics/projection"
Expand Down Expand Up @@ -188,18 +189,26 @@ func (b MetricsBuilder) String() string {
// A pattern a scope verb rejected is returned before the project is read, and the error is otherwise a
// project that cannot be located, extracted or read. It is never a rule failure.
func (b MetricsBuilder) resolve(options *kernel.CheckOptions) (projection.Subjects, error) {
return b.resolveLogged(options, nil)
}

// resolveLogged shares the existing extraction and observes it only when debug is enabled.
func (b MetricsBuilder) resolveLogged(options *kernel.CheckOptions, log *logging.Logger) (projection.Subjects, error) {
if b.err != nil {
return projection.Subjects{}, b.err
}
graph, err := options.ExtractGraph(b.locator)
if err != nil {
return projection.Subjects{}, err
}
log.LogGraph(graph)
selected := projection.SelectFiles(graph, b.fileSelectors()...)
log.LogSelection("metric file", selected)
root, err := extraction.LocateProject(b.locator)
if err != nil {
return projection.Subjects{}, err
}
files, err := metricsextraction.ExtractFileInfo(root, projection.SelectFiles(graph, b.fileSelectors()...))
files, err := metricsextraction.ExtractFileInfo(root, selected)
if err != nil {
return projection.Subjects{}, err
}
Expand Down
2 changes: 1 addition & 1 deletion metrics/fluentapi/should_be.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func (b MetricBuilder) ShouldBeAboveOrEqual(limit float64) MetricsThresholdCondi
// opened, written or closed — and never a failing rule. When it is non-nil the violations say nothing.
func (c MetricsThresholdCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) {
return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) {
subjects, err := c.rule.scope.resolve(options)
subjects, err := c.rule.scope.resolveLogged(options, log)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion metrics/fluentapi/should_satisfy.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (b MetricBuilder) ShouldSatisfy(predicate metricsassertion.Satisfaction, re
// nothing.
func (c MetricsSatisfactionCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) {
return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) {
subjects, err := c.rule.scope.resolve(options)
subjects, err := c.rule.scope.resolveLogged(options, log)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion metrics/fluentapi/zone_checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (b MetricsDistanceBuilder) ShouldNotBeInZoneOfUselessness() MetricsZoneCond
// closed — and never a failing rule. When it is non-nil the violations say nothing.
func (c MetricsZoneCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) {
return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) {
subjects, err := c.scope.resolve(options)
subjects, err := c.scope.resolveLogged(options, log)
if err != nil {
return nil, err
}
Expand Down
2 changes: 2 additions & 0 deletions slices/fluentapi/adhere_to_diagram.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ func (c SlicesDiagramCondition) Check(options *kernel.CheckOptions) ([]assertion
if err != nil {
return nil, err
}
log.LogGraph(graph)
log.LogMembership("slice", membership)
log.LogProgress("slices the slicing found", len(membership))

diagram, err := c.drawing()
Expand Down
Loading
Loading