/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/chk_serializer.py

  • Committer: Robert Collins
  • Date: 2008-01-06 20:04:22 UTC
  • mto: (3221.11.1 StackableBranch)
  • mto: This revision was merged to the branch mainline in revision 3226.
  • Revision ID: robertc@robertcollins.net-20080106200422-x8yz6cxotlzltvwp
The bzrdir format registry now accepts an ``alias`` keyword to
register_metadir, used to indicate that a format name is an alias for
some other format and thus should not be reported when describing the
format. (Robert Collins)
-------------- This line and the fmllowing will be ignored --------------

modified:
  NEWS
  bzrlib/bzrdir.py
  bzrlib/info.py
  bzrlib/tests/test_bzrdir.py
  bzrlib/tests/test_info.py

=== modified file 'NEWS'
--- a/NEWS      2008-01-02 22:30:46 +0000
+++ b/NEWS      2008-01-06 20:04:15 +0000
@@ -135,6 +135,11 @@
     * Patience Diff now supports arbitrary python objects, as long as they
       support ``hash()``. (John Arbash Meinel)
 
+    * The bzrdir format registry now accepts an ``alias`` keyword to
+      register_metadir, used to indicate that a format name is an alias for
+      some other format and thus should not be reported when describing the
+      format. (Robert Collins)
+
   API BREAKS:
 
   TESTING:

=== modified file 'bzrlib/bzrdir.py'
--- a/bzrlib/bzrdir.py  2008-01-02 22:30:46 +0000
+++ b/bzrlib/bzrdir.py  2008-01-06 19:41:29 +0000
@@ -2447,12 +2447,22 @@
     e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
     """
 
+    def __init__(self):
+        """Create a BzrDirFormatRegistry."""
+        self._aliases = set()
+        super(BzrDirFormatRegistry, self).__init__()
+
+    def aliases(self):
+        """Return a set of the format names which are aliases."""
+        return frozenset(self._aliases)
+
     def register_metadir(self, key,
              repository_format, help, native=True, deprecated=False,
              branch_format=None,
              tree_format=None,
              hidden=False,
-             experimental=False):
+             experimental=False,
+             alias=False):
         """Register a metadir subformat.
 
         These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
@@ -2491,10 +2501,10 @@
                 bd.repository_format = _load(repository_format)
             return bd
         self.register(key, helper, help, native, deprecated, hidden,
-            experimental)
+            experimental, alias)
 
     def register(self, key, factory, help, native=True, deprecated=False,
-                 hidden=False, experimental=False):
+                 hidden=False, experimental=False, alias=False):
         """Register a BzrDirFormat factory.
         
         The factory must be a callable that takes one parameter: the key.
@@ -2505,11 +2515,15 @@
         """
         registry.Registry.register(self, key, factory, help,
             BzrDirFormatInfo(native, deprecated, hidden, experimental))
