Skip to content

Commit

Permalink
moved version checking and xml tree conversion to package.py
Browse files Browse the repository at this point in the history
Signed-off-by: Anton Utz <[email protected]>
  • Loading branch information
ant-u committed Nov 29, 2024
1 parent 3ece023 commit bc4fabf
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 35 deletions.
61 changes: 26 additions & 35 deletions src/ros_license_toolkit/license_checks/schema_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from lxml import etree

from ros_license_toolkit.checks import Check
from ros_license_toolkit.package import Package


class SchemaCheck(Check):
Expand All @@ -34,56 +35,46 @@ def __init__(self):
xml_schema_1_parsed = etree.parse('./schemas/package_format1.xsd')
self.xml_schema_1 = etree.XMLSchema(xml_schema_1_parsed)

def _check(self, package):
version, status = self.validate(package.abspath + "/package.xml")
def _check(self, package: Package):
status, message = self.validate(package)
version: int = package.package_xml_format_ver
if status:
self._success(f"Detected package.xml version {version}, "
"validation of scheme successful.")
else:
reason = ''
if version == 1:
reason = "package.xml contains errors: " +\
f"{self.xml_schema_1.error_log.last_error.message}"
elif version == 2:
reason = "package.xml contains errors: " +\
f"{self.xml_schema_2.error_log.last_error.message}"
elif version == 3:
reason = "package.xml contains errors: " +\
f"{self.xml_schema_3.error_log.last_error.message}"
# Temporary workaround for not implemented version 4
elif version == 4:
if version == 4:
reason = "couldn't check package.xml scheme. Version 4 is " +\
"not available right now"
self._warning(reason)
return
elif version == -1:

if message != '':
reason = f"package.xml contains errors: {message}"
else:
reason = "package.xml does not contain correct package " +\
"format number. Please use a real version. " +\
"(e.g. <package format=\"3\">)"
self._failed(reason)

def validate(self, pck_xml_path: str) -> Tuple[int, bool]:
def validate(self, package: Package) -> Tuple[bool, str]:
"""This is validating package.xml file from given path.
Automatically detects version number and validates
it with corresponding scheme, e.g. format 3.
If everything is correct, returns format number, else -1."""
xml_doc_parsed = etree.parse(pck_xml_path)
for element in xml_doc_parsed.getiterator():
if element.tag == 'package' and 'format' in element.attrib:
version = element.attrib['format']
status_check = False
if version == '3':
version = 3
status_check = self.xml_schema_3.validate(xml_doc_parsed)
elif version == '2':
version = 2
status_check = self.xml_schema_2.validate(xml_doc_parsed)
elif version == '1':
version = 1
status_check = self.xml_schema_1.validate(xml_doc_parsed)
elif version == '4': # Work around: 4 not available right now
version = 4
else:
version = -1
return (version, status_check)
return (-1, False)
version = package.package_xml_format_ver
xml_doc = package.parsed_package_xml
validation_schema: etree.XMLSchema = False
if version == 3:
validation_schema = self.xml_schema_3
elif version == 2:
validation_schema = self.xml_schema_2
elif version == 1:
validation_schema = self.xml_schema_1
if validation_schema:
status_check = validation_schema.validate(xml_doc)
message = ''
if not status_check:
message = validation_schema.error_log.last_error_message
return status_check, message
return False, message
33 changes: 33 additions & 0 deletions src/ros_license_toolkit/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import xml.etree.ElementTree as ET
from typing import Any, Dict, List, Optional

from lxml import etree
from rospkg import RosPack, list_by_path
from rospkg.common import PACKAGE_FILE
from scancode.api import get_licenses
Expand Down Expand Up @@ -83,6 +84,12 @@ def __init__(self, path: str, repo: Optional[Repo] = None):
# All ignored files and folders
self._ignored_content: List[str] = get_ignored_content(self.abspath)

# The package.xml file, parsed as etree
self._parsed_package_xml: etree = None

# The package.xml version as set in <package format="x">
self._package_xml_format_ver: int = 0

def _get_path_relative_to_pkg(self, path: str) -> str:
"""Get path relative to pkg root"""
return os.path.relpath(path, self.abspath)
Expand Down Expand Up @@ -230,6 +237,32 @@ def license_tags(self) -> Dict[str, LicenseTag]:

return self._license_tags

@property
def package_xml_format_ver(self) -> int:
"""Returns version of package.xml format as seen in
<package format="3">. If Version is not valid, -1 is returned."""
if self._package_xml_format_ver is None:
root = self.parsed_package_xml.getroot()
if root.tag == 'package':
if 'format' in root.attrib:
version = root.attrib['format']
try:
self._package_xml_format_ver = int(version)
except ValueError:
self._package_xml_format_ver = -1
return self._package_xml_format_ver
self._package_xml_format_ver = -1
return self._package_xml_format_ver

@property
def parsed_package_xml(self) -> etree:
"""Returns the package.xml content parsed as etree."""
if self._parsed_package_xml == 0:
path = self.abspath + "/package.xml"
assert os.path.exists(path), f'Path {path} does not exist.'
self._parsed_package_xml = etree.parse(path)
return self._parsed_package_xml

@property
def repo_url(self) -> Optional[str]:
"""Get the url of the repo this package is in if the package is in a
Expand Down

0 comments on commit bc4fabf

Please sign in to comment.