Debian Codegraph @

DisplayCAL/lazydict.py

raw
1 """Lazy-loading dictionaries that defer loading from files (JSON/YAML) until accessed.""" # noqa: E501
2
3 from __future__ import annotations
4
5 import codecs
6 import json
7 import os
8 from typing import TYPE_CHECKING, Any, TextIO
9
10 from DisplayCAL.config import get_data_path
11 from DisplayCAL.debughelpers import handle_error
12 from DisplayCAL.util_str import safe_str
13
14 if TYPE_CHECKING:
15 from collections.abc import Iterable, Iterator
16
17
18 def unquote(string: str, raise_exception: bool = True) -> str:
19 """Remove outer single/double quotes and unescape YAML-style escapes.
20
21 Unlike 'string'.strip("'"'"'), only removes the outermost quote pair.
22 Raises ValueError on missing end quote if there is a start quote.
23
24 Args:
25 string (str): The string to unquote.
26 raise_exception (bool, optional): If True, raises a ValueError if the
27 string is not properly quoted. Defaults to True.
28
29 Returns:
30 str: The unquoted string.
31 """
32 if len(string) > 1 and string[0] in "'\"":
33 if string[-1] == string[0]:
34 # NOTE: Order of unescapes is important to match YAML!
35 string = unescape(string[1:-1])
36
37 elif raise_exception:
38 raise ValueError("Missing end quote while scanning quoted scalar")
39 return string
40
41
42 def escape(string: str) -> bytes:
43 """Backslash-escape special chars in string."""
44 if isinstance(string, str):
45 string = string.encode("string_escape")
46 return string
47
48
49 def unescape(string: bytes) -> str:
50 """Unescape escaped chars in string."""
51 if isinstance(string, bytes):
52 string = string.decode("string_escape")
53 return string
54
55
56 class LazyDict(dict):
57 """Lazy dictionary with key -> value mappings.
58
59 The actual mappings are loaded from the source YAML file when they
60 are accessed.
61
62 Args:
63 path (None | str, optional): The path to the file to load the
64 dictionary from. If not provided, the path set during
65 initialization will be used.
66 encoding (str, optional): The encoding to use when reading the file.
67 Defaults to "UTF-8".
68 errors (str, optional): The error handling scheme to use for decoding.
69 Defaults to "strict".
70 """
71
72 def __init__(
73 self,
74 path: None | str = None,
75 encoding: str = "UTF-8",
76 errors: str = "strict",
77 ) -> None:
78 super().__init__()
79 self._is_loaded = False
80 self.path = path
81 self.encoding = encoding
82 self.errors = errors
83
84 def __cmp__(self, other: Any) -> bool: # noqa: ANN401
85 """Compare the dictionary with another object.
86
87 Args:
88 other (Any): The object to compare with.
89
90 Returns:
91 bool: True if the dictionary is equal to the other object,
92 False otherwise.
93 """
94 self.load()
95 return super().__cmp__(other)
96
97 def __contains__(self, key: Any) -> bool: # noqa: ANN401
98 """Check if the dictionary contains a key.
99
100 Args:
101 key (Any): The key to check. Any hashable object.
102
103 Returns:
104 bool: True if the key is in the dictionary, False otherwise.
105 """
106 self.load()
107 return super().__contains__(key)
108
109 def __delitem__(self, key: Any) -> None: # noqa: ANN401
110 """Delete a key from the dictionary.
111
112 Args:
113 key (Any): The key to delete. Any hashable object.
114 """
115 self.load()
116 super().__delitem__(key)
117
118 def __eq__(self, other: object) -> bool:
119 """Compare the dictionary with another object.
120
121 Args:
122 other (Any): The object to compare with.
123
124 Returns:
125 bool: True if the dictionary is equal to the other object,
126 False otherwise.
127 """
128 self.load()
129 return super().__eq__(other)
130
131 def __ge__(self, other: Any) -> bool: # noqa: ANN401
132 """Compare the dictionary with another object.
133
134 Args:
135 other (Any): The object to compare with.
136
137 Returns:
138 bool: True if the dictionary is greater than or equal to the
139 other object, False otherwise.
140 """
141 self.load()
142 return super().__ge__(other)
143
144 def __getitem__(self, name: str) -> Any: # noqa: ANN401
145 """Get the value for a given key in the dictionary.
146
147 Args:
148 name (str): The key to get the value for.
149
150 Returns:
151 Any: The value associated with the key.
152 """
153 self.load()
154 return super().__getitem__(name)
155
156 def __gt__(self, other: Any) -> bool: # noqa: ANN401
157 """Compare the dictionary with another object.
158
159 Args:
160 other (Any): The object to compare with.
161
162 Returns:
163 bool: True if the dictionary is greater than the other object,
164 False otherwise.
165 """
166 self.load()
167 return super().__gt__(other)
168
169 def __iter__(self) -> Iterator:
170 """Return an iterator over the dictionary keys.
171
172 Returns:
173 Iterator: An iterator over the dictionary keys.
174 """
175 self.load()
176 return super().__iter__()
177
178 def __le__(self, other: Any) -> bool: # noqa: ANN401
179 """Compare the dictionary with another object.
180
181 Args:
182 other (Any): The object to compare with.
183
184 Returns:
185 bool: True if the dictionary is less than or equal to the other
186 object, False otherwise.
187 """
188 self.load()
189 return super().__le__(other)
190
191 def __len__(self) -> int:
192 """Return the number of items in the dictionary.
193
194 Returns:
195 int: The number of items in the dictionary.
196 """
197 self.load()
198 return super().__len__()
199
200 def __lt__(self, other: Any) -> bool: # noqa: ANN401
201 """Compare the dictionary with another object.
202
203 Args:
204 other (Any): The object to compare with.
205
206 Returns:
207 bool: True if the dictionary is less than the other object,
208 False otherwise.
209 """
210 self.load()
211 return super().__lt__(other)
212
213 def __ne__(self, other: object) -> bool:
214 """Compare the dictionary with another object.
215
216 Args:
217 other (Any): The object to compare with.
218
219 Returns:
220 bool: True if the dictionary is not equal to the other object,
221 False otherwise.
222 """
223 self.load()
224 return super().__ne__(other)
225
226 def __repr__(self) -> str:
227 """Return a string representation of the dictionary.
228
229 Returns:
230 str: A string representation of the dictionary.
231 """
232 self.load()
233 return super().__repr__()
234
235 def __setitem__(self, name: str, value: Any) -> None: # noqa: ANN401
236 """Set the value for a given key in the dictionary.
237
238 Args:
239 name (str): The key to set.
240 value (Any): The value to set for the key.
241 """
242 self.load()
243 super().__setitem__(name, value)
244
245 def __sizeof__(self) -> int:
246 """Return the size of the dictionary in bytes.
247
248 Returns:
249 int: The size of the dictionary in bytes.
250 """
251 self.load()
252 return super().__sizeof__()
253
254 def clear(self) -> None:
255 """Clear the dictionary."""
256 if not self._is_loaded:
257 self._is_loaded = True
258 super().clear()
259
260 def copy(self) -> dict:
261 """Return a shallow copy of the dictionary.
262
263 Returns:
264 dict: A shallow copy of the dictionary.
265 """
266 self.load()
267 return super().copy()
268
269 def get(self, name: str, fallback: None | Any = None) -> Any: # noqa: ANN401
270 """Get the value for a given key in the dictionary.
271
272 Args:
273 name (str): The key to get the value for.
274 fallback (Any, optional): The value to return if the key does not
275 exist. Defaults to None.
276
277 Returns:
278 Any: The value associated with the key, or the fallback value if
279 the key does not exist.
280 """
281 self.load()
282 return super().get(name, fallback)
283
284 def items(self) -> tuple[str, Any]:
285 """Return a tuple containing the dictionary's items.
286
287 Returns:
288 tuple[str, Any]: The dictionary's items, where each item is a tuple
289 of (key, value).
290 """
291 self.load()
292 return super().items()
293
294 def iteritems(self) -> Iterator:
295 """Return an iterator over the dictionary's items.
296
297 Returns:
298 Iterator: An iterator over the dictionary's items, where each item
299 is a tuple of (key, value).
300 """
301 self.load()
302 return super().items()
303
304 def iterkeys(self) -> Iterator:
305 """Return an iterator over the dictionary's keys.
306
307 Returns:
308 Iterator: An iterator over the dictionary's keys.
309 """
310 self.load()
311 return super().keys()
312
313 def itervalues(self) -> Iterator:
314 """Return an iterator over the dictionary's values.
315
316 Returns:
317 Iterator: An iterator over the dictionary's values.
318 """
319 self.load()
320 return super().values()
321
322 def keys(self) -> Any: # noqa: ANN401
323 """Return a view of the dictionary's keys.
324
325 Returns:
326 dict_keys: A view of the dictionary's keys.
327 """
328 self.load()
329 return super().keys()
330
331 def load(
332 self,
333 path: None | str = None,
334 encoding: None | str = None,
335 errors: None | str = None,
336 raise_exceptions: bool = False,
337 ) -> None:
338 """Load the dictionary from a file.
339
340 Args:
341 path (str, optional): The path to the file to load the dictionary
342 from. If not provided, the path set during initialization will
343 be used.
344 encoding (str, optional): The encoding to use when reading the
345 file. Defaults to "UTF-8".
346 errors (str, optional): The error handling scheme to use for
347 decoding. Defaults to "strict".
348 raise_exceptions (bool, optional): If True, exceptions will be
349 raised instead of handled. Defaults to False.
350
351 Raises:
352 UserWarning: If the file is not found or if there is an error
353 parsing the file, a UserWarning will be raised.
354 OSError: If there is an OS error while opening the file and
355 raise_exceptions is True.
356 Exception: If there is an error parsing the file and
357 raise_exceptions is True.
358 """
359 if self._is_loaded or (not path and not self.path):
360 return
361
362 self._is_loaded = True
363 if not path:
364 path = self.path
365 if path and not os.path.isabs(path):
366 path = get_data_path(path)
367 if path and os.path.isfile(path):
368 self.path = path
369 if encoding:
370 self.encoding = encoding
371 if errors:
372 self.errors = errors
373 else:
374 handle_error(UserWarning(f"Warning - file not found:\n\n{path}"), tb=False)
375 return
376 try:
377 with open(path, "r", encoding=self.encoding, errors=self.errors) as f:
378 self.parse(f)
379 except OSError as exception:
380 if raise_exceptions:
381 raise
382 handle_error(exception)
383 except Exception as exception:
384 if raise_exceptions:
385 raise
386 handle_error(
387 UserWarning(f"Error parsing file:\n\n{path}\n\n{exception}"),
388 tb=False,
389 )
390
391 def parse(self, iterable: Iterable[tuple[str, Any]]) -> None:
392 """Parse the iterable and update the dictionary.
393
394 Args:
395 iterable (Iterable[tuple[str, Any]]): An iterable object (e.g.,
396 file object) to parse and update the dictionary with.
397 """
398 # Override this in subclass
399
400 def pop(self, key: str, *args) -> Any: # noqa: ANN401
401 """Remove a key from the dictionary and return its value.
402
403 Args:
404 key (str): The key to remove.
405 *args: Optional arguments to pass to the pop method.
406
407 Returns:
408 Any: The value associated with the key that was removed.
409 """
410 self.load()
411 return super().pop(key, *args)
412
413 def popitem(self, name: str, value: Any) -> tuple[str, Any]: # noqa: ANN401
414 """Remove and return a (key, value) pair from the dictionary.
415
416 Args:
417 name (str): The key to remove.
418 value (Any): The value to return if the key does not exist.
419
420 Returns:
421 tuple: The (key, value) pair removed from the dictionary.
422 """
423 self.load()
424 return super().popitem(name, value)
425
426 def setdefault(self, name: str, value: None | Any = None) -> Any: # noqa: ANN401
427 """Set the default value for a key in the dictionary.
428
429 Args:
430 name (str): The key to set the default value for.
431 value (Any, optional): The default value to set if the key does
432 not exist. Defaults to None.
433
434 Returns:
435 Any: The value associated with the key after setting the default.
436 """
437 self.load()
438 return super().setdefault(name, value)
439
440 def update(self, other: dict | Iterable[tuple[str, Any]]) -> None:
441 """Update the dictionary with another dictionary or iterable of key-value pairs.
442
443 Args:
444 other (dict | Iterable[tuple[str, Any]]): The dictionary or
445 iterable of key-value pairs to update the dictionary with.
446 """
447 self.load()
448 super().update(other)
449
450 def values(self) -> Any: # noqa: ANN401
451 """Return a view of the dictionary's values.
452
453 Returns:
454 dict_values: A view of the dictionary's values.
455 """
456 self.load()
457 return super().values()
458
459
460 class LazyDictJSON(LazyDict):
461 """JSON lazy dictionary."""
462
463 def parse(self, fileobj: TextIO) -> None:
464 """Parse fileobj and update dict."""
465 super().update(json.load(fileobj))
466
467
468 class LazyDictYAMLUltraLite(LazyDict):
469 """'YAML Ultra Lite' lazy dictionary.
470
471 YAML Ultra Lite is a restricted subset of YAML. It only supports the
472 following notations:
473
474 Key: Value 1
475 "Key 2": "Value 2"
476 "Key 3": |-
477 Value 3 Line 1
478 Value 3 Line 2
479
480 All values are treated as strings.
481
482 Syntax checking is limited for speed.
483 Parsing is around a factor of 20 to 30 faster than PyYAML,
484 around 8 times faster than JSONDict (based on demjson),
485 and about 2 times faster than YAML_Lite.
486
487 Args:
488 path (None | str, optional): The path to the file to load the
489 dictionary from. If not provided, the path set during
490 initialization will be used.
491 encoding (str, optional): The encoding to use when reading the file.
492 Defaults to "UTF-8".
493 errors (str, optional): The error handling scheme to use for decoding.
494 Defaults to "strict".
495 debug (bool, optional): If True, debug output will be printed during
496 parsing. Defaults to False.
497 """
498
499 def __init__(
500 self,
501 path: None | str = None,
502 encoding: str = "UTF-8",
503 errors: str = "strict",
504 debug: bool = False,
505 ) -> None:
506 super().__init__(path, encoding, errors)
507 self.debug = debug
508
509 def debug_print(self, *args: Any) -> None: # noqa: ANN401
510 """Print debug information if debugging is enabled.
511
512 Args:
513 *args (Any): The arguments to print.
514 """
515 if self.debug:
516 print(*args)
517
518 def parse(self, fileobj: TextIO) -> None:
519 """Parse fileobj and update dict.
520
521 Args:
522 fileobj (TextIO): The file-like object to parse.
523 """
524 block = False
525 value = []
526 key = None
527 # Readlines is actually MUCH faster than iterating over the
528 # file object
529 for i, line in enumerate(fileobj.readlines(), 1):
530 line = line.replace("\r\n", "\n")
531 if line.lstrip(" ").startswith("#"):
532 # Ignore comments
533 pass
534 elif line != "\n" and not line.startswith(" "):
535 block, value, key = self._parse_line(line, value, key, fileobj, i)
536 else:
537 if not block:
538 raise ValueError(
539 "Unsupported format ({!r} line {})".format(
540 safe_str(getattr(fileobj, "name", line)), i
541 )
542 )
543 value.append(line[2:])
544 if key:
545 self[key] = "".join(value).rstrip("\n")
546
547 def _parse_line(
548 self, line: str, value: list, key: str, fileobj: TextIO, i: int
549 ) -> tuple[bool, list, str]:
550 """Parse a single line of the file and update the dictionary.
551
552 Args:
553 line (str): The line to parse.
554 value (list): The current value being built.
555 key (str): The current key being built.
556 fileobj (TextIO): The file-like object being parsed.
557 i (int): The current line number.
558
559 Raises:
560 ValueError: If the line is not in the expected format.
561
562 Returns:
563 tuple: A tuple containing:
564 - block (bool): Whether the line is a block style.
565 - value (list): The value parsed from the line.
566 - key (str): The key parsed from the line.
567 """
568 if value:
569 self[key] = "".join(value).rstrip("\n")
570 # tokens = line.rstrip(' -|\n').split(":", 1)
571 tokens = line.split(":", 1)
572 if len(tokens) == 1:
573 raise ValueError(
574 "Unsupported format ({!r} line {})".format(
575 safe_str(getattr(fileobj, "name", line)), i
576 )
577 )
578 # key = tokens[0].strip("'"'"')
579 key = self._unquote(tokens[0].strip(), False, False, fileobj, i)
580 token = tokens[1].strip(" \n")
581 if token.startswith("|-"):
582 block = True
583 token = token[2:].lstrip(" ")
584 if token:
585 if token.startswith("#"):
586 value = []
587 return block, value, key
588 raise ValueError(
589 "Expected a comment or a line break ({} line {})".format(
590 format(safe_str(getattr(fileobj, "name", line))), i
591 )
592 )
593 elif token.startswith(("|", ">")):
594 raise ValueError(
595 "Style not supported ({!r} line {})".format(
596 safe_str(getattr(fileobj, "name", line)), i
597 )
598 )
599 elif token.startswith("\t"):
600 raise ValueError(
601 "Found character '\\t' that cannot "
602 "start any token ({!r} line {})".format(
603 safe_str(getattr(fileobj, "name", line)), i
604 )
605 )
606 if token:
607 # Inline value
608 block = False
609 if token.startswith("#"):
610 value = []
611 return block, value, key
612 comment_offset = token.find("#")
613 if (
614 comment_offset > -1
615 and token[comment_offset - 1 : comment_offset] == " "
616 ):
617 token = token[:comment_offset].rstrip(" \n")
618 if not token:
619 value = []
620 return block, value, key
621 # value = [token.strip("'"'"')]
622 value = [self._unquote(token, True, True, fileobj, i)]
623 else:
624 value = []
625
626 return block, value, key
627
628 def _unquote(
629 self,
630 token: str,
631 do_unescape: bool = True,
632 check: bool = False,
633 fileobj: None | TextIO = None,
634 lineno: int = -1,
635 ) -> str:
636 """Unquote a token, removing outer quotes and unescaping YAML-style escapes.
637
638 Args:
639 token (str): The token to unquote.
640 do_unescape (bool, optional): If True, unescape the token. Defaults
641 to True.
642 check (bool, optional): If True, perform additional checks on the
643 token. Defaults to False.
644 fileobj (TextIO, optional): The file-like object to use for error
645 reporting. Defaults to None.
646 lineno (int, optional): The line number for error reporting.
647 Defaults to -1
648
649 Returns:
650 str: The unquoted token.
651 """
652 if len(token) <= 1:
653 return token
654 c = token[0]
655 if c in "'\"" and c == token[-1]:
656 token = token[1:-1]
657 if check and token.count(c) != token.count("\\" + c):
658 raise ValueError(
659 "Unescaped quotes found in token ({!r} line {})".format(
660 safe_str(getattr(fileobj, "name", token)), lineno
661 )
662 )
663 if do_unescape:
664 token = unescape(token)
665 elif check and (token.count('"') != token.count('\\"')):
666 raise ValueError(
667 "Unbalanced quotes found in token ({!r} line {})".format(
668 safe_str(getattr(fileobj, "name", token)), lineno
669 )
670 )
671 if check and "\\'" in token:
672 raise ValueError(
673 'Found unknown escape character "\'" ({!r} line {})'.format(
674 safe_str(getattr(fileobj, "name", token)), lineno
675 )
676 )
677 return token
678
679
680 class LazyDictYAMLLite(LazyDictYAMLUltraLite):
681 """'YAML Lite' lazy dictionary.
682
683 YAML Lite is a restricted subset of YAML. It only supports the
684 following notations:
685
686 Key: Value 1
687 "Key 2": "Value 2"
688 "Key 3": |-
689 Value 3 Line 1
690 Value 3 Line 2
691 "Key 4": |
692 Value 4 Line 1
693 Value 4 Line 2
694 "Key 5": Folded value 5
695 Folded value 5, continued
696
697 All values are treated as strings.
698
699 Syntax checking is limited for speed.
700 Parsing is around a factor of 12 to 16 faster than PyYAML,
701 and around 4 times faster than JSONDict (based on demjson).
702
703 """
704
705 def parse(self, fileobj: TextIO) -> None:
706 """Parse fileobj and update dict.
707
708 Args:
709 fileobj (TextIO): The file-like object to parse.
710 """
711 style = None
712 value = []
713 block_styles = ("|", ">", "|-", ">-", "|+", ">+")
714 quote = None
715 key = None
716 # Readlines is actually MUCH faster than iterating over the
717 # file object
718 for i, line in enumerate(fileobj.readlines(), 1):
719 line = line.replace("\r\n", "\n")
720 line_lwstrip = line.lstrip(" ")
721 line_rstrip = line.rstrip() if quote else None
722 self.debug_print("LINE", repr(line))
723 if not quote and style not in block_styles and line_lwstrip.startswith("#"):
724 # Ignore comments
725 pass
726 elif quote and line_rstrip and line_rstrip[-1] == quote:
727 self.debug_print("END QUOTE")
728 self.debug_print("+ APPEND STRIPPED", repr(line.strip()))
729 value.append(line.strip())
730 self._collect(key, value, ">i")
731 style = None
732 value = []
733 quote = None
734 key = None
735 elif (
736 style not in block_styles
737 and line.startswith(" ")
738 and line_lwstrip
739 and line_lwstrip[0] in ("'", '"')
740 ):
741 self.validate_quote(quote, line, fileobj, i)
742 self.debug_print("START QUOTE")
743 quote = line_lwstrip[0]
744 self.debug_print("+ APPEND LWSTRIPPED", repr(line_lwstrip))
745 value.append(line_lwstrip)
746 elif line.startswith(" ") and (
747 style in block_styles or line_lwstrip != "\n"
748 ):
749 if style == ">i":
750 if not quote and "\t" in line:
751 raise ValueError(
752 "Found character '\\t' that cannot "
753 "start any token ({!r} line {})".format(
754 safe_str(getattr(fileobj, "name", line)), i
755 )
756 )
757 line = line.strip() + "\n"
758 self.debug_print("APPEND STRIPPED + \\n", repr(line))
759 else:
760 line = line[2:]
761 self.debug_print("APPEND [2:]", repr(line))
762 value.append(line)
763 elif not quote and line_lwstrip != "\n" and not line.startswith(" "):
764 style, value, key, quote, skip_to_next_line = self._parse_line(
765 line, key, value, style, quote, fileobj, i
766 )
767 if skip_to_next_line:
768 continue
769 else:
770 # if line_lwstrip == "\n":
771 self.debug_print("APPEND LWSTRIPPED", repr(line_lwstrip))
772 line = line_lwstrip
773 value.append(line)
774 if quote:
775 raise ValueError(
776 "EOF while scanning quoted scalar ({!r} line {})".format(
777 safe_str(getattr(fileobj, "name", line)), i
778 )
779 )
780 if key:
781 self.debug_print("FINAL COLLECT")
782 self._collect(key, value, style)
783
784 def validate_quote(
785 self, quote: None | str, line: str, fileobj: TextIO, i: int
786 ) -> None:
787 """Validate the quote character to ensure it is properly closed.
788
789 Args:
790 quote (None | str): The current quote character, if any.
791 line (str): The line being parsed.
792 fileobj (TextIO): The file-like object being parsed.
793 i (int): The current line number.
794
795 Raises:
796 ValueError: If the quote character is not properly closed.
797 """
798 if quote:
799 raise ValueError(
800 "Wrong end quote while scanning quoted scalar ({!r} line {})".format(
801 safe_str(getattr(fileobj, "name", line)), i
802 )
803 )
804
805 def _parse_line(
806 self,
807 line: str,
808 key: str,
809 value: list,
810 style: None | str,
811 quote: None | str,
812 fileobj: TextIO,
813 i: int,
814 ) -> tuple[None | str, list, str, None | str, bool]:
815 """Parse a single line of the file and update the dictionary.
816
817 Args:
818 line (str): The line to parse.
819 key (str): The current key being built.
820 value (list): The current value being built.
821 style (None | str): The current style of the value.
822 quote (None | str): The current quote character, if any.
823 fileobj (TextIO): The file-like object being parsed.
824 i (int): The current line number.
825
826 Raises:
827 ValueError: If the line is not in the expected format.
828 NotImplementedError: If a folded style is encountered.
829
830 Returns:
831 tuple: A tuple containing:
832 - style (None | str): The style of the value.
833 - value (list): The value parsed from the line.
834 - key (str): The key parsed from the line.
835 - quote (None | str): The quote character, if any.
836 - skip_to_next_line (bool): Whether to skip to the next line.
837 """
838 if key and value:
839 self._collect(key, value, style)
840 tokens = line.split(":", 1)
841 key = unquote(tokens[0].strip())
842 if len(tokens) > 1:
843 token = tokens[1].lstrip(" ").rstrip(" \n")
844 if token.startswith(("|", ">")):
845 if token[1:2] in "+-":
846 style = token[:2]
847 token = token[2:].lstrip(" ")
848 else:
849 style = token[:1]
850 token = token[1:].lstrip(" ")
851 else:
852 style = ""
853 self.validate_token(token, line, fileobj, i)
854 self.validate_style(style, line, fileobj, i)
855 if token.startswith("#"):
856 # Block or folded
857 self.debug_print("IN BLOCK", repr(key), style)
858 value = []
859 return style, value, key, quote, True
860 if style and token:
861 raise ValueError(
862 "Expected a comment or a line break ({!r} line {})".format(
863 safe_str(getattr(fileobj, "name", line)), i
864 )
865 )
866 else:
867 raise ValueError(
868 "Unsupported format ({!r} line {})".format(
869 safe_str(getattr(fileobj, "name", line)), i
870 )
871 )
872 if style or not token:
873 # Block or folded
874 self.debug_print("IN BLOCK", repr(key), style)
875 value = []
876 else:
877 # Inline value
878 self.debug_print("IN PLAIN", repr(key), repr(token))
879 style = None
880 if token.startswith("#"):
881 value = []
882 return style, value, key, quote, True
883 token_rstrip = token.rstrip()
884 if (
885 token_rstrip
886 and token_rstrip[0] in ("'", '"')
887 and (len(token_rstrip) < 2 or token_rstrip[0] != token_rstrip[-1])
888 ):
889 self.debug_print("START QUOTE")
890 quote = token_rstrip[0]
891 else:
892 style = ">i"
893 comment_offset = token_rstrip.find("#")
894 if (
895 comment_offset > -1
896 and token_rstrip[comment_offset - 1 : comment_offset] == " "
897 ):
898 token_rstrip = token_rstrip[:comment_offset].rstrip()
899 token_rstrip += "\n"
900 self.debug_print("SET", repr(token_rstrip))
901 value = [token_rstrip]
902
903 return style, value, key, quote, False
904
905 def validate_token(self, token: str, line: str, fileobj: TextIO, i: int) -> None:
906 """Validate the token to ensure it starts with a valid character.
907
908 Args:
909 token (str): The token to validate.
910 line (str): The line containing the token.
911 fileobj (TextIO): The file-like object being parsed.
912 i (int): The current line number.
913
914 Raises:
915 ValueError: If the token starts with a tab character.
916 """
917 if token.startswith("\t"):
918 raise ValueError(
919 "Found character '\\t' that cannot "
920 "start any token ({!r} line {})".format(
921 safe_str(getattr(fileobj, "name", line)), i
922 )
923 )
924
925 def validate_style(
926 self, style: None | str, line: str, fileobj: TextIO, i: int
927 ) -> None:
928 """Validate the style to ensure it is supported.
929
930 Args:
931 style (None | str): The style to validate.
932 line (str): The line containing the style.
933 fileobj (TextIO): The file-like object being parsed.
934 i (int): The current line number.
935
936 Raises:
937 NotImplementedError: If the style is a folded style (starts with
938 '>').
939 """
940 if style.startswith(">"):
941 raise NotImplementedError(
942 "Folded style is not supported ({!r} line {})".format(
943 safe_str(getattr(fileobj, "name", line)), i
944 )
945 )
946
947 def _collect(self, key: str, value: list, style: None | str = None) -> None:
948 """Collect the key and value, formatting the value according to style.
949
950 Args:
951 key (str): The key to collect.
952 value (list): The value to collect, as a list of strings.
953 style (None | str, optional): The style to apply to the value.
954 Defaults to None.
955 """
956 self.debug_print("COLLECT", key, value, style)
957 chars = "".join(value)
958 chars = chars.rstrip(" ") if style != ">i" else chars
959 if not style or style.startswith(">"):
960 self.debug_print("FOLD")
961 out = ""
962 state = 0
963 for c in chars:
964 # print(repr(c), repr(state))
965 if c == "\n":
966 if state > 0:
967 out += c
968 state += 1
969 else:
970 if state == 1:
971 out += " "
972 state = 0
973 if style == ">i":
974 state = 0
975 out += c
976 else:
977 out = chars
978 out = out.lstrip(" ")
979 self.debug_print("OUT", repr(out))
980 if not style:
981 # Inline value
982 out = out.rstrip()
983 elif style.endswith("+"):
984 # Keep trailing newlines
985 self.debug_print("KEEP")
986 else:
987 out = out.rstrip("\n")
988 if style == ">i":
989 out = unquote(out)
990 elif style.endswith("-"):
991 # Chomp trailing newlines
992 self.debug_print("CHOMP")
993 else:
994 # Clip trailing newlines (default)
995 self.debug_print("CLIP")
996 if chars.endswith("\n"):
997 out += "\n"
998 self[key] = out