1 from __future__
import print_function
2 from __future__
import absolute_import
4 import configparser
as ConfigParser
9 from .TkAlExceptions
import AllInOneError
10 from future.utils
import PY3
17 Dictionary which handles updates of values for already existing keys
19 adapteddict[key] returns a list of all values associated with key
20 This dictionary is used in the class `BetterConfigParser` instead of the
21 default `dict_type` of the `ConfigParser` class.
26 collections.OrderedDict.__init__(self, *args, **kwargs)
28 def __setitem__(self, key, value, dict_setitem=collections.OrderedDict.__setitem__):
30 od.__setitem__(i, y) <==> od[i]=y
31 Updating an existing key appends the new value to the old value
32 instead of replacing it.
35 - `key`: key part of the key-value pair
36 - `value`: value part of the key-value pair
37 - `dict_item`: method which is used for finally setting the item
40 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
41 if isinstance(value, (str, unicode)):
43 if item == (key, value.split(
"\n")):
48 dict_setitem(self, key, value)
51 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
52 return [validation[1]
for validation
in self.
validationslist if validation[0] == key]
54 return collections.OrderedDict.__getitem__(self, key)
57 if "__name__" in self
and self[
"__name__"]==
"validation":
60 return collections.OrderedDict.items(self)
64 ConfigParser.ConfigParser.__init__(self,dict_type=AdaptedDict)
72 items = self.
items(section)
73 except ConfigParser.NoSectionError:
83 for option
in self.options( section ):
84 result[option] = self.get( section, option )
85 if "local"+section.title()
in self.sections():
86 for option
in self.options(
"local"+section.title() ):
87 result[option] = self.get(
"local"+section.title(),
89 except ConfigParser.NoSectionError
as section:
90 msg = (
"%s in configuration files. This section is mandatory."
96 result = copy.deepcopy(defaultDict)
97 for option
in demandPars:
99 result[option] = self.get( section, option )
100 except ConfigParser.NoOptionError
as globalSectionError:
101 globalSection =
str( globalSectionError ).
split(
"'" )[-2]
102 splittedSectionName = section.split(
":" )
103 if len( splittedSectionName ) > 1:
104 localSection = (
"local"+section.split(
":" )[0].
title()+
":"
105 +section.split(
":")[1])
107 localSection = (
"local"+section.split(
":" )[0].
title())
108 if self.has_section( localSection ):
110 result[option] = self.get( localSection, option )
111 except ConfigParser.NoOptionError
as option:
112 msg = (
"%s. This option is mandatory."
115 "section '"+globalSection+
"' or", 1)))
118 msg = (
"%s. This option is mandatory."
119 %(
str(globalSectionError).
replace(
":",
"", 1)))
123 except AllInOneError:
130 for section
in self.sections():
131 if "alignment:" in section:
132 alignments.append(
Alignment( section.split(
"alignment:" )[1],
134 names_after_cleaning = [alignment.name
for alignment
in alignments]
137 in collections.Counter(names_after_cleaning).
items()
139 if len(duplicates) > 0:
140 msg =
"Duplicate alignment names after removing invalid characters: "
141 msg +=
", ".
join(duplicates) +
"\n"
142 msg +=
"Please rename the alignments to avoid name clashes."
148 for section
in self.sections():
149 if "compare:" in section:
151 knownSimpleOptions = [
"levels",
"dbOutput",
"moduleList",
"modulesToPlot",
"useDefaultRange",
"plotOnlyGlobal",
"plotPng",
"makeProfilePlots",
152 "dx_min",
"dx_max",
"dy_min",
"dy_max",
"dz_min",
"dz_max",
"dr_min",
"dr_max",
"rdphi_min",
"rdphi_max",
153 "dalpha_min",
"dalpha_max",
"dbeta_min",
"dbeta_max",
"dgamma_min",
"dgamma_max",
154 "jobmode",
"3DSubdetector1",
"3Dubdetector2",
"3DTranslationalScaleFactor",
"jobid",
"multiIOV"])
155 levels = self.get( section,
"levels" )
156 dbOutput = self.get( section,
"dbOutput" )
157 compares[section.split(
":")[1]] = ( levels, dbOutput )
162 "jobmode":
"interactive",
163 "datadir":os.getcwd(),
164 "logdir":os.getcwd(),
166 mandatories = [
"eosdir",]
167 self.
checkInput(
"general", knownSimpleOptions =
list(defaults.keys()) + mandatories )
168 general = self.
getResultingSection(
"general", defaultDict = defaults, demandPars = mandatories )
169 internal_section =
"internals"
170 if not self.has_section(internal_section):
171 self.add_section(internal_section)
172 if not self.has_option(internal_section,
"workdir"):
173 self.
set(internal_section,
"workdir",
"/tmp/$USER")
174 if not self.has_option(internal_section,
"scriptsdir"):
175 self.
set(internal_section,
"scriptsdir",
"")
178 general[
"workdir"] = self.get(internal_section,
"workdir")
179 general[
"scriptsdir"] = self.get(internal_section,
"scriptsdir")
180 for folder
in "workdir",
"datadir",
"logdir",
"eosdir":
181 general[folder] = os.path.expandvars(general[folder])
185 def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[],
188 Method which checks, if the given options in `section` are in the
189 list of `knownSimpleOptions` or match an item of `knownKeywords`.
190 This is basically a check for typos and wrong parameters.
193 - `section`: Section of a configuration file
194 - `knownSimpleOptions`: List of allowed simple options in `section`.
195 - `knownKeywords`: List of allowed keywords in `section`.
199 for option
in self.options( section ):
200 if option
in knownSimpleOptions:
202 elif option.split()[0]
in knownKeywords:
204 elif option
in ignoreOptions:
205 print (
"Ignoring option '%s' in section '[%s]'."
208 msg = (
"Invalid or unknown parameter '%s' in section '%s'!"
211 except ConfigParser.NoSectionError:
214 def set(self, section, option, value=None):
216 ConfigParser.ConfigParser.set(self, section, option, value)
217 except ConfigParser.NoSectionError:
218 self.add_section(section)
219 ConfigParser.ConfigParser.set(self, section, option, value)
221 def items(self, section, raw=False, vars=None):
222 if section ==
"validation":
224 raise NotImplementedError(
"'raw' and 'vars' do not work for betterConfigParser.items()!")
225 items = self._sections[
"validation"].
items()
228 return ConfigParser.ConfigParser.items(self, section, raw, vars)
231 """Write an .ini-format representation of the configuration state."""
232 for section
in self._sections:
233 fp.write(
"[%s]\n" % section)
234 for (key, value)
in self._sections[section].
items():
235 if key ==
"__name__" or not isinstance(value, (str, unicode)):
237 if value
is not None:
239 fp.write(
"%s\n" % (key))
246 OPTCRE_VALIDATION = re.compile(
248 r'(?P<preexisting>preexisting)?'
250 r'\s*(?(preexisting)|'