Coverage for src/governed_harness/forges/codequality.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""The findings of a run as a GitLab Code Quality report (#56). 

2 

3GitLab shows a Code Quality report (``artifacts:reports:codequality`` in ``.gitlab-ci.yml``) in 

4the merge request widget and the diff. The format is a JSON array of issues with a description, 

5a check name, a fingerprint, a severity (``info``, ``minor``, ``major``, ``critical``, 

6``blocker``) and a location (path and begin line). The fingerprint is the finding's stable 

7fingerprint (``harnessFinding/v1``), the same one the SARIF report carries, so the widget 

8tracks one problem across pipelines. Findings without a path are reported on the repository 

9root, as GitLab needs a path.""" 

10 

11from __future__ import annotations 

12 

13import json 

14from collections.abc import Iterable 

15from typing import Any 

16 

17from governed_harness.domain.models import Finding 

18from governed_harness.reporting.fingerprint import finding_fingerprint 

19 

20CODE_QUALITY_FILE = "gl-code-quality-report.json" 

21"""The file name the CI templates attach as ``artifacts:reports:codequality``.""" 

22 

23_SEVERITY = { 

24 "INFO": "info", 

25 "LOW": "minor", 

26 "MEDIUM": "major", 

27 "HIGH": "critical", 

28 "CRITICAL": "blocker", 

29} 

30 

31 

32def code_quality_issues(findings: Iterable[Finding]) -> list[dict[str, Any]]: 

33 issues: list[dict[str, Any]] = [] 

34 for finding in findings: 

35 location = finding.location 

36 path = location.path if location and location.path else "." 

37 line = location.start_line if location and location.start_line else 1 

38 issues.append( 

39 { 

40 "type": "issue", 

41 "check_name": finding.rule_id, 

42 "description": finding.message, 

43 "categories": [finding.category or "Style"], 

44 "severity": _SEVERITY.get(str(finding.severity), "info"), 

45 "fingerprint": finding_fingerprint(finding).removeprefix("sha256:"), 

46 "location": {"path": path, "lines": {"begin": line}}, 

47 } 

48 ) 

49 return issues 

50 

51 

52def render_code_quality(findings: Iterable[Finding]) -> bytes: 

53 return (json.dumps(code_quality_issues(findings), indent=2, ensure_ascii=False) + "\n").encode( 

54 "utf-8" 

55 ) 

56 

57 

58__all__ = ["CODE_QUALITY_FILE", "code_quality_issues", "render_code_quality"]