parser.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. """Parser plugin interface.
  2. This module defines the parser plugin interface and contains other
  3. related parser support code.
  4. The module is mainly useful for those wanting to write a parser that
  5. can plugin to rdflib. If you are wanting to invoke a parser you likely
  6. want to do so through the Graph class parse method.
  7. """
  8. from __future__ import annotations
  9. import codecs
  10. import os
  11. import pathlib
  12. import sys
  13. from io import BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOBase, TextIOWrapper
  14. from typing import (
  15. IO,
  16. TYPE_CHECKING,
  17. Any,
  18. BinaryIO,
  19. List,
  20. Optional,
  21. TextIO,
  22. Tuple,
  23. Union,
  24. cast,
  25. )
  26. from urllib.parse import urljoin
  27. from urllib.request import Request, url2pathname
  28. from xml.sax import xmlreader
  29. import rdflib.util
  30. from rdflib import __version__
  31. from rdflib._networking import _urlopen
  32. from rdflib.namespace import Namespace
  33. from rdflib.term import URIRef
  34. if TYPE_CHECKING:
  35. from email.message import Message
  36. from io import BufferedReader
  37. from urllib.response import addinfourl
  38. from typing_extensions import Buffer
  39. from rdflib.graph import Graph
  40. __all__ = [
  41. "Parser",
  42. "InputSource",
  43. "StringInputSource",
  44. "URLInputSource",
  45. "FileInputSource",
  46. "PythonInputSource",
  47. ]
  48. class Parser:
  49. __slots__ = ()
  50. def __init__(self):
  51. pass
  52. def parse(self, source: InputSource, sink: Graph) -> None:
  53. pass
  54. class BytesIOWrapper(BufferedIOBase):
  55. __slots__ = (
  56. "wrapped",
  57. "enc_str",
  58. "text_str",
  59. "encoding",
  60. "encoder",
  61. "has_read1",
  62. "has_seek",
  63. "_name",
  64. "_fileno",
  65. "_isatty",
  66. "_leftover",
  67. "_bytes_per_char",
  68. "_text_bytes_offset",
  69. )
  70. def __init__(self, wrapped: Union[str, StringIO, TextIOBase], encoding="utf-8"):
  71. super(BytesIOWrapper, self).__init__()
  72. self.wrapped = wrapped
  73. self.encoding = encoding
  74. self.encoder = codecs.getencoder(self.encoding)
  75. self.enc_str: Optional[Union[BytesIO, BufferedIOBase]] = None
  76. self.text_str: Optional[Union[StringIO, TextIOBase]] = None
  77. self.has_read1: Optional[bool] = None
  78. self.has_seek: Optional[bool] = None
  79. self._name: Optional[str] = None
  80. self._fileno: Optional[Union[int, BaseException]] = None
  81. self._isatty: Optional[Union[bool, BaseException]] = None
  82. self._leftover: bytes = b""
  83. self._text_bytes_offset: int = 0
  84. norm_encoding = encoding.lower().replace("_", "-")
  85. if norm_encoding in ("utf-8", "utf8", "u8", "cp65001"):
  86. # utf-8 has a variable number of bytes per character, 1-4
  87. self._bytes_per_char: int = 1 # assume average of 1 byte per character
  88. elif norm_encoding in (
  89. "latin1",
  90. "latin-1",
  91. "iso-8859-1",
  92. "iso8859-1",
  93. "ascii",
  94. "us-ascii",
  95. ):
  96. # these are all 1-byte-per-character encodings
  97. self._bytes_per_char = 1
  98. elif norm_encoding.startswith("utf-16") or norm_encoding.startswith("utf16"):
  99. # utf-16 has a variable number of bytes per character, 2-3
  100. self._bytes_per_char = 2 # assume average of 2 bytes per character
  101. elif norm_encoding.startswith("utf-32") or norm_encoding.startswith("utf32"):
  102. # utf-32 is fixed length with 4 bytes per character
  103. self._bytes_per_char = 4
  104. else:
  105. # not sure, just assume it is 2 bytes per character
  106. self._bytes_per_char = 2
  107. def _init(self):
  108. name: Optional[str] = None
  109. if isinstance(self.wrapped, str):
  110. b, blen = self.encoder(self.wrapped)
  111. self.enc_str = BytesIO(b)
  112. name = "string"
  113. elif isinstance(self.wrapped, TextIOWrapper):
  114. inner = self.wrapped.buffer
  115. if isinstance(inner, BytesIOWrapper):
  116. raise Exception(
  117. "BytesIOWrapper cannot be wrapped in TextIOWrapper, "
  118. "then wrapped in another BytesIOWrapper"
  119. )
  120. else:
  121. self.enc_str = cast(BufferedIOBase, inner)
  122. elif isinstance(self.wrapped, (TextIOBase, StringIO)):
  123. self.text_str = self.wrapped
  124. use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase]
  125. if self.enc_str is not None:
  126. use_stream = self.enc_str
  127. elif self.text_str is not None:
  128. use_stream = self.text_str
  129. else:
  130. raise Exception("No stream to read from")
  131. if name is None:
  132. try:
  133. name = use_stream.name # type: ignore[union-attr]
  134. except AttributeError:
  135. name = "stream"
  136. self.has_read1 = hasattr(use_stream, "read1")
  137. try:
  138. self.has_seek = use_stream.seekable()
  139. except AttributeError:
  140. self.has_seek = hasattr(use_stream, "seek")
  141. self._name = name
  142. def _check_fileno(self):
  143. use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase]
  144. if self.enc_str is None and self.text_str is None:
  145. self._init()
  146. if self.enc_str is not None:
  147. use_stream = self.enc_str
  148. elif self.text_str is not None:
  149. use_stream = self.text_str
  150. try:
  151. self._fileno = use_stream.fileno()
  152. except OSError as e:
  153. self._fileno = e
  154. except AttributeError:
  155. self._fileno = -1
  156. def _check_isatty(self):
  157. use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase]
  158. if self.enc_str is None and self.text_str is None:
  159. self._init()
  160. if self.enc_str is not None:
  161. use_stream = self.enc_str
  162. elif self.text_str is not None:
  163. use_stream = self.text_str
  164. try:
  165. self._isatty = use_stream.isatty()
  166. except OSError as e:
  167. self._isatty = e
  168. except AttributeError:
  169. self._isatty = False
  170. @property
  171. def name(self) -> Any:
  172. if self._name is None:
  173. self._init()
  174. return self._name
  175. @property
  176. def closed(self) -> bool:
  177. if self.enc_str is None and self.text_str is None:
  178. return False
  179. closed: Optional[bool] = None
  180. if self.enc_str is not None:
  181. try:
  182. closed = self.enc_str.closed
  183. except AttributeError:
  184. closed = None
  185. elif self.text_str is not None:
  186. try:
  187. closed = self.text_str.closed
  188. except AttributeError:
  189. closed = None
  190. return False if closed is None else closed
  191. def readable(self) -> bool:
  192. return True
  193. def writable(self) -> bool:
  194. return False
  195. def truncate(self, size: Optional[int] = None) -> int:
  196. raise NotImplementedError("Cannot truncate on BytesIOWrapper")
  197. def isatty(self) -> bool:
  198. if self._isatty is None:
  199. self._check_isatty()
  200. if isinstance(self._isatty, BaseException):
  201. raise self._isatty
  202. else:
  203. return bool(self._isatty)
  204. def fileno(self) -> int:
  205. if self._fileno is None:
  206. self._check_fileno()
  207. if isinstance(self._fileno, BaseException):
  208. raise self._fileno
  209. else:
  210. return -1 if self._fileno is None else self._fileno
  211. def close(self):
  212. if self.enc_str is None and self.text_str is None:
  213. return
  214. if self.enc_str is not None:
  215. try:
  216. self.enc_str.close()
  217. except AttributeError:
  218. pass
  219. elif self.text_str is not None:
  220. try:
  221. self.text_str.close()
  222. except AttributeError:
  223. pass
  224. def flush(self):
  225. return # Does nothing on read-only streams
  226. def _read_bytes_from_text_stream(self, size: Optional[int] = -1, /) -> bytes:
  227. if TYPE_CHECKING:
  228. assert self.text_str is not None
  229. if size is None or size < 0:
  230. try:
  231. ret_str: str = self.text_str.read()
  232. except EOFError:
  233. ret_str = ""
  234. ret_encoded, enc_len = self.encoder(ret_str)
  235. if self._leftover:
  236. ret_bytes = self._leftover + ret_encoded
  237. self._leftover = b""
  238. else:
  239. ret_bytes = ret_encoded
  240. elif size == len(self._leftover):
  241. ret_bytes = self._leftover
  242. self._leftover = b""
  243. elif size < len(self._leftover):
  244. ret_bytes = self._leftover[:size]
  245. self._leftover = self._leftover[size:]
  246. else:
  247. d, m = divmod(size, self._bytes_per_char)
  248. get_per_loop = int(d) + (1 if m > 0 else 0)
  249. got_bytes: bytes = self._leftover
  250. while len(got_bytes) < size:
  251. try:
  252. got_str: str = self.text_str.read(get_per_loop)
  253. except EOFError:
  254. got_str = ""
  255. if len(got_str) < 1:
  256. break
  257. ret_encoded, enc_len = self.encoder(got_str)
  258. got_bytes += ret_encoded
  259. if len(got_bytes) == size:
  260. self._leftover = b""
  261. ret_bytes = got_bytes
  262. else:
  263. ret_bytes = got_bytes[:size]
  264. self._leftover = got_bytes[size:]
  265. del got_bytes
  266. self._text_bytes_offset += len(ret_bytes)
  267. return ret_bytes
  268. def read(self, size: Optional[int] = -1, /) -> bytes:
  269. """
  270. Read at most size bytes, returned as a bytes object.
  271. If the size argument is negative or omitted read until EOF is reached.
  272. Return an empty bytes object if already at EOF.
  273. """
  274. if size is not None and size == 0:
  275. return b""
  276. if self.enc_str is None and self.text_str is None:
  277. self._init()
  278. if self.enc_str is not None:
  279. ret_bytes = self.enc_str.read(size)
  280. else:
  281. ret_bytes = self._read_bytes_from_text_stream(size)
  282. return ret_bytes
  283. def read1(self, size: Optional[int] = -1, /) -> bytes:
  284. """
  285. Read at most size bytes, with at most one call to the underlying raw stream’s
  286. read() or readinto() method. Returned as a bytes object.
  287. If the size argument is negative or omitted, read until EOF is reached.
  288. Return an empty bytes object at EOF.
  289. """
  290. if (self.enc_str is None and self.text_str is None) or self.has_read1 is None:
  291. self._init()
  292. if not self.has_read1:
  293. raise NotImplementedError()
  294. if self.enc_str is not None:
  295. if size is None or size < 0:
  296. return self.enc_str.read1()
  297. return self.enc_str.read1(size)
  298. raise NotImplementedError("read1() not supported for TextIO in BytesIOWrapper")
  299. def readinto(self, b: Buffer, /) -> int:
  300. """
  301. Read len(b) bytes into buffer b.
  302. Returns number of bytes read (0 for EOF), or error if the object
  303. is set not to block and has no data to read.
  304. """
  305. if TYPE_CHECKING:
  306. assert isinstance(b, (memoryview, bytearray))
  307. if len(b) == 0:
  308. return 0
  309. if self.enc_str is None and self.text_str is None:
  310. self._init()
  311. if self.enc_str is not None:
  312. return self.enc_str.readinto(b)
  313. else:
  314. size = len(b)
  315. read_data: bytes = self._read_bytes_from_text_stream(size)
  316. read_len = len(read_data)
  317. if read_len == 0:
  318. return 0
  319. b[:read_len] = read_data
  320. return read_len
  321. def readinto1(self, b: Buffer, /) -> int:
  322. """
  323. Read len(b) bytes into buffer b, with at most one call to the underlying raw
  324. stream's read() or readinto() method.
  325. Returns number of bytes read (0 for EOF), or error if the object
  326. is set not to block and has no data to read.
  327. """
  328. if TYPE_CHECKING:
  329. assert isinstance(b, (memoryview, bytearray))
  330. if (self.enc_str is None and self.text_str is None) or self.has_read1 is None:
  331. self._init()
  332. if not self.has_read1:
  333. raise NotImplementedError()
  334. if self.enc_str is not None:
  335. return self.enc_str.readinto1(b)
  336. raise NotImplementedError(
  337. "readinto1() not supported for TextIO in BytesIOWrapper"
  338. )
  339. def seek(self, offset: int, whence: int = 0, /) -> int:
  340. if self.has_seek is not None and not self.has_seek:
  341. raise NotImplementedError()
  342. if (self.enc_str is None and self.text_str is None) or self.has_seek is None:
  343. self._init()
  344. if not whence == 0:
  345. raise NotImplementedError("Only SEEK_SET is supported on BytesIOWrapper")
  346. if offset != 0:
  347. raise NotImplementedError(
  348. "Only seeking to zero is supported on BytesIOWrapper"
  349. )
  350. if self.enc_str is not None:
  351. self.enc_str.seek(offset, whence)
  352. elif self.text_str is not None:
  353. self.text_str.seek(offset, whence)
  354. self._text_bytes_offset = 0
  355. self._leftover = b""
  356. return 0
  357. def seekable(self):
  358. if (self.enc_str is None and self.text_str is None) or self.has_seek is None:
  359. self._init()
  360. return self.has_seek
  361. def tell(self) -> int:
  362. if self.has_seek is not None and not self.has_seek:
  363. raise NotImplementedError("Cannot tell() pos because file is not seekable.")
  364. if self.enc_str is not None:
  365. try:
  366. self._text_bytes_offset = self.enc_str.tell()
  367. except AttributeError:
  368. pass
  369. return self._text_bytes_offset
  370. def write(self, b, /):
  371. raise NotImplementedError("Cannot write to a BytesIOWrapper")
  372. class InputSource(xmlreader.InputSource):
  373. """
  374. TODO:
  375. """
  376. def __init__(self, system_id: Optional[str] = None):
  377. xmlreader.InputSource.__init__(self, system_id=system_id)
  378. self.content_type: Optional[str] = None
  379. self.auto_close = False # see Graph.parse(), true if opened by us
  380. def close(self) -> None:
  381. c = self.getCharacterStream()
  382. if c and hasattr(c, "close"):
  383. try:
  384. c.close()
  385. except Exception:
  386. pass
  387. f = self.getByteStream()
  388. if f and hasattr(f, "close"):
  389. try:
  390. f.close()
  391. except Exception:
  392. pass
  393. class PythonInputSource(InputSource):
  394. """
  395. Constructs an RDFLib Parser InputSource from a Python data structure,
  396. for example, loaded from JSON with json.load or json.loads:
  397. >>> import json
  398. >>> as_string = \"\"\"{
  399. ... "@context" : {"ex" : "http://example.com/ns#"},
  400. ... "@graph": [{"@type": "ex:item", "@id": "#example"}]
  401. ... }\"\"\"
  402. >>> as_python = json.loads(as_string)
  403. >>> source = create_input_source(data=as_python)
  404. >>> isinstance(source, PythonInputSource)
  405. True
  406. """
  407. def __init__(self, data: Any, system_id: Optional[str] = None):
  408. self.content_type = None
  409. self.auto_close = False # see Graph.parse(), true if opened by us
  410. self.public_id: Optional[str] = None
  411. self.system_id: Optional[str] = system_id
  412. self.data = data
  413. def getPublicId(self) -> Optional[str]: # noqa: N802
  414. return self.public_id
  415. def setPublicId(self, public_id: Optional[str]) -> None: # noqa: N802
  416. self.public_id = public_id
  417. def getSystemId(self) -> Optional[str]: # noqa: N802
  418. return self.system_id
  419. def setSystemId(self, system_id: Optional[str]) -> None: # noqa: N802
  420. self.system_id = system_id
  421. def close(self) -> None:
  422. self.data = None
  423. class StringInputSource(InputSource):
  424. """
  425. Constructs an RDFLib Parser InputSource from a Python String or Bytes
  426. """
  427. def __init__(
  428. self,
  429. value: Union[str, bytes],
  430. encoding: str = "utf-8",
  431. system_id: Optional[str] = None,
  432. ):
  433. super(StringInputSource, self).__init__(system_id)
  434. stream: Union[BinaryIO, TextIO]
  435. if isinstance(value, str):
  436. stream = StringIO(value)
  437. self.setCharacterStream(stream)
  438. self.setEncoding(encoding)
  439. b_stream = BytesIOWrapper(value, encoding)
  440. self.setByteStream(b_stream)
  441. else:
  442. stream = BytesIO(value)
  443. self.setByteStream(stream)
  444. c_stream = TextIOWrapper(stream, encoding)
  445. self.setCharacterStream(c_stream)
  446. self.setEncoding(c_stream.encoding)
  447. headers = {
  448. "User-agent": "rdflib-%s (https://rdflib.github.io/; eikeon@eikeon.com)"
  449. % __version__
  450. }
  451. class URLInputSource(InputSource):
  452. """
  453. Constructs an RDFLib Parser InputSource from a URL to read it from the Web.
  454. """
  455. links: List[str]
  456. @classmethod
  457. def getallmatchingheaders(cls, message: Message, name) -> List[str]:
  458. # This is reimplemented here, because the method
  459. # getallmatchingheaders from HTTPMessage is broken since Python 3.0
  460. name = name.lower()
  461. return [val for key, val in message.items() if key.lower() == name]
  462. @classmethod
  463. def get_links(cls, response: addinfourl) -> List[str]:
  464. linkslines = cls.getallmatchingheaders(response.headers, "Link")
  465. retarray: List[str] = []
  466. for linksline in linkslines:
  467. links = [linkstr.strip() for linkstr in linksline.split(",")]
  468. for link in links:
  469. retarray.append(link)
  470. return retarray
  471. def get_alternates(self, type_: Optional[str] = None) -> List[str]:
  472. typestr: Optional[str] = f'type="{type_}"' if type_ else None
  473. relstr = 'rel="alternate"'
  474. alts = []
  475. for link in self.links:
  476. parts = [p.strip() for p in link.split(";")]
  477. if relstr not in parts:
  478. continue
  479. if typestr:
  480. if typestr in parts:
  481. alts.append(parts[0].strip("<>"))
  482. else:
  483. alts.append(parts[0].strip("<>"))
  484. return alts
  485. def __init__(self, system_id: Optional[str] = None, format: Optional[str] = None):
  486. super(URLInputSource, self).__init__(system_id)
  487. self.url = system_id
  488. # copy headers to change
  489. myheaders = dict(headers)
  490. if format == "xml":
  491. myheaders["Accept"] = "application/rdf+xml, */*;q=0.1"
  492. elif format == "n3":
  493. myheaders["Accept"] = "text/n3, */*;q=0.1"
  494. elif format in ["turtle", "ttl"]:
  495. myheaders["Accept"] = "text/turtle, application/x-turtle, */*;q=0.1"
  496. elif format == "nt":
  497. myheaders["Accept"] = "text/plain, */*;q=0.1"
  498. elif format == "trig":
  499. myheaders["Accept"] = "application/trig, */*;q=0.1"
  500. elif format == "trix":
  501. myheaders["Accept"] = "application/trix, */*;q=0.1"
  502. elif format == "json-ld":
  503. myheaders["Accept"] = (
  504. "application/ld+json, application/json;q=0.9, */*;q=0.1"
  505. )
  506. else:
  507. # if format not given, create an Accept header from all registered
  508. # parser Media Types
  509. from rdflib.parser import Parser
  510. from rdflib.plugin import plugins
  511. acc = []
  512. for p in plugins(kind=Parser): # only get parsers
  513. if "/" in p.name: # all Media Types known have a / in them
  514. acc.append(p.name)
  515. myheaders["Accept"] = ", ".join(acc)
  516. req = Request(system_id, None, myheaders) # type: ignore[arg-type]
  517. response: addinfourl = _urlopen(req)
  518. self.url = response.geturl() # in case redirections took place
  519. self.links = self.get_links(response)
  520. if format in ("json-ld", "application/ld+json"):
  521. alts = self.get_alternates(type_="application/ld+json")
  522. for link in alts:
  523. full_link = urljoin(self.url, link)
  524. if full_link != self.url and full_link != system_id:
  525. response = _urlopen(Request(full_link))
  526. self.url = response.geturl() # in case redirections took place
  527. break
  528. self.setPublicId(self.url)
  529. content_types = self.getallmatchingheaders(response.headers, "content-type")
  530. self.content_type = content_types[0] if content_types else None
  531. if self.content_type is not None:
  532. self.content_type = self.content_type.split(";", 1)[0]
  533. self.setByteStream(response)
  534. # TODO: self.setEncoding(encoding)
  535. self.response_info = response.info() # a mimetools.Message instance
  536. def __repr__(self) -> str:
  537. # type error: Incompatible return value type (got "Optional[str]", expected "str")
  538. return self.url # type: ignore[return-value]
  539. class FileInputSource(InputSource):
  540. def __init__(
  541. self,
  542. file: Union[BinaryIO, TextIO, TextIOBase, RawIOBase, BufferedIOBase],
  543. /,
  544. encoding: Optional[str] = None,
  545. ):
  546. base = pathlib.Path.cwd().as_uri()
  547. system_id = URIRef(pathlib.Path(file.name).absolute().as_uri(), base=base) # type: ignore[union-attr]
  548. super(FileInputSource, self).__init__(system_id)
  549. self.file = file
  550. if isinstance(file, TextIOBase): # Python3 unicode fp
  551. self.setCharacterStream(file)
  552. self.setEncoding(file.encoding)
  553. try:
  554. b = file.buffer # type: ignore[attr-defined]
  555. self.setByteStream(b)
  556. except (AttributeError, LookupError):
  557. self.setByteStream(BytesIOWrapper(file, encoding=file.encoding))
  558. else:
  559. if TYPE_CHECKING:
  560. assert isinstance(file, BufferedReader)
  561. self.setByteStream(file)
  562. if encoding is not None:
  563. self.setEncoding(encoding)
  564. self.setCharacterStream(TextIOWrapper(file, encoding=encoding))
  565. else:
  566. # We cannot set characterStream here because
  567. # we do not know the Raw Bytes File encoding.
  568. pass
  569. def __repr__(self) -> str:
  570. return repr(self.file)
  571. def create_input_source(
  572. source: Optional[
  573. Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
  574. ] = None,
  575. publicID: Optional[str] = None, # noqa: N803
  576. location: Optional[str] = None,
  577. file: Optional[Union[BinaryIO, TextIO]] = None,
  578. data: Optional[Union[str, bytes, dict]] = None,
  579. format: Optional[str] = None,
  580. ) -> InputSource:
  581. """
  582. Return an appropriate InputSource instance for the given
  583. parameters.
  584. """
  585. # test that exactly one of source, location, file, and data is not None.
  586. non_empty_arguments = list(
  587. filter(
  588. lambda v: v is not None,
  589. [source, location, file, data],
  590. )
  591. )
  592. if len(non_empty_arguments) != 1:
  593. raise ValueError(
  594. "exactly one of source, location, file or data must be given",
  595. )
  596. input_source = None
  597. if source is not None:
  598. if TYPE_CHECKING:
  599. assert file is None
  600. assert data is None
  601. assert location is None
  602. if isinstance(source, InputSource):
  603. input_source = source
  604. else:
  605. if isinstance(source, str):
  606. location = source
  607. elif isinstance(source, pathlib.PurePath):
  608. location = str(source)
  609. elif isinstance(source, bytes):
  610. data = source
  611. elif hasattr(source, "read") and not isinstance(source, Namespace):
  612. f = source
  613. input_source = InputSource()
  614. if hasattr(source, "encoding"):
  615. input_source.setCharacterStream(source)
  616. input_source.setEncoding(source.encoding)
  617. try:
  618. b = source.buffer # type: ignore[union-attr]
  619. input_source.setByteStream(b)
  620. except (AttributeError, LookupError):
  621. input_source.setByteStream(source)
  622. else:
  623. input_source.setByteStream(f)
  624. if f is sys.stdin:
  625. input_source.setSystemId("file:///dev/stdin")
  626. elif hasattr(f, "name"):
  627. input_source.setSystemId(f.name)
  628. else:
  629. raise Exception(
  630. "Unexpected type '%s' for source '%s'" % (type(source), source)
  631. )
  632. absolute_location = None # Further to fix for issue 130
  633. auto_close = False # make sure we close all file handles we open
  634. if location is not None:
  635. if TYPE_CHECKING:
  636. assert file is None
  637. assert data is None
  638. assert source is None
  639. (
  640. absolute_location,
  641. auto_close,
  642. file,
  643. input_source,
  644. ) = _create_input_source_from_location(
  645. file=file,
  646. format=format,
  647. input_source=input_source,
  648. location=location,
  649. )
  650. if file is not None:
  651. if TYPE_CHECKING:
  652. assert location is None
  653. assert data is None
  654. assert source is None
  655. input_source = FileInputSource(file)
  656. if data is not None:
  657. if TYPE_CHECKING:
  658. assert location is None
  659. assert file is None
  660. assert source is None
  661. if isinstance(data, dict):
  662. input_source = PythonInputSource(data)
  663. auto_close = True
  664. elif isinstance(data, (str, bytes, bytearray)):
  665. input_source = StringInputSource(data)
  666. auto_close = True
  667. else:
  668. raise RuntimeError(f"parse data can only str, or bytes. not: {type(data)}")
  669. if input_source is None:
  670. raise Exception("could not create InputSource")
  671. else:
  672. input_source.auto_close |= auto_close
  673. if publicID is not None: # Further to fix for issue 130
  674. input_source.setPublicId(publicID)
  675. # Further to fix for issue 130
  676. elif input_source.getPublicId() is None:
  677. input_source.setPublicId(absolute_location or "")
  678. return input_source
  679. def _create_input_source_from_location(
  680. file: Optional[Union[BinaryIO, TextIO]],
  681. format: Optional[str],
  682. input_source: Optional[InputSource],
  683. location: str,
  684. ) -> Tuple[URIRef, bool, Optional[Union[BinaryIO, TextIO]], Optional[InputSource]]:
  685. # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 and
  686. # https://github.com/RDFLib/rdflib/issues/1430
  687. # NOTE: using pathlib.Path.exists on a URL fails on windows as it is not a
  688. # valid path. However os.path.exists() returns false for a URL on windows
  689. # which is why it is being used instead.
  690. if os.path.exists(location):
  691. location = pathlib.Path(location).absolute().as_uri()
  692. base = pathlib.Path.cwd().as_uri()
  693. absolute_location = URIRef(rdflib.util._iri2uri(location), base=base)
  694. if absolute_location.startswith("file:///"):
  695. filename = url2pathname(absolute_location.replace("file:///", "/"))
  696. file = open(filename, "rb")
  697. else:
  698. input_source = URLInputSource(absolute_location, format)
  699. auto_close = True
  700. # publicID = publicID or absolute_location # Further to fix
  701. # for issue 130
  702. return absolute_location, auto_close, file, input_source