Skip to content

Commit

Permalink
Merge branch 'RDFLib:master' into fix-sonarcloud-reported-bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Graham Higgins committed May 24, 2022
2 parents 0ffe4dc + a3a4611 commit 2ef6f80
Show file tree
Hide file tree
Showing 45 changed files with 543 additions and 311 deletions.
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ pep8-naming = ["-N802", "-N803", "-N806", "-N815"]
pep8-naming = ["-N802", "-N803", "-N806", "-N816"]
[tool.flakeheaven.exceptions."rdflib/plugins/serializers/turtle.py"]
pep8-naming = ["-N802", "-N806", "-N815"]
[tool.flakeheaven.exceptions."rdflib/__init__.py"]
pycodestyle = ["-E402"]


[tool.black]
required-version = "22.3.0"
line-length = "88"
skip-string-normalization = true
target-version = ['py37']
include = '\.pyi?$'
exclude = '''
Expand Down
12 changes: 5 additions & 7 deletions rdflib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@
"VOID",
"XSD",
"util",
"plugin",
"query",
]

import logging
Expand Down Expand Up @@ -157,7 +159,7 @@
Literal work, eq, __neq__, __lt__, etc.
"""

from rdflib import plugin, query

from rdflib.graph import ConjunctiveGraph, Dataset, Graph
from rdflib.namespace import (
BRICK,
Expand Down Expand Up @@ -190,9 +192,5 @@
)
from rdflib.term import BNode, IdentifiedNode, Literal, URIRef, Variable

# tedious sop to flake8
assert plugin
assert query

from rdflib import util
from rdflib.container import *
from rdflib import plugin, query, util # isort:skip
from rdflib.container import * # isort:skip # noqa:F401,F403
76 changes: 40 additions & 36 deletions rdflib/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
)
from urllib.parse import urlparse
from urllib.request import url2pathname
from warnings import warn

import rdflib.exceptions as exceptions
import rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.
import rdflib.plugin as plugin
import rdflib.query as query
import rdflib.util # avoid circular dependency
from rdflib import exceptions, namespace, plugin, query
from rdflib.collection import Collection
from rdflib.exceptions import ParserError
from rdflib.namespace import RDF, Namespace, NamespaceManager
Expand Down Expand Up @@ -120,13 +122,13 @@
<class 'rdflib.term.BNode'>
Instantiating Graphs with a Memory store and an identifier -
<http://rdflib.net>:
<https://rdflib.github.io>:
>>> g = Graph('Memory', URIRef("http://rdflib.net"))
>>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
>>> g.identifier
rdflib.term.URIRef('http://rdflib.net')
rdflib.term.URIRef('https://rdflib.github.io')
>>> str(g) # doctest: +NORMALIZE_WHITESPACE
"<http://rdflib.net> a rdfg:Graph;rdflib:storage
"<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
[a rdflib:Store;rdfs:label 'Memory']."
Creating a ConjunctiveGraph - The top level container for all named Graphs
Expand All @@ -146,7 +148,7 @@
>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.subject,
... URIRef("http://rdflib.net/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
... URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
Expand Down Expand Up @@ -217,7 +219,7 @@
>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.subject,
... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
Expand All @@ -226,7 +228,7 @@
>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.subject,
... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
Expand All @@ -235,7 +237,7 @@
>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.subject,
... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
Expand Down Expand Up @@ -272,7 +274,7 @@
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
... rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
... rdf:subject <https://rdflib.github.io/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
Expand All @@ -282,11 +284,11 @@
Using Namespace class:
>>> RDFLib = Namespace("http://rdflib.net/")
>>> RDFLib = Namespace("https://rdflib.github.io/")
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef('http://rdflib.net/ConjunctiveGraph')
rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
>>> RDFLib["Graph"]
rdflib.term.URIRef('http://rdflib.net/Graph')
rdflib.term.URIRef('https://rdflib.github.io/Graph')
"""

Expand Down Expand Up @@ -387,7 +389,7 @@ def __str__(self):
"[a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']]."
) % self.store.__class__.__name__

def toPython(self):
def toPython(self): # noqa: N802
return self

def destroy(self, configuration):
Expand Down Expand Up @@ -431,7 +433,7 @@ def add(self, triple: Tuple[Node, Node, Node]):
self.__store.add((s, p, o), self, quoted=False)
return self

def addN(self, quads: Iterable[Tuple[Node, Node, Node, Any]]):
def addN(self, quads: Iterable[Tuple[Node, Node, Node, Any]]): # noqa: N802
"""Add a sequence of triple with context"""

self.__store.addN(
Expand Down Expand Up @@ -916,7 +918,7 @@ def items(self, list):
raise ValueError("List contains a recursive rdf:rest reference")
chain.add(list)

def transitiveClosure(self, func, arg, seen=None):
def transitiveClosure(self, func, arg, seen=None): # noqa: N802
"""
Generates transitive closure of a user-defined
function against the graph
Expand Down Expand Up @@ -1171,7 +1173,7 @@ def parse(
source: Optional[
Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
] = None,
publicID: Optional[str] = None,
publicID: Optional[str] = None, # noqa: N803
format: Optional[str] = None,
location: Optional[str] = None,
file: Optional[Union[BinaryIO, TextIO]] = None,
Expand Down Expand Up @@ -1293,7 +1295,7 @@ def query(
query_object,
processor: Union[str, query.Processor] = "sparql",
result: Union[str, Type[query.Result]] = "sparql",
initNs=None,
initNs=None, # noqa: N803
initBindings=None,
use_store_provided: bool = True,
**kwargs,
Expand All @@ -1312,8 +1314,8 @@ def query(
"""

initBindings = initBindings or {}
initNs = initNs or dict(self.namespaces())
initBindings = initBindings or {} # noqa: N806
initNs = initNs or dict(self.namespaces()) # noqa: N806

if hasattr(self.store, "query") and use_store_provided:
try:
Expand All @@ -1338,14 +1340,14 @@ def update(
self,
update_object,
processor="sparql",
initNs=None,
initNs=None, # noqa: N803
initBindings=None,
use_store_provided=True,
**kwargs,
):
"""Update this graph with the given update query."""
initBindings = initBindings or {}
initNs = initNs or dict(self.namespaces())
initBindings = initBindings or {} # noqa: N806
initNs = initNs or dict(self.namespaces()) # noqa: N806

if hasattr(self.store, "update") and use_store_provided:
try:
Expand Down Expand Up @@ -1716,7 +1718,7 @@ def _graph(self, c: Optional[Union[Graph, Node, str]]) -> Optional[Graph]:
else:
return c

def addN(self, quads: Iterable[Tuple[Node, Node, Node, Any]]):
def addN(self, quads: Iterable[Tuple[Node, Node, Node, Any]]): # noqa: N802
"""Add a sequence of triples with context"""

self.store.addN(
Expand Down Expand Up @@ -1841,7 +1843,7 @@ def parse(
source: Optional[
Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
] = None,
publicID: Optional[str] = None,
publicID: Optional[str] = None, # noqa: N803
format: Optional[str] = None,
location: Optional[str] = None,
file: Optional[Union[BinaryIO, TextIO]] = None,
Expand Down Expand Up @@ -2002,7 +2004,7 @@ class Dataset(ConjunctiveGraph):
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
DEFAULT
http://rdlib.net/.well-known/genid/rdflib/N...
https://rdflib.github.io/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
Expand Down Expand Up @@ -2046,10 +2048,12 @@ def __setstate__(self, state):

def graph(self, identifier=None, base=None):
if identifier is None:
from rdflib.term import rdflib_skolem_genid
from rdflib.term import _SKOLEM_DEFAULT_AUTHORITY, rdflib_skolem_genid

self.bind(
"genid", "http://rdflib.net" + rdflib_skolem_genid, override=False
"genid",
_SKOLEM_DEFAULT_AUTHORITY + rdflib_skolem_genid,
override=False,
)
identifier = BNode().skolemize()

Expand All @@ -2062,7 +2066,7 @@ def graph(self, identifier=None, base=None):
def parse(
self,
source=None,
publicID=None,
publicID=None, # noqa: N803
format=None,
location=None,
file=None,
Expand Down Expand Up @@ -2135,7 +2139,7 @@ def add(self, triple: Tuple[Node, Node, Node]):
self.store.add((s, p, o), self, quoted=True)
return self

def addN(self, quads: Tuple[Node, Node, Node, Any]) -> "QuotedGraph": # type: ignore[override]
def addN(self, quads: Tuple[Node, Node, Node, Any]) -> "QuotedGraph": # type: ignore[override] # noqa: N802
"""Add a sequence of triple with context"""

self.store.addN(
Expand Down Expand Up @@ -2193,7 +2197,7 @@ def __init__(self, graph, subject):
"""

_list = self._list = list()
LI_INDEX = URIRef(str(RDF) + "_")
LI_INDEX = URIRef(str(RDF) + "_") # noqa: N806
for (p, o) in graph.predicate_objects(subject):
if p.startswith(LI_INDEX): # != RDF.Seq: #
i = int(p.replace(LI_INDEX, ""))
Expand All @@ -2203,7 +2207,7 @@ def __init__(self, graph, subject):
# by sorting the keys (by integer) we have what we want!
_list.sort()

def toPython(self):
def toPython(self): # noqa: N802
return self

def __iter__(self):
Expand Down Expand Up @@ -2285,7 +2289,7 @@ def close(self):
def add(self, triple):
raise ModificationException()

def addN(self, quads):
def addN(self, quads): # noqa: N802
raise ModificationException()

def remove(self, triple):
Expand Down Expand Up @@ -2384,7 +2388,7 @@ def namespaces(self):
def absolutize(self, uri, defrag=1):
raise UnSupportedAggregateOperation()

def parse(self, source, publicID=None, format=None, **args):
def parse(self, source, publicID=None, format=None, **args): # noqa: N803
raise ModificationException()

def n3(self):
Expand Down Expand Up @@ -2455,7 +2459,7 @@ def add(
self.batch.append(triple_or_quad)
return self

def addN(self, quads: Iterable[Tuple[Node, Node, Node, Any]]):
def addN(self, quads: Iterable[Tuple[Node, Node, Node, Any]]): # noqa: N802
if self.__batch_addn:
for q in quads:
self.add(q)
Expand Down
6 changes: 3 additions & 3 deletions rdflib/namespace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def __getattr__(cls, name: str):
return cls.__getitem__(name)

def __repr__(cls) -> str:
return f'Namespace({str(cls._NS)!r})'
return f"Namespace({str(cls._NS)!r})"

def __str__(cls) -> str:
return str(cls._NS)
Expand Down Expand Up @@ -275,9 +275,9 @@ def as_jsonld_context(self, pfx: str) -> dict:
terms = {pfx: str(self._NS)}
for key, term in self.__annotations__.items():
if issubclass(term, URIRef):
terms[key] = f'{pfx}:{key}'
terms[key] = f"{pfx}:{key}"

return {'@context': terms}
return {"@context": terms}


class DefinedNamespace(metaclass=DefinedNamespaceMeta):
Expand Down
14 changes: 8 additions & 6 deletions rdflib/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from urllib.request import Request, url2pathname, urlopen
from xml.sax import xmlreader

import rdflib.util
from rdflib import __version__
from rdflib.namespace import Namespace
from rdflib.term import URIRef
Expand Down Expand Up @@ -183,7 +184,8 @@ def __init__(


headers = {
"User-agent": "rdflib-%s (http://rdflib.net/; eikeon@eikeon.com)" % __version__
"User-agent": "rdflib-%s (https://rdflib.github.io/; eikeon@eikeon.com)"
% __version__
}


Expand All @@ -195,14 +197,14 @@ class URLInputSource(InputSource):
links: List[str]

@classmethod
def getallmatchingheaders(cls, message: 'HTTPMessage', name):
def getallmatchingheaders(cls, message: "HTTPMessage", name):
# This is reimplemented here, because the method
# getallmatchingheaders from HTTPMessage is broken since Python 3.0
name = name.lower()
return [val for key, val in message.items() if key.lower() == name]

@classmethod
def get_links(cls, response: 'HTTPResponse'):
def get_links(cls, response: "HTTPResponse"):
linkslines = cls.getallmatchingheaders(response.headers, "Link")
retarray = []
for linksline in linkslines:
Expand All @@ -212,8 +214,8 @@ def get_links(cls, response: 'HTTPResponse'):
return retarray

def get_alternates(self, type_: Optional[str] = None) -> List[str]:
typestr: Optional[str] = f"type=\"{type_}\"" if type_ else None
relstr = "rel=\"alternate\""
typestr: Optional[str] = f'type="{type_}"' if type_ else None
relstr = 'rel="alternate"'
alts = []
for link in self.links:
parts = [p.strip() for p in link.split(";")]
Expand Down Expand Up @@ -447,7 +449,7 @@ def _create_input_source_from_location(

base = pathlib.Path.cwd().as_uri()

absolute_location = URIRef(location, base=base)
absolute_location = URIRef(rdflib.util._iri2uri(location), base=base)

if absolute_location.startswith("file:///"):
filename = url2pathname(absolute_location.replace("file:///", "/"))
Expand Down
Loading

0 comments on commit 2ef6f80

Please sign in to comment.