Commit aa0fa76e authored by Luke Mewburn's avatar Luke Mewburn
Browse files

compat_asn1: support separate commit for each file

Allow each file or dependency to have its own git commit revision.
Support optional saving of the loaded files before parsing.

  -a, --dep1 [COMMIT:]DEP1
                        optional dependency for FILE1 or COMMIT1, with
                        optional commit. Used in conjunction with any
                        COMMONDEP. May be specified multiple times
  -b, --dep2 [COMMIT:]DEP2
                        optional dependency for FILE2 or COMMIT2, with
                        optional commit. Used in conjunction with any
                        COMMONDEP. May be specified multiple times
  -A, --save1 SAVE1     filename to write combined FILE1 and its dependencies
                        after reading
  -B, --save2 SAVE2     filename to write combined FILE2 or COMMIT2 and its
                        dependencies after reading

Revert part of 6c9c658b which converted filenames to pathlib.Path and
go back to using a string for the filename because it might contain
a "COMMIT:" prefix.  This also changes the interface used by asn_compat.py
parent db9c6727
Loading
Loading
Loading
Loading
Loading
+2 −1
Changes for pyproject.toml: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -51,6 +51,8 @@ ignore = [
  "EM102",      # f-string-in-exception
  "G004",       # logging-f-string
  "S101",       # assert
  "TC002",      # typing-only-third-party-import
  "TC003",      # typing-only-standard-library-import
  "TRY002",     # raise-vanilla-class
  "TRY003",     # raise-vanilla-args
  "T201",       # print
@@ -64,7 +66,6 @@ ignore = [
  "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
]
+11 −9
Changes for testing/asn/asn_process.py: 11 added lines, 9 removed lines.
Original line number Diff line number Diff line
@@ -10,11 +10,11 @@
import argparse
import logging
import os
import pathlib
import shutil
import subprocess
import sys
import typing
from pathlib import Path
from time import perf_counter

import compat_asn1
@@ -45,7 +45,7 @@ def fix_path(path: str) -> str:
    return path


def getDependencies(asnFiles: test_config.Asn1FilesDict, fileName: Path) -> list[Path]:
def getDependencies(asnFiles: test_config.Asn1FilesDict, fileName: str) -> list[str]:
    """Return list of dependencies for fileName, and text of all files.

    Args:
@@ -61,10 +61,10 @@ def getDependencies(asnFiles: test_config.Asn1FilesDict, fileName: Path) -> list


def syntaxCheckASN(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.Any]:
    """Performs ASN syntax checking on a list of pathlib Paths.
    """Performs ASN syntax checking on a list of paths.

    Args:
        asnFiles: List of filenames (Pathlib Path)
        asnFiles: Asn1FilesDict dict.

    Returns:
        A dict of outcome against the first filename of each compile target.
@@ -128,7 +128,7 @@ def compileAllTargets(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.A
            fileNames = getDependencies(asnFiles, target)
            pycrate_asn1c.asnproc.GLOBAL.clear()
            for filename in fileNames:
                pFile = Path(filename)
                pFile = pathlib.Path(filename)
                fileTexts.append(pFile.read_text())
                logger.debug(f"  Loading {filename}")
            pycrate_asn1c.asnproc.compile_text(fileTexts, filenames=fileNames)
@@ -236,7 +236,8 @@ def compatCheckCommits(asnFiles: test_config.Asn1FilesDict) -> dict[str, typing.
                        commit1=commitIds[0],
                        commit2=commitIds[1],
                        asn1_file=target,
                        dependencies=targetDeps,
                        dependencies1=targetDeps,
                        dependencies2=targetDeps,
                    )
                except Exception as ex:
                    compareErrors = [f"Compare exception: {ex}"]
@@ -335,8 +336,9 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many-
        action=argparse.BooleanOptionalAction,
    )
    args = argparser.parse_args()
    if not Path(args.config).exists():
        argparser.error(f"Could not find config file {args.config}")
    config_file = pathlib.Path(args.config)
    if not config_file.exists():
        argparser.error(f"Could not find config file {config_file}")
    logger.debug(f"Loading config from {args.config}")
    times = []

@@ -354,7 +356,7 @@ def main() -> int: # noqa: C901, PLR0912, PLR0915 (complex-structure, too-many-
        change_path_to_unix = True

    logger.info(f"Loading {args.config}")
    testConfig = test_config.parse_json_file(Path(args.config))
    testConfig = test_config.parse_json_file(config_file)
    asn1_files = testConfig.asn1_files
    logger.info(f"{len(asn1_files)} ASN.1 files found")

+136 −56
Changes for testing/asn/compat_asn1.py: 136 added lines, 56 removed lines.
Original line number Diff line number Diff line
@@ -235,7 +235,7 @@ class CompatCheck:
    def _read_commit(
        self,
        commit: str,
        filename: pathlib.Path,
        filename: str,
    ) -> str:
        """Read file `filename` as at git commit `commit`, return text contents.

@@ -265,12 +265,13 @@ class CompatCheck:

    def _read_file(
        self,
        filename: pathlib.Path,
        filename: str,
    ) -> str:
        """Read file `filename` as UTF-8, and return text contents.

        Args:
            filename: File to read.
            filename: File to read. If format `COMMIT:FILENAME`, uses
                `_read_commit(commit, file)` instead.

        Returns:
            Contents of `filename`.
@@ -279,8 +280,18 @@ class CompatCheck:
            CompatCheckError: Problem reading `filename`.
        """
        logger.debug(f"Reading file '{filename}'")
        parts = filename.split(":")
        match len(parts):
            case 1:
                pass
            case 2:
                return self._read_commit(parts[0], parts[1])
            case _:
                raise CompatCheckError(
                    f"Invalid [COMMIT:]FILE provided in '{filename}'"
                )
        try:
            filepath = filename
            filepath = pathlib.Path(filename)
            return filepath.read_text(encoding="utf-8")
        except Exception as ex:
            raise CompatCheckError(f"Error reading '{filename}': {ex}") from ex
@@ -288,12 +299,12 @@ class CompatCheck:
    def _parse_asn1_text(
        self,
        asn1_text: list[str],
        asn1_files: list[pathlib.Path],
        asn1_files: list[str],
    ) -> pa_asnobj.ASN1Dict:
        """Parse `asn1_text` using pycrate compile_text(), returning the module object.

        Args:
            asn1_text: List of ASN.1 text strings for the module
            asn1_text: List of ASN.1 text strings for the module.
            asn1_files: List of filenames, with a 1:1 relationship with asn1_text.

        Returns:
@@ -301,22 +312,23 @@ class CompatCheck:
        """
        logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn1_text)}'")
        pycrate_asn1c.asnproc.GLOBAL.clear()
        filenames = [str(filename) for filename in asn1_files]
        pycrate_asn1c.asnproc.compile_text(text=asn1_text, filenames=filenames)
        pycrate_asn1c.asnproc.compile_text(text=asn1_text, filenames=asn1_files)
        return copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD)

    def _parse_asn1_commit(
        self,
        commit: str,
        asn1_file: pathlib.Path,
        dependencies: list[pathlib.Path],
        asn1_file: str,
        dependencies: list[str],
        save_file: pathlib.Path | None = None,
    ) -> pa_asnobj.ASN1Dict:
        """Parse `asn1_file` as at git commit `commit` as ASN.1 using pycrate.

        Args:
            commit: git commit.
            asn1_file: File to parse.
            dependencies: Optional list of dependencies.
            dependencies: List of dependencies.
            save_file: Optional path to save text of commit and dependencies.

        Returns:
            Parsed module object.
@@ -328,32 +340,38 @@ class CompatCheck:
            return cached_parse
        asn1_text: list[str] = []
        asn1_text.append(self._read_commit(commit=commit, filename=asn1_file))
        filenames: list[pathlib.Path] = [asn1_file]
        filenames = [asn1_file]
        for filename in dependencies:
            asn1_text.append(self._read_file(filename))
            filenames.append(filename)
        if save_file:
            save_file.write_text("\n".join(asn1_text))
        parse = self._parse_asn1_text(asn1_text=asn1_text, asn1_files=filenames)
        self._cache_commits[cachekey] = parse
        return parse

    def _parse_asn1_files(
        self,
        asn1_files: list[pathlib.Path],
        asn1_files: list[str],
        save_file: pathlib.Path | None = None,
    ) -> pa_asnobj.ASN1Dict:
        """Parse `asn1_files` as ASN.1 using pycrate, returning the module object.

        Args:
            asn1_files: List of files to parse.
            save_file: Optional path to save text of asn1_files.

        Returns:
            Parsed module.
        """
        logger.info(f"Parsing {' '.join(str(f) for f in asn1_files)}")
        logger.info(f"Parsing {' '.join(asn1_files)}")
        cachekey = tuple(asn1_files)
        if (cached_parse := self._cache_files.get(cachekey, None)) is not None:
            logger.info(f"Parse cache hit with key {cachekey}")
            return cached_parse
        asn1_text = [self._read_file(filename) for filename in asn1_files]
        if save_file:
            save_file.write_text("\n".join(asn1_text))
        parse = self._parse_asn1_text(asn1_text=asn1_text, asn1_files=asn1_files)
        self._cache_files[cachekey] = parse
        return parse
@@ -736,24 +754,29 @@ class CompatCheck:

        return self._errors

    def compare_commits(
    def compare_commits(  # noqa: PLR0913,PLR0917 (too-many-arguments, too-many-positional-arguments)
        self,
        commit1: str,
        commit2: str,
        asn1_file: pathlib.Path,
        dependencies: list[pathlib.Path],
        asn1_file: str,
        dependencies1: list[str],
        dependencies2: list[str],
        save_a_file: pathlib.Path | None = None,
        save_b_file: pathlib.Path | None = None,
    ) -> list[str]:
        """Compare ASN.1 for backwards compatibility issues between commits.

        Checks `asn1_file` at git commit `commit1` and `asn1_file` at git commit
        `commit2`, using optional list of dependencies in `dependencies` at
        git commit HEAD.
        Checks `asn1_file` at git commit `commit1` with `dependencies1`
        and `asn1_file` at git commit `commit2` with `dependencies2`.

        Args:
            commit1: First git commit.
            commit2: Second git commit.
            asn1_file: File to check.
            dependencies: List of files to check.
            dependencies1: List of dependencies for commit1.
            dependencies2: List of dependencies for commit2.
            save_a_file: Optional path to save text of commit1 and dependencies.
            save_b_file: Optional path to save text of commit2 and dependencies.

        Returns:
            List of error messages (if any).
