api.py 8.2 KB

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