-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathcode_quality.py
More file actions
1128 lines (996 loc) · 40.5 KB
/
Copy pathcode_quality.py
File metadata and controls
1128 lines (996 loc) · 40.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Code quality assessors for complexity, file length, type annotations, and code smells."""
import ast
import logging
import re
import tomllib
from ..models.attribute import Attribute
from ..models.finding import Citation, Finding, Remediation
from ..models.repository import Repository
from ..services.scanner import MissingToolError
from ..utils.subprocess_utils import safe_subprocess_run
from .base import BaseAssessor
logger = logging.getLogger(__name__)
class TypeAnnotationsAssessor(BaseAssessor):
"""Assesses type annotation coverage in code.
Tier 1 Essential (10% weight) - Type hints are critical for AI understanding.
"""
@property
def attribute_id(self) -> str:
return "type_annotations"
@property
def tier(self) -> int:
return 1 # Essential
@property
def attribute(self) -> Attribute:
return Attribute(
id=self.attribute_id,
name="Type Annotations",
category="Code Quality",
tier=self.tier,
description="Type hints in function signatures",
criteria=">80% of functions have type annotations",
default_weight=0.08,
)
def is_applicable(self, repository: Repository) -> bool:
"""Only applicable to statically-typed or type-hinted languages."""
applicable_languages = {
"Python",
"TypeScript",
"Java",
"C#",
"Kotlin",
"Go",
"Rust",
}
return bool(set(repository.languages.keys()) & applicable_languages)
def assess(self, repository: Repository) -> Finding:
"""Check type annotation coverage.
Dispatches based on the primary programming language (by file count)
to handle multi-language repos correctly.
"""
primary = self._primary_language(repository, {"Python", "TypeScript", "Go"})
if primary == "Python":
return self._assess_python_types(repository)
elif primary == "TypeScript":
return self._assess_typescript_types(repository)
elif primary == "Go":
return self._assess_go_types(repository)
else:
return Finding.not_applicable(
self.attribute,
reason=f"Type annotation check not implemented for {list(repository.languages.keys())}",
)
def _assess_python_types(self, repository: Repository) -> Finding:
"""Assess Python type annotations using AST parsing.
Checks both annotation coverage (current state) and strict mode
configuration (prevents new violations). Both matter — strict mode
stops new untyped code from entering; coverage measures what's already
typed.
"""
# Use AST parsing to accurately detect type annotations
try:
# Security: Use safe_subprocess_run for validation and limits
result = safe_subprocess_run(
["git", "ls-files", "*.py"],
cwd=repository.path,
capture_output=True,
text=True,
timeout=30,
check=True,
)
python_files = [f for f in result.stdout.strip().split("\n") if f]
except Exception:
python_files = [
str(f.relative_to(repository.path))
for f in repository.path.rglob("*.py")
]
total_functions = 0
typed_functions = 0
for file_path in python_files:
full_path = repository.path / file_path
try:
with open(full_path, "r", encoding="utf-8") as f:
content = f.read()
# Parse the file with AST
tree = ast.parse(content, filename=str(file_path))
# Walk the AST and count functions with type annotations
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
total_functions += 1
# Check if function has type annotations
# Return type annotation: node.returns is not None
# Parameter annotations: any arg has annotation
has_return_annotation = node.returns is not None
has_param_annotations = any(
arg.annotation is not None for arg in node.args.args
)
# Consider function typed if it has either return or param annotations
if has_return_annotation or has_param_annotations:
typed_functions += 1
except (OSError, UnicodeDecodeError, SyntaxError):
# Skip files that can't be read or parsed
continue
if total_functions == 0:
return Finding.not_applicable(
self.attribute, reason="No Python functions found"
)
coverage_percent = (typed_functions / total_functions) * 100
# Check for strict mode configuration (mypy/pyright)
strict_mode = self._check_strict_mode(repository)
# Score combines coverage (up to 80 pts) + strict mode bonus (up to 20 pts)
coverage_score = self.calculate_proportional_score(
measured_value=coverage_percent,
threshold=80.0,
higher_is_better=True,
)
score = min(100.0, coverage_score + (20.0 if strict_mode else 0.0))
status = "pass" if score >= 75 else "fail"
evidence = [
f"Typed functions: {typed_functions}/{total_functions}",
f"Coverage: {coverage_percent:.1f}%",
]
if strict_mode:
evidence.append("Strict mode configured")
else:
evidence.append("No strict mode configuration found")
return Finding(
attribute=self.attribute,
status=status,
score=score,
measured_value=f"{coverage_percent:.1f}%",
threshold="≥80% coverage + strict mode",
evidence=evidence,
remediation=self._create_remediation() if status == "fail" else None,
error_message=None,
)
@staticmethod
def _check_strict_mode(repository: Repository) -> bool:
"""Check whether the Python type checker is configured in strict mode.
Looks for mypy/pyright strict mode configuration in pyproject.toml,
mypy.ini, setup.cfg, or pyrightconfig.json.
ADR A.6: Strict mode prevents new violations; coverage measures
current state. Both matter.
"""
# Check pyproject.toml for mypy/pyright strict config
pyproject_path = repository.path / "pyproject.toml"
if pyproject_path.exists():
try:
with open(pyproject_path, "rb") as f:
data = tomllib.load(f)
# mypy: [tool.mypy] strict = true
tool = data.get("tool", {})
mypy_cfg = tool.get("mypy", {})
if mypy_cfg.get("strict", False):
return True
if "disallow_untyped_defs" in mypy_cfg and mypy_cfg[
"disallow_untyped_defs"
]:
return True
# pyright: [tool.pyright] strict = true
pyright_cfg = tool.get("pyright", {})
if pyright_cfg.get("strict", False):
return True
except (OSError, tomllib.TOMLDecodeError):
pass
# Check mypy.ini
mypy_ini_path = repository.path / "mypy.ini"
if mypy_ini_path.exists():
try:
content = mypy_ini_path.read_text(encoding="utf-8")
if "[mypy]" in content:
for line in content.splitlines():
stripped = line.strip().lower()
if stripped == "strict = true" or stripped == "strict=true":
return True
if stripped.startswith("disallow_untyped_defs"):
return True
except OSError:
pass
# Check setup.cfg
setup_cfg_path = repository.path / "setup.cfg"
if setup_cfg_path.exists():
try:
content = setup_cfg_path.read_text(encoding="utf-8")
if "[mypy]" in content or "[mypy]" in content.lower():
for line in content.splitlines():
stripped = line.strip().lower()
if "strict = true" in stripped or "strict=true" in stripped:
return True
if stripped.startswith("disallow_untyped_defs"):
return True
except OSError:
pass
# Check pyrightconfig.json
pyright_path = repository.path / "pyrightconfig.json"
if pyright_path.exists():
try:
import json
content = json.loads(pyright_path.read_text(encoding="utf-8"))
if content.get("typeCheckingMode", "") == "strict":
return True
if content.get("strict", False):
return True
except (json.JSONDecodeError, OSError):
pass
return False
def _assess_typescript_types(self, repository: Repository) -> Finding:
"""Assess TypeScript type configuration across all tsconfig.json files.
Supports monorepos with per-package tsconfig.json and JSONC comments.
"""
import json
tsconfig_files = self._find_tsconfig_files(repository)
if not tsconfig_files:
return Finding(
attribute=self.attribute,
status="fail",
score=0.0,
measured_value="missing tsconfig.json",
threshold="strict mode enabled",
evidence=["tsconfig.json not found"],
remediation=self._create_remediation(),
error_message=None,
)
strict_count = 0
total_count = 0
evidence: list[str] = []
for tsconfig_path in tsconfig_files:
rel_path = str(tsconfig_path.relative_to(repository.path))
total_count += 1
try:
raw = tsconfig_path.read_text(encoding="utf-8")
cleaned = self._strip_json_comments(raw)
tsconfig = json.loads(cleaned)
except (OSError, json.JSONDecodeError) as e:
evidence.append(f"{rel_path}: parse error ({e})")
continue
strict = tsconfig.get("compilerOptions", {}).get("strict", False)
if strict:
strict_count += 1
evidence.append(f"{rel_path}: strict: true")
else:
evidence.append(f"{rel_path}: strict mode disabled")
score = self.calculate_proportional_score(
measured_value=(strict_count / total_count) * 100,
threshold=100.0,
higher_is_better=True,
)
status = "pass" if strict_count == total_count else "fail"
return Finding(
attribute=self.attribute,
status=status,
score=score,
measured_value=f"{strict_count}/{total_count} strict",
threshold="all tsconfig.json files strict",
evidence=evidence,
remediation=self._create_remediation() if status == "fail" else None,
error_message=None,
)
@staticmethod
def _strip_go_non_code(content: str) -> str:
"""Strip comments and string literal contents from Go source.
Preserves line structure so line-anchored regexes still work.
"""
out = []
i = 0
n = len(content)
while i < n:
c = content[i]
# Block comment
if c == "/" and i + 1 < n and content[i + 1] == "*":
i += 2
while i + 1 < n and not (content[i] == "*" and content[i + 1] == "/"):
out.append("\n" if content[i] == "\n" else " ")
i += 1
out.append(" ") # *
i += 1
if i < n:
out.append(" ") # /
i += 1
continue
# Line comment
if c == "/" and i + 1 < n and content[i + 1] == "/":
i += 2
while i < n and content[i] != "\n":
i += 1
continue
# Double-quoted string
if c == '"':
out.append(c)
i += 1
while i < n and content[i] != '"':
if content[i] == "\\" and i + 1 < n:
out.append(" ")
out.append(" ")
i += 2
else:
out.append(" ")
i += 1
if i < n:
out.append(c)
i += 1
continue
# Raw string (backtick)
if c == "`":
out.append(c)
i += 1
while i < n and content[i] != "`":
out.append("\n" if content[i] == "\n" else " ")
i += 1
if i < n:
out.append(c)
i += 1
continue
out.append(c)
i += 1
return "".join(out)
@staticmethod
def _strip_json_comments(text: str) -> str:
"""Strip // and /* */ comments from JSONC, preserving string contents."""
out: list[str] = []
i = 0
n = len(text)
while i < n:
c = text[i]
if c == '"':
out.append(c)
i += 1
while i < n and text[i] != '"':
if text[i] == "\\" and i + 1 < n:
out.append(text[i])
out.append(text[i + 1])
i += 2
else:
out.append(text[i])
i += 1
if i < n:
out.append(text[i])
i += 1
continue
if c == "/" and i + 1 < n and text[i + 1] == "/":
i += 2
while i < n and text[i] != "\n":
i += 1
continue
if c == "/" and i + 1 < n and text[i + 1] == "*":
i += 2
while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"):
i += 1
i += 2
continue
out.append(c)
i += 1
return "".join(out)
def _find_tsconfig_files(self, repository: Repository) -> list:
"""Find all tsconfig.json files, excluding node_modules/vendor/testdata."""
found = []
for tsconfig in repository.path.rglob("tsconfig.json"):
parts = tsconfig.parts
if "node_modules" in parts or "vendor" in parts or "testdata" in parts:
continue
found.append(tsconfig)
return sorted(found)
def _assess_go_types(self, repository: Repository) -> Finding:
"""Assess Go type safety.
Go is statically typed at compile time. Score starts at 100 and
deducts for excessive use of interface{}/any which weakens type safety.
"""
from ..utils.subprocess_utils import safe_subprocess_run
try:
result = safe_subprocess_run(
["git", "ls-files", "*.go"],
cwd=repository.path,
capture_output=True,
text=True,
timeout=30,
check=True,
)
go_files = [
f
for f in result.stdout.strip().split("\n")
if f and not f.endswith("_test.go")
]
except Exception:
go_files = [
str(f.relative_to(repository.path))
for f in repository.path.rglob("*.go")
if not f.name.endswith("_test.go")
]
if not go_files:
return Finding.not_applicable(
self.attribute, reason="No Go source files found"
)
total_funcs = 0
any_usage_count = 0
for file_path in go_files:
full_path = repository.path / file_path
try:
content = full_path.read_text(encoding="utf-8")
code_content = self._strip_go_non_code(content)
total_funcs += len(re.findall(r"^func\s+", code_content, re.MULTILINE))
any_usage_count += len(
re.findall(r"\binterface\s*\{\s*\}|\bany\b", code_content)
)
except (OSError, UnicodeDecodeError):
continue
evidence = ["Go enforces types at compile time (statically typed)"]
if total_funcs == 0:
score = 100.0
elif any_usage_count == 0:
score = 100.0
evidence.append("No interface{}/any usage found — strong type safety")
else:
ratio = any_usage_count / max(total_funcs, 1)
if ratio < 0.1:
score = 95.0
evidence.append(
f"Minimal interface{{}}/any usage: {any_usage_count} occurrences"
)
elif ratio < 0.25:
score = 85.0
evidence.append(
f"Moderate interface{{}}/any usage: {any_usage_count} occurrences"
)
else:
score = 70.0
evidence.append(
f"Heavy interface{{}}/any usage: {any_usage_count} occurrences — consider using generics"
)
return Finding(
attribute=self.attribute,
status="pass" if score >= 75 else "fail",
score=score,
measured_value=f"{score:.0f}%",
threshold="≥80%",
evidence=evidence,
remediation=None,
error_message=None,
)
def _create_remediation(self) -> Remediation:
"""Create remediation guidance for type annotations."""
return Remediation(
summary="Add type annotations to function signatures",
steps=[
"For Python: Add type hints to function parameters and return types",
"For TypeScript: Enable strict mode in tsconfig.json",
"Use mypy or pyright for Python type checking",
"Use tsc --strict for TypeScript",
"Add type annotations gradually to existing code",
],
tools=["mypy", "pyright", "typescript"],
commands=[
"# Python",
"pip install mypy",
"mypy --strict src/",
"",
"# TypeScript",
"npm install --save-dev typescript",
'echo \'{"compilerOptions": {"strict": true}}\' > tsconfig.json',
],
examples=[
"""# Python - Before
def calculate(x, y):
return x + y
# Python - After
def calculate(x: float, y: float) -> float:
return x + y
""",
"""// TypeScript - tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}
""",
],
citations=[
Citation(
source="Python.org",
title="Type Hints",
url="https://docs.python.org/3/library/typing.html",
relevance="Official Python type hints documentation",
),
Citation(
source="TypeScript",
title="TypeScript Handbook",
url="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html",
relevance="TypeScript type system guide",
),
],
)
class CyclomaticComplexityAssessor(BaseAssessor):
"""Assesses cyclomatic complexity using radon."""
@property
def attribute_id(self) -> str:
return "cyclomatic_complexity"
@property
def tier(self) -> int:
return 3 # Important
@property
def attribute(self) -> Attribute:
return Attribute(
id=self.attribute_id,
name="Cyclomatic Complexity Thresholds",
category="Code Quality",
tier=self.tier,
description="Cyclomatic complexity thresholds enforced",
criteria="Average complexity <10, no functions >15",
default_weight=0.02,
)
def is_applicable(self, repository: Repository) -> bool:
"""Applicable to languages supported by radon, lizard, or gocyclo."""
supported = {"Python", "JavaScript", "TypeScript", "C", "C++", "Java", "Go"}
return bool(set(repository.languages.keys()) & supported)
def assess(self, repository: Repository) -> Finding:
"""Check cyclomatic complexity using radon, lizard, or gocyclo."""
primary = self._primary_language(repository, {"Python", "Go"})
if primary == "Python":
return self._assess_python_complexity(repository)
elif primary == "Go":
return self._assess_go_complexity(repository)
else:
return self._assess_with_lizard(repository)
def _assess_python_complexity(self, repository: Repository) -> Finding:
"""Assess Python complexity using radon."""
try:
# Check if radon is available
# Security: Use safe_subprocess_run for validation and limits
result = safe_subprocess_run(
["radon", "cc", str(repository.path), "-s", "-a"],
capture_output=True,
text=True,
timeout=60,
)
if result.returncode != 0:
raise MissingToolError("radon", install_command="pip install radon")
# Parse radon output for average complexity
# Output format: "Average complexity: A (5.2)"
output = result.stdout
if "Average complexity:" in output:
# Extract average value
avg_line = [
line for line in output.split("\n") if "Average complexity:" in line
][0]
avg_value = float(avg_line.split("(")[1].split(")")[0])
score = self.calculate_proportional_score(
measured_value=avg_value,
threshold=10.0,
higher_is_better=False,
)
status = "pass" if score >= 75 else "fail"
return Finding(
attribute=self.attribute,
status=status,
score=score,
measured_value=f"{avg_value:.1f}",
threshold="<10.0",
evidence=[f"Average cyclomatic complexity: {avg_value:.1f}"],
remediation=(
self._create_remediation() if status == "fail" else None
),
error_message=None,
)
else:
return Finding.not_applicable(
self.attribute, reason="No Python code to analyze"
)
except FileNotFoundError:
# radon command not found
raise MissingToolError("radon", install_command="pip install radon")
except MissingToolError:
raise # Re-raise to be caught by Scanner
except Exception as e:
return Finding.error(
self.attribute, reason=f"Complexity analysis failed: {str(e)}"
)
def _assess_with_lizard(self, repository: Repository) -> Finding:
"""Assess complexity using lizard (multi-language)."""
try:
# Security: Use safe_subprocess_run for validation and limits
result = safe_subprocess_run(
["lizard", str(repository.path)],
capture_output=True,
text=True,
timeout=60,
)
if result.returncode != 0:
raise MissingToolError("lizard", install_command="pip install lizard")
# Parse lizard output
# This is simplified - production code should parse properly
return Finding.not_applicable(
self.attribute, reason="Lizard analysis not fully implemented"
)
except FileNotFoundError:
# lizard command not found
raise MissingToolError("lizard", install_command="pip install lizard")
except MissingToolError:
raise
except Exception as e:
return Finding.error(
self.attribute, reason=f"Complexity analysis failed: {str(e)}"
)
def _assess_go_complexity(self, repository: Repository) -> Finding:
"""Assess Go complexity using gocyclo or golangci-lint config detection.
Tries gocyclo first. Falls back to checking if golangci-lint has
complexity linters (gocyclo/cyclop) enabled in config.
"""
try:
result = safe_subprocess_run(
["gocyclo", "-avg", str(repository.path)],
capture_output=True,
text=True,
timeout=60,
)
if result.returncode == 0 and result.stdout.strip():
lines = result.stdout.strip().split("\n")
avg_line = [line for line in lines if "Average" in line]
if avg_line:
avg_value = float(avg_line[0].split()[-1])
score = self.calculate_proportional_score(
measured_value=avg_value,
threshold=10.0,
higher_is_better=False,
)
status = "pass" if score >= 75 else "fail"
return Finding(
attribute=self.attribute,
status=status,
score=score,
measured_value=f"{avg_value:.1f}",
threshold="<10.0",
evidence=[
f"Average cyclomatic complexity (gocyclo): {avg_value:.1f}"
],
remediation=(
self._create_go_complexity_remediation()
if status == "fail"
else None
),
error_message=None,
)
except (FileNotFoundError, Exception):
pass
# Fallback: check if golangci-lint has complexity linters configured
# Search root and Go module root directories
search_dirs = [repository.path] + self._find_go_module_roots(repository)
for search_dir in search_dirs:
for config_name in [
".golangci.yml",
".golangci.yaml",
".golangci.toml",
]:
config_path = search_dir / config_name
if config_path.exists():
try:
content = config_path.read_text(encoding="utf-8")
has_complexity = bool(
re.search(r"\b(gocyclo|cyclop|gocognit)\b", content)
)
if has_complexity:
rel = config_path.relative_to(repository.path)
return Finding(
attribute=self.attribute,
status="pass",
score=80.0,
measured_value="configured",
threshold="complexity linter enabled",
evidence=[f"Complexity linter configured in {rel}"],
remediation=None,
error_message=None,
)
except (OSError, UnicodeDecodeError):
continue
raise MissingToolError(
"gocyclo",
install_command="go install github.com/fzipp/gocyclo/cmd/gocyclo@latest",
)
def _create_go_complexity_remediation(self) -> Remediation:
"""Create remediation guidance for Go complexity."""
return Remediation(
summary="Reduce cyclomatic complexity in Go functions",
steps=[
"Identify functions with complexity >15",
"Break complex functions into smaller, focused functions",
"Use early returns to reduce nesting",
"Extract switch/case logic into separate functions or maps",
],
tools=["gocyclo", "golangci-lint"],
commands=[
"go install github.com/fzipp/gocyclo/cmd/gocyclo@latest",
"gocyclo -over 15 .",
],
examples=[],
citations=[
Citation(
source="Go Community",
title="gocyclo - Cyclomatic Complexity for Go",
url="https://github.com/fzipp/gocyclo",
relevance="Go cyclomatic complexity analysis tool",
)
],
)
def _create_remediation(self) -> Remediation:
"""Create remediation guidance for high complexity."""
return Remediation(
summary="Reduce cyclomatic complexity by refactoring complex functions",
steps=[
"Identify functions with complexity >15",
"Break down complex functions into smaller functions",
"Extract conditional logic into separate functions",
"Use early returns to reduce nesting",
"Consider using strategy pattern for complex conditionals",
],
tools=["radon", "lizard"],
commands=[
"# Install radon",
"pip install radon",
"",
"# Check complexity",
"radon cc src/ -s -a",
"",
"# Find high complexity functions",
"radon cc src/ -n C",
],
examples=[],
citations=[
Citation(
source="Microsoft",
title="Code Metrics - Cyclomatic Complexity",
url="https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-cyclomatic-complexity",
relevance="Explanation of cyclomatic complexity and thresholds",
)
],
)
class StructuredLoggingAssessor(BaseAssessor):
"""Assesses use of structured logging libraries.
Tier 3 Important (2% weight) - Structured logs are machine-parseable
and enable AI to analyze logs for debugging and optimization.
"""
@property
def attribute_id(self) -> str:
return "structured_logging"
@property
def tier(self) -> int:
return 3 # Important
@property
def attribute(self) -> Attribute:
return Attribute(
id=self.attribute_id,
name="Structured Logging",
category="Code Quality",
tier=self.tier,
description="Logging in structured format (JSON) with consistent fields",
criteria="Structured logging library configured (structlog, winston, zap)",
default_weight=0.02,
)
def is_applicable(self, repository: Repository) -> bool:
"""Applicable to any code repository."""
return len(repository.languages) > 0
def assess(self, repository: Repository) -> Finding:
"""Check for structured logging library usage."""
primary = self._primary_language(repository, {"Python", "Go"})
if primary == "Python":
return self._assess_python_logging(repository)
elif primary == "Go":
return self._assess_go_logging(repository)
else:
return Finding.not_applicable(
self.attribute,
reason=f"Structured logging check not implemented for {list(repository.languages.keys())}",
)
def _assess_python_logging(self, repository: Repository) -> Finding:
"""Check for Python structured logging libraries."""
# Libraries to check for
structured_libs = ["structlog", "python-json-logger", "structlog-sentry"]
# Check dependency files
dep_files = [
repository.path / "pyproject.toml",
repository.path / "requirements.txt",
repository.path / "setup.py",
]
found_libs = []
checked_files = []
for dep_file in dep_files:
if not dep_file.exists():
continue
checked_files.append(dep_file.name)
try:
content = dep_file.read_text(encoding="utf-8")
for lib in structured_libs:
if lib in content:
found_libs.append(lib)
except (OSError, UnicodeDecodeError):
continue
if not checked_files:
return Finding.not_applicable(
self.attribute, reason="No Python dependency files found"
)
# Score: Binary - either has structured logging or not
if found_libs:
score = 100.0
status = "pass"
evidence = [
f"Structured logging library found: {', '.join(set(found_libs))}",
f"Checked files: {', '.join(checked_files)}",
]
remediation = None
else:
score = 0.0
status = "fail"
evidence = [
"No structured logging library found",
f"Checked files: {', '.join(checked_files)}",
"Using built-in logging module (unstructured)",
]
remediation = self._create_remediation()
return Finding(
attribute=self.attribute,
status=status,
score=score,
measured_value="configured" if found_libs else "not configured",
threshold="structured logging library",
evidence=evidence,
remediation=remediation,
error_message=None,
)
def _assess_go_logging(self, repository: Repository) -> Finding:
"""Check for Go structured logging libraries in go.mod and source."""
go_structured_libs = {
"go.uber.org/zap": "zap",
"github.com/sirupsen/logrus": "logrus",
"github.com/rs/zerolog": "zerolog",
"golang.org/x/exp/slog": "slog (experimental)",
}
found_libs = []
module_roots = self._find_go_module_roots(repository)
if not module_roots:
return Finding.not_applicable(self.attribute, reason="No go.mod found")
for root in module_roots:
try:
mod_content = (root / "go.mod").read_text(encoding="utf-8")
for lib_path, lib_name in go_structured_libs.items():
if lib_path in mod_content:
found_libs.append(lib_name)
except (OSError, UnicodeDecodeError):
pass
# Check for stdlib log/slog (Go 1.21+, no go.mod entry needed)
if not found_libs:
from ..utils.subprocess_utils import safe_subprocess_run
try:
result = safe_subprocess_run(
["git", "ls-files", "*.go"],
cwd=repository.path,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0:
for f in result.stdout.strip().split("\n"):
if not f or f.endswith("_test.go"):
continue
try:
content = (repository.path / f).read_text(encoding="utf-8")
if '"log/slog"' in content:
found_libs.append("slog (stdlib)")
break
except (OSError, UnicodeDecodeError):