[Pkg-bazaar-commits] ./bzr/unstable r802: - Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions

Martin Pool mbp at sourcefrog.net
Fri Apr 10 08:21:05 UTC 2009


------------------------------------------------------------
revno: 802
committer: Martin Pool <mbp at sourcefrog.net>
timestamp: Tue 2005-06-28 15:33:40 +1000
message:
  - Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
    called as needed.  
  
  - Avoid importing xml and ElementTree library unless needed.
modified:
  bzrlib/branch.py
  bzrlib/commands.py
  bzrlib/commit.py
  bzrlib/inventory.py
  bzrlib/remotebranch.py
  bzrlib/revision.py
  bzrlib/upgrade.py
  bzrlib/xml.py
-------------- next part --------------
=== modified file 'bzrlib/branch.py'
--- a/bzrlib/branch.py	2005-06-28 03:02:31 +0000
+++ b/bzrlib/branch.py	2005-06-28 05:33:40 +0000
@@ -291,6 +291,8 @@
 
     def _make_control(self):
         from bzrlib.inventory import Inventory
+        from bzrlib.xml import pack_xml
+        
         os.mkdir(self.controlfilename([]))
         self.controlfile('README', 'w').write(
             "This is a Bazaar-NG control directory.\n"
@@ -303,7 +305,8 @@
                   'branch-lock'):
             self.controlfile(f, 'w').write('')
         mutter('created control directory in ' + self.base)
-        Inventory().write_xml(self.controlfile('inventory','w'))
+
+        pack_xml(Inventory(), self.controlfile('inventory','w'))
 
 
     def _check_format(self):
@@ -329,13 +332,15 @@
     def read_working_inventory(self):
         """Read the working inventory."""
         from bzrlib.inventory import Inventory
+        from bzrlib.xml import unpack_xml
         from time import time
         before = time()
-        # ElementTree does its own conversion from UTF-8, so open in
-        # binary.
         self.lock_read()
         try:
-            inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
+            # ElementTree does its own conversion from UTF-8, so open in
+            # binary.
+            inv = unpack_xml(Inventory,
+                                  self.controlfile('inventory', 'rb'))
             mutter("loaded inventory of %d items in %f"
                    % (len(inv), time() - before))
             return inv
@@ -349,13 +354,14 @@
         That is to say, the inventory describing changes underway, that
         will be committed to the next revision.
         """
+        from bzrlib.atomicfile import AtomicFile
+        from bzrlib.xml import pack_xml
+        
         self.lock_write()
         try:
-            from bzrlib.atomicfile import AtomicFile
-
             f = AtomicFile(self.controlfilename('inventory'), 'wb')
             try:
-                inv.write_xml(f)
+                pack_xml(inv, f)
                 f.commit()
             finally:
                 f.close()
@@ -555,11 +561,19 @@
     def get_revision(self, revision_id):
         """Return the Revision object for a named revision"""
         from bzrlib.revision import Revision
-        if not revision_id or not isinstance(revision_id, basestring):
-            raise ValueError('invalid revision-id: %r' % revision_id)
-        r = Revision.read_xml(self.revision_store[revision_id])
+        from bzrlib.xml import unpack_xml
+
+        self.lock_read()
+        try:
+            if not revision_id or not isinstance(revision_id, basestring):
+                raise ValueError('invalid revision-id: %r' % revision_id)
+            r = unpack_xml(Revision, self.revision_store[revision_id])
+        finally:
+            self.unlock()
+            
         assert r.revision_id == revision_id
         return r
+        
 
     def get_revision_sha1(self, revision_id):
         """Hash the stored value of a revision, and return it."""
@@ -579,8 +593,10 @@
                parameter which can be either an integer revno or a
                string hash."""
         from bzrlib.inventory import Inventory
