-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
1588 lines (1119 loc) · 50.4 KB
/
__init__.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
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <[email protected]>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
from __future__ import absolute_import;
import math;
import time;
import re;
import os;
from struct import pack;
from pymfony.component.system import Object;
from pymfony.component.system.types import String;
from pymfony.component.system.types import Convert;
from pymfony.component.system.types import OrderedDict;
from pymfony.component.system.exception import InvalidArgumentException;
from pymfony.component.system.serializer import serialize;
from pymfony.component.system.serializer import unserialize;
from pymfony.component.yaml.exception import ParseException;
from pymfony.component.yaml.exception import RuntimeException;
from pymfony.component.yaml.exception import DumpException;
"""
"""
class Ref(Object):
def __init__(self, i = 0):
self.__i = i;
def __str__(self):
return str(self.__i);
def get(self):
return self.__i;
def set(self, v):
self.__i = v;
def add(self, y):
self.__i += y;
def sub(self, y):
self.__i -= y;
class Parser(Object):
"""Parser parses YAML strings to convert them to PHP arrays.
@author: Fabien Potencier <[email protected]>
"""
def __init__(self, offset = 0):
"""Constructor
@param: integer offset The offset of YAML document (used for line numbers in error messages)
"""
self.__offset = 0;
self.__lines = list();
self.__currentLineNb = -1;
self.__currentLine = '';
self.__refs = dict();
self.__offset = offset;
def __mb_detect_encoding(self, text, encoding_list = None):
"""Return first matched encoding in encoding_list, otherwise return None.
See [url]http://docs.python.org/2/howto/unicode.html#the-unicode-type[/url] for more info.
See [url]http://docs.python.org/2/library/codecs.html#standard-encodings[/url] for encodings.
"""
if encoding_list is None:
encoding_list = ['ascii'];
for best_enc in encoding_list:
try:
text.encode(best_enc, 'strict');
except Exception:
best_enc = False;
else:
break;
return best_enc;
def parse(self, value, exceptionOnInvalidType = False, objectSupport = False):
"""Parses a YAML string to a PHP value.
@param: string value A YAML string
@param Boolean exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), False otherwise:
@param Boolean objectSupport True if object support is enabled, False otherwise:
@return mixed A PHP value
@raise ParseException If the YAML is not valid
"""
self.__currentLineNb = -1;
self.__currentLine = '';
self.__lines = self.__cleanup(value).split("\n");
if not self.__mb_detect_encoding(value, ['UTF-8']) :
raise ParseException('The YAML value does not appear to be valid UTF-8.');
# if (function_exists('mb_internal_encoding') and ((int) ini_get('mbstring.func_overload')) & 2) :
# mbEncoding = mb_internal_encoding();
# mb_internal_encoding('UTF-8');
context = None;
data = None;
while (self.__moveToNextLine()):
if (self.__isCurrentLineEmpty()) :
continue;
# tab?
if ("\t" == self.__currentLine[0]) :
raise ParseException('A YAML file cannot contain tabs as indentation.', self.__getRealCurrentLineNb() + 1, self.__currentLine);
isRef = isInPlace = isProcessed = False;
match = re.search('^\-((?P<leadspaces>\s+)(?P<value>.+?))?\s*$', self.__currentLine, flags=re.U);
if match :
values = {
0: match.group(0),
1: match.group(1),
'leadspaces': match.group('leadspaces'),
'value': match.group('value'),
};
if (context and 'mapping' == context) :
raise ParseException('You cannot define a sequence item when in a mapping');
context = 'sequence';
if not data:
data = list();
if values['value']:
matches = re.search('^&(?P<ref>[^ ]+) *(?P<value>.*)', values['value'], re.U);
if matches:
isRef = matches.group('ref');
values['value'] = matches.group('value');
# array
if not values['value'] or '' == values['value'].strip(' ') or values['value'].lstrip(' ').startswith('#') :
c = self.__getRealCurrentLineNb() + 1;
parser = Parser(c);
parser.__refs = self.__refs;
data.append(parser.parse(self.__getNextEmbedBlock(), exceptionOnInvalidType, objectSupport));
else :
if (values['leadspaces']
and ' ' == values['leadspaces']
and re.search('^(?P<key>'+Inline.REGEX_QUOTED_STRING+'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$', values['value'], re.U)
):
# this is a compact notation element, add to next block and parse
c = self.__getRealCurrentLineNb();
parser = Parser(c);
parser.__refs = self.__refs;
block = values['value'];
if ( not self.__isNextLineIndented()) :
block += "\n"+self.__getNextEmbedBlock(self.__getCurrentLineIndentation() + 2);
data.append(parser.parse(block, exceptionOnInvalidType, objectSupport));
else :
data.append(self.__parseValue(values['value'], exceptionOnInvalidType, objectSupport));
elif (re.search('^(?P<key>'+Inline.REGEX_QUOTED_STRING+'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$', self.__currentLine, re.U)) :
if (context and 'sequence' == context) :
raise ParseException('You cannot define a mapping item when in a sequence');
values = re.search('^(?P<key>'+Inline.REGEX_QUOTED_STRING+'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$', self.__currentLine, re.U);
values = {
0: values.group(0),
'key': values.group('key'),
'value': values.group('value'),
};
context = 'mapping';
if not data:
data = OrderedDict();
# force correct settings
Inline.parse(None, exceptionOnInvalidType, objectSupport);
try:
key = Inline.parseScalar(values['key']);
except ParseException as e:
e.setParsedLine(self.__getRealCurrentLineNb() + 1);
e.setSnippet(self.__currentLine);
raise e;
if ('<<' == key) :
if values['value'] and values['value'].startswith('*') :
isInPlace = values['value'][1:];
if isInPlace not in self.__refs :
raise ParseException(
'Reference "{0}" does not exist.'.format(
isInPlace),
self.__getRealCurrentLineNb() + 1,
self.__currentLine
);
else :
if values['value']:
value = values['value'];
else :
value = self.__getNextEmbedBlock();
c = self.__getRealCurrentLineNb() + 1;
parser = Parser(c);
parser.__refs = self.__refs;
parsed = parser.parse(value, exceptionOnInvalidType, objectSupport);
merged = OrderedDict();
if not isinstance(parsed, (dict, list)) :
raise ParseException('YAML merge keys used with a scalar value instead of an array.', self.__getRealCurrentLineNb() + 1, self.__currentLine);
if isinstance(parsed, list) :
# Numeric array, merge individual elements
for parsedItem in reversed(parsed):
if not isinstance(parsedItem, (dict, list)) :
raise ParseException('Merge items must be arrays.', self.__getRealCurrentLineNb() + 1, parsedItem);
elif isinstance(parsedItem, list) :
# append int key into a dict
for k in range(len(parsedItem)):
v = parsedItem[k];
i = int(k);
while i in merged:
i += 1;
merged[i] = v;
else:
tmp = parsedItem.copy();
tmp.update(merged);
merged = tmp;
else:
# Associative array, merge
merged.update(parsed);
isProcessed = merged;
elif values['value'] :
matches = re.search('^&(?P<ref>[^ ]+) *(?P<value>.*)', values['value'], re.U);
if matches:
isRef = matches.group('ref');
values['value'] = matches.group('value');
if (isProcessed) :
# Merge keys
data = isProcessed;
# hash
elif not values['value'] or '' == values['value'].strip(' ') or values['value'].lstrip(' ').startswith('#') :
# if next line is less indented or equal, then it means that the current value is None:
if (self.__isNextLineIndented() and not self.__isNextLineUnIndentedCollection()) :
data[key] = None;
else :
c = self.__getRealCurrentLineNb() + 1;
parser = Parser(c);
parser.__refs = self.__refs;
data[key] = parser.parse(self.__getNextEmbedBlock(), exceptionOnInvalidType, objectSupport);
else :
if (isInPlace) :
data = self.__refs[isInPlace].copy();
else :
data[key] = self.__parseValue(values['value'], exceptionOnInvalidType, objectSupport);
else :
# 1-liner optionally followed by newline
lineCount = len(self.__lines);
if 1 == lineCount or (2 == lineCount and not self.__lines[1]) :
try:
value = Inline.parse(self.__lines[0], exceptionOnInvalidType, objectSupport);
except ParseException as e:
e.setParsedLine(self.__getRealCurrentLineNb() + 1);
e.setSnippet(self.__currentLine);
raise e;
if isinstance(value, list) and value :
first = value[0];
if isinstance(first, String) and first.startswith('*') :
data = list();
for alias in value:
data.append(self.__refs[alias[1:]]);
value = data;
return value;
error = 'Unable to parse.';
raise ParseException(error, self.__getRealCurrentLineNb() + 1, self.__currentLine);
if (isRef) :
if context == 'mapping':
v = list(data.values())[-1];
else:
v = data[-1];
self.__refs[isRef] = v;
return None if not data else data;
def __getRealCurrentLineNb(self):
"""Returns the current line number (takes the offset into account).
@return: integer The current line number
"""
return self.__currentLineNb + self.__offset;
def __getCurrentLineIndentation(self):
"""Returns the current line indentation.
@return: integer The current line indentation
"""
return len(self.__currentLine) - len(self.__currentLine.lstrip(' '));
def __getNextEmbedBlock(self, indentation = None):
"""Returns the next embed block of YAML.
@param: integer indentation The indent level at which the block is to be read, or None for default
@return string A YAML string
@raise ParseException When indentation problem are detected
"""
self.__moveToNextLine();
if (None is indentation) :
newIndent = self.__getCurrentLineIndentation();
unindentedEmbedBlock = self.__isStringUnIndentedCollectionItem();
if (not self.__isCurrentLineEmpty() and 0 == newIndent and not unindentedEmbedBlock) :
raise ParseException('Indentation problem.', self.__getRealCurrentLineNb() + 1, self.__currentLine);
else :
newIndent = indentation;
data = [self.__currentLine[newIndent:]];
isItUnindentedCollection = self.__isStringUnIndentedCollectionItem();
while (self.__moveToNextLine()):
if (isItUnindentedCollection and not self.__isStringUnIndentedCollectionItem()) :
self.__moveToPreviousLine();
break;
if (self.__isCurrentLineEmpty()) :
if (self.__isCurrentLineBlank()) :
data.append(self.__currentLine[newIndent:]);
continue;
indent = self.__getCurrentLineIndentation();
match = re.search('^(?P<text> *)$', self.__currentLine);
if match :
# empty line
data.append(match.group('text'));
elif (indent >= newIndent) :
data.append(self.__currentLine[newIndent:]);
elif (0 == indent) :
self.__moveToPreviousLine();
break;
else :
raise ParseException('Indentation problem.', self.__getRealCurrentLineNb() + 1, self.__currentLine);
return "\n".join(data);
def __moveToNextLine(self):
"""Moves the parser to the next line.
@return: Boolean
"""
if (self.__currentLineNb >= len(self.__lines) - 1) :
return False;
self.__currentLineNb += 1;
self.__currentLine = self.__lines[self.__currentLineNb];
return True;
def __moveToPreviousLine(self):
"""Moves the parser to the previous line.
"""
self.__currentLineNb -= 1;
self.__currentLine = self.__lines[self.__currentLineNb];
def __parseValue(self, value, exceptionOnInvalidType, objectSupport):
"""Parses a YAML value.
@param: string value A YAML value
@return mixed A PHP value
@raise ParseException When reference does not exist
"""
if value.startswith('*') :
if '#' in value :
pos = value.find('#');
value = value[1:1 + pos - 2];
else :
value = value[1:];
if value not in self.__refs :
raise ParseException(
'Reference "{0}" does not exist.'.format(value),
self.__currentLine
);
return self.__refs[value];
matches = re.search('^(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?$', value);
if (matches) :
modifiers = matches.group('modifiers') if matches.group('modifiers') else '';
return self.__parseFoldedScalar(matches.group('separator'), re.sub('\d+', '', modifiers), abs(Convert.str2int(modifiers)));
try:
return Inline.parse(value, exceptionOnInvalidType, objectSupport);
except ParseException as e:
e.setParsedLine(self.__getRealCurrentLineNb() + 1);
e.setSnippet(self.__currentLine);
raise e;
def __parseFoldedScalar(self, separator, indicator = '', indentation = 0):
"""Parses a folded scalar.
@param: string separator The separator that was used to begin this folded scalar (| or >)
@param string indicator The indicator that was used to begin this folded scalar (+ or -)
@param integer indentation The indentation that was used to begin this folded scalar
@return string The text value
"""
notEOF = self.__moveToNextLine();
if ( not notEOF) :
return '';
# determine indentation if not specified
if 0 == indentation :
matches = re.search('^ +', self.__currentLine);
if matches:
indentation = len(matches.group(0));
text = '';
if indentation > 0:
pattern = '^ {%d}(.*)$' % (indentation);
isCurrentLineBlank = self.__isCurrentLineBlank();
matches = re.search(pattern, self.__currentLine);
while notEOF and (isCurrentLineBlank or matches) :
if isCurrentLineBlank:
text += self.__currentLine[indentation:];
else:
text += matches.group(1);
# newline only if not EOF
notEOF = self.__moveToNextLine();
if notEOF:
text += "\n";
isCurrentLineBlank = self.__isCurrentLineBlank();
matches = re.search(pattern, self.__currentLine);
elif notEOF:
text += "\n";
if notEOF:
self.__moveToPreviousLine();
# replace all non-trailing single newlines with spaces in folded blocks
if '>' == separator:
matches = re.search('(\n*)$', text);
text = re.sub('(?<!\n)\n(?!\n)', ' ', text.rstrip("\n"));
text += matches.group(1);
# deal with trailing newlines as indicated
if '' == indicator:
text = re.compile('\n+$', re.DOTALL).sub("\n", text);
elif '-' == indicator:
text = re.compile('\n+$', re.DOTALL).sub("", text);
return text;
def __isNextLineIndented(self):
"""Returns True if the next line is indented.:
@return: Boolean Returns True if the next line is indented, False otherwise:
"""
currentIndentation = self.__getCurrentLineIndentation();
notEOF = self.__moveToNextLine();
while (notEOF and self.__isCurrentLineEmpty()):
notEOF = self.__moveToNextLine();
if (False is notEOF) :
return False;
ret = False;
if (self.__getCurrentLineIndentation() <= currentIndentation) :
ret = True;
self.__moveToPreviousLine();
return ret;
def __isCurrentLineEmpty(self):
"""Returns True if the current line is blank or if it is a comment line.:
@return: Boolean Returns True if the current line is empty or if it is a comment line, False otherwise:
"""
return self.__isCurrentLineBlank() or self.__isCurrentLineComment();
def __isCurrentLineBlank(self):
"""Returns True if the current line is blank.:
@return: Boolean Returns True if the current line is blank, False otherwise:
"""
return '' == self.__currentLine.strip(' ');
def __isCurrentLineComment(self):
"""Returns True if the current line is a comment line.:
@return: Boolean Returns True if the current line is a comment line, False otherwise:
"""
# checking explicitly the first char of the strip is faster than loops or strpos
lstripmedLine = self.__currentLine.lstrip(' ');
return lstripmedLine.startswith('#');
def __cleanup(self, value):
"""Cleanups a YAML string to be parsed.
@param: string value The input YAML string
@return string A cleaned up YAML string
"""
value = value.replace("\r\n", "\n");
value = value.replace("\r", "\n");
# strip YAML header
count = Ref(0);
def callback(match):
count.add(1);
return '';
pattern = re.compile('^\%YAML[: ][\d\.]+.*\n', re.S | re.U);
value = pattern.sub(callback, value);
self.__offset += count.get();
# remove leading comments
count.set(0);
pattern = re.compile('^(\#.*?\n)+', re.S);
stripmedValue = pattern.sub(callback, value);
if (count.get() == 1) :
# items have been removed, update the offset
self.__offset += value.count("\n") - stripmedValue.count("\n");
value = stripmedValue;
# remove start of the document marker (---)
count.set(0);
pattern = re.compile('^\-\-\-.*?\n', re.S);
stripmedValue = pattern.sub(callback, value);
if (count.get() == 1) :
# items have been removed, update the offset
self.__offset += value.count("\n") - stripmedValue.count("\n");
value = stripmedValue;
# remove end of the document marker (...)
pattern = re.compile('\.\.\.\s*$', re.S);
value = pattern.sub('', value);
return value;
def __isNextLineUnIndentedCollection(self):
"""Returns True if the next line starts unindented collection:
@return: Boolean Returns True if the next line starts unindented collection, False otherwise:
"""
currentIndentation = self.__getCurrentLineIndentation();
notEOF = self.__moveToNextLine();
while (notEOF and self.__isCurrentLineEmpty()):
notEOF = self.__moveToNextLine();
if (False is notEOF) :
return False;
ret = False;
if (self.__getCurrentLineIndentation() == currentIndentation
and self.__isStringUnIndentedCollectionItem() ):
ret = True;
self.__moveToPreviousLine();
return ret;
def __isStringUnIndentedCollectionItem(self):
"""Returns True if the string is un-indented collection item:
@return: Boolean Returns True if the string is un-indented collection item, False otherwise:
"""
return self.__currentLine.startswith('- ');
class Inline(Object):
"""Inline implements a YAML parser/dumper for the YAML inline syntax.
@author: Fabien Potencier <[email protected]>
"""
REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')';
__exceptionOnInvalidType = False;
__objectSupport = False;
@classmethod
def parse(cls, value, exceptionOnInvalidType = False, objectSupport = False):
"""Converts a YAML string to a PHP array.
@param: string value A YAML string
@param Boolean exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), False otherwise:
@param Boolean objectSupport True if object support is enabled, False otherwise:
@return array A PHP array representing the YAML string
@raise ParseException
"""
cls.__exceptionOnInvalidType = exceptionOnInvalidType;
cls.__objectSupport = objectSupport;
if not value:
value = '';
value = value.strip();
if not value :
return '';
i = Ref(0);
if value[0] == '[':
result = cls.__parseSequence(value, i);
i.add(1);
elif value[0] == '{':
result = cls.__parseMapping(value, i);
i.add(1);
else:
result = cls.parseScalar(value, None, ['"', "'"], i);
# some comments are allowed at the end
if re.sub('^\s+#.*$', '', value[i.get():]) :
raise ParseException('Unexpected characters near "{0}".'.format(
value[i.get():]
));
return result;
@classmethod
def dump(cls, value, exceptionOnInvalidType = False, objectSupport = False):
"""Dumps a given PHP variable to a YAML string.
@param: mixed value The PHP variable to convert
@param Boolean exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), False otherwise:
@param Boolean objectSupport True if object support is enabled, False otherwise:
@return string The YAML string representing the PHP array
@raise DumpException When trying to dump PHP resource
"""
if isinstance(value, (list, dict)):
return cls.__dumpArray(value, exceptionOnInvalidType, objectSupport);
if None is value:
return 'null';
if True is value:
return 'true';
if False is value:
return 'false';
if str(value).isdigit():
return "'"+value+"'" if isinstance(value, String) else str(int(value));
if cls.__is_numeric(value):
return "'"+value+"'" if isinstance(value, String) else re.compile('INF', re.I).sub('.Inf', str(value)) if math.isinf(value) else str(value);
if not isinstance(value, String):
if (objectSupport) :
return '!!python/object:'+serialize(value);
if (exceptionOnInvalidType) :
raise DumpException('Object support when dumping a YAML file has been disabled.');
return 'null';
if Escaper.requiresDoubleQuoting(value):
return Escaper.escapeWithDoubleQuotes(value);
if Escaper.requiresSingleQuoting(value):
return Escaper.escapeWithSingleQuotes(value);
if '' == value:
return "''";
if (cls.__getTimestampRegex().search(value)
or value.lower() in ['null', '~', 'true', 'false']):
return "'"+value+"'";
if isinstance(value, String):
return value;
@classmethod
def __dumpArray(cls, value, exceptionOnInvalidType, objectSupport):
"""Dumps a PHP array to a YAML string.
@param: list|dict value The PHP array to dump
@param Boolean exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), False otherwise:
@param Boolean objectSupport True if object support is enabled, False otherwise:
@return string The YAML string representing the PHP array
"""
if isinstance(value, list):
# sequence
output = list();
for val in value:
output.append(cls.dump(val, exceptionOnInvalidType, objectSupport));
return '[{0}]'.format(', '.join(output));
if isinstance(value, dict):
# mapping
output = list();
for key, val in value.items():
output.append('{0}: {1}'.format(cls.dump(key, exceptionOnInvalidType, objectSupport), cls.dump(val, exceptionOnInvalidType, objectSupport)));
return '{'+' {0} '.format(', '.join(output))+'}';
@classmethod
def parseScalar(cls, scalar, delimiters = None, stringDelimiters = None, i = None, evaluate = True):
"""Parses a scalar to a YAML string.
@param: scalar scalar
@param string delimiters
@param array stringDelimiters
@param integer &i
@param Boolean evaluate
@return string A YAML string
@raise ParseException When malformed inline YAML string is parsed
"""
if stringDelimiters is None:
stringDelimiters = ['"', "'"];
if i is None:
i = Ref(0);
assert isinstance(i, Ref);
if scalar[i.get()] in stringDelimiters :
# quoted scalar
output = cls.__parseQuotedScalar(scalar, i);
if (None is not delimiters) :
tmp = scalar[i.get():].lstrip(' ');
if tmp[0] not in delimiters :
raise ParseException('Unexpected characters ({0}).'.format(
scalar[i.get():]
));
else :
# "normal" string
if not delimiters :
output = scalar[i.get():];
i.add(len(output));
# remove comments
strpos = output.find(' #');
if strpos != -1 :
output = output[0:strpos].rstrip();
elif (re.search('^(.+?)('+'|'.join(delimiters)+')', scalar[i.get():])) :
match = re.search('^(.+?)('+'|'.join(delimiters)+')', scalar[i.get():])
output = match.group(1);
i.add(len(output));
else :
raise ParseException(
'Malformed inline YAML string ({0}).'.format(scalar)
);
output = cls.__evaluateScalar(output) if evaluate else output;
return output;
@classmethod
def __parseQuotedScalar(cls, scalar, i):
"""Parses a quoted scalar to YAML.
@param: string scalar
@param integer &i
@return string A YAML string
@raise ParseException When malformed inline YAML string is parsed
"""
assert isinstance(i, Ref);
match = re.search('^'+cls.REGEX_QUOTED_STRING, scalar[i.get():], flags=re.U);
if not match :
raise ParseException(
'Malformed inline YAML string ({0}).'.format(
scalar[i.get():]
));
output = match.group(0)[1: 1 + len(match.group(0)) - 2];
unescaper = Unescaper();
if ('"' == scalar[i.get()]) :
output = unescaper.unescapeDoubleQuotedString(output);
else :
output = unescaper.unescapeSingleQuotedString(output);
i.add(len(match.group(0)));
return output;
@classmethod
def __parseSequence(cls, sequence, i = None):
"""Parses a sequence to a YAML string.
@param: string sequence
@param integer i
@return string A YAML string
@raise ParseException When malformed inline YAML string is parsed
"""
if i is None:
i = Ref(0);
assert isinstance(i, Ref);
output = list();
lenght = len(sequence);
i.add(1);
# [foo, bar, ...]
while (i.get() < lenght):
if sequence[i.get()] == '[':
output.append(cls.__parseSequence(sequence, i));
elif sequence[i.get()] == '{':
# nested mapping
output.append(cls.__parseMapping(sequence, i));
elif sequence[i.get()] == ']':
return output;
elif sequence[i.get()] in [',', ' ']:
pass;
else:
isQuoted = sequence[i.get()] in ['"', "'"];
value = cls.parseScalar(sequence, [',', ']'], ['"', "'"], i);
if not isQuoted and isinstance(value, String) and ': ' in value :
# embedded mapping?
try:
value = cls.__parseMapping('{'+value+'}');
except InvalidArgumentException as e:
# no, it's not
pass;
output.append(value);
i.sub(1);
i.add(1);
raise ParseException('Malformed inline YAML string {0}'.format(
sequence
));
@classmethod
def __parseMapping(cls, mapping, i = None):
"""Parses a mapping to a YAML string.
@param: string mapping
@param integer i
@return string A YAML string
@raise ParseException When malformed inline YAML string is parsed
"""
if i is None:
i = Ref(0);
assert isinstance(i, Ref);
output = OrderedDict();
lenght = len(mapping);
i.add(1);
# foo: bar, bar:foo, ...
while (i.get() < lenght):
if mapping[i.get()] in [' ', ',']:
i.add(1);
continue;
elif mapping[i.get()] == '}':
return output;
# key