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