Skip to content

Commit

Permalink
Merge pull request #1 from brunohaf/feature/tool_name
Browse files Browse the repository at this point in the history
INPUT_TOOL_NAME from env
  • Loading branch information
brunohaf authored Sep 17, 2024
2 parents d083209 + d2bd1c1 commit 5260d79
Showing 1 changed file with 46 additions and 37 deletions.
83 changes: 46 additions & 37 deletions pyright_to_rdjson/pyright_to_rdjson.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,61 @@
import json
import os
import sys

from typing import Any, Dict, TextIO


def pyright_to_rdjson(jsonin: TextIO):
pyright: Dict = json.load(jsonin)

def validate_pyright_json(pyright: Dict) -> None:
"""Validate if the input JSON contains pyright diagnostics."""
if "generalDiagnostics" not in pyright:
raise RuntimeError("This doesn't look like pyright json")


def convert_range(range_info: Dict[str, Dict[str, int]]) -> Dict[str, Dict[str, int]]:
"""Convert zero-based offsets from pyright to one-based for rdjson."""
return {
"start": {
"line": range_info["start"]["line"] + 1,
"column": range_info["start"]["character"] + 1,
},
"end": {
"line": range_info["end"]["line"] + 1,
"column": range_info["end"]["character"] + 1,
},
}


def create_diagnostic_entry(diagnostic: Dict[str, Any]) -> Dict[str, Any]:
"""Create an rdjson diagnostic entry from a pyright diagnostic."""
message = diagnostic["message"]
rule = diagnostic.get("rule")

if rule:
message = f"{message} ({rule})"

return {
"message": message,
"severity": diagnostic["severity"].upper(),
"location": {
"path": diagnostic["file"],
"range": convert_range(diagnostic["range"]),
},
}


def pyright_to_rdjson(jsonin: TextIO) -> str:
"""Convert pyright JSON diagnostics to rdjson format."""
pyright: Dict[str, Any] = json.load(jsonin)
tool_name: str = os.getenv("INPUT_TOOL_NAME", "pyright")
validate_pyright_json(pyright)
rdjson: Dict[str, Any] = {
"source": {"name": "pyright", "url": "https://github.com/Microsoft/pyright"},
"source": {"name": tool_name, "url": "https://github.com/Microsoft/pyright"},
"severity": "WARNING",
"diagnostics": [],
"diagnostics": [
create_diagnostic_entry(d) for d in pyright["generalDiagnostics"]
],
}

d: Dict
for d in pyright["generalDiagnostics"]:
message = d["message"]

# If there is a rule name, append it to the message
rule = d.get("rule", None)
if rule is not None:
message = f"{message} ({rule})"

rdjson["diagnostics"].append(
{
"message": message,
"severity": d["severity"].upper(),
"location": {
"path": d["file"],
"range": {
"start": {
# pyright uses zero-based offsets
"line": d["range"]["start"]["line"] + 1,
"column": d["range"]["start"]["character"] + 1,
},
"end": {
"line": d["range"]["end"]["line"] + 1,
"column": d["range"]["end"]["character"] + 1,
},
},
},
}
)

return json.dumps(rdjson)
return json.dumps(rdjson, indent=2)


if __name__ == "__main__":
Expand Down

0 comments on commit 5260d79

Please sign in to comment.