api.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. from __future__ import annotations
  2. import contextlib
  3. import datetime as _datetime
  4. from collections.abc import Mapping
  5. from typing import IO
  6. from typing import Iterable
  7. from typing import TypeVar
  8. from tomlkit._utils import parse_rfc3339
  9. from tomlkit.container import Container
  10. from tomlkit.exceptions import UnexpectedCharError
  11. from tomlkit.items import CUSTOM_ENCODERS
  12. from tomlkit.items import AoT
  13. from tomlkit.items import Array
  14. from tomlkit.items import Bool
  15. from tomlkit.items import Comment
  16. from tomlkit.items import Date
  17. from tomlkit.items import DateTime
  18. from tomlkit.items import DottedKey
  19. from tomlkit.items import Encoder
  20. from tomlkit.items import Float
  21. from tomlkit.items import InlineTable
  22. from tomlkit.items import Integer
  23. from tomlkit.items import Item as _Item
  24. from tomlkit.items import Key
  25. from tomlkit.items import SingleKey
  26. from tomlkit.items import String
  27. from tomlkit.items import StringType as _StringType
  28. from tomlkit.items import Table
  29. from tomlkit.items import Time
  30. from tomlkit.items import Trivia
  31. from tomlkit.items import Whitespace
  32. from tomlkit.items import item
  33. from tomlkit.parser import Parser
  34. from tomlkit.toml_document import TOMLDocument
  35. def loads(string: str | bytes) -> TOMLDocument:
  36. """
  37. Parses a string into a TOMLDocument.
  38. Alias for parse().
  39. """
  40. return parse(string)
  41. def dumps(data: Mapping, sort_keys: bool = False) -> str:
  42. """
  43. Dumps a TOMLDocument into a string.
  44. """
  45. if not isinstance(data, Container) and isinstance(data, Mapping):
  46. data = item(dict(data), _sort_keys=sort_keys)
  47. try:
  48. # data should be a `Container` (and therefore implement `as_string`)
  49. # for all type safe invocations of this function
  50. return data.as_string() # type: ignore[attr-defined]
  51. except AttributeError as ex:
  52. msg = f"Expecting Mapping or TOML Container, {type(data)} given"
  53. raise TypeError(msg) from ex
  54. def load(fp: IO[str] | IO[bytes]) -> TOMLDocument:
  55. """
  56. Load toml document from a file-like object.
  57. """
  58. return parse(fp.read())
  59. def dump(data: Mapping, fp: IO[str], *, sort_keys: bool = False) -> None:
  60. """
  61. Dump a TOMLDocument into a writable file stream.
  62. :param data: a dict-like object to dump
  63. :param sort_keys: if true, sort the keys in alphabetic order
  64. """
  65. fp.write(dumps(data, sort_keys=sort_keys))
  66. def parse(string: str | bytes) -> TOMLDocument:
  67. """
  68. Parses a string or bytes into a TOMLDocument.
  69. """
  70. return Parser(string).parse()
  71. def document() -> TOMLDocument:
  72. """
  73. Returns a new TOMLDocument instance.
  74. """
  75. return TOMLDocument()
  76. # Items
  77. def integer(raw: str | int) -> Integer:
  78. """Create an integer item from a number or string."""
  79. return item(int(raw))
  80. def float_(raw: str | float) -> Float:
  81. """Create an float item from a number or string."""
  82. return item(float(raw))
  83. def boolean(raw: str) -> Bool:
  84. """Turn `true` or `false` into a boolean item."""
  85. return item(raw == "true")
  86. def string(
  87. raw: str,
  88. *,
  89. literal: bool = False,
  90. multiline: bool = False,
  91. escape: bool = True,
  92. ) -> String:
  93. """Create a string item.
  94. By default, this function will create *single line basic* strings, but
  95. boolean flags (e.g. ``literal=True`` and/or ``multiline=True``)
  96. can be used for personalization.
  97. For more information, please check the spec: `<https://toml.io/en/v1.0.0#string>`__.
  98. Common escaping rules will be applied for basic strings.
  99. This can be controlled by explicitly setting ``escape=False``.
  100. Please note that, if you disable escaping, you will have to make sure that
  101. the given strings don't contain any forbidden character or sequence.
  102. """
  103. type_ = _StringType.select(literal, multiline)
  104. return String.from_raw(raw, type_, escape)
  105. def date(raw: str) -> Date:
  106. """Create a TOML date."""
  107. value = parse_rfc3339(raw)
  108. if not isinstance(value, _datetime.date):
  109. raise ValueError("date() only accepts date strings.")
  110. return item(value)
  111. def time(raw: str) -> Time:
  112. """Create a TOML time."""
  113. value = parse_rfc3339(raw)
  114. if not isinstance(value, _datetime.time):
  115. raise ValueError("time() only accepts time strings.")
  116. return item(value)
  117. def datetime(raw: str) -> DateTime:
  118. """Create a TOML datetime."""
  119. value = parse_rfc3339(raw)
  120. if not isinstance(value, _datetime.datetime):
  121. raise ValueError("datetime() only accepts datetime strings.")
  122. return item(value)
  123. def array(raw: str = None) -> Array:
  124. """Create an array item for its string representation.
  125. :Example:
  126. >>> array("[1, 2, 3]") # Create from a string
  127. [1, 2, 3]
  128. >>> a = array()
  129. >>> a.extend([1, 2, 3]) # Create from a list
  130. >>> a
  131. [1, 2, 3]
  132. """
  133. if raw is None:
  134. raw = "[]"
  135. return value(raw)
  136. def table(is_super_table: bool | None = None) -> Table:
  137. """Create an empty table.
  138. :param is_super_table: if true, the table is a super table
  139. :Example:
  140. >>> doc = document()
  141. >>> foo = table(True)
  142. >>> bar = table()
  143. >>> bar.update({'x': 1})
  144. >>> foo.append('bar', bar)
  145. >>> doc.append('foo', foo)
  146. >>> print(doc.as_string())
  147. [foo.bar]
  148. x = 1
  149. """
  150. return Table(Container(), Trivia(), False, is_super_table)
  151. def inline_table() -> InlineTable:
  152. """Create an inline table.
  153. :Example:
  154. >>> table = inline_table()
  155. >>> table.update({'x': 1, 'y': 2})
  156. >>> print(table.as_string())
  157. {x = 1, y = 2}
  158. """
  159. return InlineTable(Container(), Trivia(), new=True)
  160. def aot() -> AoT:
  161. """Create an array of table.
  162. :Example:
  163. >>> doc = document()
  164. >>> aot = aot()
  165. >>> aot.append(item({'x': 1}))
  166. >>> doc.append('foo', aot)
  167. >>> print(doc.as_string())
  168. [[foo]]
  169. x = 1
  170. """
  171. return AoT([])
  172. def key(k: str | Iterable[str]) -> Key:
  173. """Create a key from a string. When a list of string is given,
  174. it will create a dotted key.
  175. :Example:
  176. >>> doc = document()
  177. >>> doc.append(key('foo'), 1)
  178. >>> doc.append(key(['bar', 'baz']), 2)
  179. >>> print(doc.as_string())
  180. foo = 1
  181. bar.baz = 2
  182. """
  183. if isinstance(k, str):
  184. return SingleKey(k)
  185. return DottedKey([key(_k) for _k in k])
  186. def value(raw: str) -> _Item:
  187. """Parse a simple value from a string.
  188. :Example:
  189. >>> value("1")
  190. 1
  191. >>> value("true")
  192. True
  193. >>> value("[1, 2, 3]")
  194. [1, 2, 3]
  195. """
  196. parser = Parser(raw)
  197. v = parser._parse_value()
  198. if not parser.end():
  199. raise parser.parse_error(UnexpectedCharError, char=parser._current)
  200. return v
  201. def key_value(src: str) -> tuple[Key, _Item]:
  202. """Parse a key-value pair from a string.
  203. :Example:
  204. >>> key_value("foo = 1")
  205. (Key('foo'), 1)
  206. """
  207. return Parser(src)._parse_key_value()
  208. def ws(src: str) -> Whitespace:
  209. """Create a whitespace from a string."""
  210. return Whitespace(src, fixed=True)
  211. def nl() -> Whitespace:
  212. """Create a newline item."""
  213. return ws("\n")
  214. def comment(string: str) -> Comment:
  215. """Create a comment item."""
  216. return Comment(Trivia(comment_ws=" ", comment="# " + string))
  217. E = TypeVar("E", bound=Encoder)
  218. def register_encoder(encoder: E) -> E:
  219. """Add a custom encoder, which should be a function that will be called
  220. if the value can't otherwise be converted. It should takes a single value
  221. and return a TOMLKit item or raise a ``TypeError``.
  222. """
  223. CUSTOM_ENCODERS.append(encoder)
  224. return encoder
  225. def unregister_encoder(encoder: Encoder) -> None:
  226. """Unregister a custom encoder."""
  227. with contextlib.suppress(ValueError):
  228. CUSTOM_ENCODERS.remove(encoder)