-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
items.py
1640 lines (1272 loc) · 41.5 KB
/
items.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
import copy
import re
import string
from datetime import date
from datetime import datetime
from datetime import time
from datetime import tzinfo
from enum import Enum
from functools import lru_cache
from typing import TYPE_CHECKING
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import TypeVar
from typing import Union
from typing import cast
from typing import overload
from ._compat import PY38
from ._compat import decode
from ._utils import escape_string
from .toml_char import TOMLChar
if TYPE_CHECKING: # pragma: no cover
# Define _CustomList and _CustomDict as a workaround for:
# https://github.com/python/mypy/issues/11427
#
# According to this issue, the typeshed contains a "lie"
# (it adds MutableSequence to the ancestry of list and MutableMapping to
# the ancestry of dict) which completely messes with the type inference for
# Table, InlineTable, Array and Container.
#
# Importing from builtins is preferred over simple assignment, see issues:
# https://github.com/python/mypy/issues/8715
# https://github.com/python/mypy/issues/10068
from builtins import dict as _CustomDict
from builtins import list as _CustomList
# Allow type annotations but break circular imports
from . import container
else:
from collections.abc import MutableMapping
from collections.abc import MutableSequence
class _CustomList(MutableSequence, list):
"""Adds MutableSequence mixin while pretending to be a builtin list"""
class _CustomDict(MutableMapping, dict):
"""Adds MutableMapping mixin while pretending to be a builtin dict"""
def item(
value: Any, _parent: Optional["Item"] = None, _sort_keys: bool = False
) -> "Item":
"""Create a TOML item from a Python object.
:Example:
>>> item(42)
42
>>> item([1, 2, 3])
[1, 2, 3]
>>> item({'a': 1, 'b': 2})
a = 1
b = 2
"""
from .container import Container
if isinstance(value, Item):
return value
if isinstance(value, bool):
return Bool(value, Trivia())
elif isinstance(value, int):
return Integer(value, Trivia(), str(value))
elif isinstance(value, float):
return Float(value, Trivia(), str(value))
elif isinstance(value, dict):
table_constructor = InlineTable if isinstance(_parent, Array) else Table
val = table_constructor(Container(), Trivia(), False)
for k, v in sorted(
value.items(),
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
):
val[k] = item(v, _parent=val, _sort_keys=_sort_keys)
only_child = len(value) == 1 and val[next(iter(value))]
if (
table_constructor is Table
and only_child
and isinstance(only_child, (AoT, Table))
):
# The table becomes super table if the only child is a table or AoT.
val._is_super_table = True
return val
elif isinstance(value, (list, tuple)):
if value and all(isinstance(v, dict) for v in value):
a = AoT([])
table_constructor = Table
else:
a = Array([], Trivia())
table_constructor = InlineTable
for v in value:
if isinstance(v, dict):
table = table_constructor(Container(), Trivia(), True)
for k, _v in sorted(
v.items(),
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
):
i = item(_v, _parent=a, _sort_keys=_sort_keys)
if isinstance(table, InlineTable):
i.trivia.trail = ""
table[k] = i
v = table
a.append(v)
return a
elif isinstance(value, str):
escaped = escape_string(value)
return String(StringType.SLB, decode(value), escaped, Trivia())
elif isinstance(value, datetime):
return DateTime(
value.year,
value.month,
value.day,
value.hour,
value.minute,
value.second,
value.microsecond,
value.tzinfo,
Trivia(),
value.isoformat().replace("+00:00", "Z"),
)
elif isinstance(value, date):
return Date(value.year, value.month, value.day, Trivia(), value.isoformat())
elif isinstance(value, time):
return Time(
value.hour,
value.minute,
value.second,
value.microsecond,
value.tzinfo,
Trivia(),
value.isoformat(),
)
raise ValueError(f"Invalid type {type(value)}")
class StringType(Enum):
# Single Line Basic
SLB = '"'
# Multi Line Basic
MLB = '"""'
# Single Line Literal
SLL = "'"
# Multi Line Literal
MLL = "'''"
@property
@lru_cache(maxsize=None)
def unit(self) -> str:
return self.value[0]
@lru_cache(maxsize=None)
def is_basic(self) -> bool:
return self in {StringType.SLB, StringType.MLB}
@lru_cache(maxsize=None)
def is_literal(self) -> bool:
return self in {StringType.SLL, StringType.MLL}
@lru_cache(maxsize=None)
def is_singleline(self) -> bool:
return self in {StringType.SLB, StringType.SLL}
@lru_cache(maxsize=None)
def is_multiline(self) -> bool:
return self in {StringType.MLB, StringType.MLL}
@lru_cache(maxsize=None)
def toggle(self) -> "StringType":
return {
StringType.SLB: StringType.MLB,
StringType.MLB: StringType.SLB,
StringType.SLL: StringType.MLL,
StringType.MLL: StringType.SLL,
}[self]
class BoolType(Enum):
TRUE = "true"
FALSE = "false"
@lru_cache(maxsize=None)
def __bool__(self):
return {BoolType.TRUE: True, BoolType.FALSE: False}[self]
def __iter__(self):
return iter(self.value)
def __len__(self):
return len(self.value)
class Trivia:
"""
Trivia information (aka metadata).
"""
def __init__(
self,
indent: str = None,
comment_ws: str = None,
comment: str = None,
trail: str = None,
) -> None:
# Whitespace before a value.
self.indent = indent or ""
# Whitespace after a value, but before a comment.
self.comment_ws = comment_ws or ""
# Comment, starting with # character, or empty string if no comment.
self.comment = comment or ""
# Trailing newline.
if trail is None:
trail = "\n"
self.trail = trail
def copy(self) -> "Trivia":
return type(self)(self.indent, self.comment_ws, self.comment, self.trail)
class KeyType(Enum):
"""
The type of a Key.
Keys can be bare (unquoted), or quoted using basic ("), or literal (')
quotes following the same escaping rules as single-line StringType.
"""
Bare = ""
Basic = '"'
Literal = "'"
class Key(abc.ABC):
"""Base class for a key"""
sep: str
_original: str
_keys: List["SingleKey"]
_dotted: bool
key: str
@abc.abstractmethod
def __hash__(self) -> int:
pass
@abc.abstractmethod
def __eq__(self, __o: object) -> bool:
pass
def is_dotted(self) -> bool:
"""If the key is followed by other keys"""
return self._dotted
def __iter__(self) -> Iterator["SingleKey"]:
return iter(self._keys)
def concat(self, other: "Key") -> "DottedKey":
"""Concatenate keys into a dotted key"""
keys = self._keys + other._keys
return DottedKey(keys, sep=self.sep)
def is_multi(self) -> bool:
"""Check if the key contains multiple keys"""
return len(self._keys) > 1
def as_string(self) -> str:
"""The TOML representation"""
return self._original
def __str__(self) -> str:
return self.as_string()
def __repr__(self) -> str:
return f"<Key {self.as_string()}>"
class SingleKey(Key):
"""A single key"""
def __init__(
self,
k: str,
t: Optional[KeyType] = None,
sep: Optional[str] = None,
original: Optional[str] = None,
) -> None:
if t is None:
if not k or any(
c not in string.ascii_letters + string.digits + "-" + "_" for c in k
):
t = KeyType.Basic
else:
t = KeyType.Bare
self.t = t
if sep is None:
sep = " = "
self.sep = sep
self.key = k
if original is None:
key_str = escape_string(k) if t == KeyType.Basic else k
original = f"{t.value}{key_str}{t.value}"
self._original = original
self._keys = [self]
self._dotted = False
@property
def delimiter(self) -> str:
"""The delimiter: double quote/single quote/none"""
return self.t.value
def is_bare(self) -> bool:
"""Check if the key is bare"""
return self.t == KeyType.Bare
def __hash__(self) -> int:
return hash(self.key)
def __eq__(self, other: Any) -> bool:
if isinstance(other, Key):
return isinstance(other, SingleKey) and self.key == other.key
return self.key == other
class DottedKey(Key):
def __init__(
self,
keys: Iterable[Key],
sep: Optional[str] = None,
original: Optional[str] = None,
) -> None:
self._keys = list(keys)
if original is None:
original = ".".join(k.as_string() for k in self._keys)
self.sep = " = " if sep is None else sep
self._original = original
self._dotted = False
self.key = ".".join(k.key for k in self._keys)
def __hash__(self) -> int:
return hash(tuple(self._keys))
def __eq__(self, __o: object) -> bool:
return isinstance(__o, DottedKey) and self._keys == __o._keys
class Item:
"""
An item within a TOML document.
"""
def __init__(self, trivia: Trivia) -> None:
self._trivia = trivia
@property
def trivia(self) -> Trivia:
"""The trivia element associated with this item"""
return self._trivia
@property
def discriminant(self) -> int:
raise NotImplementedError()
def as_string(self) -> str:
"""The TOML representation"""
raise NotImplementedError()
# Helpers
def comment(self, comment: str) -> "Item":
"""Attach a comment to this item"""
if not comment.strip().startswith("#"):
comment = "# " + comment
self._trivia.comment_ws = " "
self._trivia.comment = comment
return self
def indent(self, indent: int) -> "Item":
"""Indent this item with given number of spaces"""
if self._trivia.indent.startswith("\n"):
self._trivia.indent = "\n" + " " * indent
else:
self._trivia.indent = " " * indent
return self
def is_boolean(self) -> bool:
return isinstance(self, Bool)
def is_table(self) -> bool:
return isinstance(self, Table)
def is_inline_table(self) -> bool:
return isinstance(self, InlineTable)
def is_aot(self) -> bool:
return isinstance(self, AoT)
def _getstate(self, protocol=3):
return (self._trivia,)
def __reduce__(self):
return self.__reduce_ex__(2)
def __reduce_ex__(self, protocol):
return self.__class__, self._getstate(protocol)
class Whitespace(Item):
"""
A whitespace literal.
"""
def __init__(self, s: str, fixed: bool = False) -> None:
self._s = s
self._fixed = fixed
@property
def s(self) -> str:
return self._s
@property
def value(self) -> str:
"""The wrapped string of the whitespace"""
return self._s
@property
def trivia(self) -> Trivia:
raise RuntimeError("Called trivia on a Whitespace variant.")
@property
def discriminant(self) -> int:
return 0
def is_fixed(self) -> bool:
"""If the whitespace is fixed, it can't be merged or discarded from the output."""
return self._fixed
def as_string(self) -> str:
return self._s
def __repr__(self) -> str:
return f"<{self.__class__.__name__} {repr(self._s)}>"
def _getstate(self, protocol=3):
return self._s, self._fixed
class Comment(Item):
"""
A comment literal.
"""
@property
def discriminant(self) -> int:
return 1
def as_string(self) -> str:
return "{}{}{}".format(
self._trivia.indent, decode(self._trivia.comment), self._trivia.trail
)
def __str__(self) -> str:
return f"{self._trivia.indent}{decode(self._trivia.comment)}"
class Integer(int, Item):
"""
An integer literal.
"""
def __new__(cls, value: int, trivia: Trivia, raw: str) -> "Integer":
return super().__new__(cls, value)
def __init__(self, _: int, trivia: Trivia, raw: str) -> None:
super().__init__(trivia)
self._raw = raw
self._sign = False
if re.match(r"^[+\-]\d+$", raw):
self._sign = True
@property
def discriminant(self) -> int:
return 2
@property
def value(self) -> int:
"""The wrapped integer value"""
return self
def as_string(self) -> str:
return self._raw
def __add__(self, other):
result = super().__add__(other)
return self._new(result)
def __radd__(self, other):
result = super().__radd__(other)
if isinstance(other, Integer):
return self._new(result)
return result
def __sub__(self, other):
result = super().__sub__(other)
return self._new(result)
def __rsub__(self, other):
result = super().__rsub__(other)
if isinstance(other, Integer):
return self._new(result)
return result
def _new(self, result):
raw = str(result)
if self._sign:
sign = "+" if result >= 0 else "-"
raw = sign + raw
return Integer(result, self._trivia, raw)
def _getstate(self, protocol=3):
return int(self), self._trivia, self._raw
class Float(float, Item):
"""
A float literal.
"""
def __new__(cls, value: float, trivia: Trivia, raw: str) -> Integer:
return super().__new__(cls, value)
def __init__(self, _: float, trivia: Trivia, raw: str) -> None:
super().__init__(trivia)
self._raw = raw
self._sign = False
if re.match(r"^[+\-].+$", raw):
self._sign = True
@property
def discriminant(self) -> int:
return 3
@property
def value(self) -> float:
"""The wrapped float value"""
return self
def as_string(self) -> str:
return self._raw
def __add__(self, other):
result = super().__add__(other)
return self._new(result)
def __radd__(self, other):
result = super().__radd__(other)
if isinstance(other, Float):
return self._new(result)
return result
def __sub__(self, other):
result = super().__sub__(other)
return self._new(result)
def __rsub__(self, other):
result = super().__rsub__(other)
if isinstance(other, Float):
return self._new(result)
return result
def _new(self, result):
raw = str(result)
if self._sign:
sign = "+" if result >= 0 else "-"
raw = sign + raw
return Float(result, self._trivia, raw)
def _getstate(self, protocol=3):
return float(self), self._trivia, self._raw
class Bool(Item):
"""
A boolean literal.
"""
def __init__(self, t: int, trivia: Trivia) -> None:
super().__init__(trivia)
self._value = bool(t)
@property
def discriminant(self) -> int:
return 4
@property
def value(self) -> bool:
"""The wrapped boolean value"""
return self._value
def as_string(self) -> str:
return str(self._value).lower()
def _getstate(self, protocol=3):
return self._value, self._trivia
def __bool__(self):
return self._value
__nonzero__ = __bool__
def __eq__(self, other):
if not isinstance(other, bool):
return NotImplemented
return other == self._value
def __hash__(self):
return hash(self._value)
def __repr__(self):
return repr(self._value)
class DateTime(Item, datetime):
"""
A datetime literal.
"""
def __new__(
cls,
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int,
microsecond: int,
tzinfo: Optional[tzinfo],
trivia: Trivia,
raw: str,
**kwargs: Any,
) -> datetime:
return datetime.__new__(
cls,
year,
month,
day,
hour,
minute,
second,
microsecond,
tzinfo=tzinfo,
**kwargs,
)
def __init__(
self,
year: int,
month: int,
day: int,
hour: int,
minute: int,
second: int,
microsecond: int,
tzinfo: Optional[tzinfo],
trivia: Trivia,
raw: str,
) -> None:
super().__init__(trivia)
self._raw = raw
@property
def discriminant(self) -> int:
return 5
@property
def value(self) -> datetime:
return self
def as_string(self) -> str:
return self._raw
def __add__(self, other):
if PY38:
result = datetime(
self.year,
self.month,
self.day,
self.hour,
self.minute,
self.second,
self.microsecond,
self.tzinfo,
).__add__(other)
else:
result = super().__add__(other)
return self._new(result)
def __sub__(self, other):
if PY38:
result = datetime(
self.year,
self.month,
self.day,
self.hour,
self.minute,
self.second,
self.microsecond,
self.tzinfo,
).__sub__(other)
else:
result = super().__sub__(other)
if isinstance(result, datetime):
result = self._new(result)
return result
def _new(self, result):
raw = result.isoformat()
return DateTime(
result.year,
result.month,
result.day,
result.hour,
result.minute,
result.second,
result.microsecond,
result.tzinfo,
self._trivia,
raw,
)
def _getstate(self, protocol=3):
return (
self.year,
self.month,
self.day,
self.hour,
self.minute,
self.second,
self.microsecond,
self.tzinfo,
self._trivia,
self._raw,
)
class Date(Item, date):
"""
A date literal.
"""
def __new__(cls, year: int, month: int, day: int, *_: Any) -> date:
return date.__new__(cls, year, month, day)
def __init__(
self, year: int, month: int, day: int, trivia: Trivia, raw: str
) -> None:
super().__init__(trivia)
self._raw = raw
@property
def discriminant(self) -> int:
return 6
@property
def value(self) -> date:
return self
def as_string(self) -> str:
return self._raw
def __add__(self, other):
if PY38:
result = date(self.year, self.month, self.day).__add__(other)
else:
result = super().__add__(other)
return self._new(result)
def __sub__(self, other):
if PY38:
result = date(self.year, self.month, self.day).__sub__(other)
else:
result = super().__sub__(other)
if isinstance(result, date):
result = self._new(result)
return result
def _new(self, result):
raw = result.isoformat()
return Date(result.year, result.month, result.day, self._trivia, raw)
def _getstate(self, protocol=3):
return (self.year, self.month, self.day, self._trivia, self._raw)
class Time(Item, time):
"""
A time literal.
"""
def __new__(
cls,
hour: int,
minute: int,
second: int,
microsecond: int,
tzinfo: Optional[tzinfo],
*_: Any,
) -> time:
return time.__new__(cls, hour, minute, second, microsecond, tzinfo)
def __init__(
self,
hour: int,
minute: int,
second: int,
microsecond: int,
tzinfo: Optional[tzinfo],
trivia: Trivia,
raw: str,
) -> None:
super().__init__(trivia)
self._raw = raw
@property
def discriminant(self) -> int:
return 7
@property
def value(self) -> time:
return self
def as_string(self) -> str:
return self._raw
def _getstate(self, protocol: int = 3) -> tuple:
return (
self.hour,
self.minute,
self.second,
self.microsecond,
self.tzinfo,
self._trivia,
self._raw,
)
class Array(Item, _CustomList):
"""
An array literal
"""
def __init__(self, value: list, trivia: Trivia, multiline: bool = False) -> None:
super().__init__(trivia)
self._index_map: Dict[int, int] = {}
list.__init__(
self, [v.value for v in value if not isinstance(v, (Whitespace, Comment))]
)
self._value = value
self._multiline = multiline
self._reindex()
@property
def discriminant(self) -> int:
return 8
@property
def value(self) -> list:
return self
def multiline(self, multiline: bool) -> "Array":
"""Change the array to display in multiline or not.
:Example:
>>> a = item([1, 2, 3])
>>> print(a.as_string())
[1, 2, 3]
>>> print(a.multiline(True).as_string())
[
1,
2,
3,
]
"""
self._multiline = multiline
return self
def as_string(self) -> str:
if not self._multiline or not self._value:
return "[{}]".format("".join(v.as_string() for v in self._value))
s = "[\n" + self.trivia.indent + " " * 4
s += (",\n" + self.trivia.indent + " " * 4).join(
v.as_string() for v in self._value if not isinstance(v, Whitespace)
)
s += ",\n"
s += "]"
return s
def _reindex(self) -> None:
self._index_map.clear()
index = 0
for i, v in enumerate(self._value):
if isinstance(v, (Whitespace, Comment)):
continue
self._index_map[index] = i
index += 1
def add_line(
self,
*items: Any,
indent: str = " ",
comment: Optional[str] = None,
add_comma: bool = True,
newline: bool = True,
) -> None:
"""Add multiple items in a line to control the format precisely.
When add_comma is True, only accept actual values and
", " will be added between values automatically.
:Example:
>>> a = array()
>>> a.add_line(1, 2, 3)
>>> a.add_line(4, 5, 6)
>>> a.add_line(indent="")
>>> print(a.as_string())
[
1, 2, 3,
4, 5, 6,