Commit 1e3df69b authored by Luke Mewburn's avatar Luke Mewburn Committed by Luke Mewburn
Browse files

asn_process: fix ruff check, ty check, and typos

parent e0608713
Loading
Loading
Loading
Loading
+43 −34
Changes for testing/asn/asn_process.py: 43 added lines, 34 removed lines.
Original line number Diff line number Diff line
@@ -2,16 +2,17 @@ import json
import logging
import shutil
import subprocess

import sys
from pathlib import Path

# Luke has fixed the updstream issue with multiple imports in pycrate
# https://github.com/pycrate-org/pycrate/pull/57
# but it isn't yet included in the distribution (still at 0.7.11 , Jul 2025)
# When this gets updated we may be able to use only pycrate, and drop the use of asn1c

import pycrate_asn1c.asnproc

logger = logging.getLogger(__name__)


def reconstrainInteger(filename):
    Path("temp.asn").write_text(
@@ -54,14 +55,16 @@ def syntaxCheckASN(fileList):
            if file.as_posix() in filesWithBigInts:
                newFile = reconstrainInteger(str(file))
                p = subprocess.run(
                    [asn1c_path, "-E", fix_path(newFile)],
                    [str(asn1c_path), "-E", fix_path(newFile)],
                    capture_output=True,
                    check=False,
                )
                Path(newFile).unlink()
            else:
                p = subprocess.run(
                    [asn1c_path, "-E", fix_path(str(file))],
                    [str(asn1c_path), "-E", fix_path(str(file))],
                    capture_output=True,
                    check=False,
                )
            if p.returncode != 0:
                errorMessage = p.stderr.decode().splitlines()[0]
@@ -76,8 +79,8 @@ def syntaxCheckASN(fileList):
            else:
                results[str(file)] = {"ok": True}
        except Exception as ex:
            raise ex
            results[str(file)] = {"ok": False, "code": -1, "message": f"{ex!r}"}
            raise
    return results


@@ -108,7 +111,7 @@ def compileAllTargets(compileTargets):
    :returns: A dict of outcome against the first filename of each compile target. Return code and message are included for failures.

    For each compile target (list of filenames) the first filename is assumed
    to be the "primary" file. This doesn't have any relavance to the compilation,
    to be the "primary" file. This doesn't have any relevance to the compilation,
    but will be used as the identifier when reporting any compile errors.
    The compilation is performed by the pycrate ASN compile functions; errors
    are caught as exceptions and rendered into a list.
@@ -121,7 +124,7 @@ def compileAllTargets(compileTargets):
    results = {}
    for target in compileTargets:
        firstTarget = target[0]
        logging.debug(f"Compiling {firstTarget}")
        logger.debug(f"Compiling {firstTarget}")
        try:
            fileTexts = []
            fileNames = []
@@ -135,12 +138,12 @@ def compileAllTargets(compileTargets):
                else:
                    fileTexts.append(pFile.read_text())
                fileNames.append(filename)
                logging.debug(f"  Loading {filename}")
                logger.debug(f"  Loading {filename}")
            pycrate_asn1c.asnproc.compile_text(fileTexts, filenames=fileNames)
            results[str(firstTarget)] = {
                "ok": True,
            }
        except Exception as ex:
        except Exception as ex:  # noqa: BLE001 (blind-except)
            results[str(firstTarget)] = {"ok": False, "code": -1, "message": f"{ex!r}"}
            continue
    return results
@@ -154,9 +157,9 @@ def processResults(results, stageName):
    :param stageName: Name to decorate the output with
    :returns: The number of files which had errors
    """
    print("")
    print()
    errorCount = sum([1 for r in results.values() if not r["ok"]])
    logging.info(f"{errorCount} {stageName} errors encountered")
    logger.info(f"{errorCount} {stageName} errors encountered")

    print(f"{'-':-<60}")
    print(f"{stageName} results:")
@@ -177,62 +180,68 @@ def processResults(results, stageName):
    return errorCount


if __name__ == "__main__":
    logging.info("Searching for ASN1C")
def main():
    logger.info("Searching for ASN1C")
    global asn1c_path
    asn1c_path = shutil.which("asn1c")
    if asn1c_path is None:
        raise Exception("No asn1c executable found. Please install asn1c")
    logging.info(f"asn1c found at {asn1c_path}")
        raise RuntimeError("No asn1c executable found. Please install asn1c")
    logger.info(f"asn1c found at {asn1c_path}")
    if asn1c_path.lower().endswith("bat"):
        logging.info(
            f"asn1c is a batch file, so assume path separators need to be changed"
        logger.info(
            "asn1c is a batch file, so assume path separators need to be changed"
        )
        global change_path_to_unix
        change_path_to_unix = True

    logging.info("Searching for ASN.1 files")
    logger.info("Searching for ASN.1 files")
    fileList = list(Path(".").rglob("*.asn1")) + list(Path(".").rglob("*.asn"))
    logging.info(f"{len(fileList)} ASN.1 files found")
    logger.info(f"{len(fileList)} ASN.1 files found")
    for file in fileList:
        logging.debug(f"  {file}")
        logger.debug(f"  {file}")

    ignoreList = Path("testing/asn/asn_ignore.txt").read_text().splitlines()
    ignoredFiles = []
    for ignore in ignoreList:
        logging.debug(f"Ignoring pattern {ignore}")
        logger.debug(f"Ignoring pattern {ignore}")
        for file in fileList:
            if ignore in str(file):
                ignoredFiles.append(file)
                logging.debug(f" Ignoring {str(file)} as contains {ignore}")
                logger.debug(f" Ignoring {file!s} as contains {ignore}")
    ignoredFiles = list(set(ignoredFiles))
    logging.info(f"{len(ignoredFiles)} files ignored")
    logger.info(f"{len(ignoredFiles)} files ignored")
    for file in ignoredFiles:
        logging.debug(f"  {file}")
        logger.debug(f"  {file}")

    fileList = [file for file in fileList if file not in ignoredFiles]
    logging.info(f"{len(fileList)} files to process")
    logger.info(f"{len(fileList)} files to process")
    for file in fileList:
        logging.debug(f"  {file}")
        logger.debug(f"  {file}")

    if len(fileList) == 0:
        logging.warning("No files specified")
        exit(0)
        logger.warning("No files specified")
        return 1

    logging.info("Parsing ASN1 files")
    logger.info("Parsing ASN1 files")
    parseResults = syntaxCheckASN(fileList)
    if processResults(parseResults, "Parsing") > 0:
        exit(-1)
        return 1

    logging.info("Getting compile targets")
    logger.info("Getting compile targets")
    compileTargets = json.loads(
        Path("testing/asn/asn_compile_targets.json").read_text()
    )
    logging.info(f"{len(compileTargets)} compile targets found")
    logger.info(f"{len(compileTargets)} compile targets found")

    compileResults = compileAllTargets(compileTargets)
    if processResults(compileResults, "Compiling") > 0:
        exit(-1)
        return 1

    if Path("temp.asn").exists():
        Path("temp.asn").unlink()

    exit(0)
    return 0


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