incur-cli 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
incur/_yaml.py ADDED
@@ -0,0 +1,651 @@
1
+ """YAML serialization of JSON data, ported from `yaml` 2.8.2 `stringify` with its defaults.
2
+
3
+ String folding indexes UTF-16 code units, as the JavaScript implementation does.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextvars
9
+ import itertools
10
+ import re
11
+ from dataclasses import dataclass, field, replace
12
+
13
+ from . import _js
14
+ from ._js import Json
15
+
16
+ LINE_WIDTH = 80
17
+ MIN_CONTENT_WIDTH = 20
18
+
19
+ #: The line width of the current `stringify` call; 0 disables folding.
20
+ _width = contextvars.ContextVar("width", default=LINE_WIDTH)
21
+
22
+ _BLOCK, _FLOW, _QUOTED = 0, 1, 2
23
+
24
+ _DIGITS = r"[0-9]+"
25
+ _FLOAT = r"(?:\.[0-9]+|[0-9]+\.[0-9]*)"
26
+ _NON_STRING = re.compile(
27
+ "|".join(
28
+ (
29
+ r"~|null|Null|NULL|true|True|TRUE|false|False|FALSE",
30
+ rf"[+-]?{_DIGITS}",
31
+ r"0o[0-7]+",
32
+ r"0x[0-9a-fA-F]+",
33
+ r"[+-]?\.(?:inf|Inf|INF)",
34
+ r"\.nan|\.NaN|\.NAN",
35
+ rf"[+-]?(?:{_DIGITS}|{_FLOAT})[eE][+-]?{_DIGITS}",
36
+ rf"[+-]?{_FLOAT}",
37
+ )
38
+ ),
39
+ re.ASCII,
40
+ )
41
+
42
+
43
+ @dataclass
44
+ class _Ctx:
45
+ """The stringify context of one node."""
46
+
47
+ implicit_key: bool = False
48
+ indent: str = ""
49
+ indent_at_start: int | None = None
50
+ force_block_indent: bool = False
51
+ anchors: dict[int, str] = field(default_factory=dict[int, str])
52
+ emitted: set[int] = field(default_factory=set[int])
53
+
54
+
55
+ def stringify(value: Json, line_width: int = LINE_WIDTH) -> str:
56
+ """Serializes a value as a YAML document, ending with a newline.
57
+
58
+ A list or object that appears more than once is written once with an anchor (`&a1`) and
59
+ referenced by alias (`*a1`) elsewhere. A `line_width` of 0 disables line folding.
60
+
61
+ >>> shared, empty = [1], {}
62
+ >>> print(stringify({"a": [shared, shared], "b": empty, "c": empty}), end="")
63
+ a:
64
+ - &a1
65
+ - 1
66
+ - *a1
67
+ b: &a2 {}
68
+ c: *a2
69
+ """
70
+ token = _width.set(line_width)
71
+ try:
72
+ return _node(value, _Ctx(anchors=_anchors(value))) + "\n"
73
+ finally:
74
+ _width.reset(token)
75
+
76
+
77
+ def _anchors(value: Json) -> dict[int, str]:
78
+ """Names repeated lists and objects in order of their first repeat, as `yaml` does."""
79
+ seen: set[int] = set()
80
+ anchors: dict[int, str] = {}
81
+
82
+ def visit(node: Json) -> None:
83
+ if not isinstance(node, (list, dict)):
84
+ return
85
+ if id(node) in seen:
86
+ anchors.setdefault(id(node), f"a{len(anchors) + 1}")
87
+ return
88
+ seen.add(id(node))
89
+ for child in node.values() if isinstance(node, dict) else node:
90
+ visit(child)
91
+
92
+ visit(value)
93
+ return anchors
94
+
95
+
96
+ def _anchor(value: Json, ctx: _Ctx) -> tuple[str | None, bool]:
97
+ """Returns the anchor of a node, and whether this occurrence is an alias."""
98
+ name = ctx.anchors.get(id(value)) if isinstance(value, (list, dict)) else None
99
+ if name is None:
100
+ return None, False
101
+ if id(value) in ctx.emitted:
102
+ return name, True
103
+ ctx.emitted.add(id(value))
104
+ return name, False
105
+
106
+
107
+ def _item(value: Json, ctx: _Ctx) -> str:
108
+ """Writes a sequence item."""
109
+ name, alias = _anchor(value, ctx)
110
+ if name is None:
111
+ return f"- {_node(value, ctx)}"
112
+ if alias:
113
+ return f"- *{name}"
114
+ text = _node(value, ctx)
115
+ return f"- &{name} {text}" if not value else f"- &{name}\n{ctx.indent}{text}"
116
+
117
+
118
+ def _node(value: Json, ctx: _Ctx) -> str:
119
+ if value is None:
120
+ return "null"
121
+ if isinstance(value, bool):
122
+ return "true" if value else "false"
123
+ if isinstance(value, (int, float)):
124
+ return _js.number_to_string(value)
125
+ if isinstance(value, str):
126
+ return _string_scalar(value, ctx)
127
+ if isinstance(value, list):
128
+ if not value:
129
+ return "[]"
130
+ item_ctx = replace(ctx, indent=ctx.indent + " ", indent_at_start=None)
131
+ return f"\n{ctx.indent}".join(_item(item, item_ctx) for item in value)
132
+ if not value:
133
+ return "{}"
134
+ return f"\n{ctx.indent}".join(_pair(k, v, ctx) for k, v in value.items())
135
+
136
+
137
+ def _pair(key: str, value: Json, ctx: _Ctx) -> str:
138
+ pair_ctx = replace(ctx, implicit_key=True, indent=ctx.indent + " ", indent_at_start=None)
139
+ key_str = _string_scalar(key, pair_ctx)
140
+ # Keys longer than 1024 characters need explicit `? key` syntax.
141
+ explicit = _js.utf16_len(key_str) > 1024
142
+ out = f"? {key_str}\n{ctx.indent}:" if explicit else f"{key_str}:"
143
+ pair_ctx.implicit_key = False
144
+ collection = isinstance(value, (list, dict))
145
+ name, alias = _anchor(value, ctx)
146
+ if name is not None:
147
+ if alias:
148
+ return f"{out} *{name}"
149
+ value_str = _node(value, pair_ctx)
150
+ if not value:
151
+ return f"{out} &{name} {value_str}"
152
+ return f"{out} &{name}\n{pair_ctx.indent}{value_str}"
153
+ if not explicit and not collection:
154
+ pair_ctx.indent_at_start = _js.utf16_len(out) + 1
155
+ value_str = _node(value, pair_ctx)
156
+ if not explicit and collection:
157
+ ws = f"\n{pair_ctx.indent}" if "\n" in value_str or value else " "
158
+ elif not value_str or value_str.startswith("\n"):
159
+ ws = ""
160
+ else:
161
+ ws = " "
162
+ return out + ws + value_str
163
+
164
+
165
+ def _document_marker(value: str) -> bool:
166
+ r"""Whether a string matches `/^(%|---|\\.\\.\\.)/m`."""
167
+ return any(line.startswith(("%", "---", "...")) for line in value.split("\n"))
168
+
169
+
170
+ def _string_scalar(value: str, ctx: _Ctx) -> str:
171
+ for ch in value:
172
+ code = ord(ch)
173
+ if code <= 0x08 or 0x0B <= code <= 0x1F or 0x7F <= code <= 0x9F:
174
+ return _double_quoted(value, ctx)
175
+ return _plain(value, ctx)
176
+
177
+
178
+ def _plain(value: str, ctx: _Ctx) -> str:
179
+ if ctx.implicit_key and "\n" in value:
180
+ return _quoted(value, ctx)
181
+ if _needs_quotes(value):
182
+ if ctx.implicit_key or "\n" not in value:
183
+ return _quoted(value, ctx)
184
+ return _block(value, ctx)
185
+ if not ctx.implicit_key and "\n" in value:
186
+ return _block(value, ctx)
187
+ if _document_marker(value):
188
+ if not ctx.indent:
189
+ return _block(value, replace(ctx, force_block_indent=True))
190
+ if ctx.implicit_key and ctx.indent == " ":
191
+ return _quoted(value, ctx)
192
+ if value == "" or _NON_STRING.fullmatch(value):
193
+ return _quoted(value, ctx)
194
+ if ctx.implicit_key:
195
+ return value
196
+ return _fold(value, ctx.indent, _FLOW, ctx.indent_at_start)
197
+
198
+
199
+ def _needs_quotes(value: str) -> bool:
200
+ """Matches the indicator characters that forbid a plain scalar."""
201
+ if not value:
202
+ return False
203
+ first = value[0]
204
+ if first in "\n\t ,[]{}#&*!|>'\"%@`":
205
+ return True
206
+ if first in "?-" and (len(value) == 1 or value[1] in " \t"):
207
+ return True
208
+ for a, b in itertools.pairwise(value):
209
+ if (a in "\n:" and b in " \t") or (a in " \t" and b == "\n") or (a in "\n\t " and b == "#"):
210
+ return True
211
+ return value[-1] in "\n\t :"
212
+
213
+
214
+ def _quoted(value: str, ctx: _Ctx) -> str:
215
+ if '"' in value and "'" not in value:
216
+ return _single_quoted(value, ctx)
217
+ return _double_quoted(value, ctx)
218
+
219
+
220
+ def _single_quoted(value: str, ctx: _Ctx) -> str:
221
+ # Multiline strings reach here only as implicit keys or with whitespace around a line
222
+ # break, and single quotes can hold neither.
223
+ if "\n" in value:
224
+ return _double_quoted(value, ctx)
225
+ indent = " " if not ctx.indent and _document_marker(value) else ctx.indent
226
+ res = "'" + value.replace("'", "''") + "'"
227
+ if ctx.implicit_key:
228
+ return res
229
+ return _fold(res, indent, _FLOW, ctx.indent_at_start)
230
+
231
+
232
+ def _double_quoted(value: str, ctx: _Ctx) -> str:
233
+ indent = " " if not ctx.indent and _document_marker(value) else ctx.indent
234
+ json = _js.utf16(_js.stringify(value))
235
+ size = len(json)
236
+
237
+ def at(i: int) -> int:
238
+ return json[i] if i < size else 0
239
+
240
+ def part(a: int, b: int) -> str:
241
+ return _js.from_utf16(json[a:b])
242
+
243
+ out = ""
244
+ start = 0
245
+ i = 0
246
+ space, backslash, quote = ord(" "), ord("\\"), ord('"')
247
+ while i < size:
248
+ ch = at(i)
249
+ if ch == space and at(i + 1) == backslash and at(i + 2) == ord("n"):
250
+ out += part(start, i) + "\\ "
251
+ i += 1
252
+ start = i
253
+ ch = backslash
254
+ if ch == backslash:
255
+ nxt = at(i + 1)
256
+ if nxt == ord("u"):
257
+ out += part(start, i)
258
+ code = part(i + 2, i + 6)
259
+ special = {"0000": "\\0", "0007": "\\a", "000b": "\\v", "001b": "\\e"}
260
+ # `JSON.stringify` escapes only C0 controls, so `code` is `00XX`.
261
+ out += special.get(code, "\\x" + code[2:])
262
+ i += 5
263
+ start = i + 1
264
+ elif nxt == ord("n"):
265
+ if ctx.implicit_key or at(i + 2) == quote or size < 40:
266
+ i += 1
267
+ else:
268
+ out += part(start, i) + "\n\n"
269
+ while at(i + 2) == backslash and at(i + 3) == ord("n") and at(i + 4) != quote:
270
+ out += "\n"
271
+ i += 2
272
+ out += indent
273
+ if at(i + 2) == space:
274
+ out += "\\"
275
+ i += 1
276
+ start = i + 1
277
+ else:
278
+ i += 1
279
+ i += 1
280
+ result = out + part(start, size) if start > 0 else part(0, size)
281
+ if ctx.implicit_key:
282
+ return result
283
+ return _fold(result, indent, _QUOTED, ctx.indent_at_start)
284
+
285
+
286
+ def _block(value: str, ctx: _Ctx) -> str:
287
+ """Stringifies a block scalar (`|` literal or `>` folded)."""
288
+ newline = value.rfind("\n")
289
+ tail = value[newline + 1 :]
290
+ if newline >= 0 and tail and all(ch in " \t" for ch in tail):
291
+ return _quoted(value, ctx)
292
+ if ctx.indent:
293
+ indent = ctx.indent
294
+ elif ctx.force_block_indent or _document_marker(value):
295
+ indent = " "
296
+ else:
297
+ indent = ""
298
+ literal = not _line_over_limit(value, len(indent))
299
+
300
+ # Chomping from trailing whitespace.
301
+ end_start = len(value)
302
+ while end_start > 0 and value[end_start - 1] in "\n\t ":
303
+ end_start -= 1
304
+ end = value[end_start:]
305
+ body = value[:end_start]
306
+ pos = end.find("\n")
307
+ if pos < 0:
308
+ chomp = "-"
309
+ elif not body or pos != len(end) - 1:
310
+ chomp = "+"
311
+ else:
312
+ chomp = ""
313
+ if end:
314
+ end = _indent_runs(end.removesuffix("\n"), indent, inner=True)
315
+
316
+ # Indentation indicator from leading whitespace.
317
+ start_with_space = False
318
+ start_nl = -1
319
+ for index, ch in enumerate(body):
320
+ if ch == " ":
321
+ start_with_space = True
322
+ elif ch == "\n":
323
+ start_nl = index
324
+ else:
325
+ break
326
+ start = body[: start_nl + 1]
327
+ if start:
328
+ body = body[start_nl + 1 :]
329
+ start = _indent_runs(start, indent, inner=False)
330
+ header = ("2" if indent else "1") if start_with_space else ""
331
+ header += chomp
332
+
333
+ if not literal:
334
+ folded = _fold_block_body(body, indent)
335
+ overflow = [False]
336
+ folded = _fold(start + folded + end, indent, _BLOCK, len(indent), overflow)
337
+ if not overflow[0]:
338
+ return f">{header}\n{indent}{folded}"
339
+ return f"|{header}\n{indent}{start}{_indent_runs(body, indent, inner=False)}{end}"
340
+
341
+
342
+ def _indent_runs(value: str, indent: str, *, inner: bool) -> str:
343
+ """Follows each run of newlines with `indent`; with `inner`, not a trailing run."""
344
+ out: list[str] = []
345
+ run = 0
346
+ for ch in value:
347
+ if ch == "\n":
348
+ run += 1
349
+ continue
350
+ if run:
351
+ out.append("\n" * run + indent)
352
+ run = 0
353
+ out.append(ch)
354
+ if run:
355
+ out.append("\n" * run + ("" if inner else indent))
356
+ return "".join(out)
357
+
358
+
359
+ def _fold_block_body(value: str, indent: str) -> str:
360
+ """Prepares a folded block body: doubles line breaks and keeps more-indented lines literal."""
361
+ doubled = re.sub(r"\n+", lambda m: "\n" + m.group(0), value)
362
+ return _indent_runs(_keep_more_indented(doubled), indent, inner=False)
363
+
364
+
365
+ def _keep_more_indented(value: str) -> str:
366
+ """Undoes the doubled line breaks around more-indented lines."""
367
+ out: list[str] = []
368
+ size = len(value)
369
+ i = 0
370
+ while i < size:
371
+ if i == 0 and value[0] in "\t ":
372
+ line = 0
373
+ elif value[i] == "\n" and i + 1 < size and value[i + 1] in "\t ":
374
+ line = i + 1
375
+ else:
376
+ out.append(value[i])
377
+ i += 1
378
+ continue
379
+ # `.` stops at JavaScript line terminators.
380
+ end = line
381
+ while end < size and value[end] not in "\n\r\u2028\u2029":
382
+ end += 1
383
+ out.append(value[line:end])
384
+ run = end
385
+ while run < size and value[run] in "\n\t ":
386
+ run += 1
387
+ # The optional group matches only when the blank run ends with a line break.
388
+ if run > end and value[run - 1] == "\n":
389
+ out.append(value[end : run - 1])
390
+ i = run
391
+ else:
392
+ i = end
393
+ return "".join(out)
394
+
395
+
396
+ def _line_over_limit(value: str, indent: int) -> bool:
397
+ width = _width.get()
398
+ if not width:
399
+ return False
400
+ limit = width - indent
401
+ units = _js.utf16(value)
402
+ if len(units) <= limit:
403
+ return False
404
+ start = 0
405
+ for i, unit in enumerate(units):
406
+ if unit == 0x0A:
407
+ if i - start > limit:
408
+ return True
409
+ start = i + 1
410
+ if len(units) - start <= limit:
411
+ return False
412
+ return True
413
+
414
+
415
+ def _fold(
416
+ text: str,
417
+ indent: str,
418
+ mode: int,
419
+ indent_at_start: int | None,
420
+ on_overflow: list[bool] | None = None,
421
+ ) -> str:
422
+ """Folds long lines at spaces, as `foldFlowLines` does."""
423
+ if not _width.get():
424
+ return text
425
+ units = _js.utf16(text)
426
+ size = len(units)
427
+
428
+ def at(i: int) -> int | None:
429
+ return units[i] if 0 <= i < size else None
430
+
431
+ indent_len = len(indent)
432
+ end_step = max(1 + MIN_CONTENT_WIDTH, 1 + LINE_WIDTH - indent_len)
433
+ if size <= end_step:
434
+ return text
435
+ folds: list[int] = []
436
+ escaped: list[int] = []
437
+ end = LINE_WIDTH - indent_len
438
+ if indent_at_start is not None:
439
+ if indent_at_start > LINE_WIDTH - MIN_CONTENT_WIDTH:
440
+ folds.append(0)
441
+ else:
442
+ end = LINE_WIDTH - indent_at_start
443
+ split: int | None = None
444
+ prev: int | None = None
445
+ overflow = False
446
+ i = -1
447
+ esc_start = -1
448
+ esc_end = -1
449
+ if mode == _BLOCK:
450
+ i = _consume_more_indented(units, i, indent_len)
451
+ if i != -1:
452
+ end = i + end_step
453
+ sp, nl, tab = 0x20, 0x0A, 0x09
454
+ while True:
455
+ i += 1
456
+ ch = at(i)
457
+ if ch is None:
458
+ break
459
+ if mode == _QUOTED and ch == 0x5C:
460
+ esc_start = i
461
+ # Only `\xXX` escapes are longer than two units after `_double_quoted`.
462
+ i += 3 if at(i + 1) == 0x78 else 1
463
+ esc_end = i
464
+ if ch == nl:
465
+ if mode == _BLOCK:
466
+ i = _consume_more_indented(units, i, indent_len)
467
+ end = i + indent_len + end_step
468
+ split = None
469
+ else:
470
+ if ch == sp and prev is not None and prev not in (sp, nl, tab):
471
+ nxt = at(i + 1)
472
+ if nxt is not None and nxt not in (sp, nl, tab):
473
+ split = i
474
+ if i >= end:
475
+ if split is not None:
476
+ folds.append(split)
477
+ end = split + end_step
478
+ split = None
479
+ elif mode == _QUOTED:
480
+ while prev in (sp, tab):
481
+ prev = ch
482
+ i += 1
483
+ ch = at(i) or 0
484
+ overflow = True
485
+ j = max(i - 2 if i > esc_end + 1 else esc_start - 1, 0)
486
+ folds.append(j)
487
+ escaped.append(j)
488
+ end = j + end_step
489
+ split = None
490
+ else:
491
+ overflow = True
492
+ prev = ch
493
+ if overflow and on_overflow is not None:
494
+ on_overflow[0] = True
495
+ if not folds:
496
+ return text
497
+
498
+ def part(a: int, b: int) -> str:
499
+ return _js.from_utf16(units[max(a, 0) : b])
500
+
501
+ res = part(0, folds[0])
502
+ for k, fold_at in enumerate(folds):
503
+ following = folds[k + 1] if k + 1 < len(folds) else 0
504
+ stop = following if following != 0 else size
505
+ if fold_at == 0:
506
+ res = f"\n{indent}{part(0, stop)}"
507
+ else:
508
+ if mode == _QUOTED and fold_at in escaped:
509
+ res += part(fold_at, fold_at + 1) + "\\"
510
+ res += f"\n{indent}{part(fold_at + 1, stop)}"
511
+ return res
512
+
513
+
514
+ def _consume_more_indented(units: list[int], i: int, indent: int) -> int:
515
+ """Skips more-indented lines of a block scalar. Returns the last newline consumed."""
516
+
517
+ def at(k: int) -> int | None:
518
+ return units[k] if 0 <= k < len(units) else None
519
+
520
+ end = i
521
+ start = i + 1
522
+ ch = at(start)
523
+ while ch in (0x20, 0x09):
524
+ if i < start + indent:
525
+ i += 1
526
+ ch = at(i)
527
+ else:
528
+ while True:
529
+ i += 1
530
+ ch = at(i)
531
+ if ch is None or ch == 0x0A:
532
+ break
533
+ end = i
534
+ start = i + 1
535
+ ch = at(start)
536
+ return end
537
+
538
+
539
+ _PAIR = re.compile(r"^([^\s#'\"][^:]*?|\"[^\"]*\"|'[^']*'):(?:\s+(.*))?$")
540
+
541
+
542
+ def _scalar(text: str) -> Json:
543
+ """Reads a flow scalar: quoted text, or a plain scalar resolved by the core schema."""
544
+ if text.startswith("'") and text.endswith("'") and len(text) > 1:
545
+ return text[1:-1].replace("''", "'")
546
+ if text.startswith('"') and text.endswith('"') and len(text) > 1:
547
+ if _js.json_parse_error(text) is not None:
548
+ raise ValueError(f"Invalid double-quoted scalar: {text}")
549
+ return _js.parse_json(text)
550
+ plain = re.sub(r"\s+#.*$", "", text).strip()
551
+ if plain in ("", "~", "null", "Null", "NULL"):
552
+ return None
553
+ if plain in ("true", "True", "TRUE"):
554
+ return True
555
+ if plain in ("false", "False", "FALSE"):
556
+ return False
557
+ if re.fullmatch(r"[-+]?[0-9]+", plain):
558
+ return int(plain)
559
+ return plain
560
+
561
+
562
+ _BLOCK_HEADER = re.compile(r"^([|>])([1-9+-]{0,2})(?:\s+#.*)?$")
563
+
564
+
565
+ def _fold_lines(lines: list[str]) -> str:
566
+ """Folds lines as a folded scalar does.
567
+
568
+ A break between two normal lines becomes a space, empty lines keep their breaks, and breaks
569
+ around more-indented lines stay as written.
570
+ """
571
+ parts: list[str] = []
572
+ previous: str | None = None
573
+ empty = 0
574
+ for line in lines:
575
+ if not line:
576
+ empty += 1
577
+ continue
578
+ kind = "more" if line[0] in " \t" else "normal"
579
+ if previous is None:
580
+ parts.append("\n" * empty)
581
+ elif previous == kind == "normal":
582
+ parts.append("\n" * empty or " ")
583
+ else:
584
+ parts.append("\n" * (empty + 1))
585
+ parts.append(line)
586
+ previous, empty = kind, 0
587
+ return "".join(parts)
588
+
589
+
590
+ def _block_scalar(header: re.Match[str], lines: list[str]) -> str:
591
+ """Reads the body of a top-level block scalar (`|` literal or `>` folded)."""
592
+ style, indicators = header[1], header[2]
593
+ digits = [c for c in indicators if c.isdigit()]
594
+ chomp = next((c for c in indicators if c in "+-"), "")
595
+ width = int(digits[0]) if digits else None
596
+ if width is None:
597
+ # The first non-empty line sets the indentation.
598
+ width = next((len(ln) - len(ln.lstrip(" ")) for ln in lines if ln.strip()), 0)
599
+ body = [ln[width:] if ln.strip() else "" for ln in lines]
600
+ trailing = len(body) - len([*itertools.dropwhile(lambda ln: not ln, reversed(body))])
601
+ body = body[: len(body) - trailing]
602
+ content = "\n".join(body) if style == "|" else _fold_lines(body)
603
+ if chomp == "-" or not content:
604
+ return content
605
+ return content + "\n" * (1 + (trailing if chomp == "+" else 0))
606
+
607
+
608
+ def parse_mapping(text: str) -> dict[str, Json]:
609
+ r"""Parses a block mapping of scalars, such as skill frontmatter, as `yaml` reads it.
610
+
611
+ Supports `key: value` lines with plain, single-quoted, and double-quoted scalars, plain
612
+ scalars continued on indented lines, and `|` literal and `>` folded block scalars with
613
+ chomping and indentation indicators. Comments and lines of any other form are skipped.
614
+
615
+ >>> parse_mapping('name: demo\ndescription: "Say \\"hi\\""')
616
+ {'name': 'demo', 'description': 'Say "hi"'}
617
+ >>> parse_mapping("'a b': 'it''s'\n\"k\": ~\non: true\noff: FALSE\nn: -3\nx: y # c\n- z")
618
+ {'a b': "it's", 'k': None, 'on': True, 'off': False, 'n': -3, 'x': 'y'}
619
+ >>> parse_mapping("a: |\n one\n two\n\nb: >-\n folded\n text\n\n more\nc: |+\n kept\n\n")
620
+ {'a': 'one\n two\n', 'b': 'folded text\nmore', 'c': 'kept\n\n'}
621
+ >>> parse_mapping("d: >\n a\n indented\n b\ne: |2-\n x\nf: |\ng: a\n b\n\n\n c")
622
+ {'d': 'a\n indented\nb\n', 'e': ' x', 'f': '', 'g': 'a b\n\nc'}
623
+
624
+ Raises:
625
+ ValueError: When a double-quoted scalar has an invalid escape, as `yaml` rejects it.
626
+ """
627
+ out: dict[str, Json] = {}
628
+ lines = text.splitlines()
629
+ i = 0
630
+ while i < len(lines):
631
+ match = _PAIR.match(lines[i].rstrip())
632
+ i += 1
633
+ if match is None:
634
+ continue
635
+ # A value's continuation: the indented and empty lines that follow its key.
636
+ start = i
637
+ while i < len(lines) and (not lines[i].strip() or lines[i][0] in " \t"):
638
+ i += 1
639
+ rest = lines[start:i]
640
+ key = match[1].strip()
641
+ name = str(_scalar(key)) if key[0] in "'\"" else key
642
+ value = match[2] or ""
643
+ header = _BLOCK_HEADER.match(value)
644
+ if header is not None:
645
+ out[name] = _block_scalar(header, rest)
646
+ elif value[:1] not in ("'", '"') and any(ln.strip() for ln in rest):
647
+ # A multi-line plain scalar folds its lines.
648
+ out[name] = _scalar(_fold_lines([value, *(ln.strip() for ln in rest)]))
649
+ else:
650
+ out[name] = _scalar(value)
651
+ return out
incur/py.typed ADDED
File without changes