Debian Codegraph @

scripts/architecture-shape-report.sh

raw
1 #!/usr/bin/env bash
2
3 set -euo pipefail
4
5 target="."
6 target_set=0
7 baseline="${THOTH_ARCH_BASELINE:-}"
8 write_report=""
9 bin="${THOTH_BIN:-thoth}"
10
11 usage() {
12 echo "usage: $0 [--target .] [--baseline previous-report.json] [--write-report current-report.json]" >&2
13 }
14
15 set_target() {
16 if [[ "$target_set" -eq 1 ]]; then
17 echo "error: target specified more than once" >&2
18 exit 2
19 fi
20 target="$1"
21 target_set=1
22 }
23
24 while [[ $# -gt 0 ]]; do
25 case "$1" in
26 --baseline)
27 [[ $# -ge 2 ]] || { echo "error: --baseline requires a report path" >&2; exit 2; }
28 baseline="$2"
29 shift 2
30 ;;
31 --target)
32 [[ $# -ge 2 ]] || { echo "error: --target requires a path" >&2; exit 2; }
33 set_target "$2"
34 shift 2
35 ;;
36 --write-report)
37 [[ $# -ge 2 ]] || { echo "error: --write-report requires a path" >&2; exit 2; }
38 write_report="$2"
39 shift 2
40 ;;
41 -h|--help)
42 usage
43 exit 0
44 ;;
45 -*)
46 echo "error: unknown option: $1" >&2
47 usage
48 exit 2
49 ;;
50 *)
51 set_target "$1"
52 shift
53 ;;
54 esac
55 done
56
57 if [[ ! -e "$target" ]]; then
58 echo "error: target not found: $target" >&2
59 exit 1
60 fi
61 if [[ ! -d "$target" ]]; then
62 echo "error: target must be a directory: $target" >&2
63 exit 1
64 fi
65 if [[ -n "$baseline" ]]; then
66 if [[ ! -f "$baseline" ]]; then
67 echo "error: baseline not found: $baseline" >&2
68 exit 1
69 fi
70 python3 - "$baseline" <<'PY'
71 import json
72 import sys
73 from pathlib import Path
74
75 path = Path(sys.argv[1])
76 try:
77 json.loads(path.read_text())
78 except Exception as exc:
79 print(f"error: invalid baseline JSON: {path}: {exc}", file=sys.stderr)
80 sys.exit(1)
81 PY
82 fi
83
84 if ! command -v "$bin" >/dev/null 2>&1; then
85 echo "error: thoth binary not found: $bin; set THOTH_BIN or install thoth" >&2
86 exit 1
87 fi
88
89 report="$(mktemp)"
90 prod_tree="$(mktemp -d)"
91 trap 'rm -f "$report"; rm -rf "$prod_tree"' EXIT
92
93 analysis_target="$(python3 - "$target" "$prod_tree" <<'PY'
94 import shutil
95 import sys
96 from pathlib import Path
97
98 source = Path(sys.argv[1])
99 dest = Path(sys.argv[2]) / "clnkr-production"
100
101 ignored_dirs = {".git", ".worktrees", "build", "site/public"}
102
103 def ignored(path, names):
104 current = Path(path)
105 rejected = set()
106 for name in names:
107 child = current / name
108 rel = child.relative_to(source) if source in child.parents or child == source else child
109 rel_text = rel.as_posix()
110 if name in {".git", ".worktrees", "build"} or rel_text == "site/public":
111 rejected.add(name)
112 elif name.endswith("_test.go"):
113 rejected.add(name)
114 return rejected
115
116 shutil.copytree(source, dest, ignore=ignored)
117 print(dest)
118 PY
119 )"
120
121 "$bin" "$analysis_target" --report > "$report"
122
123 output="$(python3 - "$report" "$baseline" "$target" <<'PY'
124 import json
125 import math
126 import statistics
127 import sys
128 from pathlib import Path
129
130 report_path = Path(sys.argv[1])
131 baseline_path = Path(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2] else None
132 target = sys.argv[3]
133 data = json.loads(report_path.read_text())
134 summary = data.get("summary", {})
135 architecture = data.get("architecture", [])
136 modules = data.get("module_health", [])
137 cycles = data.get("dependency_cycles", [])
138
139 print("architecture shape report")
140 print(f"target: {target} production Go files")
141 print(
142 "summary: "
143 f"files={summary.get('files', 0)} "
144 f"sloc={summary.get('total_sloc', 0)} "
145 f"functions={summary.get('functions', 0)} "
146 f"dep_edges={summary.get('dep_edges', 0)} "
147 f"cycles={summary.get('cycles', 0)}"
148 )
149
150 ca_values = [int(entry.get("ca", 0)) for entry in architecture]
151 mean_ca = statistics.mean(ca_values) if ca_values else 0.0
152 std_ca = statistics.pstdev(ca_values) if len(ca_values) > 1 else 0.0
153 hub_threshold = mean_ca + (2 * std_ca)
154 hubs = [
155 entry
156 for entry in architecture
157 if int(entry.get("ca", 0)) >= 5
158 and (int(entry.get("ca", 0)) > hub_threshold or entry.get("role") == "hub")
159 ]
160
161 print(f"ca: mean={mean_ca:.2f} stddev={std_ca:.2f} hub_threshold={hub_threshold:.2f}")
162 if hubs:
163 print("hubs:")
164 for entry in hubs:
165 print(
166 f"- {entry.get('path')}: "
167 f"ca={entry.get('ca')} ce={entry.get('ce')} "
168 f"instability={entry.get('instability')} role={entry.get('role')}"
169 )
170 else:
171 print("hubs: none")
172
173 if cycles:
174 print("dependency_cycles:")
175 for cycle in cycles[:10]:
176 print("- " + " -> ".join(cycle))
177 if len(cycles) > 10:
178 print(f"- ... {len(cycles) - 10} more")
179 else:
180 print("dependency_cycles: none")
181
182 slocs = sorted(int(module.get("sloc", 0)) for module in modules)
183 if slocs:
184 buckets = {
185 "<50": sum(1 for value in slocs if value < 50),
186 "50-100": sum(1 for value in slocs if 50 <= value < 100),
187 "100-200": sum(1 for value in slocs if 100 <= value < 200),
188 "200-400": sum(1 for value in slocs if 200 <= value < 400),
189 "400+": sum(1 for value in slocs if value >= 400),
190 }
191 mean_sloc = statistics.mean(slocs)
192 median_sloc = statistics.median(slocs)
193 numerator = sum((2 * idx - len(slocs) - 1) * value for idx, value in enumerate(slocs, start=1))
194 denominator = len(slocs) * sum(slocs)
195 gini = numerator / denominator if denominator else 0.0
196 print(
197 "sloc_distribution: "
198 + " ".join(f"{name}={value}" for name, value in buckets.items())
199 )
200 print(
201 f"sloc_shape: gini={gini:.3f} "
202 f"median_mean_ratio={(median_sloc / mean_sloc if mean_sloc else math.nan):.3f}"
203 )
204 else:
205 print("sloc_distribution: no modules")
206
207 print("mode: manual-report-only")
208
209 if baseline_path:
210 baseline = json.loads(baseline_path.read_text())
211 base_summary = baseline.get("summary", {})
212 baseline_arch_entries = baseline.get("architecture", [])
213 base_architecture = {entry.get("path"): entry for entry in baseline_arch_entries}
214 current_architecture = {entry.get("path"): entry for entry in architecture}
215 base_ca_values = [int(entry.get("ca", 0)) for entry in baseline_arch_entries]
216 base_mean_ca = statistics.mean(base_ca_values) if base_ca_values else 0.0
217 base_std_ca = statistics.pstdev(base_ca_values) if len(base_ca_values) > 1 else 0.0
218 base_hub_threshold = base_mean_ca + (2 * base_std_ca)
219 base_hubs = {
220 entry.get("path")
221 for entry in baseline_arch_entries
222 if int(entry.get("ca", 0)) >= 5
223 and (int(entry.get("ca", 0)) > base_hub_threshold or entry.get("role") == "hub")
224 }
225 current_hubs = {entry.get("path") for entry in hubs}
226
227 print("budget_deltas:")
228 for key in ("files", "total_sloc", "functions", "dep_edges", "cycles"):
229 current = int(summary.get(key, 0))
230 previous = int(base_summary.get(key, 0))
231 print(f"- {key}: current={current} baseline={previous} delta={current - previous}")
232
233 new_hubs = sorted(path for path in current_hubs if path not in base_hubs)
234 print(f"- new_hubs: {', '.join(new_hubs) if new_hubs else 'none'}")
235
236 ca_growth = []
237 for path, current in current_architecture.items():
238 previous = base_architecture.get(path)
239 if not previous:
240 continue
241 delta = int(current.get("ca", 0)) - int(previous.get("ca", 0))
242 if delta > 0:
243 ca_growth.append((path, delta, current.get("ca"), previous.get("ca")))
244 if ca_growth:
245 print("- ca_growth:")
246 for path, delta, current, previous in sorted(ca_growth, key=lambda item: (-item[1], item[0]))[:20]:
247 print(f" - {path}: current={current} baseline={previous} delta={delta}")
248 else:
249 print("- ca_growth: none")
250 else:
251 print("budget_deltas: no baseline supplied")
252 PY
253 )"
254
255 echo "$output"
256
257 if [[ -n "$write_report" ]]; then
258 tmp_write="$(mktemp)"
259 cp "$report" "$tmp_write"
260 mv "$tmp_write" "$write_report"
261 fi