Loading testing/asn/compat_asn1.py +220 −64 Changes for testing/asn/compat_asn1.py: 220 added lines, 64 removed lines. Original line number Diff line number Diff line Loading @@ -7,7 +7,7 @@ import copy import logging import os import pathlib import subprocess import subprocess # noqa: S404 (suspicious-subprocess-import) import sys import pycrate_asn1c.asnobj as pa_asnobj Loading @@ -28,6 +28,12 @@ def bytes_to_utf8(data: bytes) -> str: Handles issues in legacy commits: - Removes UTF-8 BOM. - Handles Windows-1252 encoding. Args: data: Data to transcode. Returns: UTF-8 encoded string conversion of `data`. """ try: raw = data.decode("utf-8-sig") Loading @@ -40,17 +46,37 @@ def dict_swap(dictionary: dict) -> dict: """Swap keys and values in `dictionary`. Note: Doesn't attempt to handle duplicates. Args: dictionary: dict to swap keys and values. Returns: Swapped dictionary. """ return {value: key for key, value in dictionary.items()} def is_optional(asnobj: pa_asnobj.ASN1Obj) -> bool: """Determine if `asnobj` is OPTIONAL or not.""" """Determine if `asnobj` is OPTIONAL or not. Args: asnobj: ASN.1 object to check. Returns: True if OPTIONAL, False if not. """ return asnobj._flag is not None and pa_asnobj.FLAG_OPT in asnobj._flag def repr_constraint(constraint: pa_asnobj.ASN1Range | int) -> str: """Return constraint as LOWER..UPPER (for ASN1Range) or VALUE (for int).""" """Return constraint as LOWER..UPPER (for ASN1Range) or VALUE (for int). Args: constraint: ASN.1 range or integer to represent. Returns: Constraint representation, as "LOWER..UPPER" or "VALUE". """ if type(constraint) is int: return str(constraint) assert isinstance(constraint, pa_asnobj.ASN1RangeInt) Loading @@ -60,7 +86,14 @@ def repr_constraint(constraint: pa_asnobj.ASN1Range | int) -> str: def repr_modname(asnobj: pa_asnobj.ASN1Obj) -> str: """Return name of `asnobj` as MODULE.NAME or NAME.""" """Return name of `asnobj` as MODULE.NAME or NAME. Args: asnobj: ASN.1 object. Returns: Name of `asnobj` as "MODULE.NAME" or "NAME". """ result = asnobj._name if (asnmod := getattr(asnobj, "_mod", None)) is not None: result = f"{asnmod}.{result}" Loading @@ -70,7 +103,11 @@ def repr_modname(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_name(asnobj: pa_asnobj.ASN1Obj) -> str: """Return name of `asnobj` as MODULE.PARENT.NAME[TAG]. "MODULE.", "PARENT.", and "[TAG]" are optional. Args: asnobj: ASN.1 object. Returns: "MODULE.PARENT.NAME[TAG]". "MODULE.", "PARENT.", and "[TAG]" are optional. """ result = f"{asnobj._name}" if (asnparent := getattr(asnobj, "_parent", None)) is not None: Loading @@ -86,11 +123,14 @@ def repr_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: """Return tag path name of `asnobj` as MODULE.TYPE.TAG[.TAG ...]. "MODULE." and ".TAG" are optional. Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE.TAG[.TAG ...]". "MODULE." and ".TAG" are optional. """ if asnobj._tag is not None: result = str(asnobj._tag[0]) else: result = asnobj._name result = str(asnobj._tag[0]) if asnobj._tag is not None else asnobj._name if (asnparent := getattr(asnobj, "_parent", None)) is not None: result = f"{repr_tagpath(asnparent)}.{result}" Loading @@ -100,7 +140,14 @@ def repr_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_type(asnobj: pa_asnobj.ASN1Obj) -> str: """Return name of type of `asnobj`, as MODULE.TYPE or BASETYPE.""" """Return name of type of `asnobj`, as MODULE.TYPE or BASETYPE. Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE" or "BASETYPE". """ if (tr := asnobj.get_typeref()) is not None: # type reference result = repr_modname(tr) Loading @@ -116,7 +163,11 @@ def repr_type(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_type_name(asnobj: pa_asnobj.ASN1Obj) -> str: """Return type and/or field name for `asnobj`. Returns MODULE.TYPE if asnobj has a type reference or is a type, Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE" if `asnobj` has a type reference or is a type, otherwise the name of the field. """ if (tr := asnobj.get_typeref()) is not None: Loading @@ -134,7 +185,11 @@ def repr_type_name(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_type_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: """Return type and/or tagpath for `asnobj`. Returns MODULE.TYPE if asnobj has a type reference or is a type, Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE" if `asnobj` has a type reference or is a type, otherwise the tagpath (e.g., an unnamed inline container). """ if (tr := asnobj.get_typeref()) is not None: Loading @@ -150,14 +205,14 @@ def repr_type_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: return result class CompatCheckException(Exception): class CompatCheckError(Exception): """Exception raised by CompatCheck.""" class CompatCheck: """Check backwards compatibility between two ASN.1 modules.""" def __init__(self): def __init__(self) -> None: """Construct CompatCheck.""" # key is (commit, filename, tuple(dependencies)), value is parsed ASN1Dict self._cache_commits = {} Loading @@ -175,44 +230,83 @@ class CompatCheck: logger.info(f"Test Failure: {message}") self._errors.append(message) def _read_commit(self, commit: str, filename: str): """Read file `filename` as at git commit `commit`, return text contents.""" def _read_commit(self, commit: str, filename: str) -> str: """Read file `filename` as at git commit `commit`, return text contents. Args: commit: git commit. filename: File. Returns: Contents of `filename` @ `commit`, normalised to UTF-8. Raises: CompatCheckError: Problem reading `filename` at `commit`. """ logger.debug(f"Reading file '{filename}' as at git commit '{commit}'") p = subprocess.run( ["git", "cat-file", "-p", f"{commit}:{filename}"], p = subprocess.run( # noqa: S603 (subprocess-without-shell-equals-true) ["git", "cat-file", "-p", f"{commit}:{filename}"], # noqa: S607 (start-process-with-partial-path) capture_output=True, check=False, text=False, ) if p.returncode != 0: raise CompatCheckException( f"Error reading git commit '{commit}' for file '{filename}': {p.stderr.strip()}" raise CompatCheckError( # noqa: TRY003 (raise-vanilla-args) f"Error reading git commit '{commit}' for " f"file '{filename}': {p.stderr.strip()}" ) return bytes_to_utf8(p.stdout) def _read_file(self, filename: str) -> str: """Read file `filename` and return text contents.""" """Read file `filename` as UTF-8, and return text contents. Args: filename: File to read. Returns: Contents of `filename`. Raises: CompatCheckError: Problem reading `filename`. """ logger.debug(f"Reading file '{filename}'") try: filepath = pathlib.Path(filename) return filepath.read_text() except Exception as ex: # noqa: BLE001 (blind-except) raise CompatCheckException(f"Error reading '{filename}': {ex}") 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 def _parse_asn1_text( self, asn_text: list[str], filenames: list[str] ) -> pa_asnobj.ASN1Dict: """Parse `asn_text` using pycrate, returning the module object.""" """Parse `asn_text` using pycrate, returning the module object. Args: asn_text: List of ASN.1 text strings for the module Returns: Parsed module. """ logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn_text)}'") pycrate_asn1c.asnproc.GLOBAL.clear() pycrate_asn1c.asnproc.compile_text(text=asn_text, filenames=filenames) res = copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD) return res return copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD) def _parse_asn1_commit( self, commit: str, asn_file: str, dependencies: list[str] ) -> pa_asnobj.ASN1Dict: """Parse `asn_file` as at git commit `commit` as ASN.1 using pycrate, returning the module object.""" """Parse `asn_file` as at git commit `commit` as ASN.1 using pycrate. Args: commit: git commit. asn_file: File to parse. dependencies: Optional list of dependencies. Returns: Parsed module object. """ logger.info(f"Parsing {asn_file} as at git commit {commit}") cachekey = (commit, asn_file, tuple(dependencies)) if (cached_parse := self._cache_commits.get(cachekey, None)) is not None: Loading @@ -229,24 +323,36 @@ class CompatCheck: return parse def _parse_asn1_files(self, asn1_files: list[str]) -> pa_asnobj.ASN1Dict: """Parse `asn1_files` as ASN.1 using pycrate, returning the module object.""" """Parse `asn1_files` as ASN.1 using pycrate, returning the module object. Args: asn1_files: List of files to parse. Returns: Parsed module. """ 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 asn_text = [] for filename in asn1_files: asn_text.append(self._read_file(filename)) asn_text = [self._read_file(filename) for filename in asn1_files] parse = self._parse_asn1_text(asn_text=asn_text, filenames=asn1_files) self._cache_files[cachekey] = parse return parse def _container_to_tag_dict(self, container: pa_asnobj.ASN1Dict) -> dict: """Convert `container` to dict indexed on tag, value is type.""" """Convert `container` to dict indexed on tag, value is type. Args: container: ASN.1 container to convert to a dict. Returns: dict of `container`. """ result = {} for name, asntype in container.items(): if asntype._tag is not None: if asntype._tag is not None: # noqa: SIM108 (if-else-block-instead-of-if-exp) tag = asntype._tag[0] else: tag = name # no tag, use the field name Loading @@ -259,9 +365,15 @@ class CompatCheck: fb_type: pa_asnobj.ASN1Obj, seenprefix: str = "", ) -> bool: """Return True if `fa_type` and `fb_type` have already been seen. """Determine if `fa_type` and `fb_type` have already been seen. Args: fa_type: First type. fb_type: Second type. seenprefix: Namespaces the check. `seenprefix` allows for different seen check namespaces. Returns: True if already seen, False if not. """ fa_repr = repr_type_tagpath(fa_type) fb_repr = repr_type_tagpath(fb_type) Loading @@ -274,7 +386,14 @@ class CompatCheck: return False def _decode_constraints(self, asnobj: pa_asnobj.ASN1Obj) -> str: """Return representation of any constraints and defaults of `asnobj`.""" """Return representation of any constraints and defaults of `asnobj`. Args: asnobj: Object to decode Returns: String representation of constraints. """ coding = asnobj["type"] if coding in {pa_asnobj.TYPE_OID, pa_asnobj.TYPE_REL_OID}: return coding Loading Loading @@ -322,7 +441,7 @@ class CompatCheck: f"{fa_desc} constraint '{fa_constraint}' changed to '{fb_constraint}'", ) def _compare_container( def _compare_container( # noqa: C901 (complex-structure) self, fa_type: pa_asnobj.ASN1Obj, fb_type: pa_asnobj.ASN1Obj, Loading Loading @@ -371,20 +490,22 @@ class CompatCheck: if ca_typerepr != cb_typerepr: self._process_error( f"{fa_desc}.{ca_name} type '{ca_typerepr}' changed to '{cb_typerepr}'", f"{fa_desc}.{ca_name} type '{ca_typerepr}' " f"changed to '{cb_typerepr}'", ) ca_optional = is_optional(asnobj=ca_child) cb_optional = is_optional(asnobj=cb_child) if ca_optional != cb_optional: self._process_error( f"{fa_desc}.{ca_name} is now {'mandatory' if ca_optional else 'OPTIONAL'}" f"{fa_desc}.{ca_name} is now " f"{'mandatory' if ca_optional else 'OPTIONAL'}" ) self._compare_asntype(fa_type=ca_child, fb_type=cb_child, module=module) # check new SEQUENCE and SET tags are OPTIONAL if fb_type["type"] not in (pa_asnobj.TYPE_SEQ, pa_asnobj.TYPE_SET): if fb_type["type"] not in {pa_asnobj.TYPE_SEQ, pa_asnobj.TYPE_SET}: return fb_newtags = {tag: fb_tags[tag] for tag in fb_tags.keys() - fa_tags.keys()} Loading Loading @@ -470,7 +591,15 @@ class CompatCheck: fb_tagcount: int, ) -> None: """Compare ASN.1 types `fa_type` and `fb_type` for changes in extensibility. Only used if `module` is not EXTENSIBILITY IMPLIED. Args: fa_type: First type to check. fb_type: Second type to check. module: Module configuration. fa_tagcount: Number of tags in `fa_type`. fb_tagcount: Number of tags in `fb_type`. """ if module["_ext_"] == "IMPLIED": return Loading Loading @@ -505,7 +634,8 @@ class CompatCheck: if fa_type["type"] != fb_type["type"]: self._process_error( f"{fa_desc} type '{fa_type['type']}' mismatch with {fb_desc} '{fb_type['type']}'", f"{fa_desc} type '{fa_type['type']}' " f"mismatch with {fb_desc} '{fb_type['type']}'", ) # No further processing of this type can be performed return Loading @@ -524,8 +654,7 @@ class CompatCheck: def _compare_modules( self, fa_modules: pa_asnobj.ASN1Dict, fb_modules: pa_asnobj.ASN1Dict ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between modules in fa_modules and fb_modules. """Compare ASN.1 for backwards compatibility issues between modules. Issues checked: - Each module is the same: Loading @@ -538,7 +667,12 @@ class CompatCheck: - Same inner type at the tag. - New tags in SEQUENCE and SET are OPTIONAL. Returns a list of error messages (if any). Args: fa_modules: First modules to check. fb_modules: Second modules to check. Returns: List of error messages (if any). """ for module_name, fa_module in fa_modules.items(): if module_name.startswith("_"): Loading @@ -556,7 +690,8 @@ class CompatCheck: if fa_extensible != fb_extensible: self._process_error( f"Module {module_name} is now {'missing ' if not fb_extensible else ''}EXTENSIBILITY IMPLIED" f"Module {module_name} is now " f"{'missing ' if not fb_extensible else ''}EXTENSIBILITY IMPLIED" ) for type_name in fa_module["_type_"]: Loading @@ -577,11 +712,20 @@ class CompatCheck: def compare_commits( self, commit1: str, commit2: str, asn_file: str, dependencies: list[str] ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between `asn_file` at git commit `commit1` and `asn_file` at git commit `commit2`, using optional list of dependencies in `dependencies` at git commit HEAD. """Compare ASN.1 for backwards compatibility issues between commits. Returns a list of error messages (if any). Checks `asn_file` at git commit `commit1` and `asn_file` at git commit `commit2`, using optional list of dependencies in `dependencies` at git commit HEAD. Args: commit1: First git commit. commit2: Second git commit. asn_file: File to check. dependencies: List of files to check. Returns: List of error messages (if any). """ logger.info( f"Comparing file {asn_file} between git commit {commit1} and {commit2}" Loading @@ -599,10 +743,14 @@ class CompatCheck: return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules) def compare_files(self, a_files: list[str], b_files: list[str]) -> list[str]: """Compare ASN.1 for backwards compatibility issues between files `a_files` and files `b_files`. """Compare ASN.1 for backwards compatibility issues between files. Returns a list of error messages (if any). Args: a_files: First list of files to compare. b_files: Second list of files to compare. Returns: List of error messages (if any). """ logger.info(f"Comparing file {a_files[0]} with {b_files[0]}") Loading @@ -614,8 +762,12 @@ class CompatCheck: return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules) def main(): """standalone main.""" def main() -> int: """Standalone main. Returns: Exit code. """ loglevel = os.environ.get("LOGLEVEL", "WARNING").upper() logging.basicConfig(level=loglevel) pycrate_asn1c.utils.logger.setLevel(loglevel) Loading Loading @@ -656,8 +808,8 @@ usage: %(prog)s -h ) args = argparser.parse_args() compatCheck = CompatCheck() compatErrors = [] compat_check = CompatCheck() compat_errors = [] if args.commit1 is not None: if args.file2 is not None: Loading @@ -665,8 +817,8 @@ usage: %(prog)s -h args.file2 = None if args.commit2 is None: args.commit2 = "HEAD" compatErrors.extend( compatCheck.compare_commits( compat_errors.extend( compat_check.compare_commits( commit1=args.commit1, commit2=args.commit2, asn_file=args.file1, Loading @@ -682,9 +834,11 @@ usage: %(prog)s -h b_files = [args.file2] a_files.extend(args.dependencies) b_files.extend(args.dependencies) compatErrors.extend(compatCheck.compare_files(a_files=a_files, b_files=b_files)) compat_errors.extend( compat_check.compare_files(a_files=a_files, b_files=b_files) ) if compatErrors: if compat_errors: print("-----------------------------") if args.commit1: print(f"File: {args.file1}") Loading @@ -695,11 +849,13 @@ usage: %(prog)s -h print(f"File 2: {args.file2}") print(f"Dependencies: {' '.join(args.dependencies)}") print("Errors:") for error in compatErrors: for error in compat_errors: print(f" {error}") print("-----------------------------") sys.exit(1) return 1 return 0 if __name__ == "__main__": main() sys.exit(main()) Loading
testing/asn/compat_asn1.py +220 −64 Changes for testing/asn/compat_asn1.py: 220 added lines, 64 removed lines. Original line number Diff line number Diff line Loading @@ -7,7 +7,7 @@ import copy import logging import os import pathlib import subprocess import subprocess # noqa: S404 (suspicious-subprocess-import) import sys import pycrate_asn1c.asnobj as pa_asnobj Loading @@ -28,6 +28,12 @@ def bytes_to_utf8(data: bytes) -> str: Handles issues in legacy commits: - Removes UTF-8 BOM. - Handles Windows-1252 encoding. Args: data: Data to transcode. Returns: UTF-8 encoded string conversion of `data`. """ try: raw = data.decode("utf-8-sig") Loading @@ -40,17 +46,37 @@ def dict_swap(dictionary: dict) -> dict: """Swap keys and values in `dictionary`. Note: Doesn't attempt to handle duplicates. Args: dictionary: dict to swap keys and values. Returns: Swapped dictionary. """ return {value: key for key, value in dictionary.items()} def is_optional(asnobj: pa_asnobj.ASN1Obj) -> bool: """Determine if `asnobj` is OPTIONAL or not.""" """Determine if `asnobj` is OPTIONAL or not. Args: asnobj: ASN.1 object to check. Returns: True if OPTIONAL, False if not. """ return asnobj._flag is not None and pa_asnobj.FLAG_OPT in asnobj._flag def repr_constraint(constraint: pa_asnobj.ASN1Range | int) -> str: """Return constraint as LOWER..UPPER (for ASN1Range) or VALUE (for int).""" """Return constraint as LOWER..UPPER (for ASN1Range) or VALUE (for int). Args: constraint: ASN.1 range or integer to represent. Returns: Constraint representation, as "LOWER..UPPER" or "VALUE". """ if type(constraint) is int: return str(constraint) assert isinstance(constraint, pa_asnobj.ASN1RangeInt) Loading @@ -60,7 +86,14 @@ def repr_constraint(constraint: pa_asnobj.ASN1Range | int) -> str: def repr_modname(asnobj: pa_asnobj.ASN1Obj) -> str: """Return name of `asnobj` as MODULE.NAME or NAME.""" """Return name of `asnobj` as MODULE.NAME or NAME. Args: asnobj: ASN.1 object. Returns: Name of `asnobj` as "MODULE.NAME" or "NAME". """ result = asnobj._name if (asnmod := getattr(asnobj, "_mod", None)) is not None: result = f"{asnmod}.{result}" Loading @@ -70,7 +103,11 @@ def repr_modname(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_name(asnobj: pa_asnobj.ASN1Obj) -> str: """Return name of `asnobj` as MODULE.PARENT.NAME[TAG]. "MODULE.", "PARENT.", and "[TAG]" are optional. Args: asnobj: ASN.1 object. Returns: "MODULE.PARENT.NAME[TAG]". "MODULE.", "PARENT.", and "[TAG]" are optional. """ result = f"{asnobj._name}" if (asnparent := getattr(asnobj, "_parent", None)) is not None: Loading @@ -86,11 +123,14 @@ def repr_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: """Return tag path name of `asnobj` as MODULE.TYPE.TAG[.TAG ...]. "MODULE." and ".TAG" are optional. Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE.TAG[.TAG ...]". "MODULE." and ".TAG" are optional. """ if asnobj._tag is not None: result = str(asnobj._tag[0]) else: result = asnobj._name result = str(asnobj._tag[0]) if asnobj._tag is not None else asnobj._name if (asnparent := getattr(asnobj, "_parent", None)) is not None: result = f"{repr_tagpath(asnparent)}.{result}" Loading @@ -100,7 +140,14 @@ def repr_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_type(asnobj: pa_asnobj.ASN1Obj) -> str: """Return name of type of `asnobj`, as MODULE.TYPE or BASETYPE.""" """Return name of type of `asnobj`, as MODULE.TYPE or BASETYPE. Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE" or "BASETYPE". """ if (tr := asnobj.get_typeref()) is not None: # type reference result = repr_modname(tr) Loading @@ -116,7 +163,11 @@ def repr_type(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_type_name(asnobj: pa_asnobj.ASN1Obj) -> str: """Return type and/or field name for `asnobj`. Returns MODULE.TYPE if asnobj has a type reference or is a type, Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE" if `asnobj` has a type reference or is a type, otherwise the name of the field. """ if (tr := asnobj.get_typeref()) is not None: Loading @@ -134,7 +185,11 @@ def repr_type_name(asnobj: pa_asnobj.ASN1Obj) -> str: def repr_type_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: """Return type and/or tagpath for `asnobj`. Returns MODULE.TYPE if asnobj has a type reference or is a type, Args: asnobj: ASN.1 object. Returns: "MODULE.TYPE" if `asnobj` has a type reference or is a type, otherwise the tagpath (e.g., an unnamed inline container). """ if (tr := asnobj.get_typeref()) is not None: Loading @@ -150,14 +205,14 @@ def repr_type_tagpath(asnobj: pa_asnobj.ASN1Obj) -> str: return result class CompatCheckException(Exception): class CompatCheckError(Exception): """Exception raised by CompatCheck.""" class CompatCheck: """Check backwards compatibility between two ASN.1 modules.""" def __init__(self): def __init__(self) -> None: """Construct CompatCheck.""" # key is (commit, filename, tuple(dependencies)), value is parsed ASN1Dict self._cache_commits = {} Loading @@ -175,44 +230,83 @@ class CompatCheck: logger.info(f"Test Failure: {message}") self._errors.append(message) def _read_commit(self, commit: str, filename: str): """Read file `filename` as at git commit `commit`, return text contents.""" def _read_commit(self, commit: str, filename: str) -> str: """Read file `filename` as at git commit `commit`, return text contents. Args: commit: git commit. filename: File. Returns: Contents of `filename` @ `commit`, normalised to UTF-8. Raises: CompatCheckError: Problem reading `filename` at `commit`. """ logger.debug(f"Reading file '{filename}' as at git commit '{commit}'") p = subprocess.run( ["git", "cat-file", "-p", f"{commit}:{filename}"], p = subprocess.run( # noqa: S603 (subprocess-without-shell-equals-true) ["git", "cat-file", "-p", f"{commit}:{filename}"], # noqa: S607 (start-process-with-partial-path) capture_output=True, check=False, text=False, ) if p.returncode != 0: raise CompatCheckException( f"Error reading git commit '{commit}' for file '{filename}': {p.stderr.strip()}" raise CompatCheckError( # noqa: TRY003 (raise-vanilla-args) f"Error reading git commit '{commit}' for " f"file '{filename}': {p.stderr.strip()}" ) return bytes_to_utf8(p.stdout) def _read_file(self, filename: str) -> str: """Read file `filename` and return text contents.""" """Read file `filename` as UTF-8, and return text contents. Args: filename: File to read. Returns: Contents of `filename`. Raises: CompatCheckError: Problem reading `filename`. """ logger.debug(f"Reading file '{filename}'") try: filepath = pathlib.Path(filename) return filepath.read_text() except Exception as ex: # noqa: BLE001 (blind-except) raise CompatCheckException(f"Error reading '{filename}': {ex}") 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 def _parse_asn1_text( self, asn_text: list[str], filenames: list[str] ) -> pa_asnobj.ASN1Dict: """Parse `asn_text` using pycrate, returning the module object.""" """Parse `asn_text` using pycrate, returning the module object. Args: asn_text: List of ASN.1 text strings for the module Returns: Parsed module. """ logger.debug(f"Parsing ASN.1 text '{'\n'.join(asn_text)}'") pycrate_asn1c.asnproc.GLOBAL.clear() pycrate_asn1c.asnproc.compile_text(text=asn_text, filenames=filenames) res = copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD) return res return copy.deepcopy(pycrate_asn1c.asnproc.GLOBAL.MOD) def _parse_asn1_commit( self, commit: str, asn_file: str, dependencies: list[str] ) -> pa_asnobj.ASN1Dict: """Parse `asn_file` as at git commit `commit` as ASN.1 using pycrate, returning the module object.""" """Parse `asn_file` as at git commit `commit` as ASN.1 using pycrate. Args: commit: git commit. asn_file: File to parse. dependencies: Optional list of dependencies. Returns: Parsed module object. """ logger.info(f"Parsing {asn_file} as at git commit {commit}") cachekey = (commit, asn_file, tuple(dependencies)) if (cached_parse := self._cache_commits.get(cachekey, None)) is not None: Loading @@ -229,24 +323,36 @@ class CompatCheck: return parse def _parse_asn1_files(self, asn1_files: list[str]) -> pa_asnobj.ASN1Dict: """Parse `asn1_files` as ASN.1 using pycrate, returning the module object.""" """Parse `asn1_files` as ASN.1 using pycrate, returning the module object. Args: asn1_files: List of files to parse. Returns: Parsed module. """ 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 asn_text = [] for filename in asn1_files: asn_text.append(self._read_file(filename)) asn_text = [self._read_file(filename) for filename in asn1_files] parse = self._parse_asn1_text(asn_text=asn_text, filenames=asn1_files) self._cache_files[cachekey] = parse return parse def _container_to_tag_dict(self, container: pa_asnobj.ASN1Dict) -> dict: """Convert `container` to dict indexed on tag, value is type.""" """Convert `container` to dict indexed on tag, value is type. Args: container: ASN.1 container to convert to a dict. Returns: dict of `container`. """ result = {} for name, asntype in container.items(): if asntype._tag is not None: if asntype._tag is not None: # noqa: SIM108 (if-else-block-instead-of-if-exp) tag = asntype._tag[0] else: tag = name # no tag, use the field name Loading @@ -259,9 +365,15 @@ class CompatCheck: fb_type: pa_asnobj.ASN1Obj, seenprefix: str = "", ) -> bool: """Return True if `fa_type` and `fb_type` have already been seen. """Determine if `fa_type` and `fb_type` have already been seen. Args: fa_type: First type. fb_type: Second type. seenprefix: Namespaces the check. `seenprefix` allows for different seen check namespaces. Returns: True if already seen, False if not. """ fa_repr = repr_type_tagpath(fa_type) fb_repr = repr_type_tagpath(fb_type) Loading @@ -274,7 +386,14 @@ class CompatCheck: return False def _decode_constraints(self, asnobj: pa_asnobj.ASN1Obj) -> str: """Return representation of any constraints and defaults of `asnobj`.""" """Return representation of any constraints and defaults of `asnobj`. Args: asnobj: Object to decode Returns: String representation of constraints. """ coding = asnobj["type"] if coding in {pa_asnobj.TYPE_OID, pa_asnobj.TYPE_REL_OID}: return coding Loading Loading @@ -322,7 +441,7 @@ class CompatCheck: f"{fa_desc} constraint '{fa_constraint}' changed to '{fb_constraint}'", ) def _compare_container( def _compare_container( # noqa: C901 (complex-structure) self, fa_type: pa_asnobj.ASN1Obj, fb_type: pa_asnobj.ASN1Obj, Loading Loading @@ -371,20 +490,22 @@ class CompatCheck: if ca_typerepr != cb_typerepr: self._process_error( f"{fa_desc}.{ca_name} type '{ca_typerepr}' changed to '{cb_typerepr}'", f"{fa_desc}.{ca_name} type '{ca_typerepr}' " f"changed to '{cb_typerepr}'", ) ca_optional = is_optional(asnobj=ca_child) cb_optional = is_optional(asnobj=cb_child) if ca_optional != cb_optional: self._process_error( f"{fa_desc}.{ca_name} is now {'mandatory' if ca_optional else 'OPTIONAL'}" f"{fa_desc}.{ca_name} is now " f"{'mandatory' if ca_optional else 'OPTIONAL'}" ) self._compare_asntype(fa_type=ca_child, fb_type=cb_child, module=module) # check new SEQUENCE and SET tags are OPTIONAL if fb_type["type"] not in (pa_asnobj.TYPE_SEQ, pa_asnobj.TYPE_SET): if fb_type["type"] not in {pa_asnobj.TYPE_SEQ, pa_asnobj.TYPE_SET}: return fb_newtags = {tag: fb_tags[tag] for tag in fb_tags.keys() - fa_tags.keys()} Loading Loading @@ -470,7 +591,15 @@ class CompatCheck: fb_tagcount: int, ) -> None: """Compare ASN.1 types `fa_type` and `fb_type` for changes in extensibility. Only used if `module` is not EXTENSIBILITY IMPLIED. Args: fa_type: First type to check. fb_type: Second type to check. module: Module configuration. fa_tagcount: Number of tags in `fa_type`. fb_tagcount: Number of tags in `fb_type`. """ if module["_ext_"] == "IMPLIED": return Loading Loading @@ -505,7 +634,8 @@ class CompatCheck: if fa_type["type"] != fb_type["type"]: self._process_error( f"{fa_desc} type '{fa_type['type']}' mismatch with {fb_desc} '{fb_type['type']}'", f"{fa_desc} type '{fa_type['type']}' " f"mismatch with {fb_desc} '{fb_type['type']}'", ) # No further processing of this type can be performed return Loading @@ -524,8 +654,7 @@ class CompatCheck: def _compare_modules( self, fa_modules: pa_asnobj.ASN1Dict, fb_modules: pa_asnobj.ASN1Dict ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between modules in fa_modules and fb_modules. """Compare ASN.1 for backwards compatibility issues between modules. Issues checked: - Each module is the same: Loading @@ -538,7 +667,12 @@ class CompatCheck: - Same inner type at the tag. - New tags in SEQUENCE and SET are OPTIONAL. Returns a list of error messages (if any). Args: fa_modules: First modules to check. fb_modules: Second modules to check. Returns: List of error messages (if any). """ for module_name, fa_module in fa_modules.items(): if module_name.startswith("_"): Loading @@ -556,7 +690,8 @@ class CompatCheck: if fa_extensible != fb_extensible: self._process_error( f"Module {module_name} is now {'missing ' if not fb_extensible else ''}EXTENSIBILITY IMPLIED" f"Module {module_name} is now " f"{'missing ' if not fb_extensible else ''}EXTENSIBILITY IMPLIED" ) for type_name in fa_module["_type_"]: Loading @@ -577,11 +712,20 @@ class CompatCheck: def compare_commits( self, commit1: str, commit2: str, asn_file: str, dependencies: list[str] ) -> list[str]: """Compare ASN.1 for backwards compatibility issues between `asn_file` at git commit `commit1` and `asn_file` at git commit `commit2`, using optional list of dependencies in `dependencies` at git commit HEAD. """Compare ASN.1 for backwards compatibility issues between commits. Returns a list of error messages (if any). Checks `asn_file` at git commit `commit1` and `asn_file` at git commit `commit2`, using optional list of dependencies in `dependencies` at git commit HEAD. Args: commit1: First git commit. commit2: Second git commit. asn_file: File to check. dependencies: List of files to check. Returns: List of error messages (if any). """ logger.info( f"Comparing file {asn_file} between git commit {commit1} and {commit2}" Loading @@ -599,10 +743,14 @@ class CompatCheck: return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules) def compare_files(self, a_files: list[str], b_files: list[str]) -> list[str]: """Compare ASN.1 for backwards compatibility issues between files `a_files` and files `b_files`. """Compare ASN.1 for backwards compatibility issues between files. Returns a list of error messages (if any). Args: a_files: First list of files to compare. b_files: Second list of files to compare. Returns: List of error messages (if any). """ logger.info(f"Comparing file {a_files[0]} with {b_files[0]}") Loading @@ -614,8 +762,12 @@ class CompatCheck: return self._compare_modules(fa_modules=fa_modules, fb_modules=fb_modules) def main(): """standalone main.""" def main() -> int: """Standalone main. Returns: Exit code. """ loglevel = os.environ.get("LOGLEVEL", "WARNING").upper() logging.basicConfig(level=loglevel) pycrate_asn1c.utils.logger.setLevel(loglevel) Loading Loading @@ -656,8 +808,8 @@ usage: %(prog)s -h ) args = argparser.parse_args() compatCheck = CompatCheck() compatErrors = [] compat_check = CompatCheck() compat_errors = [] if args.commit1 is not None: if args.file2 is not None: Loading @@ -665,8 +817,8 @@ usage: %(prog)s -h args.file2 = None if args.commit2 is None: args.commit2 = "HEAD" compatErrors.extend( compatCheck.compare_commits( compat_errors.extend( compat_check.compare_commits( commit1=args.commit1, commit2=args.commit2, asn_file=args.file1, Loading @@ -682,9 +834,11 @@ usage: %(prog)s -h b_files = [args.file2] a_files.extend(args.dependencies) b_files.extend(args.dependencies) compatErrors.extend(compatCheck.compare_files(a_files=a_files, b_files=b_files)) compat_errors.extend( compat_check.compare_files(a_files=a_files, b_files=b_files) ) if compatErrors: if compat_errors: print("-----------------------------") if args.commit1: print(f"File: {args.file1}") Loading @@ -695,11 +849,13 @@ usage: %(prog)s -h print(f"File 2: {args.file2}") print(f"Dependencies: {' '.join(args.dependencies)}") print("Errors:") for error in compatErrors: for error in compat_errors: print(f" {error}") print("-----------------------------") sys.exit(1) return 1 return 0 if __name__ == "__main__": main() sys.exit(main())