Commit 777116f2 authored by Luke Mewburn's avatar Luke Mewburn
Browse files

Fix ruff and ty issues in testing and utils

Fix various issues detected by ruff 0.17.4 and ty 0.0.99.

Disable various ruff checks outside of testing/*/*.py
(e.g., utils/ needs future work for more documentation,
less TODO, and some source file renames).
parent 0bba1c8c
Loading
Loading
Loading
Loading
Loading
+15 −3
Changes for pyproject.toml: 15 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -35,9 +35,11 @@ ignore = [
  "EM102",      # f-string-in-exception
  "G004",       # logging-f-string
  "S101",       # assert
  "SLF001",     # private-member-access
  "TRY002",     # raise-vanilla-class
  "TRY003",     # raise-vanilla-args
  "T201",       # print
]

preview = true
select = [
  "ALL",
@@ -51,9 +53,19 @@ select = [
]

[tool.ruff.lint.per-file-ignores]
"!testing/asn/compat_asn1.py" = [
# Disable various checks except in testing/*/*.py
"!testing/*/*.py" = [
  "D",          # pydocstyle
  "FIX002",     # line-contains-todo
  "FIX004",     # line-contains-hack
  "N999",       # invalid-module-name
  "TC002",      # typing-only-third-party-import
  "TD002",      # missing-todo-author
  "TD003",      # missing-todo-link
]

"!{testing/*/*.py,utils/*.py}" = [
  "ALL",
  "DOC",
]

[tool.ruff.lint.pydocstyle]
−1
Changes for testing/asn/asn_process.py: 0 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -6,7 +6,6 @@
# ruff: noqa: N802 (invalid-function-name)
# ruff: noqa: N803 (invalid-argument-name)
# ruff: noqa: N806 (non-lowercase-variable-in-function)
# ruff: noqa: TRY003 (raise-vanilla-args)

import argparse
import json
+4 −4
Changes for testing/asn/compat_asn1.py: 4 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -15,6 +15,8 @@ import pycrate_asn1c.asnproc
import pycrate_asn1c.setobj
import pycrate_asn1c.utils

# ruff: noqa: SLF001 (private-member-access)

# Note: requires python >= 3.10, pycrate >= 0.8.1

