/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/bzrdir_weave.py

  • Committer: Jelmer Vernooij
  • Date: 2011-03-10 11:50:14 UTC
  • mto: (5582.10.90 weave-plugin)
  • mto: This revision was merged to the branch mainline in revision 5717.
  • Revision ID: jelmer@samba.org-20110310115014-av2k5m3pwklbxigm
Move weave-era BzrDir directories to a separate file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-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
"""Weave-era BzrDir formats."""
 
18
 
 
19
from bzrlib.bzrdir import (
 
20
    BzrDir,
 
21
    BzrDirFormat,
 
22
    BzrDirMetaFormat1,
 
23
    )
 
24
from bzrlib.controldir import (
 
25
    Converter,
 
26
    format_registry,
 
27
    )
 
28
from bzrlib.lazy_import import lazy_import
 
29
lazy_import(globals(), """
 
30
import os
 
31
import warnings
 
32
 
 
33
from bzrlib import (
 
34
    errors,
 
35
    graph,
 
36
    lockable_files,
 
37
    lockdir,
 
38
    osutils,
 
39
    revision as _mod_revision,
 
40
    trace,
 
41
    ui,
 
42
    urlutils,
 
43
    versionedfile,
 
44
    weave,
 
45
    xml5,
 
46
    )
 
47
from bzrlib.store.versioned import VersionedFileStore
 
48
from bzrlib.transactions import WriteTransaction
 
49
from bzrlib.transport import (
 
50
    get_transport,
 
51
    local,
 
52
    )
 
53
from bzrlib.plugins.weave_fmt import xml4
 
54
""")
 
55
 
 
56
 
 
57
class BzrDirFormatAllInOne(BzrDirFormat):
 
58
    """Common class for formats before meta-dirs."""
 
59
 
 
60
    fixed_components = True
 
61
 
 
62
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
63
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
64
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
65
        shared_repo=False):
 
66
        """See BzrDirFormat.initialize_on_transport_ex."""
 
67
        require_stacking = (stacked_on is not None)
 
68
        # Format 5 cannot stack, but we've been asked to - actually init
 
69
        # a Meta1Dir
 
70
        if require_stacking:
 
71
            format = BzrDirMetaFormat1()
 
72
            return format.initialize_on_transport_ex(transport,
 
73
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
74
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
75
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
76
                make_working_trees=make_working_trees, shared_repo=shared_repo)
 
77
        return BzrDirFormat.initialize_on_transport_ex(self, transport,
 
78
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
79
            force_new_repo=force_new_repo, stacked_on=stacked_on,
 
80
            stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
81
            make_working_trees=make_working_trees, shared_repo=shared_repo)
 
82
 
 
83
 
 
84
class BzrDirFormat5(BzrDirFormatAllInOne):
 
85
    """Bzr control format 5.
 
86
 
 
87
    This format is a combined format for working tree, branch and repository.
 
88
    It has:
 
89
     - Format 2 working trees [always]
 
90
     - Format 4 branches [always]
 
91
     - Format 5 repositories [always]
 
92
       Unhashed stores in the repository.
 
93
    """
 
94
 
 
95
    _lock_class = lockable_files.TransportLock
 
96
 
 
97
    def get_format_string(self):
 
98
        """See BzrDirFormat.get_format_string()."""
 
99
        return "Bazaar-NG branch, format 5\n"
 
100
 
 
101
    def get_branch_format(self):
 
102
        from bzrlib.plugins.weave_fmt.branch import BzrBranchFormat4
 
103
        return BzrBranchFormat4()
 
104
 
 
105
    def get_format_description(self):
 
106
        """See BzrDirFormat.get_format_description()."""
 
107
        return "All-in-one format 5"
 
108
 
 
109
    def get_converter(self, format=None):
 
110
        """See BzrDirFormat.get_converter()."""
 
111
        # there is one and only one upgrade path here.
 
112
        return ConvertBzrDir5To6()
 
113
 
 
114
    def _initialize_for_clone(self, url):
 
115
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
116
 
 
117
    def initialize_on_transport(self, transport, _cloning=False):
 
118
        """Format 5 dirs always have working tree, branch and repository.
 
119
 
 
120
        Except when they are being cloned.
 
121
        """
 
122
        from bzrlib.plugins.weave_fmt.branch import BzrBranchFormat4
 
123
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat5
 
124
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
125
        RepositoryFormat5().initialize(result, _internal=True)
 
126
        if not _cloning:
 
127
            branch = BzrBranchFormat4().initialize(result)
 
128
            result._init_workingtree()
 
129
        return result
 
130
 
 
131
    def network_name(self):
 
132
        return self.get_format_string()
 
133
 
 
134
    def _open(self, transport):
 
135
        """See BzrDirFormat._open."""
 
136
        return BzrDir5(transport, self)
 
137
 
 
138
    def __return_repository_format(self):
 
139
        """Circular import protection."""
 
140
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat5
 
141
        return RepositoryFormat5()
 
142
    repository_format = property(__return_repository_format)
 