@@ -765,24 +788,34 @@ class CompatCheck:
        self._clear()

        fa_modules = self._parse_asn1_commit(
            commit=commit1, asn1_file=asn1_file, dependencies=dependencies
            commit=commit1,
            asn1_file=asn1_file,
            dependencies=dependencies1,
            save_file=save_a_file,
        )
        fb_modules = self._parse_asn1_commit(
            commit=commit2, asn1_file=asn1_file, dependencies=dependencies
            commit=commit2,
            asn1_file=asn1_file,
            dependencies=dependencies2,
            save_file=save_b_file,
        )

        return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules)

    def compare_files(
        self,
        a_files: list[pathlib.Path],
        b_files: list[pathlib.Path],
        a_files: list[str],
        b_files: list[str],
        save_a_file: pathlib.Path | None = None,
        save_b_file: pathlib.Path | None = None,
    ) -> list[str]:
        """Compare ASN.1 for backwards compatibility issues between files.

        Args:
            a_files: First list of files to compare.
            b_files: Second list of files to compare.
            a_files: First list of files to compare, including dependencies.
            b_files: Second list of files to compare, including dependencies.
            save_a_file: Optional path to save text of a_files.
            save_b_file: Optional path to save text of b_files.

        Returns:
            List of error messages (if any).
@@ -791,13 +824,13 @@ class CompatCheck:

        self._clear()

        fa_modules = self._parse_asn1_files(a_files)
        fb_modules = self._parse_asn1_files(b_files)
        fa_modules = self._parse_asn1_files(a_files, save_file=save_a_file)
        fb_modules = self._parse_asn1_files(b_files, save_file=save_b_file)

        return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules)


def main() -> int:
def main() -> int:  # noqa: PLR0915 (too-many-statements)
    """Standalone main.

    Returns:
