/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Ian Clatworthy
  • Date: 2008-07-31 08:24:16 UTC
  • mto: (3586.1.12 views-ui)
  • mto: This revision was merged to the branch mainline in revision 4030.
  • Revision ID: ian.clatworthy@canonical.com-20080731082416-xwuwrydm935pmp85
fix storage after deleting the last view

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
 
18
 
 
19
At format 7 this was split out into Branch, Repository and Checkout control
 
20
directories.
 
21
 
 
22
Note: This module has a lot of ``open`` functions/methods that return
 
23
references to in-memory objects. As a rule, there are no matching ``close``
 
24
methods. To free any associated resources, simply stop referencing the
 
25
objects returned.
 
26
"""
 
27
 
 
28
# TODO: Move old formats into a plugin to make this file smaller.
 
29
 
 
30
from cStringIO import StringIO
 
31
import os
 
32
import sys
 
33
 
 
34
from bzrlib.lazy_import import lazy_import
 
35
lazy_import(globals(), """
 
36
from stat import S_ISDIR
 
37
import textwrap
 
38
from warnings import warn
 
39
 
 
40
import bzrlib
 
41
from bzrlib import (
 
42
    config,
 
43
    errors,
 
44
    graph,
 
45
    lockable_files,
 
46
    lockdir,
 
47
    osutils,
 
48
    registry,
 
49
    remote,
 
50
    revision as _mod_revision,
 
51
    symbol_versioning,
 
52
    ui,
 
53
    urlutils,
 
54
    versionedfile,
 
55
    win32utils,
 
56
    workingtree,
 
57
    workingtree_4,
 
58
    workingtree_5,
 
59
    xml4,
 
60
    xml5,
 
61
    )
 
62
from bzrlib.osutils import (
 
63
    sha_strings,
 
64
    sha_string,
 
65
    )
 
66
from bzrlib.repository import Repository
 
67
from bzrlib.smart.client import _SmartClient
 
68
from bzrlib.smart import protocol
 
69
from bzrlib.store.versioned import WeaveStore
 
70
from bzrlib.transactions import WriteTransaction
 
71
from bzrlib.transport import (
 
72
    do_catching_redirections,
 
73
    get_transport,
 
74
    )
 
75
from bzrlib.weave import Weave
 
76
""")
 
77
 
 
78
from bzrlib.trace import (
 
79
    mutter,
 
80
    note,
 
81
    )
 
82
from bzrlib.transport.local import LocalTransport
 
83
from bzrlib.symbol_versioning import (
 
84
    deprecated_function,
 
85
    deprecated_method,
 
86
    )
 
87
 
 
88
 
 
89
class BzrDir(object):
 
90
    """A .bzr control diretory.
 
91
    
 
92
    BzrDir instances let you create or open any of the things that can be
 
93
    found within .bzr - checkouts, branches and repositories.
 
94
    
 
95
    :ivar transport:
 
96
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
97
    :ivar root_transport:
 
98
        a transport connected to the directory this bzr was opened from
 
99
        (i.e. the parent directory holding the .bzr directory).
 
100
 
 
101
    Everything in the bzrdir should have the same file permissions.
 
102
    """
 
103
 
 
104
    def break_lock(self):
 
105
        """Invoke break_lock on the first object in the bzrdir.
 
106
 
 
107
        If there is a tree, the tree is opened and break_lock() called.
 
108
        Otherwise, branch is tried, and finally repository.
 
109
        """
 
110
        # XXX: This seems more like a UI function than something that really
 
111
        # belongs in this class.
 
112
        try:
 
113
            thing_to_unlock = self.open_workingtree()
 
114
        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
115
            try:
 
116
                thing_to_unlock = self.open_branch()
 
117
            except errors.NotBranchError:
 
118
                try:
 
119
                    thing_to_unlock = self.open_repository()
 
120
                except errors.NoRepositoryPresent:
 
121
                    return
 
122
        thing_to_unlock.break_lock()
 
123
 
 
124
    def can_convert_format(self):
 
125
        """Return true if this bzrdir is one whose format we can convert from."""
 
126
        return True
 
127
 
 
128
    def check_conversion_target(self, target_format):
 
129
        target_repo_format = target_format.repository_format
 
130
        source_repo_format = self._format.repository_format
 
131
        source_repo_format.check_conversion_target(target_repo_format)
 
132
 
 
133
    @staticmethod
 
134
    def _check_supported(format, allow_unsupported,
 
135
        recommend_upgrade=True,
 
136
        basedir=None):
 
137
        """Give an error or warning on old formats.
 
138
 
 
139
        :param format: may be any kind of format - workingtree, branch, 
 
140
        or repository.
 
141
 
 
142
        :param allow_unsupported: If true, allow opening 
 
143
        formats that are strongly deprecated, and which may 
 
144
        have limited functionality.
 
145
 
 
146
        :param recommend_upgrade: If true (default), warn
 
147
        the user through the ui object that they may wish
 
148
        to upgrade the object.
 
149
        """
 
150
        # TODO: perhaps move this into a base Format class; it's not BzrDir
 
151
        # specific. mbp 20070323
 
152
        if not allow_unsupported and not format.is_supported():
 
153
            # see open_downlevel to open legacy branches.
 
154
            raise errors.UnsupportedFormatError(format=format)
 
155
        if recommend_upgrade \
 
156
            and getattr(format, 'upgrade_recommended', False):
 
157
            ui.ui_factory.recommend_upgrade(
 
158
                format.get_format_description(),
 
159
                basedir)
 
160
 
 
161
    def clone(self, url, revision_id=None, force_new_repo=False,
 
162
              preserve_stacking=False):
 
163
        """Clone this bzrdir and its contents to url verbatim.
 
164
 
 
165
        :param url: The url create the clone at.  If url's last component does
 
166
            not exist, it will be created.
 
167
        :param revision_id: The tip revision-id to use for any branch or
 
168
            working tree.  If not None, then the clone operation may tune
 
169
            itself to download less data.
 
170
        :param force_new_repo: Do not use a shared repository for the target
 
171
                               even if one is available.
 
172
        :param preserve_stacking: When cloning a stacked branch, stack the
 
173
            new branch on top of the other branch's stacked-on branch.
 
174
        """
 
175
        return self.clone_on_transport(get_transport(url),
 
176
                                       revision_id=revision_id,
 
177
                                       force_new_repo=force_new_repo,
 
178
                                       preserve_stacking=preserve_stacking)
 
179
 
 
180
    def clone_on_transport(self, transport, revision_id=None,
 
181
                           force_new_repo=False, preserve_stacking=False):
 
182
        """Clone this bzrdir and its contents to transport verbatim.
 
183
 
 
184
        :param transport: The transport for the location to produce the clone
 
185
            at.  If the target directory does not exist, it will be created.
 
186
        :param revision_id: The tip revision-id to use for any branch or
 
187
            working tree.  If not None, then the clone operation may tune
 
188
            itself to download less data.
 
189
        :param force_new_repo: Do not use a shared repository for the target,
 
190
                               even if one is available.
 
191
        :param preserve_stacking: When cloning a stacked branch, stack the
 
192
            new branch on top of the other branch's stacked-on branch.
 
193
        """
 
194
        transport.ensure_base()
 
195
        result = self.cloning_metadir().initialize_on_transport(transport)
 
196
        repository_policy = None
 
197
        stack_on = None
 
198
        try:
 
199
            local_repo = self.find_repository()
 
200
        except errors.NoRepositoryPresent:
 
201
            local_repo = None
 
202
        try:
 
203
            local_branch = self.open_branch()
 
204
        except errors.NotBranchError:
 
205
            local_branch = None
 
206
        else:
 
207
            # enable fallbacks when branch is not a branch reference
 
208
            if local_branch.repository.has_same_location(local_repo):
 
209
                local_repo = local_branch.repository
 
210
            if preserve_stacking:
 
211
                try:
 
212
                    stack_on = local_branch.get_stacked_on_url()
 
213
                except (errors.UnstackableBranchFormat,
 
214
                        errors.UnstackableRepositoryFormat,
 
215
                        errors.NotStacked):
 
216
                    pass
 
217
 
 
218
        if local_repo:
 
219
            # may need to copy content in
 
220
            repository_policy = result.determine_repository_policy(
 
221
                force_new_repo, stack_on, self.root_transport.base)
 
222
            make_working_trees = local_repo.make_working_trees()
 
223
            result_repo = repository_policy.acquire_repository(
 
224
                make_working_trees, local_repo.is_shared())
 
225
            result_repo.fetch(local_repo, revision_id=revision_id)
 
226
        else:
 
227
            result_repo = None
 
228
        # 1 if there is a branch present
 
229
        #   make sure its content is available in the target repository
 
230
        #   clone it.
 
231
        if local_branch is not None:
 
232
            result_branch = local_branch.clone(result, revision_id=revision_id)
 
233
            if repository_policy is not None:
 
234
                repository_policy.configure_branch(result_branch)
 
235
        if result_repo is None or result_repo.make_working_trees():
 
236
            try:
 
237
                self.open_workingtree().clone(result)
 
238
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
239
                pass
 
240
        return result
 
241
 
 
242
    # TODO: This should be given a Transport, and should chdir up; otherwise
 
243
    # this will open a new connection.
 
244
    def _make_tail(self, url):
 
245
        t = get_transport(url)
 
246
        t.ensure_base()
 
247
 
 
248
    @classmethod
 
249
    def create(cls, base, format=None, possible_transports=None):
 
250
        """Create a new BzrDir at the url 'base'.
 
251
        
 
252
        :param format: If supplied, the format of branch to create.  If not
 
253
            supplied, the default is used.
 
254
        :param possible_transports: If supplied, a list of transports that 
 
255
            can be reused to share a remote connection.
 
256
        """
 
257
        if cls is not BzrDir:
 
258
            raise AssertionError("BzrDir.create always creates the default"
 
259
                " format, not one of %r" % cls)
 
260
        t = get_transport(base, possible_transports)
 
261
        t.ensure_base()
 
262
        if format is None:
 
263
            format = BzrDirFormat.get_default_format()
 
264
        return format.initialize_on_transport(t)
 
265
 
 
266
    @staticmethod
 
267
    def find_bzrdirs(transport, evaluate=None, list_current=None):
 
268
        """Find bzrdirs recursively from current location.
 
269
 
 
270
        This is intended primarily as a building block for more sophisticated
 
271
        functionality, like finding trees under a directory, or finding
 
272
        branches that use a given repository.
 
273
        :param evaluate: An optional callable that yields recurse, value,
 
274
            where recurse controls whether this bzrdir is recursed into
 
275
            and value is the value to yield.  By default, all bzrdirs
 
276
            are recursed into, and the return value is the bzrdir.
 
277
        :param list_current: if supplied, use this function to list the current
 
278
            directory, instead of Transport.list_dir
 
279
        :return: a generator of found bzrdirs, or whatever evaluate returns.
 
280
        """
 
281
        if list_current is None:
 
282
            def list_current(transport):
 
283
                return transport.list_dir('')
 
284
        if evaluate is None:
 
285
            def evaluate(bzrdir):
 
286
                return True, bzrdir
 
287
 
 
288
        pending = [transport]
 
289
        while len(pending) > 0:
 
290
            current_transport = pending.pop()
 
291
            recurse = True
 
292
            try:
 
293
                bzrdir = BzrDir.open_from_transport(current_transport)
 
294
            except errors.NotBranchError:
 
295
                pass
 
296
            else:
 
297
                recurse, value = evaluate(bzrdir)
 
298
                yield value
 
299
            try:
 
300
                subdirs = list_current(current_transport)
 
301
            except errors.NoSuchFile:
 
302
                continue
 
303
            if recurse:
 
304
                for subdir in sorted(subdirs, reverse=True):
 
305
                    pending.append(current_transport.clone(subdir))
 
306
 
 
307
    @staticmethod
 
308
    def find_branches(transport):
 
309
        """Find all branches under a transport.
 
310
 
 
311
        This will find all branches below the transport, including branches
 
312
        inside other branches.  Where possible, it will use
 
313
        Repository.find_branches.
 
314
 
 
315
        To list all the branches that use a particular Repository, see
 
316
        Repository.find_branches
 
317
        """
 
318
        def evaluate(bzrdir):
 
319
            try:
 
320
                repository = bzrdir.open_repository()
 
321
            except errors.NoRepositoryPresent:
 
322
                pass
 
323
            else:
 
324
                return False, (None, repository)
 
325
            try:
 
326
                branch = bzrdir.open_branch()
 
327
            except errors.NotBranchError:
 
328
                return True, (None, None)
 
329
            else:
 
330
                return True, (branch, None)
 
331
        branches = []
 
332
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
 
333
            if repo is not None:
 
334
                branches.extend(repo.find_branches())
 
335
            if branch is not None:
 
336
                branches.append(branch)
 
337
        return branches
 
338
 
 
339
    def destroy_repository(self):
 
340
        """Destroy the repository in this BzrDir"""
 
341
        raise NotImplementedError(self.destroy_repository)
 
342
 
 
343
    def create_branch(self):
 
344
        """Create a branch in this BzrDir.
 
345
 
 
346
        The bzrdir's format will control what branch format is created.
 
347
        For more control see BranchFormatXX.create(a_bzrdir).
 
348
        """
 
349
        raise NotImplementedError(self.create_branch)
 
350
 
 
351
    def destroy_branch(self):
 
352
        """Destroy the branch in this BzrDir"""
 
353
        raise NotImplementedError(self.destroy_branch)
 
354
 
 
355
    @staticmethod
 
356
    def create_branch_and_repo(base, force_new_repo=False, format=None):
 
357
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
358
 
 
359
        This will use the current default BzrDirFormat unless one is
 
360
        specified, and use whatever 
 
361
        repository format that that uses via bzrdir.create_branch and
 
362
        create_repository. If a shared repository is available that is used
 
363
        preferentially.
 
364
 
 
365
        The created Branch object is returned.
 
366
 
 
367
        :param base: The URL to create the branch at.
 
368
        :param force_new_repo: If True a new repository is always created.
 
369
        :param format: If supplied, the format of branch to create.  If not
 
370
            supplied, the default is used.
 
371
        """
 
372
        bzrdir = BzrDir.create(base, format)
 
373
        bzrdir._find_or_create_repository(force_new_repo)
 
374
        return bzrdir.create_branch()
 
375
 
 
376
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
 
377
                                    stack_on_pwd=None, require_stacking=False):
 
378
        """Return an object representing a policy to use.
 
379
 
 
380
        This controls whether a new repository is created, or a shared
 
381
        repository used instead.
 
382
 
 
383
        If stack_on is supplied, will not seek a containing shared repo.
 
384
 
 
385
        :param force_new_repo: If True, require a new repository to be created.
 
386
        :param stack_on: If supplied, the location to stack on.  If not
 
387
            supplied, a default_stack_on location may be used.
 
388
        :param stack_on_pwd: If stack_on is relative, the location it is
 
389
            relative to.
 
390
        """
 
391
        def repository_policy(found_bzrdir):
 
392
            stack_on = None
 
393
            stack_on_pwd = None
 
394
            config = found_bzrdir.get_config()
 
395
            stop = False
 
396
            if config is not None:
 
397
                stack_on = config.get_default_stack_on()
 
398
                if stack_on is not None:
 
399
                    stack_on_pwd = found_bzrdir.root_transport.base
 
400
                    stop = True
 
401
                    note('Using default stacking branch %s at %s', stack_on,
 
402
                         stack_on_pwd)
 
403
            # does it have a repository ?
 
404
            try:
 
405
                repository = found_bzrdir.open_repository()
 
406
            except errors.NoRepositoryPresent:
 
407
                repository = None
 
408
            else:
 
409
                if ((found_bzrdir.root_transport.base !=
 
410
                     self.root_transport.base) and not repository.is_shared()):
 
411
                    repository = None
 
412
                else:
 
413
                    stop = True
 
414
            if not stop:
 
415
                return None, False
 
416
            if repository:
 
417
                return UseExistingRepository(repository, stack_on,
 
418
                    stack_on_pwd, require_stacking=require_stacking), True
 
