Select Git revision
xml-lint 2.36 KiB
#!/usr/bin/python
import os.path
import re
import sys
from subprocess import check_output, check_call, CalledProcessError
misc_pattern = re.compile('<resource\s*url="(.+?)"\s*location="(.+?)"\s+\/>')
xsd_pattern = re.compile('xsi:noNamespaceSchemaLocation="(.+?)"')
def get_mappings(misc_file, base_dir):
mapping = {}
for line in open(misc_file):
result = misc_pattern.search(line)
if result is not None:
mapping[result.group(1)] = result.group(2).replace('$PROJECT_DIR$', base_dir)
return mapping
def get_xml_files(search_dir):
try:
return check_output(['find', search_dir, '-name', '*.xml']).splitlines()
except CalledProcessError:
print("WARNING: No XML files found")
return []
def lint_only(file):
try:
check_call(['xmllint', '--noout', file])
except CalledProcessError as err:
exit(err.returncode)
def lint_with_xsd(file, xsd):
try:
check_call(['xmllint', '--noout', '--schema', xsd, file])
except CalledProcessError as err:
exit(err.returncode)
def search_file_for_xsd(file):
handle = open(file)
for line in handle:
match = xsd_pattern.search(line)
if match is not None:
handle.close()
return match.group(1)
handle.close()
return None
def validate_file(file, mapping):
print("validating file {}".format(file))
xsd = search_file_for_xsd(file)
if xsd is not None:
if xsd in mapping:
lint_with_xsd(file, mapping[xsd])
else:
print('WARNING: Unable to map XSD to path: {}'.format(xsd))
else:
print('WARNING: Unable to find XSD for file: {}'.format(file))
lint_only(file)
def main():
if len(sys.argv) < 4:
print("Usage: xml-lint <misc.xml> <app_base_dir> <search_dir>")
exit(1)
misc_file = sys.argv[1]
base_dir = os.path.abspath(sys.argv[2])
search_dir = os.path.abspath(sys.argv[3])
if not os.path.isfile(misc_file):
print("{} is not a file".format(misc_file))
exit(1)
mapping = get_mappings(misc_file, base_dir)
print("loaded {} XSD mapping(s)".format(len(mapping)))
xml_files = get_xml_files(search_dir)
print("found {} XML file(s)".format(len(xml_files)))
print("")
for file in xml_files:
validate_file(file, mapping)
print("")
if __name__ == '__main__':
main()