@@ -807,42 +840,77 @@ def main() -> int:
    logging.basicConfig(level=loglevel)
    pycrate_asn1c.utils.logger.setLevel(loglevel)

    argparser = argparse.ArgumentParser(
        usage="""\
%(prog)s FILE1 FILE2 [DEPENDENCY ...]
usage: %(prog)s -1 COMMIT1 [-2 COMMIT2] FILE1 [DEPENDENCY ...]
usage: %(prog)s -h
"""
    )
    argparser = argparse.ArgumentParser()

    argparser.add_argument(
        "-1",
        "--commit1",
        help="first commit to check FILE1.asn against",
        help="first commit to check FILE1 against",
    )
    argparser.add_argument(
        "-2",
        "--commit2",
        help="second commit to check FILE1.asn against. [HEAD]",
        help="second commit to check FILE1 against. [HEAD]",
    )
    argparser.add_argument(
        "file1",
        metavar="FILE1",
        "-a",
        "--dep1",
        metavar="[COMMIT:]DEP1",
        action="append",
        help=(
            "optional dependency for FILE1 or COMMIT1, with optional commit. "
            "Used in conjunction with any COMMONDEP. "
            "May be specified multiple times"
        ),
    )
    argparser.add_argument(
        "-b",
        "--dep2",
        metavar="[COMMIT:]DEP2",
        action="append",
        help=(
            "optional dependency for FILE2 or COMMIT2, with optional commit. "
            "Used in conjunction with any COMMONDEP. "
            "May be specified multiple times"
        ),
    )
    argparser.add_argument(
        "-A",
        "--save1",
        type=pathlib.Path,
        help="first ASN.1 specification to check",
        help="filename to write combined FILE1 and its dependencies after reading",
    )
    argparser.add_argument(
        "file2",
        metavar="FILE2",
        "-B",
        "--save2",
        type=pathlib.Path,
        help=(
            "filename to write combined FILE2 or COMMIT2 "
            "and its dependencies after reading"
        ),
    )
    argparser.add_argument(
        "file1",
        metavar="[COMMIT:]FILE1",
        help="first ASN.1 specification to check, with optional commit",
    )
    argparser.add_argument(
        "file2",
        metavar="[COMMIT:]FILE2",
        nargs="?",
        help="second ASN.1 specification to check (if not using -1)",
        help=(
            "second ASN.1 specification to check (if not using -1), "
            "with optional commit"
        ),
    )
    argparser.add_argument(
        "dependencies",
        metavar="DEPENDENCIES",
        type=pathlib.Path,
        nargs=argparse.REMAINDER,
        help="optional dependencies for FILE1 and FILE2",
        metavar="[COMMIT:]COMMONDEP",
        nargs="*",
        help=(
            "optional common dependency for FILE1 and FILE2, with optional commit. "
            "May be specified multiple times"
        ),
    )
    args = argparser.parse_args()

