1
# Copyright (C) 2006-2010 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.
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
36
from stat import S_ISDIR
50
revision as _mod_revision,
60
from bzrlib.osutils import (
63
from bzrlib.push import (
66
from bzrlib.repofmt import pack_repo
67
from bzrlib.smart.client import _SmartClient
68
from bzrlib.store.versioned import WeaveStore
69
from bzrlib.transactions import WriteTransaction
70
from bzrlib.transport import (
71
do_catching_redirections,
75
from bzrlib.weave import Weave
78
from bzrlib.trace import (
91
class BzrDir(controldir.ControlDir):
92
"""A .bzr control diretory.
94
BzrDir instances let you create or open any of the things that can be
95
found within .bzr - checkouts, branches and repositories.
98
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
100
a transport connected to the directory this bzr was opened from
101
(i.e. the parent directory holding the .bzr directory).
103
Everything in the bzrdir should have the same file permissions.
105
:cvar hooks: An instance of BzrDirHooks.
108
def break_lock(self):
109
"""Invoke break_lock on the first object in the bzrdir.
111
If there is a tree, the tree is opened and break_lock() called.
112
Otherwise, branch is tried, and finally repository.
114
# XXX: This seems more like a UI function than something that really
115
# belongs in this class.
117
thing_to_unlock = self.open_workingtree()
118
except (errors.NotLocalUrl, errors.NoWorkingTree):
120
thing_to_unlock = self.open_branch()
121
except errors.NotBranchError:
123
thing_to_unlock = self.open_repository()
124
except errors.NoRepositoryPresent:
126
thing_to_unlock.break_lock()
128
def check_conversion_target(self, target_format):
129
"""Check that a bzrdir as a whole can be converted to a new format."""
130
# The only current restriction is that the repository content can be
131
# fetched compatibly with the target.
132
target_repo_format = target_format.repository_format
134
self.open_repository()._format.check_conversion_target(
136
except errors.NoRepositoryPresent:
137
# No repo, no problem.
141
def _check_supported(format, allow_unsupported,
142
recommend_upgrade=True,
144
"""Give an error or warning on old formats.
146
:param format: may be any kind of format - workingtree, branch,
149
:param allow_unsupported: If true, allow opening
150
formats that are strongly deprecated, and which may
151
have limited functionality.
153
:param recommend_upgrade: If true (default), warn
154
the user through the ui object that they may wish
155
to upgrade the object.
157
# TODO: perhaps move this into a base Format class; it's not BzrDir
158
# specific. mbp 20070323
159
if not allow_unsupported and not format.is_supported():
160
# see open_downlevel to open legacy branches.
161
raise errors.UnsupportedFormatError(format=format)
162
if recommend_upgrade \
163
and getattr(format, 'upgrade_recommended', False):
164
ui.ui_factory.recommend_upgrade(
165
format.get_format_description(),
168
def clone(self, url, revision_id=None, force_new_repo=False,
169
preserve_stacking=False):
170
"""Clone this bzrdir and its contents to url verbatim.
172
:param url: The url create the clone at. If url's last component does
173
not exist, it will be created.
174
:param revision_id: The tip revision-id to use for any branch or
175
working tree. If not None, then the clone operation may tune
176
itself to download less data.
177
:param force_new_repo: Do not use a shared repository for the target
178
even if one is available.
179
:param preserve_stacking: When cloning a stacked branch, stack the
180
new branch on top of the other branch's stacked-on branch.
182
return self.clone_on_transport(get_transport(url),
183
revision_id=revision_id,
184
force_new_repo=force_new_repo,
185
preserve_stacking=preserve_stacking)
187
def clone_on_transport(self, transport, revision_id=None,
188
force_new_repo=False, preserve_stacking=False, stacked_on=None,
189
create_prefix=False, use_existing_dir=True):
190
"""Clone this bzrdir and its contents to transport verbatim.
192
:param transport: The transport for the location to produce the clone
193
at. If the target directory does not exist, it will be created.
194
:param revision_id: The tip revision-id to use for any branch or
195
working tree. If not None, then the clone operation may tune
196
itself to download less data.
197
:param force_new_repo: Do not use a shared repository for the target,
198
even if one is available.
199
:param preserve_stacking: When cloning a stacked branch, stack the
200
new branch on top of the other branch's stacked-on branch.
201
:param create_prefix: Create any missing directories leading up to
203
:param use_existing_dir: Use an existing directory if one exists.
205
# Overview: put together a broad description of what we want to end up
206
# with; then make as few api calls as possible to do it.
208
# We may want to create a repo/branch/tree, if we do so what format
209
# would we want for each:
210
require_stacking = (stacked_on is not None)
211
format = self.cloning_metadir(require_stacking)
213
# Figure out what objects we want:
215
local_repo = self.find_repository()
216
except errors.NoRepositoryPresent:
219
local_branch = self.open_branch()
220
except errors.NotBranchError:
223
# enable fallbacks when branch is not a branch reference
224
if local_branch.repository.has_same_location(local_repo):
225
local_repo = local_branch.repository
226
if preserve_stacking:
228
stacked_on = local_branch.get_stacked_on_url()
229
except (errors.UnstackableBranchFormat,
230
errors.UnstackableRepositoryFormat,
233
# Bug: We create a metadir without knowing if it can support stacking,
234
# we should look up the policy needs first, or just use it as a hint,
237
make_working_trees = local_repo.make_working_trees()
238
want_shared = local_repo.is_shared()
239
repo_format_name = format.repository_format.network_name()
241
make_working_trees = False
243
repo_format_name = None
245
result_repo, result, require_stacking, repository_policy = \
246
format.initialize_on_transport_ex(transport,
247
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
248
force_new_repo=force_new_repo, stacked_on=stacked_on,
249
stack_on_pwd=self.root_transport.base,
250
repo_format_name=repo_format_name,
251
make_working_trees=make_working_trees, shared_repo=want_shared)
254
# If the result repository is in the same place as the
255
# resulting bzr dir, it will have no content, further if the
256
# result is not stacked then we know all content should be
257
# copied, and finally if we are copying up to a specific
258
# revision_id then we can use the pending-ancestry-result which
259
# does not require traversing all of history to describe it.
260
if (result_repo.user_url == result.user_url
261
and not require_stacking and
262
revision_id is not None):
263
fetch_spec = graph.PendingAncestryResult(
264
[revision_id], local_repo)
265
result_repo.fetch(local_repo, fetch_spec=fetch_spec)
267
result_repo.fetch(local_repo, revision_id=revision_id)
271
if result_repo is not None:
272
raise AssertionError('result_repo not None(%r)' % result_repo)
273
# 1 if there is a branch present
274
# make sure its content is available in the target repository
276
if local_branch is not None:
277
result_branch = local_branch.clone(result, revision_id=revision_id,
278
repository_policy=repository_policy)
280
# Cheaper to check if the target is not local, than to try making
282
result.root_transport.local_abspath('.')
283
if result_repo is None or result_repo.make_working_trees():
284
self.open_workingtree().clone(result)
285
except (errors.NoWorkingTree, errors.NotLocalUrl):
289
# TODO: This should be given a Transport, and should chdir up; otherwise
290
# this will open a new connection.
291
def _make_tail(self, url):
292
t = get_transport(url)
296
def find_bzrdirs(transport, evaluate=None, list_current=None):
297
"""Find bzrdirs recursively from current location.
299
This is intended primarily as a building block for more sophisticated
300
functionality, like finding trees under a directory, or finding
301
branches that use a given repository.
302
:param evaluate: An optional callable that yields recurse, value,
303
where recurse controls whether this bzrdir is recursed into
304
and value is the value to yield. By default, all bzrdirs
305
are recursed into, and the return value is the bzrdir.
306
:param list_current: if supplied, use this function to list the current
307
directory, instead of Transport.list_dir
308
:return: a generator of found bzrdirs, or whatever evaluate returns.
310
if list_current is None:
311
def list_current(transport):
312
return transport.list_dir('')
314
def evaluate(bzrdir):
317
pending = [transport]
318
while len(pending) > 0:
319
current_transport = pending.pop()
322
bzrdir = BzrDir.open_from_transport(current_transport)
323
except (errors.NotBranchError, errors.PermissionDenied):
326
recurse, value = evaluate(bzrdir)
329
subdirs = list_current(current_transport)
330
except (errors.NoSuchFile, errors.PermissionDenied):
333
for subdir in sorted(subdirs, reverse=True):
334
pending.append(current_transport.clone(subdir))
337
def find_branches(transport):
338
"""Find all branches under a transport.
340
This will find all branches below the transport, including branches
341
inside other branches. Where possible, it will use
342
Repository.find_branches.
344
To list all the branches that use a particular Repository, see
345
Repository.find_branches
347
def evaluate(bzrdir):
349
repository = bzrdir.open_repository()
350
except errors.NoRepositoryPresent:
353
return False, ([], repository)
354
return True, (bzrdir.list_branches(), None)
356
for branches, repo in BzrDir.find_bzrdirs(transport,
359
ret.extend(repo.find_branches())
360
if branches is not None:
365
def create_branch_and_repo(base, force_new_repo=False, format=None):
366
"""Create a new BzrDir, Branch and Repository at the url 'base'.
368
This will use the current default BzrDirFormat unless one is
369
specified, and use whatever
370
repository format that that uses via bzrdir.create_branch and
371
create_repository. If a shared repository is available that is used
374
The created Branch object is returned.
376
:param base: The URL to create the branch at.
377
:param force_new_repo: If True a new repository is always created.
378
:param format: If supplied, the format of branch to create. If not
379
supplied, the default is used.
381
bzrdir = BzrDir.create(base, format)
382
bzrdir._find_or_create_repository(force_new_repo)
383
return bzrdir.create_branch()
385
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
386
stack_on_pwd=None, require_stacking=False):
387
"""Return an object representing a policy to use.
389
This controls whether a new repository is created, and the format of
390
that repository, or some existing shared repository used instead.
392
If stack_on is supplied, will not seek a containing shared repo.
394
:param force_new_repo: If True, require a new repository to be created.
395
:param stack_on: If supplied, the location to stack on. If not
396
supplied, a default_stack_on location may be used.
397
:param stack_on_pwd: If stack_on is relative, the location it is
400
def repository_policy(found_bzrdir):
403
config = found_bzrdir.get_config()
405
stack_on = config.get_default_stack_on()
406
if stack_on is not None:
407
stack_on_pwd = found_bzrdir.user_url
409
# does it have a repository ?
411
repository = found_bzrdir.open_repository()
412
except errors.NoRepositoryPresent:
415
if (found_bzrdir.user_url != self.user_url
416
and not repository.is_shared()):
417
# Don't look higher, can't use a higher shared repo.
425
return UseExistingRepository(repository, stack_on,
426
stack_on_pwd, require_stacking=require_stacking), True
428
return CreateRepository(self, stack_on, stack_on_pwd,
429
require_stacking=require_stacking), True
431
if not force_new_repo:
433
policy = self._find_containing(repository_policy)
434
if policy is not None:
438
return UseExistingRepository(self.open_repository(),
439
stack_on, stack_on_pwd,
440
require_stacking=require_stacking)
441
except errors.NoRepositoryPresent:
443
return CreateRepository(self, stack_on, stack_on_pwd,
444
require_stacking=require_stacking)
446
def _find_or_create_repository(self, force_new_repo):
447
"""Create a new repository if needed, returning the repository."""
448
policy = self.determine_repository_policy(force_new_repo)
449
return policy.acquire_repository()[0]
452
def create_branch_convenience(base, force_new_repo=False,
453
force_new_tree=None, format=None,
454
possible_transports=None):
455
"""Create a new BzrDir, Branch and Repository at the url 'base'.
457
This is a convenience function - it will use an existing repository
458
if possible, can be told explicitly whether to create a working tree or
461
This will use the current default BzrDirFormat unless one is
462
specified, and use whatever
463
repository format that that uses via bzrdir.create_branch and
464
create_repository. If a shared repository is available that is used
465
preferentially. Whatever repository is used, its tree creation policy
468
The created Branch object is returned.
469
If a working tree cannot be made due to base not being a file:// url,
470
no error is raised unless force_new_tree is True, in which case no
471
data is created on disk and NotLocalUrl is raised.
473
:param base: The URL to create the branch at.
474
:param force_new_repo: If True a new repository is always created.
475
:param force_new_tree: If True or False force creation of a tree or
476
prevent such creation respectively.
477
:param format: Override for the bzrdir format to create.
478
:param possible_transports: An optional reusable transports list.
481
# check for non local urls
482
t = get_transport(base, possible_transports)
483
if not isinstance(t, local.LocalTransport):
484
raise errors.NotLocalUrl(base)
485
bzrdir = BzrDir.create(base, format, possible_transports)
486
repo = bzrdir._find_or_create_repository(force_new_repo)
487
result = bzrdir.create_branch()
488
if force_new_tree or (repo.make_working_trees() and
489
force_new_tree is None):
491
bzrdir.create_workingtree()
492
except errors.NotLocalUrl:
497
def create_standalone_workingtree(base, format=None):
498
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
500
'base' must be a local path or a file:// url.
502
This will use the current default BzrDirFormat unless one is
503
specified, and use whatever
504
repository format that that uses for bzrdirformat.create_workingtree,
505
create_branch and create_repository.
507
:param format: Override for the bzrdir format to create.
508
:return: The WorkingTree object.
510
t = get_transport(base)
511
if not isinstance(t, local.LocalTransport):
512
raise errors.NotLocalUrl(base)
513
bzrdir = BzrDir.create_branch_and_repo(base,
515
format=format).bzrdir
516
return bzrdir.create_workingtree()
518
def generate_backup_name(self, base):
519
"""Generate a non-existing backup file name based on base."""
521
name = "%s.~%d~" % (base, counter)
522
while self.root_transport.has(name):
524
name = "%s.~%d~" % (base, counter)
527
def backup_bzrdir(self):
528
"""Backup this bzr control directory.
530
:return: Tuple with old path name and new path name
533
backup_dir=self.generate_backup_name('backup.bzr')
534
pb = ui.ui_factory.nested_progress_bar()
536
# FIXME: bug 300001 -- the backup fails if the backup directory
537
# already exists, but it should instead either remove it or make
538
# a new backup directory.
540
old_path = self.root_transport.abspath('.bzr')
541
new_path = self.root_transport.abspath(backup_dir)
542
ui.ui_factory.note('making backup of %s\n to %s' % (old_path, new_path,))
543
self.root_transport.copy_tree('.bzr', backup_dir)
544
return (old_path, new_path)
548
def retire_bzrdir(self, limit=10000):
549
"""Permanently disable the bzrdir.
551
This is done by renaming it to give the user some ability to recover
552
if there was a problem.
554
This will have horrible consequences if anyone has anything locked or
556
:param limit: number of times to retry
561
to_path = '.bzr.retired.%d' % i
562
self.root_transport.rename('.bzr', to_path)
563
note("renamed %s to %s"
564
% (self.root_transport.abspath('.bzr'), to_path))
566
except (errors.TransportError, IOError, errors.PathError):
573
def _find_containing(self, evaluate):
574
"""Find something in a containing control directory.
576
This method will scan containing control dirs, until it finds what
577
it is looking for, decides that it will never find it, or runs out
578
of containing control directories to check.
580
It is used to implement find_repository and
581
determine_repository_policy.
583
:param evaluate: A function returning (value, stop). If stop is True,
584
the value will be returned.
588
result, stop = evaluate(found_bzrdir)
591
next_transport = found_bzrdir.root_transport.clone('..')
592
if (found_bzrdir.user_url == next_transport.base):
593
# top of the file system
595
# find the next containing bzrdir
597
found_bzrdir = BzrDir.open_containing_from_transport(
599
except errors.NotBranchError:
602
def find_repository(self):
603
"""Find the repository that should be used.
605
This does not require a branch as we use it to find the repo for
606
new branches as well as to hook existing branches up to their
609
def usable_repository(found_bzrdir):
610
# does it have a repository ?
612
repository = found_bzrdir.open_repository()
613
except errors.NoRepositoryPresent:
615
if found_bzrdir.user_url == self.user_url:
616
return repository, True
617
elif repository.is_shared():
618
return repository, True
622
found_repo = self._find_containing(usable_repository)
623
if found_repo is None:
624
raise errors.NoRepositoryPresent(self)
627
def _find_creation_modes(self):
628
"""Determine the appropriate modes for files and directories.
630
They're always set to be consistent with the base directory,
631
assuming that this transport allows setting modes.
633
# TODO: Do we need or want an option (maybe a config setting) to turn
634
# this off or override it for particular locations? -- mbp 20080512
635
if self._mode_check_done:
637
self._mode_check_done = True
639
st = self.transport.stat('.')
640
except errors.TransportNotPossible:
641
self._dir_mode = None
642
self._file_mode = None
644
# Check the directory mode, but also make sure the created
645
# directories and files are read-write for this user. This is
646
# mostly a workaround for filesystems which lie about being able to
647
# write to a directory (cygwin & win32)
648
if (st.st_mode & 07777 == 00000):
649
# FTP allows stat but does not return dir/file modes
650
self._dir_mode = None
651
self._file_mode = None
653
self._dir_mode = (st.st_mode & 07777) | 00700
654
# Remove the sticky and execute bits for files
655
self._file_mode = self._dir_mode & ~07111
657
def _get_file_mode(self):
658
"""Return Unix mode for newly created files, or None.
660
if not self._mode_check_done:
661
self._find_creation_modes()
662
return self._file_mode
664
def _get_dir_mode(self):
665
"""Return Unix mode for newly created directories, or None.
667
if not self._mode_check_done:
668
self._find_creation_modes()
669
return self._dir_mode
671
def get_config(self):
672
"""Get configuration for this BzrDir."""
673
return config.BzrDirConfig(self)
675
def _get_config(self):
676
"""By default, no configuration is available."""
679
def __init__(self, _transport, _format):
680
"""Initialize a Bzr control dir object.
682
Only really common logic should reside here, concrete classes should be
683
made with varying behaviours.
685
:param _format: the format that is creating this BzrDir instance.
686
:param _transport: the transport this dir is based at.
688
self._format = _format
689
# these are also under the more standard names of
690
# control_transport and user_transport
691
self.transport = _transport.clone('.bzr')
692
self.root_transport = _transport
693
self._mode_check_done = False
696
def user_transport(self):
697
return self.root_transport
700
def control_transport(self):
701
return self.transport
703
def is_control_filename(self, filename):
704
"""True if filename is the name of a path which is reserved for bzrdir's.
706
:param filename: A filename within the root transport of this bzrdir.
708
This is true IF and ONLY IF the filename is part of the namespace reserved
709
for bzr control dirs. Currently this is the '.bzr' directory in the root
710
of the root_transport.
712
# this might be better on the BzrDirFormat class because it refers to
713
# all the possible bzrdir disk formats.
714
# This method is tested via the workingtree is_control_filename tests-
715
# it was extracted from WorkingTree.is_control_filename. If the method's
716
# contract is extended beyond the current trivial implementation, please
717
# add new tests for it to the appropriate place.
718
return filename == '.bzr' or filename.startswith('.bzr/')
721
def open_unsupported(base):
722
"""Open a branch which is not supported."""
723
return BzrDir.open(base, _unsupported=True)
726
def open(base, _unsupported=False, possible_transports=None):
727
"""Open an existing bzrdir, rooted at 'base' (url).
729
:param _unsupported: a private parameter to the BzrDir class.
731
t = get_transport(base, possible_transports=possible_transports)
732
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
735
def open_from_transport(transport, _unsupported=False,
736
_server_formats=True):
737
"""Open a bzrdir within a particular directory.
739
:param transport: Transport containing the bzrdir.
740
:param _unsupported: private.
742
for hook in BzrDir.hooks['pre_open']:
744
# Keep initial base since 'transport' may be modified while following
746
base = transport.base
747
def find_format(transport):
748
return transport, controldir.ControlDirFormat.find_format(
749
transport, _server_formats=_server_formats)
751
def redirected(transport, e, redirection_notice):
752
redirected_transport = transport._redirected_to(e.source, e.target)
753
if redirected_transport is None:
754
raise errors.NotBranchError(base)
755
note('%s is%s redirected to %s',
756
transport.base, e.permanently, redirected_transport.base)
757
return redirected_transport
760
transport, format = do_catching_redirections(find_format,
763
except errors.TooManyRedirections:
764
raise errors.NotBranchError(base)
766
BzrDir._check_supported(format, _unsupported)
767
return format.open(transport, _found=True)
770
def open_containing(url, possible_transports=None):
771
"""Open an existing branch which contains url.
773
:param url: url to search from.
774
See open_containing_from_transport for more detail.
776
transport = get_transport(url, possible_transports)
777
return BzrDir.open_containing_from_transport(transport)
780
def open_containing_from_transport(a_transport):
781
"""Open an existing branch which contains a_transport.base.
783
This probes for a branch at a_transport, and searches upwards from there.
785
Basically we keep looking up until we find the control directory or
786
run into the root. If there isn't one, raises NotBranchError.
787
If there is one and it is either an unrecognised format or an unsupported
788
format, UnknownFormatError or UnsupportedFormatError are raised.
789
If there is one, it is returned, along with the unused portion of url.
791
:return: The BzrDir that contains the path, and a Unicode path
792
for the rest of the URL.
794
# this gets the normalised url back. I.e. '.' -> the full path.
795
url = a_transport.base
798
result = BzrDir.open_from_transport(a_transport)
799
return result, urlutils.unescape(a_transport.relpath(url))
800
except errors.NotBranchError, e:
803
new_t = a_transport.clone('..')
804
except errors.InvalidURLJoin:
805
# reached the root, whatever that may be
806
raise errors.NotBranchError(path=url)
807
if new_t.base == a_transport.base:
808
# reached the root, whatever that may be
809
raise errors.NotBranchError(path=url)
813
def open_tree_or_branch(klass, location):
814
"""Return the branch and working tree at a location.
816
If there is no tree at the location, tree will be None.
817
If there is no branch at the location, an exception will be
819
:return: (tree, branch)
821
bzrdir = klass.open(location)
822
return bzrdir._get_tree_branch()
825
def open_containing_tree_or_branch(klass, location):
826
"""Return the branch and working tree contained by a location.
828
Returns (tree, branch, relpath).
829
If there is no tree at containing the location, tree will be None.
830
If there is no branch containing the location, an exception will be
832
relpath is the portion of the path that is contained by the branch.
834
bzrdir, relpath = klass.open_containing(location)
835
tree, branch = bzrdir._get_tree_branch()
836
return tree, branch, relpath
839
def open_containing_tree_branch_or_repository(klass, location):
840
"""Return the working tree, branch and repo contained by a location.
842
Returns (tree, branch, repository, relpath).
843
If there is no tree containing the location, tree will be None.
844
If there is no branch containing the location, branch will be None.
845
If there is no repository containing the location, repository will be
847
relpath is the portion of the path that is contained by the innermost
850
If no tree, branch or repository is found, a NotBranchError is raised.
852
bzrdir, relpath = klass.open_containing(location)
854
tree, branch = bzrdir._get_tree_branch()
855
except errors.NotBranchError:
857
repo = bzrdir.find_repository()
858
return None, None, repo, relpath
859
except (errors.NoRepositoryPresent):
860
raise errors.NotBranchError(location)
861
return tree, branch, branch.repository, relpath
863
def _cloning_metadir(self):
864
"""Produce a metadir suitable for cloning with.
866
:returns: (destination_bzrdir_format, source_repository)
868
result_format = self._format.__class__()
871
branch = self.open_branch(ignore_fallbacks=True)
872
source_repository = branch.repository
873
result_format._branch_format = branch._format
874
except errors.NotBranchError:
876
source_repository = self.open_repository()
877
except errors.NoRepositoryPresent:
878
source_repository = None
880
# XXX TODO: This isinstance is here because we have not implemented
881
# the fix recommended in bug # 103195 - to delegate this choice the
883
repo_format = source_repository._format
884
if isinstance(repo_format, remote.RemoteRepositoryFormat):
885
source_repository._ensure_real()
886
repo_format = source_repository._real_repository._format
887
result_format.repository_format = repo_format
889
# TODO: Couldn't we just probe for the format in these cases,
890
# rather than opening the whole tree? It would be a little
891
# faster. mbp 20070401
892
tree = self.open_workingtree(recommend_upgrade=False)
893
except (errors.NoWorkingTree, errors.NotLocalUrl):
894
result_format.workingtree_format = None
896
result_format.workingtree_format = tree._format.__class__()
897
return result_format, source_repository
899
def cloning_metadir(self, require_stacking=False):
900
"""Produce a metadir suitable for cloning or sprouting with.
902
These operations may produce workingtrees (yes, even though they're
903
"cloning" something that doesn't have a tree), so a viable workingtree
904
format must be selected.
906
:require_stacking: If True, non-stackable formats will be upgraded
907
to similar stackable formats.
908
:returns: a BzrDirFormat with all component formats either set
909
appropriately or set to None if that component should not be
912
format, repository = self._cloning_metadir()
913
if format._workingtree_format is None:
915
if repository is None:
916
# No repository either
918
# We have a repository, so set a working tree? (Why? This seems to
919
# contradict the stated return value in the docstring).
920
tree_format = repository._format._matchingbzrdir.workingtree_format
921
format.workingtree_format = tree_format.__class__()
923
format.require_stacking()
927
def create(cls, base, format=None, possible_transports=None):
928
"""Create a new BzrDir at the url 'base'.
930
:param format: If supplied, the format of branch to create. If not
931
supplied, the default is used.
932
:param possible_transports: If supplied, a list of transports that
933
can be reused to share a remote connection.
935
if cls is not BzrDir:
936
raise AssertionError("BzrDir.create always creates the"
937
"default format, not one of %r" % cls)
938
t = get_transport(base, possible_transports)
941
format = controldir.ControlDirFormat.get_default_format()
942
return format.initialize_on_transport(t)
946
class BzrDirHooks(hooks.Hooks):
947
"""Hooks for BzrDir operations."""
950
"""Create the default hooks."""
951
hooks.Hooks.__init__(self)
952
self.create_hook(hooks.HookPoint('pre_open',
953
"Invoked before attempting to open a BzrDir with the transport "
954
"that the open will use.", (1, 14), None))
955
self.create_hook(hooks.HookPoint('post_repo_init',
956
"Invoked after a repository has been initialized. "
957
"post_repo_init is called with a "
958
"bzrlib.bzrdir.RepoInitHookParams.",
961
# install the default hooks
962
BzrDir.hooks = BzrDirHooks()
965
class RepoInitHookParams(object):
966
"""Object holding parameters passed to *_repo_init hooks.
968
There are 4 fields that hooks may wish to access:
970
:ivar repository: Repository created
971
:ivar format: Repository format
972
:ivar bzrdir: The bzrdir for the repository
973
:ivar shared: The repository is shared
976
def __init__(self, repository, format, a_bzrdir, shared):
977
"""Create a group of RepoInitHook parameters.
979
:param repository: Repository created
980
:param format: Repository format
981
:param bzrdir: The bzrdir for the repository
982
:param shared: The repository is shared
984
self.repository = repository
986
self.bzrdir = a_bzrdir
989
def __eq__(self, other):
990
return self.__dict__ == other.__dict__
994
return "<%s for %s>" % (self.__class__.__name__,
997
return "<%s for %s>" % (self.__class__.__name__,
1001
class BzrDirPreSplitOut(BzrDir):
1002
"""A common class for the all-in-one formats."""
1004
def __init__(self, _transport, _format):
1005
"""See BzrDir.__init__."""
1006
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1007
self._control_files = lockable_files.LockableFiles(
1008
self.get_branch_transport(None),
1009
self._format._lock_file_name,
1010
self._format._lock_class)
1012
def break_lock(self):
1013
"""Pre-splitout bzrdirs do not suffer from stale locks."""
1014
raise NotImplementedError(self.break_lock)
1016
def cloning_metadir(self, require_stacking=False):
1017
"""Produce a metadir suitable for cloning with."""
1018
if require_stacking:
1019
return controldir.format_registry.make_bzrdir('1.6')
1020
return self._format.__class__()
1022
def clone(self, url, revision_id=None, force_new_repo=False,
1023
preserve_stacking=False):
1024
"""See BzrDir.clone().
1026
force_new_repo has no effect, since this family of formats always
1027
require a new repository.
1028
preserve_stacking has no effect, since no source branch using this
1029
family of formats can be stacked, so there is no stacking to preserve.
1031
self._make_tail(url)
1032
result = self._format._initialize_for_clone(url)
1033
self.open_repository().clone(result, revision_id=revision_id)
1034
from_branch = self.open_branch()
1035
from_branch.clone(result, revision_id=revision_id)
1037
tree = self.open_workingtree()
1038
except errors.NotLocalUrl:
1039
# make a new one, this format always has to have one.
1040
result._init_workingtree()
1045
def create_branch(self, name=None):
1046
"""See BzrDir.create_branch."""
1047
return self._format.get_branch_format().initialize(self, name=name)
1049
def destroy_branch(self, name=None):
1050
"""See BzrDir.destroy_branch."""
1051
raise errors.UnsupportedOperation(self.destroy_branch, self)
1053
def create_repository(self, shared=False):
1054
"""See BzrDir.create_repository."""
1056
raise errors.IncompatibleFormat('shared repository', self._format)
1057
return self.open_repository()
1059
def destroy_repository(self):
1060
"""See BzrDir.destroy_repository."""
1061
raise errors.UnsupportedOperation(self.destroy_repository, self)
1063
def create_workingtree(self, revision_id=None, from_branch=None,
1064
accelerator_tree=None, hardlink=False):
1065
"""See BzrDir.create_workingtree."""
1066
# The workingtree is sometimes created when the bzrdir is created,
1067
# but not when cloning.
1069
# this looks buggy but is not -really-
1070
# because this format creates the workingtree when the bzrdir is
1072
# clone and sprout will have set the revision_id
1073
# and that will have set it for us, its only
1074
# specific uses of create_workingtree in isolation
1075
# that can do wonky stuff here, and that only
1076
# happens for creating checkouts, which cannot be
1077
# done on this format anyway. So - acceptable wart.
1079
warning("can't support hardlinked working trees in %r"
1082
result = self.open_workingtree(recommend_upgrade=False)
1083
except errors.NoSuchFile:
1084
result = self._init_workingtree()
1085
if revision_id is not None:
1086
if revision_id == _mod_revision.NULL_REVISION:
1087
result.set_parent_ids([])
1089
result.set_parent_ids([revision_id])
1092
def _init_workingtree(self):
1093
from bzrlib.workingtree import WorkingTreeFormat2
1095
return WorkingTreeFormat2().initialize(self)
1096
except errors.NotLocalUrl:
1097
# Even though we can't access the working tree, we need to
1098
# create its control files.
1099
return WorkingTreeFormat2()._stub_initialize_on_transport(
1100
self.transport, self._control_files._file_mode)
1102
def destroy_workingtree(self):
1103
"""See BzrDir.destroy_workingtree."""
1104
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1106
def destroy_workingtree_metadata(self):
1107
"""See BzrDir.destroy_workingtree_metadata."""
1108
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1111
def get_branch_transport(self, branch_format, name=None):
1112
"""See BzrDir.get_branch_transport()."""
1113
if name is not None:
1114
raise errors.NoColocatedBranchSupport(self)
1115
if branch_format is None:
1116
return self.transport
1118
branch_format.get_format_string()
1119
except NotImplementedError:
1120
return self.transport
1121
raise errors.IncompatibleFormat(branch_format, self._format)
1123
def get_repository_transport(self, repository_format):
1124
"""See BzrDir.get_repository_transport()."""
1125
if repository_format is None:
1126
return self.transport
1128
repository_format.get_format_string()
1129
except NotImplementedError:
1130
return self.transport
1131
raise errors.IncompatibleFormat(repository_format, self._format)
1133
def get_workingtree_transport(self, workingtree_format):
1134
"""See BzrDir.get_workingtree_transport()."""
1135
if workingtree_format is None:
1136
return self.transport
1138
workingtree_format.get_format_string()
1139
except NotImplementedError:
1140
return self.transport
1141
raise errors.IncompatibleFormat(workingtree_format, self._format)
1143
def needs_format_conversion(self, format=None):
1144
"""See BzrDir.needs_format_conversion()."""
1145
# if the format is not the same as the system default,
1146
# an upgrade is needed.
1148
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1149
% 'needs_format_conversion(format=None)')
1150
format = BzrDirFormat.get_default_format()
1151
return not isinstance(self._format, format.__class__)
1153
def open_branch(self, name=None, unsupported=False,
1154
ignore_fallbacks=False):
1155
"""See BzrDir.open_branch."""
1156
from bzrlib.branch import BzrBranchFormat4
1157
format = BzrBranchFormat4()
1158
self._check_supported(format, unsupported)
1159
return format.open(self, name, _found=True)
1161
def sprout(self, url, revision_id=None, force_new_repo=False,
1162
possible_transports=None, accelerator_tree=None,
1163
hardlink=False, stacked=False, create_tree_if_local=True,
1164
source_branch=None):
1165
"""See BzrDir.sprout()."""
1166
if source_branch is not None:
1167
my_branch = self.open_branch()
1168
if source_branch.base != my_branch.base:
1169
raise AssertionError(
1170
"source branch %r is not within %r with branch %r" %
1171
(source_branch, self, my_branch))
1173
raise errors.UnstackableBranchFormat(
1174
self._format, self.root_transport.base)
1175
if not create_tree_if_local:
1176
raise errors.MustHaveWorkingTree(
1177
self._format, self.root_transport.base)
1178
from bzrlib.workingtree import WorkingTreeFormat2
1179
self._make_tail(url)
1180
result = self._format._initialize_for_clone(url)
1182
self.open_repository().clone(result, revision_id=revision_id)
1183
except errors.NoRepositoryPresent:
1186
self.open_branch().sprout(result, revision_id=revision_id)
1187
except errors.NotBranchError:
1190
# we always want a working tree
1191
WorkingTreeFormat2().initialize(result,
1192
accelerator_tree=accelerator_tree,
1197
class BzrDir4(BzrDirPreSplitOut):
1198
"""A .bzr version 4 control object.
1200
This is a deprecated format and may be removed after sept 2006.
1203
def create_repository(self, shared=False):
1204
"""See BzrDir.create_repository."""
1205
return self._format.repository_format.initialize(self, shared)
1207
def needs_format_conversion(self, format=None):
1208
"""Format 4 dirs are always in need of conversion."""
1210
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1211
% 'needs_format_conversion(format=None)')
1214
def open_repository(self):
1215
"""See BzrDir.open_repository."""
1216
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1217
return RepositoryFormat4().open(self, _found=True)
1220
class BzrDir5(BzrDirPreSplitOut):
1221
"""A .bzr version 5 control object.
1223
This is a deprecated format and may be removed after sept 2006.
1226
def has_workingtree(self):
1227
"""See BzrDir.has_workingtree."""
1230
def open_repository(self):
1231
"""See BzrDir.open_repository."""
1232
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1233
return RepositoryFormat5().open(self, _found=True)
1235
def open_workingtree(self, _unsupported=False,
1236
recommend_upgrade=True):
1237
"""See BzrDir.create_workingtree."""
1238
from bzrlib.workingtree import WorkingTreeFormat2
1239
wt_format = WorkingTreeFormat2()
1240
# we don't warn here about upgrades; that ought to be handled for the
1242
return wt_format.open(self, _found=True)
1245
class BzrDir6(BzrDirPreSplitOut):
1246
"""A .bzr version 6 control object.
1248
This is a deprecated format and may be removed after sept 2006.
1251
def has_workingtree(self):
1252
"""See BzrDir.has_workingtree."""
1255
def open_repository(self):
1256
"""See BzrDir.open_repository."""
1257
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1258
return RepositoryFormat6().open(self, _found=True)
1260
def open_workingtree(self, _unsupported=False,
1261
recommend_upgrade=True):
1262
"""See BzrDir.create_workingtree."""
1263
# we don't warn here about upgrades; that ought to be handled for the
1265
from bzrlib.workingtree import WorkingTreeFormat2
1266
return WorkingTreeFormat2().open(self, _found=True)
1269
class BzrDirMeta1(BzrDir):
1270
"""A .bzr meta version 1 control object.
1272
This is the first control object where the
1273
individual aspects are really split out: there are separate repository,
1274
workingtree and branch subdirectories and any subset of the three can be
1275
present within a BzrDir.
1278
def can_convert_format(self):
1279
"""See BzrDir.can_convert_format()."""
1282
def create_branch(self, name=None):
1283
"""See BzrDir.create_branch."""
1284
return self._format.get_branch_format().initialize(self, name=name)
1286
def destroy_branch(self, name=None):
1287
"""See BzrDir.create_branch."""
1288
if name is not None:
1289
raise errors.NoColocatedBranchSupport(self)
1290
self.transport.delete_tree('branch')
1292
def create_repository(self, shared=False):
1293
"""See BzrDir.create_repository."""
1294
return self._format.repository_format.initialize(self, shared)
1296
def destroy_repository(self):
1297
"""See BzrDir.destroy_repository."""
1298
self.transport.delete_tree('repository')
1300
def create_workingtree(self, revision_id=None, from_branch=None,
1301
accelerator_tree=None, hardlink=False):
1302
"""See BzrDir.create_workingtree."""
1303
return self._format.workingtree_format.initialize(
1304
self, revision_id, from_branch=from_branch,
1305
accelerator_tree=accelerator_tree, hardlink=hardlink)
1307
def destroy_workingtree(self):
1308
"""See BzrDir.destroy_workingtree."""
1309
wt = self.open_workingtree(recommend_upgrade=False)
1310
repository = wt.branch.repository
1311
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1312
wt.revert(old_tree=empty)
1313
self.destroy_workingtree_metadata()
1315
def destroy_workingtree_metadata(self):
1316
self.transport.delete_tree('checkout')
1318
def find_branch_format(self, name=None):
1319
"""Find the branch 'format' for this bzrdir.
1321
This might be a synthetic object for e.g. RemoteBranch and SVN.
1323
from bzrlib.branch import BranchFormat
1324
return BranchFormat.find_format(self, name=name)
1326
def _get_mkdir_mode(self):
1327
"""Figure out the mode to use when creating a bzrdir subdir."""
1328
temp_control = lockable_files.LockableFiles(self.transport, '',
1329
lockable_files.TransportLock)
1330
return temp_control._dir_mode
1332
def get_branch_reference(self, name=None):
1333
"""See BzrDir.get_branch_reference()."""
1334
from bzrlib.branch import BranchFormat
1335
format = BranchFormat.find_format(self, name=name)
1336
return format.get_reference(self, name=name)
1338
def get_branch_transport(self, branch_format, name=None):
1339
"""See BzrDir.get_branch_transport()."""
1340
if name is not None:
1341
raise errors.NoColocatedBranchSupport(self)
1342
# XXX: this shouldn't implicitly create the directory if it's just
1343
# promising to get a transport -- mbp 20090727
1344
if branch_format is None:
1345
return self.transport.clone('branch')
1347
branch_format.get_format_string()
1348
except NotImplementedError:
1349
raise errors.IncompatibleFormat(branch_format, self._format)
1351
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1352
except errors.FileExists:
1354
return self.transport.clone('branch')
1356
def get_repository_transport(self, repository_format):
1357
"""See BzrDir.get_repository_transport()."""
1358
if repository_format is None:
1359
return self.transport.clone('repository')
1361
repository_format.get_format_string()
1362
except NotImplementedError:
1363
raise errors.IncompatibleFormat(repository_format, self._format)
1365
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1366
except errors.FileExists:
1368
return self.transport.clone('repository')
1370
def get_workingtree_transport(self, workingtree_format):
1371
"""See BzrDir.get_workingtree_transport()."""
1372
if workingtree_format is None:
1373
return self.transport.clone('checkout')
1375
workingtree_format.get_format_string()
1376
except NotImplementedError:
1377
raise errors.IncompatibleFormat(workingtree_format, self._format)
1379
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1380
except errors.FileExists:
1382
return self.transport.clone('checkout')
1384
def has_workingtree(self):
1385
"""Tell if this bzrdir contains a working tree.
1387
This will still raise an exception if the bzrdir has a workingtree that
1388
is remote & inaccessible.
1390
Note: if you're going to open the working tree, you should just go
1391
ahead and try, and not ask permission first.
1393
from bzrlib.workingtree import WorkingTreeFormat
1395
WorkingTreeFormat.find_format(self)
1396
except errors.NoWorkingTree:
1400
def needs_format_conversion(self, format=None):
1401
"""See BzrDir.needs_format_conversion()."""
1403
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1404
% 'needs_format_conversion(format=None)')
1406
format = BzrDirFormat.get_default_format()
1407
if not isinstance(self._format, format.__class__):
1408
# it is not a meta dir format, conversion is needed.
1410
# we might want to push this down to the repository?
1412
if not isinstance(self.open_repository()._format,
1413
format.repository_format.__class__):
1414
# the repository needs an upgrade.
1416
except errors.NoRepositoryPresent:
1418
for branch in self.list_branches():
1419
if not isinstance(branch._format,
1420
format.get_branch_format().__class__):
1421
# the branch needs an upgrade.
1424
my_wt = self.open_workingtree(recommend_upgrade=False)
1425
if not isinstance(my_wt._format,
1426
format.workingtree_format.__class__):
1427
# the workingtree needs an upgrade.
1429
except (errors.NoWorkingTree, errors.NotLocalUrl):
1433
def open_branch(self, name=None, unsupported=False,
1434
ignore_fallbacks=False):
1435
"""See BzrDir.open_branch."""
1436
format = self.find_branch_format(name=name)
1437
self._check_supported(format, unsupported)
1438
return format.open(self, name=name,
1439
_found=True, ignore_fallbacks=ignore_fallbacks)
1441
def open_repository(self, unsupported=False):
1442
"""See BzrDir.open_repository."""
1443
from bzrlib.repository import RepositoryFormat
1444
format = RepositoryFormat.find_format(self)
1445
self._check_supported(format, unsupported)
1446
return format.open(self, _found=True)
1448
def open_workingtree(self, unsupported=False,
1449
recommend_upgrade=True):
1450
"""See BzrDir.open_workingtree."""
1451
from bzrlib.workingtree import WorkingTreeFormat
1452
format = WorkingTreeFormat.find_format(self)
1453
self._check_supported(format, unsupported,
1455
basedir=self.root_transport.base)
1456
return format.open(self, _found=True)
1458
def _get_config(self):
1459
return config.TransportConfig(self.transport, 'control.conf')
1462
class BzrProber(controldir.Prober):
1463
"""Prober for formats that use a .bzr/ control directory."""
1466
"""The known .bzr formats."""
1469
def register_bzrdir_format(klass, format):
1470
klass._formats[format.get_format_string()] = format
1473
def unregister_bzrdir_format(klass, format):
1474
del klass._formats[format.get_format_string()]
1477
def probe_transport(klass, transport):
1478
"""Return the .bzrdir style format present in a directory."""
1480
format_string = transport.get_bytes(".bzr/branch-format")
1481
except errors.NoSuchFile:
1482
raise errors.NotBranchError(path=transport.base)
1484
return klass._formats[format_string]
1486
raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1489
controldir.ControlDirFormat.register_prober(BzrProber)
1492
class RemoteBzrProber(controldir.Prober):
1493
"""Prober for remote servers that provide a Bazaar smart server."""
1496
def probe_transport(klass, transport):
1497
"""Return a RemoteBzrDirFormat object if it looks possible."""
1499
medium = transport.get_smart_medium()
1500
except (NotImplementedError, AttributeError,
1501
errors.TransportNotPossible, errors.NoSmartMedium,
1502
errors.SmartProtocolError):
1503
# no smart server, so not a branch for this format type.
1504
raise errors.NotBranchError(path=transport.base)
1506
# Decline to open it if the server doesn't support our required
1507
# version (3) so that the VFS-based transport will do it.
1508
if medium.should_probe():
1510
server_version = medium.protocol_version()
1511
except errors.SmartProtocolError:
1512
# Apparently there's no usable smart server there, even though
1513
# the medium supports the smart protocol.
1514
raise errors.NotBranchError(path=transport.base)
1515
if server_version != '2':
1516
raise errors.NotBranchError(path=transport.base)
1517
return RemoteBzrDirFormat()
1520
class BzrDirFormat(controldir.ControlDirFormat):
1521
"""ControlDirFormat base class for .bzr/ directories.
1523
Formats are placed in a dict by their format string for reference
1524
during bzrdir opening. These should be subclasses of BzrDirFormat
1527
Once a format is deprecated, just deprecate the initialize and open
1528
methods on the format class. Do not deprecate the object, as the
1529
object will be created every system load.
1532
_lock_file_name = 'branch-lock'
1534
# _lock_class must be set in subclasses to the lock type, typ.
1535
# TransportLock or LockDir
1537
def get_format_string(self):
1538
"""Return the ASCII format string that identifies this format."""
1539
raise NotImplementedError(self.get_format_string)
1541
def initialize_on_transport(self, transport):
1542
"""Initialize a new bzrdir in the base directory of a Transport."""
1544
# can we hand off the request to the smart server rather than using
1546
client_medium = transport.get_smart_medium()
1547
except errors.NoSmartMedium:
1548
return self._initialize_on_transport_vfs(transport)
1550
# Current RPC's only know how to create bzr metadir1 instances, so
1551
# we still delegate to vfs methods if the requested format is not a
1553
if type(self) != BzrDirMetaFormat1:
1554
return self._initialize_on_transport_vfs(transport)
1555
remote_format = RemoteBzrDirFormat()
1556
self._supply_sub_formats_to(remote_format)
1557
return remote_format.initialize_on_transport(transport)
1559
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1560
create_prefix=False, force_new_repo=False, stacked_on=None,
1561
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1562
shared_repo=False, vfs_only=False):
1563
"""Create this format on transport.
1565
The directory to initialize will be created.
1567
:param force_new_repo: Do not use a shared repository for the target,
1568
even if one is available.
1569
:param create_prefix: Create any missing directories leading up to
1571
:param use_existing_dir: Use an existing directory if one exists.
1572
:param stacked_on: A url to stack any created branch on, None to follow
1573
any target stacking policy.
1574
:param stack_on_pwd: If stack_on is relative, the location it is
1576
:param repo_format_name: If non-None, a repository will be
1577
made-or-found. Should none be found, or if force_new_repo is True
1578
the repo_format_name is used to select the format of repository to
1580
:param make_working_trees: Control the setting of make_working_trees
1581
for a new shared repository when one is made. None to use whatever
1582
default the format has.
1583
:param shared_repo: Control whether made repositories are shared or
1585
:param vfs_only: If True do not attempt to use a smart server
1586
:return: repo, bzrdir, require_stacking, repository_policy. repo is
1587
None if none was created or found, bzrdir is always valid.
1588
require_stacking is the result of examining the stacked_on
1589
parameter and any stacking policy found for the target.
1592
# Try to hand off to a smart server
1594
client_medium = transport.get_smart_medium()
1595
except errors.NoSmartMedium:
1598
# TODO: lookup the local format from a server hint.
1599
remote_dir_format = RemoteBzrDirFormat()
1600
remote_dir_format._network_name = self.network_name()
1601
self._supply_sub_formats_to(remote_dir_format)
1602
return remote_dir_format.initialize_on_transport_ex(transport,
1603
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1604
force_new_repo=force_new_repo, stacked_on=stacked_on,
1605
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1606
make_working_trees=make_working_trees, shared_repo=shared_repo)
1607
# XXX: Refactor the create_prefix/no_create_prefix code into a
1608
# common helper function
1609
# The destination may not exist - if so make it according to policy.
1610
def make_directory(transport):
1611
transport.mkdir('.')
1613
def redirected(transport, e, redirection_notice):
1614
note(redirection_notice)
1615
return transport._redirected_to(e.source, e.target)
1617
transport = do_catching_redirections(make_directory, transport,
1619
except errors.FileExists:
1620
if not use_existing_dir:
1622
except errors.NoSuchFile:
1623
if not create_prefix:
1625
transport.create_prefix()
1627
require_stacking = (stacked_on is not None)
1628
# Now the target directory exists, but doesn't have a .bzr
1629
# directory. So we need to create it, along with any work to create
1630
# all of the dependent branches, etc.
1632
result = self.initialize_on_transport(transport)
1633
if repo_format_name:
1635
# use a custom format
1636
result._format.repository_format = \
1637
repository.network_format_registry.get(repo_format_name)
1638
except AttributeError:
1639
# The format didn't permit it to be set.
1641
# A repository is desired, either in-place or shared.
1642
repository_policy = result.determine_repository_policy(
1643
force_new_repo, stacked_on, stack_on_pwd,
1644
require_stacking=require_stacking)
1645
result_repo, is_new_repo = repository_policy.acquire_repository(
1646
make_working_trees, shared_repo)
1647
if not require_stacking and repository_policy._require_stacking:
1648
require_stacking = True
1649
result._format.require_stacking()
1650
result_repo.lock_write()
1653
repository_policy = None
1654
return result_repo, result, require_stacking, repository_policy
1656
def _initialize_on_transport_vfs(self, transport):
1657
"""Initialize a new bzrdir using VFS calls.
1659
:param transport: The transport to create the .bzr directory in.
1662
# Since we are creating a .bzr directory, inherit the
1663
# mode from the root directory
1664
temp_control = lockable_files.LockableFiles(transport,
1665
'', lockable_files.TransportLock)
1666
temp_control._transport.mkdir('.bzr',
1667
# FIXME: RBC 20060121 don't peek under
1669
mode=temp_control._dir_mode)
1670
if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1671
win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1672
file_mode = temp_control._file_mode
1674
bzrdir_transport = transport.clone('.bzr')
1675
utf8_files = [('README',
1676
"This is a Bazaar control directory.\n"
1677
"Do not change any files in this directory.\n"
1678
"See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1679
('branch-format', self.get_format_string()),
1681
# NB: no need to escape relative paths that are url safe.
1682
control_files = lockable_files.LockableFiles(bzrdir_transport,
1683
self._lock_file_name, self._lock_class)
1684
control_files.create_lock()
1685
control_files.lock_write()
1687
for (filename, content) in utf8_files:
1688
bzrdir_transport.put_bytes(filename, content,
1691
control_files.unlock()
1692
return self.open(transport, _found=True)
1694
def open(self, transport, _found=False):
1695
"""Return an instance of this format for the dir transport points at.
1697
_found is a private parameter, do not use it.
1700
found_format = controldir.ControlDirFormat.find_format(transport)
1701
if not isinstance(found_format, self.__class__):
1702
raise AssertionError("%s was asked to open %s, but it seems to need "
1704
% (self, transport, found_format))
1705
# Allow subclasses - use the found format.
1706
self._supply_sub_formats_to(found_format)
1707
return found_format._open(transport)
1708
return self._open(transport)
1710
def _open(self, transport):
1711
"""Template method helper for opening BzrDirectories.
1713
This performs the actual open and any additional logic or parameter
1716
raise NotImplementedError(self._open)
1719
def register_format(klass, format):
1720
BzrProber.register_bzrdir_format(format)
1721
# bzr native formats have a network name of their format string.
1722
network_format_registry.register(format.get_format_string(), format.__class__)
1723
controldir.ControlDirFormat.register_format(format)
1725
def _supply_sub_formats_to(self, other_format):
1726
"""Give other_format the same values for sub formats as this has.
1728
This method is expected to be used when parameterising a
1729
RemoteBzrDirFormat instance with the parameters from a
1730
BzrDirMetaFormat1 instance.
1732
:param other_format: other_format is a format which should be
1733
compatible with whatever sub formats are supported by self.
1738
def unregister_format(klass, format):
1739
BzrProber.unregister_bzrdir_format(format)
1740
controldir.ControlDirFormat.unregister_format(format)
1741
network_format_registry.remove(format.get_format_string())
1744
class BzrDirFormat4(BzrDirFormat):
1745
"""Bzr dir format 4.
1747
This format is a combined format for working tree, branch and repository.
1749
- Format 1 working trees [always]
1750
- Format 4 branches [always]
1751
- Format 4 repositories [always]
1753
This format is deprecated: it indexes texts using a text it which is
1754
removed in format 5; write support for this format has been removed.
1757
_lock_class = lockable_files.TransportLock
1759
def get_format_string(self):
1760
"""See BzrDirFormat.get_format_string()."""
1761
return "Bazaar-NG branch, format 0.0.4\n"
1763
def get_format_description(self):
1764
"""See BzrDirFormat.get_format_description()."""
1765
return "All-in-one format 4"
1767
def get_converter(self, format=None):
1768
"""See BzrDirFormat.get_converter()."""
1769
# there is one and only one upgrade path here.
1770
return ConvertBzrDir4To5()
1772
def initialize_on_transport(self, transport):
1773
"""Format 4 branches cannot be created."""
1774
raise errors.UninitializableFormat(self)
1776
def is_supported(self):
1777
"""Format 4 is not supported.
1779
It is not supported because the model changed from 4 to 5 and the
1780
conversion logic is expensive - so doing it on the fly was not
1785
def network_name(self):
1786
return self.get_format_string()
1788
def _open(self, transport):
1789
"""See BzrDirFormat._open."""
1790
return BzrDir4(transport, self)
1792
def __return_repository_format(self):
1793
"""Circular import protection."""
1794
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1795
return RepositoryFormat4()
1796
repository_format = property(__return_repository_format)
1799
class BzrDirFormatAllInOne(BzrDirFormat):
1800
"""Common class for formats before meta-dirs."""
1802
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1803
create_prefix=False, force_new_repo=False, stacked_on=None,
1804
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1806
"""See BzrDirFormat.initialize_on_transport_ex."""
1807
require_stacking = (stacked_on is not None)
1808
# Format 5 cannot stack, but we've been asked to - actually init
1810
if require_stacking:
1811
format = BzrDirMetaFormat1()
1812
return format.initialize_on_transport_ex(transport,
1813
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1814
force_new_repo=force_new_repo, stacked_on=stacked_on,
1815
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1816
make_working_trees=make_working_trees, shared_repo=shared_repo)
1817
return BzrDirFormat.initialize_on_transport_ex(self, transport,
1818
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1819
force_new_repo=force_new_repo, stacked_on=stacked_on,
1820
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1821
make_working_trees=make_working_trees, shared_repo=shared_repo)
1824
class BzrDirFormat5(BzrDirFormatAllInOne):
1825
"""Bzr control format 5.
1827
This format is a combined format for working tree, branch and repository.
1829
- Format 2 working trees [always]
1830
- Format 4 branches [always]
1831
- Format 5 repositories [always]
1832
Unhashed stores in the repository.
1835
_lock_class = lockable_files.TransportLock
1837
def get_format_string(self):
1838
"""See BzrDirFormat.get_format_string()."""
1839
return "Bazaar-NG branch, format 5\n"
1841
def get_branch_format(self):
1842
from bzrlib import branch
1843
return branch.BzrBranchFormat4()
1845
def get_format_description(self):
1846
"""See BzrDirFormat.get_format_description()."""
1847
return "All-in-one format 5"
1849
def get_converter(self, format=None):
1850
"""See BzrDirFormat.get_converter()."""
1851
# there is one and only one upgrade path here.
1852
return ConvertBzrDir5To6()
1854
def _initialize_for_clone(self, url):
1855
return self.initialize_on_transport(get_transport(url), _cloning=True)
1857
def initialize_on_transport(self, transport, _cloning=False):
1858
"""Format 5 dirs always have working tree, branch and repository.
1860
Except when they are being cloned.
1862
from bzrlib.branch import BzrBranchFormat4
1863
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1864
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1865
RepositoryFormat5().initialize(result, _internal=True)
1867
branch = BzrBranchFormat4().initialize(result)
1868
result._init_workingtree()
1871
def network_name(self):
1872
return self.get_format_string()
1874
def _open(self, transport):
1875
"""See BzrDirFormat._open."""
1876
return BzrDir5(transport, self)
1878
def __return_repository_format(self):
1879
"""Circular import protection."""
1880
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1881
return RepositoryFormat5()
1882
repository_format = property(__return_repository_format)
1885
class BzrDirFormat6(BzrDirFormatAllInOne):
1886
"""Bzr control format 6.
1888
This format is a combined format for working tree, branch and repository.
1890
- Format 2 working trees [always]
1891
- Format 4 branches [always]
1892
- Format 6 repositories [always]
1895
_lock_class = lockable_files.TransportLock
1897
def get_format_string(self):
1898
"""See BzrDirFormat.get_format_string()."""
1899
return "Bazaar-NG branch, format 6\n"
1901
def get_format_description(self):
1902
"""See BzrDirFormat.get_format_description()."""
1903
return "All-in-one format 6"
1905
def get_branch_format(self):
1906
from bzrlib import branch
1907
return branch.BzrBranchFormat4()
1909
def get_converter(self, format=None):
1910
"""See BzrDirFormat.get_converter()."""
1911
# there is one and only one upgrade path here.
1912
return ConvertBzrDir6ToMeta()
1914
def _initialize_for_clone(self, url):
1915
return self.initialize_on_transport(get_transport(url), _cloning=True)
1917
def initialize_on_transport(self, transport, _cloning=False):
1918
"""Format 6 dirs always have working tree, branch and repository.
1920
Except when they are being cloned.
1922
from bzrlib.branch import BzrBranchFormat4
1923
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1924
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1925
RepositoryFormat6().initialize(result, _internal=True)
1927
branch = BzrBranchFormat4().initialize(result)
1928
result._init_workingtree()
1931
def network_name(self):
1932
return self.get_format_string()
1934
def _open(self, transport):
1935
"""See BzrDirFormat._open."""
1936
return BzrDir6(transport, self)
1938
def __return_repository_format(self):
1939
"""Circular import protection."""
1940
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1941
return RepositoryFormat6()
1942
repository_format = property(__return_repository_format)
1945
class BzrDirMetaFormat1(BzrDirFormat):
1946
"""Bzr meta control format 1
1948
This is the first format with split out working tree, branch and repository
1951
- Format 3 working trees [optional]
1952
- Format 5 branches [optional]
1953
- Format 7 repositories [optional]
1956
_lock_class = lockdir.LockDir
1959
self._workingtree_format = None
1960
self._branch_format = None
1961
self._repository_format = None
1963
def __eq__(self, other):
1964
if other.__class__ is not self.__class__:
1966
if other.repository_format != self.repository_format:
1968
if other.workingtree_format != self.workingtree_format:
1972
def __ne__(self, other):
1973
return not self == other
1975
def get_branch_format(self):
1976
if self._branch_format is None:
1977
from bzrlib.branch import BranchFormat
1978
self._branch_format = BranchFormat.get_default_format()
1979
return self._branch_format
1981
def set_branch_format(self, format):
1982
self._branch_format = format
1984
def require_stacking(self, stack_on=None, possible_transports=None,
1986
"""We have a request to stack, try to ensure the formats support it.
1988
:param stack_on: If supplied, it is the URL to a branch that we want to
1989
stack on. Check to see if that format supports stacking before
1992
# Stacking is desired. requested by the target, but does the place it
1993
# points at support stacking? If it doesn't then we should
1994
# not implicitly upgrade. We check this here.
1995
new_repo_format = None
1996
new_branch_format = None
1998
# a bit of state for get_target_branch so that we don't try to open it
1999
# 2 times, for both repo *and* branch
2000
target = [None, False, None] # target_branch, checked, upgrade anyway
2001
def get_target_branch():
2003
# We've checked, don't check again
2005
if stack_on is None:
2006
# No target format, that means we want to force upgrading
2007
target[:] = [None, True, True]
2010
target_dir = BzrDir.open(stack_on,
2011
possible_transports=possible_transports)
2012
except errors.NotBranchError:
2013
# Nothing there, don't change formats
2014
target[:] = [None, True, False]
2016
except errors.JailBreak:
2017
# JailBreak, JFDI and upgrade anyway
2018
target[:] = [None, True, True]
2021
target_branch = target_dir.open_branch()
2022
except errors.NotBranchError:
2023
# No branch, don't upgrade formats
2024
target[:] = [None, True, False]
2026
target[:] = [target_branch, True, False]
2029
if (not _skip_repo and
2030
not self.repository_format.supports_external_lookups):
2031
# We need to upgrade the Repository.
2032
target_branch, _, do_upgrade = get_target_branch()
2033
if target_branch is None:
2034
# We don't have a target branch, should we upgrade anyway?
2036
# stack_on is inaccessible, JFDI.
2037
# TODO: bad monkey, hard-coded formats...
2038
if self.repository_format.rich_root_data:
2039
new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
2041
new_repo_format = pack_repo.RepositoryFormatKnitPack5()
2043
# If the target already supports stacking, then we know the
2044
# project is already able to use stacking, so auto-upgrade
2046
new_repo_format = target_branch.repository._format
2047
if not new_repo_format.supports_external_lookups:
2048
# target doesn't, source doesn't, so don't auto upgrade
2050
new_repo_format = None
2051
if new_repo_format is not None:
2052
self.repository_format = new_repo_format
2053
note('Source repository format does not support stacking,'
2054
' using format:\n %s',
2055
new_repo_format.get_format_description())
2057
if not self.get_branch_format().supports_stacking():
2058
# We just checked the repo, now lets check if we need to
2059
# upgrade the branch format
2060
target_branch, _, do_upgrade = get_target_branch()
2061
if target_branch is None:
2063
# TODO: bad monkey, hard-coded formats...
2064
new_branch_format = branch.BzrBranchFormat7()
2066
new_branch_format = target_branch._format
2067
if not new_branch_format.supports_stacking():
2068
new_branch_format = None
2069
if new_branch_format is not None:
2070
# Does support stacking, use its format.
2071
self.set_branch_format(new_branch_format)
2072
note('Source branch format does not support stacking,'
2073
' using format:\n %s',
2074
new_branch_format.get_format_description())
2076
def get_converter(self, format=None):
2077
"""See BzrDirFormat.get_converter()."""
2079
format = BzrDirFormat.get_default_format()
2080
if not isinstance(self, format.__class__):
2081
# converting away from metadir is not implemented
2082
raise NotImplementedError(self.get_converter)
2083
return ConvertMetaToMeta(format)
2085
def get_format_string(self):
2086
"""See BzrDirFormat.get_format_string()."""
2087
return "Bazaar-NG meta directory, format 1\n"
2089
def get_format_description(self):
2090
"""See BzrDirFormat.get_format_description()."""
2091
return "Meta directory format 1"
2093
def network_name(self):
2094
return self.get_format_string()
2096
def _open(self, transport):
2097
"""See BzrDirFormat._open."""
2098
# Create a new format instance because otherwise initialisation of new
2099
# metadirs share the global default format object leading to alias
2101
format = BzrDirMetaFormat1()
2102
self._supply_sub_formats_to(format)
2103
return BzrDirMeta1(transport, format)
2105
def __return_repository_format(self):
2106
"""Circular import protection."""
2107
if self._repository_format:
2108
return self._repository_format
2109
from bzrlib.repository import RepositoryFormat
2110
return RepositoryFormat.get_default_format()
2112
def _set_repository_format(self, value):
2113
"""Allow changing the repository format for metadir formats."""
2114
self._repository_format = value
2116
repository_format = property(__return_repository_format,
2117
_set_repository_format)
2119
def _supply_sub_formats_to(self, other_format):
2120
"""Give other_format the same values for sub formats as this has.
2122
This method is expected to be used when parameterising a
2123
RemoteBzrDirFormat instance with the parameters from a
2124
BzrDirMetaFormat1 instance.
2126
:param other_format: other_format is a format which should be
2127
compatible with whatever sub formats are supported by self.
2130
if getattr(self, '_repository_format', None) is not None:
2131
other_format.repository_format = self.repository_format
2132
if self._branch_format is not None:
2133
other_format._branch_format = self._branch_format
2134
if self._workingtree_format is not None:
2135
other_format.workingtree_format = self.workingtree_format
2137
def __get_workingtree_format(self):
2138
if self._workingtree_format is None:
2139
from bzrlib.workingtree import WorkingTreeFormat
2140
self._workingtree_format = WorkingTreeFormat.get_default_format()
2141
return self._workingtree_format
2143
def __set_workingtree_format(self, wt_format):
2144
self._workingtree_format = wt_format
2146
workingtree_format = property(__get_workingtree_format,
2147
__set_workingtree_format)
2150
network_format_registry = registry.FormatRegistry()
2151
"""Registry of formats indexed by their network name.
2153
The network name for a BzrDirFormat is an identifier that can be used when
2154
referring to formats with smart server operations. See
2155
BzrDirFormat.network_name() for more detail.
2159
# Register bzr formats
2160
BzrDirFormat.register_format(BzrDirFormat4())
2161
BzrDirFormat.register_format(BzrDirFormat5())
2162
BzrDirFormat.register_format(BzrDirFormat6())
2163
__default_format = BzrDirMetaFormat1()
2164
BzrDirFormat.register_format(__default_format)
2165
controldir.ControlDirFormat._default_format = __default_format
2168
class Converter(object):
2169
"""Converts a disk format object from one format to another."""
2171
def convert(self, to_convert, pb):
2172
"""Perform the conversion of to_convert, giving feedback via pb.
2174
:param to_convert: The disk object to convert.
2175
:param pb: a progress bar to use for progress information.
2178
def step(self, message):
2179
"""Update the pb by a step."""
2181
self.pb.update(message, self.count, self.total)
2184
class ConvertBzrDir4To5(Converter):
2185
"""Converts format 4 bzr dirs to format 5."""
2188
super(ConvertBzrDir4To5, self).__init__()
2189
self.converted_revs = set()
2190
self.absent_revisions = set()
2194
def convert(self, to_convert, pb):
2195
"""See Converter.convert()."""
2196
self.bzrdir = to_convert
2198
warnings.warn("pb parameter to convert() is deprecated")
2199
self.pb = ui.ui_factory.nested_progress_bar()
2201
ui.ui_factory.note('starting upgrade from format 4 to 5')
2202
if isinstance(self.bzrdir.transport, local.LocalTransport):
2203
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2204
self._convert_to_weaves()
2205
return BzrDir.open(self.bzrdir.user_url)
2209
def _convert_to_weaves(self):
2210
ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
2213
stat = self.bzrdir.transport.stat('weaves')
2214
if not S_ISDIR(stat.st_mode):
2215
self.bzrdir.transport.delete('weaves')
2216
self.bzrdir.transport.mkdir('weaves')
2217
except errors.NoSuchFile:
2218
self.bzrdir.transport.mkdir('weaves')
2219
# deliberately not a WeaveFile as we want to build it up slowly.
2220
self.inv_weave = Weave('inventory')
2221
# holds in-memory weaves for all files
2222
self.text_weaves = {}
2223
self.bzrdir.transport.delete('branch-format')
2224
self.branch = self.bzrdir.open_branch()
2225
self._convert_working_inv()
2226
rev_history = self.branch.revision_history()
2227
# to_read is a stack holding the revisions we still need to process;
2228
# appending to it adds new highest-priority revisions
2229
self.known_revisions = set(rev_history)
2230
self.to_read = rev_history[-1:]
2232
rev_id = self.to_read.pop()
2233
if (rev_id not in self.revisions
2234
and rev_id not in self.absent_revisions):
2235
self._load_one_rev(rev_id)
2237
to_import = self._make_order()
2238
for i, rev_id in enumerate(to_import):
2239
self.pb.update('converting revision', i, len(to_import))
2240
self._convert_one_rev(rev_id)
2242
self._write_all_weaves()
2243
self._write_all_revs()
2244
ui.ui_factory.note('upgraded to weaves:')
2245
ui.ui_factory.note(' %6d revisions and inventories' % len(self.revisions))
2246
ui.ui_factory.note(' %6d revisions not present' % len(self.absent_revisions))
2247
ui.ui_factory.note(' %6d texts' % self.text_count)
2248
self._cleanup_spare_files_after_format4()
2249
self.branch._transport.put_bytes(
2251
BzrDirFormat5().get_format_string(),
2252
mode=self.bzrdir._get_file_mode())
2254
def _cleanup_spare_files_after_format4(self):
2255
# FIXME working tree upgrade foo.
2256
for n in 'merged-patches', 'pending-merged-patches':
2258
## assert os.path.getsize(p) == 0
2259
self.bzrdir.transport.delete(n)
2260
except errors.NoSuchFile:
2262
self.bzrdir.transport.delete_tree('inventory-store')
2263
self.bzrdir.transport.delete_tree('text-store')
2265
def _convert_working_inv(self):
2266
inv = xml4.serializer_v4.read_inventory(
2267
self.branch._transport.get('inventory'))
2268
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2269
self.branch._transport.put_bytes('inventory', new_inv_xml,
2270
mode=self.bzrdir._get_file_mode())
2272
def _write_all_weaves(self):
2273
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2274
weave_transport = self.bzrdir.transport.clone('weaves')
2275
weaves = WeaveStore(weave_transport, prefixed=False)
2276
transaction = WriteTransaction()
2280
for file_id, file_weave in self.text_weaves.items():
2281
self.pb.update('writing weave', i, len(self.text_weaves))
2282
weaves._put_weave(file_id, file_weave, transaction)
2284
self.pb.update('inventory', 0, 1)
2285
controlweaves._put_weave('inventory', self.inv_weave, transaction)
2286
self.pb.update('inventory', 1, 1)
2290
def _write_all_revs(self):
2291
"""Write all revisions out in new form."""
2292
self.bzrdir.transport.delete_tree('revision-store')
2293
self.bzrdir.transport.mkdir('revision-store')
2294
revision_transport = self.bzrdir.transport.clone('revision-store')
2296
from bzrlib.xml5 import serializer_v5
2297
from bzrlib.repofmt.weaverepo import RevisionTextStore
2298
revision_store = RevisionTextStore(revision_transport,
2299
serializer_v5, False, versionedfile.PrefixMapper(),
2300
lambda:True, lambda:True)
2302
for i, rev_id in enumerate(self.converted_revs):
2303
self.pb.update('write revision', i, len(self.converted_revs))
2304
text = serializer_v5.write_revision_to_string(
2305
self.revisions[rev_id])
2307
revision_store.add_lines(key, None, osutils.split_lines(text))
2311
def _load_one_rev(self, rev_id):
2312
"""Load a revision object into memory.
2314
Any parents not either loaded or abandoned get queued to be
2316
self.pb.update('loading revision',
2317
len(self.revisions),
2318
len(self.known_revisions))
2319
if not self.branch.repository.has_revision(rev_id):
2321
ui.ui_factory.note('revision {%s} not present in branch; '
2322
'will be converted as a ghost' %
2324
self.absent_revisions.add(rev_id)
2326
rev = self.branch.repository.get_revision(rev_id)
2327
for parent_id in rev.parent_ids:
2328
self.known_revisions.add(parent_id)
2329
self.to_read.append(parent_id)
2330
self.revisions[rev_id] = rev
2332
def _load_old_inventory(self, rev_id):
2333
f = self.branch.repository.inventory_store.get(rev_id)
2335
old_inv_xml = f.read()
2338
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2339
inv.revision_id = rev_id
2340
rev = self.revisions[rev_id]
2343
def _load_updated_inventory(self, rev_id):
2344
inv_xml = self.inv_weave.get_text(rev_id)
2345
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2348
def _convert_one_rev(self, rev_id):
2349
"""Convert revision and all referenced objects to new format."""
2350
rev = self.revisions[rev_id]
2351
inv = self._load_old_inventory(rev_id)
2352
present_parents = [p for p in rev.parent_ids
2353
if p not in self.absent_revisions]
2354
self._convert_revision_contents(rev, inv, present_parents)
2355
self._store_new_inv(rev, inv, present_parents)
2356
self.converted_revs.add(rev_id)
2358
def _store_new_inv(self, rev, inv, present_parents):
2359
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2360
new_inv_sha1 = sha_string(new_inv_xml)
2361
self.inv_weave.add_lines(rev.revision_id,
2363
new_inv_xml.splitlines(True))
2364
rev.inventory_sha1 = new_inv_sha1
2366
def _convert_revision_contents(self, rev, inv, present_parents):
2367
"""Convert all the files within a revision.
2369
Also upgrade the inventory to refer to the text revision ids."""
2370
rev_id = rev.revision_id
2371
mutter('converting texts of revision {%s}',
2373
parent_invs = map(self._load_updated_inventory, present_parents)
2374
entries = inv.iter_entries()
2376
for path, ie in entries:
2377
self._convert_file_version(rev, ie, parent_invs)
2379
def _convert_file_version(self, rev, ie, parent_invs):
2380
"""Convert one version of one file.
2382
The file needs to be added into the weave if it is a merge
2383
of >=2 parents or if it's changed from its parent.
2385
file_id = ie.file_id
2386
rev_id = rev.revision_id
2387
w = self.text_weaves.get(file_id)
2390
self.text_weaves[file_id] = w
2391
text_changed = False
2392
parent_candiate_entries = ie.parent_candidates(parent_invs)
2393
heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2394
# XXX: Note that this is unordered - and this is tolerable because
2395
# the previous code was also unordered.
2396
previous_entries = dict((head, parent_candiate_entries[head]) for head
2398
self.snapshot_ie(previous_entries, ie, w, rev_id)
2400
def get_parent_map(self, revision_ids):
2401
"""See graph.StackedParentsProvider.get_parent_map"""
2402
return dict((revision_id, self.revisions[revision_id])
2403
for revision_id in revision_ids
2404
if revision_id in self.revisions)
2406
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2407
# TODO: convert this logic, which is ~= snapshot to
2408
# a call to:. This needs the path figured out. rather than a work_tree
2409
# a v4 revision_tree can be given, or something that looks enough like
2410
# one to give the file content to the entry if it needs it.
2411
# and we need something that looks like a weave store for snapshot to
2413
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2414
if len(previous_revisions) == 1:
2415
previous_ie = previous_revisions.values()[0]
2416
if ie._unchanged(previous_ie):
2417
ie.revision = previous_ie.revision
2420
f = self.branch.repository._text_store.get(ie.text_id)
2422
file_lines = f.readlines()
2425
w.add_lines(rev_id, previous_revisions, file_lines)
2426
self.text_count += 1
2428
w.add_lines(rev_id, previous_revisions, [])
2429
ie.revision = rev_id
2431
def _make_order(self):
2432
"""Return a suitable order for importing revisions.
2434
The order must be such that an revision is imported after all
2435
its (present) parents.
2437
todo = set(self.revisions.keys())
2438
done = self.absent_revisions.copy()
2441
# scan through looking for a revision whose parents
2443
for rev_id in sorted(list(todo)):
2444
rev = self.revisions[rev_id]
2445
parent_ids = set(rev.parent_ids)
2446
if parent_ids.issubset(done):
2447
# can take this one now
2448
order.append(rev_id)
2454
class ConvertBzrDir5To6(Converter):
2455
"""Converts format 5 bzr dirs to format 6."""
2457
def convert(self, to_convert, pb):
2458
"""See Converter.convert()."""
2459
self.bzrdir = to_convert
2460
pb = ui.ui_factory.nested_progress_bar()
2462
ui.ui_factory.note('starting upgrade from format 5 to 6')
2463
self._convert_to_prefixed()
2464
return BzrDir.open(self.bzrdir.user_url)
2468
def _convert_to_prefixed(self):
2469
from bzrlib.store import TransportStore
2470
self.bzrdir.transport.delete('branch-format')
2471
for store_name in ["weaves", "revision-store"]:
2472
ui.ui_factory.note("adding prefixes to %s" % store_name)
2473
store_transport = self.bzrdir.transport.clone(store_name)
2474
store = TransportStore(store_transport, prefixed=True)
2475
for urlfilename in store_transport.list_dir('.'):
2476
filename = urlutils.unescape(urlfilename)
2477
if (filename.endswith(".weave") or
2478
filename.endswith(".gz") or
2479
filename.endswith(".sig")):
2480
file_id, suffix = os.path.splitext(filename)
2484
new_name = store._mapper.map((file_id,)) + suffix
2485
# FIXME keep track of the dirs made RBC 20060121
2487
store_transport.move(filename, new_name)
2488
except errors.NoSuchFile: # catches missing dirs strangely enough
2489
store_transport.mkdir(osutils.dirname(new_name))
2490
store_transport.move(filename, new_name)
2491
self.bzrdir.transport.put_bytes(
2493
BzrDirFormat6().get_format_string(),
2494
mode=self.bzrdir._get_file_mode())
2497
class ConvertBzrDir6ToMeta(Converter):
2498
"""Converts format 6 bzr dirs to metadirs."""
2500
def convert(self, to_convert, pb):
2501
"""See Converter.convert()."""
2502
from bzrlib.repofmt.weaverepo import RepositoryFormat7
2503
from bzrlib.branch import BzrBranchFormat5
2504
self.bzrdir = to_convert
2505
self.pb = ui.ui_factory.nested_progress_bar()
2507
self.total = 20 # the steps we know about
2508
self.garbage_inventories = []
2509
self.dir_mode = self.bzrdir._get_dir_mode()
2510
self.file_mode = self.bzrdir._get_file_mode()
2512
ui.ui_factory.note('starting upgrade from format 6 to metadir')
2513
self.bzrdir.transport.put_bytes(
2515
"Converting to format 6",
2516
mode=self.file_mode)
2517
# its faster to move specific files around than to open and use the apis...
2518
# first off, nuke ancestry.weave, it was never used.
2520
self.step('Removing ancestry.weave')
2521
self.bzrdir.transport.delete('ancestry.weave')
2522
except errors.NoSuchFile:
2524
# find out whats there
2525
self.step('Finding branch files')
2526
last_revision = self.bzrdir.open_branch().last_revision()
2527
bzrcontents = self.bzrdir.transport.list_dir('.')
2528
for name in bzrcontents:
2529
if name.startswith('basis-inventory.'):
2530
self.garbage_inventories.append(name)
2531
# create new directories for repository, working tree and branch
2532
repository_names = [('inventory.weave', True),
2533
('revision-store', True),
2535
self.step('Upgrading repository ')
2536
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2537
self.make_lock('repository')
2538
# we hard code the formats here because we are converting into
2539
# the meta format. The meta format upgrader can take this to a
2540
# future format within each component.
2541
self.put_format('repository', RepositoryFormat7())
2542
for entry in repository_names:
2543
self.move_entry('repository', entry)
2545
self.step('Upgrading branch ')
2546
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2547
self.make_lock('branch')
2548
self.put_format('branch', BzrBranchFormat5())
2549
branch_files = [('revision-history', True),
2550
('branch-name', True),
2552
for entry in branch_files:
2553
self.move_entry('branch', entry)
2555
checkout_files = [('pending-merges', True),
2556
('inventory', True),
2557
('stat-cache', False)]
2558
# If a mandatory checkout file is not present, the branch does not have
2559
# a functional checkout. Do not create a checkout in the converted
2561
for name, mandatory in checkout_files:
2562
if mandatory and name not in bzrcontents:
2563
has_checkout = False
2567
if not has_checkout:
2568
ui.ui_factory.note('No working tree.')
2569
# If some checkout files are there, we may as well get rid of them.
2570
for name, mandatory in checkout_files:
2571
if name in bzrcontents:
2572
self.bzrdir.transport.delete(name)
2574
from bzrlib.workingtree import WorkingTreeFormat3
2575
self.step('Upgrading working tree')
2576
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2577
self.make_lock('checkout')
2579
'checkout', WorkingTreeFormat3())
2580
self.bzrdir.transport.delete_multi(
2581
self.garbage_inventories, self.pb)
2582
for entry in checkout_files:
2583
self.move_entry('checkout', entry)
2584
if last_revision is not None:
2585
self.bzrdir.transport.put_bytes(
2586
'checkout/last-revision', last_revision)
2587
self.bzrdir.transport.put_bytes(
2589
BzrDirMetaFormat1().get_format_string(),
2590
mode=self.file_mode)
2592
return BzrDir.open(self.bzrdir.user_url)
2594
def make_lock(self, name):
2595
"""Make a lock for the new control dir name."""
2596
self.step('Make %s lock' % name)
2597
ld = lockdir.LockDir(self.bzrdir.transport,
2599
file_modebits=self.file_mode,
2600
dir_modebits=self.dir_mode)
2603
def move_entry(self, new_dir, entry):
2604
"""Move then entry name into new_dir."""
2606
mandatory = entry[1]
2607
self.step('Moving %s' % name)
2609
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2610
except errors.NoSuchFile:
2614
def put_format(self, dirname, format):
2615
self.bzrdir.transport.put_bytes('%s/format' % dirname,
2616
format.get_format_string(),
2620
class ConvertMetaToMeta(Converter):
2621
"""Converts the components of metadirs."""
2623
def __init__(self, target_format):
2624
"""Create a metadir to metadir converter.
2626
:param target_format: The final metadir format that is desired.
2628
self.target_format = target_format
2630
def convert(self, to_convert, pb):
2631
"""See Converter.convert()."""
2632
self.bzrdir = to_convert
2633
self.pb = ui.ui_factory.nested_progress_bar()
2636
self.step('checking repository format')
2638
repo = self.bzrdir.open_repository()
2639
except errors.NoRepositoryPresent:
2642
if not isinstance(repo._format, self.target_format.repository_format.__class__):
2643
from bzrlib.repository import CopyConverter
2644
ui.ui_factory.note('starting repository conversion')
2645
converter = CopyConverter(self.target_format.repository_format)
2646
converter.convert(repo, pb)
2647
for branch in self.bzrdir.list_branches():
2648
# TODO: conversions of Branch and Tree should be done by
2649
# InterXFormat lookups/some sort of registry.
2650
# Avoid circular imports
2651
from bzrlib import branch as _mod_branch
2652
old = branch._format.__class__
2653
new = self.target_format.get_branch_format().__class__
2655
if (old == _mod_branch.BzrBranchFormat5 and
2656
new in (_mod_branch.BzrBranchFormat6,
2657
_mod_branch.BzrBranchFormat7,
2658
_mod_branch.BzrBranchFormat8)):
2659
branch_converter = _mod_branch.Converter5to6()
2660
elif (old == _mod_branch.BzrBranchFormat6 and
2661
new in (_mod_branch.BzrBranchFormat7,
2662
_mod_branch.BzrBranchFormat8)):
2663
branch_converter = _mod_branch.Converter6to7()
2664
elif (old == _mod_branch.BzrBranchFormat7 and
2665
new is _mod_branch.BzrBranchFormat8):
2666
branch_converter = _mod_branch.Converter7to8()
2668
raise errors.BadConversionTarget("No converter", new,
2670
branch_converter.convert(branch)
2671
branch = self.bzrdir.open_branch()
2672
old = branch._format.__class__
2674
tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2675
except (errors.NoWorkingTree, errors.NotLocalUrl):
2678
# TODO: conversions of Branch and Tree should be done by
2679
# InterXFormat lookups
2680
if (isinstance(tree, workingtree.WorkingTree3) and
2681
not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2682
isinstance(self.target_format.workingtree_format,
2683
workingtree_4.DirStateWorkingTreeFormat)):
2684
workingtree_4.Converter3to4().convert(tree)
2685
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2686
not isinstance(tree, workingtree_4.WorkingTree5) and
2687
isinstance(self.target_format.workingtree_format,
2688
workingtree_4.WorkingTreeFormat5)):
2689
workingtree_4.Converter4to5().convert(tree)
2690
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2691
not isinstance(tree, workingtree_4.WorkingTree6) and
2692
isinstance(self.target_format.workingtree_format,
2693
workingtree_4.WorkingTreeFormat6)):
2694
workingtree_4.Converter4or5to6().convert(tree)
2699
# This is not in remote.py because it's relatively small, and needs to be
2700
# registered. Putting it in remote.py creates a circular import problem.
2701
# we can make it a lazy object if the control formats is turned into something
2703
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2704
"""Format representing bzrdirs accessed via a smart server"""
2706
supports_workingtrees = False
2709
BzrDirMetaFormat1.__init__(self)
2710
# XXX: It's a bit ugly that the network name is here, because we'd
2711
# like to believe that format objects are stateless or at least
2712
# immutable, However, we do at least avoid mutating the name after
2713
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
2714
self._network_name = None
2717
return "%s(_network_name=%r)" % (self.__class__.__name__,
2720
def get_format_description(self):
2721
if self._network_name:
2722
real_format = network_format_registry.get(self._network_name)
2723
return 'Remote: ' + real_format.get_format_description()
2724
return 'bzr remote bzrdir'
2726
def get_format_string(self):
2727
raise NotImplementedError(self.get_format_string)
2729
def network_name(self):
2730
if self._network_name:
2731
return self._network_name
2733
raise AssertionError("No network name set.")
2735
def initialize_on_transport(self, transport):
2737
# hand off the request to the smart server
2738
client_medium = transport.get_smart_medium()
2739
except errors.NoSmartMedium:
2740
# TODO: lookup the local format from a server hint.
2741
local_dir_format = BzrDirMetaFormat1()
2742
return local_dir_format.initialize_on_transport(transport)
2743
client = _SmartClient(client_medium)
2744
path = client.remote_path_from_transport(transport)
2746
response = client.call('BzrDirFormat.initialize', path)
2747
except errors.ErrorFromSmartServer, err:
2748
remote._translate_error(err, path=path)
2749
if response[0] != 'ok':
2750
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2751
format = RemoteBzrDirFormat()
2752
self._supply_sub_formats_to(format)
2753
return remote.RemoteBzrDir(transport, format)
2755
def parse_NoneTrueFalse(self, arg):
2762
raise AssertionError("invalid arg %r" % arg)
2764
def _serialize_NoneTrueFalse(self, arg):
2771
def _serialize_NoneString(self, arg):
2774
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
2775
create_prefix=False, force_new_repo=False, stacked_on=None,
2776
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
2779
# hand off the request to the smart server
2780
client_medium = transport.get_smart_medium()
2781
except errors.NoSmartMedium:
2784
# Decline to open it if the server doesn't support our required
2785
# version (3) so that the VFS-based transport will do it.
2786
if client_medium.should_probe():
2788
server_version = client_medium.protocol_version()
2789
if server_version != '2':
2793
except errors.SmartProtocolError:
2794
# Apparently there's no usable smart server there, even though
2795
# the medium supports the smart protocol.
2800
client = _SmartClient(client_medium)
2801
path = client.remote_path_from_transport(transport)
2802
if client_medium._is_remote_before((1, 16)):
2805
# TODO: lookup the local format from a server hint.
2806
local_dir_format = BzrDirMetaFormat1()
2807
self._supply_sub_formats_to(local_dir_format)
2808
return local_dir_format.initialize_on_transport_ex(transport,
2809
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2810
force_new_repo=force_new_repo, stacked_on=stacked_on,
2811
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2812
make_working_trees=make_working_trees, shared_repo=shared_repo,
2814
return self._initialize_on_transport_ex_rpc(client, path, transport,
2815
use_existing_dir, create_prefix, force_new_repo, stacked_on,
2816
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
2818
def _initialize_on_transport_ex_rpc(self, client, path, transport,
2819
use_existing_dir, create_prefix, force_new_repo, stacked_on,
2820
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
2822
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
2823
args.append(self._serialize_NoneTrueFalse(create_prefix))
2824
args.append(self._serialize_NoneTrueFalse(force_new_repo))
2825
args.append(self._serialize_NoneString(stacked_on))
2826
# stack_on_pwd is often/usually our transport
2829
stack_on_pwd = transport.relpath(stack_on_pwd)
2830
if not stack_on_pwd:
2832
except errors.PathNotChild:
2834
args.append(self._serialize_NoneString(stack_on_pwd))
2835
args.append(self._serialize_NoneString(repo_format_name))
2836
args.append(self._serialize_NoneTrueFalse(make_working_trees))
2837
args.append(self._serialize_NoneTrueFalse(shared_repo))
2838
request_network_name = self._network_name or \
2839
BzrDirFormat.get_default_format().network_name()
2841
response = client.call('BzrDirFormat.initialize_ex_1.16',
2842
request_network_name, path, *args)
2843
except errors.UnknownSmartMethod:
2844
client._medium._remember_remote_is_before((1,16))
2845
local_dir_format = BzrDirMetaFormat1()
2846
self._supply_sub_formats_to(local_dir_format)
2847
return local_dir_format.initialize_on_transport_ex(transport,
2848
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2849
force_new_repo=force_new_repo, stacked_on=stacked_on,
2850
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2851
make_working_trees=make_working_trees, shared_repo=shared_repo,
2853
except errors.ErrorFromSmartServer, err:
2854
remote._translate_error(err, path=path)
2855
repo_path = response[0]
2856
bzrdir_name = response[6]
2857
require_stacking = response[7]
2858
require_stacking = self.parse_NoneTrueFalse(require_stacking)
2859
format = RemoteBzrDirFormat()
2860
format._network_name = bzrdir_name
2861
self._supply_sub_formats_to(format)
2862
bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
2864
repo_format = remote.response_tuple_to_repo_format(response[1:])
2865
if repo_path == '.':
2868
repo_bzrdir_format = RemoteBzrDirFormat()
2869
repo_bzrdir_format._network_name = response[5]
2870
repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
2874
final_stack = response[8] or None
2875
final_stack_pwd = response[9] or None
2877
final_stack_pwd = urlutils.join(
2878
transport.base, final_stack_pwd)
2879
remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
2880
if len(response) > 10:
2881
# Updated server verb that locks remotely.
2882
repo_lock_token = response[10] or None
2883
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
2885
remote_repo.dont_leave_lock_in_place()
2887
remote_repo.lock_write()
2888
policy = UseExistingRepository(remote_repo, final_stack,
2889
final_stack_pwd, require_stacking)
2890
policy.acquire_repository()
2894
bzrdir._format.set_branch_format(self.get_branch_format())
2895
if require_stacking:
2896
# The repo has already been created, but we need to make sure that
2897
# we'll make a stackable branch.
2898
bzrdir._format.require_stacking(_skip_repo=True)
2899
return remote_repo, bzrdir, require_stacking, policy
2901
def _open(self, transport):
2902
return remote.RemoteBzrDir(transport, self)
2904
def __eq__(self, other):
2905
if not isinstance(other, RemoteBzrDirFormat):
2907
return self.get_format_description() == other.get_format_description()
2909
def __return_repository_format(self):
2910
# Always return a RemoteRepositoryFormat object, but if a specific bzr
2911
# repository format has been asked for, tell the RemoteRepositoryFormat
2912
# that it should use that for init() etc.
2913
result = remote.RemoteRepositoryFormat()
2914
custom_format = getattr(self, '_repository_format', None)
2916
if isinstance(custom_format, remote.RemoteRepositoryFormat):
2917
return custom_format
2919
# We will use the custom format to create repositories over the
2920
# wire; expose its details like rich_root_data for code to
2922
result._custom_format = custom_format
2925
def get_branch_format(self):
2926
result = BzrDirMetaFormat1.get_branch_format(self)
2927
if not isinstance(result, remote.RemoteBranchFormat):
2928
new_result = remote.RemoteBranchFormat()
2929
new_result._custom_format = result
2931
self.set_branch_format(new_result)
2935
repository_format = property(__return_repository_format,
2936
BzrDirMetaFormat1._set_repository_format) #.im_func)
2939
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
2942
class RepositoryAcquisitionPolicy(object):
2943
"""Abstract base class for repository acquisition policies.
2945
A repository acquisition policy decides how a BzrDir acquires a repository
2946
for a branch that is being created. The most basic policy decision is
2947
whether to create a new repository or use an existing one.
2949
def __init__(self, stack_on, stack_on_pwd, require_stacking):
2952
:param stack_on: A location to stack on
2953
:param stack_on_pwd: If stack_on is relative, the location it is
2955
:param require_stacking: If True, it is a failure to not stack.
2957
self._stack_on = stack_on
2958
self._stack_on_pwd = stack_on_pwd
2959
self._require_stacking = require_stacking
2961
def configure_branch(self, branch):
2962
"""Apply any configuration data from this policy to the branch.
2964
Default implementation sets repository stacking.
2966
if self._stack_on is None:
2968
if self._stack_on_pwd is None:
2969
stack_on = self._stack_on
2972
stack_on = urlutils.rebase_url(self._stack_on,
2975
except errors.InvalidRebaseURLs:
2976
stack_on = self._get_full_stack_on()
2978
branch.set_stacked_on_url(stack_on)
2979
except (errors.UnstackableBranchFormat,
2980
errors.UnstackableRepositoryFormat):
2981
if self._require_stacking:
2984
def requires_stacking(self):
2985
"""Return True if this policy requires stacking."""
2986
return self._stack_on is not None and self._require_stacking
2988
def _get_full_stack_on(self):
2989
"""Get a fully-qualified URL for the stack_on location."""
2990
if self._stack_on is None:
2992
if self._stack_on_pwd is None:
2993
return self._stack_on
2995
return urlutils.join(self._stack_on_pwd, self._stack_on)
2997
def _add_fallback(self, repository, possible_transports=None):
2998
"""Add a fallback to the supplied repository, if stacking is set."""
2999
stack_on = self._get_full_stack_on()
3000
if stack_on is None:
3003
stacked_dir = BzrDir.open(stack_on,
3004
possible_transports=possible_transports)
3005
except errors.JailBreak:
3006
# We keep the stacking details, but we are in the server code so
3007
# actually stacking is not needed.
3010
stacked_repo = stacked_dir.open_branch().repository
3011
except errors.NotBranchError:
3012
stacked_repo = stacked_dir.open_repository()
3014
repository.add_fallback_repository(stacked_repo)
3015
except errors.UnstackableRepositoryFormat:
3016
if self._require_stacking:
3019
self._require_stacking = True
3021
def acquire_repository(self, make_working_trees=None, shared=False):
3022
"""Acquire a repository for this bzrdir.
3024
Implementations may create a new repository or use a pre-exising
3026
:param make_working_trees: If creating a repository, set
3027
make_working_trees to this value (if non-None)
3028
:param shared: If creating a repository, make it shared if True
3029
:return: A repository, is_new_flag (True if the repository was
3032
raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
3035
class CreateRepository(RepositoryAcquisitionPolicy):
3036
"""A policy of creating a new repository"""
3038
def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3039
require_stacking=False):
3042
:param bzrdir: The bzrdir to create the repository on.
3043
:param stack_on: A location to stack on
3044
:param stack_on_pwd: If stack_on is relative, the location it is
3047
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3049
self._bzrdir = bzrdir
3051
def acquire_repository(self, make_working_trees=None, shared=False):
3052
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3054
Creates the desired repository in the bzrdir we already have.
3056
stack_on = self._get_full_stack_on()
3058
format = self._bzrdir._format
3059
format.require_stacking(stack_on=stack_on,
3060
possible_transports=[self._bzrdir.root_transport])
3061
if not self._require_stacking:
3062
# We have picked up automatic stacking somewhere.
3063
note('Using default stacking branch %s at %s', self._stack_on,
3065
repository = self._bzrdir.create_repository(shared=shared)
3066
self._add_fallback(repository,
3067
possible_transports=[self._bzrdir.transport])
3068
if make_working_trees is not None:
3069
repository.set_make_working_trees(make_working_trees)
3070
return repository, True
3073
class UseExistingRepository(RepositoryAcquisitionPolicy):
3074
"""A policy of reusing an existing repository"""
3076
def __init__(self, repository, stack_on=None, stack_on_pwd=None,
3077
require_stacking=False):
3080
:param repository: The repository to use.
3081
:param stack_on: A location to stack on
3082
:param stack_on_pwd: If stack_on is relative, the location it is
3085
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3087
self._repository = repository
3089
def acquire_repository(self, make_working_trees=None, shared=False):
3090
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3092
Returns an existing repository to use.
3094
self._add_fallback(self._repository,
3095
possible_transports=[self._repository.bzrdir.transport])
3096
return self._repository, False
3099
def register_metadir(registry, key,
3100
repository_format, help, native=True, deprecated=False,
3106
"""Register a metadir subformat.
3108
These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
3109
by the Repository/Branch/WorkingTreeformats.
3111
:param repository_format: The fully-qualified repository format class
3113
:param branch_format: Fully-qualified branch format class name as
3115
:param tree_format: Fully-qualified tree format class name as
3118
# This should be expanded to support setting WorkingTree and Branch
3119
# formats, once BzrDirMetaFormat1 supports that.
3120
def _load(full_name):
3121
mod_name, factory_name = full_name.rsplit('.', 1)
3123
mod = __import__(mod_name, globals(), locals(),
3125
except ImportError, e:
3126
raise ImportError('failed to load %s: %s' % (full_name, e))
3128
factory = getattr(mod, factory_name)
3129
except AttributeError:
3130
raise AttributeError('no factory %s in module %r'
3135
bd = BzrDirMetaFormat1()
3136
if branch_format is not None:
3137
bd.set_branch_format(_load(branch_format))
3138
if tree_format is not None:
3139
bd.workingtree_format = _load(tree_format)
3140
if repository_format is not None:
3141
bd.repository_format = _load(repository_format)
3143
registry.register(key, helper, help, native, deprecated, hidden,
3144
experimental, alias)
3146
# The pre-0.8 formats have their repository format network name registered in
3147
# repository.py. MetaDir formats have their repository format network name
3148
# inferred from their disk format string.
3149
controldir.format_registry.register('weave', BzrDirFormat6,
3150
'Pre-0.8 format. Slower than knit and does not'
3151
' support checkouts or shared repositories.',
3154
register_metadir(controldir.format_registry, 'metaweave',
3155
'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3156
'Transitional format in 0.8. Slower than knit.',
3157
branch_format='bzrlib.branch.BzrBranchFormat5',
3158
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3161
register_metadir(controldir.format_registry, 'knit',
3162
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3163
'Format using knits. Recommended for interoperation with bzr <= 0.14.',
3164
branch_format='bzrlib.branch.BzrBranchFormat5',
3165
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3168
register_metadir(controldir.format_registry, 'dirstate',
3169
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3170
help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3171
'above when accessed over the network.',
3172
branch_format='bzrlib.branch.BzrBranchFormat5',
3173
# this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3174
# directly from workingtree_4 triggers a circular import.
3175
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3178
register_metadir(controldir.format_registry, 'dirstate-tags',
3179
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3180
help='New in 0.15: Fast local operations and improved scaling for '
3181
'network operations. Additionally adds support for tags.'
3182
' Incompatible with bzr < 0.15.',
3183
branch_format='bzrlib.branch.BzrBranchFormat6',
3184
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3187
register_metadir(controldir.format_registry, 'rich-root',
3188
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3189
help='New in 1.0. Better handling of tree roots. Incompatible with'
3191
branch_format='bzrlib.branch.BzrBranchFormat6',
3192
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3195
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
3196
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3197
help='New in 0.15: Fast local operations and improved scaling for '
3198
'network operations. Additionally adds support for versioning nested '
3199
'bzr branches. Incompatible with bzr < 0.15.',
3200
branch_format='bzrlib.branch.BzrBranchFormat6',
3201
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3205
register_metadir(controldir.format_registry, 'pack-0.92',
3206
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3207
help='New in 0.92: Pack-based format with data compatible with '
3208
'dirstate-tags format repositories. Interoperates with '
3209
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3211
branch_format='bzrlib.branch.BzrBranchFormat6',
3212
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3214
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
3215
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3216
help='New in 0.92: Pack-based format with data compatible with '
3217
'dirstate-with-subtree format repositories. Interoperates with '
3218
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3220
branch_format='bzrlib.branch.BzrBranchFormat6',
3221
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3225
register_metadir(controldir.format_registry, 'rich-root-pack',
3226
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3227
help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3228
'(needed for bzr-svn and bzr-git).',
3229
branch_format='bzrlib.branch.BzrBranchFormat6',
3230
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3233
register_metadir(controldir.format_registry, '1.6',
3234
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3235
help='A format that allows a branch to indicate that there is another '
3236
'(stacked) repository that should be used to access data that is '
3237
'not present locally.',
3238
branch_format='bzrlib.branch.BzrBranchFormat7',
3239
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3242
register_metadir(controldir.format_registry, '1.6.1-rich-root',
3243
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3244
help='A variant of 1.6 that supports rich-root data '
3245
'(needed for bzr-svn and bzr-git).',
3246
branch_format='bzrlib.branch.BzrBranchFormat7',
3247
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3250
register_metadir(controldir.format_registry, '1.9',
3251
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3252
help='A repository format using B+tree indexes. These indexes '
3253
'are smaller in size, have smarter caching and provide faster '
3254
'performance for most operations.',
3255
branch_format='bzrlib.branch.BzrBranchFormat7',
3256
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3259
register_metadir(controldir.format_registry, '1.9-rich-root',
3260
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3261
help='A variant of 1.9 that supports rich-root data '
3262
'(needed for bzr-svn and bzr-git).',
3263
branch_format='bzrlib.branch.BzrBranchFormat7',
3264
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3267
register_metadir(controldir.format_registry, '1.14',
3268
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3269
help='A working-tree format that supports content filtering.',
3270
branch_format='bzrlib.branch.BzrBranchFormat7',
3271
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3273
register_metadir(controldir.format_registry, '1.14-rich-root',
3274
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3275
help='A variant of 1.14 that supports rich-root data '
3276
'(needed for bzr-svn and bzr-git).',
3277
branch_format='bzrlib.branch.BzrBranchFormat7',
3278
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3280
# The following un-numbered 'development' formats should always just be aliases.
3281
register_metadir(controldir.format_registry, 'development-rich-root',
3282
'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3283
help='Current development format. Supports rich roots. Can convert data '
3284
'to and from rich-root-pack (and anything compatible with '
3285
'rich-root-pack) format repositories. Repositories and branches in '
3286
'this format can only be read by bzr.dev. Please read '
3287
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3289
branch_format='bzrlib.branch.BzrBranchFormat7',
3290
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3295
register_metadir(controldir.format_registry, 'development5-subtree',
3296
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3297
help='Development format, subtree variant. Can convert data to and '
3298
'from pack-0.92-subtree (and anything compatible with '
3299
'pack-0.92-subtree) format repositories. Repositories and branches in '
3300
'this format can only be read by bzr.dev. Please read '
3301
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3303
branch_format='bzrlib.branch.BzrBranchFormat7',
3304
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3311
register_metadir(controldir.format_registry, 'development-subtree',
3312
'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
3313
help='Current development format, subtree variant. Can convert data to and '
3314
'from pack-0.92-subtree (and anything compatible with '
3315
'pack-0.92-subtree) format repositories. Repositories and branches in '
3316
'this format can only be read by bzr.dev. Please read '
3317
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3319
branch_format='bzrlib.branch.BzrBranchFormat7',
3320
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3323
alias=False, # Restore to being an alias when an actual development subtree format is added
3324
# This current non-alias status is simply because we did not introduce a
3325
# chk based subtree format.
3328
# And the development formats above will have aliased one of the following:
3329
register_metadir(controldir.format_registry, 'development6-rich-root',
3330
'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3331
help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
3333
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3335
branch_format='bzrlib.branch.BzrBranchFormat7',
3336
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3341
register_metadir(controldir.format_registry, 'development7-rich-root',
3342
'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
3343
help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
3344
'rich roots. Please read '
3345
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3347
branch_format='bzrlib.branch.BzrBranchFormat7',
3348
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3353
register_metadir(controldir.format_registry, '2a',
3354
'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3355
help='First format for bzr 2.0 series.\n'
3356
'Uses group-compress storage.\n'
3357
'Provides rich roots which are a one-way transition.\n',
3358
# 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
3359
# 'rich roots. Supported by bzr 1.16 and later.',
3360
branch_format='bzrlib.branch.BzrBranchFormat7',
3361
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3365
# The following format should be an alias for the rich root equivalent
3366
# of the default format
3367
register_metadir(controldir.format_registry, 'default-rich-root',
3368
'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3369
branch_format='bzrlib.branch.BzrBranchFormat7',
3370
tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3375
# The current format that is made on 'bzr init'.
3376
controldir.format_registry.set_default('2a')
3378
# XXX 2010-08-20 JRV: There is still a lot of code relying on
3379
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
3380
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
3381
format_registry = controldir.format_registry