1#! /usr/bin/python3
2
3# Copyright (c) 2014, Intel Corporation
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without modification,
7# are permitted provided that the following conditions are met:
8#
9# 1. Redistributions of source code must retain the above copyright notice, this
10# list of conditions and the following disclaimer.
11#
12# 2. Redistributions in binary form must reproduce the above copyright notice,
13# this list of conditions and the following disclaimer in the documentation and/or
14# other materials provided with the distribution.
15#
16# 3. Neither the name of the copyright holder nor the names of its contributors
17# may be used to endorse or promote products derived from this software without
18# specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
24# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
27# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31from os import path
32from os import walk
33from sys import argv
34
35from lxml import etree
36
37class PrintColor():
38    @staticmethod
39    def success(stringToPrint):
40        green = 32
41        PrintColor._printColor(green, stringToPrint)
42
43    @staticmethod
44    def error(stringToPrint):
45        red = 31
46        PrintColor._printColor(red, stringToPrint)
47
48    @staticmethod
49    def _printColor(color, stringToPrint):
50        """prints strings in color via ascii escape sequence"""
51        print("\033[%sm%s\033[0m" % (str(color), stringToPrint))
52
53def getSchemaFilenameFromXmlFile(xmlFilePath):
54    """getSchemaFileNameFromXmlFile
55
56    The pfw considers that the .xsd file has the same name as the
57    root element name of the .xml.
58    With of this knowledge, we may easily find the
59    schema file we need.
60
61    Args:
62        xmlFilePath: the xml file.
63
64    Returns:
65        str: the corresponding .schema name
66    """
67    xmlTree = etree.parse(xmlFilePath)
68    rootElement = xmlTree.getroot()
69    return rootElement.tag + '.xsd'
70
71def validateXmlWithSchema(xmlFilePath, schemaFilePath):
72    """validateXmlWithSchema
73
74    Validates an .xml file based on his corresponding schema.
75
76    Args:
77        xmlFilePath (str): the absolute path to the xml file.
78        schemaFilePath (str): the absolute path to the schema.
79    """
80    baseXmlName = path.basename(xmlFilePath)
81    baseSchemaName = path.basename(schemaFilePath)
82    print 'Attempt to validate', baseXmlName, 'with', baseSchemaName
83
84    schemaContent = etree.parse(schemaFilePath)
85    schema = etree.XMLSchema(schemaContent)
86    xmlContent = etree.parse(xmlFilePath)
87    xmlContent.xinclude()
88
89    if schema.validate(xmlContent):
90        PrintColor.success('%s is valid' % str(baseXmlName))
91    else:
92        PrintColor.error('Error: %s' % str(schema.error_log))
93
94# handle main arguments
95if len(argv) != 3:
96    PrintColor.error('Error: usage %s xmlDirectory schemaDirectory' % str(argv[0]))
97    exit(1)
98
99xmlDirectory = argv[1]
100schemaDirectory = argv[2]
101
102print('[*] Validate xml files in %s with %s' % (xmlDirectory, schemaDirectory))
103
104for rootPath, _, files in walk(xmlDirectory):
105    for filename in files:
106        if filename.endswith('.xml'):
107            xmlFilePath = path.join(rootPath, filename)
108            schemaFileName = getSchemaFilenameFromXmlFile(xmlFilePath)
109            schemaFilePath = path.join(schemaDirectory, schemaFileName)
110            validateXmlWithSchema(xmlFilePath, schemaFilePath)
111