Migrated the project writer to a stream writer.

Mon, 13 Sep 2010 19:52:30 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Mon, 13 Sep 2010 19:52:30 +0200
changeset 610
3a625b0793d8
parent 608
d8fea1e76975
child 611
4d2c91bd319e

Migrated the project writer to a stream writer.

E5XML/ProjectWriter.py file | annotate | diff | comparison | revisions
E5XML/XMLStreamWriterBase.py file | annotate | diff | comparison | revisions
Project/Project.py file | annotate | diff | comparison | revisions
--- a/E5XML/ProjectWriter.py	Mon Sep 13 16:14:10 2010 +0200
+++ b/E5XML/ProjectWriter.py	Mon Sep 13 19:52:30 2010 +0200
@@ -11,24 +11,24 @@
 
 from E5Gui.E5Application import e5App
 
-from .XMLWriterBase import XMLWriterBase
+from .XMLStreamWriterBase import XMLStreamWriterBase
 from .Config import projectFileFormatVersion
 
 import Preferences
 import Utilities
 
-class ProjectWriter(XMLWriterBase):
+class ProjectWriter(XMLStreamWriterBase):
     """
     Class implementing the writer class for writing an XML project file.
     """
-    def __init__(self, file, projectName):
+    def __init__(self, device, projectName):
         """
         Constructor
         
-        @param file open file (like) object for writing
+        @param device reference to the I/O device to write to (QIODevice)
         @param projectName name of the project (string)
         """
-        XMLWriterBase.__init__(self, file)
+        XMLStreamWriterBase.__init__(self, device)
         
         self.pdata = e5App().getObject("Project").pdata
         self.name = projectName
@@ -37,196 +37,184 @@
         """
         Public method to write the XML to the file.
         """
-        XMLWriterBase.writeXML(self)
+        XMLStreamWriterBase.writeXML(self)
         
