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
48
revision as _mod_revision,
58
from bzrlib.osutils import (
61
from bzrlib.push import (
64
from bzrlib.smart.client import _SmartClient
65
from bzrlib.store.versioned import WeaveStore
66
from bzrlib.transactions import WriteTransaction
67
from bzrlib.transport import (
68
do_catching_redirections,
71
remote as remote_transport,
73
from bzrlib.weave import Weave
76
from bzrlib.trace import (
89
"""A .bzr control diretory.
91
BzrDir instances let you create or open any of the things that can be
92
found within .bzr - checkouts, branches and repositories.
95
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
97
a transport connected to the directory this bzr was opened from
98
(i.e. the parent directory holding the .bzr directory).
100
Everything in the bzrdir should have the same file permissions.
102
:cvar hooks: An instance of BzrDirHooks.
105
def break_lock(self):
106
"""Invoke break_lock on the first object in the bzrdir.
108
If there is a tree, the tree is opened and break_lock() called.
109
Otherwise, branch is tried, and finally repository.
111
# XXX: This seems more like a UI function than something that really
112
# belongs in this class.
114
thing_to_unlock = self.open_workingtree()
115
except (errors.NotLocalUrl, errors.NoWorkingTree):
117
thing_to_unlock = self.open_branch()
118
except errors.NotBranchError:
120
thing_to_unlock = self.open_repository()
121
except errors.NoRepositoryPresent:
123
thing_to_unlock.break_lock()
125
def can_convert_format(self):
126
"""Return true if this bzrdir is one whose format we can convert from."""
129
def check_conversion_target(self, target_format):
130
target_repo_format = target_format.repository_format
131
source_repo_format = self._format.repository_format
132
source_repo_format.check_conversion_target(target_repo_format)
135
def _check_supported(format, allow_unsupported,
136
recommend_upgrade=True,
138
"""Give an error or warning on old formats.
140
:param format: may be any kind of format - workingtree, branch,
143
:param allow_unsupported: If true, allow opening
144
formats that are strongly deprecated, and which may
145
have limited functionality.
147
:param recommend_upgrade: If true (default), warn
148
the user through the ui object that they may wish
149
to upgrade the object.
151
# TODO: perhaps move this into a base Format class; it's not BzrDir
152
# specific. mbp 20070323
153
if not allow_unsupported and not format.is_supported():
154
# see open_downlevel to open legacy branches.
155
raise errors.UnsupportedFormatError(format=format)
156
if recommend_upgrade \
157
and getattr(format, 'upgrade_recommended', False):
158
ui.ui_factory.recommend_upgrade(
159
format.get_format_description(),
162
def clone(self, url, revision_id=None, force_new_repo=False,
163
preserve_stacking=False):
164
"""Clone this bzrdir and its contents to url verbatim.
166
:param url: The url create the clone at. If url's last component does
167
not exist, it will be created.
168
:param revision_id: The tip revision-id to use for any branch or
169
working tree. If not None, then the clone operation may tune
170
itself to download less data.
171
:param force_new_repo: Do not use a shared repository for the target
172
even if one is available.
173
:param preserve_stacking: When cloning a stacked branch, stack the
174
new branch on top of the other branch's stacked-on branch.
176
return self.clone_on_transport(get_transport(url),
177
revision_id=revision_id,
178
force_new_repo=force_new_repo,
179
preserve_stacking=preserve_stacking)
181
def clone_on_transport(self, transport, revision_id=None,
182
force_new_repo=False, preserve_stacking=False, stacked_on=None,
183
create_prefix=False, use_existing_dir=True):
184
"""Clone this bzrdir and its contents to transport verbatim.
186
:param transport: The transport for the location to produce the clone
187
at. If the target directory does not exist, it will be created.
188
:param revision_id: The tip revision-id to use for any branch or
189
working tree. If not None, then the clone operation may tune
190
itself to download less data.
191
:param force_new_repo: Do not use a shared repository for the target,
192
even if one is available.
193
:param preserve_stacking: When cloning a stacked branch, stack the
194
new branch on top of the other branch's stacked-on branch.
195
:param create_prefix: Create any missing directories leading up to
197
:param use_existing_dir: Use an existing directory if one exists.
199
# Overview: put together a broad description of what we want to end up
200
# with; then make as few api calls as possible to do it.
202
# We may want to create a repo/branch/tree, if we do so what format
203
# would we want for each:
204
require_stacking = (stacked_on is not None)
205
format = self.cloning_metadir(require_stacking)
207
# Figure out what objects we want:
209
local_repo = self.find_repository()
210
except errors.NoRepositoryPresent:
213
local_branch = self.open_branch()
214
except errors.NotBranchError:
217
# enable fallbacks when branch is not a branch reference
218
if local_branch.repository.has_same_location(local_repo):
219
local_repo = local_branch.repository
220
if preserve_stacking:
222
stacked_on = local_branch.get_stacked_on_url()
223
except (errors.UnstackableBranchFormat,
224
errors.UnstackableRepositoryFormat,
227
# Bug: We create a metadir without knowing if it can support stacking,
228
# we should look up the policy needs first, or just use it as a hint,
231
make_working_trees = local_repo.make_working_trees()
232
want_shared = local_repo.is_shared()
233
repo_format_name = format.repository_format.network_name()
235
make_working_trees = False
237
repo_format_name = None
239
result_repo, result, require_stacking, repository_policy = \
240
format.initialize_on_transport_ex(transport,
241
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
242
force_new_repo=force_new_repo, stacked_on=stacked_on,
243
stack_on_pwd=self.root_transport.base,
244
repo_format_name=repo_format_name,
245
make_working_trees=make_working_trees, shared_repo=want_shared)
247
# If the result repository is in the same place as the resulting
248
# bzr dir, it will have no content, further if the result is not stacked
249
# then we know all content should be copied, and finally if we are
250
# copying up to a specific revision_id then we can use the
251
# pending-ancestry-result which does not require traversing all of
252
# history to describe it.
253
if (result_repo.bzrdir.root_transport.base ==
254
result.root_transport.base and not require_stacking and
255
revision_id is not None):
256
fetch_spec = graph.PendingAncestryResult(
257
[revision_id], local_repo)
258
result_repo.fetch(local_repo, fetch_spec=fetch_spec)
260
result_repo.fetch(local_repo, revision_id=revision_id)
263
# 1 if there is a branch present
264
# make sure its content is available in the target repository
266
if local_branch is not None:
267
result_branch = local_branch.clone(result, revision_id=revision_id,
268
repository_policy=repository_policy)
270
# Cheaper to check if the target is not local, than to try making
272
result.root_transport.local_abspath('.')
273
if result_repo is None or result_repo.make_working_trees():
274
self.open_workingtree().clone(result)
275
except (errors.NoWorkingTree, errors.NotLocalUrl):
279
# TODO: This should be given a Transport, and should chdir up; otherwise
280
# this will open a new connection.
281
def _make_tail(self, url):
282
t = get_transport(url)
286
def create(cls, base, format=None, possible_transports=None):
287
"""Create a new BzrDir at the url 'base'.
289
:param format: If supplied, the format of branch to create. If not
290
supplied, the default is used.
291
:param possible_transports: If supplied, a list of transports that
292
can be reused to share a remote connection.
294
if cls is not BzrDir:
295
raise AssertionError("BzrDir.create always creates the default"
296
" format, not one of %r" % cls)
297
t = get_transport(base, possible_transports)
300
format = BzrDirFormat.get_default_format()
301
return format.initialize_on_transport(t)
304
def find_bzrdirs(transport, evaluate=None, list_current=None):
305
"""Find bzrdirs recursively from current location.
307
This is intended primarily as a building block for more sophisticated
308
functionality, like finding trees under a directory, or finding
309
branches that use a given repository.
310
:param evaluate: An optional callable that yields recurse, value,
311
where recurse controls whether this bzrdir is recursed into
312
and value is the value to yield. By default, all bzrdirs
313
are recursed into, and the return value is the bzrdir.
314
:param list_current: if supplied, use this function to list the current
315
directory, instead of Transport.list_dir
316
:return: a generator of found bzrdirs, or whatever evaluate returns.
318
if list_current is None:
319
def list_current(transport):
320
return transport.list_dir('')
322
def evaluate(bzrdir):
325
pending = [transport]
326
while len(pending) > 0:
327
current_transport = pending.pop()
330
bzrdir = BzrDir.open_from_transport(current_transport)
331
except errors.NotBranchError:
334
recurse, value = evaluate(bzrdir)
337
subdirs = list_current(current_transport)
338
except errors.NoSuchFile:
341
for subdir in sorted(subdirs, reverse=True):
342
pending.append(current_transport.clone(subdir))
345
def find_branches(transport):
346
"""Find all branches under a transport.
348
This will find all branches below the transport, including branches
349
inside other branches. Where possible, it will use
350
Repository.find_branches.
352
To list all the branches that use a particular Repository, see
353
Repository.find_branches
355
def evaluate(bzrdir):
357
repository = bzrdir.open_repository()
358
except errors.NoRepositoryPresent:
361
return False, (None, repository)
363
branch = bzrdir.open_branch()
364
except errors.NotBranchError:
365
return True, (None, None)
367
return True, (branch, None)
369
for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
371
branches.extend(repo.find_branches())
372
if branch is not None:
373
branches.append(branch)
376
def destroy_repository(self):
377
"""Destroy the repository in this BzrDir"""
378
raise NotImplementedError(self.destroy_repository)
380
def create_branch(self):
381
"""Create a branch in this BzrDir.
383
The bzrdir's format will control what branch format is created.
384
For more control see BranchFormatXX.create(a_bzrdir).
386
raise NotImplementedError(self.create_branch)
388
def destroy_branch(self):
389
"""Destroy the branch in this BzrDir"""
390
raise NotImplementedError(self.destroy_branch)
393
def create_branch_and_repo(base, force_new_repo=False, format=None):
394
"""Create a new BzrDir, Branch and Repository at the url 'base'.
396
This will use the current default BzrDirFormat unless one is
397
specified, and use whatever
398
repository format that that uses via bzrdir.create_branch and
399
create_repository. If a shared repository is available that is used
402
The created Branch object is returned.
404
:param base: The URL to create the branch at.
405
:param force_new_repo: If True a new repository is always created.
406
:param format: If supplied, the format of branch to create. If not
407
supplied, the default is used.
409
bzrdir = BzrDir.create(base, format)
410
bzrdir._find_or_create_repository(force_new_repo)
411
return bzrdir.create_branch()
413
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
414
stack_on_pwd=None, require_stacking=False):
415
"""Return an object representing a policy to use.
417
This controls whether a new repository is created, and the format of
418
that repository, or some existing shared repository used instead.
420
If stack_on is supplied, will not seek a containing shared repo.
422
:param force_new_repo: If True, require a new repository to be created.
423
:param stack_on: If supplied, the location to stack on. If not
424
supplied, a default_stack_on location may be used.
425
:param stack_on_pwd: If stack_on is relative, the location it is
428
def repository_policy(found_bzrdir):
431
config = found_bzrdir.get_config()
433
stack_on = config.get_default_stack_on()
434
if stack_on is not None:
435
stack_on_pwd = found_bzrdir.root_transport.base
437
# does it have a repository ?
439
repository = found_bzrdir.open_repository()
440
except errors.NoRepositoryPresent:
443
if ((found_bzrdir.root_transport.base !=
444
self.root_transport.base) and not repository.is_shared()):
445
# Don't look higher, can't use a higher shared repo.
453
return UseExistingRepository(repository, stack_on,
454
stack_on_pwd, require_stacking=require_stacking), True
456
return CreateRepository(self, stack_on, stack_on_pwd,
457
require_stacking=require_stacking), True
459
if not force_new_repo:
461
policy = self._find_containing(repository_policy)
462
if policy is not None:
466
return UseExistingRepository(self.open_repository(),
467
stack_on, stack_on_pwd,
468
require_stacking=require_stacking)
469
except errors.NoRepositoryPresent:
471
return CreateRepository(self, stack_on, stack_on_pwd,
472
require_stacking=require_stacking)
474
def _find_or_create_repository(self, force_new_repo):
475
"""Create a new repository if needed, returning the repository."""
476
policy = self.determine_repository_policy(force_new_repo)
477
return policy.acquire_repository()[0]
480
def create_branch_convenience(base, force_new_repo=False,
481
force_new_tree=None, format=None,
482
possible_transports=None):
483
"""Create a new BzrDir, Branch and Repository at the url 'base'.
485
This is a convenience function - it will use an existing repository
486
if possible, can be told explicitly whether to create a working tree or
489
This will use the current default BzrDirFormat unless one is
490
specified, and use whatever
491
repository format that that uses via bzrdir.create_branch and
492
create_repository. If a shared repository is available that is used
493
preferentially. Whatever repository is used, its tree creation policy
496
The created Branch object is returned.
497
If a working tree cannot be made due to base not being a file:// url,
498
no error is raised unless force_new_tree is True, in which case no
499
data is created on disk and NotLocalUrl is raised.
501
:param base: The URL to create the branch at.
502
:param force_new_repo: If True a new repository is always created.
503
:param force_new_tree: If True or False force creation of a tree or
504
prevent such creation respectively.
505
:param format: Override for the bzrdir format to create.
506
:param possible_transports: An optional reusable transports list.
509
# check for non local urls
510
t = get_transport(base, possible_transports)
511
if not isinstance(t, local.LocalTransport):
512
raise errors.NotLocalUrl(base)
513
bzrdir = BzrDir.create(base, format, possible_transports)
514
repo = bzrdir._find_or_create_repository(force_new_repo)
515
result = bzrdir.create_branch()
516
if force_new_tree or (repo.make_working_trees() and
517
force_new_tree is None):
519
bzrdir.create_workingtree()
520
except errors.NotLocalUrl:
525
def create_standalone_workingtree(base, format=None):
526
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
528
'base' must be a local path or a file:// url.
530
This will use the current default BzrDirFormat unless one is
531
specified, and use whatever
532
repository format that that uses for bzrdirformat.create_workingtree,
533
create_branch and create_repository.
535
:param format: Override for the bzrdir format to create.
536
:return: The WorkingTree object.
538
t = get_transport(base)
539
if not isinstance(t, local.LocalTransport):
540
raise errors.NotLocalUrl(base)
541
bzrdir = BzrDir.create_branch_and_repo(base,
543
format=format).bzrdir
544
return bzrdir.create_workingtree()
546
def create_workingtree(self, revision_id=None, from_branch=None,
547
accelerator_tree=None, hardlink=False):
548
"""Create a working tree at this BzrDir.
550
:param revision_id: create it as of this revision id.
551
:param from_branch: override bzrdir branch (for lightweight checkouts)
552
:param accelerator_tree: A tree which can be used for retrieving file
553
contents more quickly than the revision tree, i.e. a workingtree.
554
The revision tree will be used for cases where accelerator_tree's
555
content is different.
557
raise NotImplementedError(self.create_workingtree)
559
def backup_bzrdir(self):
560
"""Backup this bzr control directory.
562
:return: Tuple with old path name and new path name
564
pb = ui.ui_factory.nested_progress_bar()
566
# FIXME: bug 300001 -- the backup fails if the backup directory
567
# already exists, but it should instead either remove it or make
568
# a new backup directory.
570
# FIXME: bug 262450 -- the backup directory should have the same
571
# permissions as the .bzr directory (probably a bug in copy_tree)
572
old_path = self.root_transport.abspath('.bzr')
573
new_path = self.root_transport.abspath('backup.bzr')
574
pb.note('making backup of %s' % (old_path,))
575
pb.note(' to %s' % (new_path,))
576
self.root_transport.copy_tree('.bzr', 'backup.bzr')
577
return (old_path, new_path)
581
def retire_bzrdir(self, limit=10000):
582
"""Permanently disable the bzrdir.
584
This is done by renaming it to give the user some ability to recover
585
if there was a problem.
587
This will have horrible consequences if anyone has anything locked or
589
:param limit: number of times to retry
594
to_path = '.bzr.retired.%d' % i
595
self.root_transport.rename('.bzr', to_path)
596
note("renamed %s to %s"
597
% (self.root_transport.abspath('.bzr'), to_path))
599
except (errors.TransportError, IOError, errors.PathError):
606
def destroy_workingtree(self):
607
"""Destroy the working tree at this BzrDir.
609
Formats that do not support this may raise UnsupportedOperation.
611
raise NotImplementedError(self.destroy_workingtree)
613
def destroy_workingtree_metadata(self):
614
"""Destroy the control files for the working tree at this BzrDir.
616
The contents of working tree files are not affected.
617
Formats that do not support this may raise UnsupportedOperation.
619
raise NotImplementedError(self.destroy_workingtree_metadata)
621
def _find_containing(self, evaluate):
622
"""Find something in a containing control directory.
624
This method will scan containing control dirs, until it finds what
625
it is looking for, decides that it will never find it, or runs out
626
of containing control directories to check.
628
It is used to implement find_repository and
629
determine_repository_policy.
631
:param evaluate: A function returning (value, stop). If stop is True,
632
the value will be returned.
636
result, stop = evaluate(found_bzrdir)
639
next_transport = found_bzrdir.root_transport.clone('..')
640
if (found_bzrdir.root_transport.base == next_transport.base):
641
# top of the file system
643
# find the next containing bzrdir
645
found_bzrdir = BzrDir.open_containing_from_transport(
647
except errors.NotBranchError:
650
def find_repository(self):
651
"""Find the repository that should be used.
653
This does not require a branch as we use it to find the repo for
654
new branches as well as to hook existing branches up to their
657
def usable_repository(found_bzrdir):
658
# does it have a repository ?
660
repository = found_bzrdir.open_repository()
661
except errors.NoRepositoryPresent:
663
if found_bzrdir.root_transport.base == self.root_transport.base:
664
return repository, True
665
elif repository.is_shared():
666
return repository, True
670
found_repo = self._find_containing(usable_repository)
671
if found_repo is None:
672
raise errors.NoRepositoryPresent(self)
675
def get_branch_reference(self):
676
"""Return the referenced URL for the branch in this bzrdir.
678
:raises NotBranchError: If there is no Branch.
679
:return: The URL the branch in this bzrdir references if it is a
680
reference branch, or None for regular branches.
684
def get_branch_transport(self, branch_format):
685
"""Get the transport for use by branch format in this BzrDir.
687
Note that bzr dirs that do not support format strings will raise
688
IncompatibleFormat if the branch format they are given has
689
a format string, and vice versa.
691
If branch_format is None, the transport is returned with no
692
checking. If it is not None, then the returned transport is
693
guaranteed to point to an existing directory ready for use.
695
raise NotImplementedError(self.get_branch_transport)
697
def _find_creation_modes(self):
698
"""Determine the appropriate modes for files and directories.
700
They're always set to be consistent with the base directory,
701
assuming that this transport allows setting modes.
703
# TODO: Do we need or want an option (maybe a config setting) to turn
704
# this off or override it for particular locations? -- mbp 20080512
705
if self._mode_check_done:
707
self._mode_check_done = True
709
st = self.transport.stat('.')
710
except errors.TransportNotPossible:
711
self._dir_mode = None
712
self._file_mode = None
714
# Check the directory mode, but also make sure the created
715
# directories and files are read-write for this user. This is
716
# mostly a workaround for filesystems which lie about being able to
717
# write to a directory (cygwin & win32)
718
if (st.st_mode & 07777 == 00000):
719
# FTP allows stat but does not return dir/file modes
720
self._dir_mode = None
721
self._file_mode = None
723
self._dir_mode = (st.st_mode & 07777) | 00700
724
# Remove the sticky and execute bits for files
725
self._file_mode = self._dir_mode & ~07111
727
def _get_file_mode(self):
728
"""Return Unix mode for newly created files, or None.
730
if not self._mode_check_done:
731
self._find_creation_modes()
732
return self._file_mode
734
def _get_dir_mode(self):
735
"""Return Unix mode for newly created directories, or None.
737
if not self._mode_check_done:
738
self._find_creation_modes()
739
return self._dir_mode
741
def get_repository_transport(self, repository_format):
742
"""Get the transport for use by repository format in this BzrDir.
744
Note that bzr dirs that do not support format strings will raise
745
IncompatibleFormat if the repository format they are given has
746
a format string, and vice versa.
748
If repository_format is None, the transport is returned with no
749
checking. If it is not None, then the returned transport is
750
guaranteed to point to an existing directory ready for use.
752
raise NotImplementedError(self.get_repository_transport)
754
def get_workingtree_transport(self, tree_format):
755
"""Get the transport for use by workingtree format in this BzrDir.
757
Note that bzr dirs that do not support format strings will raise
758
IncompatibleFormat if the workingtree format they are given has a
759
format string, and vice versa.
761
If workingtree_format is None, the transport is returned with no
762
checking. If it is not None, then the returned transport is
763
guaranteed to point to an existing directory ready for use.
765
raise NotImplementedError(self.get_workingtree_transport)
767
def get_config(self):
768
"""Get configuration for this BzrDir."""
769
return config.BzrDirConfig(self)
771
def _get_config(self):
772
"""By default, no configuration is available."""
775
def __init__(self, _transport, _format):
776
"""Initialize a Bzr control dir object.
778
Only really common logic should reside here, concrete classes should be
779
made with varying behaviours.
781
:param _format: the format that is creating this BzrDir instance.
782
:param _transport: the transport this dir is based at.
784
self._format = _format
785
self.transport = _transport.clone('.bzr')
786
self.root_transport = _transport
787
self._mode_check_done = False
789
def is_control_filename(self, filename):
790
"""True if filename is the name of a path which is reserved for bzrdir's.
792
:param filename: A filename within the root transport of this bzrdir.
794
This is true IF and ONLY IF the filename is part of the namespace reserved
795
for bzr control dirs. Currently this is the '.bzr' directory in the root
796
of the root_transport. it is expected that plugins will need to extend
797
this in the future - for instance to make bzr talk with svn working
800
# this might be better on the BzrDirFormat class because it refers to
801
# all the possible bzrdir disk formats.
802
# This method is tested via the workingtree is_control_filename tests-
803
# it was extracted from WorkingTree.is_control_filename. If the method's
804
# contract is extended beyond the current trivial implementation, please
805
# add new tests for it to the appropriate place.
806
return filename == '.bzr' or filename.startswith('.bzr/')
808
def needs_format_conversion(self, format=None):
809
"""Return true if this bzrdir needs convert_format run on it.
811
For instance, if the repository format is out of date but the
812
branch and working tree are not, this should return True.
814
:param format: Optional parameter indicating a specific desired
815
format we plan to arrive at.
817
raise NotImplementedError(self.needs_format_conversion)
820
def open_unsupported(base):
821
"""Open a branch which is not supported."""
822
return BzrDir.open(base, _unsupported=True)
825
def open(base, _unsupported=False, possible_transports=None):
826
"""Open an existing bzrdir, rooted at 'base' (url).
828
:param _unsupported: a private parameter to the BzrDir class.
830
t = get_transport(base, possible_transports=possible_transports)
831
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
834
def open_from_transport(transport, _unsupported=False,
835
_server_formats=True):
836
"""Open a bzrdir within a particular directory.
838
:param transport: Transport containing the bzrdir.
839
:param _unsupported: private.
841
for hook in BzrDir.hooks['pre_open']:
843
# Keep initial base since 'transport' may be modified while following
845
base = transport.base
846
def find_format(transport):
847
return transport, BzrDirFormat.find_format(
848
transport, _server_formats=_server_formats)
850
def redirected(transport, e, redirection_notice):
851
redirected_transport = transport._redirected_to(e.source, e.target)
852
if redirected_transport is None:
853
raise errors.NotBranchError(base)
854
note('%s is%s redirected to %s',
855
transport.base, e.permanently, redirected_transport.base)
856
return redirected_transport
859
transport, format = do_catching_redirections(find_format,
862
except errors.TooManyRedirections:
863
raise errors.NotBranchError(base)
865
BzrDir._check_supported(format, _unsupported)
866
return format.open(transport, _found=True)
868
def open_branch(self, unsupported=False, ignore_fallbacks=False):
869
"""Open the branch object at this BzrDir if one is present.
871
If unsupported is True, then no longer supported branch formats can
874
TODO: static convenience version of this?
876
raise NotImplementedError(self.open_branch)
879
def open_containing(url, possible_transports=None):
880
"""Open an existing branch which contains url.
882
:param url: url to search from.
883
See open_containing_from_transport for more detail.
885
transport = get_transport(url, possible_transports)
886
return BzrDir.open_containing_from_transport(transport)
889
def open_containing_from_transport(a_transport):
890
"""Open an existing branch which contains a_transport.base.
892
This probes for a branch at a_transport, and searches upwards from there.
894
Basically we keep looking up until we find the control directory or
895
run into the root. If there isn't one, raises NotBranchError.
896
If there is one and it is either an unrecognised format or an unsupported
897
format, UnknownFormatError or UnsupportedFormatError are raised.
898
If there is one, it is returned, along with the unused portion of url.
900
:return: The BzrDir that contains the path, and a Unicode path
901
for the rest of the URL.
903
# this gets the normalised url back. I.e. '.' -> the full path.
904
url = a_transport.base
907
result = BzrDir.open_from_transport(a_transport)
908
return result, urlutils.unescape(a_transport.relpath(url))
909
except errors.NotBranchError, e:
912
new_t = a_transport.clone('..')
913
except errors.InvalidURLJoin:
914
# reached the root, whatever that may be
915
raise errors.NotBranchError(path=url)
916
if new_t.base == a_transport.base:
917
# reached the root, whatever that may be
918
raise errors.NotBranchError(path=url)
921
def _get_tree_branch(self):
922
"""Return the branch and tree, if any, for this bzrdir.
924
Return None for tree if not present or inaccessible.
925
Raise NotBranchError if no branch is present.
926
:return: (tree, branch)
929
tree = self.open_workingtree()
930
except (errors.NoWorkingTree, errors.NotLocalUrl):
932
branch = self.open_branch()
938
def open_tree_or_branch(klass, location):
939
"""Return the branch and working tree at a location.
941
If there is no tree at the location, tree will be None.
942
If there is no branch at the location, an exception will be
944
:return: (tree, branch)
946
bzrdir = klass.open(location)
947
return bzrdir._get_tree_branch()
950
def open_containing_tree_or_branch(klass, location):
951
"""Return the branch and working tree contained by a location.
953
Returns (tree, branch, relpath).
954
If there is no tree at containing the location, tree will be None.
955
If there is no branch containing the location, an exception will be
957
relpath is the portion of the path that is contained by the branch.
959
bzrdir, relpath = klass.open_containing(location)
960
tree, branch = bzrdir._get_tree_branch()
961
return tree, branch, relpath
964
def open_containing_tree_branch_or_repository(klass, location):
965
"""Return the working tree, branch and repo contained by a location.
967
Returns (tree, branch, repository, relpath).
968
If there is no tree containing the location, tree will be None.
969
If there is no branch containing the location, branch will be None.
970
If there is no repository containing the location, repository will be
972
relpath is the portion of the path that is contained by the innermost
975
If no tree, branch or repository is found, a NotBranchError is raised.
977
bzrdir, relpath = klass.open_containing(location)
979
tree, branch = bzrdir._get_tree_branch()
980
except errors.NotBranchError:
982
repo = bzrdir.find_repository()
983
return None, None, repo, relpath
984
except (errors.NoRepositoryPresent):
985
raise errors.NotBranchError(location)
986
return tree, branch, branch.repository, relpath
988
def open_repository(self, _unsupported=False):
989
"""Open the repository object at this BzrDir if one is present.
991
This will not follow the Branch object pointer - it's strictly a direct
992
open facility. Most client code should use open_branch().repository to
995
:param _unsupported: a private parameter, not part of the api.
996
TODO: static convenience version of this?
998
raise NotImplementedError(self.open_repository)
1000
def open_workingtree(self, _unsupported=False,
1001
recommend_upgrade=True, from_branch=None):
1002
"""Open the workingtree object at this BzrDir if one is present.
1004
:param recommend_upgrade: Optional keyword parameter, when True (the
1005
default), emit through the ui module a recommendation that the user
1006
upgrade the working tree when the workingtree being opened is old
1007
(but still fully supported).
1008
:param from_branch: override bzrdir branch (for lightweight checkouts)
1010
raise NotImplementedError(self.open_workingtree)
1012
def has_branch(self):
1013
"""Tell if this bzrdir contains a branch.
1015
Note: if you're going to open the branch, you should just go ahead
1016
and try, and not ask permission first. (This method just opens the
1017
branch and discards it, and that's somewhat expensive.)
1022
except errors.NotBranchError:
1025
def has_workingtree(self):
1026
"""Tell if this bzrdir contains a working tree.
1028
This will still raise an exception if the bzrdir has a workingtree that
1029
is remote & inaccessible.
1031
Note: if you're going to open the working tree, you should just go ahead
1032
and try, and not ask permission first. (This method just opens the
1033
workingtree and discards it, and that's somewhat expensive.)
1036
self.open_workingtree(recommend_upgrade=False)
1038
except errors.NoWorkingTree:
1041
def _cloning_metadir(self):
1042
"""Produce a metadir suitable for cloning with.
1044
:returns: (destination_bzrdir_format, source_repository)
1046
result_format = self._format.__class__()
1049
branch = self.open_branch(ignore_fallbacks=True)
1050
source_repository = branch.repository
1051
result_format._branch_format = branch._format
1052
except errors.NotBranchError:
1053
source_branch = None
1054
source_repository = self.open_repository()
1055
except errors.NoRepositoryPresent:
1056
source_repository = None
1058
# XXX TODO: This isinstance is here because we have not implemented
1059
# the fix recommended in bug # 103195 - to delegate this choice the
1060
# repository itself.
1061
repo_format = source_repository._format
1062
if isinstance(repo_format, remote.RemoteRepositoryFormat):
1063
source_repository._ensure_real()
1064
repo_format = source_repository._real_repository._format
1065
result_format.repository_format = repo_format
1067
# TODO: Couldn't we just probe for the format in these cases,
1068
# rather than opening the whole tree? It would be a little
1069
# faster. mbp 20070401
1070
tree = self.open_workingtree(recommend_upgrade=False)
1071
except (errors.NoWorkingTree, errors.NotLocalUrl):
1072
result_format.workingtree_format = None
1074
result_format.workingtree_format = tree._format.__class__()
1075
return result_format, source_repository
1077
def cloning_metadir(self, require_stacking=False):
1078
"""Produce a metadir suitable for cloning or sprouting with.
1080
These operations may produce workingtrees (yes, even though they're
1081
"cloning" something that doesn't have a tree), so a viable workingtree
1082
format must be selected.
1084
:require_stacking: If True, non-stackable formats will be upgraded
1085
to similar stackable formats.
1086
:returns: a BzrDirFormat with all component formats either set
1087
appropriately or set to None if that component should not be
1090
format, repository = self._cloning_metadir()
1091
if format._workingtree_format is None:
1093
if repository is None:
1094
# No repository either
1096
# We have a repository, so set a working tree? (Why? This seems to
1097
# contradict the stated return value in the docstring).
1098
tree_format = repository._format._matchingbzrdir.workingtree_format
1099
format.workingtree_format = tree_format.__class__()
1100
if require_stacking:
1101
format.require_stacking()
1104
def checkout_metadir(self):
1105
return self.cloning_metadir()
1107
def sprout(self, url, revision_id=None, force_new_repo=False,
1108
recurse='down', possible_transports=None,
1109
accelerator_tree=None, hardlink=False, stacked=False,
1110
source_branch=None, create_tree_if_local=True):
1111
"""Create a copy of this bzrdir prepared for use as a new line of
1114
If url's last component does not exist, it will be created.
1116
Attributes related to the identity of the source branch like
1117
branch nickname will be cleaned, a working tree is created
1118
whether one existed before or not; and a local branch is always
1121
if revision_id is not None, then the clone operation may tune
1122
itself to download less data.
1123
:param accelerator_tree: A tree which can be used for retrieving file
1124
contents more quickly than the revision tree, i.e. a workingtree.
1125
The revision tree will be used for cases where accelerator_tree's
1126
content is different.
1127
:param hardlink: If true, hard-link files from accelerator_tree,
1129
:param stacked: If true, create a stacked branch referring to the
1130
location of this control directory.
1131
:param create_tree_if_local: If true, a working-tree will be created
1132
when working locally.
1134
target_transport = get_transport(url, possible_transports)
1135
target_transport.ensure_base()
1136
cloning_format = self.cloning_metadir(stacked)
1137
# Create/update the result branch
1138
result = cloning_format.initialize_on_transport(target_transport)
1139
# if a stacked branch wasn't requested, we don't create one
1140
# even if the origin was stacked
1141
stacked_branch_url = None
1142
if source_branch is not None:
1144
stacked_branch_url = self.root_transport.base
1145
source_repository = source_branch.repository
1148
source_branch = self.open_branch()
1149
source_repository = source_branch.repository
1151
stacked_branch_url = self.root_transport.base
1152
except errors.NotBranchError:
1153
source_branch = None
1155
source_repository = self.open_repository()
1156
except errors.NoRepositoryPresent:
1157
source_repository = None
1158
repository_policy = result.determine_repository_policy(
1159
force_new_repo, stacked_branch_url, require_stacking=stacked)
1160
result_repo, is_new_repo = repository_policy.acquire_repository()
1161
if is_new_repo and revision_id is not None and not stacked:
1162
fetch_spec = graph.PendingAncestryResult(
1163
[revision_id], source_repository)
1166
if source_repository is not None:
1167
# Fetch while stacked to prevent unstacked fetch from
1169
if fetch_spec is None:
1170
result_repo.fetch(source_repository, revision_id=revision_id)
1172
result_repo.fetch(source_repository, fetch_spec=fetch_spec)
1174
if source_branch is None:
1175
# this is for sprouting a bzrdir without a branch; is that
1177
# Not especially, but it's part of the contract.
1178
result_branch = result.create_branch()
1180
result_branch = source_branch.sprout(result,
1181
revision_id=revision_id, repository_policy=repository_policy)
1182
mutter("created new branch %r" % (result_branch,))
1184
# Create/update the result working tree
1185
if (create_tree_if_local and
1186
isinstance(target_transport, local.LocalTransport) and
1187
(result_repo is None or result_repo.make_working_trees())):
1188
wt = result.create_workingtree(accelerator_tree=accelerator_tree,
1192
if wt.path2id('') is None:
1194
wt.set_root_id(self.open_workingtree.get_root_id())
1195
except errors.NoWorkingTree:
1201
if recurse == 'down':
1203
basis = wt.basis_tree()
1205
subtrees = basis.iter_references()
1206
elif result_branch is not None:
1207
basis = result_branch.basis_tree()
1209
subtrees = basis.iter_references()
1210
elif source_branch is not None:
1211
basis = source_branch.basis_tree()
1213
subtrees = basis.iter_references()
1218
for path, file_id in subtrees:
1219
target = urlutils.join(url, urlutils.escape(path))
1220
sublocation = source_branch.reference_parent(file_id, path)
1221
sublocation.bzrdir.sprout(target,
1222
basis.get_reference_revision(file_id, path),
1223
force_new_repo=force_new_repo, recurse=recurse,
1226
if basis is not None:
1230
def push_branch(self, source, revision_id=None, overwrite=False,
1232
"""Push the source branch into this BzrDir."""
1234
# If we can open a branch, use its direct repository, otherwise see
1235
# if there is a repository without a branch.
1237
br_to = self.open_branch()
1238
except errors.NotBranchError:
1239
# Didn't find a branch, can we find a repository?
1240
repository_to = self.find_repository()
1242
# Found a branch, so we must have found a repository
1243
repository_to = br_to.repository
1245
push_result = PushResult()
1246
push_result.source_branch = source
1248
# We have a repository but no branch, copy the revisions, and then
1250
repository_to.fetch(source.repository, revision_id=revision_id)
1251
br_to = source.clone(self, revision_id=revision_id)
1252
if source.get_push_location() is None or remember:
1253
source.set_push_location(br_to.base)
1254
push_result.stacked_on = None
1255
push_result.branch_push_result = None
1256
push_result.old_revno = None
1257
push_result.old_revid = _mod_revision.NULL_REVISION
1258
push_result.target_branch = br_to
1259
push_result.master_branch = None
1260
push_result.workingtree_updated = False
1262
# We have successfully opened the branch, remember if necessary:
1263
if source.get_push_location() is None or remember:
1264
source.set_push_location(br_to.base)
1266
tree_to = self.open_workingtree()
1267
except errors.NotLocalUrl:
1268
push_result.branch_push_result = source.push(br_to,
1269
overwrite, stop_revision=revision_id)
1270
push_result.workingtree_updated = False
1271
except errors.NoWorkingTree:
1272
push_result.branch_push_result = source.push(br_to,
1273
overwrite, stop_revision=revision_id)
1274
push_result.workingtree_updated = None # Not applicable
1276
tree_to.lock_write()
1278
push_result.branch_push_result = source.push(
1279
tree_to.branch, overwrite, stop_revision=revision_id)
1283
push_result.workingtree_updated = True
1284
push_result.old_revno = push_result.branch_push_result.old_revno
1285
push_result.old_revid = push_result.branch_push_result.old_revid
1286
push_result.target_branch = \
1287
push_result.branch_push_result.target_branch
1291
class BzrDirHooks(hooks.Hooks):
1292
"""Hooks for BzrDir operations."""
1295
"""Create the default hooks."""
1296
hooks.Hooks.__init__(self)
1297
self.create_hook(hooks.HookPoint('pre_open',
1298
"Invoked before attempting to open a BzrDir with the transport "
1299
"that the open will use.", (1, 14), None))
1301
# install the default hooks
1302
BzrDir.hooks = BzrDirHooks()
1305
class BzrDirPreSplitOut(BzrDir):
1306
"""A common class for the all-in-one formats."""
1308
def __init__(self, _transport, _format):
1309
"""See BzrDir.__init__."""
1310
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1311
self._control_files = lockable_files.LockableFiles(
1312
self.get_branch_transport(None),
1313
self._format._lock_file_name,
1314
self._format._lock_class)
1316
def break_lock(self):
1317
"""Pre-splitout bzrdirs do not suffer from stale locks."""
1318
raise NotImplementedError(self.break_lock)
1320
def cloning_metadir(self, require_stacking=False):
1321
"""Produce a metadir suitable for cloning with."""
1322
if require_stacking:
1323
return format_registry.make_bzrdir('1.6')
1324
return self._format.__class__()
1326
def clone(self, url, revision_id=None, force_new_repo=False,
1327
preserve_stacking=False):
1328
"""See BzrDir.clone().
1330
force_new_repo has no effect, since this family of formats always
1331
require a new repository.
1332
preserve_stacking has no effect, since no source branch using this
1333
family of formats can be stacked, so there is no stacking to preserve.
1335
self._make_tail(url)
1336
result = self._format._initialize_for_clone(url)
1337
self.open_repository().clone(result, revision_id=revision_id)
1338
from_branch = self.open_branch()
1339
from_branch.clone(result, revision_id=revision_id)
1341
tree = self.open_workingtree()
1342
except errors.NotLocalUrl:
1343
# make a new one, this format always has to have one.
1344
result._init_workingtree()
1349
def create_branch(self):
1350
"""See BzrDir.create_branch."""
1351
return self._format.get_branch_format().initialize(self)
1353
def destroy_branch(self):
1354
"""See BzrDir.destroy_branch."""
1355
raise errors.UnsupportedOperation(self.destroy_branch, self)
1357
def create_repository(self, shared=False):
1358
"""See BzrDir.create_repository."""
1360
raise errors.IncompatibleFormat('shared repository', self._format)
1361
return self.open_repository()
1363
def destroy_repository(self):
1364
"""See BzrDir.destroy_repository."""
1365
raise errors.UnsupportedOperation(self.destroy_repository, self)
1367
def create_workingtree(self, revision_id=None, from_branch=None,
1368
accelerator_tree=None, hardlink=False):
1369
"""See BzrDir.create_workingtree."""
1370
# The workingtree is sometimes created when the bzrdir is created,
1371
# but not when cloning.
1373
# this looks buggy but is not -really-
1374
# because this format creates the workingtree when the bzrdir is
1376
# clone and sprout will have set the revision_id
1377
# and that will have set it for us, its only
1378
# specific uses of create_workingtree in isolation
1379
# that can do wonky stuff here, and that only
1380
# happens for creating checkouts, which cannot be
1381
# done on this format anyway. So - acceptable wart.
1383
result = self.open_workingtree(recommend_upgrade=False)
1384
except errors.NoSuchFile:
1385
result = self._init_workingtree()
1386
if revision_id is not None:
1387
if revision_id == _mod_revision.NULL_REVISION:
1388
result.set_parent_ids([])
1390
result.set_parent_ids([revision_id])
1393
def _init_workingtree(self):
1394
from bzrlib.workingtree import WorkingTreeFormat2
1396
return WorkingTreeFormat2().initialize(self)
1397
except errors.NotLocalUrl:
1398
# Even though we can't access the working tree, we need to
1399
# create its control files.
1400
return WorkingTreeFormat2()._stub_initialize_on_transport(
1401
self.transport, self._control_files._file_mode)
1403
def destroy_workingtree(self):
1404
"""See BzrDir.destroy_workingtree."""
1405
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1407
def destroy_workingtree_metadata(self):
1408
"""See BzrDir.destroy_workingtree_metadata."""
1409
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1412
def get_branch_transport(self, branch_format):
1413
"""See BzrDir.get_branch_transport()."""
1414
if branch_format is None:
1415
return self.transport
1417
branch_format.get_format_string()
1418
except NotImplementedError:
1419
return self.transport
1420
raise errors.IncompatibleFormat(branch_format, self._format)
1422
def get_repository_transport(self, repository_format):
1423
"""See BzrDir.get_repository_transport()."""
1424
if repository_format is None:
1425
return self.transport
1427
repository_format.get_format_string()
1428
except NotImplementedError:
1429
return self.transport
1430
raise errors.IncompatibleFormat(repository_format, self._format)
1432
def get_workingtree_transport(self, workingtree_format):
1433
"""See BzrDir.get_workingtree_transport()."""
1434
if workingtree_format is None:
1435
return self.transport
1437
workingtree_format.get_format_string()
1438
except NotImplementedError:
1439
return self.transport
1440
raise errors.IncompatibleFormat(workingtree_format, self._format)
1442
def needs_format_conversion(self, format=None):
1443
"""See BzrDir.needs_format_conversion()."""
1444
# if the format is not the same as the system default,
1445
# an upgrade is needed.
1447
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1448
% 'needs_format_conversion(format=None)')
1449
format = BzrDirFormat.get_default_format()
1450
return not isinstance(self._format, format.__class__)
1452
def open_branch(self, unsupported=False, ignore_fallbacks=False):
1453
"""See BzrDir.open_branch."""
1454
from bzrlib.branch import BzrBranchFormat4
1455
format = BzrBranchFormat4()
1456
self._check_supported(format, unsupported)
1457
return format.open(self, _found=True)
1459
def sprout(self, url, revision_id=None, force_new_repo=False,
1460
possible_transports=None, accelerator_tree=None,
1461
hardlink=False, stacked=False, create_tree_if_local=True,
1462
source_branch=None):
1463
"""See BzrDir.sprout()."""
1464
if source_branch is not None:
1465
my_branch = self.open_branch()
1466
if source_branch.base != my_branch.base:
1467
raise AssertionError(
1468
"source branch %r is not within %r with branch %r" %
1469
(source_branch, self, my_branch))
1471
raise errors.UnstackableBranchFormat(
1472
self._format, self.root_transport.base)
1473
if not create_tree_if_local:
1474
raise errors.MustHaveWorkingTree(
1475
self._format, self.root_transport.base)
1476
from bzrlib.workingtree import WorkingTreeFormat2
1477
self._make_tail(url)
1478
result = self._format._initialize_for_clone(url)
1480
self.open_repository().clone(result, revision_id=revision_id)
1481
except errors.NoRepositoryPresent:
1484
self.open_branch().sprout(result, revision_id=revision_id)
1485
except errors.NotBranchError:
1488
# we always want a working tree
1489
WorkingTreeFormat2().initialize(result,
1490
accelerator_tree=accelerator_tree,
1495
class BzrDir4(BzrDirPreSplitOut):
1496
"""A .bzr version 4 control object.
1498
This is a deprecated format and may be removed after sept 2006.
1501
def create_repository(self, shared=False):
1502
"""See BzrDir.create_repository."""
1503
return self._format.repository_format.initialize(self, shared)
1505
def needs_format_conversion(self, format=None):
1506
"""Format 4 dirs are always in need of conversion."""
1508
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1509
% 'needs_format_conversion(format=None)')
1512
def open_repository(self):
1513
"""See BzrDir.open_repository."""
1514
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1515
return RepositoryFormat4().open(self, _found=True)
1518
class BzrDir5(BzrDirPreSplitOut):
1519
"""A .bzr version 5 control object.
1521
This is a deprecated format and may be removed after sept 2006.
1524
def open_repository(self):
1525
"""See BzrDir.open_repository."""
1526
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1527
return RepositoryFormat5().open(self, _found=True)
1529
def open_workingtree(self, _unsupported=False,
1530
recommend_upgrade=True):
1531
"""See BzrDir.create_workingtree."""
1532
from bzrlib.workingtree import WorkingTreeFormat2
1533
wt_format = WorkingTreeFormat2()
1534
# we don't warn here about upgrades; that ought to be handled for the
1536
return wt_format.open(self, _found=True)
1539
class BzrDir6(BzrDirPreSplitOut):
1540
"""A .bzr version 6 control object.
1542
This is a deprecated format and may be removed after sept 2006.
1545
def open_repository(self):
1546
"""See BzrDir.open_repository."""
1547
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1548
return RepositoryFormat6().open(self, _found=True)
1550
def open_workingtree(self, _unsupported=False,
1551
recommend_upgrade=True):
1552
"""See BzrDir.create_workingtree."""
1553
# we don't warn here about upgrades; that ought to be handled for the
1555
from bzrlib.workingtree import WorkingTreeFormat2
1556
return WorkingTreeFormat2().open(self, _found=True)
1559
class BzrDirMeta1(BzrDir):
1560
"""A .bzr meta version 1 control object.
1562
This is the first control object where the
1563
individual aspects are really split out: there are separate repository,
1564
workingtree and branch subdirectories and any subset of the three can be
1565
present within a BzrDir.
1568
def can_convert_format(self):
1569
"""See BzrDir.can_convert_format()."""
1572
def create_branch(self):
1573
"""See BzrDir.create_branch."""
1574
return self._format.get_branch_format().initialize(self)
1576
def destroy_branch(self):
1577
"""See BzrDir.create_branch."""
1578
self.transport.delete_tree('branch')
1580
def create_repository(self, shared=False):
1581
"""See BzrDir.create_repository."""
1582
return self._format.repository_format.initialize(self, shared)
1584
def destroy_repository(self):
1585
"""See BzrDir.destroy_repository."""
1586
self.transport.delete_tree('repository')
1588
def create_workingtree(self, revision_id=None, from_branch=None,
1589
accelerator_tree=None, hardlink=False):
1590
"""See BzrDir.create_workingtree."""
1591
return self._format.workingtree_format.initialize(
1592
self, revision_id, from_branch=from_branch,
1593
accelerator_tree=accelerator_tree, hardlink=hardlink)
1595
def destroy_workingtree(self):
1596
"""See BzrDir.destroy_workingtree."""
1597
wt = self.open_workingtree(recommend_upgrade=False)
1598
repository = wt.branch.repository
1599
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1600
wt.revert(old_tree=empty)
1601
self.destroy_workingtree_metadata()
1603
def destroy_workingtree_metadata(self):
1604
self.transport.delete_tree('checkout')
1606
def find_branch_format(self):
1607
"""Find the branch 'format' for this bzrdir.
1609
This might be a synthetic object for e.g. RemoteBranch and SVN.
1611
from bzrlib.branch import BranchFormat
1612
return BranchFormat.find_format(self)
1614
def _get_mkdir_mode(self):
1615
"""Figure out the mode to use when creating a bzrdir subdir."""
1616
temp_control = lockable_files.LockableFiles(self.transport, '',
1617
lockable_files.TransportLock)
1618
return temp_control._dir_mode
1620
def get_branch_reference(self):
1621
"""See BzrDir.get_branch_reference()."""
1622
from bzrlib.branch import BranchFormat
1623
format = BranchFormat.find_format(self)
1624
return format.get_reference(self)
1626
def get_branch_transport(self, branch_format):
1627
"""See BzrDir.get_branch_transport()."""
1628
if branch_format is None:
1629
return self.transport.clone('branch')
1631
branch_format.get_format_string()
1632
except NotImplementedError:
1633
raise errors.IncompatibleFormat(branch_format, self._format)
1635
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1636
except errors.FileExists:
1638
return self.transport.clone('branch')
1640
def get_repository_transport(self, repository_format):
1641
"""See BzrDir.get_repository_transport()."""
1642
if repository_format is None:
1643
return self.transport.clone('repository')
1645
repository_format.get_format_string()
1646
except NotImplementedError:
1647
raise errors.IncompatibleFormat(repository_format, self._format)
1649
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1650
except errors.FileExists:
1652
return self.transport.clone('repository')
1654
def get_workingtree_transport(self, workingtree_format):
1655
"""See BzrDir.get_workingtree_transport()."""
1656
if workingtree_format is None:
1657
return self.transport.clone('checkout')
1659
workingtree_format.get_format_string()
1660
except NotImplementedError:
1661
raise errors.IncompatibleFormat(workingtree_format, self._format)
1663
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1664
except errors.FileExists:
1666
return self.transport.clone('checkout')
1668
def needs_format_conversion(self, format=None):
1669
"""See BzrDir.needs_format_conversion()."""
1671
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1672
% 'needs_format_conversion(format=None)')
1674
format = BzrDirFormat.get_default_format()
1675
if not isinstance(self._format, format.__class__):
1676
# it is not a meta dir format, conversion is needed.
1678
# we might want to push this down to the repository?
1680
if not isinstance(self.open_repository()._format,
1681
format.repository_format.__class__):
1682
# the repository needs an upgrade.
1684
except errors.NoRepositoryPresent:
1687
if not isinstance(self.open_branch()._format,
1688
format.get_branch_format().__class__):
1689
# the branch needs an upgrade.
1691
except errors.NotBranchError:
1694
my_wt = self.open_workingtree(recommend_upgrade=False)
1695
if not isinstance(my_wt._format,
1696
format.workingtree_format.__class__):
1697
# the workingtree needs an upgrade.
1699
except (errors.NoWorkingTree, errors.NotLocalUrl):
1703
def open_branch(self, unsupported=False, ignore_fallbacks=False):
1704
"""See BzrDir.open_branch."""
1705
format = self.find_branch_format()
1706
self._check_supported(format, unsupported)
1707
return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
1709
def open_repository(self, unsupported=False):
1710
"""See BzrDir.open_repository."""
1711
from bzrlib.repository import RepositoryFormat
1712
format = RepositoryFormat.find_format(self)
1713
self._check_supported(format, unsupported)
1714
return format.open(self, _found=True)
1716
def open_workingtree(self, unsupported=False,
1717
recommend_upgrade=True):
1718
"""See BzrDir.open_workingtree."""
1719
from bzrlib.workingtree import WorkingTreeFormat
1720
format = WorkingTreeFormat.find_format(self)
1721
self._check_supported(format, unsupported,
1723
basedir=self.root_transport.base)
1724
return format.open(self, _found=True)
1726
def _get_config(self):
1727
return config.TransportConfig(self.transport, 'control.conf')
1730
class BzrDirFormat(object):
1731
"""An encapsulation of the initialization and open routines for a format.
1733
Formats provide three things:
1734
* An initialization routine,
1738
Formats are placed in a dict by their format string for reference
1739
during bzrdir opening. These should be subclasses of BzrDirFormat
1742
Once a format is deprecated, just deprecate the initialize and open
1743
methods on the format class. Do not deprecate the object, as the
1744
object will be created every system load.
1747
_default_format = None
1748
"""The default format used for new .bzr dirs."""
1751
"""The known formats."""
1753
_control_formats = []
1754
"""The registered control formats - .bzr, ....
1756
This is a list of BzrDirFormat objects.
1759
_control_server_formats = []
1760
"""The registered control server formats, e.g. RemoteBzrDirs.
1762
This is a list of BzrDirFormat objects.
1765
_lock_file_name = 'branch-lock'
1767
# _lock_class must be set in subclasses to the lock type, typ.
1768
# TransportLock or LockDir
1771
def find_format(klass, transport, _server_formats=True):
1772
"""Return the format present at transport."""
1774
formats = klass._control_server_formats + klass._control_formats
1776
formats = klass._control_formats
1777
for format in formats:
1779
return format.probe_transport(transport)
1780
except errors.NotBranchError:
1781
# this format does not find a control dir here.
1783
raise errors.NotBranchError(path=transport.base)
1786
def probe_transport(klass, transport):
1787
"""Return the .bzrdir style format present in a directory."""
1789
format_string = transport.get(".bzr/branch-format").read()
1790
except errors.NoSuchFile:
1791
raise errors.NotBranchError(path=transport.base)
1794
return klass._formats[format_string]
1796
raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1799
def get_default_format(klass):
1800
"""Return the current default format."""
1801
return klass._default_format
1803
def get_format_string(self):
1804
"""Return the ASCII format string that identifies this format."""
1805
raise NotImplementedError(self.get_format_string)
1807
def get_format_description(self):
1808
"""Return the short description for this format."""
1809
raise NotImplementedError(self.get_format_description)
1811
def get_converter(self, format=None):
1812
"""Return the converter to use to convert bzrdirs needing converts.
1814
This returns a bzrlib.bzrdir.Converter object.
1816
This should return the best upgrader to step this format towards the
1817
current default format. In the case of plugins we can/should provide
1818
some means for them to extend the range of returnable converters.
1820
:param format: Optional format to override the default format of the
1823
raise NotImplementedError(self.get_converter)
1825
def initialize(self, url, possible_transports=None):
1826
"""Create a bzr control dir at this url and return an opened copy.
1828
While not deprecated, this method is very specific and its use will
1829
lead to many round trips to setup a working environment. See
1830
initialize_on_transport_ex for a [nearly] all-in-one method.
1832
Subclasses should typically override initialize_on_transport
1833
instead of this method.
1835
return self.initialize_on_transport(get_transport(url,
1836
possible_transports))
1838
def initialize_on_transport(self, transport):
1839
"""Initialize a new bzrdir in the base directory of a Transport."""
1841
# can we hand off the request to the smart server rather than using
1843
client_medium = transport.get_smart_medium()
1844
except errors.NoSmartMedium:
1845
return self._initialize_on_transport_vfs(transport)
1847
# Current RPC's only know how to create bzr metadir1 instances, so
1848
# we still delegate to vfs methods if the requested format is not a
1850
if type(self) != BzrDirMetaFormat1:
1851
return self._initialize_on_transport_vfs(transport)
1852
remote_format = RemoteBzrDirFormat()
1853
self._supply_sub_formats_to(remote_format)
1854
return remote_format.initialize_on_transport(transport)
1856
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1857
create_prefix=False, force_new_repo=False, stacked_on=None,
1858
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1860
"""Create this format on transport.
1862
:param force_new_repo: Do not use a shared repository for the target,
1863
even if one is available.
1864
:param create_prefix: Create any missing directories leading up to
1866
:param use_existing_dir: Use an existing directory if one exists.
1867
:param stacked_on: A url to stack any created branch on, None to follow
1868
any target stacking policy.
1869
:param stack_on_pwd: If stack_on is relative, the location it is
1871
:param repo_format_name: If non-None, a repository will be
1872
made-or-found. Should none be found, or if force_new_repo is True
1873
the repo_format_name is used to select the format of repository to
1875
:param make_working_trees: Control the setting of make_working_trees
1876
for a new shared repository when one is made. None to use whatever
1877
default the format has.
1878
:param shared_repo: Control whether made repositories are shared or
1880
:return: repo, bzrdir, require_stacking, repository_policy. repo is
1881
None if none was created or found, bzrdir is always valid.
1882
require_stacking is the result of examining the stacked_on
1883
parameter and any stacking policy found for the target.
1885
# XXX: Refactor the create_prefix/no_create_prefix code into a
1886
# common helper function
1887
# The destination may not exist - if so make it according to policy.
1888
def make_directory(transport):
1889
transport.mkdir('.')
1891
def redirected(transport, e, redirection_notice):
1892
note(redirection_notice)
1893
return transport._redirected_to(e.source, e.target)
1895
transport = do_catching_redirections(make_directory, transport,
1897
except errors.FileExists:
1898
if not use_existing_dir:
1900
except errors.NoSuchFile:
1901
if not create_prefix:
1903
transport.create_prefix()
1905
require_stacking = (stacked_on is not None)
1906
# Now the target directory exists, but doesn't have a .bzr
1907
# directory. So we need to create it, along with any work to create
1908
# all of the dependent branches, etc.
1910
result = self.initialize_on_transport(transport)
1911
if repo_format_name:
1913
# use a custom format
1914
result._format.repository_format = \
1915
repository.network_format_registry.get(repo_format_name)
1916
except AttributeError:
1917
# The format didn't permit it to be set.
1919
# A repository is desired, either in-place or shared.
1920
repository_policy = result.determine_repository_policy(
1921
force_new_repo, stacked_on, stack_on_pwd,
1922
require_stacking=require_stacking)
1923
result_repo, is_new_repo = repository_policy.acquire_repository(
1924
make_working_trees, shared_repo)
1925
if not require_stacking and repository_policy._require_stacking:
1926
require_stacking = True
1927
result._format.require_stacking()
1930
repository_policy = None
1931
return result_repo, result, require_stacking, repository_policy
1933
def _initialize_on_transport_vfs(self, transport):
1934
"""Initialize a new bzrdir using VFS calls.
1936
:param transport: The transport to create the .bzr directory in.
1939
# Since we are creating a .bzr directory, inherit the
1940
# mode from the root directory
1941
temp_control = lockable_files.LockableFiles(transport,
1942
'', lockable_files.TransportLock)
1943
temp_control._transport.mkdir('.bzr',
1944
# FIXME: RBC 20060121 don't peek under
1946
mode=temp_control._dir_mode)
1947
if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1948
win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1949
file_mode = temp_control._file_mode
1951
bzrdir_transport = transport.clone('.bzr')
1952
utf8_files = [('README',
1953
"This is a Bazaar control directory.\n"
1954
"Do not change any files in this directory.\n"
1955
"See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1956
('branch-format', self.get_format_string()),
1958
# NB: no need to escape relative paths that are url safe.
1959
control_files = lockable_files.LockableFiles(bzrdir_transport,
1960
self._lock_file_name, self._lock_class)
1961
control_files.create_lock()
1962
control_files.lock_write()
1964
for (filename, content) in utf8_files:
1965
bzrdir_transport.put_bytes(filename, content,
1968
control_files.unlock()
1969
return self.open(transport, _found=True)
1971
def is_supported(self):
1972
"""Is this format supported?
1974
Supported formats must be initializable and openable.
1975
Unsupported formats may not support initialization or committing or
1976
some other features depending on the reason for not being supported.
1980
def network_name(self):
1981
"""A simple byte string uniquely identifying this format for RPC calls.
1983
Bzr control formats use thir disk format string to identify the format
1984
over the wire. Its possible that other control formats have more
1985
complex detection requirements, so we permit them to use any unique and
1986
immutable string they desire.
1988
raise NotImplementedError(self.network_name)
1990
def same_model(self, target_format):
1991
return (self.repository_format.rich_root_data ==
1992
target_format.rich_root_data)
1995
def known_formats(klass):
1996
"""Return all the known formats.
1998
Concrete formats should override _known_formats.
2000
# There is double indirection here to make sure that control
2001
# formats used by more than one dir format will only be probed
2002
# once. This can otherwise be quite expensive for remote connections.
2004
for format in klass._control_formats:
2005
result.update(format._known_formats())
2009
def _known_formats(klass):
2010
"""Return the known format instances for this control format."""
2011
return set(klass._formats.values())
2013
def open(self, transport, _found=False):
2014
"""Return an instance of this format for the dir transport points at.
2016
_found is a private parameter, do not use it.
2019
found_format = BzrDirFormat.find_format(transport)
2020
if not isinstance(found_format, self.__class__):
2021
raise AssertionError("%s was asked to open %s, but it seems to need "
2023
% (self, transport, found_format))
2024
# Allow subclasses - use the found format.
2025
self._supply_sub_formats_to(found_format)
2026
return found_format._open(transport)
2027
return self._open(transport)
2029
def _open(self, transport):
2030
"""Template method helper for opening BzrDirectories.
2032
This performs the actual open and any additional logic or parameter
2035
raise NotImplementedError(self._open)
2038
def register_format(klass, format):
2039
klass._formats[format.get_format_string()] = format
2040
# bzr native formats have a network name of their format string.
2041
network_format_registry.register(format.get_format_string(), format.__class__)
2044
def register_control_format(klass, format):
2045
"""Register a format that does not use '.bzr' for its control dir.
2047
TODO: This should be pulled up into a 'ControlDirFormat' base class
2048
which BzrDirFormat can inherit from, and renamed to register_format
2049
there. It has been done without that for now for simplicity of
2052
klass._control_formats.append(format)
2055
def register_control_server_format(klass, format):
2056
"""Register a control format for client-server environments.
2058
These formats will be tried before ones registered with
2059
register_control_format. This gives implementations that decide to the
2060
chance to grab it before anything looks at the contents of the format
2063
klass._control_server_formats.append(format)
2066
def _set_default_format(klass, format):
2067
"""Set default format (for testing behavior of defaults only)"""
2068
klass._default_format = format
2072
return self.get_format_description().rstrip()
2074
def _supply_sub_formats_to(self, other_format):
2075
"""Give other_format the same values for sub formats as this has.
2077
This method is expected to be used when parameterising a
2078
RemoteBzrDirFormat instance with the parameters from a
2079
BzrDirMetaFormat1 instance.
2081
:param other_format: other_format is a format which should be
2082
compatible with whatever sub formats are supported by self.
2087
def unregister_format(klass, format):
2088
del klass._formats[format.get_format_string()]
2091
def unregister_control_format(klass, format):
2092
klass._control_formats.remove(format)
2095
class BzrDirFormat4(BzrDirFormat):
2096
"""Bzr dir format 4.
2098
This format is a combined format for working tree, branch and repository.
2100
- Format 1 working trees [always]
2101
- Format 4 branches [always]
2102
- Format 4 repositories [always]
2104
This format is deprecated: it indexes texts using a text it which is
2105
removed in format 5; write support for this format has been removed.
2108
_lock_class = lockable_files.TransportLock
2110
def get_format_string(self):
2111
"""See BzrDirFormat.get_format_string()."""
2112
return "Bazaar-NG branch, format 0.0.4\n"
2114
def get_format_description(self):
2115
"""See BzrDirFormat.get_format_description()."""
2116
return "All-in-one format 4"
2118
def get_converter(self, format=None):
2119
"""See BzrDirFormat.get_converter()."""
2120
# there is one and only one upgrade path here.
2121
return ConvertBzrDir4To5()
2123
def initialize_on_transport(self, transport):
2124
"""Format 4 branches cannot be created."""
2125
raise errors.UninitializableFormat(self)
2127
def is_supported(self):
2128
"""Format 4 is not supported.
2130
It is not supported because the model changed from 4 to 5 and the
2131
conversion logic is expensive - so doing it on the fly was not
2136
def network_name(self):
2137
return self.get_format_string()
2139
def _open(self, transport):
2140
"""See BzrDirFormat._open."""
2141
return BzrDir4(transport, self)
2143
def __return_repository_format(self):
2144
"""Circular import protection."""
2145
from bzrlib.repofmt.weaverepo import RepositoryFormat4
2146
return RepositoryFormat4()
2147
repository_format = property(__return_repository_format)
2150
class BzrDirFormatAllInOne(BzrDirFormat):
2151
"""Common class for formats before meta-dirs."""
2153
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
2154
create_prefix=False, force_new_repo=False, stacked_on=None,
2155
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
2157
"""See BzrDirFormat.initialize_on_transport_ex."""
2158
require_stacking = (stacked_on is not None)
2159
# Format 5 cannot stack, but we've been asked do - actually init
2161
if require_stacking:
2162
format = BzrDirMetaFormat1()
2163
return format.initialize_on_transport_ex(transport,
2164
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2165
force_new_repo=force_new_repo, stacked_on=stacked_on,
2166
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2167
make_working_trees=make_working_trees, shared_repo=shared_repo)
2168
return BzrDirFormat.initialize_on_transport_ex(self, transport,
2169
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2170
force_new_repo=force_new_repo, stacked_on=stacked_on,
2171
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2172
make_working_trees=make_working_trees, shared_repo=shared_repo)
2175
class BzrDirFormat5(BzrDirFormatAllInOne):
2176
"""Bzr control format 5.
2178
This format is a combined format for working tree, branch and repository.
2180
- Format 2 working trees [always]
2181
- Format 4 branches [always]
2182
- Format 5 repositories [always]
2183
Unhashed stores in the repository.
2186
_lock_class = lockable_files.TransportLock
2188
def get_format_string(self):
2189
"""See BzrDirFormat.get_format_string()."""
2190
return "Bazaar-NG branch, format 5\n"
2192
def get_branch_format(self):
2193
from bzrlib import branch
2194
return branch.BzrBranchFormat4()
2196
def get_format_description(self):
2197
"""See BzrDirFormat.get_format_description()."""
2198
return "All-in-one format 5"
2200
def get_converter(self, format=None):
2201
"""See BzrDirFormat.get_converter()."""
2202
# there is one and only one upgrade path here.
2203
return ConvertBzrDir5To6()
2205
def _initialize_for_clone(self, url):
2206
return self.initialize_on_transport(get_transport(url), _cloning=True)
2208
def initialize_on_transport(self, transport, _cloning=False):
2209
"""Format 5 dirs always have working tree, branch and repository.
2211
Except when they are being cloned.
2213
from bzrlib.branch import BzrBranchFormat4
2214
from bzrlib.repofmt.weaverepo import RepositoryFormat5
2215
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
2216
RepositoryFormat5().initialize(result, _internal=True)
2218
branch = BzrBranchFormat4().initialize(result)
2219
result._init_workingtree()
2222
def network_name(self):
2223
return self.get_format_string()
2225
def _open(self, transport):
2226
"""See BzrDirFormat._open."""
2227
return BzrDir5(transport, self)
2229
def __return_repository_format(self):
2230
"""Circular import protection."""
2231
from bzrlib.repofmt.weaverepo import RepositoryFormat5
2232
return RepositoryFormat5()
2233
repository_format = property(__return_repository_format)
2236
class BzrDirFormat6(BzrDirFormatAllInOne):
2237
"""Bzr control format 6.
2239
This format is a combined format for working tree, branch and repository.
2241
- Format 2 working trees [always]
2242
- Format 4 branches [always]
2243
- Format 6 repositories [always]
2246
_lock_class = lockable_files.TransportLock
2248
def get_format_string(self):
2249
"""See BzrDirFormat.get_format_string()."""
2250
return "Bazaar-NG branch, format 6\n"
2252
def get_format_description(self):
2253
"""See BzrDirFormat.get_format_description()."""
2254
return "All-in-one format 6"
2256
def get_branch_format(self):
2257
from bzrlib import branch
2258
return branch.BzrBranchFormat4()
2260
def get_converter(self, format=None):
2261
"""See BzrDirFormat.get_converter()."""
2262
# there is one and only one upgrade path here.
2263
return ConvertBzrDir6ToMeta()
2265
def _initialize_for_clone(self, url):
2266
return self.initialize_on_transport(get_transport(url), _cloning=True)
2268
def initialize_on_transport(self, transport, _cloning=False):
2269
"""Format 6 dirs always have working tree, branch and repository.
2271
Except when they are being cloned.
2273
from bzrlib.branch import BzrBranchFormat4
2274
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2275
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
2276
RepositoryFormat6().initialize(result, _internal=True)
2278
branch = BzrBranchFormat4().initialize(result)
2279
result._init_workingtree()
2282
def network_name(self):
2283
return self.get_format_string()
2285
def _open(self, transport):
2286
"""See BzrDirFormat._open."""
2287
return BzrDir6(transport, self)
2289
def __return_repository_format(self):
2290
"""Circular import protection."""
2291
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2292
return RepositoryFormat6()
2293
repository_format = property(__return_repository_format)
2296
class BzrDirMetaFormat1(BzrDirFormat):
2297
"""Bzr meta control format 1
2299
This is the first format with split out working tree, branch and repository
2302
- Format 3 working trees [optional]
2303
- Format 5 branches [optional]
2304
- Format 7 repositories [optional]
2307
_lock_class = lockdir.LockDir
2310
self._workingtree_format = None
2311
self._branch_format = None
2312
self._repository_format = None
2314
def __eq__(self, other):
2315
if other.__class__ is not self.__class__:
2317
if other.repository_format != self.repository_format:
2319
if other.workingtree_format != self.workingtree_format:
2323
def __ne__(self, other):
2324
return not self == other
2326
def get_branch_format(self):
2327
if self._branch_format is None:
2328
from bzrlib.branch import BranchFormat
2329
self._branch_format = BranchFormat.get_default_format()
2330
return self._branch_format
2332
def set_branch_format(self, format):
2333
self._branch_format = format
2335
def require_stacking(self):
2336
if not self.get_branch_format().supports_stacking():
2337
# We need to make a stacked branch, but the default format for the
2338
# target doesn't support stacking. So force a branch that *can*
2340
from bzrlib.branch import BzrBranchFormat7
2341
branch_format = BzrBranchFormat7()
2342
self.set_branch_format(branch_format)
2343
mutter("using %r for stacking" % (branch_format,))
2344
from bzrlib.repofmt import pack_repo
2345
if self.repository_format.rich_root_data:
2346
bzrdir_format_name = '1.6.1-rich-root'
2347
repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
2349
bzrdir_format_name = '1.6'
2350
repo_format = pack_repo.RepositoryFormatKnitPack5()
2351
note('Source format does not support stacking, using format:'
2353
bzrdir_format_name, repo_format.get_format_description())
2354
self.repository_format = repo_format
2356
def get_converter(self, format=None):
2357
"""See BzrDirFormat.get_converter()."""
2359
format = BzrDirFormat.get_default_format()
2360
if not isinstance(self, format.__class__):
2361
# converting away from metadir is not implemented
2362
raise NotImplementedError(self.get_converter)
2363
return ConvertMetaToMeta(format)
2365
def get_format_string(self):
2366
"""See BzrDirFormat.get_format_string()."""
2367
return "Bazaar-NG meta directory, format 1\n"
2369
def get_format_description(self):
2370
"""See BzrDirFormat.get_format_description()."""
2371
return "Meta directory format 1"
2373
def network_name(self):
2374
return self.get_format_string()
2376
def _open(self, transport):
2377
"""See BzrDirFormat._open."""
2378
return BzrDirMeta1(transport, self)
2380
def __return_repository_format(self):
2381
"""Circular import protection."""
2382
if self._repository_format:
2383
return self._repository_format
2384
from bzrlib.repository import RepositoryFormat
2385
return RepositoryFormat.get_default_format()
2387
def _set_repository_format(self, value):
2388
"""Allow changing the repository format for metadir formats."""
2389
self._repository_format = value
2391
repository_format = property(__return_repository_format,
2392
_set_repository_format)
2394
def _supply_sub_formats_to(self, other_format):
2395
"""Give other_format the same values for sub formats as this has.
2397
This method is expected to be used when parameterising a
2398
RemoteBzrDirFormat instance with the parameters from a
2399
BzrDirMetaFormat1 instance.
2401
:param other_format: other_format is a format which should be
2402
compatible with whatever sub formats are supported by self.
2405
if getattr(self, '_repository_format', None) is not None:
2406
other_format.repository_format = self.repository_format
2407
if self._branch_format is not None:
2408
other_format._branch_format = self._branch_format
2409
if self._workingtree_format is not None:
2410
other_format.workingtree_format = self.workingtree_format
2412
def __get_workingtree_format(self):
2413
if self._workingtree_format is None:
2414
from bzrlib.workingtree import WorkingTreeFormat
2415
self._workingtree_format = WorkingTreeFormat.get_default_format()
2416
return self._workingtree_format
2418
def __set_workingtree_format(self, wt_format):
2419
self._workingtree_format = wt_format
2421
workingtree_format = property(__get_workingtree_format,
2422
__set_workingtree_format)
2425
network_format_registry = registry.FormatRegistry()
2426
"""Registry of formats indexed by their network name.
2428
The network name for a BzrDirFormat is an identifier that can be used when
2429
referring to formats with smart server operations. See
2430
BzrDirFormat.network_name() for more detail.
2434
# Register bzr control format
2435
BzrDirFormat.register_control_format(BzrDirFormat)
2437
# Register bzr formats
2438
BzrDirFormat.register_format(BzrDirFormat4())
2439
BzrDirFormat.register_format(BzrDirFormat5())
2440
BzrDirFormat.register_format(BzrDirFormat6())
2441
__default_format = BzrDirMetaFormat1()
2442
BzrDirFormat.register_format(__default_format)
2443
BzrDirFormat._default_format = __default_format
2446
class Converter(object):
2447
"""Converts a disk format object from one format to another."""
2449
def convert(self, to_convert, pb):
2450
"""Perform the conversion of to_convert, giving feedback via pb.
2452
:param to_convert: The disk object to convert.
2453
:param pb: a progress bar to use for progress information.
2456
def step(self, message):
2457
"""Update the pb by a step."""
2459
self.pb.update(message, self.count, self.total)
2462
class ConvertBzrDir4To5(Converter):
2463
"""Converts format 4 bzr dirs to format 5."""
2466
super(ConvertBzrDir4To5, self).__init__()
2467
self.converted_revs = set()
2468
self.absent_revisions = set()
2472
def convert(self, to_convert, pb):
2473
"""See Converter.convert()."""
2474
self.bzrdir = to_convert
2476
self.pb.note('starting upgrade from format 4 to 5')
2477
if isinstance(self.bzrdir.transport, local.LocalTransport):
2478
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2479
self._convert_to_weaves()
2480
return BzrDir.open(self.bzrdir.root_transport.base)
2482
def _convert_to_weaves(self):
2483
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
2486
stat = self.bzrdir.transport.stat('weaves')
2487
if not S_ISDIR(stat.st_mode):
2488
self.bzrdir.transport.delete('weaves')
2489
self.bzrdir.transport.mkdir('weaves')
2490
except errors.NoSuchFile:
2491
self.bzrdir.transport.mkdir('weaves')
2492
# deliberately not a WeaveFile as we want to build it up slowly.
2493
self.inv_weave = Weave('inventory')
2494
# holds in-memory weaves for all files
2495
self.text_weaves = {}
2496
self.bzrdir.transport.delete('branch-format')
2497
self.branch = self.bzrdir.open_branch()
2498
self._convert_working_inv()
2499
rev_history = self.branch.revision_history()
2500
# to_read is a stack holding the revisions we still need to process;
2501
# appending to it adds new highest-priority revisions
2502
self.known_revisions = set(rev_history)
2503
self.to_read = rev_history[-1:]
2505
rev_id = self.to_read.pop()
2506
if (rev_id not in self.revisions
2507
and rev_id not in self.absent_revisions):
2508
self._load_one_rev(rev_id)
2510
to_import = self._make_order()
2511
for i, rev_id in enumerate(to_import):
2512
self.pb.update('converting revision', i, len(to_import))
2513
self._convert_one_rev(rev_id)
2515
self._write_all_weaves()
2516
self._write_all_revs()
2517
self.pb.note('upgraded to weaves:')
2518
self.pb.note(' %6d revisions and inventories', len(self.revisions))
2519
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
2520
self.pb.note(' %6d texts', self.text_count)
2521
self._cleanup_spare_files_after_format4()
2522
self.branch._transport.put_bytes(
2524
BzrDirFormat5().get_format_string(),
2525
mode=self.bzrdir._get_file_mode())
2527
def _cleanup_spare_files_after_format4(self):
2528
# FIXME working tree upgrade foo.
2529
for n in 'merged-patches', 'pending-merged-patches':
2531
## assert os.path.getsize(p) == 0
2532
self.bzrdir.transport.delete(n)
2533
except errors.NoSuchFile:
2535
self.bzrdir.transport.delete_tree('inventory-store')
2536
self.bzrdir.transport.delete_tree('text-store')
2538
def _convert_working_inv(self):
2539
inv = xml4.serializer_v4.read_inventory(
2540
self.branch._transport.get('inventory'))
2541
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2542
self.branch._transport.put_bytes('inventory', new_inv_xml,
2543
mode=self.bzrdir._get_file_mode())
2545
def _write_all_weaves(self):
2546
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2547
weave_transport = self.bzrdir.transport.clone('weaves')
2548
weaves = WeaveStore(weave_transport, prefixed=False)
2549
transaction = WriteTransaction()
2553
for file_id, file_weave in self.text_weaves.items():
2554
self.pb.update('writing weave', i, len(self.text_weaves))
2555
weaves._put_weave(file_id, file_weave, transaction)
2557
self.pb.update('inventory', 0, 1)
2558
controlweaves._put_weave('inventory', self.inv_weave, transaction)
2559
self.pb.update('inventory', 1, 1)
2563
def _write_all_revs(self):
2564
"""Write all revisions out in new form."""
2565
self.bzrdir.transport.delete_tree('revision-store')
2566
self.bzrdir.transport.mkdir('revision-store')
2567
revision_transport = self.bzrdir.transport.clone('revision-store')
2569
from bzrlib.xml5 import serializer_v5
2570
from bzrlib.repofmt.weaverepo import RevisionTextStore
2571
revision_store = RevisionTextStore(revision_transport,
2572
serializer_v5, False, versionedfile.PrefixMapper(),
2573
lambda:True, lambda:True)
2575
for i, rev_id in enumerate(self.converted_revs):
2576
self.pb.update('write revision', i, len(self.converted_revs))
2577
text = serializer_v5.write_revision_to_string(
2578
self.revisions[rev_id])
2580
revision_store.add_lines(key, None, osutils.split_lines(text))
2584
def _load_one_rev(self, rev_id):
2585
"""Load a revision object into memory.
2587
Any parents not either loaded or abandoned get queued to be
2589
self.pb.update('loading revision',
2590
len(self.revisions),
2591
len(self.known_revisions))
2592
if not self.branch.repository.has_revision(rev_id):
2594
self.pb.note('revision {%s} not present in branch; '
2595
'will be converted as a ghost',
2597
self.absent_revisions.add(rev_id)
2599
rev = self.branch.repository.get_revision(rev_id)
2600
for parent_id in rev.parent_ids:
2601
self.known_revisions.add(parent_id)
2602
self.to_read.append(parent_id)
2603
self.revisions[rev_id] = rev
2605
def _load_old_inventory(self, rev_id):
2606
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
2607
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2608
inv.revision_id = rev_id
2609
rev = self.revisions[rev_id]
2612
def _load_updated_inventory(self, rev_id):
2613
inv_xml = self.inv_weave.get_text(rev_id)
2614
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2617
def _convert_one_rev(self, rev_id):
2618
"""Convert revision and all referenced objects to new format."""
2619
rev = self.revisions[rev_id]
2620
inv = self._load_old_inventory(rev_id)
2621
present_parents = [p for p in rev.parent_ids
2622
if p not in self.absent_revisions]
2623
self._convert_revision_contents(rev, inv, present_parents)
2624
self._store_new_inv(rev, inv, present_parents)
2625
self.converted_revs.add(rev_id)
2627
def _store_new_inv(self, rev, inv, present_parents):
2628
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2629
new_inv_sha1 = sha_string(new_inv_xml)
2630
self.inv_weave.add_lines(rev.revision_id,
2632
new_inv_xml.splitlines(True))
2633
rev.inventory_sha1 = new_inv_sha1
2635
def _convert_revision_contents(self, rev, inv, present_parents):
2636
"""Convert all the files within a revision.
2638
Also upgrade the inventory to refer to the text revision ids."""
2639
rev_id = rev.revision_id
2640
mutter('converting texts of revision {%s}',
2642
parent_invs = map(self._load_updated_inventory, present_parents)
2643
entries = inv.iter_entries()
2645
for path, ie in entries:
2646
self._convert_file_version(rev, ie, parent_invs)
2648
def _convert_file_version(self, rev, ie, parent_invs):
2649
"""Convert one version of one file.
2651
The file needs to be added into the weave if it is a merge
2652
of >=2 parents or if it's changed from its parent.
2654
file_id = ie.file_id
2655
rev_id = rev.revision_id
2656
w = self.text_weaves.get(file_id)
2659
self.text_weaves[file_id] = w
2660
text_changed = False
2661
parent_candiate_entries = ie.parent_candidates(parent_invs)
2662
heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2663
# XXX: Note that this is unordered - and this is tolerable because
2664
# the previous code was also unordered.
2665
previous_entries = dict((head, parent_candiate_entries[head]) for head
2667
self.snapshot_ie(previous_entries, ie, w, rev_id)
2670
def get_parent_map(self, revision_ids):
2671
"""See graph._StackedParentsProvider.get_parent_map"""
2672
return dict((revision_id, self.revisions[revision_id])
2673
for revision_id in revision_ids
2674
if revision_id in self.revisions)
2676
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2677
# TODO: convert this logic, which is ~= snapshot to
2678
# a call to:. This needs the path figured out. rather than a work_tree
2679
# a v4 revision_tree can be given, or something that looks enough like
2680
# one to give the file content to the entry if it needs it.
2681
# and we need something that looks like a weave store for snapshot to
2683
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2684
if len(previous_revisions) == 1:
2685
previous_ie = previous_revisions.values()[0]
2686
if ie._unchanged(previous_ie):
2687
ie.revision = previous_ie.revision
2690
text = self.branch.repository._text_store.get(ie.text_id)
2691
file_lines = text.readlines()
2692
w.add_lines(rev_id, previous_revisions, file_lines)
2693
self.text_count += 1
2695
w.add_lines(rev_id, previous_revisions, [])
2696
ie.revision = rev_id
2698
def _make_order(self):
2699
"""Return a suitable order for importing revisions.
2701
The order must be such that an revision is imported after all
2702
its (present) parents.
2704
todo = set(self.revisions.keys())
2705
done = self.absent_revisions.copy()
2708
# scan through looking for a revision whose parents
2710
for rev_id in sorted(list(todo)):
2711
rev = self.revisions[rev_id]
2712
parent_ids = set(rev.parent_ids)
2713
if parent_ids.issubset(done):
2714
# can take this one now
2715
order.append(rev_id)
2721
class ConvertBzrDir5To6(Converter):
2722
"""Converts format 5 bzr dirs to format 6."""
2724
def convert(self, to_convert, pb):
2725
"""See Converter.convert()."""
2726
self.bzrdir = to_convert
2728
self.pb.note('starting upgrade from format 5 to 6')
2729
self._convert_to_prefixed()
2730
return BzrDir.open(self.bzrdir.root_transport.base)
2732
def _convert_to_prefixed(self):
2733
from bzrlib.store import TransportStore
2734
self.bzrdir.transport.delete('branch-format')
2735
for store_name in ["weaves", "revision-store"]:
2736
self.pb.note("adding prefixes to %s" % store_name)
2737
store_transport = self.bzrdir.transport.clone(store_name)
2738
store = TransportStore(store_transport, prefixed=True)
2739
for urlfilename in store_transport.list_dir('.'):
2740
filename = urlutils.unescape(urlfilename)
2741
if (filename.endswith(".weave") or
2742
filename.endswith(".gz") or
2743
filename.endswith(".sig")):
2744
file_id, suffix = os.path.splitext(filename)
2748
new_name = store._mapper.map((file_id,)) + suffix
2749
# FIXME keep track of the dirs made RBC 20060121
2751
store_transport.move(filename, new_name)
2752
except errors.NoSuchFile: # catches missing dirs strangely enough
2753
store_transport.mkdir(osutils.dirname(new_name))
2754
store_transport.move(filename, new_name)
2755
self.bzrdir.transport.put_bytes(
2757
BzrDirFormat6().get_format_string(),
2758
mode=self.bzrdir._get_file_mode())
2761
class ConvertBzrDir6ToMeta(Converter):
2762
"""Converts format 6 bzr dirs to metadirs."""
2764
def convert(self, to_convert, pb):
2765
"""See Converter.convert()."""
2766
from bzrlib.repofmt.weaverepo import RepositoryFormat7
2767
from bzrlib.branch import BzrBranchFormat5
2768
self.bzrdir = to_convert
2771
self.total = 20 # the steps we know about
2772
self.garbage_inventories = []
2773
self.dir_mode = self.bzrdir._get_dir_mode()
2774
self.file_mode = self.bzrdir._get_file_mode()
2776
self.pb.note('starting upgrade from format 6 to metadir')
2777
self.bzrdir.transport.put_bytes(
2779
"Converting to format 6",
2780
mode=self.file_mode)
2781
# its faster to move specific files around than to open and use the apis...
2782
# first off, nuke ancestry.weave, it was never used.
2784
self.step('Removing ancestry.weave')
2785
self.bzrdir.transport.delete('ancestry.weave')
2786
except errors.NoSuchFile:
2788
# find out whats there
2789
self.step('Finding branch files')
2790
last_revision = self.bzrdir.open_branch().last_revision()
2791
bzrcontents = self.bzrdir.transport.list_dir('.')
2792
for name in bzrcontents:
2793
if name.startswith('basis-inventory.'):
2794
self.garbage_inventories.append(name)
2795
# create new directories for repository, working tree and branch
2796
repository_names = [('inventory.weave', True),
2797
('revision-store', True),
2799
self.step('Upgrading repository ')
2800
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2801
self.make_lock('repository')
2802
# we hard code the formats here because we are converting into
2803
# the meta format. The meta format upgrader can take this to a
2804
# future format within each component.
2805
self.put_format('repository', RepositoryFormat7())
2806
for entry in repository_names:
2807
self.move_entry('repository', entry)
2809
self.step('Upgrading branch ')
2810
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2811
self.make_lock('branch')
2812
self.put_format('branch', BzrBranchFormat5())
2813
branch_files = [('revision-history', True),
2814
('branch-name', True),
2816
for entry in branch_files:
2817
self.move_entry('branch', entry)
2819
checkout_files = [('pending-merges', True),
2820
('inventory', True),
2821
('stat-cache', False)]
2822
# If a mandatory checkout file is not present, the branch does not have
2823
# a functional checkout. Do not create a checkout in the converted
2825
for name, mandatory in checkout_files:
2826
if mandatory and name not in bzrcontents:
2827
has_checkout = False
2831
if not has_checkout:
2832
self.pb.note('No working tree.')
2833
# If some checkout files are there, we may as well get rid of them.
2834
for name, mandatory in checkout_files:
2835
if name in bzrcontents:
2836
self.bzrdir.transport.delete(name)
2838
from bzrlib.workingtree import WorkingTreeFormat3
2839
self.step('Upgrading working tree')
2840
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2841
self.make_lock('checkout')
2843
'checkout', WorkingTreeFormat3())
2844
self.bzrdir.transport.delete_multi(
2845
self.garbage_inventories, self.pb)
2846
for entry in checkout_files:
2847
self.move_entry('checkout', entry)
2848
if last_revision is not None:
2849
self.bzrdir.transport.put_bytes(
2850
'checkout/last-revision', last_revision)
2851
self.bzrdir.transport.put_bytes(
2853
BzrDirMetaFormat1().get_format_string(),
2854
mode=self.file_mode)
2855
return BzrDir.open(self.bzrdir.root_transport.base)
2857
def make_lock(self, name):
2858
"""Make a lock for the new control dir name."""
2859
self.step('Make %s lock' % name)
2860
ld = lockdir.LockDir(self.bzrdir.transport,
2862
file_modebits=self.file_mode,
2863
dir_modebits=self.dir_mode)
2866
def move_entry(self, new_dir, entry):
2867
"""Move then entry name into new_dir."""
2869
mandatory = entry[1]
2870
self.step('Moving %s' % name)
2872
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2873
except errors.NoSuchFile:
2877
def put_format(self, dirname, format):
2878
self.bzrdir.transport.put_bytes('%s/format' % dirname,
2879
format.get_format_string(),
2883
class ConvertMetaToMeta(Converter):
2884
"""Converts the components of metadirs."""
2886
def __init__(self, target_format):
2887
"""Create a metadir to metadir converter.
2889
:param target_format: The final metadir format that is desired.
2891
self.target_format = target_format
2893
def convert(self, to_convert, pb):
2894
"""See Converter.convert()."""
2895
self.bzrdir = to_convert
2899
self.step('checking repository format')
2901
repo = self.bzrdir.open_repository()
2902
except errors.NoRepositoryPresent:
2905
if not isinstance(repo._format, self.target_format.repository_format.__class__):
2906
from bzrlib.repository import CopyConverter
2907
self.pb.note('starting repository conversion')
2908
converter = CopyConverter(self.target_format.repository_format)
2909
converter.convert(repo, pb)
2911
branch = self.bzrdir.open_branch()
2912
except errors.NotBranchError:
2915
# TODO: conversions of Branch and Tree should be done by
2916
# InterXFormat lookups/some sort of registry.
2917
# Avoid circular imports
2918
from bzrlib import branch as _mod_branch
2919
old = branch._format.__class__
2920
new = self.target_format.get_branch_format().__class__
2922
if (old == _mod_branch.BzrBranchFormat5 and
2923
new in (_mod_branch.BzrBranchFormat6,
2924
_mod_branch.BzrBranchFormat7)):
2925
branch_converter = _mod_branch.Converter5to6()
2926
elif (old == _mod_branch.BzrBranchFormat6 and
2927
new == _mod_branch.BzrBranchFormat7):
2928
branch_converter = _mod_branch.Converter6to7()
2930
raise errors.BadConversionTarget("No converter", new)
2931
branch_converter.convert(branch)
2932
branch = self.bzrdir.open_branch()
2933
old = branch._format.__class__
2935
tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2936
except (errors.NoWorkingTree, errors.NotLocalUrl):
2939
# TODO: conversions of Branch and Tree should be done by
2940
# InterXFormat lookups
2941
if (isinstance(tree, workingtree.WorkingTree3) and
2942
not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2943
isinstance(self.target_format.workingtree_format,
2944
workingtree_4.DirStateWorkingTreeFormat)):
2945
workingtree_4.Converter3to4().convert(tree)
2946
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2947
not isinstance(tree, workingtree_4.WorkingTree5) and
2948
isinstance(self.target_format.workingtree_format,
2949
workingtree_4.WorkingTreeFormat5)):
2950
workingtree_4.Converter4to5().convert(tree)
2951
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2952
not isinstance(tree, workingtree_4.WorkingTree6) and
2953
isinstance(self.target_format.workingtree_format,
2954
workingtree_4.WorkingTreeFormat6)):
2955
workingtree_4.Converter4or5to6().convert(tree)
2959
# This is not in remote.py because it's small, and needs to be registered.
2960
# Putting it in remote.py creates a circular import problem.
2961
# we can make it a lazy object if the control formats is turned into something
2963
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2964
"""Format representing bzrdirs accessed via a smart server"""
2967
BzrDirMetaFormat1.__init__(self)
2968
self._network_name = None
2970
def get_format_description(self):
2971
return 'bzr remote bzrdir'
2973
def get_format_string(self):
2974
raise NotImplementedError(self.get_format_string)
2976
def network_name(self):
2977
if self._network_name:
2978
return self._network_name
2980
raise AssertionError("No network name set.")
2983
def probe_transport(klass, transport):
2984
"""Return a RemoteBzrDirFormat object if it looks possible."""
2986
medium = transport.get_smart_medium()
2987
except (NotImplementedError, AttributeError,
2988
errors.TransportNotPossible, errors.NoSmartMedium,
2989
errors.SmartProtocolError):
2990
# no smart server, so not a branch for this format type.
2991
raise errors.NotBranchError(path=transport.base)
2993
# Decline to open it if the server doesn't support our required
2994
# version (3) so that the VFS-based transport will do it.
2995
if medium.should_probe():
2997
server_version = medium.protocol_version()
2998
except errors.SmartProtocolError:
2999
# Apparently there's no usable smart server there, even though
3000
# the medium supports the smart protocol.
3001
raise errors.NotBranchError(path=transport.base)
3002
if server_version != '2':
3003
raise errors.NotBranchError(path=transport.base)
3006
def initialize_on_transport(self, transport):
3008
# hand off the request to the smart server
3009
client_medium = transport.get_smart_medium()
3010
except errors.NoSmartMedium:
3011
# TODO: lookup the local format from a server hint.
3012
local_dir_format = BzrDirMetaFormat1()
3013
return local_dir_format.initialize_on_transport(transport)
3014
client = _SmartClient(client_medium)
3015
path = client.remote_path_from_transport(transport)
3016
response = client.call('BzrDirFormat.initialize', path)
3017
if response[0] != 'ok':
3018
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
3019
format = RemoteBzrDirFormat()
3020
self._supply_sub_formats_to(format)
3021
return remote.RemoteBzrDir(transport, format)
3023
def _open(self, transport):
3024
return remote.RemoteBzrDir(transport, self)
3026
def __eq__(self, other):
3027
if not isinstance(other, RemoteBzrDirFormat):
3029
return self.get_format_description() == other.get_format_description()
3031
def __return_repository_format(self):
3032
# Always return a RemoteRepositoryFormat object, but if a specific bzr
3033
# repository format has been asked for, tell the RemoteRepositoryFormat
3034
# that it should use that for init() etc.
3035
result = remote.RemoteRepositoryFormat()
3036
custom_format = getattr(self, '_repository_format', None)
3038
if isinstance(custom_format, remote.RemoteRepositoryFormat):
3039
return custom_format
3041
# We will use the custom format to create repositories over the
3042
# wire; expose its details like rich_root_data for code to
3044
result._custom_format = custom_format
3047
def get_branch_format(self):
3048
result = BzrDirMetaFormat1.get_branch_format(self)
3049
if not isinstance(result, remote.RemoteBranchFormat):
3050
new_result = remote.RemoteBranchFormat()
3051
new_result._custom_format = result
3053
self.set_branch_format(new_result)
3057
repository_format = property(__return_repository_format,
3058
BzrDirMetaFormat1._set_repository_format) #.im_func)
3061
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
3064
class BzrDirFormatInfo(object):
3066
def __init__(self, native, deprecated, hidden, experimental):
3067
self.deprecated = deprecated
3068
self.native = native
3069
self.hidden = hidden
3070
self.experimental = experimental
3073
class BzrDirFormatRegistry(registry.Registry):
3074
"""Registry of user-selectable BzrDir subformats.
3076
Differs from BzrDirFormat._control_formats in that it provides sub-formats,
3077
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
3081
"""Create a BzrDirFormatRegistry."""
3082
self._aliases = set()
3083
self._registration_order = list()
3084
super(BzrDirFormatRegistry, self).__init__()
3087
"""Return a set of the format names which are aliases."""
3088
return frozenset(self._aliases)
3090
def register_metadir(self, key,
3091
repository_format, help, native=True, deprecated=False,
3097
"""Register a metadir subformat.
3099
These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
3100
by the Repository/Branch/WorkingTreeformats.
3102
:param repository_format: The fully-qualified repository format class
3104
:param branch_format: Fully-qualified branch format class name as
3106
:param tree_format: Fully-qualified tree format class name as
3109
# This should be expanded to support setting WorkingTree and Branch
3110
# formats, once BzrDirMetaFormat1 supports that.
3111
def _load(full_name):
3112
mod_name, factory_name = full_name.rsplit('.', 1)
3114
mod = __import__(mod_name, globals(), locals(),
3116
except ImportError, e:
3117
raise ImportError('failed to load %s: %s' % (full_name, e))
3119
factory = getattr(mod, factory_name)
3120
except AttributeError:
3121
raise AttributeError('no factory %s in module %r'
3126
bd = BzrDirMetaFormat1()
3127
if branch_format is not None:
3128
bd.set_branch_format(_load(branch_format))
3129
if tree_format is not None:
3130
bd.workingtree_format = _load(tree_format)
3131
if repository_format is not None:
3132
bd.repository_format = _load(repository_format)
3134
self.register(key, helper, help, native, deprecated, hidden,
3135
experimental, alias)
3137
def register(self, key, factory, help, native=True, deprecated=False,
3138
hidden=False, experimental=False, alias=False):
3139
"""Register a BzrDirFormat factory.
3141
The factory must be a callable that takes one parameter: the key.
3142
It must produce an instance of the BzrDirFormat when called.
3144
This function mainly exists to prevent the info object from being
3147
registry.Registry.register(self, key, factory, help,
3148
BzrDirFormatInfo(native, deprecated, hidden, experimental))
3150
self._aliases.add(key)
3151
self._registration_order.append(key)
3153
def register_lazy(self, key, module_name, member_name, help, native=True,
3154
deprecated=False, hidden=False, experimental=False, alias=False):
3155
registry.Registry.register_lazy(self, key, module_name, member_name,
3156
help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
3158
self._aliases.add(key)
3159
self._registration_order.append(key)
3161
def set_default(self, key):
3162
"""Set the 'default' key to be a clone of the supplied key.
3164
This method must be called once and only once.
3166
registry.Registry.register(self, 'default', self.get(key),
3167
self.get_help(key), info=self.get_info(key))
3168
self._aliases.add('default')
3170
def set_default_repository(self, key):
3171
"""Set the FormatRegistry default and Repository default.
3173
This is a transitional method while Repository.set_default_format
3176
if 'default' in self:
3177
self.remove('default')
3178
self.set_default(key)
3179
format = self.get('default')()
3181
def make_bzrdir(self, key):
3182
return self.get(key)()
3184
def help_topic(self, topic):
3186
default_realkey = None
3187
default_help = self.get_help('default')
3189
for key in self._registration_order:
3190
if key == 'default':
3192
help = self.get_help(key)
3193
if help == default_help:
3194
default_realkey = key
3196
help_pairs.append((key, help))
3198
def wrapped(key, help, info):
3200
help = '(native) ' + help
3201
return ':%s:\n%s\n\n' % (key,
3202
textwrap.fill(help, initial_indent=' ',
3203
subsequent_indent=' '))
3204
if default_realkey is not None:
3205
output += wrapped(default_realkey, '(default) %s' % default_help,
3206
self.get_info('default'))
3207
deprecated_pairs = []
3208
experimental_pairs = []
3209
for key, help in help_pairs:
3210
info = self.get_info(key)
3213
elif info.deprecated:
3214
deprecated_pairs.append((key, help))
3215
elif info.experimental:
3216
experimental_pairs.append((key, help))
3218
output += wrapped(key, help, info)
3219
output += "\nSee ``bzr help formats`` for more about storage formats."
3221
if len(experimental_pairs) > 0:
3222
other_output += "Experimental formats are shown below.\n\n"
3223
for key, help in experimental_pairs:
3224
info = self.get_info(key)
3225
other_output += wrapped(key, help, info)
3228
"No experimental formats are available.\n\n"
3229
if len(deprecated_pairs) > 0:
3230
other_output += "\nDeprecated formats are shown below.\n\n"
3231
for key, help in deprecated_pairs:
3232
info = self.get_info(key)
3233
other_output += wrapped(key, help, info)
3236
"\nNo deprecated formats are available.\n\n"
3238
"\nSee ``bzr help formats`` for more about storage formats."
3240
if topic == 'other-formats':
3246
class RepositoryAcquisitionPolicy(object):
3247
"""Abstract base class for repository acquisition policies.
3249
A repository acquisition policy decides how a BzrDir acquires a repository
3250
for a branch that is being created. The most basic policy decision is
3251
whether to create a new repository or use an existing one.
3253
def __init__(self, stack_on, stack_on_pwd, require_stacking):
3256
:param stack_on: A location to stack on
3257
:param stack_on_pwd: If stack_on is relative, the location it is
3259
:param require_stacking: If True, it is a failure to not stack.
3261
self._stack_on = stack_on
3262
self._stack_on_pwd = stack_on_pwd
3263
self._require_stacking = require_stacking
3265
def configure_branch(self, branch):
3266
"""Apply any configuration data from this policy to the branch.
3268
Default implementation sets repository stacking.
3270
if self._stack_on is None:
3272
if self._stack_on_pwd is None:
3273
stack_on = self._stack_on
3276
stack_on = urlutils.rebase_url(self._stack_on,
3278
branch.bzrdir.root_transport.base)
3279
except errors.InvalidRebaseURLs:
3280
stack_on = self._get_full_stack_on()
3282
branch.set_stacked_on_url(stack_on)
3283
except (errors.UnstackableBranchFormat,
3284
errors.UnstackableRepositoryFormat):
3285
if self._require_stacking:
3288
def _get_full_stack_on(self):
3289
"""Get a fully-qualified URL for the stack_on location."""
3290
if self._stack_on is None:
3292
if self._stack_on_pwd is None:
3293
return self._stack_on
3295
return urlutils.join(self._stack_on_pwd, self._stack_on)
3297
def _add_fallback(self, repository, possible_transports=None):
3298
"""Add a fallback to the supplied repository, if stacking is set."""
3299
stack_on = self._get_full_stack_on()
3300
if stack_on is None:
3302
stacked_dir = BzrDir.open(stack_on,
3303
possible_transports=possible_transports)
3305
stacked_repo = stacked_dir.open_branch().repository
3306
except errors.NotBranchError:
3307
stacked_repo = stacked_dir.open_repository()
3309
repository.add_fallback_repository(stacked_repo)
3310
except errors.UnstackableRepositoryFormat:
3311
if self._require_stacking:
3314
self._require_stacking = True
3316
def acquire_repository(self, make_working_trees=None, shared=False):
3317
"""Acquire a repository for this bzrdir.
3319
Implementations may create a new repository or use a pre-exising
3321
:param make_working_trees: If creating a repository, set
3322
make_working_trees to this value (if non-None)
3323
:param shared: If creating a repository, make it shared if True
3324
:return: A repository, is_new_flag (True if the repository was
3327
raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
3330
class CreateRepository(RepositoryAcquisitionPolicy):
3331
"""A policy of creating a new repository"""
3333
def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3334
require_stacking=False):
3337
:param bzrdir: The bzrdir to create the repository on.
3338
:param stack_on: A location to stack on
3339
:param stack_on_pwd: If stack_on is relative, the location it is
3342
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3344
self._bzrdir = bzrdir
3346
def acquire_repository(self, make_working_trees=None, shared=False):
3347
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3349
Creates the desired repository in the bzrdir we already have.
3351
stack_on = self._get_full_stack_on()
3353
# Stacking is desired. requested by the target, but does the place it
3354
# points at support stacking? If it doesn't then we should
3355
# not implicitly upgrade. We check this here.
3356
format = self._bzrdir._format
3357
if not (format.repository_format.supports_external_lookups
3358
and format.get_branch_format().supports_stacking()):
3359
# May need to upgrade - but only do if the target also
3360
# supports stacking. Note that this currently wastes
3361
# network round trips to check - but we only do this
3362
# when the source can't stack so it will fade away
3363
# as people do upgrade.
3365
target_dir = BzrDir.open(stack_on,
3366
possible_transports=[self._bzrdir.root_transport])
3367
except errors.NotBranchError:
3368
# Nothing there, don't change formats
3372
target_branch = target_dir.open_branch()
3373
except errors.NotBranchError:
3374
# No branch, don't change formats
3377
branch_format = target_branch._format
3378
repo_format = target_branch.repository._format
3379
if not (branch_format.supports_stacking()
3380
and repo_format.supports_external_lookups):
3381
# Doesn't stack itself, don't force an upgrade
3384
# Does support stacking, use its format.
3385
format.repository_format = repo_format
3386
format.set_branch_format(branch_format)
3387
note('Source format does not support stacking, '
3388
'using format: \'%s\'\n %s\n',
3389
branch_format.get_format_description(),
3390
repo_format.get_format_description())
3391
if not self._require_stacking:
3392
# We have picked up automatic stacking somewhere.
3393
note('Using default stacking branch %s at %s', self._stack_on,
3395
repository = self._bzrdir.create_repository(shared=shared)
3396
self._add_fallback(repository,
3397
possible_transports=[self._bzrdir.transport])
3398
if make_working_trees is not None:
3399
repository.set_make_working_trees(make_working_trees)
3400
return repository, True
3403
class UseExistingRepository(RepositoryAcquisitionPolicy):
3404
"""A policy of reusing an existing repository"""
3406
def __init__(self, repository, stack_on=None, stack_on_pwd=None,
3407
require_stacking=False):
3410
:param repository: The repository to use.
3411
:param stack_on: A location to stack on
3412
:param stack_on_pwd: If stack_on is relative, the location it is
3415
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3417
self._repository = repository
3419
def acquire_repository(self, make_working_trees=None, shared=False):
3420
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3422
Returns an existing repository to use.
3424
self._add_fallback(self._repository,
3425
possible_transports=[self._repository.bzrdir.transport])
3426
return self._repository, False
3429
# Please register new formats after old formats so that formats
3430
# appear in chronological order and format descriptions can build
3432
format_registry = BzrDirFormatRegistry()
3433
# The pre-0.8 formats have their repository format network name registered in
3434
# repository.py. MetaDir formats have their repository format network name
3435
# inferred from their disk format string.
3436
format_registry.register('weave', BzrDirFormat6,
3437
'Pre-0.8 format. Slower than knit and does not'
3438
' support checkouts or shared repositories.',
3440
format_registry.register_metadir('metaweave',
3441
'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3442
'Transitional format in 0.8. Slower than knit.',
3443
branch_format='bzrlib.branch.BzrBranchFormat5',
3444
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3446
format_registry.register_metadir('knit',
3447
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3448
'Format using knits. Recommended for interoperation with bzr <= 0.14.',
3449
branch_format='bzrlib.branch.BzrBranchFormat5',
3450
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3452
format_registry.register_metadir('dirstate',
3453
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3454
help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3455
'above when accessed over the network.',
3456
branch_format='bzrlib.branch.BzrBranchFormat5',
3457
# this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3458
# directly from workingtree_4 triggers a circular import.
3459
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3461
format_registry.register_metadir('dirstate-tags',
3462
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3463
help='New in 0.15: Fast local operations and improved scaling for '
3464
'network operations. Additionally adds support for tags.'
3465
' Incompatible with bzr < 0.15.',
3466
branch_format='bzrlib.branch.BzrBranchFormat6',
3467
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3469
format_registry.register_metadir('rich-root',
3470
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3471
help='New in 1.0. Better handling of tree roots. Incompatible with'
3473
branch_format='bzrlib.branch.BzrBranchFormat6',
3474
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3476
format_registry.register_metadir('dirstate-with-subtree',
3477
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3478
help='New in 0.15: Fast local operations and improved scaling for '
3479
'network operations. Additionally adds support for versioning nested '
3480
'bzr branches. Incompatible with bzr < 0.15.',
3481
branch_format='bzrlib.branch.BzrBranchFormat6',
3482
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3486
format_registry.register_metadir('pack-0.92',
3487
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3488
help='New in 0.92: Pack-based format with data compatible with '
3489
'dirstate-tags format repositories. Interoperates with '
3490
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3491
'Previously called knitpack-experimental. '
3492
'For more information, see '
3493
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3494
branch_format='bzrlib.branch.BzrBranchFormat6',
3495
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3497
format_registry.register_metadir('pack-0.92-subtree',
3498
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3499
help='New in 0.92: Pack-based format with data compatible with '
3500
'dirstate-with-subtree format repositories. Interoperates with '
3501
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3502
'Previously called knitpack-experimental. '
3503
'For more information, see '
3504
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3505
branch_format='bzrlib.branch.BzrBranchFormat6',
3506
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3510
format_registry.register_metadir('rich-root-pack',
3511
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3512
help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3513
'(needed for bzr-svn and bzr-git).',
3514
branch_format='bzrlib.branch.BzrBranchFormat6',
3515
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3517
format_registry.register_metadir('1.6',
3518
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3519
help='A format that allows a branch to indicate that there is another '
3520
'(stacked) repository that should be used to access data that is '
3521
'not present locally.',
3522
branch_format='bzrlib.branch.BzrBranchFormat7',
3523
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3525
format_registry.register_metadir('1.6.1-rich-root',
3526
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3527
help='A variant of 1.6 that supports rich-root data '
3528
'(needed for bzr-svn and bzr-git).',
3529
branch_format='bzrlib.branch.BzrBranchFormat7',
3530
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3532
format_registry.register_metadir('1.9',
3533
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3534
help='A repository format using B+tree indexes. These indexes '
3535
'are smaller in size, have smarter caching and provide faster '
3536
'performance for most operations.',
3537
branch_format='bzrlib.branch.BzrBranchFormat7',
3538
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3540
format_registry.register_metadir('1.9-rich-root',
3541
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3542
help='A variant of 1.9 that supports rich-root data '
3543
'(needed for bzr-svn and bzr-git).',
3544
branch_format='bzrlib.branch.BzrBranchFormat7',
3545
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3547
format_registry.register_metadir('1.14',
3548
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3549
help='A working-tree format that supports content filtering.',
3550
branch_format='bzrlib.branch.BzrBranchFormat7',
3551
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3553
format_registry.register_metadir('1.14-rich-root',
3554
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3555
help='A variant of 1.14 that supports rich-root data '
3556
'(needed for bzr-svn and bzr-git).',
3557
branch_format='bzrlib.branch.BzrBranchFormat7',
3558
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3560
# The following un-numbered 'development' formats should always just be aliases.
3561
format_registry.register_metadir('development-rich-root',
3562
'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3563
help='Current development format. Supports rich roots. Can convert data '
3564
'to and from rich-root-pack (and anything compatible with '
3565
'rich-root-pack) format repositories. Repositories and branches in '
3566
'this format can only be read by bzr.dev. Please read '
3567
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3569
branch_format='bzrlib.branch.BzrBranchFormat7',
3570
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3574
format_registry.register_metadir('development-subtree',
3575
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3576
help='Current development format, subtree variant. Can convert data to and '
3577
'from pack-0.92-subtree (and anything compatible with '
3578
'pack-0.92-subtree) format repositories. Repositories and branches in '
3579
'this format can only be read by bzr.dev. Please read '
3580
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3582
branch_format='bzrlib.branch.BzrBranchFormat7',
3583
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3585
alias=False, # Restore to being an alias when an actual development subtree format is added
3586
# This current non-alias status is simply because we did not introduce a
3587
# chk based subtree format.
3590
# And the development formats above will have aliased one of the following:
3591
format_registry.register_metadir('development6-rich-root',
3592
'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3593
help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
3595
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3597
branch_format='bzrlib.branch.BzrBranchFormat7',
3598
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3603
# The following format should be an alias for the rich root equivalent
3604
# of the default format
3605
format_registry.register_metadir('default-rich-root',
3606
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3607
help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
3608
branch_format='bzrlib.branch.BzrBranchFormat6',
3609
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3612
# The current format that is made on 'bzr init'.
3613
format_registry.set_default('pack-0.92')