Architecture Linting Golang CI: Enforce Clean Architecture Otomatis
Implement architecture linting untuk Go di CI/CD. Custom rules untuk Clean Architecture, depguard configuration, import graph analysis, dan AI-powered architecture review.
Architecture Linting: Enforce Clean Architecture via Pipeline
Architecture linting golang CI adalah satu-satunya cara sustainable untuk menjaga Clean Architecture tetap bersih dalam jangka panjang. Clean Architecture adalah pola yang powerful tapi mudah ter-erode seiring waktu. Developer yang terburu-buru mengambil shortcut. Reviewer yang lelah miss import yang salah. Dalam 6 bulan, arsitektur yang rapi bisa menjadi big ball of mud.
Solusinya adalah menegakkan aturan arsitektur di CI: setiap PR di-check terhadap architecture rules, dan violations di-block sebelum masuk ke codebase. Di artikel ini kita bangun enforcement berlapis, dari depguard sampai AI review.
08.1 Masalah Nyata: Architecture Drift
Sebelum bicara solusi, mari lihat bagaimana arsitektur “membusuk” secara diam-diam. Kronologi berikut menggambarkan bagaimana satu shortcut kecil menumpuk menjadi utang teknis berbulan-bulan.
1Sprint 1: Tim implement Clean Architecture dengan baik
2 handler → usecase (interface) → repository (interface) → domain
3
4Sprint 4: Developer baru join, tidak familiar dengan architecture
5 shortcut: handler langsung panggil repository implementation
6 reviewer: miss karena code review fokus ke logic
7
8Sprint 8: CI/CD analyst melihat import graph
9 handler → usecase → repository ✅
10 handler → repository (direct!) ❌
11 usecase → pgx driver (direct!) ❌
12 domain → echo framework ❌
13
14 Refactoring sekarang butuh 2 sprint karena perlu untangle dependencies
15
16Dengan architecture linting sejak Sprint 1:
17 Sprint 1: violations di-catch → developer fix sebelum merge
18 Sprint 8: import graph masih clean, tidak ada refactoring burden
19
20 Cost pencegahan: 5 menit fix per PR
21 Cost remediation: 2 sprint = ~2 minggu × 5 developer = 400 jamPerbandingan angkanya tajam: 5 menit pencegahan per PR versus 400 jam remediasi. Enforcement otomatis sejak awal jauh lebih murah daripada membersihkan kekacauan di kemudian hari.
08.2 Tiga Layer Architecture Enforcement
Enforcement yang komprehensif tidak bergantung pada satu alat saja, melainkan tiga lapis dengan trade-off berbeda. Ringkasan berikut memetakan tiap layer, cakupannya, dan biayanya.
1LAYER 1: golangci-lint dengan depguard (paling mudah setup)
2 → Catch import yang explicitly forbidden
3 → Rule-based, konfigurasi di .golangci.yml
4 → Zero AI cost
5
6LAYER 2: Custom Go script (lebih flexible)
7 → Catch cross-layer imports dengan path matching
8 → Bisa detect subtler violations
9 → Zero AI cost
10
11LAYER 3: AI Architecture Review (paling sophisticated)
12 → Catch violations yang butuh semantic understanding
13 → "Handler ini properly delegates ke usecase, atau bypass?"
14 → Low AI costKetiganya saling melengkapi: Layer 1 dan 2 gratis dan deterministik untuk pelanggaran eksplisit, sementara Layer 3 menangani kasus yang butuh pemahaman konteks. Kita bahas satu per satu.
08.3 Layer 1: depguard Configuration
Layer termudah adalah depguard, yang cukup dikonfigurasi di YAML tanpa menulis kode. Konfigurasi berikut mendefinisikan import terlarang per layer — handler, usecase, dan domain.
1# .golangci.yml — tambahkan depguard rules
2
3linters-settings:
4 depguard:
5 rules:
6 # Rule: handler layer tidak boleh import repository impl
7 handler-no-repo:
8 files:
9 - "!**/delivery/http/handler/**" # hanya untuk handler files
10 - "!**/*_test.go"
11 deny:
12 - pkg: "github.com/santekno/santekno-shop/internal/repository"
13 desc: "Handler must use usecase interfaces, not repository directly"
14 - pkg: "github.com/jackc/pgx"
15 desc: "Handler must not import database drivers"
16 - pkg: "github.com/redis/go-redis"
17 desc: "Handler must not import cache drivers"
18
19 # Rule: usecase layer tidak boleh import framework
20 usecase-no-framework:
21 files:
22 - "!**/internal/usecase/**"
23 - "!**/*_test.go"
24 deny:
25 - pkg: "github.com/labstack/echo"
26 desc: "Usecase must not import HTTP framework"
27 - pkg: "github.com/jackc/pgx"
28 desc: "Usecase must use repository interfaces, not DB directly"
29 - pkg: "github.com/redis/go-redis"
30 desc: "Usecase must not import cache directly"
31
32 # Rule: domain layer — zero external imports
33 domain-pure:
34 files:
35 - "!**/internal/domain/**"
36 - "!**/*_test.go"
37 deny:
38 - pkg: "github.com/labstack/echo"
39 desc: "Domain must have zero framework dependencies"
40 - pkg: "github.com/jackc/pgx"
41 desc: "Domain must have zero infrastructure dependencies"
42 - pkg: "github.com/redis/go-redis"
43 desc: "Domain must have zero infrastructure dependencies"
44 - pkg: "github.com/confluentinc/confluent-kafka-go"
45 desc: "Domain must have zero infrastructure dependencies"
46
47 # Rule: test files boleh import apa saja
48 test-files:
49 files:
50 - "**/*_test.go"
51 allow:
52 - $all # allow everything in test filesKeunggulan depguard adalah maintainability: aturan tinggal ditambah di YAML, dan setiap deny menyertakan desc yang menjelaskan ke developer kenapa import itu dilarang.
08.4 Layer 2: Custom Architecture Check Script
depguard tidak bisa mengungkapkan semua aturan. Untuk pola yang lebih kompleks, kita tulis script Go yang men-traverse file tree, mem-parse import, dan mencocokkannya dengan aturan per layer.
1// scripts/check-architecture.go
2// Comprehensive architecture boundary enforcement
3// Run: go run scripts/check-architecture.go ./...
4
5//go:build ignore
6
7package main
8
9import (
10 "fmt"
11 "go/parser"
12 "go/token"
13 "os"
14 "path/filepath"
15 "strings"
16)
17
18// LayerRule mendefinisikan apa yang boleh/tidak boleh di-import per layer
19type LayerRule struct {
20 Name string
21 PathPattern string // pattern untuk identify file ke layer ini
22 ForbiddenImports []ForbiddenImport
23}
24
25type ForbiddenImport struct {
26 Pattern string // import path yang dilarang
27 Description string // kenapa dilarang
28 Severity string // CRITICAL | WARNING
29}
30
31var architectureRules = []LayerRule{
32 {
33 Name: "handler",
34 PathPattern: "delivery/http/handler",
35 ForbiddenImports: []ForbiddenImport{
36 {
37 Pattern: "internal/repository",
38 Description: "Handler must depend on usecase interfaces, not repository",
39 Severity: "CRITICAL",
40 },
41 {
42 Pattern: "github.com/jackc/pgx",
43 Description: "Handler must not touch database directly",
44 Severity: "CRITICAL",
45 },
46 {
47 Pattern: "github.com/redis/go-redis",
48 Description: "Handler must not touch cache directly",
49 Severity: "CRITICAL",
50 },
51 },
52 },
53 {
54 Name: "usecase",
55 PathPattern: "internal/usecase",
56 ForbiddenImports: []ForbiddenImport{
57 {
58 Pattern: "delivery/",
59 Description: "Usecase must not import from delivery layer (circular dep risk)",
60 Severity: "CRITICAL",
61 },
62 {
63 Pattern: "github.com/jackc/pgx",
64 Description: "Usecase must use repository interface, not DB driver",
65 Severity: "CRITICAL",
66 },
67 {
68 Pattern: "github.com/labstack/echo",
69 Description: "Usecase must not depend on HTTP framework",
70 Severity: "CRITICAL",
71 },
72 },
73 },
74 {
75 Name: "domain",
76 PathPattern: "internal/domain",
77 ForbiddenImports: []ForbiddenImport{
78 {
79 Pattern: "github.com/", // any github package
80 Description: "Domain must have zero external dependencies (stdlib only)",
81 Severity: "CRITICAL",
82 // Exception: github.com/google/uuid is allowed
83 },
84 },
85 },
86}
87
88// Domain UUID exception
89var domainAllowedExceptions = []string{
90 "github.com/google/uuid",
91 "github.com/santekno/santekno-shop/shared/", // shared domain packages
92}
93
94type Violation struct {
95 File string
96 Layer string
97 Import string
98 Description string
99 Severity string
100}
101
102func main() {
103 var violations []Violation
104 fset := token.NewFileSet()
105
106 err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
107 if err != nil || info.IsDir() {
108 return err
109 }
110 if !strings.HasSuffix(path, ".go") {
111 return nil
112 }
113 if strings.HasSuffix(path, "_test.go") {
114 return nil // skip test files
115 }
116 // Skip generated files
117 if strings.Contains(path, "mock_") || strings.Contains(path, ".pb.go") {
118 return nil
119 }
120
121 // Determine which layer this file belongs to
122 var matchedRule *LayerRule
123 for i := range architectureRules {
124 if strings.Contains(path, architectureRules[i].PathPattern) {
125 matchedRule = &architectureRules[i]
126 break
127 }
128 }
129 if matchedRule == nil {
130 return nil
131 }
132
133 // Parse imports
134 f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
135 if err != nil {
136 return nil
137 }
138
139 for _, imp := range f.Imports {
140 importPath := strings.Trim(imp.Path.Value, `"`)
141
142 for _, forbidden := range matchedRule.ForbiddenImports {
143 if !strings.Contains(importPath, forbidden.Pattern) {
144 continue
145 }
146
147 // Check exception list
148 isException := false
149 for _, exc := range domainAllowedExceptions {
150 if strings.HasPrefix(importPath, exc) {
151 isException = true
152 break
153 }
154 }
155 if isException {
156 continue
157 }
158
159 violations = append(violations, Violation{
160 File: path,
161 Layer: matchedRule.Name,
162 Import: importPath,
163 Description: forbidden.Description,
164 Severity: forbidden.Severity,
165 })
166 }
167 }
168 return nil
169 })
170
171 if err != nil {
172 fmt.Fprintf(os.Stderr, "walk error: %v\n", err)
173 os.Exit(2)
174 }
175
176 if len(violations) == 0 {
177 fmt.Println("✅ Architecture check PASSED — all layer boundaries respected")
178 os.Exit(0)
179 }
180
181 // Print violations
182 criticalCount := 0
183 warningCount := 0
184
185 fmt.Printf("❌ Architecture violations found: %d\n\n", len(violations))
186 for _, v := range violations {
187 marker := "❌"
188 if v.Severity == "WARNING" {
189 marker = "⚠️ "
190 }
191 fmt.Printf("%s [%s] %s\n", marker, v.Layer, v.File)
192 fmt.Printf(" Imports: %s\n", v.Import)
193 fmt.Printf(" Reason: %s\n\n", v.Description)
194
195 if v.Severity == "CRITICAL" {
196 criticalCount++
197 } else {
198 warningCount++
199 }
200 }
201
202 fmt.Printf("CRITICAL: %d | WARNING: %d\n", criticalCount, warningCount)
203
204 if criticalCount > 0 {
205 os.Exit(1) // block pipeline
206 }
207
208 os.Exit(0) // warnings only, tidak block
209}Script ini memberi kontrol penuh: severity per aturan, exception list untuk uuid, dan exit code 1 hanya jika ada violation CRITICAL. Fleksibilitas ini yang tidak bisa dicapai depguard sendirian.
08.5 Layer 3: AI Architecture Review
Sebagian violation butuh pemahaman semantik, bukan sekadar path matching. Script berikut memberi AI deskripsi arsitektur lengkap plus diff, lalu meminta penilaian apakah ada pelanggaran yang tersembunyi.
1#!/bin/bash
2# scripts/ai-architecture-review.sh
3# AI review untuk violations yang butuh semantic understanding
4
5set -euo pipefail
6
7DIFF_FILE="${1}"
8
9# Load architecture description
10ARCH_DESC=$(cat << 'ARCH'
11Clean Architecture for Santekno Shop:
12
13LAYERS (outer to inner):
141. delivery/http/handler/ — HTTP request/response only
15 - Parse request, call usecase, format response
16 - MUST depend on usecase interfaces only
17 - MUST NOT access DB, cache, or messaging directly
18
192. internal/usecase/ — Business logic
20 - Orchestrate business rules
21 - MUST depend on repository interfaces only
22 - MUST NOT import HTTP framework or DB drivers
23
243. internal/repository/ — Data access
25 - Implement repository interfaces from domain
26 - CAN import database drivers (pgx, redis)
27 - MUST NOT import usecase or handler
28
294. internal/domain/ — Pure domain
30 - Entities, value objects, errors, interfaces
31 - MUST NOT import anything external except stdlib
32 - Exception: github.com/google/uuid
33
34RED FLAGS to detect:
35- Handler calling repository directly (bypassing usecase)
36- Usecase importing pgx, echo, or redis packages
37- Domain importing any github.com/* except uuid
38- Any circular dependency pattern
39ARCH
40)
41
42DIFF=$(cat "$DIFF_FILE" | head -400)
43
44PROMPT="You are an architecture reviewer for a Go Clean Architecture project.
45
46ARCHITECTURE:
47$ARCH_DESC
48
49CODE DIFF:
50$DIFF
51
52Review for architecture violations. Be specific about:
531. Does any handler directly access repository without going through usecase?
542. Does any usecase import infrastructure packages (pgx, echo, redis)?
553. Does any domain type import external frameworks?
564. Are there any circular dependency patterns?
57
58Output:
59VIOLATION: [yes/no]
60Details (if violation):
61 CRITICAL: [description] at [file:line]
62 Fix: [specific change needed]
63
64ARCHITECTURE_SCORE: [0-100]
65(100=perfect, 80=minor issues, 60=violations, <60=serious problems)"
66
67RESULT=$(./scripts/claude-call.sh "$PROMPT" 600)
68echo "$RESULT"
69
70if echo "$RESULT" | grep -q "^ CRITICAL:"; then
71 echo ""
72 echo "::error::Architecture violations detected"
73 exit 1
74fi
75
76SCORE=$(echo "$RESULT" | grep "ARCHITECTURE_SCORE:" | grep -oP '\d+' || echo "85")
77if [ "$SCORE" -lt 70 ]; then
78 echo "::warning::Architecture score $SCORE — review architecture concerns"
79fiKekuatan Layer 3 adalah menangkap kasus seperti handler yang secara teknis hanya import interface usecase, tapi usecase itu sendiri diam-diam import pgx — pelanggaran yang lolos dari path matching sederhana.
08.6 Workflow: Architecture Linting di CI
Ketiga layer digabung dalam satu workflow yang berjalan berurutan. Konfigurasi berikut menjalankan depguard, custom script, lalu AI review yang hanya dieksekusi jika dua layer sebelumnya lulus.
1# .github/workflows/architecture.yml
2
3name: Architecture Linting
4
5on:
6 pull_request:
7 paths:
8 - '**.go'
9 - 'go.mod'
10 - 'go.sum'
11
12jobs:
13 layer1-depguard:
14 name: "L1: depguard Import Rules"
15 runs-on: ubuntu-latest
16 steps:
17 - uses: actions/checkout@v4
18 - uses: actions/setup-go@v5
19 with: { go-version: '1.22', cache: true }
20 - uses: golangci/golangci-lint-action@v6
21 with:
22 args: --enable depguard --disable-all
23 # Only run depguard, not full lint suite
24
25 layer2-custom-script:
26 name: "L2: Custom Architecture Check"
27 runs-on: ubuntu-latest
28 steps:
29 - uses: actions/checkout@v4
30 - uses: actions/setup-go@v5
31 with: { go-version: '1.22' }
32 - name: Run architecture check
33 run: |
34 go run scripts/check-architecture.go ./...
35
36 layer3-ai-review:
37 name: "L3: AI Architecture Review"
38 runs-on: ubuntu-latest
39 needs: [layer1-depguard, layer2-custom-script]
40 # Hanya jalan jika L1 dan L2 pass (tidak buang token AI untuk broken arch)
41 if: success()
42 permissions:
43 pull-requests: write
44 contents: read
45 env:
46 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
47 steps:
48 - uses: actions/checkout@v4
49 with: { fetch-depth: 0 }
50
51 - name: Get diff
52 run: |
53 git diff origin/${{ github.base_ref }}...HEAD -- '*.go' \
54 | head -400 > /tmp/arch-diff.txt
55
56 - name: AI Architecture Review
57 id: arch_review
58 continue-on-error: true
59 run: |
60 chmod +x scripts/ai-architecture-review.sh
61 RESULT=$(./scripts/ai-architecture-review.sh /tmp/arch-diff.txt 2>&1) || true
62
63 echo "result<<EOF" >> $GITHUB_OUTPUT
64 echo "$RESULT" >> $GITHUB_OUTPUT
65 echo "EOF" >> $GITHUB_OUTPUT
66
67 SCORE=$(echo "$RESULT" | grep "ARCHITECTURE_SCORE:" | grep -oP '\d+' || echo "85")
68 echo "score=$SCORE" >> $GITHUB_OUTPUT
69
70 - name: Post architecture review
71 if: steps.arch_review.outputs.result != ''
72 uses: actions/github-script@v7
73 with:
74 script: |
75 const result = `${{ steps.arch_review.outputs.result }}`;
76 const score = parseInt('${{ steps.arch_review.outputs.score }}') || 85;
77 const emoji = score >= 80 ? '🟢' : score >= 60 ? '🟡' : '🔴';
78
79 const body = [
80 `## 🏗️ Architecture Review`,
81 `**Score:** ${emoji} ${score}/100`,
82 ``,
83 result,
84 `---`,
85 `*Layer boundaries: handler → usecase → repository → domain*`
86 ].join('\n');
87
88 // Find or update existing arch comment
89 const { data: comments } = await github.rest.issues.listComments({
90 owner: context.repo.owner,
91 repo: context.repo.repo,
92 issue_number: context.issue.number
93 });
94
95 const existing = comments.find(c => c.body.includes('🏗️ Architecture Review'));
96
97 if (existing) {
98 await github.rest.issues.updateComment({
99 owner: context.repo.owner,
100 repo: context.repo.repo,
101 comment_id: existing.id,
102 body
103 });
104 } else {
105 await github.rest.issues.createComment({
106 owner: context.repo.owner,
107 repo: context.repo.repo,
108 issue_number: context.issue.number,
109 body
110 });
111 }Perhatikan needs: [layer1-depguard, layer2-custom-script] dan if: success() pada Layer 3 — token AI tidak dibuang untuk mereview kode yang sudah jelas melanggar aturan deterministik.
08.7 Import Graph Visualization
Kadang lebih mudah melihat masalah lewat graf ketimbang daftar. Script berikut memakai goda untuk menghasilkan import graph dan mengecek apakah repository di-import oleh layer yang tidak semestinya.
1#!/bin/bash
2# scripts/generate-import-graph.sh
3# Generate import graph untuk visualisasi architecture
4
5go install golang.org/x/tools/cmd/callgraph@latest
6go install github.com/loov/goda@latest
7
8# Generate import graph untuk internal packages
9goda graph "github.com/santekno/santekno-shop/internal/..." | \
10 grep -v "_test" > /tmp/import-graph.dot
11
12# Convert ke readable format
13echo "Package dependencies:"
14goda list "github.com/santekno/santekno-shop/internal/..." 2>/dev/null | \
15 grep -v "_test" | \
16 sort
17
18# Check untuk cross-layer imports yang tidak boleh ada
19echo ""
20echo "Checking for forbidden cross-layer dependencies..."
21goda list -f "{{.ImportedBy}}" "github.com/santekno/santekno-shop/internal/repository/..." | \
22 grep -E "(delivery|usecase)" && \
23 echo "⚠️ Repository imported by non-allowed layer" || \
24 echo "✅ Repository layer isolation: OK"Pemeriksaan ImportedBy pada repository adalah cara cepat mendeteksi kebocoran arsitektur: jika delivery atau usecase muncul di daftar, ada layer yang melanggar batas.
08.8 Architecture Rules sebagai Tests
Pendekatan paling elegan adalah meng-encode aturan arsitektur sebagai Go test biasa — tidak perlu CI step khusus. Test berikut memverifikasi bahwa handler tidak import package terlarang dan domain hanya import stdlib plus uuid.
1// internal/architecture_test.go
2// Architecture rules di-encode sebagai Go tests
3
4package architecture_test
5
6import (
7 "go/build"
8 "testing"
9
10 "github.com/stretchr/testify/assert"
11 "golang.org/x/tools/go/packages"
12)
13
14// TestHandlerLayerDependencies verifikasi handler hanya import yang boleh
15func TestHandlerLayerDependencies(t *testing.T) {
16 pkgs, err := packages.Load(&packages.Config{
17 Mode: packages.NeedImports,
18 Dir: "../",
19 }, "github.com/santekno/santekno-shop/delivery/http/handler/...")
20
21 if err != nil {
22 t.Skip("Cannot load packages:", err)
23 }
24
25 forbiddenInHandler := []string{
26 "github.com/jackc/pgx",
27 "github.com/redis/go-redis",
28 "github.com/santekno/santekno-shop/internal/repository",
29 }
30
31 for _, pkg := range pkgs {
32 for importPath := range pkg.Imports {
33 for _, forbidden := range forbiddenInHandler {
34 assert.NotContains(t, importPath, forbidden,
35 "Handler %s imports forbidden package %s",
36 pkg.PkgPath, importPath)
37 }
38 }
39 }
40}
41
42// TestDomainLayerPurity verifikasi domain hanya import stdlib
43func TestDomainLayerPurity(t *testing.T) {
44 pkgs, err := packages.Load(&packages.Config{
45 Mode: packages.NeedImports,
46 }, "github.com/santekno/santekno-shop/internal/domain/...")
47
48 if err != nil {
49 t.Skip("Cannot load packages:", err)
50 }
51
52 allowedExternalInDomain := []string{
53 "github.com/google/uuid", // only exception
54 }
55
56 for _, pkg := range pkgs {
57 for importPath := range pkg.Imports {
58 if !isStdlibOrAllowed(importPath, allowedExternalInDomain) {
59 t.Errorf("Domain package %s imports external package %s",
60 pkg.PkgPath, importPath)
61 }
62 }
63 }
64}
65
66func isStdlibOrAllowed(importPath string, allowed []string) bool {
67 // Check stdlib
68 if !strings.Contains(importPath, ".") {
69 return true
70 }
71 // Check allowed list
72 for _, a := range allowed {
73 if strings.HasPrefix(importPath, a) {
74 return true
75 }
76 }
77 return false
78}Keindahan pendekatan ini: aturan arsitektur ikut dijalankan setiap kali go test, sehingga pelanggaran gagal seketika tanpa perlu tooling tambahan atau job CI terpisah.
08.9 Handling Architecture Exceptions
Tidak semua “pelanggaran” itu buruk — ada exception yang sah dan perlu di-document. Contoh berikut menunjukkan cara mendokumentasikan pengecualian dengan komentar nolint sekaligus allowlist di depguard.
1// Terkadang ada legitimate exceptions yang perlu di-document
2
3// Contoh: repository layer perlu return domain.ErrNotFound
4// yang seharusnya hanya diketahui oleh domain
5// Tapi ini acceptable karena repository implement domain interface
6
7// Cara document exception:
8// 1. Tambahkan comment yang explain kenapa
9// 2. Tambahkan ke golangci-lint nolint atau allowlist
10
11// Dalam code:
12// repository/postgres/order_repository.go
13// nolint:depguard -- using domain.ErrOrderNotFound is intentional:
14// repository implements domain.OrderRepository interface
15import "github.com/santekno/santekno-shop/internal/domain"Kunci exception yang sehat adalah setiap nolint selalu disertai alasan. “Technical debt yang disadari” jauh lebih baik daripada “technical debt yang tidak terdeteksi”. Sisi konfigurasinya di-set di depguard seperti berikut.
1# Dalam .golangci.yml:
2linters-settings:
3 depguard:
4 rules:
5 repo-domain-exception:
6 files:
7 - "internal/repository/**"
8 allow:
9 - "github.com/santekno/santekno-shop/internal/domain" # implementing domain interfacesDengan allowlist eksplisit ini, repository boleh import domain karena memang meng-implement interface-nya — pengecualian yang terdokumentasi, bukan celah yang lolos diam-diam.
08.10 Architecture Documentation via AI
Dokumentasi arsitektur yang ditulis manual cepat basi. Script berikut men-generate dokumentasi langsung dari import graph aktual, sehingga selalu sinkron dengan kode.
1#!/bin/bash
2# scripts/generate-arch-doc.sh
3# AI generate architecture documentation dari actual code
4
5set -euo pipefail
6
7# Collect import relationships
8IMPORT_ANALYSIS=$(go list -f '{{.ImportPath}} imports: {{range .Imports}}{{.}} {{end}}' \
9 ./internal/... 2>/dev/null | grep "santekno" | head -50)
10
11LAYER_COUNT=$(find internal -mindepth 1 -maxdepth 1 -type d | wc -l)
12
13PROMPT="Generate architecture documentation for this Go project.
14
15Import relationships (internal packages only):
16$IMPORT_ANALYSIS
17
18Write:
191. Architecture overview (2-3 paragraphs)
202. Layer descriptions with responsibilities
213. Dependency rules (what can depend on what)
224. Known violations or concerns (if any from the import analysis)
23
24Format as Markdown. Technical but readable for new developers."
25
26RESULT=$(./scripts/claude-call.sh "$PROMPT" 1000)
27
28# Save ke docs
29mkdir -p docs
30echo "# Architecture Documentation" > docs/architecture.md
31echo "*Auto-generated from codebase — $(date -u +%Y-%m-%d)*" >> docs/architecture.md
32echo "" >> docs/architecture.md
33echo "$RESULT" >> docs/architecture.md
34
35echo "Architecture documentation generated: docs/architecture.md"Karena input-nya adalah import graph nyata, dokumentasi yang dihasilkan mencerminkan kondisi kode saat ini — bukan niat arsitektur yang mungkin sudah lama menyimpang.
08.11 Tips & Gotchas Architecture Linting
💡 Tip 1: Start dengan depguard, bukan custom script. depguard lebih mudah maintain karena konfigurasi di YAML. Custom script untuk edge cases yang depguard tidak bisa handle.
💡 Tip 2: Architecture rules sebagai test. architecture_test.go yang test import rules bisa run dengan go test — tidak perlu CI step khusus.
💡 Tip 3: Exceptions harus explicit dan di-document. Setiap nolint atau allowlist harus ada komentar kenapa exception itu valid. “Technical debt yang disadari” lebih baik dari “technical debt yang tidak terdeteksi”.
💡 Tip 4: Run architecture check di pre-commit. Jauh lebih cepat mendapat feedback di local daripada menunggu CI. Tambahkan ke pre-commit hook.
⚠️ Gotcha 1: Path-based detection bisa miss files. Custom script yang detect “jika path contains ‘handler’” bisa miss kalau developer taruh file di wrong directory. Pair dengan golangci-lint yang lebih robust.
⚠️ Gotcha 2: Third-party wrappers. Jika usecase wrap pgx error, itu acceptable. Jika usecase import pgx package, itu violation. Bedakan antara type assertion dan direct import.
⚠️ Gotcha 3: Shared packages bisa jadi loophole. Package di shared/ yang di-import oleh semua layer harus benar-benar pure (hanya types, interfaces). Jangan taruh infrastructure code di shared package.
08.12 Metrik Architecture Health
Enforcement saja tidak cukup; kita juga ingin memantau tren kesehatan arsitektur. Script berikut menghitung jumlah violation, kedalaman import, dan package dengan dependent terbanyak sebagai metrik mingguan.
1# Weekly architecture health check
2
3# 1. Count architecture violations
4VIOLATIONS=$(go run scripts/check-architecture.go ./... 2>&1 | \
5 grep "^❌" | wc -l || echo "0")
6
7# 2. Import depth (deeper = more complex)
8MAX_DEPTH=$(go list -f '{{len .Imports}}' ./... | sort -n | tail -1)
9
10# 3. Packages with most dependents
11MOST_DEPENDED=$(go list -f '{{.ImportedBy}}' ./internal/... | \
12 sort | uniq -c | sort -rn | head -5)
13
14echo "Architecture Health Report"
15echo "=========================="
16echo "Violations: $VIOLATIONS (target: 0)"
17echo "Max import count: $MAX_DEPTH (target: < 20)"
18echo ""
19echo "Most depended packages:"
20echo "$MOST_DEPENDED"Metrik seperti “max import count” dan “most depended packages” memberi sinyal dini tentang package yang terlalu kompleks atau menjadi bottleneck dependency — sebelum jadi masalah besar.
08.13 Case Study: Migration dari Monolith ke Clean Architecture
Teori enforcement terlihat berbeda saat diterapkan pada codebase legacy 50K baris. Kronologi berikut menunjukkan bagaimana satu tim memakai architecture linting untuk melacak progres migrasi secara bertahap.
1Tim Santekno, service lama dengan 50K lines tanpa layer yang jelas.
2Menggunakan architecture linting untuk track progress migration.
3
4Phase 1 (Sprint 1-3): Setup linting dengan severity=warning
5 Day 1: 847 violations terdeteksi
6 Action: prioritize per layer dan severity
7
8Phase 2 (Sprint 4-8): Fix per feature
9 Sprint 4: 847 → 612 violations
10 Sprint 6: 612 → 341 violations
11 Sprint 8: 341 → 89 violations
12
13Phase 3 (Sprint 9-10): Hard enforcement
14 Sprint 10: 0 violations
15 Architecture linting: fully enforced
16
17Lessons: soft enforcement dulu adalah kunci untuk buy-in.Pelajaran utamanya: memulai dengan severity=warning memungkinkan tim menurunkan 847 violation secara bertahap tanpa langsung mem-block semua PR — hard enforcement baru dinyalakan setelah angka mendekati nol.
08.14 Import Graph Analysis
Untuk analisis dependency yang lebih dalam, tooling dari golang.org/x/tools bisa dipakai. Perintah berikut menghasilkan import graph dan mengecek cross-layer dependency terlarang secara ringkas.
1# golang.org/x/tools/cmd/callgraph untuk analyze dependencies
2go install golang.org/x/tools/cmd/callgraph@latest
3
4# Generate import graph untuk internal packages
5goda graph "github.com/santekno/santekno-shop/internal/..." > /tmp/import-graph.dot
6
7# Check forbidden cross-layer deps
8goda list -f "{{.ImportedBy}}" \
9 "github.com/santekno/santekno-shop/internal/repository/..." | \
10 grep -E "(delivery|usecase)" && echo "VIOLATION" || echo "OK"Output biner “VIOLATION” atau “OK” ini mudah diintegrasikan ke pipeline sebagai gate cepat sebelum analisis yang lebih mahal dijalankan.
08.15 Enforcement Levels per Environment
Enforcement tidak harus seragam di semua branch. Konfigurasi berikut menerapkan aturan ketat (zero violation) di main, tapi hanya warning di develop.
1# Berbeda enforcement untuk berbeda context
2- name: Architecture check
3 run: |
4 VIOLATIONS=$(go run scripts/check-architecture.go ./... 2>&1 | \
5 grep "^VIOLATION" | wc -l)
6
7 # main branch: strict (zero violations)
8 if [ "${{ github.ref }}" == "refs/heads/main" ]; then
9 [ "$VIOLATIONS" -gt 0 ] && exit 1
10 fi
11
12 # develop: warning only
13 if [ "${{ github.ref }}" == "refs/heads/develop" ]; then
14 [ "$VIOLATIONS" -gt 0 ] && echo "::warning::$VIOLATIONS architecture violations"
15 fiPendekatan bertingkat ini memberi ruang gerak di branch pengembangan sambil menjaga main tetap bersih — standar tertinggi berlaku untuk kode yang benar-benar dirilis.
08.16 Ringkasan Architecture Linting
Architecture linting dengan tiga layer memberikan coverage yang komprehensif:
depguard (Layer 1): Konfigurasi YAML yang mudah maintain, catch import yang explicitly forbidden.
Custom script (Layer 2): Lebih flexible, bisa detect pattern yang lebih complex, generate detailed violation reports dengan exact file:line.
AI review (Layer 3): Semantic understanding untuk violations yang butuh context — “apakah ini benar-benar bypass atau legitimate wrapper?”
Architecture tests (bonus): Encode rules sebagai Go tests yang bisa run dengan go test, zero infrastructure overhead.
Insight kuncinya: architecture yang baik adalah architecture yang di-enforce secara otomatis — bukan hanya yang tertulis rapi di dokumen tapi tak pernah dijaga.
08.17 Transisi ke Artikel Berikutnya
Sekarang kita punya empat quality gate independen — AI code review, security audit, coverage enforcement, dan architecture linting. Tapi keempatnya masih bisa diabaikan jika developer memaksakan merge. Pertanyaan berikutnya: bagaimana menjadikan semua gate ini sebagai hard requirement yang tidak bisa di-bypass?
Jawabannya ada di GitHub Branch Protection dengan required status checks dan aggregate quality gate, yang menyatukan seluruh gate menjadi satu sistem enforcement yang koheren.