143
 
 
144
 
 
145
class BzrDirFormat6(BzrDirFormatAllInOne):
 
146
    """Bzr control format 6.
 
147
 
 
148
    This format is a combined format for working tree, branch and repository.
 
149
    It has:
 
150
     - Format 2 working trees [always]
 
151
     - Format 4 branches [always]
 
152
     - Format 6 repositories [always]
 
153
    """
 
154
 
 
155
    _lock_class = lockable_files.TransportLock
 
156
 
 
157
    def get_format_string(self):
 
158
        """See BzrDirFormat.get_format_string()."""
 
159
        return "Bazaar-NG branch, format 6\n"
 
160
 
 
161
    def get_format_description(self):
 
162
        """See BzrDirFormat.get_format_description()."""
 
163
        return "All-in-one format 6"
 
164
 
 
165
    def get_branch_format(self):
 
166
        from bzrlib.plugins.weave_fmt.branch import BzrBranchFormat4
 
167
        return BzrBranchFormat4()
 
168
 
 
169
    def get_converter(self, format=None):
 
170
        """See BzrDirFormat.get_converter()."""
 
171
        # there is one and only one upgrade path here.
 
172
        return ConvertBzrDir6ToMeta()
 
173
 
 
174
    def _initialize_for_clone(self, url):
 
175
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
176
 
 
177
    def initialize_on_transport(self, transport, _cloning=False):
 
178
        """Format 6 dirs always have working tree, branch and repository.
 
179
 
 
180
        Except when they are being cloned.
 
181
        """
 
182
        from bzrlib.plugins.weave_fmt.branch import BzrBranchFormat4
 
183
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat6
 
184
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
185
        RepositoryFormat6().initialize(result, _internal=True)
 
186
        if not _cloning:
 
187
            branch = BzrBranchFormat4().initialize(result)
 
188
            result._init_workingtree()
 
189
        return result
 
190
 
 
191
    def network_name(self):
 
192
        return self.get_format_string()
 
193
 
 
194
    def _open(self, transport):
 
195
        """See BzrDirFormat._open."""
 
196
        return BzrDir6(transport, self)
 
197
 
 
198
    def __return_repository_format(self):
 
199
        """Circular import protection."""
 
200
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat6
 
201
        return RepositoryFormat6()
 
202
    repository_format = property(__return_repository_format)
 
203
 
 
204
 
 
205
class ConvertBzrDir4To5(Converter):
 
206
    """Converts format 4 bzr dirs to format 5."""
 
207
 
 
208
    def __init__(self):
 
209
        super(ConvertBzrDir4To5, self).__init__()
 
210
        self.converted_revs = set()
 
211
        self.absent_revisions = set()
 
212
        self.text_count = 0
 
213
        self.revisions = {}
 
214
 
 
215
    def convert(self, to_convert, pb):
 
216
        """See Converter.convert()."""
 
217
        self.bzrdir = to_convert
 
218
        if pb is not None:
 
219
            warnings.warn("pb parameter to convert() is deprecated")
 
220
        self.pb = ui.ui_factory.nested_progress_bar()
 
221
        try:
 
222
            ui.ui_factory.note('starting upgrade from format 4 to 5')
 
223
            if isinstance(self.bzrdir.transport, local.LocalTransport):
 
224
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
225
            self._convert_to_weaves()
 
226
            return BzrDir.open(self.bzrdir.user_url)
 
227
        finally:
 
228
            self.pb.finished()
 
229
 
 
230
    def _convert_to_weaves(self):
 
231
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
 
232
        try:
 
233
            # TODO permissions
 
234
            stat = self.bzrdir.transport.stat('weaves')
 
235
            if not S_ISDIR(stat.st_mode):
 
236
                self.bzrdir.transport.delete('weaves')
 
237
                self.bzrdir.transport.mkdir('weaves')
 
238
        except errors.NoSuchFile:
 
239
            self.bzrdir.transport.mkdir('weaves')
 
240
        # deliberately not a WeaveFile as we want to build it up slowly.
 
241
        self.inv_weave = weave.Weave('inventory')
 
242
        # holds in-memory weaves for all files
 
243
        self.text_weaves = {}
 
244
        self.bzrdir.transport.delete('branch-format')
 
245
        self.branch = self.bzrdir.open_branch()
 
246
        self._convert_working_inv()
 
247
        rev_history = self.branch.revision_history()
 
248
        # to_read is a stack holding the revisions we still need to process;
 
249
        # appending to it adds new highest-priority revisions
 
250
        self.known_revisions = set(rev_history)
 
251
        self.to_read = rev_history[-1:]
 
252
        while self.to_read:
 
253
            rev_id = self.to_read.pop()
 
254
            if (rev_id not in self.revisions
 
255
                and rev_id not in self.absent_revisions):
 
256
                self._load_one_rev(rev_id)
 
257
        self.pb.clear()
 
258
        to_import = self._make_order()
 
259
        for i, rev_id in enumerate(to_import):
 
260
            self.pb.update('converting revision', i, len(to_import))
 
261
            self._convert_one_rev(rev_id)
 
