14 Generate _confDb.py files for ConfigurableUser classes.
16 from __future__
import division
23 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: \
30 logging.log(logging.VERBOSE, msg, *args, **kwargs)
35 Check if any of the class names in 'basenames' is anywhere in the base
36 classes of the class 'derived'.
37 If 'derived' _is_ one in 'basenames', returns False.
39 'basenames' can be a string or an iterable (of strings).
41 if isinstance(basenames, str):
42 basenames = (basenames, )
43 for b
in derived.__bases__:
44 if b.__name__
in basenames:
54 Equivalent to GaudiKernel.ConfigurableDb.loadConfigurableDb(), but does a
55 deep search and executes the '*.confdb' files instead of importing them.
57 log = GaudiKernel.ConfigurableDb.log
58 from os.path
import join
as path_join
64 f
for f
in glob(path_join(path,
'*',
'*.confdb'))
69 for root, _, files
in os.walk(build_dir):
71 os.path.join(root, f)
for f
in files
if f.endswith(
'.confdb')
74 pathlist = os.getenv(
"LD_LIBRARY_PATH",
"").split(os.pathsep)
75 for path
in filter(os.path.isdir, pathlist):
78 path_join(path, f)
for f
in os.listdir(path)
79 if f.endswith(
'.confdb')
83 for confDb
in set(confDbFiles):
84 log.debug(
"\t-loading [%s]..." % confDb)
86 cfgDb._loadModule(confDb)
87 except Exception
as err:
90 log.warning(
"Could not load file [%s] !", confDb)
91 log.warning(
"Reason: %s", err)
98 Find in the module 'modulename' all the classes that derive from ConfigurableUser.
99 Return the list of the names.
100 The flag mayNotExist is used to choose the level of the logging message in case
101 the requested module does not exist.
104 oldpath = list(sys.path)
106 moduleelements = modulename.split(
'.')
107 if len(moduleelements) > 1:
108 moddir = os.sep.join([root] + moduleelements[:-1])
112 shortmodname = moduleelements[-1]
114 if not os.path.exists(os.path.join(moddir, shortmodname) +
".py"):
115 msg =
"Module %s does not exist" % modulename
123 sys.path.insert(0, moddir)
124 logging.verbose(
"sys.path prepended with %r", sys.path[0])
126 logging.info(
"Looking for ConfigurableUser in %r", modulename)
129 logging.verbose(
"importing %s", shortmodname)
130 exec(
"import %s as mod" % shortmodname, g, l)
133 logging.verbose(
"restoring old sys.path")
136 if "__all__" in dir(mod)
and mod.__all__:
139 all = [n
for n
in dir(mod)
if not n.startswith(
"_")]
142 cfg = cfgDb.get(name)
143 if cfg
and cfg[
"module"] != modulename:
145 logging.verbose(
"Object %r already found in module %r", name,
148 t = getattr(mod, name)
150 t, (
'ConfigurableUser',
'SuperAlgorithm')):
152 logging.verbose(
"Found %r", result)
157 from optparse
import OptionParser
158 parser = OptionParser(
159 prog=os.path.basename(sys.argv[0]),
160 usage=
"%prog [options] <PackageName> [<Module1> ...]")
167 "output file for confDb data [default = '../genConfDir/<PackageName>_user_confDb.py']."
174 help=
"root directory of the python modules [default = '../python'].")
179 help=
"print some debugging information")
183 help=
"print more debugging information")
188 "build directory where to look for .confdb files (search all subdirectories)"
190 parser.set_defaults(root=os.path.join(
"..",
"python"))
192 opts, args = parser.parse_args()
195 log_level = logging.DEBUG
197 log_level = logging.VERBOSE
199 log_level = logging.INFO
if os.environ.get(
200 'VERBOSE')
else logging.WARNING
202 format=
"%(levelname)s: %(message)s",
207 parser.error(
"PackageName is required")
209 package_name = args.pop(0)
211 usingConvention =
False
214 args = [package_name +
".Configuration"]
215 usingConvention =
True
217 genConfDir = os.path.join(
"..", os.environ.get(
"CMTCONFIG",
""),
219 if not os.path.exists(genConfDir):
220 genConfDir = os.path.join(
"..",
"genConfDir")
223 outputfile = os.path.join(genConfDir, package_name +
'_user.confdb')
225 outputfile = opts.output
230 import Gaudi.Configurables
231 Gaudi.Configurables.ignoreMissingConfigurables =
True
240 sys.path.insert(0, genConfDir)
241 sys.path.insert(0, os.path.join(
"..",
"python"))
242 localConfDb = os.path.join(genConfDir, package_name,
243 package_name +
'.confdb')
244 if os.path.exists(localConfDb):
245 cfgDb._loadModule(localConfDb)
247 package_module = __import__(package_name)
248 package_module.__path__.insert(
249 0, os.path.join(genConfDir, package_name))
259 mod, root=opts.root, mayNotExist=usingConvention)
263 "Cannot import module %r:\n%s", mod,
264 traceback.format_exc().rstrip())
271 configurable=m, package=
'None', module=
'None', lib=
'None')
272 elif not usingConvention:
274 "Specified module %r does not contain ConfigurableUser specializations",
278 logging.info(
"ConfigurableUser found:\n%s", pformat(cus))
280 output =
"""## -*- ascii -*-
281 # db file automatically generated by %s on: %s
282 """ % (parser.prog, time.asctime())
286 output +=
"%s %s %s\n" % (mod,
'None', cu)
289 output +=
"## %s\n" % package_name
290 elif usingConvention:
291 logging.info(
"No ConfigurableUser found")
292 output = (
"# db file automatically generated by %s on: %s\n"
293 "# No ConfigurableUser specialization in %s\n") % (
294 parser.prog, time.asctime(), package_name)
296 logging.error(
"No ConfigurableUser specialization found")
300 output_dir = os.path.dirname(outputfile)
302 logging.info(
"Creating directory %r", output_dir)
303 os.makedirs(output_dir, 0o755)
304 except OSError
as err:
306 if err.errno == errno.EEXIST:
313 logging.verbose(
"Writing confDb data to %r", outputfile)
314 open(outputfile,
"w").write(output)
318 if __name__ ==
'__main__':