Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/tomlkit/api.py: 54%
102 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 07:01 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 07:01 +0000
1import datetime as _datetime
3from collections.abc import Mapping
4from typing import IO
5from typing import Iterable
6from typing import Optional
7from typing import Tuple
8from typing import Union
10from tomlkit._utils import parse_rfc3339
11from tomlkit.container import Container
12from tomlkit.exceptions import UnexpectedCharError
13from tomlkit.items import AoT
14from tomlkit.items import Array
15from tomlkit.items import Bool
16from tomlkit.items import Comment
17from tomlkit.items import Date
18from tomlkit.items import DateTime
19from tomlkit.items import DottedKey
20from tomlkit.items import Float
21from tomlkit.items import InlineTable
22from tomlkit.items import Integer
23from tomlkit.items import Item as _Item
24from tomlkit.items import Key
25from tomlkit.items import SingleKey
26from tomlkit.items import String
27from tomlkit.items import StringType as _StringType
28from tomlkit.items import Table
29from tomlkit.items import Time
30from tomlkit.items import Trivia
31from tomlkit.items import Whitespace
32from tomlkit.items import item
33from tomlkit.parser import Parser
34from tomlkit.toml_document import TOMLDocument
37def loads(string: Union[str, bytes]) -> TOMLDocument:
38 """
39 Parses a string into a TOMLDocument.
41 Alias for parse().
42 """
43 return parse(string)
46def dumps(data: Mapping, sort_keys: bool = False) -> str:
47 """
48 Dumps a TOMLDocument into a string.
49 """
50 if not isinstance(data, Container) and isinstance(data, Mapping):
51 data = item(dict(data), _sort_keys=sort_keys)
53 try:
54 # data should be a `Container` (and therefore implement `as_string`)
55 # for all type safe invocations of this function
56 return data.as_string() # type: ignore[attr-defined]
57 except AttributeError as ex:
58 msg = f"Expecting Mapping or TOML Container, {type(data)} given"
59 raise TypeError(msg) from ex
62def load(fp: Union[IO[str], IO[bytes]]) -> TOMLDocument:
63 """
64 Load toml document from a file-like object.
65 """
66 return parse(fp.read())
69def dump(data: Mapping, fp: IO[str], *, sort_keys: bool = False) -> None:
70 """
71 Dump a TOMLDocument into a writable file stream.
73 :param data: a dict-like object to dump
74 :param sort_keys: if true, sort the keys in alphabetic order
75 """
76 fp.write(dumps(data, sort_keys=sort_keys))
79def parse(string: Union[str, bytes]) -> TOMLDocument:
80 """
81 Parses a string or bytes into a TOMLDocument.
82 """
83 return Parser(string).parse()
86def document() -> TOMLDocument:
87 """
88 Returns a new TOMLDocument instance.
89 """
90 return TOMLDocument()
93# Items
94def integer(raw: Union[str, int]) -> Integer:
95 """Create an integer item from a number or string."""
96 return item(int(raw))
99def float_(raw: Union[str, float]) -> Float:
100 """Create an float item from a number or string."""
101 return item(float(raw))
104def boolean(raw: str) -> Bool:
105 """Turn `true` or `false` into a boolean item."""
106 return item(raw == "true")
109def string(
110 raw: str,
111 *,
112 literal: bool = False,
113 multiline: bool = False,
114 escape: bool = True,
115) -> String:
116 """Create a string item.
118 By default, this function will create *single line basic* strings, but
119 boolean flags (e.g. ``literal=True`` and/or ``multiline=True``)
120 can be used for personalization.
122 For more information, please check the spec: `<https://toml.io/en/v1.0.0#string>`__.
124 Common escaping rules will be applied for basic strings.
125 This can be controlled by explicitly setting ``escape=False``.
126 Please note that, if you disable escaping, you will have to make sure that
127 the given strings don't contain any forbidden character or sequence.
128 """
129 type_ = _StringType.select(literal, multiline)
130 return String.from_raw(raw, type_, escape)
133def date(raw: str) -> Date:
134 """Create a TOML date."""
135 value = parse_rfc3339(raw)
136 if not isinstance(value, _datetime.date):
137 raise ValueError("date() only accepts date strings.")
139 return item(value)
142def time(raw: str) -> Time:
143 """Create a TOML time."""
144 value = parse_rfc3339(raw)
145 if not isinstance(value, _datetime.time):
146 raise ValueError("time() only accepts time strings.")
148 return item(value)
151def datetime(raw: str) -> DateTime:
152 """Create a TOML datetime."""
153 value = parse_rfc3339(raw)
154 if not isinstance(value, _datetime.datetime):
155 raise ValueError("datetime() only accepts datetime strings.")
157 return item(value)
160def array(raw: str = None) -> Array:
161 """Create an array item for its string representation.
163 :Example:
165 >>> array("[1, 2, 3]") # Create from a string
166 [1, 2, 3]
167 >>> a = array()
168 >>> a.extend([1, 2, 3]) # Create from a list
169 >>> a
170 [1, 2, 3]
171 """
172 if raw is None:
173 raw = "[]"
175 return value(raw)
178def table(is_super_table: Optional[bool] = None) -> Table:
179 """Create an empty table.
181 :param is_super_table: if true, the table is a super table
183 :Example:
185 >>> doc = document()
186 >>> foo = table(True)
187 >>> bar = table()
188 >>> bar.update({'x': 1})
189 >>> foo.append('bar', bar)
190 >>> doc.append('foo', foo)
191 >>> print(doc.as_string())
192 [foo.bar]
193 x = 1
194 """
195 return Table(Container(), Trivia(), False, is_super_table)
198def inline_table() -> InlineTable:
199 """Create an inline table.
201 :Example:
203 >>> table = inline_table()
204 >>> table.update({'x': 1, 'y': 2})
205 >>> print(table.as_string())
206 {x = 1, y = 2}
207 """
208 return InlineTable(Container(), Trivia(), new=True)
211def aot() -> AoT:
212 """Create an array of table.
214 :Example:
216 >>> doc = document()
217 >>> aot = aot()
218 >>> aot.append(item({'x': 1}))
219 >>> doc.append('foo', aot)
220 >>> print(doc.as_string())
221 [[foo]]
222 x = 1
223 """
224 return AoT([])
227def key(k: Union[str, Iterable[str]]) -> Key:
228 """Create a key from a string. When a list of string is given,
229 it will create a dotted key.
231 :Example:
233 >>> doc = document()
234 >>> doc.append(key('foo'), 1)
235 >>> doc.append(key(['bar', 'baz']), 2)
236 >>> print(doc.as_string())
237 foo = 1
238 bar.baz = 2
239 """
240 if isinstance(k, str):
241 return SingleKey(k)
242 return DottedKey([key(_k) for _k in k])
245def value(raw: str) -> _Item:
246 """Parse a simple value from a string.
248 :Example:
250 >>> value("1")
251 1
252 >>> value("true")
253 True
254 >>> value("[1, 2, 3]")
255 [1, 2, 3]
256 """
257 parser = Parser(raw)
258 v = parser._parse_value()
259 if not parser.end():
260 raise parser.parse_error(UnexpectedCharError, char=parser._current)
261 return v
264def key_value(src: str) -> Tuple[Key, _Item]:
265 """Parse a key-value pair from a string.
267 :Example:
269 >>> key_value("foo = 1")
270 (Key('foo'), 1)
271 """
272 return Parser(src)._parse_key_value()
275def ws(src: str) -> Whitespace:
276 """Create a whitespace from a string."""
277 return Whitespace(src, fixed=True)
280def nl() -> Whitespace:
281 """Create a newline item."""
282 return ws("\n")
285def comment(string: str) -> Comment:
286 """Create a comment item."""
287 return Comment(Trivia(comment_ws=" ", comment="# " + string))