14 # pragma warning( disable : 279 )
37 #include <boost/algorithm/string/case_conv.hpp>
38 #include <boost/algorithm/string/classification.hpp>
39 #include <boost/algorithm/string/replace.hpp>
40 #include <boost/algorithm/string/split.hpp>
41 #include <boost/algorithm/string/trim.hpp>
42 #include <boost/filesystem/exception.hpp>
43 #include <boost/filesystem/operations.hpp>
44 #include <boost/log/core.hpp>
45 #include <boost/log/expressions.hpp>
46 #include <boost/log/trivial.hpp>
47 #include <boost/log/utility/setup/common_attributes.hpp>
48 #include <boost/log/utility/setup/console.hpp>
49 #include <boost/program_options.hpp>
50 #include <boost/regex.hpp>
51 #include <boost/tokenizer.hpp>
54 #include <fmt/format.h>
59 #include <type_traits>
62 namespace po = boost::program_options;
63 namespace fs = boost::filesystem;
65 #define LOG_ERROR BOOST_LOG_TRIVIAL( error )
66 #define LOG_WARNING BOOST_LOG_TRIVIAL( warning )
67 #define LOG_INFO BOOST_LOG_TRIVIAL( info )
80 std::string quote( std::string_view sv ) {
82 s << std::quoted( sv,
'\'' );
86 const std::string py_tab =
" ";
90 const boost::regex pythonIdentifier(
"^[a-zA-Z_][a-zA-Z0-9_]*$" );
93 enum class component_t {
112 const std::map<std::string, component_t> allowedFactories{
113 {
typeid( Gaudi::Algorithm::Factory::FactoryType ).
name(), component_t::Algorithm },
114 {
typeid( Service::Factory::FactoryType ).
name(), component_t::Service },
115 {
typeid( AlgTool::Factory::FactoryType ).
name(), component_t::AlgTool },
117 {
typeid( Gaudi::Auditor::Factory::FactoryType ).
name(), component_t::Auditor },
121 static const std::array<std::string, 11> names = {
"Module",
"DefaultName",
"Algorithm",
"AlgTool",
122 "Auditor",
"Service",
"ApplicationMgr",
"IInterface",
123 "Converter",
"DataObject",
"Unknown" };
124 return names.at(
static_cast<std::underlying_type_t<component_t>
>(
type ) );
128 std::set<std::string> ignored_interfaces{
129 {
"IInterface",
"IProperty",
"INamedInterface",
"IAlgorithm",
"IAlgTool",
"IService",
"IAuditor" } };
133 std::string pythonizeName(
const std::string&
name ) {
134 static const string in(
"<>&*,: ()." );
135 static const string out(
"__rp__s___" );
136 auto r = boost::algorithm::replace_all_copy(
name,
", ",
"," );
137 for (
auto&
c : r ) {
138 auto rep = in.find(
c );
139 if ( rep != string::npos )
c =
out[rep];
144 template <
typename T>
145 std::type_index typeIndex() {
146 return std::type_index{
typeid( T ) };
149 inline std::string libNativeName(
const std::string& libName ) {
150 #if defined( __linux ) || defined( __APPLE__ )
151 return "lib" + libName +
".so";
172 bool m_importGaudiHandles =
false;
173 bool m_importDataHandles =
false;
196 : m_pkgName( pkgName ), m_outputDirName( outputDirName ) {}
202 int genConfig(
const Strings_t& modules,
const string& userModule );
212 m_configurable[component_t::DefaultName] = defaultName;
217 m_configurable[component_t::Algorithm] = cfgAlgorithm;
228 m_configurable[component_t::Service] = cfgService;
229 m_configurable[component_t::ApplicationMgr] = cfgService;
233 bool genComponent(
const std::string& libName,
const std::string& componentName, component_t componentType,
235 const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
237 bool genComponent2(
const std::string& componentName, component_t componentType,
238 const vector<PropertyBase*>&
properties,
const std::vector<std::string>& interfaces,
239 const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
241 void genImport( std::ostream&
s, std::string_view frmt, std::string indent );
242 void genHeader( std::ostream& pyOut, std::ostream& dbOut );
243 void genBody( std::ostream& pyOut, std::ostream& dbOut ) {
244 pyOut << m_pyBuf.str() << flush;
245 dbOut << m_dbBuf.str() << flush;
247 void genTrailer( std::ostream& pyOut, std::ostream& dbOut );
250 void pythonizeValue(
const PropertyBase* prop,
string& pvalue,
string& ptype );
257 namespace keywords = boost::log::keywords;
258 namespace expr = boost::log::expressions;
262 << logging::trivial::severity <<
"] " << expr::smessage ) );
272 ? boost::log::trivial::info
273 : boost::log::trivial::warning );
279 std::string userModule;
282 po::options_description
generic(
"Generic options" );
283 generic.add_options()(
"help,h",
"produce this help message" )(
284 "package-name,p", po::value<string>(),
"name of the package for which we create the configurables file" )(
285 "input-libraries,i", po::value<string>(),
"libraries to extract the component configurables from" )(
286 "input-cfg,c", po::value<string>(),
287 "path to the cfg file holding the description of the Configurable base "
288 "classes, the python module holding the Configurable definitions, etc..." )(
289 "output-dir,o", po::value<string>()->default_value(
"../genConfDir" ),
290 "output directory for genconf files." )(
"debug-level,d", po::value<int>()->default_value( 0 ),
"debug level" )(
291 "load-library,l", po::value<Strings_t>()->composing(),
"preloading library" )(
292 "user-module,m", po::value<string>(),
"user-defined module to be imported by the genConf-generated one" )(
293 "no-init",
"do not generate the (empty) __init__.py" )(
294 "type", po::value<string>()->default_value(
"conf,conf2" ),
"comma-separate types of configurables to generate" );
298 po::options_description
config(
"Configuration" );
299 config.add_options()(
"configurable-module", po::value<string>()->default_value(
"AthenaCommon" ),
300 "Name of the module holding the configurable classes" )(
301 "configurable-default-name", po::value<string>()->default_value(
"Configurable.DefaultName" ),
302 "Default name for the configurable instance" )(
"configurable-algorithm",
303 po::value<string>()->default_value(
"ConfigurableAlgorithm" ),
304 "Name of the configurable base class for Algorithm components" )(
305 "configurable-algtool", po::value<string>()->default_value(
"ConfigurableAlgTool" ),
306 "Name of the configurable base class for AlgTool components" )(
307 "configurable-auditor", po::value<string>()->default_value(
"ConfigurableAuditor" ),
308 "Name of the configurable base class for Auditor components" )(
309 "configurable-service", po::value<string>()->default_value(
"ConfigurableService" ),
310 "Name of the configurable base class for Service components" );
312 po::options_description cmdline_options;
313 cmdline_options.add(
generic ).add(
config );
315 po::options_description config_file_options;
316 config_file_options.add(
config );
318 po::options_description visible(
"Allowed options" );
319 visible.add(
generic ).add(
config );
321 po::variables_map vm;
324 po::store( po::command_line_parser(
argc,
argv ).
options( cmdline_options ).run(), vm );
329 if ( vm.contains(
"input-cfg" ) ) {
330 string cfgFileName = vm[
"input-cfg"].as<
string>();
331 cfgFileName = fs::system_complete(
fs::path( cfgFileName ) ).string();
332 std::ifstream ifs( cfgFileName );
333 po::store( parse_config_file( ifs, config_file_options ), vm );
337 }
catch ( po::error& err ) {
338 LOG_ERROR <<
"error detected while parsing command options: " << err.what();
343 if ( vm.contains(
"help" ) ) {
344 cout << visible << endl;
348 if ( vm.contains(
"package-name" ) ) {
349 pkgName = vm[
"package-name"].as<
string>();
352 cout << visible << endl;
356 if ( vm.contains(
"user-module" ) ) {
357 userModule = vm[
"user-module"].as<
string>();
358 LOG_INFO <<
"INFO: will import user module " << userModule;
361 if ( vm.contains(
"input-libraries" ) ) {
365 std::string tmp = vm[
"input-libraries"].as<std::string>();
367 boost::split( libs, tmp, boost::is_any_of(
" " ), boost::token_compress_on );
369 LOG_ERROR <<
"input component library(ies) required";
370 cout << visible << endl;
374 if ( vm.contains(
"output-dir" ) ) {
out = fs::system_complete(
fs::path( vm[
"output-dir"].as<string>() ) ); }
378 if ( vm.contains(
"load-library" ) ) {
379 for (
const auto& lLib : vm[
"load-library"].as<Strings_t>() ) {
383 if ( err != 1 )
LOG_WARNING <<
"failed to load: " << lLib;
387 std::set<conf_t> confTypes;
388 if ( vm.contains(
"type" ) ) {
389 for (
const std::string&
type : boost::tokenizer{ vm[
"type"].as<std::string>(), boost::char_separator{
"," } } ) {
390 if (
type ==
"conf" ) {
391 confTypes.insert( conf_t::CONF );
392 }
else if (
type ==
"conf2" ) {
393 confTypes.insert( conf_t::CONF2 );
396 cout << visible << endl;
402 if ( !fs::exists(
out ) ) {
404 fs::create_directory(
out );
405 }
catch ( fs::filesystem_error& err ) {
406 LOG_ERROR <<
"error creating directory: " << err.what();
412 std::ostringstream
msg;
413 msg <<
":::::: libraries : [ ";
414 std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>(
msg,
" " ) );
428 int sc = EXIT_FAILURE;
431 }
catch ( exception& e ) {
432 cout <<
"ERROR: Could not generate Configurable(s) !\n"
433 <<
"ERROR: Got exception: " << e.what() << endl;
437 if ( EXIT_SUCCESS == sc && !vm.contains(
"no-init" ) ) {
440 initPy <<
"## Hook for " << pkgName <<
" genConf module\n" << flush;
444 std::ostringstream
msg;
445 msg <<
":::::: libraries : [ ";
446 std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>(
msg,
" " ) );
447 msg <<
"] :::::: [DONE]";
457 const auto endLib = libs.end();
459 static const std::string gaudiSvc =
"GaudiCoreSvc";
460 const bool isGaudiSvc =
461 std::find_if( libs.begin(), endLib, [](
const auto&
s ) {
462 return s.find( gaudiSvc ) != std::string::npos;
467 cout <<
"ERROR: ApplicationMgr can not be created. Check environment" << endl;
472 using Gaudi::PluginService::Details::Registry;
473 const Registry&
registry = Registry::instance();
475 auto bkgNames =
registry.loadedFactoryNames();
478 IInterface* dummySvc =
new Service(
"DummySvc", svcLoc );
484 for (
const auto& iLib : libs ) {
485 std::string lib =
fs::path( iLib ).stem().string();
486 if ( lib.compare( 0, 3,
"lib" ) == 0 ) {
487 lib = lib.substr( 3 );
489 LOG_INFO <<
":::: processing library: " << iLib <<
"...";
492 m_importGaudiHandles =
false;
493 m_importDataHandles =
false;
508 for (
const auto& factoryName :
registry.loadedFactoryNames() ) {
509 if ( bkgNames.find( factoryName ) != bkgNames.end() ) {
511 LOG_INFO <<
"\t==> skipping [" << factoryName <<
"]...";
515 auto entry =
factories.find( factoryName );
517 LOG_ERROR <<
"inconsistency in component factories list: I cannot find anymore " << factoryName;
520 const auto& info = entry->second;
521 if ( !info.is_set() )
continue;
524 if ( !info.getprop(
"ReflexName" ).empty() )
continue;
530 if ( libNativeName( lib ) != info.library ) {
531 LOG_WARNING <<
"library [" << lib <<
"] exposes factory [" << factoryName <<
"] which is declared in ["
532 << info.library <<
"] !!";
536 component_t
type = component_t::Unknown;
538 const auto ft = allowedFactories.find( info.factory.type().name() );
539 if ( ft != allowedFactories.end() ) {
541 }
else if ( factoryName ==
"ApplicationMgr" ) {
542 type = component_t::ApplicationMgr;
548 std::string
name = boost::trim_copy( factoryName );
550 const auto className = info.getprop(
"ClassName" );
551 LOG_INFO <<
" - component: " << className <<
" (" << ( className !=
name ? (
name +
": " ) : std::string() )
554 string cname =
"DefaultName";
558 case component_t::Algorithm:
561 case component_t::Service:
564 case component_t::AlgTool:
570 case component_t::Auditor:
573 case component_t::ApplicationMgr:
579 }
catch ( exception& e ) {
580 LOG_ERROR <<
"Error instantiating " <<
name <<
" from " << iLib;
581 LOG_ERROR <<
"Got exception: " << e.what();
585 LOG_ERROR <<
"Error instantiating " <<
name <<
" from " << iLib;
590 if ( m_confTypes.contains( conf_t::CONF ) && !genComponent( lib,
name,
type, prop->getProperties(), info ) ) {
593 if ( m_confTypes.contains( conf_t::CONF2 ) &&
594 !genComponent2(
name,
type, prop->getProperties(), prop->getInterfaceNames(), info ) ) {
599 LOG_ERROR <<
"could not cast IInterface* object to an IProperty* !";
600 LOG_ERROR <<
"NO Configurable will be generated for [" <<
name <<
"] !";
608 if ( m_confTypes.contains( conf_t::CONF ) ) {
609 const std::string pyName = (
fs::path( m_outputDirName ) /
fs::path( lib +
"Conf.py" ) ).
string();
610 const std::string dbName = (
fs::path( m_outputDirName ) /
fs::path( lib +
".confdb" ) ).
string();
616 if ( !userModule.empty() ) py <<
"from " << userModule <<
" import *" << endl;
618 genTrailer( py, db );
620 if ( m_confTypes.contains( conf_t::CONF2 ) ) {
621 const std::string db2Name = (
fs::path( m_outputDirName ) /
fs::path( lib +
".confdb2_part" ) ).
string();
623 db2 <<
"{\n" << m_db2Buf.str() <<
"}\n";
631 return allGood ? EXIT_SUCCESS : EXIT_FAILURE;
636 std::string::size_type pos = 0, nxtpos = 0;
639 while ( std::string::npos != pos ) {
641 nxtpos = m_configurable[component_t::Module].find_first_of(
',', pos );
644 mod = m_configurable[component_t::Module].substr( pos, nxtpos - pos );
645 std::ostringstream
import;
650 if ( std::string::npos == nxtpos ) {
652 s << indent <<
import.str() <<
"\n" << flush;
653 pos = std::string::npos;
656 s << indent <<
"try:\n" << indent << py_tab <<
import.str() <<
"\n" << indent <<
"except ImportError:\n" << flush;
671 <<
"\"\"\"Automatically generated. DO NOT EDIT please\"\"\"\n";
673 if ( m_importGaudiHandles ) { py <<
"from GaudiKernel.GaudiHandles import *\n"; }
675 if ( m_importDataHandles ) { py <<
"from GaudiKernel.DataHandle import DataHandle\n"; }
677 genImport( py,
"from {}.Configurable import *" );
680 db <<
"## -*- ascii -*- \n"
681 <<
"# db file automatically generated by genconf on: " << now <<
"\n"
689 db <<
"## " << m_pkgName <<
"\n" << std::flush;
694 component_t componentType,
const vector<PropertyBase*>&
properties,
695 const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
698 auto cname = pythonizeName( componentName );
699 const auto decl_loc = info.getprop(
"declaration_location" );
701 std::vector<std::pair<std::string, std::string>> propDoc;
704 m_pyBuf <<
"\nclass " << cname <<
"( " << m_configurable[componentType] <<
" ) :\n";
705 m_pyBuf <<
" __slots__ = { \n";
707 const string&
pname = prop->name();
709 if ( !boost::regex_match(
pname, pythonIdentifier ) ) {
710 LOG_ERROR <<
"invalid property name \"" <<
pname <<
"\" in component " << cname <<
" (invalid Python identifier)"
713 m_pyBuf <<
" #ERROR-invalid identifier '" <<
pname <<
"'\n"
718 string pvalue, ptype;
719 pythonizeValue( prop, pvalue, ptype );
720 m_pyBuf <<
" '" <<
pname <<
"' : " << pvalue <<
",\n";
722 if ( prop->documentation() !=
"none" ) {
723 propDoc.emplace_back(
pname, prop->documentation() +
" [" + prop->ownerTypeName() +
"]" );
727 m_pyBuf <<
" _propertyDocDct = { \n";
728 for (
const auto& prop : propDoc ) {
729 m_pyBuf << std::setw( 5 ) <<
"'" << prop.first <<
"' : "
730 <<
"\"\"\" " << prop.second <<
" \"\"\",\n";
734 if ( !decl_loc.empty() ) { m_pyBuf <<
" __declaration_location__ = '" << decl_loc <<
"'\n"; }
735 m_pyBuf <<
" def __init__(self, name = " << m_configurable[component_t::DefaultName] <<
", **kwargs):\n"
736 <<
" super(" << cname <<
", self).__init__(name)\n"
737 <<
" for n,v in kwargs.items():\n"
738 <<
" setattr(self, n, v)\n"
739 <<
" def getDlls( self ):\n"
740 <<
" return '" << libName <<
"'\n"
741 <<
" def getType( self ):\n"
742 <<
" return '" << componentName <<
"'\n"
743 <<
" pass # class " << cname <<
"\n"
747 const string pyName = (
fs::path( m_outputDirName ) /
fs::path( libName +
"Conf.py" ) ).
string();
748 const string modName =
fs::path( pyName ).filename().stem().string();
751 m_dbBuf << m_pkgName <<
"." << modName <<
" " << libName <<
" " << cname <<
"\n" << flush;
758 const vector<PropertyBase*>&
properties,
const vector<std::string>& interfaces,
759 const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
762 m_db2Buf <<
" '" << componentName <<
"': {\n";
763 m_db2Buf <<
" '__component_type__': '";
764 switch ( componentType ) {
765 case component_t::Algorithm:
766 m_db2Buf <<
"Algorithm";
768 case component_t::AlgTool:
769 m_db2Buf <<
"AlgTool";
771 case component_t::ApplicationMgr:
772 case component_t::Service:
773 m_db2Buf <<
"Service";
775 case component_t::Auditor:
776 m_db2Buf <<
"Auditor";
779 m_db2Buf <<
"Unknown";
782 const auto decl_loc = info.getprop(
"declaration_location" );
783 if ( !decl_loc.empty() ) { m_db2Buf <<
"',\n '__declaration_location__': '" << decl_loc; }
785 m_db2Buf <<
"',\n '__interfaces__': (";
786 for (
const auto& intf : std::set<std::string>{
begin( interfaces ),
end( interfaces ) } ) {
787 if ( ignored_interfaces.find( intf ) ==
end( ignored_interfaces ) ) { m_db2Buf <<
'\'' << intf <<
"', "; }
789 m_db2Buf <<
"),\n 'properties': {\n";
793 const string&
pname = prop->name();
795 if ( !boost::regex_match(
pname, pythonIdentifier ) ) {
796 LOG_ERROR <<
"invalid property name \"" <<
pname <<
"\" in component " << componentName
797 <<
" (invalid Python identifier)" << std::endl;
798 m_db2Buf <<
" #ERROR-invalid identifier '" <<
pname <<
"'\n";
803 string pvalue, ptype;
804 pythonizeValue( prop, pvalue, ptype );
806 m_db2Buf <<
" '" <<
pname <<
"': ('" << ptype <<
"', " << pvalue <<
", '''" << prop->documentation()
807 <<
" [" << prop->ownerTypeName() <<
"]'''";
808 auto sem = prop->semantics();
809 if ( !sem.empty() ) { m_db2Buf <<
", '" << sem <<
'\''; }
813 m_db2Buf <<
" },\n },\n";
822 const std::string cvalue = p->
toString();
823 const std::type_index ti = std::type_index( *p->
type_info() );
826 if ( ti == typeIndex<bool>() ) {
827 pvalue = ( cvalue ==
"0" || cvalue ==
"False" || cvalue ==
"false" ) ?
"False" :
"True";
828 }
else if ( ti == typeIndex<char>() || ti == typeIndex<signed char>() || ti == typeIndex<unsigned char>() ||
829 ti == typeIndex<short>() || ti == typeIndex<unsigned short>() || ti == typeIndex<int>() ||
830 ti == typeIndex<unsigned int>() || ti == typeIndex<long>() || ti == typeIndex<unsigned long>() ||
831 ti == typeIndex<long long>() || ti == typeIndex<unsigned long long>() ) {
833 }
else if ( ti == typeIndex<float>() || ti == typeIndex<double>() ) {
835 pvalue = boost::to_lower_copy( cvalue );
836 if ( std::string::npos != pvalue.find(
"nan" ) ) {
837 pvalue =
"float('nan')";
838 }
else if ( std::string::npos == pvalue.find(
"." ) && std::string::npos == pvalue.find(
"e" ) ) {
839 pvalue = cvalue +
".0";
841 }
else if ( ti == typeIndex<string>() ) {
842 pvalue = quote( cvalue );
843 }
else if ( ti == typeIndex<GaudiHandleBase>() ) {
847 pvalue =
base.pythonRepr();
848 ptype =
base.pythonPropertyClassName();
849 m_importGaudiHandles =
true;
850 }
else if ( ti == typeIndex<GaudiHandleArrayBase>() ) {
854 pvalue =
base.pythonRepr();
855 ptype =
base.pythonPropertyClassName();
856 m_importGaudiHandles =
true;
861 pvalue =
base.pythonRepr();
862 m_importDataHandles =
true;
864 std::ostringstream v_str;
865 v_str.setf( std::ios::showpoint );
867 pvalue = v_str.str();
878 if ( !propMgr || !appUI )
return EXIT_FAILURE;
882 propMgr->setProperty(
"AppName",
"" ).
ignore( );
884 propMgr->setProperty(
"OutputLevel", 7 ).
ignore( );
886 appUI->configure().ignore( );
888 msgSvc->setPropertyRepr(
"setWarning",
"['DefaultName', 'PropertyHolder']" )
890 msgSvc->setProperty(
"Format",
"%T %0W%M" ).ignore( );