|
| 1 | +# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
| 2 | +# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE |
| 3 | +# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt |
| 4 | + |
| 5 | +# pylint: disable=wrong-spelling-in-comment,wrong-spelling-in-docstring |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import os.path |
| 11 | +from textwrap import shorten |
| 12 | +from typing import TYPE_CHECKING, Literal, TypedDict |
| 13 | +from urllib.parse import quote |
| 14 | + |
| 15 | +import pylint |
| 16 | +import pylint.message |
| 17 | +from pylint.constants import MSG_TYPES |
| 18 | +from pylint.reporters import BaseReporter |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from pylint.lint import PyLinter |
| 22 | + from pylint.reporters.ureports.nodes import Section |
| 23 | + |
| 24 | + |
| 25 | +def register(linter: PyLinter) -> None: |
| 26 | + linter.register_reporter(SARIFReporter) |
| 27 | + |
| 28 | + |
| 29 | +class SARIFReporter(BaseReporter): |
| 30 | + name = "sarif" |
| 31 | + extension = "sarif" |
| 32 | + linter: PyLinter |
| 33 | + |
| 34 | + def display_reports(self, layout: Section) -> None: |
| 35 | + """Don't do anything in this reporter.""" |
| 36 | + |
| 37 | + def _display(self, layout: Section) -> None: |
| 38 | + """Do nothing.""" |
| 39 | + |
| 40 | + def display_messages(self, layout: Section | None) -> None: |
| 41 | + """Launch layouts display.""" |
| 42 | + output: Log = { |
| 43 | + "version": "2.1.0", |
| 44 | + "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json", |
| 45 | + "runs": [ |
| 46 | + { |
| 47 | + "tool": { |
| 48 | + "driver": { |
| 49 | + "name": "pylint", |
| 50 | + "fullName": f"pylint {pylint.__version__}", |
| 51 | + "version": pylint.__version__, |
| 52 | + # should be versioned but not all versions are kept so... |
| 53 | + "informationUri": "https://pylint.readthedocs.io/", |
| 54 | + "rules": [ |
| 55 | + { |
| 56 | + "id": m.msgid, |
| 57 | + "name": m.symbol, |
| 58 | + "deprecatedIds": [ |
| 59 | + msgid for msgid, _ in m.old_names |
| 60 | + ], |
| 61 | + "deprecatedNames": [ |
| 62 | + name for _, name in m.old_names |
| 63 | + ], |
| 64 | + # per 3.19.19 shortDescription should be a |
| 65 | + # single sentence which can't be guaranteed, |
| 66 | + # however github requires it... |
| 67 | + "shortDescription": { |
| 68 | + "text": m.description.split(".", 1)[0] |
| 69 | + }, |
| 70 | + # github requires that this is less than 1024 characters |
| 71 | + "fullDescription": { |
| 72 | + "text": shorten( |
| 73 | + m.description, 1024, placeholder="..." |
| 74 | + ) |
| 75 | + }, |
| 76 | + "help": {"text": m.format_help()}, |
| 77 | + "helpUri": f"https://pylint.readthedocs.io/en/stable/user_guide/messages/{MSG_TYPES[m.msgid[0]]}/{m.symbol}.html", |
| 78 | + # handle_message only gets the formatted message, |
| 79 | + # so to use `messageStrings` we'd need to |
| 80 | + # convert the templating and extract the args |
| 81 | + # out of the msg |
| 82 | + } |
| 83 | + for checker in self.linter.get_checkers() |
| 84 | + for m in checker.messages |
| 85 | + if m.symbol in self.linter.stats.by_msg |
| 86 | + ], |
| 87 | + } |
| 88 | + }, |
| 89 | + "results": [self.serialize(message) for message in self.messages], |
| 90 | + } |
| 91 | + ], |
| 92 | + } |
| 93 | + json.dump(output, self.out) |
| 94 | + |
| 95 | + @staticmethod |
| 96 | + def serialize(message: pylint.message.Message) -> Result: |
| 97 | + region: Region = { |
| 98 | + "startLine": message.line, |
| 99 | + "startColumn": message.column + 1, |
| 100 | + "endLine": message.end_line or message.line, |
| 101 | + "endColumn": (message.end_column or message.column) + 1, |
| 102 | + } |
| 103 | + |
| 104 | + location: Location = { |
| 105 | + "physicalLocation": { |
| 106 | + "artifactLocation": { |
| 107 | + "uri": path_to_uri(message.path), |
| 108 | + }, |
| 109 | + "region": region, |
| 110 | + }, |
| 111 | + } |
| 112 | + if message.obj: |
| 113 | + logical_location: LogicalLocation = { |
| 114 | + "name": message.obj, |
| 115 | + "fullyQualifiedName": f"{message.module}.{message.obj}", |
| 116 | + } |
| 117 | + location["logicalLocations"] = [logical_location] |
| 118 | + |
| 119 | + return { |
| 120 | + "ruleId": message.msg_id, |
| 121 | + "message": {"text": message.msg}, |
| 122 | + "level": CATEGORY_MAP[message.category], |
| 123 | + "locations": [location], |
| 124 | + "partialFingerprints": { |
| 125 | + # encoding the node path seems like it would be useful to dedup alerts? |
| 126 | + "nodePath/v1": "", |
| 127 | + }, |
| 128 | + } |
| 129 | + |
| 130 | + |
| 131 | +def path_to_uri(path: str) -> str: |
| 132 | + """Converts a relative FS path to a relative URI. |
| 133 | +
|
| 134 | + Does not check the validity of the path. |
| 135 | +
|
| 136 | + An alternative would be to use `Path.as_uri` (on concrete path) on both the |
| 137 | + artifact path and a reference path, then create a relative URI from this. |
| 138 | + """ |
| 139 | + if os.path.altsep: |
| 140 | + path = path.replace(os.path.altsep, "/") |
| 141 | + if os.path.sep != "/": |
| 142 | + path = path.replace(os.path.sep, "/") |
| 143 | + return quote(path) |
| 144 | + |
| 145 | + |
| 146 | +CATEGORY_MAP: dict[str, ResultLevel] = { |
| 147 | + "convention": "note", |
| 148 | + "refactor": "note", |
| 149 | + "statement": "note", |
| 150 | + "info": "note", |
| 151 | + "warning": "warning", |
| 152 | + "error": "error", |
| 153 | + "fatal": "error", |
| 154 | +} |
| 155 | + |
| 156 | + |
| 157 | +class Run(TypedDict): |
| 158 | + tool: Tool |
| 159 | + # invocation parameters / environment for the tool |
| 160 | + # invocation: list[Invocations] |
| 161 | + results: list[Result] |
| 162 | + # originalUriBaseIds: dict[str, ArtifactLocation] |
| 163 | + |
| 164 | + |
| 165 | +Log = TypedDict( |
| 166 | + "Log", |
| 167 | + { |
| 168 | + "version": Literal["2.1.0"], |
| 169 | + "$schema": Literal[ |
| 170 | + "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json" |
| 171 | + ], |
| 172 | + "runs": list[Run], |
| 173 | + }, |
| 174 | +) |
| 175 | + |
| 176 | + |
| 177 | +class Tool(TypedDict): |
| 178 | + driver: Driver |
| 179 | + |
| 180 | + |
| 181 | +class Driver(TypedDict): |
| 182 | + name: Literal["pylint"] |
| 183 | + # optional but azure wants it |
| 184 | + fullName: str |
| 185 | + version: str |
| 186 | + informationUri: str # not required but validator wants it |
| 187 | + rules: list[ReportingDescriptor] |
| 188 | + |
| 189 | + |
| 190 | +class ReportingDescriptorOpt(TypedDict, total=False): |
| 191 | + deprecatedIds: list[str] |
| 192 | + deprecatedNames: list[str] |
| 193 | + messageStrings: dict[str, MessageString] |
| 194 | + |
| 195 | + |
| 196 | +class ReportingDescriptor(ReportingDescriptorOpt): |
| 197 | + id: str |
| 198 | + # optional but validator really wants it (then complains that it's not pascal cased) |
| 199 | + name: str |
| 200 | + # not required per spec but required by github |
| 201 | + shortDescription: MessageString |
| 202 | + fullDescription: MessageString |
| 203 | + help: MessageString |
| 204 | + helpUri: str |
| 205 | + |
| 206 | + |
| 207 | +class MarkdownMessageString(TypedDict, total=False): |
| 208 | + markdown: str |
| 209 | + |
| 210 | + |
| 211 | +class MessageString(MarkdownMessageString): |
| 212 | + text: str |
| 213 | + |
| 214 | + |
| 215 | +ResultLevel = Literal["none", "note", "warning", "error"] |
| 216 | + |
| 217 | + |
| 218 | +class ResultOpt(TypedDict, total=False): |
| 219 | + ruleId: str |
| 220 | + ruleIndex: int |
| 221 | + |
| 222 | + level: ResultLevel |
| 223 | + |
| 224 | + |
| 225 | +class Result(ResultOpt): |
| 226 | + message: Message |
| 227 | + # not required per spec but required by github |
| 228 | + locations: list[Location] |
| 229 | + partialFingerprints: dict[str, str] |
| 230 | + |
| 231 | + |
| 232 | +class Message(TypedDict, total=False): |
| 233 | + # needs to have either text or id but it's a PITA to type |
| 234 | + |
| 235 | + #: plain text message string (can have markdown links but no other formatting) |
| 236 | + text: str |
| 237 | + #: formatted GFM text |
| 238 | + markdown: str |
| 239 | + #: rule id |
| 240 | + id: str |
| 241 | + #: arguments for templated rule messages |
| 242 | + arguments: list[str] |
| 243 | + |
| 244 | + |
| 245 | +class Location(TypedDict, total=False): |
| 246 | + physicalLocation: PhysicalLocation # actually required by github |
| 247 | + logicalLocations: list[LogicalLocation] |
| 248 | + |
| 249 | + |
| 250 | +class PhysicalLocation(TypedDict): |
| 251 | + artifactLocation: ArtifactLocation |
| 252 | + # not required per spec, required by github |
| 253 | + region: Region |
| 254 | + |
| 255 | + |
| 256 | +class ArtifactLocation(TypedDict, total=False): |
| 257 | + uri: str |
| 258 | + #: id of base URI for resolving relative `uri` |
| 259 | + uriBaseId: str |
| 260 | + description: Message |
| 261 | + |
| 262 | + |
| 263 | +class LogicalLocation(TypedDict, total=False): |
| 264 | + name: str |
| 265 | + fullyQualifiedName: str |
| 266 | + #: schema is `str` with a bunch of *suggested* terms, of which this is a subset |
| 267 | + kind: Literal[ |
| 268 | + "function", "member", "module", "parameter", "returnType", "type", "variable" |
| 269 | + ] |
| 270 | + |
| 271 | + |
| 272 | +class Region(TypedDict): |
| 273 | + # none required per spec, all required by github |
| 274 | + startLine: int |
| 275 | + startColumn: int |
| 276 | + endLine: int |
| 277 | + endColumn: int |
0 commit comments