-        i = Inventory.read_xml(self.inventory_store[inventory_id])
-        return i
+        from bzrlib.xml import unpack_xml
+
+        return unpack_xml(Inventory, self.inventory_store[inventory_id])
+            
 
     def get_inventory_sha1(self, inventory_id):
         """Return the sha1 hash of the inventory entry

=== modified file 'bzrlib/commands.py'
--- a/bzrlib/commands.py	2005-06-28 03:02:31 +0000
+++ b/bzrlib/commands.py	2005-06-28 05:33:40 +0000
@@ -323,7 +323,8 @@
     takes_args = ['revision_id']
     
     def run(self, revision_id):
-        find_branch('.').get_revision(revision_id).write_xml(sys.stdout)
+        from bzrlib.xml import pack_xml
+        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
 
 
 class cmd_revno(Command):

=== modified file 'bzrlib/commit.py'
--- a/bzrlib/commit.py	2005-06-20 04:57:46 +0000
+++ b/bzrlib/commit.py	2005-06-28 05:33:40 +0000
@@ -60,6 +60,7 @@
     from bzrlib.errors import BzrError
     from bzrlib.revision import Revision, RevisionReference
     from bzrlib.trace import mutter, note
+    from bzrlib.xml import pack_xml
 
     branch.lock_write()
 
@@ -108,7 +109,7 @@
         inv_id = rev_id
 
         inv_tmp = tempfile.TemporaryFile()
-        new_inv.write_xml(inv_tmp)
+        pack_xml(new_inv, inv_tmp)
         inv_tmp.seek(0)
         branch.inventory_store.add(inv_tmp, inv_id)
         mutter('new inventory_id is {%s}' % inv_id)
@@ -144,7 +145,7 @@
             rev.parents = [RevisionReference(precursor_id, precursor_sha1)]
 
         rev_tmp = tempfile.TemporaryFile()
-        rev.write_xml(rev_tmp)
+        pack_xml(rev, rev_tmp)
         rev_tmp.seek(0)
         branch.revision_store.add(rev_tmp, rev_id)
         mutter("new revision_id is {%s}" % rev_id)

=== modified file 'bzrlib/inventory.py'
--- a/bzrlib/inventory.py	2005-06-28 03:02:31 +0000
+++ b/bzrlib/inventory.py	2005-06-28 05:33:40 +0000
@@ -23,13 +23,12 @@
 import sys, os.path, types, re
 
 import bzrlib
-from bzrlib.xml import XMLMixin, Element
 from bzrlib.errors import BzrError, BzrCheckError
 
 from bzrlib.osutils import uuid, quotefn, splitpath, joinpath, appendpath
 from bzrlib.trace import mutter
 
-class InventoryEntry(XMLMixin):
+class InventoryEntry(object):
     """Description of a versioned file.
 
     An InventoryEntry has the following fields, which are also
@@ -155,6 +154,8 @@
     
     def to_element(self):
         """Convert to XML element"""
+        from bzrlib.xml import Element
+        
         e = Element('entry')
 
         e.set('name', self.name)
@@ -243,7 +244,7 @@
 
 
 
-class Inventory(XMLMixin):
+class Inventory(object):
     """Inventory of versioned files in a tree.
 
     This describes which file_id is present at each point in the tree,
@@ -261,9 +262,6 @@
     inserted, other than through the Inventory API.
 
     >>> inv = Inventory()
-    >>> inv.write_xml(sys.stdout)
-    <inventory>
-    </inventory>
     >>> inv.add(InventoryEntry('123-123', 'hello.c', 'file', ROOT_ID))
     >>> inv['123-123'].name
     'hello.c'
@@ -279,12 +277,6 @@
 
     >>> [x[0] for x in inv.iter_entries()]
     ['hello.c']
-    
-    >>> inv.write_xml(sys.stdout)
-    <inventory>
-    <entry file_id="123-123" kind="file" name="hello.c" />
-    </inventory>
-
     """
     def __init__(self):
         """Create or read an inventory.
@@ -473,6 +465,8 @@
 
     def to_element(self):
         """Convert to XML Element"""
+        from bzrlib.xml import Element
+        
         e = Element('inventory')
         e.text = '\n'
         for path, ie in self.iter_entries():

=== modified file 'bzrlib/remotebranch.py'
--- a/bzrlib/remotebranch.py	2005-06-24 04:35:47 +0000
+++ b/bzrlib/remotebranch.py	2005-06-28 05:33:40 +0000
@@ -143,10 +143,12 @@
         pl = len(self.baseurl)
         return path[pl:].lstrip('/')
 
+
     def get_revision(self, revision_id):
-        from revision import Revision
+        from bzrlib.revision import Revision
+        from bzrlib.xml import unpack_xml
         revf = self.revision_store[revision_id]
-        r = Revision.read_xml(revf)
+        r = unpack_xml(Revision, revf)
         if r.revision_id != revision_id:
             raise BzrCheckError('revision stored as {%s} actually contains {%s}'
                                 % (revision_id, r.revision_id))
@@ -170,9 +172,10 @@
 
 def simple_walk():
     """For experimental purposes, traverse many parts of a remote branch"""
-    from revision import Revision
-    from branch import Branch
-    from inventory import Inventory
+    from bzrlib.revision import Revision
+    from bzrlib.branch import Branch
+    from bzrlib.inventory import Inventory
+    from bzrlib.xml import unpack_xml
 
     got_invs = {}
     got_texts = {}
@@ -190,7 +193,7 @@
         rev_f = get_url('/.bzr/revision-store/%s' % rev_id,
                         compressed=True)
 
-        rev = Revision.read_xml(rev_f)
+        rev = unpack_xml(Revision, rev_f)
         print rev.message
         inv_id = rev.inventory_id
         if inv_id not in got_invs:

=== modified file 'bzrlib/revision.py'
--- a/bzrlib/revision.py	2005-06-28 03:02:31 +0000
+++ b/bzrlib/revision.py	2005-06-28 05:33:40 +0000
@@ -17,12 +17,7 @@
 
 
 
-from xml import XMLMixin, Element, SubElement
-
-from errors import BzrError
-
-
-class RevisionReference:
+class RevisionReference(object):
     """
     Reference to a stored revision.
 
