-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlex.py
More file actions
2697 lines (2420 loc) · 86.6 KB
/
Copy pathlex.py
File metadata and controls
2697 lines (2420 loc) · 86.6 KB
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/python
r'''
Lexical analysis functions, tokenisers, transcribers:
an arbitrary assortment of lexical and tokenisation functions useful
for writing recursive descent parsers, of which I have several.
There are also some transcription functions for producing text
from various objects, such as `hexify` and `unctrl`.
Generally the `get_*` functions accept a source string and an offset
(usually optional, default `0`) and return a token and the new offset,
raising `ValueError` on failed tokenisation.
'''
# pylint: disable=too-many-lines
import binascii
from collections.abc import Mapping as MappingABC
from dataclasses import dataclass
from datetime import date, datetime
from functools import partial
from json import JSONEncoder
import os
from pathlib import Path, PurePosixPath, PureWindowsPath
from pprint import PrettyPrinter
import re
from string import (
ascii_letters,
ascii_uppercase,
digits,
printable,
whitespace,
Formatter,
)
import sys
from textwrap import dedent
from typing import Any, Callable, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
from dateutil.tz import tzlocal
from icontract import require
from typeguard import typechecked
from cs.ascii_art import box_char, HORIZ, LARGE_CIRCLE
from cs.dateutils import unixtime2datetime, UTC
from cs.deco import attr, fmtdoc, decorator, OBSOLETE, Promotable
from cs.gimmicks import warning
from cs.obj import public_subclasses
from cs.pfx import Pfx, pfx_call, pfx_method
from cs.py.func import funcname
from cs.seq import common_prefix_length, common_suffix_length, with_neighbours
__version__ = '20260526-post'
DISTINFO = {
'keywords': ["python3"],
'classifiers': [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Topic :: Text Processing",
],
'install_requires': [
'cs.ascii_art>=LARGE_CIRCLE',
'cs.dateutils',
'cs.deco',
'cs.gimmicks',
'cs.obj',
'cs.pfx',
'cs.py.func',
'cs.seq>=with_neighbours',
'python-dateutil',
'icontract',
'typeguard',
],
}
unhexify = binascii.unhexlify # pylint: disable=c-extension-no-member
hexify = binascii.hexlify # pylint: disable=c-extension-no-member
if sys.hexversion >= 0x030000:
_hexify = hexify
# pylint: disable=function-redefined
def hexify(bs: bytes) -> str:
''' A flavour of `binascii.hexlify` returning a `str`.
'''
return _hexify(bs).decode()
ord_space = ord(' ')
# pylint: disable=too-many-branches,redefined-outer-name
def unctrl(s: str, tabsize: int = 8) -> str:
''' Return the string `s` with `TAB`s expanded and control characters
replaced with printable representations.
'''
if tabsize < 1:
raise ValueError("tabsize(%r) < 1" % (tabsize,))
s2 = ''
sofar = 0
for i, ch in enumerate(s):
ch2 = None
if ch == '\t':
if sofar < i:
s2 += s[sofar:i]
sofar = i
ch2 = ' ' * (tabsize - (len(s2) % tabsize))
elif ch == '\f':
ch2 = '\\f'
elif ch == '\n':
ch2 = '\\n'
elif ch == '\r':
ch2 = '\\r'
elif ch == '\v':
ch2 = '\\v'
else:
o = ord(ch)
if o < ord_space or printable.find(ch) == -1:
if o >= 256:
ch2 = "\\u%04x" % o
else:
ch2 = "\\%03o" % o
if ch2 is not None:
if sofar < i:
s2 += s[sofar:i]
s2 += ch2
sofar = i + 1
if sofar < len(s):
s2 += s[sofar:]
return s2.expandtabs(tabsize)
def lc_(value: str) -> str:
''' Return `value.lower()`
with `'-'` translated into `'_'` and `' '` translated into `'-'`.
I use this to construct lowercase filenames containing a
readable transcription of a title string.
See also `titleify_lc()`, an imperfect reversal of this.
'''
return value.lower().replace('-', '_').replace(' ', '-')
def titleify_lc(value_lc: str) -> str:
''' Translate `'-'` into `' '` and `'_'` translated into `'-'`,
then titlecase.
See also `lc_()`, which this reverses imperfectly.
'''
return value_lc.replace('-', ' ').replace('_', '-').title()
def tabpadding(padlen: int, tabsize: int = 8, offset: int = 0) -> str:
''' Compute some spaces to use a tab padding at an offfset.
'''
pad = ''
nexttab = tabsize - offset % tabsize
while nexttab <= padlen:
pad += '\t'
padlen -= nexttab
nexttab = tabsize
if padlen > 0:
pad += "%*s" % (padlen, ' ')
return pad
def typed_str(
obj: Any,
*,
use_cls: bool = False,
use_repr: bool = False,
max_length: Optional[int] = 32,
) -> str:
''' Return "type(obj).__name__:str(obj)" for some object `obj`.
This is available as both `typed_str` and `s`.
Parameters:
* `use_cls`: default `False`;
if true, use `str(type(obj))` instead of `type(obj).__name__`
* `use_repr`: default `False`;
if true, use `repr(obj)` instead of `str(obj)`
I use this a lot when debugging. Example:
from cs.lex import typed_str as s
......
X("foo = %s", s(foo))
'''
# pylint: disable=redefined-outer-name
o_s = cropped_repr(obj) if use_repr else str(obj)
if max_length is not None:
o_s = cropped(o_s, max_length)
s = "%s:%s" % (type(obj) if use_cls else type(obj).__name__, o_s)
return s
# convenience alias
s = typed_str
def typed_repr(
obj: Any,
max_length: Optional[int] = None,
*,
use_cls: bool = False
) -> str:
''' Like `typed_str` but using `repr` instead of `str`.
This is available as both `typed_repr` and `r`.
'''
return typed_str(obj, use_cls=use_cls, max_length=max_length, use_repr=True)
# convenience alias
r = typed_repr
def strlist(ary: Iterable, sep: str = ", ") -> str:
''' Convert an iterable to strings and join with `sep` (default `', '`).
'''
return sep.join([str(a) for a in ary])
# pylint: disable=redefined-outer-name
def htmlify(s: str, nbsp: bool = False) -> str:
''' Convert a string for safe transcription in HTML.
Parameters:
* `s`: the string
* `nbsp`: replaces spaces with `" "` to prevent word folding,
default `False`.
'''
s = s.replace("&", "&")
s = s.replace("<", "<")
s = s.replace(">", ">")
if nbsp:
s = s.replace(" ", " ")
return s
def htmlquote(s: str) -> str:
''' Quote a string for use in HTML.
'''
s = htmlify(s)
s = s.replace('"', "&dquot;")
return '"' + s + '"'
def jsquote(s: str) -> str:
''' Quote a string for use in JavaScript.
'''
s = s.replace('"', "&dquot;")
return '"' + s + '"'
def phpquote(s: str) -> str:
''' Quote a string for use in PHP code.
'''
return "'" + s.replace('\\', '\\\\').replace("'", "\\'") + "'"
# characters that may appear in text sections of a texthexify result
# Notable exclusions:
# \ - to avoid double in slosh escaped presentation
# % - likewise, for percent escaped presentation
# [ ] - the delimiters of course
# { } - used for JSON data and some other markup
# / - path separator
#
_texthexify_white_chars = ascii_letters + digits + '_-+.,'
def texthexify(
bs: bytes,
shiftin: str = '[',
shiftout: str = ']',
whitelist: Optional[Union[str, bytes]] = None
) -> str:
''' Transcribe the bytes `bs` to text using compact text runs for
some common text values.
This can be reversed with the `untexthexify` function.
This is an ad doc format devised to be compact but also to
expose "text" embedded within to the eye. The original use
case was transcribing a binary directory entry format, where
the filename parts would be somewhat visible in the transcription.
The output is a string of hexadecimal digits for the encoded
bytes except for runs of values from the whitelist, which are
enclosed in the shiftin and shiftout markers and transcribed
as is. The default whitelist is values of the ASCII letters,
the decimal digits and the punctuation characters '_-+.,'.
The default shiftin and shiftout markers are '[' and ']'.
String objects converted with either `hexify` and `texthexify`
output strings may be freely concatenated and decoded with
`untexthexify`.
Example:
>>> texthexify(b'&^%&^%abcdefghi)(*)(*')
'265e25265e25[abcdefghi]29282a29282a'
Parameters:
* `bs`: the bytes to transcribe
* `shiftin`: Optional. The marker string used to indicate a shift to
direct textual transcription of the bytes, default: `'['`.
* `shiftout`: Optional. The marker string used to indicate a
shift from text mode back into hexadecimal transcription,
default `']'`.
* `whitelist`: an optional bytes or string object indicating byte
values which may be represented directly in text;
the default value is the ASCII letters, the decimal digits
and the punctuation characters `'_-+.,'`.
'''
if whitelist is None:
whitelist = _texthexify_white_chars
if isinstance(whitelist, str):
whitelist: bytes = bytes(ord(ch) for ch in whitelist)
inout_len = len(shiftin) + len(shiftout)
chunks = []
offset = 0
offset0 = offset
inwhite = False
while offset < len(bs):
b = bs[offset]
if inwhite:
if b not in whitelist:
inwhite = False
if offset - offset0 > inout_len:
# gather up whitelist span if long enough to bother
chunk = (
shiftin +
''.join(chr(bs[off])
for off in range(offset0, offset)) + shiftout
)
else:
# transcribe as hex anyway - too short
chunk = hexify(bs[offset0:offset])
chunks.append(chunk)
offset0 = offset
elif b in whitelist:
inwhite = True
chunk = hexify(bs[offset0:offset])
chunks.append(chunk)
offset0 = offset
offset += 1
if offset > offset0:
if inwhite and offset - offset0 > inout_len:
chunk = (
shiftin + ''.join(chr(bs[off])
for off in range(offset0, offset)) + shiftout
)
else:
chunk = hexify(bs[offset0:offset])
chunks.append(chunk)
return ''.join(chunks)
# pylint: disable=redefined-outer-name
def untexthexify(s: str, shiftin: str = '[', shiftout: str = ']') -> bytes:
''' Decode a textual representation of binary data into binary data.
This is the reverse of the `texthexify` function.
Outside of the `shiftin`/`shiftout` markers the binary data
are represented as hexadecimal. Within the markers the bytes
have the values of the ordinals of the characters.
Example:
>>> untexthexify('265e25265e25[abcdefghi]29282a29282a')
b'&^%&^%abcdefghi)(*)(*'
Parameters:
* `s`: the string containing the text representation.
* `shiftin`: Optional. The marker string commencing a sequence
of direct text transcription, default `'['`.
* `shiftout`: Optional. The marker string ending a sequence
of direct text transcription, default `']'`.
'''
chunks = []
while s:
hexlen = s.find(shiftin)
if hexlen < 0:
break
if hexlen > 0:
hextext = s[:hexlen]
if hexlen % 2 != 0:
raise ValueError("uneven hex sequence %r" % (hextext,))
chunks.append(unhexify(s[:hexlen]))
s = s[hexlen + len(shiftin):]
textlen = s.find(shiftout)
if textlen < 0:
raise ValueError("missing shift out marker %r" % (shiftout,))
if sys.hexversion < 0x03000000:
chunks.append(s[:textlen])
else:
chunks.append(bytes(ord(c) for c in s[:textlen]))
s = s[textlen + len(shiftout):]
if s:
if len(s) % 2 != 0:
raise ValueError("uneven hex sequence %r" % (s,))
chunks.append(unhexify(s))
return b''.join(chunks)
# pylint: disable=redefined-outer-name
def get_chars(s: str, offset: int, gochars: str) -> Tuple[str, int]:
''' Scan the string `s` for characters in `gochars` starting at `offset`.
Return `(match,new_offset)`.
`gochars` may also be a callable, in which case a character
`ch` is accepted if `gochars(ch)` is true.
'''
ooffset = offset
if callable(gochars):
while offset < len(s) and gochars(s[offset]):
offset += 1
else:
while offset < len(s) and s[offset] in gochars:
offset += 1
return s[ooffset:offset], offset
# pylint: disable=redefined-outer-name
def get_white(s: str, offset: int = 0) -> Tuple[str, int]:
''' Scan the string `s` for characters in `string.whitespace`
starting at `offset` (default `0`).
Return `(match,new_offset)`.
'''
return get_chars(s, offset, whitespace)
# pylint: disable=redefined-outer-name
def skipwhite(s: str, offset: int = 0) -> int:
''' Convenience routine for skipping past whitespace;
returns the offset of the next nonwhitespace character.
'''
_, offset = get_white(s, offset=offset)
return offset
def indent(paragraph: str, line_indent: str = " ") -> str:
''' Return the `paragraph` indented by `line_indent` (default `" "`).
'''
return "\n".join(
line and line_indent + line for line in paragraph.split("\n")
)
# TODO: add an optional detab=n parameter?
def stripped_dedent(
s: str, post_indent: str = '', sub_indent: str = ''
) -> str:
''' Slightly smarter dedent which ignores a string's opening indent.
Algorithm:
strip the supplied string `s`, pull off the leading line,
dedent the rest, put back the leading line.
This is a lot like the `inspect.cleandoc()` function.
This supports my preferred docstring layout, where the opening
line of text is on the same line as the opening quote.
The optional `post_indent` parameter may be used to indent
the dedented text before return.
The optional `sub_indent` parameter may be used to indent
the second and following lines if the dedented text before return.
Examples:
>>> def func(s):
... """ Slightly smarter dedent which ignores a string's opening indent.
... Strip the supplied string `s`. Pull off the leading line.
... Dedent the rest. Put back the leading line.
... """
... pass
...
>>> from cs.lex import stripped_dedent
>>> print(stripped_dedent(func.__doc__))
Slightly smarter dedent which ignores a string's opening indent.
Strip the supplied string `s`. Pull off the leading line.
Dedent the rest. Put back the leading line.
>>> print(stripped_dedent(func.__doc__, sub_indent=' '))
Slightly smarter dedent which ignores a string's opening indent.
Strip the supplied string `s`. Pull off the leading line.
Dedent the rest. Put back the leading line.
>>> print(stripped_dedent(func.__doc__, post_indent=' '))
Slightly smarter dedent which ignores a string's opening indent.
Strip the supplied string `s`. Pull off the leading line.
Dedent the rest. Put back the leading line.
>>> print(stripped_dedent(func.__doc__, post_indent=' ', sub_indent='| '))
Slightly smarter dedent which ignores a string's opening indent.
| Strip the supplied string `s`. Pull off the leading line.
| Dedent the rest. Put back the leading line.
'''
s = s.strip()
lines = s.split('\n')
if not lines:
return ''
line1 = lines.pop(0)
if not lines:
return indent(line1, post_indent)
adjusted = indent(dedent('\n'.join(lines)), sub_indent)
return indent(line1 + '\n' + adjusted, post_indent)
@require(lambda offset: offset >= 0)
def get_prefix_n(
s: str,
prefix: str,
n: Optional[int] = None,
*,
offset: int = 0,
) -> Tuple[Union[str, None], Union[int, None], int]:
''' Strip a leading `prefix` and numeric value `n` from the string `s`
starting at `offset` (default `0`).
Return the matched prefix, the numeric value and the new offset.
Returns `(None,None,offset)` on no match.
Parameters:
* `s`: the string to parse
* `prefix`: the prefix string which must appear at `offset`
or an object with a `match(str,offset)` method
such as an `re.Pattern` regexp instance
* `n`: optional integer value;
if omitted any value will be accepted, otherwise the numeric
part must match `n`
If `prefix` is a `str`, the "matched prefix" return value is `prefix`.
Otherwise the "matched prefix" return value is the result of
the `prefix.match(s,offset)` call. The result must also support
a `.end()` method returning the offset in `s` beyond the match,
used to locate the following numeric portion.
Examples:
>>> import re
>>> get_prefix_n('s03e01--', 's')
('s', 3, 3)
>>> get_prefix_n('s03e01--', 's', 3)
('s', 3, 3)
>>> get_prefix_n('s03e01--', 's', 4)
(None, None, 0)
>>> get_prefix_n('s03e01--', re.compile('[es]',re.I))
(<re.Match object; span=(0, 1), match='s'>, 3, 3)
>>> get_prefix_n('s03e01--', re.compile('[es]',re.I), offset=3)
(<re.Match object; span=(3, 4), match='e'>, 1, 6)
'''
no_match = None, None, offset
if isinstance(prefix, str):
if s.startswith(prefix, offset):
matched = prefix
offset += len(prefix)
else:
# no match, return unchanged
return no_match
else:
matched = pfx_call(prefix.match, s, offset)
if not matched:
return no_match
offset = matched.end()
if offset >= len(s) or not s[offset].isdigit():
return no_match
gn, offset = get_decimal_value(s, offset)
if n is not None and gn != n:
return no_match
return matched, gn, offset
NUMERAL_NAMES = {
'en': {
# all the single word numbers
'zero': 0,
'nought': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
},
}
def get_suffix_part(
s: str,
*,
keywords: Iterable[str] = ('part',),
numeral_map: Optional[Mapping[str, int]] = None,
) -> Union[Tuple[str, int], Tuple[None, None]]:
''' Strip a trailing "part N" suffix from the string `s`.
Return the matched suffix and the number part number.
Retrn `(None,None)` on no match.
Parameters:
* `s`: the string
* `keywords`: an iterable of `str` to match, or a single `str`;
default `'part'`
* `numeral_map`: an optional mapping of numeral names to numeric values;
default `NUMERAL_NAMES['en']`, the English numerals
Exanmple:
>>> get_suffix_part('s09e10 - A New World: Part One')
(': Part One', 1)
'''
if isinstance(keywords, str):
keywords = (keywords,)
if numeral_map is None:
numeral_map = NUMERAL_NAMES['en']
regexp_s = ''.join(
(
r'\W+(',
r'|'.join(keywords),
r')\s+(?P<numeral>\d+|',
r'|'.join(numeral_map.keys()),
r')\s*$',
)
)
regexp = re.compile(regexp_s, re.I)
m = regexp.search(s)
if not m:
return None, None
numeral = m.group('numeral')
try:
part_n = int(numeral)
except ValueError:
try:
part_n = numeral_map[numeral]
except KeyError:
try:
part_n = numeral_map[numeral.lower()]
except KeyError:
return None, None
return m.group(0), part_n
# pylint: disable=redefined-outer-name
def get_nonwhite(s: str, offset: int = 0) -> Tuple[str, int]:
''' Scan the string `s` for characters not in `string.whitespace`
starting at `offset` (default `0`).
Return `(match,new_offset)`.
'''
return get_other_chars(s, offset=offset, stopchars=whitespace)
# pylint: disable=redefined-outer-name
def get_decimal(s: str, offset: int = 0) -> Tuple[str, int]:
''' Scan the string `s` for decimal characters starting at `offset` (default `0`).
Return `(dec_string,new_offset)`.
'''
return get_chars(s, offset, digits)
# pylint: disable=redefined-outer-name
def get_decimal_value(s: str, offset: int = 0) -> Tuple[int, int]:
''' Scan the string `s` for a decimal value starting at `offset` (default `0`).
Return `(value,new_offset)`.
'''
value_s, offset = get_decimal(s, offset)
if not value_s:
raise ValueError("expected decimal value")
return int(value_s), offset
# pylint: disable=redefined-outer-name
def get_hexadecimal(s: str, offset: int = 0) -> Tuple[str, int]:
''' Scan the string `s` for hexadecimal characters starting at `offset` (default `0`).
Return `(hex_string,new_offset)`.
'''
return get_chars(s, offset, '0123456789abcdefABCDEF')
# pylint: disable=redefined-outer-name
def get_hexadecimal_value(s: str, offset: int = 0) -> Tuple[int, int]:
''' Scan the string `s` for a hexadecimal value starting at `offset` (default `0`).
Return `(value,new_offset)`.
'''
value_s, offset = get_hexadecimal(s, offset)
if not value_s:
raise ValueError("expected hexadecimal value")
return int('0x' + value_s), offset
# pylint: disable=redefined-outer-name
def get_decimal_or_float_value(s: str,
offset: int = 0
) -> Tuple[Union[int, float], int]:
''' Fetch a decimal or basic float (nnn.nnn) value
from the str `s` at `offset` (default `0`).
Return `(value,new_offset)`.
'''
int_part, offset = get_decimal(s, offset)
if not int_part:
raise ValueError("expected decimal or basic float value")
if offset == len(s) or s[offset] != '.':
return int(int_part), offset
sub_part, offset = get_decimal(s, offset + 1)
return float('.'.join((int_part, sub_part))), offset
def get_identifier(
s: str,
offset: int = 0,
*,
alpha: str = ascii_letters,
number: str = digits,
extras: str = '_',
) -> Tuple[str, int]:
''' Scan the string `s` for an identifier (by default an ASCII
letter or underscore followed by letters, digits or underscores)
starting at `offset` (default 0).
Return `(match,new_offset)`.
*Note*: the empty string and an unchanged offset will be returned if
there is no leading letter/underscore.
Parameters:
* `s`: the string to scan
* `offset`: the starting offset, default `0`.
* `alpha`: the characters considered alphabetic,
default `string.ascii_letters`.
* `number`: the characters considered numeric,
default `string.digits`.
* `extras`: extra characters considered part of an identifier,
default `'_'`.
'''
if offset >= len(s):
return '', offset
ch = s[offset]
if ch not in alpha and ch not in extras:
return '', offset
idtail, offset = get_chars(s, offset + 1, alpha + number + extras)
return ch + idtail, offset
# pylint: disable=redefined-outer-name
def is_identifier(s: str, offset: int = 0, **kw) -> bool:
''' Test if the string `s` is an identifier
from position `offset` (default `0`) onward.
'''
s2, offset2 = get_identifier(s, offset=offset, **kw)
return len(s2) > 0 and offset2 == len(s)
# pylint: disable=redefined-outer-name
def get_uc_identifier(
s: str,
offset: int = 0,
number: str = digits,
extras: str = '_',
) -> Tuple[str, int]:
''' Scan the string `s` for an identifier as for `get_identifier`,
but require the letters to be uppercase.
'''
return get_identifier(
s, offset=offset, alpha=ascii_uppercase, number=number, extras=extras
)
def is_uc_identifier(s: str, offset: int = 0, **kw) -> bool:
''' Test if the string `s` is an uppercase identifier
from position `offset` (default `0`) onward.
'''
s2, offset2 = get_uc_identifier(s, offset=offset, **kw)
return len(s2) > 0 and offset2 == len(s)
# pylint: disable=redefined-outer-name
def get_dotted_identifier(s: str, offset: int = 0, **kw) -> Tuple[str, int]:
''' Scan the string `s` for a dotted identifier (by default an
ASCII letter or underscore followed by letters, digits or
underscores) with optional trailing dot and another dotted
identifier, starting at `offset` (default `0`).
Return `(match,new_offset)`.
Note: the empty string and an unchanged offset will be returned if
there is no leading letter/underscore.
Keyword arguments are passed to `get_identifier`
(used for each component of the dotted identifier).
'''
offset0 = offset
_, offset = get_identifier(s, offset=offset, **kw)
if _:
while offset < len(s) - 1 and s[offset] == '.':
_, offset2 = get_identifier(s, offset=offset + 1, **kw)
if not _:
break
offset = offset2
return s[offset0:offset], offset
# pylint: disable=redefined-outer-name
def is_dotted_identifier(s: str, offset: int = 0, **kw) -> bool:
''' Test if the string `s` is an identifier from position `offset` onward.
'''
s2, offset2 = get_dotted_identifier(s, offset=offset, **kw)
return len(s2) > 0 and offset2 == len(s)
# pylint: disable=redefined-outer-name
def get_other_chars(s: str,
offset: int = 0,
stopchars: Optional[str] = None) -> Tuple[str, int]:
''' Scan the string `s` for characters not in `stopchars` starting
at `offset` (default `0`).
Return `(match,new_offset)`.
'''
ooffset = offset
while offset < len(s) and s[offset] not in stopchars:
offset += 1
return s[ooffset:offset], offset
# default character map for \c notation
SLOSH_CHARMAP = {
'a': '\a',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
}
def slosh_mapper(c, charmap=None):
''' Return a string to replace backslash-`c`, or `None`.
'''
if charmap is None:
charmap = SLOSH_CHARMAP
return charmap.get(c)
# pylint: disable=too-many-arguments,too-many-locals,too-many-branches
# pylint: disable=too-many-statements,too-many-arguments
def get_sloshed_text(
s, delim, offset=0, slosh='\\', mapper=slosh_mapper, specials=None
):
''' Collect slosh escaped text from the string `s` from position
`offset` (default `0`) and return the decoded unicode string and
the offset of the completed parse.
Parameters:
* `delim`: end of string delimiter, such as a single or double quote.
* `offset`: starting offset within `s`, default `0`.
* `slosh`: escape character, default a slosh ('\\').
* `mapper`: a mapping function which accepts a single character
and returns a replacement string or `None`; this is used the
replace things such as '\\t' or '\\n'. The default is the
`slosh_mapper` function, whose default mapping is `SLOSH_CHARMAP`.
* `specials`: a mapping of other special character sequences and parse
functions for gathering them up. When one of the special
character sequences is found in the string, the parse
function is called to parse at that point.
The parse functions accept
`s` and the offset of the special character. They return
the decoded string and the offset past the parse.
The escape character `slosh` introduces an encoding of some
replacement text whose value depends on the following character.
If the following character is:
* the escape character `slosh`, insert the escape character.
* the string delimiter `delim`, insert the delimiter.
* the character 'x', insert the character with code from the following
2 hexadecimal digits.
* the character 'u', insert the character with code from the following
4 hexadecimal digits.
* the character 'U', insert the character with code from the following
8 hexadecimal digits.
* a character from the keys of `mapper`
'''
if specials is not None:
# gather up starting character of special keys and a list of
# keys in reverse order of length
special_starts = set()
special_seqs = []
for special in specials.keys():
if not special:
raise ValueError(
'empty strings may not be used as keys for specials: %r' %
(specials,)
)
special_starts.add(special[0])
special_seqs.append(special)
special_starts = ''.join(special_starts)
special_seqs = sorted(special_seqs, key=lambda s: -len(s))
chunks = []
slen = len(s)
while True:
if offset >= slen:
if delim is not None:
raise ValueError("missing delimiter %r at offset %d" % (delim, offset))
break
offset0 = offset
c = s[offset]
offset += 1
if delim is not None and c == delim:
# delimiter; end text
break
if c == slosh:
# \something
if offset >= slen:
raise ValueError('incomplete slosh escape at offset %d' % (offset0,))
offset1 = offset
c = s[offset]
offset += 1
if c == slosh or (delim is not None and c == delim):
chunks.append(c)
continue
if c == 'x':
# \xhh
if slen - offset < 2:
raise ValueError(
'short hexcode for %sxhh at offset %d' % (slosh, offset0)
)
hh = s[offset:offset + 2]
offset += 2
chunks.append(chr(int(hh, 16)))
continue
if c == 'u':
# \uhhhh
if slen - offset < 4:
raise ValueError(
'short hexcode for %suhhhh at offset %d' % (slosh, offset0)
)
hh = s[offset:offset + 4]
offset += 4
chunks.append(chr(int(hh, 16)))
continue
if c == 'U':
# \Uhhhhhhhh
if slen - offset < 8:
raise ValueError(
'short hexcode for %sUhhhhhhhh at offset %d' % (slosh, offset0)
)
hh = s[offset:offset + 8]
offset += 8
chunks.append(chr(int(hh, 16)))
continue
chunk = mapper(c)
if chunk is not None:
# supplied \X mapping
chunks.append(chunk)
continue
# check for escaped special syntax
if specials is not None and c in special_starts:
# test sequence prefixes from longest to shortest
chunk = None
for seq in special_seqs:
if s.startswith(seq, offset1):
# special sequence
chunk = c
break
if chunk is not None:
chunks.append(chunk)
continue
raise ValueError(
'unrecognised %s%s escape at offset %d' % (slosh, c, offset0)
)
if specials is not None and c in special_starts:
# test sequence prefixes from longest to shortest
chunk = None
for seq in special_seqs:
if s.startswith(seq, offset0):
# special sequence
chunk, offset = specials[seq](s, offset0)
if offset < offset0 + 1:
raise ValueError(
"special parser for %r at offset %d moved offset backwards" %
(c, offset0)
)
break
if chunk is not None:
chunks.append(chunk)
continue
chunks.append(c)
continue
while offset < slen:
c = s[offset]
if (c == slosh or (delim is not None and c == delim)
or (specials is not None and c in special_starts)):
break
offset += 1
chunks.append(s[offset0:offset])
return ''.join(chunks), offset
def slosh_quote(raw_s: str, q: str):
''' Quote a string `raw_s` with quote character `q`.
'''
return q + raw_s.replace('\\', '\\\\').replace(q, '\\' + q)
# pylint: disable=redefined-outer-name
def get_envvar(s, offset=0, environ=None, default=None, specials=None):
''' Parse a simple environment variable reference to $varname or
$x where "x" is a special character.
Parameters:
* `s`: the string with the variable reference
* `offset`: the starting point for the reference
* `default`: default value for missing environment variables;
if `None` (the default) a `ValueError` is raised
* `environ`: the environment mapping, default `os.environ`
* `specials`: the mapping of special single character variables
'''
if environ is None:
environ = os.environ
offset0 = offset
if not s.startswith('$', offset):
raise ValueError("no leading '$' at offset %d: %r" % (offset, s))
offset += 1
if offset >= len(s):
raise ValueError(
"short string, nothing after '$' at offset %d" % (offset,)
)
identifier, offset = get_identifier(s, offset)
if identifier: