From 0f5729d01cf680de91427cb3efc74c3aad232704 Mon Sep 17 00:00:00 2001
From: imcovangent <I.vanGent@tudelft.nl>
Date: Wed, 4 Apr 2018 14:16:29 +0200
Subject: [PATCH] Added method find_cmdows_file( file_list ) to be used by
 interactive VISTOMS.

Former-commit-id: e8ef2914a244e1ef501e462c758174f7aa5a6836
---
 kadmos/cmdows/cmdows.py | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)

diff --git a/kadmos/cmdows/cmdows.py b/kadmos/cmdows/cmdows.py
index d1ef5e03c..65372a00e 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
-- 
GitLab