예제 #1
0
def getVersion(extrBcfPath: str, versionSchemaPath: str):
    """
    Tries to open `extrBcfPath`/bcf.version. If successful it parses it
    into a python dictonary and returns the content of the attribute
    `VersionId` of the element `Version`.

    If `bcf.version` was not found a ValueError is raised. If `bcf.version`
    does not parse against versionSchema then `None` is returned.
    """

    logger.debug("Retrieving version from the BCF project")
    versionFileName = "bcf.version"
    versionFilePath = os.path.join(extrBcfPath, versionFileName)
    if not os.path.exists(versionFilePath):
        raise ValueError("{} was not found in the extracted zip archive {}."\
                "Make sure that you opened a correct bcf zip archive.".format(
                    versionFileName,
                    os.path.basename(extrBcfPath)))

    versionSchema = XMLSchema(versionSchemaPath)
    if not versionSchema.is_valid(versionFilePath):
        return None

    versionDict = versionSchema.to_dict(versionFilePath)
    version = versionDict["@VersionId"]
    logger.debug("Version of the BCF project is {}".format(version))
    return version
예제 #2
0
 def is_valid(self):
     """ Check if XML is valid with XSD file """
     if self.xsd_path is not None:
         xsd_file = XMLSchema(self.xsd_path)
         xml_file = ElementTree.parse(self.get_xml_path())
         return xsd_file.is_valid(xml_file)
     return False
예제 #3
0
class EntriesParser:
    def __init__(self):
        self.db = Database()
        self.schema = XMLSchema(f"res{os.sep}schemas{os.sep}plugin_schema.xsd")

    def validatePluginSchema(self, instancePath):
        xml = open(instancePath, "r").read().strip()
        return self.schema.is_valid(xml)

    def getPluginFromXml(self, instancePath):
        xml = open(instancePath, "r").read().strip()
        tree = ET.fromstring(xml)
        plugin = PluginItem()
        plugin.name = tree[0].text
        plugin.description = tree[1].text
        plugin.types = ["All"] + [t.text for t in tree[2]]
        plugin.outputs = [o.text for o in tree[3]]
        for i in range(4, len(tree)):
            poi = {}
            poi['name'] = tree[i][0].text
            poi['type'] = tree[i][1].text
            poi['map'] = tree[i][2].text
            plugin.pois[tree[i][0].text] = poi
        self.db.updateEntry("plugin", plugin.asDictionary())

    def updateEntry(self, which, item):
        if which == "project":
            self.db.updateEntry("project", item.asDictionary())
        if which == "plugin":
            self.db.updateEntry("plugin", item.asDictionary())

    def getEntries(self, which):
        if which == "plugin":
            entries = {}
            for entry in self.db.getEntries('plugin'):
                item = PluginItem()
                item.id = entry['_id']
                item.name = entry['name']
                item.description = entry['description']
                item.outputs = entry['fields']
                item.pois = entry['pois']
                item.types = entry['types']
                entries[item.name] = item
            return entries
        if which == "project":
            entries = {}
            for entry in self.db.getEntries('project'):
                item = ProjectItem()
                item.id = entry['_id']
                item.name = entry['name']
                item.description = entry['description']
                item.binaryPath = entry['path']
                item.binaryProperties = entry['properties']
                item.results = entry['results']
                entries[item.name] = item
            return entries

    def deleteEntry(self, which, item):
        self.db.deleteEntry(which, item.id)
예제 #4
0
    def parser(self, xml, xsd, pattern=None):
        """
        Validate xml to match with xsd. Calling parsers to get Model from xml. If provided pattern, filtering Model.
        :param xml: path to MOBILE_API.xml
        :param xsd: path to MOBILE_API.xsd
        :param pattern: regex-pattern from command-line arguments to filter element from initial Model
        :return: initial Model
        """
        self.logger.info(
            '''Validating XML and generating model with following parameters:
            Source xml      : %s
            Source xsd      : %s''', xml, xsd)

        try:
            schema = XMLSchema(xsd)
            if not schema.is_valid(xml):
                raise GenerateError(schema.validate(xml))
            interface = Parser().parse(xml)
        except (InterfaceError, XMLSchemaError, GenerateError) as message1:
            self.logger.critical('Invalid XML file content: %s, %s', xml,
                                 message1)
            sys.exit(1)

        enum_names = tuple(interface.enums.keys())
        struct_names = tuple(interface.structs.keys())

        if pattern:
            intermediate = OrderedDict()
            intermediate.update({'params': interface.params})
            for kind, content in vars(interface).items():
                if kind == 'params':
                    continue
                for name, item in content.items():
                    if re.match(pattern, item.name):
                        self.logger.info('%s/%s match with %s', kind,
                                         item.name, pattern)
                        if kind in intermediate:
                            intermediate[kind].update({name: item})
                        else:
                            intermediate.update({kind: {name: item}})
            interface = Interface(**intermediate)

        self.logger.debug({
            'enums':
            tuple(interface.enums.keys()),
            'structs':
            tuple(interface.structs.keys()),
            'functions':
            tuple(
                map(lambda i: i.function_id.name,
                    interface.functions.values())),
            'params':
            interface.params
        })
        return enum_names, struct_names, interface
예제 #5
0
    def parse(self, filename, xsd=None):
        filename = str(filename)
        if not xsd:
            if not Path(filename).exists():
                raise modelParseError('File not found: ' + filename)
            replace = filename.replace('.xml', '.xsd')
            if Path(replace).exists():
                xsd = replace
            else:
                raise modelParseError('File not found: ' + replace)

        try:
            schema = XMLSchema(xsd)
            if not schema.is_valid(filename):
                raise modelParseError('Invalid XML file content:\n' +
                                      schema.validate(filename))
            return super(Parser, self).parse(filename)
        except xmlParseError as error:
            raise modelParseError(error)
예제 #6
0
def load_xml(schema: XMLSchema, p: Path) -> Dict:
    assert schema.is_valid(str(p)), f"invalid xml detected! {p}"
    return schema.to_dict(str(p))