13 Generate _confDb.py files for ConfigurableUser classes.
15 from __future__
import division
22 from pprint
import pformat
27 logging.VERBOSE = (logging.INFO + logging.DEBUG) // 2
28 logging.addLevelName(logging.VERBOSE,
"VERBOSE")
29 logging.verbose =
lambda msg, *args, **kwargs: logging.log(
30 logging.VERBOSE, msg, *args, **kwargs
36 Check if any of the class names in 'basenames' is anywhere in the base
37 classes of the class 'derived'.
38 If 'derived' _is_ one in 'basenames', returns False.
40 'basenames' can be a string or an iterable (of strings).
42 if isinstance(basenames, str):
43 basenames = (basenames,)
44 for b
in derived.__bases__:
45 if b.__name__
in basenames:
55 Equivalent to GaudiKernel.ConfigurableDb.loadConfigurableDb(), but does a
56 deep search and executes the '*.confdb' files instead of importing them.
58 log = GaudiKernel.ConfigurableDb.log
59 from os.path
import join
as path_join
66 f
for f
in glob(path_join(path,
"*",
"*.confdb"))
if os.path.isfile(f)
70 for root, _, files
in os.walk(build_dir):
72 os.path.join(root, f)
for f
in files
if f.endswith(
".confdb")
75 pathlist = os.getenv(
"LD_LIBRARY_PATH",
"").split(os.pathsep)
76 for path
in filter(os.path.isdir, pathlist):
80 path_join(path, f)
for f
in os.listdir(path)
if f.endswith(
".confdb")
84 ignored_files = set(os.environ.get(
"CONFIGURABLE_DB_IGNORE",
"").split(
","))
86 for confDb
in set(confDbFiles):
87 if confDb
in ignored_files
or (
89 and os.path.basename(confDb) == (
"{}.confdb".
format(project_name))
92 log.debug(
"\t-ignoring [%s]", confDb)
94 ignored_files.add(confDb)
96 log.debug(
"\t-loading [%s]...", confDb)
98 cfgDb._loadModule(confDb)
99 except Exception
as err:
102 log.warning(
"Could not load file [%s] !", confDb)
103 log.warning(
"Reason: %s", err)
106 os.environ[
"CONFIGURABLE_DB_IGNORE"] =
",".join(ignored_files)
112 Find in the module 'modulename' all the classes that derive from ConfigurableUser.
113 Return the list of the names.
114 The flag mayNotExist is used to choose the level of the logging message in case
115 the requested module does not exist.
118 oldpath = list(sys.path)
120 moduleelements = modulename.split(
".")
121 if len(moduleelements) > 1:
122 moddir = os.sep.join([root] + moduleelements[:-1])
126 shortmodname = moduleelements[-1]
128 if not os.path.exists(os.path.join(moddir, shortmodname) +
".py"):
129 msg =
"Module %s does not exist" % modulename
137 sys.path.insert(0, moddir)
138 logging.verbose(
"sys.path prepended with %r", sys.path[0])
140 logging.info(
"Looking for ConfigurableUser in %r", modulename)
143 logging.verbose(
"importing %s", shortmodname)
144 exec(
"import %s as mod" % shortmodname, g, l)
147 logging.verbose(
"restoring old sys.path")
150 if "__all__" in dir(mod)
and mod.__all__:
153 all = [n
for n
in dir(mod)
if not n.startswith(
"_")]
156 cfg = cfgDb.get(name)
157 if cfg
and cfg[
"module"] != modulename:
159 logging.verbose(
"Object %r already found in module %r", name, cfg[
"module"])
161 t = getattr(mod, name)
163 t, (
"ConfigurableUser",
"SuperAlgorithm")
166 logging.verbose(
"Found %r", result)
171 from optparse
import OptionParser
173 parser = OptionParser(
174 prog=os.path.basename(sys.argv[0]),
175 usage=
"%prog [options] <PackageName> [<Module1> ...]",
182 help=
"output file for confDb data [default = '../genConfDir/<PackageName>_user_confDb.py'].",
189 help=
"root directory of the python modules [default = '../python'].",
192 "-v",
"--verbose", action=
"store_true", help=
"print some debugging information"
195 "--debug", action=
"store_true", help=
"print more debugging information"
200 help=
"build directory where to look for .confdb files (search all subdirectories)",
205 help=
"name of the current project (used to exclude spurious versions of the .confdb file for the current project)",
207 parser.set_defaults(root=os.path.join(
"..",
"python"))
209 opts, args = parser.parse_args()
212 log_level = logging.DEBUG
214 log_level = logging.VERBOSE
216 log_level = logging.INFO
if os.environ.get(
"VERBOSE")
else logging.WARNING
218 format=
"%(levelname)s: %(message)s", stream=sys.stdout, level=log_level
222 parser.error(
"PackageName is required")
224 package_name = args.pop(0)
226 usingConvention =
False
229 args = [package_name +
".Configuration"]
230 usingConvention =
True
232 genConfDir = os.path.join(
"..", os.environ.get(
"CMTCONFIG",
""),
"genConfDir")
233 if not os.path.exists(genConfDir):
234 genConfDir = os.path.join(
"..",
"genConfDir")
237 outputfile = os.path.join(genConfDir, package_name +
"_user.confdb")
239 outputfile = opts.output
244 import Gaudi.Configurables
246 Gaudi.Configurables.ignoreMissingConfigurables =
True
255 sys.path.insert(0, genConfDir)
256 sys.path.insert(0, os.path.join(
"..",
"python"))
257 localConfDb = os.path.join(genConfDir, package_name, package_name +
".confdb")
258 if os.path.exists(localConfDb):
259 cfgDb._loadModule(localConfDb)
261 package_module = __import__(package_name)
262 package_module.__path__.insert(0, os.path.join(genConfDir, package_name))
276 "Cannot import module %r:\n%s", mod, traceback.format_exc().rstrip()
283 cfgDb.add(configurable=m, package=
"None", module=
"None", lib=
"None")
284 elif not usingConvention:
286 "Specified module %r does not contain ConfigurableUser specializations",
291 logging.info(
"ConfigurableUser found:\n%s", pformat(cus))
293 output =
"""## -*- ascii -*-
294 # db file automatically generated by %s on: %s
302 output +=
"%s %s %s\n" % (mod,
"None", cu)
305 output +=
"## %s\n" % package_name
306 elif usingConvention:
307 logging.info(
"No ConfigurableUser found")
309 "# db file automatically generated by %s on: %s\n"
310 "# No ConfigurableUser specialization in %s\n"
311 ) % (parser.prog, time.asctime(), package_name)
313 logging.error(
"No ConfigurableUser specialization found")
317 output_dir = os.path.dirname(outputfile)
319 logging.info(
"Creating directory %r", output_dir)
320 os.makedirs(output_dir, 0o755)
321 except OSError
as err:
324 if err.errno == errno.EEXIST:
331 logging.verbose(
"Writing confDb data to %r", outputfile)
332 open(outputfile,
"w").write(output)
336 if __name__ ==
"__main__":