src/rdflib/plugins/serializers/nt.py
1from __future__ import annotations
2
3import codecs
4import warnings
5from typing import IO, TYPE_CHECKING, Any, Optional, Tuple, Union
6
7from rdflib.graph import Graph
8from rdflib.serializer import Serializer
9from rdflib.term import Literal
10
11if TYPE_CHECKING:
12 from rdflib.graph import _TripleType
13
14"""
15N-Triples RDF graph serializer for RDFLib.
16See <http://www.w3.org/TR/rdf-testcases/#ntriples> for details about the
17format.
18"""
19
20__all__ = ["NTSerializer"]
21
22
23class NTSerializer(Serializer):
24 """Serializes RDF graphs to NTriples format."""
25
26 def __init__(self, store: Graph):
27 Serializer.__init__(self, store)
28
29 def serialize(
30 self,
31 stream: IO[bytes],
32 base: Optional[str] = None,
33 encoding: Optional[str] = "utf-8",
34 **kwargs: Any,
35 ) -> None:
36 if base is not None:
37 warnings.warn("NTSerializer does not support base.")
38 if encoding != "utf-8":
39 warnings.warn(
40 "NTSerializer always uses UTF-8 encoding. "
41 f"Given encoding was: {encoding}"
42 )
43
44 for triple in self.store:
45 stream.write(_nt_row(triple).encode())
46
47
48class NT11Serializer(NTSerializer):
49 """Serializes RDF graphs to RDF 1.1 NTriples format.
50
51 Exactly like nt - only utf8 encoded.
52 """
53
54 def __init__(self, store: Graph):
55 Serializer.__init__(self, store) # default to utf-8
56
57
58def _nt_row(triple: _TripleType) -> str:
59 if isinstance(triple[2], Literal):
60 return "%s %s %s .\n" % (
61 triple[0].n3(),
62 triple[1].n3(),
63 _quoteLiteral(triple[2]),
64 )
65 else:
66 return "%s %s %s .\n" % (triple[0].n3(), triple[1].n3(), triple[2].n3())
67
68
69def _quoteLiteral(l_: Literal) -> str: # noqa: N802
70 """A simpler version of term.Literal.n3()"""
71
72 encoded = _quote_encode(l_)
73
74 if l_.language:
75 if l_.datatype:
76 raise Exception("Literal has datatype AND language!")
77 return "%s@%s" % (encoded, l_.language)
78 elif l_.datatype:
79 return "%s^^<%s>" % (encoded, l_.datatype)
80 else:
81 return "%s" % encoded
82
83
84def _quote_encode(l_: str) -> str:
85 return '"%s"' % l_.replace("\\", "\\\\").replace("\n", "\\n").replace(
86 '"', '\\"'
87 ).replace("\r", "\\r")
88
89
90def _nt_unicode_error_resolver(
91 err: UnicodeError,
92) -> Tuple[Union[str, bytes], int]:
93 """
94 Do unicode char replaces as defined in https://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#ntrip_strings
95 """
96
97 def _replace_single(c):
98 c = ord(c)
99 fmt = "\\u%04X" if c <= 0xFFFF else "\\U%08X"
100 return fmt % c
101
102 # type error: "UnicodeError" has no attribute "object"
103 # type error: "UnicodeError" has no attribute "start"
104 # type error: "UnicodeError" has no attribute "end"
105 string = err.object[err.start : err.end] # type: ignore[attr-defined]
106 # type error: "UnicodeError" has no attribute "end"
107 return "".join(_replace_single(c) for c in string), err.end # type: ignore[attr-defined]
108
109
110codecs.register_error("_rdflib_nt_escape", _nt_unicode_error_resolver)