-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinivars.py
More file actions
executable file
·2129 lines (1816 loc) · 71 KB
/
Copy pathinivars.py
File metadata and controls
executable file
·2129 lines (1816 loc) · 71 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
__version__ = "$Revision: 484 $, $Date: 2012-07-27 17:33:31 +0200 (vr, 27 jul 2012) $, $Author: quintijn $"
# -*- coding: latin-1 -*-
"""contains class IniVars, that does inifiles
"""
import win32api, types
import os, os.path, sys, re, copy, string
import utilsqh
from utilsqh import path, peek_ahead
import locale
locale.setlocale(locale.LC_ALL, '')
lineNum = 0
fileName = ''
class IniError(Exception):
"""Return the line number in the reading section, and the filename if there"""
def __init__(self, value):
self.value = value
self.lineNum = lineNum
self.fileName = fileName
def __str__(self):
s = ['Inivars error ']
if fileName:
s.append('in file %s, '%fileName)
if lineNum:
s.append('on line %s'%lineNum)
s.append(': ')
s.append(self.value)
return ''.join(s)
DEBUG = 0
# doctest at the bottom
#reAllSections = re.compile(r'^\s*[([^]]+)\]\s*$', re.M)
#reAllKeys = re.compile(r'(^[^=\n]+)[=]', re.M)
reValidSection = re.compile(r'\[\b([- \.\w]+)]\s*$', re.L)
reFindKeyValue = re.compile(r'\b([- \.\w]+)\s*=(.*)$', re.L)
reValidKey = re.compile(r'(\w[\w \.\-]*)$', re.L)
reQuotes = re.compile(r'[\'"]')
reListValueSplit = re.compile(r'[\n;]', re.M)
reWhiteSpace = re.compile(r'\s+')
reDoubleQuotes = re.compile(r'^"([^"]*)"$', re.M)
reSingleQuotes = re.compile(r"^'([^']*)'$", re.M)
def quoteSpecial(t, extraProtect = None):
"""add quotes to string, to protect starting quotes, spaces
extraProtect is possibly a string/list/tuple of characters that
also need to be protected with quotes
>>> quoteSpecial("abc")
'abc'
>>> quoteSpecial(" abc ")
'" abc "'
>>> quoteSpecial("'abc' ")
'"\\'abc\\' "'
with newlines in text:
>>> quoteSpecial("'abc'\\n ")
'"\\'abc\\'\\n "'
>>> quoteSpecial(' "ab"')
'\\' "ab"\\''
but singular quotes inside a string are kept as they were:
>>> quoteSpecial('a" b "c')
'a" b "c'
with both quotes:
>>> quoteSpecial('a" \\'b "c')
'a" \\'b "c'
>>> quoteSpecial("'a\\" 'b \\"c'")
'"\\'a" \\'b "c\\'"'
>>> quoteSpecial('" \\'b "c\\' xyz')
'"" \\'b "c\\' xyz"'
>>> quoteSpecial('ab"')
'ab"'
>>> quoteSpecial("ab' '")
"ab' '"
>>> quoteSpecial("a' b 'c")
"a' b 'c"
now for the list possibility:
>>> quoteSpecial("a;bc", ";\\n")
'"a;bc"'
>>> quoteSpecial("ab\\nc", ";\\n")
'"ab\\nc"'
and for the dict possibility:
>>> quoteSpecial("abc,", ",")
'"abc,"'
>>> quoteSpecial("a,bc", ",")
'"a,bc"'
>>> quoteSpecial("a,bc", "'|;")
'a,bc'
"""
if t is None:
return ''
if t.strip() != t:
# leading or trailing spaces:
if t.find('"') >= 0:
if t.find("'") >= 0:
t = t.replace('"', '"')
#raise IniError("string may not contain single AND double quotes: |%s|"% t)
return "'%s'" % t
else:
return '"%s"'% t
elif t.find('"') == 0:
if t.find("'") >= 0:
t = t.replace('"', '"')
#print 'Inifile warning: text contains single AND double quotes:'
return '"%s"'% t
return "'%s'"% t
elif t.find("'") == 0:
if t.find('"') >= 0:
t = t.replace('"', '"')
#raise IniError("string may start with single quote AND contain double quotes: |%s|"% t)
return '"%s"'% t
elif extraProtect:
for c in extraProtect:
if t.find(c) >= 0:
if t.find('"') >= 0:
if t.find("'") >= 0:
raise IniError("string contains character to protect |%s| AND single and double quotes: |%s|"% (c, t))
else:
return "'%s'"% t
else:
return '"%s"'% t
return t
def quoteSpecialDict(t):
"""quote special with additional protection of comma
"""
return quoteSpecial(t, ',')
def quoteSpecialList(t):
"""quote special with additional protection of semicolon, newline
"""
return quoteSpecial(t, ';\n')
def stripSpecial(t):
"""strips text string, BUT if quotes or single quotes leaves rest
new lines are preserved, BUT all lines are stripped
>>> stripSpecial('""')
''
>>> stripSpecial('abc')
'abc'
>>> stripSpecial(" x ")
'x'
>>> stripSpecial("' a '")
' a '
>>> stripSpecial('" a "')
' a '
"""
#if t.find('\n') >= 0:
# return '\n'.join(map(stripSpecial, t.split('\n')))
#
t = t.strip()
if not t:
return ''
elif reDoubleQuotes.match(t):
r = reDoubleQuotes.match(t)
inside = r.group(1)
if inside.find('"') == -1:
return inside
else:
raise IniError, 'invalid double quotes in string: |%s|'% t
elif reSingleQuotes.match(t):
r = reSingleQuotes.match(t)
inside = r.group(1)
if inside.find("'") == -1:
return inside
else:
raise IniError, 'invalid single quotes in string: |%s|'% t
elif t.find("'") == 0 or t.find('"') == 0:
raise IniError, 'starting quote without matching end quote in string: |%s|'% t
else:
return t
def getIniList(t, sep=(";", "\n")):
"""gets a list from inifile with quotes entries
inside this function a state is maintained, for keeping track
of the action to be taken if some character occurs:
state = 0: start of string, or start after separator
state = 1: normal string, including spaces
state = 2: inside a quoted string, that everything go except
the quote that is maintained in hadQuote
state = 3: after a quoted string, waits for a separator or
the end of the string. Raises error if anything else than a
space his met
>>> list(getIniList("a; c"))
['a', 'c']
>>> list(getIniList("a;c"))
['a', 'c']
>>> list(getIniList("a; c;"))
['a', 'c', '']
>>> list(getIniList("'a\\"b'; c"))
['a"b', 'c']
>>> list(getIniList('"a "; c'))
['a ', 'c']
>>> list(getIniList("a ; ' c '"))
['a', ' c ']
>>> list(getIniList("';a '; ' c '"))
[';a ', ' c ']
>>> list(getIniList("'a '\\n' c '"))
['a ', ' c ']
"""
i = 0
l = len(t)
state = 0
hadQuote = ''
## print '---------------------------length: %s'% l
for j in range(l):
c = t[j]
## print 'do c: |%s|, index: %s'% (c, j)
if c == "'" or c == '"':
if state == 0:
# starting quoted state
state = 2
hadQuote = c
i = j + 1
continue
elif state == 1:
# quoted inside a string, let it pass
continue
elif state == 2:
if c == hadQuote:
yield t[i:j]
state = 3
continue
elif state == 3:
raise IniError('invalid character |%s| after quoted string: |%s|'%
(c, t))
elif c in sep:
if state == 0:
# yielding empty string
yield ''
elif state == 1:
# end of normal string
yield t[i:j].strip()
elif state == 2:
# ignore separator when in quoted string
continue
# reset the state now:
state = 0
i = j + 1
continue
elif c == ' ':
continue
else:
if state == 3:
raise IniError('invalid character |%s| after quoted string: |%s|'%
(c, t))
elif state == 0:
i = j
state = 1
continue
if state == 0:
# empty string at end
yield ''
elif state == 1:
## print 'yielding normal last part: |%s|, i: %s,length: %s'% (t[i:],i,l)
yield t[i:].strip()
elif state == 2:
raise IniError('no end of quoted string found: |%s|'% t)
def getIniDict(t):
"""gets a dict from inifile with generator function
provides this generator with one list item (getDict should call getIniList first)
each time a tuple pair (key, value) is returned,
with value being a string or a list of strings, is separated by comma's
If more keys are provided (separated by comma's), these result
in different yield statements
>>> list(getIniDict("a"))
[('a', None)]
>>> list(getIniDict("a:value of a"))
[('a', 'value of a')]
>>> list(getIniDict("a: ' '"))
[('a', ' ')]
>>> list(getIniDict('a: "with, comma"'))
[('a', 'with, comma')]
>>> list(getIniDict("a: 'with, comma'"))
[('a', 'with, comma')]
>>> list(getIniDict('a: more, "intricate, with, comma", example'))
[('a', ['more', 'intricate, with, comma', 'example'])]
>>> list(getIniDict("a: c, d"))
[('a', ['c', 'd'])]
>>> list(getIniDict("a, b: c"))
[('a', 'c'), ('b', 'c')]
>>> list(getIniDict("a,b : c, d"))
[('a', ['c', 'd']), ('b', ['c', 'd'])]
"""
if t.find('\n') >= 0:
raise IniError('getIniDict must be called through getIniList, so newline chars are not possible: |%s|'%
t)
if t.find(':') >= 0:
Keys, Values = map(string.strip, t.split(':', 1))
else:
Keys = t.strip()
Values = ''
if not Values:
Values = None
else:
Values = list(getIniList(Values, ","))
if len(Values) == 1:
Values = Values[0]
if not Keys:
return
if Keys.find(',') > 0:
Keys = map(string.strip, Keys.split(','))
for k in Keys:
if not reValidKey.match(k):
raise IniError('invalid character in key |%s| of dictionary entry: |%s|'%
(k, t))
yield k, Values
else:
if not reValidKey.match(Keys):
raise IniError('invalid character in key |%s| of dictionary entry: |%s|'%
(Keys, t))
yield Keys, Values
def lensort(a, b):
"""sorts two strings, longest first, if length is equal, normal sort
>>> lensort('a', 'b')
-1
>>> lensort('aaa', 'a')
-1
>>> lensort('zzz', 'zzzzz')
1
"""
la = len(a)
lb = len(b)
if la == lb:
return cmp(a, b)
else:
return -cmp(la, lb)
class IniSection(dict):
"""represents a section of an inivars instance"""
def __init__(self, parent):
"""init with ignore case if given in inivars
"""
self._parent = parent
self._SKIgnorecase = parent._SKIgnorecase
def __getitem__(self, key):
'''double underscore means internal value'''
if type(key) == types.StringType and key.startswith == '__':
return self.__dict__[key]
else:
key = key.strip()
if reWhiteSpace.search(key):
key = reWhiteSpace.sub(' ', key)
if self._SKIgnorecase:
key = key.lower()
try:
return dict.__getitem__(self, key)
except KeyError:
return ""
def __setitem__(self, key, value):
key = key.strip()
if reWhiteSpace.search(key):
key = reWhiteSpace.sub(' ', key)
if not key:
raise IniError, '__setitem__, invalid key |%s|(false), with value |%s| in inifile: %s'% \
(key, value, self._parent._file)
if type(key) == types.StringType and key.startswith == '__':
self.__dict__[key] = value
else:
if self._SKIgnorecase:
key = key.lower()
dict.__setitem__(self, key, value)
def __delitem__(self, key):
key = key.strip()
if reWhiteSpace.search(key):
key = reWhiteSpace.sub(' ', key)
if not key:
raise IniError, '__delitem__, invalid key |%s|(false), inifile: %s'% \
(key, self._parent._file)
if type(key) == types.StringType and key.startswith == '__':
del self.__dict__[key]
else:
if self._SKIgnorecase:
key = key.lower()
try:
dict.__delitem__(self, key)
except KeyError:
pass
class IniVars(dict):
"""do inivars from an .ini file, or possibly (extending this class)
with other file types.
File doesn't have to exist before.
version 7: quoting is allowed when spaces or special characters
" or ' or ; in lists or ; or , in dicts are found.
version 6: change format of getDict:
if key has value it is followed by a colon, more keys can
be defined in one stroke
version 6:
options at start: sectionsLC = 1: convert all section names to lowercase (default 0)
keysLC = 0: convert all keys to lowercase (default 0)
gettting of keys, with optional parameters
version 5:
In this version also a getDict, getList (was already), getInt
getFloat and getTuple are defined. When setting a dict, list, etc.
inside the instance this type is conserved, when writing back
into the inifile the appropriate formatting is done.
version 4:
In this version 4 empty sections and keys are accepted, and set as
[empty section] or
[section]
empty key =
If the set command contains lists, elements are cycled through,
If the sets command contains empty values these empty values are set like
the example above.
When an empty section or key is asked for [] or '' is returned. You can see
no difference if a section doesn't exist or is empty, as long has no default values
are provided in the get function.
When you get a value from a key through a list of sections, as soon as the key
has been found (also when value is empty), this value is returned.
second version:
getList and setList are included
third version, new methods:
getSectionPostfixesWithPrefix:
sets a private dict _sectionPostfixesWP, see below
getFromSectionsWithPrefix(prefix, text, key)
text is a string (eg a window title) in which the postfix
of the section name is found.
getSectionsWithPrefix(prefix, longerText)
gets a list of section names, that contain prefix and postfix
matches a part of the longerText
get is extended with a list of sections:
get(['a', 'b'], 'key'): the list of sections searched,
until a nonempty value is found.
get(['a', 'b']): returns all the keys in their respective sections,
without making duplicates
getKeysOrderedFromSections gives a dictionary with the keys
of several sections ordered
formatKeysOrderedFromSections gives a long string of the keys
of several sections ordered
getMatchingSection gives from a section list the name of thefirst section
that contains the key. Returns "section not found" if not found.
>>> import os
>>> try: os.remove('empty.ini')
... except: pass
>>> ini = IniVars('empty.ini')
>>> ini.write()
>>> os.path.isfile('empty.ini')
1
>>> try: os.remove('simple.ini')
... except: pass
>>> ini = IniVars('simple.ini')
>>> ini.set('s', 'k', 'v')
>>> ini.set('s','k2','v2')
>>> ini.write()
>>> ini2 = IniVars('simple.ini')
>>> ini2.get()
['s']
>>> ini2.get('s')
['k2', 'k']
>>> ini2.get('s', 'k')
'v'
>>> ini == ini2
1
>>> ini.getFilename()
'simple.ini'
"""
_SKIgnorecase = None
def __init__(self, File, **kw):
"""init from valid files, raise error if invalid file
"""
# add str function in case file is a path instance:
file = str(File)
self._name = os.path.basename(file)
self._file = file
self._ext = self.getExtension(file)
self._changed = 0
self._maxLength = 60
self._SKIgnorecase = kw.get('SKIgnorecase', None)
self._repairErrors = kw.get('repairErrors', None)
#if self._repairErrors:
# print 'try to ignore errors in inifile: %s'% self._file
if not self._ext:
raise IniError, 'file has no extension: %s'% self._file
# start with new file:
if not os.path.isfile(file):
return
else:
try:
execstring = 'self._read%s(file)'% self._ext
exec(execstring)
except AttributeError:
raise IniError, 'file has invalid extension: %s'% self._file
if DEBUG: print 'read from INI:', self
def __nonzero__(self):
"""always true!"""
return True
def getFilename(self):
return self._file
def getName(self):
return self._name
def __getitem__(self, key):
if type(key) == types.StringType and key.startswith == '__':
return self.__dict__[key]
else:
key = key.strip()
if reWhiteSpace.search(key):
key = reWhiteSpace.sub(' ', key)
if self._SKIgnorecase:
key = key.lower()
try:
return dict.__getitem__(self, key)
except KeyError:
return ""
def __setitem__(self, key, value):
key = key.strip()
if reWhiteSpace.search(key):
key = reWhiteSpace.sub(' ', key)
if not key:
raise IniError, '__setitem__, invalid key |%s|(false), with value |%s| in inifile: %s'% \
(key, value, self._file)
if type(key) == types.StringType and key.startswith == '__':
self.__dict__[key] = value
else:
if self._SKIgnorecase:
key = key.lower()
dict.__setitem__(self, key, value)
def __delitem__(self, key):
key = key.strip()
if reWhiteSpace.search(key):
key = reWhiteSpace.sub(' ', key)
if not key:
raise IniError, '__delitem__, invalid key |%s|(false), with value |%s| in inifile: %s'% \
(key, value, self._file)
if type(key) == types.StringType and key.startswith == '__':
del self.__dict__[key]
else:
if self._SKIgnorecase:
key = key.lower()
try:
dict.__delitem__(self, key)
except KeyError:
pass
## def _readPy(self, file):
##
## # prepare file for importing:
## d, f = os.path.split(file)
## if not d in sys.path:
## sys.path.append(d)
## r, t = os.path.splitext(f)
## mod = __import__(r)
## d = {}
## for k,v in mod.__dict__.items():
## if k[0:2] != '__' and type(v) == types.DictType:
## d[k] = v
## if DEBUG: print 'read from py:', d
## return d
def _readIni(self, file):
global lineNum, fileName
lineNum = 0
fileName = file
section = None
sectionName = ''
key = None
keyName = ''
sectionNameLines = {}
for line in open(file, 'r'):
line = line.rstrip()
lineNum += 1
m = reValidSection.match(line)
if self._repairErrors and not m:
# with repairErrors option, characters in front of a valid section:
n = reValidSection.search(line)
if n and not m:
print 'ignore data in front of section: "%s"\n\t(please correct later in file "%s", line %s)'% (line,
fileName, lineNum)
m = n
elif not sectionName:
if not line:
continue
print 'no valid section found yet, skip line: "%s"\n\t(please correct later in file "%s", line %s)'% (line,
fileName, lineNum)
continue
if m:
sectionName = m.group(1).strip()
if sectionName in self:
if self._repairErrors:
print 'Warning: duplicate section "%s" on line %s and on line %s, take latter one\n\t(please correct later in file "%s")'% (
sectionName, sectionNameLines[sectionName], lineNum, fileName)
del self[sectionName]
else:
raise IniError('Duplicate section "%s" on line %s and on line %s\n\t(please correct in file "%s")'% (
sectionName, sectionNameLines[sectionName], lineNum, fileName))
self[sectionName] = IniSection(parent = self)
section = self[sectionName]
key = None
sectionNameLines[sectionName] = lineNum
continue
m = reFindKeyValue.match(line)
if m:
keyName = m.group(1).strip()
if section is None:
raise IniError('no section defined yet')
if keyName in section:
if self._repairErrors:
print 'Warning: duplicate keyname "%s" in section %s on line %s, take latter one\n\t(please correct later in file "%s")'% (
keyName, sectionName, lineNum, fileName)
del section[keyName]
else:
raise IniError('Duplicate keyname "%s" in section %s on line %s\n\t(please correct in file "%s")'% (
keyName, sectionName, lineNum, fileName))
section[keyName] = [m.group(2)]
key = section[keyName]
continue
if key:
# append to list of lines of key: stripping spaces etc.
key.append(line.strip())
elif line.strip():
if section is None:
raise IniError('no key or section found yet')
elif key is None:
if self._repairErrors:
print 'Warning: no key found in section "%s" on line %s, ignore\n\t(please correct later in file "%s")'% (
sectionName, lineNum, fileName)
continue
else:
raise IniError('No key found in section "%s" on line %s\n\t(please correct in file "%s")'% (
sectionName, lineNum, fileName))
for s in self:
section = self[s]
for k in section:
section[k] = listToString(section[k])
def writeIfChanged(self, file=None):
if self._changed:
self.write(file=file)
self._changed = 0
def write(self, file=None):
if not file:
file = self._file
ext = self._ext
else:
ext = self.getExtension(file)
if ext == 'Ini':
self._writeIni(file)
else:
raise IniError, 'invalid extension for writing to file: %s'% file
def _writeIni(self, file):
"""writes to file of type ini"""
L = []
sections = self.get()
sections.sort()
hasTrailingNewline = 1 # no newline for section
for s in sections:
hadTrailingNewline = hasTrailingNewline
hasTrailingNewline = 0
if not hadTrailingNewline:
L.append('') # prevent extra newlines at top or after multiline key
L.append('[%s]'% s)
keys = self.get(s)
# key char has '-', for sitegen:
keyhashyphen = 0
for k in keys:
if k.find('-') > 0:
keyhashyphen = 1
break
if keyhashyphen:
# special case for sitegen:
keys = sortHyphenKeys(keys)
else:
keys.sort()
for k in keys:
hadTrailingNewline = hasTrailingNewline
hasTrailingNewline = 0
v = self[s][k]
if type(v) == types.IntType:
L.append('%s = %s' % (k, v))
elif type(v) == types.FloatType:
L.append('%s = %s' % (k, v))
elif type(v) == types.BooleanType:
L.append('%s = %s' % (k, str(v)))
elif not v:
L.append('%s =' % k)
elif type(v) == types.StringType:
v = v.strip()
if v.find('\n') >= 0:
hasTrailingNewline = 1
V = v.split('\n')
if not hadTrailingNewline:
L.append('') # 1 extra newline
L.append('%s =' % k)
spacing = ' '*4
for li in V:
if li:
L.append('%s%s' % (spacing, li))
else:
L.append('')
L.append('')
elif len(k) + len(v) > 72:
if not hasTrailingNewline:
L.append('')
L.append('%s = %s' % (k, v))
L.append('')
hasTrailingNewline = 1
else:
L.append('%s = %s' % (k, v))
elif type(v) == types.ListType or type(v) == types.TupleType:
valueList = map(quoteSpecialList, v)
startString = '%s = '% k
length = len(startString)
listToWrite = []
for v in valueList:
if listToWrite and length + len(v) + 2 > self._maxLength:
L.append('%s%s' % (startString, '; '.join(listToWrite)))
listToWrite = [v]
startString = ' '*len(startString)
length = len(startString) + len(v)
else:
listToWrite.append(v)
length += len(v) + 2
if length > 72:
hasTrailingNewline = 1
L.append('%s%s' % (startString, '; '.join(listToWrite)))
L.append('')
elif type(v) == types.DictType:
inverse = {}
for K, V in v.items():
if type(V) == types.StringType:
vv = quoteSpecialDict(V)
elif type(V) == types.ListType or type(V) == types.TupleType:
vv = ', '.join(map(quoteSpecialDict, V))
elif V == None:
vv = None
if vv in inverse:
inverse[vv].append(K)
else:
inverse[vv] = [K]
startString = '%s = '% k
length = len(startString)
if not inverse:
L.append('%s' % startString)
else:
if None in inverse:
L.append('%s%s' % (startString, ', '.join(inverse[None])))
del inverse[None]
startString = ' '*len(startString)
if inverse:
for K, V in inverse.items():
## print 'writing back value: |%s|, startString: |%s|, keys: |%s|'% \
## (K, startString, V)
L.append('%s%s: %s' % (startString, ', '.join(V), K))
startString = ' '*len(startString)
hasTrailingNewline = 1
L.append('')
if not hadTrailingNewline:
L.append('')
## if path(self._file).isfile():
## old = open(self._file).read()
## else:
## old = ""
new = '\n'.join(L)
## if old == new:
## pass
#### print 'no changes'
## else:
#### self.saveOldInifile()
open(file, 'w').write(new)
pass
def saveOldInifile(self):
"""make copy -1, ..., -9 for previous versions"""
orgfile = self._file
for i in range(1,10):
newfile = path('%s-%s'% (orgfile, i))
if not newfile.isfile():
break
else:
newfile.delete()
for j in range(i,0, -1):
pass
def get(self, s=None, k=None, value="", stripping=stripSpecial):
"""get sections, keys or values, in version 3 extended
with s also being a list, examples of this far below.
with version 6, strips more smart, see function stripSpecial below
when setting a string, this smart quoting must also be performed.
>>> import os
>>> try: os.remove('get.ini')
... except: pass
>>> ini = IniVars("get.ini")
>>> ini.get()
[]
>>> ini.get("s")
[]
>>> ini.get()
[]
>>> ini.get("s", "k")
''
>>> ini.get("s", "k", "v")
'v'
spaces in section or key name are stripped and made single:
>>> ini.set(" s t ", "a k ", 'strange')
>>> ini.get("s t", 'a k')
'strange'
>>> ini.get("s t ", 'a k ')
'strange'
>>>
"""
if type(s) == types.ListType or type(s) == types.TupleType:
if k:
k = k.strip()
if reWhiteSpace.search(k):
k = reWhiteSpace.sub(' ', k)
# look for the section with this key
for S in s:
v = self.get(S, k, None, stripping=stripping)
if v != None:
return v
else:
# key not found, return default value
return value
else:
# get list of all keys with these sections:
L = []
for S in s:
l = self.get(S)
for k in l:
if k not in L:
L.append(k)
return L
# not found, return default:
if k:
return value
else:
# asking for list of possible keys:
return L
if s:
s = s.strip()
if reWhiteSpace.search(s):
s = reWhiteSpace.sub(' ', s)
if self.hasSection(s):
# s exists, process key requests
if k:
k = k.strip()
if reWhiteSpace.search(k):
k = reWhiteSpace.sub(' ', k)
# request value from s,k
if self.hasKey(s, k):
# k exists, return value
v = self[s][k]
if stripping and type(v) == types.StringType:
return stripping(v)
else:
return v
else:
# no key, return default value
return value
else:
# no key given, request a list of keys
return self[s].keys()
elif k:
# s doesn't exist, return default value
return value
else:
# s doesn't exist, return empty list of keys
return []
else:
# no section, request section list
return self.keys()
def set(self, s, k=None, v=None):
"""set section, key to value
section can be a list, as can be the key. If the value
is not given, empty sections or keys are made.
>>> try: os.remove('set.ini')
... except: pass
>>> ini = IniVars("set.ini")
>>> ini.set("section","key","value")
>>> ini.get("section")
['key']
>>> ini.get("section","key")
'value'
>>> ini.set('empty section')
>>> ini.get()
['section', 'empty section']
>>> ini.set(['empty 1', 'empty 2'])
>>> ini.get('empty 1')
[]
>>> ini.set(['not empty 1'], ['empty key 1', 'empty key 2'])
>>> ini.get('not empty 1', 'empty key 1')
>>> ini.set(['not empty 1'], ['key 1', 'key 2'], ' value ')
>>> ini.get('not empty 1', 'key 1')
' value '
>>> ini.set('quotes', 'double', '" a "')
>>> ini.get('quotes', 'double')
'" a "'
>>> ini.set('quotes', 'single', "' a '")
>>> ini.get('quotes', 'single')
"' a '"
>>> ini.close()
>>> ini = IniVars("set.ini")
>>> L = ini.get()