262
        self.pb.clear()
 
263
        self._write_all_weaves()
 
264
        self._write_all_revs()
 
265
        ui.ui_factory.note('upgraded to weaves:')
 
266
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
 
267
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
 
268
        ui.ui_factory.note('  %6d texts' % self.text_count)
 
269
        self._cleanup_spare_files_after_format4()
 
270
        self.branch._transport.put_bytes(
 
271
            'branch-format',
 
272
            BzrDirFormat5().get_format_string(),
 
273
            mode=self.bzrdir._get_file_mode())
 
274
 
 
275
    def _cleanup_spare_files_after_format4(self):
 
276
        # FIXME working tree upgrade foo.
 
277
        for n in 'merged-patches', 'pending-merged-patches':
 
278
            try:
 
279
                ## assert os.path.getsize(p) == 0
 
280
                self.bzrdir.transport.delete(n)
 
281
            except errors.NoSuchFile:
 
282
                pass
 
283
        self.bzrdir.transport.delete_tree('inventory-store')
 
284
        self.bzrdir.transport.delete_tree('text-store')
 
285
 
 
286
    def _convert_working_inv(self):
 
287
        inv = xml4.serializer_v4.read_inventory(
 
288
                self.branch._transport.get('inventory'))
 
289
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
290
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
291
            mode=self.bzrdir._get_file_mode())
 
292
 
 
293
    def _write_all_weaves(self):
 
294
        controlweaves = VersionedFileStore(self.bzrdir.transport, prefixed=False,
 
295
            versionedfile_class=weave.WeaveFile)
 
296
        weave_transport = self.bzrdir.transport.clone('weaves')
 
297
        weaves = VersionedFileStore(weave_transport, prefixed=False,
 
298
                versionedfile_class=weave.WeaveFile)
 
299
        transaction = WriteTransaction()
 
300
 
 
301
        try:
 
302
            i = 0
 
303
            for file_id, file_weave in self.text_weaves.items():
 
304
                self.pb.update('writing weave', i, len(self.text_weaves))
 
305
                weaves._put_weave(file_id, file_weave, transaction)
 
306
                i += 1
 
307
            self.pb.update('inventory', 0, 1)
 
308
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
309
            self.pb.update('inventory', 1, 1)
 
310
        finally:
 
311
            self.pb.clear()
 
312
 
 
313
    def _write_all_revs(self):
 
314
        """Write all revisions out in new form."""
 
315
        self.bzrdir.transport.delete_tree('revision-store')
 
316
        self.bzrdir.transport.mkdir('revision-store')
 
317
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
318
        # TODO permissions
 
319
        from bzrlib.xml5 import serializer_v5
 
320
        from bzrlib.plugins.weave_fmt.repository import RevisionTextStore
 
321
        revision_store = RevisionTextStore(revision_transport,
 
322
            serializer_v5, False, versionedfile.PrefixMapper(),
 
323
            lambda:True, lambda:True)
 
324
        try:
 
325
            for i, rev_id in enumerate(self.converted_revs):
 
326
                self.pb.update('write revision', i, len(self.converted_revs))
 
327
                text = serializer_v5.write_revision_to_string(
 
328
                    self.revisions[rev_id])
 
329
                key = (rev_id,)
 
330
                revision_store.add_lines(key, None, osutils.split_lines(text))
 
331
        finally:
 
332
            self.pb.clear()
 
333
 
 
334
    def _load_one_rev(self, rev_id):
 
335
        """Load a revision object into memory.
 
336
 
 
337
        Any parents not either loaded or abandoned get queued to be
 
338
        loaded."""
 
339
        self.pb.update('loading revision',
 
340
                       len(self.revisions),
 
341
                       len(self.known_revisions))
 
342
        if not self.branch.repository.has_revision(rev_id):
 
343
            self.pb.clear()
 
344
            ui.ui_factory.note('revision {%s} not present in branch; '
 
345
                         'will be converted as a ghost' %
 
346
                         rev_id)
 
347
            self.absent_revisions.add(rev_id)
 
348
        else:
 
349
            rev = self.branch.repository.get_revision(rev_id)
 
350
            for parent_id in rev.parent_ids:
 
351
                self.known_revisions.add(parent_id)
 
352
                self.to_read.append(parent_id)
 
353
            self.revisions[rev_id] = rev
 
354
 
 
355
    def _load_old_inventory(self, rev_id):
 
356
        f = self.branch.repository.inventory_store.get(rev_id)
 
357
        try:
 
358
            old_inv_xml = f.read()
 
359
        finally:
 
360
            f.close()
 
361
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
362
        inv.revision_id = rev_id
 
363
        rev = self.revisions[rev_id]
 
364
        return inv
 
365
 
 
366
    def _load_updated_inventory(self, rev_id):
 
367
        inv_xml = self.inv_weave.get_text(rev_id)
 
368
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
 
369
        return inv
 
370
 
 
371
    def _convert_one_rev(self, rev_id):
 
372
        """Convert revision and all referenced objects to new format."""
 
373
        rev = self.revisions[rev_id]
 
