diff --git a/kadmos/cmdows/cmdows.py b/kadmos/cmdows/cmdows.py index d1ef5e03c8fff63f9ae630a3a173fb6f606ca39d..65372a00e55502f70f6338a00052cfa0c689d746 100644 --- a/kadmos/cmdows/cmdows.py +++ b/kadmos/cmdows/cmdows.py @@ -771,6 +771,46 @@ class CMDOWS(object): ElementTree(self.root).write(file_path, pretty_print=pretty_print, method=method, xml_declaration=xml_declaration, encoding=encoding) + +# ----------------------------------------- # +# Static functions # +# ----------------------------------------- # +def find_cmdows_file(file_list): + """Function to find the CMDOWS file among a list of files. + + :param file_list: list with file names to be checked for being a CMDOWS file + :type file_list: list + :return: name of the CMDOWS file in the list + :rtype: basestring + """ + + # Input assertions + assert isinstance(file_list, list), 'File list should be a list, not it is of type {}.'.format(type(file_list)) + for file_name in file_list: + assert os.path.isfile(file_name), 'Item {} in file_list does not appear to be a file.'.format(file_name) + + # Loop through the list and check first for XML extension + xml_files = [file_name for file_name in file_list if file_name.endswith('.xml')] + + # Loop through the xml_files and check which ones have the root CMDOWS + cmdows_files = [] + for xml_file in xml_files: + try: + xml_root = etree.parse(xml_file, parser).getroot() + if xml_root.tag == 'cmdows': + cmdows_files.append(xml_file) + except: + logger.warning('Could not parse XML file {} for some reason.'.format(xml_file)) + + # Check the results and return the right message + if not cmdows_files: + raise AssertionError('Could not find a CMDOWS file in the list of files.') + elif len(cmdows_files) == 1: + return cmdows_files[0] + elif len(cmdows_files) > 1: + raise AssertionError('Multiple CMDOWS files were found {} in the list of files.'.format(cmdows_files)) + + # Set element on the module level parser.set_element_class_lookup(etree.ElementDefaultClassLookup(element=ExtendedElement)) Element = parser.makeelement