1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
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.
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.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
19
At format 7 this was split out into Branch, Repository and Checkout control
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
28
# TODO: Move old formats into a plugin to make this file smaller.
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
35
from stat import S_ISDIR
47
revision as _mod_revision,
57
from bzrlib.osutils import (
60
from bzrlib.smart.client import _SmartClient
61
from bzrlib.store.versioned import WeaveStore
62
from bzrlib.transactions import WriteTransaction
63
from bzrlib.transport import (
64
do_catching_redirections,
67
remote as remote_transport,
69
from bzrlib.weave import Weave
72
from bzrlib.trace import (
85
"""A .bzr control diretory.
87
BzrDir instances let you create or open any of the things that can be
88
found within .bzr - checkouts, branches and repositories.
91
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
93
a transport connected to the directory this bzr was opened from
94
(i.e. the parent directory holding the .bzr directory).
96
Everything in the bzrdir should have the same file permissions.
98
:cvar hooks: An instance of BzrDirHooks.
101
def break_lock(self):
102
"""Invoke break_lock on the first object in the bzrdir.
104
If there is a tree, the tree is opened and break_lock() called.
105
Otherwise, branch is tried, and finally repository.
107
# XXX: This seems more like a UI function than something that really
108
# belongs in this class.
110
thing_to_unlock = self.open_workingtree()
111
except (errors.NotLocalUrl, errors.NoWorkingTree):
113
thing_to_unlock = self.open_branch()
114
except errors.NotBranchError:
116
thing_to_unlock = self.open_repository()
117
except errors.NoRepositoryPresent:
119
thing_to_unlock.break_lock()
121
def can_convert_format(self):
122
"""Return true if this bzrdir is one whose format we can convert from."""
125
def check_conversion_target(self, target_format):
126
target_repo_format = target_format.repository_format
127
source_repo_format = self._format.repository_format
128
source_repo_format.check_conversion_target(target_repo_format)
131
def _check_supported(format, allow_unsupported,
132
recommend_upgrade=True,
134
"""Give an error or warning on old formats.
136
:param format: may be any kind of format - workingtree, branch,
139
:param allow_unsupported: If true, allow opening
140
formats that are strongly deprecated, and which may
141
have limited functionality.
143
:param recommend_upgrade: If true (default), warn
144
the user through the ui object that they may wish
145
to upgrade the object.
147
# TODO: perhaps move this into a base Format class; it's not BzrDir
148
# specific. mbp 20070323
149
if not allow_unsupported and not format.is_supported():
150
# see open_downlevel to open legacy branches.
151
raise errors.UnsupportedFormatError(format=format)
152
if recommend_upgrade \
153
and getattr(format, 'upgrade_recommended', False):
154
ui.ui_factory.recommend_upgrade(
155
format.get_format_description(),
158
def clone(self, url, revision_id=None, force_new_repo=False,
159
preserve_stacking=False):
160
"""Clone this bzrdir and its contents to url verbatim.
162
:param url: The url create the clone at. If url's last component does
163
not exist, it will be created.
164
:param revision_id: The tip revision-id to use for any branch or
165
working tree. If not None, then the clone operation may tune
166
itself to download less data.
167
:param force_new_repo: Do not use a shared repository for the target
168
even if one is available.
169
:param preserve_stacking: When cloning a stacked branch, stack the
170
new branch on top of the other branch's stacked-on branch.
172
return self.clone_on_transport(get_transport(url),
173
revision_id=revision_id,
174
force_new_repo=force_new_repo,
175
preserve_stacking=preserve_stacking)
177
def clone_on_transport(self, transport, revision_id=None,
178
force_new_repo=False, preserve_stacking=False,
180
"""Clone this bzrdir and its contents to transport verbatim.
182
:param transport: The transport for the location to produce the clone
183
at. If the target directory does not exist, it will be created.
184
:param revision_id: The tip revision-id to use for any branch or
185
working tree. If not None, then the clone operation may tune
186
itself to download less data.
187
:param force_new_repo: Do not use a shared repository for the target,
188
even if one is available.
189
:param preserve_stacking: When cloning a stacked branch, stack the
190
new branch on top of the other branch's stacked-on branch.
192
transport.ensure_base()
193
require_stacking = (stacked_on is not None)
194
format = self.cloning_metadir(require_stacking)
195
# Bug: We create a metadir without knowing if it can support stacking,
196
# we should look up the policy needs first.
197
result = format.initialize_on_transport(transport)
198
repository_policy = None
200
local_repo = self.find_repository()
201
except errors.NoRepositoryPresent:
204
local_branch = self.open_branch()
205
except errors.NotBranchError:
208
# enable fallbacks when branch is not a branch reference
209
if local_branch.repository.has_same_location(local_repo):
210
local_repo = local_branch.repository
211
if preserve_stacking:
213
stacked_on = local_branch.get_stacked_on_url()
214
except (errors.UnstackableBranchFormat,
215
errors.UnstackableRepositoryFormat,
220
# may need to copy content in
221
repository_policy = result.determine_repository_policy(
222
force_new_repo, stacked_on, self.root_transport.base,
223
require_stacking=require_stacking)
224
make_working_trees = local_repo.make_working_trees()
225
result_repo, is_new_repo = repository_policy.acquire_repository(
226
make_working_trees, local_repo.is_shared())
227
if not require_stacking and repository_policy._require_stacking:
228
require_stacking = True
229
result._format.require_stacking()
230
if is_new_repo and not require_stacking and revision_id is not None:
231
fetch_spec = graph.PendingAncestryResult(
232
[revision_id], local_repo)
233
result_repo.fetch(local_repo, fetch_spec=fetch_spec)
235
result_repo.fetch(local_repo, revision_id=revision_id)
238
# 1 if there is a branch present
239
# make sure its content is available in the target repository
241
if local_branch is not None:
242
result_branch = local_branch.clone(result, revision_id=revision_id,
243
repository_policy=repository_policy)
245
# Cheaper to check if the target is not local, than to try making
247
result.root_transport.local_abspath('.')
248
if result_repo is None or result_repo.make_working_trees():
249
self.open_workingtree().clone(result)
250
except (errors.NoWorkingTree, errors.NotLocalUrl):
254
# TODO: This should be given a Transport, and should chdir up; otherwise
255
# this will open a new connection.
256
def _make_tail(self, url):
257
t = get_transport(url)
261
def create(cls, base, format=None, possible_transports=None):
262
"""Create a new BzrDir at the url 'base'.
264
:param format: If supplied, the format of branch to create. If not
265
supplied, the default is used.
266
:param possible_transports: If supplied, a list of transports that
267
can be reused to share a remote connection.
269
if cls is not BzrDir:
270
raise AssertionError("BzrDir.create always creates the default"
271
" format, not one of %r" % cls)
272
t = get_transport(base, possible_transports)
275
format = BzrDirFormat.get_default_format()
276
return format.initialize_on_transport(t)
279
def find_bzrdirs(transport, evaluate=None, list_current=None):
280
"""Find bzrdirs recursively from current location.
282
This is intended primarily as a building block for more sophisticated
283
functionality, like finding trees under a directory, or finding
284
branches that use a given repository.
285
:param evaluate: An optional callable that yields recurse, value,
286
where recurse controls whether this bzrdir is recursed into
287
and value is the value to yield. By default, all bzrdirs
288
are recursed into, and the return value is the bzrdir.
289
:param list_current: if supplied, use this function to list the current
290
directory, instead of Transport.list_dir
291
:return: a generator of found bzrdirs, or whatever evaluate returns.
293
if list_current is None:
294
def list_current(transport):
295
return transport.list_dir('')
297
def evaluate(bzrdir):
300
pending = [transport]
301
while len(pending) > 0:
302
current_transport = pending.pop()
305
bzrdir = BzrDir.open_from_transport(current_transport)
306
except errors.NotBranchError:
309
recurse, value = evaluate(bzrdir)
312
subdirs = list_current(current_transport)
313
except errors.NoSuchFile:
316
for subdir in sorted(subdirs, reverse=True):
317
pending.append(current_transport.clone(subdir))
320
def find_branches(transport):
321
"""Find all branches under a transport.
323
This will find all branches below the transport, including branches
324
inside other branches. Where possible, it will use
325
Repository.find_branches.
327
To list all the branches that use a particular Repository, see
328
Repository.find_branches
330
def evaluate(bzrdir):
332
repository = bzrdir.open_repository()
333
except errors.NoRepositoryPresent:
336
return False, (None, repository)
338
branch = bzrdir.open_branch()
339
except errors.NotBranchError:
340
return True, (None, None)
342
return True, (branch, None)
344
for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
346
branches.extend(repo.find_branches())
347
if branch is not None:
348
branches.append(branch)
351
def destroy_repository(self):
352
"""Destroy the repository in this BzrDir"""
353
raise NotImplementedError(self.destroy_repository)
355
def create_branch(self):
356
"""Create a branch in this BzrDir.
358
The bzrdir's format will control what branch format is created.
359
For more control see BranchFormatXX.create(a_bzrdir).
361
raise NotImplementedError(self.create_branch)
363
def destroy_branch(self):
364
"""Destroy the branch in this BzrDir"""
365
raise NotImplementedError(self.destroy_branch)
368
def create_branch_and_repo(base, force_new_repo=False, format=None):
369
"""Create a new BzrDir, Branch and Repository at the url 'base'.
371
This will use the current default BzrDirFormat unless one is
372
specified, and use whatever
373
repository format that that uses via bzrdir.create_branch and
374
create_repository. If a shared repository is available that is used
377
The created Branch object is returned.
379
:param base: The URL to create the branch at.
380
:param force_new_repo: If True a new repository is always created.
381
:param format: If supplied, the format of branch to create. If not
382
supplied, the default is used.
384
bzrdir = BzrDir.create(base, format)
385
bzrdir._find_or_create_repository(force_new_repo)
386
return bzrdir.create_branch()
388
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
389
stack_on_pwd=None, require_stacking=False):
390
"""Return an object representing a policy to use.
392
This controls whether a new repository is created, and the format of
393
that repository, or some existing shared repository used instead.
395
If stack_on is supplied, will not seek a containing shared repo.
397
:param force_new_repo: If True, require a new repository to be created.
398
:param stack_on: If supplied, the location to stack on. If not
399
supplied, a default_stack_on location may be used.
400
:param stack_on_pwd: If stack_on is relative, the location it is
403
def repository_policy(found_bzrdir):
406
config = found_bzrdir.get_config()
408
if config is not None:
409
stack_on = config.get_default_stack_on()
410
if stack_on is not None:
411
stack_on_pwd = found_bzrdir.root_transport.base
413
# does it have a repository ?
415
repository = found_bzrdir.open_repository()
416
except errors.NoRepositoryPresent:
419
if ((found_bzrdir.root_transport.base !=
420
self.root_transport.base) and not repository.is_shared()):
421
# Don't look higher, can't use a higher shared repo.
429
return UseExistingRepository(repository, stack_on,
430
stack_on_pwd, require_stacking=require_stacking), True
432
return CreateRepository(self, stack_on, stack_on_pwd,
433
require_stacking=require_stacking), True
435
if not force_new_repo:
437
policy = self._find_containing(repository_policy)
438
if policy is not None:
442
return UseExistingRepository(self.open_repository(),
443
stack_on, stack_on_pwd,
444
require_stacking=require_stacking)
445
except errors.NoRepositoryPresent:
447
return CreateRepository(self, stack_on, stack_on_pwd,
448
require_stacking=require_stacking)
450
def _find_or_create_repository(self, force_new_repo):
451
"""Create a new repository if needed, returning the repository."""
452
policy = self.determine_repository_policy(force_new_repo)
453
return policy.acquire_repository()[0]
456
def create_branch_convenience(base, force_new_repo=False,
457
force_new_tree=None, format=None,
458
possible_transports=None):
459
"""Create a new BzrDir, Branch and Repository at the url 'base'.
461
This is a convenience function - it will use an existing repository
462
if possible, can be told explicitly whether to create a working tree or
465
This will use the current default BzrDirFormat unless one is
466
specified, and use whatever
467
repository format that that uses via bzrdir.create_branch and
468
create_repository. If a shared repository is available that is used
469
preferentially. Whatever repository is used, its tree creation policy
472
The created Branch object is returned.
473
If a working tree cannot be made due to base not being a file:// url,
474
no error is raised unless force_new_tree is True, in which case no
475
data is created on disk and NotLocalUrl is raised.
477
:param base: The URL to create the branch at.
478
:param force_new_repo: If True a new repository is always created.
479
:param force_new_tree: If True or False force creation of a tree or
480
prevent such creation respectively.
481
:param format: Override for the bzrdir format to create.
482
:param possible_transports: An optional reusable transports list.
485
# check for non local urls
486
t = get_transport(base, possible_transports)
487
if not isinstance(t, local.LocalTransport):
488
raise errors.NotLocalUrl(base)
489
bzrdir = BzrDir.create(base, format, possible_transports)
490
repo = bzrdir._find_or_create_repository(force_new_repo)
491
result = bzrdir.create_branch()
492
if force_new_tree or (repo.make_working_trees() and
493
force_new_tree is None):
495
bzrdir.create_workingtree()
496
except errors.NotLocalUrl:
501
def create_standalone_workingtree(base, format=None):
502
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
504
'base' must be a local path or a file:// url.
506
This will use the current default BzrDirFormat unless one is
507
specified, and use whatever
508
repository format that that uses for bzrdirformat.create_workingtree,
509
create_branch and create_repository.
511
:param format: Override for the bzrdir format to create.
512
:return: The WorkingTree object.
514
t = get_transport(base)
515
if not isinstance(t, local.LocalTransport):
516
raise errors.NotLocalUrl(base)
517
bzrdir = BzrDir.create_branch_and_repo(base,
519
format=format).bzrdir
520
return bzrdir.create_workingtree()
522
def create_workingtree(self, revision_id=None, from_branch=None,
523
accelerator_tree=None, hardlink=False):
524
"""Create a working tree at this BzrDir.
526
:param revision_id: create it as of this revision id.
527
:param from_branch: override bzrdir branch (for lightweight checkouts)
528
:param accelerator_tree: A tree which can be used for retrieving file
529
contents more quickly than the revision tree, i.e. a workingtree.
530
The revision tree will be used for cases where accelerator_tree's
531
content is different.
533
raise NotImplementedError(self.create_workingtree)
535
def backup_bzrdir(self):
536
"""Backup this bzr control directory.
538
:return: Tuple with old path name and new path name
540
pb = ui.ui_factory.nested_progress_bar()
542
# FIXME: bug 300001 -- the backup fails if the backup directory
543
# already exists, but it should instead either remove it or make
544
# a new backup directory.
546
# FIXME: bug 262450 -- the backup directory should have the same
547
# permissions as the .bzr directory (probably a bug in copy_tree)
548
old_path = self.root_transport.abspath('.bzr')
549
new_path = self.root_transport.abspath('backup.bzr')
550
pb.note('making backup of %s' % (old_path,))
551
pb.note(' to %s' % (new_path,))
552
self.root_transport.copy_tree('.bzr', 'backup.bzr')
553
return (old_path, new_path)
557
def retire_bzrdir(self, limit=10000):
558
"""Permanently disable the bzrdir.
560
This is done by renaming it to give the user some ability to recover
561
if there was a problem.
563
This will have horrible consequences if anyone has anything locked or
565
:param limit: number of times to retry
570
to_path = '.bzr.retired.%d' % i
571
self.root_transport.rename('.bzr', to_path)
572
note("renamed %s to %s"
573
% (self.root_transport.abspath('.bzr'), to_path))
575
except (errors.TransportError, IOError, errors.PathError):
582
def destroy_workingtree(self):
583
"""Destroy the working tree at this BzrDir.
585
Formats that do not support this may raise UnsupportedOperation.
587
raise NotImplementedError(self.destroy_workingtree)
589
def destroy_workingtree_metadata(self):
590
"""Destroy the control files for the working tree at this BzrDir.
592
The contents of working tree files are not affected.
593
Formats that do not support this may raise UnsupportedOperation.
595
raise NotImplementedError(self.destroy_workingtree_metadata)
597
def _find_containing(self, evaluate):
598
"""Find something in a containing control directory.
600
This method will scan containing control dirs, until it finds what
601
it is looking for, decides that it will never find it, or runs out
602
of containing control directories to check.
604
It is used to implement find_repository and
605
determine_repository_policy.
607
:param evaluate: A function returning (value, stop). If stop is True,
608
the value will be returned.
612
result, stop = evaluate(found_bzrdir)
615
next_transport = found_bzrdir.root_transport.clone('..')
616
if (found_bzrdir.root_transport.base == next_transport.base):
617
# top of the file system
619
# find the next containing bzrdir
621
found_bzrdir = BzrDir.open_containing_from_transport(
623
except errors.NotBranchError:
626
def find_repository(self):
627
"""Find the repository that should be used.
629
This does not require a branch as we use it to find the repo for
630
new branches as well as to hook existing branches up to their
633
def usable_repository(found_bzrdir):
634
# does it have a repository ?
636
repository = found_bzrdir.open_repository()
637
except errors.NoRepositoryPresent:
639
if found_bzrdir.root_transport.base == self.root_transport.base:
640
return repository, True
641
elif repository.is_shared():
642
return repository, True
646
found_repo = self._find_containing(usable_repository)
647
if found_repo is None:
648
raise errors.NoRepositoryPresent(self)
651
def get_branch_reference(self):
652
"""Return the referenced URL for the branch in this bzrdir.
654
:raises NotBranchError: If there is no Branch.
655
:return: The URL the branch in this bzrdir references if it is a
656
reference branch, or None for regular branches.
660
def get_branch_transport(self, branch_format):
661
"""Get the transport for use by branch format in this BzrDir.
663
Note that bzr dirs that do not support format strings will raise
664
IncompatibleFormat if the branch format they are given has
665
a format string, and vice versa.
667
If branch_format is None, the transport is returned with no
668
checking. If it is not None, then the returned transport is
669
guaranteed to point to an existing directory ready for use.
671
raise NotImplementedError(self.get_branch_transport)
673
def _find_creation_modes(self):
674
"""Determine the appropriate modes for files and directories.
676
They're always set to be consistent with the base directory,
677
assuming that this transport allows setting modes.
679
# TODO: Do we need or want an option (maybe a config setting) to turn
680
# this off or override it for particular locations? -- mbp 20080512
681
if self._mode_check_done:
683
self._mode_check_done = True
685
st = self.transport.stat('.')
686
except errors.TransportNotPossible:
687
self._dir_mode = None
688
self._file_mode = None
690
# Check the directory mode, but also make sure the created
691
# directories and files are read-write for this user. This is
692
# mostly a workaround for filesystems which lie about being able to
693
# write to a directory (cygwin & win32)
694
if (st.st_mode & 07777 == 00000):
695
# FTP allows stat but does not return dir/file modes
696
self._dir_mode = None
697
self._file_mode = None
699
self._dir_mode = (st.st_mode & 07777) | 00700
700
# Remove the sticky and execute bits for files
701
self._file_mode = self._dir_mode & ~07111
703
def _get_file_mode(self):
704
"""Return Unix mode for newly created files, or None.
706
if not self._mode_check_done:
707
self._find_creation_modes()
708
return self._file_mode
710
def _get_dir_mode(self):
711
"""Return Unix mode for newly created directories, or None.
713
if not self._mode_check_done:
714
self._find_creation_modes()
715
return self._dir_mode
717
def get_repository_transport(self, repository_format):
718
"""Get the transport for use by repository format in this BzrDir.
720
Note that bzr dirs that do not support format strings will raise
721
IncompatibleFormat if the repository format they are given has
722
a format string, and vice versa.
724
If repository_format is None, the transport is returned with no
725
checking. If it is not None, then the returned transport is
726
guaranteed to point to an existing directory ready for use.
728
raise NotImplementedError(self.get_repository_transport)
730
def get_workingtree_transport(self, tree_format):
731
"""Get the transport for use by workingtree format in this BzrDir.
733
Note that bzr dirs that do not support format strings will raise
734
IncompatibleFormat if the workingtree format they are given has a
735
format string, and vice versa.
737
If workingtree_format is None, the transport is returned with no
738
checking. If it is not None, then the returned transport is
739
guaranteed to point to an existing directory ready for use.
741
raise NotImplementedError(self.get_workingtree_transport)
743
def get_config(self):
744
if getattr(self, '_get_config', None) is None:
746
return self._get_config()
748
def __init__(self, _transport, _format):
749
"""Initialize a Bzr control dir object.
751
Only really common logic should reside here, concrete classes should be
752
made with varying behaviours.
754
:param _format: the format that is creating this BzrDir instance.
755
:param _transport: the transport this dir is based at.
757
self._format = _format
758
self.transport = _transport.clone('.bzr')
759
self.root_transport = _transport
760
self._mode_check_done = False
762
def is_control_filename(self, filename):
763
"""True if filename is the name of a path which is reserved for bzrdir's.
765
:param filename: A filename within the root transport of this bzrdir.
767
This is true IF and ONLY IF the filename is part of the namespace reserved
768
for bzr control dirs. Currently this is the '.bzr' directory in the root
769
of the root_transport. it is expected that plugins will need to extend
770
this in the future - for instance to make bzr talk with svn working
773
# this might be better on the BzrDirFormat class because it refers to
774
# all the possible bzrdir disk formats.
775
# This method is tested via the workingtree is_control_filename tests-
776
# it was extracted from WorkingTree.is_control_filename. If the method's
777
# contract is extended beyond the current trivial implementation, please
778
# add new tests for it to the appropriate place.
779
return filename == '.bzr' or filename.startswith('.bzr/')
781
def needs_format_conversion(self, format=None):
782
"""Return true if this bzrdir needs convert_format run on it.
784
For instance, if the repository format is out of date but the
785
branch and working tree are not, this should return True.
787
:param format: Optional parameter indicating a specific desired
788
format we plan to arrive at.
790
raise NotImplementedError(self.needs_format_conversion)
793
def open_unsupported(base):
794
"""Open a branch which is not supported."""
795
return BzrDir.open(base, _unsupported=True)
798
def open(base, _unsupported=False, possible_transports=None):
799
"""Open an existing bzrdir, rooted at 'base' (url).
801
:param _unsupported: a private parameter to the BzrDir class.
803
t = get_transport(base, possible_transports=possible_transports)
804
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
807
def open_from_transport(transport, _unsupported=False,
808
_server_formats=True):
809
"""Open a bzrdir within a particular directory.
811
:param transport: Transport containing the bzrdir.
812
:param _unsupported: private.
814
for hook in BzrDir.hooks['pre_open']:
816
# Keep initial base since 'transport' may be modified while following
818
base = transport.base
819
def find_format(transport):
820
return transport, BzrDirFormat.find_format(
821
transport, _server_formats=_server_formats)
823
def redirected(transport, e, redirection_notice):
824
redirected_transport = transport._redirected_to(e.source, e.target)
825
if redirected_transport is None:
826
raise errors.NotBranchError(base)
827
note('%s is%s redirected to %s',
828
transport.base, e.permanently, redirected_transport.base)
829
return redirected_transport
832
transport, format = do_catching_redirections(find_format,
835
except errors.TooManyRedirections:
836
raise errors.NotBranchError(base)
838
BzrDir._check_supported(format, _unsupported)
839
return format.open(transport, _found=True)
841
def open_branch(self, unsupported=False, ignore_fallbacks=False):
842
"""Open the branch object at this BzrDir if one is present.
844
If unsupported is True, then no longer supported branch formats can
847
TODO: static convenience version of this?
849
raise NotImplementedError(self.open_branch)
852
def open_containing(url, possible_transports=None):
853
"""Open an existing branch which contains url.
855
:param url: url to search from.
856
See open_containing_from_transport for more detail.
858
transport = get_transport(url, possible_transports)
859
return BzrDir.open_containing_from_transport(transport)
862
def open_containing_from_transport(a_transport):
863
"""Open an existing branch which contains a_transport.base.
865
This probes for a branch at a_transport, and searches upwards from there.
867
Basically we keep looking up until we find the control directory or
868
run into the root. If there isn't one, raises NotBranchError.
869
If there is one and it is either an unrecognised format or an unsupported
870
format, UnknownFormatError or UnsupportedFormatError are raised.
871
If there is one, it is returned, along with the unused portion of url.
873
:return: The BzrDir that contains the path, and a Unicode path
874
for the rest of the URL.
876
# this gets the normalised url back. I.e. '.' -> the full path.
877
url = a_transport.base
880
result = BzrDir.open_from_transport(a_transport)
881
return result, urlutils.unescape(a_transport.relpath(url))
882
except errors.NotBranchError, e:
885
new_t = a_transport.clone('..')
886
except errors.InvalidURLJoin:
887
# reached the root, whatever that may be
888
raise errors.NotBranchError(path=url)
889
if new_t.base == a_transport.base:
890
# reached the root, whatever that may be
891
raise errors.NotBranchError(path=url)
894
def _get_tree_branch(self):
895
"""Return the branch and tree, if any, for this bzrdir.
897
Return None for tree if not present or inaccessible.
898
Raise NotBranchError if no branch is present.
899
:return: (tree, branch)
902
tree = self.open_workingtree()
903
except (errors.NoWorkingTree, errors.NotLocalUrl):
905
branch = self.open_branch()
911
def open_tree_or_branch(klass, location):
912
"""Return the branch and working tree at a location.
914
If there is no tree at the location, tree will be None.
915
If there is no branch at the location, an exception will be
917
:return: (tree, branch)
919
bzrdir = klass.open(location)
920
return bzrdir._get_tree_branch()
923
def open_containing_tree_or_branch(klass, location):
924
"""Return the branch and working tree contained by a location.
926
Returns (tree, branch, relpath).
927
If there is no tree at containing the location, tree will be None.
928
If there is no branch containing the location, an exception will be
930
relpath is the portion of the path that is contained by the branch.
932
bzrdir, relpath = klass.open_containing(location)
933
tree, branch = bzrdir._get_tree_branch()
934
return tree, branch, relpath
937
def open_containing_tree_branch_or_repository(klass, location):
938
"""Return the working tree, branch and repo contained by a location.
940
Returns (tree, branch, repository, relpath).
941
If there is no tree containing the location, tree will be None.
942
If there is no branch containing the location, branch will be None.
943
If there is no repository containing the location, repository will be
945
relpath is the portion of the path that is contained by the innermost
948
If no tree, branch or repository is found, a NotBranchError is raised.
950
bzrdir, relpath = klass.open_containing(location)
952
tree, branch = bzrdir._get_tree_branch()
953
except errors.NotBranchError:
955
repo = bzrdir.find_repository()
956
return None, None, repo, relpath
957
except (errors.NoRepositoryPresent):
958
raise errors.NotBranchError(location)
959
return tree, branch, branch.repository, relpath
961
def open_repository(self, _unsupported=False):
962
"""Open the repository object at this BzrDir if one is present.
964
This will not follow the Branch object pointer - it's strictly a direct
965
open facility. Most client code should use open_branch().repository to
968
:param _unsupported: a private parameter, not part of the api.
969
TODO: static convenience version of this?
971
raise NotImplementedError(self.open_repository)
973
def open_workingtree(self, _unsupported=False,
974
recommend_upgrade=True, from_branch=None):
975
"""Open the workingtree object at this BzrDir if one is present.
977
:param recommend_upgrade: Optional keyword parameter, when True (the
978
default), emit through the ui module a recommendation that the user
979
upgrade the working tree when the workingtree being opened is old
980
(but still fully supported).
981
:param from_branch: override bzrdir branch (for lightweight checkouts)
983
raise NotImplementedError(self.open_workingtree)
985
def has_branch(self):
986
"""Tell if this bzrdir contains a branch.
988
Note: if you're going to open the branch, you should just go ahead
989
and try, and not ask permission first. (This method just opens the
990
branch and discards it, and that's somewhat expensive.)
995
except errors.NotBranchError:
998
def has_workingtree(self):
999
"""Tell if this bzrdir contains a working tree.
1001
This will still raise an exception if the bzrdir has a workingtree that
1002
is remote & inaccessible.
1004
Note: if you're going to open the working tree, you should just go ahead
1005
and try, and not ask permission first. (This method just opens the
1006
workingtree and discards it, and that's somewhat expensive.)
1009
self.open_workingtree(recommend_upgrade=False)
1011
except errors.NoWorkingTree:
1014
def _cloning_metadir(self):
1015
"""Produce a metadir suitable for cloning with.
1017
:returns: (destination_bzrdir_format, source_repository)
1019
result_format = self._format.__class__()
1022
branch = self.open_branch(ignore_fallbacks=True)
1023
source_repository = branch.repository
1024
result_format._branch_format = branch._format
1025
except errors.NotBranchError:
1026
source_branch = None
1027
source_repository = self.open_repository()
1028
except errors.NoRepositoryPresent:
1029
source_repository = None
1031
# XXX TODO: This isinstance is here because we have not implemented
1032
# the fix recommended in bug # 103195 - to delegate this choice the
1033
# repository itself.
1034
repo_format = source_repository._format
1035
if isinstance(repo_format, remote.RemoteRepositoryFormat):
1036
source_repository._ensure_real()
1037
repo_format = source_repository._real_repository._format
1038
result_format.repository_format = repo_format
1040
# TODO: Couldn't we just probe for the format in these cases,
1041
# rather than opening the whole tree? It would be a little
1042
# faster. mbp 20070401
1043
tree = self.open_workingtree(recommend_upgrade=False)
1044
except (errors.NoWorkingTree, errors.NotLocalUrl):
1045
result_format.workingtree_format = None
1047
result_format.workingtree_format = tree._format.__class__()
1048
return result_format, source_repository
1050
def cloning_metadir(self, require_stacking=False):
1051
"""Produce a metadir suitable for cloning or sprouting with.
1053
These operations may produce workingtrees (yes, even though they're
1054
"cloning" something that doesn't have a tree), so a viable workingtree
1055
format must be selected.
1057
:require_stacking: If True, non-stackable formats will be upgraded
1058
to similar stackable formats.
1059
:returns: a BzrDirFormat with all component formats either set
1060
appropriately or set to None if that component should not be
1063
format, repository = self._cloning_metadir()
1064
if format._workingtree_format is None:
1065
if repository is None:
1067
tree_format = repository._format._matchingbzrdir.workingtree_format
1068
format.workingtree_format = tree_format.__class__()
1069
if require_stacking:
1070
format.require_stacking()
1073
def checkout_metadir(self):
1074
return self.cloning_metadir()
1076
def sprout(self, url, revision_id=None, force_new_repo=False,
1077
recurse='down', possible_transports=None,
1078
accelerator_tree=None, hardlink=False, stacked=False,
1079
source_branch=None, create_tree_if_local=True):
1080
"""Create a copy of this bzrdir prepared for use as a new line of
1083
If url's last component does not exist, it will be created.
1085
Attributes related to the identity of the source branch like
1086
branch nickname will be cleaned, a working tree is created
1087
whether one existed before or not; and a local branch is always
1090
if revision_id is not None, then the clone operation may tune
1091
itself to download less data.
1092
:param accelerator_tree: A tree which can be used for retrieving file
1093
contents more quickly than the revision tree, i.e. a workingtree.
1094
The revision tree will be used for cases where accelerator_tree's
1095
content is different.
1096
:param hardlink: If true, hard-link files from accelerator_tree,
1098
:param stacked: If true, create a stacked branch referring to the
1099
location of this control directory.
1100
:param create_tree_if_local: If true, a working-tree will be created
1101
when working locally.
1103
target_transport = get_transport(url, possible_transports)
1104
target_transport.ensure_base()
1105
cloning_format = self.cloning_metadir(stacked)
1106
# Create/update the result branch
1107
result = cloning_format.initialize_on_transport(target_transport)
1108
# if a stacked branch wasn't requested, we don't create one
1109
# even if the origin was stacked
1110
stacked_branch_url = None
1111
if source_branch is not None:
1113
stacked_branch_url = self.root_transport.base
1114
source_repository = source_branch.repository
1117
source_branch = self.open_branch()
1118
source_repository = source_branch.repository
1120
stacked_branch_url = self.root_transport.base
1121
except errors.NotBranchError:
1122
source_branch = None
1124
source_repository = self.open_repository()
1125
except errors.NoRepositoryPresent:
1126
source_repository = None
1127
repository_policy = result.determine_repository_policy(
1128
force_new_repo, stacked_branch_url, require_stacking=stacked)
1129
result_repo, is_new_repo = repository_policy.acquire_repository()
1130
if is_new_repo and revision_id is not None and not stacked:
1131
fetch_spec = graph.PendingAncestryResult(
1132
[revision_id], source_repository)
1135
if source_repository is not None:
1136
# Fetch while stacked to prevent unstacked fetch from
1138
if fetch_spec is None:
1139
result_repo.fetch(source_repository, revision_id=revision_id)
1141
result_repo.fetch(source_repository, fetch_spec=fetch_spec)
1143
if source_branch is None:
1144
# this is for sprouting a bzrdir without a branch; is that
1146
# Not especially, but it's part of the contract.
1147
result_branch = result.create_branch()
1149
result_branch = source_branch.sprout(result,
1150
revision_id=revision_id, repository_policy=repository_policy)
1151
mutter("created new branch %r" % (result_branch,))
1153
# Create/update the result working tree
1154
if (create_tree_if_local and
1155
isinstance(target_transport, local.LocalTransport) and
1156
(result_repo is None or result_repo.make_working_trees())):
1157
wt = result.create_workingtree(accelerator_tree=accelerator_tree,
1161
if wt.path2id('') is None:
1163
wt.set_root_id(self.open_workingtree.get_root_id())
1164
except errors.NoWorkingTree:
1170
if recurse == 'down':
1172
basis = wt.basis_tree()
1174
subtrees = basis.iter_references()
1175
elif result_branch is not None:
1176
basis = result_branch.basis_tree()
1178
subtrees = basis.iter_references()
1179
elif source_branch is not None:
1180
basis = source_branch.basis_tree()
1182
subtrees = basis.iter_references()
1187
for path, file_id in subtrees:
1188
target = urlutils.join(url, urlutils.escape(path))
1189
sublocation = source_branch.reference_parent(file_id, path)
1190
sublocation.bzrdir.sprout(target,
1191
basis.get_reference_revision(file_id, path),
1192
force_new_repo=force_new_repo, recurse=recurse,
1195
if basis is not None:
1200
class BzrDirHooks(hooks.Hooks):
1201
"""Hooks for BzrDir operations."""
1204
"""Create the default hooks."""
1205
hooks.Hooks.__init__(self)
1206
self.create_hook(hooks.HookPoint('pre_open',
1207
"Invoked before attempting to open a BzrDir with the transport "
1208
"that the open will use.", (1, 14), None))
1210
# install the default hooks
1211
BzrDir.hooks = BzrDirHooks()
1214
class BzrDirPreSplitOut(BzrDir):
1215
"""A common class for the all-in-one formats."""
1217
def __init__(self, _transport, _format):
1218
"""See BzrDir.__init__."""
1219
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1220
self._control_files = lockable_files.LockableFiles(
1221
self.get_branch_transport(None),
1222
self._format._lock_file_name,
1223
self._format._lock_class)
1225
def break_lock(self):
1226
"""Pre-splitout bzrdirs do not suffer from stale locks."""
1227
raise NotImplementedError(self.break_lock)
1229
def cloning_metadir(self, require_stacking=False):
1230
"""Produce a metadir suitable for cloning with."""
1231
if require_stacking:
1232
return format_registry.make_bzrdir('1.6')
1233
return self._format.__class__()
1235
def clone(self, url, revision_id=None, force_new_repo=False,
1236
preserve_stacking=False):
1237
"""See BzrDir.clone().
1239
force_new_repo has no effect, since this family of formats always
1240
require a new repository.
1241
preserve_stacking has no effect, since no source branch using this
1242
family of formats can be stacked, so there is no stacking to preserve.
1244
self._make_tail(url)
1245
result = self._format._initialize_for_clone(url)
1246
self.open_repository().clone(result, revision_id=revision_id)
1247
from_branch = self.open_branch()
1248
from_branch.clone(result, revision_id=revision_id)
1250
tree = self.open_workingtree()
1251
except errors.NotLocalUrl:
1252
# make a new one, this format always has to have one.
1253
result._init_workingtree()
1258
def create_branch(self):
1259
"""See BzrDir.create_branch."""
1260
return self._format.get_branch_format().initialize(self)
1262
def destroy_branch(self):
1263
"""See BzrDir.destroy_branch."""
1264
raise errors.UnsupportedOperation(self.destroy_branch, self)
1266
def create_repository(self, shared=False):
1267
"""See BzrDir.create_repository."""
1269
raise errors.IncompatibleFormat('shared repository', self._format)
1270
return self.open_repository()
1272
def destroy_repository(self):
1273
"""See BzrDir.destroy_repository."""
1274
raise errors.UnsupportedOperation(self.destroy_repository, self)
1276
def create_workingtree(self, revision_id=None, from_branch=None,
1277
accelerator_tree=None, hardlink=False):
1278
"""See BzrDir.create_workingtree."""
1279
# The workingtree is sometimes created when the bzrdir is created,
1280
# but not when cloning.
1282
# this looks buggy but is not -really-
1283
# because this format creates the workingtree when the bzrdir is
1285
# clone and sprout will have set the revision_id
1286
# and that will have set it for us, its only
1287
# specific uses of create_workingtree in isolation
1288
# that can do wonky stuff here, and that only
1289
# happens for creating checkouts, which cannot be
1290
# done on this format anyway. So - acceptable wart.
1292
result = self.open_workingtree(recommend_upgrade=False)
1293
except errors.NoSuchFile:
1294
result = self._init_workingtree()
1295
if revision_id is not None:
1296
if revision_id == _mod_revision.NULL_REVISION:
1297
result.set_parent_ids([])
1299
result.set_parent_ids([revision_id])
1302
def _init_workingtree(self):
1303
from bzrlib.workingtree import WorkingTreeFormat2
1305
return WorkingTreeFormat2().initialize(self)
1306
except errors.NotLocalUrl:
1307
# Even though we can't access the working tree, we need to
1308
# create its control files.
1309
return WorkingTreeFormat2()._stub_initialize_on_transport(
1310
self.transport, self._control_files._file_mode)
1312
def destroy_workingtree(self):
1313
"""See BzrDir.destroy_workingtree."""
1314
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1316
def destroy_workingtree_metadata(self):
1317
"""See BzrDir.destroy_workingtree_metadata."""
1318
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1321
def get_branch_transport(self, branch_format):
1322
"""See BzrDir.get_branch_transport()."""
1323
if branch_format is None:
1324
return self.transport
1326
branch_format.get_format_string()
1327
except NotImplementedError:
1328
return self.transport
1329
raise errors.IncompatibleFormat(branch_format, self._format)
1331
def get_repository_transport(self, repository_format):
1332
"""See BzrDir.get_repository_transport()."""
1333
if repository_format is None:
1334
return self.transport
1336
repository_format.get_format_string()
1337
except NotImplementedError:
1338
return self.transport
1339
raise errors.IncompatibleFormat(repository_format, self._format)
1341
def get_workingtree_transport(self, workingtree_format):
1342
"""See BzrDir.get_workingtree_transport()."""
1343
if workingtree_format is None:
1344
return self.transport
1346
workingtree_format.get_format_string()
1347
except NotImplementedError:
1348
return self.transport
1349
raise errors.IncompatibleFormat(workingtree_format, self._format)
1351
def needs_format_conversion(self, format=None):
1352
"""See BzrDir.needs_format_conversion()."""
1353
# if the format is not the same as the system default,
1354
# an upgrade is needed.
1356
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1357
% 'needs_format_conversion(format=None)')
1358
format = BzrDirFormat.get_default_format()
1359
return not isinstance(self._format, format.__class__)
1361
def open_branch(self, unsupported=False, ignore_fallbacks=False):
1362
"""See BzrDir.open_branch."""
1363
from bzrlib.branch import BzrBranchFormat4
1364
format = BzrBranchFormat4()
1365
self._check_supported(format, unsupported)
1366
return format.open(self, _found=True)
1368
def sprout(self, url, revision_id=None, force_new_repo=False,
1369
possible_transports=None, accelerator_tree=None,
1370
hardlink=False, stacked=False, create_tree_if_local=True,
1371
source_branch=None):
1372
"""See BzrDir.sprout()."""
1373
if source_branch is not None:
1374
my_branch = self.open_branch()
1375
if source_branch.base != my_branch.base:
1376
raise AssertionError(
1377
"source branch %r is not within %r with branch %r" %
1378
(source_branch, self, my_branch))
1380
raise errors.UnstackableBranchFormat(
1381
self._format, self.root_transport.base)
1382
if not create_tree_if_local:
1383
raise errors.MustHaveWorkingTree(
1384
self._format, self.root_transport.base)
1385
from bzrlib.workingtree import WorkingTreeFormat2
1386
self._make_tail(url)
1387
result = self._format._initialize_for_clone(url)
1389
self.open_repository().clone(result, revision_id=revision_id)
1390
except errors.NoRepositoryPresent:
1393
self.open_branch().sprout(result, revision_id=revision_id)
1394
except errors.NotBranchError:
1397
# we always want a working tree
1398
WorkingTreeFormat2().initialize(result,
1399
accelerator_tree=accelerator_tree,
1404
class BzrDir4(BzrDirPreSplitOut):
1405
"""A .bzr version 4 control object.
1407
This is a deprecated format and may be removed after sept 2006.
1410
def create_repository(self, shared=False):
1411
"""See BzrDir.create_repository."""
1412
return self._format.repository_format.initialize(self, shared)
1414
def needs_format_conversion(self, format=None):
1415
"""Format 4 dirs are always in need of conversion."""
1417
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1418
% 'needs_format_conversion(format=None)')
1421
def open_repository(self):
1422
"""See BzrDir.open_repository."""
1423
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1424
return RepositoryFormat4().open(self, _found=True)
1427
class BzrDir5(BzrDirPreSplitOut):
1428
"""A .bzr version 5 control object.
1430
This is a deprecated format and may be removed after sept 2006.
1433
def open_repository(self):
1434
"""See BzrDir.open_repository."""
1435
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1436
return RepositoryFormat5().open(self, _found=True)
1438
def open_workingtree(self, _unsupported=False,
1439
recommend_upgrade=True):
1440
"""See BzrDir.create_workingtree."""
1441
from bzrlib.workingtree import WorkingTreeFormat2
1442
wt_format = WorkingTreeFormat2()
1443
# we don't warn here about upgrades; that ought to be handled for the
1445
return wt_format.open(self, _found=True)
1448
class BzrDir6(BzrDirPreSplitOut):
1449
"""A .bzr version 6 control object.
1451
This is a deprecated format and may be removed after sept 2006.
1454
def open_repository(self):
1455
"""See BzrDir.open_repository."""
1456
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1457
return RepositoryFormat6().open(self, _found=True)
1459
def open_workingtree(self, _unsupported=False,
1460
recommend_upgrade=True):
1461
"""See BzrDir.create_workingtree."""
1462
# we don't warn here about upgrades; that ought to be handled for the
1464
from bzrlib.workingtree import WorkingTreeFormat2
1465
return WorkingTreeFormat2().open(self, _found=True)
1468
class BzrDirMeta1(BzrDir):
1469
"""A .bzr meta version 1 control object.
1471
This is the first control object where the
1472
individual aspects are really split out: there are separate repository,
1473
workingtree and branch subdirectories and any subset of the three can be
1474
present within a BzrDir.
1477
def can_convert_format(self):
1478
"""See BzrDir.can_convert_format()."""
1481
def create_branch(self):
1482
"""See BzrDir.create_branch."""
1483
return self._format.get_branch_format().initialize(self)
1485
def destroy_branch(self):
1486
"""See BzrDir.create_branch."""
1487
self.transport.delete_tree('branch')
1489
def create_repository(self, shared=False):
1490
"""See BzrDir.create_repository."""
1491
return self._format.repository_format.initialize(self, shared)
1493
def destroy_repository(self):
1494
"""See BzrDir.destroy_repository."""
1495
self.transport.delete_tree('repository')
1497
def create_workingtree(self, revision_id=None, from_branch=None,
1498
accelerator_tree=None, hardlink=False):
1499
"""See BzrDir.create_workingtree."""
1500
return self._format.workingtree_format.initialize(
1501
self, revision_id, from_branch=from_branch,
1502
accelerator_tree=accelerator_tree, hardlink=hardlink)
1504
def destroy_workingtree(self):
1505
"""See BzrDir.destroy_workingtree."""
1506
wt = self.open_workingtree(recommend_upgrade=False)
1507
repository = wt.branch.repository
1508
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1509
wt.revert(old_tree=empty)
1510
self.destroy_workingtree_metadata()
1512
def destroy_workingtree_metadata(self):
1513
self.transport.delete_tree('checkout')
1515
def find_branch_format(self):
1516
"""Find the branch 'format' for this bzrdir.
1518
This might be a synthetic object for e.g. RemoteBranch and SVN.
1520
from bzrlib.branch import BranchFormat
1521
return BranchFormat.find_format(self)
1523
def _get_mkdir_mode(self):
1524
"""Figure out the mode to use when creating a bzrdir subdir."""
1525
temp_control = lockable_files.LockableFiles(self.transport, '',
1526
lockable_files.TransportLock)
1527
return temp_control._dir_mode
1529
def get_branch_reference(self):
1530
"""See BzrDir.get_branch_reference()."""
1531
from bzrlib.branch import BranchFormat
1532
format = BranchFormat.find_format(self)
1533
return format.get_reference(self)
1535
def get_branch_transport(self, branch_format):
1536
"""See BzrDir.get_branch_transport()."""
1537
if branch_format is None:
1538
return self.transport.clone('branch')
1540
branch_format.get_format_string()
1541
except NotImplementedError:
1542
raise errors.IncompatibleFormat(branch_format, self._format)
1544
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1545
except errors.FileExists:
1547
return self.transport.clone('branch')
1549
def get_repository_transport(self, repository_format):
1550
"""See BzrDir.get_repository_transport()."""
1551
if repository_format is None:
1552
return self.transport.clone('repository')
1554
repository_format.get_format_string()
1555
except NotImplementedError:
1556
raise errors.IncompatibleFormat(repository_format, self._format)
1558
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1559
except errors.FileExists:
1561
return self.transport.clone('repository')
1563
def get_workingtree_transport(self, workingtree_format):
1564
"""See BzrDir.get_workingtree_transport()."""
1565
if workingtree_format is None:
1566
return self.transport.clone('checkout')
1568
workingtree_format.get_format_string()
1569
except NotImplementedError:
1570
raise errors.IncompatibleFormat(workingtree_format, self._format)
1572
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1573
except errors.FileExists:
1575
return self.transport.clone('checkout')
1577
def needs_format_conversion(self, format=None):
1578
"""See BzrDir.needs_format_conversion()."""
1580
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1581
% 'needs_format_conversion(format=None)')
1583
format = BzrDirFormat.get_default_format()
1584
if not isinstance(self._format, format.__class__):
1585
# it is not a meta dir format, conversion is needed.
1587
# we might want to push this down to the repository?
1589
if not isinstance(self.open_repository()._format,
1590
format.repository_format.__class__):
1591
# the repository needs an upgrade.
1593
except errors.NoRepositoryPresent:
1596
if not isinstance(self.open_branch()._format,
1597
format.get_branch_format().__class__):
1598
# the branch needs an upgrade.
1600
except errors.NotBranchError:
1603
my_wt = self.open_workingtree(recommend_upgrade=False)
1604
if not isinstance(my_wt._format,
1605
format.workingtree_format.__class__):
1606
# the workingtree needs an upgrade.
1608
except (errors.NoWorkingTree, errors.NotLocalUrl):
1612
def open_branch(self, unsupported=False, ignore_fallbacks=False):
1613
"""See BzrDir.open_branch."""
1614
format = self.find_branch_format()
1615
self._check_supported(format, unsupported)
1616
return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
1618
def open_repository(self, unsupported=False):
1619
"""See BzrDir.open_repository."""
1620
from bzrlib.repository import RepositoryFormat
1621
format = RepositoryFormat.find_format(self)
1622
self._check_supported(format, unsupported)
1623
return format.open(self, _found=True)
1625
def open_workingtree(self, unsupported=False,
1626
recommend_upgrade=True):
1627
"""See BzrDir.open_workingtree."""
1628
from bzrlib.workingtree import WorkingTreeFormat
1629
format = WorkingTreeFormat.find_format(self)
1630
self._check_supported(format, unsupported,
1632
basedir=self.root_transport.base)
1633
return format.open(self, _found=True)
1635
def _get_config(self):
1636
return config.BzrDirConfig(self.transport)
1639
class BzrDirFormat(object):
1640
"""An encapsulation of the initialization and open routines for a format.
1642
Formats provide three things:
1643
* An initialization routine,
1647
Formats are placed in a dict by their format string for reference
1648
during bzrdir opening. These should be subclasses of BzrDirFormat
1651
Once a format is deprecated, just deprecate the initialize and open
1652
methods on the format class. Do not deprecate the object, as the
1653
object will be created every system load.
1656
_default_format = None
1657
"""The default format used for new .bzr dirs."""
1660
"""The known formats."""
1662
_control_formats = []
1663
"""The registered control formats - .bzr, ....
1665
This is a list of BzrDirFormat objects.
1668
_control_server_formats = []
1669
"""The registered control server formats, e.g. RemoteBzrDirs.
1671
This is a list of BzrDirFormat objects.
1674
_lock_file_name = 'branch-lock'
1676
# _lock_class must be set in subclasses to the lock type, typ.
1677
# TransportLock or LockDir
1680
def find_format(klass, transport, _server_formats=True):
1681
"""Return the format present at transport."""
1683
formats = klass._control_server_formats + klass._control_formats
1685
formats = klass._control_formats
1686
for format in formats:
1688
return format.probe_transport(transport)
1689
except errors.NotBranchError:
1690
# this format does not find a control dir here.
1692
raise errors.NotBranchError(path=transport.base)
1695
def probe_transport(klass, transport):
1696
"""Return the .bzrdir style format present in a directory."""
1698
format_string = transport.get(".bzr/branch-format").read()
1699
except errors.NoSuchFile:
1700
raise errors.NotBranchError(path=transport.base)
1703
return klass._formats[format_string]
1705
raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1708
def get_default_format(klass):
1709
"""Return the current default format."""
1710
return klass._default_format
1712
def get_format_string(self):
1713
"""Return the ASCII format string that identifies this format."""
1714
raise NotImplementedError(self.get_format_string)
1716
def get_format_description(self):
1717
"""Return the short description for this format."""
1718
raise NotImplementedError(self.get_format_description)
1720
def get_converter(self, format=None):
1721
"""Return the converter to use to convert bzrdirs needing converts.
1723
This returns a bzrlib.bzrdir.Converter object.
1725
This should return the best upgrader to step this format towards the
1726
current default format. In the case of plugins we can/should provide
1727
some means for them to extend the range of returnable converters.
1729
:param format: Optional format to override the default format of the
1732
raise NotImplementedError(self.get_converter)
1734
def initialize(self, url, possible_transports=None):
1735
"""Create a bzr control dir at this url and return an opened copy.
1737
Subclasses should typically override initialize_on_transport
1738
instead of this method.
1740
return self.initialize_on_transport(get_transport(url,
1741
possible_transports))
1743
def initialize_on_transport(self, transport):
1744
"""Initialize a new bzrdir in the base directory of a Transport."""
1746
# can we hand off the request to the smart server rather than using
1748
client_medium = transport.get_smart_medium()
1749
except errors.NoSmartMedium:
1750
return self._initialize_on_transport_vfs(transport)
1752
# Current RPC's only know how to create bzr metadir1 instances, so
1753
# we still delegate to vfs methods if the requested format is not a
1755
if type(self) != BzrDirMetaFormat1:
1756
return self._initialize_on_transport_vfs(transport)
1757
remote_format = RemoteBzrDirFormat()
1758
self._supply_sub_formats_to(remote_format)
1759
return remote_format.initialize_on_transport(transport)
1761
def _initialize_on_transport_vfs(self, transport):
1762
"""Initialize a new bzrdir using VFS calls.
1764
:param transport: The transport to create the .bzr directory in.
1767
# Since we are creating a .bzr directory, inherit the
1768
# mode from the root directory
1769
temp_control = lockable_files.LockableFiles(transport,
1770
'', lockable_files.TransportLock)
1771
temp_control._transport.mkdir('.bzr',
1772
# FIXME: RBC 20060121 don't peek under
1774
mode=temp_control._dir_mode)
1775
if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1776
win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1777
file_mode = temp_control._file_mode
1779
bzrdir_transport = transport.clone('.bzr')
1780
utf8_files = [('README',
1781
"This is a Bazaar control directory.\n"
1782
"Do not change any files in this directory.\n"
1783
"See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1784
('branch-format', self.get_format_string()),
1786
# NB: no need to escape relative paths that are url safe.
1787
control_files = lockable_files.LockableFiles(bzrdir_transport,
1788
self._lock_file_name, self._lock_class)
1789
control_files.create_lock()
1790
control_files.lock_write()
1792
for (filename, content) in utf8_files:
1793
bzrdir_transport.put_bytes(filename, content,
1796
control_files.unlock()
1797
return self.open(transport, _found=True)
1799
def is_supported(self):
1800
"""Is this format supported?
1802
Supported formats must be initializable and openable.
1803
Unsupported formats may not support initialization or committing or
1804
some other features depending on the reason for not being supported.
1808
def network_name(self):
1809
"""A simple byte string uniquely identifying this format for RPC calls.
1811
Bzr control formats use thir disk format string to identify the format
1812
over the wire. Its possible that other control formats have more
1813
complex detection requirements, so we permit them to use any unique and
1814
immutable string they desire.
1816
raise NotImplementedError(self.network_name)
1818
def same_model(self, target_format):
1819
return (self.repository_format.rich_root_data ==
1820
target_format.rich_root_data)
1823
def known_formats(klass):
1824
"""Return all the known formats.
1826
Concrete formats should override _known_formats.
1828
# There is double indirection here to make sure that control
1829
# formats used by more than one dir format will only be probed
1830
# once. This can otherwise be quite expensive for remote connections.
1832
for format in klass._control_formats:
1833
result.update(format._known_formats())
1837
def _known_formats(klass):
1838
"""Return the known format instances for this control format."""
1839
return set(klass._formats.values())
1841
def open(self, transport, _found=False):
1842
"""Return an instance of this format for the dir transport points at.
1844
_found is a private parameter, do not use it.
1847
found_format = BzrDirFormat.find_format(transport)
1848
if not isinstance(found_format, self.__class__):
1849
raise AssertionError("%s was asked to open %s, but it seems to need "
1851
% (self, transport, found_format))
1852
# Allow subclasses - use the found format.
1853
self._supply_sub_formats_to(found_format)
1854
return found_format._open(transport)
1855
return self._open(transport)
1857
def _open(self, transport):
1858
"""Template method helper for opening BzrDirectories.
1860
This performs the actual open and any additional logic or parameter
1863
raise NotImplementedError(self._open)
1866
def register_format(klass, format):
1867
klass._formats[format.get_format_string()] = format
1868
# bzr native formats have a network name of their format string.
1869
network_format_registry.register(format.get_format_string(), format.__class__)
1872
def register_control_format(klass, format):
1873
"""Register a format that does not use '.bzr' for its control dir.
1875
TODO: This should be pulled up into a 'ControlDirFormat' base class
1876
which BzrDirFormat can inherit from, and renamed to register_format
1877
there. It has been done without that for now for simplicity of
1880
klass._control_formats.append(format)
1883
def register_control_server_format(klass, format):
1884
"""Register a control format for client-server environments.
1886
These formats will be tried before ones registered with
1887
register_control_format. This gives implementations that decide to the
1888
chance to grab it before anything looks at the contents of the format
1891
klass._control_server_formats.append(format)
1894
def _set_default_format(klass, format):
1895
"""Set default format (for testing behavior of defaults only)"""
1896
klass._default_format = format
1900
return self.get_format_description().rstrip()
1902
def _supply_sub_formats_to(self, other_format):
1903
"""Give other_format the same values for sub formats as this has.
1905
This method is expected to be used when parameterising a
1906
RemoteBzrDirFormat instance with the parameters from a
1907
BzrDirMetaFormat1 instance.
1909
:param other_format: other_format is a format which should be
1910
compatible with whatever sub formats are supported by self.
1915
def unregister_format(klass, format):
1916
del klass._formats[format.get_format_string()]
1919
def unregister_control_format(klass, format):
1920
klass._control_formats.remove(format)
1923
class BzrDirFormat4(BzrDirFormat):
1924
"""Bzr dir format 4.
1926
This format is a combined format for working tree, branch and repository.
1928
- Format 1 working trees [always]
1929
- Format 4 branches [always]
1930
- Format 4 repositories [always]
1932
This format is deprecated: it indexes texts using a text it which is
1933
removed in format 5; write support for this format has been removed.
1936
_lock_class = lockable_files.TransportLock
1938
def get_format_string(self):
1939
"""See BzrDirFormat.get_format_string()."""
1940
return "Bazaar-NG branch, format 0.0.4\n"
1942
def get_format_description(self):
1943
"""See BzrDirFormat.get_format_description()."""
1944
return "All-in-one format 4"
1946
def get_converter(self, format=None):
1947
"""See BzrDirFormat.get_converter()."""
1948
# there is one and only one upgrade path here.
1949
return ConvertBzrDir4To5()
1951
def initialize_on_transport(self, transport):
1952
"""Format 4 branches cannot be created."""
1953
raise errors.UninitializableFormat(self)
1955
def is_supported(self):
1956
"""Format 4 is not supported.
1958
It is not supported because the model changed from 4 to 5 and the
1959
conversion logic is expensive - so doing it on the fly was not
1964
def network_name(self):
1965
return self.get_format_string()
1967
def _open(self, transport):
1968
"""See BzrDirFormat._open."""
1969
return BzrDir4(transport, self)
1971
def __return_repository_format(self):
1972
"""Circular import protection."""
1973
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1974
return RepositoryFormat4()
1975
repository_format = property(__return_repository_format)
1978
class BzrDirFormat5(BzrDirFormat):
1979
"""Bzr control format 5.
1981
This format is a combined format for working tree, branch and repository.
1983
- Format 2 working trees [always]
1984
- Format 4 branches [always]
1985
- Format 5 repositories [always]
1986
Unhashed stores in the repository.
1989
_lock_class = lockable_files.TransportLock
1991
def get_format_string(self):
1992
"""See BzrDirFormat.get_format_string()."""
1993
return "Bazaar-NG branch, format 5\n"
1995
def get_branch_format(self):
1996
from bzrlib import branch
1997
return branch.BzrBranchFormat4()
1999
def get_format_description(self):
2000
"""See BzrDirFormat.get_format_description()."""
2001
return "All-in-one format 5"
2003
def get_converter(self, format=None):
2004
"""See BzrDirFormat.get_converter()."""
2005
# there is one and only one upgrade path here.
2006
return ConvertBzrDir5To6()
2008
def _initialize_for_clone(self, url):
2009
return self.initialize_on_transport(get_transport(url), _cloning=True)
2011
def initialize_on_transport(self, transport, _cloning=False):
2012
"""Format 5 dirs always have working tree, branch and repository.
2014
Except when they are being cloned.
2016
from bzrlib.branch import BzrBranchFormat4
2017
from bzrlib.repofmt.weaverepo import RepositoryFormat5
2018
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
2019
RepositoryFormat5().initialize(result, _internal=True)
2021
branch = BzrBranchFormat4().initialize(result)
2022
result._init_workingtree()
2025
def network_name(self):
2026
return self.get_format_string()
2028
def _open(self, transport):
2029
"""See BzrDirFormat._open."""
2030
return BzrDir5(transport, self)
2032
def __return_repository_format(self):
2033
"""Circular import protection."""
2034
from bzrlib.repofmt.weaverepo import RepositoryFormat5
2035
return RepositoryFormat5()
2036
repository_format = property(__return_repository_format)
2039
class BzrDirFormat6(BzrDirFormat):
2040
"""Bzr control format 6.
2042
This format is a combined format for working tree, branch and repository.
2044
- Format 2 working trees [always]
2045
- Format 4 branches [always]
2046
- Format 6 repositories [always]
2049
_lock_class = lockable_files.TransportLock
2051
def get_format_string(self):
2052
"""See BzrDirFormat.get_format_string()."""
2053
return "Bazaar-NG branch, format 6\n"
2055
def get_format_description(self):
2056
"""See BzrDirFormat.get_format_description()."""
2057
return "All-in-one format 6"
2059
def get_branch_format(self):
2060
from bzrlib import branch
2061
return branch.BzrBranchFormat4()
2063
def get_converter(self, format=None):
2064
"""See BzrDirFormat.get_converter()."""
2065
# there is one and only one upgrade path here.
2066
return ConvertBzrDir6ToMeta()
2068
def _initialize_for_clone(self, url):
2069
return self.initialize_on_transport(get_transport(url), _cloning=True)
2071
def initialize_on_transport(self, transport, _cloning=False):
2072
"""Format 6 dirs always have working tree, branch and repository.
2074
Except when they are being cloned.
2076
from bzrlib.branch import BzrBranchFormat4
2077
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2078
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
2079
RepositoryFormat6().initialize(result, _internal=True)
2081
branch = BzrBranchFormat4().initialize(result)
2082
result._init_workingtree()
2085
def network_name(self):
2086
return self.get_format_string()
2088
def _open(self, transport):
2089
"""See BzrDirFormat._open."""
2090
return BzrDir6(transport, self)
2092
def __return_repository_format(self):
2093
"""Circular import protection."""
2094
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2095
return RepositoryFormat6()
2096
repository_format = property(__return_repository_format)
2099
class BzrDirMetaFormat1(BzrDirFormat):
2100
"""Bzr meta control format 1
2102
This is the first format with split out working tree, branch and repository
2105
- Format 3 working trees [optional]
2106
- Format 5 branches [optional]
2107
- Format 7 repositories [optional]
2110
_lock_class = lockdir.LockDir
2113
self._workingtree_format = None
2114
self._branch_format = None
2115
self._repository_format = None
2117
def __eq__(self, other):
2118
if other.__class__ is not self.__class__:
2120
if other.repository_format != self.repository_format:
2122
if other.workingtree_format != self.workingtree_format:
2126
def __ne__(self, other):
2127
return not self == other
2129
def get_branch_format(self):
2130
if self._branch_format is None:
2131
from bzrlib.branch import BranchFormat
2132
self._branch_format = BranchFormat.get_default_format()
2133
return self._branch_format
2135
def set_branch_format(self, format):
2136
self._branch_format = format
2138
def require_stacking(self):
2139
if not self.get_branch_format().supports_stacking():
2140
# We need to make a stacked branch, but the default format for the
2141
# target doesn't support stacking. So force a branch that *can*
2143
from bzrlib.branch import BzrBranchFormat7
2144
branch_format = BzrBranchFormat7()
2145
self.set_branch_format(branch_format)
2146
mutter("using %r for stacking" % (branch_format,))
2147
from bzrlib.repofmt import pack_repo
2148
if self.repository_format.rich_root_data:
2149
bzrdir_format_name = '1.6.1-rich-root'
2150
repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
2152
bzrdir_format_name = '1.6'
2153
repo_format = pack_repo.RepositoryFormatKnitPack5()
2154
note('Source format does not support stacking, using format:'
2156
bzrdir_format_name, repo_format.get_format_description())
2157
self.repository_format = repo_format
2159
def get_converter(self, format=None):
2160
"""See BzrDirFormat.get_converter()."""
2162
format = BzrDirFormat.get_default_format()
2163
if not isinstance(self, format.__class__):
2164
# converting away from metadir is not implemented
2165
raise NotImplementedError(self.get_converter)
2166
return ConvertMetaToMeta(format)
2168
def get_format_string(self):
2169
"""See BzrDirFormat.get_format_string()."""
2170
return "Bazaar-NG meta directory, format 1\n"
2172
def get_format_description(self):
2173
"""See BzrDirFormat.get_format_description()."""
2174
return "Meta directory format 1"
2176
def network_name(self):
2177
return self.get_format_string()
2179
def _open(self, transport):
2180
"""See BzrDirFormat._open."""
2181
return BzrDirMeta1(transport, self)
2183
def __return_repository_format(self):
2184
"""Circular import protection."""
2185
if self._repository_format:
2186
return self._repository_format
2187
from bzrlib.repository import RepositoryFormat
2188
return RepositoryFormat.get_default_format()
2190
def _set_repository_format(self, value):
2191
"""Allow changing the repository format for metadir formats."""
2192
self._repository_format = value
2194
repository_format = property(__return_repository_format,
2195
_set_repository_format)
2197
def _supply_sub_formats_to(self, other_format):
2198
"""Give other_format the same values for sub formats as this has.
2200
This method is expected to be used when parameterising a
2201
RemoteBzrDirFormat instance with the parameters from a
2202
BzrDirMetaFormat1 instance.
2204
:param other_format: other_format is a format which should be
2205
compatible with whatever sub formats are supported by self.
2208
if getattr(self, '_repository_format', None) is not None:
2209
other_format.repository_format = self.repository_format
2210
if self._branch_format is not None:
2211
other_format._branch_format = self._branch_format
2212
if self._workingtree_format is not None:
2213
other_format.workingtree_format = self.workingtree_format
2215
def __get_workingtree_format(self):
2216
if self._workingtree_format is None:
2217
from bzrlib.workingtree import WorkingTreeFormat
2218
self._workingtree_format = WorkingTreeFormat.get_default_format()
2219
return self._workingtree_format
2221
def __set_workingtree_format(self, wt_format):
2222
self._workingtree_format = wt_format
2224
workingtree_format = property(__get_workingtree_format,
2225
__set_workingtree_format)
2228
network_format_registry = registry.FormatRegistry()
2229
"""Registry of formats indexed by their network name.
2231
The network name for a BzrDirFormat is an identifier that can be used when
2232
referring to formats with smart server operations. See
2233
BzrDirFormat.network_name() for more detail.
2237
# Register bzr control format
2238
BzrDirFormat.register_control_format(BzrDirFormat)
2240
# Register bzr formats
2241
BzrDirFormat.register_format(BzrDirFormat4())
2242
BzrDirFormat.register_format(BzrDirFormat5())
2243
BzrDirFormat.register_format(BzrDirFormat6())
2244
__default_format = BzrDirMetaFormat1()
2245
BzrDirFormat.register_format(__default_format)
2246
BzrDirFormat._default_format = __default_format
2249
class Converter(object):
2250
"""Converts a disk format object from one format to another."""
2252
def convert(self, to_convert, pb):
2253
"""Perform the conversion of to_convert, giving feedback via pb.
2255
:param to_convert: The disk object to convert.
2256
:param pb: a progress bar to use for progress information.
2259
def step(self, message):
2260
"""Update the pb by a step."""
2262
self.pb.update(message, self.count, self.total)
2265
class ConvertBzrDir4To5(Converter):
2266
"""Converts format 4 bzr dirs to format 5."""
2269
super(ConvertBzrDir4To5, self).__init__()
2270
self.converted_revs = set()
2271
self.absent_revisions = set()
2275
def convert(self, to_convert, pb):
2276
"""See Converter.convert()."""
2277
self.bzrdir = to_convert
2279
self.pb.note('starting upgrade from format 4 to 5')
2280
if isinstance(self.bzrdir.transport, local.LocalTransport):
2281
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2282
self._convert_to_weaves()
2283
return BzrDir.open(self.bzrdir.root_transport.base)
2285
def _convert_to_weaves(self):
2286
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
2289
stat = self.bzrdir.transport.stat('weaves')
2290
if not S_ISDIR(stat.st_mode):
2291
self.bzrdir.transport.delete('weaves')
2292
self.bzrdir.transport.mkdir('weaves')
2293
except errors.NoSuchFile:
2294
self.bzrdir.transport.mkdir('weaves')
2295
# deliberately not a WeaveFile as we want to build it up slowly.
2296
self.inv_weave = Weave('inventory')
2297
# holds in-memory weaves for all files
2298
self.text_weaves = {}
2299
self.bzrdir.transport.delete('branch-format')
2300
self.branch = self.bzrdir.open_branch()
2301
self._convert_working_inv()
2302
rev_history = self.branch.revision_history()
2303
# to_read is a stack holding the revisions we still need to process;
2304
# appending to it adds new highest-priority revisions
2305
self.known_revisions = set(rev_history)
2306
self.to_read = rev_history[-1:]
2308
rev_id = self.to_read.pop()
2309
if (rev_id not in self.revisions
2310
and rev_id not in self.absent_revisions):
2311
self._load_one_rev(rev_id)
2313
to_import = self._make_order()
2314
for i, rev_id in enumerate(to_import):
2315
self.pb.update('converting revision', i, len(to_import))
2316
self._convert_one_rev(rev_id)
2318
self._write_all_weaves()
2319
self._write_all_revs()
2320
self.pb.note('upgraded to weaves:')
2321
self.pb.note(' %6d revisions and inventories', len(self.revisions))
2322
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
2323
self.pb.note(' %6d texts', self.text_count)
2324
self._cleanup_spare_files_after_format4()
2325
self.branch._transport.put_bytes(
2327
BzrDirFormat5().get_format_string(),
2328
mode=self.bzrdir._get_file_mode())
2330
def _cleanup_spare_files_after_format4(self):
2331
# FIXME working tree upgrade foo.
2332
for n in 'merged-patches', 'pending-merged-patches':
2334
## assert os.path.getsize(p) == 0
2335
self.bzrdir.transport.delete(n)
2336
except errors.NoSuchFile:
2338
self.bzrdir.transport.delete_tree('inventory-store')
2339
self.bzrdir.transport.delete_tree('text-store')
2341
def _convert_working_inv(self):
2342
inv = xml4.serializer_v4.read_inventory(
2343
self.branch._transport.get('inventory'))
2344
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2345
self.branch._transport.put_bytes('inventory', new_inv_xml,
2346
mode=self.bzrdir._get_file_mode())
2348
def _write_all_weaves(self):
2349
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2350
weave_transport = self.bzrdir.transport.clone('weaves')
2351
weaves = WeaveStore(weave_transport, prefixed=False)
2352
transaction = WriteTransaction()
2356
for file_id, file_weave in self.text_weaves.items():
2357
self.pb.update('writing weave', i, len(self.text_weaves))
2358
weaves._put_weave(file_id, file_weave, transaction)
2360
self.pb.update('inventory', 0, 1)
2361
controlweaves._put_weave('inventory', self.inv_weave, transaction)
2362
self.pb.update('inventory', 1, 1)
2366
def _write_all_revs(self):
2367
"""Write all revisions out in new form."""
2368
self.bzrdir.transport.delete_tree('revision-store')
2369
self.bzrdir.transport.mkdir('revision-store')
2370
revision_transport = self.bzrdir.transport.clone('revision-store')
2372
from bzrlib.xml5 import serializer_v5
2373
from bzrlib.repofmt.weaverepo import RevisionTextStore
2374
revision_store = RevisionTextStore(revision_transport,
2375
serializer_v5, False, versionedfile.PrefixMapper(),
2376
lambda:True, lambda:True)
2378
for i, rev_id in enumerate(self.converted_revs):
2379
self.pb.update('write revision', i, len(self.converted_revs))
2380
text = serializer_v5.write_revision_to_string(
2381
self.revisions[rev_id])
2383
revision_store.add_lines(key, None, osutils.split_lines(text))
2387
def _load_one_rev(self, rev_id):
2388
"""Load a revision object into memory.
2390
Any parents not either loaded or abandoned get queued to be
2392
self.pb.update('loading revision',
2393
len(self.revisions),
2394
len(self.known_revisions))
2395
if not self.branch.repository.has_revision(rev_id):
2397
self.pb.note('revision {%s} not present in branch; '
2398
'will be converted as a ghost',
2400
self.absent_revisions.add(rev_id)
2402
rev = self.branch.repository.get_revision(rev_id)
2403
for parent_id in rev.parent_ids:
2404
self.known_revisions.add(parent_id)
2405
self.to_read.append(parent_id)
2406
self.revisions[rev_id] = rev
2408
def _load_old_inventory(self, rev_id):
2409
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
2410
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2411
inv.revision_id = rev_id
2412
rev = self.revisions[rev_id]
2415
def _load_updated_inventory(self, rev_id):
2416
inv_xml = self.inv_weave.get_text(rev_id)
2417
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2420
def _convert_one_rev(self, rev_id):
2421
"""Convert revision and all referenced objects to new format."""
2422
rev = self.revisions[rev_id]
2423
inv = self._load_old_inventory(rev_id)
2424
present_parents = [p for p in rev.parent_ids
2425
if p not in self.absent_revisions]
2426
self._convert_revision_contents(rev, inv, present_parents)
2427
self._store_new_inv(rev, inv, present_parents)
2428
self.converted_revs.add(rev_id)
2430
def _store_new_inv(self, rev, inv, present_parents):
2431
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2432
new_inv_sha1 = sha_string(new_inv_xml)
2433
self.inv_weave.add_lines(rev.revision_id,
2435
new_inv_xml.splitlines(True))
2436
rev.inventory_sha1 = new_inv_sha1
2438
def _convert_revision_contents(self, rev, inv, present_parents):
2439
"""Convert all the files within a revision.
2441
Also upgrade the inventory to refer to the text revision ids."""
2442
rev_id = rev.revision_id
2443
mutter('converting texts of revision {%s}',
2445
parent_invs = map(self._load_updated_inventory, present_parents)
2446
entries = inv.iter_entries()
2448
for path, ie in entries:
2449
self._convert_file_version(rev, ie, parent_invs)
2451
def _convert_file_version(self, rev, ie, parent_invs):
2452
"""Convert one version of one file.
2454
The file needs to be added into the weave if it is a merge
2455
of >=2 parents or if it's changed from its parent.
2457
file_id = ie.file_id
2458
rev_id = rev.revision_id
2459
w = self.text_weaves.get(file_id)
2462
self.text_weaves[file_id] = w
2463
text_changed = False
2464
parent_candiate_entries = ie.parent_candidates(parent_invs)
2465
heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2466
# XXX: Note that this is unordered - and this is tolerable because
2467
# the previous code was also unordered.
2468
previous_entries = dict((head, parent_candiate_entries[head]) for head
2470
self.snapshot_ie(previous_entries, ie, w, rev_id)
2473
def get_parent_map(self, revision_ids):
2474
"""See graph._StackedParentsProvider.get_parent_map"""
2475
return dict((revision_id, self.revisions[revision_id])
2476
for revision_id in revision_ids
2477
if revision_id in self.revisions)
2479
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2480
# TODO: convert this logic, which is ~= snapshot to
2481
# a call to:. This needs the path figured out. rather than a work_tree
2482
# a v4 revision_tree can be given, or something that looks enough like
2483
# one to give the file content to the entry if it needs it.
2484
# and we need something that looks like a weave store for snapshot to
2486
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2487
if len(previous_revisions) == 1:
2488
previous_ie = previous_revisions.values()[0]
2489
if ie._unchanged(previous_ie):
2490
ie.revision = previous_ie.revision
2493
text = self.branch.repository._text_store.get(ie.text_id)
2494
file_lines = text.readlines()
2495
w.add_lines(rev_id, previous_revisions, file_lines)
2496
self.text_count += 1
2498
w.add_lines(rev_id, previous_revisions, [])
2499
ie.revision = rev_id
2501
def _make_order(self):
2502
"""Return a suitable order for importing revisions.
2504
The order must be such that an revision is imported after all
2505
its (present) parents.
2507
todo = set(self.revisions.keys())
2508
done = self.absent_revisions.copy()
2511
# scan through looking for a revision whose parents
2513
for rev_id in sorted(list(todo)):
2514
rev = self.revisions[rev_id]
2515
parent_ids = set(rev.parent_ids)
2516
if parent_ids.issubset(done):
2517
# can take this one now
2518
order.append(rev_id)
2524
class ConvertBzrDir5To6(Converter):
2525
"""Converts format 5 bzr dirs to format 6."""
2527
def convert(self, to_convert, pb):
2528
"""See Converter.convert()."""
2529
self.bzrdir = to_convert
2531
self.pb.note('starting upgrade from format 5 to 6')
2532
self._convert_to_prefixed()
2533
return BzrDir.open(self.bzrdir.root_transport.base)
2535
def _convert_to_prefixed(self):
2536
from bzrlib.store import TransportStore
2537
self.bzrdir.transport.delete('branch-format')
2538
for store_name in ["weaves", "revision-store"]:
2539
self.pb.note("adding prefixes to %s" % store_name)
2540
store_transport = self.bzrdir.transport.clone(store_name)
2541
store = TransportStore(store_transport, prefixed=True)
2542
for urlfilename in store_transport.list_dir('.'):
2543
filename = urlutils.unescape(urlfilename)
2544
if (filename.endswith(".weave") or
2545
filename.endswith(".gz") or
2546
filename.endswith(".sig")):
2547
file_id, suffix = os.path.splitext(filename)
2551
new_name = store._mapper.map((file_id,)) + suffix
2552
# FIXME keep track of the dirs made RBC 20060121
2554
store_transport.move(filename, new_name)
2555
except errors.NoSuchFile: # catches missing dirs strangely enough
2556
store_transport.mkdir(osutils.dirname(new_name))
2557
store_transport.move(filename, new_name)
2558
self.bzrdir.transport.put_bytes(
2560
BzrDirFormat6().get_format_string(),
2561
mode=self.bzrdir._get_file_mode())
2564
class ConvertBzrDir6ToMeta(Converter):
2565
"""Converts format 6 bzr dirs to metadirs."""
2567
def convert(self, to_convert, pb):
2568
"""See Converter.convert()."""
2569
from bzrlib.repofmt.weaverepo import RepositoryFormat7
2570
from bzrlib.branch import BzrBranchFormat5
2571
self.bzrdir = to_convert
2574
self.total = 20 # the steps we know about
2575
self.garbage_inventories = []
2576
self.dir_mode = self.bzrdir._get_dir_mode()
2577
self.file_mode = self.bzrdir._get_file_mode()
2579
self.pb.note('starting upgrade from format 6 to metadir')
2580
self.bzrdir.transport.put_bytes(
2582
"Converting to format 6",
2583
mode=self.file_mode)
2584
# its faster to move specific files around than to open and use the apis...
2585
# first off, nuke ancestry.weave, it was never used.
2587
self.step('Removing ancestry.weave')
2588
self.bzrdir.transport.delete('ancestry.weave')
2589
except errors.NoSuchFile:
2591
# find out whats there
2592
self.step('Finding branch files')
2593
last_revision = self.bzrdir.open_branch().last_revision()
2594
bzrcontents = self.bzrdir.transport.list_dir('.')
2595
for name in bzrcontents:
2596
if name.startswith('basis-inventory.'):
2597
self.garbage_inventories.append(name)
2598
# create new directories for repository, working tree and branch
2599
repository_names = [('inventory.weave', True),
2600
('revision-store', True),
2602
self.step('Upgrading repository ')
2603
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2604
self.make_lock('repository')
2605
# we hard code the formats here because we are converting into
2606
# the meta format. The meta format upgrader can take this to a
2607
# future format within each component.
2608
self.put_format('repository', RepositoryFormat7())
2609
for entry in repository_names:
2610
self.move_entry('repository', entry)
2612
self.step('Upgrading branch ')
2613
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2614
self.make_lock('branch')
2615
self.put_format('branch', BzrBranchFormat5())
2616
branch_files = [('revision-history', True),
2617
('branch-name', True),
2619
for entry in branch_files:
2620
self.move_entry('branch', entry)
2622
checkout_files = [('pending-merges', True),
2623
('inventory', True),
2624
('stat-cache', False)]
2625
# If a mandatory checkout file is not present, the branch does not have
2626
# a functional checkout. Do not create a checkout in the converted
2628
for name, mandatory in checkout_files:
2629
if mandatory and name not in bzrcontents:
2630
has_checkout = False
2634
if not has_checkout:
2635
self.pb.note('No working tree.')
2636
# If some checkout files are there, we may as well get rid of them.
2637
for name, mandatory in checkout_files:
2638
if name in bzrcontents:
2639
self.bzrdir.transport.delete(name)
2641
from bzrlib.workingtree import WorkingTreeFormat3
2642
self.step('Upgrading working tree')
2643
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2644
self.make_lock('checkout')
2646
'checkout', WorkingTreeFormat3())
2647
self.bzrdir.transport.delete_multi(
2648
self.garbage_inventories, self.pb)
2649
for entry in checkout_files:
2650
self.move_entry('checkout', entry)
2651
if last_revision is not None:
2652
self.bzrdir.transport.put_bytes(
2653
'checkout/last-revision', last_revision)
2654
self.bzrdir.transport.put_bytes(
2656
BzrDirMetaFormat1().get_format_string(),
2657
mode=self.file_mode)
2658
return BzrDir.open(self.bzrdir.root_transport.base)
2660
def make_lock(self, name):
2661
"""Make a lock for the new control dir name."""
2662
self.step('Make %s lock' % name)
2663
ld = lockdir.LockDir(self.bzrdir.transport,
2665
file_modebits=self.file_mode,
2666
dir_modebits=self.dir_mode)
2669
def move_entry(self, new_dir, entry):
2670
"""Move then entry name into new_dir."""
2672
mandatory = entry[1]
2673
self.step('Moving %s' % name)
2675
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2676
except errors.NoSuchFile:
2680
def put_format(self, dirname, format):
2681
self.bzrdir.transport.put_bytes('%s/format' % dirname,
2682
format.get_format_string(),
2686
class ConvertMetaToMeta(Converter):
2687
"""Converts the components of metadirs."""
2689
def __init__(self, target_format):
2690
"""Create a metadir to metadir converter.
2692
:param target_format: The final metadir format that is desired.
2694
self.target_format = target_format
2696
def convert(self, to_convert, pb):
2697
"""See Converter.convert()."""
2698
self.bzrdir = to_convert
2702
self.step('checking repository format')
2704
repo = self.bzrdir.open_repository()
2705
except errors.NoRepositoryPresent:
2708
if not isinstance(repo._format, self.target_format.repository_format.__class__):
2709
from bzrlib.repository import CopyConverter
2710
self.pb.note('starting repository conversion')
2711
converter = CopyConverter(self.target_format.repository_format)
2712
converter.convert(repo, pb)
2714
branch = self.bzrdir.open_branch()
2715
except errors.NotBranchError:
2718
# TODO: conversions of Branch and Tree should be done by
2719
# InterXFormat lookups/some sort of registry.
2720
# Avoid circular imports
2721
from bzrlib import branch as _mod_branch
2722
old = branch._format.__class__
2723
new = self.target_format.get_branch_format().__class__
2725
if (old == _mod_branch.BzrBranchFormat5 and
2726
new in (_mod_branch.BzrBranchFormat6,
2727
_mod_branch.BzrBranchFormat7)):
2728
branch_converter = _mod_branch.Converter5to6()
2729
elif (old == _mod_branch.BzrBranchFormat6 and
2730
new == _mod_branch.BzrBranchFormat7):
2731
branch_converter = _mod_branch.Converter6to7()
2733
raise errors.BadConversionTarget("No converter", new)
2734
branch_converter.convert(branch)
2735
branch = self.bzrdir.open_branch()
2736
old = branch._format.__class__
2738
tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2739
except (errors.NoWorkingTree, errors.NotLocalUrl):
2742
# TODO: conversions of Branch and Tree should be done by
2743
# InterXFormat lookups
2744
if (isinstance(tree, workingtree.WorkingTree3) and
2745
not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2746
isinstance(self.target_format.workingtree_format,
2747
workingtree_4.DirStateWorkingTreeFormat)):
2748
workingtree_4.Converter3to4().convert(tree)
2749
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2750
not isinstance(tree, workingtree_4.WorkingTree5) and
2751
isinstance(self.target_format.workingtree_format,
2752
workingtree_4.WorkingTreeFormat5)):
2753
workingtree_4.Converter4to5().convert(tree)
2757
# This is not in remote.py because it's small, and needs to be registered.
2758
# Putting it in remote.py creates a circular import problem.
2759
# we can make it a lazy object if the control formats is turned into something
2761
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2762
"""Format representing bzrdirs accessed via a smart server"""
2765
BzrDirMetaFormat1.__init__(self)
2766
self._network_name = None
2768
def get_format_description(self):
2769
return 'bzr remote bzrdir'
2771
def get_format_string(self):
2772
raise NotImplementedError(self.get_format_string)
2774
def network_name(self):
2775
if self._network_name:
2776
return self._network_name
2778
raise AssertionError("No network name set.")
2781
def probe_transport(klass, transport):
2782
"""Return a RemoteBzrDirFormat object if it looks possible."""
2784
medium = transport.get_smart_medium()
2785
except (NotImplementedError, AttributeError,
2786
errors.TransportNotPossible, errors.NoSmartMedium,
2787
errors.SmartProtocolError):
2788
# no smart server, so not a branch for this format type.
2789
raise errors.NotBranchError(path=transport.base)
2791
# Decline to open it if the server doesn't support our required
2792
# version (3) so that the VFS-based transport will do it.
2793
if medium.should_probe():
2795
server_version = medium.protocol_version()
2796
except errors.SmartProtocolError:
2797
# Apparently there's no usable smart server there, even though
2798
# the medium supports the smart protocol.
2799
raise errors.NotBranchError(path=transport.base)
2800
if server_version != '2':
2801
raise errors.NotBranchError(path=transport.base)
2804
def initialize_on_transport(self, transport):
2806
# hand off the request to the smart server
2807
client_medium = transport.get_smart_medium()
2808
except errors.NoSmartMedium:
2809
# TODO: lookup the local format from a server hint.
2810
local_dir_format = BzrDirMetaFormat1()
2811
return local_dir_format.initialize_on_transport(transport)
2812
client = _SmartClient(client_medium)
2813
path = client.remote_path_from_transport(transport)
2814
response = client.call('BzrDirFormat.initialize', path)
2815
if response[0] != 'ok':
2816
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2817
format = RemoteBzrDirFormat()
2818
self._supply_sub_formats_to(format)
2819
return remote.RemoteBzrDir(transport, format)
2821
def _open(self, transport):
2822
return remote.RemoteBzrDir(transport, self)
2824
def __eq__(self, other):
2825
if not isinstance(other, RemoteBzrDirFormat):
2827
return self.get_format_description() == other.get_format_description()
2829
def __return_repository_format(self):
2830
# Always return a RemoteRepositoryFormat object, but if a specific bzr
2831
# repository format has been asked for, tell the RemoteRepositoryFormat
2832
# that it should use that for init() etc.
2833
result = remote.RemoteRepositoryFormat()
2834
custom_format = getattr(self, '_repository_format', None)
2836
if isinstance(custom_format, remote.RemoteRepositoryFormat):
2837
return custom_format
2839
# We will use the custom format to create repositories over the
2840
# wire; expose its details like rich_root_data for code to
2842
result._custom_format = custom_format
2845
def get_branch_format(self):
2846
result = BzrDirMetaFormat1.get_branch_format(self)
2847
if not isinstance(result, remote.RemoteBranchFormat):
2848
new_result = remote.RemoteBranchFormat()
2849
new_result._custom_format = result
2851
self.set_branch_format(new_result)
2855
repository_format = property(__return_repository_format,
2856
BzrDirMetaFormat1._set_repository_format) #.im_func)
2859
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2862
class BzrDirFormatInfo(object):
2864
def __init__(self, native, deprecated, hidden, experimental):
2865
self.deprecated = deprecated
2866
self.native = native
2867
self.hidden = hidden
2868
self.experimental = experimental
2871
class BzrDirFormatRegistry(registry.Registry):
2872
"""Registry of user-selectable BzrDir subformats.
2874
Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2875
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
2879
"""Create a BzrDirFormatRegistry."""
2880
self._aliases = set()
2881
self._registration_order = list()
2882
super(BzrDirFormatRegistry, self).__init__()
2885
"""Return a set of the format names which are aliases."""
2886
return frozenset(self._aliases)
2888
def register_metadir(self, key,
2889
repository_format, help, native=True, deprecated=False,
2895
"""Register a metadir subformat.
2897
These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2898
by the Repository/Branch/WorkingTreeformats.
2900
:param repository_format: The fully-qualified repository format class
2902
:param branch_format: Fully-qualified branch format class name as
2904
:param tree_format: Fully-qualified tree format class name as
2907
# This should be expanded to support setting WorkingTree and Branch
2908
# formats, once BzrDirMetaFormat1 supports that.
2909
def _load(full_name):
2910
mod_name, factory_name = full_name.rsplit('.', 1)
2912
mod = __import__(mod_name, globals(), locals(),
2914
except ImportError, e:
2915
raise ImportError('failed to load %s: %s' % (full_name, e))
2917
factory = getattr(mod, factory_name)
2918
except AttributeError:
2919
raise AttributeError('no factory %s in module %r'
2924
bd = BzrDirMetaFormat1()
2925
if branch_format is not None:
2926
bd.set_branch_format(_load(branch_format))
2927
if tree_format is not None:
2928
bd.workingtree_format = _load(tree_format)
2929
if repository_format is not None:
2930
bd.repository_format = _load(repository_format)
2932
self.register(key, helper, help, native, deprecated, hidden,
2933
experimental, alias)
2935
def register(self, key, factory, help, native=True, deprecated=False,
2936
hidden=False, experimental=False, alias=False):
2937
"""Register a BzrDirFormat factory.
2939
The factory must be a callable that takes one parameter: the key.
2940
It must produce an instance of the BzrDirFormat when called.
2942
This function mainly exists to prevent the info object from being
2945
registry.Registry.register(self, key, factory, help,
2946
BzrDirFormatInfo(native, deprecated, hidden, experimental))
2948
self._aliases.add(key)
2949
self._registration_order.append(key)
2951
def register_lazy(self, key, module_name, member_name, help, native=True,
2952
deprecated=False, hidden=False, experimental=False, alias=False):
2953
registry.Registry.register_lazy(self, key, module_name, member_name,
2954
help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
2956
self._aliases.add(key)
2957
self._registration_order.append(key)
2959
def set_default(self, key):
2960
"""Set the 'default' key to be a clone of the supplied key.
2962
This method must be called once and only once.
2964
registry.Registry.register(self, 'default', self.get(key),
2965
self.get_help(key), info=self.get_info(key))
2966
self._aliases.add('default')
2968
def set_default_repository(self, key):
2969
"""Set the FormatRegistry default and Repository default.
2971
This is a transitional method while Repository.set_default_format
2974
if 'default' in self:
2975
self.remove('default')
2976
self.set_default(key)
2977
format = self.get('default')()
2979
def make_bzrdir(self, key):
2980
return self.get(key)()
2982
def help_topic(self, topic):
2984
default_realkey = None
2985
default_help = self.get_help('default')
2987
for key in self._registration_order:
2988
if key == 'default':
2990
help = self.get_help(key)
2991
if help == default_help:
2992
default_realkey = key
2994
help_pairs.append((key, help))
2996
def wrapped(key, help, info):
2998
help = '(native) ' + help
2999
return ':%s:\n%s\n\n' % (key,
3000
textwrap.fill(help, initial_indent=' ',
3001
subsequent_indent=' '))
3002
if default_realkey is not None:
3003
output += wrapped(default_realkey, '(default) %s' % default_help,
3004
self.get_info('default'))
3005
deprecated_pairs = []
3006
experimental_pairs = []
3007
for key, help in help_pairs:
3008
info = self.get_info(key)
3011
elif info.deprecated:
3012
deprecated_pairs.append((key, help))
3013
elif info.experimental:
3014
experimental_pairs.append((key, help))
3016
output += wrapped(key, help, info)
3017
output += "\nSee ``bzr help formats`` for more about storage formats."
3019
if len(experimental_pairs) > 0:
3020
other_output += "Experimental formats are shown below.\n\n"
3021
for key, help in experimental_pairs:
3022
info = self.get_info(key)
3023
other_output += wrapped(key, help, info)
3026
"No experimental formats are available.\n\n"
3027
if len(deprecated_pairs) > 0:
3028
other_output += "\nDeprecated formats are shown below.\n\n"
3029
for key, help in deprecated_pairs:
3030
info = self.get_info(key)
3031
other_output += wrapped(key, help, info)
3034
"\nNo deprecated formats are available.\n\n"
3036
"\nSee ``bzr help formats`` for more about storage formats."
3038
if topic == 'other-formats':
3044
class RepositoryAcquisitionPolicy(object):
3045
"""Abstract base class for repository acquisition policies.
3047
A repository acquisition policy decides how a BzrDir acquires a repository
3048
for a branch that is being created. The most basic policy decision is
3049
whether to create a new repository or use an existing one.
3051
def __init__(self, stack_on, stack_on_pwd, require_stacking):
3054
:param stack_on: A location to stack on
3055
:param stack_on_pwd: If stack_on is relative, the location it is
3057
:param require_stacking: If True, it is a failure to not stack.
3059
self._stack_on = stack_on
3060
self._stack_on_pwd = stack_on_pwd
3061
self._require_stacking = require_stacking
3063
def configure_branch(self, branch):
3064
"""Apply any configuration data from this policy to the branch.
3066
Default implementation sets repository stacking.
3068
if self._stack_on is None:
3070
if self._stack_on_pwd is None:
3071
stack_on = self._stack_on
3074
stack_on = urlutils.rebase_url(self._stack_on,
3076
branch.bzrdir.root_transport.base)
3077
except errors.InvalidRebaseURLs:
3078
stack_on = self._get_full_stack_on()
3080
branch.set_stacked_on_url(stack_on)
3081
except (errors.UnstackableBranchFormat,
3082
errors.UnstackableRepositoryFormat):
3083
if self._require_stacking:
3086
def _get_full_stack_on(self):
3087
"""Get a fully-qualified URL for the stack_on location."""
3088
if self._stack_on is None:
3090
if self._stack_on_pwd is None:
3091
return self._stack_on
3093
return urlutils.join(self._stack_on_pwd, self._stack_on)
3095
def _add_fallback(self, repository, possible_transports=None):
3096
"""Add a fallback to the supplied repository, if stacking is set."""
3097
stack_on = self._get_full_stack_on()
3098
if stack_on is None:
3100
stacked_dir = BzrDir.open(stack_on,
3101
possible_transports=possible_transports)
3103
stacked_repo = stacked_dir.open_branch().repository
3104
except errors.NotBranchError:
3105
stacked_repo = stacked_dir.open_repository()
3107
repository.add_fallback_repository(stacked_repo)
3108
except errors.UnstackableRepositoryFormat:
3109
if self._require_stacking:
3112
self._require_stacking = True
3114
def acquire_repository(self, make_working_trees=None, shared=False):
3115
"""Acquire a repository for this bzrdir.
3117
Implementations may create a new repository or use a pre-exising
3119
:param make_working_trees: If creating a repository, set
3120
make_working_trees to this value (if non-None)
3121
:param shared: If creating a repository, make it shared if True
3122
:return: A repository, is_new_flag (True if the repository was
3125
raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
3128
class CreateRepository(RepositoryAcquisitionPolicy):
3129
"""A policy of creating a new repository"""
3131
def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3132
require_stacking=False):
3135
:param bzrdir: The bzrdir to create the repository on.
3136
:param stack_on: A location to stack on
3137
:param stack_on_pwd: If stack_on is relative, the location it is
3140
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3142
self._bzrdir = bzrdir
3144
def acquire_repository(self, make_working_trees=None, shared=False):
3145
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3147
Creates the desired repository in the bzrdir we already have.
3149
stack_on = self._get_full_stack_on()
3151
# Stacking is desired. requested by the target, but does the place it
3152
# points at support stacking? If it doesn't then we should
3153
# not implicitly upgrade. We check this here.
3154
format = self._bzrdir._format
3155
if not (format.repository_format.supports_external_lookups
3156
and format.get_branch_format().supports_stacking()):
3157
# May need to upgrade - but only do if the target also
3158
# supports stacking. Note that this currently wastes
3159
# network round trips to check - but we only do this
3160
# when the source can't stack so it will fade away
3161
# as people do upgrade.
3163
target_dir = BzrDir.open(stack_on,
3164
possible_transports=[self._bzrdir.root_transport])
3165
except errors.NotBranchError:
3166
# Nothing there, don't change formats
3170
target_branch = target_dir.open_branch()
3171
except errors.NotBranchError:
3172
# No branch, don't change formats
3175
branch_format = target_branch._format
3176
repo_format = target_branch.repository._format
3177
if not (branch_format.supports_stacking()
3178
and repo_format.supports_external_lookups):
3179
# Doesn't stack itself, don't force an upgrade
3182
# Does support stacking, use its format.
3183
format.repository_format = repo_format
3184
format.set_branch_format(branch_format)
3185
note('Source format does not support stacking, '
3186
'using format: \'%s\'\n %s\n',
3187
branch_format.get_format_description(),
3188
repo_format.get_format_description())
3189
if not self._require_stacking:
3190
# We have picked up automatic stacking somewhere.
3191
note('Using default stacking branch %s at %s', self._stack_on,
3193
repository = self._bzrdir.create_repository(shared=shared)
3194
self._add_fallback(repository,
3195
possible_transports=[self._bzrdir.transport])
3196
if make_working_trees is not None:
3197
repository.set_make_working_trees(make_working_trees)
3198
return repository, True
3201
class UseExistingRepository(RepositoryAcquisitionPolicy):
3202
"""A policy of reusing an existing repository"""
3204
def __init__(self, repository, stack_on=None, stack_on_pwd=None,
3205
require_stacking=False):
3208
:param repository: The repository to use.
3209
:param stack_on: A location to stack on
3210
:param stack_on_pwd: If stack_on is relative, the location it is
3213
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3215
self._repository = repository
3217
def acquire_repository(self, make_working_trees=None, shared=False):
3218
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3220
Returns an existing repository to use.
3222
self._add_fallback(self._repository,
3223
possible_transports=[self._repository.bzrdir.transport])
3224
return self._repository, False
3227
# Please register new formats after old formats so that formats
3228
# appear in chronological order and format descriptions can build
3230
format_registry = BzrDirFormatRegistry()
3231
# The pre-0.8 formats have their repository format network name registered in
3232
# repository.py. MetaDir formats have their repository format network name
3233
# inferred from their disk format string.
3234
format_registry.register('weave', BzrDirFormat6,
3235
'Pre-0.8 format. Slower than knit and does not'
3236
' support checkouts or shared repositories.',
3238
format_registry.register_metadir('metaweave',
3239
'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3240
'Transitional format in 0.8. Slower than knit.',
3241
branch_format='bzrlib.branch.BzrBranchFormat5',
3242
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3244
format_registry.register_metadir('knit',
3245
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3246
'Format using knits. Recommended for interoperation with bzr <= 0.14.',
3247
branch_format='bzrlib.branch.BzrBranchFormat5',
3248
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3250
format_registry.register_metadir('dirstate',
3251
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3252
help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3253
'above when accessed over the network.',
3254
branch_format='bzrlib.branch.BzrBranchFormat5',
3255
# this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3256
# directly from workingtree_4 triggers a circular import.
3257
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3259
format_registry.register_metadir('dirstate-tags',
3260
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3261
help='New in 0.15: Fast local operations and improved scaling for '
3262
'network operations. Additionally adds support for tags.'
3263
' Incompatible with bzr < 0.15.',
3264
branch_format='bzrlib.branch.BzrBranchFormat6',
3265
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3267
format_registry.register_metadir('rich-root',
3268
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3269
help='New in 1.0. Better handling of tree roots. Incompatible with'
3271
branch_format='bzrlib.branch.BzrBranchFormat6',
3272
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3274
format_registry.register_metadir('dirstate-with-subtree',
3275
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3276
help='New in 0.15: Fast local operations and improved scaling for '
3277
'network operations. Additionally adds support for versioning nested '
3278
'bzr branches. Incompatible with bzr < 0.15.',
3279
branch_format='bzrlib.branch.BzrBranchFormat6',
3280
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3284
format_registry.register_metadir('pack-0.92',
3285
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3286
help='New in 0.92: Pack-based format with data compatible with '
3287
'dirstate-tags format repositories. Interoperates with '
3288
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3289
'Previously called knitpack-experimental. '
3290
'For more information, see '
3291
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3292
branch_format='bzrlib.branch.BzrBranchFormat6',
3293
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3295
format_registry.register_metadir('pack-0.92-subtree',
3296
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3297
help='New in 0.92: Pack-based format with data compatible with '
3298
'dirstate-with-subtree format repositories. Interoperates with '
3299
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3300
'Previously called knitpack-experimental. '
3301
'For more information, see '
3302
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3303
branch_format='bzrlib.branch.BzrBranchFormat6',
3304
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3308
format_registry.register_metadir('rich-root-pack',
3309
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3310
help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3311
'(needed for bzr-svn and bzr-git).',
3312
branch_format='bzrlib.branch.BzrBranchFormat6',
3313
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3315
format_registry.register_metadir('1.6',
3316
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3317
help='A format that allows a branch to indicate that there is another '
3318
'(stacked) repository that should be used to access data that is '
3319
'not present locally.',
3320
branch_format='bzrlib.branch.BzrBranchFormat7',
3321
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3323
format_registry.register_metadir('1.6.1-rich-root',
3324
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3325
help='A variant of 1.6 that supports rich-root data '
3326
'(needed for bzr-svn and bzr-git).',
3327
branch_format='bzrlib.branch.BzrBranchFormat7',
3328
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3330
format_registry.register_metadir('1.9',
3331
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3332
help='A repository format using B+tree indexes. These indexes '
3333
'are smaller in size, have smarter caching and provide faster '
3334
'performance for most operations.',
3335
branch_format='bzrlib.branch.BzrBranchFormat7',
3336
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3338
format_registry.register_metadir('1.9-rich-root',
3339
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3340
help='A variant of 1.9 that supports rich-root data '
3341
'(needed for bzr-svn and bzr-git).',
3342
branch_format='bzrlib.branch.BzrBranchFormat7',
3343
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3345
format_registry.register_metadir('development-wt5',
3346
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3347
help='A working-tree format that supports views and content filtering.',
3348
branch_format='bzrlib.branch.BzrBranchFormat7',
3349
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3352
format_registry.register_metadir('development-wt5-rich-root',
3353
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3354
help='A variant of development-wt5 that supports rich-root data '
3355
'(needed for bzr-svn and bzr-git).',
3356
branch_format='bzrlib.branch.BzrBranchFormat7',
3357
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3360
# The following two formats should always just be aliases.
3361
format_registry.register_metadir('development',
3362
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
3363
help='Current development format. Can convert data to and from pack-0.92 '
3364
'(and anything compatible with pack-0.92) format repositories. '
3365
'Repositories and branches in this format can only be read by bzr.dev. '
3367
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3369
branch_format='bzrlib.branch.BzrBranchFormat7',
3370
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3374
format_registry.register_metadir('development-subtree',
3375
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3376
help='Current development format, subtree variant. Can convert data to and '
3377
'from pack-0.92-subtree (and anything compatible with '
3378
'pack-0.92-subtree) format repositories. Repositories and branches in '
3379
'this format can only be read by bzr.dev. Please read '
3380
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3382
branch_format='bzrlib.branch.BzrBranchFormat7',
3383
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3387
# And the development formats above will have aliased one of the following:
3388
format_registry.register_metadir('development2',
3389
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
3390
help='1.6.1 with B+Tree based index. '
3392
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3394
branch_format='bzrlib.branch.BzrBranchFormat7',
3395
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3399
format_registry.register_metadir('development2-subtree',
3400
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3401
help='1.6.1-subtree with B+Tree based index. '
3403
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3405
branch_format='bzrlib.branch.BzrBranchFormat7',
3406
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3410
# The following format should be an alias for the rich root equivalent
3411
# of the default format
3412
format_registry.register_metadir('default-rich-root',
3413
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3414
help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
3415
branch_format='bzrlib.branch.BzrBranchFormat6',
3416
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3419
# The current format that is made on 'bzr init'.
3420
format_registry.set_default('pack-0.92')