374
        inv = self._load_old_inventory(rev_id)
 
375
        present_parents = [p for p in rev.parent_ids
 
376
                           if p not in self.absent_revisions]
 
377
        self._convert_revision_contents(rev, inv, present_parents)
 
378
        self._store_new_inv(rev, inv, present_parents)
 
379
        self.converted_revs.add(rev_id)
 
380
 
 
381
    def _store_new_inv(self, rev, inv, present_parents):
 
382
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
383
        new_inv_sha1 = osutils.sha_string(new_inv_xml)
 
384
        self.inv_weave.add_lines(rev.revision_id,
 
385
                                 present_parents,
 
386
                                 new_inv_xml.splitlines(True))
 
387
        rev.inventory_sha1 = new_inv_sha1
 
388
 
 
389
    def _convert_revision_contents(self, rev, inv, present_parents):
 
390
        """Convert all the files within a revision.
 
391
 
 
392
        Also upgrade the inventory to refer to the text revision ids."""
 
393
        rev_id = rev.revision_id
 
394
        trace.mutter('converting texts of revision {%s}', rev_id)
 
395
        parent_invs = map(self._load_updated_inventory, present_parents)
 
396
        entries = inv.iter_entries()
 
397
        entries.next()
 
398
        for path, ie in entries:
 
399
            self._convert_file_version(rev, ie, parent_invs)
 
400
 
 
401
    def _convert_file_version(self, rev, ie, parent_invs):
 
402
        """Convert one version of one file.
 
403
 
 
404
        The file needs to be added into the weave if it is a merge
 
405
        of >=2 parents or if it's changed from its parent.
 
406
        """
 
407
        file_id = ie.file_id
 
408
        rev_id = rev.revision_id
 
409
        w = self.text_weaves.get(file_id)
 
410
        if w is None:
 
411
            w = weave.Weave(file_id)
 
412
            self.text_weaves[file_id] = w
 
413
        text_changed = False
 
414
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
415
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
416
        # XXX: Note that this is unordered - and this is tolerable because
 
417
        # the previous code was also unordered.
 
418
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
419
            in heads)
 
420
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
421
 
 
422
    def get_parent_map(self, revision_ids):
 
423
        """See graph.StackedParentsProvider.get_parent_map"""
 
424
        return dict((revision_id, self.revisions[revision_id])
 
425
                    for revision_id in revision_ids
 
426
                     if revision_id in self.revisions)
 
427
 
 
428
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
429
        # TODO: convert this logic, which is ~= snapshot to
 
430
        # a call to:. This needs the path figured out. rather than a work_tree
 
431
        # a v4 revision_tree can be given, or something that looks enough like
 
432
        # one to give the file content to the entry if it needs it.
 
433
        # and we need something that looks like a weave store for snapshot to
 
434
        # save against.
 
435
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
436
        if len(previous_revisions) == 1:
 
437
            previous_ie = previous_revisions.values()[0]
 
438
            if ie._unchanged(previous_ie):
 
439
                ie.revision = previous_ie.revision
 
440
                return
 
441
        if ie.has_text():
 
442
            f = self.branch.repository._text_store.get(ie.text_id)
 
443
            try:
 
444
                file_lines = f.readlines()
 
445
            finally:
 
446
                f.close()
 
447
            w.add_lines(rev_id, previous_revisions, file_lines)
 
448
            self.text_count += 1
 
449
        else:
 
450
            w.add_lines(rev_id, previous_revisions, [])
 
451
        ie.revision = rev_id
 
452
 
 
453
    def _make_order(self):
 
454
        """Return a suitable order for importing revisions.
 
455
 
 
456
        The order must be such that an revision is imported after all
 
457
        its (present) parents.
 
458
        """
 
459
        todo = set(self.revisions.keys())
 
460
        done = self.absent_revisions.copy()
 
461
        order = []
 
462
        while todo:
 
463
            # scan through looking for a revision whose parents
 
464
            # are all done
 
465
            for rev_id in sorted(list(todo)):
 
466
                rev = self.revisions[rev_id]
 
467
                parent_ids = set(rev.parent_ids)
 
468
                if parent_ids.issubset(done):
 
469
                    # can take this one now
 
470
                    order.append(rev_id)
 
471
                    todo.remove(rev_id)
 
472
                    done.add(rev_id)
 
473
        return order
 
474
 
 
475
 
 
476
 
 
477
 
 
478
class ConvertBzrDir5To6(Converter):
 
479
    """Converts format 5 bzr dirs to format 6."""
 
480
 
 
481
    def convert(self, to_convert, pb):
 
482
        """See Converter.convert()."""
 
483
        self.bzrdir = to_convert
 
484
        pb = ui.ui_factory.nested_progress_bar()
 
485
        try:
 
486
            ui.ui_factory.note('starting upgrade from format 5 to 6')
 
487
            self._convert_to_prefixed()
 
488
            return BzrDir.open(self.bzrdir.user_url)
 
489
        finally:
 
490
            pb.finished()
 
491
 
 
492
    def _convert_to_prefixed(self):
 
