def _addApplicationToCMake(self): # Locate the CMake file srcFile = self._appDir + "CMakeLists.txt" dstFile = self._appDir + "CMakeLists.txt.tmp" msgCount = 0 # We can check it this way, as is not that large with open(srcFile, 'r') as src: if self._nameCamel in src.read(): msg = Formatc([ {'color': bcolors.WARNING, 'msg': '[WARNING]'}, {'color': bcolors.CYAN, 'msg': ' {}'.format(self._nameCamel+'Application')}, {'color': None, 'msg': ' already has an entry in "'}, {'color': bcolors.CYAN, 'msg': '{}'.format('CMakeLists.txt')}, {'color': None, 'msg': '". Skipping step.'}, ], sys.stderr) print(msg, file=sys.stderr) return with open(srcFile, 'r') as src, open(dstFile, 'w+') as dst: for l in src: # Skip the first message if 'message( " ")' in l and msgCount == 0: msgCount += 1 # Add the applciation to the list message elif 'message( " ")' in l and msgCount == 1: newLine = '' newLine += 'message("' + self._nameUpper + '_APPLICATION' newLine += ('.' * (24 - len(self._nameUpper))) newLine += ' ${' + self._nameUpper + '_APPLICATION}")\n' dst.write(newLine) # TODO: Probably is not a good idea to use the end comment as a # token for adding this, but we cannot use the end of the file # until that same comment is removed # Write the add subdirectory clause if '# get_property(inc_dirs DIRECTORY PROPERTY INCLUDE_DIRECTORIES)' in l: dst.write('if(${' + self._nameUpper + '_APPLICATION} MATCHES ON)\n') dst.write(' add_subdirectory(' + self._nameCamel+'Application)\n') dst.write('endif(${' + self._nameUpper + '_APPLICATION} MATCHES ON)\n') dst.write('\n') # Write the old line dst.write(l) # Replace the old file with the new one os.remove(srcFile) os.rename(dstFile, srcFile)
def GetRule(self, ruleName): try: return next(r for r in self.rules if r['token'] == ruleName) except: msg = Formatc([ {'color': bcolors.FAIL, 'msg': '[ERROR]'}, {'color': None, 'msg': ' Rule: "'}, {'color': bcolors.CYAN, 'msg': '{}'.format(ruleName)}, {'color': None, 'msg': '" does not exist'}, ], sys.stderr) raise ValueError(msg)
def __init__(self, name): super(ApplicationGenerator, self).__init__() appStrPos = name.lower().find('application') maxi = 5 while appStrPos != -1 and maxi > 0: oldname = name name = name[0:appStrPos] + name[appStrPos+len('application'):len(name)] msg = Formatc([ {'color': bcolors.WARNING, 'msg': '[WARNING]'}, {'color': bcolors.CYAN, 'msg': ' {}'.format(oldname)}, {'color': None, 'msg': ' already contains the substring "'}, {'color': bcolors.CYAN, 'msg': '{}'.format('Application')}, {'color': None, 'msg': '". Removing... : '+name}, ], sys.stderr) print(msg, file=sys.stderr) appStrPos = name.lower().find('application') maxi = maxi -1 if difflib.SequenceMatcher(None, name.lower(), 'application').ratio() > 0.65: msg = Formatc([ {'color': bcolors.WARNING, 'msg': '[WARNING]'}, {'color': None, 'msg': ' Your application name contains something wrong after automatic fix, please select another name.'}, ], sys.stderr) print(msg, file=sys.stderr) exit() self._appDir = GetApplicationsDirectory() self._nameCamel = name self._nameUpper = ToUpperFromCamel(self._nameCamel) self._nameLower = ToLowerFromCamel(self._nameCamel) self._elements = [] self._conditions = [] self._processes = [] self._strategies = [] self._variables = [] self.isDerived = False # Define the application tree rules ( directory names, files, etc...) self.rules += [ {'token': '@{APP_NAME_CAMEL}', 'value': self._nameCamel}, {'token': '@{APP_NAME_CAPS}', 'value': self._nameUpper}, {'token': '@{APP_NAME_LOW}', 'value': self._nameLower}, {'token': '@{APP_DEPEND_LIST}', 'value': ''}, {'token': '@{APP_SOURCE_LIST}', 'value': ''} ] # Define the templates files needed for every class self._classTemplateFiles = { 'Elements': ['element_template.cpp', 'element_template.h'], 'Conditions': ['condition_template.cpp', 'condition_template.h'], 'Processes': ['process_template.cpp', 'process_template.h'], 'Variables': [ self._nameLower+'_application.h', self._nameLower+'_application.cpp', self._nameLower+'_application_variables.h', self._nameLower+'_application_variables.cpp', 'custom_python/' + self._nameLower+'_python_application.cpp', ] } # Define where the generated classes should be placed self._classTemplatePath = { 'Elements': ['classes', 'custom_elements'], 'Conditions': ['classes', 'custom_conditions'], 'Processes': ['classes', 'custom_processes'] }
def _addApplicationToAppList(self): # Locate the applications lists srcFile = self._appDir + "applications_interface.py" dstFile = self._appDir + "applications_interface.py.tmp" # For this file is just easier to reconstruct the whole thing fileStruct = { 'header': [], 'importFalseBlock': [], 'printMsgBlock': [], 'appDirBlock': [], 'importValueBlock': [], 'prepareBlock': [], 'initializeBlock': [], 'footer': [], } currentBlock = 'header' # We can check it this way, as is not that large with open(srcFile, 'r') as src: if self._nameCamel in src.read(): msg = Formatc([ {'color': bcolors.WARNING, 'msg': '[WARNING]'}, {'color': bcolors.CYAN, 'msg': ' {}'.format(self._nameCamel+'Application')}, {'color': None, 'msg': ' already has an entry in "'}, {'color': bcolors.CYAN, 'msg': '{}'.format('applications_interface.py')}, {'color': None, 'msg': '". Skipping step.'}, ], sys.stderr) print(msg, file=sys.stderr) return # First read the file and parse all the info with open(srcFile, 'r') as src: for l in src: # Select the block if 'Import_' in l and 'Application = False' in l: currentBlock = 'importFalseBlock' if 'print("Applications Available:")' in l and currentBlock == 'importFalseBlock': currentBlock = 'printMsgBlock' if 'application_directory = os.path.dirname' in l and currentBlock == 'printMsgBlock': currentBlock = 'appDirBlock' if 'def ImportApplications' in l and currentBlock == 'appDirBlock': currentBlock = 'importValueBlock' if 'if(Import_' in l and currentBlock == 'importValueBlock': currentBlock = 'prepareBlock' if '# dynamic renumbering of variables' in l and currentBlock == 'prepareBlock': currentBlock = 'initializeBlock' if '# def ImportApplications(kernel ):' in l and currentBlock == 'initializeBlock': currentBlock = 'footer' # Append the result if its not null if l is not '\n' or currentBlock == 'prepareBlock': fileStruct[currentBlock].append(l) # Prepare some blocks prepareBlockContent = [ ptab + 'if(Import_{CAMEL}Application):\n', ptab * 2 + 'print("importing Kratos{CAMEL}Application ...")\n', ptab * 2 + 'sys.path.append(applications_path + \'/{CAMEL}/python_scripts\')\n', ptab * 2 + 'sys.path.append(applications_path + \'/{CAMEL}/Linux\')\n', ptab * 2 + 'from Kratos{CAMEL}Application import *\n', ptab * 2 + '{LOWER}_application = Kratos{CAMEL}Application()\n', ptab * 2 + 'kernel.ImportApplication({LOWER}_application)\n', ptab * 2 + 'print("Kratos{CAMEL}Application Succesfully imported")\n', '\n' ] prepareBlockContent = [ s.format( CAMEL=self._nameCamel, LOWER=self._nameLower ) for s in prepareBlockContent] # Add our application to the requeired blocks fileStruct['importFalseBlock'].append( 'Import_' + self._nameCamel + 'Application = False\n' ) fileStruct['printMsgBlock'].append( 'print("Import_' + self._nameCamel + 'Application: False")\n' ) fileStruct['importValueBlock'].append( ptab + 'print("Import_{CAMEL}Application: " + str(Import_{CAMEL}Application))\n'.format( CAMEL=self._nameCamel) ) fileStruct['prepareBlock'].append( prepareBlockContent ) fileStruct['initializeBlock'].append([ ptab + 'if(Import_' + self._nameCamel + 'Application):\n', ptab * 2 + 'kernel.InitializeApplication(' + self._nameLower + '_application)\n' ]) # Write the whole thing down with open(dstFile, 'w+') as dst: for l in fileStruct['header']: dst.write(l) dst.write('\n') for l in fileStruct['importFalseBlock']: dst.write(l) dst.write('\n') for l in fileStruct['printMsgBlock']: dst.write(l) dst.write('\n') for l in fileStruct['appDirBlock']: dst.write(l) dst.write('\n') for l in fileStruct['importValueBlock']: dst.write(l) dst.write('\n') for b in fileStruct['prepareBlock']: for l in b: dst.write(l) dst.write('\n') for b in fileStruct['initializeBlock']: for l in b: dst.write(l) dst.write('\n') for l in fileStruct['footer']: dst.write(l) # Replace the old file with the new one os.remove(srcFile) os.rename(dstFile, srcFile)
def __init__(self, name, vtype=None, default=None): # This wil be extended with valid and invalid types if vtype is None: msg = Formatc([ { 'color': bcolors.FAIL, 'msg': '[ERROR]' }, { 'color': None, 'msg': ' while creating variable: "' }, { 'color': bcolors.CYAN, 'msg': '{}'.format(name) }, { 'color': None, 'msg': '" :No type defined' }, ], sys.stderr) raise ValueError(msg) self.isRef = '&' in vtype self.isPtr = '*' in vtype self.isStatic = 'static' in vtype self.default = default if self.isRef and self.default is None: msg = Formatc([ { 'color': bcolors.WARNING, 'msg': '[WARNING]' }, { 'color': None, 'msg': ' while creating variable: "' }, { 'color': bcolors.CYAN, 'msg': '{}'.format(name) }, { 'color': None, 'msg': '" : Reference variable without default value.' }, ], sys.stderr) print(msg, file=sys.stderr) if self.isStatic and self.default is not None: msg = Formatc([ { 'color': bcolors.WARNING, 'msg': '[WARNING]' }, { 'color': None, 'msg': ' while creating variable: "' }, { 'color': bcolors.CYAN, 'msg': '{}'.format(name) }, { 'color': None, 'msg': '" : static variable default values are not currently supported.\n' }, { 'color': None, 'msg': 'Variable will be left unitialized' }, ], sys.stderr) print(msg, file=sys.stderr) self.default = None self.name = name self.type = vtype
def __init__( self, name, base=None, template=None, members=None, procedures=None, author='KratosAppGenerator' ): # Check that name is in camelcase, or at least something parseable super(ClassCreator, self).__init__() if not TestCamel(name): msg = Formatc([ {'color': bcolors.FAIL, 'msg': '[ERROR]'}, {'color': None, 'msg': ' Name: "'}, {'color': bcolors.CYAN, 'msg': '{}'.format(name)}, {'color': None, 'msg': '" is not camelcase'}, ], sys.stderr) raise ValueError(msg) # Check name, if a class already exists with that name in the context # specified, ask if you want to continue. In case of continuing a # warning message will be shown (in red?) and a backup of the class # will be created. self.author = author self.nameCamel = name self.nameUpper = ToUpperFromCamel(name) self.nameLower = ToLowerFromCamel(name) self.baseHead = [': public ' + base, ''][base is None] self.base = base self.template = template self.procedures = procedures # List of common rules for all classes self.rules += [ {'token': '@{KRATOS_APP_AUTHOR}', 'value': ', '+self.author}, {'token': '@{KRATOS_NAME_CAMEL}', 'value': self.nameCamel}, {'token': '@{KRATOS_NAME_UPPER}', 'value': self.nameUpper}, {'token': '@{KRATOS_NAME_LOWER}', 'value': self.nameLower}, {'token': '@{KRATOS_CLASS_BASE}', 'value': self.base}, {'token': '@{KRATOS_CLASS_BASE_HEADER}', 'value': self.baseHead}, {'token': '@{KRATOS_SYSTEM_INCLUDES}', 'value': ''}, {'token': '@{KRATOS_EXTERNAL_INCLUDES}', 'value': ''}, {'token': '@{KRATOS_PROJECT_INCLUDES}', 'value': ''}, {'token': '@{KRATOS_CLASS_TEMPLATE}', 'value': ''}, {'token': '@{KRATOS_INCLUDE_LIST}', 'value': ''}, {'token': '@{KRATOS_MEMBERS_LIST}', 'value': ''}, {'token': '@{KRATOS_STATIC_MEMBERS_LIST}', 'value': ''}, {'token': '@{KRATOS_INIT_MEMBER_LIST}', 'value': ''}, {'token': '@{KRATOS_CC_INIT_MEMBER_LIST}', 'value': ''}, {'token': '@{KRATOS_ASIGN_INIT_MEMBER_LIST}', 'value': ''}, {'token': '@{KRATOS_PROCEDURES_LIST}', 'value': ''} ] [a, b, c, d] = self._CheckClassNameAvailable( self.nameCamel, "Kratos", True ) for m in c.values(): msg = Formatc([ {'color': bcolors.FAIL, 'msg': '[ERROR]'}, {'color': None, 'msg': ' Class with name: "'}, {'color': bcolors.CYAN, 'msg': '{}'.format(name)}, {'color': None, 'msg': '" already defined in:'}, ], sys.stderr) print(msg, file=sys.stderr) print(" ["+m[0]+"]: \""+m[1].replace("\n", "")+"\""+"\n", file=sys.stderr) for m in d.values(): msg = Formatc([ {'color': bcolors.WARNING, 'msg': '[WARNING]'}, {'color': None, 'msg': ' Class with name: "'}, {'color': bcolors.CYAN, 'msg': '{}'.format(name)}, {'color': None, 'msg': '" probably ({}%) defined in:'.format( str(m[2]*100))}, ], sys.stderr) print(msg, file=sys.stderr) print(" ["+m[0]+"]: \""+m[1].replace("\n", "")+"\""+"\n", file=sys.stderr)