Gaudi Framework, version v24r2

Home   Generated: Wed Dec 4 2013
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
genconf.cpp
Go to the documentation of this file.
1 #ifdef _WIN32
2 // Disable a warning in Boost program_options headers:
3 // inconsistent linkage in program_options/variables_map.hpp
4 #pragma warning ( disable : 4273 )
5 
6 // Avoid conflicts between windows and the message service.
7 #define NOMSG
8 #define NOGDI
9 #endif
10 
11 #ifdef __ICC
12 // disable icc warning #279: controlling expression is constant
13 // ... a lot of noise produced by the boost/filesystem/operations.hpp
14 #pragma warning(disable:279)
15 // Avoid icc remark #193: zero used for undefined preprocessing identifier "_MSC_VER"
16 #if !defined(_WIN32) && !defined(_MSC_VER)
17 #define _MSC_VER 0
18 #endif
19 #endif
20 
21 #include "boost/program_options.hpp"
22 // the hack for remark #193 is needed only for program_options and breaks regex.
23 #if defined(__ICC) && !defined(_WIN32) && (_MSC_VER == 0)
24 #undef _MSC_VER
25 #endif
26 
27 // Include files----------------------------------------------------------------
28 #include "boost/filesystem/operations.hpp"
29 #include "boost/filesystem/exception.hpp"
30 #include "boost/filesystem/convenience.hpp"
31 #include "boost/algorithm/string/split.hpp"
32 #include "boost/algorithm/string/classification.hpp"
33 #include "boost/algorithm/string/trim.hpp"
34 #include "boost/algorithm/string/case_conv.hpp"
35 #include "boost/format.hpp"
36 #include "boost/regex.hpp"
37 
38 #include "GaudiKernel/System.h"
40 #include "GaudiKernel/IProperty.h"
41 #include "GaudiKernel/IAppMgrUI.h"
42 #include "GaudiKernel/IAlgorithm.h"
43 #include "GaudiKernel/IAlgTool.h"
44 #include "GaudiKernel/IAuditor.h"
45 #include "GaudiKernel/IAppMgrUI.h"
46 #include "GaudiKernel/Service.h"
47 #include "GaudiKernel/Bootstrap.h"
48 #include "GaudiKernel/SmartIF.h"
49 #include "GaudiKernel/HashMap.h"
51 
52 #include "GaudiKernel/Time.h"
53 
54 #include "Reflex/PluginService.h"
55 #include "Reflex/Reflex.h"
56 #include "Reflex/SharedLibrary.h"
57 
58 #include "RVersion.h"
59 
60 #include <algorithm>
61 #include <iostream>
62 #include <fstream>
63 #include <sstream>
64 #include <exception>
65 #include <set>
66 #include <vector>
67 
68 
69 #include "DsoUtils.h"
70 
71 
72 
73 namespace po = boost::program_options;
74 namespace fs = boost::filesystem;
75 
76 using namespace std;
77 using namespace ROOT::Reflex;
78 
79 // useful typedefs
82 
83 namespace {
84  const std::string py_tab = " ";
85 
88  const boost::regex pythonIdentifier("^[a-zA-Z_][a-zA-Z0-9_]*$");
89 }
90 
92 {
94  string m_pkgName;
95 
99 
102 
106 
112 
119 
120 public:
121  configGenerator( const string& pkgName,
122  const string& outputDirName ) :
123  m_pkgName ( pkgName ),
124  m_outputDirName ( outputDirName ),
125  m_pyBuf ( ),
126  m_importGaudiHandles( false ),
127  m_dbBuf ( ),
128  m_configurable ( )
129  {}
130 
135  int genConfig( const Strings_t& modules, const string& userModule );
136 
138  void setConfigurableModule( const std::string& moduleName )
139  {
140  m_configurable[ "Module" ] = moduleName;
141  }
142 
144  void setConfigurableDefaultName( const std::string& defaultName )
145  {
146  m_configurable[ "DefaultName" ] = defaultName;
147  }
148 
150  void setConfigurableAlgorithm( const std::string& cfgAlgorithm )
151  {
152  m_configurable[ "Algorithm" ] = cfgAlgorithm;
153  }
154 
156  void setConfigurableAlgTool( const std::string& cfgAlgTool )
157  {
158  m_configurable[ "AlgTool" ] = cfgAlgTool;
159  }
160 
162  void setConfigurableAuditor( const std::string& cfgAuditor )
163  {
164  m_configurable[ "Auditor" ] = cfgAuditor;
165  }
166 
168  void setConfigurableService( const std::string& cfgService )
169  {
170  m_configurable[ "Service" ] = cfgService;
171  m_configurable[ "ApplicationMgr" ] = cfgService;
172  }
173 
174 private:
175  int genComponent( const std::string& libName,
176  const std::string& componentName,
177  const std::string& componentType,
178  const vector<Property*>& properties );
179  void genImport( std::ostream& s, const boost::format& frmt,std::string indent);
180  void genHeader( std::ostream& pyOut, std::ostream& dbOut );
181  void genBody( std::ostream& pyOut,
182  std::ostream& dbOut ) {
183  pyOut << m_pyBuf.str() << flush;
184  dbOut << m_dbBuf.str() << flush;
185  }
186  void genTrailer( std::ostream& pyOut,
187  std::ostream& dbOut );
188 
190  void pythonizeValue( const Property* prop,
191  string& pvalue,
192  string& ptype );
193 
195  void pythonizeName( string& name );
196 };
197 
198 int createAppMgr();
199 
200 //--- Command main program-----------------------------------------------------
201 int main ( int argc, char** argv )
202 //-----------------------------------------------------------------------------
203 {
204  fs::path pwd = fs::initial_path();
205  fs::path out;
206  Strings_t libs;
207  std::string pkgName;
208  std::string userModule;
209 
210  // declare a group of options that will be allowed only on command line
211  po::options_description generic("Generic options");
212  generic.add_options()
213  ("help,h",
214  "produce this help message")
215  ("package-name,p",
216  po::value<string>(),
217  "name of the package for which we create the configurables file")
218  ("input-libraries,i",
219  po::value<string>(),
220  "libraries to extract the component configurables from")
221  ("input-cfg,c",
222  po::value<string>(),
223  "path to the cfg file holding the description of the Configurable base "
224  "classes, the python module holding the Configurable definitions, etc...")
225  ("output-dir,o",
226  po::value<string>()->default_value("../genConf"),
227  "output directory for genconf files.")
228  ("debug-level,d",
229  po::value<int>()->default_value(0),
230  "debug level")
231  ("load-library,l",
232  po::value< Strings_t >()->composing(),
233  "preloading library")
234  ("user-module,m",
235  po::value<string>(),
236  "user-defined module to be imported by the genConf-generated one")
237  ;
238 
239  // declare a group of options that will be allowed both on command line
240  // _and_ in configuration file
241  po::options_description config("Configuration");
242  config.add_options()
243  ("configurable-module",
244  po::value<string>()->default_value("AthenaCommon"),
245  "Name of the module holding the configurable classes")
246  ("configurable-default-name",
247  po::value<string>()->default_value("Configurable.DefaultName"),
248  "Default name for the configurable instance")
249  ("configurable-algorithm",
250  po::value<string>()->default_value("ConfigurableAlgorithm"),
251  "Name of the configurable base class for Algorithm components")
252  ("configurable-algtool",
253  po::value<string>()->default_value("ConfigurableAlgTool"),
254  "Name of the configurable base class for AlgTool components")
255  ("configurable-auditor",
256  po::value<string>()->default_value("ConfigurableAuditor"),
257  "Name of the configurable base class for Auditor components")
258  ("configurable-service",
259  po::value<string>()->default_value("ConfigurableService"),
260  "Name of the configurable base class for Service components")
261  ;
262 
263  po::options_description cmdline_options;
264  cmdline_options.add(generic).add(config);
265 
266  po::options_description config_file_options;
267  config_file_options.add(config);
268 
269  po::options_description visible("Allowed options");
270  visible.add(generic).add(config);
271 
272  po::variables_map vm;
273 
274  try {
275  po::store( po::command_line_parser(argc, argv).
276  options(cmdline_options).run(),
277  vm );
278 
279  po::notify(vm);
280 
281  // try to read configuration from the optionally given configuration file
282  if( vm.count("input-cfg") ) {
283  string cfgFileName = vm["input-cfg"].as<string>();
284  cfgFileName = fs::system_complete( fs::path( cfgFileName ) ).string();
285  std::ifstream ifs( cfgFileName.c_str() );
286  po::store( parse_config_file( ifs, config_file_options ), vm );
287  }
288 
289  po::notify(vm);
290  }
291  catch ( po::error& err ) {
292  cout << "ERR0R: error detected while parsing command options: "<< err.what() << endl;
293  return EXIT_FAILURE;
294  }
295 
296  //--- Process command options -----------------------------------------------
297  if( vm.count("help")) {
298  cout << visible << endl;
299  return EXIT_FAILURE;
300  }
301 
302  if( vm.count("package-name") ) {
303  pkgName = vm["package-name"].as<string>();
304  }
305  else {
306  cout << "ERROR: 'package-name' required" << endl;
307  cout << visible << endl;
308  return EXIT_FAILURE;
309  }
310 
311  if( vm.count("user-module") ) {
312  userModule = vm["user-module"].as<string>();
313  cout << "INFO: will import user module " << userModule << endl;
314  }
315 
316  if( vm.count("input-libraries") ) {
317  // re-shape the input arguments:
318  // - removes spurious spaces,
319  // - split into tokens.
320  Strings_t inputLibs;
321  {
322  string tmp = vm["input-libraries"].as<string>();
323  boost::trim(tmp);
324  boost::split( inputLibs, tmp,
325  boost::is_any_of(" "),
326  boost::token_compress_on );
327  }
328 
329  //
330  libs.reserve( inputLibs.size() );
331  for ( Strings_t::const_iterator iLib = inputLibs.begin();
332  iLib != inputLibs.end();
333  ++iLib ) {
334  std::string lib = fs::path(*iLib).stem().string();
335  if ( 0 == lib.find("lib") ) {
336  lib = lib.substr(3); // For *NIX remove "lib"
337  }
338  // remove duplicates
339  if ( !lib.empty() &&
340  std::find( libs.begin(), libs.end(), lib ) == libs.end() ) {
341  libs.push_back( lib );
342  }
343  } //> end loop over input-libraries
344  if ( libs.empty() ) {
345  cout << "ERROR: input component library(ies) required !\n"
346  << "ERROR: 'input-libraries' argument was ["
347  << vm["input-libraries"].as<string>()
348  << "]"
349  << endl;
350  return EXIT_FAILURE;
351  }
352  }
353  else {
354  cout << "ERROR: input component library(ies) required" << endl;
355  cout << visible << endl;
356  return EXIT_FAILURE;
357  }
358 
359  if( vm.count("output-dir") ) {
360  out = fs::system_complete( fs::path( vm["output-dir"].as<string>() ) );
361  }
362 
363  if ( vm.count("debug-level") ) {
364  PluginService::SetDebug( vm["debug-level"].as<int>() );
365  }
366 
367  if ( vm.count("load-library") ) {
368  Strings_t lLib_list = vm["load-library"].as< Strings_t >();
369  for (Strings_t::const_iterator lLib=lLib_list.begin();
370  lLib != lLib_list.end();
371  ++lLib) {
372  // load done through ROOT::Reflex helper class
373  SharedLibrary tmplib(*lLib) ;
374  tmplib.Load() ;
375  }
376  }
377 
378 
379  if ( !fs::exists( out ) ) {
380  try {
381  fs::create_directory(out);
382  }
383  catch ( fs::filesystem_error &err ) {
384  cout << "ERR0R: error creating directory: "<< err.what() << endl;
385  return EXIT_FAILURE;
386  }
387  }
388 
389  cout << ":::::: libraries : [ ";
390  copy( libs.begin(), libs.end(), ostream_iterator<string>(cout, " ") );
391  cout << "] ::::::" << endl;
392 
393  configGenerator py( pkgName, out.string() );
394  py.setConfigurableModule (vm["configurable-module"].as<string>());
395  py.setConfigurableDefaultName(vm["configurable-default-name"].as<string>());
396  py.setConfigurableAlgorithm (vm["configurable-algorithm"].as<string>());
397  py.setConfigurableAlgTool (vm["configurable-algtool"].as<string>());
398  py.setConfigurableAuditor (vm["configurable-auditor"].as<string>());
399  py.setConfigurableService (vm["configurable-service"].as<string>());
400 
401  int sc = EXIT_FAILURE;
402  try {
403  sc = py.genConfig( libs, userModule );
404  }
405  catch ( exception& e ) {
406  cout << "ERROR: Could not generate Configurable(s) !\n"
407  << "ERROR: Got exception: " << e.what() << endl;
408  return EXIT_FAILURE;
409  }
410 
411  if ( EXIT_SUCCESS == sc ) {
412  // create an empty __init__.py file in the output dir
413  fstream initPy( ( out / fs::path( "__init__.py" ) ).string().c_str(),
415  initPy << "## Hook for " << pkgName << " genConf module\n" << flush;
416  }
417 
418  cout << ":::::: libraries : [ ";
419  copy( libs.begin(), libs.end(), ostream_iterator<string>(cout, " ") );
420  cout << "] :::::: [DONE]" << endl;
421 
422  return sc;
423 }
424 
427 inline std::string getId(const Member & m) {
428  return (m.Properties().HasProperty("id") && (m.Properties().PropertyValue("id").TypeInfo() == typeid(std::string))) ?
429  m.Properties().PropertyAsString("id") :
430  m.Properties().PropertyAsString("name") ;
431 }
432 
433 template <class T>
434 IProperty *makeInstance(const Member &member, const vector<void*> &args)
435 {
436  Object dummy;
437  T* obj;
438 #if ROOT_VERSION_CODE < ROOT_VERSION(5,21,6)
439  obj = static_cast<T*>(member.Invoke(dummy,args).Address());
440 #else
441  member.Invoke(dummy,obj,args);
442 #endif
443  return dynamic_cast<IProperty*>(obj);
444 }
445 
446 
447 //-----------------------------------------------------------------------------
448 int configGenerator::genConfig( const Strings_t& libs, const string& userModule )
449 //-----------------------------------------------------------------------------
450 {
451  //--- Disable checking StatusCode -------------------------------------------
453 
454  const Strings_t::const_iterator endLib = libs.end();
455 
456  const std::string gaudiSvc = "GaudiCoreSvc";
457  const bool isGaudiSvc = ( std::find( libs.begin(), endLib, gaudiSvc ) != endLib );
458 
459  //--- Instantiate ApplicationMgr --------------------------------------------
460  if ( !isGaudiSvc && createAppMgr() ) {
461  cout << "ERROR: ApplicationMgr can not be created. Check environment" << endl;
462  return EXIT_FAILURE;
463  }
464 
465  //--- Iterate over component factories --------------------------------------
466  Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS);
467  if ( !factories ) {
468  cout << "ERROR: No PluginSvc factory namespace could be found" << endl;
469  return EXIT_FAILURE;
470  }
471 
472  ISvcLocator* svcLoc = Gaudi::svcLocator();
473  IInterface* dummySvc = new Service( "DummySvc", svcLoc );
474  dummySvc->addRef();
475 
476  bool allGood = true;
477 
478  // iterate over all the requested libraries
479  for ( Strings_t::const_iterator iLib=libs.begin(); iLib != endLib; ++iLib ) {
480 
481  std::cout << ":::: processing library: " << *iLib << "..." << std::endl;
482 
483  // reset state
484  m_importGaudiHandles = false;
485  m_pyBuf.str("");
486  m_dbBuf.str("");
487 
488  // Scan the pluginSvc namespace and store the "background" of already
489  // alive components, so we can extract our signal later on
490  set<string> bkgNames;
491  if ( !isGaudiSvc ) {
492  for ( Member_Iterator it = factories.FunctionMember_Begin();
493  it != factories.FunctionMember_End(); ++it ) {
494  string ident = getId(*it);
495  if ( PluginService::Debug() > 0 ) {
496  cout << "::: " << ident << endl;
497  }
498  bkgNames.insert( ident );
499  }
500  }
501  const set<string>::const_iterator bkgNamesEnd = bkgNames.end();
502 
503  //--- Load component library ----------------------------------------------
504  System::ImageHandle handle;
505  unsigned long err = System::loadDynamicLib( *iLib, &handle );
506  if ( err != 1 ) {
507  cout << "ERROR: " << System::getLastErrorString() << endl;
508  allGood = false;
509  continue;
510  }
511 
512  for ( Member_Iterator it = factories.FunctionMember_Begin();
513  it != factories.FunctionMember_End();
514  ++it ) {
515  const string ident = getId(*it);
516  if ( bkgNames.find(ident) != bkgNamesEnd ) {
517  if ( PluginService::Debug() > 0 ) {
518  cout << "\t==> skipping [" << ident << "]..." << endl;
519  }
520  continue;
521  }
522 
523  // Atlas contributed code (patch #1247)
524  // Skip the generation of configurables if the component does not come
525  // from the same library we are processing (i.e. we found a symbol that
526  // is coming from a library loaded by the linker).
527  // Windows implementation is empty.
528  if ( !DsoUtils::inDso( *it, DsoUtils::libNativeName(*iLib) ) ) {
529  cout << "WARNING: library [" << *iLib << "] requested factory "
530  << "from another library ["
531  << DsoUtils::dsoName(*it) << "]"
532  << " ==> [" << ident << "] !!"
533  << endl;
534  continue;
535  }
536 
537  const string rtype = it->TypeOf().ReturnType().Name();
538  string type;
539  bool known = true;
540  if ( ident == "ApplicationMgr" ) type = "ApplicationMgr";
541  else if ( rtype == "IInterface*" ) type = "IInterface";
542  else if ( rtype == "IAlgorithm*" ) type = "Algorithm";
543  else if ( rtype == "IService*" ) type = "Service";
544  else if ( rtype == "IAlgTool*" ) type = "AlgTool";
545  else if ( rtype == "IAuditor*" ) type = "Auditor";
546  else if ( rtype == "IConverter*" ) type = "Converter";
547  else if ( rtype == "DataObject*" ) type = "DataObject";
548  else type = "Unknown", known = false;
549  string name = ident;
550  // handle possible problems with templated components
551  boost::trim(name);
552 
553  cout << " - component: " << name << endl;
554 
555  if ( type == "IInterface" ) {
558  continue;
559  }
560 
561  if ( type == "Converter" || type == "DataObject" ) {
563  continue;
564  }
565 
566  //if ( type == "ApplicationMgr" ) {
569  //}
570 
571  if ( !known ) {
572  cout << "WARNING: Unknown (return) type [" << rtype << "] !!\n"
573  << "WARNING: component [" << ident << "] is skipped !"
574  << endl;
575  allGood = false;
576  continue;
577  }
578 
579  string cname = "DefaultName";
581  args.reserve( 3 );
582  if ( type == "AlgTool" ) {
583  args.resize( 3 );
584  args[0] = &cname;
585  args[1] = &type;
586  args[2] = dummySvc;
587  }
588  else {
589  args.resize( 2 );
590  args[0] = &cname;
591  args[1] = svcLoc;
592  }
593  IProperty* prop = 0;
594  try {
595  if ( type == "Algorithm" ) {
596  prop = makeInstance<IAlgorithm>(*it,args);
597  }
598  else if ( type == "Service") {
599  prop = makeInstance<IService>(*it,args);
600  }
601  else if ( type == "AlgTool") {
602  prop = makeInstance<IAlgTool>(*it,args);
603  }
604  else if ( type == "Auditor") {
605  prop = makeInstance<IAuditor>(*it,args);
606  }
607  else if ( type == "ApplicationMgr") {
608  //svcLoc->queryInterface(IProperty::interfaceID(), pp_cast<void>(&prop));
609  svcLoc->queryInterface(IProperty::interfaceID(), (void**)(&prop));
610  }
611  else {
612  prop = makeInstance<IInterface>(*it,args);
613  }
614  }
615  catch ( exception& e ) {
616  cout << "ERROR: Error instantiating " << name
617  << " from " << *iLib << endl;
618  cout << "ERROR: Got exception: " << e.what() << endl;
619  allGood = false;
620  continue;
621  }
622  catch ( ... ) {
623  cout << "ERROR: Error instantiating " << name
624  << " from " << *iLib << endl;
625  allGood = false;
626  continue;
627  }
628  if( prop ) {
629  if (genComponent( *iLib, name, type, prop->getProperties() )) {
630  allGood = false;
631  }
632  prop->release();
633  } else {
634  cout << "ERROR: could not cast IInterface* object to an IProperty* !\n"
635  << "ERROR: return type from PluginSvc is [" << rtype << "]...\n"
636  << "ERROR: NO Configurable will be generated for ["
637  << name << "] !"
638  << endl;
639  allGood = false;
640  }
641  } //> end loop over factories
642 
646  const std::string pyName = ( fs::path(m_outputDirName) /
647  fs::path(*iLib+"Conf.py") ).string();
648  const std::string dbName = ( fs::path(m_outputDirName) /
649  fs::path(*iLib+"_confDb.py") ).string();
650 
651  std::fstream py( pyName.c_str(),
653  std::fstream db( dbName.c_str(),
655 
656  genHeader ( py, db );
657  if (!userModule.empty())
658  py << "from " << userModule << " import *" <<endl;
659  genBody ( py, db );
660  genTrailer( py, db );
661 
662  } //> end loop over libraries
663 
664  dummySvc->release();
665  dummySvc = 0;
666 
667  return allGood ? EXIT_SUCCESS : EXIT_FAILURE;
668 }
669 
671  const boost::format& frmt,
672  std::string indent = ""){
673 
674  std::string::size_type pos = 0, nxtpos = 0;
676 
677  while ( std::string::npos != pos ){
678  // find end of module name
679  nxtpos = m_configurable["Module"].find_first_of(',',pos);
680 
681  // Prepare import string
682  mod = m_configurable["Module"].substr(pos,nxtpos-pos);
683  std::ostringstream import;
684  import << boost::format(frmt) % mod;
685 
686  // append a normal import or a try/except enclosed one depending
687  // on availability of a fall-back module (next in the list)
688  if ( std::string::npos == nxtpos ) {
689  // last possible module
690  s << indent << import.str() << "\n" << flush;
691  pos = std::string::npos;
692  } else {
693  // we have a fallback for this
694  s << indent << "try:\n"
695  << indent << py_tab << import.str() << "\n"
696  << indent << "except ImportError:\n"
697  << flush;
698  pos = nxtpos+1;
699  }
700  // increase indentation level for next iteration
701  indent += py_tab;
702  }
703 }
704 
705 //-----------------------------------------------------------------------------
707  std::ostream& db )
708 //-----------------------------------------------------------------------------
709 {
710  // python file part
711  std::string now = Gaudi::Time::current().format(true);
712  py << "#" << now //<< "\n"
713  << "\"\"\"Automatically generated. DO NOT EDIT please\"\"\"\n";
714  if ( m_importGaudiHandles ) {
715  py << "from GaudiKernel.GaudiHandles import *\n";
716  }
717 
718  genImport(py,boost::format("from %1%.Configurable import *"));
719 
720  // db file part
721  db << "## -*- python -*- \n"
722  << "# db file automatically generated by genconf on: "
723  << now; // << "\n";
724  db << "## insulates outside world against anything bad that could happen\n"
725  << "## also prevents global scope pollution\n"
726  << "def _fillCfgDb():\n";
727  genImport(db,boost::format("from %1%.ConfigurableDb import CfgDb"),py_tab);
728 
729  db << "\n"
730  << py_tab << "# get a handle on the repository of Configurables\n"
731  << py_tab << "cfgDb = CfgDb()\n"
732  << "\n"
733  << py_tab << "# populate the repository with informations on Configurables \n"
734  << "\n"
735  << flush;
736 }
737 //-----------------------------------------------------------------------------
739  std::ostream& db )
740 //-----------------------------------------------------------------------------
741 {
742  // db file part
743  db << py_tab << "return #_fillCfgDb\n"
744  << "# fill cfgDb at module import...\n"
745  << "try:\n"
746  << py_tab << "_fillCfgDb()\n"
747  << py_tab << "#house cleaning...\n"
748  << py_tab << "del _fillCfgDb\n"
749  << "except Exception,err:\n"
750  << py_tab << "print \"Py:ConfigurableDb ERROR Problem with [%s] content!"
751  << "\" % __name__\n"
752  << py_tab << "print \"Py:ConfigurableDb ERROR\",err\n"
753  << py_tab << "print \"Py:ConfigurableDb ERROR ==> culprit is package ["
754  << m_pkgName << "] !\"\n"
755  << std::flush;
756 }
757 
758 //-----------------------------------------------------------------------------
759 int
761  const std::string& componentName,
762  const std::string& componentType,
763  const vector<Property*>& properties )
764 //-----------------------------------------------------------------------------
765 {
766  string cname = componentName;
767  pythonizeName(cname);
768 
769  typedef GaudiUtils::HashMap<std::string, std::string> PropertyDoc_t;
770  PropertyDoc_t propDoc;
771 
772  m_pyBuf << "\n";
773  m_pyBuf << "class " << cname
774  << "( " << m_configurable[componentType] << " ) :"
775  << "\n";
776  m_pyBuf << " __slots__ = { \n";
777  for ( vector<Property*>::const_iterator it = properties.begin() ;
778  it != properties.end(); ++it ) {
779 
780  const string pname = (*it)->name();
781  // Validate property name (it must be a valid Python identifier)
782  if (!boost::regex_match(pname, pythonIdentifier)) {
783  std::cout << "ERROR: invalid property name \"" << pname
784  << "\" in component " << cname
785  << " (invalid Python identifier)" << std::endl;
786  // try to make the buffer at least more or less valid python code.
787  m_pyBuf << " #ERROR-invalid identifier '" << pname << "'\n"
788  << " }\n";
789  return 1;
790  }
791 
792  string pvalue, ptype;
793  pythonizeValue( (*it), pvalue, ptype );
794  m_pyBuf << " '" << pname << "' : " << pvalue <<", # " << ptype << "\n";
795 
796  if ( (*it)->documentation() != "none" ) {
797  propDoc[pname] = (*it)->documentation();
798  }
799 
800  }
801  m_pyBuf << " }\n";
802  m_pyBuf << " _propertyDocDct = { \n";
803  for ( PropertyDoc_t::const_iterator iProp = propDoc.begin();
804  iProp != propDoc.end();
805  ++iProp ) {
806  m_pyBuf << std::setw(5)
807  << "'" << iProp->first << "' : "
808  << "\"\"\" " << iProp->second << " \"\"\",\n";
809  }
810  m_pyBuf << " }\n";
811 
812  m_pyBuf
813  << " def __init__(self, name = " << m_configurable["DefaultName"]
814  << ", **kwargs):\n"
815  << " super(" << cname << ", self).__init__(name)\n"
816  << " for n,v in kwargs.items():\n"
817  << " setattr(self, n, v)\n"
818  << " def getDlls( self ):\n"
819  << " return '" << libName << "'\n"
820  << " def getType( self ):\n"
821  << " return '" << componentName << "'\n"
822  << " pass # class " << cname << "\n"
823  << flush;
824 
825  // name of the auto-generated module
826  const string pyName = ( fs::path(m_outputDirName) /
827  fs::path(libName+"Conf.py") ).string();
828  const string modName = fs::basename( fs::path( pyName ).leaf() );
829 
830  // now the db part
831  m_dbBuf
832  << py_tab << "cfgDb.add( configurable = '" << cname << "',\n"
833  << py_tab << " package = '" << m_pkgName << "',\n"
834  << py_tab << " module = '" << m_pkgName << "." << modName << "',\n"
835  << py_tab << " lib = '" << libName << "' )\n"
836  << flush;
837 
838  return 0;
839 }
840 //-----------------------------------------------------------------------------
841 void configGenerator::pythonizeName( string& name )
842 //-----------------------------------------------------------------------------
843 {
844  static string in("<>&*,: ().");
845  static string out("__rp__s___");
846  for ( string::iterator i = name.begin(); i != name.end(); ++i ) {
847  if ( in.find(*i) != string::npos ) *i = out[in.find(*i)];
848  }
849 }
850 
851 //-----------------------------------------------------------------------------
853  string& pvalue, string& ptype )
854 //-----------------------------------------------------------------------------
855 {
856  const std::string cvalue = p->toString();
857  const type_info& ti = *p->type_info();
858  if ( ti == typeid(bool) ) {
859  pvalue = ( cvalue == "0" || cvalue == "False" || cvalue == "false" )
860  ? "False"
861  : "True";
862  ptype = "bool";
863  }
864  else if ( ti == typeid(char) || ti == typeid(signed char)
865  || ti == typeid(unsigned char) ||
866  ti == typeid(short) || ti == typeid(unsigned short) ||
867  ti == typeid(int) || ti == typeid(unsigned int) ||
868  ti == typeid(long) || ti == typeid(unsigned long) ) {
869  pvalue = cvalue;
870  ptype = "int";
871  }
872  else if ( ti == typeid(long long) || ti == typeid(unsigned long long) ) {
873  pvalue = cvalue + "L";
874  ptype = "long";
875  }
876  else if ( ti == typeid(float) || ti == typeid(double) ) {
877  // forces python to handle this as a float: put a dot in there...
878  pvalue = boost::to_lower_copy(cvalue);
879  if ( pvalue == "nan" ) {
880  pvalue = "float('nan')";
881  std::cout << "WARNING: default value for ["
882  << p->name() << "] is NaN !!"
883  << std::endl;
884  } else if ( std::string::npos == pvalue.find(".") &&
885  std::string::npos == pvalue.find("e") ) {
886  pvalue = cvalue + ".0";
887  }
888  ptype = "float";
889  }
890  else if ( ti == typeid(string) ) {
891 
892  pvalue = "'"+cvalue+"'";
893  ptype = "str";
894  }
895  else if ( ti == typeid(GaudiHandleBase) ) {
896  m_importGaudiHandles = true;
897  const GaudiHandleProperty& hdl
898  = dynamic_cast<const GaudiHandleProperty&>(*p);
899  const GaudiHandleBase& base = hdl.value();
900 
901  pvalue = base.pythonRepr();
902  ptype = "GaudiHandle";
903  }
904  else if ( ti == typeid(GaudiHandleArrayBase) ) {
905  m_importGaudiHandles = true;
906  const GaudiHandleArrayProperty& hdl
907  = dynamic_cast<const GaudiHandleArrayProperty&>(*p);
908  const GaudiHandleArrayBase& base = hdl.value();
909 
910  pvalue = base.pythonRepr();
911  ptype = "GaudiHandleArray";
912  }
913  else {
914  std::ostringstream v_str;
915  v_str.setf(std::ios::fixed); // to correctly display floats
916  p->toStream(v_str);
917  pvalue = v_str.str();
918  ptype = "list";
919  }
920 }
921 
922 //-----------------------------------------------------------------------------
924 //-----------------------------------------------------------------------------
925 {
927  SmartIF<IProperty> propMgr ( iface );
928  SmartIF<IAppMgrUI> appUI ( iface );
929 
930  if ( propMgr.isValid() && appUI.isValid() ) {
931  propMgr->setProperty( "JobOptionsType", "NONE" ); // No job options
932  propMgr->setProperty( "AppName", ""); // No initial printout message
933  propMgr->setProperty( "OutputLevel", "7"); // No other printout messages
934  appUI->configure();
935  return EXIT_SUCCESS;
936  }
937  else {
938  return EXIT_FAILURE;
939  }
940 }

Generated at Wed Dec 4 2013 14:33:10 for Gaudi Framework, version v24r2 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004