slopthreshold 2.1.0.dev22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. slopthreshold/__init__.py +1 -0
  2. slopthreshold/guide/STYLE_GUIDE.md +495 -0
  3. slopthreshold/packs/editorconfig-pack/.editorconfig +899 -0
  4. slopthreshold/packs/editorconfig-pack/Directory.Build.props +47 -0
  5. slopthreshold/packs/editorconfig-pack/Directory.Build.targets +16 -0
  6. slopthreshold/packs/editorconfig-pack/Directory.Packages.props +29 -0
  7. slopthreshold/packs/editorconfig-pack/README.md +141 -0
  8. slopthreshold/packs/editorconfig-pack/global.json +7 -0
  9. slopthreshold/packs/editorconfig-pack/nuget.config +19 -0
  10. slopthreshold/packs/editorconfig-pack/ruff.toml +29 -0
  11. slopthreshold/packs/editorconfig-pack/sonar-drift-allowlist.json +10 -0
  12. slopthreshold/packs/frontend-lint-pack/.prettierrc.json +7 -0
  13. slopthreshold/packs/frontend-lint-pack/.stylelintrc.json +64 -0
  14. slopthreshold/packs/frontend-lint-pack/README.md +64 -0
  15. slopthreshold/packs/frontend-lint-pack/eslint.config.mjs +108 -0
  16. slopthreshold/packs/frontend-lint-pack/package.json +23 -0
  17. slopthreshold/packs/frontend-lint-pack/tsconfig.app.json +17 -0
  18. slopthreshold/packs/frontend-lint-pack/tsconfig.base.json +20 -0
  19. slopthreshold/packs/frontend-lint-pack/tsconfig.json +4 -0
  20. slopthreshold/packs/frontend-lint-pack/tsconfig.spec.json +8 -0
  21. slopthreshold/packs/project-guide-starters/app-STYLE_GUIDE.md +35 -0
  22. slopthreshold/packs/project-guide-starters/frontend-STYLE_GUIDE.md +33 -0
  23. slopthreshold/packs/project-guide-starters/library-STYLE_GUIDE.md +36 -0
  24. slopthreshold/packs/three-layer-wiring/.githooks/commit-msg +13 -0
  25. slopthreshold/packs/three-layer-wiring/.githooks/post-merge +8 -0
  26. slopthreshold/packs/three-layer-wiring/.githooks/pre-commit +10 -0
  27. slopthreshold/packs/three-layer-wiring/.githooks/pre-push +14 -0
  28. slopthreshold/packs/three-layer-wiring/.github/actionlint.yaml +3 -0
  29. slopthreshold/packs/three-layer-wiring/.github/workflows/quality.yml +164 -0
  30. slopthreshold/packs/three-layer-wiring/.gitleaks.toml +16 -0
  31. slopthreshold/packs/three-layer-wiring/.hadolint.yaml +6 -0
  32. slopthreshold/packs/three-layer-wiring/README.md +62 -0
  33. slopthreshold/packs/three-layer-wiring/budget.json +14 -0
  34. slopthreshold/tools/check_characters.py +104 -0
  35. slopthreshold/tools/check_ci_config.py +405 -0
  36. slopthreshold/tools/check_package_health.py +554 -0
  37. slopthreshold/tools/check_sonar_drift.py +1123 -0
  38. slopthreshold/tools/mine_sonar_metrics.py +1259 -0
  39. slopthreshold/tools/validate_guide_tags.py +795 -0
  40. slopthreshold/zh.py +973 -0
  41. slopthreshold-2.1.0.dev22.dist-info/METADATA +49 -0
  42. slopthreshold-2.1.0.dev22.dist-info/RECORD +44 -0
  43. slopthreshold-2.1.0.dev22.dist-info/WHEEL +4 -0
  44. slopthreshold-2.1.0.dev22.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,1123 @@
