|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from codecs import getreader |
| 4 | +from enum import Enum |
| 5 | +from typing import TYPE_CHECKING, Any, MutableMapping, Optional, Union |
| 6 | + |
| 7 | +from rdflib.exceptions import ParserError as ParseError |
| 8 | +from rdflib.graph import Dataset |
| 9 | +from rdflib.parser import InputSource |
| 10 | +from rdflib.plugins.parsers.nquads import NQuadsParser |
| 11 | + |
| 12 | +# Build up from the NTriples parser: |
| 13 | +from rdflib.plugins.parsers.ntriples import r_nodeid, r_tail, r_uriref, r_wspace |
| 14 | +from rdflib.term import BNode, URIRef |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + import typing_extensions as te |
| 18 | + |
| 19 | +__all__ = ["RDFPatchParser", "Operation"] |
| 20 | + |
| 21 | +_BNodeContextType = MutableMapping[str, BNode] |
| 22 | + |
| 23 | + |
| 24 | +class Operation(Enum): |
| 25 | + """ |
| 26 | + Enum of RDF Patch operations. |
| 27 | +
|
| 28 | + Operations: |
| 29 | + - `AddTripleOrQuad` (A): Adds a triple or quad. |
| 30 | + - `DeleteTripleOrQuad` (D): Deletes a triple or quad. |
| 31 | + - `AddPrefix` (PA): Adds a prefix. |
| 32 | + - `DeletePrefix` (PD): Deletes a prefix. |
| 33 | + - `TransactionStart` (TX): Starts a transaction. |
| 34 | + - `TransactionCommit` (TC): Commits a transaction. |
| 35 | + - `TransactionAbort` (TA): Aborts a transaction. |
| 36 | + - `Header` (H): Specifies a header. |
| 37 | + """ |
| 38 | + |
| 39 | + AddTripleOrQuad = "A" |
| 40 | + DeleteTripleOrQuad = "D" |
| 41 | + AddPrefix = "PA" |
| 42 | + DeletePrefix = "PD" |
| 43 | + TransactionStart = "TX" |
| 44 | + TransactionCommit = "TC" |
| 45 | + TransactionAbort = "TA" |
| 46 | + Header = "H" |
| 47 | + |
| 48 | + |
| 49 | +class RDFPatchParser(NQuadsParser): |
| 50 | + def parse( # type: ignore[override] |
| 51 | + self, |
| 52 | + inputsource: InputSource, |
| 53 | + sink: Dataset, |
| 54 | + bnode_context: Optional[_BNodeContextType] = None, |
| 55 | + skolemize: bool = False, |
| 56 | + **kwargs: Any, |
| 57 | + ) -> Dataset: |
| 58 | + """ |
| 59 | + Parse inputsource as an RDF Patch file. |
| 60 | +
|
| 61 | + :type inputsource: `rdflib.parser.InputSource` |
| 62 | + :param inputsource: the source of RDF Patch formatted data |
| 63 | + :type sink: `rdflib.graph.Dataset` |
| 64 | + :param sink: where to send parsed data |
| 65 | + :type bnode_context: `dict`, optional |
| 66 | + :param bnode_context: a dict mapping blank node identifiers to `~rdflib.term.BNode` instances. |
| 67 | + See `.W3CNTriplesParser.parse` |
| 68 | + """ |
| 69 | + assert sink.store.context_aware, ( |
| 70 | + "RDFPatchParser must be given" " a context aware store." |
| 71 | + ) |
| 72 | + # type error: Incompatible types in assignment (expression has type "ConjunctiveGraph", base class "W3CNTriplesParser" defined the type as "Union[DummySink, NTGraphSink]") |
| 73 | + self.sink: Dataset = Dataset(store=sink.store) |
| 74 | + self.skolemize = skolemize |
| 75 | + |
| 76 | + source = inputsource.getCharacterStream() |
| 77 | + if not source: |
| 78 | + source = inputsource.getByteStream() |
| 79 | + source = getreader("utf-8")(source) |
| 80 | + |
| 81 | + if not hasattr(source, "read"): |
| 82 | + raise ParseError("Item to parse must be a file-like object.") |
| 83 | + |
| 84 | + self.file = source |
| 85 | + self.buffer = "" |
| 86 | + while True: |
| 87 | + self.line = __line = self.readline() |
| 88 | + if self.line is None: |
| 89 | + break |
| 90 | + try: |
| 91 | + self.parsepatch(bnode_context) |
| 92 | + except ParseError as msg: |
| 93 | + raise ParseError("Invalid line (%s):\n%r" % (msg, __line)) |
| 94 | + return self.sink |
| 95 | + |
| 96 | + def parsepatch(self, bnode_context: Optional[_BNodeContextType] = None) -> None: |
| 97 | + self.eat(r_wspace) |
| 98 | + # From spec: "No comments should be included (comments start # and run to end |
| 99 | + # of line)." |
| 100 | + if (not self.line) or self.line.startswith("#"): |
| 101 | + return # The line is empty or a comment |
| 102 | + |
| 103 | + # if header, transaction, skip |
| 104 | + operation = self.operation() |
| 105 | + self.eat(r_wspace) |
| 106 | + |
| 107 | + if operation in [Operation.AddTripleOrQuad, Operation.DeleteTripleOrQuad]: |
| 108 | + self.add_or_remove_triple_or_quad(operation, bnode_context) |
| 109 | + elif operation == Operation.AddPrefix: |
| 110 | + self.add_prefix() |
| 111 | + elif operation == Operation.DeletePrefix: |
| 112 | + self.delete_prefix() |
| 113 | + |
| 114 | + def add_or_remove_triple_or_quad( |
| 115 | + self, operation, bnode_context: Optional[_BNodeContextType] = None |
| 116 | + ) -> None: |
| 117 | + self.eat(r_wspace) |
| 118 | + if (not self.line) or self.line.startswith("#"): |
| 119 | + return # The line is empty or a comment |
| 120 | + |
| 121 | + subject = self.labeled_bnode() or self.subject(bnode_context) |
| 122 | + self.eat(r_wspace) |
| 123 | + |
| 124 | + predicate = self.predicate() |
| 125 | + self.eat(r_wspace) |
| 126 | + |
| 127 | + obj = self.labeled_bnode() or self.object(bnode_context) |
| 128 | + self.eat(r_wspace) |
| 129 | + |
| 130 | + context = self.labeled_bnode() or self.uriref() or self.nodeid(bnode_context) |
| 131 | + self.eat(r_tail) |
| 132 | + |
| 133 | + if self.line: |
| 134 | + raise ParseError("Trailing garbage") |
| 135 | + # Must have a context aware store - add on a normal Graph |
| 136 | + # discards anything where the ctx != graph.identifier |
| 137 | + if operation == Operation.AddTripleOrQuad: |
| 138 | + if context: |
| 139 | + self.sink.get_context(context).add((subject, predicate, obj)) |
| 140 | + else: |
| 141 | + self.sink.default_context.add((subject, predicate, obj)) |
| 142 | + elif operation == Operation.DeleteTripleOrQuad: |
| 143 | + if context: |
| 144 | + self.sink.get_context(context).remove((subject, predicate, obj)) |
| 145 | + else: |
| 146 | + self.sink.default_context.remove((subject, predicate, obj)) |
| 147 | + |
| 148 | + def add_prefix(self): |
| 149 | + # Extract prefix and URI from the line |
| 150 | + prefix, ns, _ = self.line.replace('"', "").replace("'", "").split(" ") # type: ignore[union-attr] |
| 151 | + ns_stripped = ns.strip("<>") |
| 152 | + self.sink.bind(prefix, ns_stripped) |
| 153 | + |
| 154 | + def delete_prefix(self): |
| 155 | + prefix, _, _ = self.line.replace('"', "").replace("'", "").split(" ") # type: ignore[union-attr] |
| 156 | + self.sink.namespace_manager.bind(prefix, None, replace=True) |
| 157 | + |
| 158 | + def operation(self) -> Operation: |
| 159 | + for op in Operation: |
| 160 | + if self.line.startswith(op.value): # type: ignore[union-attr] |
| 161 | + self.eat_op(op.value) |
| 162 | + return op |
| 163 | + raise ValueError( |
| 164 | + f'Invalid or no Operation found in line: "{self.line}". Valid Operations ' |
| 165 | + f"codes are {', '.join([op.value for op in Operation])}" |
| 166 | + ) |
| 167 | + |
| 168 | + def eat_op(self, op: str) -> None: |
| 169 | + self.line = self.line.lstrip(op) # type: ignore[union-attr] |
| 170 | + |
| 171 | + def nodeid( |
| 172 | + self, bnode_context: Optional[_BNodeContextType] = None |
| 173 | + ) -> Union[te.Literal[False], BNode, URIRef]: |
| 174 | + if self.peek("_"): |
| 175 | + return BNode(self.eat(r_nodeid).group(1)) |
| 176 | + return False |
| 177 | + |
| 178 | + def labeled_bnode(self): |
| 179 | + if self.peek("<_"): |
| 180 | + plain_uri = self.eat(r_uriref).group(1) |
| 181 | + bnode_id = r_nodeid.match(plain_uri).group(1) # type: ignore[union-attr] |
| 182 | + return BNode(bnode_id) |
| 183 | + return False |
0 commit comments