Mercurial > repos > bcclaywell > argo_navis
comparison venv/lib/python2.7/site-packages/planemo/xml/validation.py @ 0:d67268158946 draft
planemo upload commit a3f181f5f126803c654b3a66dd4e83a48f7e203b
author | bcclaywell |
---|---|
date | Mon, 12 Oct 2015 17:43:33 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:d67268158946 |
---|---|
1 import abc | |
2 from collections import namedtuple | |
3 import subprocess | |
4 | |
5 from galaxy.tools.deps.commands import which | |
6 | |
7 try: | |
8 from lxml import etree | |
9 except ImportError: | |
10 etree = None | |
11 | |
12 XMLLINT_COMMAND = "xmllint --noout --schema {0} {1} 2>&1" | |
13 INSTALL_VALIDATOR_MESSAGE = ("This feature requires an external dependency " | |
14 "to function, pleaes install xmllint (e.g 'brew " | |
15 "install libxml2' or 'apt-get install " | |
16 "libxml2-utils'.") | |
17 | |
18 | |
19 class XsdValidator(object): | |
20 __metaclass__ = abc.ABCMeta | |
21 | |
22 @abc.abstractmethod | |
23 def validate(self, schema_path, target_path): | |
24 """ Validate ``target_path`` against ``schema_path``. | |
25 | |
26 :return type: ValidationResult | |
27 """ | |
28 | |
29 @abc.abstractmethod | |
30 def enabled(self): | |
31 """ Return True iff system has dependencies for this validator. | |
32 | |
33 :return type: bool | |
34 """ | |
35 | |
36 ValidationResult = namedtuple("ValidationResult", ["passed", "output"]) | |
37 | |
38 | |
39 class LxmlValidator(XsdValidator): | |
40 """ Validate XSD files using lxml library. """ | |
41 | |
42 def validate(self, schema_path, target_path): | |
43 try: | |
44 xsd_doc = etree.parse(schema_path) | |
45 xsd = etree.XMLSchema(xsd_doc) | |
46 xml = etree.parse(target_path) | |
47 passed = xsd.validate(xml) | |
48 return ValidationResult(passed, xsd.error_log) | |
49 except etree.XMLSyntaxError as e: | |
50 return ValidationResult(False, str(e)) | |
51 | |
52 def enabled(self): | |
53 return etree is not None | |
54 | |
55 | |
56 class XmllintValidator(XsdValidator): | |
57 """ Validate XSD files with the external tool xmllint. """ | |
58 | |
59 def validate(self, schema_path, target_path): | |
60 command = XMLLINT_COMMAND.format(schema_path, target_path) | |
61 p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) | |
62 stdout, _ = p.communicate() | |
63 passed = p.returncode == 0 | |
64 return ValidationResult(passed, stdout) | |
65 | |
66 def enabled(self): | |
67 return bool(which("xmllint")) | |
68 | |
69 | |
70 VALIDATORS = [LxmlValidator(), XmllintValidator()] | |
71 | |
72 | |
73 def get_validator(require=True): | |
74 for validator in VALIDATORS: | |
75 if validator.enabled(): | |
76 return validator | |
77 | |
78 if require: | |
79 raise Exception(INSTALL_VALIDATOR_MESSAGE) | |
80 | |
81 return None |