493
        from bzrlib.store import TransportStore
 
494
        self.bzrdir.transport.delete('branch-format')
 
495
        for store_name in ["weaves", "revision-store"]:
 
496
            ui.ui_factory.note("adding prefixes to %s" % store_name)
 
497
            store_transport = self.bzrdir.transport.clone(store_name)
 
498
            store = TransportStore(store_transport, prefixed=True)
 
499
            for urlfilename in store_transport.list_dir('.'):
 
500
                filename = urlutils.unescape(urlfilename)
 
501
                if (filename.endswith(".weave") or
 
502
                    filename.endswith(".gz") or
 
503
                    filename.endswith(".sig")):
 
504
                    file_id, suffix = os.path.splitext(filename)
 
505
                else:
 
506
                    file_id = filename
 
507
                    suffix = ''
 
508
                new_name = store._mapper.map((file_id,)) + suffix
 
509
                # FIXME keep track of the dirs made RBC 20060121
 
510
                try:
 
511
                    store_transport.move(filename, new_name)
 
512
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
513
                    store_transport.mkdir(osutils.dirname(new_name))
 
514
                    store_transport.move(filename, new_name)
 
515
        self.bzrdir.transport.put_bytes(
 
516
            'branch-format',
 
517
            BzrDirFormat6().get_format_string(),
 
518
            mode=self.bzrdir._get_file_mode())
 
519
 
 
520
 
 
521
class ConvertBzrDir6ToMeta(Converter):
 
522
    """Converts format 6 bzr dirs to metadirs."""
 
523
 
 
524
    def convert(self, to_convert, pb):
 
525
        """See Converter.convert()."""
 
526
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat7
 
527
        from bzrlib.branch import BzrBranchFormat5
 
528
        self.bzrdir = to_convert
 
529
        self.pb = ui.ui_factory.nested_progress_bar()
 
530
        self.count = 0
 
531
        self.total = 20 # the steps we know about
 
532
        self.garbage_inventories = []
 
533
        self.dir_mode = self.bzrdir._get_dir_mode()
 
534
        self.file_mode = self.bzrdir._get_file_mode()
 
535
 
 
536
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
 
537
        self.bzrdir.transport.put_bytes(
 
538
                'branch-format',
 
539
                "Converting to format 6",
 
540
                mode=self.file_mode)
 
541
        # its faster to move specific files around than to open and use the apis...
 
542
        # first off, nuke ancestry.weave, it was never used.
 
543
        try:
 
544
            self.step('Removing ancestry.weave')
 
545
            self.bzrdir.transport.delete('ancestry.weave')
 
546
        except errors.NoSuchFile:
 
547
            pass
 
548
        # find out whats there
 
549
        self.step('Finding branch files')
 
550
        last_revision = self.bzrdir.open_branch().last_revision()
 
551
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
552
        for name in bzrcontents:
 
553
            if name.startswith('basis-inventory.'):
 
554
                self.garbage_inventories.append(name)
 
555
        # create new directories for repository, working tree and branch
 
556
        repository_names = [('inventory.weave', True),
 
557
                            ('revision-store', True),
 
558
                            ('weaves', True)]
 
559
        self.step('Upgrading repository  ')
 
560
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
561
        self.make_lock('repository')
 
562
        # we hard code the formats here because we are converting into
 
563
        # the meta format. The meta format upgrader can take this to a
 
564
        # future format within each component.
 
565
        self.put_format('repository', RepositoryFormat7())
 
566
        for entry in repository_names:
 
567
            self.move_entry('repository', entry)
 
568
 
 
569
        self.step('Upgrading branch      ')
 
570
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
571
        self.make_lock('branch')
 
572
        self.put_format('branch', BzrBranchFormat5())
 
573
        branch_files = [('revision-history', True),
 
574
                        ('branch-name', True),
 
575
                        ('parent', False)]
 
576
        for entry in branch_files:
 
577
            self.move_entry('branch', entry)
 
578
 
 
579
        checkout_files = [('pending-merges', True),
 
580
                          ('inventory', True),
 
581
                          ('stat-cache', False)]
 
582
        # If a mandatory checkout file is not present, the branch does not have
 
583
        # a functional checkout. Do not create a checkout in the converted
 
584
        # branch.
 
585
        for name, mandatory in checkout_files:
 
586
            if mandatory and name not in bzrcontents:
 
587
                has_checkout = False
 
588
                break
 
589
        else:
 
590
            has_checkout = True
 
591
        if not has_checkout:
 
592
            ui.ui_factory.note('No working tree.')
 
593
            # If some checkout files are there, we may as well get rid of them.
 
594
            for name, mandatory in checkout_files:
 
595
                if name in bzrcontents:
 
596
                    self.bzrdir.transport.delete(name)
 
597
        else:
 
598
            from bzrlib.workingtree import WorkingTreeFormat3
 
599
            self.step('Upgrading working tree')
 
600
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
601
            self.make_lock('checkout')
 
602
            self.put_format(
 
603
                'checkout', WorkingTreeFormat3())
 