+        if alias:
+            self._aliases.add(key)
 
     def register_lazy(self, key, module_name, member_name, help, native=True,
-                      deprecated=False, hidden=False, experimental=False):
+        deprecated=False, hidden=False, experimental=False, alias=False):
         registry.Registry.register_lazy(self, key, module_name, member_name,
             help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
+        if alias:
+            self._aliases.add(key)
 
     def set_default(self, key):
         """Set the 'default' key to be a clone of the supplied key.
@@ -2518,6 +2532,7 @@
         """
         registry.Registry.register(self, 'default', self.get(key),
             self.get_help(key), info=self.get_info(key))
+        self._aliases.add('default')
 
     def set_default_repository(self, key):
         """Set the FormatRegistry default and Repository default.
@@ -2670,6 +2685,7 @@
     tree_format='bzrlib.workingtree.WorkingTreeFormat4',
     hidden=False,
     )
+# The following two formats should always just be aliases.
 format_registry.register_metadir('development',
     'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0',
     help='Current development format. Can convert data to and from pack-0.92 '
@@ -2681,6 +2697,7 @@
     branch_format='bzrlib.branch.BzrBranchFormat6',
     tree_format='bzrlib.workingtree.WorkingTreeFormat4',
     experimental=True,
+    alias=True,
     )
 format_registry.register_metadir('development-subtree',
     'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0Subtree',
@@ -2693,7 +2710,9 @@
     branch_format='bzrlib.branch.BzrBranchFormat6',
     tree_format='bzrlib.workingtree.WorkingTreeFormat4',
     experimental=True,
+    alias=True,
     )
+# And the development formats which the will have aliased one of follow:
 format_registry.register_metadir('development0',
     'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0',
     help='Trivial rename of pack-0.92 to provide a development format. '

=== modified file 'bzrlib/info.py'
--- a/bzrlib/info.py    2007-11-06 09:00:25 +0000
+++ b/bzrlib/info.py    2008-01-06 20:01:30 +0000
@@ -440,7 +440,9 @@
         tree.bzrdir.root_transport.base):
         branch = None
         repository = None
-    for key in bzrdir.format_registry.keys():
+    non_aliases = set(bzrdir.format_registry.keys())
+    non_aliases.difference_update(bzrdir.format_registry.aliases())
+    for key in non_aliases:
         format = bzrdir.format_registry.make_bzrdir(key)
         if isinstance(format, bzrdir.BzrDirMetaFormat1):
             if (tree and format.workingtree_format !=
@@ -457,11 +459,12 @@
         candidates.append(key)
     if len(candidates) == 0:
         return 'unnamed'
-    new_candidates = [c for c in candidates if c != 'default']
-    if len(new_candidates) > 0:
-        candidates = new_candidates
+    candidates.sort()
     new_candidates = [c for c in candidates if not
         bzrdir.format_registry.get_info(c).hidden]
     if len(new_candidates) > 0:
+        # If there are any non-hidden formats that match, only return those to
+        # avoid listing hidden formats except when only a hidden format will
+        # do.
         candidates = new_candidates
     return ' or '.join(candidates)

=== modified file 'bzrlib/tests/test_bzrdir.py'
--- a/bzrlib/tests/test_bzrdir.py       2007-12-21 20:32:22 +0000
+++ b/bzrlib/tests/test_bzrdir.py       2008-01-06 19:45:00 +0000
@@ -170,6 +170,16 @@
         finally:
             bzrdir.format_registry.set_default_repository(old_default)
 
+    def test_aliases(self):
+        a_registry = bzrdir.BzrDirFormatRegistry()
+        a_registry.register('weave', bzrdir.BzrDirFormat6,
+            'Pre-0.8 format.  Slower and does not support checkouts or shared'
+            ' repositories', deprecated=True)
+        a_registry.register('weavealias', bzrdir.BzrDirFormat6,
+            'Pre-0.8 format.  Slower and does not support checkouts or shared'
+            ' repositories', deprecated=True, alias=True)
+        self.assertEqual(frozenset(['weavealias']), a_registry.aliases())
+    
 
 class SampleBranch(bzrlib.branch.Branch):
     """A dummy branch for guess what, dummy use."""

=== modified file 'bzrlib/tests/test_info.py'
--- a/bzrlib/tests/test_info.py 2007-11-26 13:55:51 +0000
+++ b/bzrlib/tests/test_info.py 2008-01-06 20:02:10 +0000
@@ -126,16 +126,22 @@
 
     def test_describe_tree_format(self):
         for key in bzrdir.format_registry.keys():
-            if key == 'default':
+            if key in bzrdir.format_registry.aliases():
                 continue
             self.assertTreeDescription(key)
 
     def test_describe_checkout_format(self):
         for key in bzrdir.format_registry.keys():
-            if key in ('default', 'weave', 'experimental'):
-                continue
-            if key.startswith('experimental-'):
-                # these are typically hidden or aliases for other formats
+            if key in bzrdir.format_registry.aliases():
+                # Aliases will not describe correctly in the UI because the
+                # real format is found.
+                continue
+            # legacy: weave does not support checkouts
+            if key == 'weave':
+                continue
+            if bzrdir.format_registry.get_info(key).experimental:
+                # We don't require that experimental formats support checkouts
+                # or describe correctly in the UI.
                 continue
             expected = None
             if key in ('dirstate', 'dirstate-tags', 'dirstate-with-subtree',
@@ -149,7 +155,7 @@
 
     def test_describe_branch_format(self):
         for key in bzrdir.format_registry.keys():
-            if key == 'default':
+            if key in bzrdir.format_registry.aliases():
                 continue
             expected = None
             if key in ('dirstate', 'knit'):
@@ -158,7 +164,7 @@
 
     def test_describe_repo_format(self):
         for key in bzrdir.format_registry.keys():
-            if key == 'default':
+            if key in bzrdir.format_registry.aliases():
                 continue
             expected = None
             if key in ('dirstate', 'knit', 'dirstate-tags'):

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
2
 
#
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
"""Serializer object for CHK based inventory storage."""
18
 
 
19
 
from bzrlib import (
20
 
    bencode,
21
 
    cache_utf8,
22
 
    inventory,
23
 
    revision as _mod_revision,
24
 
    xml6,
25
 
    xml7,
26
 
    )
27
 
 
28
 
 
29
 
def _validate_properties(props, _decode=cache_utf8._utf8_decode):
30
 
    # TODO: we really want an 'isascii' check for key
31
 
    # Cast the utf8 properties into Unicode 'in place'
32
 
    for key, value in props.iteritems():
33
 
        props[key] = _decode(value)[0]
34
 
    return props
35
 
 
36
 
 
37
 
def _is_format_10(value):
38
 
    if value != 10:
39
 
        raise ValueError('Format number was not recognized, expected 10 got %d'
40
 
                         % (value,))
41
 
    return 10
42
 
 
43
 
 
44
 
class BEncodeRevisionSerializer1(object):
45
 
    """Simple revision serializer based around bencode.
46
 
    """
47
 
 
48
 
    squashes_xml_invalid_characters = False
49
 
 
50
 
    # Maps {key:(Revision attribute, bencode_type, validator)}
51
 
    # This tells us what kind we expect bdecode to create, what variable on
52
 
    # Revision we should be using, and a function to call to validate/transform
53
 
    # the type.
54
 
    # TODO: add a 'validate_utf8' for things like revision_id and file_id
55
 
    #       and a validator for parent-ids
56
 
    _schema = {'format': (None, int, _is_format_10),
57
 
               'committer': ('committer', str, cache_utf8.decode),
58
 
               'timezone': ('timezone', int, None),
59
 
               'timestamp': ('timestamp', str, float),
60
 
               'revision-id': ('revision_id', str, None),
61
 
               'parent-ids': ('parent_ids', list, None),
62
 
               'inventory-sha1': ('inventory_sha1', str, None),
63
 
               'message': ('message', str, cache_utf8.decode),
64
 
               'properties': ('properties', dict, _validate_properties),
65
 
    }
66
 
 
67
 
    def write_revision_to_string(self, rev):
68
 
        encode_utf8 = cache_utf8._utf8_encode
69
 
        # Use a list of tuples rather than a dict
70
 
        # This lets us control the ordering, so that we are able to create
71
 
        # smaller deltas
72
 
        ret = [
73
 
            ("format", 10),
74
 
            ("committer", encode_utf8(rev.committer)[0]),
75
 
        ]
76
 
        if rev.timezone is not None:
77
 
            ret.append(("timezone", rev.timezone))
78
 
        # For bzr revisions, the most common property is just 'branch-nick'
79
 
        # which changes infrequently.
80
 
        revprops = {}
81
 
        for key, value in rev.properties.iteritems():
82
 
            revprops[key] = encode_utf8(value)[0]
83
 
        ret.append(('properties', revprops))
84
 
        ret.extend([
85
 
            ("timestamp", "%.3f" % rev.timestamp),
86
 
            ("revision-id", rev.revision_id),
87
 
            ("parent-ids", rev.parent_ids),
88
 
            ("inventory-sha1", rev.inventory_sha1),
89
 
            ("message", encode_utf8(rev.message)[0]),
90
 
        ])
91
 
        return bencode.bencode(ret)
92
 
 
93
 
    def write_revision(self, rev, f):
94
 
        f.write(self.write_revision_to_string(rev))
95
 
 
96
 
    def read_revision_from_string(self, text):
97
 
        # TODO: consider writing a Revision decoder, rather than using the
98
 
        #       generic bencode decoder
99
 
        #       However, to decode all 25k revisions of bzr takes approx 1.3s
100
 
        #       If we remove all extra validation that goes down to about 1.2s.
101
 
        #       Of that time, probably 0.6s is spend in bencode.bdecode().
102
 
        #       Regardless 'time bzr log' of everything is 7+s, so 1.3s to
103
 
        #       extract revision texts isn't a majority of time.
104
 
        ret = bencode.bdecode(text)
105
 
        if not isinstance(ret, list):
106
 
            raise ValueError("invalid revision text")
107
 
        schema = self._schema
108
 
        # timezone is allowed to be missing, but should be set
109
 
        bits = {'timezone': None}
110
 
        for key, value in ret:
111
 
            # Will raise KeyError if not a valid part of the schema, or an
112
 
            # entry is given 2 times.
113
 
            var_name, expected_type, validator = schema[key]
114
 
            if value.__class__ is not expected_type:
115
 
                raise ValueError('key %s did not conform to the expected type'
116
 
                                 ' %s, but was %s'
117
 
                                 % (key, expected_type, type(value)))
118
 
            if validator is not None:
119
 
                value = validator(value)
120
 
            bits[var_name] = value
121
 
        if len(bits) != len(schema):
122
 
            missing = [key for key, (var_name, _, _) in schema.iteritems()
123
 
                       if var_name not in bits]
124
 
            raise ValueError('Revision text was missing expected keys %s.'
125
 
                             ' text %r' % (missing, text))
126
 
        del bits[None]  # Get rid of 'format' since it doesn't get mapped
127
 
        rev = _mod_revision.Revision(**bits)
128
 
        return rev
129
 
 
130
 
    def read_revision(self, f):
131
 
        return self.read_revision_from_string(f.read())
132
 
 
133
 
 
134
 
class CHKSerializerSubtree(BEncodeRevisionSerializer1, xml7.Serializer_v7):
135
 
    """A CHKInventory based serializer that supports tree references"""
136
 
 
137
 
    supported_kinds = set(['file', 'directory', 'symlink', 'tree-reference'])
138
 
    format_num = '9'
139
 
    revision_format_num = None
140
 
    support_altered_by_hack = False
141
 
 
142
 
    def _unpack_entry(self, elt, entry_cache=None, return_from_cache=False):
143
 
        kind = elt.tag
144
 
        if not kind in self.supported_kinds:
145
 
            raise AssertionError('unsupported entry kind %s' % kind)
146
 
        if kind == 'tree-reference':
147
 
            file_id = elt.attrib['file_id']
148
 
            name = elt.attrib['name']
149
 
            parent_id = elt.attrib['parent_id']
150
 
            revision = elt.get('revision')
151
 
            reference_revision = elt.get('reference_revision')
152
 
            return inventory.TreeReference(file_id, name, parent_id, revision,
153
 
                                           reference_revision)
154
 
        else:
155
 
            return xml7.Serializer_v7._unpack_entry(self, elt,
156
 
                entry_cache=entry_cache, return_from_cache=return_from_cache)
157
 
 
158
 
    def __init__(self, node_size, search_key_name):
159
 
        self.maximum_size = node_size
160
 
        self.search_key_name = search_key_name
161
 
 
162
 
 
163
 
class CHKSerializer(xml6.Serializer_v6):
164
 
    """A CHKInventory based serializer with 'plain' behaviour."""
165
 
 
166
 
    format_num = '9'
167
 
    revision_format_num = None
168
 
    support_altered_by_hack = False
169
 
 
170
 
    def __init__(self, node_size, search_key_name):
171
 
        self.maximum_size = node_size
172
 
        self.search_key_name = search_key_name
173
 
 
174
 
 
175
 
chk_serializer_255_bigpage = CHKSerializer(65536, 'hash-255-way')
176
 
 
177
 
 
178
 
class CHKBEncodeSerializer(BEncodeRevisionSerializer1, CHKSerializer):
179
 
    """A CHKInventory and BEncode based serializer with 'plain' behaviour."""
180
 
 
181
 
    format_num = '10'
182
 
 
183
 
 
184
 
chk_bencode_serializer = CHKBEncodeSerializer(65536, 'hash-255-way')