1
+ #!/usr/bin/env python3
2
+ """Check drift between the SonarQube C# quality profile and the local
3
+ editorconfig pack.
4
+
5
+ Compares, per C# quality profile actually used by the house projects:
6
+
7
+ * SonarQube active rules (``/api/qualityprofiles/search`` to discover the
8
+ profile per project, then ``/api/rules/search`` with ``qprofile`` +
9
+ ``activation=true`` + ``f=...,actives`` for the profile severities), with
10
+ * ``dotnet_diagnostic.Sxxxx.severity`` lines in
11
+ ``editorconfig-pack/.editorconfig`` (SonarAnalyzer.CSharp diagnostics).
12
+
13
+ Presence/absence is the primary drift; severity-class mismatch is
14
+ secondary. Exit code 1 means drift, 0 means clean, 2 means the check
15
+ itself failed (auth, network, bad input). See README.md for the severity
16
+ mapping, the mirrorability rules (server-only / taint) and CI usage.
17
+
18
+ Auth follows the custom.sonarqube connector pattern: inside Muse the
19
+ stored credential is attached as a surrogate (never printed); in CI set
20
+ SONAR_TOKEN and it is sent as a Bearer header. Use --auth to force a mode.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import contextlib
27
+ import json
28
+ import os
29
+ import re
30
+ import sys
31
+ import urllib.error
32
+ import urllib.parse
33
+ import urllib.request
34
+ from dataclasses import dataclass, field
35
+ from datetime import datetime, timezone
36
+ from pathlib import Path
37
+
38
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
39
+ from safe_paths import read_text_under, resolve_under, write_text_under # noqa: E402
40
+ from http_util import open_https # noqa: E402
41
+
42
+ DEFAULT_SONAR_URL = "https://sonar.hassanragai.dev"
43
+ DEFAULT_LANGUAGE = "cs"
44
+ BROWSER_UA = (
45
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
46
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
47
+ )
48
+
49
+ # House projects whose C# profile is checked by default: name -> project key.
50
+ DEFAULT_PROJECTS = {
51
+ "Essentials": "ZHEAISNSAABN_ZhEaIsNsAaBn.Essentials_46150f9b-9ffd-49a9-96d1-3241c6e39fd0",
52
+ "Libraries.V1": "ZHEAISNSAABN_ZhEaIsNsAaBn.Libraries.V1_0acb29d0-de5a-4470-8561-ba6218da007b",
53
+ "MarketPulse": "ZHEAISNSAABN_ZhEaIsNsAaBn.MarketPulse_294a1803-0b28-4363-bd29-bb25f32f9158",
54
+ "Sql": "ZHEAISNSAABN_ZhEaIsNsAaBn.Sql_706d02f9-2a15-4408-a166-5278b47aaaf7",
55
+ }
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Severity mapping
59
+ # ---------------------------------------------------------------------------
60
+
61
+ # Sonar profile severity -> expected editorconfig severity.
62
+ SONAR_TO_LOCAL = {
63
+ "BLOCKER": "error",
64
+ "CRITICAL": "error",
65
+ "MAJOR": "warning",
66
+ "MINOR": "suggestion",
67
+ "INFO": "suggestion",
68
+ }
69
+ SONAR_SEVERITY_ORDER = {"BLOCKER": 0, "CRITICAL": 1, "MAJOR": 2, "MINOR": 3, "INFO": 4}
70
+ LOCAL_RANK = {"error": 3, "warning": 2, "suggestion": 1, "none": 0}
71
+ # Build-gate classes. Under TreatWarningsAsErrors (the pack sets it),
72
+ # error and warning both fail the build, so they share the blocking class.
73
+ LOCAL_CLASS = {"error": "blocking", "warning": "blocking", "suggestion": "advisory", "none": "off"}
74
+ VALID_LOCAL_SEVERITIES = {"error", "warning", "suggestion", "none", "silent", "default"}
75
+
76
+ # Repositories whose rules have no SonarAnalyzer.CSharp Roslyn diagnostic
77
+ # and therefore cannot be mirrored in .editorconfig. Reported as
78
+ # informational, excluded from drift and from the exit code.
79
+ SERVER_ONLY_REPOS = {"csharparchitecture"}
80
+ # Taint/security rules: diagnostic IDs exist and severities are
81
+ # configurable, but full taint evaluation needs the Sonar scanner.
82
+ # Counted as mirrorable drift (tagged kind=security_taint) unless
83
+ # --exclude-taint moves them to informational.
84
+ TAINT_REPOS = {"roslyn.sonaranalyzer.security.cs"}
85
+
86
+ S_RULE_RE = re.compile(r"^S\d+$")
87
+ DIAGNOSTIC_RE = re.compile(r"^dotnet_diagnostic\.([^.]+)\.severity$")
88
+
89
+
90
+ def map_sonar_severity(sonar_severity: str) -> str:
91
+ """Map a Sonar severity to the expected editorconfig severity."""
92
+ try:
93
+ return SONAR_TO_LOCAL[sonar_severity.strip().upper()]
94
+ except KeyError:
95
+ raise ValueError(f"unknown Sonar severity: {sonar_severity!r}") from None
96
+
97
+
98
+ def rule_sort_key(rule_id: str) -> tuple[int, str]:
99
+ """Sort S-ids numerically (S101 before S1006), others last."""
100
+ if S_RULE_RE.match(rule_id):
101
+ return (int(rule_id[1:]), rule_id)
102
+ return (10**9, rule_id)
103
+
104
+
105
+ def sonar_sort_key(entry: dict) -> tuple[int, int, str]:
106
+ sev = entry.get("sonar_severity") or entry.get("severity") or ""
107
+ return (SONAR_SEVERITY_ORDER.get(sev, 99), *rule_sort_key(entry.get("id", "")))
108
+
109
+
110
+ # ---------------------------------------------------------------------------
111
+ # Editorconfig parsing
112
+ # ---------------------------------------------------------------------------
113
+
114
+
115
+ @dataclass
116
+ class LocalRule:
117
+ id: str
118
+ severity: str | None # normalized: error/warning/suggestion/none, None = unspecified ("default")
119
+ raw_severity: str
120
+ line: int
121
+ section: str
122
+
123
+ @property
124
+ def enabled(self) -> bool:
125
+ return self.severity in ("error", "warning", "suggestion")
126
+
127
+
128
+ @dataclass
129
+ class EditorconfigParse:
130
+ rules: dict[str, LocalRule] = field(default_factory=dict)
131
+ duplicates: list[dict] = field(default_factory=list)
132
+ warnings: list[str] = field(default_factory=list)
133
+ non_s_diagnostics: int = 0
134
+
135
+
136
+ def _section_name(line: str) -> str | None:
137
+ if line.startswith("[") and line.endswith("]"):
138
+ return line[1:-1].strip()
139
+ return None
140
+
141
+
142
+ def _diagnostic_entry(line: str) -> tuple[str, str] | None:
143
+ """Return (diagnostic id, severity token) for a diagnostic line, else None."""
144
+ if "=" not in line:
145
+ return None
146
+ key, _, value = line.partition("=")
147
+ m = DIAGNOSTIC_RE.match(key.strip().lower())
148
+ if not m:
149
+ return None
150
+ parts = value.strip().lower().split()
151
+ return (m.group(1).upper(), parts[0] if parts else "")
152
+
153
+
154
+ def _validated_token(token: str, diag_id: str, lineno: int, result: EditorconfigParse) -> str:
155
+ if token not in VALID_LOCAL_SEVERITIES:
156
+ result.warnings.append(
157
+ f"line {lineno}: {diag_id} has unrecognized severity {token!r}; treated as unspecified"
158
+ )
159
+ return "default"
160
+ return token
161
+
162
+
163
+ def _normalize_severity(token: str) -> str | None:
164
+ # editorconfig severity word, not a credential
165
+ if token == "silent": # noqa: S105
166
+ return "none"
167
+ if token == "default": # noqa: S105
168
+ return None
169
+ return token
170
+
171
+
172
+ def _record_s_rule(
173
+ result: EditorconfigParse,
174
+ seen: dict[str, list[int]],
175
+ diag_id: str,
176
+ token: str,
177
+ lineno: int,
178
+ section: str,
179
+ ) -> None:
180
+ token = _validated_token(token, diag_id, lineno, result)
181
+ seen.setdefault(diag_id, []).append(lineno)
182
+ result.rules[diag_id] = LocalRule(
183
+ id=diag_id, severity=_normalize_severity(token), raw_severity=token, line=lineno, section=section
184
+ )
185
+
186
+
187
+ def _collect_duplicates(result: EditorconfigParse, seen: dict[str, list[int]]) -> None:
188
+ for diag_id, lines in sorted(seen.items(), key=lambda kv: rule_sort_key(kv[0])):
189
+ if len(lines) > 1:
190
+ result.duplicates.append({"id": diag_id, "lines": lines, "kept_line": lines[-1]})
191
+
192
+
193
+ def parse_editorconfig_text(text: str) -> EditorconfigParse:
194
+ """Parse dotnet_diagnostic.Sxxxx.severity lines from editorconfig text.
195
+
196
+ Last occurrence wins (editorconfig semantics). Comments (# / ; at line
197
+ start), blank lines and non-diagnostic keys are ignored. Keys and
198
+ values are case-insensitive. ``silent`` normalizes to ``none``;
199
+ ``default`` means unspecified (severity None). Non-S diagnostics
200
+ (IDE*, CA*, MA*, ...) are counted but not returned as rules.
201
+ """
202
+ result = EditorconfigParse()
203
+ section = ""
204
+ seen: dict[str, list[int]] = {}
205
+ for lineno, raw_line in enumerate(text.splitlines(), start=1):
206
+ line = raw_line.strip()
207
+ if not line or line.startswith("#") or line.startswith(";"):
208
+ continue
209
+ name = _section_name(line)
210
+ if name is not None:
211
+ section = name
212
+ continue
213
+ entry = _diagnostic_entry(line)
214
+ if entry is None:
215
+ continue
216
+ diag_id, token = entry
217
+ if not S_RULE_RE.match(diag_id):
218
+ result.non_s_diagnostics += 1
219
+ continue
220
+ _record_s_rule(result, seen, diag_id, token, lineno, section)
221
+ _collect_duplicates(result, seen)
222
+ return result
223
+
224
+
225
+ def parse_editorconfig(path: Path) -> EditorconfigParse:
226
+ return parse_editorconfig_text(read_text_under(path, Path.cwd(), encoding="utf-8-sig"))
227
+
228
+
229
+ # ---------------------------------------------------------------------------
230
+ # Sonar data model + payload parsing
231
+ # ---------------------------------------------------------------------------
232
+
233
+
234
+ @dataclass
235
+ class SonarRule:
236
+ key: str # e.g. "csharpsquid:S2306"
237
+ id: str # e.g. "S2306"
238
+ repo: str
239
+ name: str
240
+ type: str
241
+ status: str
242
+ scope: str
243
+ default_severity: str
244
+ profile_severity: str | None = None # from actives; None when not active
245
+ params: list = field(default_factory=list)
246
+ is_external: bool = False
247
+
248
+ @property
249
+ def severity(self) -> str:
250
+ return self.profile_severity or self.default_severity
251
+
252
+ @property
253
+ def kind(self) -> str:
254
+ if self.repo in SERVER_ONLY_REPOS:
255
+ return "server_only"
256
+ if self.repo in TAINT_REPOS:
257
+ return "security_taint"
258
+ return "mirrorable"
259
+
260
+
261
+ def split_rule_key(key: str) -> tuple[str, str]:
262
+ repo, _, rule_id = key.rpartition(":")
263
+ return (repo or "unknown", rule_id or key)
264
+
265
+
266
+ def parse_rules_search_payload(payload: dict, profile_key: str | None = None) -> list[SonarRule]:
267
+ """Parse one /api/rules/search page. Profile severities come from the
268
+ top-level ``actives`` map (requested with f=...,actives); the rule's
269
+ own ``severity`` field is only the default."""
270
+ actives = payload.get("actives") or {}
271
+ rules: list[SonarRule] = []
272
+ for raw in payload.get("rules", []):
273
+ key = raw.get("key", "")
274
+ repo, rule_id = split_rule_key(key)
275
+ profile_severity = None
276
+ params: list = []
277
+ for active in actives.get(key, []):
278
+ if profile_key is None or active.get("qProfile") == profile_key:
279
+ profile_severity = active.get("severity")
280
+ params = active.get("params") or []
281
+ break
282
+ rules.append(
283
+ SonarRule(
284
+ key=key,
285
+ id=rule_id,
286
+ repo=raw.get("repo") or repo,
287
+ name=raw.get("name", ""),
288
+ type=raw.get("type", ""),
289
+ status=raw.get("status", ""),
290
+ scope=raw.get("scope", ""),
291
+ default_severity=raw.get("severity", ""),
292
+ profile_severity=profile_severity,
293
+ params=params,
294
+ is_external=bool(raw.get("isExternal")),
295
+ )
296
+ )
297
+ return rules
298
+
299
+
300
+ def merge_rule_pages(pages: list[dict], profile_key: str | None = None) -> list[SonarRule]:
301
+ merged: dict[str, SonarRule] = {}
302
+ for page in pages:
303
+ for rule in parse_rules_search_payload(page, profile_key=profile_key):
304
+ merged[rule.key] = rule
305
+ return list(merged.values())
306
+
307
+
308
+ # ---------------------------------------------------------------------------
309
+ # Sonar API client
310
+ # ---------------------------------------------------------------------------
311
+
312
+
313
+ class SonarError(RuntimeError):
314
+ pass
315
+
316
+
317
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
318
+ def redirect_request(self, *args): # noqa: D102 - refuse redirects on authed calls
319
+ raise SonarError("redirect refused; verify the Sonar endpoint")
320
+
321
+
322
+ class SonarClient:
323
+ """Minimal SonarQube REST client following the connector pattern.
324
+
325
+ auth="auto": SONAR_TOKEN env (Bearer) if set, else the Muse
326
+ surrogate credential if importable, else unauthenticated.
327
+ Secrets are never logged or included in errors.
328
+ """
329
+
330
+ def __init__(
331
+ self,
332
+ base_url: str = DEFAULT_SONAR_URL,
333
+ auth: str = "auto",
334
+ token_env: str = "SONAR_TOKEN", # noqa: S107
335
+ timeout: int = 30,
336
+ page_size: int = 500,
337
+ ):
338
+ self.base_url = base_url.rstrip("/")
339
+ self.host = urllib.parse.urlparse(self.base_url).netloc
340
+ self.timeout = timeout
341
+ self.page_size = page_size
342
+ self.auth_mode = self._resolve_auth(auth, token_env)
343
+ self._token = os.environ.get(token_env) if self.auth_mode == "env" else None
344
+
345
+ def _resolve_auth(self, auth: str, token_env: str) -> str:
346
+ if auth == "env":
347
+ if not os.environ.get(token_env):
348
+ raise SonarError(f"--auth env requires ${token_env} to be set")
349
+ return "env"
350
+ if auth in ("surrogate", "none"):
351
+ return auth
352
+ if auth == "auto":
353
+ if os.environ.get(token_env):
354
+ return "env"
355
+ try:
356
+ sys.path.insert(0, "/opt/muse/skills/custom-connector-setup/bin")
357
+ import dynamic_credentials # noqa: F401
358
+
359
+ return "surrogate"
360
+ except Exception:
361
+ return "none"
362
+ raise SonarError(f"unknown auth mode: {auth!r}")
363
+
364
+ def _get_json(self, path: str, params: dict | None = None) -> dict:
365
+ url = self.base_url + path
366
+ if params:
367
+ url += "?" + urllib.parse.urlencode(params)
368
+ # Cloudflare in front of sonar.hassanragai.dev bans the default
369
+ # Python-urllib UA (Error 1010); send a browser UA (connector note).
370
+ headers = {"Accept": "application/json", "User-Agent": BROWSER_UA}
371
+ request_hook = None
372
+ if self.auth_mode == "env":
373
+ headers["Authorization"] = f"Bearer {self._token}"
374
+ elif self.auth_mode == "surrogate":
375
+ sys.path.insert(0, "/opt/muse/skills/custom-connector-setup/bin")
376
+ from dynamic_credentials import add_surrogate_to_request
377
+
378
+ def request_hook(req):
379
+ add_surrogate_to_request(req, "custom.sonarqube", allowed_hosts=[self.host])
380
+
381
+ opener = urllib.request.build_opener(_NoRedirect())
382
+ try:
383
+ with open_https(url, headers=headers, timeout=self.timeout,
384
+ opener=opener, request_hook=request_hook) as resp:
385
+ body = resp.read().decode("utf-8", errors="replace")
386
+ except urllib.error.HTTPError as exc:
387
+ detail = ""
388
+ # Best-effort error detail; an unreadable body must not mask
389
+ # the HTTPError itself, so failures here are suppressed.
390
+ with contextlib.suppress(Exception):
391
+ detail = exc.read().decode("utf-8", errors="replace")[:500]
392
+ hint = ""
393
+ if exc.code in (401, 403):
394
+ hint = " (check token/auth mode; a Cloudflare 1010 body means the UA was rejected, not the token)"
395
+ raise SonarError(f"GET {path} failed: HTTP {exc.code}{hint} {detail}".strip()) from None
396
+ except Exception as exc: # network, timeout, redirect refusal
397
+ raise SonarError(f"GET {path} failed: {exc}") from None
398
+ try:
399
+ return json.loads(body)
400
+ except json.JSONDecodeError:
401
+ raise SonarError(f"GET {path} returned non-JSON output") from None
402
+
403
+ def get_project_profiles(self, project_key: str, language: str = DEFAULT_LANGUAGE) -> list[dict]:
404
+ payload = self._get_json(
405
+ "/api/qualityprofiles/search", {"project": project_key, "language": language}
406
+ )
407
+ return [p for p in payload.get("profiles", []) if p.get("language") == language]
408
+
409
+ def get_profiles(self, language: str = DEFAULT_LANGUAGE) -> list[dict]:
410
+ payload = self._get_json("/api/qualityprofiles/search", {"language": language})
411
+ return payload.get("profiles", [])
412
+
413
+ def _search_rules(self, params: dict, profile_key: str | None = None) -> list[SonarRule]:
414
+ pages: list[dict] = []
415
+ page = 1
416
+ total: int | None = None
417
+ while True:
418
+ page_params = dict(params, ps=self.page_size, p=page)
419
+ payload = self._get_json("/api/rules/search", page_params)
420
+ pages.append(payload)
421
+ paging = payload.get("paging") or {}
422
+ total = paging.get("total", payload.get("total"))
423
+ collected = sum(len(p.get("rules", [])) for p in pages)
424
+ if total is None or collected >= total or not payload.get("rules"):
425
+ break
426
+ page += 1
427
+ return merge_rule_pages(pages, profile_key=profile_key)
428
+
429
+ def get_active_rules(self, profile_key: str, language: str = DEFAULT_LANGUAGE) -> list[SonarRule]:
430
+ return self._search_rules(
431
+ {
432
+ "languages": language,
433
+ "qprofile": profile_key,
434
+ "activation": "true",
435
+ "f": "name,severity,status,actives,repo,scope,isExternal",
436
+ },
437
+ profile_key=profile_key,
438
+ )
439
+
440
+ def get_all_rules(self, language: str = DEFAULT_LANGUAGE) -> list[SonarRule]:
441
+ return self._search_rules(
442
+ {"languages": language, "f": "name,severity,status,repo,scope,isExternal"}
443
+ )
444
+
445
+
446
+ # ---------------------------------------------------------------------------
447
+ # Allowlist
448
+ # ---------------------------------------------------------------------------
449
+
450
+
451
+ def load_allowlist(path: Path | None) -> dict[str, str]:
452
+ """Load intentional-drift allowlist: JSON {id: reason} or text lines
453
+ ``S1234 reason`` / ``S1234 # reason``. Returns id -> reason."""
454
+ if path is None:
455
+ return {}
456
+ text = read_text_under(path, Path.cwd(), encoding="utf-8-sig").strip()
457
+ if not text:
458
+ return {}
459
+ if text.startswith("{"):
460
+ data = json.loads(text)
461
+ return {str(k).upper(): str(v) for k, v in data.items()}
462
+ allow: dict[str, str] = {}
463
+ for line in text.splitlines():
464
+ line = line.strip()
465
+ if not line or line.startswith("#"):
466
+ continue
467
+ parts = line.replace("#", " ", 1).split(None, 1)
468
+ rule_id = parts[0].upper()
469
+ if S_RULE_RE.match(rule_id):
470
+ allow[rule_id] = parts[1].strip() if len(parts) > 1 else ""
471
+ return allow
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Drift classification
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ def classify_severity_mismatch(
480
+ sonar_severity: str, local_severity: str, severity_mode: str = "exact"
481
+ ) -> dict | None:
482
+ """Return mismatch detail, or None when severities agree.
483
+
484
+ exact mode: mismatch when local != mapped Sonar severity.
485
+ class mode: mismatch only when the build-gate class differs
486
+ (blocking = error/warning, advisory = suggestion, off = none).
487
+ ``material`` always means the class differs.
488
+ """
489
+ expected = map_sonar_severity(sonar_severity)
490
+ exact_mismatch = local_severity != expected
491
+ class_mismatch = LOCAL_CLASS[local_severity] != LOCAL_CLASS[expected]
492
+ is_mismatch = class_mismatch if severity_mode == "class" else exact_mismatch
493
+ if not is_mismatch:
494
+ return None
495
+ delta = LOCAL_RANK[local_severity] - LOCAL_RANK[expected]
496
+ return {
497
+ "sonar_severity": sonar_severity,
498
+ "expected_local": expected,
499
+ "actual_local": local_severity,
500
+ "direction": "local_stricter" if delta > 0 else "local_looser",
501
+ "rank_delta": delta,
502
+ "exact_mismatch": exact_mismatch,
503
+ "class_mismatch": class_mismatch,
504
+ "material": class_mismatch,
505
+ }
506
+
507
+
508
+ def _rule_entry(rule: SonarRule, **extra) -> dict:
509
+ entry = {
510
+ "id": rule.id,
511
+ "key": rule.key,
512
+ "repo": rule.repo,
513
+ "kind": rule.kind,
514
+ "name": rule.name,
515
+ "type": rule.type,
516
+ "status": rule.status,
517
+ "scope": rule.scope,
518
+ "sonar_severity": rule.severity,
519
+ "expected_local": map_sonar_severity(rule.severity) if rule.severity in SONAR_TO_LOCAL else None,
520
+ }
521
+ if rule.params:
522
+ entry["params"] = rule.params
523
+ entry.update(extra)
524
+ return entry
525
+
526
+
527
+ def _index_rules_by_id(rules: list[SonarRule], collisions: list[dict]) -> dict[str, SonarRule]:
528
+ """Index rules by S-id, keeping the most severe on a duplicate id."""
529
+ by_id: dict[str, SonarRule] = {}
530
+ for rule in rules:
531
+ if not S_RULE_RE.match(rule.id):
532
+ continue
533
+ existing = by_id.get(rule.id)
534
+ if existing is None:
535
+ by_id[rule.id] = rule
536
+ continue
537
+ collisions.append({"id": rule.id, "keys": [existing.key, rule.key]})
538
+ if SONAR_SEVERITY_ORDER.get(rule.severity, 99) < SONAR_SEVERITY_ORDER.get(existing.severity, 99):
539
+ by_id[rule.id] = rule
540
+ return by_id
541
+
542
+
543
+ def _is_drift_relevant(rule: SonarRule, exclude_taint: bool) -> bool:
544
+ return not (rule.kind == "server_only"
545
+ or (exclude_taint and rule.kind == "security_taint"))
546
+
547
+
548
+ def _append_allowlisted(
549
+ entry: dict, rule_id: str, allowlist: dict[str, str], fallback: list[dict], allowlisted: list[dict]
550
+ ) -> None:
551
+ if rule_id in allowlist:
552
+ allowlisted.append({**entry, "allowlist_reason": allowlist[rule_id]})
553
+ return
554
+ fallback.append(entry)
555
+
556
+
557
+ def _classify_severity_outcome(
558
+ rule: SonarRule,
559
+ local_rule: LocalRule,
560
+ severity_mode: str,
561
+ allowlist: dict[str, str],
562
+ buckets: dict[str, list],
563
+ ) -> None:
564
+ mismatch = classify_severity_mismatch(rule.severity, local_rule.severity, severity_mode)
565
+ if mismatch is None:
566
+ buckets["matched"].append(rule.id)
567
+ return
568
+ entry = _rule_entry(rule, local_line=local_rule.line, **mismatch)
569
+ _append_allowlisted(entry, rule.id, allowlist, buckets["mismatches"], buckets["allowlisted"])
570
+
571
+
572
+ def _classify_active_rule(
573
+ rule: SonarRule,
574
+ local: EditorconfigParse,
575
+ allowlist: dict[str, str],
576
+ severity_mode: str,
577
+ exclude_taint: bool,
578
+ buckets: dict[str, list],
579
+ ) -> None:
580
+ if not _is_drift_relevant(rule, exclude_taint):
581
+ target = buckets["informational_taint"] if rule.kind == "security_taint" else buckets["server_only"]
582
+ target.append(_rule_entry(rule, reason="excluded_from_drift"))
583
+ return
584
+ local_rule = local.rules.get(rule.id)
585
+ if local_rule is None:
586
+ entry = _rule_entry(rule, local_state="absent")
587
+ _append_allowlisted(entry, rule.id, allowlist, buckets["missing"], buckets["allowlisted"])
588
+ return
589
+ if local_rule.severity is None:
590
+ entry = _rule_entry(rule, local_state="unspecified_default", local_line=local_rule.line)
591
+ _append_allowlisted(entry, rule.id, allowlist, buckets["missing"], buckets["allowlisted"])
592
+ return
593
+ if local_rule.severity == "none":
594
+ entry = _rule_entry(rule, local_state="disabled", actual_local="none", local_line=local_rule.line)
595
+ _append_allowlisted(entry, rule.id, allowlist, buckets["disabled_locally"], buckets["allowlisted"])
596
+ return
597
+ _classify_severity_outcome(rule, local_rule, severity_mode, allowlist, buckets)
598
+
599
+
600
+ def _local_not_active_entry(
601
+ rule_id: str,
602
+ local_rule: LocalRule,
603
+ active_by_id: dict[str, SonarRule],
604
+ all_by_id: dict[str, SonarRule],
605
+ ) -> dict:
606
+ if rule_id in active_by_id:
607
+ # Active but server-only/taint-excluded: a local line cannot mirror it.
608
+ active = active_by_id[rule_id]
609
+ state = "active_server_only" if active.kind == "server_only" else "active_excluded_taint"
610
+ return {
611
+ "id": rule_id,
612
+ "state": state,
613
+ "actual_local": local_rule.severity,
614
+ "local_line": local_rule.line,
615
+ "key": active.key,
616
+ "name": active.name,
617
+ }
618
+ known = all_by_id.get(rule_id)
619
+ if known is not None:
620
+ state = "inactive_deprecated" if known.status == "DEPRECATED" else "inactive"
621
+ return {
622
+ "id": rule_id,
623
+ "state": state,
624
+ "actual_local": local_rule.severity,
625
+ "local_line": local_rule.line,
626
+ "key": known.key,
627
+ "name": known.name,
628
+ "sonar_severity": known.default_severity,
629
+ "status": known.status,
630
+ }
631
+ return {
632
+ "id": rule_id,
633
+ "state": "unknown_absent",
634
+ "actual_local": local_rule.severity,
635
+ "local_line": local_rule.line,
636
+ }
637
+
638
+
639
+ def _classify_local_rule(
640
+ rule_id: str,
641
+ local_rule: LocalRule,
642
+ active_by_id: dict[str, SonarRule],
643
+ all_by_id: dict[str, SonarRule],
644
+ allowlist: dict[str, str],
645
+ exclude_taint: bool,
646
+ buckets: dict[str, list],
647
+ ) -> None:
648
+ if not local_rule.enabled:
649
+ return # disabled/unspecified locally: drift only if Sonar activates it (handled above)
650
+ if rule_id in active_by_id and _is_drift_relevant(active_by_id[rule_id], exclude_taint):
651
+ return
652
+ entry = _local_not_active_entry(rule_id, local_rule, active_by_id, all_by_id)
653
+ _append_allowlisted(entry, rule_id, allowlist, buckets["local_not_active"], buckets["allowlisted"])
654
+
655
+
656
+ def _sort_drift_buckets(buckets: dict[str, list]) -> None:
657
+ buckets["missing"].sort(key=sonar_sort_key)
658
+ buckets["disabled_locally"].sort(key=sonar_sort_key)
659
+ buckets["mismatches"].sort(key=sonar_sort_key)
660
+ buckets["server_only"].sort(key=sonar_sort_key)
661
+ buckets["informational_taint"].sort(key=sonar_sort_key)
662
+
663
+
664
+ def _drift_counts(
665
+ active_by_id: dict[str, SonarRule],
666
+ local: EditorconfigParse,
667
+ buckets: dict[str, list],
668
+ exclude_taint: bool,
669
+ ) -> dict:
670
+ return {
671
+ "sonar_active": len(active_by_id),
672
+ "sonar_active_mirrorable": sum(1 for r in active_by_id.values() if _is_drift_relevant(r, exclude_taint)),
673
+ "server_only_active": len(buckets["server_only"]),
674
+ "taint_excluded": len(buckets["informational_taint"]),
675
+ "local_s_rules": len(local.rules),
676
+ "local_enabled": sum(1 for r in local.rules.values() if r.enabled),
677
+ "matched": len(buckets["matched"]),
678
+ "missing_locally": len(buckets["missing"]),
679
+ "disabled_locally": len(buckets["disabled_locally"]),
680
+ "local_not_active": len(buckets["local_not_active"]),
681
+ "severity_mismatch": len(buckets["mismatches"]),
682
+ "severity_mismatch_material": sum(1 for m in buckets["mismatches"] if m["material"]),
683
+ "allowlisted": len(buckets["allowlisted"]),
684
+ }
685
+
686
+
687
+ def classify_drift(
688
+ active_rules: list[SonarRule],
689
+ all_rules: list[SonarRule],
690
+ local: EditorconfigParse,
691
+ allowlist: dict[str, str] | None = None,
692
+ severity_mode: str = "exact",
693
+ exclude_taint: bool = False,
694
+ ) -> dict:
695
+ """Classify drift for one profile. Pure function (unit-testable)."""
696
+ allowlist = allowlist or {}
697
+ # Index Sonar rules by S-id. S-ids are unique across repos today; if a
698
+ # future server duplicates one, keep the most severe and flag it.
699
+ collisions: list[dict] = []
700
+ active_by_id = _index_rules_by_id(active_rules, collisions)
701
+ all_by_id = _index_rules_by_id(all_rules, collisions)
702
+ buckets: dict[str, list] = {
703
+ "missing": [],
704
+ "disabled_locally": [],
705
+ "mismatches": [],
706
+ "server_only": [],
707
+ "informational_taint": [],
708
+ "allowlisted": [],
709
+ "matched": [],
710
+ "local_not_active": [],
711
+ }
712
+ for rule_id in sorted(active_by_id, key=rule_sort_key):
713
+ _classify_active_rule(active_by_id[rule_id], local, allowlist, severity_mode, exclude_taint, buckets)
714
+ for rule_id in sorted(local.rules, key=rule_sort_key):
715
+ _classify_local_rule(
716
+ rule_id, local.rules[rule_id], active_by_id, all_by_id, allowlist, exclude_taint, buckets
717
+ )
718
+ _sort_drift_buckets(buckets)
719
+ return {
720
+ "counts": _drift_counts(active_by_id, local, buckets, exclude_taint),
721
+ "missing_locally": buckets["missing"],
722
+ "disabled_locally": buckets["disabled_locally"],
723
+ "local_not_active": buckets["local_not_active"],
724
+ "severity_mismatches": buckets["mismatches"],
725
+ "server_only_active": buckets["server_only"],
726
+ "informational_taint": buckets["informational_taint"],
727
+ "allowlisted": buckets["allowlisted"],
728
+ "matched": sorted(buckets["matched"], key=rule_sort_key),
729
+ "id_collisions": collisions,
730
+ }
731
+
732
+
733
+ def has_drift(classified: dict, fail_on: str = "any") -> bool:
734
+ counts = classified["counts"]
735
+ presence = counts["missing_locally"] + counts["disabled_locally"] + counts["local_not_active"]
736
+ if fail_on == "never":
737
+ return False
738
+ if fail_on == "presence":
739
+ return presence > 0
740
+ if fail_on == "material":
741
+ return presence > 0 or counts["severity_mismatch_material"] > 0
742
+ return presence > 0 or counts["severity_mismatch"] > 0 # any
743
+
744
+
745
+ # ---------------------------------------------------------------------------
746
+ # Orchestration + reporting
747
+ # ---------------------------------------------------------------------------
748
+
749
+
750
+ def discover_profiles(client, projects: dict[str, str], language: str) -> list[dict]:
751
+ """Group projects by the C# profile each one actually uses."""
752
+ by_key: dict[str, dict] = {}
753
+ for name, project_key in projects.items():
754
+ profiles = client.get_project_profiles(project_key, language)
755
+ if not profiles:
756
+ raise SonarError(f"no {language} quality profile found for project {name} ({project_key})")
757
+ profile = profiles[0]
758
+ group = by_key.setdefault(profile["key"], {"profile": profile, "projects": []})
759
+ group["projects"].append({"name": name, "key": project_key})
760
+ return list(by_key.values())
761
+
762
+
763
+ def _resolve_profile_groups(client, projects: dict[str, str] | None, profile_key: str | None, language: str) -> list[dict]:
764
+ if profile_key:
765
+ matches = [p for p in client.get_profiles(language) if p.get("key") == profile_key]
766
+ if not matches:
767
+ raise SonarError(f"quality profile {profile_key} not found for language {language}")
768
+ return [{"profile": matches[0], "projects": []}]
769
+ return discover_profiles(client, projects or DEFAULT_PROJECTS, language)
770
+
771
+
772
+ def _profile_warnings(profile: dict, active_rules: list[SonarRule]) -> list[str]:
773
+ expected_count = profile.get("activeRuleCount")
774
+ if expected_count is not None and expected_count != len(active_rules):
775
+ return [
776
+ f"profile activeRuleCount={expected_count} but rules/search returned {len(active_rules)} active rules"
777
+ ]
778
+ return []
779
+
780
+
781
+ @dataclass
782
+ class DriftOptions:
783
+ """Run options for run_check (one bundle instead of eight parameters)."""
784
+
785
+ projects: dict[str, str] | None = None
786
+ profile_key: str | None = None
787
+ language: str = DEFAULT_LANGUAGE
788
+ allowlist: dict[str, str] | None = None
789
+ severity_mode: str = "exact"
790
+ fail_on: str = "any"
791
+ exclude_taint: bool = False
792
+ sonar_url: str = DEFAULT_SONAR_URL
793
+
794
+
795
+ def _profile_report(
796
+ client,
797
+ group: dict,
798
+ all_rules: list[SonarRule],
799
+ local: EditorconfigParse,
800
+ options: DriftOptions,
801
+ ) -> dict:
802
+ profile = group["profile"]
803
+ active_rules = client.get_active_rules(profile["key"], options.language)
804
+ classified = classify_drift(
805
+ active_rules,
806
+ all_rules,
807
+ local,
808
+ allowlist=options.allowlist,
809
+ severity_mode=options.severity_mode,
810
+ exclude_taint=options.exclude_taint,
811
+ )
812
+ return {
813
+ "profile": {
814
+ "key": profile.get("key"),
815
+ "name": profile.get("name"),
816
+ "language": profile.get("language"),
817
+ "languageName": profile.get("languageName"),
818
+ "isDefault": profile.get("isDefault"),
819
+ "isBuiltIn": profile.get("isBuiltIn"),
820
+ "activeRuleCount": profile.get("activeRuleCount"),
821
+ "projects": group["projects"],
822
+ },
823
+ "drift": has_drift(classified, options.fail_on),
824
+ "warnings": _profile_warnings(profile, active_rules),
825
+ **classified,
826
+ }
827
+
828
+
829
+ def _local_summary(local: EditorconfigParse) -> dict:
830
+ return {
831
+ "total_s_rules": len(local.rules),
832
+ "enabled": sum(1 for r in local.rules.values() if r.enabled),
833
+ "disabled": sum(1 for r in local.rules.values() if r.severity == "none"),
834
+ "unspecified": sum(1 for r in local.rules.values() if r.severity is None),
835
+ "non_s_diagnostics": local.non_s_diagnostics,
836
+ "duplicates": local.duplicates,
837
+ "warnings": local.warnings,
838
+ "rules": {
839
+ rid: {"severity": r.severity, "raw_severity": r.raw_severity, "line": r.line, "section": r.section}
840
+ for rid, r in sorted(local.rules.items(), key=lambda kv: rule_sort_key(kv[0]))
841
+ },
842
+ }
843
+
844
+
845
+ def run_check(client, editorconfig_path: Path, options: DriftOptions | None = None) -> dict:
846
+ options = options or DriftOptions()
847
+ local = parse_editorconfig(editorconfig_path)
848
+ groups = _resolve_profile_groups(client, options.projects, options.profile_key, options.language)
849
+ all_rules = client.get_all_rules(options.language)
850
+ profile_reports: list[dict] = []
851
+ any_drift = False
852
+ for group in groups:
853
+ report = _profile_report(client, group, all_rules, local, options)
854
+ profile_reports.append(report)
855
+ any_drift = any_drift or report["drift"]
856
+ return {
857
+ "generated_at": datetime.now(timezone.utc).isoformat(),
858
+ "sonar_url": options.sonar_url,
859
+ "editorconfig": str(editorconfig_path),
860
+ "language": options.language,
861
+ "severity_mode": options.severity_mode,
862
+ "fail_on": options.fail_on,
863
+ "exclude_taint": options.exclude_taint,
864
+ "mapping": SONAR_TO_LOCAL,
865
+ "local": _local_summary(local),
866
+ "profiles": profile_reports,
867
+ "drift": any_drift,
868
+ }
869
+
870
+
871
+ def _fmt_rule_line(entry: dict) -> str:
872
+ params = ""
873
+ if entry.get("params"):
874
+ params = " params=" + ",".join(f"{p.get('key')}={p.get('value')}" for p in entry["params"])
875
+ return (
876
+ f" {entry['id']:<8} {entry.get('sonar_severity', ''):<9} "
877
+ f"{entry.get('type', ''):<14} {entry.get('key', '')} - {entry.get('name', '')}{params}"
878
+ )
879
+
880
+
881
+ def _render_header_lines(report: dict) -> list[str]:
882
+ lines: list[str] = []
883
+ lines.append("Sonar drift check - quality profile vs editorconfig pack")
884
+ lines.append(f"Generated: {report['generated_at']}")
885
+ lines.append(f"Sonar: {report['sonar_url']} Language: {report['language']}")
886
+ lines.append(f"Editorconfig: {report['editorconfig']}")
887
+ lines.append(
888
+ "Mapping: BLOCKER/CRITICAL->error, MAJOR->warning, MINOR->suggestion, INFO->suggestion"
889
+ f" (severity-mode={report['severity_mode']}, fail-on={report['fail_on']})"
890
+ )
891
+ local = report["local"]
892
+ lines.append(
893
+ f"Local S-rules: {local['total_s_rules']} "
894
+ f"({local['enabled']} enabled, {local['disabled']} disabled, {local['unspecified']} unspecified; "
895
+ f"{local['non_s_diagnostics']} non-S diagnostics ignored)"
896
+ )
897
+ for dup in local["duplicates"]:
898
+ lines.append(f" duplicate {dup['id']} on lines {dup['lines']}; kept line {dup['kept_line']}")
899
+ for warning in local["warnings"]:
900
+ lines.append(f" warning: {warning}")
901
+ return lines
902
+
903
+
904
+ def _render_profile_header_lines(prof: dict) -> list[str]:
905
+ p = prof["profile"]
906
+ c = prof["counts"]
907
+ project_names = ", ".join(pr["name"] for pr in p["projects"]) or "(explicit profile)"
908
+ lines = ["", f"Profile: {p['name']} [{p['key']}] language={p['language']} default={p['isDefault']}"]
909
+ lines.append(f"Projects: {project_names}")
910
+ lines.append(
911
+ f"Sonar active: {c['sonar_active']} ({c['sonar_active_mirrorable']} mirrorable, "
912
+ f"{c['server_only_active']} server-only, {c['taint_excluded']} taint-excluded)"
913
+ )
914
+ lines.append(
915
+ f"Matched: {c['matched']} Missing locally: {c['missing_locally']} "
916
+ f"Disabled locally: {c['disabled_locally']} Local-not-active: {c['local_not_active']} "
917
+ f"Severity mismatches: {c['severity_mismatch']} ({c['severity_mismatch_material']} material) "
918
+ f"Allowlisted: {c['allowlisted']}"
919
+ )
920
+ for warning in prof["warnings"]:
921
+ lines.append(f" warning: {warning}")
922
+ return lines
923
+
924
+
925
+ def _append_rule_section(lines: list[str], heading: str, entries: list[dict]) -> None:
926
+ if entries:
927
+ lines.append(heading)
928
+ lines.extend(_fmt_rule_line(e) for e in entries)
929
+
930
+
931
+ def _append_local_not_active(lines: list[str], entries: list[dict]) -> None:
932
+ if not entries:
933
+ return
934
+ lines.append(f"\n(b) Local but inactive/absent in Sonar ({len(entries)}):")
935
+ for e in entries:
936
+ lines.append(
937
+ f" {e['id']:<8} local={e['actual_local']:<11} state={e['state']:<22} "
938
+ f"line={e['local_line']} {e.get('key', '')} {e.get('name', '')}".rstrip()
939
+ )
940
+
941
+
942
+ def _append_severity_mismatches(lines: list[str], entries: list[dict]) -> None:
943
+ if not entries:
944
+ return
945
+ lines.append(f"\n(c) Severity mismatches ({len(entries)}):")
946
+ for e in entries:
947
+ material = "material" if e["material"] else "non-material (same build-gate class)"
948
+ lines.append(
949
+ f" {e['id']:<8} sonar={e['sonar_severity']:<9} expected={e['expected_local']:<11} "
950
+ f"actual={e['actual_local']:<11} {e['direction']:<16} {material} - {e['name']}"
951
+ )
952
+
953
+
954
+ def _append_allowlisted_section(lines: list[str], entries: list[dict]) -> None:
955
+ if not entries:
956
+ return
957
+ lines.append(f"\nAllowlisted intentional drift ({len(entries)}):")
958
+ for e in entries:
959
+ lines.append(f" {e['id']:<8} {e.get('allowlist_reason', '')} ({e.get('name', e.get('state', ''))})")
960
+
961
+
962
+ def _append_matched(lines: list[str], matched: list[str]) -> None:
963
+ if matched:
964
+ lines.append(f"\nMatched ({len(matched)}): {', '.join(matched)}")
965
+
966
+
967
+ def _append_profile_detail(lines: list[str], prof: dict) -> None:
968
+ _append_rule_section(
969
+ lines, f"\n(a) Active in Sonar, missing locally ({len(prof['missing_locally'])}):", prof["missing_locally"]
970
+ )
971
+ _append_rule_section(
972
+ lines,
973
+ f"\n(a2) Active in Sonar, disabled locally (none/silent) ({len(prof['disabled_locally'])}):",
974
+ prof["disabled_locally"],
975
+ )
976
+ _append_local_not_active(lines, prof["local_not_active"])
977
+ _append_severity_mismatches(lines, prof["severity_mismatches"])
978
+ _append_rule_section(
979
+ lines,
980
+ f"\nServer-only active rules, excluded from drift ({len(prof['server_only_active'])}):",
981
+ prof["server_only_active"],
982
+ )
983
+ _append_rule_section(
984
+ lines,
985
+ f"\nTaint rules excluded by --exclude-taint ({len(prof['informational_taint'])}):",
986
+ prof["informational_taint"],
987
+ )
988
+ _append_allowlisted_section(lines, prof["allowlisted"])
989
+ _append_matched(lines, prof["matched"])
990
+
991
+
992
+ def _render_profile_lines(prof: dict, summary_only: bool) -> list[str]:
993
+ lines = _render_profile_header_lines(prof)
994
+ if summary_only:
995
+ return lines
996
+ _append_profile_detail(lines, prof)
997
+ return lines
998
+
999
+
1000
+ def render_text(report: dict, summary_only: bool = False) -> str:
1001
+ lines = _render_header_lines(report)
1002
+ for prof in report["profiles"]:
1003
+ lines.extend(_render_profile_lines(prof, summary_only))
1004
+ lines.append("")
1005
+ lines.append("VERDICT: DRIFT" if report["drift"] else "VERDICT: CLEAN")
1006
+ lines.append(
1007
+ "Note: 'missing locally' means the severity is unpinned in .editorconfig; "
1008
+ "SonarAnalyzer.CSharp defaults may still fire in build. Pinning makes intent explicit."
1009
+ )
1010
+ return "\n".join(lines) + "\n"
1011
+
1012
+
1013
+ # ---------------------------------------------------------------------------
1014
+ # CLI
1015
+ # ---------------------------------------------------------------------------
1016
+
1017
+
1018
+ def default_editorconfig_path() -> Path:
1019
+ here = Path(__file__).resolve().parent
1020
+ candidate = here.parent / "editorconfig-pack" / ".editorconfig"
1021
+ if candidate.exists():
1022
+ return candidate
1023
+ return Path("editorconfig-pack/.editorconfig")
1024
+
1025
+
1026
+ def parse_projects(values: list[str] | None) -> dict[str, str]:
1027
+ if not values:
1028
+ return dict(DEFAULT_PROJECTS)
1029
+ projects: dict[str, str] = {}
1030
+ for value in values:
1031
+ for item in value.split(","):
1032
+ item = item.strip()
1033
+ if not item:
1034
+ continue
1035
+ if "=" in item:
1036
+ name, _, key = item.partition("=")
1037
+ projects[name.strip()] = key.strip()
1038
+ else:
1039
+ projects[item] = item
1040
+ return projects
1041
+
1042
+
1043
+ def build_arg_parser() -> argparse.ArgumentParser:
1044
+ parser = argparse.ArgumentParser(
1045
+ description="Compare SonarQube C# quality profile severities with editorconfig-pack/.editorconfig."
1046
+ )
1047
+ parser.add_argument("--sonar-url", default=DEFAULT_SONAR_URL, help=f"Sonar base URL (default {DEFAULT_SONAR_URL})")
1048
+ parser.add_argument("--editorconfig", default=None, help="Path to .editorconfig (default ../editorconfig-pack/.editorconfig)")
1049
+ parser.add_argument(
1050
+ "--projects",
1051
+ action="append",
1052
+ default=None,
1053
+ help="Project keys, comma-separated, optionally NAME=KEY. Repeatable. Default: Essentials, Libraries.V1, MarketPulse, Sql.",
1054
+ )
1055
+ parser.add_argument("--profile-key", default=None, help="Check this profile key directly instead of discovering per project")
1056
+ parser.add_argument("--language", default=DEFAULT_LANGUAGE, help="Sonar language key (default cs)")
1057
+ parser.add_argument("--json", action="store_true", help="Print JSON report to stdout instead of text")
1058
+ parser.add_argument("--output-json", default=None, help="Also write the JSON report to this path")
1059
+ parser.add_argument("--output-text", default=None, help="Also write the text report to this path")
1060
+ parser.add_argument("--summary-only", action="store_true", help="Text output: counts only, no rule lists")
1061
+ parser.add_argument("--allowlist", default=None, help="Allowlist file (JSON {id: reason} or text lines) of intentional drift")
1062
+ parser.add_argument(
1063
+ "--severity-mode",
1064
+ choices=["exact", "class"],
1065
+ default="exact",
1066
+ help="exact: local must equal mapped severity. class: error/warning count as one blocking class (TreatWarningsAsErrors).",
1067
+ )
1068
+ parser.add_argument(
1069
+ "--fail-on",
1070
+ choices=["any", "presence", "material", "never"],
1071
+ default="any",
1072
+ help="What counts as drift for exit 1 (default any)",
1073
+ )
1074
+ parser.add_argument("--exclude-taint", action="store_true", help="Treat taint/security rules as informational, not drift")
1075
+ parser.add_argument("--auth", choices=["auto", "surrogate", "env", "none"], default="auto", help="Auth mode (default auto)")
1076
+ parser.add_argument("--token-env", default="SONAR_TOKEN", help="Env var holding the Sonar token for --auth env/auto (default SONAR_TOKEN)")
1077
+ parser.add_argument("--timeout", type=int, default=30, help="HTTP timeout seconds (default 30)")
1078
+ return parser
1079
+
1080
+
1081
+ def main(argv: list[str] | None = None, client=None) -> int:
1082
+ args = build_arg_parser().parse_args(argv)
1083
+ editorconfig_path = Path(args.editorconfig) if args.editorconfig else default_editorconfig_path()
1084
+ try:
1085
+ if not editorconfig_path.exists():
1086
+ raise SonarError(f"editorconfig not found: {editorconfig_path}")
1087
+ allowlist = load_allowlist(Path(args.allowlist)) if args.allowlist else {}
1088
+ if client is None:
1089
+ client = SonarClient(
1090
+ base_url=args.sonar_url, auth=args.auth, token_env=args.token_env, timeout=args.timeout
1091
+ )
1092
+ report = run_check(
1093
+ client,
1094
+ editorconfig_path,
1095
+ DriftOptions(
1096
+ projects=parse_projects(args.projects),
1097
+ profile_key=args.profile_key,
1098
+ language=args.language,
1099
+ allowlist=allowlist,
1100
+ severity_mode=args.severity_mode,
1101
+ fail_on=args.fail_on,
1102
+ exclude_taint=args.exclude_taint,
1103
+ sonar_url=args.sonar_url,
1104
+ ),
1105
+ )
1106
+ except (SonarError, OSError, ValueError) as exc:
1107
+ print(f"error: {exc}", file=sys.stderr)
1108
+ return 2
1109
+
1110
+ text = render_text(report, summary_only=args.summary_only)
1111
+ if args.output_text:
1112
+ write_text_under(args.output_text, Path.cwd(), text)
1113
+ if args.output_json:
1114
+ write_text_under(args.output_json, Path.cwd(), json.dumps(report, indent=2) + "\n")
1115
+ if args.json:
1116
+ print(json.dumps(report, indent=2))
1117
+ else:
1118
+ print(text, end="")
1119
+ return 1 if report["drift"] else 0
1120
+
1121
+
1122
+ if __name__ == "__main__":
1123
+ raise SystemExit(main())