TYPE_CONTAINER_OF = (pa_asnobj.TYPE_SEQ_OF, pa_asnobj.TYPE_SET_OF)
@@ -251,7 +253,7 @@ class CompatCheck:
            text=False,
        )
        if p.returncode != 0:
            raise CompatCheckError(  # noqa: TRY003 (raise-vanilla-args)
            raise CompatCheckError(
                f"Error reading git commit '{commit}' for "
                f"file '{filename}': {p.stderr.strip()}"
            )
@@ -274,9 +276,7 @@ class CompatCheck:
            filepath = pathlib.Path(filename)
            return filepath.read_text(encoding="utf-8")
        except Exception as ex:
            raise CompatCheckError(  # noqa: TRY003 (raise-vanilla-args)
                f"Error reading '{filename}': {ex}"
            ) from ex
            raise CompatCheckError(f"Error reading '{filename}': {ex}") from ex

    def _parse_asn1_text(
        self, asn_text: list[str], filenames: list[str]
+35 −17
Changes for testing/json/lint_json.py: 35 added lines, 17 removed lines.
Original line number Diff line number Diff line
#!/usr/bin/env python3

from pathlib import Path
from difflib import *
"""Tool to lint JSON in the repository."""

import subprocess
import sys
from difflib import unified_diff
from pathlib import Path

import colorama
from colorama import Fore, Style
@@ -12,7 +15,8 @@ colorama.init()
ignore_paths = [Path(x) for x in ["testing/deps"]]


def print_colorized_diff_line(line: str):
def print_colorized_diff_line(line: str) -> None:
    """Print a colorized diff line."""
    if line.startswith("-"):
        print(f"{Fore.RED}{line}{Style.RESET_ALL}")
    elif line.startswith("+"):
@@ -21,13 +25,22 @@ def print_colorized_diff_line(line: str):
        print(line)


def lint(file: Path):
    completed = subprocess.run(
        ["jq", ".", str(file)], capture_output=True, text=True, encoding="utf8"
def lint(file: Path) -> int:
    """Lint `file` with `jq`.

    Returns:
       Number of lint error lines.
    """
    completed = subprocess.run(  # noqa: S603 (subprocess-without-shell-equals-true)
        ["jq", ".", str(file)],  # noqa: S607 (start-process-with-partial-path)
        capture_output=True,
        check=False,
        text=True,
        encoding="utf8",
    )

    if completed.returncode != 0:
        print(f"  {str(f)}: FAIL")
        print(f"  {file!s}: FAIL")
        print(f"      jq error code {completed.returncode}")
        lines = completed.stderr.splitlines()
        for line in lines:
@@ -38,18 +51,20 @@ def lint(file: Path):
    orig_xml = file.read_text(encoding="utf8")
    diff = list(unified_diff(orig_xml.splitlines(), linted_xml.splitlines()))
    if len(diff) == 0:
        print(f"✅ {str(f)}")
        print(f"✅ {file!s}")
        return 0
    else:
        print(f"❌ {str(f)}: {len(diff)} linting errors")
        # for d in diff:
        #     print("".join(d))
    print(f"❌ {file!s}: {len(diff)} linting errors")
    for d in diff:
        print_colorized_diff_line(d)
    return len(diff)


if __name__ == "__main__":
def main() -> int:
    """Standalone main.

    Returns:
        Exit code.
    """
    root = Path("./")
    files = list(root.rglob("*.json"))

@@ -57,7 +72,7 @@ if __name__ == "__main__":
    errors = 0

    print("───────────────────────────────────────────────────────────────────")
    print(f"Linting JSON files...")
    print("Linting JSON files...")

    for f in files:
        if len(list(set(f.parents) & set(ignore_paths))) > 0:
@@ -78,6 +93,9 @@ if __name__ == "__main__":
    print("───────────────────────────────────────────────────────────────────")

    if files_with_errors > 0:
        exit(-1)
    else:
        exit(0)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
+79 −35
Changes for testing/xml/lint_xml.py: 79 added lines, 35 removed lines.
Original line number Diff line number Diff line
#!/usr/bin/env python3

from pathlib import Path
from difflib import *
"""Tool to lint XML and XSD in the repository."""

import argparse
import subprocess
import sys
from difflib import unified_diff
from pathlib import Path

import colorama
from colorama import Fore, Style

import argparse

from lxml import etree

# ruff: noqa: FIX002 (line-contains-todo)
# ruff: noqa: TD002 (missing-todo-author)
# ruff: noqa: TD003 (missing-todo-link)

colorama.init()

ignore_paths = [Path(x) for x in ["testing/deps"]]

# TODO - get rid of these exceptions when we can
ignore_files = [
# TODO: get rid of these exceptions when we can
ignore_files = {
    str(Path("104000/schema/TS_104_000.xsd")),
    str(Path("103221-2/TS_103_221_02_Configuration.xsd")),
    str(Path("103707/TS_103_707.xsd")),
]
}

XS = "{http://www.w3.org/2001/XMLSchema}"
etree_parser = etree.XMLParser(
@@ -32,31 +37,48 @@ etree_parser = etree.XMLParser(
)


def print_colorized_diff_line(line: str):
def print_colorized_diff_line(line: str) -> str:
    """Format a colorized diff line.

    Returns:
        Colorized diff line.
    """
    if line.startswith("-"):
        return f"{Fore.RED}{line}{Style.RESET_ALL}"
    elif line.startswith("+"):
    if line.startswith("+"):
        return f"{Fore.GREEN}{line}{Style.RESET_ALL}"
    else:
    return line


def run_linter(file: Path) -> str:
    completed = subprocess.run(
        # TODO - get the spacing from the editorconfig, rather than hardcoding it
        ["xmllint", "--format", str(file)],
    """Lint `file` with `xmllint`.

    Returns:
        Linted XML text.

    Raises:
        RuntimeError: If xmllint failed to run.
    """
    completed = subprocess.run(  # noqa: S603 (subprocess-without-shell-equals-true)
        # TODO: get the spacing from the editorconfig, rather than hardcoding it
        ["xmllint", "--format", str(file)],  # noqa: S607 (start-process-with-partial-path)
        capture_output=True,
        check=False,
        text=True,
        encoding="utf8",
        env={"XMLLINT_INDENT": "    "},
    )
    if completed.returncode != 0:
        raise RuntimeError(f"xmllint failed with error code {completed.returncode}")
    linted_xml = completed.stdout
    return linted_xml
    return completed.stdout


def get_errors(file: Path) -> str:
    """Get lint and type errors for `file`.

    Returns:
        String of errors.
    """
    errors = get_linting_errors(file)
    errors += get_type_errors(file)

@@ -64,17 +86,26 @@ def get_errors(file: Path) -> str:


def get_linting_errors(file: Path) -> str:
    """Get diff of file to linted file.

    Returns:
        String of diff.
    """
    linted_xml = run_linter(file)
    orig_xml = file.read_text(encoding="utf8")
    diff = list(unified_diff(orig_xml.splitlines(), linted_xml.splitlines()))
    if len(diff) == 0:
        return ""
    else:
    return "\n".join([print_colorized_diff_line(d) for d in diff])


def get_type_errors(file: Path) -> str:
    with open(file) as f:
    """Process file for type errors.

    Returns:
        String of errors.
    """
    with Path(file).open() as f:
        lines = f.read().splitlines()

    tree = etree.parse(file, parser=etree_parser)
@@ -84,7 +115,7 @@ def get_type_errors(file: Path) -> str:

    for el in root.iter(f"{XS}element"):
        try:
            has_nolint = "<!-- nolint:" in lines[el.sourceline - 2]
            has_nolint = "<!-- nolint:" in lines[(el.sourceline or 0) - 2]
        except IndexError:
            has_nolint = False

@@ -104,7 +135,12 @@ def get_type_errors(file: Path) -> str:
    return ""


def prettify_file(file: Path):
def prettify_file(file: Path) -> bool:
    """Prettify `file` using `xmllint`.

    Returns:
        True if changed, False if not.
    """
    linted_xml = run_linter(file)

    errors = get_errors(file)
@@ -116,13 +152,21 @@ def prettify_file(file: Path):
    return False


if __name__ == "__main__":
def main() -> int:  # noqa: C901,PLR0912 (complex-structure, too-many-branches)
    """Standalone main.

    Returns:
        Exit code.
    """
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-i",
        "--input",
        help="Specific file to lint (use - for stdin). If omitted, lint all XML files in the repo.",
        help=(
            "Specific file to lint (use - for stdin). "
            "If omitted, lint all XML files in the repo."
        ),
    )
    parser.add_argument(
        "-p",
@@ -135,15 +179,13 @@ if __name__ == "__main__":
    if args.prettify:
        if args.input is None:
            print("Prettify required an input file to be specified (-i | --input)")
            exit(-1)
        else:
            return 1
        path = Path(args.input)
        if not path.exists():
            print(f"Could not find file {args.input}")
        if prettify_file(path):
                exit(1)
            else:
                exit(0)
            return 1
        return 0

    files = []
    if args.input:
@@ -153,10 +195,9 @@ if __name__ == "__main__":
        files = list(root.rglob("*.xml")) + list(root.rglob("*.xsd"))

    files_with_errors = 0
    errors = 0

    print("")
    print(f"Linting XML / XSD files...")
    print()
    print("Linting XML / XSD files...")

    error_files = {}

@@ -169,10 +210,10 @@ if __name__ == "__main__":
        new_errors = get_errors(f)
        if new_errors:
            files_with_errors += 1
            print(f"❌ {str(f)}")
            print(f"❌ {f!s}")
            error_files[str(f)] = new_errors
        else:
            print(f"✅ {str(f)}")
            print(f"✅ {f!s}")

    for k, v in error_files.items():
        print("───────────────────────────────────────────────────────────────────")
@@ -186,6 +227,9 @@ if __name__ == "__main__":
    print("───────────────────────────────────────────────────────────────────")

    if files_with_errors > 0:
        exit(-1)
    else:
        exit(0)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
Loading