Source code

Download source archive ↓

src/rdflib/plugins/serializers/trig.py

1"""
2Trig RDF graph serializer for RDFLib.
3See <http://www.w3.org/TR/trig/> for syntax specification.
4"""
5
6from __future__ import annotations
7
8from typing import IO, TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
9
10from rdflib.graph import ConjunctiveGraph, Graph
11from rdflib.plugins.serializers.turtle import TurtleSerializer
12from rdflib.term import BNode, Node
13
14if TYPE_CHECKING:
15    from rdflib.graph import _ContextType, _SubjectType
16
17__all__ = ["TrigSerializer"]
18
19
20class TrigSerializer(TurtleSerializer):
21    """TriG RDF graph serializer."""
22
23    short_name = "trig"
24    indentString = 4 * " "
25
26    def __init__(self, store: Union[Graph, ConjunctiveGraph]):
27        self.default_context: Optional[Node]
28        if store.context_aware:
29            if TYPE_CHECKING:
30                assert isinstance(store, ConjunctiveGraph)
31            self.contexts = list(store.contexts())
32            self.default_context = store.default_context.identifier
33            if store.default_context:
34                self.contexts.append(store.default_context)
35        else:
36            self.contexts = [store]
37            self.default_context = None
38
39        super(TrigSerializer, self).__init__(store)
40
41    def preprocess(self) -> None:
42        for context in self.contexts:
43            # do not write unnecessary prefix (ex: for an empty default graph)
44            if len(context) == 0:
45                continue
46            self.store = context
47            # Don't generate a new prefix for a graph URI if one already exists
48            self.get_pname(context.identifier, False)
49            self._subjects = {}
50
51            for triple in context:
52                self.preprocessTriple(triple)
53
54            for subject in self._subjects.keys():
55                self._references[subject] += 1
56
57            self._contexts[context] = (self.orderSubjects(), self._subjects)
58
59    def reset(self) -> None:
60        super(TrigSerializer, self).reset()
61        self._contexts: Dict[
62            _ContextType,
63            Tuple[List[_SubjectType], Dict[_SubjectType, bool]],
64        ] = {}
65
66    def serialize(
67        self,
68        stream: IO[bytes],
69        base: Optional[str] = None,
70        encoding: Optional[str] = None,
71        spacious: Optional[bool] = None,
72        **kwargs: Any,
73    ) -> None:
74        self.reset()
75        self.stream = stream
76        # if base is given here, use that, if not and a base is set for the graph use that
77        if base is not None:
78            self.base = base
79        elif self.store.base is not None:
80            self.base = self.store.base
81
82        if spacious is not None:
83            self._spacious = spacious
84
85        self.preprocess()
86
87        self.startDocument()
88
89        firstTime = True
90        for store, (ordered_subjects, subjects) in self._contexts.items():
91            if not ordered_subjects:
92                continue
93
94            self._serialized = {}
95            self.store = store
96            self._subjects = subjects
97
98            if self.default_context and store.identifier == self.default_context:
99                self.write(self.indent() + "\n{")
100            else:
101                iri: Optional[str]
102                if isinstance(store.identifier, BNode):
103                    iri = store.identifier.n3()
104                else:
105                    # Show the full graph URI if a prefix for it doesn't already exist
106                    iri = self.get_pname(store.identifier, False)
107                    if iri is None:
108                        iri = store.identifier.n3()
109                self.write(self.indent() + "\n%s {" % iri)
110
111            self.depth += 1
112            for subject in ordered_subjects:
113                if self.isDone(subject):
114                    continue
115                if firstTime:
116                    firstTime = False
117                if self.statement(subject) and not firstTime:
118                    self.write("\n")
119            self.depth -= 1
120            self.write("}\n")
121
122        self.endDocument()
123        stream.write("\n".encode("latin-1"))