604
            self.bzrdir.transport.delete_multi(
 
605
                self.garbage_inventories, self.pb)
 
606
            for entry in checkout_files:
 
607
                self.move_entry('checkout', entry)
 
608
            if last_revision is not None:
 
609
                self.bzrdir.transport.put_bytes(
 
610
                    'checkout/last-revision', last_revision)
 
611
        self.bzrdir.transport.put_bytes(
 
612
            'branch-format',
 
613
            BzrDirMetaFormat1().get_format_string(),
 
614
            mode=self.file_mode)
 
615
        self.pb.finished()
 
616
        return BzrDir.open(self.bzrdir.user_url)
 
617
 
 
618
    def make_lock(self, name):
 
619
        """Make a lock for the new control dir name."""
 
620
        self.step('Make %s lock' % name)
 
621
        ld = lockdir.LockDir(self.bzrdir.transport,
 
622
                             '%s/lock' % name,
 
623
                             file_modebits=self.file_mode,
 
624
                             dir_modebits=self.dir_mode)
 
625
        ld.create()
 
626
 
 
627
    def move_entry(self, new_dir, entry):
 
628
        """Move then entry name into new_dir."""
 
629
        name = entry[0]
 
630
        mandatory = entry[1]
 
631
        self.step('Moving %s' % name)
 
632
        try:
 
633
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
634
        except errors.NoSuchFile:
 
635
            if mandatory:
 
636
                raise
 
637
 
 
638
    def put_format(self, dirname, format):
 
639
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
640
            format.get_format_string(),
 
641
            self.file_mode)
 
642
 
 
643
 
 
644
class BzrDirFormat4(BzrDirFormat):
 
645
    """Bzr dir format 4.
 
646
 
 
647
    This format is a combined format for working tree, branch and repository.
 
648
    It has:
 
649
     - Format 1 working trees [always]
 
650
     - Format 4 branches [always]
 
651
     - Format 4 repositories [always]
 
652
 
 
653
    This format is deprecated: it indexes texts using a text it which is
 
654
    removed in format 5; write support for this format has been removed.
 
655
    """
 
656
 
 
657
    _lock_class = lockable_files.TransportLock
 
658
 
 
659
    def get_format_string(self):
 
660
        """See BzrDirFormat.get_format_string()."""
 
661
        return "Bazaar-NG branch, format 0.0.4\n"
 
662
 
 
663
    def get_format_description(self):
 
664
        """See BzrDirFormat.get_format_description()."""
 
665
        return "All-in-one format 4"
 
666
 
 
667
    def get_converter(self, format=None):
 
668
        """See BzrDirFormat.get_converter()."""
 
669
        # there is one and only one upgrade path here.
 
670
        return ConvertBzrDir4To5()
 
671
 
 
672
    def initialize_on_transport(self, transport):
 
673
        """Format 4 branches cannot be created."""
 
674
        raise errors.UninitializableFormat(self)
 
675
 
 
676
    def is_supported(self):
 
677
        """Format 4 is not supported.
 
678
 
 
679
        It is not supported because the model changed from 4 to 5 and the
 
680
        conversion logic is expensive - so doing it on the fly was not
 
681
        feasible.
 
682
        """
 
683
        return False
 
684
 
 
685
    def network_name(self):
 
686
        return self.get_format_string()
 
687
 
 
688
    def _open(self, transport):
 
689
        """See BzrDirFormat._open."""
 
690
        return BzrDir4(transport, self)
 
691
 
 
692
    def __return_repository_format(self):
 
693
        """Circular import protection."""
 
694
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat4
 
695
        return RepositoryFormat4()
 
696
    repository_format = property(__return_repository_format)
 
697
 
 
698
 
 
699
class BzrDirPreSplitOut(BzrDir):
 
700
    """A common class for the all-in-one formats."""
 
701
 
 
702
    def __init__(self, _transport, _format):
 
703
        """See BzrDir.__init__."""
 
704
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
705
        self._control_files = lockable_files.LockableFiles(
 
706
                                            self.get_branch_transport(None),
 
707
                                            self._format._lock_file_name,
 
708
                                            self._format._lock_class)
 
709
 
 
710
    def break_lock(self):
 
711
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
712
        raise NotImplementedError(self.break_lock)
 
713
 
 
714
    def cloning_metadir(self, require_stacking=False):
 
715
        """Produce a metadir suitable for cloning with."""
 
716
        if require_stacking:
 
717
            return format_registry.make_bzrdir('1.6')
 
718
        return self._format.__class__()
 
719
 
 
720
    def clone(self, url, revision_id=None, force_new_repo=False,
 
721
              preserve_stacking=False):
 
722
        """See BzrDir.clone().
 
723
 
 
724
        force_new_repo has no effect, since this family of formats always
 
725
        require a new repository.
 
726
        preserve_stacking has no effect, since no source branch using this
 
727
        family of formats can be stacked, so there is no stacking to preserve.
 
728
        """
 
729
        self._make_tail(url)
 
730
        result = self._format._initialize_for_clone(url)
 