@@ -850,17 +918,24 @@ usage: %(prog)s -h
    compat_errors = []

    if args.commit1 is not None:
        if ":" in args.file1:
            argparser.error("Can't provide COMMIT1: in FILE1 when using -1 COMMIT1")
        if args.file2 is not None:
            args.dependencies.insert(0, args.file2)
            args.file2 = None
        if args.commit2 is None:
            args.commit2 = "HEAD"
        all_dep1 = (args.dep1 or []) + args.dependencies
        all_dep2 = (args.dep2 or []) + args.dependencies
        compat_errors.extend(
            compat_check.compare_commits(
                commit1=args.commit1,
                commit2=args.commit2,
                asn1_file=args.file1,
                dependencies=args.dependencies,
                dependencies1=all_dep1,
                dependencies2=all_dep2,
                save_a_file=args.save1,
                save_b_file=args.save2,
            )
        )
    else:
@@ -868,12 +943,15 @@ usage: %(prog)s -h
            argparser.error("FILE2 is required")
        if args.commit2 is not None:
            argparser.error("-2 COMMIT2 provided without -1 COMMIT1")
        a_files: list[pathlib.Path] = [args.file1]
        b_files: list[pathlib.Path] = [args.file2]
        a_files.extend(args.dependencies)
        b_files.extend(args.dependencies)
        a_files = [args.file1, *(args.dep1 or []), *args.dependencies]
        b_files = [args.file2, *(args.dep2 or []), *args.dependencies]
        compat_errors.extend(
            compat_check.compare_files(a_files=a_files, b_files=b_files)
            compat_check.compare_files(
                a_files=a_files,
                b_files=b_files,
                save_a_file=args.save1,
                save_b_file=args.save2,
            )
        )

    if compat_errors:
@@ -885,7 +963,9 @@ usage: %(prog)s -h
        else:
            print(f"File 1:       {args.file1}")
            print(f"File 2:       {args.file2}")
        print(f"Dependencies: {' '.join(str(p) for p in args.dependencies)}")
        print(f"Common deps:  {' '.join(args.dependencies)}")
        print(f"File 1 deps:  {' '.join(args.dep1 or [])}")
        print(f"File 2 deps:  {' '.join(args.dep2 or [])}")
        print("Errors:")
        for error in compat_errors:
            print(f"  {error}")
−1
Changes for testing/asn/lint_asn1.py: 0 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -6,7 +6,6 @@ NOTE: ASN.1 linting is not yet implemented.
# ruff: noqa: ARG001 (unused-function-argument)
# ruff: noqa: INP001 (implicit-namespace-package)
# ruff: noqa: N802 (invalid-function-name)
# ruff: noqa: TC002 (typing-only-third-party-import)

import test_config

+4 −4
Changes for testing/asn/test_config.py: 4 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -12,9 +12,9 @@ type ErrorList = list[str]

type CompatCommitsDict = dict[str, ErrorList]

type CompatFilesDict = dict[pathlib.Path, ErrorList]
type CompatFilesDict = dict[str, ErrorList]

type PathList = list[pathlib.Path]
type PathList = list[str]


class Asn1FileEntry(pydantic.BaseModel):
@@ -47,7 +47,7 @@ class Asn1FileEntry(pydantic.BaseModel):
    )


type Asn1FilesDict = dict[pathlib.Path, Asn1FileEntry]
type Asn1FilesDict = dict[str, Asn1FileEntry]


class TestConfig(pydantic.BaseModel):
@@ -75,7 +75,7 @@ def parse_json_file(path: pathlib.Path) -> TestConfig:
        RuntimeError: Parse or validation error.
    """
    try:
        with pathlib.Path.open(path) as fp:
        with path.open() as fp:
            config = fp.read()
    except Exception as exc:
        raise RuntimeError(f"{path}: {exc}") from exc