419
            else:
 
420
                return CreateRepository(self, stack_on, stack_on_pwd,
 
421
                    require_stacking=require_stacking), True
 
422
 
 
423
        if not force_new_repo:
 
424
            if stack_on is None:
 
425
                policy = self._find_containing(repository_policy)
 
426
                if policy is not None:
 
427
                    return policy
 
428
            else:
 
429
                try:
 
430
                    return UseExistingRepository(self.open_repository(),
 
431
                        stack_on, stack_on_pwd,
 
432
                        require_stacking=require_stacking)
 
433
                except errors.NoRepositoryPresent:
 
434
                    pass
 
435
        return CreateRepository(self, stack_on, stack_on_pwd,
 
436
                                require_stacking=require_stacking)
 
437
 
 
438
    def _find_or_create_repository(self, force_new_repo):
 
439
        """Create a new repository if needed, returning the repository."""
 
440
        policy = self.determine_repository_policy(force_new_repo)
 
441
        return policy.acquire_repository()
 
442
 
 
443
    @staticmethod
 
444
    def create_branch_convenience(base, force_new_repo=False,
 
445
                                  force_new_tree=None, format=None,
 
446
                                  possible_transports=None):
 
447
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
448
 
 
449
        This is a convenience function - it will use an existing repository
 
450
        if possible, can be told explicitly whether to create a working tree or
 
451
        not.
 
452
 
 
453
        This will use the current default BzrDirFormat unless one is
 
454
        specified, and use whatever 
 
455
        repository format that that uses via bzrdir.create_branch and
 
456
        create_repository. If a shared repository is available that is used
 
457
        preferentially. Whatever repository is used, its tree creation policy
 
458
        is followed.
 
459
 
 
460
        The created Branch object is returned.
 
461
        If a working tree cannot be made due to base not being a file:// url,
 
462
        no error is raised unless force_new_tree is True, in which case no 
 
463
        data is created on disk and NotLocalUrl is raised.
 
464
 
 
465
        :param base: The URL to create the branch at.
 
466
        :param force_new_repo: If True a new repository is always created.
 
467
        :param force_new_tree: If True or False force creation of a tree or 
 
468
                               prevent such creation respectively.
 
469
        :param format: Override for the bzrdir format to create.
 
470
        :param possible_transports: An optional reusable transports list.
 
471
        """
 
472
        if force_new_tree:
 
473
            # check for non local urls
 
474
            t = get_transport(base, possible_transports)
 
475
            if not isinstance(t, LocalTransport):
 
476
                raise errors.NotLocalUrl(base)
 
477
        bzrdir = BzrDir.create(base, format, possible_transports)
 
478
        repo = bzrdir._find_or_create_repository(force_new_repo)
 
479
        result = bzrdir.create_branch()
 
480
        if force_new_tree or (repo.make_working_trees() and
 
481
                              force_new_tree is None):
 
482
            try:
 
483
                bzrdir.create_workingtree()
 
484
            except errors.NotLocalUrl:
 
485
                pass
 
486
        return result
 
487
 
 
488
    @staticmethod
 
489
    def create_standalone_workingtree(base, format=None):
 
490
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
491
 
 
492
        'base' must be a local path or a file:// url.
 
493
 
 
494
        This will use the current default BzrDirFormat unless one is
 
495
        specified, and use whatever 
 
496
        repository format that that uses for bzrdirformat.create_workingtree,
 
497
        create_branch and create_repository.
 
498
 
 
499
        :param format: Override for the bzrdir format to create.
 
500
        :return: The WorkingTree object.
 
501
        """
 
502
        t = get_transport(base)
 
503
        if not isinstance(t, LocalTransport):
 
504
            raise errors.NotLocalUrl(base)
 
505
        bzrdir = BzrDir.create_branch_and_repo(base,
 
506
                                               force_new_repo=True,
 
507
                                               format=format).bzrdir
 
508
        return bzrdir.create_workingtree()
 
509
 
 
510
    def create_workingtree(self, revision_id=None, from_branch=None,
 
511
        accelerator_tree=None, hardlink=False):
 
512
        """Create a working tree at this BzrDir.
 
513
        
 
514
        :param revision_id: create it as of this revision id.
 
515
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
516
        :param accelerator_tree: A tree which can be used for retrieving file
 
517
            contents more quickly than the revision tree, i.e. a workingtree.
 
518
            The revision tree will be used for cases where accelerator_tree's
 
519
            content is different.
 
520
        """
 
521
        raise NotImplementedError(self.create_workingtree)
 
522
 
 
523
    def retire_bzrdir(self, limit=10000):
 
524
        """Permanently disable the bzrdir.
 
525
 
 
526
        This is done by renaming it to give the user some ability to recover
 
527
        if there was a problem.
 
528
 
 
529
        This will have horrible consequences if anyone has anything locked or
 
530
        in use.
 
531
        :param limit: number of times to retry
 
532
        """
 
533
        i  = 0
 
534
        while True:
 
535
            try:
 
536
                to_path = '.bzr.retired.%d' % i
 
537
                self.root_transport.rename('.bzr', to_path)
 
538
                note("renamed %s to %s"
 
539
                    % (self.root_transport.abspath('.bzr'), to_path))
 
540
                return
 
541
            except (errors.TransportError, IOError, errors.PathError):
 
542
                i += 1
 
543
                if i > limit:
 
544
                    raise
 
545
                else:
 
546
                    pass
 
547
 
 
548
    def destroy_workingtree(self):
 
549
        """Destroy the working tree at this BzrDir.
 
550
 
 
551
        Formats that do not support this may raise UnsupportedOperation.
 
552
        """
 
553
        raise NotImplementedError(self.destroy_workingtree)
 
554
 
 
555
    def destroy_workingtree_metadata(self):
 
556
        """Destroy the control files for the working tree at this BzrDir.
 
557
 
 
558
        The contents of working tree files are not affected.
 
559
        Formats that do not support this may raise UnsupportedOperation.
 
560
        """
 
561
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
562
 
 
563
    def _find_containing(self, evaluate):
 
564
        """Find something in a containing control directory.
 
565
 
 
566
        This method will scan containing control dirs, until it finds what
 
567
        it is looking for, decides that it will never find it, or runs out
 
568
        of containing control directories to check.
 
569
 
 
570
        It is used to implement find_repository and
 
571
        determine_repository_policy.
 
572
 
 
573
        :param evaluate: A function returning (value, stop).  If stop is True,
 
574
            the value will be returned.
 
575
        """
 
576
        found_bzrdir = self
 
577
        while True:
 
578
            result, stop = evaluate(found_bzrdir)
 
579
            if stop:
 
580
                return result
 
581
            next_transport = found_bzrdir.root_transport.clone('..')
 
582
            if (found_bzrdir.root_transport.base == next_transport.base):
 
583
                # top of the file system
 
584
                return None
 
585
            # find the next containing bzrdir
 
586
            try:
 
587
                found_bzrdir = BzrDir.open_containing_from_transport(
 
588
                    next_transport)[0]
 
589
            except errors.NotBranchError:
 
590
                return None
 
591
 
 
592
    def find_repository(self):
 
593
        """Find the repository that should be used.
 
594
 
 
595
        This does not require a branch as we use it to find the repo for
 
596
        new branches as well as to hook existing branches up to their
 
597
        repository.
 
598
        """
 
599
        def usable_repository(found_bzrdir):
 
600
            # does it have a repository ?
 
601
            try:
 
602
                repository = found_bzrdir.open_repository()
 
603
            except errors.NoRepositoryPresent:
 
604
                return None, False
 
605
            if found_bzrdir.root_transport.base == self.root_transport.base:
 
606
                return repository, True
 
607
            elif repository.is_shared():
 
608
                return repository, True
 
609
            else:
 
610
                return None, True
 
611
 
 
612
        found_repo = self._find_containing(usable_repository)
 
613
        if found_repo is None:
 
614
            raise errors.NoRepositoryPresent(self)
 
615
        return found_repo
 
616
 
 
617
    def get_branch_reference(self):
 
618
        """Return the referenced URL for the branch in this bzrdir.
 
619
 
 
620
        :raises NotBranchError: If there is no Branch.
 
621
        :return: The URL the branch in this bzrdir references if it is a
 
622
            reference branch, or None for regular branches.
 
623
        """
 
624
        return None
 
625
 
 
626
    def get_branch_transport(self, branch_format):
 
627
        """Get the transport for use by branch format in this BzrDir.
 
628
 
 
629
        Note that bzr dirs that do not support format strings will raise
 
630
        IncompatibleFormat if the branch format they are given has
 
631
        a format string, and vice versa.
 
632
 
 
633
        If branch_format is None, the transport is returned with no 
 
634
        checking. If it is not None, then the returned transport is
 
635
        guaranteed to point to an existing directory ready for use.
 
636
        """
 
637
        raise NotImplementedError(self.get_branch_transport)
 
638
 
 
639
    def _find_creation_modes(self):
 
640
        """Determine the appropriate modes for files and directories.
 
641
        
 
642
        They're always set to be consistent with the base directory,
 
643
        assuming that this transport allows setting modes.
 
644
        """
 
645
        # TODO: Do we need or want an option (maybe a config setting) to turn
 
646
        # this off or override it for particular locations? -- mbp 20080512
 
647
        if self._mode_check_done:
 
648
            return
 
649
        self._mode_check_done = True
 
650
        try:
 
651
            st = self.transport.stat('.')
 
652
        except errors.TransportNotPossible:
 
653
            self._dir_mode = None
 
654
            self._file_mode = None
 
655
        else:
 
656
            # Check the directory mode, but also make sure the created
 
657
            # directories and files are read-write for this user. This is
 
658
            # mostly a workaround for filesystems which lie about being able to
 
659
            # write to a directory (cygwin & win32)
 
660
            self._dir_mode = (st.st_mode & 07777) | 00700
 
661
            # Remove the sticky and execute bits for files
 
662
            self._file_mode = self._dir_mode & ~07111
 
663
 
 
664
    def _get_file_mode(self):
 
665
        """Return Unix mode for newly created files, or None.
 
666
        """
 
667
        if not self._mode_check_done:
 
668
            self._find_creation_modes()
 
669
        return self._file_mode
 
670
 
 
671
    def _get_dir_mode(self):
 
672
        """Return Unix mode for newly created directories, or None.
 
673
        """
 
674
        if not self._mode_check_done:
 
675
            self._find_creation_modes()
 
676
        return self._dir_mode
 
677
        
 
678
    def get_repository_transport(self, repository_format):
 
679
        """Get the transport for use by repository format in this BzrDir.
 
680
 
 
681
        Note that bzr dirs that do not support format strings will raise
 
682
        IncompatibleFormat if the repository format they are given has
 
683
        a format string, and vice versa.
 
684
 
 
685
        If repository_format is None, the transport is returned with no 
 
686
        checking. If it is not None, then the returned transport is
 
687
        guaranteed to point to an existing directory ready for use.
 
688
        """
 
689
        raise NotImplementedError(self.get_repository_transport)
 
690
        
 
691
    def get_workingtree_transport(self, tree_format):
 
692
        """Get the transport for use by workingtree format in this BzrDir.
 
693
 
 
694
        Note that bzr dirs that do not support format strings will raise
 
695
        IncompatibleFormat if the workingtree format they are given has a
 
696
        format string, and vice versa.
 
697
 
 
698
        If workingtree_format is None, the transport is returned with no 
 
699
        checking. If it is not None, then the returned transport is
 
700
        guaranteed to point to an existing directory ready for use.
 
701
        """
 
702
        raise NotImplementedError(self.get_workingtree_transport)
 
703
 
 
704
    def get_config(self):
 
705
        if getattr(self, '_get_config', None) is None:
 
706
            return None
 
707
        return self._get_config()
 
708
 
 
709
    def __init__(self, _transport, _format):
 
710
        """Initialize a Bzr control dir object.
 
711
        
 
712
        Only really common logic should reside here, concrete classes should be
 
713
        made with varying behaviours.
 
714
 
 
715
        :param _format: the format that is creating this BzrDir instance.
 
716
        :param _transport: the transport this dir is based at.
 
717
        """
 
718
        self._format = _format
 
719
        self.transport = _transport.clone('.bzr')
 
720
        self.root_transport = _transport
 
721
        self._mode_check_done = False
 
722
 
 
723
    def is_control_filename(self, filename):
 
724
        """True if filename is the name of a path which is reserved for bzrdir's.
 
725
        
 
726
        :param filename: A filename within the root transport of this bzrdir.
 
727
 
 
728
        This is true IF and ONLY IF the filename is part of the namespace reserved
 
729
        for bzr control dirs. Currently this is the '.bzr' directory in the root
 
730
        of the root_transport. it is expected that plugins will need to extend
 
731
        this in the future - for instance to make bzr talk with svn working
 
732
        trees.
 
733
        """
 
734
        # this might be better on the BzrDirFormat class because it refers to 
 
735
        # all the possible bzrdir disk formats. 
 
736
        # This method is tested via the workingtree is_control_filename tests- 
 
737
        # it was extracted from WorkingTree.is_control_filename. If the method's
 
738
        # contract is extended beyond the current trivial implementation, please
 
739
        # add new tests for it to the appropriate place.
 
740
        return filename == '.bzr' or filename.startswith('.bzr/')
 
741
 
 
742
    def needs_format_conversion(self, format=None):
 
743
        """Return true if this bzrdir needs convert_format run on it.
 
744
        
 
745
        For instance, if the repository format is out of date but the 
 
746
        branch and working tree are not, this should return True.
 
747
 
 
748
        :param format: Optional parameter indicating a specific desired
 
749
                       format we plan to arrive at.
 
750
        """
 
751
        raise NotImplementedError(self.needs_format_conversion)
 
752
 
 
753
    @staticmethod
 
754
    def open_unsupported(base):
 
755
        """Open a branch which is not supported."""
 
756
        return BzrDir.open(base, _unsupported=True)
 
757
        
 
758
    @staticmethod
 
759
    def open(base, _unsupported=False, possible_transports=None):
 
760
        """Open an existing bzrdir, rooted at 'base' (url).
 
761
        
 
762
        :param _unsupported: a private parameter to the BzrDir class.
 
763
        """
 
764
        t = get_transport(base, possible_transports=possible_transports)
 
765
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
 
766
 
 
767
    @staticmethod
 
768
    def open_from_transport(transport, _unsupported=False,
 
769
                            _server_formats=True):
 
770
        """Open a bzrdir within a particular directory.
 
771
 
 
772
        :param transport: Transport containing the bzrdir.
 
773
        :param _unsupported: private.
 
774
        """
 
775
        base = transport.base
 
776
 
 
777
        def find_format(transport):
 
778
            return transport, BzrDirFormat.find_format(
 
779
                transport, _server_formats=_server_formats)
 
780
 
 
781
        def redirected(transport, e, redirection_notice):
 
782
            qualified_source = e.get_source_url()
 
783
            relpath = transport.relpath(qualified_source)
 
784
            if not e.target.endswith(relpath):
 
785
                # Not redirected to a branch-format, not a branch
 
786
                raise errors.NotBranchError(path=e.target)
 
787
            target = e.target[:-len(relpath)]
 
788
            note('%s is%s redirected to %s',
 
789
                 transport.base, e.permanently, target)
 
790
            # Let's try with a new transport
 
791
            # FIXME: If 'transport' has a qualifier, this should
 
792
            # be applied again to the new transport *iff* the
 
793
            # schemes used are the same. Uncomment this code
 
794
            # once the function (and tests) exist.
 
795
            # -- vila20070212
 
796
            #target = urlutils.copy_url_qualifiers(original, target)
 
797
            return get_transport(target)
 
798
 
 
799
        try:
 
800
            transport, format = do_catching_redirections(find_format,
 
801
                                                         transport,
 
802
                                                         redirected)
 
803
        except errors.TooManyRedirections:
 
804
            raise errors.NotBranchError(base)
 
805
 
 
806
        BzrDir._check_supported(format, _unsupported)
 
807
        return format.open(transport, _found=True)
 
