def _build_document(self): """Take the internal fields dictionary, the _root_elem_name, and the style sheet url to build an xml document. """ # check for all required xml fields fields_known = self._fields.keys() fields_known.sort() for requiredKey in self._required_fields: if requiredKey not in fields_known: raise DashXMLLogException("Missing Required Field %s" % requiredKey) doc = Document() processingInstr = doc.createProcessingInstruction( "xml-stylesheet", "type=\"text/xsl\" href=\"%s\"" % self._style_sheet_url) doc.appendChild(processingInstr) # create the base element base = doc.createElement(self._root_elem_name) doc.appendChild(base) for key in fields_known: elem = doc.createElement(key) base.appendChild(elem) val = doc.createTextNode("%s" % self._fields[key]) elem.appendChild(val) return doc
def go(tests, output_prefix) : """genere les balises de tests de l arbre xml et leurs contenus.""" from xml.dom.minidom import Document doc = Document()#creation du document doc.appendChild(doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"report.xsl\"")) testsElt = doc.createElement("tests")#creation du noeud "tests" doc.appendChild(testsElt) #creation des noeuds "test" et de leurs contenus for test in tests: testElt = doc.createElement("test") testsElt.appendChild(testElt) #construction du noeud diagnostic testElt.appendChild(serializeDiagnostic(doc, test["diagnostic"])) #creation du noeud "comparisons" comparisons = doc.createElement("comparisons") #pour chaque instance de comparaison for comparison in test["comparisons"]: comparisons.appendChild(serializeComparison(doc, comparison)) testElt.appendChild(comparisons) output_file = os.path.join(output_prefix, 'report.xml') output_file_xsl = os.path.join(output_prefix, 'report.xsl') #on genere le fichier xml logfile = open(output_file, 'w') logfile.write(doc.toprettyxml(indent=" ", encoding="UTF-8")) logfile.close() print 'Le fichier résultat est', output_file # copie de la feuille xsl shutil.copyfile('xslt/report.xsl', output_file_xsl)
def impl_create_pydevproject(self, appname, system_path, user_path): # create a pydevproject file doc = Document() doc.appendChild(doc.createProcessingInstruction("eclipse-pydev", 'version="1.0"')) pydevproject = doc.createElement("pydev_project") prop = self.add( doc, pydevproject, "pydev_property", "python %d.%d" % (sys.version_info[0], sys.version_info[1]) ) prop.setAttribute("name", "org.python.pydev.PYTHON_PROJECT_VERSION") prop = self.add(doc, pydevproject, "pydev_property", "Default") prop.setAttribute("name", "org.python.pydev.PYTHON_PROJECT_INTERPRETER") # add waf's paths wafadmin = [p for p in system_path if p.find("wafadmin") != -1] if wafadmin: prop = self.add( doc, pydevproject, "pydev_pathproperty", {"name": "org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH"} ) for i in wafadmin: self.add(doc, prop, "path", i) if user_path: prop = self.add(doc, pydevproject, "pydev_pathproperty", {"name": "org.python.pydev.PROJECT_SOURCE_PATH"}) for i in user_path: self.add(doc, prop, "path", "/" + appname + "/" + i) doc.appendChild(pydevproject) return doc
def dumps(self, obj): """ Dump the given object which may be a container of any objects supported by the reports added to the manager. """ document = Document() if self.stylesheet: type = "text/xsl" href = "file://%s" % posixpath.abspath(self.stylesheet) style = document.createProcessingInstruction("xml-stylesheet", "type=\"%s\" href=\"%s\"" % (type, href)) document.appendChild(style) node = document.createElement(self.name) document.appendChild(node) if self.version: node.setAttribute("version", self.version) try: self.call_dumps(obj, node) except KeyError as e: raise ValueError("Unsupported type: %s" % e) return document
def dumps(self, obj): """ Dump the given object which may be a container of any objects supported by the reports added to the manager. """ document = Document() if self.stylesheet: type = "text/xsl" href = "file://%s" % posixpath.abspath(self.stylesheet) style = document.createProcessingInstruction( "xml-stylesheet", "type=\"%s\" href=\"%s\"" % (type, href)) document.appendChild(style) node = document.createElement(self.name) document.appendChild(node) if self.version: node.setAttribute("version", self.version) try: self.call_dumps(obj, node) except KeyError as e: raise ValueError("Unsupported type: %s" % e) return document
def impl_create_pydevproject(self, system_path, user_path): # create a pydevproject file doc = Document() doc.appendChild(doc.createProcessingInstruction('eclipse-pydev', 'version="1.0"')) pydevproject = doc.createElement('pydev_project') prop = self.add(doc, pydevproject, 'pydev_property', 'python %d.%d'%(sys.version_info[0], sys.version_info[1])) prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_VERSION') prop = self.add(doc, pydevproject, 'pydev_property', 'Default') prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_INTERPRETER') # add waf's paths wafadmin = [p for p in system_path if p.find('wafadmin') != -1] if wafadmin: prop = self.add(doc, pydevproject, 'pydev_pathproperty', {'name':'org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH'}) for i in wafadmin: self.add(doc, prop, 'path', i) if user_path: prop = self.add(doc, pydevproject, 'pydev_pathproperty', {'name':'org.python.pydev.PROJECT_SOURCE_PATH'}) for i in user_path: self.add(doc, prop, 'path', '/${PROJECT_DIR_NAME}/'+i) doc.appendChild(pydevproject) return doc
def impl_create_pydevproject(self, appname, system_path, user_path): # create a pydevproject file doc = Document() doc.appendChild(doc.createProcessingInstruction('eclipse-pydev', 'version="1.0"')) pydevproject = doc.createElement('pydev_project') prop = self.add(doc, pydevproject, 'pydev_property', 'python %d.%d'%(sys.version_info[0], sys.version_info[1])) prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_VERSION') prop = self.add(doc, pydevproject, 'pydev_property', 'Default') prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_INTERPRETER') # add waf's paths wafadmin = [p for p in system_path if p.find('wafadmin') != -1] if wafadmin: prop = self.add(doc, pydevproject, 'pydev_pathproperty', {'name':'org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH'}) for i in wafadmin: self.add(doc, prop, 'path', i) if user_path: prop = self.add(doc, pydevproject, 'pydev_pathproperty', {'name':'org.python.pydev.PROJECT_SOURCE_PATH'}) for i in user_path: self.add(doc, prop, 'path', '/'+appname+'/'+i) doc.appendChild(pydevproject) return doc
def createXML(IRDtestResults): # Create the minidom document doc = Document() # create the Tests container: root = doc.createElement("IRDTests") doc.appendChild(root) #XSL processing instruction: pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="testResult.xslt"') root = doc.firstChild doc.insertBefore(pi, root) IRDs = list() failedIRDs = list() # add the test results: tests = doc.createElement("Tests") root.appendChild(tests) for irdResult in IRDtestResults: test = doc.createElement("Test") test.setAttribute("id", str(irdResult.TestId).lower()) test.setAttribute("IRD", irdResult.IRD) if not irdResult.IRD in IRDs: IRDs.append(irdResult.IRD) if(not irdResult.bIsPass): if not irdResult.IRD in failedIRDs: failedIRDs.append(irdResult.IRD) test.setAttribute("pass", str(irdResult.bIsPass).lower()) tests.appendChild(test) IRDs.sort() failedIRDs.sort() #add summary of IRDs: IRDsNode = doc.createElement("IRDs") root.appendChild(IRDsNode) for IRD in IRDs: irdNode = doc.createElement("IRD") IRDsNode.appendChild(irdNode) irdNode.setAttribute("name", IRD) bSuccess = True if IRD in failedIRDs: bSuccess = False irdNode.setAttribute("pass", str(bSuccess).lower()) return doc
def main(args): # Input file should be called men.csv filename = 'men.csv' # The XML nodes will be named <bot> single_item = 'bot' safe_filename = filename[:-4] try: f = csv.reader(open(filename, 'r')) except IOError: print('ERROR: Input file men.csv not found in current working directory') sys.exit(1) doc = Document() # Use the file name as the root node name root_element = doc.createElement(safe_filename) doc.appendChild(root_element) # Add the style sheet info pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl"' 'href="men.xsl"') doc.insertBefore(pi, doc.firstChild) # Get the header row from the csv file # If it's missing or short, use a default columns = next(f) if len(columns) < 4: columns = ['ipaddress','port','seq_no','active'] # Remove white space from around column names for i in range(len(columns)): columns[i] = columns[i].strip() # Populate the XML document index = 0 for row in f: index += 1 item = doc.createElement(single_item) item.setAttribute('id', str(index)) root_element.appendChild(item) for c in enumerate(create_col_nodes(columns, item, doc)): # jpo: Strip white space from node entries row[0] = row[0].strip() c[1].appendChild(doc.createTextNode(row.pop(0))) output_file = safe_filename + ".xml" # jpo: Add indents and newlines to the XML output doc.writexml(open(output_file, 'w'), ' ' * 2, ' ' * 2, '\n') # Write file print("Done: Created %s" % output_file)
def main(args): # Input file should be called men.csv filename = 'men.csv' # The XML nodes will be named <bot> single_item = 'bot' safe_filename = filename[:-4] try: f = csv.reader(open(filename, 'r')) except IOError: print( 'ERROR: Input file men.csv not found in current working directory') sys.exit(1) doc = Document() # Use the file name as the root node name root_element = doc.createElement(safe_filename) doc.appendChild(root_element) # Add the style sheet info pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl"' 'href="men.xsl"') doc.insertBefore(pi, doc.firstChild) # Get the header row from the csv file # If it's missing or short, use a default columns = next(f) if len(columns) < 4: columns = ['ipaddress', 'port', 'seq_no', 'active'] # Remove white space from around column names for i in range(len(columns)): columns[i] = columns[i].strip() # Populate the XML document index = 0 for row in f: index += 1 item = doc.createElement(single_item) item.setAttribute('id', str(index)) root_element.appendChild(item) for c in enumerate(create_col_nodes(columns, item, doc)): # jpo: Strip white space from node entries row[0] = row[0].strip() c[1].appendChild(doc.createTextNode(row.pop(0))) output_file = safe_filename + ".xml" # jpo: Add indents and newlines to the XML output doc.writexml(open(output_file, 'w'), ' ' * 2, ' ' * 2, '\n') # Write file print("Done: Created %s" % output_file)
class XMLDocument: def __init__(self, listRetreived, setWords): # Create the minidom document self.doc = Document() self.listRetreived = listRetreived self.setWords = setWords def getXML(self): # <!DOCTYPE Resultado SYSTEM "Resultados.dtd"> self.doc.appendChild(self.doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"Resultados.xsl\"")) Resultado = self.doc.createElement("Resultado") self.doc.appendChild(Resultado) Pregunta = self.doc.createElement("Pregunta") Resultado.appendChild(Pregunta) for word in self.setWords: Item = self.doc.createElement("Item") Pregunta.appendChild(Item) textItem = self.doc.createTextNode("%s" %(word)) Item.appendChild(textItem) for element in self.listRetreived: Documento = self.doc.createElement("Documento") Documento.setAttribute("ID", "%s" %(element[0])) Resultado.appendChild(Documento) Titulo = self.doc.createElement("Titulo") Documento.appendChild(Titulo) textTitulo = self.doc.createTextNode("%s" %(element[1])) Titulo.appendChild(textTitulo) Relevancia = self.doc.createElement("Relevancia") Documento.appendChild(Relevancia) textRelevancia = self.doc.createTextNode('%s' %(element[3])) Relevancia.appendChild(textRelevancia) Texto = self.doc.createElement("Texto") Documento.appendChild(Texto) text = self.doc.createTextNode("%s" %(element[2])) Texto.appendChild(text) return self.doc.toprettyxml(indent="\t")
def export(results, handle): '''save the chats in results (from get_chats or get_chats_between) as xml to handle (file like object) the caller is responsible of closing the handle ''' from xml.dom.minidom import Document doc = Document() doc.appendChild( doc.createProcessingInstruction( "xml-stylesheet", "type=\"text/css\" href=\"conversation.css\"")) conversation = doc.createElement("conversation") doc.appendChild(conversation) for stat, timestamp, message, nick, account in results: timestamp_tag = doc.createElement("timestamp") date_text = time.strftime('[%c]', time.gmtime(timestamp)) timestamp_text = doc.createTextNode(date_text) timestamp_tag.appendChild(timestamp_text) nick_tag = doc.createElement("nick") nick_text = doc.createTextNode(nick) nick_tag.appendChild(nick_text) timestamp_tag.appendChild(nick_tag) status_tag = doc.createElement("status") status_text = doc.createTextNode(str(stat)) status_tag.appendChild(status_text) timestamp_tag.appendChild(status_tag) account_tag = doc.createElement("account") account_text = doc.createTextNode(account) account_tag.appendChild(account_text) timestamp_tag.appendChild(account_tag) message_tag = doc.createElement("message") message_text = doc.createTextNode(message) message_tag.appendChild(message_text) timestamp_tag.appendChild(message_tag) conversation.appendChild(timestamp_tag) handle.write(doc.toprettyxml(indent=" ", encoding="UTF-8"))
def save_logs_as_xml(results, handle): '''save the chats in results (from get_chats or get_chats_between) as xml to handle (file like object) the caller is responsible of closing the handle ''' from xml.dom.minidom import Document doc = Document() doc.appendChild(doc.createProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"conversation.css\"")) conversation = doc.createElement("conversation") doc.appendChild(conversation) for stat, timestamp, message, nick, account in results: timestamp_tag = doc.createElement("timestamp") date_text = time.strftime('[%c]', time.gmtime(timestamp)) timestamp_text = doc.createTextNode(date_text) timestamp_tag.appendChild(timestamp_text) nick_tag = doc.createElement("nick") nick_text = doc.createTextNode(nick) nick_tag.appendChild(nick_text) timestamp_tag.appendChild(nick_tag) status_tag = doc.createElement("status") status_text = doc.createTextNode(str(stat)) status_tag.appendChild(status_text) timestamp_tag.appendChild(status_tag) account_tag = doc.createElement("account") account_text = doc.createTextNode(account) account_tag.appendChild(account_text) timestamp_tag.appendChild(account_tag) message_tag = doc.createElement("message") message_text = doc.createTextNode(message) message_tag.appendChild(message_text) timestamp_tag.appendChild(message_tag) conversation.appendChild(timestamp_tag) handle.write(doc.toprettyxml(indent=" ", encoding="UTF-8"))
def impl_create_pydevproject(self, system_path, user_path): # create a pydevproject file doc = Document() doc.appendChild( doc.createProcessingInstruction("eclipse-pydev", 'version="1.0"')) pydevproject = doc.createElement("pydev_project") prop = self.add( doc, pydevproject, "pydev_property", "python %d.%d" % (sys.version_info[0], sys.version_info[1]), ) prop.setAttribute("name", "org.python.pydev.PYTHON_PROJECT_VERSION") prop = self.add(doc, pydevproject, "pydev_property", "Default") prop.setAttribute("name", "org.python.pydev.PYTHON_PROJECT_INTERPRETER") # add waf's paths wafadmin = [p for p in system_path if p.find("wafadmin") != -1] if wafadmin: prop = self.add( doc, pydevproject, "pydev_pathproperty", {"name": "org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH"}, ) for i in wafadmin: self.add(doc, prop, "path", i) if user_path: prop = self.add( doc, pydevproject, "pydev_pathproperty", {"name": "org.python.pydev.PROJECT_SOURCE_PATH"}, ) for i in user_path: self.add(doc, prop, "path", "/${PROJECT_DIR_NAME}/" + i) doc.appendChild(pydevproject) return doc
def impl_create_cproject(self, executable, waf, appname, workspace_includes, cpppath, source_dirs=[]): doc = Document() doc.appendChild(doc.createProcessingInstruction('fileVersion', '4.0.0')) cconf_id = cdt_core + '.default.config.1' cproject = doc.createElement('cproject') storageModule = self.add(doc, cproject, 'storageModule', {'moduleId': cdt_core + '.settings'}) cconf = self.add(doc, storageModule, 'cconfiguration', {'id':cconf_id}) storageModule = self.add(doc, cconf, 'storageModule', {'buildSystemId': oe_cdt + '.managedbuilder.core.configurationDataProvider', 'id': cconf_id, 'moduleId': cdt_core + '.settings', 'name': 'Default'}) self.add(doc, storageModule, 'externalSettings') extensions = self.add(doc, storageModule, 'extensions') extension_list = """ VCErrorParser MakeErrorParser GCCErrorParser GASErrorParser GLDErrorParser """.split() ext = self.add(doc, extensions, 'extension', {'id': cdt_core + '.ELF', 'point':cdt_core + '.BinaryParser'}) for e in extension_list: ext = self.add(doc, extensions, 'extension', {'id': cdt_core + '.' + e, 'point':cdt_core + '.ErrorParser'}) storageModule = self.add(doc, cconf, 'storageModule', {'moduleId': 'cdtBuildSystem', 'version': '4.0.0'}) config = self.add(doc, storageModule, 'configuration', {'artifactName': appname, 'id': cconf_id, 'name': 'Default', 'parent': cdt_bld + '.prefbase.cfg'}) folderInfo = self.add(doc, config, 'folderInfo', {'id': cconf_id+'.', 'name': '/', 'resourcePath': ''}) toolChain = self.add(doc, folderInfo, 'toolChain', {'id': cdt_bld + '.prefbase.toolchain.1', 'name': 'No ToolChain', 'resourceTypeBasedDiscovery': 'false', 'superClass': cdt_bld + '.prefbase.toolchain'}) targetPlatform = self.add(doc, toolChain, 'targetPlatform', { 'binaryParser': 'org.eclipse.cdt.core.ELF', 'id': cdt_bld + '.prefbase.toolchain.1', 'name': ''}) waf_build = '"%s" %s'%(waf, eclipse.fun) waf_clean = '"%s" clean'%(waf) builder = self.add(doc, toolChain, 'builder', {'autoBuildTarget': waf_build, 'command': executable, 'enableAutoBuild': 'false', 'cleanBuildTarget': waf_clean, 'enableIncrementalBuild': 'true', 'id': cdt_bld + '.settings.default.builder.1', 'incrementalBuildTarget': waf_build, 'managedBuildOn': 'false', 'name': 'Gnu Make Builder', 'superClass': cdt_bld + '.settings.default.builder'}) for tool_name in ("Assembly", "GNU C++", "GNU C"): tool = self.add(doc, toolChain, 'tool', {'id': cdt_bld + '.settings.holder.1', 'name': tool_name, 'superClass': cdt_bld + '.settings.holder'}) if cpppath or workspace_includes: incpaths = cdt_bld + '.settings.holder.incpaths' option = self.add(doc, tool, 'option', {'id': incpaths+'.1', 'name': 'Include Paths', 'superClass': incpaths, 'valueType': 'includePath'}) for i in workspace_includes: self.add(doc, option, 'listOptionValue', {'builtIn': 'false', 'value': '"${workspace_loc:/%s/%s}"'%(appname, i)}) for i in cpppath: self.add(doc, option, 'listOptionValue', {'builtIn': 'false', 'value': '"%s"'%(i)}) if source_dirs: sourceEntries = self.add(doc, config, 'sourceEntries') for i in source_dirs: self.add(doc, sourceEntries, 'entry', {'excluding': i, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': ''}) self.add(doc, sourceEntries, 'entry', { 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': i}) storageModule = self.add(doc, cconf, 'storageModule', {'moduleId': cdt_mk + '.buildtargets'}) buildTargets = self.add(doc, storageModule, 'buildTargets') def addTargetWrap(name, runAll): return self.addTarget(doc, buildTargets, executable, name, '"%s" %s'%(waf, name), runAll) addTargetWrap('configure', True) addTargetWrap('dist', False) addTargetWrap('install', False) addTargetWrap('check', False) storageModule = self.add(doc, cproject, 'storageModule', {'moduleId': 'cdtBuildSystem', 'version': '4.0.0'}) project = self.add(doc, storageModule, 'project', {'id': '%s.null.1'%appname, 'name': appname}) doc.appendChild(cproject) return doc
def xml(self,log4xml,Start_Time): Total,Pass,Fail=0,0,-len(self.result) for x in range(len(log4xml)): if log4xml[x].get('CODE') == '1': Total+=1 elif log4xml[x].get('CODE') == '0': Pass+=1 elif log4xml[x].get('CODE') == '-2' or log4xml[x].get('CODE') == '-1': Fail+=1 testPlan = 'wait for write' Hosename=os.popen('Hostname').read() doc = Document() abc = doc.createProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"cts_result.xsl\"") doc.appendChild(abc) Result = doc.createElement('TestResult') Result.setAttribute('testPlan', testPlan) Result.setAttribute('starttime', self.StartTime) Result.setAttribute('endtime', self.EndTime) Result.setAttribute('suite', 'QGP_Automation') doc.appendChild(Result) DeviceInfo = doc.createElement('DeviceInfo') Result.appendChild(DeviceInfo) BuildInfo =doc.createElement('BuildInfo') BuildInfo.setAttribute('productName', ADB_getValue().product_Name) BuildInfo.setAttribute('productModel', ADB_getValue().product_Model) BuildInfo.setAttribute('deviceID', serial_number) BuildInfo.setAttribute('AUVersion', ADB_getValue().version_AU) BuildInfo.setAttribute('METAVersion', ADB_getValue().version_Meta) BuildInfo.setAttribute('AndroidVersion', ADB_getValue().version_Release) BuildInfo.setAttribute('AndroidAPILevel', ADB_getValue().version_SDK) DeviceInfo.appendChild(BuildInfo) HostInfo =doc.createElement('HostInfo') HostInfo.setAttribute('name', Hosename) HostInfo.setAttribute('osversion', 'wait for write') HostInfo.setAttribute('osname', 'wait for write') Result.appendChild(HostInfo) Summary=doc.createElement('Summary') Summary.setAttribute('total',str(Total)) Summary.setAttribute('pass',str(Pass)) Summary.setAttribute('failed',str(Fail)) Result.appendChild(Summary) for y in range(len(self.result)): TestPackage=doc.createElement('TestPackage') TestPackage.setAttribute('name',self.result[y][:-4]) aaa=self.result[y][:-4].replace('-','') TestPackage.setAttribute('appPackageName',self.result[y][:-4])#wuyou TestSuite=doc.createElement('TestSuite') TestCase =doc.createElement('TestCase') for x in range(len(log4xml)): CLASS = log4xml[x].get('class') if CLASS !=None: className=CLASS.split('.') if className[1]==aaa: if log4xml[x].get('CODE') == '1': pass elif log4xml[x].get('CODE') == '-1': Test=doc.createElement('Test') Test.setAttribute('name',log4xml[x].get('test')) Test.setAttribute('result','fail') FailedScene=doc.createElement('FailedScene') FailedScene.setAttribute('message',log4xml[x].get('stack')) Test.appendChild(FailedScene) a1=log4xml[x].get('FailReason') if a1 !=None: StackTrace=doc.createElement('StackTrace') testR=doc.createTextNode(a1[0]) StackTrace.appendChild(testR) FailedScene.appendChild(StackTrace) TestCase.appendChild(Test) elif log4xml[x].get('CODE') == '0': Test=doc.createElement('Test') Test.setAttribute('name',log4xml[x].get('test')) Test.setAttribute('result','pass') TestCase.appendChild(Test) elif log4xml[x].get('CODE') == '-2': Test=doc.createElement('Test') Test.setAttribute('name',log4xml[x].get('test')) Test.setAttribute('result','fail') FailedScene=doc.createElement('FailedScene') FailedScene.setAttribute('message',log4xml[x].get('stack')) Test.appendChild(FailedScene) a1=log4xml[x].get('FailReason') if a1 !=None: #print a1 StackTrace=doc.createElement('StackTrace') testR=doc.createTextNode(a1[0]) StackTrace.appendChild(testR) FailedScene.appendChild(StackTrace) TestCase.appendChild(Test) else: pass TestSuite.appendChild(TestCase) TestPackage.appendChild(TestSuite) Result.appendChild(TestPackage) #f = open('C:\\Users\\c_youwu\\Desktop\\result\\testResult.xml','w') f = open('%s\\%s\\testResult.xml' % (QGP_Path().PATH_RESULTS,Start_Time) , 'w') f.write(doc.toprettyxml(indent = '',encoding='utf-8')) f.close() self.coverFiles(QGP_Path().PATH_DOCS,'%s\%s' % (QGP_Path().PATH_RESULTS,Start_Time))
import sys if len(sys.argv) != 3: sys.exit() dir = sys.argv[1] eventfile = dir + "SMSSend_monitoring.log" filefile = dir + "KernelFile_monitoring.log" networkfile = dir + "KernelNetwork_monitoring.log" smsfile = dir + "SMSSend_monitoring.log" urlfile = dir + "OutboundUrl_monitoring.log" xml = Document() pi = xml.createProcessingInstruction( 'xml-stylesheet', 'type="text/xsl" href="' + sys.argv[2] + '/m3style/styler.xls"') xml.appendChild(pi) analysis = xml.createElement("analysis") xml.appendChild(analysis) testStrategy = xml.createElement("testStrategy") testStrategy.setAttribute("name", "WidgetBasedRandomSelection") analysis.appendChild(testStrategy) events = xml.createElement("events") testStrategy.appendChild(events) actionset = xml.createElement("actionset") testStrategy.appendChild(actionset)
def impl_create_cproject(self, executable, waf_executable, appname, workspace_includes, cpppath, source_dirs=[]): doc = Document() doc.appendChild(doc.createProcessingInstruction('fileVersion', '4.0.0')) cconf_id = cdt_core + '.default.config.1' cproject = doc.createElement('cproject') storageModule = self.add(doc, cproject, 'storageModule', {'moduleId': cdt_core + '.settings'}) cconf = self.add(doc, storageModule, 'cconfiguration', {'id':cconf_id}) storageModule = self.add(doc, cconf, 'storageModule', {'buildSystemId': oe_cdt + '.managedbuilder.core.configurationDataProvider', 'id': cconf_id, 'moduleId': cdt_core + '.settings', 'name': 'Default'}) self.add(doc, storageModule, 'externalSettings') extensions = self.add(doc, storageModule, 'extensions') extension_list = """ VCErrorParser MakeErrorParser GCCErrorParser GASErrorParser GLDErrorParser """.split() self.add(doc, extensions, 'extension', {'id': cdt_core + '.ELF', 'point':cdt_core + '.BinaryParser'}) for e in extension_list: self.add(doc, extensions, 'extension', {'id': cdt_core + '.' + e, 'point':cdt_core + '.ErrorParser'}) storageModule = self.add(doc, cconf, 'storageModule', {'moduleId': 'cdtBuildSystem', 'version': '4.0.0'}) config = self.add(doc, storageModule, 'configuration', {'artifactName': appname, 'id': cconf_id, 'name': 'Default', 'parent': cdt_bld + '.prefbase.cfg'}) folderInfo = self.add(doc, config, 'folderInfo', {'id': cconf_id+'.', 'name': '/', 'resourcePath': ''}) toolChain = self.add(doc, folderInfo, 'toolChain', {'id': cdt_bld + '.prefbase.toolchain.1', 'name': 'No ToolChain', 'resourceTypeBasedDiscovery': 'false', 'superClass': cdt_bld + '.prefbase.toolchain'}) self.add(doc, toolChain, 'targetPlatform', {'binaryParser': 'org.eclipse.cdt.core.ELF', 'id': cdt_bld + '.prefbase.toolchain.1', 'name': ''}) waf_build = '"%s" %s'%(waf_executable, eclipse.fun) waf_clean = '"%s" clean'%(waf_executable) self.add(doc, toolChain, 'builder', {'autoBuildTarget': waf_build, 'command': executable, 'enableAutoBuild': 'false', 'cleanBuildTarget': waf_clean, 'enableIncrementalBuild': 'true', 'id': cdt_bld + '.settings.default.builder.1', 'incrementalBuildTarget': waf_build, 'managedBuildOn': 'false', 'name': 'Gnu Make Builder', 'superClass': cdt_bld + '.settings.default.builder'}) tool_index = 1; for tool_name in ("Assembly", "GNU C++", "GNU C"): tool = self.add(doc, toolChain, 'tool', {'id': cdt_bld + '.settings.holder.' + str(tool_index), 'name': tool_name, 'superClass': cdt_bld + '.settings.holder'}) if cpppath or workspace_includes: incpaths = cdt_bld + '.settings.holder.incpaths' option = self.add(doc, tool, 'option', {'id': incpaths + '.' + str(tool_index), 'name': 'Include Paths', 'superClass': incpaths, 'valueType': 'includePath'}) for i in workspace_includes: self.add(doc, option, 'listOptionValue', {'builtIn': 'false', 'value': '"${workspace_loc:/%s/%s}"'%(appname, i)}) for i in cpppath: self.add(doc, option, 'listOptionValue', {'builtIn': 'false', 'value': '"%s"'%(i)}) if tool_name == "GNU C++" or tool_name == "GNU C": self.add(doc,tool,'inputType',{ 'id':'org.eclipse.cdt.build.core.settings.holder.inType.' + str(tool_index), \ 'languageId':'org.eclipse.cdt.core.gcc' if tool_name == "GNU C" else 'org.eclipse.cdt.core.g++','languageName':tool_name, \ 'sourceContentType':'org.eclipse.cdt.core.cSource,org.eclipse.cdt.core.cHeader', \ 'superClass':'org.eclipse.cdt.build.core.settings.holder.inType' }) tool_index += 1 if source_dirs: sourceEntries = self.add(doc, config, 'sourceEntries') for i in source_dirs: self.add(doc, sourceEntries, 'entry', {'excluding': i, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': ''}) self.add(doc, sourceEntries, 'entry', { 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': i}) storageModule = self.add(doc, cconf, 'storageModule', {'moduleId': cdt_mk + '.buildtargets'}) buildTargets = self.add(doc, storageModule, 'buildTargets') def addTargetWrap(name, runAll): return self.addTarget(doc, buildTargets, executable, name, '"%s" %s'%(waf_executable, name), runAll) addTargetWrap('configure', True) addTargetWrap('dist', False) addTargetWrap('install', False) addTargetWrap('check', False) storageModule = self.add(doc, cproject, 'storageModule', {'moduleId': 'cdtBuildSystem', 'version': '4.0.0'}) self.add(doc, storageModule, 'project', {'id': '%s.null.1'%appname, 'name': appname}) doc.appendChild(cproject) return doc
class XmlDataGenerator: def __init__(self, xmlTDT, nonXmlPrint=None, xmlStyleData=None): from xml.dom.minidom import Document self.xmlDoc = Document() self.xmlTDT = xmlTDT eleCount = 0 self.eleMap = {} for eleTDT in self.xmlTDT: self.eleMap[eleTDT['name']] = eleCount if eleTDT.__contains__('alias'): for eName in eleTDT['alias']: self.eleMap[eName] = eleCount eleTDT['ele'] = None if not eleTDT.__contains__('cls'): eleTDT['cls'] = eleTDT['findex'] + 1 if not eleTDT.__contains__('sname'): eleTDT['sname'] = eleTDT['name'] if not eleTDT.__contains__('must'): eleTDT['must'] = True eleCount += 1 for eleTDT in self.xmlTDT: eleTDT['clslist'] = [ index for index in range(0, eleCount) if self.xmlTDT[index]['cls'] > eleTDT['cls'] ] self.topEle = self.__createElement(self.xmlDoc, self.xmlTDT[0]) if xmlStyleData != None: self.xmlDoc.insertBefore( self.xmlDoc.createProcessingInstruction( "xml-stylesheet", xmlStyleData), self.topEle) def __getFele(self, eleIndex): feleIndex = self.xmlTDT[eleIndex]['findex'] feleTDT = self.xmlTDT[feleIndex] if feleIndex > 0: fele = feleTDT['ele'] if fele == None: ffele = self.__getFele(feleIndex) if feleTDT['must']: fele = self.__createElement(ffele, feleTDT) else: fele = ffele return fele else: return self.topEle def __createElement(self, fele, eleTDT, content=None, eleName=None, **eleAttrs): ele = self.xmlDoc.createElement( eleName if eleName != None else eleTDT['sname']) eleTDT['ele'] = ele fele.appendChild(ele) for eleAttr in eleAttrs.keys(): ele.setAttribute(eleAttr, eleAttrs[eleAttr]) if content != None: ele.appendChild(self.xmlDoc.createCDATASection(content)) for index in eleTDT['clslist']: self.xmlTDT[index]['ele'] = None return ele def addElement(self, eleName, content=None, **eleAttrs): eleIndex = self.eleMap[eleName] fele = self.__getFele(eleIndex) self.__createElement(fele, self.xmlTDT[eleIndex], content, eleName, **eleAttrs) def __str__(self, indent="\t", newl="\n", encoding=None): return self.xmlDoc.toprettyxml(indent, newl, encoding)
#!/usr/bin/python import sys, os, re from xml.dom.minidom import Document tables=[] errors=[] ingroup = False currenttable = '' xmlDoc = Document() pi= xmlDoc.createProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"template.xsl\"") xmlDoc.insertBefore(pi, xmlDoc.documentElement) wml = xmlDoc.createElement("database") xmlDoc.appendChild(wml) schema = open(sys.argv[1], 'r') result = file(sys.argv[2],"w") createTablePattern = re.compile(r'^\s+create_table \"([a-z_-]+)\"',re.M|re.I) endTablePattern = re.compile(r'^\s+end',re.M|re.I) fieldPattern = re.compile(r'^\s+t\.[a-z]+\s+\"([a-z0-9-_]+)\"',re.M|re.I) for i, line in enumerate(schema): if re.match('^\s+$',line,re.M|re.I):
def exportNmapXML(pcap, out='nmapout-p0f3p.xml', retdom=False): import time doc = Document() pyobj = processCaptures(pcap) root = doc.createElement('nmaprun') pi = doc.createProcessingInstruction( 'xml-stylesheet', 'type="text/xsl" href="file:///usr/local/bin/../share/nmap/nmap.xsl"') first = doc.firstChild doc.insertBefore(pi, first) root.setAttribute('scanner', 'p0fplus') t = int(time.time()) root.setAttribute('start', str(t)) ftime = time.ctime(t) root.setAttribute('startstr', ftime.replace(' ', ' ')) doc.appendChild(root) for k, v in pyobj.items(): host = doc.createElement('host') root.appendChild(host) addr = doc.createElement('address') addr.setAttribute('addrtype', 'ipv4') k = convB2Str(k) addr.setAttribute('ipaddr', k) host.appendChild(addr) hostnames = doc.createElement('hostnames') host.appendChild(hostnames) if v['hostnames'] is not None: for h in v['hostnames']: hostname = doc.createElement('hostname') if h[-1] == '.': h = h[:-1] hostname.setAttribute('name', h) hostnames.appendChild(hostname) ports = None if v['applications'] is not None: for app in v['applications']: if 'sport' in app: ports = doc.createElement('ports') host.appendChild(ports) port = doc.createElement('port') port.setAttribute( 'protocol', 'tcp') # FIXME: change when UDP is supported port.setAttribute('portid', str(app['sport'])) ports.appendChild(port) state = doc.createElement('state') state.setAttribute('state', 'open') state.setAttribute('reason', 'push-ack') port.appendChild(state) service = doc.createElement('service') if 'appname' in app: service.setAttribute('product', app['appname']) if 'version' in app: service.setAttribute('version', app['version']) if 'extrainf' in app: service.setAttribute('extrainfo', app['extrainf']) port.appendChild(service) if v['otherports'] is not None: for portk, value in v['otherports'].items(): if value['matched'] is False: if ports is None: ports = doc.createElement('ports') host.appendChild(ports) port = doc.createElement('port') port.setAttribute('protocol', 'tcp') port.setAttribute('portid', str(portk)) ports.appendChild(port) state = doc.createElement('state') state.setAttribute('state', 'open') reasonstr = flag2str(value['flag']) if reasonstr is not None: state.setAttribute('reason', reasonstr) port.appendChild(state) if 'guesses' in v['matches']: os = doc.createElement('os') host.appendChild(os) osmatch = doc.createElement('osmatch') for guess in v['matches']['guesses']: if guess['type'] != '!': #is a system osmatch = doc.createElement('osmatch') namematch = ' '.join( guess['label'].split(':')[2:]).replace('.x', '') osmatch.setAttribute('name', namematch) accuracy = str(100 - guess['distance']) # best formula ever! osmatch.setAttribute('accuracy', accuracy) os.appendChild(osmatch) osclass = doc.createElement('osclass') osclass.setAttribute('osfamily', guess['os']) osclass.setAttribute('osgen', guess['version']) osclass.setAttribute('accuracy', accuracy) osmatch.appendChild(osclass) if retdom is True: return doc # return only the minidom object else: doc.writexml(open(out, 'w'), indent=" ", addindent=" ", newl='\n')
def impl_create_cproject(self, executable, waf, appname, workspace_includes, cpppath, source_dirs=[]): doc = Document() doc.appendChild(doc.createProcessingInstruction("fileVersion", "4.0.0")) cconf_id = cdt_core + ".default.config.1" cproject = doc.createElement("cproject") storageModule = self.add(doc, cproject, "storageModule", {"moduleId": cdt_core + ".settings"}) cconf = self.add(doc, storageModule, "cconfiguration", {"id": cconf_id}) storageModule = self.add( doc, cconf, "storageModule", { "buildSystemId": oe_cdt + ".managedbuilder.core.configurationDataProvider", "id": cconf_id, "moduleId": cdt_core + ".settings", "name": "Default", }, ) self.add(doc, storageModule, "externalSettings") extensions = self.add(doc, storageModule, "extensions") extension_list = """ VCErrorParser MakeErrorParser GCCErrorParser GASErrorParser GLDErrorParser """.split() ext = self.add(doc, extensions, "extension", {"id": cdt_core + ".ELF", "point": cdt_core + ".BinaryParser"}) for e in extension_list: ext = self.add(doc, extensions, "extension", {"id": cdt_core + "." + e, "point": cdt_core + ".ErrorParser"}) storageModule = self.add(doc, cconf, "storageModule", {"moduleId": "cdtBuildSystem", "version": "4.0.0"}) config = self.add( doc, storageModule, "configuration", {"artifactName": appname, "id": cconf_id, "name": "Default", "parent": cdt_bld + ".prefbase.cfg"}, ) folderInfo = self.add(doc, config, "folderInfo", {"id": cconf_id + ".", "name": "/", "resourcePath": ""}) toolChain = self.add( doc, folderInfo, "toolChain", { "id": cdt_bld + ".prefbase.toolchain.1", "name": "No ToolChain", "resourceTypeBasedDiscovery": "false", "superClass": cdt_bld + ".prefbase.toolchain", }, ) targetPlatform = self.add( doc, toolChain, "targetPlatform", {"binaryParser": "org.eclipse.cdt.core.ELF", "id": cdt_bld + ".prefbase.toolchain.1", "name": ""}, ) waf_build = '"%s" %s' % (waf, eclipse.fun) waf_clean = '"%s" clean' % (waf) builder = self.add( doc, toolChain, "builder", { "autoBuildTarget": waf_build, "command": executable, "enableAutoBuild": "false", "cleanBuildTarget": waf_clean, "enableIncrementalBuild": "true", "id": cdt_bld + ".settings.default.builder.1", "incrementalBuildTarget": waf_build, "managedBuildOn": "false", "name": "Gnu Make Builder", "superClass": cdt_bld + ".settings.default.builder", }, ) for tool_name in ("Assembly", "GNU C++", "GNU C"): tool = self.add( doc, toolChain, "tool", {"id": cdt_bld + ".settings.holder.1", "name": tool_name, "superClass": cdt_bld + ".settings.holder"}, ) if cpppath or workspace_includes: incpaths = cdt_bld + ".settings.holder.incpaths" option = self.add( doc, tool, "option", { "id": incpaths + ".1", "name": "Include Paths", "superClass": incpaths, "valueType": "includePath", }, ) for i in workspace_includes: self.add( doc, option, "listOptionValue", {"builtIn": "false", "value": '"${workspace_loc:/%s/%s}"' % (appname, i)}, ) for i in cpppath: self.add(doc, option, "listOptionValue", {"builtIn": "false", "value": '"%s"' % (i)}) if source_dirs: sourceEntries = self.add(doc, config, "sourceEntries") for i in source_dirs: self.add( doc, sourceEntries, "entry", {"excluding": i, "flags": "VALUE_WORKSPACE_PATH|RESOLVED", "kind": "sourcePath", "name": ""}, ) self.add( doc, sourceEntries, "entry", {"flags": "VALUE_WORKSPACE_PATH|RESOLVED", "kind": "sourcePath", "name": i}, ) storageModule = self.add(doc, cconf, "storageModule", {"moduleId": cdt_mk + ".buildtargets"}) buildTargets = self.add(doc, storageModule, "buildTargets") def addTargetWrap(name, runAll): return self.addTarget(doc, buildTargets, executable, name, '"%s" %s' % (waf, name), runAll) addTargetWrap("configure", True) addTargetWrap("dist", False) addTargetWrap("install", False) addTargetWrap("check", False) storageModule = self.add(doc, cproject, "storageModule", {"moduleId": "cdtBuildSystem", "version": "4.0.0"}) project = self.add(doc, storageModule, "project", {"id": "%s.null.1" % appname, "name": appname}) doc.appendChild(cproject) return doc
class BaseGraph: """Abstract base class for all diagramKinds providing base functionallity. """ __computed_results__ = None specialAttribName = None def __init__(self, data=None, legend=None, colnames=None, title=None, stylesheet=None, errortext=None, otherParams={}): "See IDiagramKind.__init__" self.data = data self.width = otherParams.get('width', 0) self.height = otherParams.get('height', 0) self.legend = legend self.colnames = colnames self.gridlines = otherParams.get('gridlines') self.fillgaps = otherParams.get('fillgaps') self.intcaption = otherParams.get('intcaption') self.title = title self.stylesheet = stylesheet self.errortext = errortext self.result = '' ## Achtung: die Koordinaten 0,0 sind im SVG links oben! ## gridbasey unteres Ende in y-Richtung ## gridboundy oberes Ende in y-Richtung ## gridbasey groesser gridboundy! ## gridbasex unteres (linkes) Ende in x-Richtung ## gridboundx oberes (rechtes) Ende in x-Richtung ## gridbasex kleiner gridboundx! self.gridbasey = self.height - 20 self.gridboundy = 20 self.gridbasex = 40 if self.hasLegend(): self.gridboundx = self.width - 120 else: self.gridboundx = self.width - 12 def setSpecialAttrib(self, value): """Set the value of the special attribute.""" self.specialAttrib = value def hasLegend(self): "Has the graph a legend?" return (type(self.legend) in (type([]), type({}))) and self.legend def getDom(self): self.xmldoc = Document() # XXX minidom kann keine customisierte xml-processing instruction # XXX also mit umlauten testen, ob 'encoding="UTF-8"' nötig ## xml = self.xmldoc.createProcessingInstruction( ## 'xml', ## 'version="1.0" encoding="UTF-8"') ## self.xmldoc.appendChild(xml) if self.stylesheet: style = self.xmldoc.createProcessingInstruction( 'xml-stylesheet', 'href="%s" type="text/css"' % self.stylesheet) self.xmldoc.appendChild(style) svg = self.xmldoc.appendChild(self.xmldoc.createElement("svg")) svg.setAttribute('xmlns', "http://www.w3.org/2000/svg") svg.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink") svg.setAttribute('width', str(self.width)) svg.setAttribute('height', str(self.height)) def svgHeader(self): res = u"""<?xml version="1.0" encoding="UTF-8" ?>\n""" if self.stylesheet: res += u"""<?xml-stylesheet href="%s" type="text/css"?>\n""" % ( self.stylesheet) return res + """<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="%i" height="%i"> """ % (self.width, self.height) def svgFooter(self): return "</svg>" def minX(self): return self._computeMinMax('minX') def realMinX(self): return self._computeMinMax('realMinX') def minY(self): return self._computeMinMax('minY') def realMinY(self): return self._computeMinMax('realMinY') def maxX(self): return self._computeMinMax('maxX') def realMaxX(self): return self._computeMinMax('realMaxX') def maxY(self): return self._computeMinMax('maxY') def realMaxY(self): return self._computeMinMax('realMaxY') def distValsX(self): return self._computeMinMax('distValsX') def distValsY(self): return self._computeMinMax('distValsY') def allX(self): return self._computeMinMax('allX') def allY(self): return self._computeMinMax('allY') def numgraphs(self): return len(self.data) def _compRoundedValMax(self, val): """Compute a rounded maximum value.""" if val == 0: return 0 valBase = 10**(int(log10(abs(val)))) return valBase * ceil((float(val + valBase / 10.0) / valBase)) def _compRoundedValMin(self, val): """Compute a rounded minimum value.""" if val == 0: return 0 valBase = 10**(int(log10(abs(val)))) return valBase * floor((float(val) / valBase) - 1) def _getDistinctValues(self, list): """Make a list having only distinct values.""" if not len(list): return [] if type(list[0]) == type(self): # objects in list tmp = list[:] res = [] while (tmp): if not tmp[0] in tmp[1:]: res.append(tmp[0]) del tmp[0] return res else: return dict([(x, 1) for x in list]).keys() def _computeMinMax(self, key): if self.__computed_results__: return self.__computed_results__[key] self._testFormatOfData() self.__computed_results__ = {} cr = self.__computed_results__ allX = [] allY = [] allXfloat = [] allYfloat = [] stringInX = stringInY = False for dataset in self.data: for value in dataset: allX.append(value[0]) if not stringInX: try: allXfloat.append(float(value[0])) except ValueError: stringInX = True if isinstance(value[0], basestring): stringInX = True allY.append(value[1]) if not stringInY: try: allYfloat.append(float(value[1])) except ValueError: stringInY = True if isinstance(value[1], basestring): stringInY = True if stringInX: cr['realMaxX'] = None cr['maxX'] = None cr['realMinX'] = None cr['minX'] = None else: cr['realMaxX'] = max(allX) cr['maxX'] = self._compRoundedValMax(cr['realMaxX']) cr['realMinX'] = min(allX) cr['minX'] = self._compRoundedValMin(cr['realMinX']) if self.fillgaps: cr['distValsX'] = range(cr['realMinX'], cr['realMaxX'] + 1) allX = allXfloat if stringInY: cr['realMaxY'] = None cr['maxY'] = None cr['realMinY'] = None cr['minY'] = None else: cr['realMaxY'] = max(allY) cr['maxY'] = self._compRoundedValMax(cr['realMaxY']) cr['realMinY'] = min(allY) cr['minY'] = self._compRoundedValMin(cr['realMinY']) if self.fillgaps: cr['distValsY'] = range(cr['realMinY'], cr['realMaxY'] + 1) allY = allYfloat cr['allX'] = allX cr['allY'] = allY if cr.get('distValsX') is None: cr['distValsX'] = self._getDistinctValues(allX) if cr.get('distValsY') is None: cr['distValsY'] = self._getDistinctValues(allY) return cr[key] def _change_computed_result(self, key, value): """Set the value of key in __computed_results__ after computation. Use with caution! """ self._computeMinMax(key) self.__computed_results__[key] = value def _testFormatOfData(self): if self.data is None: raise RuntimeError, config.SVGrafZ_empty_dataset if type(self.data) != ListType: raise RuntimeError, 'Data is not a list. Maybe wrong converter.' if len(self.data) == 0: raise RuntimeError, 'Data is empty.' i = 0 for dataset in self.data: i = i + 1 if type(dataset) != ListType: raise RuntimeError, 'Dataset %i is no List.' % i if len(dataset) == 0: raise RuntimeError, 'Dataset %i is empty.' % i j = 0 for dataItem in dataset: j = j + 1 if type(dataItem) != ListType: raise RuntimeError, 'DataItem %i in Dataset %i is no List.'\ % (i,j) if len(dataItem) != 2: raise RuntimeError,\ 'DataItem %i in Dataset %i: More than 2 dimensions.'\ % (j,i) k = 0 for dim in dataItem: k = k + 1 if type(dim) not in [ IntType, LongType, FloatType, StringType, UnicodeType, InstanceType, ]: raise RuntimeError,\ 'Dimension %i of DataItem %i in Dataset %i: \ Not allowed Type of %s.' \ % (k,j,i,type(dim)) return 1 def _computeGridLines(self, minVal, maxVal, lines, rtype): """Compute the variable values for the gridlines. minVal ... first grid value maxVal ... last grid value lines ... number of lines in grid rtype ... <type 'int'> or <type 'float'> for type of the result values """ if (rtype == int) and ((maxVal - minVal) < lines): lines = maxVal - minVal ystep = (maxVal - minVal) / rtype(abs(lines) + 1) return [rtype(minVal + (y * ystep)) for y in range(1, abs(lines) + 1)] def drawXGridLines(self): """Draw gridlines in parallel to the y-axis.""" if not self.gridlines: return '' if self.intcaption: rtype = int else: rtype = float grid = self._computeGridLines(self.minX(), self.maxX(), self.gridlines, rtype) res = '<g id="xGrid">\n' for xval in grid: res += '<line x1="%s" x2="%s" y1="%s" y2="%s"/>\n' % ( self.gridbasex + xval * self.xScale, self.gridbasex + xval * self.xScale, self.gridbasey, self.gridboundy) res += '<text x="%s" y="%s" style="text-anchor: middle;">%s</text>'\ % (self.gridbasex + xval * self.xScale, self.gridbasey + 15, self.confLT(xval)) res += '\n' return res + '</g>\n' def drawYGridLines(self): """Draw gridlines in parallel to the x-axis.""" if not self.gridlines: return '' if self.intcaption: rtype = int else: rtype = float grid = self._computeGridLines(self.minY(), self.maxY(), self.gridlines, rtype) res = '<g id="yGrid">\n' for yval in grid: res += '<line x1="%s" x2="%s" y1="%s" y2="%s"/>\n' % ( self.gridbasex, self.gridboundx, self.gridbasey - yval * self.yScale, self.gridbasey - yval * self.yScale) res += '<text x="3" y="%s" style="text-anchor: start;">%s</text>'\ % (self.gridbasey - yval * self.yScale + 5, self.confLT(yval)) res += '\n' return res + '</g>\n' def drawYGridLinesDiscrete(self): """Draw gridlines in parallel to the x-axis label it with the discrete values.""" if not self.gridlines: return '' if self.intcaption: rtype = int else: rtype = float distY = self.distValsY() distY.sort() grid = self._computeGridLines(self.minY(), self.maxY(), self.gridlines, rtype) res = '<g id="yGrid">\n' for yval in grid: if yval == 0: text = '' else: text = distY[yval - 1] res += '<line x1="%s" x2="%s" y1="%s" y2="%s"/>\n' % ( self.gridbasex, self.gridboundx, self.gridbasey - yval * self.yScale, self.gridbasey - yval * self.yScale) res += '<text x="3" y="%s" style="text-anchor: start;">%s</text>'\ % (self.gridbasey - yval * self.yScale + 5, self.confLT(text)) res += '\n' return res + '</g>\n' def drawXYAxis(self): """Draw the x- and y-axis.""" res = '<g id="xyaxis" style="stroke:#000000; stroke-opacity:1;">\n' res += '<line x1="%s" x2="%s" y1="%s" y2="%s"/>\n' % ( self.gridbasex - 10, self.gridboundx, self.gridbasey, self.gridbasey) res += '<line x1="%s" x2="%s" y1="%s" y2="%s"/>\n' % ( self.gridbasex, self.gridbasex, self.gridbasey + 10, self.gridboundy) return res + '</g>\n' def drawTitle(self): if not self.title: return '' res = '<g id="title">\n' res += '<text x="%s" y="%s" style="text-anchor: middle;">%s</text>'\ % (self.width / 2, self.gridboundy - 4, self.confLT(self.title)) return res + '\n</g>\n' def drawLegend(self): """Draw the Legend.""" if not self.legend: return '' res = """<g id="legend"> <text x="%s" y="%s" style="%s">%s</text> """ % ((self.gridboundx + self.width) / 2, self.gridboundy + 10, 'text-anchor: middle; font-weight: bold;', config.SVGrafZ_legend_name) for i in range(len(self.legend)): res += """<line class="%s" x1="%s" x2="%s" y1="%s" y2="%s" stroke-width="10" stroke-linecap="round" stroke="%s" /> """ % ('dataset%s' % (i), self.width - 5, self.width - 15, self.gridboundy + 26 + (15 * i), self.gridboundy + 26 + (15 * i), config.SVGrafZ_default_Color) res += """<text x="%s" y="%s" style="text-anchor:end;">%s</text>"""\ % (self.width - 25, self.gridboundy + 30 + (15 * i), self.confLT(self.legend[i]), ) return res + "\n</g>" def printError(self): """Print the textual description of an error.""" res = ''' <g id="SVGrafZicon" transform="translate(%s,%s) scale(2)"> <g id="icondata"> <rect style="fill: #ef2715;" x="1" y="11.332" height="2.7" width="8.76864"/> <rect style="fill: #ef2715;" x="1" y="4.8" height="2.7" width="4.38432"/> <rect style="fill: #131ef4;" x="1" y="8.6328" height="2.7" width="11.6915"/> <rect style="fill: #131ef4;" x="1" y="2" height="2.7" width="8.76864"/> </g> <g id="iconxyaxis" style="stroke:#000000; stroke-opacity:1;"> <line x1="0" x2="15.68" y1="16" y2="16"/> <line x1="1" x2="1" y1="17" y2="0.5328"/> </g> </g>''' % (self.width / 2, (self.gridbasey - self.gridboundy) / 4) step = 0 print ` self.errortext ` err_txt = u"%s: %s" % (config.SVGrafZ_error_name, self.errortext) for errortext in split(self.confLT(err_txt), '\n'): res += '<text x="%s" y="%s" font-size="12pt" text-anchor="middle" fill="red">%s</text>' % ( self.width / 2, (self.gridbasey - self.gridboundy) / 2 + step, errortext) step += 20 return res def xAxis_verticalLabels(self, labels, firstWidth, xWidth): """Print the labels on x-axis vertically. labels ... list of strings with labelnames, if self.colnames exists, then it is taken instead firstWidth ... float points from self.gridbasex to first label xWidth ... float points between labels """ if self.colnames: # use colnames, if given labels = self.colnames res = '' for i in range(len(labels)): label = labels[i] res += '''<defs> <path d="M %s %s V 15" id="xAxisLabel%s"/> </defs>\n <text> <textPath xlink:href="#xAxisLabel%s">%s</textPath> </text>\n''' % (firstWidth + i * xWidth + 2, self.height - 2, i, i, self.confLT(str(label))) return res def xAxis_diagonalLabels(self, labels, firstWidth, xWidth, withLines=0): """Print labels on x-axis diagonally from bottom-left to upper-right. labels ... list of strings with labelnames, if self.colnames exists, then it is taken instead firstWidth ... float points from self.gridbasex to first label xWidth ... float points between labels withLines ... if withLines: draw lines in parallel to y-axis """ if self.colnames: # use colnames, if given labels = self.colnames res = '' diff = self.height - self.gridbasey for i in range(len(labels)): label = labels[i] res += '''<defs> <path d="M %s %s l 600 600" id="xAxisLabel%s"/> </defs>\n <text style="text-anchor: start;"> <textPath xlink:href="#xAxisLabel%s">%s</textPath> </text>\n''' % (firstWidth + i * xWidth - 7, self.gridbasey + 7, i, i, self.confLT(str(label))) ## res += '<line x1="%s" x2="%s" y1="%s" y2="%s" />\n' % ( ## firstWidth + i * xWidth - 7, ## firstWidth + i * xWidth + 600 -7 , ## self.gridbasey + 7, ## self.gridbasey + 607, ## ) if withLines: res += '<line x1="%s" x2="%s" y1="%s" y2="%s" />\n' % ( firstWidth + i * xWidth, firstWidth + i * xWidth, self.gridbasey, self.gridboundy, ) return res def yAxis_horizontalLabels(self, labels, firstHeight, yHeight): """Print horizontal Labels on yAxis. labels ... list: of strings with labelnames, if self.colnames exists, then it is taken instead firstHeight ... float: points from self.gridbasey to first label yHeight ... float: points between labels """ res = '' if self.colnames: # use colnames, if given labels = self.colnames for i in range(len(labels)): label = labels[i] res += '''<text x="5" y="%s" style="text-anchor:start;"> <tspan baseline-shift="sub">%s</tspan> </text>\n''' % (self.gridbasey - i * yHeight - firstHeight, self.confLT(label)) return res def compute(self): """Compute the Diagram.""" if self.result: return self.result if usedom: self.getDom() return self.xmldoc.toxml() # else: not usedom self.result = self.svgHeader() if self.errortext: self.result += self.printError() else: try: for action in self.getDrawingActions(): self.result += action() except RuntimeError: import sys self.errortext = sys.exc_info()[1].args[0] self.result = self.svgHeader() + self.printError() self.result += self.svgFooter() return self.result def computeYScale(self): """Compute scaling factor for y-direction.""" if self.maxY() is None: raise RuntimeError, 'All values on y-axis must be numbers!' self.specialAttribHook() difY = float(self.maxY() - self.minY()) if difY: self.yScale = float((self.gridbasey - self.gridboundy) / difY) else: self.yScale = 1.0 return '' def computeXScale(self): """Compute scaling factor for x-direction.""" if self.maxX() is None: raise RuntimeError, 'All values on x-axis must be numbers!' self.specialAttribHook() difX = float(self.maxX() - self.minX()) if difX: self.xScale = float((self.gridboundx - self.gridbasex) / difX) else: self.xScale = 1.0 return '' def confLT(self, text): """Convert the less than symbols in text ('<') to <.""" if type(text) in StringTypes: return text.replace("<", "<") return text def getDrawingActions(self): """Returns the methods which are used to draw the graph.""" return [ self.drawGraph, self.drawXYAxis, self.drawLegend, self.drawTitle ] def drawGraph(self): "Abstract Method: Draw the the graph and name the columns." raise RuntimeError, "Can't use the abstract method drawGraph!"
def impl_create_cproject(self, executable, waf_executable, appname, workspace_includes, cpppath, source_dirs=[]): doc = Document() doc.appendChild(doc.createProcessingInstruction( "fileVersion", "4.0.0")) cconf_id = cdt_core + ".default.config.1" cproject = doc.createElement("cproject") storageModule = self.add(doc, cproject, "storageModule", {"moduleId": cdt_core + ".settings"}) cconf = self.add(doc, storageModule, "cconfiguration", {"id": cconf_id}) storageModule = self.add( doc, cconf, "storageModule", { "buildSystemId": oe_cdt + ".managedbuilder.core.configurationDataProvider", "id": cconf_id, "moduleId": cdt_core + ".settings", "name": "Default", }, ) self.add(doc, storageModule, "externalSettings") extensions = self.add(doc, storageModule, "extensions") extension_list = """ VCErrorParser MakeErrorParser GCCErrorParser GASErrorParser GLDErrorParser """.split() self.add( doc, extensions, "extension", { "id": cdt_core + ".ELF", "point": cdt_core + ".BinaryParser" }, ) for e in extension_list: self.add( doc, extensions, "extension", { "id": cdt_core + "." + e, "point": cdt_core + ".ErrorParser" }, ) storageModule = self.add(doc, cconf, "storageModule", { "moduleId": "cdtBuildSystem", "version": "4.0.0" }) config = self.add( doc, storageModule, "configuration", { "artifactName": appname, "id": cconf_id, "name": "Default", "parent": cdt_bld + ".prefbase.cfg", }, ) folderInfo = self.add(doc, config, "folderInfo", { "id": cconf_id + ".", "name": "/", "resourcePath": "" }) toolChain = self.add( doc, folderInfo, "toolChain", { "id": cdt_bld + ".prefbase.toolchain.1", "name": "No ToolChain", "resourceTypeBasedDiscovery": "false", "superClass": cdt_bld + ".prefbase.toolchain", }, ) self.add( doc, toolChain, "targetPlatform", { "binaryParser": "org.eclipse.cdt.core.ELF", "id": cdt_bld + ".prefbase.toolchain.1", "name": "", }, ) waf_build = f'"{waf_executable}" {eclipse.fun}' waf_clean = '"%s" clean' % (waf_executable) self.add( doc, toolChain, "builder", { "autoBuildTarget": waf_build, "command": executable, "enableAutoBuild": "false", "cleanBuildTarget": waf_clean, "enableIncrementalBuild": "true", "id": cdt_bld + ".settings.default.builder.1", "incrementalBuildTarget": waf_build, "managedBuildOn": "false", "name": "Gnu Make Builder", "superClass": cdt_bld + ".settings.default.builder", }, ) tool_index = 1 for tool_name in ("Assembly", "GNU C++", "GNU C"): tool = self.add( doc, toolChain, "tool", { "id": cdt_bld + ".settings.holder." + str(tool_index), "name": tool_name, "superClass": cdt_bld + ".settings.holder", }, ) if cpppath or workspace_includes: incpaths = cdt_bld + ".settings.holder.incpaths" option = self.add( doc, tool, "option", { "id": incpaths + "." + str(tool_index), "name": "Include Paths", "superClass": incpaths, "valueType": "includePath", }, ) for i in workspace_includes: self.add( doc, option, "listOptionValue", { "builtIn": "false", "value": f'"${{workspace_loc:/{appname}/{i}}}"' }, ) for i in cpppath: self.add(doc, option, "listOptionValue", { "builtIn": "false", "value": '"%s"' % (i) }) if tool_name == "GNU C++" or tool_name == "GNU C": self.add( doc, tool, "inputType", { "id": "org.eclipse.cdt.build.core.settings.holder.inType." + str(tool_index), "languageId": "org.eclipse.cdt.core.gcc" if tool_name == "GNU C" else "org.eclipse.cdt.core.g++", "languageName": tool_name, "sourceContentType": "org.eclipse.cdt.core.cSource,org.eclipse.cdt.core.cHeader", "superClass": "org.eclipse.cdt.build.core.settings.holder.inType", }, ) tool_index += 1 if source_dirs: sourceEntries = self.add(doc, config, "sourceEntries") for i in source_dirs: self.add( doc, sourceEntries, "entry", { "excluding": i, "flags": "VALUE_WORKSPACE_PATH|RESOLVED", "kind": "sourcePath", "name": "", }, ) self.add( doc, sourceEntries, "entry", { "flags": "VALUE_WORKSPACE_PATH|RESOLVED", "kind": "sourcePath", "name": i }, ) storageModule = self.add(doc, cconf, "storageModule", {"moduleId": cdt_mk + ".buildtargets"}) buildTargets = self.add(doc, storageModule, "buildTargets") def addTargetWrap(name, runAll): return self.addTarget(doc, buildTargets, executable, name, f'"{waf_executable}" {name}', runAll) addTargetWrap("configure", True) addTargetWrap("dist", False) addTargetWrap("install", False) addTargetWrap("check", False) storageModule = self.add(doc, cproject, "storageModule", { "moduleId": "cdtBuildSystem", "version": "4.0.0" }) self.add(doc, storageModule, "project", { "id": "%s.null.1" % appname, "name": appname }) doc.appendChild(cproject) return doc
class Xul(object): """This is the base xul element which all other elements inherit from. Also is used as the base container for the document >>> x = Xul(); x+=Window(); print x <?xml version="1.0" ?> <?xml-stylesheet type="text/css" href="chrome://global/skin"?> <window height="600" title="Xul Application" width="800" xmlns="\ http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" \ xmlns:html="http://www.w3.org/1999/xhtml"/> <BLANKLINE> """ def __init__(self, element=None, kwargs=None, addprop=None): """This is a init function that is used to initilize common thing across the different children. """ self._properties = { "align": "string", "allowevents": "string", "allownegativeassertions": "string", "eclass": "string", "class": "string", "coalesceduplicatearcs": "string", "collapsed": "string", "container": "string", "containment": "string", "context": "string", "contextmenu": "string", "datasources": "string", "dir": "string", "edir": "string", "empty": "string", "equalsize": "string", "flags": "string", "flex": "string", "height": "string", "hidden": "string", "eid": "string", "id": "string", "insertafter": "string", "insertbefore": "string", "left": "string", "maxheight": "string", "maxwidth": "string", "menu": "string", "minheight": "string", "minwidth": "string", "mousethrough": "string", "observes": "string", "ordinal": "string", "orient": "string", "pack": "string", "persist": "string", "popup": "string", "position": "string", "preference-editable": "string", "querytype": "string", "ref": "string", "removeelement": "string", "sortDirection": "string", "sortResource": "string", "sortResource2": "string", "statustext": "string", "style": "string", "template": "string", "tooltip": "string", "tooltiptext": "string", "top": "string", "uri": "string", "wait-cursor": "string", "width": "string", "xmlns": "string", "xmlns:html": "string" } if(addprop): self._properties = dict(self._properties, **addprop) self._doc = Document() type(self).__name__="xulelement" if(element): self._element = self._doc.createElement(element) else: self._element = self._doc self._doc.appendChild(self._doc.createProcessingInstruction(\ "xml-stylesheet","type=\"text/css\" href=\"chrome://global/skin\"")) if(kwargs): for key in kwargs: if(key=="eid"): self.__setattr__("id", kwargs[key]) elif(key=="eclass"): self.__setattr__("class", kwargs[key]) elif(key=="eopen"): self.__setattr__("open", kwargs[key]) elif(key=="etype"): self.__setattr__("type", kwargs[key]) elif(key=="edir"): self.__setattr__("dir", kwargs[key]) else: self.__setattr__(key, kwargs[key]) def __setattr__(self, name, value): if name in self.__dict__ or name in ["_element", "_doc", "_properties"]: super(Xul, self).__setattr__(name, value) else: element = self.getelement() if STRICT: if name in self._properties: element.setAttribute(str(name), str(value)) else: raise StrictError("Your trying to add an attribute that \ is not supported by the element") else: element.setAttribute(str(name), str(value)) def __getattr__(self, name): if name in self.__dict__: super(Xul, self).__getattr__(name) else: element = self.getelement() ret = Attribute(name, element.getAttribute(name)) return ret def _adder(self, other, parent): """This is a helper function so it's possible to go recursively through adding elements""" if(self == other): raise SelfReference('Your adding your self') if type(other).__name__=="list" or type(other).__name__=="List": last = None for other_element in other: if type(other_element).__name__=="list": if(last): self._adder(other_element, last) last = List(other_element) last.parent = parent else: raise EmptyList("You cant start with two lists") elif type(other_element).__name__=="str" or \ type(other).__name__=="int": cdata = CDATASection() cdata.data = str(other_element) element = parent.getelement() element.appendChild(cdata) last = other_element elif type(other_element).__name__=="xulelement": if type(parent).__name__=="List": if parent.parent: element = parent.parent.getelement() eelement = other_element.getelement() element.appendChild(eelement) last = other_element else: raise ParentList(\ "You can't have list as an parent") elif type(parent).__name__=="list": raise ParentList(\ "You can't have list as an parent") else: element = parent.getelement() eelement = other_element.getelement() element.appendChild(eelement) last = other_element else: print("What is happening") print("type: "+type(other).__name__) elif type(other).__name__=="str" or type(other).__name__=="int": cdata = CDATASection() cdata.data = str(other) element = parent.getelement() element.appendChild(cdata) elif type(other).__name__=="xulelement": element = parent.getelement() oelement = other.getelement() element.appendChild(oelement) else: print("What is happening") print("type: "+type(other).__name__) def __iadd__(self, other): self._adder(other, self) return self def __str__(self): element = self.getelement() return element.toprettyxml(indent=" ") def __repr__(self): return self.__str__() def getelement(self): """This returns the xml element to you so you can change it. """ return self._element
def impl_create_cproject(self, executable, waf, appname, workspace_includes, cpppath, source_dirs=[]): doc = Document() doc.appendChild(doc.createProcessingInstruction( 'fileVersion', '4.0.0')) cconf_id = cdt_core + '.default.config.1' cproject = doc.createElement('cproject') storageModule = self.add(doc, cproject, 'storageModule', {'moduleId': cdt_core + '.settings'}) cconf = self.add(doc, storageModule, 'cconfiguration', {'id': cconf_id}) storageModule = self.add( doc, cconf, 'storageModule', { 'buildSystemId': oe_cdt + '.managedbuilder.core.configurationDataProvider', 'id': cconf_id, 'moduleId': cdt_core + '.settings', 'name': 'Default' }) self.add(doc, storageModule, 'externalSettings') extensions = self.add(doc, storageModule, 'extensions') extension_list = """ VCErrorParser MakeErrorParser GCCErrorParser GASErrorParser GLDErrorParser """.split() ext = self.add(doc, extensions, 'extension', { 'id': cdt_core + '.ELF', 'point': cdt_core + '.BinaryParser' }) for e in extension_list: ext = self.add(doc, extensions, 'extension', { 'id': cdt_core + '.' + e, 'point': cdt_core + '.ErrorParser' }) storageModule = self.add(doc, cconf, 'storageModule', { 'moduleId': 'cdtBuildSystem', 'version': '4.0.0' }) config = self.add( doc, storageModule, 'configuration', { 'artifactName': appname, 'id': cconf_id, 'name': 'Default', 'parent': cdt_bld + '.prefbase.cfg' }) folderInfo = self.add(doc, config, 'folderInfo', { 'id': cconf_id + '.', 'name': '/', 'resourcePath': '' }) toolChain = self.add( doc, folderInfo, 'toolChain', { 'id': cdt_bld + '.prefbase.toolchain.1', 'name': 'No ToolChain', 'resourceTypeBasedDiscovery': 'false', 'superClass': cdt_bld + '.prefbase.toolchain' }) targetPlatform = self.add( doc, toolChain, 'targetPlatform', { 'binaryParser': 'org.eclipse.cdt.core.ELF', 'id': cdt_bld + '.prefbase.toolchain.1', 'name': '' }) waf_build = 'waf %s' % (eclipse.fun) waf_clean = 'waf clean' builder = self.add( doc, toolChain, 'builder', { 'autoBuildTarget': waf_build, 'command': executable, 'enableAutoBuild': 'false', 'cleanBuildTarget': waf_clean, 'enableIncrementalBuild': 'true', 'id': cdt_bld + '.settings.default.builder.1', 'incrementalBuildTarget': waf_build, 'managedBuildOn': 'false', 'name': 'Gnu Make Builder', 'superClass': cdt_bld + '.settings.default.builder' }) for tool_name in ("Assembly", "GNU C", "GNU C++"): tool = self.add( doc, toolChain, 'tool', { 'id': cdt_bld + '.settings.holder.1', 'name': tool_name, 'superClass': cdt_bld + '.settings.holder' }) if cpppath or workspace_includes: incpaths = cdt_bld + '.settings.holder.incpaths' option = self.add( doc, tool, 'option', { 'id': incpaths + '.1', 'name': 'Include Paths', 'superClass': incpaths, 'valueType': 'includePath' }) for i in workspace_includes: self.add( doc, option, 'listOptionValue', { 'builtIn': 'false', 'value': '"${workspace_loc:/%s}"' % (i) }) for i in cpppath: self.add(doc, option, 'listOptionValue', { 'builtIn': 'false', 'value': '"%s"' % (i) }) if tool_name == "Assembly": input_type = self.add( doc, tool, 'inputType', { 'id': cdt_bld + '.settings.holder.inType.1', 'languageId': 'org.eclipse.cdt.core.assembly', 'languageName': 'Assembly', 'sourceContentType': 'org.eclipse.cdt.core.asmSource', 'superClass': cdt_bld + 'settings.holder.inType' }) if tool_name == "GNU C": input_type = self.add( doc, tool, 'inputType', { 'id': cdt_bld + '.settings.holder.inType.2', 'languageId': 'org.eclipse.cdt.core.gcc', 'languageName': 'GNU C', 'sourceContentType': 'org.eclipse.cdt.core.cSource,org.eclipse.cdt.core.cHeader', 'superClass': cdt_bld + 'settings.holder.inType' }) if tool_name == "GNU C++": input_type = self.add( doc, tool, 'inputType', { 'id': cdt_bld + '.settings.holder.inType.3', 'languageId': 'org.eclipse.cdt.core.g++', 'languageName': 'GNU C++', 'sourceContentType': 'org.eclipse.cdt.core.cxxSource,org.eclipse.cdt.core.cxxHeader', 'superClass': cdt_bld + 'settings.holder.inType' }) if source_dirs: sourceEntries = self.add(doc, config, 'sourceEntries') for i in source_dirs: self.add( doc, sourceEntries, 'entry', { 'excluding': i, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': '' }) self.add( doc, sourceEntries, 'entry', { 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': i }) storageModule = self.add(doc, cconf, 'storageModule', {'moduleId': cdt_mk + '.buildtargets'}) buildTargets = self.add(doc, storageModule, 'buildTargets') def addTargetWrap(name, runAll): return self.addTarget(doc, buildTargets, executable, name, 'waf %s' % (name), runAll) addTargetWrap('configure', True) addTargetWrap('dist', False) addTargetWrap('install', False) addTargetWrap('check', False) storageModule = self.add(doc, cproject, 'storageModule', { 'moduleId': 'cdtBuildSystem', 'version': '4.0.0' }) project = self.add(doc, storageModule, 'project', { 'id': '%s.null.1' % appname, 'name': appname }) # Add DoxyGen comment parser storageModule = self.add( doc, cproject, 'storageModule', { 'moduleId': 'org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings' }) docCommentOwner = self.add(doc, storageModule, 'doc-comment-owner', {'id': 'org.eclipse.cdt.ui.doxygen'}) path = self.add(doc, docCommentOwner, 'path', {'value': ''}) # Add scanner info generator storageModule = self.add(doc, cproject, 'storageModule', {'moduleId': 'scannerConfiguration'}) self.add( doc, storageModule, 'autodiscovery', { 'enabled': 'true', 'problemReportingEnabled': 'true', 'selectedProfileId': 'org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile' }) scannerConfigBuildInfo = self.add(doc, storageModule, 'scannerConfigBuildInfo', {'instanceId': cconf_id}) self.add( doc, scannerConfigBuildInfo, 'autodiscovery', { 'enabled': 'true', 'problemReportingEnabled': 'true', 'selectedProfileId': 'org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile' }) profile = self.add(doc, scannerConfigBuildInfo, 'profile', { 'id': 'org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile' }) buildOutputProvider = self.add(doc, profile, 'buildOutputProvider', {}) self.add(doc, buildOutputProvider, 'openAction', { 'enabled': 'true', 'filePath': '' }) self.add(doc, buildOutputProvider, 'parser', {'enabled': 'true'}) scannerInfoProvider = self.add(doc, profile, 'scannerInfoProvider', {'id': 'specsFile'}) # Generate compiler string if type(self.env.CC) == list: cc_str = self.env.CC[0] else: cc_str = self.env.CC # Generate CFLAGS ccflags_str = '' for flag in self.env.CFLAGS: ccflags_str = ccflags_str + ' ' + flag self.add( doc, scannerInfoProvider, 'runAction', { 'arguments': ccflags_str + ' -E -P -v -dD ${plugin_state_location}/${specs_file}', 'command': cc_str, 'useDefault': 'true' }) self.add(doc, scannerInfoProvider, 'parser', {'enabled': 'true'}) # Generate list of sources sources = list() for group in self.groups: for task in group: #print(task) #print(task.source) sources += task.source files = self.srcnode.ant_glob('**/*.c', excl='/build') files = filter(lambda x: x not in sources, files) #print(sources) #print(len(sources)) #print(files) #print(len(files)) excludes = '|'.join([fil.nice_path() for fil in files]) sourceEntries = self.add(doc, config, 'sourceEntries', {}) self.add( doc, sourceEntries, 'entry', { 'excluding': excludes, 'flags': 'VALUE_WORKSPACE_PATH', 'kind': 'sourcePath', 'name': '' }) doc.appendChild(cproject) return doc