-        self._write('<!DOCTYPE Project SYSTEM "Project-{0}.dtd">'.format(
+        self.writeDTD('<!DOCTYPE Project SYSTEM "Project-{0}.dtd">'.format(
             projectFileFormatVersion))
         
         # add some generation comments
-        self._write("<!-- eric5 project file for project {0} -->".format(self.name))
+        self.writeComment(" eric5 project file for project {0} ".format(self.name))
         if Preferences.getProject("XMLTimestamp"):
-            self._write("<!-- Saved: {0} -->".format(time.strftime('%Y-%m-%d, %H:%M:%S')))
-            self._write("<!-- Copyright (C) {0} {1}, {2} -->".format(
+            self.writeComment(" Saved: {0} ".format(time.strftime('%Y-%m-%d, %H:%M:%S')))
+            self.writeComment(" Copyright (C) {0} {1}, {2} ".format(
                     time.strftime('%Y'), 
                     self.escape(self.pdata["AUTHOR"][0]), 
                     self.escape(self.pdata["EMAIL"][0])))
         
         # add the main tag
-        self._write('<Project version="{0}">'.format(projectFileFormatVersion))
+        self.writeStartElement("Project")
+        self.writeAttribute("version", projectFileFormatVersion)
         
         # do the language (used for spell checking)
-        self._write('  <Language>{0}</Language>'.format(self.pdata["SPELLLANGUAGE"][0]))
+        self.writeTextElement("Language", self.pdata["SPELLLANGUAGE"][0])
         if len(self.pdata["SPELLWORDS"][0]) > 0:
-            self._write("  <ProjectWordList>{0}</ProjectWordList>".format(
-                Utilities.fromNativeSeparators(self.pdata["SPELLWORDS"][0])))
+            self.writeTextElement("ProjectWordList", 
+                Utilities.fromNativeSeparators(self.pdata["SPELLWORDS"][0]))
         if len(self.pdata["SPELLEXCLUDES"][0]) > 0:
-            self._write("  <ProjectExcludeList>{0}</ProjectExcludeList>".format(
-                Utilities.fromNativeSeparators(self.pdata["SPELLEXCLUDES"][0])))
+            self.writeTextElement("ProjectExcludeList", 
+                Utilities.fromNativeSeparators(self.pdata["SPELLEXCLUDES"][0]))
         
         # do the hash
-        self._write('  <Hash>{0}</Hash>'.format(self.pdata["HASH"][0]))
+        self.writeTextElement("Hash", self.pdata["HASH"][0])
         
         # do the programming language
-        self._write('  <ProgLanguage mixed="{0:d}">{1}</ProgLanguage>'.format(
-            self.pdata["MIXEDLANGUAGE"][0], self.pdata["PROGLANGUAGE"][0]))
+        self.writeStartElement("ProgLanguage")
+        self.writeAttribute("mixed", str(int(self.pdata["MIXEDLANGUAGE"][0])))
+        self.writeCharacters(self.pdata["PROGLANGUAGE"][0])
+        self.writeEndElement()
         
         # do the UI type
-        self._write('  <ProjectType>{0}</ProjectType>'.format(
-            self.pdata["PROJECTTYPE"][0]))
+        self.writeTextElement("ProjectType", self.pdata["PROJECTTYPE"][0])
         
         # do description
         if self.pdata["DESCRIPTION"]:
-            self._write("  <Description>{0}</Description>".format(
-                self.escape(self.encodedNewLines(self.pdata["DESCRIPTION"][0]))))
+            self.writeTextElement("Description", self.pdata["DESCRIPTION"][0])
         
         # do version, author and email
-        for key in ["VERSION", "AUTHOR", "EMAIL"]:
-            element = key.capitalize()
-            if self.pdata[key]:
-                self._write("  <{0}>{1}</{0}>".format(
-                    element, self.escape(self.pdata[key][0])))
+        self.writeTextElement("Version", self.pdata["VERSION"][0])
+        self.writeTextElement("Author", self.pdata["AUTHOR"][0])
+        self.writeTextElement("Email", self.pdata["EMAIL"][0])
             
         # do the translation pattern
         if self.pdata["TRANSLATIONPATTERN"]:
-            self._write("  <TranslationPattern>{0}</TranslationPattern>".format(
-                Utilities.fromNativeSeparators(self.pdata["TRANSLATIONPATTERN"][0])))
+            self.writeTextElement("TranslationPattern", 
+                Utilities.fromNativeSeparators(self.pdata["TRANSLATIONPATTERN"][0]))
         
         # do the binary translations path
         if self.pdata["TRANSLATIONSBINPATH"]:
-            self._write("  <TranslationsBinPath>{0}</TranslationsBinPath>".format(
-                Utilities.fromNativeSeparators(self.pdata["TRANSLATIONSBINPATH"][0])))
+            self.writeTextElement("TranslationsBinPath", 
+                Utilities.fromNativeSeparators(self.pdata["TRANSLATIONSBINPATH"][0]))
         
         # do the eol setting
         if self.pdata["EOL"] and self.pdata["EOL"][0]:
-            self._write('  <Eol index="{0:d}" />'.format(self.pdata["EOL"][0]))
+            self.writeEmptyElement("Eol")
+            self.writeAttribute("index", str(int(self.pdata["EOL"][0])))
         
         # do the sources
-        self._write("  <Sources>")
+        self.writeStartElement("Sources")
         for name in self.pdata["SOURCES"]:
-            self._write("    <Source>{0}</Source>".format(
-                Utilities.fromNativeSeparators(name)))
-        self._write("  </Sources>")
+            self.writeTextElement("Source", Utilities.fromNativeSeparators(name))
+        self.writeEndElement()
         
         # do the forms
-        self._write("  <Forms>")
+        self.writeStartElement("Forms")
         for name in self.pdata["FORMS"]:
-            self._write("    <Form>{0}</Form>".format(
-                Utilities.fromNativeSeparators(name)))
-        self._write("  </Forms>")
+            self.writeTextElement("Form", Utilities.fromNativeSeparators(name))
+        self.writeEndElement()
         
         # do the translations
-        self._write("  <Translations>")
+        self.writeStartElement("Translations")
         for name in self.pdata["TRANSLATIONS"]:
-            self._write("    <Translation>{0}</Translation>".format(
-                Utilities.fromNativeSeparators(name)))
-        self._write("  </Translations>")
+            self.writeTextElement("Translation", Utilities.fromNativeSeparators(name))
+        self.writeEndElement()
         
         # do the translation exceptions
         if self.pdata["TRANSLATIONEXCEPTIONS"]:
-            self._write("  <TranslationExceptions>")
+            self.writeStartElement("TranslationExceptions")
             for name in self.pdata["TRANSLATIONEXCEPTIONS"]:
-                self._write("    <TranslationException>{0}</TranslationException>".format(
-                    Utilities.fromNativeSeparators(name)))
-            self._write("  </TranslationExceptions>")
+                self.writeTextElement("TranslationException", 
+                    Utilities.fromNativeSeparators(name))
+            self.writeEndElement()
         
         # do the resources
-        self._write("  <Resources>")
+        self.writeStartElement("Resources")
         for name in self.pdata["RESOURCES"]:
-            self._write("    <Resource>{0}</Resource>".format(
-                Utilities.fromNativeSeparators(name)))
-        self._write("  </Resources>")
+            self.writeTextElement("Resource", Utilities.fromNativeSeparators(name))
+        self.writeEndElement()
         
         # do the interfaces (IDL)
-        self._write("  <Interfaces>")
+        self.writeStartElement("Interfaces")
         for name in self.pdata["INTERFACES"]:
-            self._write("    <Interface>{0}</Interface>".format(
-                Utilities.fromNativeSeparators(name)))
-        self._write("  </Interfaces>")
+            self.writeTextElement("Interface", Utilities.fromNativeSeparators(name))
+        self.writeEndElement()
         
         # do the others
-        self._write("  <Others>")
+        self.writeStartElement("Others")
         for name in self.pdata["OTHERS"]:
-            self._write("    <Other>{0}</Other>".format(
-                Utilities.fromNativeSeparators(name)))
-        self._write("  </Others>")
+            self.writeTextElement("Other", Utilities.fromNativeSeparators(name))
+        self.writeEndElement()
         
         # do the main script
         if self.pdata["MAINSCRIPT"]:
-            self._write("  <MainScript>{0}</MainScript>".format(
-                Utilities.fromNativeSeparators(self.pdata["MAINSCRIPT"][0])))
+            self.writeTextElement("MainScript", 
+                Utilities.fromNativeSeparators(self.pdata["MAINSCRIPT"][0]))
         
         # do the vcs stuff
-        self._write("  <Vcs>")
+        self.writeStartElement("Vcs")
         if self.pdata["VCS"]:
-            self._write("    <VcsType>{0}</VcsType>".format(self.pdata["VCS"][0]))
+            self.writeTextElement("VcsType", self.pdata["VCS"][0])
         if self.pdata["VCSOPTIONS"]:
-            self._write("    <VcsOptions>")
-            self._writeBasics(self.pdata["VCSOPTIONS"][0], 3)
-            self._write("    </VcsOptions>")
+            self.writeBasics("VcsOptions", self.pdata["VCSOPTIONS"][0])
         if self.pdata["VCSOTHERDATA"]:
-            self._write("    <VcsOtherData>")
-            self._writeBasics(self.pdata["VCSOTHERDATA"][0], 3)
-            self._write("    </VcsOtherData>")
-        self._write("  </Vcs>")
+            self.writeBasics("VcsOtherData", self.pdata["VCSOTHERDATA"][0])
+        self.writeEndElement()
         
         # do the filetype associations
-        self._write("  <FiletypeAssociations>")
+        self.writeStartElement("FiletypeAssociations")
         for pattern, filetype in list(self.pdata["FILETYPES"].items()):
-            self._write('    <FiletypeAssociation pattern="{0}" type="{1}" />'.format(
-                pattern, filetype))
-        self._write("  </FiletypeAssociations>")
+            self.writeEmptyElement("FiletypeAssociation")
+            self.writeAttribute("pattern", pattern)
+            self.writeAttribute("type", filetype)
+        self.writeEndElement()
         
         # do the lexer associations
         if self.pdata["LEXERASSOCS"]:
-            self._write("  <LexerAssociations>")
+            self.writeStartElement("LexerAssociations")
             for pattern, lexer in list(self.pdata["LEXERASSOCS"].items()):
-                self._write('    <LexerAssociation pattern="{0}" lexer="{1}" />'.format(
-                    pattern, lexer))
-            self._write("  </LexerAssociations>")
+                self.writeEmptyElement("LexerAssociation")
+                self.writeAttribute("pattern", pattern)
+                self.writeAttribute("lexer", lexer)
+            self.writeEndElement()
         
         # do the extra project data stuff
         if len(self.pdata["PROJECTTYPESPECIFICDATA"]):
-            self._write("  <ProjectTypeSpecific>")
+            self.writeStartElement("ProjectTypeSpecific")
             if self.pdata["PROJECTTYPESPECIFICDATA"]:
-                self._write("    <ProjectTypeSpecificData>")
-                self._writeBasics(self.pdata["PROJECTTYPESPECIFICDATA"], 3)
-                self._write("    </ProjectTypeSpecificData>")
-            self._write("  </ProjectTypeSpecific>")
+                self.writeBasics("ProjectTypeSpecificData", 
+                    self.pdata["PROJECTTYPESPECIFICDATA"])
+            self.writeEndElement()
         
         # do the documentation generators stuff
         if len(self.pdata["DOCUMENTATIONPARMS"]):
-            self._write("  <Documentation>")
+            self.writeStartElement("Documentation")
             if self.pdata["DOCUMENTATIONPARMS"]:
-                self._write("    <DocumentationParams>")
-                self._writeBasics(self.pdata["DOCUMENTATIONPARMS"], 3)
-                self._write("    </DocumentationParams>")
-            self._write("  </Documentation>")
+                self.writeBasics("DocumentationParams", 
+                    self.pdata["DOCUMENTATIONPARMS"])
+            self.writeEndElement()
         
         # do the packagers stuff
         if len(self.pdata["PACKAGERSPARMS"]):
-            self._write("  <Packagers>")
+            self.writeStartElement("Packagers")
             if self.pdata["PACKAGERSPARMS"]:
-                self._write("    <PackagersParams>")
-                self._writeBasics(self.pdata["PACKAGERSPARMS"], 3)
-                self._write("    </PackagersParams>")
-            self._write("  </Packagers>")
+                self.writeBasics("PackagersParams", 
+                    self.pdata["PACKAGERSPARMS"])
+            self.writeEndElement()
         
         # do the checkers stuff
         if len(self.pdata["CHECKERSPARMS"]):
-            self._write("  <Checkers>")
+            self.writeStartElement("Checkers")
             if self.pdata["CHECKERSPARMS"]:
-                self._write("    <CheckersParams>")
-                self._writeBasics(self.pdata["CHECKERSPARMS"], 3)
-                self._write("    </CheckersParams>")
-            self._write("  </Checkers>")
+                self.writeBasics("CheckersParams", 
+                    self.pdata["CHECKERSPARMS"])
+            self.writeEndElement()
         
         # do the other tools stuff
         if len(self.pdata["OTHERTOOLSPARMS"]):
-            self._write("  <OtherTools>")
+            self.writeStartElement("OtherTools")
             if self.pdata["OTHERTOOLSPARMS"]:
-                self._write("    <OtherToolsParams>")
-                self._writeBasics(self.pdata["OTHERTOOLSPARMS"], 3)
-                self._write("    </OtherToolsParams>")
-            self._write("  </OtherTools>")
+                self.writeBasics("OtherToolsParams", 
+                    self.pdata["OTHERTOOLSPARMS"])
+            self.writeEndElement()
         
-        self._write("</Project>", newline = False)
+        self.writeEndElement()
+        self.writeEndDocument()
--- a/E5XML/XMLStreamWriterBase.py	Mon Sep 13 16:14:10 2010 +0200
+++ b/E5XML/XMLStreamWriterBase.py	Mon Sep 13 19:52:30 2010 +0200
@@ -50,6 +50,17 @@
         # write the XML header
         self.writeStartDocument()
     
+    def writeBasics(self, tag, pyobject):
+        """
+        Public method to write a tag with a basic Python object dump.
+        
+        @param tag tag name (string)
+        @param pyobject object to be dumped
+        """
+        self.writeStartElement(tag)
+        self._writeBasics(pyobject)
+        self.writeEndElement()
+    
     def _writeBasics(self, pyobject):
         """
         Protected method to dump an object of a basic Python type.
--- a/Project/Project.py	Mon Sep 13 16:14:10 2010 +0200
+++ b/Project/Project.py	Mon Sep 13 19:52:30 2010 +0200
@@ -756,7 +756,16 @@
         if fn is None:
             fn = self.pfile
         
-        res = self.__writeXMLProject(fn)
+        f = QFile(fn)
+        if f.open(QIODevice.WriteOnly):
+            ProjectWriter(f, os.path.splitext(os.path.basename(fn))[0]).writeXML()
+            res = True
+        else:
+            E5MessageBox.critical(self.ui,
+                self.trUtf8("Save project file"),
+                self.trUtf8("<p>The project file <b>{0}</b> could not be written.</p>")\
+                    .format(fn))
+            res = False
         
         if res:
             self.pfile = os.path.abspath(fn)
@@ -773,48 +782,6 @@
         
         return res
         
-    def __writeXMLProject(self, fn = None):
-        """
-        Private method to write the project data to an XML file.
-        
-        @param fn the filename of the project file (string)
-        @return flag indicating success (boolean)
-        """
-        try:
-            if self.pdata["EOL"][0] == 0:
-                newline = None
-            else:
-                newline = self.getEolString()
-            if fn.lower().endswith("e4pz"):
-                try:
-                    import gzip
-                except ImportError:
-                    E5MessageBox.critical(self.ui,
-                        self.trUtf8("Save project file"),
-                        self.trUtf8("""Compressed project files not supported."""
-                                    """ The compression library is missing."""))
-                    return False
-                f = io.StringIO(newline = newline)
-            else:
-                f = open(fn, "w", encoding = "utf-8", newline = newline)
-            
-            ProjectWriter(f, os.path.splitext(os.path.basename(fn))[0]).writeXML()
-            
-            if fn.lower().endswith("e4pz"):
-                g = gzip.open(fn, "wb")
-                g.write(f.getvalue().encode("utf-8"))
-                g.close()
-            f.close()
-            
-        except IOError:
-            E5MessageBox.critical(self.ui,
-                self.trUtf8("Save project file"),
-                self.trUtf8("<p>The project file <b>{0}</b> could not be written.</p>")\
-                    .format(fn))
-            return False
-        
-        return True
-        
     def __readUserProperties(self):
         """
         Private method to read in the user specific project file (.e4q)

eric ide

mercurial