808
 
 
809
    def open_branch(self, unsupported=False):
 
810
        """Open the branch object at this BzrDir if one is present.
 
811
 
 
812
        If unsupported is True, then no longer supported branch formats can
 
813
        still be opened.
 
814
        
 
815
        TODO: static convenience version of this?
 
816
        """
 
817
        raise NotImplementedError(self.open_branch)
 
818
 
 
819
    @staticmethod
 
820
    def open_containing(url, possible_transports=None):
 
821
        """Open an existing branch which contains url.
 
822
        
 
823
        :param url: url to search from.
 
824
        See open_containing_from_transport for more detail.
 
825
        """
 
826
        transport = get_transport(url, possible_transports)
 
827
        return BzrDir.open_containing_from_transport(transport)
 
828
    
 
829
    @staticmethod
 
830
    def open_containing_from_transport(a_transport):
 
831
        """Open an existing branch which contains a_transport.base.
 
832
 
 
833
        This probes for a branch at a_transport, and searches upwards from there.
 
834
 
 
835
        Basically we keep looking up until we find the control directory or
 
836
        run into the root.  If there isn't one, raises NotBranchError.
 
837
        If there is one and it is either an unrecognised format or an unsupported 
 
838
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
839
        If there is one, it is returned, along with the unused portion of url.
 
840
 
 
841
        :return: The BzrDir that contains the path, and a Unicode path 
 
842
                for the rest of the URL.
 
843
        """
 
844
        # this gets the normalised url back. I.e. '.' -> the full path.
 
845
        url = a_transport.base
 
846
        while True:
 
847
            try:
 
848
                result = BzrDir.open_from_transport(a_transport)
 
849
                return result, urlutils.unescape(a_transport.relpath(url))
 
850
            except errors.NotBranchError, e:
 
851
                pass
 
852
            try:
 
853
                new_t = a_transport.clone('..')
 
854
            except errors.InvalidURLJoin:
 
855
                # reached the root, whatever that may be
 
856
                raise errors.NotBranchError(path=url)
 
857
            if new_t.base == a_transport.base:
 
858
                # reached the root, whatever that may be
 
859
                raise errors.NotBranchError(path=url)
 
860
            a_transport = new_t
 
861
 
 
862
    def _get_tree_branch(self):
 
863
        """Return the branch and tree, if any, for this bzrdir.
 
864
 
 
865
        Return None for tree if not present or inaccessible.
 
866
        Raise NotBranchError if no branch is present.
 
867
        :return: (tree, branch)
 
868
        """
 
869
        try:
 
870
            tree = self.open_workingtree()
 
871
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
872
            tree = None
 
873
            branch = self.open_branch()
 
874
        else:
 
875
            branch = tree.branch
 
876
        return tree, branch
 
877
 
 
878
    @classmethod
 
879
    def open_tree_or_branch(klass, location):
 
880
        """Return the branch and working tree at a location.
 
881
 
 
882
        If there is no tree at the location, tree will be None.
 
883
        If there is no branch at the location, an exception will be
 
884
        raised
 
885
        :return: (tree, branch)
 
886
        """
 
887
        bzrdir = klass.open(location)
 
888
        return bzrdir._get_tree_branch()
 
889
 
 
890
    @classmethod
 
891
    def open_containing_tree_or_branch(klass, location):
 
892
        """Return the branch and working tree contained by a location.
 
893
 
 
894
        Returns (tree, branch, relpath).
 
895
        If there is no tree at containing the location, tree will be None.
 
896
        If there is no branch containing the location, an exception will be
 
897
        raised
 
898
        relpath is the portion of the path that is contained by the branch.
 
899
        """
 
900
        bzrdir, relpath = klass.open_containing(location)
 
901
        tree, branch = bzrdir._get_tree_branch()
 
902
        return tree, branch, relpath
 
903
 
 
904
    @classmethod
 
905
    def open_containing_tree_branch_or_repository(klass, location):
 
906
        """Return the working tree, branch and repo contained by a location.
 
907
 
 
908
        Returns (tree, branch, repository, relpath).
 
909
        If there is no tree containing the location, tree will be None.
 
910
        If there is no branch containing the location, branch will be None.
 
911
        If there is no repository containing the location, repository will be
 
912
        None.
 
913
        relpath is the portion of the path that is contained by the innermost
 
914
        BzrDir.
 
915
 
 
916
        If no tree, branch or repository is found, a NotBranchError is raised.
 
917
        """
 
918
        bzrdir, relpath = klass.open_containing(location)
 
919
        try:
 
920
            tree, branch = bzrdir._get_tree_branch()
 
921
        except errors.NotBranchError:
 
922
            try:
 
923
                repo = bzrdir.find_repository()
 
924
                return None, None, repo, relpath
 
925
            except (errors.NoRepositoryPresent):
 
926
                raise errors.NotBranchError(location)
 
927
        return tree, branch, branch.repository, relpath
 
928
 
 
929
    def open_repository(self, _unsupported=False):
 
930
        """Open the repository object at this BzrDir if one is present.
 
931
 
 
932
        This will not follow the Branch object pointer - it's strictly a direct
 
933
        open facility. Most client code should use open_branch().repository to
 
934
        get at a repository.
 
935
 
 
936
        :param _unsupported: a private parameter, not part of the api.
 
937
        TODO: static convenience version of this?
 
938
        """
 
939
        raise NotImplementedError(self.open_repository)
 
940
 
 
941
    def open_workingtree(self, _unsupported=False,
 
942
                         recommend_upgrade=True, from_branch=None):
 
943
        """Open the workingtree object at this BzrDir if one is present.
 
944
 
 
945
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
946
            default), emit through the ui module a recommendation that the user
 
947
            upgrade the working tree when the workingtree being opened is old
 
948
            (but still fully supported).
 
949
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
950
        """
 
951
        raise NotImplementedError(self.open_workingtree)
 
952
 
 
953
    def has_branch(self):
 
954
        """Tell if this bzrdir contains a branch.
 
955
        
 
956
        Note: if you're going to open the branch, you should just go ahead
 
957
        and try, and not ask permission first.  (This method just opens the 
 
958
        branch and discards it, and that's somewhat expensive.) 
 
959
        """
 
960
        try:
 
961
            self.open_branch()
 
962
            return True
 
963
        except errors.NotBranchError:
 
964
            return False
 
965
 
 
966
    def has_workingtree(self):
 
967
        """Tell if this bzrdir contains a working tree.
 
968
 
 
969
        This will still raise an exception if the bzrdir has a workingtree that
 
970
        is remote & inaccessible.
 
971
        
 
972
        Note: if you're going to open the working tree, you should just go ahead
 
973
        and try, and not ask permission first.  (This method just opens the 
 
974
        workingtree and discards it, and that's somewhat expensive.) 
 
975
        """
 
976
        try:
 
977
            self.open_workingtree(recommend_upgrade=False)
 
978
            return True
 
979
        except errors.NoWorkingTree:
 
980
            return False
 
981
 
 
982
    def _cloning_metadir(self):
 
983
        """Produce a metadir suitable for cloning with.
 
984
        
 
985
        :returns: (destination_bzrdir_format, source_repository)
 
986
        """
 
987
        result_format = self._format.__class__()
 
988
        try:
 
989
            try:
 
990
                branch = self.open_branch()
 
991
                source_repository = branch.repository
 
992
            except errors.NotBranchError:
 
993
                source_branch = None
 
994
                source_repository = self.open_repository()
 
995
        except errors.NoRepositoryPresent:
 
996
            source_repository = None
 
997
        else:
 
998
            # XXX TODO: This isinstance is here because we have not implemented
 
999
            # the fix recommended in bug # 103195 - to delegate this choice the
 
1000
            # repository itself.
 
1001
            repo_format = source_repository._format
 
1002
            if not isinstance(repo_format, remote.RemoteRepositoryFormat):
 
1003
                result_format.repository_format = repo_format
 
1004
        try:
 
1005
            # TODO: Couldn't we just probe for the format in these cases,
 
1006
            # rather than opening the whole tree?  It would be a little
 
1007
            # faster. mbp 20070401
 
1008
            tree = self.open_workingtree(recommend_upgrade=False)
 
1009
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1010
            result_format.workingtree_format = None
 
1011
        else:
 
1012
            result_format.workingtree_format = tree._format.__class__()
 
1013
        return result_format, source_repository
 
1014
 
 
1015
    def cloning_metadir(self):
 
1016
        """Produce a metadir suitable for cloning or sprouting with.
 
1017
 
 
1018
        These operations may produce workingtrees (yes, even though they're
 
1019
        "cloning" something that doesn't have a tree), so a viable workingtree
 
1020
        format must be selected.
 
1021
 
 
1022
        :returns: a BzrDirFormat with all component formats either set
 
1023
            appropriately or set to None if that component should not be 
 
1024
            created.
 
1025
        """
 
1026
        format, repository = self._cloning_metadir()
 
1027
        if format._workingtree_format is None:
 
1028
            if repository is None:
 
1029
                return format
 
1030
            tree_format = repository._format._matchingbzrdir.workingtree_format
 
1031
            format.workingtree_format = tree_format.__class__()
 
1032
        return format
 
1033
 
 
1034
    def checkout_metadir(self):
 
1035
        return self.cloning_metadir()
 
1036
 
 
1037
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1038
               recurse='down', possible_transports=None,
 
1039
               accelerator_tree=None, hardlink=False, stacked=False):
 
1040
        """Create a copy of this bzrdir prepared for use as a new line of
 
1041
        development.
 
1042
 
 
1043
        If url's last component does not exist, it will be created.
 
1044
 
 
1045
        Attributes related to the identity of the source branch like
 
1046
        branch nickname will be cleaned, a working tree is created
 
1047
        whether one existed before or not; and a local branch is always
 
1048
        created.
 
1049
 
 
1050
        if revision_id is not None, then the clone operation may tune
 
1051
            itself to download less data.
 
1052
        :param accelerator_tree: A tree which can be used for retrieving file
 
1053
            contents more quickly than the revision tree, i.e. a workingtree.
 
1054
            The revision tree will be used for cases where accelerator_tree's
 
1055
            content is different.
 
1056
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1057
            where possible.
 
1058
        :param stacked: If true, create a stacked branch referring to the
 
1059
            location of this control directory.
 
1060
        """
 
1061
        target_transport = get_transport(url, possible_transports)
 
1062
        target_transport.ensure_base()
 
1063
        cloning_format = self.cloning_metadir()
 
1064
        result = cloning_format.initialize_on_transport(target_transport)
 
1065
        try:
 
1066
            source_branch = self.open_branch()
 
1067
            source_repository = source_branch.repository
 
1068
            if stacked:
 
1069
                stacked_branch_url = self.root_transport.base
 
1070
            else:
 
1071
                # if a stacked branch wasn't requested, we don't create one
 
1072
                # even if the origin was stacked
 
1073
                stacked_branch_url = None
 
1074
        except errors.NotBranchError:
 
1075
            source_branch = None
 
1076
            try:
 
1077
                source_repository = self.open_repository()
 
1078
            except errors.NoRepositoryPresent:
 
1079
                source_repository = None
 
1080
            stacked_branch_url = None
 
1081
        repository_policy = result.determine_repository_policy(
 
1082
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
1083
        result_repo = repository_policy.acquire_repository()
 
1084
        if source_repository is not None:
 
1085
            # XXX: Isn't this redundant with the copy_content_into used below
 
1086
            # after creating the branch? -- mbp 20080724
 
1087
            result_repo.fetch(source_repository, revision_id=revision_id)
 
1088
 
 
1089
        # Create/update the result branch
 
1090
        if ((stacked 
 
1091
             or repository_policy._require_stacking 
 
1092
             or repository_policy._stack_on)
 
1093
            and not result._format.get_branch_format().supports_stacking()):
 
1094
            # force a branch that can support stacking 
 
1095
            from bzrlib.branch import BzrBranchFormat7
 
1096
            format = BzrBranchFormat7()
 
1097
            result_branch = format.initialize(result)
 
1098
            mutter("using %r for stacking" % (format,))
 
1099
        elif source_branch is None:
 
1100
            # this is for sprouting a bzrdir without a branch; is that
 
1101
            # actually useful?
 
1102
            result_branch = result.create_branch()
 
1103
        else:
 
1104
            result_branch = source_branch._format.initialize(result)
 
1105
        mutter("created new branch %r" % (result_branch,))
 
1106
        repository_policy.configure_branch(result_branch)
 
1107
        if source_branch is not None:
 
1108
            # XXX: this duplicates Branch.sprout(); it probably belongs on an
 
1109
            # InterBranch method? -- mbp 20080724
 
1110
            source_branch.copy_content_into(result_branch,
 
1111
                 revision_id=revision_id)
 
1112
            result_branch.set_parent(self.root_transport.base)
 
1113
 
 
1114
        # Create/update the result working tree
 
1115
        if isinstance(target_transport, LocalTransport) and (
 
1116
            result_repo is None or result_repo.make_working_trees()):
 
1117
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
1118
                hardlink=hardlink)
 
1119
            wt.lock_write()
 
1120
            try:
 
1121
                if wt.path2id('') is None:
 
1122
                    try:
 
1123
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
1124
                    except errors.NoWorkingTree:
 
1125
                        pass
 
1126
            finally:
 
1127
                wt.unlock()
 
1128
        else:
 
1129
            wt = None
 
1130
        if recurse == 'down':
 
1131
            if wt is not None:
 
1132
                basis = wt.basis_tree()
 
1133
                basis.lock_read()
 
1134
                subtrees = basis.iter_references()
 
1135
            elif source_branch is not None:
 
1136
                basis = source_branch.basis_tree()
 
1137
                basis.lock_read()
 
1138
                subtrees = basis.iter_references()
 
1139
            else:
 
1140
                subtrees = []
 
1141
                basis = None
 
1142
            try:
 
1143
                for path, file_id in subtrees:
 
1144
                    target = urlutils.join(url, urlutils.escape(path))
 
1145
                    sublocation = source_branch.reference_parent(file_id, path)
 
1146
                    sublocation.bzrdir.sprout(target,
 
1147
                        basis.get_reference_revision(file_id, path),
 
1148
                        force_new_repo=force_new_repo, recurse=recurse,
 
1149
                        stacked=stacked)
 
1150
            finally:
 
1151
                if basis is not None:
 
1152
                    basis.unlock()
 
1153
        return result
 
1154
 
 
1155
 
 
1156
class BzrDirPreSplitOut(BzrDir):
 
1157
    """A common class for the all-in-one formats."""
 
1158
 
 
1159
    def __init__(self, _transport, _format):
 
1160
        """See BzrDir.__init__."""
 
1161
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
1162
        self._control_files = lockable_files.LockableFiles(
 
1163
                                            self.get_branch_transport(None),
 
1164
                                            self._format._lock_file_name,
 
1165
                                            self._format._lock_class)
 
1166
 
 
1167
    def break_lock(self):
 
1168
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
1169
        raise NotImplementedError(self.break_lock)
 
1170
 
 
1171
    def cloning_metadir(self):
 
1172
        """Produce a metadir suitable for cloning with."""
 
1173
        return self._format.__class__()
 
1174
 
 
1175
    def clone(self, url, revision_id=None, force_new_repo=False,
 
1176
              preserve_stacking=False):
 
1177
        """See BzrDir.clone().
 
1178
 
 
1179
        force_new_repo has no effect, since this family of formats always
 
1180
        require a new repository.
 
1181
        preserve_stacking has no effect, since no source branch using this
 
1182
        family of formats can be stacked, so there is no stacking to preserve.
 
1183
        """
 
1184
        from bzrlib.workingtree import WorkingTreeFormat2
 
1185
        self._make_tail(url)
 
1186
        result = self._format._initialize_for_clone(url)
 
1187
        self.open_repository().clone(result, revision_id=revision_id)
 
1188
        from_branch = self.open_branch()
 
1189
        from_branch.clone(result, revision_id=revision_id)
 
1190
        try:
 
1191
            self.open_workingtree().clone(result)
 
1192
        except errors.NotLocalUrl:
 