731
        self.open_repository().clone(result, revision_id=revision_id)
 
732
        from_branch = self.open_branch()
 
733
        from_branch.clone(result, revision_id=revision_id)
 
734
        try:
 
735
            tree = self.open_workingtree()
 
736
        except errors.NotLocalUrl:
 
737
            # make a new one, this format always has to have one.
 
738
            result._init_workingtree()
 
739
        else:
 
740
            tree.clone(result)
 
741
        return result
 
742
 
 
743
    def create_branch(self, name=None, repository=None):
 
744
        """See BzrDir.create_branch."""
 
745
        if repository is not None:
 
746
            raise NotImplementedError(
 
747
                "create_branch(repository=<not None>) on %r" % (self,))
 
748
        return self._format.get_branch_format().initialize(self, name=name)
 
749
 
 
750
    def destroy_branch(self, name=None):
 
751
        """See BzrDir.destroy_branch."""
 
752
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
753
 
 
754
    def create_repository(self, shared=False):
 
755
        """See BzrDir.create_repository."""
 
756
        if shared:
 
757
            raise errors.IncompatibleFormat('shared repository', self._format)
 
758
        return self.open_repository()
 
759
 
 
760
    def destroy_repository(self):
 
761
        """See BzrDir.destroy_repository."""
 
762
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
763
 
 
764
    def create_workingtree(self, revision_id=None, from_branch=None,
 
765
                           accelerator_tree=None, hardlink=False):
 
766
        """See BzrDir.create_workingtree."""
 
767
        # The workingtree is sometimes created when the bzrdir is created,
 
768
        # but not when cloning.
 
769
 
 
770
        # this looks buggy but is not -really-
 
771
        # because this format creates the workingtree when the bzrdir is
 
772
        # created
 
773
        # clone and sprout will have set the revision_id
 
774
        # and that will have set it for us, its only
 
775
        # specific uses of create_workingtree in isolation
 
776
        # that can do wonky stuff here, and that only
 
777
        # happens for creating checkouts, which cannot be
 
778
        # done on this format anyway. So - acceptable wart.
 
779
        if hardlink:
 
780
            warning("can't support hardlinked working trees in %r"
 
781
                % (self,))
 
782
        try:
 
783
            result = self.open_workingtree(recommend_upgrade=False)
 
784
        except errors.NoSuchFile:
 
785
            result = self._init_workingtree()
 
786
        if revision_id is not None:
 
787
            if revision_id == _mod_revision.NULL_REVISION:
 
788
                result.set_parent_ids([])
 
789
            else:
 
790
                result.set_parent_ids([revision_id])
 
791
        return result
 
792
 
 
793
    def _init_workingtree(self):
 
794
        from bzrlib.plugins.weave_fmt.workingtree import WorkingTreeFormat2
 
795
        try:
 
796
            return WorkingTreeFormat2().initialize(self)
 
797
        except errors.NotLocalUrl:
 
798
            # Even though we can't access the working tree, we need to
 
799
            # create its control files.
 
800
            return WorkingTreeFormat2()._stub_initialize_on_transport(
 
801
                self.transport, self._control_files._file_mode)
 
802
 
 
803
    def destroy_workingtree(self):
 
804
        """See BzrDir.destroy_workingtree."""
 
805
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
806
 
 
807
    def destroy_workingtree_metadata(self):
 
808
        """See BzrDir.destroy_workingtree_metadata."""
 
809
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
 
810
                                          self)
 
811
 
 
812
    def get_branch_transport(self, branch_format, name=None):
 
813
        """See BzrDir.get_branch_transport()."""
 
814
        if name is not None:
 
815
            raise errors.NoColocatedBranchSupport(self)
 
816
        if branch_format is None:
 
817
            return self.transport
 
818
        try:
 
819
            branch_format.get_format_string()
 
820
        except NotImplementedError:
 
821
            return self.transport
 
822
        raise errors.IncompatibleFormat(branch_format, self._format)
 
823
 
 
824
    def get_repository_transport(self, repository_format):
 
825
        """See BzrDir.get_repository_transport()."""
 
826
        if repository_format is None:
 
827
            return self.transport
 
828
        try:
 
829
            repository_format.get_format_string()
 
830
        except NotImplementedError:
 
831
            return self.transport
 
832
        raise errors.IncompatibleFormat(repository_format, self._format)
 
833
 
 
834
    def get_workingtree_transport(self, workingtree_format):
 
835
        """See BzrDir.get_workingtree_transport()."""
 
836
        if workingtree_format is None:
 
837
            return self.transport
 
838
        try:
 
839
            workingtree_format.get_format_string()
 
840
        except NotImplementedError:
 
841
            return self.transport
 
842
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
843
 
 
844
    def needs_format_conversion(self, format=None):
 
845
        """See BzrDir.needs_format_conversion()."""
 
846
        # if the format is not the same as the system default,
 
847
        # an upgrade is needed.
 
848
        if format is None:
 
849
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
850
                % 'needs_format_conversion(format=None)')
 
851
            format = BzrDirFormat.get_default_format()
 
