-
Notifications
You must be signed in to change notification settings - Fork 2
/
viv.py
executable file
·3888 lines (3351 loc) · 127 KB
/
viv.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
#!/usr/bin/env python3
"""viv isn't venv!
viv -h
OR
__import__("viv").use("requests", "bs4")
"""
from __future__ import annotations
import hashlib
import itertools
import json
import logging
import os
import platform
import re
import shutil
import site
import subprocess
import sys
import tempfile
import threading
import venv
from argparse import (
SUPPRESS,
Action,
HelpFormatter,
Namespace,
RawDescriptionHelpFormatter,
_SubParsersAction,
)
from argparse import ArgumentParser as StdArgParser
from contextlib import contextmanager
from datetime import datetime
from enum import Enum
from logging.handlers import RotatingFileHandler
from pathlib import Path
from textwrap import dedent, fill
from time import sleep
from types import TracebackType
from typing import (
Any,
Dict,
Generator,
List,
NoReturn,
Optional,
Sequence,
Set,
TextIO,
Tuple,
Type,
Union,
)
__version__ = "2024.1004"
#### START VENDORED TOMLI ####
if sys.version_info >= (3, 11):
from tomllib import loads as toml_loads
else:
# MODIFIED FROM https://github.com/hukkin/tomli
# see below for original license
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
import string # noqa
from collections.abc import Iterable # noqa
from functools import lru_cache # noqa
from datetime import date, datetime, time, timedelta, timezone, tzinfo # noqa
from types import MappingProxyType # noqa
from typing import IO, Any, Callable, NamedTuple # noqa
v_tomli_ParseFloat = Callable[[str], Any]
Key = Tuple[str, ...]
v_tomli_Pos = int
v_tomli__TIME_RE_STR = (
"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\\.([0-9]{1,6})[0-9]*)?"
)
v_tomli_RE_NUMBER = re.compile(
"""
0
(?:
x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex
|
b[01](?:_?[01])* # bin
|
o[0-7](?:_?[0-7])* # oct
)
|
[+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part
(?P<floatpart>
(?:\\.[0-9](?:_?[0-9])*)? # optional fractional part
(?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part
)
""",
flags=re.VERBOSE,
)
v_tomli_RE_LOCALTIME = re.compile(v_tomli__TIME_RE_STR)
v_tomli_RE_DATETIME = re.compile(
f"""
([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
(?:
[Tt ]
{v_tomli__TIME_RE_STR}
(?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset
)?
""",
flags=re.VERBOSE,
)
def v_tomli_match_to_datetime(match: re.Match) -> datetime | date:
(
year_str,
month_str,
day_str,
hour_str,
minute_str,
sec_str,
micros_str,
zulu_time,
offset_sign_str,
offset_hour_str,
offset_minute_str,
) = match.groups()
year, month, day = int(year_str), int(month_str), int(day_str)
if hour_str is None:
return date(year, month, day)
hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
micros = int(micros_str.ljust(6, "0")) if micros_str else 0
if offset_sign_str:
tz: tzinfo | None = v_tomli_cached_tz(
offset_hour_str, offset_minute_str, offset_sign_str
)
elif zulu_time:
tz = timezone.utc
else:
tz = None
return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
@lru_cache(maxsize=None)
def v_tomli_cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
sign = 1 if sign_str == "+" else -1
return timezone(
timedelta(hours=sign * int(hour_str), minutes=sign * int(minute_str))
)
def v_tomli_match_to_localtime(match: re.Match) -> time:
hour_str, minute_str, sec_str, micros_str = match.groups()
micros = int(micros_str.ljust(6, "0")) if micros_str else 0
return time(int(hour_str), int(minute_str), int(sec_str), micros)
def v_tomli_match_to_number(
match: re.Match, parse_float: v_tomli_ParseFloat
) -> Any:
if match.group("floatpart"):
return parse_float(match.group())
return int(match.group(), 0)
v_tomli_ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
v_tomli_ILLEGAL_BASIC_STR_CHARS = v_tomli_ASCII_CTRL - frozenset("\t")
v_tomli_ILLEGAL_MULTILINE_BASIC_STR_CHARS = v_tomli_ASCII_CTRL - frozenset("\t\n")
v_tomli_ILLEGAL_LITERAL_STR_CHARS = v_tomli_ILLEGAL_BASIC_STR_CHARS
v_tomli_ILLEGAL_MULTILINE_LITERAL_STR_CHARS = (
v_tomli_ILLEGAL_MULTILINE_BASIC_STR_CHARS
)
v_tomli_ILLEGAL_COMMENT_CHARS = v_tomli_ILLEGAL_BASIC_STR_CHARS
v_tomli_TOML_WS = frozenset(" \t")
v_tomli_TOML_WS_AND_NEWLINE = v_tomli_TOML_WS | frozenset("\n")
v_tomli_BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_")
v_tomli_KEY_INITIAL_CHARS = v_tomli_BARE_KEY_CHARS | frozenset("\"'")
v_tomli_HEXDIGIT_CHARS = frozenset(string.hexdigits)
v_tomli_BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(
{
"\\b": "\x08",
"\\t": "\t",
"\\n": "\n",
"\\f": "\x0c",
"\\r": "\r",
'\\"': '"',
"\\\\": "\\",
}
)
class v_tomli_TOMLDecodeError(ValueError):
pass
def v_tomli_load(
__fp: IO[bytes], *, parse_float: v_tomli_ParseFloat = float
) -> dict[str, Any]:
b = __fp.read()
try:
s = b.decode()
except AttributeError:
raise TypeError(
"File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"
) from None
return v_tomli_loads(s, parse_float=parse_float)
def v_tomli_loads(
__s: str, *, parse_float: v_tomli_ParseFloat = float
) -> dict[str, Any]:
src = __s.replace("\r\n", "\n")
pos = 0
out = v_tomli_Output(v_tomli_NestedDict(), v_tomli_Flags())
header: Key = ()
parse_float = v_tomli_make_safe_parse_float(parse_float)
while True:
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
try:
char = src[pos]
except IndexError:
break
if char == "\n":
pos += 1
continue
if char in v_tomli_KEY_INITIAL_CHARS:
pos = v_tomli_key_value_rule(src, pos, out, header, parse_float)
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
elif char == "[":
try:
second_char: str | None = src[pos + 1]
except IndexError:
second_char = None
out.flags.finalize_pending()
if second_char == "[":
pos, header = v_tomli_create_list_rule(src, pos, out)
else:
pos, header = v_tomli_create_dict_rule(src, pos, out)
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
elif char != "#":
raise v_tomli_suffixed_err(src, pos, "Invalid statement")
pos = v_tomli_skip_comment(src, pos)
try:
char = src[pos]
except IndexError:
break
if char != "\n":
raise v_tomli_suffixed_err(
src, pos, "Expected newline or end of document after a statement"
)
pos += 1
return out.data.dict
class v_tomli_Flags:
FROZEN = 0
EXPLICIT_NEST = 1
def __init__(self) -> None:
self._flags: dict[str, dict] = {}
self._pending_flags: set[tuple[Key, int]] = set()
def add_pending(self, key: Key, flag: int) -> None:
self._pending_flags.add((key, flag))
def finalize_pending(self) -> None:
for key, flag in self._pending_flags:
self.set(key, flag, recursive=False)
self._pending_flags.clear()
def unset_all(self, key: Key) -> None:
cont = self._flags
for k in key[:-1]:
if k not in cont:
return
cont = cont[k]["nested"]
cont.pop(key[-1], None)
def set(self, key: Key, flag: int, *, recursive: bool) -> None:
cont = self._flags
key_parent, key_stem = key[:-1], key[-1]
for k in key_parent:
if k not in cont:
cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}}
cont = cont[k]["nested"]
if key_stem not in cont:
cont[key_stem] = {
"flags": set(),
"recursive_flags": set(),
"nested": {},
}
cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag)
def is_(self, key: Key, flag: int) -> bool:
if not key:
return False
cont = self._flags
for k in key[:-1]:
if k not in cont:
return False
inner_cont = cont[k]
if flag in inner_cont["recursive_flags"]:
return True
cont = inner_cont["nested"]
key_stem = key[-1]
if key_stem in cont:
cont = cont[key_stem]
return flag in cont["flags"] or flag in cont["recursive_flags"]
return False
class v_tomli_NestedDict:
def __init__(self) -> None:
self.dict: dict[str, Any] = {}
def get_or_create_nest(self, key: Key, *, access_lists: bool = True) -> dict:
cont: Any = self.dict
for k in key:
if k not in cont:
cont[k] = {}
cont = cont[k]
if access_lists and isinstance(cont, list):
cont = cont[-1]
if not isinstance(cont, dict):
raise KeyError("There is no nest behind this key")
return cont
def append_nest_to_list(self, key: Key) -> None:
cont = self.get_or_create_nest(key[:-1])
last_key = key[-1]
if last_key in cont:
list_ = cont[last_key]
if not isinstance(list_, list):
raise KeyError("An object other than list found behind this key")
list_.append({})
else:
cont[last_key] = [{}]
class v_tomli_Output(NamedTuple):
data: v_tomli_NestedDict
flags: v_tomli_Flags
def v_tomli_skip_chars(
src: str, pos: v_tomli_Pos, chars: Iterable[str]
) -> v_tomli_Pos:
try:
while src[pos] in chars:
pos += 1
except IndexError:
pass
return pos
def v_tomli_skip_until(
src: str,
pos: v_tomli_Pos,
expect: str,
*,
error_on: frozenset[str],
error_on_eof: bool,
) -> v_tomli_Pos:
try:
new_pos = src.index(expect, pos)
except ValueError:
new_pos = len(src)
if error_on_eof:
raise v_tomli_suffixed_err(
src, new_pos, f"Expected {expect!r}"
) from None
if not error_on.isdisjoint(src[pos:new_pos]):
while src[pos] not in error_on:
pos += 1
raise v_tomli_suffixed_err(
src, pos, f"Found invalid character {src[pos]!r}"
)
return new_pos
def v_tomli_skip_comment(src: str, pos: v_tomli_Pos) -> v_tomli_Pos:
try:
char: str | None = src[pos]
except IndexError:
char = None
if char == "#":
return v_tomli_skip_until(
src,
pos + 1,
"\n",
error_on=v_tomli_ILLEGAL_COMMENT_CHARS,
error_on_eof=False,
)
return pos
def v_tomli_skip_comments_and_array_ws(src: str, pos: v_tomli_Pos) -> v_tomli_Pos:
while True:
pos_before_skip = pos
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS_AND_NEWLINE)
pos = v_tomli_skip_comment(src, pos)
if pos == pos_before_skip:
return pos
def v_tomli_create_dict_rule(
src: str, pos: v_tomli_Pos, out: v_tomli_Output
) -> tuple[v_tomli_Pos, Key]:
pos += 1
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
pos, key = v_tomli_parse_key(src, pos)
if out.flags.is_(key, v_tomli_Flags.EXPLICIT_NEST) or out.flags.is_(
key, v_tomli_Flags.FROZEN
):
raise v_tomli_suffixed_err(src, pos, f"Cannot declare {key} twice")
out.flags.set(key, v_tomli_Flags.EXPLICIT_NEST, recursive=False)
try:
out.data.get_or_create_nest(key)
except KeyError:
raise v_tomli_suffixed_err(src, pos, "Cannot overwrite a value") from None
if not src.startswith("]", pos):
raise v_tomli_suffixed_err(
src, pos, "Expected ']' at the end of a table declaration"
)
return pos + 1, key
def v_tomli_create_list_rule(
src: str, pos: v_tomli_Pos, out: v_tomli_Output
) -> tuple[v_tomli_Pos, Key]:
pos += 2
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
pos, key = v_tomli_parse_key(src, pos)
if out.flags.is_(key, v_tomli_Flags.FROZEN):
raise v_tomli_suffixed_err(
src, pos, f"Cannot mutate immutable namespace {key}"
)
out.flags.unset_all(key)
out.flags.set(key, v_tomli_Flags.EXPLICIT_NEST, recursive=False)
try:
out.data.append_nest_to_list(key)
except KeyError:
raise v_tomli_suffixed_err(src, pos, "Cannot overwrite a value") from None
if not src.startswith("]]", pos):
raise v_tomli_suffixed_err(
src, pos, "Expected ']]' at the end of an array declaration"
)
return pos + 2, key
def v_tomli_key_value_rule(
src: str,
pos: v_tomli_Pos,
out: v_tomli_Output,
header: Key,
parse_float: v_tomli_ParseFloat,
) -> v_tomli_Pos:
pos, key, value = v_tomli_parse_key_value_pair(src, pos, parse_float)
key_parent, key_stem = key[:-1], key[-1]
abs_key_parent = header + key_parent
relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))
for cont_key in relative_path_cont_keys:
if out.flags.is_(cont_key, v_tomli_Flags.EXPLICIT_NEST):
raise v_tomli_suffixed_err(
src, pos, f"Cannot redefine namespace {cont_key}"
)
out.flags.add_pending(cont_key, v_tomli_Flags.EXPLICIT_NEST)
if out.flags.is_(abs_key_parent, v_tomli_Flags.FROZEN):
raise v_tomli_suffixed_err(
src, pos, f"Cannot mutate immutable namespace {abs_key_parent}"
)
try:
nest = out.data.get_or_create_nest(abs_key_parent)
except KeyError:
raise v_tomli_suffixed_err(src, pos, "Cannot overwrite a value") from None
if key_stem in nest:
raise v_tomli_suffixed_err(src, pos, "Cannot overwrite a value")
if isinstance(value, (dict, list)):
out.flags.set(header + key, v_tomli_Flags.FROZEN, recursive=True)
nest[key_stem] = value
return pos
def v_tomli_parse_key_value_pair(
src: str, pos: v_tomli_Pos, parse_float: v_tomli_ParseFloat
) -> tuple[v_tomli_Pos, Key, Any]:
pos, key = v_tomli_parse_key(src, pos)
try:
char: str | None = src[pos]
except IndexError:
char = None
if char != "=":
raise v_tomli_suffixed_err(
src, pos, "Expected '=' after a key in a key/value pair"
)
pos += 1
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
pos, value = v_tomli_parse_value(src, pos, parse_float)
return pos, key, value
def v_tomli_parse_key(src: str, pos: v_tomli_Pos) -> tuple[v_tomli_Pos, Key]:
pos, key_part = v_tomli_parse_key_part(src, pos)
key: Key = (key_part,)
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
while True:
try:
char: str | None = src[pos]
except IndexError:
char = None
if char != ".":
return pos, key
pos += 1
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
pos, key_part = v_tomli_parse_key_part(src, pos)
key += (key_part,)
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
def v_tomli_parse_key_part(src: str, pos: v_tomli_Pos) -> tuple[v_tomli_Pos, str]:
try:
char: str | None = src[pos]
except IndexError:
char = None
if char in v_tomli_BARE_KEY_CHARS:
start_pos = pos
pos = v_tomli_skip_chars(src, pos, v_tomli_BARE_KEY_CHARS)
return pos, src[start_pos:pos]
if char == "'":
return v_tomli_parse_literal_str(src, pos)
if char == '"':
return v_tomli_parse_one_line_basic_str(src, pos)
raise v_tomli_suffixed_err(src, pos, "Invalid initial character for a key part")
def v_tomli_parse_one_line_basic_str(
src: str, pos: v_tomli_Pos
) -> tuple[v_tomli_Pos, str]:
pos += 1
return v_tomli_parse_basic_str(src, pos, multiline=False)
def v_tomli_parse_array(
src: str, pos: v_tomli_Pos, parse_float: v_tomli_ParseFloat
) -> tuple[v_tomli_Pos, list]:
pos += 1
array: list = []
pos = v_tomli_skip_comments_and_array_ws(src, pos)
if src.startswith("]", pos):
return pos + 1, array
while True:
pos, val = v_tomli_parse_value(src, pos, parse_float)
array.append(val)
pos = v_tomli_skip_comments_and_array_ws(src, pos)
c = src[pos : pos + 1]
if c == "]":
return pos + 1, array
if c != ",":
raise v_tomli_suffixed_err(src, pos, "Unclosed array")
pos += 1
pos = v_tomli_skip_comments_and_array_ws(src, pos)
if src.startswith("]", pos):
return pos + 1, array
def v_tomli_parse_inline_table(
src: str, pos: v_tomli_Pos, parse_float: v_tomli_ParseFloat
) -> tuple[v_tomli_Pos, dict]:
pos += 1
nested_dict = v_tomli_NestedDict()
flags = v_tomli_Flags()
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
if src.startswith("}", pos):
return pos + 1, nested_dict.dict
while True:
pos, key, value = v_tomli_parse_key_value_pair(src, pos, parse_float)
key_parent, key_stem = key[:-1], key[-1]
if flags.is_(key, v_tomli_Flags.FROZEN):
raise v_tomli_suffixed_err(
src, pos, f"Cannot mutate immutable namespace {key}"
)
try:
nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
except KeyError:
raise v_tomli_suffixed_err(
src, pos, "Cannot overwrite a value"
) from None
if key_stem in nest:
raise v_tomli_suffixed_err(
src, pos, f"Duplicate inline table key {key_stem!r}"
)
nest[key_stem] = value
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
c = src[pos : pos + 1]
if c == "}":
return pos + 1, nested_dict.dict
if c != ",":
raise v_tomli_suffixed_err(src, pos, "Unclosed inline table")
if isinstance(value, (dict, list)):
flags.set(key, v_tomli_Flags.FROZEN, recursive=True)
pos += 1
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
def v_tomli_parse_basic_str_escape(
src: str, pos: v_tomli_Pos, *, multiline: bool = False
) -> tuple[v_tomli_Pos, str]:
escape_id = src[pos : pos + 2]
pos += 2
if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}:
if escape_id != "\\\n":
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS)
try:
char = src[pos]
except IndexError:
return pos, ""
if char != "\n":
raise v_tomli_suffixed_err(src, pos, "Unescaped '\\' in a string")
pos += 1
pos = v_tomli_skip_chars(src, pos, v_tomli_TOML_WS_AND_NEWLINE)
return pos, ""
if escape_id == "\\u":
return v_tomli_parse_hex_char(src, pos, 4)
if escape_id == "\\U":
return v_tomli_parse_hex_char(src, pos, 8)
try:
return pos, v_tomli_BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]
except KeyError:
raise v_tomli_suffixed_err(src, pos, "Unescaped '\\' in a string") from None
def v_tomli_parse_basic_str_escape_multiline(
src: str, pos: v_tomli_Pos
) -> tuple[v_tomli_Pos, str]:
return v_tomli_parse_basic_str_escape(src, pos, multiline=True)
def v_tomli_parse_hex_char(
src: str, pos: v_tomli_Pos, hex_len: int
) -> tuple[v_tomli_Pos, str]:
hex_str = src[pos : pos + hex_len]
if len(hex_str) != hex_len or not v_tomli_HEXDIGIT_CHARS.issuperset(hex_str):
raise v_tomli_suffixed_err(src, pos, "Invalid hex value")
pos += hex_len
hex_int = int(hex_str, 16)
if not v_tomli_is_unicode_scalar_value(hex_int):
raise v_tomli_suffixed_err(
src, pos, "Escaped character is not a Unicode scalar value"
)
return pos, chr(hex_int)
def v_tomli_parse_literal_str(
src: str, pos: v_tomli_Pos
) -> tuple[v_tomli_Pos, str]:
pos += 1
start_pos = pos
pos = v_tomli_skip_until(
src, pos, "'", error_on=v_tomli_ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True
)
return pos + 1, src[start_pos:pos]
def v_tomli_parse_multiline_str(
src: str, pos: v_tomli_Pos, *, literal: bool
) -> tuple[v_tomli_Pos, str]:
pos += 3
if src.startswith("\n", pos):
pos += 1
if literal:
delim = "'"
end_pos = v_tomli_skip_until(
src,
pos,
"'''",
error_on=v_tomli_ILLEGAL_MULTILINE_LITERAL_STR_CHARS,
error_on_eof=True,
)
result = src[pos:end_pos]
pos = end_pos + 3
else:
delim = '"'
pos, result = v_tomli_parse_basic_str(src, pos, multiline=True)
if not src.startswith(delim, pos):
return pos, result
pos += 1
if not src.startswith(delim, pos):
return pos, result + delim
pos += 1
return pos, result + delim * 2
def v_tomli_parse_basic_str(
src: str, pos: v_tomli_Pos, *, multiline: bool
) -> tuple[v_tomli_Pos, str]:
if multiline:
error_on = v_tomli_ILLEGAL_MULTILINE_BASIC_STR_CHARS
parse_escapes = v_tomli_parse_basic_str_escape_multiline
else:
error_on = v_tomli_ILLEGAL_BASIC_STR_CHARS
parse_escapes = v_tomli_parse_basic_str_escape
result = ""
start_pos = pos
while True:
try:
char = src[pos]
except IndexError:
raise v_tomli_suffixed_err(src, pos, "Unterminated string") from None
if char == '"':
if not multiline:
return pos + 1, result + src[start_pos:pos]
if src.startswith('"""', pos):
return pos + 3, result + src[start_pos:pos]
pos += 1
continue
if char == "\\":
result += src[start_pos:pos]
pos, parsed_escape = parse_escapes(src, pos)
result += parsed_escape
start_pos = pos
continue
if char in error_on:
raise v_tomli_suffixed_err(src, pos, f"Illegal character {char!r}")
pos += 1
def v_tomli_parse_value(
src: str, pos: v_tomli_Pos, parse_float: v_tomli_ParseFloat
) -> tuple[v_tomli_Pos, Any]:
try:
char: str | None = src[pos]
except IndexError:
char = None
if char == '"':
if src.startswith('"""', pos):
return v_tomli_parse_multiline_str(src, pos, literal=False)
return v_tomli_parse_one_line_basic_str(src, pos)
if char == "'":
if src.startswith("'''", pos):
return v_tomli_parse_multiline_str(src, pos, literal=True)
return v_tomli_parse_literal_str(src, pos)
if char == "t":
if src.startswith("true", pos):
return pos + 4, True
if char == "f":
if src.startswith("false", pos):
return pos + 5, False
if char == "[":
return v_tomli_parse_array(src, pos, parse_float)
if char == "{":
return v_tomli_parse_inline_table(src, pos, parse_float)
datetime_match = v_tomli_RE_DATETIME.match(src, pos)
if datetime_match:
try:
datetime_obj = v_tomli_match_to_datetime(datetime_match)
except ValueError as e:
raise v_tomli_suffixed_err(src, pos, "Invalid date or datetime") from e
return datetime_match.end(), datetime_obj
localtime_match = v_tomli_RE_LOCALTIME.match(src, pos)
if localtime_match:
return localtime_match.end(), v_tomli_match_to_localtime(localtime_match)
number_match = v_tomli_RE_NUMBER.match(src, pos)
if number_match:
return number_match.end(), v_tomli_match_to_number(
number_match, parse_float
)
first_three = src[pos : pos + 3]
if first_three in {"inf", "nan"}:
return pos + 3, parse_float(first_three)
first_four = src[pos : pos + 4]
if first_four in {"-inf", "+inf", "-nan", "+nan"}:
return pos + 4, parse_float(first_four)
raise v_tomli_suffixed_err(src, pos, "Invalid value")
def v_tomli_suffixed_err(
src: str, pos: v_tomli_Pos, msg: str
) -> v_tomli_TOMLDecodeError:
def coord_repr(src: str, pos: v_tomli_Pos) -> str:
if pos >= len(src):
return "end of document"
line = src.count("\n", 0, pos) + 1
if line == 1:
column = pos + 1
else:
column = pos - src.rindex("\n", 0, pos)
return f"line {line}, column {column}"
return v_tomli_TOMLDecodeError(f"{msg} (at {coord_repr(src, pos)})")
def v_tomli_is_unicode_scalar_value(codepoint: int) -> bool:
return 0 <= codepoint <= 55295 or 57344 <= codepoint <= 1114111
def v_tomli_make_safe_parse_float(
parse_float: v_tomli_ParseFloat,
) -> v_tomli_ParseFloat:
if parse_float is float:
return float
def safe_parse_float(float_str: str) -> Any:
float_value = parse_float(float_str)
if isinstance(float_value, (dict, list)):
raise ValueError("parse_float must not return dicts or lists")
return float_value
return safe_parse_float
toml_loads = v_tomli_loads
#### END VENDORED TOMLI ####
#### START VENDORED PACKAGING ####
# MODIFIED FROM https://github.com/pypa/packaging
# see repo for original licenses
# This software is made available under the terms of *either* of the licenses
# found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
# under the terms of *both* these licenses.
import abc # noqa
import itertools # noqa
import re # noqa
from typing import ( # noqa
Any,
Callable,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Set,
SupportsInt,
Tuple,
TypeVar,
Union,
)
class v_packaging_InfinityType:
def __repr__(self) -> str:
return "v_packaging_Infinity"
def __hash__(self) -> int:
return hash(repr(self))
def __lt__(self, other: object) -> bool:
return False
def __le__(self, other: object) -> bool:
return False
def __eq__(self, other: object) -> bool:
return isinstance(other, self.__class__)
def __gt__(self, other: object) -> bool:
return True
def __ge__(self, other: object) -> bool:
return True
def __neg__(self: object) -> "v_packaging_NegativeInfinityType":
return v_packaging_NegativeInfinity
v_packaging_Infinity = v_packaging_InfinityType()
class v_packaging_NegativeInfinityType:
def __repr__(self) -> str:
return "-Infinity"
def __hash__(self) -> int:
return hash(repr(self))
def __lt__(self, other: object) -> bool:
return True
def __le__(self, other: object) -> bool:
return True
def __eq__(self, other: object) -> bool:
return isinstance(other, self.__class__)
def __gt__(self, other: object) -> bool:
return False
def __ge__(self, other: object) -> bool:
return False
def __neg__(self: object) -> v_packaging_InfinityType:
return v_packaging_Infinity
v_packaging_NegativeInfinity = v_packaging_NegativeInfinityType()
v_packaging_LocalType = Tuple[Union[int, str], ...]
v_packaging_CmpPrePostDevType = Union[
v_packaging_InfinityType, v_packaging_NegativeInfinityType, Tuple[str, int]
]
v_packaging_CmpLocalType = Union[
v_packaging_NegativeInfinityType,
Tuple[
Union[
Tuple[int, str], Tuple[v_packaging_NegativeInfinityType, Union[int, str]]
],
...,
],
]
v_packaging_CmpKey = Tuple[
int,
Tuple[int, ...],
v_packaging_CmpPrePostDevType,
v_packaging_CmpPrePostDevType,
v_packaging_CmpPrePostDevType,
v_packaging_CmpLocalType,
]
v_packaging_VersionComparisonMethod = Callable[
[v_packaging_CmpKey, v_packaging_CmpKey], bool
]
class v_packaging__Version(NamedTuple):
epoch: int
release: Tuple[int, ...]
dev: Optional[Tuple[str, int]]
pre: Optional[Tuple[str, int]]
post: Optional[Tuple[str, int]]
local: Optional[v_packaging_LocalType]
def v_packaging_parse(version: str) -> "v_packaging_Version":
return v_packaging_Version(version)
class v_packaging_InvalidVersion(ValueError):
pass
class v_packaging__BaseVersion:
_key: Tuple[Any, ...]
def __hash__(self) -> int:
return hash(self._key)
def __lt__(self, other: "v_packaging__BaseVersion") -> bool:
if not isinstance(other, v_packaging__BaseVersion):
return NotImplemented
return self._key < other._key
def __le__(self, other: "v_packaging__BaseVersion") -> bool:
if not isinstance(other, v_packaging__BaseVersion):
return NotImplemented
return self._key <= other._key
def __eq__(self, other: object) -> bool:
if not isinstance(other, v_packaging__BaseVersion):
return NotImplemented
return self._key == other._key
def __ge__(self, other: "v_packaging__BaseVersion") -> bool:
if not isinstance(other, v_packaging__BaseVersion):
return NotImplemented
return self._key >= other._key
def __gt__(self, other: "v_packaging__BaseVersion") -> bool:
if not isinstance(other, v_packaging__BaseVersion):
return NotImplemented
return self._key > other._key
def __ne__(self, other: object) -> bool:
if not isinstance(other, v_packaging__BaseVersion):
return NotImplemented
return self._key != other._key
v_packaging__VERSION_PATTERN = """
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\\.]?
(?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)
[-_\\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\\.]?
(?P<post_l>post|rev|r)
[-_\\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\\.]?
(?P<dev_l>dev)
[-_\\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\\+(?P<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))? # local version
"""
v_packaging_VERSION_PATTERN = v_packaging__VERSION_PATTERN
class v_packaging_Version(v_packaging__BaseVersion):
_regex = re.compile(
"^\\s*" + v_packaging_VERSION_PATTERN + "\\s*$", re.VERBOSE | re.IGNORECASE
)
_key: v_packaging_CmpKey
def __init__(self, version: str) -> None:
match = self._regex.search(version)
if not match:
raise v_packaging_InvalidVersion(f"Invalid version: '{version}'")
self._version = v_packaging__Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=v_packaging__parse_letter_version(
match.group("pre_l"), match.group("pre_n")
),
post=v_packaging__parse_letter_version(
match.group("post_l"), match.group("post_n1") or match.group("post_n2")
),
dev=v_packaging__parse_letter_version(
match.group("dev_l"), match.group("dev_n")