1193
            # make a new one, this format always has to have one.
 
1194
            try:
 
1195
                WorkingTreeFormat2().initialize(result)
 
1196
            except errors.NotLocalUrl:
 
1197
                # but we cannot do it for remote trees.
 
1198
                to_branch = result.open_branch()
 
1199
                WorkingTreeFormat2()._stub_initialize_remote(to_branch)
 
1200
        return result
 
1201
 
 
1202
    def create_branch(self):
 
1203
        """See BzrDir.create_branch."""
 
1204
        return self.open_branch()
 
1205
 
 
1206
    def destroy_branch(self):
 
1207
        """See BzrDir.destroy_branch."""
 
1208
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
1209
 
 
1210
    def create_repository(self, shared=False):
 
1211
        """See BzrDir.create_repository."""
 
1212
        if shared:
 
1213
            raise errors.IncompatibleFormat('shared repository', self._format)
 
1214
        return self.open_repository()
 
1215
 
 
1216
    def destroy_repository(self):
 
1217
        """See BzrDir.destroy_repository."""
 
1218
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
1219
 
 
1220
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1221
                           accelerator_tree=None, hardlink=False):
 
1222
        """See BzrDir.create_workingtree."""
 
1223
        # this looks buggy but is not -really-
 
1224
        # because this format creates the workingtree when the bzrdir is
 
1225
        # created
 
1226
        # clone and sprout will have set the revision_id
 
1227
        # and that will have set it for us, its only
 
1228
        # specific uses of create_workingtree in isolation
 
1229
        # that can do wonky stuff here, and that only
 
1230
        # happens for creating checkouts, which cannot be 
 
1231
        # done on this format anyway. So - acceptable wart.
 
1232
        result = self.open_workingtree(recommend_upgrade=False)
 
1233
        if revision_id is not None:
 
1234
            if revision_id == _mod_revision.NULL_REVISION:
 
1235
                result.set_parent_ids([])
 
1236
            else:
 
1237
                result.set_parent_ids([revision_id])
 
1238
        return result
 
1239
 
 
1240
    def destroy_workingtree(self):
 
1241
        """See BzrDir.destroy_workingtree."""
 
1242
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
1243
 
 
1244
    def destroy_workingtree_metadata(self):
 
1245
        """See BzrDir.destroy_workingtree_metadata."""
 
1246
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
1247
                                          self)
 
1248
 
 
1249
    def get_branch_transport(self, branch_format):
 
1250
        """See BzrDir.get_branch_transport()."""
 
1251
        if branch_format is None:
 
1252
            return self.transport
 
1253
        try:
 
1254
            branch_format.get_format_string()
 
1255
        except NotImplementedError:
 
1256
            return self.transport
 
1257
        raise errors.IncompatibleFormat(branch_format, self._format)
 
1258
 
 
1259
    def get_repository_transport(self, repository_format):
 
1260
        """See BzrDir.get_repository_transport()."""
 
1261
        if repository_format is None:
 
1262
            return self.transport
 
1263
        try:
 
1264
            repository_format.get_format_string()
 
1265
        except NotImplementedError:
 
1266
            return self.transport
 
1267
        raise errors.IncompatibleFormat(repository_format, self._format)
 
1268
 
 
1269
    def get_workingtree_transport(self, workingtree_format):
 
1270
        """See BzrDir.get_workingtree_transport()."""
 
1271
        if workingtree_format is None:
 
1272
            return self.transport
 
1273
        try:
 
1274
            workingtree_format.get_format_string()
 
1275
        except NotImplementedError:
 
1276
            return self.transport
 
1277
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
1278
 
 
1279
    def needs_format_conversion(self, format=None):
 
1280
        """See BzrDir.needs_format_conversion()."""
 
1281
        # if the format is not the same as the system default,
 
1282
        # an upgrade is needed.
 
1283
        if format is None:
 
1284
            format = BzrDirFormat.get_default_format()
 
1285
        return not isinstance(self._format, format.__class__)
 
1286
 
 
1287
    def open_branch(self, unsupported=False):
 
1288
        """See BzrDir.open_branch."""
 
1289
        from bzrlib.branch import BzrBranchFormat4
 
1290
        format = BzrBranchFormat4()
 
1291
        self._check_supported(format, unsupported)
 
1292
        return format.open(self, _found=True)
 
1293
 
 
1294
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1295
               possible_transports=None, accelerator_tree=None,
 
1296
               hardlink=False, stacked=False):
 
1297
        """See BzrDir.sprout()."""
 
1298
        if stacked:
 
1299
            raise errors.UnstackableBranchFormat(
 
1300
                self._format, self.root_transport.base)
 
1301
        from bzrlib.workingtree import WorkingTreeFormat2
 
1302
        self._make_tail(url)
 
1303
        result = self._format._initialize_for_clone(url)
 
1304
        try:
 
1305
            self.open_repository().clone(result, revision_id=revision_id)
 
1306
        except errors.NoRepositoryPresent:
 
1307
            pass
 
1308
        try:
 
1309
            self.open_branch().sprout(result, revision_id=revision_id)
 
1310
        except errors.NotBranchError:
 
1311
            pass
 
1312
        # we always want a working tree
 
1313
        WorkingTreeFormat2().initialize(result,
 
1314
                                        accelerator_tree=accelerator_tree,
 
1315
                                        hardlink=hardlink)
 
1316
        return result
 
1317
 
 
1318
 
 
1319
class BzrDir4(BzrDirPreSplitOut):
 
1320
    """A .bzr version 4 control object.
 
1321
    
 
1322
    This is a deprecated format and may be removed after sept 2006.
 
1323
    """
 
1324
 
 
1325
    def create_repository(self, shared=False):
 
1326
        """See BzrDir.create_repository."""
 
1327
        return self._format.repository_format.initialize(self, shared)
 
1328
 
 
1329
    def needs_format_conversion(self, format=None):
 
1330
        """Format 4 dirs are always in need of conversion."""
 
1331
        return True
 
1332
 
 
1333
    def open_repository(self):
 
1334
        """See BzrDir.open_repository."""
 
1335
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1336
        return RepositoryFormat4().open(self, _found=True)
 
1337
 
 
1338
 
 
1339
class BzrDir5(BzrDirPreSplitOut):
 
1340
    """A .bzr version 5 control object.
 
1341
 
 
1342
    This is a deprecated format and may be removed after sept 2006.
 
1343
    """
 
1344
 
 
1345
    def open_repository(self):
 
1346
        """See BzrDir.open_repository."""
 
1347
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1348
        return RepositoryFormat5().open(self, _found=True)
 
1349
 
 
1350
    def open_workingtree(self, _unsupported=False,
 
1351
            recommend_upgrade=True):
 
1352
        """See BzrDir.create_workingtree."""
 
1353
        from bzrlib.workingtree import WorkingTreeFormat2
 
1354
        wt_format = WorkingTreeFormat2()
 
1355
        # we don't warn here about upgrades; that ought to be handled for the
 
1356
        # bzrdir as a whole
 
1357
        return wt_format.open(self, _found=True)
 
1358
 
 
1359
 
 
1360
class BzrDir6(BzrDirPreSplitOut):
 
1361
    """A .bzr version 6 control object.
 
1362
 
 
1363
    This is a deprecated format and may be removed after sept 2006.
 
1364
    """
 
1365
 
 
1366
    def open_repository(self):
 
1367
        """See BzrDir.open_repository."""
 
1368
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1369
        return RepositoryFormat6().open(self, _found=True)
 
1370
 
 
1371
    def open_workingtree(self, _unsupported=False,
 
1372
        recommend_upgrade=True):
 
1373
        """See BzrDir.create_workingtree."""
 
1374
        # we don't warn here about upgrades; that ought to be handled for the
 
1375
        # bzrdir as a whole
 
1376
        from bzrlib.workingtree import WorkingTreeFormat2
 
1377
        return WorkingTreeFormat2().open(self, _found=True)
 
1378
 
 
1379
 
 
1380
class BzrDirMeta1(BzrDir):
 
1381
    """A .bzr meta version 1 control object.
 
1382
    
 
1383
    This is the first control object where the 
 
1384
    individual aspects are really split out: there are separate repository,
 
1385
    workingtree and branch subdirectories and any subset of the three can be
 
1386
    present within a BzrDir.
 
1387
    """
 
1388
 
 
1389
    def can_convert_format(self):
 
1390
        """See BzrDir.can_convert_format()."""
 
1391
        return True
 
1392
 
 
1393
    def create_branch(self):
 
1394
        """See BzrDir.create_branch."""
 
1395
        return self._format.get_branch_format().initialize(self)
 
1396
 
 
1397
    def destroy_branch(self):
 
1398
        """See BzrDir.create_branch."""
 
1399
        self.transport.delete_tree('branch')
 
1400
 
 
1401
    def create_repository(self, shared=False):
 
1402
        """See BzrDir.create_repository."""
 
1403
        return self._format.repository_format.initialize(self, shared)
 
1404
 
 
1405
    def destroy_repository(self):
 
1406
        """See BzrDir.destroy_repository."""
 
1407
        self.transport.delete_tree('repository')
 
1408
 
 
1409
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1410
                           accelerator_tree=None, hardlink=False):
 
1411
        """See BzrDir.create_workingtree."""
 
1412
        return self._format.workingtree_format.initialize(
 
1413
            self, revision_id, from_branch=from_branch,
 
1414
            accelerator_tree=accelerator_tree, hardlink=hardlink)
 
1415
 
 
1416
    def destroy_workingtree(self):
 
1417
        """See BzrDir.destroy_workingtree."""
 
1418
        wt = self.open_workingtree(recommend_upgrade=False)
 
1419
        repository = wt.branch.repository
 
1420
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
 
1421
        wt.revert(old_tree=empty)
 
1422
        self.destroy_workingtree_metadata()
 
1423
 
 
1424
    def destroy_workingtree_metadata(self):
 
1425
        self.transport.delete_tree('checkout')
 
1426
 
 
1427
    def find_branch_format(self):
 
1428
        """Find the branch 'format' for this bzrdir.
 
1429
 
 
1430
        This might be a synthetic object for e.g. RemoteBranch and SVN.
 
1431
        """
 
1432
        from bzrlib.branch import BranchFormat
 
1433
        return BranchFormat.find_format(self)
 
1434
 
 
1435
    def _get_mkdir_mode(self):
 
1436
        """Figure out the mode to use when creating a bzrdir subdir."""
 
1437
        temp_control = lockable_files.LockableFiles(self.transport, '',
 
1438
                                     lockable_files.TransportLock)
 
1439
        return temp_control._dir_mode
 
1440
 
 
1441
    def get_branch_reference(self):
 
1442
        """See BzrDir.get_branch_reference()."""
 
1443
        from bzrlib.branch import BranchFormat
 
1444
        format = BranchFormat.find_format(self)
 
1445
        return format.get_reference(self)
 
1446
 
 
1447
    def get_branch_transport(self, branch_format):
 
1448
        """See BzrDir.get_branch_transport()."""
 
1449
        if branch_format is None:
 
1450
            return self.transport.clone('branch')
 
1451
        try:
 
1452
            branch_format.get_format_string()
 
1453
        except NotImplementedError:
 
1454
            raise errors.IncompatibleFormat(branch_format, self._format)
 
1455
        try:
 
1456
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
1457
        except errors.FileExists:
 
1458
            pass
 
1459
        return self.transport.clone('branch')
 
1460
 
 
1461
    def get_repository_transport(self, repository_format):
 
1462
        """See BzrDir.get_repository_transport()."""
 
1463
        if repository_format is None:
 
1464
            return self.transport.clone('repository')
 
1465
        try:
 
1466
            repository_format.get_format_string()
 
1467
        except NotImplementedError:
 
1468
            raise errors.IncompatibleFormat(repository_format, self._format)
 
1469
        try:
 
1470
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
 
1471
        except errors.FileExists:
 
1472
            pass
 
1473
        return self.transport.clone('repository')
 
1474
 
 
1475
    def get_workingtree_transport(self, workingtree_format):
 
1476
        """See BzrDir.get_workingtree_transport()."""
 
1477
        if workingtree_format is None:
 
1478
            return self.transport.clone('checkout')
 
1479
        try:
 
1480
            workingtree_format.get_format_string()
 
1481
        except NotImplementedError:
 
1482
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
1483
        try:
 
1484
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
 
1485
        except errors.FileExists:
 
1486
            pass
 
1487
        return self.transport.clone('checkout')
 
1488
 
 
1489
    def needs_format_conversion(self, format=None):
 
1490
        """See BzrDir.needs_format_conversion()."""
 
1491
        if format is None:
 
1492
            format = BzrDirFormat.get_default_format()
 
1493
        if not isinstance(self._format, format.__class__):
 
1494
            # it is not a meta dir format, conversion is needed.
 
1495
            return True
 
1496
        # we might want to push this down to the repository?
 
1497
        try:
 
1498
            if not isinstance(self.open_repository()._format,
 
1499
                              format.repository_format.__class__):
 
1500
                # the repository needs an upgrade.
 
1501
                return True
 
1502
        except errors.NoRepositoryPresent:
 
1503
            pass
 
1504
        try:
 
1505
            if not isinstance(self.open_branch()._format,
 
1506
                              format.get_branch_format().__class__):
 
1507
                # the branch needs an upgrade.
 
1508
                return True
 
1509
        except errors.NotBranchError:
 
1510
            pass
 
1511
        try:
 
1512
            my_wt = self.open_workingtree(recommend_upgrade=False)
 
1513
            if not isinstance(my_wt._format,
 
1514
                              format.workingtree_format.__class__):
 
1515
                # the workingtree needs an upgrade.
 
1516
                return True
 
1517
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1518
            pass
 
1519
        return False
 
1520
 
 
1521
    def open_branch(self, unsupported=False):
 
1522
        """See BzrDir.open_branch."""
 
1523
        format = self.find_branch_format()
 
1524
        self._check_supported(format, unsupported)
 
1525
        return format.open(self, _found=True)
 
1526
 
 
1527
    def open_repository(self, unsupported=False):
 
1528
        """See BzrDir.open_repository."""
 
1529
        from bzrlib.repository import RepositoryFormat
 
1530
        format = RepositoryFormat.find_format(self)
 
1531
        self._check_supported(format, unsupported)
 
1532
        return format.open(self, _found=True)
 
1533
 
 
1534
    def open_workingtree(self, unsupported=False,
 
1535
            recommend_upgrade=True):
 
1536
        """See BzrDir.open_workingtree."""
 
1537
        from bzrlib.workingtree import WorkingTreeFormat
 
1538
        format = WorkingTreeFormat.find_format(self)
 
1539
        self._check_supported(format, unsupported,
 
1540
            recommend_upgrade,
 
1541
            basedir=self.root_transport.base)
 
1542
        return format.open(self, _found=True)
 
1543
 
 
1544
    def _get_config(self):
 
1545
        return config.BzrDirConfig(self.transport)
 
1546
 
 
1547
 
 
1548
class BzrDirFormat(object):
 
1549
    """An encapsulation of the initialization and open routines for a format.
 
1550
 
 
1551
    Formats provide three things:
 
1552
     * An initialization routine,
 
1553
     * a format string,
 
1554
     * an open routine.
 
1555
 
 
1556
    Formats are placed in a dict by their format string for reference 
 
1557
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
1558
    for consistency.
 
1559
 
 
1560
    Once a format is deprecated, just deprecate the initialize and open
 
1561
    methods on the format class. Do not deprecate the object, as the 
 
1562
    object will be created every system load.
 
1563
    """
 
1564
 
 
1565
    _default_format = None
 
1566
    """The default format used for new .bzr dirs."""
 
1567
 
 
1568
    _formats = {}
 
1569
    """The known formats."""
 
1570
 
 
1571
    _control_formats = []
 
1572
    """The registered control formats - .bzr, ....
 
1573
    
 
1574
    This is a list of BzrDirFormat objects.
 
1575
    """
 
1576
 
 
1577
    _control_server_formats = []
 
1578
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1579
 
 
1580
    This is a list of BzrDirFormat objects.
 
