|
| 1 | +# Inspired by https://github.com/soul-catcher/mypy-gitlab-code-quality |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import re |
| 7 | +from base64 import b64encode |
| 8 | +from collections.abc import Hashable, Sequence |
| 9 | +from sys import byteorder, hash_info, stdin |
| 10 | +from typing import TextIO |
| 11 | + |
| 12 | + |
| 13 | +def get_hash(tpl: Sequence[Hashable]) -> str: |
| 14 | + return b64encode( |
| 15 | + hash(tpl).to_bytes(hash_info.width // 8, byteorder, signed=True) |
| 16 | + ).decode() |
| 17 | + |
| 18 | + |
| 19 | +def append_line_to_issues( |
| 20 | + issues: list[dict], |
| 21 | + fingerprint: str, |
| 22 | + severity: str, |
| 23 | + lineNumber: int, |
| 24 | + description: str, |
| 25 | + path: str, |
| 26 | + check_name: str, |
| 27 | +) -> None: |
| 28 | + issues.append( |
| 29 | + { |
| 30 | + "type": "issue", |
| 31 | + "check_name": check_name, |
| 32 | + "description": description, |
| 33 | + "categories": [ |
| 34 | + "Style", |
| 35 | + ], |
| 36 | + "severity": severity, |
| 37 | + "location": { |
| 38 | + "path": path, |
| 39 | + "lines": { |
| 40 | + "begin": lineNumber, |
| 41 | + }, |
| 42 | + }, |
| 43 | + "fingerprint": fingerprint, |
| 44 | + } |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def parse_lines(lines: TextIO) -> list[dict]: |
| 49 | + issues: list[dict] = [] |
| 50 | + while True: |
| 51 | + try: |
| 52 | + brief_line: str = next(lines) |
| 53 | + details_line: str = next(lines) |
| 54 | + except StopIteration: |
| 55 | + break |
| 56 | + brief_line = brief_line.rstrip("\n") |
| 57 | + details_line = details_line.rstrip("\n") |
| 58 | + |
| 59 | + match_brief = re.fullmatch( |
| 60 | + r"^(?P<path>.+?)" r":(?P<line>\d+)" r"\s(?P<brief>.*)$", |
| 61 | + brief_line, |
| 62 | + ) |
| 63 | + if match_brief is None: |
| 64 | + continue |
| 65 | + |
| 66 | + match_details = re.fullmatch( |
| 67 | + r"^\s*(?P<check_name>\w{4,5})" r":\s(?P<details>.*)$", |
| 68 | + details_line, |
| 69 | + ) |
| 70 | + if match_details is None: |
| 71 | + continue |
| 72 | + |
| 73 | + severity: str = "info" |
| 74 | + path: str = match_brief["path"] |
| 75 | + lineNumber: int = int(match_brief["line"]) |
| 76 | + brief: str = match_brief["brief"] |
| 77 | + check_name: str = match_details["check_name"] |
| 78 | + details: str = match_details["details"] |
| 79 | + description: str = brief + " " + details |
| 80 | + fingerprint: str = get_hash(match_brief.groups() + match_details.groups()) |
| 81 | + |
| 82 | + append_line_to_issues( |
| 83 | + issues, fingerprint, severity, lineNumber, details, path, check_name |
| 84 | + ) |
| 85 | + return issues |
| 86 | + |
| 87 | + |
| 88 | +def main() -> None: |
| 89 | + print( |
| 90 | + json.dumps( |
| 91 | + parse_lines(stdin), |
| 92 | + indent="\t", |
| 93 | + ) |
| 94 | + ) |
0 commit comments