852
        return not isinstance(self._format, format.__class__)
 
853
 
 
854
    def open_branch(self, name=None, unsupported=False,
 
855
                    ignore_fallbacks=False):
 
856
        """See BzrDir.open_branch."""
 
857
        from bzrlib.plugins.weave_fmt.branch import BzrBranchFormat4
 
858
        format = BzrBranchFormat4()
 
859
        self._check_supported(format, unsupported)
 
860
        return format.open(self, name, _found=True)
 
861
 
 
862
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
863
               possible_transports=None, accelerator_tree=None,
 
864
               hardlink=False, stacked=False, create_tree_if_local=True,
 
865
               source_branch=None):
 
866
        """See BzrDir.sprout()."""
 
867
        if source_branch is not None:
 
868
            my_branch = self.open_branch()
 
869
            if source_branch.base != my_branch.base:
 
870
                raise AssertionError(
 
871
                    "source branch %r is not within %r with branch %r" %
 
872
                    (source_branch, self, my_branch))
 
873
        if stacked:
 
874
            raise errors.UnstackableBranchFormat(
 
875
                self._format, self.root_transport.base)
 
876
        if not create_tree_if_local:
 
877
            raise errors.MustHaveWorkingTree(
 
878
                self._format, self.root_transport.base)
 
879
        from bzrlib.plugins.weave_fmt.workingtree import WorkingTreeFormat2
 
880
        self._make_tail(url)
 
881
        result = self._format._initialize_for_clone(url)
 
882
        try:
 
883
            self.open_repository().clone(result, revision_id=revision_id)
 
884
        except errors.NoRepositoryPresent:
 
885
            pass
 
886
        try:
 
887
            self.open_branch().sprout(result, revision_id=revision_id)
 
888
        except errors.NotBranchError:
 
889
            pass
 
890
 
 
891
        # we always want a working tree
 
892
        WorkingTreeFormat2().initialize(result,
 
893
                                        accelerator_tree=accelerator_tree,
 
894
                                        hardlink=hardlink)
 
895
        return result
 
896
 
 
897
 
 
898
class BzrDir4(BzrDirPreSplitOut):
 
899
    """A .bzr version 4 control object.
 
900
 
 
901
    This is a deprecated format and may be removed after sept 2006.
 
902
    """
 
903
 
 
904
    def create_repository(self, shared=False):
 
905
        """See BzrDir.create_repository."""
 
906
        return self._format.repository_format.initialize(self, shared)
 
907
 
 
908
    def needs_format_conversion(self, format=None):
 
909
        """Format 4 dirs are always in need of conversion."""
 
910
        if format is None:
 
911
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
912
                % 'needs_format_conversion(format=None)')
 
913
        return True
 
914
 
 
915
    def open_repository(self):
 
916
        """See BzrDir.open_repository."""
 
917
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat4
 
918
        return RepositoryFormat4().open(self, _found=True)
 
919
 
 
920
 
 
921
 
 
922
 
 
923
class BzrDir5(BzrDirPreSplitOut):
 
924
    """A .bzr version 5 control object.
 
925
 
 
926
    This is a deprecated format and may be removed after sept 2006.
 
927
    """
 
928
 
 
929
    def has_workingtree(self):
 
930
        """See BzrDir.has_workingtree."""
 
931
        return True
 
932
    
 
933
    def open_repository(self):
 
934
        """See BzrDir.open_repository."""
 
935
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat5
 
936
        return RepositoryFormat5().open(self, _found=True)
 
937
 
 
938
    def open_workingtree(self, _unsupported=False,
 
939
            recommend_upgrade=True):
 
940
        """See BzrDir.create_workingtree."""
 
941
        from bzrlib.plugins.weave_fmt.workingtree import WorkingTreeFormat2
 
942
        wt_format = WorkingTreeFormat2()
 
943
        # we don't warn here about upgrades; that ought to be handled for the
 
944
        # bzrdir as a whole
 
945
        return wt_format.open(self, _found=True)
 
946
 
 
947
 
 
948
class BzrDir6(BzrDirPreSplitOut):
 
949
    """A .bzr version 6 control object.
 
950
 
 
951
    This is a deprecated format and may be removed after sept 2006.
 
952
    """
 
953
 
 
954
    def has_workingtree(self):
 
955
        """See BzrDir.has_workingtree."""
 
956
        return True
 
957
 
 
958
    def open_repository(self):
 
959
        """See BzrDir.open_repository."""
 
960
        from bzrlib.plugins.weave_fmt.repository import RepositoryFormat6
 
961
        return RepositoryFormat6().open(self, _found=True)
 
962
 
 
963
    def open_workingtree(self, _unsupported=False,
 
964
        recommend_upgrade=True):
 
965
        """See BzrDir.create_workingtree."""
 
966
        # we don't warn here about upgrades; that ought to be handled for the
 
967
        # bzrdir as a whole
 
968
        from bzrlib.plugins.weave_fmt.workingtree import WorkingTreeFormat2
 
969
        return WorkingTreeFormat2().open(self, _found=True)