|
| 1 | +""" |
| 2 | +CWL file formats utilities. |
| 3 | +
|
| 4 | +For more information, please visit https://www.commonwl.org/user_guide/16-file-formats/ |
| 5 | +""" |
| 6 | + |
| 7 | +from typing import List, Optional, Set, Union |
| 8 | + |
| 9 | +from rdflib import OWL, RDFS, Graph, URIRef |
| 10 | +from schema_salad.exceptions import ValidationException |
| 11 | +from schema_salad.utils import aslist, json_dumps |
| 12 | + |
| 13 | +from cwl_utils.types import CWLObjectType |
| 14 | + |
| 15 | + |
| 16 | +def formatSubclassOf( |
| 17 | + fmt: str, cls: str, ontology: Optional[Graph], visited: Set[str] |
| 18 | +) -> bool: |
| 19 | + """Determine if `fmt` is a subclass of `cls`.""" |
| 20 | + if URIRef(fmt) == URIRef(cls): |
| 21 | + return True |
| 22 | + |
| 23 | + if ontology is None: |
| 24 | + return False |
| 25 | + |
| 26 | + if fmt in visited: |
| 27 | + return False |
| 28 | + |
| 29 | + visited.add(fmt) |
| 30 | + |
| 31 | + uriRefFmt = URIRef(fmt) |
| 32 | + |
| 33 | + for _s, _p, o in ontology.triples((uriRefFmt, RDFS.subClassOf, None)): |
| 34 | + # Find parent classes of `fmt` and search upward |
| 35 | + if formatSubclassOf(o, cls, ontology, visited): |
| 36 | + return True |
| 37 | + |
| 38 | + for _s, _p, o in ontology.triples((uriRefFmt, OWL.equivalentClass, None)): |
| 39 | + # Find equivalent classes of `fmt` and search horizontally |
| 40 | + if formatSubclassOf(o, cls, ontology, visited): |
| 41 | + return True |
| 42 | + |
| 43 | + for s, _p, _o in ontology.triples((None, OWL.equivalentClass, uriRefFmt)): |
| 44 | + # Find equivalent classes of `fmt` and search horizontally |
| 45 | + if formatSubclassOf(s, cls, ontology, visited): |
| 46 | + return True |
| 47 | + |
| 48 | + return False |
| 49 | + |
| 50 | + |
| 51 | +def check_format( |
| 52 | + actual_file: Union[CWLObjectType, List[CWLObjectType]], |
| 53 | + input_formats: Union[List[str], str], |
| 54 | + ontology: Optional[Graph], |
| 55 | +) -> None: |
| 56 | + """Confirm that the format present is valid for the allowed formats.""" |
| 57 | + for afile in aslist(actual_file): |
| 58 | + if not afile: |
| 59 | + continue |
| 60 | + if "format" not in afile: |
| 61 | + raise ValidationException( |
| 62 | + f"File has no 'format' defined: {json_dumps(afile, indent=4)}" |
| 63 | + ) |
| 64 | + for inpf in aslist(input_formats): |
| 65 | + if afile["format"] == inpf or formatSubclassOf( |
| 66 | + afile["format"], inpf, ontology, set() |
| 67 | + ): |
| 68 | + return |
| 69 | + raise ValidationException( |
| 70 | + f"File has an incompatible format: {json_dumps(afile, indent=4)}" |
| 71 | + ) |
0 commit comments