1581
    """
 
1582
 
 
1583
    _lock_file_name = 'branch-lock'
 
1584
 
 
1585
    # _lock_class must be set in subclasses to the lock type, typ.
 
1586
    # TransportLock or LockDir
 
1587
 
 
1588
    @classmethod
 
1589
    def find_format(klass, transport, _server_formats=True):
 
1590
        """Return the format present at transport."""
 
1591
        if _server_formats:
 
1592
            formats = klass._control_server_formats + klass._control_formats
 
1593
        else:
 
1594
            formats = klass._control_formats
 
1595
        for format in formats:
 
1596
            try:
 
1597
                return format.probe_transport(transport)
 
1598
            except errors.NotBranchError:
 
1599
                # this format does not find a control dir here.
 
1600
                pass
 
1601
        raise errors.NotBranchError(path=transport.base)
 
1602
 
 
1603
    @classmethod
 
1604
    def probe_transport(klass, transport):
 
1605
        """Return the .bzrdir style format present in a directory."""
 
1606
        try:
 
1607
            format_string = transport.get(".bzr/branch-format").read()
 
1608
        except errors.NoSuchFile:
 
1609
            raise errors.NotBranchError(path=transport.base)
 
1610
 
 
1611
        try:
 
1612
            return klass._formats[format_string]
 
1613
        except KeyError:
 
1614
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1615
 
 
1616
    @classmethod
 
1617
    def get_default_format(klass):
 
1618
        """Return the current default format."""
 
1619
        return klass._default_format
 
1620
 
 
1621
    def get_format_string(self):
 
1622
        """Return the ASCII format string that identifies this format."""
 
1623
        raise NotImplementedError(self.get_format_string)
 
1624
 
 
1625
    def get_format_description(self):
 
1626
        """Return the short description for this format."""
 
1627
        raise NotImplementedError(self.get_format_description)
 
1628
 
 
1629
    def get_converter(self, format=None):
 
1630
        """Return the converter to use to convert bzrdirs needing converts.
 
1631
 
 
1632
        This returns a bzrlib.bzrdir.Converter object.
 
1633
 
 
1634
        This should return the best upgrader to step this format towards the
 
1635
        current default format. In the case of plugins we can/should provide
 
1636
        some means for them to extend the range of returnable converters.
 
1637
 
 
1638
        :param format: Optional format to override the default format of the 
 
1639
                       library.
 
1640
        """
 
1641
        raise NotImplementedError(self.get_converter)
 
1642
 
 
1643
    def initialize(self, url, possible_transports=None):
 
1644
        """Create a bzr control dir at this url and return an opened copy.
 
1645
        
 
1646
        Subclasses should typically override initialize_on_transport
 
1647
        instead of this method.
 
1648
        """
 
1649
        return self.initialize_on_transport(get_transport(url,
 
1650
                                                          possible_transports))
 
1651
 
 
1652
    def initialize_on_transport(self, transport):
 
1653
        """Initialize a new bzrdir in the base directory of a Transport."""
 
1654
        # Since we don't have a .bzr directory, inherit the
 
1655
        # mode from the root directory
 
1656
        temp_control = lockable_files.LockableFiles(transport,
 
1657
                            '', lockable_files.TransportLock)
 
1658
        temp_control._transport.mkdir('.bzr',
 
1659
                                      # FIXME: RBC 20060121 don't peek under
 
1660
                                      # the covers
 
1661
                                      mode=temp_control._dir_mode)
 
1662
        if sys.platform == 'win32' and isinstance(transport, LocalTransport):
 
1663
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
 
1664
        file_mode = temp_control._file_mode
 
1665
        del temp_control
 
1666
        bzrdir_transport = transport.clone('.bzr')
 
1667
        utf8_files = [('README',
 
1668
                       "This is a Bazaar control directory.\n"
 
1669
                       "Do not change any files in this directory.\n"
 
1670
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
 
1671
                      ('branch-format', self.get_format_string()),
 
1672
                      ]
 
1673
        # NB: no need to escape relative paths that are url safe.
 
1674
        control_files = lockable_files.LockableFiles(bzrdir_transport,
 
1675
            self._lock_file_name, self._lock_class)
 
1676
        control_files.create_lock()
 
1677
        control_files.lock_write()
 
1678
        try:
 
1679
            for (filename, content) in utf8_files:
 
1680
                bzrdir_transport.put_bytes(filename, content,
 
1681
                    mode=file_mode)
 
1682
        finally:
 
1683
            control_files.unlock()
 
1684
        return self.open(transport, _found=True)
 
1685
 
 
1686
    def is_supported(self):
 
1687
        """Is this format supported?
 
1688
 
 
1689
        Supported formats must be initializable and openable.
 
1690
        Unsupported formats may not support initialization or committing or 
 
1691
        some other features depending on the reason for not being supported.
 
1692
        """
 
1693
        return True
 
1694
 
 
1695
    def same_model(self, target_format):
 
1696
        return (self.repository_format.rich_root_data == 
 
1697
            target_format.rich_root_data)
 
1698
 
 
1699
    @classmethod
 
1700
    def known_formats(klass):
 
1701
        """Return all the known formats.
 
1702
        
 
1703
        Concrete formats should override _known_formats.
 
1704
        """
 
1705
        # There is double indirection here to make sure that control 
 
1706
        # formats used by more than one dir format will only be probed 
 
1707
        # once. This can otherwise be quite expensive for remote connections.
 
1708
        result = set()
 
1709
        for format in klass._control_formats:
 
1710
            result.update(format._known_formats())
 
1711
        return result
 
1712
    
 
1713
    @classmethod
 
1714
    def _known_formats(klass):
 
1715
        """Return the known format instances for this control format."""
 
1716
        return set(klass._formats.values())
 
1717
 
 
1718
    def open(self, transport, _found=False):
 
1719
        """Return an instance of this format for the dir transport points at.
 
1720
        
 
1721
        _found is a private parameter, do not use it.
 
1722
        """
 
1723
        if not _found:
 
1724
            found_format = BzrDirFormat.find_format(transport)
 
1725
            if not isinstance(found_format, self.__class__):
 
1726
                raise AssertionError("%s was asked to open %s, but it seems to need "
 
1727
                        "format %s" 
 
1728
                        % (self, transport, found_format))
 
1729
        return self._open(transport)
 
1730
 
 
1731
    def _open(self, transport):
 
1732
        """Template method helper for opening BzrDirectories.
 
1733
 
 
1734
        This performs the actual open and any additional logic or parameter
 
1735
        passing.
 
1736
        """
 
1737
        raise NotImplementedError(self._open)
 
1738
 
 
1739
    @classmethod
 
1740
    def register_format(klass, format):
 
1741
        klass._formats[format.get_format_string()] = format
 
1742
 
 
1743
    @classmethod
 
1744
    def register_control_format(klass, format):
 
1745
        """Register a format that does not use '.bzr' for its control dir.
 
1746
 
 
1747
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
1748
        which BzrDirFormat can inherit from, and renamed to register_format 
 
1749
        there. It has been done without that for now for simplicity of
 
1750
        implementation.
 
1751
        """
 
1752
        klass._control_formats.append(format)
 
1753
 
 
1754
    @classmethod
 
1755
    def register_control_server_format(klass, format):
 
1756
        """Register a control format for client-server environments.
 
1757
 
 
1758
        These formats will be tried before ones registered with
 
1759
        register_control_format.  This gives implementations that decide to the
 
1760
        chance to grab it before anything looks at the contents of the format
 
1761
        file.
 
1762
        """
 
1763
        klass._control_server_formats.append(format)
 
1764
 
 
1765
    @classmethod
 
1766
    def _set_default_format(klass, format):
 
1767
        """Set default format (for testing behavior of defaults only)"""
 
1768
        klass._default_format = format
 
1769
 
 
1770
    def __str__(self):
 
1771
        # Trim the newline
 
1772
        return self.get_format_string().rstrip()
 
1773
 
 
1774
    @classmethod
 
1775
    def unregister_format(klass, format):
 
1776
        del klass._formats[format.get_format_string()]
 
1777
 
 
1778
    @classmethod
 
1779
    def unregister_control_format(klass, format):
 
1780
        klass._control_formats.remove(format)
 
1781
 
 
1782
 
 
1783
class BzrDirFormat4(BzrDirFormat):
 
1784
    """Bzr dir format 4.
 
1785
 
 
1786
    This format is a combined format for working tree, branch and repository.
 
1787
    It has:
 
1788
     - Format 1 working trees [always]
 
1789
     - Format 4 branches [always]
 
1790
     - Format 4 repositories [always]
 
1791
 
 
1792
    This format is deprecated: it indexes texts using a text it which is
 
1793
    removed in format 5; write support for this format has been removed.
 
1794
    """
 
1795
 
 
1796
    _lock_class = lockable_files.TransportLock
 
1797
 
 
1798
    def get_format_string(self):
 
1799
        """See BzrDirFormat.get_format_string()."""
 
1800
        return "Bazaar-NG branch, format 0.0.4\n"
 
1801
 
 
1802
    def get_format_description(self):
 
1803
        """See BzrDirFormat.get_format_description()."""
 
1804
        return "All-in-one format 4"
 
1805
 
 
1806
    def get_converter(self, format=None):
 
1807
        """See BzrDirFormat.get_converter()."""
 
1808
        # there is one and only one upgrade path here.
 
1809
        return ConvertBzrDir4To5()
 
1810
        
 
1811
    def initialize_on_transport(self, transport):
 
1812
        """Format 4 branches cannot be created."""
 
1813
        raise errors.UninitializableFormat(self)
 
1814
 
 
1815
    def is_supported(self):
 
1816
        """Format 4 is not supported.
 
1817
 
 
1818
        It is not supported because the model changed from 4 to 5 and the
 
1819
        conversion logic is expensive - so doing it on the fly was not 
 
1820
        feasible.
 
1821
        """
 
1822
        return False
 
1823
 
 
1824
    def _open(self, transport):
 
1825
        """See BzrDirFormat._open."""
 
1826
        return BzrDir4(transport, self)
 
1827
 
 
1828
    def __return_repository_format(self):
 
1829
        """Circular import protection."""
 
1830
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1831
        return RepositoryFormat4()
 
1832
    repository_format = property(__return_repository_format)
 
1833
 
 
1834
 
 
1835
class BzrDirFormat5(BzrDirFormat):
 
1836
    """Bzr control format 5.
 
1837
 
 
1838
    This format is a combined format for working tree, branch and repository.
 
1839
    It has:
 
1840
     - Format 2 working trees [always] 
 
1841
     - Format 4 branches [always] 
 
1842
     - Format 5 repositories [always]
 
1843
       Unhashed stores in the repository.
 
1844
    """
 
1845
 
 
1846
    _lock_class = lockable_files.TransportLock
 
1847
 
 
1848
    def get_format_string(self):
 
1849
        """See BzrDirFormat.get_format_string()."""
 
1850
        return "Bazaar-NG branch, format 5\n"
 
1851
 
 
1852
    def get_format_description(self):
 
1853
        """See BzrDirFormat.get_format_description()."""
 
1854
        return "All-in-one format 5"
 
1855
 
 
1856
    def get_converter(self, format=None):
 
1857
        """See BzrDirFormat.get_converter()."""
 
1858
        # there is one and only one upgrade path here.
 
1859
        return ConvertBzrDir5To6()
 
1860
 
 
1861
    def _initialize_for_clone(self, url):
 
1862
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1863
        
 
1864
    def initialize_on_transport(self, transport, _cloning=False):
 
1865
        """Format 5 dirs always have working tree, branch and repository.
 
1866
        
 
1867
        Except when they are being cloned.
 
1868
        """
 
1869
        from bzrlib.branch import BzrBranchFormat4
 
1870
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1871
        from bzrlib.workingtree import WorkingTreeFormat2
 
1872
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
1873
        RepositoryFormat5().initialize(result, _internal=True)
 
1874
        if not _cloning:
 
1875
            branch = BzrBranchFormat4().initialize(result)
 
1876
            try:
 
1877
                WorkingTreeFormat2().initialize(result)
 
1878
            except errors.NotLocalUrl:
 
1879
                # Even though we can't access the working tree, we need to
 
1880
                # create its control files.
 
1881
                WorkingTreeFormat2()._stub_initialize_remote(branch)
 
1882
        return result
 
1883
 
 
1884
    def _open(self, transport):
 
1885
        """See BzrDirFormat._open."""
 
1886
        return BzrDir5(transport, self)
 
1887
 
 
1888
    def __return_repository_format(self):
 
1889
        """Circular import protection."""
 
1890
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1891
        return RepositoryFormat5()
 
1892
    repository_format = property(__return_repository_format)
 
1893
 
 
1894
 
 
1895
class BzrDirFormat6(BzrDirFormat):
 
1896
    """Bzr control format 6.
 
1897
 
 
1898
    This format is a combined format for working tree, branch and repository.
 
1899
    It has:
 
1900
     - Format 2 working trees [always] 
 
1901
     - Format 4 branches [always] 
 
1902
     - Format 6 repositories [always]
 
1903
    """
 
1904
 
 
1905
    _lock_class = lockable_files.TransportLock
 
1906
 
 
1907
    def get_format_string(self):
 
1908
        """See BzrDirFormat.get_format_string()."""
 
1909
        return "Bazaar-NG branch, format 6\n"
 
1910
 
 
1911
    def get_format_description(self):
 
1912
        """See BzrDirFormat.get_format_description()."""
 
1913
        return "All-in-one format 6"
 
1914
 
 
1915
    def get_converter(self, format=None):
 
1916
        """See BzrDirFormat.get_converter()."""
 
1917
        # there is one and only one upgrade path here.
 
1918
        return ConvertBzrDir6ToMeta()
 
1919
        
 
1920
    def _initialize_for_clone(self, url):
 
1921
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1922
 
 
1923
    def initialize_on_transport(self, transport, _cloning=False):
 
1924
        """Format 6 dirs always have working tree, branch and repository.
 
1925
        
 
1926
        Except when they are being cloned.
 
1927
        """
 
1928
        from bzrlib.branch import BzrBranchFormat4
 
1929
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1930
        from bzrlib.workingtree import WorkingTreeFormat2
 
1931
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
1932
        RepositoryFormat6().initialize(result, _internal=True)
 
1933
        if not _cloning:
 
1934
            branch = BzrBranchFormat4().initialize(result)
 
1935
            try:
 
1936
                WorkingTreeFormat2().initialize(result)
 
1937
            except errors.NotLocalUrl:
 
1938
                # Even though we can't access the working tree, we need to
 
1939
                # create its control files.
 
1940
                WorkingTreeFormat2()._stub_initialize_remote(branch)
 
1941
        return result
 
1942
 
 
1943
    def _open(self, transport):
 
1944
        """See BzrDirFormat._open."""
 
1945
        return BzrDir6(transport, self)
 
1946
 
 
1947
    def __return_repository_format(self):
 
1948
        """Circular import protection."""
 
1949
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1950
        return RepositoryFormat6()
 
1951
    repository_format = property(__return_repository_format)
 
1952
 
 
1953
 
 
1954
class BzrDirMetaFormat1(BzrDirFormat):
 
1955
    """Bzr meta control format 1
 
1956
 
 
1957
    This is the first format with split out working tree, branch and repository
 
1958
    disk storage.
 
1959
    It has:
 
1960
     - Format 3 working trees [optional]
 
1961
     - Format 5 branches [optional]
 
1962
     - Format 7 repositories [optional]
 
