~bzr-pqm/bzr/bzr.dev

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