/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 breezy/plugins/weave_fmt/bzrdir.py

  • Committer: John Arbash Meinel
  • Date: 2006-04-25 15:05:42 UTC
  • mfrom: (1185.85.85 bzr-encoding)
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060425150542-c7b518dca9928691
[merge] the old bzr-encoding changes, reparenting them on bzr.dev

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