1963
    """
 
1964
 
 
1965
    _lock_class = lockdir.LockDir
 
1966
 
 
1967
    def __init__(self):
 
1968
        self._workingtree_format = None
 
1969
        self._branch_format = None
 
1970
 
 
1971
    def __eq__(self, other):
 
1972
        if other.__class__ is not self.__class__:
 
1973
            return False
 
1974
        if other.repository_format != self.repository_format:
 
1975
            return False
 
1976
        if other.workingtree_format != self.workingtree_format:
 
1977
            return False
 
1978
        return True
 
1979
 
 
1980
    def __ne__(self, other):
 
1981
        return not self == other
 
1982
 
 
1983
    def get_branch_format(self):
 
1984
        if self._branch_format is None:
 
1985
            from bzrlib.branch import BranchFormat
 
1986
            self._branch_format = BranchFormat.get_default_format()
 
1987
        return self._branch_format
 
1988
 
 
1989
    def set_branch_format(self, format):
 
1990
        self._branch_format = format
 
1991
 
 
1992
    def get_converter(self, format=None):
 
1993
        """See BzrDirFormat.get_converter()."""
 
1994
        if format is None:
 
1995
            format = BzrDirFormat.get_default_format()
 
1996
        if not isinstance(self, format.__class__):
 
1997
            # converting away from metadir is not implemented
 
1998
            raise NotImplementedError(self.get_converter)
 
1999
        return ConvertMetaToMeta(format)
 
2000
 
 
2001
    def get_format_string(self):
 
2002
        """See BzrDirFormat.get_format_string()."""
 
2003
        return "Bazaar-NG meta directory, format 1\n"
 
2004
 
 
2005
    def get_format_description(self):
 
2006
        """See BzrDirFormat.get_format_description()."""
 
2007
        return "Meta directory format 1"
 
2008
 
 
2009
    def _open(self, transport):
 
2010
        """See BzrDirFormat._open."""
 
2011
        return BzrDirMeta1(transport, self)
 
2012
 
 
2013
    def __return_repository_format(self):
 
2014
        """Circular import protection."""
 
2015
        if getattr(self, '_repository_format', None):
 
2016
            return self._repository_format
 
2017
        from bzrlib.repository import RepositoryFormat
 
2018
        return RepositoryFormat.get_default_format()
 
2019
 
 
2020
    def __set_repository_format(self, value):
 
2021
        """Allow changing the repository format for metadir formats."""
 
2022
        self._repository_format = value
 
2023
 
 
2024
    repository_format = property(__return_repository_format, __set_repository_format)
 
2025
 
 
2026
    def __get_workingtree_format(self):
 
2027
        if self._workingtree_format is None:
 
2028
            from bzrlib.workingtree import WorkingTreeFormat
 
2029
            self._workingtree_format = WorkingTreeFormat.get_default_format()
 
2030
        return self._workingtree_format
 
2031
 
 
2032
    def __set_workingtree_format(self, wt_format):
 
2033
        self._workingtree_format = wt_format
 
2034
 
 
2035
    workingtree_format = property(__get_workingtree_format,
 
2036
                                  __set_workingtree_format)
 
2037
 
 
2038
 
 
2039
# Register bzr control format
 
2040
BzrDirFormat.register_control_format(BzrDirFormat)
 
2041
 
 
2042
# Register bzr formats
 
2043
BzrDirFormat.register_format(BzrDirFormat4())
 
2044
BzrDirFormat.register_format(BzrDirFormat5())
 
2045
BzrDirFormat.register_format(BzrDirFormat6())
 
2046
__default_format = BzrDirMetaFormat1()
 
2047
BzrDirFormat.register_format(__default_format)
 
2048
BzrDirFormat._default_format = __default_format
 
2049
 
 
2050
 
 
2051
class Converter(object):
 
2052
    """Converts a disk format object from one format to another."""
 
2053
 
 
2054
    def convert(self, to_convert, pb):
 
2055
        """Perform the conversion of to_convert, giving feedback via pb.
 
2056
 
 
2057
        :param to_convert: The disk object to convert.
 
2058
        :param pb: a progress bar to use for progress information.
 
2059
        """
 
2060
 
 
2061
    def step(self, message):
 
2062
        """Update the pb by a step."""
 
2063
        self.count +=1
 
2064
        self.pb.update(message, self.count, self.total)
 
2065
 
 
2066
 
 
2067
class ConvertBzrDir4To5(Converter):
 
2068
    """Converts format 4 bzr dirs to format 5."""
 
2069
 
 
2070
    def __init__(self):
 
2071
        super(ConvertBzrDir4To5, self).__init__()
 
2072
        self.converted_revs = set()
 
2073
        self.absent_revisions = set()
 
2074
        self.text_count = 0
 
2075
        self.revisions = {}
 
2076
        
 
2077
    def convert(self, to_convert, pb):
 
2078
        """See Converter.convert()."""
 
2079
        self.bzrdir = to_convert
 
2080
        self.pb = pb
 
2081
        self.pb.note('starting upgrade from format 4 to 5')
 
2082
        if isinstance(self.bzrdir.transport, LocalTransport):
 
2083
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2084
        self._convert_to_weaves()
 
2085
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2086
 
 
2087
    def _convert_to_weaves(self):
 
2088
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
2089
        try:
 
2090
            # TODO permissions
 
2091
            stat = self.bzrdir.transport.stat('weaves')
 
2092
            if not S_ISDIR(stat.st_mode):
 
2093
                self.bzrdir.transport.delete('weaves')
 
2094
                self.bzrdir.transport.mkdir('weaves')
 
2095
        except errors.NoSuchFile:
 
2096
            self.bzrdir.transport.mkdir('weaves')
 
2097
        # deliberately not a WeaveFile as we want to build it up slowly.
 
2098
        self.inv_weave = Weave('inventory')
 
2099
        # holds in-memory weaves for all files
 
2100
        self.text_weaves = {}
 
2101
        self.bzrdir.transport.delete('branch-format')
 
2102
        self.branch = self.bzrdir.open_branch()
 
2103
        self._convert_working_inv()
 
2104
        rev_history = self.branch.revision_history()
 
2105
        # to_read is a stack holding the revisions we still need to process;
 
2106
        # appending to it adds new highest-priority revisions
 
2107
        self.known_revisions = set(rev_history)
 
2108
        self.to_read = rev_history[-1:]
 
2109
        while self.to_read:
 
2110
            rev_id = self.to_read.pop()
 
2111
            if (rev_id not in self.revisions
 
2112
                and rev_id not in self.absent_revisions):
 
2113
                self._load_one_rev(rev_id)
 
2114
        self.pb.clear()
 
2115
        to_import = self._make_order()
 
2116
        for i, rev_id in enumerate(to_import):
 
2117
            self.pb.update('converting revision', i, len(to_import))
 
2118
            self._convert_one_rev(rev_id)
 
2119
        self.pb.clear()
 
2120
        self._write_all_weaves()
 
2121
        self._write_all_revs()
 
2122
        self.pb.note('upgraded to weaves:')
 
2123
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
 
2124
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
 
2125
        self.pb.note('  %6d texts', self.text_count)
 
2126
        self._cleanup_spare_files_after_format4()
 
2127
        self.branch._transport.put_bytes(
 
2128
            'branch-format',
 
2129
            BzrDirFormat5().get_format_string(),
 
2130
            mode=self.bzrdir._get_file_mode())
 
2131
 
 
2132
    def _cleanup_spare_files_after_format4(self):
 
2133
        # FIXME working tree upgrade foo.
 
2134
        for n in 'merged-patches', 'pending-merged-patches':
 
2135
            try:
 
2136
                ## assert os.path.getsize(p) == 0
 
2137
                self.bzrdir.transport.delete(n)
 
2138
            except errors.NoSuchFile:
 
2139
                pass
 
2140
        self.bzrdir.transport.delete_tree('inventory-store')
 
2141
        self.bzrdir.transport.delete_tree('text-store')
 
2142
 
 
2143
    def _convert_working_inv(self):
 
2144
        inv = xml4.serializer_v4.read_inventory(
 
2145
                self.branch._transport.get('inventory'))
 
2146
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
2147
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
2148
            mode=self.bzrdir._get_file_mode())
 
2149
 
 
2150
    def _write_all_weaves(self):
 
2151
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
2152
        weave_transport = self.bzrdir.transport.clone('weaves')
 
2153
        weaves = WeaveStore(weave_transport, prefixed=False)
 
2154
        transaction = WriteTransaction()
 
2155
 
 
2156
        try:
 
2157
            i = 0
 
2158
            for file_id, file_weave in self.text_weaves.items():
 
2159
                self.pb.update('writing weave', i, len(self.text_weaves))
 
2160
                weaves._put_weave(file_id, file_weave, transaction)
 
2161
                i += 1
 
2162
            self.pb.update('inventory', 0, 1)
 
2163
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
2164
            self.pb.update('inventory', 1, 1)
 
2165
        finally:
 
2166
            self.pb.clear()
 
2167
 
 
2168
    def _write_all_revs(self):
 
2169
        """Write all revisions out in new form."""
 
2170
        self.bzrdir.transport.delete_tree('revision-store')
 
2171
        self.bzrdir.transport.mkdir('revision-store')
 
2172
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
2173
        # TODO permissions
 
2174
        from bzrlib.xml5 import serializer_v5
 
2175
        from bzrlib.repofmt.weaverepo import RevisionTextStore
 
2176
        revision_store = RevisionTextStore(revision_transport,
 
2177
            serializer_v5, False, versionedfile.PrefixMapper(),
 
2178
            lambda:True, lambda:True)
 
2179
        try:
 
2180
            for i, rev_id in enumerate(self.converted_revs):
 
2181
                self.pb.update('write revision', i, len(self.converted_revs))
 
2182
                text = serializer_v5.write_revision_to_string(
 
2183
                    self.revisions[rev_id])
 
2184
                key = (rev_id,)
 
2185
                revision_store.add_lines(key, None, osutils.split_lines(text))
 
2186
        finally:
 
2187
            self.pb.clear()
 
2188
            
 
2189
    def _load_one_rev(self, rev_id):
 
2190
        """Load a revision object into memory.
 
2191
 
 
2192
        Any parents not either loaded or abandoned get queued to be
 
2193
        loaded."""
 
2194
        self.pb.update('loading revision',
 
2195
                       len(self.revisions),
 
2196
                       len(self.known_revisions))
 
2197
        if not self.branch.repository.has_revision(rev_id):
 
2198
            self.pb.clear()
 
2199
            self.pb.note('revision {%s} not present in branch; '
 
2200
                         'will be converted as a ghost',
 
2201
                         rev_id)
 
2202
            self.absent_revisions.add(rev_id)
 
2203
        else:
 
2204
            rev = self.branch.repository.get_revision(rev_id)
 
2205
            for parent_id in rev.parent_ids:
 
2206
                self.known_revisions.add(parent_id)
 
2207
                self.to_read.append(parent_id)
 
2208
            self.revisions[rev_id] = rev
 
2209
 
 
2210
    def _load_old_inventory(self, rev_id):
 
2211
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
2212
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
2213
        inv.revision_id = rev_id
 
2214
        rev = self.revisions[rev_id]
 
2215
        return inv
 
2216
 
 
2217
    def _load_updated_inventory(self, rev_id):
 
2218
        inv_xml = self.inv_weave.get_text(rev_id)
 
2219
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
 
2220
        return inv
 
2221
 
 
2222
    def _convert_one_rev(self, rev_id):
 
2223
        """Convert revision and all referenced objects to new format."""
 
2224
        rev = self.revisions[rev_id]
 
2225
        inv = self._load_old_inventory(rev_id)
 
2226
        present_parents = [p for p in rev.parent_ids
 
2227
                           if p not in self.absent_revisions]
 
2228
        self._convert_revision_contents(rev, inv, present_parents)
 
2229
        self._store_new_inv(rev, inv, present_parents)
 
2230
        self.converted_revs.add(rev_id)
 
2231
 
 
2232
    def _store_new_inv(self, rev, inv, present_parents):
 
2233
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
2234
        new_inv_sha1 = sha_string(new_inv_xml)
 
2235
        self.inv_weave.add_lines(rev.revision_id,
 
2236
                                 present_parents,
 
2237
                                 new_inv_xml.splitlines(True))
 
2238
        rev.inventory_sha1 = new_inv_sha1
 
2239
 
 
2240
    def _convert_revision_contents(self, rev, inv, present_parents):
 
2241
        """Convert all the files within a revision.
 
2242
 
 
2243
        Also upgrade the inventory to refer to the text revision ids."""
 
2244
        rev_id = rev.revision_id
 
2245
        mutter('converting texts of revision {%s}',
 
2246
               rev_id)
 
2247
        parent_invs = map(self._load_updated_inventory, present_parents)
 
2248
        entries = inv.iter_entries()
 
2249
        entries.next()
 
2250
        for path, ie in entries:
 
2251
            self._convert_file_version(rev, ie, parent_invs)
 
2252
 
 
2253
    def _convert_file_version(self, rev, ie, parent_invs):
 
2254
        """Convert one version of one file.
 
2255
 
 
2256
        The file needs to be added into the weave if it is a merge
 
2257
        of >=2 parents or if it's changed from its parent.
 
2258
        """
 
2259
        file_id = ie.file_id
 
2260
        rev_id = rev.revision_id
 
2261
        w = self.text_weaves.get(file_id)
 
2262
        if w is None:
 
2263
            w = Weave(file_id)
 
2264
            self.text_weaves[file_id] = w
 
2265
        text_changed = False
 
2266
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
2267
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
2268
        # XXX: Note that this is unordered - and this is tolerable because 
 
2269
        # the previous code was also unordered.
 
2270
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
2271
            in heads)
 
2272
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
2273
        del ie.text_id
 
2274
 
 
2275
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
 
2276
    def get_parents(self, revision_ids):
 
2277
        for revision_id in revision_ids:
 
2278
            yield self.revisions[revision_id].parent_ids
 
2279
 
 
2280
    def get_parent_map(self, revision_ids):
 
2281
        """See graph._StackedParentsProvider.get_parent_map"""
 
2282
        return dict((revision_id, self.revisions[revision_id])
 
2283
                    for revision_id in revision_ids
 
2284
                     if revision_id in self.revisions)
 
2285
 
 
2286
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
2287
        # TODO: convert this logic, which is ~= snapshot to
 
2288
        # a call to:. This needs the path figured out. rather than a work_tree
 
2289
        # a v4 revision_tree can be given, or something that looks enough like
 
2290
        # one to give the file content to the entry if it needs it.
 
2291
        # and we need something that looks like a weave store for snapshot to 
 
2292
        # save against.
 
2293
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
2294
        if len(previous_revisions) == 1:
 
2295
            previous_ie = previous_revisions.values()[0]
 
2296
            if ie._unchanged(previous_ie):
 
2297
                ie.revision = previous_ie.revision
 
2298
                return
 
2299
        if ie.has_text():
 
2300
            text = self.branch.repository._text_store.get(ie.text_id)
 
2301
            file_lines = text.readlines()
 
2302
            w.add_lines(rev_id, previous_revisions, file_lines)
 
2303
            self.text_count += 1
 
2304
        else:
 
2305
            w.add_lines(rev_id, previous_revisions, [])
 
2306
        ie.revision = rev_id
 
2307
 
 
2308
    def _make_order(self):
 
2309
        """Return a suitable order for importing revisions.
 
2310
 
 
2311
        The order must be such that an revision is imported after all
 
2312
        its (present) parents.
 
