api.py 6.9 KB

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