@@ -46,7 +41,7 @@
                 
 
 
-class Revision(XMLMixin):
+class Revision(object):
     """Single revision on a branch.
 
     Revisions may know their revision_hash, but only once they've been
@@ -105,6 +100,8 @@
 
         
     def to_element(self):
+        from bzrlib.xml import Element, SubElement
+        
         root = Element('revision',
                        committer = self.committer,
                        timestamp = '%.9f' % self.timestamp,
@@ -154,6 +151,8 @@
 def unpack_revision(elt):
     """Convert XML element into Revision object."""
     # <changeset> is deprecated...
+    from bzrlib.errors import BzrError
+    
     if elt.tag not in ('revision', 'changeset'):
         raise BzrError("unexpected tag in revision file: %r" % elt)
 

=== modified file 'bzrlib/upgrade.py'
--- a/bzrlib/upgrade.py	2005-06-20 03:45:02 +0000
+++ b/bzrlib/upgrade.py	2005-06-28 05:33:40 +0000
@@ -92,8 +92,10 @@
                 # there should be *some* way of making old entries have
                 # the full meta information.
                 import tempfile, os, errno
+                from bzrlib.xml import pack_xml
+                
                 rev_tmp = tempfile.TemporaryFile()
-                rev.write_xml(rev_tmp)
+                pack_xml(rev, rev_tmp)
                 rev_tmp.seek(0)
 
                 tmpfd, tmp_path = tempfile.mkstemp(prefix=rev_id, suffix='.gz',

=== modified file 'bzrlib/xml.py'
--- a/bzrlib/xml.py	2005-06-28 03:06:39 +0000
+++ b/bzrlib/xml.py	2005-06-28 05:33:40 +0000
@@ -20,55 +20,21 @@
 # "XML is like violence: if it doesn't solve your problem, you aren't
 # using enough of it." -- various
 
-
-__copyright__ = "Copyright (C) 2005 Canonical Ltd."
-__author__ = "Martin Pool <mbp at canonical.com>"
-
-_ElementTree = None
-def ElementTree(*args, **kwargs):
-    global _ElementTree
-    if _ElementTree is None:
-        try:
-            from cElementTree import ElementTree
-        except ImportError:
-            from elementtree.ElementTree import ElementTree
-        _ElementTree = ElementTree
-    return _ElementTree(*args, **kwargs)
-
-_Element = None
-def Element(*args, **kwargs):
-    global _Element
-    if _Element is None:
-        try:
-            from cElementTree import Element
-        except ImportError:
-            from elementtree.ElementTree import Element
-        _Element = Element
-    return _Element(*args, **kwargs)
-
-
-_SubElement = None
-def SubElement(*args, **kwargs):
-    global _SubElement
-    if _SubElement is None:
-        try:
-            from cElementTree import SubElement
-        except ImportError:
-            from elementtree.ElementTree import SubElement
-        _SubElement = SubElement
-    return _SubElement(*args, **kwargs)
-
-
-class XMLMixin:
-    def to_element(self):
-        raise Exception("XMLMixin.to_element must be overridden in concrete classes")
-    
-    def write_xml(self, f):
-        ElementTree(self.to_element()).write(f, 'utf-8')
-        f.write('\n')
-
-    def read_xml(cls, f):
-        return cls.from_element(ElementTree().parse(f))
-
-    read_xml = classmethod(read_xml)
-
+# importing this module is fairly slow because it has to load several ElementTree bits
+try:
+    from cElementTree import ElementTree, SubElement, Element
+except ImportError:
+    from elementtree.ElementTree import ElementTree, SubElement, Element
+
+
+def pack_xml(o, f):
+    """Write object o to file f as XML.
+
+    o must provide a to_element method.
+    """
+    ElementTree(o.to_element()).write(f, 'utf-8')
+    f.write('\n')
+
+
+def unpack_xml(cls, f):
+    return cls.from_element(ElementTree().parse(f))



More information about the Pkg-bazaar-commits mailing list