2313
        """
 
2314
        todo = set(self.revisions.keys())
 
2315
        done = self.absent_revisions.copy()
 
2316
        order = []
 
2317
        while todo:
 
2318
            # scan through looking for a revision whose parents
 
2319
            # are all done
 
2320
            for rev_id in sorted(list(todo)):
 
2321
                rev = self.revisions[rev_id]
 
2322
                parent_ids = set(rev.parent_ids)
 
2323
                if parent_ids.issubset(done):
 
2324
                    # can take this one now
 
2325
                    order.append(rev_id)
 
2326
                    todo.remove(rev_id)
 
2327
                    done.add(rev_id)
 
2328
        return order
 
2329
 
 
2330
 
 
2331
class ConvertBzrDir5To6(Converter):
 
2332
    """Converts format 5 bzr dirs to format 6."""
 
2333
 
 
2334
    def convert(self, to_convert, pb):
 
2335
        """See Converter.convert()."""
 
2336
        self.bzrdir = to_convert
 
2337
        self.pb = pb
 
2338
        self.pb.note('starting upgrade from format 5 to 6')
 
2339
        self._convert_to_prefixed()
 
2340
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2341
 
 
2342
    def _convert_to_prefixed(self):
 
2343
        from bzrlib.store import TransportStore
 
2344
        self.bzrdir.transport.delete('branch-format')
 
2345
        for store_name in ["weaves", "revision-store"]:
 
2346
            self.pb.note("adding prefixes to %s" % store_name)
 
2347
            store_transport = self.bzrdir.transport.clone(store_name)
 
2348
            store = TransportStore(store_transport, prefixed=True)
 
2349
            for urlfilename in store_transport.list_dir('.'):
 
2350
                filename = urlutils.unescape(urlfilename)
 
2351
                if (filename.endswith(".weave") or
 
2352
                    filename.endswith(".gz") or
 
2353
                    filename.endswith(".sig")):
 
2354
                    file_id, suffix = os.path.splitext(filename)
 
2355
                else:
 
2356
                    file_id = filename
 
2357
                    suffix = ''
 
2358
                new_name = store._mapper.map((file_id,)) + suffix
 
2359
                # FIXME keep track of the dirs made RBC 20060121
 
2360
                try:
 
2361
                    store_transport.move(filename, new_name)
 
2362
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
2363
                    store_transport.mkdir(osutils.dirname(new_name))
 
2364
                    store_transport.move(filename, new_name)
 
2365
        self.bzrdir.transport.put_bytes(
 
2366
            'branch-format',
 
2367
            BzrDirFormat6().get_format_string(),
 
2368
            mode=self.bzrdir._get_file_mode())
 
2369
 
 
2370
 
 
2371
class ConvertBzrDir6ToMeta(Converter):
 
2372
    """Converts format 6 bzr dirs to metadirs."""
 
2373
 
 
2374
    def convert(self, to_convert, pb):
 
2375
        """See Converter.convert()."""
 
2376
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2377
        from bzrlib.branch import BzrBranchFormat5
 
2378
        self.bzrdir = to_convert
 
2379
        self.pb = pb
 
2380
        self.count = 0
 
2381
        self.total = 20 # the steps we know about
 
2382
        self.garbage_inventories = []
 
2383
        self.dir_mode = self.bzrdir._get_dir_mode()
 
2384
        self.file_mode = self.bzrdir._get_file_mode()
 
2385
 
 
2386
        self.pb.note('starting upgrade from format 6 to metadir')
 
2387
        self.bzrdir.transport.put_bytes(
 
2388
                'branch-format',
 
2389
                "Converting to format 6",
 
2390
                mode=self.file_mode)
 
2391
        # its faster to move specific files around than to open and use the apis...
 
2392
        # first off, nuke ancestry.weave, it was never used.
 
2393
        try:
 
2394
            self.step('Removing ancestry.weave')
 
2395
            self.bzrdir.transport.delete('ancestry.weave')
 
2396
        except errors.NoSuchFile:
 
2397
            pass
 
2398
        # find out whats there
 
2399
        self.step('Finding branch files')
 
2400
        last_revision = self.bzrdir.open_branch().last_revision()
 
2401
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
2402
        for name in bzrcontents:
 
2403
            if name.startswith('basis-inventory.'):
 
2404
                self.garbage_inventories.append(name)
 
2405
        # create new directories for repository, working tree and branch
 
2406
        repository_names = [('inventory.weave', True),
 
2407
                            ('revision-store', True),
 
2408
                            ('weaves', True)]
 
2409
        self.step('Upgrading repository  ')
 
2410
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
2411
        self.make_lock('repository')
 
2412
        # we hard code the formats here because we are converting into
 
2413
        # the meta format. The meta format upgrader can take this to a 
 
2414
        # future format within each component.
 
2415
        self.put_format('repository', RepositoryFormat7())
 
2416
        for entry in repository_names:
 
2417
            self.move_entry('repository', entry)
 
2418
 
 
2419
        self.step('Upgrading branch      ')
 
2420
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
2421
        self.make_lock('branch')
 
2422
        self.put_format('branch', BzrBranchFormat5())
 
2423
        branch_files = [('revision-history', True),
 
2424
                        ('branch-name', True),
 
2425
                        ('parent', False)]
 
2426
        for entry in branch_files:
 
2427
            self.move_entry('branch', entry)
 
2428
 
 
2429
        checkout_files = [('pending-merges', True),
 
2430
                          ('inventory', True),
 
2431
                          ('stat-cache', False)]
 
2432
        # If a mandatory checkout file is not present, the branch does not have
 
2433
        # a functional checkout. Do not create a checkout in the converted
 
2434
        # branch.
 
2435
        for name, mandatory in checkout_files:
 
2436
            if mandatory and name not in bzrcontents:
 
2437
                has_checkout = False
 
2438
                break
 
2439
        else:
 
2440
            has_checkout = True
 
2441
        if not has_checkout:
 
2442
            self.pb.note('No working tree.')
 
2443
            # If some checkout files are there, we may as well get rid of them.
 
2444
            for name, mandatory in checkout_files:
 
2445
                if name in bzrcontents:
 
2446
                    self.bzrdir.transport.delete(name)
 
2447
        else:
 
2448
            from bzrlib.workingtree import WorkingTreeFormat3
 
2449
            self.step('Upgrading working tree')
 
2450
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
2451
            self.make_lock('checkout')
 
2452
            self.put_format(
 
2453
                'checkout', WorkingTreeFormat3())
 
2454
            self.bzrdir.transport.delete_multi(
 
2455
                self.garbage_inventories, self.pb)
 
2456
            for entry in checkout_files:
 
2457
                self.move_entry('checkout', entry)
 
2458
            if last_revision is not None:
 
2459
                self.bzrdir.transport.put_bytes(
 
2460
                    'checkout/last-revision', last_revision)
 
2461
        self.bzrdir.transport.put_bytes(
 
2462
            'branch-format',
 
2463
            BzrDirMetaFormat1().get_format_string(),
 
2464
            mode=self.file_mode)
 
2465
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2466
 
 
2467
    def make_lock(self, name):
 
2468
        """Make a lock for the new control dir name."""
 
2469
        self.step('Make %s lock' % name)
 
2470
        ld = lockdir.LockDir(self.bzrdir.transport,
 
2471
                             '%s/lock' % name,
 
2472
                             file_modebits=self.file_mode,
 
2473
                             dir_modebits=self.dir_mode)
 
2474
        ld.create()
 
2475
 
 
2476
    def move_entry(self, new_dir, entry):
 
2477
        """Move then entry name into new_dir."""
 
2478
        name = entry[0]
 
2479
        mandatory = entry[1]
 
2480
        self.step('Moving %s' % name)
 
2481
        try:
 
2482
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
2483
        except errors.NoSuchFile:
 
2484
            if mandatory:
 
2485
                raise
 
2486
 
 
2487
    def put_format(self, dirname, format):
 
2488
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
2489
            format.get_format_string(),
 
2490
            self.file_mode)
 
2491
 
 
2492
 
 
2493
class ConvertMetaToMeta(Converter):
 
2494
    """Converts the components of metadirs."""
 
2495
 
 
2496
    def __init__(self, target_format):
 
2497
        """Create a metadir to metadir converter.
 
2498
 
 
2499
        :param target_format: The final metadir format that is desired.
 
2500
        """
 
2501
        self.target_format = target_format
 
2502
 
 
2503
    def convert(self, to_convert, pb):
 
2504
        """See Converter.convert()."""
 
2505
        self.bzrdir = to_convert
 
2506
        self.pb = pb
 
2507
        self.count = 0
 
2508
        self.total = 1
 
2509
        self.step('checking repository format')
 
2510
        try:
 
2511
            repo = self.bzrdir.open_repository()
 
2512
        except errors.NoRepositoryPresent:
 
2513
            pass
 
2514
        else:
 
2515
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
 
2516
                from bzrlib.repository import CopyConverter
 
2517
                self.pb.note('starting repository conversion')
 
2518
                converter = CopyConverter(self.target_format.repository_format)
 
2519
                converter.convert(repo, pb)
 
2520
        try:
 
2521
            branch = self.bzrdir.open_branch()
 
2522
        except errors.NotBranchError:
 
2523
            pass
 
2524
        else:
 
2525
            # TODO: conversions of Branch and Tree should be done by
 
2526
            # InterXFormat lookups/some sort of registry.
 
2527
            # Avoid circular imports
 
2528
            from bzrlib import branch as _mod_branch
 
2529
            old = branch._format.__class__
 
2530
            new = self.target_format.get_branch_format().__class__
 
2531
            while old != new:
 
2532
                if (old == _mod_branch.BzrBranchFormat5 and
 
2533
                    new in (_mod_branch.BzrBranchFormat6,
 
2534
                        _mod_branch.BzrBranchFormat7)):
 
2535
                    branch_converter = _mod_branch.Converter5to6()
 
2536
                elif (old == _mod_branch.BzrBranchFormat6 and
 
2537
                    new == _mod_branch.BzrBranchFormat7):
 
2538
                    branch_converter = _mod_branch.Converter6to7()
 
2539
                else:
 
2540
                    raise errors.BadConversionTarget("No converter", new)
 
2541
                branch_converter.convert(branch)
 
2542
                branch = self.bzrdir.open_branch()
 
2543
                old = branch._format.__class__
 
2544
        try:
 
2545
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
 
2546
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2547
            pass
 
2548
        else:
 
2549
            # TODO: conversions of Branch and Tree should be done by
 
2550
            # InterXFormat lookups
 
2551
            if (isinstance(tree, workingtree.WorkingTree3) and
 
2552
                not isinstance(tree, workingtree_4.WorkingTree4) and
 
2553
                isinstance(self.target_format.workingtree_format,
 
2554
                    workingtree_4.WorkingTreeFormat4)):
 
2555
                workingtree_4.Converter3to4().convert(tree)
 
2556
            if (isinstance(tree, workingtree_4.WorkingTree4) and
 
2557
                not isinstance(tree, workingtree_5.WorkingTree5) and
 
2558
                isinstance(self.target_format.workingtree_format,
 
2559
                    workingtree_5.WorkingTreeFormat5)):
 
2560
                workingtree_5.Converter4to5().convert(tree)
 
2561
        return to_convert
 
2562
 
 
2563
 
 
2564
# This is not in remote.py because it's small, and needs to be registered.
 
2565
# Putting it in remote.py creates a circular import problem.
 
2566
# we can make it a lazy object if the control formats is turned into something
 
2567
# like a registry.
 
2568
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
2569
    """Format representing bzrdirs accessed via a smart server"""
 
2570
 
 
2571
    def get_format_description(self):
 
2572
        return 'bzr remote bzrdir'
 
2573
    
 
2574
    @classmethod
 
2575
    def probe_transport(klass, transport):
 
2576
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
2577
        try:
 
2578
            medium = transport.get_smart_medium()
 
2579
        except (NotImplementedError, AttributeError,
 
2580
                errors.TransportNotPossible, errors.NoSmartMedium,
 
2581
                errors.SmartProtocolError):
 
2582
            # no smart server, so not a branch for this format type.
 
2583
            raise errors.NotBranchError(path=transport.base)
 
2584
        else:
 
2585
            # Decline to open it if the server doesn't support our required
 
2586
            # version (3) so that the VFS-based transport will do it.
 
2587
            if medium.should_probe():
 
2588
                try:
 
2589
                    server_version = medium.protocol_version()
 
2590
                except errors.SmartProtocolError:
 
2591
                    # Apparently there's no usable smart server there, even though
 
2592
                    # the medium supports the smart protocol.
 
2593
                    raise errors.NotBranchError(path=transport.base)
 
2594
                if server_version != '2':
 
2595
                    raise errors.NotBranchError(path=transport.base)
 
2596
            return klass()
 
2597
 
 
2598
    def initialize_on_transport(self, transport):
 
2599
        try:
 
2600
            # hand off the request to the smart server
 
2601
            client_medium = transport.get_smart_medium()
 
2602
        except errors.NoSmartMedium:
 
2603
            # TODO: lookup the local format from a server hint.
 
2604
            local_dir_format = BzrDirMetaFormat1()
 
2605
            return local_dir_format.initialize_on_transport(transport)
 
2606
        client = _SmartClient(client_medium)
 
2607
        path = client.remote_path_from_transport(transport)
 
2608
        response = client.call('BzrDirFormat.initialize', path)
 
2609
        if response[0] != 'ok':
 
2610
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
2611
        return remote.RemoteBzrDir(transport)
 
2612
 
 
2613
    def _open(self, transport):
 
2614
        return remote.RemoteBzrDir(transport)
 
2615
 
 
2616
    def __eq__(self, other):
 
2617
        if not isinstance(other, RemoteBzrDirFormat):
 
2618
            return False
 
2619
        return self.get_format_description() == other.get_format_description()
 
2620
 
 
2621
 
 
2622
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
2623
 
 
2624
 
 
2625
class BzrDirFormatInfo(object):
 
2626
 
 
2627
    def __init__(self, native, deprecated, hidden, experimental):
 
2628
        self.deprecated = deprecated
 
2629
        self.native = native
 
2630
        self.hidden = hidden
 
2631
        self.experimental = experimental
 
2632
 
 
2633
 
 
2634
class BzrDirFormatRegistry(registry.Registry):
 
2635
    """Registry of user-selectable BzrDir subformats.
 
2636
    
 
2637
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
2638
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
2639
    """
 
2640
 
 
2641
    def __init__(self):
 
2642
        """Create a BzrDirFormatRegistry."""
 
2643
        self._aliases = set()
 
2644
        super(BzrDirFormatRegistry, self).__init__()
 
2645
 
 
2646
    def aliases(self):
 
2647
        """Return a set of the format names which are aliases."""
 
2648
        return frozenset(self._aliases)
 
2649
 
 
2650
    def register_metadir(self, key,
 
2651
             repository_format, help, native=True, deprecated=False,
 
2652
             branch_format=None,
 
2653
             tree_format=None,
 
2654
             hidden=False,
 
2655
             experimental=False,
 
2656
             alias=False):
 
2657
        """Register a metadir subformat.
 
2658
 
 
2659
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
2660
        by the Repository format.
 
2661
 
 
2662
        :param repository_format: The fully-qualified repository format class
 
2663
            name as a string.
 
2664
        :param branch_format: Fully-qualified branch format class name as
 
2665
            a string.
 
2666
        :param tree_format: Fully-qualified tree format class name as
 
2667
            a string.
 
2668
        """
 
2669
        # This should be expanded to support setting WorkingTree and Branch
 
2670
        # formats, once BzrDirMetaFormat1 supports that.
 
2671
        def _load(full_name):
 
2672
            mod_name, factory_name = full_name.rsplit('.', 1)
 
2673
            try:
 
2674
                mod = __import__(mod_name, globals(), locals(),
 
2675
                        [factory_name])
 
2676
            except ImportError, e:
 
2677
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
2678
            try:
 
2679
                factory = getattr(mod, factory_name)
 
2680
            except AttributeError:
 
2681
                raise AttributeError('no factory %s in module %r'
 
2682
                    % (full_name, mod))
 
2683
            return factory()
 
2684
 
 
2685
        def helper():
 
2686
            bd = BzrDirMetaFormat1()
 
2687
            if branch_format is not None:
 
2688
                bd.set_branch_format(_load(branch_format))
 
2689
            if tree_format is not None:
 
2690
                bd.workingtree_format = _load(tree_format)
 
2691
            if repository_format is not None:
 
2692
                bd.repository_format = _load(repository_format)
 
2693
            return bd
 
2694
        self.register(key, helper, help, native, deprecated, hidden,
 
2695
            experimental, alias)
 
2696
 
 
2697
    def register(self, key, factory, help, native=True, deprecated=False,
 
2698
                 hidden=False, experimental=False, alias=False):
 
2699
        """Register a BzrDirFormat factory.
 
2700
        
 
2701
        The factory must be a callable that takes one parameter: the key.
 
2702
        It must produce an instance of the BzrDirFormat when called.
 
2703
 
 
2704
        This function mainly exists to prevent the info object from being
 
2705
        supplied directly.
 
