/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: Martin
  • Date: 2019-06-16 19:53:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7349.
  • Revision ID: gzlist@googlemail.com-20190616195327-awvhgbjo9g6mkt57
Relocate the bzr log file out of $HOME

Now under $XDG_CACHE_HOME on nix and %LOCALAPPDATA% on windows.

Setting $BRZ_HOME will override the cache location, to simplify test
isolation, and $BRZ_LOG is still the final word.

Drive-by fix various docs around bzr/brz spelling.

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