-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfgparse.py
1762 lines (1500 loc) · 65.9 KB
/
cfgparse.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
"""cfgparse - a powerful, extensible, and easy-to-use configuration parser.
By Dan Gass <[email protected]>
If you have problems with this module, please file bugs through the Source
Forge project page:
http://sourceforge.net/projects/cfgparse
"""
# @future use option note when get error
# @future print file/section/linenumber information when checks fail
# @future - check type='choice' and choices=[] one must have the other
# @future -- do we have a command line --cfgcheck option that expands all configuration and checks all possible keys?
__version__ = "1.00"
__all__ = []
__copyright__ = """
Copyright (c) 2004 by Daniel M. Gass. All rights reserved.
Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved.
Copyright (c) 2002-2004 Python Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import ConfigParser as _ConfigParser
import cStringIO
import os
import re
import sys
import textwrap
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# U T I L I T Y
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# <borrowed file="Lib/optparse.py" version="python2.4" modified="yes">
try:
from gettext import gettext as _
except ImportError:
_ = lambda arg: arg
class HelpFormatter:
"""
Abstract base class for formatting option help. ConfigParser
instances should use one of the HelpFormatter subclasses for
formatting help; by default IndentedHelpFormatter is used.
Instance attributes:
parser : OptionParser
the controlling OptionParser instance
indent_increment : int
the number of columns to indent per nesting level
max_help_position : int
the maximum starting column for option help text
help_position : int
the calculated starting column for option help text;
initially the same as the maximum
width : int
total number of columns for output (pass None to constructor for
this value to be taken from the $COLUMNS environment variable)
level : int
current indentation level
current_indent : int
current indentation level (in columns)
help_width : int
number of columns available for option help text (calculated)
default_tag : str
text to replace with each option's default value, "%default"
by default. Set to false value to disable default value expansion.
option_strings : { Option : str }
maps Option instances to the snippet of help text explaining
the syntax of that option, e.g. "option=VALUE"
"""
NO_DEFAULT_VALUE = "none"
def __init__(self,
indent_increment,
max_help_position,
width,
short_first):
self.parser = None
self.indent_increment = indent_increment
self.help_position = self.max_help_position = max_help_position
if width is None:
try:
width = int(os.environ['COLUMNS'])
except (KeyError, ValueError):
width = 80
width -= 2
self.width = width
self.current_indent = 0
self.level = 0
self.help_width = None # computed later
self.short_first = short_first
self.default_tag = "%default"
self.option_strings = {}
self._short_opt_fmt = "%s %s"
self._long_opt_fmt = "%s=%s"
def set_parser(self, parser):
self.parser = parser
def indent(self):
self.current_indent += self.indent_increment
self.level += 1
def dedent(self):
self.current_indent -= self.indent_increment
assert self.current_indent >= 0, "Indent decreased below 0."
self.level -= 1
def format_usage(self, usage):
raise NotImplementedError, "subclasses must implement"
def format_heading(self, heading):
raise NotImplementedError, "subclasses must implement"
def format_description(self, description):
if not description:
return ""
desc_width = self.width - self.current_indent
indent = " "*self.current_indent
return textwrap.fill(description,
desc_width,
initial_indent=indent,
subsequent_indent=indent) + "\n"
def expand_default(self, option):
if self.parser is None or not self.default_tag:
return option.help
try:
default_value = option.default
except AttributeError:
default_value = None
if default_value is NO_DEFAULT or default_value is None:
default_value = self.NO_DEFAULT_VALUE
return option.help.replace(self.default_tag, str(default_value))
def format_option(self, option):
# The help for each option consists of two parts:
# * the opt strings and metavars
# eg. ("option=VALUE")
# * the user-supplied help string
# eg. ("turn on expert mode", "read data from FILENAME")
#
# If possible, we write both of these on the same line:
# option=VALUE explanation of some option
#
# But if the opt string list is too long, we put the help
# string on a second line, indented to the same column it would
# start in if it fit on the first line.
# thisoption=WAY_TO_LONG
# explanation of the long option
result = []
opts = self.option_strings[option]
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else: # start help on same line as opts
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = self.expand_default(option)
help_lines = textwrap.wrap(help_text, self.help_width)
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
result.extend(["%*s%s\n" % (self.help_position, "", line)
for line in help_lines[1:]])
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)
def store_option_strings(self, parser):
self.indent()
max_len = 0
for opt in parser.option_list:
strings = self.format_option_strings(opt)
self.option_strings[opt] = strings
max_len = max(max_len, len(strings) + self.current_indent)
self.indent()
for group in parser.option_groups:
for opt in group.option_list:
strings = self.format_option_strings(opt)
self.option_strings[opt] = strings
max_len = max(max_len, len(strings) + self.current_indent)
self.dedent()
self.dedent()
self.help_position = min(max_len + 2, self.max_help_position)
self.help_width = self.width - self.help_position
def format_option_strings(self, option):
"""Return a comma-separated list of option strings & metavariables."""
metavar = option.metavar or option.dest.upper()
return '%s=%s' % (option.name,metavar)
class IndentedHelpFormatter (HelpFormatter):
"""Format help with indented section bodies.
"""
# NOTE optparse
def __init__(self,
indent_increment=2,
max_help_position=24,
width=None,
short_first=1):
HelpFormatter.__init__(
self, indent_increment, max_help_position, width, short_first)
def format_usage(self, usage):
return _("usage: %s\n") % usage
def format_heading(self, heading):
return "%*s%s:\n" % (self.current_indent, "", heading)
class TitledHelpFormatter (HelpFormatter):
"""Format help with underlined section headers.
"""
# NOTE optparse
def __init__(self,
indent_increment=0,
max_help_position=24,
width=None,
short_first=0):
HelpFormatter.__init__ (
self, indent_increment, max_help_position, width, short_first)
def format_usage(self, usage):
return "%s %s\n" % (self.format_heading(_("Usage")), usage)
def format_heading(self, heading):
return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
SUPPRESS_HELP = "SUPPRESS"+"HELP"
NO_DEFAULT = ("NO", "DEFAULT")
def _repr(self):
return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
# </borrowed>
NOTHING_FOUND = ("NOTHING","FOUND")
def split_keys(keys):
"""Returns list of keys resulting from keys argument.
--- NO KEYS ---
>>> split_keys( None )
[]
>>> split_keys( [] )
[]
--- STRINGS ---
>>> split_keys( "key1" )
['key1']
>>> split_keys( "key1,key2" )
['key1', 'key2']
>>> split_keys( "key1.key2" )
['key1', 'key2']
>>> split_keys( "key1.key2,key3" )
['key1', 'key2', 'key3']
--- LISTS ---
>>> split_keys( ['key1'] ) # single item
['key1']
>>> split_keys( ['key1','key2'] ) # multiple items
['key1', 'key2']
--- QUOTING ---
These tests check that quotes can be used to protect '.' and ','.
>>> split_keys( "'some.key1','some,key2'" ) # single ticks work
['some.key1', 'some,key2']
>>> split_keys( '"some,key1","some.key2"' ) # double ticks work
['some,key1', 'some.key2']
>>> split_keys( '"some,key1",some.key2' ) # must quote everything
Traceback (most recent call last):
ConfigParserError: Keys not quoted properly. Quotes must surround all keys.
>>> split_keys( "some,key1,'some.key2'" ) # must quote everything
Traceback (most recent call last):
ConfigParserError: Keys not quoted properly. Quotes must surround all keys.
>>> split_keys( "key1,'some.key2'.key3" ) # must quote everything
Traceback (most recent call last):
ConfigParserError: Keys not quoted properly. Quotes must surround all keys.
>>> split_keys('DEFAULT')
[]
>>> split_keys(['DEFAULT'])
[]
"""
if (keys is None) or (keys == 'DEFAULT') or (keys == ['DEFAULT']):
return []
try:
keys = keys.replace('"',"'")
if "'" in keys:
keys = keys.strip("'").split("','")
for key in keys:
if "'" in key:
IMPROPER_QUOTES = "Keys not quoted properly. Quotes must surround all keys."
raise ConfigParserUserError(IMPROPER_QUOTES)
else:
keys = keys.replace('.',',').split(',')
except AttributeError:
pass
return keys
def join_keys(keys,sep=','):
"""
>>> join_keys(['key1'])
'key1'
>>> join_keys(['key1','key2'])
'key1,key2'
>>> join_keys(['key1','key2'],'.')
'key1.key2'
>>> join_keys(['key.1','key2'],'.')
"'key.1','key2'"
>>> join_keys(['key,1','key2'],'.')
"'key,1','key2'"
>>> join_keys([])
'DEFAULT'
"""
if not keys:
return 'DEFAULT'
mash = ''.join(keys)
if '.' in mash or ',' in mash:
quote = "'"
sep = quote + ',' + quote
return quote + sep.join(keys) + quote
return sep.join(keys)
def split_paths(paths):
"""Returns list of paths resulting from paths argument.
--- NO KEYS ---
>>> split_paths( None )
[]
>>> split_paths( [] )
[]
--- STRINGS ---
>>> split_paths( "path1" )
['path1']
>>> split_paths( os.path.pathsep.join(["path1","path2"]) )
['path1', 'path2']
>>> split_paths( "path.1,path.2" )
['path.1', 'path.2']
--- LISTS ---
>>> split_paths( ['path1'] ) # single item
['path1']
>>> split_paths( ['path1','path2'] ) # multiple items
['path1', 'path2']
"""
if paths is None:
return []
try:
return paths.replace(',',os.path.pathsep).split(os.path.pathsep)
except AttributeError:
return paths
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# E X C E P T I O N S
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class ConfigParserError(Exception):
"""Exception associated with the cfgparse module"""
pass
class ConfigParserAppError(Exception):
"""Exception due to application programming error"""
pass
class ConfigParserUserError(Exception):
"""Exception due to user error"""
pass
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# K E Y S
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Keys(object):
"""Prioritizes and stores default configuration keys.
This class is used to store default configuration keys for an instance
of the Config class. The different sources of keys are supported (stored)
by the following methods of this class:
add_cfg_keys -- configuration file specified default keys
add_cmd_keys -- command line option keys
add_env_keys -- environment variable keys
The 'get' method returns a combined list of keys in the following order:
application keys (passed when calling 'get' method)
command line keys
environment variable keys
configuration file keys
a 'DEFAULT' key (always present)
Setup: modify os module to fake out environment variable gets
>>> _getenv = os.getenv
>>> def getenv(variable,default):
... if variable == 'VAR12':
... return 'env1,env2'
... elif variable == 'VAR3':
... return 'env3'
... elif variable == 'VAR4':
... return 'env4'
... else:
... return default
>>> os.getenv = getenv
Case 1: normal string lists of keys
>>> k = Keys()
>>> k.add_env_keys('VAR12,VAR3') # this has effect
>>> k.add_env_keys('VAR_NONE') # no effect
>>> k.add_cfg_keys('cfg1,cfg2')
>>> k.add_cmd_keys('cmd1.cmd2')
>>> k.add_env_keys('VAR12') # no effect (already read)
>>> k.get('app1,app2')
['app1', 'app2', 'cmd1', 'cmd2', 'env1', 'env2', 'env3', 'cfg1', 'cfg2', 'DEFAULT']
Case 2: extend lists using other key input flavors just to make sure each
method uses split_keys()
>>> k.add_env_keys(['VAR4']) # this has effect
>>> k.add_cfg_keys(['cfg3'])
>>> k.add_cmd_keys(['cmd3'])
>>> k.get(['app'])
['app', 'cmd1', 'cmd2', 'cmd3', 'env1', 'env2', 'env3', 'env4', 'cfg1', 'cfg2', 'cfg3', 'DEFAULT']
Teardown: restore os module
>>> os.getenv = _getenv
"""
def __init__(self):
"""Initialize Keys Instance"""
self.cmd_keys = []
self.env_keys = []
self.cfg_keys = []
self.env_vars = []
def __repr__(self):
"""Return string representation of object"""
return ','.join(self.get([]))
def add_cmd_keys(self,keys):
"""Store keys from command line interface
keys -- list of keys (typically from the command line) to store. May
be a list of keys or a string with keys separated by commas.
Use any value which evaluates False when no keys.
"""
self.cmd_keys.extend(split_keys(keys))
def add_env_keys(self,variables):
"""Store keys from invoking shell's environment variable
variable -- (string) environment variable name from which to obtain
keys to store
"""
variables = split_keys(variables)
for variable in variables:
# only add keys from shell environment variable if we haven't already
if variable not in self.env_vars:
# save key variable name so we can't add same keys twice
self.env_vars.append(variable)
# if shell environment variable has a option save it
keys = os.getenv(variable,None)
if keys is not None:
self.env_keys.extend(split_keys(keys))
def add_cfg_keys(self,keys):
"""Store keys from user's configuration file.
keys -- list of keys (from user's configuration file) to store. May
be a list of keys or a string with keys separated by comma.
Use any value which evaluates False when no keys.
"""
self.cfg_keys.extend(split_keys(keys))
def get(self,keys=None):
"""Return prioritized list of stored configuration keys
keys -- list of differentiator keys. May be a list of keys or a string
with keys separated by commas. Use any valid which evaluates
False when no keys.
"""
keys = split_keys(keys)
return (keys + self.cmd_keys + self.env_keys + self.cfg_keys +
['DEFAULT'])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# O P T I O N V A L U E
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Value(object):
"""Used to store option settings in the blended option dictionary.
Needed to be able to tie the option setting back to the configuration
file for better error reporting and for round trip get/set/write
capability."""
def __init__(self,value,parent,section_keys):
"""Initializes instance."""
self.value = value
self.parent = parent
self.section_keys = section_keys
def set(self,value):
"""Sets option setting to 'value' argument passed in.
By default configuration file parsers to do not support round trip.
If they do they should subclass Value() and override this method
"""
self.value = value
def get_roots(self):
return ["File: %s" % self.parent.get_filename(),
"Section: [%s]" % join_keys(self.section_keys,'.')]
def __str__(self):
"""Returns string representation of the setting."""
return str(self.value)
__repr__ = _repr
def get(self):
"""Returns the option setting."""
return self.value
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# O P T I O N
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Option(object):
"""Options added to configuration parser are an instance of this class."""
def __init__(self,**kwargs):
"""Instance initializer.
Arguments:
kwargs -- dictionary with keys parser,name,type,default,help,check,keys,
choices (see add_option of OptionContainer)
"""
self.__dict__.update(kwargs)
if self.dest is None:
self.dest = self.name
if self.type not in self.conversions:
TYPE_DOES_NOT_EXIST = "type '%s' is not valid" % self.type
raise ConfigParserAppError(TYPE_DOES_NOT_EXIST)
# help cross reference for options partnered with OptionParser
self._help_xref = ""
self.note = None
def __str__(self):
"""Returns string representation of the option."""
return self.name
__repr__ = _repr
def add_note(self,note):
"""Adds 'note' argument text to configuration parser help text and
to error messages associated with this option."""
self.parser.add_note(note)
self.note = note
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Get
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def _get(self,keys):
# Read any pending configuration files at the top level in order to
# pick up user's default keys in those files.
self.parser.parse_pending_cfg([])
keys = split_keys(keys) + self.keys
keys = self.parser.keys.get(keys)
# Get the option's dictionary from the configuration parser so that
# any pending configuration files that are needed are read.
option = self.parser.get_option_dict(self.name,keys)
# When keys are given as an argument, we don't have the constraints
# of an exact match like a section. Instead we use the default
# key list (highest priority key first) to walk the option
# dictionary. At each level of the dictionary we look for the
# highest priority key and if it exists we move down a level
# otherwise the remaining keys are checked in order of priority.
def walk_option(option):
if option.__class__ is dict:
for key in keys:
if key in option:
v = walk_option(option[key])
if v.__class__ is not dict:
return v
if isinstance(option,Value):
return option
else:
return NOTHING_FOUND
return walk_option(option)
def get(self,keys=[],errors=None):
"""Returns option value associated with 'keys' argument or options
option value using 'keys' argument (in combination with other keys).
keys -- name of keys to obtain option value from
Note:
If option is partnered with an optparse option and that option
is present, the optparse option will take priority and be returned.
"""
warnings = []
option = NOTHING_FOUND
def convert(value,option_help):
# Do conversion to the type application specified
value,warning = self.conversions[self.type](self,value)
# Do final check using application check function if supplied
if not warning and self.check is not None:
value,warning = self.check(value)
if warning:
try:
warnings.extend(option_help.get_roots())
except AttributeError:
warnings.append(option_help)
warnings.append(warning)
return value
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Priority 1: Get option from optparse partner (command line)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if self.dest in self.parser.optpar_option_partners:
option = getattr(self.parser.optparser_options,self.dest,None)
if option is None:
option = NOTHING_FOUND
else:
option = convert(option,'command line option')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Priority 2: Get a default option
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if option is NOTHING_FOUND and not warnings:
option = self._get(keys)
if option is not NOTHING_FOUND:
value = option.get()
option = convert(value,option)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Priority 3: Use default specified when adding the option
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if option is NOTHING_FOUND and not warnings:
if self.default is not NO_DEFAULT:
option = self.default
else:
warnings.append('No valid default found.')
keys = split_keys(keys) + self.keys
keys = self.parser.keys.get(keys)
warnings.append('keys=%s' % ','.join(keys))
if warnings:
lines = ['Option: %s' % self.name] + warnings
lines = '\n'.join(lines) + '\n'
if errors is not None:
errors.append(lines)
else:
# not coming back
self.parser.write_errors([lines])
return option
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Conversions
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def convert_choice(self,value):
if value in self.choices:
return value,None
else:
choices = str(self.choices).strip('[]()')
warning = "Invalid choice '%s', must be one of: %s" % (value,choices)
return None,warning
def convert_complex(self,value):
try:
return complex(value),None
except ValueError:
return None,"Cannot convert '%s' to a complex number" % (value)
def convert_float(self,value):
try:
return float(value),None
except ValueError:
return None,"Cannot convert '%s' to a float" % (value)
def convert_int(self,value):
try:
return int(value),None
except ValueError:
return None,"Cannot convert '%s' to an integer" % (value)
def convert_long(self,value):
try:
return long(value),None
except ValueError:
return None,"Cannot convert '%s' to a long" % (value)
def convert_string(self,value):
try:
return str(value),None
except ValueError:
return None,"Cannot convert '%s' to a string" % (value)
def convert_nothing(self,value):
return value,None
conversions = {
'choice' : convert_choice,
'complex' : convert_complex,
'float' : convert_float,
'int' : convert_int,
'long' : convert_long,
'string' : convert_string,
None : convert_nothing,
}
def set(self,value,cfgfile=None,keys=None):
value = str(value)
if cfgfile:
if keys is not None:
keys = split_keys(keys)
else:
keys = self.keys
cfgfile.set_option(self.name,value,keys,self.help)
else:
keys = split_keys(keys) + self.keys
keys = self.parser.keys.get(keys)
option = self._get(keys)
if option is NOTHING_FOUND:
NOTHING_TO_SET = '\n'.join([
'ERROR: No option found',
'option name: %s' % self.name,
'keys: %s' % keys])
raise ConfigParserUserError(NOTHING_TO_SET)
else:
option.set(value)
cfgfile = option.parent
return cfgfile
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# O P T I O N C O N T A I N E R B A S E C L A S S E S
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class OptionContainer(object):
OptionClass = Option
def __init__(self,description):
self.option_list = []
self.set_description(description)
def set_description(self, description):
self.description = description
def get_description(self):
return self.description
def add_option(self,name,help=None,type=None,choices=None,dest=None,metavar=None,default=NO_DEFAULT,check=None,keys=None):
"""
name -- configuration file option name (used same as optparse)
type -- choices similar to optparse (used same as optparse)
default -- default value (used same as optparse)
help -- help string (used same as optparse)
dest -- option database attribute name (used same as optparse)
check -- check function
keys -- name of keys to obtain option from
choices -- list of choices (used same as optparse)
metavar -- FUTURE
"""
if dest is None:
dest = name
kwargs = {
'parser' : self.parser,
'name' : name,
'type' : type,
'help' : help,
'dest' : dest,
'check' : check,
'keys' : split_keys(keys),
'choices' : choices,
'metavar' : metavar,
'default' : default}
option = self.OptionClass(**kwargs)
self.parser.master_option_list.append(option)
self.parser.master_option_dict[dest] = option
self.option_list.append(option)
return option
# <borrowed file="Lib/optparse.py" version="python2.4" modified="yes">
def format_option_help(self, formatter):
if not self.option_list:
return ""
result = []
for option in self.option_list:
if not option.help == SUPPRESS_HELP:
result.append(formatter.format_option(option))
return "".join(result)
def format_description(self, formatter):
return formatter.format_description(self.get_description())
def format_help(self, formatter):
result = []
if self.description:
result.append(self.format_description(formatter))
if self.option_list:
result.append(self.format_option_help(formatter))
return "\n".join(result)
# </borrowed>
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# O P T I O N G R O U P
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class OptionGroup(OptionContainer):
def __init__(self,parser,title,description):
OptionContainer.__init__(self,description)
self.parser = parser
self.title = title
# <borrowed file="Lib/optparse.py" version="python2.4" modified="yes">
def set_title (self, title):
self.title = title
# -- Help-formatting methods ---------------------------------------
def format_help (self, formatter):
result = formatter.format_heading(self.title)
formatter.indent()
result += OptionContainer.format_help(self, formatter)
formatter.dedent()
return result
# </borrowed>
class ConfigFile(object):
def __init__(self,cfgfile,content,keys,parent,parser):
p,n = os.path.split(cfgfile)
try:
p = os.path.join(parent.path,p)
except AttributeError:
pass
p = os.path.abspath(p)
self.path = p
self.filename = n
self.content = content
self.underkeys = keys
self.parent = parent
self.parser = parser
self.parsed = False
def get_filename(self):
return os.path.join(self.path,self.filename)
def __str__(self):
return os.path.join(self.path,self.filename)
__repr__ = _repr
def get_as_str(self):
content = self.content
if content is None:
cfgfile = os.path.join(self.path,self.filename)
f = open(cfgfile)
content = f.read()
f.close()
else:
try:
content = self.content.read()
except AttributeError:
pass
return content
def parse_if_unparsed(self):
if not self.parsed:
# The parent is important in that it is used error messages but more
# importantly when getting ready to read a configuration script we
# must set the current directory of the parent so relative path
# specification of any configuration file works out.
try:
parent_path = self.parent.path
except AttributeError:
parent_path = os.getcwd()
# Save so we can restore after we are done
cwd = os.getcwd()
# Make sure file is present
cfgfile = os.path.join(self.path,self.filename)
if not self.content and not os.path.exists(cfgfile):
lines = ["File not found: '%s'" % cfgfile]
# remember, top level configuration file parent is just the
# current working directory when ConfigParser was instantiated
# FUTURE parent info in here too
FILE_NOT_FOUND = '\n'.join(lines)
raise ConfigParserUserError(FILE_NOT_FOUND)
# Change the current working directory to where the configuration
# script is (to accomodate Python configuraton scripts so that it
# can use os.getcwd() to determine its location).
os.chdir(self.path)
self.parse()
# Restore
os.chdir(cwd)
# Mark it as done so it isn't parsed twice
self.parsed = True
class ConfigFilePy(ConfigFile):
def parse(self):
underkeys = self.underkeys
parser = self.parser
# Parsing can be easy!
options = {}
if self.content is None:
cfgfile = os.path.join(self.path,self.filename)
execfile(cfgfile,options)
else:
exec self.get_as_str() in options
# Update the keys. "KEYS_VARIABLE" option used to specify the
# environment variable that holds additional default keys, if
# present get keys from the environment using it. If reading
# configuration file that is being included under a key, don't
# bother with its keys because it would get too confusing.
if not underkeys:
try:
parser.keys.add_env_keys(options['KEYS_VARIABLE'])
del options['KEYS_VARIABLE']
except KeyError:
pass