14 # pragma warning( disable : 4273 )
24 # pragma warning( disable : 279 )
47 #include <boost/algorithm/string/case_conv.hpp>
48 #include <boost/algorithm/string/classification.hpp>
49 #include <boost/algorithm/string/replace.hpp>
50 #include <boost/algorithm/string/split.hpp>
51 #include <boost/algorithm/string/trim.hpp>
52 #include <boost/filesystem/exception.hpp>
53 #include <boost/filesystem/operations.hpp>
54 #include <boost/log/core.hpp>
55 #include <boost/log/expressions.hpp>
56 #include <boost/log/trivial.hpp>
57 #include <boost/log/utility/setup/common_attributes.hpp>
58 #include <boost/log/utility/setup/console.hpp>
59 #include <boost/program_options.hpp>
60 #include <boost/regex.hpp>
61 #include <boost/tokenizer.hpp>
64 #include <fmt/format.h>
69 #include <type_traits>
72 namespace po = boost::program_options;
73 namespace fs = boost::filesystem;
75 #define LOG_ERROR BOOST_LOG_TRIVIAL( error )
76 #define LOG_WARNING BOOST_LOG_TRIVIAL( warning )
77 #define LOG_INFO BOOST_LOG_TRIVIAL( info )
92 s << std::quoted( sv,
'\'' );
100 const boost::regex pythonIdentifier(
"^[a-zA-Z_][a-zA-Z0-9_]*$" );
103 enum class component_t {
123 {
typeid( Gaudi::Algorithm::Factory::FactoryType ).
name(), component_t::Algorithm },
124 {
typeid( Service::Factory::FactoryType ).
name(), component_t::Service },
125 {
typeid( AlgTool::Factory::FactoryType ).
name(), component_t::AlgTool },
126 {
typeid( Auditor::Factory::FactoryType ).
name(), component_t::Auditor },
131 "Auditor",
"Service",
"ApplicationMgr",
"IInterface",
132 "Converter",
"DataObject",
"Unknown" };
133 return names.
at(
static_cast<std::underlying_type_t<component_t>
>(
type ) );
138 {
"IInterface",
"IProperty",
"INamedInterface",
"IAlgorithm",
"IAlgTool",
"IService",
"IAuditor" } };
143 static const string in(
"<>&*,: ()." );
144 static const string out(
"__rp__s___" );
145 auto r = boost::algorithm::replace_all_copy(
name,
", ",
"," );
146 for (
auto&
c : r ) {
147 auto rep = in.
find(
c );
148 if ( rep != string::npos )
c =
out[rep];
153 template <
typename T>
159 #if defined( _WIN32 )
160 return libName +
".dll";
161 #elif defined( __linux ) || defined( __APPLE__ )
162 return "lib" + libName +
".so";
183 bool m_importGaudiHandles =
false;
184 bool m_importDataHandles =
false;
207 : m_pkgName( pkgName ), m_outputDirName( outputDirName ) {}
213 int genConfig(
const Strings_t& modules,
const string& userModule );
223 m_configurable[component_t::DefaultName] = defaultName;
228 m_configurable[component_t::Algorithm] = cfgAlgorithm;
239 m_configurable[component_t::Service] = cfgService;
240 m_configurable[component_t::ApplicationMgr] = cfgService;
244 bool genComponent(
const std::string& libName,
const std::string& componentName, component_t componentType,
246 const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
248 bool genComponent2(
const std::string& componentName, component_t componentType,
250 const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
261 void pythonizeValue(
const PropertyBase* prop,
string& pvalue,
string& ptype );
268 namespace keywords = boost::log::keywords;
269 namespace expr = boost::log::expressions;
273 << logging::trivial::severity <<
"] " << expr::smessage ) );
283 ? boost::log::trivial::info
284 : boost::log::trivial::warning );
293 po::options_description
generic(
"Generic options" );
294 generic.add_options()(
"help,h",
"produce this help message" )(
295 "package-name,p", po::value<string>(),
"name of the package for which we create the configurables file" )(
296 "input-libraries,i", po::value<string>(),
"libraries to extract the component configurables from" )(
297 "input-cfg,c", po::value<string>(),
298 "path to the cfg file holding the description of the Configurable base "
299 "classes, the python module holding the Configurable definitions, etc..." )(
300 "output-dir,o", po::value<string>()->default_value(
"../genConfDir" ),
301 "output directory for genconf files." )(
"debug-level,d", po::value<int>()->default_value( 0 ),
"debug level" )(
302 "load-library,l", po::value<Strings_t>()->composing(),
"preloading library" )(
303 "user-module,m", po::value<string>(),
"user-defined module to be imported by the genConf-generated one" )(
304 "no-init",
"do not generate the (empty) __init__.py" )(
305 "type", po::value<string>()->default_value(
"conf,conf2" ),
"comma-separate types of configurables to generate" );
309 po::options_description
config(
"Configuration" );
310 config.add_options()(
"configurable-module", po::value<string>()->default_value(
"AthenaCommon" ),
311 "Name of the module holding the configurable classes" )(
312 "configurable-default-name", po::value<string>()->default_value(
"Configurable.DefaultName" ),
313 "Default name for the configurable instance" )(
"configurable-algorithm",
314 po::value<string>()->default_value(
"ConfigurableAlgorithm" ),
315 "Name of the configurable base class for Algorithm components" )(
316 "configurable-algtool", po::value<string>()->default_value(
"ConfigurableAlgTool" ),
317 "Name of the configurable base class for AlgTool components" )(
318 "configurable-auditor", po::value<string>()->default_value(
"ConfigurableAuditor" ),
319 "Name of the configurable base class for Auditor components" )(
320 "configurable-service", po::value<string>()->default_value(
"ConfigurableService" ),
321 "Name of the configurable base class for Service components" );
323 po::options_description cmdline_options;
324 cmdline_options.add(
generic ).add(
config );
326 po::options_description config_file_options;
327 config_file_options.add(
config );
329 po::options_description visible(
"Allowed options" );
330 visible.add(
generic ).add(
config );
332 po::variables_map vm;
335 po::store( po::command_line_parser(
argc,
argv ).
options( cmdline_options ).run(), vm );
340 if ( vm.contains(
"input-cfg" ) ) {
341 string cfgFileName = vm[
"input-cfg"].as<
string>();
342 cfgFileName = fs::system_complete(
fs::path( cfgFileName ) ).
string();
344 po::store( parse_config_file( ifs, config_file_options ), vm );
348 }
catch ( po::error& err ) {
349 LOG_ERROR <<
"error detected while parsing command options: " << err.what();
354 if ( vm.contains(
"help" ) ) {
359 if ( vm.contains(
"package-name" ) ) {
360 pkgName = vm[
"package-name"].as<
string>();
367 if ( vm.contains(
"user-module" ) ) {
368 userModule = vm[
"user-module"].as<
string>();
369 LOG_INFO <<
"INFO: will import user module " << userModule;
372 if ( vm.contains(
"input-libraries" ) ) {
378 boost::split( libs, tmp, boost::is_any_of(
" " ), boost::token_compress_on );
380 LOG_ERROR <<
"input component library(ies) required";
385 if ( vm.contains(
"output-dir" ) ) {
out = fs::system_complete(
fs::path( vm[
"output-dir"].as<string>() ) ); }
389 if ( vm.contains(
"load-library" ) ) {
390 for (
const auto& lLib : vm[
"load-library"].as<Strings_t>() ) {
394 if ( err != 1 )
LOG_WARNING <<
"failed to load: " << lLib;
399 if ( vm.contains(
"type" ) ) {
401 if (
type ==
"conf" ) {
402 confTypes.
insert( conf_t::CONF );
403 }
else if (
type ==
"conf2" ) {
404 confTypes.
insert( conf_t::CONF2 );
413 if ( !fs::exists(
out ) ) {
415 fs::create_directory(
out );
416 }
catch ( fs::filesystem_error& err ) {
417 LOG_ERROR <<
"error creating directory: " << err.what();
424 msg <<
":::::: libraries : [ ";
439 int sc = EXIT_FAILURE;
443 cout <<
"ERROR: Could not generate Configurable(s) !\n"
444 <<
"ERROR: Got exception: " << e.
what() <<
endl;
448 if ( EXIT_SUCCESS == sc && !vm.contains(
"no-init" ) ) {
451 initPy <<
"## Hook for " << pkgName <<
" genConf module\n" <<
flush;
456 msg <<
":::::: libraries : [ ";
458 msg <<
"] :::::: [DONE]";
468 const auto endLib = libs.
end();
470 static const std::string gaudiSvc =
"GaudiCoreSvc";
471 const bool isGaudiSvc =
473 return s.find( gaudiSvc ) != std::string::npos;
478 cout <<
"ERROR: ApplicationMgr can not be created. Check environment" <<
endl;
483 using Gaudi::PluginService::Details::Registry;
484 const Registry&
registry = Registry::instance();
486 auto bkgNames =
registry.loadedFactoryNames();
489 IInterface* dummySvc =
new Service(
"DummySvc", svcLoc );
495 for (
const auto& iLib : libs ) {
497 if ( lib.
compare( 0, 3,
"lib" ) == 0 ) {
500 LOG_INFO <<
":::: processing library: " << iLib <<
"...";
503 m_importGaudiHandles =
false;
504 m_importDataHandles =
false;
519 for (
const auto& factoryName :
registry.loadedFactoryNames() ) {
520 if ( bkgNames.find( factoryName ) != bkgNames.end() ) {
522 LOG_INFO <<
"\t==> skipping [" << factoryName <<
"]...";
526 auto entry =
factories.find( factoryName );
528 LOG_ERROR <<
"inconsistency in component factories list: I cannot find anymore " << factoryName;
531 const auto& info = entry->second;
532 if ( !info.is_set() )
continue;
535 if ( !info.getprop(
"ReflexName" ).empty() )
continue;
541 if ( libNativeName( lib ) != info.library ) {
542 LOG_WARNING <<
"library [" << lib <<
"] exposes factory [" << factoryName <<
"] which is declared in ["
543 << info.library <<
"] !!";
547 component_t
type = component_t::Unknown;
549 const auto ft = allowedFactories.find( info.factory.type().name() );
550 if ( ft != allowedFactories.end() ) {
552 }
else if ( factoryName ==
"ApplicationMgr" ) {
553 type = component_t::ApplicationMgr;
561 const auto className = info.getprop(
"ClassName" );
565 string cname =
"DefaultName";
569 case component_t::Algorithm:
572 case component_t::Service:
575 case component_t::AlgTool:
581 case component_t::Auditor:
584 case component_t::ApplicationMgr:
591 LOG_ERROR <<
"Error instantiating " <<
name <<
" from " << iLib;
596 LOG_ERROR <<
"Error instantiating " <<
name <<
" from " << iLib;
601 if ( m_confTypes.contains( conf_t::CONF ) && !genComponent( lib,
name,
type, prop->getProperties(), info ) ) {
604 if ( m_confTypes.contains( conf_t::CONF2 ) &&
605 !genComponent2(
name,
type, prop->getProperties(), prop->getInterfaceNames(), info ) ) {
610 LOG_ERROR <<
"could not cast IInterface* object to an IProperty* !";
611 LOG_ERROR <<
"NO Configurable will be generated for [" <<
name <<
"] !";
619 if ( m_confTypes.contains( conf_t::CONF ) ) {
627 if ( !userModule.
empty() ) py <<
"from " << userModule <<
" import *" <<
endl;
629 genTrailer( py, db );
631 if ( m_confTypes.contains( conf_t::CONF2 ) ) {
634 db2 <<
"{\n" << m_db2Buf.str() <<
"}\n";
642 return allGood ? EXIT_SUCCESS : EXIT_FAILURE;
647 std::string::size_type pos = 0, nxtpos = 0;
650 while ( std::string::npos != pos ) {
652 nxtpos = m_configurable[component_t::Module].find_first_of(
',', pos );
655 mod = m_configurable[component_t::Module].substr( pos, nxtpos - pos );
661 if ( std::string::npos == nxtpos ) {
663 s << indent <<
import.str() <<
"\n" <<
flush;
664 pos = std::string::npos;
667 s << indent <<
"try:\n" << indent << py_tab <<
import.str() <<
"\n" << indent <<
"except ImportError:\n" <<
flush;
682 <<
"\"\"\"Automatically generated. DO NOT EDIT please\"\"\"\n";
684 if ( m_importGaudiHandles ) { py <<
"from GaudiKernel.GaudiHandles import *\n"; }
686 if ( m_importDataHandles ) { py <<
"from GaudiKernel.DataHandle import DataHandle\n"; }
688 genImport( py,
"from {}.Configurable import *" );
691 db <<
"## -*- ascii -*- \n"
692 <<
"# db file automatically generated by genconf on: " << now <<
"\n"
700 db <<
"## " << m_pkgName <<
"\n" <<
std::flush;
706 const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
709 auto cname = pythonizeName( componentName );
710 const auto decl_loc = info.getprop(
"declaration_location" );
715 m_pyBuf <<
"\nclass " << cname <<
"( " << m_configurable[componentType] <<
" ) :\n";
716 m_pyBuf <<
" __slots__ = { \n";
718 const string&
pname = prop->name();
720 if ( !boost::regex_match(
pname, pythonIdentifier ) ) {
721 LOG_ERROR <<
"invalid property name \"" <<
pname <<
"\" in component " << cname <<
" (invalid Python identifier)"
724 m_pyBuf <<
" #ERROR-invalid identifier '" <<
pname <<
"'\n"
729 string pvalue, ptype;
730 pythonizeValue( prop, pvalue, ptype );
731 m_pyBuf <<
" '" <<
pname <<
"' : " << pvalue <<
",\n";
733 if ( prop->documentation() !=
"none" ) {
734 propDoc.
emplace_back(
pname, prop->documentation() +
" [" + prop->ownerTypeName() +
"]" );
738 m_pyBuf <<
" _propertyDocDct = { \n";
739 for (
const auto& prop : propDoc ) {
740 m_pyBuf <<
std::setw( 5 ) <<
"'" << prop.first <<
"' : "
741 <<
"\"\"\" " << prop.second <<
" \"\"\",\n";
745 if ( !decl_loc.empty() ) { m_pyBuf <<
" __declaration_location__ = '" << decl_loc <<
"'\n"; }
746 m_pyBuf <<
" def __init__(self, name = " << m_configurable[component_t::DefaultName] <<
", **kwargs):\n"
747 <<
" super(" << cname <<
", self).__init__(name)\n"
748 <<
" for n,v in kwargs.items():\n"
749 <<
" setattr(self, n, v)\n"
750 <<
" def getDlls( self ):\n"
751 <<
" return '" << libName <<
"'\n"
752 <<
" def getType( self ):\n"
753 <<
" return '" << componentName <<
"'\n"
754 <<
" pass # class " << cname <<
"\n"
758 const string pyName = (
fs::path( m_outputDirName ) /
fs::path( libName +
"Conf.py" ) ).
string();
759 const string modName =
fs::path( pyName ).filename().stem().string();
762 m_dbBuf << m_pkgName <<
"." << modName <<
" " << libName <<
" " << cname <<
"\n" <<
flush;
770 const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
773 m_db2Buf <<
" '" << componentName <<
"': {\n";
774 m_db2Buf <<
" '__component_type__': '";
775 switch ( componentType ) {
776 case component_t::Algorithm:
777 m_db2Buf <<
"Algorithm";
779 case component_t::AlgTool:
780 m_db2Buf <<
"AlgTool";
782 case component_t::ApplicationMgr:
783 case component_t::Service:
784 m_db2Buf <<
"Service";
786 case component_t::Auditor:
787 m_db2Buf <<
"Auditor";
790 m_db2Buf <<
"Unknown";
793 const auto decl_loc = info.getprop(
"declaration_location" );
794 if ( !decl_loc.empty() ) { m_db2Buf <<
"',\n '__declaration_location__': '" << decl_loc; }
796 m_db2Buf <<
"',\n '__interfaces__': (";
798 if ( ignored_interfaces.find( intf ) ==
end( ignored_interfaces ) ) { m_db2Buf <<
'\'' << intf <<
"', "; }
800 m_db2Buf <<
"),\n 'properties': {\n";
804 const string&
pname = prop->name();
806 if ( !boost::regex_match(
pname, pythonIdentifier ) ) {
807 LOG_ERROR <<
"invalid property name \"" <<
pname <<
"\" in component " << componentName
808 <<
" (invalid Python identifier)" <<
std::endl;
809 m_db2Buf <<
" #ERROR-invalid identifier '" <<
pname <<
"'\n";
814 string pvalue, ptype;
815 pythonizeValue( prop, pvalue, ptype );
817 m_db2Buf <<
" '" <<
pname <<
"': ('" << ptype <<
"', " << pvalue <<
", '''" << prop->documentation()
818 <<
" [" << prop->ownerTypeName() <<
"]'''";
819 auto sem = prop->semantics();
820 if ( !sem.empty() ) { m_db2Buf <<
", '" << sem <<
'\''; }
824 m_db2Buf <<
" },\n },\n";
837 if ( ti == typeIndex<bool>() ) {
838 pvalue = ( cvalue ==
"0" || cvalue ==
"False" || cvalue ==
"false" ) ?
"False" :
"True";
839 }
else if ( ti == typeIndex<char>() || ti == typeIndex<signed char>() || ti == typeIndex<unsigned char>() ||
840 ti == typeIndex<short>() || ti == typeIndex<unsigned short>() || ti == typeIndex<int>() ||
841 ti == typeIndex<unsigned int>() || ti == typeIndex<long>() || ti == typeIndex<unsigned long>() ||
842 ti == typeIndex<long long>() || ti == typeIndex<unsigned long long>() ) {
844 }
else if ( ti == typeIndex<float>() || ti == typeIndex<double>() ) {
846 pvalue = boost::to_lower_copy( cvalue );
847 if ( std::string::npos != pvalue.
find(
"nan" ) ) {
848 pvalue =
"float('nan')";
849 }
else if ( std::string::npos == pvalue.
find(
"." ) && std::string::npos == pvalue.
find(
"e" ) ) {
850 pvalue = cvalue +
".0";
852 }
else if ( ti == typeIndex<string>() ) {
853 pvalue = quote( cvalue );
854 }
else if ( ti == typeIndex<GaudiHandleBase>() ) {
858 pvalue =
base.pythonRepr();
859 ptype =
base.pythonPropertyClassName();
860 m_importGaudiHandles =
true;
861 }
else if ( ti == typeIndex<GaudiHandleArrayBase>() ) {
865 pvalue =
base.pythonRepr();
866 ptype =
base.pythonPropertyClassName();
867 m_importGaudiHandles =
true;
872 pvalue =
base.pythonRepr();
873 m_importDataHandles =
true;
876 v_str.
setf( std::ios::showpoint );
878 pvalue = v_str.
str();
889 if ( !propMgr || !appUI )
return EXIT_FAILURE;
893 propMgr->setProperty(
"AppName",
"" ).
ignore( );
895 propMgr->setProperty(
"OutputLevel", 7 ).
ignore( );
897 appUI->configure().ignore( );
899 msgSvc->setPropertyRepr(
"setWarning",
"['DefaultName', 'PropertyHolder']" )
901 msgSvc->setProperty(
"Format",
"%T %0W%M" ).ignore( );