2706
        """
 
2707
        registry.Registry.register(self, key, factory, help,
 
2708
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
2709
        if alias:
 
2710
            self._aliases.add(key)
 
2711
 
 
2712
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
2713
        deprecated=False, hidden=False, experimental=False, alias=False):
 
2714
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
2715
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
2716
        if alias:
 
2717
            self._aliases.add(key)
 
2718
 
 
2719
    def set_default(self, key):
 
2720
        """Set the 'default' key to be a clone of the supplied key.
 
2721
        
 
2722
        This method must be called once and only once.
 
2723
        """
 
2724
        registry.Registry.register(self, 'default', self.get(key),
 
2725
            self.get_help(key), info=self.get_info(key))
 
2726
        self._aliases.add('default')
 
2727
 
 
2728
    def set_default_repository(self, key):
 
2729
        """Set the FormatRegistry default and Repository default.
 
2730
        
 
2731
        This is a transitional method while Repository.set_default_format
 
2732
        is deprecated.
 
2733
        """
 
2734
        if 'default' in self:
 
2735
            self.remove('default')
 
2736
        self.set_default(key)
 
2737
        format = self.get('default')()
 
2738
 
 
2739
    def make_bzrdir(self, key):
 
2740
        return self.get(key)()
 
2741
 
 
2742
    def help_topic(self, topic):
 
2743
        output = textwrap.dedent("""\
 
2744
            These formats can be used for creating branches, working trees, and
 
2745
            repositories.
 
2746
 
 
2747
            """)
 
2748
        default_realkey = None
 
2749
        default_help = self.get_help('default')
 
2750
        help_pairs = []
 
2751
        for key in self.keys():
 
2752
            if key == 'default':
 
2753
                continue
 
2754
            help = self.get_help(key)
 
2755
            if help == default_help:
 
2756
                default_realkey = key
 
2757
            else:
 
2758
                help_pairs.append((key, help))
 
2759
 
 
2760
        def wrapped(key, help, info):
 
2761
            if info.native:
 
2762
                help = '(native) ' + help
 
2763
            return ':%s:\n%s\n\n' % (key, 
 
2764
                    textwrap.fill(help, initial_indent='    ', 
 
2765
                    subsequent_indent='    '))
 
2766
        if default_realkey is not None:
 
2767
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
2768
                              self.get_info('default'))
 
2769
        deprecated_pairs = []
 
2770
        experimental_pairs = []
 
2771
        for key, help in help_pairs:
 
2772
            info = self.get_info(key)
 
2773
            if info.hidden:
 
2774
                continue
 
2775
            elif info.deprecated:
 
2776
                deprecated_pairs.append((key, help))
 
2777
            elif info.experimental:
 
2778
                experimental_pairs.append((key, help))
 
2779
            else:
 
2780
                output += wrapped(key, help, info)
 
2781
        if len(experimental_pairs) > 0:
 
2782
            output += "Experimental formats are shown below.\n\n"
 
2783
            for key, help in experimental_pairs:
 
2784
                info = self.get_info(key)
 
2785
                output += wrapped(key, help, info)
 
2786
        if len(deprecated_pairs) > 0:
 
2787
            output += "Deprecated formats are shown below.\n\n"
 
2788
            for key, help in deprecated_pairs:
 
2789
                info = self.get_info(key)
 
2790
                output += wrapped(key, help, info)
 
2791
 
 
2792
        return output
 
2793
 
 
2794
 
 
2795
class RepositoryAcquisitionPolicy(object):
 
2796
    """Abstract base class for repository acquisition policies.
 
2797
 
 
2798
    A repository acquisition policy decides how a BzrDir acquires a repository
 
2799
    for a branch that is being created.  The most basic policy decision is
 
2800
    whether to create a new repository or use an existing one.
 
2801
    """
 
2802
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
 
2803
        """Constructor.
 
2804
 
 
2805
        :param stack_on: A location to stack on
 
2806
        :param stack_on_pwd: If stack_on is relative, the location it is
 
2807
            relative to.
 
2808
        :param require_stacking: If True, it is a failure to not stack.
 
2809
        """
 
2810
        self._stack_on = stack_on
 
2811
        self._stack_on_pwd = stack_on_pwd
 
2812
        self._require_stacking = require_stacking
 
2813
 
 
2814
    def configure_branch(self, branch):
 
2815
        """Apply any configuration data from this policy to the branch.
 
2816
 
 
2817
        Default implementation sets repository stacking.
 
2818
        """
 
2819
        if self._stack_on is None:
 
2820
            return
 
2821
        if self._stack_on_pwd is None:
 
2822
            stack_on = self._stack_on
 
2823
        else:
 
2824
            try:
 
2825
                stack_on = urlutils.rebase_url(self._stack_on,
 
2826
                    self._stack_on_pwd,
 
2827
                    branch.bzrdir.root_transport.base)
 
2828
            except errors.InvalidRebaseURLs:
 
2829
                stack_on = self._get_full_stack_on()
 
2830
        try:
 
2831
            branch.set_stacked_on_url(stack_on)
 
2832
        except errors.UnstackableBranchFormat:
 
2833
            if self._require_stacking:
 
2834
                raise
 
2835
 
 
2836
    def _get_full_stack_on(self):
 
2837
        """Get a fully-qualified URL for the stack_on location."""
 
2838
        if self._stack_on is None:
 
2839
            return None
 
2840
        if self._stack_on_pwd is None:
 
2841
            return self._stack_on
 
2842
        else:
 
2843
            return urlutils.join(self._stack_on_pwd, self._stack_on)
 
2844
 
 
2845
    def _add_fallback(self, repository):
 
2846
        """Add a fallback to the supplied repository, if stacking is set."""
 
2847
        stack_on = self._get_full_stack_on()
 
2848
        if stack_on is None:
 
2849
            return
 
2850
        stacked_dir = BzrDir.open(stack_on)
 
2851
        try:
 
2852
            stacked_repo = stacked_dir.open_branch().repository
 
2853
        except errors.NotBranchError:
 
2854
            stacked_repo = stacked_dir.open_repository()
 
2855
        try:
 
2856
            repository.add_fallback_repository(stacked_repo)
 
2857
        except errors.UnstackableRepositoryFormat:
 
2858
            if self._require_stacking:
 
2859
                raise
 
2860
 
 
2861
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2862
        """Acquire a repository for this bzrdir.
 
2863
 
 
2864
        Implementations may create a new repository or use a pre-exising
 
2865
        repository.
 
2866
        :param make_working_trees: If creating a repository, set
 
2867
            make_working_trees to this value (if non-None)
 
2868
        :param shared: If creating a repository, make it shared if True
 
2869
        :return: A repository
 
2870
        """
 
2871
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
 
2872
 
 
2873
 
 
2874
class CreateRepository(RepositoryAcquisitionPolicy):
 
2875
    """A policy of creating a new repository"""
 
2876
 
 
2877
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
 
2878
                 require_stacking=False):
 
2879
        """
 
2880
        Constructor.
 
2881
        :param bzrdir: The bzrdir to create the repository on.
 
2882
        :param stack_on: A location to stack on
 
2883
        :param stack_on_pwd: If stack_on is relative, the location it is
 
2884
            relative to.
 
2885
        """
 
2886
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
 
2887
                                             require_stacking)
 
2888
        self._bzrdir = bzrdir
 
2889
 
 
2890
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2891
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
2892
 
 
2893
        Creates the desired repository in the bzrdir we already have.
 
2894
        """
 
2895
        if self._stack_on or self._require_stacking:
 
2896
            # we may be coming from a format that doesn't support stacking,
 
2897
            # but we require it in the destination, so force creation of a new
 
2898
            # one here.
 
2899
            #
 
2900
            # TODO: perhaps this should be treated as a distinct repository
 
2901
            # acquisition policy?
 
2902
            repository_format = self._bzrdir._format.repository_format
 
2903
            if not repository_format.supports_external_lookups:
 
2904
                # should possibly be controlled by the registry rather than
 
2905
                # hardcoded here.
 
2906
                from bzrlib.repofmt import pack_repo
 
2907
                if repository_format.rich_root_data:
 
2908
                    repository_format = \
 
2909
                        pack_repo.RepositoryFormatKnitPack5RichRoot()
 
2910
                else:
 
2911
                    repository_format = pack_repo.RepositoryFormatKnitPack5()
 
2912
                note("using %r for stacking" % (repository_format,))
 
2913
            repository = repository_format.initialize(self._bzrdir,
 
2914
                shared=shared)
 
2915
        else:
 
2916
            # let bzrdir choose
 
2917
            repository = self._bzrdir.create_repository(shared=shared)
 
2918
        self._add_fallback(repository)
 
2919
        if make_working_trees is not None:
 
2920
            repository.set_make_working_trees(make_working_trees)
 
2921
        return repository
 
2922
 
 
2923
 
 
2924
class UseExistingRepository(RepositoryAcquisitionPolicy):
 
2925
    """A policy of reusing an existing repository"""
 
2926
 
 
2927
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
 
2928
                 require_stacking=False):
 
2929
        """Constructor.
 
2930
 
 
2931
        :param repository: The repository to use.
 
2932
        :param stack_on: A location to stack on
 
2933
        :param stack_on_pwd: If stack_on is relative, the location it is
 
2934
            relative to.
 
2935
        """
 
2936
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
 
2937
                                             require_stacking)
 
2938
        self._repository = repository
 
2939
 
 
2940
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2941
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
2942
 
 
2943
        Returns an existing repository to use
 
2944
        """
 
2945
        self._add_fallback(self._repository)
 
2946
        return self._repository
 
2947
 
 
2948
 
 
2949
format_registry = BzrDirFormatRegistry()
 
2950
format_registry.register('weave', BzrDirFormat6,
 
2951
    'Pre-0.8 format.  Slower than knit and does not'
 
2952
    ' support checkouts or shared repositories.',
 
2953
    deprecated=True)
 
2954
format_registry.register_metadir('knit',
 
2955
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2956
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
 
2957
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2958
    tree_format='bzrlib.workingtree.WorkingTreeFormat3')
 
2959
format_registry.register_metadir('metaweave',
 
2960
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
2961
    'Transitional format in 0.8.  Slower than knit.',
 
2962
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2963
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
2964
    deprecated=True)
 
2965
format_registry.register_metadir('dirstate',
 
2966
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2967
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
 
2968
        'above when accessed over the network.',
 
2969
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2970
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
2971
    # directly from workingtree_4 triggers a circular import.
 
2972
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2973
    )
 
2974
format_registry.register_metadir('dirstate-tags',
 
2975
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
2976
    help='New in 0.15: Fast local operations and improved scaling for '
 
2977
        'network operations. Additionally adds support for tags.'
 
2978
        ' Incompatible with bzr < 0.15.',
 
2979
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2980
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2981
    )
 
2982
format_registry.register_metadir('rich-root',
 
2983
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
 
2984
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
 
2985
        ' bzr < 1.0',
 
2986
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2987
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2988
    )
 
2989
format_registry.register_metadir('dirstate-with-subtree',
 
2990
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
 
2991
    help='New in 0.15: Fast local operations and improved scaling for '
 
2992
        'network operations. Additionally adds support for versioning nested '
 
2993
        'bzr branches. Incompatible with bzr < 0.15.',
 
2994
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
2995
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
2996
    experimental=True,
 
2997
    hidden=True,
 
2998
    )
 
2999
format_registry.register_metadir('pack-0.92',
 
3000
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
 
3001
    help='New in 0.92: Pack-based format with data compatible with '
 
3002
        'dirstate-tags format repositories. Interoperates with '
 
3003
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
3004
        'Previously called knitpack-experimental.  '
 
3005
        'For more information, see '
 
3006
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3007
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3008
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3009
    )
 
3010
format_registry.register_metadir('pack-0.92-subtree',
 
3011
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
 
3012
    help='New in 0.92: Pack-based format with data compatible with '
 
3013
        'dirstate-with-subtree format repositories. Interoperates with '
 
3014
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
3015
        'Previously called knitpack-experimental.  '
 
3016
        'For more information, see '
 
3017
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3018
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3019
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3020
    hidden=True,
 
3021
    experimental=True,
 
3022
    )
 
3023
format_registry.register_metadir('rich-root-pack',
 
3024
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
 
3025
    help='New in 1.0: Pack-based format with data compatible with '
 
3026
        'rich-root format repositories. Incompatible with'
 
3027
        ' bzr < 1.0',
 
3028
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3029
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3030
    )
 
3031
format_registry.register_metadir('1.6',
 
3032
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
 
3033
    help='A branch and pack based repository that supports stacking. ',
 
3034
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3035
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3036
    )
 
3037
format_registry.register_metadir('1.6-rich-root',
 
3038
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
 
3039
    help='A branch and pack based repository that supports stacking '
 
3040
         'and rich root data (needed for bzr-svn). ',
 
3041
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3042
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3043
    )
 
3044
# The following two formats should always just be aliases.
 
3045
format_registry.register_metadir('development',
 
3046
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1',
 
3047
    help='Current development format. Can convert data to and from pack-0.92 '
 
3048
        '(and anything compatible with pack-0.92) format repositories. '
 
3049
        'Repositories and branches in this format can only be read by bzr.dev. '
 
3050
        'Please read '
 
3051
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3052
        'before use.',
 
3053
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3054
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
 
3055
    experimental=True,
 
3056
    alias=True,
 
3057
    )
 
3058
format_registry.register_metadir('development-subtree',
 
3059
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1Subtree',
 
3060
    help='Current development format, subtree variant. Can convert data to and '
 
3061
        'from pack-0.92-subtree (and anything compatible with '
 
3062
        'pack-0.92-subtree) format repositories. Repositories and branches in '
 
3063
        'this format can only be read by bzr.dev. Please read '
 
3064
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3065
        'before use.',
 
3066
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3067
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
 
3068
    experimental=True,
 
3069
    alias=True,
 
3070
    )
 
3071
# And the development formats which the will have aliased one of follow:
 
3072
format_registry.register_metadir('development0',
 
3073
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0',
 
3074
    help='Trivial rename of pack-0.92 to provide a development format. '
 
3075
        'Please read '
 
3076
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3077
        'before use.',
 
3078
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3079
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3080
    hidden=True,
 
3081
    experimental=True,
 
3082
    )
 
3083
format_registry.register_metadir('development0-subtree',
 
3084
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment0Subtree',
 
3085
    help='Trivial rename of pack-0.92-subtree to provide a development format. '
 
3086
        'Please read '
 
3087
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3088
        'before use.',
 
3089
    branch_format='bzrlib.branch.BzrBranchFormat6',
 
3090
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3091
    hidden=True,
 
3092
    experimental=True,
 
3093
    )
 
3094
format_registry.register_metadir('development1',
 
3095
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1',
 
3096
    help='A branch and pack based repository that supports stacking. '
 
3097
        'Please read '
 
3098
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3099
        'before use.',
 
3100
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3101
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3102
    hidden=True,
 
3103
    experimental=True,
 
3104
    )
 
3105
format_registry.register_metadir('development1-subtree',
 
3106
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1Subtree',
 
3107
    help='A branch and pack based repository that supports stacking. '
 
3108
        'Please read '
 
3109
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3110
        'before use.',
 
3111
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3112
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3113
    hidden=True,
 
3114
    experimental=True,
 
3115
    )
 
3116
format_registry.register_metadir('development2',
 
3117
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1',
 
3118
    help='A format that supports stacking, filtered views and content filters. '
 
3119
        'Please read '
 
3120
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3121
        'before use.',
 
3122
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3123
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
 
3124
    hidden=True,
 
3125
    experimental=True,
 
3126
    )
 
3127
format_registry.register_metadir('development2-subtree',
 
3128
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment1Subtree',
 
3129
    help='A format that supports stacking, filtered views and content filters. '
 
3130
        'Please read '
 
3131
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3132
        'before use.',
 
3133
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3134
    tree_format='bzrlib.workingtree_5.WorkingTreeFormat5',
 
3135
    hidden=True,
 
3136
    experimental=True,
 
3137
    )
 
3138
# The current format that is made on 'bzr init'.
 
3139
format_registry.set_default('pack-0.92')